OSDP.Net 5.3.0-beta.3
A .NET library for implementing the Open Supervised Device Protocol (OSDP)
Loading...
Searching...
No Matches
MessageSpy.cs
1#nullable enable
2
3using System;
4using System.Collections.Generic;
5using System.Dynamic;
6using System.Globalization;
7using System.Linq;
8using System.Text.Json;
11using OSDP.Net.Model;
14
15namespace OSDP.Net.Tracing;
16
21public class MessageSpy
22{
23 private const byte MarkByte = 0xFF;
24
25 private readonly SecurityContext _context;
26 private readonly MessageSecureChannel _commandSpyChannel;
27 private readonly MessageSecureChannel _replySpyChannel;
28
33 public MessageSpy(byte[]? securityKey = null)
34 {
35 _context = new SecurityContext(securityKey);
36 _commandSpyChannel = new PdMessageSecureChannelBase(_context);
37 _replySpyChannel = new ACUMessageSecureChannel(_context);
38 }
39
45 public byte PeekAddressByte(ReadOnlySpan<byte> data)
46 {
47 return SkipMarkBytes(data)[1];
48 }
49
56 private static ReadOnlySpan<byte> SkipMarkBytes(ReadOnlySpan<byte> data)
57 {
58 int index = 0;
59 while (index < data.Length && data[index] == MarkByte)
60 {
61 index++;
62 }
63
64 return data.Slice(index);
65 }
66
72 public IncomingMessage ParseCommand(byte[] data)
73 {
74 var command = new IncomingMessage(SkipMarkBytes(data), _commandSpyChannel);
75
76 return (CommandType)command.Type switch
77 {
78 CommandType.SessionChallenge => HandleSessionChallenge(command),
79 CommandType.ServerCryptogram => HandleSCrypt(command),
80 CommandType.KeySet => HandleKeySet(command),
81 _ => command
82 };
83 }
84
85 private IncomingMessage HandleKeySet(IncomingMessage command)
86 {
87 // osdp_KEYSET installs a new Secure Channel Base Key. The command is delivered over the
88 // current secure channel, so once its payload has been decrypted we capture the new key and
89 // apply it to the shared security context. The ACU then tears down and re-establishes the
90 // secure channel, and that handshake must derive its session keys (S-ENC/S-MAC) from this
91 // new key rather than the one originally supplied to the parser. Without this, every
92 // encrypted payload after the re-key decodes to garbage (e.g. "missing a padding byte").
93 if (command.IsPayloadDecrypted)
94 {
95 var keyConfiguration = EncryptionKeyConfiguration.ParseData(command.Payload);
96 _context.UpdateSecurityKey(keyConfiguration.KeyData);
97 }
98
99 return command;
100 }
101
107 public IncomingMessage ParseReply(byte[] data)
108 {
109 var reply = new IncomingMessage(SkipMarkBytes(data), _replySpyChannel);
110
111 return (ReplyType)reply.Type switch
112 {
113 ReplyType.InitialRMac => HandleInitialRMac(reply),
114 _ => reply
115 };
116 }
117
118 private IncomingMessage HandleSessionChallenge(IncomingMessage command)
119 {
120 // The osdp_CHLNG security block data byte is the authoritative indicator of which key the
121 // session uses: 0x00 = well-known default key (SCBK-D), anything else = per-installation key
122 // (SCBK). Record it so every subsequent secure message in this session reports the actual
123 // wire key type rather than the key that happened to be supplied to the parser.
124 if (command.SecureBlockData is { Length: > 0 })
125 {
126 bool isUsingDefaultKey = command.SecureBlockData[0] == 0x00;
127 _context.IsUsingDefaultKey = isUsingDefaultKey;
128 // The command message was constructed before the context was updated above, so re-stamp
129 // it too, keeping the osdp_CHLNG packet consistent with the rest of the session.
130 command.IsUsingDefaultKey = isUsingDefaultKey;
131 }
132
133 byte[] rndA = command.Payload;
134 var crypto = _context.CreateCypher(true);
135 _context.Enc = SecurityContext.GenerateKey(crypto,
136 [0x01, 0x82, rndA[0], rndA[1], rndA[2], rndA[3], rndA[4], rndA[5]]);
137 _context.SMac1 = SecurityContext.GenerateKey(crypto,
138 [0x01, 0x01, rndA[0], rndA[1], rndA[2], rndA[3], rndA[4], rndA[5]]);
139 _context.SMac2 = SecurityContext.GenerateKey(crypto,
140 [0x01, 0x02, rndA[0], rndA[1], rndA[2], rndA[3], rndA[4], rndA[5]]);
141 return command;
142 }
143
144 private IncomingMessage HandleSCrypt(IncomingMessage command)
145 {
146 var serverCryptogram = command.Payload;
147 using var crypto = _context.CreateCypher(true, _context.SMac1);
148 var intermediate = SecurityContext.GenerateKey(crypto, serverCryptogram);
149 crypto.Key = _context.SMac2;
150 _context.RMac = SecurityContext.GenerateKey(crypto, intermediate);
151 return command;
152 }
153
154 private IncomingMessage HandleInitialRMac(IncomingMessage reply)
155 {
156 _context.IsSecurityEstablished = true;
157 return reply;
158 }
159
165 public Packet ParsePacket(byte[] data)
166 {
167 const byte replyAddress = 0x80;
168 var message = PeekAddressByte(data) < replyAddress
169 ? ParseCommand(data)
170 : ParseReply(data);
171 return new Packet(message);
172 }
173
180 public bool TryParsePacket(byte[] data, out Packet? packet)
181 {
182 try
183 {
184 packet = ParsePacket(data);
185 return true;
186 }
187 catch
188 {
189 packet = null;
190 return false;
191 }
192 }
193
199 public IEnumerable<OSDPCaptureEntry> ParseCaptureFile(string json)
200 {
201 var lines = json.Split('\n');
202 foreach (var line in lines)
203 {
204 if (string.IsNullOrWhiteSpace(line)) continue;
205
206 dynamic? entry = JsonSerializer.Deserialize<ExpandoObject>(line);
207 if (entry == null) continue;
208
209 DateTime dateTime = new DateTime(1970, 1, 1)
210 .AddSeconds(double.Parse(entry.timeSec.ToString(), CultureInfo.InvariantCulture))
211 .AddTicks(long.Parse(entry.timeNano.ToString(), CultureInfo.InvariantCulture) / 100L);
212 Enum.TryParse(entry.io.ToString(), true, out TraceDirection io);
213 string data = entry.data.ToString();
214
215 var rawData = BinaryUtils.HexToBytes(data).ToArray();
216
217 // A capture can begin or end mid-frame (e.g. libosdp-conformance records the tail of a
218 // frame already in flight when tracing starts). Such fragments can't be decoded, so skip
219 // them rather than aborting the whole file.
220 if (!IsCompleteFrame(SkipMarkBytes(rawData))) continue;
221
222 var packet = ParsePacket(rawData);
223
224 yield return new OSDPCaptureEntry(
225 dateTime,
226 io,
227 packet,
228 entry.osdpTraceVersion.ToString(),
229 entry.osdpSource.ToString());
230 }
231 }
232
239 private static bool IsCompleteFrame(ReadOnlySpan<byte> data)
240 {
241 // SOM, ADDR, LEN_LSB, LEN_MSB, CTRL, CMND/REPLY and a one-byte checksum
242 const int minimumFrameSize = 7;
243
244 return data.Length >= minimumFrameSize &&
245 data[0] == Message.StartOfMessage &&
246 (data[2] | (data[3] << 8)) == data.Length;
247 }
248}
Represents a message that was received from the wire.
bool IsPayloadDecrypted
Indicates whether the payload was successfully decrypted.
byte[] SecureBlockData
Raw security block bytes.
byte[] Payload
Returns the raw message payload.
const byte StartOfMessage
OSDP message SOM (start of the message) byte.
Definition Message.cs:21
Message channel which represents the Access Control Unit (ACU) side of the OSDP communications (i....
V2 implementation of a SecureChannel class.
Security context used within MessageSecureChannel.
Command data to set the encryption key configuration on a PD.
static EncryptionKeyConfiguration ParseData(ReadOnlySpan< byte > data)
Parses the message payload bytes.
Information details of a message packet.
Definition Packet.cs:14
IEnumerable< OSDPCaptureEntry > ParseCaptureFile(string json)
Parses an OSDP capture file in JSON format.
bool TryParsePacket(byte[] data, out Packet? packet)
Attempts to parse raw OSDP data into a Packet without throwing exceptions.
byte PeekAddressByte(ReadOnlySpan< byte > data)
Retrieves the address byte from raw OSDP data without parsing the entire message.
Definition MessageSpy.cs:45
Packet ParsePacket(byte[] data)
Parses raw OSDP data into a Packet, automatically detecting command vs.
IncomingMessage ParseCommand(byte[] data)
Parses raw OSDP command data into an IncomingMessage, handling the secure channel establishment.
Definition MessageSpy.cs:72
IncomingMessage ParseReply(byte[] data)
Parses raw OSDP reply data into an IncomingMessage, handling the secure channel establishment.
MessageSpy(byte[]? securityKey=null)
Initializes a new instance of the MessageSpy class with an optional security key.
Definition MessageSpy.cs:33
One line entry of a file that captures OSDP messages.
Helper routines for manipulating binary representations of data that are used within the OSDP....
static IEnumerable< byte > HexToBytes(IEnumerable< char > seq)
Convert a sequence of hex digit characters into their byte representation.
ReplyType
Identifies the type of OSDP protocol reply (PD -> ACU) message.
Definition ReplyType.cs:7
@ InitialRMac
osdp_RMAC_I - client cryptogram packet and the initial R-MAC
Definition ReplyType.cs:91
CommandType
Identifies the type of OSDP protocol command (ACU -> PD) message.
Definition CommandType.cs:7
@ ServerCryptogram
osdp_SCRYPT - server's random number and server cryptogram
@ KeySet
osdp_KEYSET - Encryption key set
@ SessionChallenge
osdp_CHLNG - challenge and secure session initialization request
TraceDirection
Direction of trace.
Definition TraceEntry.cs:9