identify.go 10 KB
Newer Older
1 2 3 4 5
// The identify package handles how peers identify with eachother upon
// connection to the network
package identify

import (
6
	"bytes"
7 8 9 10 11 12 13 14
	"crypto/aes"
	"crypto/cipher"
	"crypto/elliptic"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
Brendan Mc's avatar
Brendan Mc committed
15
	"errors"
16 17 18 19
	"hash"
	"math/big"
	"strings"

20
	proto "code.google.com/p/goprotobuf/proto"
21
	ci "github.com/jbenet/go-ipfs/crypto"
22
	peer "github.com/jbenet/go-ipfs/peer"
23
	u "github.com/jbenet/go-ipfs/util"
24 25
)

26 27 28 29 30 31
// List of supported protocols--each section in order of preference.
// Takes the form:  ECDH curves : Ciphers : Hashes
var SupportedExchanges = "P-256,P-224,P-384,P-521"
var SupportedCiphers = "AES-256,AES-128"
var SupportedHashes = "SHA256,SHA512,SHA1"

32 33 34
// ErrUnsupportedKeyType is returned when a private key cast/type switch fails.
var ErrUnsupportedKeyType = errors.New("unsupported key type")

35
// Perform initial communication with this peer to share node ID's and
Brendan Mc's avatar
Brendan Mc committed
36
// initiate communication.  (secureIn, secureOut, error)
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
func Handshake(self, remote *peer.Peer, in, out chan []byte) (chan []byte, chan []byte, error) {
	// Generate and send Hello packet.
	// Hello = (rand, PublicKey, Supported)
	nonce := make([]byte, 16)
	rand.Read(nonce)

	hello := new(Hello)

	myPubKey, err := self.PubKey.Bytes()
	if err != nil {
		return nil, nil, err
	}

	hello.Rand = nonce
	hello.Pubkey = myPubKey
	hello.Exchanges = &SupportedExchanges
	hello.Ciphers = &SupportedCiphers
	hello.Hashes = &SupportedHashes

	encoded, err := proto.Marshal(hello)
57
	if err != nil {
58
		return nil, nil, err
59
	}
60

61
	out <- encoded
62 63 64

	// Parse their Hello packet and generate an Exchange packet.
	// Exchange = (EphemeralPubKey, Signature)
65
	resp := <-in
66

67 68
	helloResp := new(Hello)
	err = proto.Unmarshal(resp, helloResp)
69
	if err != nil {
70
		return nil, nil, err
71 72
	}

73 74 75
	remote.PubKey, err = ci.UnmarshalPublicKey(helloResp.GetPubkey())
	if err != nil {
		return nil, nil, err
76 77
	}

78
	remote.ID, err = IdFromPubKey(remote.PubKey)
79
	if err != nil {
80
		return nil, nil, err
81 82
	}

83
	exchange, err := selectBest(SupportedExchanges, helloResp.GetExchanges())
84
	if err != nil {
85
		return nil, nil, err
86 87
	}

Brendan Mc's avatar
Brendan Mc committed
88
	cipherType, err := selectBest(SupportedCiphers, helloResp.GetCiphers())
89
	if err != nil {
90
		return nil, nil, err
91 92
	}

Brendan Mc's avatar
Brendan Mc committed
93
	hashType, err := selectBest(SupportedHashes, helloResp.GetHashes())
94 95
	if err != nil {
		return nil, nil, err
96 97
	}

98
	epubkey, done, err := generateEPubKey(exchange) // Generate EphemeralPubKey
99

100 101 102 103
	var handshake bytes.Buffer // Gather corpus to sign.
	handshake.Write(encoded)
	handshake.Write(resp)
	handshake.Write(epubkey)
104

105 106 107 108
	exPacket := new(Exchange)

	exPacket.Epubkey = epubkey
	exPacket.Signature, err = self.PrivKey.Sign(handshake.Bytes())
109
	if err != nil {
110
		return nil, nil, err
111 112
	}

113 114 115 116 117 118 119
	exEncoded, err := proto.Marshal(exPacket)

	out <- exEncoded

	// Parse their Exchange packet and generate a Finish packet.
	// Finish = E('Finish')
	resp1 := <-in
120

121 122
	exchangeResp := new(Exchange)
	err = proto.Unmarshal(resp1, exchangeResp)
123
	if err != nil {
124
		return nil, nil, err
125 126
	}

127 128 129 130
	var theirHandshake bytes.Buffer
	theirHandshake.Write(resp)
	theirHandshake.Write(encoded)
	theirHandshake.Write(exchangeResp.GetEpubkey())
131

132
	ok, err := remote.PubKey.Verify(theirHandshake.Bytes(), exchangeResp.GetSignature())
133
	if err != nil {
134 135 136 137 138
		return nil, nil, err
	}

	if !ok {
		return nil, nil, errors.New("Bad signature!")
139 140
	}

141 142 143
	secret, err := done(exchangeResp.GetEpubkey())
	if err != nil {
		return nil, nil, err
144 145
	}

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
	cmp := bytes.Compare(myPubKey, helloResp.GetPubkey())
	mIV, tIV, mCKey, tCKey, mMKey, tMKey := keyGenerator(cmp, cipherType, hashType, secret)

	secureIn := make(chan []byte)
	secureOut := make(chan []byte)

	go func() {
		myBlock, _ := aes.NewCipher(mCKey)
		myCipher := cipher.NewCTR(myBlock, mIV)

		theirBlock, _ := aes.NewCipher(tCKey)
		theirCipher := cipher.NewCTR(theirBlock, tIV)

		var myMac, theirMac hash.Hash
		var macSize int

		switch hashType {
		case "SHA1":
			myMac = hmac.New(sha1.New, mMKey)
			theirMac = hmac.New(sha1.New, tMKey)
			macSize = 20

		case "SHA256":
			myMac = hmac.New(sha256.New, mMKey)
			theirMac = hmac.New(sha256.New, tMKey)
			macSize = 32

		case "SHA512":
			myMac = hmac.New(sha512.New, mMKey)
			theirMac = hmac.New(sha512.New, tMKey)
			macSize = 64
		}

		for {
			select {
			case data, ok := <-secureOut:
				if !ok {
					return
				}

				if len(data) == 0 {
					continue
				}

				buff := make([]byte, len(data)+macSize)

				myCipher.XORKeyStream(buff, data)

				myMac.Write(buff[0:len(data)])
				copy(buff[len(data):], myMac.Sum(nil))
				myMac.Reset()

				out <- buff

			case data, ok := <-in:
				if !ok {
					return
				}

				if len(data) <= macSize {
					continue
				}

				mark := len(data) - macSize
				buff := make([]byte, mark)

				theirCipher.XORKeyStream(buff, data[0:mark])

				theirMac.Write(data[0:mark])
				expected := theirMac.Sum(nil)
				theirMac.Reset()

				hmacOk := hmac.Equal(data[mark:], expected)

				if hmacOk {
					secureIn <- buff
				} else {
					secureIn <- nil
				}
			}
		}
	}()

	u.DOut("[%s] identify: Got node id: %s\n", self.ID.Pretty(), remote.ID.Pretty())

	return secureIn, secureOut, nil
232 233
}

