RLPx Encryption(RLPx加密)
之前介紹的discover節點發現協定, 因為承載的資料不是很重要,基本是明文傳輸的。
每一個節點會開啟兩個同樣的端口,一個是UDP端口,用來節點發現,一個是TCP端口,用來承載業務資料。 UDP的端口和TCP的端口的端口号是同樣的。 這樣隻要通過UDP發現了端口,就等于可以用TCP來連接配接到對應的端口。
RLPx協定就定義了TCP連結的加密過程。
RLPx使用了(Perfect Forward Secrecy), 簡單來說。 連結的兩方生成生成随機的私鑰,通過随機的私鑰得到公鑰。 然後雙方交換各自的公鑰, 這樣雙方都可以通過自己随機的私鑰和對方的公鑰來生成一個同樣的共享密鑰(shared-secret)。後續的通訊使用這個共享密鑰作為對稱加密算法的密鑰。 這樣來說。如果有一天一方的私鑰被洩露,也隻會影響洩露之後的消息的安全性, 對于之前的通訊是安全的(因為通訊的密鑰是随機生成的,用完後就消失了)。
## 前向安全性(引用自維基百科)
前向安全或前向保密(英語:Forward Secrecy,縮寫:FS),有時也被稱為完美前向安全[1](英語:Perfect Forward Secrecy,縮寫:PFS),是密碼學中通訊協定的安全屬性,指的是長期使用的主密鑰洩漏不會導緻過去的會話密鑰洩漏。[2]前向安全能夠保護過去進行的通訊不受密碼或密鑰在未來暴露的威脅。[3]如果系統具有前向安全性,就可以保證萬一密碼或密鑰在某個時刻不慎洩露,過去已經進行的通訊依然是安全,不會受到任何影響,即使系統遭到主動攻ji也是如此。
### 迪菲-赫爾曼密鑰交換
迪菲-赫爾曼密鑰交換(英語:Diffie–Hellman key exchange,縮寫為D-H) 是一種安全協定。它可以讓雙方在完全沒有對方任何預先資訊的條件下通過不安全信道建立起一個密鑰。這個密鑰可以在後續的通訊中作為對稱密鑰來加密通訊内容。公鑰交換的概念最早由瑞夫·墨克(Ralph C. Merkle)提出,而這個密鑰交換方法,由惠特菲爾德·迪菲(Bailey Whitfield Diffie)和馬丁·赫爾曼(Martin Edward Hellman)在1976年首次發表。馬丁·赫爾曼曾主張這個密鑰交換方法,應被稱為迪菲-赫爾曼-墨克密鑰交換(英語:Diffie–Hellman–Merkle key exchange)。
- 迪菲-赫爾曼密鑰交換的同義詞包括:
- 迪菲-赫爾曼密鑰協商
- 迪菲-赫爾曼密鑰建立
- 指數密鑰交換
- 迪菲-赫爾曼協定
雖然迪菲-赫爾曼密鑰交換本身是一個匿名(無認證)的密鑰交換協定,它卻是很多認證協定的基礎,并且被用來提供傳輸層安全協定的短暫模式中的完備的前向安全性。
#### 描述
迪菲-赫爾曼通過公共信道交換一個資訊,就可以建立一個可以用于在公共信道上安全通信的共享秘密(shared secret)。
## p2p/rlpx.go源碼解讀
這個檔案實作了RLPx的鍊路協定。
連結聯系的大緻流程如下:
1. doEncHandshake() 通過這個方法來完成交換密鑰,建立加密信道的流程。如果失敗,那麼連結關閉。
2. doProtoHandshake() 這個方法來進行協定特性之間的協商,比如雙方的協定版本,是否支援Snappy加密方式等操作。
連結經過這兩次處理之後,就算建立起來了。因為TCP是流式的協定。所有RLPx協定定義了分幀的方式。所有的資料都可以了解為一個接一個的rlpxFrame。 rlpx的讀寫都是通過rlpxFrameRW對象來進行處理。
### doEncHandshake
連結的發起者被稱為initiator。連結的被動接受者被成為receiver。 這兩種模式下處理的流程是不同的。完成握手後。 生成了一個sec.可以了解為拿到了對稱加密的密鑰。 然後建立了一個newRLPXFrameRW幀讀寫器。完成加密信道的建立過程。
func (t *rlpx) doEncHandshake(prv *ecdsa.PrivateKey, dial *discover.Node) (discover.NodeID, error) {
var (
sec secrets
err error
)
if dial == nil {
sec, err = receiverEncHandshake(t.fd, prv, nil)
} else {
sec, err = initiatorEncHandshake(t.fd, prv, dial.ID, nil)
}
if err != nil {
return discover.NodeID{}, err
t.wmu.Lock()
t.rw = newRLPXFrameRW(t.fd, sec)
t.wmu.Unlock()
return sec.RemoteID, nil
}
initiatorEncHandshake 首先看看連結的發起者的操作。首先通過makeAuthMsg建立了authMsg。 然後通過網絡發送給對端。然後通過readHandshakeMsg讀取對端的回應。 最後調用secrets建立了共享秘密。
// initiatorEncHandshake negotiates a session token on conn.
// it should be called on the dialing side of the connection.
//
// prv is the local client's private key.
func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remoteID discover.NodeID, token []byte) (s secrets, err error) {
h := &encHandshake{initiator: true, remoteID: remoteID}
authMsg, err := h.makeAuthMsg(prv, token)
return s, err
authPacket, err := sealEIP8(authMsg, h)
if _, err = conn.Write(authPacket); err != nil {
authRespMsg := new(authRespV4)
authRespPacket, err := readHandshakeMsg(authRespMsg, encAuthRespLen, prv, conn)
if err := h.handleAuthResp(authRespMsg); err != nil {
return h.secrets(authPacket, authRespPacket)
makeAuthMsg。這個方法建立了initiator的handshake message。 首先對端的公鑰可以通過對端的ID來擷取。是以對端的公鑰對于發起連接配接的人來說是知道的。 但是對于被連接配接的人來說,對端的公鑰應該是不知道的。
// makeAuthMsg creates the initiator handshake message.
func (h *encHandshake) makeAuthMsg(prv *ecdsa.PrivateKey, token []byte) (*authMsgV4, error) {
rpub, err := h.remoteID.Pubkey()
return nil, fmt.Errorf("bad remoteID: %v", err)
h.remotePub = ecies.ImportECDSAPublic(rpub)
// Generate random initiator nonce.
// 生成一個随機的初始值, 是為了避免重放攻ji麼? 還是為了避免通過多次連接配接猜測密鑰?
h.initNonce = make([]byte, shaLen)
if _, err := rand.Read(h.initNonce); err != nil {
return nil, err
// Generate random keypair to for ECDH.
//生成一個随機的私鑰
h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
// Sign known message: static-shared-secret ^ nonce
// 這個地方應該是直接使用了靜态的共享秘密。 使用自己的私鑰和對方的公鑰生成的一個共享秘密。
token, err = h.staticSharedSecret(prv)
//這裡我了解用共享秘密來加密這個initNonce。
signed := xor(token, h.initNonce)
// 使用随機的私鑰來加密這個資訊。
signature, err := crypto.Sign(signed, h.randomPrivKey.ExportECDSA())
msg := new(authMsgV4)
copy(msg.Signature[:], signature)
//這裡把發起者的公鑰告知對方。 這樣對方使用自己的私鑰和這個公鑰可以生成靜态的共享秘密。
copy(msg.InitiatorPubkey[:], crypto.FromECDSAPub(&prv.PublicKey)[1:])
copy(msg.Nonce[:], h.initNonce)
msg.Version = 4
return msg, nil
// staticSharedSecret returns the static shared secret, the result
// of key agreement between the local and remote static node key.
func (h *encHandshake) staticSharedSecret(prv *ecdsa.PrivateKey) ([]byte, error) {
return ecies.ImportECDSA(prv).GenerateShared(h.remotePub, sskLen, sskLen)
sealEIP8方法,這個方法是一個組包方法,對msg進行rlp的編碼。 填充一些資料。 然後使用對方的公鑰把資料進行加密。 這意味着隻有對方的私鑰才能解密這段資訊。
func sealEIP8(msg interface{}, h *encHandshake) ([]byte, error) {
buf := new(bytes.Buffer)
if err := rlp.Encode(buf, msg); err != nil {
// pad with random amount of data. the amount needs to be at least 100 bytes to make
// the message distinguishable from pre-EIP-8 handshakes.
pad := padSpace[:mrand.Intn(len(padSpace)-100)+100]
buf.Write(pad)
prefix := make([]byte, 2)
binary.BigEndian.PutUint16(prefix, uint16(buf.Len()+eciesOverhead))
enc, err := ecies.Encrypt(rand.Reader, h.remotePub, buf.Bytes(), nil, prefix)
return append(prefix, enc...), err
readHandshakeMsg這個方法會從兩個地方調用。 一個是在initiatorEncHandshake。一個就是在receiverEncHandshake。 這個方法比較簡單。 首先用一種格式嘗試解碼。如果不行就換另外一種。應該是一種相容性的設定。 基本上就是使用自己的私鑰進行解碼然後調用rlp解碼成結構體。 結構體的描述就是下面的authRespV4,裡面最重要的就是對端的随機公鑰。 雙方通過自己的私鑰和對端的随機公鑰可以得到一樣的共享秘密。 而這個共享秘密是第三方拿不到的。
// RLPx v4 handshake response (defined in EIP-8).
type authRespV4 struct {
RandomPubkey [pubLen]byte
Nonce [shaLen]byte
Version uint
// Ignore additional fields (forward-compatibility)
Rest []rlp.RawValue `rlp:"tail"`
func readHandshakeMsg(msg plainDecoder, plainSize int, prv *ecdsa.PrivateKey, r io.Reader) ([]byte, error) {
buf := make([]byte, plainSize)
if _, err := io.ReadFull(r, buf); err != nil {
return buf, err
// Attempt decoding pre-EIP-8 "plain" format.
key := ecies.ImportECDSA(prv)
if dec, err := key.Decrypt(rand.Reader, buf, nil, nil); err == nil {
msg.decodePlain(dec)
return buf, nil
// Could be EIP-8 format, try that.
prefix := buf[:2]
size := binary.BigEndian.Uint16(prefix)
if size < uint16(plainSize) {
return buf, fmt.Errorf("size underflow, need at least %d bytes", plainSize)
buf = append(buf, make([]byte, size-uint16(plainSize)+2)...)
if _, err := io.ReadFull(r, buf[plainSize:]); err != nil {
dec, err := key.Decrypt(rand.Reader, buf[2:], nil, prefix)
// Can't use rlp.DecodeBytes here because it rejects
// trailing data (forward-compatibility).
s := rlp.NewStream(bytes.NewReader(dec), 0)
return buf, s.Decode(msg)
handleAuthResp這個方法非常簡單。
func (h *encHandshake) handleAuthResp(msg *authRespV4) (err error) {
h.respNonce = msg.Nonce[:]
h.remoteRandomPub, err = importPublicKey(msg.RandomPubkey[:])
return err
最後是secrets函數,這個函數是在handshake完成之後調用。它通過自己的随機私鑰和對端的公鑰來生成一個共享秘密,這個共享秘密是瞬時的(隻在目前這個連結中存在)。是以當有一天私鑰被破解。 之前的消息還是安全的。
// secrets is called after the handshake is completed.
// It extracts the connection secrets from the handshake values.
func (h *encHandshake) secrets(auth, authResp []byte) (secrets, error) {
ecdheSecret, err := h.randomPrivKey.GenerateShared(h.remoteRandomPub, sskLen, sskLen)
return secrets{}, err
// derive base secrets from ephemeral key agreement
sharedSecret := crypto.Keccak256(ecdheSecret, crypto.Keccak256(h.respNonce, h.initNonce))
aesSecret := crypto.Keccak256(ecdheSecret, sharedSecret)
// 實際上這個MAC保護了ecdheSecret這個共享秘密。respNonce和initNonce這三個值
s := secrets{
RemoteID: h.remoteID,
AES: aesSecret,
MAC: crypto.Keccak256(ecdheSecret, aesSecret),
// setup sha3 instances for the MACs
mac1 := sha3.NewKeccak256()
mac1.Write(xor(s.MAC, h.respNonce))
mac1.Write(auth)
mac2 := sha3.NewKeccak256()
mac2.Write(xor(s.MAC, h.initNonce))
mac2.Write(authResp)
//收到的每個包都會檢查其MAC值是否滿足計算的結果。如果不滿足說明有問題。
if h.initiator {
s.EgressMAC, s.IngressMAC = mac1, mac2
s.EgressMAC, s.IngressMAC = mac2, mac1
return s, nil
receiverEncHandshake函數和initiatorEncHandshake的内容大緻相同。 但是順序有些不一樣。
// receiverEncHandshake negotiates a session token on conn.
// it should be called on the listening side of the connection.
// token is the token from a previous session with this node.
func receiverEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, token []byte) (s secrets, err error) {
authMsg := new(authMsgV4)
authPacket, err := readHandshakeMsg(authMsg, encAuthMsgLen, prv, conn)
h := new(encHandshake)
if err := h.handleAuthMsg(authMsg, prv); err != nil {
authRespMsg, err := h.makeAuthResp()
var authRespPacket []byte
if authMsg.gotPlain {
authRespPacket, err = authRespMsg.sealPlain(h)
authRespPacket, err = sealEIP8(authRespMsg, h)
if _, err = conn.Write(authRespPacket); err != nil {
### doProtocolHandshake
這個方法比較簡單, 加密信道已經建立完畢。 我們看到這裡隻是約定了是否使用Snappy加密然後就退出了。
// doEncHandshake runs the protocol handshake using authenticated
// messages. the protocol handshake is the first authenticated message
// and also verifies whether the encryption handshake 'worked' and the
// remote side actually provided the right public key.
func (t *rlpx) doProtoHandshake(our *protoHandshake) (their *protoHandshake, err error) {
// Writing our handshake happens concurrently, we prefer
// returning the handshake read error. If the remote side
// disconnects us early with a valid reason, we should return it
// as the error so it can be tracked elsewhere.
werr := make(chan error, 1)
go func() { werr <- Send(t.rw, handshakeMsg, our) }()
if their, err = readProtocolHandshake(t.rw, our); err != nil {
<-werr // make sure the write terminates too
if err := <-werr; err != nil {
return nil, fmt.Errorf("write error: %v", err)
// If the protocol version supports Snappy encoding, upgrade immediately
t.rw.snappy = their.Version >= snappyProtocolVersion
return their, nil
### rlpxFrameRW 資料分幀
資料分幀主要通過rlpxFrameRW類來完成的。
// rlpxFrameRW implements a simplified version of RLPx framing.
// chunked messages are not supported and all headers are equal to
// zeroHeader.
// rlpxFrameRW is not safe for concurrent use from multiple goroutines.
type rlpxFrameRW struct {
conn io.ReadWriter
enc cipher.Stream
dec cipher.Stream
macCipher cipher.Block
egressMAC hash.Hash
ingressMAC hash.Hash
snappy bool
我們在完成兩次握手之後。調用newRLPXFrameRW方法建立了這個對象。
t.rw = newRLPXFrameRW(t.fd, sec)
然後提供ReadMsg和WriteMsg方法。這兩個方法直接調用了rlpxFrameRW的ReadMsg和WriteMsg
func (t *rlpx) ReadMsg() (Msg, error) {
t.rmu.Lock()
defer t.rmu.Unlock()
t.fd.SetReadDeadline(time.Now().Add(frameReadTimeout))
return t.rw.ReadMsg()
func (t *rlpx) WriteMsg(msg Msg) error {
defer t.wmu.Unlock()
t.fd.SetWriteDeadline(time.Now().Add(frameWriteTimeout))
return t.rw.WriteMsg(msg)
WriteMsg
func (rw *rlpxFrameRW) WriteMsg(msg Msg) error {
ptype, _ := rlp.EncodeToBytes(msg.Code)
// if snappy is enabled, compress message now
if rw.snappy {
if msg.Size > maxUint24 {
return errPlainMessageTooLarge
}
payload, _ := ioutil.ReadAll(msg.Payload)
payload = snappy.Encode(nil, payload)
msg.Payload = bytes.NewReader(payload)
msg.Size = uint32(len(payload))
// write header
headbuf := make([]byte, 32)
fsize := uint32(len(ptype)) + msg.Size
if fsize > maxUint24 {
return errors.New("message size overflows uint24")
putInt24(fsize, headbuf) // TODO: check overflow
copy(headbuf[3:], zeroHeader)
rw.enc.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now encrypted
// write header MAC
copy(headbuf[16:], updateMAC(rw.egressMAC, rw.macCipher, headbuf[:16]))
if _, err := rw.conn.Write(headbuf); err != nil {
return err
// write encrypted frame, updating the egress MAC hash with
// the data written to conn.
tee := cipher.StreamWriter{S: rw.enc, W: io.MultiWriter(rw.conn, rw.egressMAC)}
if _, err := tee.Write(ptype); err != nil {
if _, err := io.Copy(tee, msg.Payload); err != nil {
if padding := fsize % 16; padding > 0 {
if _, err := tee.Write(zero16[:16-padding]); err != nil {
return err
// write frame MAC. egress MAC hash is up to date because
// frame content was written to it as well.
fmacseed := rw.egressMAC.Sum(nil)
mac := updateMAC(rw.egressMAC, rw.macCipher, fmacseed)
_, err := rw.conn.Write(mac)
ReadMsg
func (rw *rlpxFrameRW) ReadMsg() (msg Msg, err error) {
// read the header
if _, err := io.ReadFull(rw.conn, headbuf); err != nil {
return msg, err
// verify header mac
shouldMAC := updateMAC(rw.ingressMAC, rw.macCipher, headbuf[:16])
if !hmac.Equal(shouldMAC, headbuf[16:]) {
return msg, errors.New("bad header MAC")
rw.dec.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now decrypted
fsize := readInt24(headbuf)
// ignore protocol type for now
// read the frame content
var rsize = fsize // frame size rounded up to 16 byte boundary
rsize += 16 - padding
framebuf := make([]byte, rsize)
if _, err := io.ReadFull(rw.conn, framebuf); err != nil {
// read and validate frame MAC. we can re-use headbuf for that.
rw.ingressMAC.Write(framebuf)
fmacseed := rw.ingressMAC.Sum(nil)
if _, err := io.ReadFull(rw.conn, headbuf[:16]); err != nil {
shouldMAC = updateMAC(rw.ingressMAC, rw.macCipher, fmacseed)
if !hmac.Equal(shouldMAC, headbuf[:16]) {
return msg, errors.New("bad frame MAC")
// decrypt frame content
rw.dec.XORKeyStream(framebuf, framebuf)
// decode message code
content := bytes.NewReader(framebuf[:fsize])
if err := rlp.Decode(content, &msg.Code); err != nil {
msg.Size = uint32(content.Len())
msg.Payload = content
// if snappy is enabled, verify and decompress message
payload, err := ioutil.ReadAll(msg.Payload)
if err != nil {
return msg, err
size, err := snappy.DecodedLen(payload)
if size > int(maxUint24) {
return msg, errPlainMessageTooLarge
payload, err = snappy.Decode(nil, payload)
msg.Size, msg.Payload = uint32(size), bytes.NewReader(payload)
幀結構
normal = not chunked
chunked-0 = First frame of a multi-frame packet
chunked-n = Subsequent frames for multi-frame packet
|| is concatenate
^ is xor
Single-frame packet:
header || header-mac || frame || frame-mac
Multi-frame packet:
header || header-mac || frame-0 ||
[ header || header-mac || frame-n || ... || ]
header || header-mac || frame-last || frame-mac
header: frame-size || header-data || padding
frame-size: 3-byte integer size of frame, big endian encoded (excludes padding)
header-data:
normal: rlp.list(protocol-type[, context-id])
chunked-0: rlp.list(protocol-type, context-id, total-packet-size)
chunked-n: rlp.list(protocol-type, context-id)
values:
protocol-type: < 2**16
context-id: < 2**16 (optional for normal frames)
total-packet-size: < 2**32
padding: zero-fill to 16-byte boundary
header-mac: right128 of egress-mac.update(aes(mac-secret,egress-mac) ^ header-ciphertext).digest
frame:
normal: rlp(packet-type) [|| rlp(packet-data)] || padding
chunked-0: rlp(packet-type) || rlp(packet-data...)
chunked-n: rlp(...packet-data) || padding
padding: zero-fill to 16-byte boundary (only necessary for last frame)
frame-mac: right128 of egress-mac.update(aes(mac-secret,egress-mac) ^ right128(egress-mac.update(frame-ciphertext).digest))
egress-mac: h256, continuously updated with egress-bytes*
ingress-mac: h256, continuously updated with ingress-bytes*
因為加密解密算法我也不是很熟,是以這裡的分析還不是很徹底。 暫時隻是分析了大緻的流程。還有很多細節沒有确認。