1 // https://wiki.vuze.com/w/Message_Stream_Encryption
21 "github.com/bradfitz/iter"
27 CryptoMethodPlaintext = 1
29 AllSupportedCrypto = CryptoMethodPlaintext | CryptoMethodRC4
33 // Prime P according to the spec, and G, the generator.
35 // The rand.Int max arg for use in newPadLen()
37 // For use in initer's hashes
41 // Verification constant "VC" which is all zeroes in the bittorrent
46 // Tracks counts of received crypto_provides
47 cryptoProvidesCount = expvar.NewMap("mseCryptoProvides")
51 p.SetString("0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A36210000000000090563", 0)
53 newPadLenMax.SetInt64(maxPadLen + 1)
56 func hash(parts ...[]byte) []byte {
58 for _, p := range parts {
70 func newEncrypt(initer bool, s []byte, skey []byte) (c *rc4.Cipher) {
71 c, err := rc4.NewCipher(hash([]byte(func() string {
81 var burnSrc, burnDst [1024]byte
82 c.XORKeyStream(burnDst[:], burnSrc[:])
86 type cipherReader struct {
93 func (cr *cipherReader) Read(b []byte) (n int, err error) {
96 if len(cr.be) >= len(b) {
102 be = make([]byte, len(b))
104 n, err = cr.r.Read(be[:len(b)])
105 cr.c.XORKeyStream(b[:n], be[:n])
107 if len(be) > len(cr.be) {
114 func newCipherReader(c *rc4.Cipher, r io.Reader) io.Reader {
115 return &cipherReader{c: c, r: r}
118 type cipherWriter struct {
124 func (cr *cipherWriter) Write(b []byte) (n int, err error) {
125 be := func() []byte {
126 if len(cr.b) < len(b) {
127 return make([]byte, len(b))
134 cr.c.XORKeyStream(be[:], b)
135 n, err = cr.w.Write(be[:len(b)])
137 // The cipher will have advanced beyond the callers stream position.
138 // We can't use the cipher anymore.
141 if len(be) > len(cr.b) {
147 func newX() big.Int {
149 X.SetBytes(func() []byte {
151 _, err := rand.Read(b[:])
160 func paddedLeft(b []byte, _len int) []byte {
164 ret := make([]byte, _len)
165 if n := copy(ret[_len-len(b):], b); n != len(b) {
171 // Calculate, and send Y, our public key.
172 func (h *handshake) postY(x *big.Int) error {
175 return h.postWrite(paddedLeft(y.Bytes(), 96))
178 func (h *handshake) establishS() (err error) {
182 _, err = io.ReadFull(h.conn, b[:])
190 copy(h.s[96-len(sBytes):96], sBytes)
194 func newPadLen() int64 {
195 i, err := rand.Int(rand.Reader, &newPadLenMax)
200 if ret < 0 || ret > maxPadLen {
206 // Manages state for both initiating and receiving handshakes.
207 type handshake struct {
210 initer bool // Whether we're initiating or receiving.
211 skeys SecretKeyIter // Skeys we'll accept if receiving.
212 skey []byte // Skey we're initiating with.
213 ia []byte // Initial payload. Only used by the initiator.
214 // Return the bit for the crypto method the receiver wants to use.
215 chooseMethod func(supported uint32) uint32
216 // Sent to the receiver.
217 cryptoProvides uint32
230 func (h *handshake) finishWriting() {
233 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(dst, src []byte) (ret []byte) {
292 ret = make([]byte, 0, max)
293 for i := range iter.N(max) {
294 ret = append(ret, dst[i]^src[i])
299 func marshal(w io.Writer, data ...interface{}) (err error) {
300 for _, data := range data {
301 err = binary.Write(w, binary.BigEndian, data)
309 func unmarshal(r io.Reader, data ...interface{}) (err error) {
310 for _, data := range data {
311 err = binary.Read(r, binary.BigEndian, data)
319 // Looking for b at the end of a.
320 func suffixMatchLen(a, b []byte) int {
324 // i is how much of b to try to match
325 for i := len(b); i > 0; i-- {
326 // j is how many chars we've compared
329 if b[i-1-j] != a[len(a)-1-j] {
339 // Reads from r until b has been seen. Keeps the minimum amount of data in
341 func readUntil(r io.Reader, b []byte) error {
342 b1 := make([]byte, len(b))
345 _, err := io.ReadFull(r, b1[i:])
349 i = suffixMatchLen(b1, b)
353 if copy(b1, b1[len(b1)-i:]) != i {
360 type readWriter struct {
365 func (h *handshake) newEncrypt(initer bool) *rc4.Cipher {
366 return newEncrypt(initer, h.s[:], h.skey)
369 func (h *handshake) initerSteps() (ret io.ReadWriter, err error) {
370 h.postWrite(hash(req1, h.s[:]))
371 h.postWrite(xor(hash(req2, h.skey), hash(req3, h.s[:])))
372 buf := &bytes.Buffer{}
373 padLen := uint16(newPadLen())
374 if len(h.ia) > math.MaxUint16 {
375 err = errors.New("initial payload too large")
378 err = marshal(buf, vc[:], h.cryptoProvides, padLen, zeroPad[:padLen], uint16(len(h.ia)), h.ia)
382 e := h.newEncrypt(true)
383 be := make([]byte, buf.Len())
384 e.XORKeyStream(be, buf.Bytes())
386 bC := h.newEncrypt(false)
388 bC.XORKeyStream(eVC[:], vc[:])
389 // Read until the all zero VC. At this point we've only read the 96 byte
390 // public key, Y. There is potentially 512 byte padding, between us and
391 // the 8 byte verification constant.
392 err = readUntil(io.LimitReader(h.conn, 520), eVC[:])
395 err = errors.New("failed to synchronize on VC")
397 err = fmt.Errorf("error reading until VC: %s", err)
401 r := newCipherReader(bC, h.conn)
403 err = unmarshal(r, &method, &padLen)
407 _, err = io.CopyN(ioutil.Discard, r, int64(padLen))
411 switch method & h.cryptoProvides {
412 case CryptoMethodRC4:
413 ret = readWriter{r, &cipherWriter{e, h.conn, nil}}
414 case CryptoMethodPlaintext:
417 err = fmt.Errorf("receiver chose unsupported method: %x", method)
422 var ErrNoSecretKeyMatch = errors.New("no skey matched")
424 func (h *handshake) receiverSteps() (ret io.ReadWriter, err error) {
425 // There is up to 512 bytes of padding, then the 20 byte hash.
426 err = readUntil(io.LimitReader(h.conn, 532), hash(req1, h.s[:]))
429 err = errors.New("failed to synchronize on S hash")
434 _, err = io.ReadFull(h.conn, b[:])
438 err = ErrNoSecretKeyMatch
439 h.skeys(func(skey []byte) bool {
440 if bytes.Equal(xor(hash(req2, skey), hash(req3, h.s[:])), b[:]) {
450 r := newCipherReader(newEncrypt(true, h.s[:], h.skey), h.conn)
457 err = unmarshal(r, vc[:], &provides, &padLen)
461 cryptoProvidesCount.Add(strconv.FormatUint(uint64(provides), 16), 1)
462 chosen := h.chooseMethod(provides)
463 _, err = io.CopyN(ioutil.Discard, r, int64(padLen))
470 h.ia = make([]byte, lenIA)
473 buf := &bytes.Buffer{}
474 w := cipherWriter{h.newEncrypt(false), buf, nil}
475 padLen = uint16(newPadLen())
476 err = marshal(&w, &vc, uint32(chosen), padLen, zeroPad[:padLen])
480 err = h.postWrite(buf.Bytes())
485 case CryptoMethodRC4:
487 io.MultiReader(bytes.NewReader(h.ia), r),
488 &cipherWriter{w.c, h.conn, nil},
490 case CryptoMethodPlaintext:
492 io.MultiReader(bytes.NewReader(h.ia), h.conn),
496 err = errors.New("chosen crypto method is not supported")
501 func (h *handshake) Do() (ret io.ReadWriter, err error) {
502 h.writeCond.L = &h.writeMu
503 h.writerCond.L = &h.writerMu
513 err = fmt.Errorf("error while establishing secret: %s", err)
516 pad := make([]byte, newPadLen())
517 io.ReadFull(rand.Reader, pad)
518 err = h.postWrite(pad)
523 ret, err = h.initerSteps()
525 ret, err = h.receiverSteps()
530 func InitiateHandshake(rw io.ReadWriter, skey []byte, initialPayload []byte, cryptoProvides uint32) (ret io.ReadWriter, err error) {
536 cryptoProvides: cryptoProvides,
541 func ReceiveHandshake(rw io.ReadWriter, skeys SecretKeyIter, selectCrypto func(uint32) uint32) (ret io.ReadWriter, err error) {
546 chooseMethod: selectCrypto,
551 // A function that given a function, calls it with secret keys until it
552 // returns false or exhausted.
553 type SecretKeyIter func(callback func(skey []byte) (more bool))
555 func DefaultCryptoSelector(provided uint32) uint32 {
556 if provided&CryptoMethodPlaintext != 0 {
557 return CryptoMethodPlaintext
559 return CryptoMethodRC4
562 type CryptoSelector func(uint32) uint32