234 235
func IdFromPubKey(pk ci.PubKey) (peer.ID, error) {
	b, err := pk.Bytes()
236 237 238
	if err != nil {
		return nil, err
	}
239
	hash, err := u.Hash(b)
240 241 242 243 244
	if err != nil {
		return nil, err
	}
	return peer.ID(hash), nil
}
245 246 247 248 249 250

// Generates a set of keys for each party by stretching the shared key.
// (myIV, theirIV, myCipherKey, theirCipherKey, myMACKey, theirMACKey)
func keyGenerator(cmp int, cipherType string, hashType string, secret []byte) ([]byte, []byte, []byte, []byte, []byte, []byte) {
	var cipherKeySize int
	switch cipherType {
Brendan Mc's avatar
Brendan Mc committed
251 252 253 254
	case "AES-128":
		cipherKeySize = 16
	case "AES-256":
		cipherKeySize = 32
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
	}

	ivSize := 16
	hmacKeySize := 20

	seed := []byte("key expansion")

	result := make([]byte, 2*(ivSize+cipherKeySize+hmacKeySize))

	var h func() hash.Hash

	switch hashType {
	case "SHA1":
		h = sha1.New
	case "SHA256":
		h = sha256.New
	case "SHA512":
		h = sha512.New
	}

	m := hmac.New(h, secret)
	m.Write(seed)

	a := m.Sum(nil)

	j := 0
	for j < len(result) {
		m.Reset()
		m.Write(a)
		m.Write(seed)
		b := m.Sum(nil)

		todo := len(b)

		if j+todo > len(result) {
			todo = len(result) - j
		}

		copy(result[j:j+todo], b)

		j += todo

		m.Reset()
		m.Write(a)
		a = m.Sum(nil)
	}

	myResult := make([]byte, ivSize+cipherKeySize+hmacKeySize)
	theirResult := make([]byte, ivSize+cipherKeySize+hmacKeySize)

	half := len(result) / 2

	if cmp == 1 {
		copy(myResult, result[:half])
		copy(theirResult, result[half:])
	} else if cmp == -1 {
		copy(myResult, result[half:])
		copy(theirResult, result[:half])
	} else { // Shouldn't happen, but oh well.
		copy(myResult, result[half:])
		copy(theirResult, result[half:])
	}

	myIV := myResult[0:ivSize]
	myCKey := myResult[ivSize : ivSize+cipherKeySize]
	myMKey := myResult[ivSize+cipherKeySize:]

	theirIV := theirResult[0:ivSize]
	theirCKey := theirResult[ivSize : ivSize+cipherKeySize]
	theirMKey := theirResult[ivSize+cipherKeySize:]

	return myIV, theirIV, myCKey, theirCKey, myMKey, theirMKey
}

