forked from lightningdevkit/rust-lightning
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsigner.rs
510 lines (440 loc) · 17.7 KB
/
signer.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! Utilities for signing offer messages and verifying metadata.
use bitcoin::hashes::{Hash, HashEngine};
use bitcoin::hashes::cmp::fixed_time_eq;
use bitcoin::hashes::hmac::{Hmac, HmacEngine};
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::secp256k1::{Keypair, PublicKey, Secp256k1, SecretKey, self};
use types::payment::PaymentHash;
use core::fmt;
use crate::blinded_path::payment::UnauthenticatedReceiveTlvs;
use crate::ln::channelmanager::PaymentId;
use crate::ln::inbound_payment::{ExpandedKey, IV_LEN};
use crate::offers::merkle::TlvRecord;
use crate::offers::nonce::Nonce;
use crate::util::ser::Writeable;
use crate::prelude::*;
// Use a different HMAC input for each derivation. Otherwise, an attacker could:
// - take an Offer that has metadata consisting of a nonce and HMAC
// - strip off the HMAC and replace the signing_pubkey where the privkey is the HMAC,
// - generate and sign an invoice using the new signing_pubkey, and
// - claim they paid it since they would know the preimage of the invoice's payment_hash
const DERIVED_METADATA_HMAC_INPUT: &[u8; 16] = &[1; 16];
const DERIVED_METADATA_AND_KEYS_HMAC_INPUT: &[u8; 16] = &[2; 16];
// Additional HMAC inputs to distinguish use cases, either Offer or Refund/InvoiceRequest, where
// metadata for the latter contain an encrypted PaymentId.
const WITHOUT_ENCRYPTED_PAYMENT_ID_HMAC_INPUT: &[u8; 16] = &[3; 16];
const WITH_ENCRYPTED_PAYMENT_ID_HMAC_INPUT: &[u8; 16] = &[4; 16];
// HMAC input for a `PaymentId`. The HMAC is used in `OffersContext::OutboundPayment`.
const OFFER_PAYMENT_ID_HMAC_INPUT: &[u8; 16] = &[5; 16];
// HMAC input for a `PaymentId`. The HMAC is used in `AsyncPaymentsContext::OutboundPayment`.
#[cfg(async_payments)]
const ASYNC_PAYMENT_ID_HMAC_INPUT: &[u8; 16] = &[6; 16];
// HMAC input for a `PaymentHash`. The HMAC is used in `OffersContext::InboundPayment`.
const PAYMENT_HASH_HMAC_INPUT: &[u8; 16] = &[7; 16];
// HMAC input for `ReceiveTlvs`. The HMAC is used in `blinded_path::payment::PaymentContext`.
const PAYMENT_TLVS_HMAC_INPUT: &[u8; 16] = &[8; 16];
// HMAC input used in `AsyncPaymentsContext::InboundPayment` to authenticate inbound
// held_htlc_available onion messages.
#[cfg(async_payments)]
const ASYNC_PAYMENTS_HELD_HTLC_HMAC_INPUT: &[u8; 16] = &[9; 16];
/// Message metadata which possibly is derived from [`MetadataMaterial`] such that it can be
/// verified.
#[derive(Clone)]
pub(super) enum Metadata {
/// Metadata as parsed, supplied by the user, or derived from the message contents.
///
/// This is the terminal variant; any `Metadata` in a created message will always use this.
Bytes(Vec<u8>),
/// Metadata for deriving keys included as recipient data in a blinded path.
///
/// This variant should only be used at verification time, never when building.
RecipientData(Nonce),
/// Metadata for deriving keys included as payer data in a blinded path.
///
/// This variant should only be used at verification time, never when building.
PayerData([u8; PaymentId::LENGTH + Nonce::LENGTH]),
/// Metadata to be derived from message contents and given material.
///
/// This variant should only be used at building time.
Derived(MetadataMaterial),
/// Metadata and signing pubkey to be derived from message contents and given material.
///
/// This variant should only be used at building time.
DerivedSigningPubkey(MetadataMaterial),
}
impl Metadata {
pub fn payer_data(payment_id: PaymentId, nonce: Nonce, expanded_key: &ExpandedKey) -> Self {
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut bytes = [0u8; PaymentId::LENGTH + Nonce::LENGTH];
bytes[..PaymentId::LENGTH].copy_from_slice(encrypted_payment_id.as_slice());
bytes[PaymentId::LENGTH..].copy_from_slice(nonce.as_slice());
Metadata::PayerData(bytes)
}
pub fn as_bytes(&self) -> Option<&Vec<u8>> {
match self {
Metadata::Bytes(bytes) => Some(bytes),
_ => { debug_assert!(false); None },
}
}
pub fn has_derivation_material(&self) -> bool {
match self {
Metadata::Bytes(_) => false,
Metadata::RecipientData(_) => { debug_assert!(false); false },
Metadata::PayerData(_) => { debug_assert!(false); false },
Metadata::Derived(_) => true,
Metadata::DerivedSigningPubkey(_) => true,
}
}
pub fn derives_payer_keys(&self) -> bool {
match self {
// Infer whether Metadata::derived_from was called on Metadata::DerivedSigningPubkey to
// produce Metadata::Bytes. This is merely to determine which fields should be included
// when verifying a message. It doesn't necessarily indicate that keys were in fact
// derived, as wouldn't be the case if a Metadata::Bytes with length PaymentId::LENGTH +
// Nonce::LENGTH had been set explicitly.
Metadata::Bytes(bytes) => bytes.len() == PaymentId::LENGTH + Nonce::LENGTH,
Metadata::RecipientData(_) => false,
Metadata::PayerData(_) => true,
Metadata::Derived(_) => false,
Metadata::DerivedSigningPubkey(_) => true,
}
}
pub fn derives_recipient_keys(&self) -> bool {
match self {
// Infer whether Metadata::derived_from was called on Metadata::DerivedSigningPubkey to
// produce Metadata::Bytes. This is merely to determine which fields should be included
// when verifying a message. It doesn't necessarily indicate that keys were in fact
// derived, as wouldn't be the case if a Metadata::Bytes with length Nonce::LENGTH had
// been set explicitly.
Metadata::Bytes(bytes) => bytes.len() == Nonce::LENGTH,
Metadata::RecipientData(_) => true,
Metadata::PayerData(_) => false,
Metadata::Derived(_) => false,
Metadata::DerivedSigningPubkey(_) => true,
}
}
/// Indicates that signing keys should not be derived when calling [`derive_from`]. Only
/// applicable to state [`Metadata::DerivedSigningPubkey`]; calling this in other states will
/// result in no change.
///
/// [`derive_from`]: Self::derive_from
pub fn without_keys(self) -> Self {
match self {
Metadata::Bytes(_) => self,
Metadata::RecipientData(_) => { debug_assert!(false); self },
Metadata::PayerData(_) => { debug_assert!(false); self },
Metadata::Derived(_) => self,
Metadata::DerivedSigningPubkey(material) => Metadata::Derived(material),
}
}
pub fn derive_from<W: Writeable, T: secp256k1::Signing>(
self, iv_bytes: &[u8; IV_LEN], tlv_stream: W, secp_ctx: Option<&Secp256k1<T>>
) -> (Self, Option<Keypair>) {
match self {
Metadata::Bytes(_) => (self, None),
Metadata::RecipientData(_) => { debug_assert!(false); (self, None) },
Metadata::PayerData(_) => { debug_assert!(false); (self, None) },
Metadata::Derived(metadata_material) => {
(Metadata::Bytes(metadata_material.derive_metadata(iv_bytes, tlv_stream)), None)
},
Metadata::DerivedSigningPubkey(metadata_material) => {
let secp_ctx = secp_ctx.unwrap();
let (metadata, keys) =
metadata_material.derive_metadata_and_keys(iv_bytes, tlv_stream, secp_ctx);
(Metadata::Bytes(metadata), Some(keys))
},
}
}
}
impl Default for Metadata {
fn default() -> Self {
Metadata::Bytes(vec![])
}
}
impl AsRef<[u8]> for Metadata {
fn as_ref(&self) -> &[u8] {
match self {
Metadata::Bytes(bytes) => &bytes,
Metadata::RecipientData(nonce) => &nonce.0,
Metadata::PayerData(bytes) => bytes.as_slice(),
Metadata::Derived(_) => { debug_assert!(false); &[] },
Metadata::DerivedSigningPubkey(_) => { debug_assert!(false); &[] },
}
}
}
impl fmt::Debug for Metadata {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Metadata::Bytes(bytes) => bytes.fmt(f),
Metadata::RecipientData(Nonce(bytes)) => bytes.fmt(f),
Metadata::PayerData(bytes) => bytes.fmt(f),
Metadata::Derived(_) => f.write_str("Derived"),
Metadata::DerivedSigningPubkey(_) => f.write_str("DerivedSigningPubkey"),
}
}
}
#[cfg(test)]
impl PartialEq for Metadata {
fn eq(&self, other: &Self) -> bool {
match self {
Metadata::Bytes(bytes) => if let Metadata::Bytes(other_bytes) = other {
bytes == other_bytes
} else {
false
},
Metadata::RecipientData(_) => false,
Metadata::PayerData(_) => false,
Metadata::Derived(_) => false,
Metadata::DerivedSigningPubkey(_) => false,
}
}
}
/// Material used to create metadata for a message.
#[derive(Clone)]
pub(super) struct MetadataMaterial {
nonce: Nonce,
hmac: HmacEngine<Sha256>,
// Some for payer metadata and None for offer metadata
encrypted_payment_id: Option<[u8; PaymentId::LENGTH]>,
}
impl MetadataMaterial {
pub fn new(nonce: Nonce, expanded_key: &ExpandedKey, payment_id: Option<PaymentId>) -> Self {
// Encrypt payment_id
let encrypted_payment_id = payment_id.map(|payment_id| {
expanded_key.crypt_for_offer(payment_id.0, nonce)
});
Self {
nonce,
hmac: expanded_key.hmac_for_offer(),
encrypted_payment_id,
}
}
fn derive_metadata<W: Writeable>(mut self, iv_bytes: &[u8; IV_LEN], tlv_stream: W) -> Vec<u8> {
self.hmac.input(iv_bytes);
self.hmac.input(&self.nonce.0);
tlv_stream.write(&mut self.hmac).unwrap();
self.hmac.input(DERIVED_METADATA_HMAC_INPUT);
self.maybe_include_encrypted_payment_id();
let mut bytes = self.encrypted_payment_id.map(|id| id.to_vec()).unwrap_or_default();
bytes.extend_from_slice(self.nonce.as_slice());
bytes.extend_from_slice(Hmac::from_engine(self.hmac).as_byte_array());
bytes
}
fn derive_metadata_and_keys<W: Writeable, T: secp256k1::Signing>(
mut self, iv_bytes: &[u8; IV_LEN], tlv_stream: W, secp_ctx: &Secp256k1<T>
) -> (Vec<u8>, Keypair) {
self.hmac.input(iv_bytes);
self.hmac.input(&self.nonce.0);
tlv_stream.write(&mut self.hmac).unwrap();
self.hmac.input(DERIVED_METADATA_AND_KEYS_HMAC_INPUT);
self.maybe_include_encrypted_payment_id();
let bytes = self.encrypted_payment_id.map(|id| id.to_vec()).unwrap_or_default();
let hmac = Hmac::from_engine(self.hmac);
let privkey = SecretKey::from_slice(hmac.as_byte_array()).unwrap();
let keys = Keypair::from_secret_key(secp_ctx, &privkey);
(bytes, keys)
}
fn maybe_include_encrypted_payment_id(&mut self) {
match self.encrypted_payment_id {
None => self.hmac.input(WITHOUT_ENCRYPTED_PAYMENT_ID_HMAC_INPUT),
Some(encrypted_payment_id) => {
self.hmac.input(WITH_ENCRYPTED_PAYMENT_ID_HMAC_INPUT);
self.hmac.input(&encrypted_payment_id)
},
}
}
}
pub(super) fn derive_keys(nonce: Nonce, expanded_key: &ExpandedKey) -> Keypair {
const IV_BYTES: &[u8; IV_LEN] = b"LDK Invoice ~~~~";
let mut hmac = expanded_key.hmac_for_offer();
hmac.input(IV_BYTES);
hmac.input(&nonce.0);
let secp_ctx = Secp256k1::new();
let privkey = SecretKey::from_slice(Hmac::from_engine(hmac).as_byte_array()).unwrap();
Keypair::from_secret_key(&secp_ctx, &privkey)
}
/// Verifies data given in a TLV stream was used to produce the given metadata, consisting of:
/// - a 256-bit [`PaymentId`],
/// - a 128-bit [`Nonce`], and possibly
/// - a [`Sha256`] hash of the nonce and the TLV records using the [`ExpandedKey`].
///
/// If the latter is not included in the metadata, the TLV stream is used to check if the given
/// `signing_pubkey` can be derived from it.
///
/// Returns the [`PaymentId`] that should be used for sending the payment.
pub(super) fn verify_payer_metadata<'a, T: secp256k1::Signing>(
metadata: &[u8], expanded_key: &ExpandedKey, iv_bytes: &[u8; IV_LEN],
signing_pubkey: PublicKey, tlv_stream: impl core::iter::Iterator<Item = TlvRecord<'a>>,
secp_ctx: &Secp256k1<T>
) -> Result<PaymentId, ()> {
if metadata.len() < PaymentId::LENGTH {
return Err(());
}
let mut encrypted_payment_id = [0u8; PaymentId::LENGTH];
encrypted_payment_id.copy_from_slice(&metadata[..PaymentId::LENGTH]);
let mut hmac = hmac_for_message(
&metadata[PaymentId::LENGTH..], expanded_key, iv_bytes, tlv_stream
)?;
hmac.input(WITH_ENCRYPTED_PAYMENT_ID_HMAC_INPUT);
hmac.input(&encrypted_payment_id);
verify_metadata(
&metadata[PaymentId::LENGTH..], Hmac::from_engine(hmac), signing_pubkey, secp_ctx
)?;
let nonce = Nonce::try_from(&metadata[PaymentId::LENGTH..][..Nonce::LENGTH]).unwrap();
let payment_id = expanded_key.crypt_for_offer(encrypted_payment_id, nonce);
Ok(PaymentId(payment_id))
}
/// Verifies data given in a TLV stream was used to produce the given metadata, consisting of:
/// - a 128-bit [`Nonce`] and possibly
/// - a [`Sha256`] hash of the nonce and the TLV records using the [`ExpandedKey`].
///
/// If the latter is not included in the metadata, the TLV stream is used to check if the given
/// `signing_pubkey` can be derived from it.
///
/// Returns the [`Keypair`] for signing the invoice, if it can be derived from the metadata.
pub(super) fn verify_recipient_metadata<'a, T: secp256k1::Signing>(
metadata: &[u8], expanded_key: &ExpandedKey, iv_bytes: &[u8; IV_LEN],
signing_pubkey: PublicKey, tlv_stream: impl core::iter::Iterator<Item = TlvRecord<'a>>,
secp_ctx: &Secp256k1<T>
) -> Result<Option<Keypair>, ()> {
let mut hmac = hmac_for_message(metadata, expanded_key, iv_bytes, tlv_stream)?;
hmac.input(WITHOUT_ENCRYPTED_PAYMENT_ID_HMAC_INPUT);
verify_metadata(metadata, Hmac::from_engine(hmac), signing_pubkey, secp_ctx)
}
fn verify_metadata<T: secp256k1::Signing>(
metadata: &[u8], hmac: Hmac<Sha256>, signing_pubkey: PublicKey, secp_ctx: &Secp256k1<T>
) -> Result<Option<Keypair>, ()> {
if metadata.len() == Nonce::LENGTH {
let derived_keys = Keypair::from_secret_key(
secp_ctx, &SecretKey::from_slice(hmac.as_byte_array()).unwrap()
);
if fixed_time_eq(&signing_pubkey.serialize(), &derived_keys.public_key().serialize()) {
Ok(Some(derived_keys))
} else {
Err(())
}
} else if metadata[Nonce::LENGTH..].len() == Sha256::LEN {
if fixed_time_eq(&metadata[Nonce::LENGTH..], &hmac.to_byte_array()) {
Ok(None)
} else {
Err(())
}
} else {
Err(())
}
}
fn hmac_for_message<'a>(
metadata: &[u8], expanded_key: &ExpandedKey, iv_bytes: &[u8; IV_LEN],
tlv_stream: impl core::iter::Iterator<Item = TlvRecord<'a>>
) -> Result<HmacEngine<Sha256>, ()> {
if metadata.len() < Nonce::LENGTH {
return Err(());
}
let nonce = match Nonce::try_from(&metadata[..Nonce::LENGTH]) {
Ok(nonce) => nonce,
Err(_) => return Err(()),
};
let mut hmac = expanded_key.hmac_for_offer();
hmac.input(iv_bytes);
hmac.input(&nonce.0);
for record in tlv_stream {
hmac.input(record.record_bytes);
}
if metadata.len() == Nonce::LENGTH {
hmac.input(DERIVED_METADATA_AND_KEYS_HMAC_INPUT);
} else {
hmac.input(DERIVED_METADATA_HMAC_INPUT);
}
Ok(hmac)
}
pub(crate) fn hmac_for_offer_payment_id(
payment_id: PaymentId, nonce: Nonce, expanded_key: &ExpandedKey,
) -> Hmac<Sha256> {
hmac_for_payment_id(payment_id, nonce, OFFER_PAYMENT_ID_HMAC_INPUT, expanded_key)
}
pub(crate) fn verify_offer_payment_id(
payment_id: PaymentId, hmac: Hmac<Sha256>, nonce: Nonce, expanded_key: &ExpandedKey,
) -> Result<(), ()> {
if hmac_for_offer_payment_id(payment_id, nonce, expanded_key) == hmac { Ok(()) } else { Err(()) }
}
pub(crate) fn hmac_for_payment_hash(
payment_hash: PaymentHash, nonce: Nonce, expanded_key: &ExpandedKey,
) -> Hmac<Sha256> {
const IV_BYTES: &[u8; IV_LEN] = b"LDK Payment Hash";
let mut hmac = expanded_key.hmac_for_offer();
hmac.input(IV_BYTES);
hmac.input(&nonce.0);
hmac.input(PAYMENT_HASH_HMAC_INPUT);
hmac.input(&payment_hash.0);
Hmac::from_engine(hmac)
}
pub(crate) fn verify_payment_hash(
payment_hash: PaymentHash, hmac: Hmac<Sha256>, nonce: Nonce, expanded_key: &ExpandedKey,
) -> Result<(), ()> {
if hmac_for_payment_hash(payment_hash, nonce, expanded_key) == hmac { Ok(()) } else { Err(()) }
}
#[cfg(async_payments)]
pub(crate) fn hmac_for_async_payment_id(
payment_id: PaymentId, nonce: Nonce, expanded_key: &ExpandedKey,
) -> Hmac<Sha256> {
hmac_for_payment_id(payment_id, nonce, ASYNC_PAYMENT_ID_HMAC_INPUT, expanded_key)
}
#[cfg(async_payments)]
pub(crate) fn verify_async_payment_id(
payment_id: PaymentId, hmac: Hmac<Sha256>, nonce: Nonce, expanded_key: &ExpandedKey,
) -> Result<(), ()> {
if hmac_for_async_payment_id(payment_id, nonce, expanded_key) == hmac { Ok(()) } else { Err(()) }
}
fn hmac_for_payment_id(
payment_id: PaymentId, nonce: Nonce, hmac_input: &[u8; 16], expanded_key: &ExpandedKey,
) -> Hmac<Sha256> {
const IV_BYTES: &[u8; IV_LEN] = b"LDK Payment ID ~";
let mut hmac = expanded_key.hmac_for_offer();
hmac.input(IV_BYTES);
hmac.input(&nonce.0);
hmac.input(hmac_input);
hmac.input(&payment_id.0);
Hmac::from_engine(hmac)
}
pub(crate) fn hmac_for_payment_tlvs(
receive_tlvs: &UnauthenticatedReceiveTlvs, nonce: Nonce, expanded_key: &ExpandedKey,
) -> Hmac<Sha256> {
const IV_BYTES: &[u8; IV_LEN] = b"LDK Payment TLVs";
let mut hmac = expanded_key.hmac_for_offer();
hmac.input(IV_BYTES);
hmac.input(&nonce.0);
hmac.input(PAYMENT_TLVS_HMAC_INPUT);
receive_tlvs.write(&mut hmac).unwrap();
Hmac::from_engine(hmac)
}
pub(crate) fn verify_payment_tlvs(
receive_tlvs: &UnauthenticatedReceiveTlvs, hmac: Hmac<Sha256>, nonce: Nonce,
expanded_key: &ExpandedKey,
) -> Result<(), ()> {
if hmac_for_payment_tlvs(receive_tlvs, nonce, expanded_key) == hmac { Ok(()) } else { Err(()) }
}
#[cfg(async_payments)]
pub(crate) fn hmac_for_held_htlc_available_context(
nonce: Nonce, expanded_key: &ExpandedKey,
) -> Hmac<Sha256> {
const IV_BYTES: &[u8; IV_LEN] = b"LDK Held HTLC OM";
let mut hmac = expanded_key.hmac_for_offer();
hmac.input(IV_BYTES);
hmac.input(&nonce.0);
hmac.input(ASYNC_PAYMENTS_HELD_HTLC_HMAC_INPUT);
Hmac::from_engine(hmac)
}
#[cfg(async_payments)]
pub(crate) fn verify_held_htlc_available_context(
nonce: Nonce, hmac: Hmac<Sha256>, expanded_key: &ExpandedKey,
) -> Result<(), ()> {
if hmac_for_held_htlc_available_context(nonce, expanded_key) == hmac { Ok(()) } else { Err(()) }
}