Skip to main content

smgw_core/
wakeup.rs

1//! Offline inspection of a gateway administrator (GWA) wake-up message addressed
2//! to a smart meter gateway (SMGW).
3//!
4//! The layout follows [BSI TR-03109-1 Detailspecification v2.0], §2.1, tables
5//! 2.1–2.2. The timestamp follows the table's explicit least-significant-byte-first
6//! rule. Its displayed hex example uses the opposite order.
7//!
8//! Parsing returns borrowed, unauthenticated fields. The gateway host verifies the
9//! configured recipient, signature, freshness and replay history before accepting a wake-up.
10//!
11//! [BSI TR-03109-1 Detailspecification v2.0]: https://www.bsi.bund.de/SharedDocs/Downloads/DE/BSI/Publikationen/TechnischeRichtlinien/TR03109/TR-03109-1_Detailspezifikation_v2_0.pdf?__blob=publicationFile&v=2
12
13use core::fmt;
14
15/// Width of one plain ECDSA signature component, selected from the trusted
16/// signing key's curve. Selecting a width makes no algorithm-policy decision.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum SignatureWidth {
19    /// 32 octets per integer.
20    Bits256,
21    /// 48 octets per integer.
22    Bits384,
23    /// 64 octets per integer.
24    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/// Structurally parsed, unauthenticated fields borrowed from one complete datagram.
38#[derive(Debug, PartialEq, Eq)]
39#[non_exhaustive]
40pub struct UnverifiedWakeUp<'a> {
41    /// The nine wire octets of the gateway's DIN 43849 equipment identifier.
42    pub recipient_id: &'a [u8; 9],
43    /// Sender-supplied UTC seconds since the Unix epoch.
44    pub unix_seconds: i64,
45    /// Exact wire bytes covered by the signature.
46    pub signed_bytes: &'a [u8; 32],
47    /// Encoded OID contents, without an ASN.1 tag or length.
48    pub algorithm_oid: &'a [u8],
49    /// Plain big-endian ECDSA integer r.
50    pub r: &'a [u8],
51    /// Plain big-endian ECDSA integer s.
52    pub s: &'a [u8],
53}
54
55/// The structural check that failed. All inputs are treated as untrusted.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum ParseError {
58    /// Truncated data, trailing data, or signature width inconsistent with the configured key.
59    Length,
60    /// Incorrect wake-up marker.
61    Header,
62    /// Unsupported protocol version.
63    Version,
64    /// Invalid equipment identifier.
65    Recipient,
66    /// Malformed version-one reserved bytes.
67    Padding,
68    /// Unsupported signature encoding.
69    SignatureFormat,
70    /// Empty, oversized or malformed algorithm object identifier.
71    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
90/// Check the structural constraints of a nine-octet wake-up recipient identifier.
91/// An application can use this when commissioning its own gateway ID.
92pub 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
101/// DER OID contents for plain ECDSA with SHA-256 (0.4.0.127.0.7.1.1.4.1.3).
102pub const ECDSA_PLAIN_SHA256_OID: &[u8; 10] = &[4, 0, 127, 0, 7, 1, 1, 4, 1, 3];
103
104/// The exact 32 octets signed by the GWA in a version-one wake-up.
105pub struct WakeUpPrefix([u8; 32]);
106
107impl WakeUpPrefix {
108    /// Encode an equipment identifier and signed UTC timestamp following the §2.1 field rule.
109    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    /// Borrow the original message to pass to the ECDSA/SHA-256 signer.
121    pub fn as_bytes(&self) -> &[u8; 32] {
122        &self.0
123    }
124
125    /// Attach the fixed-width big-endian ECDSA components to the signed prefix.
126    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
138/// Inspect a complete version-one message with fixed space and bounded work.
139///
140/// ```
141/// use smgw_core::wakeup::{parse, ParseError, SignatureWidth};
142/// assert_eq!(parse(&[], SignatureWidth::Bits256), Err(ParseError::Length));
143/// ```
144pub 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    // OID subidentifiers use minimal base-128 groups and must terminate.
177    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    // Dummy signature bytes exercise the wire parser only.
203    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}