1use core::fmt;
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum SignatureWidth {
19 Bits256,
21 Bits384,
23 Bits512,
25}
26
27impl SignatureWidth {
28 fn octets(self) -> usize {
29 match self {
30 Self::Bits256 => 32,
31 Self::Bits384 => 48,
32 Self::Bits512 => 64,
33 }
34 }
35}
36
37#[derive(Debug, PartialEq, Eq)]
39#[non_exhaustive]
40pub struct UnverifiedWakeUp<'a> {
41 pub recipient_id: &'a [u8; 9],
43 pub unix_seconds: i64,
45 pub signed_bytes: &'a [u8; 32],
47 pub algorithm_oid: &'a [u8],
49 pub r: &'a [u8],
51 pub s: &'a [u8],
53}
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum ParseError {
58 Length,
60 Header,
62 Version,
64 Recipient,
66 Padding,
68 SignatureFormat,
70 AlgorithmOid,
72}
73
74impl fmt::Display for ParseError {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 f.write_str(match self {
77 Self::Length => "invalid wake-up message length",
78 Self::Header => "invalid wake-up header",
79 Self::Version => "unsupported wake-up version",
80 Self::Recipient => "invalid wake-up recipient identifier",
81 Self::Padding => "invalid wake-up reserved bytes",
82 Self::SignatureFormat => "unsupported wake-up signature format",
83 Self::AlgorithmOid => "invalid wake-up signature algorithm identifier",
84 })
85 }
86}
87
88impl core::error::Error for ParseError {}
89
90pub fn valid_recipient(id: &[u8; 9]) -> bool {
93 let [0x0e, manufacturer @ .., block, n1, n2, n3, n4] = id else {
94 return false;
95 };
96 manufacturer.iter().all(u8::is_ascii_uppercase)
97 && *block != 0xff
98 && u32::from_be_bytes([*n1, *n2, *n3, *n4]) <= 99_999_999
99}
100
101pub const ECDSA_PLAIN_SHA256_OID: &[u8; 10] = &[4, 0, 127, 0, 7, 1, 1, 4, 1, 3];
103
104pub struct WakeUpPrefix([u8; 32]);
106
107impl WakeUpPrefix {
108 pub fn new(recipient: [u8; 9], unix_seconds: i64) -> Result<Self, ParseError> {
110 if !valid_recipient(&recipient) {
111 return Err(ParseError::Recipient);
112 }
113 let mut bytes = [0x0b; 32];
114 bytes[..3].copy_from_slice(b"WU\x01");
115 bytes[3..12].copy_from_slice(&recipient);
116 bytes[12..20].copy_from_slice(&unix_seconds.to_le_bytes());
117 Ok(Self(bytes))
118 }
119
120 pub fn as_bytes(&self) -> &[u8; 32] {
122 &self.0
123 }
124
125 pub fn with_p256_signature(&self, r: &[u8; 32], s: &[u8; 32]) -> [u8; 108] {
127 let mut bytes = [0; 108];
128 bytes[..32].copy_from_slice(&self.0);
129 bytes[32] = 1;
130 bytes[33] = ECDSA_PLAIN_SHA256_OID.len() as u8;
131 bytes[34..44].copy_from_slice(ECDSA_PLAIN_SHA256_OID);
132 bytes[44..76].copy_from_slice(r);
133 bytes[76..].copy_from_slice(s);
134 bytes
135 }
136}
137
138pub fn parse(packet: &[u8], width: SignatureWidth) -> Result<UnverifiedWakeUp<'_>, ParseError> {
145 let (signed_bytes, rest) = packet.split_first_chunk::<32>().ok_or(ParseError::Length)?;
146 let [b'W', b'U', version, payload @ ..] = signed_bytes else {
147 return Err(ParseError::Header);
148 };
149 if *version != 1 {
150 return Err(ParseError::Version);
151 }
152 let (recipient_id, rest_payload) =
153 payload.split_first_chunk::<9>().ok_or(ParseError::Length)?;
154 if !valid_recipient(recipient_id) {
155 return Err(ParseError::Recipient);
156 }
157 let (timestamp, padding) = rest_payload
158 .split_first_chunk::<8>()
159 .ok_or(ParseError::Length)?;
160 if padding != [0x0b; 12] {
161 return Err(ParseError::Padding);
162 }
163 let ([format, oid_len], tail) = rest.split_first_chunk::<2>().ok_or(ParseError::Length)?;
164 if *format != 1 {
165 return Err(ParseError::SignatureFormat);
166 }
167 if !(1..=14).contains(oid_len) {
168 return Err(ParseError::AlgorithmOid);
169 }
170 let (algorithm_oid, signature) = tail
171 .split_at_checked(usize::from(*oid_len))
172 .ok_or(ParseError::Length)?;
173 if signature.len() != width.octets() * 2 {
174 return Err(ParseError::Length);
175 }
176 let mut start = true;
178 for &octet in algorithm_oid {
179 if start && octet == 0x80 {
180 return Err(ParseError::AlgorithmOid);
181 }
182 start = octet & 0x80 == 0;
183 }
184 if !start {
185 return Err(ParseError::AlgorithmOid);
186 }
187 let (r, s) = signature.split_at(width.octets());
188 Ok(UnverifiedWakeUp {
189 recipient_id,
190 unix_seconds: i64::from_le_bytes(*timestamp),
191 signed_bytes,
192 algorithm_oid,
193 r,
194 s,
195 })
196}
197
198#[cfg(test)]
199mod tests {
200 use super::*;
201
202 fn fixture() -> [u8; 108] {
204 let mut bytes = [0; 108];
205 bytes[..12].copy_from_slice(b"WU\x01\x0eTST\x00\x00\x00\x00\x01");
206 bytes[12..20].copy_from_slice(&(-3_i64).to_le_bytes());
207 bytes[20..32].fill(0x0b);
208 bytes[32..44].copy_from_slice(&[1, 10, 4, 0, 127, 0, 7, 1, 1, 4, 1, 3]);
209 bytes[76..].fill(0x42);
210 bytes
211 }
212
213 #[test]
214 fn encodes_the_exact_v1_prefix_and_plain_signature() {
215 let recipient = [0x0e, b'T', b'S', b'T', 0, 0, 0, 0, 1];
216 let prefix = WakeUpPrefix::new(recipient, -3).unwrap();
217 assert_eq!(prefix.as_bytes().as_slice(), &fixture()[..32]);
218 assert_eq!(prefix.with_p256_signature(&[0; 32], &[0x42; 32]), fixture());
219 assert!(matches!(
220 WakeUpPrefix::new([0; 9], 0),
221 Err(ParseError::Recipient)
222 ));
223 }
224
225 #[test]
226 fn exposes_exact_signed_prefix_and_signature_components() {
227 let bytes = fixture();
228 let message = parse(&bytes, SignatureWidth::Bits256).unwrap();
229 assert_eq!(message.unix_seconds, -3);
230 assert_eq!(message.recipient_id, &bytes[3..12]);
231 assert_eq!(message.signed_bytes, &bytes[..32]);
232 assert_eq!(message.algorithm_oid, &bytes[34..44]);
233 assert_eq!(message.r, &[0; 32]);
234 assert_eq!(message.s, &[0x42; 32]);
235 }
236
237 #[test]
238 fn rejects_truncation_trailing_bytes_and_wrong_key_width() {
239 let mut bytes = [0; 109];
240 bytes[..108].copy_from_slice(&fixture());
241 for len in (0..108).chain([109]) {
242 assert!(parse(&bytes[..len], SignatureWidth::Bits256).is_err());
243 }
244 assert_eq!(
245 parse(&bytes[..108], SignatureWidth::Bits384),
246 Err(ParseError::Length)
247 );
248 let mut wider = [0; 172];
249 wider[..108].copy_from_slice(&fixture());
250 assert_eq!(
251 parse(&wider[..140], SignatureWidth::Bits384)
252 .unwrap()
253 .s
254 .len(),
255 48
256 );
257 assert_eq!(parse(&wider, SignatureWidth::Bits512).unwrap().s.len(), 64);
258 }
259
260 #[test]
261 fn rejects_invalid_structure_before_exposing_fields() {
262 for (offset, value, expected) in [
263 (0, 0, ParseError::Header),
264 (2, 2, ParseError::Version),
265 (3, 0, ParseError::Recipient),
266 (4, b'a', ParseError::Recipient),
267 (7, 0xff, ParseError::Recipient),
268 (8, 6, ParseError::Recipient),
269 (29, 0, ParseError::Padding),
270 (32, 0, ParseError::SignatureFormat),
271 (33, 0, ParseError::AlgorithmOid),
272 (33, 15, ParseError::AlgorithmOid),
273 (34, 0x80, ParseError::AlgorithmOid),
274 (43, 0x81, ParseError::AlgorithmOid),
275 ] {
276 let mut bytes = fixture();
277 bytes[offset] = value;
278 assert_eq!(parse(&bytes, SignatureWidth::Bits256), Err(expected));
279 }
280 }
281}