2015-01-18 11:46:08 +02:00
|
|
|
package p2p
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/ecdsa"
|
|
|
|
"crypto/rand"
|
|
|
|
"fmt"
|
2015-01-20 01:42:13 +02:00
|
|
|
"io"
|
2015-01-18 11:46:08 +02:00
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/crypto"
|
|
|
|
"github.com/obscuren/ecies"
|
|
|
|
"github.com/obscuren/secp256k1-go"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2015-01-20 18:47:46 +02:00
|
|
|
sskLen int = 16 // ecies.MaxSharedKeyLength(pubKey) / 2
|
|
|
|
sigLen int = 65 // elliptic S256
|
|
|
|
pubLen int = 64 // 512 bit pubkey in uncompressed representation without format byte
|
|
|
|
keyLen int = 32 // ECDSA
|
|
|
|
msgLen int = 194 // sigLen + keyLen + pubLen + keyLen + 1 = 194
|
|
|
|
resLen int = 97 // pubLen + keyLen + 1
|
2015-01-18 11:46:08 +02:00
|
|
|
)
|
|
|
|
|
2015-01-19 01:53:45 +02:00
|
|
|
// aesSecret, macSecret, egressMac, ingress
|
2015-01-18 11:46:08 +02:00
|
|
|
type secretRW struct {
|
|
|
|
aesSecret, macSecret, egressMac, ingressMac []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
type cryptoId struct {
|
2015-01-20 18:47:46 +02:00
|
|
|
prvKey *ecdsa.PrivateKey
|
|
|
|
pubKey *ecdsa.PublicKey
|
|
|
|
pubKeyS []byte
|
2015-01-18 11:46:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func newCryptoId(id ClientIdentity) (self *cryptoId, err error) {
|
|
|
|
// will be at server init
|
2015-01-20 18:47:46 +02:00
|
|
|
var prvKeyS []byte = id.PrivKey()
|
|
|
|
if prvKeyS == nil {
|
2015-01-18 11:46:08 +02:00
|
|
|
err = fmt.Errorf("no private key for client")
|
|
|
|
return
|
|
|
|
}
|
2015-01-20 18:47:46 +02:00
|
|
|
// initialise ecies private key via importing keys (known via our own clientIdentity)
|
|
|
|
// the key format is what elliptic package is using: elliptic.Marshal(Curve, X, Y)
|
|
|
|
var prvKey = crypto.ToECDSA(prvKeyS)
|
2015-01-18 11:46:08 +02:00
|
|
|
if prvKey == nil {
|
|
|
|
err = fmt.Errorf("invalid private key for client")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
self = &cryptoId{
|
|
|
|
prvKey: prvKey,
|
|
|
|
// initialise public key from the imported private key
|
|
|
|
pubKey: &prvKey.PublicKey,
|
|
|
|
// to be created at server init shared between peers and sessions
|
|
|
|
// for reuse, call wth ReadAt, no reset seek needed
|
|
|
|
}
|
2015-01-20 18:47:46 +02:00
|
|
|
self.pubKeyS = id.Pubkey()
|
2015-01-18 11:46:08 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-01-20 18:47:46 +02:00
|
|
|
func (self *cryptoId) Run(conn io.ReadWriter, remotePubKeyS []byte, sessionToken []byte, initiator bool) (token []byte, rw *secretRW, err error) {
|
2015-01-20 01:42:13 +02:00
|
|
|
var auth, initNonce, recNonce []byte
|
|
|
|
var randomPrivKey *ecdsa.PrivateKey
|
|
|
|
var remoteRandomPubKey *ecdsa.PublicKey
|
|
|
|
if initiator {
|
2015-01-20 18:47:46 +02:00
|
|
|
if auth, initNonce, randomPrivKey, _, err = self.startHandshake(remotePubKeyS, sessionToken); err != nil {
|
2015-01-20 01:42:13 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
conn.Write(auth)
|
|
|
|
var response []byte
|
|
|
|
conn.Read(response)
|
|
|
|
// write out auth message
|
|
|
|
// wait for response, then call complete
|
|
|
|
if recNonce, remoteRandomPubKey, _, err = self.completeHandshake(response); err != nil {
|
|
|
|
return
|
|
|
|
}
|
2015-01-19 13:21:13 +02:00
|
|
|
} else {
|
2015-01-20 01:42:13 +02:00
|
|
|
conn.Read(auth)
|
|
|
|
// we are listening connection. we are responders in the handshake.
|
2015-01-19 13:21:13 +02:00
|
|
|
// Extract info from the authentication. The initiator starts by sending us a handshake that we need to respond to.
|
2015-01-20 01:42:13 +02:00
|
|
|
// so we read auth message first, then respond
|
|
|
|
var response []byte
|
2015-01-20 18:47:46 +02:00
|
|
|
if response, recNonce, initNonce, randomPrivKey, remoteRandomPubKey, err = self.respondToHandshake(auth, remotePubKeyS, sessionToken); err != nil {
|
2015-01-20 01:42:13 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
conn.Write(response)
|
2015-01-19 13:21:13 +02:00
|
|
|
}
|
2015-01-20 01:42:13 +02:00
|
|
|
return self.newSession(initNonce, recNonce, auth, randomPrivKey, remoteRandomPubKey)
|
2015-01-19 13:21:13 +02:00
|
|
|
}
|
|
|
|
|
2015-01-19 06:53:48 +02:00
|
|
|
/* startHandshake is called by peer if it initiated the connection.
|
|
|
|
By protocol spec, the party who initiates the connection (initiator) will send an 'auth' packet
|
|
|
|
New: authInitiator -> E(remote-pubk, S(ecdhe-random, ecdh-shared-secret^nonce) || H(ecdhe-random-pubk) || pubk || nonce || 0x0)
|
|
|
|
authRecipient -> E(remote-pubk, ecdhe-random-pubk || nonce || 0x0)
|
|
|
|
|
|
|
|
Known: authInitiator = E(remote-pubk, S(ecdhe-random, token^nonce) || H(ecdhe-random-pubk) || pubk || nonce || 0x1)
|
|
|
|
authRecipient = E(remote-pubk, ecdhe-random-pubk || nonce || 0x1) // token found
|
|
|
|
authRecipient = E(remote-pubk, ecdhe-random-pubk || nonce || 0x0) // token not found
|
|
|
|
|
|
|
|
The caller provides the public key of the peer as conjuctured from lookup based on IP:port, given as user input or proven by signatures. The caller must have access to persistant information about the peers, and pass the previous session token as an argument to cryptoId.
|
|
|
|
|
|
|
|
The handshake is the process by which the peers establish their connection for a session.
|
|
|
|
|
|
|
|
*/
|
|
|
|
|
2015-01-20 18:47:46 +02:00
|
|
|
func ImportPublicKey(pubKey []byte) (pubKeyEC *ecdsa.PublicKey, err error) {
|
|
|
|
var pubKey65 []byte
|
|
|
|
switch len(pubKey) {
|
|
|
|
case 64:
|
|
|
|
pubKey65 = append([]byte{0x04}, pubKey...)
|
|
|
|
case 65:
|
|
|
|
pubKey65 = pubKey
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("invalid public key length %v (expect 64/65)", len(pubKey))
|
|
|
|
}
|
|
|
|
return crypto.ToECDSAPub(pubKey65), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func ExportPublicKey(pubKeyEC *ecdsa.PublicKey) (pubKey []byte, err error) {
|
|
|
|
if pubKeyEC == nil {
|
|
|
|
return nil, fmt.Errorf("no ECDSA public key given")
|
|
|
|
}
|
|
|
|
return crypto.FromECDSAPub(pubKeyEC)[1:], nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (self *cryptoId) startHandshake(remotePubKeyS, sessionToken []byte) (auth []byte, initNonce []byte, randomPrvKey *ecdsa.PrivateKey, remotePubKey *ecdsa.PublicKey, err error) {
|
2015-01-18 11:46:08 +02:00
|
|
|
// session init, common to both parties
|
2015-01-20 18:47:46 +02:00
|
|
|
if remotePubKey, err = ImportPublicKey(remotePubKeyS); err != nil {
|
2015-01-18 11:46:08 +02:00
|
|
|
return
|
|
|
|
}
|
2015-01-19 01:53:45 +02:00
|
|
|
|
|
|
|
var tokenFlag byte
|
2015-01-18 11:46:08 +02:00
|
|
|
if sessionToken == nil {
|
2015-01-19 01:53:45 +02:00
|
|
|
// no session token found means we need to generate shared secret.
|
|
|
|
// ecies shared secret is used as initial session token for new peers
|
|
|
|
// generate shared key from prv and remote pubkey
|
|
|
|
if sessionToken, err = ecies.ImportECDSA(self.prvKey).GenerateShared(ecies.ImportECDSAPublic(remotePubKey), sskLen, sskLen); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// tokenFlag = 0x00 // redundant
|
|
|
|
} else {
|
|
|
|
// for known peers, we use stored token from the previous session
|
|
|
|
tokenFlag = 0x01
|
2015-01-18 11:46:08 +02:00
|
|
|
}
|
2015-01-19 01:53:45 +02:00
|
|
|
|
|
|
|
//E(remote-pubk, S(ecdhe-random, ecdh-shared-secret^nonce) || H(ecdhe-random-pubk) || pubk || nonce || 0x0)
|
|
|
|
// E(remote-pubk, S(ecdhe-random, token^nonce) || H(ecdhe-random-pubk) || pubk || nonce || 0x1)
|
|
|
|
// allocate msgLen long message,
|
2015-01-18 11:46:08 +02:00
|
|
|
var msg []byte = make([]byte, msgLen)
|
2015-01-19 01:53:45 +02:00
|
|
|
initNonce = msg[msgLen-keyLen-1 : msgLen-1]
|
|
|
|
if _, err = rand.Read(initNonce); err != nil {
|
2015-01-18 11:46:08 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
// create known message
|
2015-01-19 01:53:45 +02:00
|
|
|
// ecdh-shared-secret^nonce for new peers
|
|
|
|
// token^nonce for old peers
|
|
|
|
var sharedSecret = Xor(sessionToken, initNonce)
|
2015-01-18 11:46:08 +02:00
|
|
|
|
|
|
|
// generate random keypair to use for signing
|
2015-01-19 06:53:48 +02:00
|
|
|
if randomPrvKey, err = crypto.GenerateKey(); err != nil {
|
2015-01-18 11:46:08 +02:00
|
|
|
return
|
|
|
|
}
|
2015-01-19 01:53:45 +02:00
|
|
|
// sign shared secret (message known to both parties): shared-secret
|
2015-01-18 11:46:08 +02:00
|
|
|
var signature []byte
|
2015-01-19 01:53:45 +02:00
|
|
|
// signature = sign(ecdhe-random, shared-secret)
|
2015-01-18 11:46:08 +02:00
|
|
|
// uses secp256k1.Sign
|
2015-01-19 06:53:48 +02:00
|
|
|
if signature, err = crypto.Sign(sharedSecret, randomPrvKey); err != nil {
|
2015-01-18 11:46:08 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-01-19 01:53:45 +02:00
|
|
|
// message
|
|
|
|
// signed-shared-secret || H(ecdhe-random-pubk) || pubk || nonce || 0x0
|
|
|
|
copy(msg, signature) // copy signed-shared-secret
|
|
|
|
// H(ecdhe-random-pubk)
|
2015-01-20 18:47:46 +02:00
|
|
|
var randomPubKey64 []byte
|
|
|
|
if randomPubKey64, err = ExportPublicKey(&randomPrvKey.PublicKey); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
copy(msg[sigLen:sigLen+keyLen], crypto.Sha3(randomPubKey64))
|
2015-01-19 01:53:45 +02:00
|
|
|
// pubkey copied to the correct segment.
|
2015-01-20 18:47:46 +02:00
|
|
|
copy(msg[sigLen+keyLen:sigLen+keyLen+pubLen], self.pubKeyS)
|
2015-01-19 01:53:45 +02:00
|
|
|
// nonce is already in the slice
|
|
|
|
// stick tokenFlag byte to the end
|
|
|
|
msg[msgLen-1] = tokenFlag
|
|
|
|
|
|
|
|
// encrypt using remote-pubk
|
2015-01-18 11:46:08 +02:00
|
|
|
// auth = eciesEncrypt(remote-pubk, msg)
|
2015-01-19 01:53:45 +02:00
|
|
|
|
2015-01-18 11:46:08 +02:00
|
|
|
if auth, err = crypto.Encrypt(remotePubKey, msg); err != nil {
|
|
|
|
return
|
|
|
|
}
|
2015-01-19 01:53:45 +02:00
|
|
|
|
2015-01-18 11:46:08 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-01-19 01:53:45 +02:00
|
|
|
// verifyAuth is called by peer if it accepted (but not initiated) the connection
|
2015-01-20 18:47:46 +02:00
|
|
|
func (self *cryptoId) respondToHandshake(auth, remotePubKeyS, sessionToken []byte) (authResp []byte, respNonce []byte, initNonce []byte, randomPrivKey *ecdsa.PrivateKey, remoteRandomPubKey *ecdsa.PublicKey, err error) {
|
2015-01-18 11:46:08 +02:00
|
|
|
var msg []byte
|
2015-01-20 18:47:46 +02:00
|
|
|
var remotePubKey *ecdsa.PublicKey
|
|
|
|
if remotePubKey, err = ImportPublicKey(remotePubKeyS); err != nil {
|
2015-01-20 01:42:13 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-01-18 11:46:08 +02:00
|
|
|
// they prove that msg is meant for me,
|
|
|
|
// I prove I possess private key if i can read it
|
|
|
|
if msg, err = crypto.Decrypt(self.prvKey, auth); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-01-19 02:55:24 +02:00
|
|
|
var tokenFlag byte
|
|
|
|
if sessionToken == nil {
|
|
|
|
// no session token found means we need to generate shared secret.
|
|
|
|
// ecies shared secret is used as initial session token for new peers
|
|
|
|
// generate shared key from prv and remote pubkey
|
|
|
|
if sessionToken, err = ecies.ImportECDSA(self.prvKey).GenerateShared(ecies.ImportECDSAPublic(remotePubKey), sskLen, sskLen); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// tokenFlag = 0x00 // redundant
|
|
|
|
} else {
|
|
|
|
// for known peers, we use stored token from the previous session
|
|
|
|
tokenFlag = 0x01
|
|
|
|
}
|
|
|
|
|
|
|
|
// the initiator nonce is read off the end of the message
|
2015-01-19 01:53:45 +02:00
|
|
|
initNonce = msg[msgLen-keyLen-1 : msgLen-1]
|
|
|
|
// I prove that i own prv key (to derive shared secret, and read nonce off encrypted msg) and that I own shared secret
|
|
|
|
// they prove they own the private key belonging to ecdhe-random-pubk
|
2015-01-19 02:55:24 +02:00
|
|
|
// we can now reconstruct the signed message and recover the peers pubkey
|
|
|
|
var signedMsg = Xor(sessionToken, initNonce)
|
2015-01-20 18:47:46 +02:00
|
|
|
var remoteRandomPubKeyS []byte
|
|
|
|
if remoteRandomPubKeyS, err = secp256k1.RecoverPubkey(signedMsg, msg[:sigLen]); err != nil {
|
2015-01-18 11:46:08 +02:00
|
|
|
return
|
|
|
|
}
|
2015-01-19 02:55:24 +02:00
|
|
|
// convert to ECDSA standard
|
2015-01-20 18:47:46 +02:00
|
|
|
if remoteRandomPubKey, err = ImportPublicKey(remoteRandomPubKeyS); err != nil {
|
2015-01-18 11:46:08 +02:00
|
|
|
return
|
|
|
|
}
|
2015-01-19 01:53:45 +02:00
|
|
|
|
2015-01-19 02:55:24 +02:00
|
|
|
// now we find ourselves a long task too, fill it random
|
|
|
|
var resp = make([]byte, resLen)
|
|
|
|
// generate keyLen long nonce
|
2015-01-20 18:47:46 +02:00
|
|
|
respNonce = resp[pubLen : pubLen+keyLen]
|
2015-01-19 01:53:45 +02:00
|
|
|
if _, err = rand.Read(respNonce); err != nil {
|
|
|
|
return
|
|
|
|
}
|
2015-01-19 02:55:24 +02:00
|
|
|
// generate random keypair for session
|
2015-01-20 01:42:13 +02:00
|
|
|
if randomPrivKey, err = crypto.GenerateKey(); err != nil {
|
2015-01-19 01:53:45 +02:00
|
|
|
return
|
|
|
|
}
|
2015-01-19 02:55:24 +02:00
|
|
|
// responder auth message
|
2015-01-19 01:53:45 +02:00
|
|
|
// E(remote-pubk, ecdhe-random-pubk || nonce || 0x0)
|
2015-01-20 18:47:46 +02:00
|
|
|
var randomPubKeyS []byte
|
|
|
|
if randomPubKeyS, err = ExportPublicKey(&randomPrivKey.PublicKey); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
copy(resp[:pubLen], randomPubKeyS)
|
2015-01-19 01:53:45 +02:00
|
|
|
// nonce is already in the slice
|
2015-01-19 02:55:24 +02:00
|
|
|
resp[resLen-1] = tokenFlag
|
2015-01-19 01:53:45 +02:00
|
|
|
|
|
|
|
// encrypt using remote-pubk
|
|
|
|
// auth = eciesEncrypt(remote-pubk, msg)
|
|
|
|
// why not encrypt with ecdhe-random-remote
|
|
|
|
if authResp, err = crypto.Encrypt(remotePubKey, resp); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-01-19 06:53:48 +02:00
|
|
|
func (self *cryptoId) completeHandshake(auth []byte) (respNonce []byte, remoteRandomPubKey *ecdsa.PublicKey, tokenFlag bool, err error) {
|
2015-01-19 01:53:45 +02:00
|
|
|
var msg []byte
|
|
|
|
// they prove that msg is meant for me,
|
|
|
|
// I prove I possess private key if i can read it
|
|
|
|
if msg, err = crypto.Decrypt(self.prvKey, auth); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-01-20 18:47:46 +02:00
|
|
|
respNonce = msg[pubLen : pubLen+keyLen]
|
|
|
|
var remoteRandomPubKeyS = msg[:pubLen]
|
|
|
|
if remoteRandomPubKey, err = ImportPublicKey(remoteRandomPubKeyS); err != nil {
|
2015-01-19 01:53:45 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if msg[resLen-1] == 0x01 {
|
|
|
|
tokenFlag = true
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-01-19 06:53:48 +02:00
|
|
|
func (self *cryptoId) newSession(initNonce, respNonce, auth []byte, privKey *ecdsa.PrivateKey, remoteRandomPubKey *ecdsa.PublicKey) (sessionToken []byte, rw *secretRW, err error) {
|
2015-01-19 01:53:45 +02:00
|
|
|
// 3) Now we can trust ecdhe-random-pubk to derive new keys
|
2015-01-18 11:46:08 +02:00
|
|
|
//ecdhe-shared-secret = ecdh.agree(ecdhe-random, remote-ecdhe-random-pubk)
|
|
|
|
var dhSharedSecret []byte
|
2015-01-19 06:53:48 +02:00
|
|
|
pubKey := ecies.ImportECDSAPublic(remoteRandomPubKey)
|
|
|
|
if dhSharedSecret, err = ecies.ImportECDSA(privKey).GenerateShared(pubKey, sskLen, sskLen); err != nil {
|
2015-01-18 11:46:08 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
// shared-secret = crypto.Sha3(ecdhe-shared-secret || crypto.Sha3(nonce || initiator-nonce))
|
2015-01-19 01:53:45 +02:00
|
|
|
var sharedSecret = crypto.Sha3(append(dhSharedSecret, crypto.Sha3(append(respNonce, initNonce...))...))
|
2015-01-18 11:46:08 +02:00
|
|
|
// token = crypto.Sha3(shared-secret)
|
|
|
|
sessionToken = crypto.Sha3(sharedSecret)
|
|
|
|
// aes-secret = crypto.Sha3(ecdhe-shared-secret || shared-secret)
|
|
|
|
var aesSecret = crypto.Sha3(append(dhSharedSecret, sharedSecret...))
|
|
|
|
// # destroy shared-secret
|
|
|
|
// mac-secret = crypto.Sha3(ecdhe-shared-secret || aes-secret)
|
|
|
|
var macSecret = crypto.Sha3(append(dhSharedSecret, aesSecret...))
|
|
|
|
// # destroy ecdhe-shared-secret
|
|
|
|
// egress-mac = crypto.Sha3(mac-secret^nonce || auth)
|
2015-01-19 01:53:45 +02:00
|
|
|
var egressMac = crypto.Sha3(append(Xor(macSecret, respNonce), auth...))
|
2015-01-18 11:46:08 +02:00
|
|
|
// # destroy nonce
|
|
|
|
// ingress-mac = crypto.Sha3(mac-secret^initiator-nonce || auth),
|
2015-01-19 01:53:45 +02:00
|
|
|
var ingressMac = crypto.Sha3(append(Xor(macSecret, initNonce), auth...))
|
2015-01-18 11:46:08 +02:00
|
|
|
// # destroy remote-nonce
|
|
|
|
rw = &secretRW{
|
|
|
|
aesSecret: aesSecret,
|
|
|
|
macSecret: macSecret,
|
|
|
|
egressMac: egressMac,
|
|
|
|
ingressMac: ingressMac,
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-01-19 01:53:45 +02:00
|
|
|
// should use cipher.xorBytes from crypto/cipher/xor.go for fast xor
|
2015-01-18 11:46:08 +02:00
|
|
|
func Xor(one, other []byte) (xor []byte) {
|
2015-01-19 01:53:45 +02:00
|
|
|
xor = make([]byte, len(one))
|
2015-01-18 11:46:08 +02:00
|
|
|
for i := 0; i < len(one); i++ {
|
|
|
|
xor[i] = one[i] ^ other[i]
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|