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 DHCPv6 Server.
32  */
33 
34 #include "dhcp6_server.hpp"
35 
36 #if OPENTHREAD_CONFIG_DHCP6_SERVER_ENABLE
37 
38 #include "common/array.hpp"
39 #include "common/as_core_type.hpp"
40 #include "common/code_utils.hpp"
41 #include "common/encoding.hpp"
42 #include "common/instance.hpp"
43 #include "common/locator_getters.hpp"
44 #include "common/log.hpp"
45 #include "thread/mle.hpp"
46 #include "thread/thread_netif.hpp"
47 
48 namespace ot {
49 namespace Dhcp6 {
50 
51 RegisterLogModule("Dhcp6Server");
52 
Server(Instance & aInstance)53 Server::Server(Instance &aInstance)
54     : InstanceLocator(aInstance)
55     , mSocket(aInstance)
56     , mPrefixAgentsCount(0)
57     , mPrefixAgentsMask(0)
58 {
59     memset(mPrefixAgents, 0, sizeof(mPrefixAgents));
60 }
61 
UpdateService(void)62 Error Server::UpdateService(void)
63 {
64     Error                           error  = kErrorNone;
65     uint16_t                        rloc16 = Get<Mle::MleRouter>().GetRloc16();
66     NetworkData::Iterator           iterator;
67     NetworkData::OnMeshPrefixConfig config;
68     Lowpan::Context                 lowpanContext;
69 
70     // remove dhcp agent aloc and prefix delegation
71     for (PrefixAgent &prefixAgent : mPrefixAgents)
72     {
73         bool found = false;
74 
75         if (!prefixAgent.IsValid())
76         {
77             continue;
78         }
79 
80         iterator = NetworkData::kIteratorInit;
81 
82         while (Get<NetworkData::Leader>().GetNextOnMeshPrefix(iterator, rloc16, config) == kErrorNone)
83         {
84             if (!(config.mDhcp || config.mConfigure))
85             {
86                 continue;
87             }
88 
89             error = Get<NetworkData::Leader>().GetContext(prefixAgent.GetPrefixAsAddress(), lowpanContext);
90 
91             if ((error == kErrorNone) && (prefixAgent.GetContextId() == lowpanContext.mContextId))
92             {
93                 // still in network data
94                 found = true;
95                 break;
96             }
97         }
98 
99         if (!found)
100         {
101             Get<ThreadNetif>().RemoveUnicastAddress(prefixAgent.GetAloc());
102             prefixAgent.Clear();
103             mPrefixAgentsCount--;
104         }
105     }
106 
107     // add dhcp agent aloc and prefix delegation
108     iterator = NetworkData::kIteratorInit;
109 
110     while (Get<NetworkData::Leader>().GetNextOnMeshPrefix(iterator, rloc16, config) == kErrorNone)
111     {
112         if (!(config.mDhcp || config.mConfigure))
113         {
114             continue;
115         }
116 
117         error = Get<NetworkData::Leader>().GetContext(AsCoreType(&config.mPrefix.mPrefix), lowpanContext);
118 
119         if (error == kErrorNone)
120         {
121             AddPrefixAgent(config.GetPrefix(), lowpanContext);
122         }
123     }
124 
125     if (mPrefixAgentsCount > 0)
126     {
127         Start();
128     }
129     else
130     {
131         Stop();
132     }
133 
134     return error;
135 }
136 
Start(void)137 void Server::Start(void)
138 {
139     VerifyOrExit(!mSocket.IsOpen());
140 
141     IgnoreError(mSocket.Open(&Server::HandleUdpReceive, this));
142     IgnoreError(mSocket.Bind(kDhcpServerPort));
143 
144 exit:
145     return;
146 }
147 
Stop(void)148 void Server::Stop(void) { IgnoreError(mSocket.Close()); }
149 
AddPrefixAgent(const Ip6::Prefix & aIp6Prefix,const Lowpan::Context & aContext)150 void Server::AddPrefixAgent(const Ip6::Prefix &aIp6Prefix, const Lowpan::Context &aContext)
151 {
152     Error        error    = kErrorNone;
153     PrefixAgent *newEntry = nullptr;
154 
155     for (PrefixAgent &prefixAgent : mPrefixAgents)
156     {
157         if (!prefixAgent.IsValid())
158         {
159             newEntry = &prefixAgent;
160         }
161         else if (prefixAgent.GetPrefix() == aIp6Prefix)
162         {
163             // already added
164             ExitNow();
165         }
166     }
167 
168     VerifyOrExit(newEntry != nullptr, error = kErrorNoBufs);
169 
170     newEntry->Set(aIp6Prefix, Get<Mle::MleRouter>().GetMeshLocalPrefix(), aContext.mContextId);
171     Get<ThreadNetif>().AddUnicastAddress(newEntry->GetAloc());
172     mPrefixAgentsCount++;
173 
174 exit:
175 
176     if (error != kErrorNone)
177     {
178         LogNote("Failed to add DHCPv6 prefix agent: %s", ErrorToString(error));
179     }
180 }
181 
HandleUdpReceive(void * aContext,otMessage * aMessage,const otMessageInfo * aMessageInfo)182 void Server::HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo)
183 {
184     static_cast<Server *>(aContext)->HandleUdpReceive(AsCoreType(aMessage), AsCoreType(aMessageInfo));
185 }
186 
HandleUdpReceive(Message & aMessage,const Ip6::MessageInfo & aMessageInfo)187 void Server::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
188 {
189     Header header;
190 
191     SuccessOrExit(aMessage.Read(aMessage.GetOffset(), header));
192     aMessage.MoveOffset(sizeof(header));
193 
194     // discard if not solicit type
195     VerifyOrExit((header.GetType() == kTypeSolicit));
196 
197     ProcessSolicit(aMessage, aMessageInfo.GetPeerAddr(), header.GetTransactionId());
198 
199 exit:
200     return;
201 }
202 
ProcessSolicit(Message & aMessage,const Ip6::Address & aDst,const TransactionId & aTransactionId)203 void Server::ProcessSolicit(Message &aMessage, const Ip6::Address &aDst, const TransactionId &aTransactionId)
204 {
205     IaNa             iana;
206     ClientIdentifier clientIdentifier;
207     uint16_t         optionOffset;
208     uint16_t         offset = aMessage.GetOffset();
209     uint16_t         length = aMessage.GetLength() - aMessage.GetOffset();
210 
211     // Client Identifier (discard if not present)
212     VerifyOrExit((optionOffset = FindOption(aMessage, offset, length, kOptionClientIdentifier)) > 0);
213     SuccessOrExit(ProcessClientIdentifier(aMessage, optionOffset, clientIdentifier));
214 
215     // Server Identifier (assuming Rapid Commit, discard if present)
216     VerifyOrExit(FindOption(aMessage, offset, length, kOptionServerIdentifier) == 0);
217 
218     // Rapid Commit (assuming Rapid Commit, discard if not present)
219     VerifyOrExit(FindOption(aMessage, offset, length, kOptionRapidCommit) > 0);
220 
221     // Elapsed Time if present
222     if ((optionOffset = FindOption(aMessage, offset, length, kOptionElapsedTime)) > 0)
223     {
224         SuccessOrExit(ProcessElapsedTime(aMessage, optionOffset));
225     }
226 
227     // IA_NA (discard if not present)
228     VerifyOrExit((optionOffset = FindOption(aMessage, offset, length, kOptionIaNa)) > 0);
229     SuccessOrExit(ProcessIaNa(aMessage, optionOffset, iana));
230 
231     SuccessOrExit(SendReply(aDst, aTransactionId, clientIdentifier, iana));
232 
233 exit:
234     return;
235 }
236 
FindOption(Message & aMessage,uint16_t aOffset,uint16_t aLength,Code aCode)237 uint16_t Server::FindOption(Message &aMessage, uint16_t aOffset, uint16_t aLength, Code aCode)
238 {
239     uint16_t end  = aOffset + aLength;
240     uint16_t rval = 0;
241 
242     while (aOffset <= end)
243     {
244         Option option;
245 
246         SuccessOrExit(aMessage.Read(aOffset, option));
247 
248         if (option.GetCode() == aCode)
249         {
250             ExitNow(rval = aOffset);
251         }
252 
253         aOffset += sizeof(option) + option.GetLength();
254     }
255 
256 exit:
257     return rval;
258 }
ProcessClientIdentifier(Message & aMessage,uint16_t aOffset,ClientIdentifier & aClientId)259 Error Server::ProcessClientIdentifier(Message &aMessage, uint16_t aOffset, ClientIdentifier &aClientId)
260 {
261     Error error = kErrorNone;
262 
263     SuccessOrExit(error = aMessage.Read(aOffset, aClientId));
264     VerifyOrExit((aClientId.GetLength() == sizeof(aClientId) - sizeof(Option)) &&
265                      (aClientId.GetDuidType() == kDuidLinkLayerAddress) &&
266                      (aClientId.GetDuidHardwareType() == kHardwareTypeEui64),
267                  error = kErrorParse);
268 exit:
269     return error;
270 }
271 
ProcessElapsedTime(Message & aMessage,uint16_t aOffset)272 Error Server::ProcessElapsedTime(Message &aMessage, uint16_t aOffset)
273 {
274     Error       error = kErrorNone;
275     ElapsedTime option;
276 
277     SuccessOrExit(error = aMessage.Read(aOffset, option));
278     VerifyOrExit(option.GetLength() == sizeof(option) - sizeof(Option), error = kErrorParse);
279 exit:
280     return error;
281 }
282 
ProcessIaNa(Message & aMessage,uint16_t aOffset,IaNa & aIaNa)283 Error Server::ProcessIaNa(Message &aMessage, uint16_t aOffset, IaNa &aIaNa)
284 {
285     Error    error = kErrorNone;
286     uint16_t optionOffset;
287     uint16_t length;
288 
289     SuccessOrExit(error = aMessage.Read(aOffset, aIaNa));
290 
291     aOffset += sizeof(aIaNa);
292     length = aIaNa.GetLength() + sizeof(Option) - sizeof(IaNa);
293 
294     VerifyOrExit(length <= aMessage.GetLength() - aOffset, error = kErrorParse);
295 
296     mPrefixAgentsMask = 0;
297 
298     while (length > 0)
299     {
300         VerifyOrExit((optionOffset = FindOption(aMessage, aOffset, length, kOptionIaAddress)) > 0);
301         SuccessOrExit(error = ProcessIaAddress(aMessage, optionOffset));
302 
303         length -= ((optionOffset - aOffset) + sizeof(IaAddress));
304         aOffset = optionOffset + sizeof(IaAddress);
305     }
306 
307 exit:
308     return error;
309 }
310 
ProcessIaAddress(Message & aMessage,uint16_t aOffset)311 Error Server::ProcessIaAddress(Message &aMessage, uint16_t aOffset)
312 {
313     Error     error = kErrorNone;
314     IaAddress option;
315 
316     SuccessOrExit(error = aMessage.Read(aOffset, option));
317     VerifyOrExit(option.GetLength() == sizeof(option) - sizeof(Option), error = kErrorParse);
318 
319     // mask matching prefix
320     for (uint16_t i = 0; i < GetArrayLength(mPrefixAgents); i++)
321     {
322         if (mPrefixAgents[i].IsValid() && mPrefixAgents[i].IsPrefixMatch(option.GetAddress()))
323         {
324             mPrefixAgentsMask |= (1 << i);
325             break;
326         }
327     }
328 
329 exit:
330     return error;
331 }
332 
SendReply(const Ip6::Address & aDst,const TransactionId & aTransactionId,ClientIdentifier & aClientId,IaNa & aIaNa)333 Error Server::SendReply(const Ip6::Address  &aDst,
334                         const TransactionId &aTransactionId,
335                         ClientIdentifier    &aClientId,
336                         IaNa                &aIaNa)
337 {
338     Error            error = kErrorNone;
339     Ip6::MessageInfo messageInfo;
340     Message         *message;
341 
342     VerifyOrExit((message = mSocket.NewMessage()) != nullptr, error = kErrorNoBufs);
343     SuccessOrExit(error = AppendHeader(*message, aTransactionId));
344     SuccessOrExit(error = AppendServerIdentifier(*message));
345     SuccessOrExit(error = AppendClientIdentifier(*message, aClientId));
346     SuccessOrExit(error = AppendIaNa(*message, aIaNa));
347     SuccessOrExit(error = AppendStatusCode(*message, kStatusSuccess));
348     SuccessOrExit(error = AppendIaAddress(*message, aClientId));
349     SuccessOrExit(error = AppendRapidCommit(*message));
350 
351     messageInfo.SetPeerAddr(aDst);
352     messageInfo.SetPeerPort(kDhcpClientPort);
353     SuccessOrExit(error = mSocket.SendTo(*message, messageInfo));
354 
355 exit:
356     FreeMessageOnError(message, error);
357     return error;
358 }
359 
AppendHeader(Message & aMessage,const TransactionId & aTransactionId)360 Error Server::AppendHeader(Message &aMessage, const TransactionId &aTransactionId)
361 {
362     Header header;
363 
364     header.Clear();
365     header.SetType(kTypeReply);
366     header.SetTransactionId(aTransactionId);
367     return aMessage.Append(header);
368 }
369 
AppendClientIdentifier(Message & aMessage,ClientIdentifier & aClientId)370 Error Server::AppendClientIdentifier(Message &aMessage, ClientIdentifier &aClientId)
371 {
372     return aMessage.Append(aClientId);
373 }
374 
AppendServerIdentifier(Message & aMessage)375 Error Server::AppendServerIdentifier(Message &aMessage)
376 {
377     Error            error = kErrorNone;
378     ServerIdentifier option;
379     Mac::ExtAddress  eui64;
380 
381     Get<Radio>().GetIeeeEui64(eui64);
382 
383     option.Init();
384     option.SetDuidType(kDuidLinkLayerAddress);
385     option.SetDuidHardwareType(kHardwareTypeEui64);
386     option.SetDuidLinkLayerAddress(eui64);
387     SuccessOrExit(error = aMessage.Append(option));
388 
389 exit:
390     return error;
391 }
392 
AppendIaNa(Message & aMessage,IaNa & aIaNa)393 Error Server::AppendIaNa(Message &aMessage, IaNa &aIaNa)
394 {
395     Error    error  = kErrorNone;
396     uint16_t length = 0;
397 
398     if (mPrefixAgentsMask)
399     {
400         for (uint16_t i = 0; i < GetArrayLength(mPrefixAgents); i++)
401         {
402             if (mPrefixAgentsMask & (1 << i))
403             {
404                 length += sizeof(IaAddress);
405             }
406         }
407     }
408     else
409     {
410         length += sizeof(IaAddress) * mPrefixAgentsCount;
411     }
412 
413     length += sizeof(IaNa) + sizeof(StatusCode) - sizeof(Option);
414 
415     aIaNa.SetLength(length);
416     aIaNa.SetT1(IaNa::kDefaultT1);
417     aIaNa.SetT2(IaNa::kDefaultT2);
418     SuccessOrExit(error = aMessage.Append(aIaNa));
419 
420 exit:
421     return error;
422 }
423 
AppendStatusCode(Message & aMessage,Status aStatusCode)424 Error Server::AppendStatusCode(Message &aMessage, Status aStatusCode)
425 {
426     StatusCode option;
427 
428     option.Init();
429     option.SetStatusCode(aStatusCode);
430     return aMessage.Append(option);
431 }
432 
AppendIaAddress(Message & aMessage,ClientIdentifier & aClientId)433 Error Server::AppendIaAddress(Message &aMessage, ClientIdentifier &aClientId)
434 {
435     Error error = kErrorNone;
436 
437     if (mPrefixAgentsMask)
438     {
439         // if specified, only apply specified prefixes
440         for (uint16_t i = 0; i < GetArrayLength(mPrefixAgents); i++)
441         {
442             if (mPrefixAgentsMask & (1 << i))
443             {
444                 SuccessOrExit(error = AddIaAddress(aMessage, mPrefixAgents[i].GetPrefixAsAddress(), aClientId));
445             }
446         }
447     }
448     else
449     {
450         // if not specified, apply all configured prefixes
451         for (const PrefixAgent &prefixAgent : mPrefixAgents)
452         {
453             if (prefixAgent.IsValid())
454             {
455                 SuccessOrExit(error = AddIaAddress(aMessage, prefixAgent.GetPrefixAsAddress(), aClientId));
456             }
457         }
458     }
459 
460 exit:
461     return error;
462 }
463 
AddIaAddress(Message & aMessage,const Ip6::Address & aPrefix,ClientIdentifier & aClientId)464 Error Server::AddIaAddress(Message &aMessage, const Ip6::Address &aPrefix, ClientIdentifier &aClientId)
465 {
466     Error     error = kErrorNone;
467     IaAddress option;
468 
469     option.Init();
470     option.GetAddress().SetPrefix(aPrefix.mFields.m8, OT_IP6_PREFIX_BITSIZE);
471     option.GetAddress().GetIid().SetFromExtAddress(aClientId.GetDuidLinkLayerAddress());
472     option.SetPreferredLifetime(IaAddress::kDefaultPreferredLifetime);
473     option.SetValidLifetime(IaAddress::kDefaultValidLifetime);
474     SuccessOrExit(error = aMessage.Append(option));
475 
476 exit:
477     return error;
478 }
479 
AppendRapidCommit(Message & aMessage)480 Error Server::AppendRapidCommit(Message &aMessage)
481 {
482     RapidCommit option;
483 
484     option.Init();
485     return aMessage.Append(option);
486 }
487 
ApplyMeshLocalPrefix(void)488 void Server::ApplyMeshLocalPrefix(void)
489 {
490     for (PrefixAgent &prefixAgent : mPrefixAgents)
491     {
492         if (prefixAgent.IsValid())
493         {
494             PrefixAgent *entry = &prefixAgent;
495 
496             Get<ThreadNetif>().RemoveUnicastAddress(entry->GetAloc());
497             entry->GetAloc().GetAddress().SetPrefix(Get<Mle::MleRouter>().GetMeshLocalPrefix());
498             Get<ThreadNetif>().AddUnicastAddress(entry->GetAloc());
499         }
500     }
501 }
502 
503 } // namespace Dhcp6
504 } // namespace ot
505 
506 #endif //  OPENTHREAD_CONFIG_DHCP6_SERVER_ENABLE
507