capsules_extra/net/thread/
thread_utils.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2023.
4
5use crate::net::stream::{encode_bytes, SResult};
6use crate::net::thread::tlv::{unwrap_tlv_offset, LinkMode, MulticastResponder, Tlv};
7use crate::net::{ieee802154::MacAddress, ipv6::ip_utils::IPAddr};
8pub const THREAD_PORT_NUMBER: u16 = 19788;
9
10use kernel::ErrorCode;
11
12pub const SECURITY_SUITE_LEN: usize = 1;
13pub const AUX_SEC_HEADER_LENGTH: usize = 10;
14pub const AUTH_DATA_LEN: usize = 42;
15pub const IPV6_LEN: usize = 16;
16const PARENT_REQUEST_MLE_SIZE: usize = 21;
17pub const MULTICAST_IPV6: IPAddr = IPAddr([
18    0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
19]);
20
21#[derive(Clone, Copy)]
22pub struct NetworkKey {
23    pub mle_key: [u8; 16],
24    pub mac_key: [u8; 16],
25}
26
27pub enum ThreadState {
28    SendParentReq,
29    WaitingParentRsp,
30    RecvParentRsp(IPAddr),
31    SendChildIdReq(IPAddr),
32    WaitingChildRsp,
33    RecvChildRsp(IPAddr),
34    SEDActive(IPAddr, MacAddress),
35    SendUpdate(IPAddr, MacAddress),
36    SendUDPMsg,
37    Detached,
38}
39
40pub enum MleCommand {
41    LinkRequest = 0,
42    LinkAccept = 1,
43    LinkAcceptAndRequest = 2,
44    LinkAdvertisement = 4,
45    DataRequest = 7,
46    DataResponse = 8,
47    ParentRequest = 9,
48    ParentResponse = 10,
49    ChildIdRequest = 11,
50    ChildIdResponse = 12,
51    ChildUpdateRequest = 13,
52    ChildUpdateResponse = 14,
53    Announce = 15,
54    DiscoverRequest = 16,
55    DiscoveryResponse = 17,
56    LinkMetricsManagReq = 18,
57    LinkMetricsManagResp = 19,
58    LinkProbe = 20,
59}
60
61/// Helper function to generate a link-local IPV6 address
62/// from the device's mac address.
63pub fn generate_src_ipv6(macaddr: &[u8; 8]) -> IPAddr {
64    // -----------------------------------------------------------------------------------------------
65    // THREAD SPEC 5.2.2.4 (V1.3.0) -- A Thread Device MUST assign a link-local IPv6 address where the
66    // interface identifier is set to the MAC Extended Address with the universal/local bit inverted.
67    // ------------------------------------------------------------------------------------------------
68
69    let mut output: [u8; 16] = [0; 16];
70    let mut lower_bytes = *macaddr;
71
72    // The universal/local bit is the 2nd least significant bit.
73    // Invert by xor first byte of MAC addr with 2
74    lower_bytes[0] = macaddr[0] ^ 2;
75    let upper_bytes: [u8; 8] = [0xfe, 0x80, 0, 0, 0, 0, 0, 0];
76
77    encode_bytes(&mut output[..8], &upper_bytes);
78    encode_bytes(&mut output[8..16], &lower_bytes);
79    IPAddr(output)
80}
81
82/// Helper function to recover the mac address from
83/// an IPV6 address.
84pub fn mac_from_ipv6(ipv6: IPAddr) -> [u8; 8] {
85    // Helper function to generate the mac address from the mac address;
86    // reversing the tranformation used/described in `generate_src_ipv6`
87    let mut output: [u8; 8] = [0; 8];
88    let mut lower_bytes = ipv6.0;
89    lower_bytes[8] ^= 2;
90
91    encode_bytes(&mut output[..8], &lower_bytes[8..16]);
92    output
93}
94
95/// Helper function to locate the challenge TLV in a received
96/// MLE packet. Return the challenge to be used as a response
97/// TLV in reply.
98fn find_challenge(buf: &[u8]) -> Result<&[u8], ErrorCode> {
99    let mut index = 0;
100    while index < buf.len() {
101        let tlv_len = buf[index + 1] as usize;
102        if buf[index] == 3 {
103            return Ok(&buf[index + 2..index + 2 + tlv_len]);
104        } else {
105            index += tlv_len + 2;
106        }
107    }
108    Err(ErrorCode::FAIL)
109}
110
111/// Function to encode the crypt data into a/m data
112pub fn encode_cryp_data(
113    src_addr: IPAddr,
114    dst_addr: IPAddr,
115    aux_sec_header: &[u8; AUX_SEC_HEADER_LENGTH],
116    payload: &[u8],
117    output: &mut [u8],
118) -> SResult {
119    // --------------AUTH DATA----------------||-- M DATA--
120    // SRC IPV6 || DST IPV6 || AUX SEC HEADER ||  PAYLOAD
121    let mut off = enc_consume!(output; encode_bytes, &src_addr.0);
122    off = enc_consume!(output, off; encode_bytes, &dst_addr.0);
123    off = enc_consume!(output, off; encode_bytes, aux_sec_header);
124    off = enc_consume!(output, off; encode_bytes, payload);
125    stream_done!(off)
126}
127
128/// This helper function creates a parent request. For now,
129/// this implementation hard codes all values for the parent request
130pub fn form_parent_req() -> [u8; PARENT_REQUEST_MLE_SIZE] {
131    // TODO: form parent request from alterable values, generate
132    // challenge from random number generator
133    let mut output = [0u8; PARENT_REQUEST_MLE_SIZE];
134    let mut offset = 0;
135
136    // Command: Parent Request //
137    output[0..1].copy_from_slice(&[MleCommand::ParentRequest as u8]);
138    offset += 1;
139
140    // Mode TLV //
141    offset += unwrap_tlv_offset(Tlv::encode(
142        &Tlv::Mode(
143            LinkMode::FullNetworkDataRequired as u8
144                + LinkMode::FullThreadDevice as u8
145                + LinkMode::SecureDataRequests as u8
146                + LinkMode::ReceiverOnWhenIdle as u8,
147        ),
148        &mut output[offset..],
149    ));
150
151    // Challenge TLV //
152    // TODO: challenge is hardcoded currently; randomly generate number
153    offset += unwrap_tlv_offset(Tlv::encode(
154        &Tlv::Challenge([0, 0, 0, 0, 0, 0, 0, 0]),
155        &mut output[offset..],
156    ));
157
158    // Scan Mask TLV //
159    offset += unwrap_tlv_offset(Tlv::encode(
160        &Tlv::ScanMask(MulticastResponder::Router as u8),
161        &mut output[offset..],
162    ));
163
164    // Version TLV //
165    unwrap_tlv_offset(Tlv::encode(&Tlv::Version(4), &mut output[offset..]));
166
167    output
168}
169
170/// This helper function creates a child id request. For now,
171/// this implementation hard codes many of the values
172pub fn form_child_id_req(
173    recv_buf: &[u8],
174    frame_count: u32,
175) -> Result<([u8; 200], usize), ErrorCode> {
176    let mut output: [u8; 200] = [0; 200];
177    let mut offset = 0;
178
179    /* -- Child ID Request TLVs (Thread Spec 4.5.1 (v1.3.0)) --
180    Response TLV
181    Link-layer Frame Counter TLV
182    [MLE Frame Counter TLV] **optional if Link-layer frame counter is the same**
183    Mode TLV
184    Timeout TLV
185    Version TLV
186    [Address Registration TLV]
187    [TLV Request TLV: Address16 (Network Data and/or Route)]
188    [Active Timestamp TLV]
189    [Pending Timestamp TLV]
190    */
191
192    // Command Child ID Request //
193    output[0..1].copy_from_slice(&[MleCommand::ChildIdRequest as u8]);
194    offset += 1;
195
196    // Response TLV //
197    let received_challenge_tlv: Result<&[u8], ErrorCode> = find_challenge(&recv_buf[1..]);
198
199    if received_challenge_tlv.is_err() {
200        // Challenge TLV not found; malformed request
201        return Err(ErrorCode::FAIL);
202    } else {
203        // Encode response into output
204        let mut rsp_buf: [u8; 8] = [0; 8];
205        rsp_buf.copy_from_slice(received_challenge_tlv.unwrap());
206        rsp_buf.reverse(); // NEED TO DISCUSS BIG/LITTLE ENDIAN ASSUMPTIONS
207        offset += unwrap_tlv_offset(Tlv::encode(&Tlv::Response(rsp_buf), &mut output[offset..]));
208    }
209
210    // Link-layer Frame Counter TLV //
211    offset += unwrap_tlv_offset(Tlv::encode(
212        &Tlv::LinkLayerFrameCounter(0),
213        &mut output[offset..],
214    ));
215
216    // MLE Frame Counter TLV //
217    offset += unwrap_tlv_offset(Tlv::encode(
218        &Tlv::MleFrameCounter(frame_count.to_be()),
219        &mut output[offset..],
220    ));
221
222    // Mode TLV //
223    offset += unwrap_tlv_offset(Tlv::encode(
224        &Tlv::Mode(LinkMode::FullThreadDevice as u8 + LinkMode::ReceiverOnWhenIdle as u8),
225        &mut output[offset..],
226    ));
227
228    // Timeout TLV //
229    offset += unwrap_tlv_offset(Tlv::encode(
230        &Tlv::Timeout((10_u32).to_be()),
231        &mut output[offset..],
232    ));
233
234    // Version TLV //
235    offset += unwrap_tlv_offset(Tlv::encode(&Tlv::Version(4), &mut output[offset..]));
236
237    // TODO: hardcoded for now, but replace in future
238    output[offset..offset + 4].copy_from_slice(&[0x1b, 0x02, 0x00, 0x81]);
239    offset += 4;
240
241    offset += unwrap_tlv_offset(Tlv::encode(
242        &Tlv::TlvRequest(&[0x0a, 0x0c, 0x09]),
243        &mut output[offset..],
244    ));
245
246    Ok((output, offset))
247}
248
249/*
250This is just here as a note for when retries are added
251==================================================================================================
252THREAD SPEC v1.3.0 -- section 4.5.1
253A Thread Device attempting to attach MUST first attempt to attach with the Scan Mask TLV of
254the Parent Request set to only solicit responses from Routers. If no responses are received, or
255there is no response with the highest link quality, this request is deemed to have failed. If it
256failed, the Device MUST attempt to attach again using the same request. If it still failed, the device
257MUST attempt to attach with the Scan Mask TLV of the Parent Request set to solicit responses from both
258Routers and REEDs. There is no requirement on minimum link quality for
259responses to this request. If no responses are received, this request is deemed to have failed. If
260this Parent Request failed it MUST be retried up to three times.
261
262If the Thread Device is a REED and it still fails to successfully attach to a parent after all retries,
263it forms a new Partition as described in Section 5.16, Thread Network Partitions in Chapter 5,
264Network Layer.
265
266If the Thread Device is not a REED and it fails to successfully attach to a parent after all retries,
267then it SHOULD first wait for a vendor-specific timeout and then attempt to attach again using a
268Parent Request set to only solicit responses from Routers. If no responses are received, or if
269there is no response with the highest link quality, this request is deemed to have failed. If it
270failed, the Device MUST attempt to attach with the Scan Mask TLV of the Parent Request set to
271solicit responses from both Routers and REEDs. There is no requirement on minimum link quality
272for responses to this request. If this request still failed, the Thread Device again waits for a
273vendor-specific timeout and repeats the cycle defined in this paragraph.
274
275SENDING/RETRYING PARENT REQUESTS THREAD SPEC v1.3.0 -- section 4.5.1
276**Attempt 1/2 considered to fail if no response received or no response with highest link quality
277**Attempt 3-6 considered to fail if no response received
278    (Attempt 1) Send parent request with scan mask only set to routers
279    (Attempt 2) Repeat attempt 1
280    (Attempt 3) Send parent request with scan mask set to routers and REEDs
281    (Attempt 4) Repeat attempt 3
282    (Attempt 5) Repeat attempt 3
283    (Attempt 6) Repeat attempt 3
284
285
286
287*/