-
Notifications
You must be signed in to change notification settings - Fork 0
/
interest.hpp
600 lines (534 loc) · 16.3 KB
/
interest.hpp
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
#ifndef NDNPH_PACKET_INTEREST_HPP
#define NDNPH_PACKET_INTEREST_HPP
#include "../keychain/private-key.hpp"
#include "../keychain/public-key.hpp"
#include "../port/random/port.hpp"
#include "../port/sha256/port.hpp"
#include "../port/timingsafe/port.hpp"
#include "convention.hpp"
namespace ndnph {
namespace detail {
inline bool
encodeFwHint(Encoder& encoder, const Name& fwHint)
{
if (!fwHint) {
return false;
}
return encoder.prependTlv(TT::ForwardingHint, fwHint);
}
inline bool
decodeFwHint(const Decoder::Tlv& d, Name* target)
{
return EvDecoder::decode(d, { TT::ForwardingHint }, EvDecoder::def<TT::Name>(target));
}
/** @brief Fields in parameterized/signed Interest. */
struct InterestParams
{
tlv::Value appParameters;
ISigInfo sigInfo;
tlv::Value sigValue;
tlv::Value signedParams;
tlv::Value allParams;
};
/** @brief Fields in Interest or Nack. */
class InterestObj : public InRegion
{
public:
explicit InterestObj(Region& region)
: InRegion(region)
, canBePrefix(false)
, mustBeFresh(false)
, nackReason(0)
{
port::RandomSource::generate(reinterpret_cast<uint8_t*>(&nonce), sizeof(nonce));
}
enum
{
DefaultLifetime = 4000,
MaxHopLimit = 0xFF,
};
public:
InterestParams* params = nullptr; // only relevant on a decoded packet
Name name;
Name fwHint;
uint32_t nonce = 0;
uint16_t lifetime = DefaultLifetime;
uint8_t hopLimit = MaxHopLimit;
bool canBePrefix : 1;
bool mustBeFresh : 1;
uint8_t nackReason : 3;
};
class InterestRefBase : public RefRegion<InterestObj>
{
public:
using RefRegion::RefRegion;
const Name& getName() const
{
return obj->name;
}
bool getCanBePrefix() const
{
return obj->canBePrefix;
}
bool getMustBeFresh() const
{
return obj->mustBeFresh;
}
const Name& getFwHint() const
{
return obj->fwHint;
}
uint32_t getNonce() const
{
return obj->nonce;
}
uint16_t getLifetime() const
{
return obj->lifetime;
}
uint8_t getHopLimit() const
{
return obj->hopLimit;
}
protected:
~InterestRefBase() = default;
void encodeMiddle(Encoder& encoder) const
{
encoder.prepend(
[this](Encoder& encoder) {
if (obj->canBePrefix) {
encoder.prependTlv(TT::CanBePrefix);
}
},
[this](Encoder& encoder) {
if (obj->mustBeFresh) {
encoder.prependTlv(TT::MustBeFresh);
}
},
[this](Encoder& encoder) { return encodeFwHint(encoder, obj->fwHint); },
tlv::NniElement<tlv::NNI4>(TT::Nonce, obj->nonce),
[this](Encoder& encoder) {
if (obj->lifetime != InterestObj::DefaultLifetime) {
encoder.prependTlv(TT::InterestLifetime, tlv::NNI(obj->lifetime));
}
},
[this](Encoder& encoder) {
if (obj->hopLimit != InterestObj::MaxHopLimit) {
encoder.prependTlv(TT::HopLimit, tlv::NNI1(obj->hopLimit));
}
});
}
static int findParamsDigest(const Name& name)
{
int pos = -1;
for (const auto& comp : name) {
++pos;
if (comp.type() == TT::ParametersSha256DigestComponent) {
return pos;
}
}
return -1;
}
};
class ParameterizedInterestRef : public InterestRefBase
{
public:
explicit ParameterizedInterestRef() = default;
explicit ParameterizedInterestRef(InterestObj* interest, tlv::Value appParameters)
: InterestRefBase(interest)
, m_appParameters(std::move(appParameters))
{}
void encodeTo(Encoder& encoder) const
{
if (obj == nullptr) {
encoder.setError();
return;
}
encodeImpl(encoder, [this](Encoder& encoder) { encodeAppParameters(encoder); });
}
protected:
~ParameterizedInterestRef() = default;
void encodeName(Encoder& encoder, const tlv::Value& params) const
{
port::Sha256 hash;
hash.update(params.begin(), params.size());
uint8_t digestComp[34];
if (!hash.final(&digestComp[2])) {
encoder.setError();
return;
}
digestComp[0] = TT::ParametersSha256DigestComponent;
digestComp[1] = NDNPH_SHA256_LEN;
tlv::Value prefix, suffix;
int posParamsDigest = findParamsDigest(obj->name);
if (posParamsDigest >= 0) {
auto namePrefix = obj->name.slice(0, posParamsDigest);
prefix = tlv::Value(namePrefix.value(), namePrefix.length());
auto nameSuffix = obj->name.slice(posParamsDigest + 1);
suffix = tlv::Value(nameSuffix.value(), nameSuffix.length());
} else {
prefix = tlv::Value(obj->name.value(), obj->name.length());
}
encoder.prependTlv(TT::Name, prefix, tlv::Value(digestComp, sizeof(digestComp)), suffix);
}
void encodeAppParameters(Encoder& encoder) const
{
encoder.prependTlv(TT::AppParameters, m_appParameters);
}
template<typename Fn>
void encodeImpl(Encoder& encoder, const Fn& encodeParams) const
{
tlv::Value params;
encoder.prependTlv(
TT::Interest, [this, ¶ms](Encoder& encoder) { encodeName(encoder, params); },
[this](Encoder& encoder) { encodeMiddle(encoder); },
[&](Encoder& encoder) {
const uint8_t* afterParams = encoder.begin();
encodeParams(encoder);
if (!encoder) {
return;
}
params = tlv::Value(encoder.begin(), afterParams);
});
}
protected:
tlv::Value m_appParameters;
};
class SignedInterestRef : public ParameterizedInterestRef
{
public:
explicit SignedInterestRef() = default;
explicit SignedInterestRef(InterestObj* interest, tlv::Value appParameters, const PrivateKey& key,
ISigInfo sigInfo)
: ParameterizedInterestRef(interest, std::move(appParameters))
, m_key(&key)
{
key.updateSigInfo(sigInfo);
m_sigInfo = std::move(sigInfo);
}
void encodeTo(Encoder& encoder) const
{
if (m_key == nullptr) {
encoder.setError();
return;
}
tlv::Value signedName;
int posParamsDigest = findParamsDigest(obj->name);
if (posParamsDigest < 0) {
signedName = tlv::Value(obj->name.value(), obj->name.length());
} else if (static_cast<size_t>(posParamsDigest) == obj->name.size() - 1) {
auto prefix = obj->name.getPrefix(-1);
signedName = tlv::Value(prefix.value(), prefix.length());
} else {
encoder.setError();
return;
}
const uint8_t* afterSig = encoder.begin();
size_t maxSigLen = m_key->getMaxSigLen();
uint8_t* sigBuf = encoder.prependRoom(maxSigLen);
encoder.prependTypeLength(TT::DSigValue, maxSigLen);
const uint8_t* afterSignedPortion = encoder.begin();
encoder.prepend([this](Encoder& encoder) { encodeAppParameters(encoder); }, m_sigInfo);
if (!encoder) {
return;
}
tlv::Value signedPortion(encoder.begin(), afterSignedPortion);
ssize_t sigLen = m_key->sign({ signedName, signedPortion }, sigBuf);
if (sigLen < 0) {
encoder.setError();
return;
}
encoder.resetFront(const_cast<uint8_t*>(afterSig));
encodeImpl(encoder, [=](Encoder& encoder) {
encoder.prepend(
[=](Encoder& encoder) {
uint8_t* room = encoder.prependRoom(signedPortion.size());
assert(room != nullptr);
if (room != signedPortion.begin()) {
std::memmove(room, signedPortion.begin(), signedPortion.size());
}
},
[=](Encoder& encoder) {
uint8_t* room = encoder.prependRoom(sigLen);
assert(room != nullptr);
if (room != sigBuf) {
std::memmove(room, sigBuf, sigLen);
}
encoder.prependTypeLength(TT::ISigValue, sigLen);
});
});
}
private:
const PrivateKey* m_key = nullptr;
ISigInfo m_sigInfo;
};
} // namespace detail
/** @brief Interest packet. */
class Interest
: public Printable
, public detail::InterestRefBase
{
public:
using InterestRefBase::InterestRefBase;
void setName(const Name& v)
{
obj->name = v;
}
void setCanBePrefix(bool v)
{
obj->canBePrefix = v;
}
void setMustBeFresh(bool v)
{
obj->mustBeFresh = v;
}
void setFwHint(const Name& v)
{
obj->fwHint = v;
}
void setNonce(uint32_t v)
{
obj->nonce = v;
}
void setLifetime(uint16_t v)
{
obj->lifetime = v;
}
void setHopLimit(uint8_t v)
{
obj->hopLimit = v;
}
/**
* @brief Retrieve AppParameters.
* @pre only available on decoded packet.
* @note To create Interest packet with AppParameters, use parameterize().
*/
tlv::Value getAppParameters() const
{
if (obj->params == nullptr) {
return tlv::Value();
}
return obj->params->appParameters;
}
/**
* @brief Retrieve SignatureInfo.
* @pre only available on decoded packet.
*/
const ISigInfo* getSigInfo() const
{
return obj->params == nullptr ? nullptr : &obj->params->sigInfo;
}
/** @brief Encode the Interest without AppParameters. */
void encodeTo(Encoder& encoder) const
{
encoder.prependTlv(TT::Interest, obj->name,
[this](Encoder& encoder) { encodeMiddle(encoder); });
}
/** @brief Result of Interest::sign operation. */
using Signed = detail::SignedInterestRef;
/** @brief Result of Interest::parameterize operation. */
class Parameterized : public detail::ParameterizedInterestRef
{
public:
using detail::ParameterizedInterestRef::ParameterizedInterestRef;
Signed sign(const PrivateKey& key, ISigInfo sigInfo = ISigInfo()) const
{
return Signed(obj, m_appParameters, key, std::move(sigInfo));
}
template<typename ISigPolicy>
Signed sign(const PrivateKey& key, Region& region, ISigPolicy& policy) const
{
ISigInfo si;
if (!policy.create(region, si)) {
return Signed();
}
return sign(key, si);
}
};
/**
* @brief Add AppParameters to the packet.
* @pre Name contains zero or one ParametersSha256DigestComponent.
* @return an Encodable object, with an additional `sign(const PrivateKey&)` method
* to create a signed Interest. This object is valid only if Interest and
* appParameters are kept alive. It's recommended to pass it to Encoder
* immediately without saving as variable.
* @note Unrecognized fields found during decoding are not preserved in encoding output.
* @note This method does not set sigValue. Packet is not verifiable after this operation.
*/
Parameterized parameterize(tlv::Value appParameters) const
{
return Parameterized(obj, std::move(appParameters));
}
/**
* @brief Sign the packet with a private key.
* @pre If Name contains ParametersSha256DigestComponent, it is the last component.
* @return an Encodable object. This object is valid only if Interest and PrivateKey are kept
* alive. It's recommended to pass it to Encoder immediately without saving as variable.
* @note Unrecognized fields found during decoding are not preserved in encoding output.
* @note This method does not set sigValue. Packet is not verifiable after this operation.
*
* To create a signed Interest with AppParameters, call parameterize() first, then
* call sign() on its return value.
*/
template<typename... Arg>
Signed sign(Arg&&... arg) const
{
return parameterize(tlv::Value()).sign(std::forward<Arg>(arg)...);
}
/** @brief Decode packet. */
bool decodeFrom(const Decoder::Tlv& input)
{
return EvDecoder::decode(
input, { TT::Interest }, EvDecoder::def<TT::Name>(&obj->name),
EvDecoder::def<TT::CanBePrefix>([this](const Decoder::Tlv&) { setCanBePrefix(true); }),
EvDecoder::def<TT::MustBeFresh>([this](const Decoder::Tlv&) { setMustBeFresh(true); }),
EvDecoder::def<TT::ForwardingHint>(
[this](const Decoder::Tlv& d) { return detail::decodeFwHint(d, &obj->fwHint); }),
EvDecoder::defNni<TT::Nonce, tlv::NNI4>(&obj->nonce),
EvDecoder::defNni<TT::InterestLifetime>(&obj->lifetime),
EvDecoder::defNni<TT::HopLimit, tlv::NNI1>(&obj->hopLimit),
EvDecoder::def<TT::AppParameters>([this, &input](const Decoder::Tlv& d) {
obj->params = regionOf(obj).template make<detail::InterestParams>();
if (obj->params == nullptr) {
return false;
}
obj->params->allParams = tlv::Value(d.tlv, input.tlv + input.size);
return obj->params->appParameters.decodeFrom(d);
}),
EvDecoder::def<TT::ISigInfo>([this](const Decoder::Tlv& d) {
return obj->params != nullptr && obj->params->sigInfo.decodeFrom(d);
}),
EvDecoder::def<TT::ISigValue>([this](const Decoder::Tlv& d) {
if (obj->params == nullptr) {
return false;
}
obj->params->signedParams = tlv::Value(obj->params->allParams.begin(), d.tlv);
return obj->params->sigValue.decodeFrom(d);
}));
}
/**
* @brief Encode then decode as Interest packet.
*
* This is useful for obtaining an Interest packet in decoded state from the result of signing.
*/
template<typename Encodable>
bool decodeFrom(Encodable&& encodable)
{
if (obj == nullptr) {
return false;
}
Encoder encoder(regionOf(obj));
if (!encoder.prepend(std::forward<Encodable>(encodable))) {
encoder.discard();
return false;
}
encoder.trim();
return Decoder(encoder.begin(), encoder.size()).decode(*this);
}
/**
* @brief Check ParametersSha256DigestComponent.
* @return whether the digest is correct.
*
* This method only works on decoded packet.
* It's unnecessary to call this method if you are going to use verify().
*/
bool checkDigest() const
{
if (obj->params == nullptr) {
return false;
}
int posParamsDigest = findParamsDigest(obj->name);
if (posParamsDigest < 0) {
return false;
}
Component paramsDigest = obj->name[posParamsDigest];
uint8_t digest[NDNPH_SHA256_LEN];
port::Sha256 hash;
hash.update(obj->params->allParams.begin(), obj->params->allParams.size());
return hash.final(digest) &&
port::TimingSafeEqual()(digest, sizeof(digest), paramsDigest.value(),
paramsDigest.length());
}
/**
* @brief Verify the packet with a public key.
* @return verification result.
*
* This method only works on decoded packet. It does not work on packet that
* has been modified or (re-)signed.
*/
bool verify(const PublicKey& key) const
{
if (!checkDigest()) {
return false;
}
int posParamsDigest = findParamsDigest(obj->name);
if (static_cast<size_t>(posParamsDigest) != obj->name.size() - 1) {
return false;
}
auto signedName = obj->name.getPrefix(-1);
return key.verify(
{ tlv::Value(signedName.value(), signedName.length()), obj->params->signedParams },
obj->params->sigValue.begin(), obj->params->sigValue.size());
}
/**
* @brief Determine whether Data can satisfy Interest.
* @tparam DataT the ndnph::Data type.
*
* This method only works reliably on decoded packets. For packets that are being constructed
* or modified, this method may give incorrect results for parameterized/signed Interests or
* Interest carrying implicit digest component.
*/
template<typename DataT>
bool match(const DataT& data) const
{
if (obj->mustBeFresh && data.getFreshnessPeriod() == 0) {
return false;
}
const Name& dataName = data.getName();
switch (obj->name.compare(dataName)) {
case Name::CMP_EQUAL:
return true;
case Name::CMP_LPREFIX:
return obj->canBePrefix;
case Name::CMP_RPREFIX: {
Component lastComp = obj->name[-1];
uint8_t digest[NDNPH_SHA256_LEN];
return obj->name.size() == dataName.size() + 1 &&
lastComp.is<convention::ImplicitDigest>() && data.computeImplicitDigest(digest) &&
port::TimingSafeEqual()(digest, sizeof(digest), lastComp.value(), lastComp.length());
}
default:
return false;
}
}
#ifdef NDNPH_PRINT_ARDUINO
size_t printTo(::Print& p) const final
{
size_t count = 0;
count += p.print(getName());
if (getCanBePrefix()) {
count += p.print("[P]");
}
if (getMustBeFresh()) {
count += p.print("[F]");
}
return count;
}
#endif
};
#ifdef NDNPH_PRINT_OSTREAM
inline std::ostream&
operator<<(std::ostream& os, const Interest& interest)
{
os << interest.getName();
if (interest.getCanBePrefix()) {
os << "[P]";
}
if (interest.getMustBeFresh()) {
os << "[F]";
}
return os;
}
#endif
} // namespace ndnph
#endif // NDNPH_PACKET_INTEREST_HPP