1 // https://wiki.vuze.com/w/Message_Stream_Encryption
20 "github.com/bradfitz/iter"
26 cryptoMethodPlaintext = 1
31 // Prime P according to the spec, and G, the generator.
33 // The rand.Int max arg for use in newPadLen()
35 // For use in initer's hashes
39 // Verification constant "VC" which is all zeroes in the bittorrent
44 // Tracks counts of received crypto_provides
45 cryptoProvidesCount = expvar.NewMap("mseCryptoProvides")
49 p.SetString("0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A36210000000000090563", 0)
51 newPadLenMax.SetInt64(maxPadLen + 1)
54 func hash(parts ...[]byte) []byte {
56 for _, p := range parts {
68 func newEncrypt(initer bool, s []byte, skey []byte) (c *rc4.Cipher) {
69 c, err := rc4.NewCipher(hash([]byte(func() string {
79 var burnSrc, burnDst [1024]byte
80 c.XORKeyStream(burnDst[:], burnSrc[:])
84 type cipherReader struct {
91 func (cr *cipherReader) Read(b []byte) (n int, err error) {
94 if len(cr.be) >= len(b) {
100 be = make([]byte, len(b))
102 n, err = cr.r.Read(be[:len(b)])
103 cr.c.XORKeyStream(b[:n], be[:n])
105 if len(be) > len(cr.be) {
112 func newCipherReader(c *rc4.Cipher, r io.Reader) io.Reader {
113 return &cipherReader{c: c, r: r}
116 type cipherWriter struct {
121 func (cr *cipherWriter) Write(b []byte) (n int, err error) {
122 be := make([]byte, len(b))
123 cr.c.XORKeyStream(be, b)
124 n, err = cr.w.Write(be)
126 // The cipher will have advanced beyond the callers stream position.
127 // We can't use the cipher anymore.
133 func readY(r io.Reader) (y big.Int, err error) {
135 _, err = io.ReadFull(r, b[:])
143 func newX() big.Int {
145 X.SetBytes(func() []byte {
147 _, err := rand.Read(b[:])
156 func paddedLeft(b []byte, _len int) []byte {
160 ret := make([]byte, _len)
161 if n := copy(ret[_len-len(b):], b); n != len(b) {
167 // Calculate, and send Y, our public key.
168 func (h *handshake) postY(x *big.Int) error {
171 return h.postWrite(paddedLeft(y.Bytes(), 96))
174 func (h *handshake) establishS() (err error) {
178 _, err = io.ReadFull(h.conn, b[:])
186 copy(h.s[96-len(sBytes):96], sBytes)
190 func newPadLen() int64 {
191 i, err := rand.Int(rand.Reader, &newPadLenMax)
196 if ret < 0 || ret > maxPadLen {
202 // Manages state for both initiating and receiving handshakes.
203 type handshake struct {
206 initer bool // Whether we're initiating or receiving.
207 skeys SecretKeyIter // Skeys we'll accept if receiving.
208 skey []byte // Skey we're initiating with.
209 ia []byte // Initial payload. Only used by the initiator.
222 func (h *handshake) finishWriting() {
225 h.writeCond.Broadcast()
236 func (h *handshake) writer() {
240 h.writerCond.Broadcast()
246 if len(h.writes) != 0 {
256 h.writes = h.writes[1:]
258 _, err := h.conn.Write(b)
268 func (h *handshake) postWrite(b []byte) error {
270 defer h.writeMu.Unlock()
271 if h.writeErr != nil {
274 h.writes = append(h.writes, b)
279 func xor(dst, src []byte) (ret []byte) {
284 ret = make([]byte, 0, max)
285 for i := range iter.N(max) {
286 ret = append(ret, dst[i]^src[i])
291 func marshal(w io.Writer, data ...interface{}) (err error) {
292 for _, data := range data {
293 err = binary.Write(w, binary.BigEndian, data)
301 func unmarshal(r io.Reader, data ...interface{}) (err error) {
302 for _, data := range data {
303 err = binary.Read(r, binary.BigEndian, data)
311 // Looking for b at the end of a.
312 func suffixMatchLen(a, b []byte) int {
316 // i is how much of b to try to match
317 for i := len(b); i > 0; i-- {
318 // j is how many chars we've compared
321 if b[i-1-j] != a[len(a)-1-j] {
331 // Reads from r until b has been seen. Keeps the minimum amount of data in
333 func readUntil(r io.Reader, b []byte) error {
334 b1 := make([]byte, len(b))
337 _, err := io.ReadFull(r, b1[i:])
341 i = suffixMatchLen(b1, b)
345 if copy(b1, b1[len(b1)-i:]) != i {
352 type readWriter struct {
357 func (h *handshake) newEncrypt(initer bool) *rc4.Cipher {
358 return newEncrypt(initer, h.s[:], h.skey)
361 func (h *handshake) initerSteps() (ret io.ReadWriter, err error) {
362 h.postWrite(hash(req1, h.s[:]))
363 h.postWrite(xor(hash(req2, h.skey), hash(req3, h.s[:])))
364 buf := &bytes.Buffer{}
365 padLen := uint16(newPadLen())
366 err = marshal(buf, vc[:], uint32(cryptoMethodRC4), padLen, zeroPad[:padLen], uint16(len(h.ia)), h.ia)
370 e := h.newEncrypt(true)
371 be := make([]byte, buf.Len())
372 e.XORKeyStream(be, buf.Bytes())
374 bC := h.newEncrypt(false)
376 bC.XORKeyStream(eVC[:], vc[:])
377 // Read until the all zero VC. At this point we've only read the 96 byte
378 // public key, Y. There is potentially 512 byte padding, between us and
379 // the 8 byte verification constant.
380 err = readUntil(io.LimitReader(h.conn, 520), eVC[:])
383 err = errors.New("failed to synchronize on VC")
385 err = fmt.Errorf("error reading until VC: %s", err)
389 r := newCipherReader(bC, h.conn)
391 err = unmarshal(r, &method, &padLen)
395 if method != cryptoMethodRC4 {
396 err = fmt.Errorf("receiver chose unsupported method: %x", method)
399 _, err = io.CopyN(ioutil.Discard, r, int64(padLen))
403 ret = readWriter{r, &cipherWriter{e, h.conn}}
407 var ErrNoSecretKeyMatch = errors.New("no skey matched")
409 func (h *handshake) receiverSteps() (ret io.ReadWriter, err error) {
410 // There is up to 512 bytes of padding, then the 20 byte hash.
411 err = readUntil(io.LimitReader(h.conn, 532), hash(req1, h.s[:]))
414 err = errors.New("failed to synchronize on S hash")
419 _, err = io.ReadFull(h.conn, b[:])
423 err = ErrNoSecretKeyMatch
424 h.skeys(func(skey []byte) bool {
425 if bytes.Equal(xor(hash(req2, skey), hash(req3, h.s[:])), b[:]) {
435 r := newCipherReader(newEncrypt(true, h.s[:], h.skey), h.conn)
442 err = unmarshal(r, vc[:], &method, &padLen)
446 cryptoProvidesCount.Add(strconv.FormatUint(uint64(method), 16), 1)
447 if method&cryptoMethodRC4 == 0 {
448 err = errors.New("no supported crypto methods were provided")
451 _, err = io.CopyN(ioutil.Discard, r, int64(padLen))
458 h.ia = make([]byte, lenIA)
461 buf := &bytes.Buffer{}
462 w := cipherWriter{h.newEncrypt(false), buf}
463 padLen = uint16(newPadLen())
464 err = marshal(&w, &vc, uint32(cryptoMethodRC4), padLen, zeroPad[:padLen])
468 err = h.postWrite(buf.Bytes())
472 ret = readWriter{io.MultiReader(bytes.NewReader(h.ia), r), &cipherWriter{w.c, h.conn}}
476 func (h *handshake) Do() (ret io.ReadWriter, err error) {
477 h.writeCond.L = &h.writeMu
478 h.writerCond.L = &h.writerMu
488 err = fmt.Errorf("error while establishing secret: %s", err)
491 pad := make([]byte, newPadLen())
492 io.ReadFull(rand.Reader, pad)
493 err = h.postWrite(pad)
498 ret, err = h.initerSteps()
500 ret, err = h.receiverSteps()
505 func InitiateHandshake(rw io.ReadWriter, skey []byte, initialPayload []byte) (ret io.ReadWriter, err error) {
515 func ReceiveHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, err error) {
519 skeys: sliceIter(skeys),
524 func sliceIter(skeys [][]byte) SecretKeyIter {
525 return func(callback func([]byte) bool) {
526 for _, sk := range skeys {
534 // A function that given a function, calls it with secret keys until it
535 // returns false or exhausted.
536 type SecretKeyIter func(callback func(skey []byte) (more bool))
538 // Doesn't unpack the secret keys until it needs to, and through the passed
540 func ReceiveHandshakeLazy(rw io.ReadWriter, skeys SecretKeyIter) (ret io.ReadWriter, err error) {