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
	"errors"

9 10 11 12 13 14 15 16 17 18 19 20
	"crypto/aes"
	"crypto/cipher"
	"crypto/elliptic"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
	"hash"
	"math/big"
	"strings"

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

27 28 29 30 31 32
// 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"

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

36
// Perform initial communication with this peer to share node ID's and
Brendan Mc's avatar
Brendan Mc committed
37
// initiate communication.  (secureIn, secureOut, error)
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
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)
58
	if err != nil {
59
		return nil, nil, err
60
	}
61

62
	out <- encoded
63 64 65

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

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

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

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

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

89
	cipherType, err := selectBest(SupportedExchanges, helloResp.GetCiphers())
90
	if err != nil {
91
		return nil, nil, err
92 93
	}

94 95 96
	hashType, err := selectBest(SupportedExchanges, helloResp.GetHashes())
	if err != nil {
		return nil, nil, err
97 98
	}

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

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

106 107 108 109
	exPacket := new(Exchange)

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

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

	out <- exEncoded

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

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

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

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

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

142 143 144
	secret, err := done(exchangeResp.GetEpubkey())
	if err != nil {
		return nil, nil, err
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 232
	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
233 234
}

235 236
func IdFromPubKey(pk ci.PubKey) (peer.ID, error) {
	b, err := pk.Bytes()
237 238 239
	if err != nil {
		return nil, err
	}
240
	hash, err := u.Hash(b)
241 242 243 244 245
	if err != nil {
		return nil, err
	}
	return peer.ID(hash), nil
}
246 247 248 249 250 251 252 253 254 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 389 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 459

// 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 {
	case "AES128":
		cipherKeySize = 2 * 16
	case "AES256":
		cipherKeySize = 2 * 32
	}

	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

		if len(theirPub) != (curveSize / 2) {
			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.")
}