identify.go 3.62 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
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"errors"
	"io/ioutil"

14
	proto "code.google.com/p/goprotobuf/proto"
15
	peer "github.com/jbenet/go-ipfs/peer"
16
	u "github.com/jbenet/go-ipfs/util"
17 18
)

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

22 23
// Perform initial communication with this peer to share node ID's and
// initiate communication
24
func Handshake(self, remote *peer.Peer, in, out chan []byte) error {
25 26 27 28 29
	encoded, err := buildHandshake(self)
	if err != nil {
		return err
	}
	out <- encoded
30
	resp := <-in
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

	pbresp := new(Identify)
	err = proto.Unmarshal(resp, pbresp)
	if err != nil {
		return err
	}

	// Verify that the given ID matches their given public key
	if verifyErr := verifyID(peer.ID(pbresp.GetId()), pbresp.GetPubkey()); verifyErr != nil {
		return verifyErr
	}

	pubkey, err := x509.ParsePKIXPublicKey(pbresp.GetPubkey())
	if err != nil {
		return err
	}

	// Challenge peer to ensure they own the given pubkey
49
	secret := make([]byte, 16)
50 51 52 53 54 55 56 57 58 59
	rand.Read(secret)
	encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, pubkey.(*rsa.PublicKey), secret)
	if err != nil {
		//... this is odd
		return err
	}

	out <- encrypted
	challenge := <-in

Jeromy's avatar
Jeromy committed
60
	// Decrypt challenge and send plaintext to partner
61 62 63 64 65 66 67 68 69 70 71
	plain, err := rsa.DecryptPKCS1v15(rand.Reader, self.PrivKey.(*rsa.PrivateKey), challenge)
	if err != nil {
		return err
	}

	out <- plain
	chalResp := <-in
	if !bytes.Equal(chalResp, secret) {
		return errors.New("Recieved incorrect challenge response!")
	}

72
	remote.ID = peer.ID(pbresp.GetId())
73
	remote.PubKey = pubkey
74
	u.DOut("[%s] identify: Got node id: %s\n", self.ID.Pretty(), remote.ID.Pretty())
75 76 77

	return nil
}
78

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
func buildHandshake(self *peer.Peer) ([]byte, error) {
	pkb, err := x509.MarshalPKIXPublicKey(self.PubKey)
	if err != nil {
		return nil, err
	}

	pmes := new(Identify)
	pmes.Id = []byte(self.ID)
	pmes.Pubkey = pkb

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

	return encoded, nil
}

func verifyID(id peer.ID, pubkey []byte) error {
	hash, err := u.Hash(pubkey)
	if err != nil {
		return err
	}

	if id.Equal(peer.ID(hash)) {
		return nil
	}

	return errors.New("ID did not match public key!")
}

110 111 112 113 114
type KeyPair struct {
	Pub  crypto.PublicKey
	Priv crypto.PrivateKey
}

Jeromy's avatar
Jeromy committed
115 116
func GenKeypair(bits int) (*KeyPair, error) {
	priv, err := rsa.GenerateKey(rand.Reader, bits)
117 118 119 120 121 122
	if err != nil {
		return nil, err
	}

	return &KeyPair{
		Priv: priv,
Jeromy's avatar
Jeromy committed
123
		Pub:  &priv.PublicKey,
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
	}, nil
}

func LoadKeypair(dir string) (*KeyPair, error) {
	var kp KeyPair
	pk_b, err := ioutil.ReadFile(dir + "/priv.key")
	if err != nil {
		return nil, err
	}

	priv, err := x509.ParsePKCS1PrivateKey(pk_b)
	if err != nil {
		return nil, err
	}

	kp.Priv = priv
	kp.Pub = priv.PublicKey

	return &kp, nil
}

func (pk *KeyPair) ID() (peer.ID, error) {
	pub_b, err := x509.MarshalPKIXPublicKey(pk.Pub)
	if err != nil {
		return nil, err
	}
	hash, err := u.Hash(pub_b)
	if err != nil {
		return nil, err
	}
	return peer.ID(hash), nil
}

157 158 159 160 161 162 163 164 165
func (pk *KeyPair) PrivBytes() []byte {
	switch k := pk.Priv.(type) {
	case *rsa.PrivateKey:
		return x509.MarshalPKCS1PrivateKey(k)
	default:
		panic("Unsupported private key type.")
	}
}

166 167 168 169 170 171 172 173 174 175 176 177 178 179
func (kp *KeyPair) Save(dir string) error {
	switch k := kp.Priv.(type) {
	case *rsa.PrivateKey:
		err := k.Validate()
		if err != nil {
			return err
		}
		pk_b := x509.MarshalPKCS1PrivateKey(k)
		err = ioutil.WriteFile(dir+"/priv.key", pk_b, 0600)
		return err
	default:
		return errors.New("invalid private key type.")
	}
}