forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPairingSession.cpp
316 lines (267 loc) · 12.7 KB
/
PairingSession.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
/*
*
* Copyright (c) 2021 Project CHIP Authors
* 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.
*/
#include <protocols/secure_channel/PairingSession.h>
#include <app/SpecificationDefinedRevisions.h>
#include <lib/core/CHIPConfig.h>
#include <lib/core/TLVTypes.h>
#include <lib/support/SafeInt.h>
#include <lib/support/TypeTraits.h>
#include <platform/CHIPDeviceEvent.h>
#include <platform/PlatformManager.h>
#include <transport/SessionManager.h>
namespace chip {
CHIP_ERROR PairingSession::AllocateSecureSession(SessionManager & sessionManager, const ScopedNodeId & sessionEvictionHint)
{
auto handle = sessionManager.AllocateSession(GetSecureSessionType(), sessionEvictionHint);
VerifyOrReturnError(handle.HasValue(), CHIP_ERROR_NO_MEMORY);
VerifyOrReturnError(mSecureSessionHolder.GrabPairingSession(handle.Value()), CHIP_ERROR_INTERNAL);
mSessionManager = &sessionManager;
return CHIP_NO_ERROR;
}
CHIP_ERROR PairingSession::ActivateSecureSession(const Transport::PeerAddress & peerAddress)
{
// Prepare SecureSession fields, including key derivation, first, before activation
Transport::SecureSession * secureSession = mSecureSessionHolder->AsSecureSession();
ReturnErrorOnFailure(DeriveSecureSession(secureSession->GetCryptoContext()));
uint16_t peerSessionId = GetPeerSessionId();
secureSession->SetPeerAddress(peerAddress);
secureSession->GetSessionMessageCounter().GetPeerMessageCounter().SetCounter(Transport::PeerMessageCounter::kInitialSyncValue);
// Call Activate last, otherwise errors on anything after would lead to
// a partially valid session.
secureSession->Activate(GetLocalScopedNodeId(), GetPeer(), GetPeerCATs(), peerSessionId, GetRemoteSessionParameters());
ChipLogDetail(Inet, "New secure session activated for device " ChipLogFormatScopedNodeId ", LSID:%d PSID:%d!",
ChipLogValueScopedNodeId(GetPeer()), secureSession->GetLocalSessionId(), peerSessionId);
return CHIP_NO_ERROR;
}
void PairingSession::Finish()
{
Transport::PeerAddress address = mExchangeCtxt.Value()->GetSessionHandle()->AsUnauthenticatedSession()->GetPeerAddress();
#if INET_CONFIG_ENABLE_TCP_ENDPOINT
if (address.GetTransportType() == Transport::Type::kTcp)
{
// Fetch the connection for the unauthenticated session used to set up
// the secure session.
Transport::ActiveTCPConnectionState * conn =
mExchangeCtxt.Value()->GetSessionHandle()->AsUnauthenticatedSession()->GetTCPConnection();
// Associate the connection with the secure session being activated.
mSecureSessionHolder->AsSecureSession()->SetTCPConnection(conn);
}
#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT
// Discard the exchange so that Clear() doesn't try closing it. The exchange will handle that.
DiscardExchange();
CHIP_ERROR err = ActivateSecureSession(address);
if (err == CHIP_NO_ERROR)
{
VerifyOrDie(mSecureSessionHolder);
DeviceLayer::ChipDeviceEvent event;
event.Type = DeviceLayer::DeviceEventType::kSecureSessionEstablished;
event.SecureSessionEstablished.TransportType = to_underlying(address.GetTransportType());
event.SecureSessionEstablished.SecureSessionType =
to_underlying(mSecureSessionHolder->AsSecureSession()->GetSecureSessionType());
if (mSecureSessionHolder->AsSecureSession()->GetSecureSessionType() == Transport::SecureSession::Type::kCASE)
{
event.SecureSessionEstablished.PeerNodeId = mSecureSessionHolder->GetPeer().GetNodeId();
event.SecureSessionEstablished.FabricIndex = mSecureSessionHolder->GetPeer().GetFabricIndex();
}
if (DeviceLayer::PlatformMgr().PostEvent(&event) != CHIP_NO_ERROR)
{
ChipLogError(SecureChannel, "Failed to post Secure Session established event");
}
// Make sure to null out mDelegate so we don't send it any other
// notifications.
auto * delegate = mDelegate;
mDelegate = nullptr;
delegate->OnSessionEstablished(mSecureSessionHolder.Get().Value());
}
else
{
NotifySessionEstablishmentError(err);
}
}
void PairingSession::DiscardExchange()
{
if (mExchangeCtxt.HasValue())
{
// Make sure the exchange doesn't try to notify us when it closes,
// since we might be dead by then.
mExchangeCtxt.Value()->SetDelegate(nullptr);
// Null out mExchangeCtxt so that Clear() doesn't try closing it. The
// exchange will handle that.
mExchangeCtxt.ClearValue();
}
}
CHIP_ERROR PairingSession::EncodeSessionParameters(TLV::Tag tag, const ReliableMessageProtocolConfig & mrpLocalConfig,
TLV::TLVWriter & tlvWriter)
{
TLV::TLVType mrpParamsContainer;
ReturnErrorOnFailure(tlvWriter.StartContainer(tag, TLV::kTLVType_Structure, mrpParamsContainer));
ReturnErrorOnFailure(
tlvWriter.Put(TLV::ContextTag(SessionParameters::Tag::kSessionIdleInterval), mrpLocalConfig.mIdleRetransTimeout.count()));
ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(SessionParameters::Tag::kSessionActiveInterval),
mrpLocalConfig.mActiveRetransTimeout.count()));
ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(SessionParameters::Tag::kSessionActiveThreshold),
mrpLocalConfig.mActiveThresholdTime.count()));
uint16_t dataModel = Revision::kDataModelRevision;
ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(SessionParameters::Tag::kDataModelRevision), dataModel));
uint16_t interactionModel = Revision::kInteractionModelRevision;
ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(SessionParameters::Tag::kInteractionModelRevision), interactionModel));
uint32_t specVersion = Revision::kSpecificationVersion;
ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(SessionParameters::Tag::kSpecificationVersion), specVersion));
uint16_t maxPathsPerInvoke = CHIP_CONFIG_MAX_PATHS_PER_INVOKE;
ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(SessionParameters::Tag::kMaxPathsPerInvoke), maxPathsPerInvoke));
return tlvWriter.EndContainer(mrpParamsContainer);
}
CHIP_ERROR PairingSession::DecodeMRPParametersIfPresent(TLV::Tag expectedTag, TLV::ContiguousBufferTLVReader & tlvReader)
{
CHIP_ERROR err = CHIP_NO_ERROR;
// The MRP parameters are optional.
if (tlvReader.GetTag() != expectedTag)
{
return CHIP_NO_ERROR;
}
TLV::TLVType containerType = TLV::kTLVType_Structure;
ReturnErrorOnFailure(tlvReader.EnterContainer(containerType));
ReturnErrorOnFailure(tlvReader.Next());
ChipLogDetail(SecureChannel, "Found MRP parameters in the message");
// All TLV elements in the structure are optional. If the first element is present, process it and move
// the TLV reader to the next element.
if (TLV::TagNumFromTag(tlvReader.GetTag()) == SessionParameters::Tag::kSessionIdleInterval)
{
uint32_t idleRetransTimeout;
ReturnErrorOnFailure(tlvReader.Get(idleRetransTimeout));
mRemoteSessionParams.SetMRPIdleRetransTimeout(System::Clock::Milliseconds32(idleRetransTimeout));
// The next element is optional. If it's not present, return CHIP_NO_ERROR.
SuccessOrExit(err = tlvReader.Next());
}
if (TLV::TagNumFromTag(tlvReader.GetTag()) == SessionParameters::Tag::kSessionActiveInterval)
{
uint32_t activeRetransTimeout;
ReturnErrorOnFailure(tlvReader.Get(activeRetransTimeout));
mRemoteSessionParams.SetMRPActiveRetransTimeout(System::Clock::Milliseconds32(activeRetransTimeout));
// The next element is optional. If it's not present, return CHIP_NO_ERROR.
SuccessOrExit(err = tlvReader.Next());
}
if (TLV::TagNumFromTag(tlvReader.GetTag()) == SessionParameters::Tag::kSessionActiveThreshold)
{
uint16_t activeThresholdTime;
ReturnErrorOnFailure(tlvReader.Get(activeThresholdTime));
mRemoteSessionParams.SetMRPActiveThresholdTime(System::Clock::Milliseconds16(activeThresholdTime));
// The next element is optional. If it's not present, return CHIP_NO_ERROR.
SuccessOrExit(err = tlvReader.Next());
}
if (TLV::TagNumFromTag(tlvReader.GetTag()) == SessionParameters::Tag::kDataModelRevision)
{
uint16_t dataModelRevision;
ReturnErrorOnFailure(tlvReader.Get(dataModelRevision));
mRemoteSessionParams.SetDataModelRevision(dataModelRevision);
// The next element is optional. If it's not present, return CHIP_NO_ERROR.
SuccessOrExit(err = tlvReader.Next());
}
if (TLV::TagNumFromTag(tlvReader.GetTag()) == SessionParameters::Tag::kInteractionModelRevision)
{
uint16_t interactionModelRevision;
ReturnErrorOnFailure(tlvReader.Get(interactionModelRevision));
mRemoteSessionParams.SetInteractionModelRevision(interactionModelRevision);
// The next element is optional. If it's not present, return CHIP_NO_ERROR.
SuccessOrExit(err = tlvReader.Next());
}
if (TLV::TagNumFromTag(tlvReader.GetTag()) == SessionParameters::Tag::kSpecificationVersion)
{
uint32_t specificationVersion;
ReturnErrorOnFailure(tlvReader.Get(specificationVersion));
mRemoteSessionParams.SetSpecificationVersion(specificationVersion);
// The next element is optional. If it's not present, return CHIP_NO_ERROR.
SuccessOrExit(err = tlvReader.Next());
}
if (TLV::TagNumFromTag(tlvReader.GetTag()) == SessionParameters::Tag::kMaxPathsPerInvoke)
{
uint16_t maxPathsPerInvoke;
ReturnErrorOnFailure(tlvReader.Get(maxPathsPerInvoke));
mRemoteSessionParams.SetMaxPathsPerInvoke(maxPathsPerInvoke);
// The next element is optional. If it's not present, return CHIP_NO_ERROR.
SuccessOrExit(err = tlvReader.Next());
}
// Future proofing - Don't error out if there are other tags
exit:
if (err == CHIP_END_OF_TLV)
{
return tlvReader.ExitContainer(containerType);
}
return err;
}
bool PairingSession::IsSessionEstablishmentInProgress()
{
if (!mSecureSessionHolder)
{
return false;
}
Transport::SecureSession * secureSession = mSecureSessionHolder->AsSecureSession();
return secureSession->IsEstablishing();
}
void PairingSession::Clear()
{
// Clear acts like the destructor of PairingSession. If it is called during
// the middle of pairing, that means we should terminate the exchange. For the
// normal path, the exchange should already be discarded before calling Clear.
if (mExchangeCtxt.HasValue())
{
// The only time we reach this is when we are getting destroyed in the
// middle of our handshake. In that case, there is no point in trying to
// do MRP resends of the last message we sent. So, abort the exchange
// instead of just closing it.
mExchangeCtxt.Value()->Abort();
mExchangeCtxt.ClearValue();
}
mSecureSessionHolder.Release();
mPeerSessionId.ClearValue();
mSessionManager = nullptr;
}
void PairingSession::NotifySessionEstablishmentError(CHIP_ERROR error, SessionEstablishmentStage stage)
{
if (mDelegate == nullptr)
{
// Already notified success or error.
return;
}
auto * delegate = mDelegate;
mDelegate = nullptr;
delegate->OnSessionEstablishmentError(error, stage);
}
void PairingSession::OnSessionReleased()
{
if (mRole == CryptoContext::SessionRole::kInitiator)
{
NotifySessionEstablishmentError(CHIP_ERROR_CONNECTION_ABORTED);
return;
}
// Send the error notification async, because our delegate is likely to want
// to create a new session to listen for new connection attempts, and doing
// that under an OnSessionReleased notification is not safe.
if (!mSessionManager)
{
return;
}
mSessionManager->SystemLayer()->ScheduleWork(
[](auto * systemLayer, auto * appState) -> void {
ChipLogError(Inet, "ASYNC CASE Session establishment failed");
auto * _this = static_cast<PairingSession *>(appState);
_this->NotifySessionEstablishmentError(CHIP_ERROR_CONNECTION_ABORTED);
},
this);
}
} // namespace chip