-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
SecureSessionMgr.cpp
523 lines (434 loc) · 19.5 KB
/
SecureSessionMgr.cpp
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
/*
*
* Copyright (c) 2020-2021 Project CHIP Authors
* Copyright (c) 2013-2017 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* This file implements the CHIP Connection object that maintains a UDP connection.
* TODO This class should be extended to support TCP as well...
*
*/
#include "SecureSessionMgr.h"
#include <inttypes.h>
#include <string.h>
#include <app/util/basic-types.h>
#include <core/CHIPKeyIds.h>
#include <platform/CHIPDeviceLayer.h>
#include <protocols/secure_channel/Constants.h>
#include <support/CodeUtils.h>
#include <support/SafeInt.h>
#include <support/logging/CHIPLogging.h>
#include <transport/AdminPairingTable.h>
#include <transport/SecureMessageCodec.h>
#include <transport/TransportMgr.h>
#include <inttypes.h>
namespace chip {
using System::PacketBufferHandle;
using Transport::PeerAddress;
using Transport::PeerConnectionState;
uint32_t EncryptedPacketBufferHandle::GetMsgId() const
{
PacketHeader header;
uint16_t headerSize = 0;
CHIP_ERROR err = header.Decode((*this)->Start(), (*this)->DataLength(), &headerSize);
if (err == CHIP_NO_ERROR)
{
return header.GetMessageId();
}
ChipLogError(Inet, "Failed to decode EncryptedPacketBufferHandle header with error: %s", ErrorStr(err));
return 0;
}
SecureSessionMgr::SecureSessionMgr() : mState(State::kNotReady) {}
SecureSessionMgr::~SecureSessionMgr()
{
CancelExpiryTimer();
}
CHIP_ERROR SecureSessionMgr::Init(NodeId localNodeId, System::Layer * systemLayer, TransportMgrBase * transportMgr,
Transport::AdminPairingTable * admins,
Transport::MessageCounterManagerInterface * messageCounterManager)
{
VerifyOrReturnError(mState == State::kNotReady, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(transportMgr != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
mState = State::kInitialized;
mLocalNodeId = localNodeId;
mSystemLayer = systemLayer;
mTransportMgr = transportMgr;
mAdmins = admins;
mMessageCounterManager = messageCounterManager;
mGlobalEncryptedMessageCounter.Init();
ChipLogProgress(Inet, "local node id is 0x" ChipLogFormatX64, ChipLogValueX64(mLocalNodeId));
ScheduleExpiryTimer();
mTransportMgr->SetSecureSessionMgr(this);
return CHIP_NO_ERROR;
}
void SecureSessionMgr::Shutdown()
{
CancelExpiryTimer();
mMessageCounterManager = nullptr;
mState = State::kNotReady;
mLocalNodeId = kUndefinedNodeId;
mSystemLayer = nullptr;
mTransportMgr = nullptr;
mAdmins = nullptr;
mCB = nullptr;
}
Transport::Type SecureSessionMgr::GetTransportType(NodeId peerNodeId)
{
PeerConnectionState * state = mPeerConnections.FindPeerConnectionState(peerNodeId, nullptr);
if (state)
{
return state->GetPeerAddress().GetTransportType();
}
return Transport::Type::kUndefined;
}
CHIP_ERROR SecureSessionMgr::SendMessage(SecureSessionHandle session, PayloadHeader & payloadHeader,
System::PacketBufferHandle && msgBuf, EncryptedPacketBufferHandle * bufferRetainSlot)
{
PacketHeader unusedPacketHeader;
return SendMessage(session, payloadHeader, unusedPacketHeader, std::move(msgBuf), bufferRetainSlot,
EncryptionState::kPayloadIsUnencrypted);
}
CHIP_ERROR SecureSessionMgr::SendEncryptedMessage(SecureSessionHandle session, EncryptedPacketBufferHandle && msgBuf,
EncryptedPacketBufferHandle * bufferRetainSlot)
{
VerifyOrReturnError(!msgBuf.IsNull(), CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(!msgBuf.HasChainedBuffer(), CHIP_ERROR_INVALID_MESSAGE_LENGTH);
// Our send path needs a (writable) PacketBuffer (e.g. so it can encode a
// PacketHeader into it), so get that from the EncryptedPacketBufferHandle.
System::PacketBufferHandle mutableBuf(std::move(msgBuf).CastToWritable());
// Advancing the start to encrypted header, since SendMessage will attach the packet header on top of it.
PacketHeader packetHeader;
ReturnErrorOnFailure(packetHeader.DecodeAndConsume(mutableBuf));
PayloadHeader payloadHeader;
return SendMessage(session, payloadHeader, packetHeader, std::move(mutableBuf), bufferRetainSlot,
EncryptionState::kPayloadIsEncrypted);
}
CHIP_ERROR SecureSessionMgr::SendMessage(SecureSessionHandle session, PayloadHeader & payloadHeader, PacketHeader & packetHeader,
System::PacketBufferHandle && msgBuf, EncryptedPacketBufferHandle * bufferRetainSlot,
EncryptionState encryptionState)
{
CHIP_ERROR err = CHIP_NO_ERROR;
PeerConnectionState * state = nullptr;
NodeId localNodeId = mLocalNodeId;
Transport::AdminPairingInfo * admin = nullptr;
VerifyOrExit(mState == State::kInitialized, err = CHIP_ERROR_INCORRECT_STATE);
VerifyOrExit(!msgBuf.IsNull(), err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(!msgBuf->HasChainedBuffer(), err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
// Find an active connection to the specified peer node
state = GetPeerConnectionState(session);
VerifyOrExit(state != nullptr, err = CHIP_ERROR_NOT_CONNECTED);
// This marks any connection where we send data to as 'active'
mPeerConnections.MarkConnectionActive(state);
admin = mAdmins->FindAdminWithId(state->GetAdminId());
VerifyOrExit(admin != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
localNodeId = admin->GetNodeId();
if (IsControlMessage(payloadHeader))
{
packetHeader.SetSecureSessionControlMsg(true);
}
if (encryptionState == EncryptionState::kPayloadIsUnencrypted)
{
MessageCounter & counter = GetSendCounterForPacket(payloadHeader, *state);
err = SecureMessageCodec::Encode(localNodeId, state, payloadHeader, packetHeader, msgBuf, counter);
SuccessOrExit(err);
}
err = packetHeader.EncodeBeforeData(msgBuf);
SuccessOrExit(err);
// Retain the packet buffer in case it's needed for retransmissions.
if (bufferRetainSlot != nullptr)
{
*bufferRetainSlot = EncryptedPacketBufferHandle::MarkEncrypted(msgBuf.Retain());
}
ChipLogProgress(Inet, "Sending msg from 0x" ChipLogFormatX64 " to 0x" ChipLogFormatX64 " at utc time: %" PRId64 " msec",
ChipLogValueX64(localNodeId), ChipLogValueX64(state->GetPeerNodeId()), System::Layer::GetClock_MonotonicMS());
if (state->GetTransport() != nullptr)
{
ChipLogProgress(Inet, "Sending secure msg on connection specific transport");
err = state->GetTransport()->SendMessage(state->GetPeerAddress(), std::move(msgBuf));
}
else if (mTransportMgr != nullptr)
{
ChipLogProgress(Inet, "Sending secure msg on generic transport");
err = mTransportMgr->SendMessage(state->GetPeerAddress(), std::move(msgBuf));
}
else
{
ChipLogError(Inet, "The transport manager is not initialized. Unable to send the message");
err = CHIP_ERROR_INCORRECT_STATE;
}
ChipLogProgress(Inet, "Secure msg send status %s", ErrorStr(err));
SuccessOrExit(err);
exit:
if (!msgBuf.IsNull())
{
const char * errStr = ErrorStr(err);
if (state == nullptr)
{
ChipLogError(Inet, "Secure transport could not find a valid PeerConnection: %s", errStr);
}
}
return err;
}
CHIP_ERROR SecureSessionMgr::NewPairing(const Optional<Transport::PeerAddress> & peerAddr, NodeId peerNodeId,
PairingSession * pairing, SecureSession::SessionRole direction, Transport::AdminId admin,
Transport::Base * transport)
{
uint16_t peerKeyId = pairing->GetPeerKeyId();
uint16_t localKeyId = pairing->GetLocalKeyId();
PeerConnectionState * state = mPeerConnections.FindPeerConnectionState(Optional<NodeId>::Value(peerNodeId), peerKeyId, nullptr);
// Find any existing connection with the same node and key ID
if (state && (state->GetAdminId() == Transport::kUndefinedAdminId || state->GetAdminId() == admin))
{
mPeerConnections.MarkConnectionExpired(
state, [this](const Transport::PeerConnectionState & state1) { HandleConnectionExpired(state1); });
}
ChipLogDetail(Inet, "New pairing for device 0x%08" PRIx32 "%08" PRIx32 ", key %d!!", static_cast<uint32_t>(peerNodeId >> 32),
static_cast<uint32_t>(peerNodeId), peerKeyId);
state = nullptr;
ReturnErrorOnFailure(
mPeerConnections.CreateNewPeerConnectionState(Optional<NodeId>::Value(peerNodeId), peerKeyId, localKeyId, &state));
ReturnErrorCodeIf(state == nullptr, CHIP_ERROR_NO_MEMORY);
state->SetAdminId(admin);
state->SetTransport(transport);
if (peerAddr.HasValue() && peerAddr.Value().GetIPAddress() != Inet::IPAddress::Any)
{
state->SetPeerAddress(peerAddr.Value());
}
else if (peerAddr.HasValue() && peerAddr.Value().GetTransportType() == Transport::Type::kBle)
{
state->SetPeerAddress(peerAddr.Value());
}
else if (peerAddr.HasValue() &&
(peerAddr.Value().GetTransportType() == Transport::Type::kTcp ||
peerAddr.Value().GetTransportType() == Transport::Type::kUdp))
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
ReturnErrorOnFailure(pairing->DeriveSecureSession(state->GetSecureSession(), direction));
if (mCB != nullptr)
{
state->GetSessionMessageCounter().GetPeerMessageCounter().SetCounter(pairing->GetPeerCounter());
mCB->OnNewConnection({ state->GetPeerNodeId(), state->GetPeerKeyID(), admin }, this);
}
return CHIP_NO_ERROR;
}
void SecureSessionMgr::ScheduleExpiryTimer()
{
CHIP_ERROR err =
mSystemLayer->StartTimer(CHIP_PEER_CONNECTION_TIMEOUT_CHECK_FREQUENCY_MS, SecureSessionMgr::ExpiryTimerCallback, this);
VerifyOrDie(err == CHIP_NO_ERROR);
}
void SecureSessionMgr::CancelExpiryTimer()
{
if (mSystemLayer != nullptr)
{
mSystemLayer->CancelTimer(SecureSessionMgr::ExpiryTimerCallback, this);
}
}
void SecureSessionMgr::OnMessageReceived(const PeerAddress & peerAddress, System::PacketBufferHandle && msg)
{
PacketHeader packetHeader;
ReturnOnFailure(packetHeader.DecodeAndConsume(msg));
if (packetHeader.GetFlags().Has(Header::FlagValues::kSecure))
{
SecureMessageDispatch(packetHeader, peerAddress, std::move(msg));
}
else
{
MessageDispatch(packetHeader, peerAddress, std::move(msg));
}
}
void SecureSessionMgr::MessageDispatch(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress,
System::PacketBufferHandle && msg)
{
if (mCB != nullptr)
{
PayloadHeader payloadHeader;
ReturnOnFailure(payloadHeader.DecodeAndConsume(msg));
mCB->OnMessageReceived(packetHeader, payloadHeader, SecureSessionHandle(), peerAddress, std::move(msg), this);
}
}
void SecureSessionMgr::SecureMessageDispatch(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress,
System::PacketBufferHandle && msg)
{
CHIP_ERROR err = CHIP_NO_ERROR;
PeerConnectionState * state = mPeerConnections.FindPeerConnectionState(packetHeader.GetEncryptionKeyID(), nullptr);
PayloadHeader payloadHeader;
Transport::AdminPairingInfo * admin = nullptr;
bool modifiedAdmin = false;
NodeId localNodeId;
FabricId fabricId;
VerifyOrExit(!msg.IsNull(), ChipLogError(Inet, "Secure transport received NULL packet, discarding"));
if (state == nullptr)
{
ChipLogError(Inet, "Data received on an unknown connection (%d). Dropping it!!", packetHeader.GetEncryptionKeyID());
ExitNow(err = CHIP_ERROR_KEY_NOT_FOUND_FROM_PEER);
}
// Verify message counter
if (packetHeader.GetFlags().Has(Header::FlagValues::kSecureSessionControlMessage))
{
// TODO: control message counter is not implemented yet
}
else
{
if (!state->GetSessionMessageCounter().GetPeerMessageCounter().IsSynchronized())
{
// Queue and start message sync procedure
err = mMessageCounterManager->QueueReceivedMessageAndStartSync(
packetHeader, { state->GetPeerNodeId(), state->GetPeerKeyID(), state->GetAdminId() }, state, peerAddress,
std::move(msg));
if (err != CHIP_NO_ERROR)
{
ChipLogError(Inet,
"Message counter synchronization for received message, failed to "
"QueueReceivedMessageAndStartSync, err = %" PRId32,
err);
}
else
{
ChipLogDetail(Inet, "Received message have been queued due to peer counter is not synced");
}
return;
}
err = state->GetSessionMessageCounter().GetPeerMessageCounter().Verify(packetHeader.GetMessageId());
if (err != CHIP_NO_ERROR)
{
ChipLogError(Inet, "Message counter verify failed, err = %" PRId32, err);
}
SuccessOrExit(err);
}
admin = mAdmins->FindAdminWithId(state->GetAdminId());
VerifyOrExit(admin != nullptr,
ChipLogError(Inet, "Secure transport received packet for unknown admin (%p, %d) pairing, discarding", state,
state->GetAdminId()));
if (packetHeader.GetDestinationNodeId().HasValue() && admin->GetNodeId() != kUndefinedNodeId)
{
VerifyOrExit(admin->GetNodeId() == packetHeader.GetDestinationNodeId().Value(),
ChipLogError(Inet,
"Secure transport received message, but destination node ID (0x" ChipLogFormatX64
") doesn't match our node ID (0x" ChipLogFormatX64 "), discarding",
ChipLogValueX64(packetHeader.GetDestinationNodeId().Value()),
ChipLogValueX64(admin->GetNodeId())));
}
if (packetHeader.GetDestinationNodeId().HasValue())
{
ChipLogProgress(Inet, "Secure transport received message destined to fabric %d, node 0x" ChipLogFormatX64 ". Key ID %d",
static_cast<int>(state->GetAdminId()), ChipLogValueX64(packetHeader.GetDestinationNodeId().Value()),
packetHeader.GetEncryptionKeyID());
}
else
{
ChipLogProgress(Inet, "Secure transport received message for fabric %d without node ID. Key ID %d",
static_cast<int>(state->GetAdminId()), packetHeader.GetEncryptionKeyID());
}
mPeerConnections.MarkConnectionActive(state);
// Decode the message
VerifyOrExit(CHIP_NO_ERROR == SecureMessageCodec::Decode(state, payloadHeader, packetHeader, msg),
ChipLogError(Inet, "Secure transport received message, but failed to decode it, discarding"));
if (packetHeader.GetFlags().Has(Header::FlagValues::kSecureSessionControlMessage))
{
// TODO: control message counter is not implemented yet
}
else
{
state->GetSessionMessageCounter().GetPeerMessageCounter().Commit(packetHeader.GetMessageId());
}
// See operational-credentials-server.cpp for explanation as to why fabricId is being set to commissioner node id
// This is temporary code until AddOptCert is implemented through which an admin will be correctly added with the correct
// fields.
// TODO: Remove temporary code once AddOptCert is implemented
if (packetHeader.GetSourceNodeId().HasValue())
{
if (state->GetPeerNodeId() == kUndefinedNodeId)
{
state->SetPeerNodeId(packetHeader.GetSourceNodeId().Value());
}
}
// TODO: Remove temporary code once AddOptCert is implemented
if (packetHeader.GetDestinationNodeId().HasValue())
{
localNodeId = packetHeader.GetDestinationNodeId().Value();
if (localNodeId != kUndefinedNodeId && admin->GetNodeId() != localNodeId)
{
admin->SetNodeId(localNodeId);
ChipLogProgress(Inet, "Setting nodeID %" PRIX64 " on admin.", admin->GetNodeId());
modifiedAdmin = true;
}
}
// TODO: Remove temporary code once AddOptCert is implemented
if (packetHeader.GetSourceNodeId().HasValue())
{
fabricId = packetHeader.GetSourceNodeId().Value();
if (fabricId != kUndefinedFabricId && admin->GetFabricId() != fabricId)
{
admin->SetFabricId(packetHeader.GetSourceNodeId().Value());
ChipLogProgress(Inet, "Setting fabricID %" PRIX64 " on admin.", admin->GetFabricId());
modifiedAdmin = true;
}
}
// TODO: Remove temporary code once AddOptCert is implemented
if (modifiedAdmin)
{
ChipLogProgress(Inet, "Since admin was modified, persisting changes to KVS");
mAdmins->Store(admin->GetAdminId());
}
// TODO: once mDNS address resolution is available reconsider if this is required
// This updates the peer address once a packet is received from a new address
// and serves as a way to auto-detect peer changing IPs.
if (state->GetPeerAddress() != peerAddress)
{
state->SetPeerAddress(peerAddress);
}
if (mCB != nullptr)
{
SecureSessionHandle session(state->GetPeerNodeId(), state->GetPeerKeyID(), state->GetAdminId());
mCB->OnMessageReceived(packetHeader, payloadHeader, session, peerAddress, std::move(msg), this);
}
exit:
if (err != CHIP_NO_ERROR && mCB != nullptr)
{
mCB->OnReceiveError(err, peerAddress, this);
}
}
void SecureSessionMgr::HandleConnectionExpired(const Transport::PeerConnectionState & state)
{
char addr[Transport::PeerAddress::kMaxToStringSize];
state.GetPeerAddress().ToString(addr);
ChipLogDetail(Inet, "Connection from '%s' expired", addr);
if (mCB != nullptr)
{
mCB->OnConnectionExpired({ state.GetPeerNodeId(), state.GetPeerKeyID(), state.GetAdminId() }, this);
}
mTransportMgr->Disconnect(state.GetPeerAddress());
}
void SecureSessionMgr::ExpiryTimerCallback(System::Layer * layer, void * param, System::Error error)
{
SecureSessionMgr * mgr = reinterpret_cast<SecureSessionMgr *>(param);
#if CHIP_CONFIG_SESSION_REKEYING
// TODO(#2279): session expiration is currently disabled until rekeying is supported
// the #ifdef should be removed after that.
mgr->mPeerConnections.ExpireInactiveConnections(
CHIP_PEER_CONNECTION_TIMEOUT_MS,
[this](const Transport::PeerConnectionState & state1) { HandleConnectionExpired(state1); });
#endif
mgr->ScheduleExpiryTimer(); // re-schedule the oneshot timer
}
PeerConnectionState * SecureSessionMgr::GetPeerConnectionState(SecureSessionHandle session)
{
return mPeerConnections.FindPeerConnectionState(Optional<NodeId>::Value(session.mPeerNodeId), session.mPeerKeyId, nullptr);
}
} // namespace chip