handshake.go 8.86 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3 4 5 6 7
// Package spipe handles establishing secure communication between two peers.

package spipe

import (
	"bytes"
	"errors"
8
	"fmt"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
	"strings"

	"crypto/aes"
	"crypto/cipher"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
	"hash"

	proto "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
	ci "github.com/jbenet/go-ipfs/crypto"
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
)

// List of supported ECDH curves
var SupportedExchanges = "P-256,P-224,P-384,P-521"

// List of supported Ciphers
var SupportedCiphers = "AES-256,AES-128"

// List of supported Hashes
var SupportedHashes = "SHA256,SHA512,SHA1"

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

// ErrClosed signals the closing of a connection.
var ErrClosed = errors.New("connection closed")

// handsahke performs initial communication over insecure channel to share
// keys, IDs, and initiate communication.
func (s *SecurePipe) handshake() error {
	// Generate and send Hello packet.
	// Hello = (rand, PublicKey, Supported)
	nonce := make([]byte, 16)
	_, err := rand.Read(nonce)
	if err != nil {
		return err
	}

52
	// u.DOut("handshake: %s <--> %s\n", s.local.ID.Pretty(), s.remote.ID.Pretty())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
	myPubKey, err := s.local.PubKey.Bytes()
	if err != nil {
		return err
	}

	proposeMsg := new(Propose)
	proposeMsg.Rand = nonce
	proposeMsg.Pubkey = myPubKey
	proposeMsg.Exchanges = &SupportedExchanges
	proposeMsg.Ciphers = &SupportedCiphers
	proposeMsg.Hashes = &SupportedHashes

	encoded, err := proto.Marshal(proposeMsg)
	if err != nil {
		return err
	}

70 71 72 73 74 75
	// Send our Propose packet
	select {
	case s.insecure.Out <- encoded:
	case <-s.ctx.Done():
		return ErrClosed
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
76 77 78 79 80 81 82

	// Parse their Propose packet and generate an Exchange packet.
	// Exchange = (EphemeralPubKey, Signature)
	var resp []byte
	select {
	case <-s.ctx.Done():
		return ErrClosed
83
	case resp = <-s.insecure.In:
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
84 85
	}

86
	// u.POut("received encoded handshake\n")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
87 88 89 90 91 92
	proposeResp := new(Propose)
	err = proto.Unmarshal(resp, proposeResp)
	if err != nil {
		return err
	}

93 94
	// get remote identity
	remotePubKey, err := ci.UnmarshalPublicKey(proposeResp.GetPubkey())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
95 96 97 98
	if err != nil {
		return err
	}

99 100
	// get or construct peer
	s.remote, err = getOrConstructPeer(s.peers, remotePubKey)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
101 102 103
	if err != nil {
		return err
	}
104
	u.DOut("[%s] Remote Peer Identified as %s\n", s.local.ID.Pretty(), s.remote.ID.Pretty())
105

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
	exchange, err := selectBest(SupportedExchanges, proposeResp.GetExchanges())
	if err != nil {
		return err
	}

	cipherType, err := selectBest(SupportedCiphers, proposeResp.GetCiphers())
	if err != nil {
		return err
	}

	hashType, err := selectBest(SupportedHashes, proposeResp.GetHashes())
	if err != nil {
		return err
	}

121
	// u.POut("Selected %s %s %s\n", exchange, cipherType, hashType)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
	epubkey, done, err := ci.GenerateEKeyPair(exchange) // Generate EphemeralPubKey

	var handshake bytes.Buffer // Gather corpus to sign.
	handshake.Write(encoded)
	handshake.Write(resp)
	handshake.Write(epubkey)

	exPacket := new(Exchange)

	exPacket.Epubkey = epubkey
	exPacket.Signature, err = s.local.PrivKey.Sign(handshake.Bytes())
	if err != nil {
		return err
	}

	exEncoded, err := proto.Marshal(exPacket)

139 140 141 142 143 144
	// send out Exchange packet
	select {
	case s.insecure.Out <- exEncoded:
	case <-s.ctx.Done():
		return ErrClosed
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165

	// Parse their Exchange packet and generate a Finish packet.
	// Finish = E('Finish')
	var resp1 []byte
	select {
	case <-s.ctx.Done():
		return ErrClosed
	case resp1 = <-s.insecure.In:
	}

	exchangeResp := new(Exchange)
	err = proto.Unmarshal(resp1, exchangeResp)
	if err != nil {
		return err
	}

	var theirHandshake bytes.Buffer
	theirHandshake.Write(resp)
	theirHandshake.Write(encoded)
	theirHandshake.Write(exchangeResp.GetEpubkey())

166
	// u.POut("Remote Peer Identified as %s\n", s.remote.ID.Pretty())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
	ok, err := s.remote.PubKey.Verify(theirHandshake.Bytes(), exchangeResp.GetSignature())
	if err != nil {
		return err
	}

	if !ok {
		return errors.New("Bad signature!")
	}

	secret, err := done(exchangeResp.GetEpubkey())
	if err != nil {
		return err
	}

	cmp := bytes.Compare(myPubKey, proposeResp.GetPubkey())
	mIV, tIV, mCKey, tCKey, mMKey, tMKey := ci.KeyStretcher(cmp, cipherType, hashType, secret)

	go s.handleSecureIn(hashType, tIV, tCKey, tMKey)
	go s.handleSecureOut(hashType, mIV, mCKey, mMKey)

	finished := []byte("Finished")

189 190 191 192 193 194 195 196
	// send finished msg
	select {
	case <-s.ctx.Done():
		return ErrClosed
	case s.Out <- finished:
	}

	// recv finished msg
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
197 198 199 200
	var resp2 []byte
	select {
	case <-s.ctx.Done():
		return ErrClosed
201
	case resp2 = <-s.In:
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
202 203 204 205 206 207
	}

	if bytes.Compare(resp2, finished) != 0 {
		return errors.New("Negotiation failed.")
	}

208
	u.DOut("[%s] handshake: Got node id: %s\n", s.local.ID.Pretty(), s.remote.ID.Pretty())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
	return nil
}

func makeMac(hashType string, key []byte) (hash.Hash, int) {
	switch hashType {
	case "SHA1":
		return hmac.New(sha1.New, key), sha1.Size
	case "SHA512":
		return hmac.New(sha512.New, key), sha512.Size
	default:
		return hmac.New(sha256.New, key), sha256.Size
	}
}

func (s *SecurePipe) handleSecureIn(hashType string, tIV, tCKey, tMKey []byte) {
	theirBlock, _ := aes.NewCipher(tCKey)
	theirCipher := cipher.NewCTR(theirBlock, tIV)

	theirMac, macSize := makeMac(hashType, tMKey)

	for {
		data, ok := <-s.insecure.In
		if !ok {
			return
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
235
		// u.DOut("[peer %s] secure in [from = %s] %d\n", s.local.ID.Pretty(), s.remote.ID.Pretty(), len(data))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
236 237 238 239 240 241 242 243 244 245 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
		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 {
			s.Duplex.In <- buff
		} else {
			s.Duplex.In <- nil
		}
	}
}

func (s *SecurePipe) handleSecureOut(hashType string, mIV, mCKey, mMKey []byte) {
	myBlock, _ := aes.NewCipher(mCKey)
	myCipher := cipher.NewCTR(myBlock, mIV)

	myMac, macSize := makeMac(hashType, mMKey)

	for {
		data, ok := <-s.Out
		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()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
283
		// u.DOut("[peer %s] secure out [to = %s] %d\n", s.local.ID.Pretty(), s.remote.ID.Pretty(), len(buff))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
		s.insecure.Out <- buff
	}
}

// IDFromPubKey retrieves a Public Key from the peer given by pk
func IDFromPubKey(pk ci.PubKey) (peer.ID, error) {
	b, err := pk.Bytes()
	if err != nil {
		return nil, err
	}
	hash, err := u.Hash(b)
	if err != nil {
		return nil, err
	}
	return peer.ID(hash), nil
}

// 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!")
}
338 339 340 341 342 343 344 345 346 347 348 349

// getOrConstructPeer attempts to fetch a peer from a peerstore.
// if succeeds, verify ID and PubKey match.
// else, construct it.
func getOrConstructPeer(peers peer.Peerstore, rpk ci.PubKey) (*peer.Peer, error) {

	rid, err := IDFromPubKey(rpk)
	if err != nil {
		return nil, err
	}

	npeer, err := peers.Get(rid)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
350
	if err != nil || npeer == nil {
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
		if err != peer.ErrNotFound {
			return nil, err // unexpected error happened.
		}

		// dont have peer, so construct it + add it to peerstore.
		npeer = &peer.Peer{ID: rid, PubKey: rpk}
		if err := peers.Put(npeer); err != nil {
			return nil, err
		}

		// done, return the newly constructed peer.
		return npeer, nil
	}

	// did have it locally.

	// let's verify ID
	if !npeer.ID.Equal(rid) {
		e := "Expected peer.ID does not match sent pubkey's hash: %v - %v"
		return nil, fmt.Errorf(e, npeer.ID.Pretty(), rid.Pretty())
	}

	if npeer.PubKey == nil {
		// didn't have a pubkey, just set it.
		npeer.PubKey = rpk
		return npeer, nil
	}

	// did have pubkey, let's verify it's really the same.
	// this shouldn't ever happen, given we hashed, etc, but it could mean
	// expected code (or protocol) invariants violated.
382
	if !npeer.PubKey.Equals(rpk) {
383 384 385 386
		return nil, fmt.Errorf("WARNING: PubKey mismatch: %v", npeer.ID.Pretty())
	}
	return npeer, nil
}