// Determines which algorithm to use.  Note:  f(a, b) = f(b, a)
func selectBest(myPrefs, theirPrefs string) (string, error) {
	// Person with greatest hash gets first choice.
	myHash, err := u.Hash([]byte(myPrefs))
	if err != nil {
		return "", err
	}

	theirHash, err := u.Hash([]byte(theirPrefs))
	if err != nil {
		return "", err
	}

	cmp := bytes.Compare(myHash, theirHash)
	var firstChoiceArr, secChoiceArr []string

	if cmp == -1 {
		firstChoiceArr = strings.Split(theirPrefs, ",")
		secChoiceArr = strings.Split(myPrefs, ",")
	} else if cmp == 1 {
		firstChoiceArr = strings.Split(myPrefs, ",")
		secChoiceArr = strings.Split(theirPrefs, ",")
	} else { // Exact same preferences.
		myPrefsArr := strings.Split(myPrefs, ",")
		return myPrefsArr[0], nil
	}

	for _, secChoice := range secChoiceArr {
		for _, firstChoice := range firstChoiceArr {
			if firstChoice == secChoice {
				return firstChoice, nil
			}
		}
	}

	return "", errors.New("No algorithms in common!")
}

// Generates an ephemeral public key and returns a function that will compute
// the shared secret key.
//
// Focuses only on ECDH now, but can be made more general in the future.
func generateEPubKey(exchange string) ([]byte, func([]byte) ([]byte, error), error) {
	genKeyPair := func(curve elliptic.Curve) ([]byte, []byte, error) {
		priv, x, y, err := elliptic.GenerateKey(curve, rand.Reader)
		if err != nil {
			return nil, nil, err
		}

		var pubKey bytes.Buffer
		pubKey.Write(x.Bytes())
		pubKey.Write(y.Bytes())

		return pubKey.Bytes(), priv, nil
	}

	genSec := func(curve elliptic.Curve, theirPub []byte, myPriv []byte) ([]byte, error) {
		// Verify and unpack node's public key.
		curveSize := curve.Params().BitSize

Brendan Mc's avatar
Brendan Mc committed
389
		if len(theirPub) != (curveSize / 4) {
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
			return nil, errors.New("Malformed public key.")
		}

		bound := (curveSize / 8)
		x := big.NewInt(0)
		y := big.NewInt(0)

		x.SetBytes(theirPub[0:bound])
		y.SetBytes(theirPub[bound : bound*2])

		if !curve.IsOnCurve(x, y) {
			return nil, errors.New("Invalid public key.")
		}

		// Generate shared secret.
		secret, _ := curve.ScalarMult(x, y, myPriv)

		return secret.Bytes(), nil
	}

	switch exchange {
	case "P-224":
		curve := elliptic.P224()
		pub, priv, err := genKeyPair(curve)
		if err != nil {
			return nil, nil, err
		}

		done := func(theirs []byte) ([]byte, error) { return genSec(curve, theirs, priv) }

		return pub, done, nil

	case "P-256":
		curve := elliptic.P256()
		pub, priv, err := genKeyPair(curve)
		if err != nil {
			return nil, nil, err
		}

		done := func(theirs []byte) ([]byte, error) { return genSec(curve, theirs, priv) }

		return pub, done, nil

	case "P-384":
		curve := elliptic.P384()
		pub, priv, err := genKeyPair(curve)
		if err != nil {
			return nil, nil, err
		}

		done := func(theirs []byte) ([]byte, error) { return genSec(curve, theirs, priv) }

		return pub, done, nil

	case "P-521":
		curve := elliptic.P521()
		pub, priv, err := genKeyPair(curve)
		if err != nil {
			return nil, nil, err
		}

		done := func(theirs []byte) ([]byte, error) { return genSec(curve, theirs, priv) }

		return pub, done, nil

	}

	return nil, nil, errors.New("Something silly happened.")
}