Stateless verification of InvoiceRequest
[rust-lightning] / lightning / src / offers / signer.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Utilities for signing offer messages and verifying metadata.
11
12 use bitcoin::hashes::{Hash, HashEngine};
13 use bitcoin::hashes::cmp::fixed_time_eq;
14 use bitcoin::hashes::hmac::{Hmac, HmacEngine};
15 use bitcoin::hashes::sha256::Hash as Sha256;
16 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey, self};
17 use core::convert::TryFrom;
18 use core::fmt;
19 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
20 use crate::offers::merkle::TlvRecord;
21 use crate::util::ser::Writeable;
22
23 use crate::prelude::*;
24
25 const DERIVED_METADATA_HMAC_INPUT: &[u8; 16] = &[1; 16];
26 const DERIVED_METADATA_AND_KEYS_HMAC_INPUT: &[u8; 16] = &[2; 16];
27
28 /// Message metadata which possibly is derived from [`MetadataMaterial`] such that it can be
29 /// verified.
30 #[derive(Clone)]
31 pub(super) enum Metadata {
32         /// Metadata as parsed, supplied by the user, or derived from the message contents.
33         Bytes(Vec<u8>),
34
35         /// Metadata to be derived from message contents and given material.
36         Derived(MetadataMaterial),
37
38         /// Metadata and signing pubkey to be derived from message contents and given material.
39         DerivedSigningPubkey(MetadataMaterial),
40 }
41
42 impl Metadata {
43         pub fn as_bytes(&self) -> Option<&Vec<u8>> {
44                 match self {
45                         Metadata::Bytes(bytes) => Some(bytes),
46                         Metadata::Derived(_) => None,
47                         Metadata::DerivedSigningPubkey(_) => None,
48                 }
49         }
50
51         pub fn has_derivation_material(&self) -> bool {
52                 match self {
53                         Metadata::Bytes(_) => false,
54                         Metadata::Derived(_) => true,
55                         Metadata::DerivedSigningPubkey(_) => true,
56                 }
57         }
58
59         pub fn derives_keys(&self) -> bool {
60                 match self {
61                         // Infer whether Metadata::derived_from was called on Metadata::DerivedSigningPubkey to
62                         // produce Metadata::Bytes. This is merely to determine which fields should be included
63                         // when verifying a message. It doesn't necessarily indicate that keys were in fact
64                         // derived, as wouldn't be the case if a Metadata::Bytes with length Nonce::LENGTH had
65                         // been set explicitly.
66                         Metadata::Bytes(bytes) => bytes.len() == Nonce::LENGTH,
67                         Metadata::Derived(_) => false,
68                         Metadata::DerivedSigningPubkey(_) => true,
69                 }
70         }
71
72         pub fn without_keys(self) -> Self {
73                 match self {
74                         Metadata::Bytes(_) => self,
75                         Metadata::Derived(_) => self,
76                         Metadata::DerivedSigningPubkey(material) => Metadata::Derived(material),
77                 }
78         }
79
80         pub fn derive_from<W: Writeable, T: secp256k1::Signing>(
81                 self, tlv_stream: W, secp_ctx: Option<&Secp256k1<T>>
82         ) -> (Self, Option<KeyPair>) {
83                 match self {
84                         Metadata::Bytes(_) => (self, None),
85                         Metadata::Derived(mut metadata_material) => {
86                                 tlv_stream.write(&mut metadata_material.hmac).unwrap();
87                                 (Metadata::Bytes(metadata_material.derive_metadata()), None)
88                         },
89                         Metadata::DerivedSigningPubkey(mut metadata_material) => {
90                                 tlv_stream.write(&mut metadata_material.hmac).unwrap();
91                                 let secp_ctx = secp_ctx.unwrap();
92                                 let (metadata, keys) = metadata_material.derive_metadata_and_keys(secp_ctx);
93                                 (Metadata::Bytes(metadata), Some(keys))
94                         },
95                 }
96         }
97 }
98
99 impl fmt::Debug for Metadata {
100         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101                 match self {
102                         Metadata::Bytes(bytes) => bytes.fmt(f),
103                         Metadata::Derived(_) => f.write_str("Derived"),
104                         Metadata::DerivedSigningPubkey(_) => f.write_str("DerivedSigningPubkey"),
105                 }
106         }
107 }
108
109 #[cfg(test)]
110 impl PartialEq for Metadata {
111         fn eq(&self, other: &Self) -> bool {
112                 match self {
113                         Metadata::Bytes(bytes) => if let Metadata::Bytes(other_bytes) = other {
114                                 bytes == other_bytes
115                         } else {
116                                 false
117                         },
118                         Metadata::Derived(_) => false,
119                         Metadata::DerivedSigningPubkey(_) => false,
120                 }
121         }
122 }
123
124 /// Material used to create metadata for a message.
125 #[derive(Clone)]
126 pub(super) struct MetadataMaterial {
127         nonce: Nonce,
128         hmac: HmacEngine<Sha256>,
129 }
130
131 impl MetadataMaterial {
132         pub fn new(nonce: Nonce, expanded_key: &ExpandedKey, iv_bytes: &[u8; IV_LEN]) -> Self {
133                 Self {
134                         nonce,
135                         hmac: expanded_key.hmac_for_offer(nonce, iv_bytes),
136                 }
137         }
138
139         fn derive_metadata(mut self) -> Vec<u8> {
140                 self.hmac.input(DERIVED_METADATA_HMAC_INPUT);
141
142                 let mut bytes = self.nonce.as_slice().to_vec();
143                 bytes.extend_from_slice(&Hmac::from_engine(self.hmac).into_inner());
144                 bytes
145         }
146
147         fn derive_metadata_and_keys<T: secp256k1::Signing>(
148                 mut self, secp_ctx: &Secp256k1<T>
149         ) -> (Vec<u8>, KeyPair) {
150                 self.hmac.input(DERIVED_METADATA_AND_KEYS_HMAC_INPUT);
151
152                 let hmac = Hmac::from_engine(self.hmac);
153                 let privkey = SecretKey::from_slice(hmac.as_inner()).unwrap();
154                 let keys = KeyPair::from_secret_key(secp_ctx, &privkey);
155                 (self.nonce.as_slice().to_vec(), keys)
156         }
157 }
158
159 /// Verifies data given in a TLV stream was used to produce the given metadata, consisting of:
160 /// - a 128-bit [`Nonce`] and possibly
161 /// - a [`Sha256`] hash of the nonce and the TLV records using the [`ExpandedKey`].
162 ///
163 /// If the latter is not included in the metadata, the TLV stream is used to check if the given
164 /// `signing_pubkey` can be derived from it.
165 pub(super) fn verify_metadata<'a, T: secp256k1::Signing>(
166         metadata: &Vec<u8>, expanded_key: &ExpandedKey, iv_bytes: &[u8; IV_LEN],
167         signing_pubkey: PublicKey, tlv_stream: impl core::iter::Iterator<Item = TlvRecord<'a>>,
168         secp_ctx: &Secp256k1<T>
169 ) -> bool {
170         if metadata.len() < Nonce::LENGTH {
171                 return false;
172         }
173
174         let nonce = match Nonce::try_from(&metadata[..Nonce::LENGTH]) {
175                 Ok(nonce) => nonce,
176                 Err(_) => return false,
177         };
178         let mut hmac = expanded_key.hmac_for_offer(nonce, iv_bytes);
179
180         for record in tlv_stream {
181                 hmac.input(record.record_bytes);
182         }
183
184         if metadata.len() == Nonce::LENGTH {
185                 hmac.input(DERIVED_METADATA_AND_KEYS_HMAC_INPUT);
186                 let hmac = Hmac::from_engine(hmac);
187                 let derived_pubkey = SecretKey::from_slice(hmac.as_inner()).unwrap().public_key(&secp_ctx);
188                 fixed_time_eq(&signing_pubkey.serialize(), &derived_pubkey.serialize())
189         } else if metadata[Nonce::LENGTH..].len() == Sha256::LEN {
190                 hmac.input(DERIVED_METADATA_HMAC_INPUT);
191                 fixed_time_eq(&metadata[Nonce::LENGTH..], &Hmac::from_engine(hmac).into_inner())
192         } else {
193                 false
194         }
195 }