Skip to content
LearnBitcoin

ResearchBitcoin Dev Archive lightning-dev list

Encryption spec

7 messages, Mar 7 to Jun 28, 2016. Started by Rusty Russell.

Rusty Russell (4), Anthony Towns, CJP, Peter Todd

Permalink First message in the Wayback Machine

Rusty Russell permalink original

Hi all,

        I'm back, and I've even had some sleep!  I've decided I need to
do more documentation in parallel with actual implementation, so I've
put this temporarily in a fork of Mats' document repo:
        https://github.com/rustyrussell/lightning/blob/master/communications/low/01-encryption.md

But here it is inline (I think I prefer plaintext, but MD isn't too painful to read). Feedback welcome, this is what I'll be moving my implementation towards...

Thanks! Rusty.

# Basis of Lightning Technology RFC 1 #

# Status #

Initial draft

# Author #

Rusty Russell, Blockstream <mailto:rusty at rustcorp.com.au>

# Abstract #

All communications between lightning nodes should be encrypted to make analysis more difficult, and authenticated to avoid malicious interference. Each node has a known identifier which is a unique bitcoin-style public key[1].

## Initial Handshake ##

The first packet sent by a node is of form:

1. `length`: 4 byte little-endian
2. `sessionpubkey`: 33 byte DER-encoded compressed public EC-key

The `length` field is the length after the field itself, and MUST be 33 or greater. `length` MUST NOT exceed 1MB (1048576 bytes).

The `sessionpubkey` field is a compressed public key corresponding to a `sessionsecretkey`. The receiver MUST check that `sessionpubkey` is a valid point.

The `sessionsecretkey` MUST be is unguessable, MUST BE unique for this session, MUST NOT be zero and MUST BE a valid EC key.

Additional fields MAY be added, and MUST be included in the `length` field. These MUST be ignored by implementations which do not understand them.

### Derivation of the Shared Secret and Encryption Keys ###

Once a node has received the initial handshake, it can derive the shared secret using the received `sessionpubkey` point and its own `sessionsecretkey` scalar using EC Diffie-Hellman.

Now both nodes have obtained the shared secret, all packets are encrypted using keys derived from the shared secret. Keys are derived as follows:

* sending-key: SHA256(shared-secret || sending-node-id)
* receiving-key: SHA256(shared-secret || receiving-node-id)

ie. each node combines the secret with its node id to produce the key to encrypt data it sends.

## Encryption of Packets ##

The protocol uses Authenticated Encryption with Additional Data using ChaCha20-Poly1305[2].

Each packet contains a header and a body. The header consists of a 4-byte length indicating the size of the unencrypted body, and an 8-byte packet counter. The 4-byte length and 8-byte counter MUST be encoded in little-endian. The 8-byte counter MUST begin at 0 and be incremented before each transmission after the initial authentication packet; it MAY be non-zero for the authentication packet for re-establishing an existing session.

The 12-byte header for each packet is encrypted separately (resulting in a 28 byte header, when the authentication tag is appended), to offer additional protection from traffic analysis.

The body also has a 16-byte authentication tag appended.

Nonces are 64-bit little-endian numbers, which MUST begin at 0 and MUST be incremented after each encryption (ie. twice per packet), such that headers are encrypted with even nonces and the packet bodies encrypted with odd nonces.

## Authentication Packet ##

Once the shared secret has been exchanged, the identity of the peer has still not been authenticated. The first packet sent MUST be an authentication packet:

	message authenticate {
	  // Which node this is.
	  required bitcoin_pubkey node_id = 1;
	  // Signature of your session key.
	  required signature session_sig = 2;
	};

The receiving node MUST check that:

1. `node_id` is the expected value for the sending node.
2. `session_sig` is a valid secp256k1 ECDSA signature encoded as a
32-byte big endian R value, followed by a 32-byte big endian S value.
3. `session_sig` is the signature of the SHA256 of SHA256 of the receivers
   `node_id`, using the secret key corresponding to the sender's `node_id`.

Additional fields MAY be included, and MUST BE ignored if not understood (to allow for future extensions).

## Rationale ##

Multiple choices are possible for symmetric encryption; AES256-GSM is the other obvious choice but it is slower if there is no hardware acceleration, and the well-supported libsodium[3] doesn't support it on non-accelerated platforms.

The header encryption could use a different key for encryption and eschew 16-bytes for the authentication tag, but modern APIs tend to shy away from offering unauthenticated encryption.

While multiple choices are possible for public-key cryptography, the bitcoin protocol already relies on the secp256k1 elliptic curve, so reusing it here avoids additional dependencies.

The authentication signature ensures that the node owning the `node_id` has specifically initiated this session; using double-sha256 is done because bitcoin transaction signatures use that scheme.

# Security Considerations #

It is strongly recommended that existing, commonly-used, validated libraries be used for encryption and decryption, to avoid the many implementation pitfalls possible.

# References #

1. https://en.bitcoin.it/wiki/Secp256k1
2. https://tools.ietf.org/html/rfc7539
3. https://download.libsodium.org/doc/index.html

# Acknowledgements #

Thanks to Olaoluwa Osuntokun for pointing out the idea of encrypting the length, and noting that it needed a separate key if it didn't include the authentication tag.

Thanks to Mats Jerratsch and Anthony Towns for feedback on initial handshake design.

# Feedback #

Feedback is welcome on the [lightning-dev list](https://www.learnbitcoin.com/archive/lists/lightning-dev).

Anthony Towns in reply to Rusty Russell permalink original

On Mon, Mar 07, 2016 at 02:21:02PM +1030, Rusty Russell wrote:

Quoted text (4 lines)
> ### Derivation of the Shared Secret and Encryption Keys ###
> Once a node has received the initial handshake, it can derive the
> shared secret using the received `sessionpubkey` point and its own
> `sessionsecretkey` scalar using EC Diffie-Hellman.

I think this should be expanded -- I'm assuming the sessionsecretkey is calculated as per libsecp256k1, as:

 (x,y) = y.public*x.secret = x.public*y.secret = g*(x.secret*y.secret)
 sha256( (2 + y%2) || x )

This is different to the NIST specification (see 5.7.1.2 in [0]) which just uses the x coordinate of the point directly, ignoring y and not (necessarily) hashing it.

I've added some wording for this for your consideration:

  https://github.com/rustyrussell/lightning/pull/1
Quoted text (3 lines)
> While multiple choices are possible for public-key cryptography, the
> bitcoin protocol already relies on the secp256k1 elliptic curve, so
> reusing it here avoids additional dependencies.

Hmm, if secp256k1 breaks and gets deprecated, that would be a backwards incompatible change. You could handle this with the protocol as described by incrementing the high byte of "length" in the first message; old clients would see that as an invalid length, >16M, and refuse the connection; new clients could just treat it as a version byte.

Cheers, aj

[0] http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar2.pdf
Rusty Russell in reply to Anthony Towns permalink original

Anthony Towns <aj at erisian.com.au> writes:

Quoted text (19 lines)
> On Mon, Mar 07, 2016 at 02:21:02PM +1030, Rusty Russell wrote:
>> ### Derivation of the Shared Secret and Encryption Keys ###
>> Once a node has received the initial handshake, it can derive the
>> shared secret using the received `sessionpubkey` point and its own
>> `sessionsecretkey` scalar using EC Diffie-Hellman.
>
> I think this should be expanded -- I'm assuming the sessionsecretkey is
> calculated as per libsecp256k1, as:
>
>  (x,y) = y.public*x.secret = x.public*y.secret = g*(x.secret*y.secret)
>  sha256( (2 + y%2) || x )
>
> This is different to the NIST specification (see 5.7.1.2 in [0]) which
> just uses the x coordinate of the point directly, ignoring y and not
> (necessarily) hashing it.
>
> I've added some wording for this for your consideration:
>
>   https://github.com/rustyrussell/lightning/pull/1

Thanks!

Quoted text (9 lines)
>> While multiple choices are possible for public-key cryptography, the
>> bitcoin protocol already relies on the secp256k1 elliptic curve, so
>> reusing it here avoids additional dependencies.
>
> Hmm, if secp256k1 breaks and gets deprecated, that would be a backwards
> incompatible change. You could handle this with the protocol as described
> by incrementing the high byte of "length" in the first message; old
> clients would see that as an invalid length, >16M, and refuse the
> connection; new clients could just treat it as a version byte.

The intention is that you'd do any upgrade by adding a second key, and increasing the `length` field to cover it (say, to 66). If either side sends a 33-byte initial packet, they've not ugpraded (whether you hang up at this point or continue is up to you); if both send >= 66 bytes, you use the second value instead.

I don't see what manipulating the length does?

Cheers, Rusty. PS. I should add an "Extensions" section to each BOLT...

Quoted text (5 lines)
>
> Cheers,
> aj
>
> [0] http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar2.pdf
CJP in reply to Rusty Russell permalink original

Hi,

I'm about to start implementing an encryption layer for Amiko Pay, and since there already is a BOLT for encryption, I thought I might as well see if I can use it. Now that I've read it[1], I have some questions.

But first, let me comment that, in general, I like the general design of the encryption layer. It's generic and simple, making it easy to analyze, which is A Good Thing.

My first question is: would it be possible / useful for a node to use different public keys for different links? I guess it is possible: the node that's establishing the connection knows what link it tries to connect, so it can already send out an authenticate message. The other node initially doesn't know what link the new connection belongs to, but, after receiving the authenticate message, it knows, so it can select its own corresponding key and reply with its own authenticate message. Then again, I'm not sure if this is very useful. Using different keys could be good for privacy (not revealing that both links go to the same node), but a node that listens for multiple links on the same network location (e.g. host:port in TCP) already shows to its peers that both links have a shared identity. The key used for authentication could be different from keys used for other things, like routing addresses or output addresses of microtransaction channels, maybe linked in master/slave key configurations (one key signs the other). Maybe there still is a deniability problem (your peer reveals data and you want to say 'it wasn't me') but I'm not sure that can be solved.

I was wondering to what degree communication truly looks like random data, or can be distinguished from it. I guess that the very first 4 bytes, usually being the little-endian value 33, already gives away that this protocol is being used. Furthermore, timing analysis could reveal the size of messages being sent, possibly revealing information about what is being done with the payload protocol inside the encryption layer. Is there a way to protect against that? You might want to append unused data to messages to make them fixed size (or at least multiples of a fixed size), or random size, but that reduces bandwidth efficiency, and the required amount of padding depends on the payload protocol.

How is the authenticate message distinguished from other messages? I don't see something like a message type ID. Is it simply that the first message in a session is ALWAYS an authenticate message, and other messages are NEVER an authenticate message?

Right now, the description of session_sig in the authenticate message says: "session_sig is the signature of the SHA256 of SHA256 of the receivers node_id, using the secret key corresponding to the sender's node_id". I am not sure how that is useful. More importantly, I don't understand what stops someone from performing a MITM attack. Shouldn't you include something like a signature of your sessionpubkey, signed with your node_id key?

Assuming that a MITM attacker can guess the boundaries of messages, what stops him/her from duplicating messages, or removing messages? Is a certain state preserved between encryption/authentication of different messages?

What is the meaning of the ack field in the authenticate message? The number of non-authenticate messages before an authenticate message *in a session* is always zero, isn't it? I see it's the number of messages *received and processed*. Since, to my knowledge, data streams in both directions are asynchronous, that could be a non-deterministic value, right? What should a receiving node check about the ack value? If it can't check anything, then what is the use of the value? Is this about message re-transmission across multiple sessions? In that case, please think about wrap-around behavior. I'm not sure a 64-bit counter will ever wrap around, but we should make sure the first time it happens won't be "in the field".

thanks, CJP

[1] https://github.com/rustyrussell/lightning-rfc/blob/master/bolts/01-encryption.md

Peter Todd in reply to CJP permalink original

On Sun, Jun 26, 2016 at 01:53:11PM +0200, CJP wrote:

FYI, have you seen the work being done by Jonas Schnelli for Bitcoin on P at P layer encryption?

https://github.com/bitcoin/bips/blob/master/bip-0151.mediawiki

He's using a subset of the encryption scheme OpenSSH uses, which means he gets the benefit of all the review that's been done for OpenSSH. If you use it, you get that benefit, as well as review from the Bitcoin Core team.

Quoted text (5 lines)
> Hi,
>
> I'm about to start implementing an encryption layer for Amiko Pay, and
> since there already is a BOLT for encryption, I thought I might as well
> see if I can use it. Now that I've read it[1], I have some questions.
Rusty Russell in reply to Peter Todd permalink original

Peter Todd <pete at petertodd.org> writes:

Quoted text (10 lines)
> On Sun, Jun 26, 2016 at 01:53:11PM +0200, CJP wrote:
>
> FYI, have you seen the work being done by Jonas Schnelli for Bitcoin on P at P
> layer encryption?
>
> https://github.com/bitcoin/bips/blob/master/bip-0151.mediawiki
>
> He's using a subset of the encryption scheme OpenSSH uses, which means he gets
> the benefit of all the review that's been done for OpenSSH. If you use it, you
> get that benefit, as well as review from the Bitcoin Core team.

Yes, this draft predates that work, but it would be nicer.

They're pretty similar, let's see if we can make them closer. Our needs are slightly different: there's no "unencrypted" comms we need to bootstrap, and we want peer authentication always.

Cheers, Rusty.

Rusty Russell in reply to CJP permalink original

CJP <cjp at ultimatestunts.nl> writes:

Quoted text (5 lines)
> Hi,
>
> I'm about to start implementing an encryption layer for Amiko Pay, and
> since there already is a BOLT for encryption, I thought I might as well
> see if I can use it. Now that I've read it[1], I have some questions.

Good!

Quoted text (21 lines)
> But first, let me comment that, in general, I like the general design of
> the encryption layer. It's generic and simple, making it easy to
> analyze, which is A Good Thing.
>
> My first question is: would it be possible / useful for a node to use
> different public keys for different links? I guess it is possible: the
> node that's establishing the connection knows what link it tries to
> connect, so it can already send out an authenticate message. The other
> node initially doesn't know what link the new connection belongs to,
> but, after receiving the authenticate message, it knows, so it can
> select its own corresponding key and reply with its own authenticate
> message. Then again, I'm not sure if this is very useful. Using
> different keys could be good for privacy (not revealing that both links
> go to the same node), but a node that listens for multiple links on the
> same network location (e.g. host:port in TCP) already shows to its peers
> that both links have a shared identity. The key used for authentication
> could be different from keys used for other things, like routing
> addresses or output addresses of microtransaction channels, maybe linked
> in master/slave key configurations (one key signs the other). Maybe
> there still is a deniability problem (your peer reveals data and you
> want to say 'it wasn't me') but I'm not sure that can be solved.

One can imagine a front end cache which points to different backends depending on who the incoming connection is for. (The classic http multihost problem).

This is one reason packets are extensible, if we turn out to want this in future.

Quoted text (10 lines)
> I was wondering to what degree communication truly looks like random
> data, or can be distinguished from it. I guess that the very first 4
> bytes, usually being the little-endian value 33, already gives away that
> this protocol is being used. Furthermore, timing analysis could reveal
> the size of messages being sent, possibly revealing information about
> what is being done with the payload protocol inside the encryption
> layer. Is there a way to protect against that? You might want to append
> unused data to messages to make them fixed size (or at least multiples
> of a fixed size), or random size, but that reduces bandwidth efficiency,
> and the required amount of padding depends on the payload protocol.

The lengths (after that first packet) are encrypted. We can add ping and pong messages for dummies later if we want to, but solving traffic analysis is not really a priority for now (AFAICT a bottomless well).

Quoted text (4 lines)
> How is the authenticate message distinguished from other messages? I
> don't see something like a message type ID. Is it simply that the first
> message in a session is ALWAYS an authenticate message, and other
> messages are NEVER an authenticate message?

It's a protobuf, like all messages. We should probably mention that :)

Quoted text (7 lines)
> Right now, the description of session_sig in the authenticate message
> says: "session_sig is the signature of the SHA256 of SHA256 of the
> receivers node_id, using the secret key corresponding to the sender's
> node_id". I am not sure how that is useful. More importantly, I don't
> understand what stops someone from performing a MITM attack. Shouldn't
> you include something like a signature of your sessionpubkey, signed
> with your node_id key?

Yes :( It should sign the sessionpubkey of course. I'll fix...

Quoted text (4 lines)
> Assuming that a MITM attacker can guess the boundaries of messages, what
> stops him/her from duplicating messages, or removing messages? Is a
> certain state preserved between encryption/authentication of different
> messages?

The nonce increments:

Nonces are 64-bit little-endian numbers, which MUST begin at 0 and MUST be incremented after each encryption (ie. twice per message), such that headers are encrypted with even nonces and the message bodies encrypted with odd nonces.

Quoted text (3 lines)
> What is the meaning of the ack field in the authenticate message? The
> number of non-authenticate messages before an authenticate message *in a
> session* is always zero, isn't it?

It's to resume existing sessions. It's underspecified because I had not implemented that (and my protocol test uses the count of commitments received, which turns out to be superior).

Quoted text (9 lines)
> I see it's the number of messages
> *received and processed*. Since, to my knowledge, data streams in both
> directions are asynchronous, that could be a non-deterministic value,
> right? What should a receiving node check about the ack value? If it
> can't check anything, then what is the use of the value? Is this about
> message re-transmission across multiple sessions? In that case, please
> think about wrap-around behavior. I'm not sure a 64-bit counter will
> ever wrap around, but we should make sure the first time it happens
> won't be "in the field".

64 bit counters won't wrap during my watch :)

Thanks, Rusty.