1 // https://wiki.vuze.com/w/Message_Stream_Encryption
20 "github.com/anacrolix/missinggo/perf"
26 CryptoMethodPlaintext CryptoMethod = 1 // After header obfuscation, drop into plaintext
27 CryptoMethodRC4 CryptoMethod = 2 // After header obfuscation, use RC4 for the rest of the stream
28 AllSupportedCrypto = CryptoMethodPlaintext | CryptoMethodRC4
31 type CryptoMethod uint32
34 // Prime P according to the spec, and G, the generator.
36 // The rand.Int max arg for use in newPadLen()
38 // For use in initer's hashes
42 // Verification constant "VC" which is all zeroes in the bittorrent
47 // Tracks counts of received crypto_provides
48 cryptoProvidesCount = expvar.NewMap("mseCryptoProvides")
52 p.SetString("0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A36210000000000090563", 0)
54 newPadLenMax.SetInt64(maxPadLen + 1)
57 func hash(parts ...[]byte) []byte {
59 for _, p := range parts {
71 func newEncrypt(initer bool, s, skey []byte) (c *rc4.Cipher) {
72 c, err := rc4.NewCipher(hash([]byte(func() string {
82 var burnSrc, burnDst [1024]byte
83 c.XORKeyStream(burnDst[:], burnSrc[:])
87 type cipherReader struct {
94 func (cr *cipherReader) Read(b []byte) (n int, err error) {
97 if len(cr.be) >= len(b) {
103 be = make([]byte, len(b))
105 n, err = cr.r.Read(be[:len(b)])
106 cr.c.XORKeyStream(b[:n], be[:n])
108 if len(be) > len(cr.be) {
115 func newCipherReader(c *rc4.Cipher, r io.Reader) io.Reader {
116 return &cipherReader{c: c, r: r}
119 type cipherWriter struct {
125 func (cr *cipherWriter) Write(b []byte) (n int, err error) {
126 be := func() []byte {
127 if len(cr.b) < len(b) {
128 return make([]byte, len(b))
135 cr.c.XORKeyStream(be, b)
136 n, err = cr.w.Write(be[:len(b)])
138 // The cipher will have advanced beyond the callers stream position.
139 // We can't use the cipher anymore.
142 if len(be) > len(cr.b) {
148 func newX() big.Int {
150 X.SetBytes(func() []byte {
152 _, err := rand.Read(b[:])
161 func paddedLeft(b []byte, _len int) []byte {
165 ret := make([]byte, _len)
166 if n := copy(ret[_len-len(b):], b); n != len(b) {
172 // Calculate, and send Y, our public key.
173 func (h *handshake) postY(x *big.Int) error {
176 return h.postWrite(paddedLeft(y.Bytes(), 96))
179 func (h *handshake) establishS() error {
183 _, err := io.ReadFull(h.conn, b[:])
185 return fmt.Errorf("error reading Y: %w", err)
191 copy(h.s[96-len(sBytes):96], sBytes)
195 func newPadLen() int64 {
196 i, err := rand.Int(rand.Reader, &newPadLenMax)
201 if ret < 0 || ret > maxPadLen {
207 // Manages state for both initiating and receiving handshakes.
208 type handshake struct {
211 initer bool // Whether we're initiating or receiving.
212 skeys SecretKeyIter // Skeys we'll accept if receiving.
213 skey []byte // Skey we're initiating with.
214 ia []byte // Initial payload. Only used by the initiator.
215 // Return the bit for the crypto method the receiver wants to use.
216 chooseMethod CryptoSelector
217 // Sent to the receiver.
218 cryptoProvides CryptoMethod
231 func (h *handshake) finishWriting() {
234 h.writeCond.Broadcast()
244 func (h *handshake) writer() {
248 h.writerCond.Broadcast()
254 if len(h.writes) != 0 {
264 h.writes = h.writes[1:]
266 _, err := h.conn.Write(b)
276 func (h *handshake) postWrite(b []byte) error {
278 defer h.writeMu.Unlock()
279 if h.writeErr != nil {
282 h.writes = append(h.writes, b)
287 func xor(a, b []byte) (ret []byte) {
292 ret = make([]byte, max)
293 xorInPlace(ret, a, b)
297 func xorInPlace(dst, a, b []byte) {
303 func marshal(w io.Writer, data ...interface{}) (err error) {
304 for _, data := range data {
305 err = binary.Write(w, binary.BigEndian, data)
313 func unmarshal(r io.Reader, data ...interface{}) (err error) {
314 for _, data := range data {
315 err = binary.Read(r, binary.BigEndian, data)
323 // Looking for b at the end of a.
324 func suffixMatchLen(a, b []byte) int {
328 // i is how much of b to try to match
329 for i := len(b); i > 0; i-- {
330 // j is how many chars we've compared
333 if b[i-1-j] != a[len(a)-1-j] {
343 // Reads from r until b has been seen. Keeps the minimum amount of data in
345 func readUntil(r io.Reader, b []byte) error {
346 b1 := make([]byte, len(b))
349 _, err := io.ReadFull(r, b1[i:])
353 i = suffixMatchLen(b1, b)
357 if copy(b1, b1[len(b1)-i:]) != i {
364 type readWriter struct {
369 func (h *handshake) newEncrypt(initer bool) *rc4.Cipher {
370 return newEncrypt(initer, h.s[:], h.skey)
373 func (h *handshake) initerSteps() (ret io.ReadWriter, selected CryptoMethod, err error) {
374 h.postWrite(hash(req1, h.s[:]))
375 h.postWrite(xor(hash(req2, h.skey), hash(req3, h.s[:])))
376 buf := &bytes.Buffer{}
377 padLen := uint16(newPadLen())
378 if len(h.ia) > math.MaxUint16 {
379 err = errors.New("initial payload too large")
382 err = marshal(buf, vc[:], h.cryptoProvides, padLen, zeroPad[:padLen], uint16(len(h.ia)), h.ia)
386 e := h.newEncrypt(true)
387 be := make([]byte, buf.Len())
388 e.XORKeyStream(be, buf.Bytes())
390 bC := h.newEncrypt(false)
392 bC.XORKeyStream(eVC[:], vc[:])
393 // Read until the all zero VC. At this point we've only read the 96 byte
394 // public key, Y. There is potentially 512 byte padding, between us and
395 // the 8 byte verification constant.
396 err = readUntil(io.LimitReader(h.conn, 520), eVC[:])
399 err = errors.New("failed to synchronize on VC")
401 err = fmt.Errorf("error reading until VC: %s", err)
405 r := newCipherReader(bC, h.conn)
406 var method CryptoMethod
407 err = unmarshal(r, &method, &padLen)
411 _, err = io.CopyN(io.Discard, r, int64(padLen))
415 selected = method & h.cryptoProvides
417 case CryptoMethodRC4:
418 ret = readWriter{r, &cipherWriter{e, h.conn, nil}}
419 case CryptoMethodPlaintext:
422 err = fmt.Errorf("receiver chose unsupported method: %x", method)
427 var ErrNoSecretKeyMatch = errors.New("no skey matched")
429 func (h *handshake) receiverSteps() (ret io.ReadWriter, chosen CryptoMethod, err error) {
430 // There is up to 512 bytes of padding, then the 20 byte hash.
431 err = readUntil(io.LimitReader(h.conn, 532), hash(req1, h.s[:]))
434 err = errors.New("failed to synchronize on S hash")
439 _, err = io.ReadFull(h.conn, b[:])
443 expectedHash := hash(req3, h.s[:])
444 eachHash := sha1.New()
445 var sum, xored [sha1.Size]byte
446 err = ErrNoSecretKeyMatch
447 h.skeys(func(skey []byte) bool {
451 eachHash.Sum(sum[:0])
452 xorInPlace(xored[:], sum[:], expectedHash)
453 if bytes.Equal(xored[:], b[:]) {
463 r := newCipherReader(newEncrypt(true, h.s[:], h.skey), h.conn)
466 provides CryptoMethod
470 err = unmarshal(r, vc[:], &provides, &padLen)
474 cryptoProvidesCount.Add(strconv.FormatUint(uint64(provides), 16), 1)
475 chosen = h.chooseMethod(provides)
476 _, err = io.CopyN(io.Discard, r, int64(padLen))
483 h.ia = make([]byte, lenIA)
486 buf := &bytes.Buffer{}
487 w := cipherWriter{h.newEncrypt(false), buf, nil}
488 padLen = uint16(newPadLen())
489 err = marshal(&w, &vc, uint32(chosen), padLen, zeroPad[:padLen])
493 err = h.postWrite(buf.Bytes())
498 case CryptoMethodRC4:
500 io.MultiReader(bytes.NewReader(h.ia), r),
501 &cipherWriter{w.c, h.conn, nil},
503 case CryptoMethodPlaintext:
505 io.MultiReader(bytes.NewReader(h.ia), h.conn),
509 err = errors.New("chosen crypto method is not supported")
514 func (h *handshake) Do() (ret io.ReadWriter, method CryptoMethod, err error) {
515 h.writeCond.L = &h.writeMu
516 h.writerCond.L = &h.writerMu
526 err = fmt.Errorf("error while establishing secret: %w", err)
529 pad := make([]byte, newPadLen())
530 io.ReadFull(rand.Reader, pad)
531 err = h.postWrite(pad)
536 ret, method, err = h.initerSteps()
538 ret, method, err = h.receiverSteps()
543 func InitiateHandshake(
544 rw io.ReadWriter, skey, initialPayload []byte, cryptoProvides CryptoMethod,
546 ret io.ReadWriter, method CryptoMethod, err error,
553 cryptoProvides: cryptoProvides,
555 defer perf.ScopeTimerErr(&err)()
559 type HandshakeResult struct {
566 func ReceiveHandshake(rw io.ReadWriter, skeys SecretKeyIter, selectCrypto CryptoSelector) (io.ReadWriter, CryptoMethod, error) {
567 res := ReceiveHandshakeEx(rw, skeys, selectCrypto)
568 return res.ReadWriter, res.CryptoMethod, res.error
571 func ReceiveHandshakeEx(rw io.ReadWriter, skeys SecretKeyIter, selectCrypto CryptoSelector) (ret HandshakeResult) {
576 chooseMethod: selectCrypto,
578 ret.ReadWriter, ret.CryptoMethod, ret.error = h.Do()
579 ret.SecretKey = h.skey
583 // A function that given a function, calls it with secret keys until it
584 // returns false or exhausted.
585 type SecretKeyIter func(callback func(skey []byte) (more bool))
587 func DefaultCryptoSelector(provided CryptoMethod) CryptoMethod {
588 // We prefer plaintext for performance reasons.
589 if provided&CryptoMethodPlaintext != 0 {
590 return CryptoMethodPlaintext
592 return CryptoMethodRC4
595 type CryptoSelector func(CryptoMethod) CryptoMethod