1 // https://wiki.vuze.com/w/Message_Stream_Encryption
21 "github.com/bradfitz/iter"
27 CryptoMethodPlaintext CryptoMethod = 1
28 CryptoMethodRC4 CryptoMethod = 2
29 AllSupportedCrypto = CryptoMethodPlaintext | CryptoMethodRC4
32 type CryptoMethod uint32
35 // Prime P according to the spec, and G, the generator.
37 // The rand.Int max arg for use in newPadLen()
39 // For use in initer's hashes
43 // Verification constant "VC" which is all zeroes in the bittorrent
48 // Tracks counts of received crypto_provides
49 cryptoProvidesCount = expvar.NewMap("mseCryptoProvides")
53 p.SetString("0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A36210000000000090563", 0)
55 newPadLenMax.SetInt64(maxPadLen + 1)
58 func hash(parts ...[]byte) []byte {
60 for _, p := range parts {
72 func newEncrypt(initer bool, s []byte, skey []byte) (c *rc4.Cipher) {
73 c, err := rc4.NewCipher(hash([]byte(func() string {
83 var burnSrc, burnDst [1024]byte
84 c.XORKeyStream(burnDst[:], burnSrc[:])
88 type cipherReader struct {
95 func (cr *cipherReader) Read(b []byte) (n int, err error) {
98 if len(cr.be) >= len(b) {
104 be = make([]byte, len(b))
106 n, err = cr.r.Read(be[:len(b)])
107 cr.c.XORKeyStream(b[:n], be[:n])
109 if len(be) > len(cr.be) {
116 func newCipherReader(c *rc4.Cipher, r io.Reader) io.Reader {
117 return &cipherReader{c: c, r: r}
120 type cipherWriter struct {
126 func (cr *cipherWriter) Write(b []byte) (n int, err error) {
127 be := func() []byte {
128 if len(cr.b) < len(b) {
129 return make([]byte, len(b))
136 cr.c.XORKeyStream(be[:], b)
137 n, err = cr.w.Write(be[:len(b)])
139 // The cipher will have advanced beyond the callers stream position.
140 // We can't use the cipher anymore.
143 if len(be) > len(cr.b) {
149 func newX() big.Int {
151 X.SetBytes(func() []byte {
153 _, err := rand.Read(b[:])
162 func paddedLeft(b []byte, _len int) []byte {
166 ret := make([]byte, _len)
167 if n := copy(ret[_len-len(b):], b); n != len(b) {
173 // Calculate, and send Y, our public key.
174 func (h *handshake) postY(x *big.Int) error {
177 return h.postWrite(paddedLeft(y.Bytes(), 96))
180 func (h *handshake) establishS() error {
184 _, err := io.ReadFull(h.conn, b[:])
186 return fmt.Errorf("error reading Y: %s", err)
192 copy(h.s[96-len(sBytes):96], sBytes)
196 func newPadLen() int64 {
197 i, err := rand.Int(rand.Reader, &newPadLenMax)
202 if ret < 0 || ret > maxPadLen {
208 // Manages state for both initiating and receiving handshakes.
209 type handshake struct {
212 initer bool // Whether we're initiating or receiving.
213 skeys SecretKeyIter // Skeys we'll accept if receiving.
214 skey []byte // Skey we're initiating with.
215 ia []byte // Initial payload. Only used by the initiator.
216 // Return the bit for the crypto method the receiver wants to use.
217 chooseMethod CryptoSelector
218 // Sent to the receiver.
219 cryptoProvides CryptoMethod
232 func (h *handshake) finishWriting() {
235 h.writeCond.Broadcast()
245 func (h *handshake) writer() {
249 h.writerCond.Broadcast()
255 if len(h.writes) != 0 {
265 h.writes = h.writes[1:]
267 _, err := h.conn.Write(b)
277 func (h *handshake) postWrite(b []byte) error {
279 defer h.writeMu.Unlock()
280 if h.writeErr != nil {
283 h.writes = append(h.writes, b)
288 func xor(dst, src []byte) (ret []byte) {
293 ret = make([]byte, 0, max)
294 for i := range iter.N(max) {
295 ret = append(ret, dst[i]^src[i])
300 func marshal(w io.Writer, data ...interface{}) (err error) {
301 for _, data := range data {
302 err = binary.Write(w, binary.BigEndian, data)
310 func unmarshal(r io.Reader, data ...interface{}) (err error) {
311 for _, data := range data {
312 err = binary.Read(r, binary.BigEndian, data)
320 // Looking for b at the end of a.
321 func suffixMatchLen(a, b []byte) int {
325 // i is how much of b to try to match
326 for i := len(b); i > 0; i-- {
327 // j is how many chars we've compared
330 if b[i-1-j] != a[len(a)-1-j] {
340 // Reads from r until b has been seen. Keeps the minimum amount of data in
342 func readUntil(r io.Reader, b []byte) error {
343 b1 := make([]byte, len(b))
346 _, err := io.ReadFull(r, b1[i:])
350 i = suffixMatchLen(b1, b)
354 if copy(b1, b1[len(b1)-i:]) != i {
361 type readWriter struct {
366 func (h *handshake) newEncrypt(initer bool) *rc4.Cipher {
367 return newEncrypt(initer, h.s[:], h.skey)
370 func (h *handshake) initerSteps() (ret io.ReadWriter, selected CryptoMethod, err error) {
371 h.postWrite(hash(req1, h.s[:]))
372 h.postWrite(xor(hash(req2, h.skey), hash(req3, h.s[:])))
373 buf := &bytes.Buffer{}
374 padLen := uint16(newPadLen())
375 if len(h.ia) > math.MaxUint16 {
376 err = errors.New("initial payload too large")
379 err = marshal(buf, vc[:], h.cryptoProvides, padLen, zeroPad[:padLen], uint16(len(h.ia)), h.ia)
383 e := h.newEncrypt(true)
384 be := make([]byte, buf.Len())
385 e.XORKeyStream(be, buf.Bytes())
387 bC := h.newEncrypt(false)
389 bC.XORKeyStream(eVC[:], vc[:])
390 // Read until the all zero VC. At this point we've only read the 96 byte
391 // public key, Y. There is potentially 512 byte padding, between us and
392 // the 8 byte verification constant.
393 err = readUntil(io.LimitReader(h.conn, 520), eVC[:])
396 err = errors.New("failed to synchronize on VC")
398 err = fmt.Errorf("error reading until VC: %s", err)
402 r := newCipherReader(bC, h.conn)
403 var method CryptoMethod
404 err = unmarshal(r, &method, &padLen)
408 _, err = io.CopyN(ioutil.Discard, r, int64(padLen))
412 selected = method & h.cryptoProvides
414 case CryptoMethodRC4:
415 ret = readWriter{r, &cipherWriter{e, h.conn, nil}}
416 case CryptoMethodPlaintext:
419 err = fmt.Errorf("receiver chose unsupported method: %x", method)
424 var ErrNoSecretKeyMatch = errors.New("no skey matched")
426 func (h *handshake) receiverSteps() (ret io.ReadWriter, chosen CryptoMethod, err error) {
427 // There is up to 512 bytes of padding, then the 20 byte hash.
428 err = readUntil(io.LimitReader(h.conn, 532), hash(req1, h.s[:]))
431 err = errors.New("failed to synchronize on S hash")
436 _, err = io.ReadFull(h.conn, b[:])
440 err = ErrNoSecretKeyMatch
441 h.skeys(func(skey []byte) bool {
442 if bytes.Equal(xor(hash(req2, skey), hash(req3, h.s[:])), b[:]) {
452 r := newCipherReader(newEncrypt(true, h.s[:], h.skey), h.conn)
455 provides CryptoMethod
459 err = unmarshal(r, vc[:], &provides, &padLen)
463 cryptoProvidesCount.Add(strconv.FormatUint(uint64(provides), 16), 1)
464 chosen = h.chooseMethod(provides)
465 _, err = io.CopyN(ioutil.Discard, r, int64(padLen))
472 h.ia = make([]byte, lenIA)
475 buf := &bytes.Buffer{}
476 w := cipherWriter{h.newEncrypt(false), buf, nil}
477 padLen = uint16(newPadLen())
478 err = marshal(&w, &vc, uint32(chosen), padLen, zeroPad[:padLen])
482 err = h.postWrite(buf.Bytes())
487 case CryptoMethodRC4:
489 io.MultiReader(bytes.NewReader(h.ia), r),
490 &cipherWriter{w.c, h.conn, nil},
492 case CryptoMethodPlaintext:
494 io.MultiReader(bytes.NewReader(h.ia), h.conn),
498 err = errors.New("chosen crypto method is not supported")
503 func (h *handshake) Do() (ret io.ReadWriter, method CryptoMethod, err error) {
504 h.writeCond.L = &h.writeMu
505 h.writerCond.L = &h.writerMu
515 err = fmt.Errorf("error while establishing secret: %s", err)
518 pad := make([]byte, newPadLen())
519 io.ReadFull(rand.Reader, pad)
520 err = h.postWrite(pad)
525 ret, method, err = h.initerSteps()
527 ret, method, err = h.receiverSteps()
532 func InitiateHandshake(rw io.ReadWriter, skey []byte, initialPayload []byte, cryptoProvides CryptoMethod) (ret io.ReadWriter, method CryptoMethod, err error) {
538 cryptoProvides: cryptoProvides,
543 func ReceiveHandshake(rw io.ReadWriter, skeys SecretKeyIter, selectCrypto CryptoSelector) (ret io.ReadWriter, method CryptoMethod, err error) {
548 chooseMethod: selectCrypto,
553 // A function that given a function, calls it with secret keys until it
554 // returns false or exhausted.
555 type SecretKeyIter func(callback func(skey []byte) (more bool))
557 func DefaultCryptoSelector(provided CryptoMethod) CryptoMethod {
558 if provided&CryptoMethodPlaintext != 0 {
559 return CryptoMethodPlaintext
561 return CryptoMethodRC4
564 type CryptoSelector func(CryptoMethod) CryptoMethod