1 // https://wiki.vuze.com/w/Message_Stream_Encryption
21 "github.com/anacrolix/missinggo/perf"
23 "github.com/bradfitz/iter"
29 CryptoMethodPlaintext CryptoMethod = 1
30 CryptoMethodRC4 CryptoMethod = 2
31 AllSupportedCrypto = CryptoMethodPlaintext | CryptoMethodRC4
34 type CryptoMethod uint32
37 // Prime P according to the spec, and G, the generator.
39 // The rand.Int max arg for use in newPadLen()
41 // For use in initer's hashes
45 // Verification constant "VC" which is all zeroes in the bittorrent
50 // Tracks counts of received crypto_provides
51 cryptoProvidesCount = expvar.NewMap("mseCryptoProvides")
55 p.SetString("0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A36210000000000090563", 0)
57 newPadLenMax.SetInt64(maxPadLen + 1)
60 func hash(parts ...[]byte) []byte {
62 for _, p := range parts {
74 func newEncrypt(initer bool, s []byte, skey []byte) (c *rc4.Cipher) {
75 c, err := rc4.NewCipher(hash([]byte(func() string {
85 var burnSrc, burnDst [1024]byte
86 c.XORKeyStream(burnDst[:], burnSrc[:])
90 type cipherReader struct {
97 func (cr *cipherReader) Read(b []byte) (n int, err error) {
100 if len(cr.be) >= len(b) {
106 be = make([]byte, len(b))
108 n, err = cr.r.Read(be[:len(b)])
109 cr.c.XORKeyStream(b[:n], be[:n])
111 if len(be) > len(cr.be) {
118 func newCipherReader(c *rc4.Cipher, r io.Reader) io.Reader {
119 return &cipherReader{c: c, r: r}
122 type cipherWriter struct {
128 func (cr *cipherWriter) Write(b []byte) (n int, err error) {
129 be := func() []byte {
130 if len(cr.b) < len(b) {
131 return make([]byte, len(b))
138 cr.c.XORKeyStream(be[:], b)
139 n, err = cr.w.Write(be[:len(b)])
141 // The cipher will have advanced beyond the callers stream position.
142 // We can't use the cipher anymore.
145 if len(be) > len(cr.b) {
151 func newX() big.Int {
153 X.SetBytes(func() []byte {
155 _, err := rand.Read(b[:])
164 func paddedLeft(b []byte, _len int) []byte {
168 ret := make([]byte, _len)
169 if n := copy(ret[_len-len(b):], b); n != len(b) {
175 // Calculate, and send Y, our public key.
176 func (h *handshake) postY(x *big.Int) error {
179 return h.postWrite(paddedLeft(y.Bytes(), 96))
182 func (h *handshake) establishS() error {
186 _, err := io.ReadFull(h.conn, b[:])
188 return fmt.Errorf("error reading Y: %s", err)
194 copy(h.s[96-len(sBytes):96], sBytes)
198 func newPadLen() int64 {
199 i, err := rand.Int(rand.Reader, &newPadLenMax)
204 if ret < 0 || ret > maxPadLen {
210 // Manages state for both initiating and receiving handshakes.
211 type handshake struct {
214 initer bool // Whether we're initiating or receiving.
215 skeys SecretKeyIter // Skeys we'll accept if receiving.
216 skey []byte // Skey we're initiating with.
217 ia []byte // Initial payload. Only used by the initiator.
218 // Return the bit for the crypto method the receiver wants to use.
219 chooseMethod CryptoSelector
220 // Sent to the receiver.
221 cryptoProvides CryptoMethod
234 func (h *handshake) finishWriting() {
237 h.writeCond.Broadcast()
247 func (h *handshake) writer() {
251 h.writerCond.Broadcast()
257 if len(h.writes) != 0 {
267 h.writes = h.writes[1:]
269 _, err := h.conn.Write(b)
279 func (h *handshake) postWrite(b []byte) error {
281 defer h.writeMu.Unlock()
282 if h.writeErr != nil {
285 h.writes = append(h.writes, b)
290 func xor(dst, src []byte) (ret []byte) {
295 ret = make([]byte, 0, max)
296 for i := range iter.N(max) {
297 ret = append(ret, dst[i]^src[i])
302 func marshal(w io.Writer, data ...interface{}) (err error) {
303 for _, data := range data {
304 err = binary.Write(w, binary.BigEndian, data)
312 func unmarshal(r io.Reader, data ...interface{}) (err error) {
313 for _, data := range data {
314 err = binary.Read(r, binary.BigEndian, data)
322 // Looking for b at the end of a.
323 func suffixMatchLen(a, b []byte) int {
327 // i is how much of b to try to match
328 for i := len(b); i > 0; i-- {
329 // j is how many chars we've compared
332 if b[i-1-j] != a[len(a)-1-j] {
342 // Reads from r until b has been seen. Keeps the minimum amount of data in
344 func readUntil(r io.Reader, b []byte) error {
345 b1 := make([]byte, len(b))
348 _, err := io.ReadFull(r, b1[i:])
352 i = suffixMatchLen(b1, b)
356 if copy(b1, b1[len(b1)-i:]) != i {
363 type readWriter struct {
368 func (h *handshake) newEncrypt(initer bool) *rc4.Cipher {
369 return newEncrypt(initer, h.s[:], h.skey)
372 func (h *handshake) initerSteps() (ret io.ReadWriter, selected CryptoMethod, err error) {
373 h.postWrite(hash(req1, h.s[:]))
374 h.postWrite(xor(hash(req2, h.skey), hash(req3, h.s[:])))
375 buf := &bytes.Buffer{}
376 padLen := uint16(newPadLen())
377 if len(h.ia) > math.MaxUint16 {
378 err = errors.New("initial payload too large")
381 err = marshal(buf, vc[:], h.cryptoProvides, padLen, zeroPad[:padLen], uint16(len(h.ia)), h.ia)
385 e := h.newEncrypt(true)
386 be := make([]byte, buf.Len())
387 e.XORKeyStream(be, buf.Bytes())
389 bC := h.newEncrypt(false)
391 bC.XORKeyStream(eVC[:], vc[:])
392 // Read until the all zero VC. At this point we've only read the 96 byte
393 // public key, Y. There is potentially 512 byte padding, between us and
394 // the 8 byte verification constant.
395 err = readUntil(io.LimitReader(h.conn, 520), eVC[:])
398 err = errors.New("failed to synchronize on VC")
400 err = fmt.Errorf("error reading until VC: %s", err)
404 r := newCipherReader(bC, h.conn)
405 var method CryptoMethod
406 err = unmarshal(r, &method, &padLen)
410 _, err = io.CopyN(ioutil.Discard, r, int64(padLen))
414 selected = method & h.cryptoProvides
416 case CryptoMethodRC4:
417 ret = readWriter{r, &cipherWriter{e, h.conn, nil}}
418 case CryptoMethodPlaintext:
421 err = fmt.Errorf("receiver chose unsupported method: %x", method)
426 var ErrNoSecretKeyMatch = errors.New("no skey matched")
428 func (h *handshake) receiverSteps() (ret io.ReadWriter, chosen CryptoMethod, err error) {
429 // There is up to 512 bytes of padding, then the 20 byte hash.
430 err = readUntil(io.LimitReader(h.conn, 532), hash(req1, h.s[:]))
433 err = errors.New("failed to synchronize on S hash")
438 _, err = io.ReadFull(h.conn, b[:])
442 err = ErrNoSecretKeyMatch
443 h.skeys(func(skey []byte) bool {
444 if bytes.Equal(xor(hash(req2, skey), hash(req3, h.s[:])), b[:]) {
454 r := newCipherReader(newEncrypt(true, h.s[:], h.skey), h.conn)
457 provides CryptoMethod
461 err = unmarshal(r, vc[:], &provides, &padLen)
465 cryptoProvidesCount.Add(strconv.FormatUint(uint64(provides), 16), 1)
466 chosen = h.chooseMethod(provides)
467 _, err = io.CopyN(ioutil.Discard, r, int64(padLen))
474 h.ia = make([]byte, lenIA)
477 buf := &bytes.Buffer{}
478 w := cipherWriter{h.newEncrypt(false), buf, nil}
479 padLen = uint16(newPadLen())
480 err = marshal(&w, &vc, uint32(chosen), padLen, zeroPad[:padLen])
484 err = h.postWrite(buf.Bytes())
489 case CryptoMethodRC4:
491 io.MultiReader(bytes.NewReader(h.ia), r),
492 &cipherWriter{w.c, h.conn, nil},
494 case CryptoMethodPlaintext:
496 io.MultiReader(bytes.NewReader(h.ia), h.conn),
500 err = errors.New("chosen crypto method is not supported")
505 func (h *handshake) Do() (ret io.ReadWriter, method CryptoMethod, err error) {
506 h.writeCond.L = &h.writeMu
507 h.writerCond.L = &h.writerMu
517 err = fmt.Errorf("error while establishing secret: %s", err)
520 pad := make([]byte, newPadLen())
521 io.ReadFull(rand.Reader, pad)
522 err = h.postWrite(pad)
527 ret, method, err = h.initerSteps()
529 ret, method, err = h.receiverSteps()
534 func InitiateHandshake(rw io.ReadWriter, skey []byte, initialPayload []byte, cryptoProvides CryptoMethod) (ret io.ReadWriter, method CryptoMethod, err error) {
540 cryptoProvides: cryptoProvides,
542 defer perf.ScopeTimerErr(&err)()
546 func ReceiveHandshake(rw io.ReadWriter, skeys SecretKeyIter, selectCrypto CryptoSelector) (ret io.ReadWriter, method CryptoMethod, err error) {
551 chooseMethod: selectCrypto,
556 // A function that given a function, calls it with secret keys until it
557 // returns false or exhausted.
558 type SecretKeyIter func(callback func(skey []byte) (more bool))
560 func DefaultCryptoSelector(provided CryptoMethod) CryptoMethod {
561 if provided&CryptoMethodPlaintext != 0 {
562 return CryptoMethodPlaintext
564 return CryptoMethodRC4
567 type CryptoSelector func(CryptoMethod) CryptoMethod