1 /*
2  *  Copyright (c) 2016, The OpenThread Authors.
3  *  All rights reserved.
4  *
5  *  Redistribution and use in source and binary forms, with or without
6  *  modification, are permitted provided that the following conditions are met:
7  *  1. Redistributions of source code must retain the above copyright
8  *     notice, this list of conditions and the following disclaimer.
9  *  2. Redistributions in binary form must reproduce the above copyright
10  *     notice, this list of conditions and the following disclaimer in the
11  *     documentation and/or other materials provided with the distribution.
12  *  3. Neither the name of the copyright holder nor the
13  *     names of its contributors may be used to endorse or promote products
14  *     derived from this software without specific prior written permission.
15  *
16  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17  *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20  *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  *  POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /**
30  * @file
31  *   This file implements the Joiner Router role.
32  */
33 
34 #include "joiner_router.hpp"
35 
36 #if OPENTHREAD_FTD
37 
38 #include <stdio.h>
39 
40 #include "common/as_core_type.hpp"
41 #include "common/code_utils.hpp"
42 #include "common/encoding.hpp"
43 #include "common/locator_getters.hpp"
44 #include "common/log.hpp"
45 #include "instance/instance.hpp"
46 #include "meshcop/meshcop.hpp"
47 #include "meshcop/meshcop_tlvs.hpp"
48 #include "thread/mle.hpp"
49 #include "thread/thread_netif.hpp"
50 #include "thread/uri_paths.hpp"
51 
52 namespace ot {
53 namespace MeshCoP {
54 
55 RegisterLogModule("JoinerRouter");
56 
JoinerRouter(Instance & aInstance)57 JoinerRouter::JoinerRouter(Instance &aInstance)
58     : InstanceLocator(aInstance)
59     , mSocket(aInstance)
60     , mTimer(aInstance)
61     , mJoinerUdpPort(0)
62     , mIsJoinerPortConfigured(false)
63 {
64 }
65 
HandleNotifierEvents(Events aEvents)66 void JoinerRouter::HandleNotifierEvents(Events aEvents)
67 {
68     if (aEvents.Contains(kEventThreadNetdataChanged))
69     {
70         Start();
71     }
72 }
73 
Start(void)74 void JoinerRouter::Start(void)
75 {
76     VerifyOrExit(Get<Mle::MleRouter>().IsFullThreadDevice());
77 
78     if (Get<NetworkData::Leader>().IsJoiningAllowed())
79     {
80         uint16_t port = GetJoinerUdpPort();
81 
82         VerifyOrExit(!mSocket.IsBound());
83 
84         IgnoreError(mSocket.Open(&JoinerRouter::HandleUdpReceive, this));
85         IgnoreError(mSocket.Bind(port));
86         IgnoreError(Get<Ip6::Filter>().AddUnsecurePort(port));
87         LogInfo("Joiner Router: start");
88     }
89     else
90     {
91         VerifyOrExit(mSocket.IsBound());
92 
93         IgnoreError(Get<Ip6::Filter>().RemoveUnsecurePort(mSocket.GetSockName().mPort));
94 
95         IgnoreError(mSocket.Close());
96     }
97 
98 exit:
99     return;
100 }
101 
GetJoinerUdpPort(void) const102 uint16_t JoinerRouter::GetJoinerUdpPort(void) const
103 {
104     uint16_t port;
105 
106     if (mIsJoinerPortConfigured)
107     {
108         ExitNow(port = mJoinerUdpPort);
109     }
110 
111     if (Get<NetworkData::Leader>().FindJoinerUdpPort(port) == kErrorNone)
112     {
113         ExitNow();
114     }
115 
116     port = kDefaultJoinerUdpPort;
117 
118 exit:
119     return port;
120 }
121 
SetJoinerUdpPort(uint16_t aJoinerUdpPort)122 void JoinerRouter::SetJoinerUdpPort(uint16_t aJoinerUdpPort)
123 {
124     mJoinerUdpPort          = aJoinerUdpPort;
125     mIsJoinerPortConfigured = true;
126     Start();
127 }
128 
HandleUdpReceive(void * aContext,otMessage * aMessage,const otMessageInfo * aMessageInfo)129 void JoinerRouter::HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo)
130 {
131     static_cast<JoinerRouter *>(aContext)->HandleUdpReceive(AsCoreType(aMessage), AsCoreType(aMessageInfo));
132 }
133 
HandleUdpReceive(Message & aMessage,const Ip6::MessageInfo & aMessageInfo)134 void JoinerRouter::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
135 {
136     Error            error;
137     Coap::Message   *message = nullptr;
138     Tmf::MessageInfo messageInfo(GetInstance());
139     ExtendedTlv      tlv;
140     uint16_t         borderAgentRloc;
141 
142     LogInfo("JoinerRouter::HandleUdpReceive");
143 
144     SuccessOrExit(error = Get<NetworkData::Leader>().FindBorderAgentRloc(borderAgentRloc));
145 
146     message = Get<Tmf::Agent>().NewPriorityNonConfirmablePostMessage(kUriRelayRx);
147     VerifyOrExit(message != nullptr, error = kErrorNoBufs);
148 
149     SuccessOrExit(error = Tlv::Append<JoinerUdpPortTlv>(*message, aMessageInfo.GetPeerPort()));
150     SuccessOrExit(error = Tlv::Append<JoinerIidTlv>(*message, aMessageInfo.GetPeerAddr().GetIid()));
151     SuccessOrExit(error = Tlv::Append<JoinerRouterLocatorTlv>(*message, Get<Mle::MleRouter>().GetRloc16()));
152 
153     tlv.SetType(Tlv::kJoinerDtlsEncapsulation);
154     tlv.SetLength(aMessage.GetLength() - aMessage.GetOffset());
155     SuccessOrExit(error = message->Append(tlv));
156     SuccessOrExit(error = message->AppendBytesFromMessage(aMessage, aMessage.GetOffset(), tlv.GetLength()));
157 
158     messageInfo.SetSockAddrToRlocPeerAddrTo(borderAgentRloc);
159 
160     SuccessOrExit(error = Get<Tmf::Agent>().SendMessage(*message, messageInfo));
161 
162     LogInfo("Sent %s", UriToString<kUriRelayRx>());
163 
164 exit:
165     FreeMessageOnError(message, error);
166 }
167 
HandleTmf(Coap::Message & aMessage,const Ip6::MessageInfo & aMessageInfo)168 template <> void JoinerRouter::HandleTmf<kUriRelayTx>(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
169 {
170     OT_UNUSED_VARIABLE(aMessageInfo);
171 
172     Error                    error;
173     uint16_t                 joinerPort;
174     Ip6::InterfaceIdentifier joinerIid;
175     Kek                      kek;
176     uint16_t                 offset;
177     uint16_t                 length;
178     Message                 *message = nullptr;
179     Message::Settings        settings(Message::kNoLinkSecurity, Message::kPriorityNet);
180     Ip6::MessageInfo         messageInfo;
181 
182     VerifyOrExit(aMessage.IsNonConfirmablePostRequest(), error = kErrorDrop);
183 
184     LogInfo("Received %s", UriToString<kUriRelayTx>());
185 
186     SuccessOrExit(error = Tlv::Find<JoinerUdpPortTlv>(aMessage, joinerPort));
187     SuccessOrExit(error = Tlv::Find<JoinerIidTlv>(aMessage, joinerIid));
188 
189     SuccessOrExit(error = Tlv::FindTlvValueOffset(aMessage, Tlv::kJoinerDtlsEncapsulation, offset, length));
190 
191     VerifyOrExit((message = mSocket.NewMessage(0, settings)) != nullptr, error = kErrorNoBufs);
192 
193     SuccessOrExit(error = message->AppendBytesFromMessage(aMessage, offset, length));
194 
195     messageInfo.GetPeerAddr().SetToLinkLocalAddress(joinerIid);
196     messageInfo.SetPeerPort(joinerPort);
197 
198     SuccessOrExit(error = mSocket.SendTo(*message, messageInfo));
199 
200     if (Tlv::Find<JoinerRouterKekTlv>(aMessage, kek) == kErrorNone)
201     {
202         LogInfo("Received kek");
203 
204         DelaySendingJoinerEntrust(messageInfo, kek);
205     }
206 
207 exit:
208     FreeMessageOnError(message, error);
209 }
210 
DelaySendingJoinerEntrust(const Ip6::MessageInfo & aMessageInfo,const Kek & aKek)211 void JoinerRouter::DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessageInfo, const Kek &aKek)
212 {
213     Error                 error   = kErrorNone;
214     Message              *message = Get<MessagePool>().Allocate(Message::kTypeOther);
215     JoinerEntrustMetadata metadata;
216 
217     VerifyOrExit(message != nullptr, error = kErrorNoBufs);
218 
219     metadata.mMessageInfo = aMessageInfo;
220     metadata.mMessageInfo.SetPeerPort(Tmf::kUdpPort);
221     metadata.mSendTime = TimerMilli::GetNow() + kJoinerEntrustTxDelay;
222     metadata.mKek      = aKek;
223 
224     SuccessOrExit(error = metadata.AppendTo(*message));
225 
226     mDelayedJoinEnts.Enqueue(*message);
227 
228     if (!mTimer.IsRunning())
229     {
230         mTimer.FireAt(metadata.mSendTime);
231     }
232 
233 exit:
234     FreeMessageOnError(message, error);
235     LogError("schedule joiner entrust", error);
236 }
237 
HandleTimer(void)238 void JoinerRouter::HandleTimer(void) { SendDelayedJoinerEntrust(); }
239 
SendDelayedJoinerEntrust(void)240 void JoinerRouter::SendDelayedJoinerEntrust(void)
241 {
242     JoinerEntrustMetadata metadata;
243     Message              *message = mDelayedJoinEnts.GetHead();
244 
245     VerifyOrExit(message != nullptr);
246     VerifyOrExit(!mTimer.IsRunning());
247 
248     metadata.ReadFrom(*message);
249 
250     if (TimerMilli::GetNow() < metadata.mSendTime)
251     {
252         mTimer.FireAt(metadata.mSendTime);
253     }
254     else
255     {
256         mDelayedJoinEnts.DequeueAndFree(*message);
257 
258         Get<KeyManager>().SetKek(metadata.mKek);
259 
260         if (SendJoinerEntrust(metadata.mMessageInfo) != kErrorNone)
261         {
262             mTimer.Start(0);
263         }
264     }
265 
266 exit:
267     return;
268 }
269 
SendJoinerEntrust(const Ip6::MessageInfo & aMessageInfo)270 Error JoinerRouter::SendJoinerEntrust(const Ip6::MessageInfo &aMessageInfo)
271 {
272     Error          error = kErrorNone;
273     Coap::Message *message;
274 
275     message = PrepareJoinerEntrustMessage();
276     VerifyOrExit(message != nullptr, error = kErrorNoBufs);
277 
278     IgnoreError(Get<Tmf::Agent>().AbortTransaction(&JoinerRouter::HandleJoinerEntrustResponse, this));
279 
280     SuccessOrExit(error = Get<Tmf::Agent>().SendMessage(*message, aMessageInfo,
281                                                         &JoinerRouter::HandleJoinerEntrustResponse, this));
282 
283     LogInfo("Sent %s (len= %d)", UriToString<kUriJoinerEntrust>(), message->GetLength());
284     LogCert("[THCI] direction=send | type=JOIN_ENT.ntf");
285 
286 exit:
287     FreeMessageOnError(message, error);
288     return error;
289 }
290 
PrepareJoinerEntrustMessage(void)291 Coap::Message *JoinerRouter::PrepareJoinerEntrustMessage(void)
292 {
293     static const Tlv::Type kTlvTypes[] = {
294         Tlv::kNetworkKey,      Tlv::kMeshLocalPrefix, Tlv::kExtendedPanId, Tlv::kNetworkName,
295         Tlv::kActiveTimestamp, Tlv::kChannelMask,     Tlv::kPskc,          Tlv::kSecurityPolicy,
296     };
297 
298     Error          error   = kErrorNone;
299     Coap::Message *message = nullptr;
300     Dataset        dataset;
301 
302     message = Get<Tmf::Agent>().NewPriorityConfirmablePostMessage(kUriJoinerEntrust);
303     VerifyOrExit(message != nullptr, error = kErrorNoBufs);
304 
305     message->SetSubType(Message::kSubTypeJoinerEntrust);
306 
307     SuccessOrExit(error = Get<ActiveDatasetManager>().Read(dataset));
308 
309     for (Tlv::Type tlvType : kTlvTypes)
310     {
311         const Tlv *tlv = dataset.FindTlv(tlvType);
312 
313         VerifyOrExit(tlv != nullptr, error = kErrorInvalidState);
314         SuccessOrExit(error = tlv->AppendTo(*message));
315     }
316 
317     SuccessOrExit(error = Tlv::Append<NetworkKeySequenceTlv>(*message, Get<KeyManager>().GetCurrentKeySequence()));
318 
319 exit:
320     FreeAndNullMessageOnError(message, error);
321     return message;
322 }
323 
HandleJoinerEntrustResponse(void * aContext,otMessage * aMessage,const otMessageInfo * aMessageInfo,Error aResult)324 void JoinerRouter::HandleJoinerEntrustResponse(void                *aContext,
325                                                otMessage           *aMessage,
326                                                const otMessageInfo *aMessageInfo,
327                                                Error                aResult)
328 {
329     static_cast<JoinerRouter *>(aContext)->HandleJoinerEntrustResponse(AsCoapMessagePtr(aMessage),
330                                                                        AsCoreTypePtr(aMessageInfo), aResult);
331 }
332 
HandleJoinerEntrustResponse(Coap::Message * aMessage,const Ip6::MessageInfo * aMessageInfo,Error aResult)333 void JoinerRouter::HandleJoinerEntrustResponse(Coap::Message          *aMessage,
334                                                const Ip6::MessageInfo *aMessageInfo,
335                                                Error                   aResult)
336 {
337     OT_UNUSED_VARIABLE(aMessageInfo);
338 
339     SendDelayedJoinerEntrust();
340 
341     VerifyOrExit(aResult == kErrorNone && aMessage != nullptr);
342 
343     VerifyOrExit(aMessage->GetCode() == Coap::kCodeChanged);
344 
345     LogInfo("Receive %s response", UriToString<kUriJoinerEntrust>());
346     LogCert("[THCI] direction=recv | type=JOIN_ENT.rsp");
347 
348 exit:
349     return;
350 }
351 
ReadFrom(const Message & aMessage)352 void JoinerRouter::JoinerEntrustMetadata::ReadFrom(const Message &aMessage)
353 {
354     uint16_t length = aMessage.GetLength();
355 
356     OT_ASSERT(length >= sizeof(*this));
357     IgnoreError(aMessage.Read(length - sizeof(*this), *this));
358 }
359 
360 } // namespace MeshCoP
361 } // namespace ot
362 
363 #endif // OPENTHREAD_FTD
364