OSDP.Net 5.3.0-beta.3
A .NET library for implementing the Open Supervised Device Protocol (OSDP)
Loading...
Searching...
No Matches
OSDPPacketTextFormatter.cs
1using System;
2using System.Collections.Generic;
3using System.Globalization;
4using System.Text;
7
8namespace OSDP.Net.Tracing;
9
14{
17 public string FormatPacket(Packet packet, DateTime timestamp, TimeSpan? timeDelta = null)
18 {
19 if (packet == null)
20 throw new ArgumentNullException(nameof(packet));
21
22 var sb = new StringBuilder();
23
24 string deltaString = FormatTimeDelta(timeDelta);
25 string direction = packet.CommandType != null ? "ACU -> PD" : "PD -> ACU";
26 string type = (packet.CommandType?.GetDisplayName() ?? packet.ReplyType?.GetDisplayName()) ?? "Unknown";
27
28 sb.AppendLine($"{FormatTimestamp(timestamp)}{deltaString} {direction}: {type}");
29 sb.Append($" Address: {packet.Address} Sequence: {packet.Sequence}");
30 if (packet.IsSecureMessage)
31 {
32 sb.Append(packet.IsUsingDefaultKey ? " [Secure - Default Key]" : " [Secure]");
33 }
34 else
35 {
36 sb.Append(" [Clear Text]");
37 }
38 sb.AppendLine();
39
40 if (!packet.IsPayloadDecrypted)
41 {
42 sb.AppendLine(" *** Payload is encrypted - SCBK (Secure Channel Base Key) required to decrypt ***");
43 }
44 else
45 {
46 string secureChannelDetails = FormatSecureChannelHandshake(packet);
47 if (secureChannelDetails != null)
48 {
49 sb.AppendLine(secureChannelDetails);
50 }
51 else
52 {
53 var payloadData = packet.ParsePayloadData();
54 if (payloadData != null)
55 {
56 string payloadString = payloadData switch
57 {
58 byte[] data => $" {BitConverter.ToString(data)}",
59 _ => $" {payloadData}"
60 };
61 sb.AppendLine(payloadString);
62 }
63 }
64 }
65
66 sb.AppendLine();
67 return sb.ToString();
68 }
69
75 private static string FormatSecureChannelHandshake(Packet packet)
76 {
77 switch (packet.CommandType)
78 {
79 case CommandType.SessionChallenge:
80 return FormatSessionChallenge(packet);
81 case CommandType.ServerCryptogram:
82 return FormatServerCryptogram(packet);
83 }
84
85 switch (packet.ReplyType)
86 {
87 case ReplyType.CrypticData:
88 return FormatCrypticData(packet);
89 case ReplyType.InitialRMac:
90 return FormatInitialRMac(packet);
91 }
92
93 return null;
94 }
95
96 private static string FormatSessionChallenge(Packet packet)
97 {
98 var payload = packet.RawPayloadData;
99 var lines = new List<string>
100 {
101 " Secure Channel Handshake: osdp_CHLNG (Step 1 of 4 - ACU challenge)",
102 FormatSecurityBlockLine(packet, DescribeKeyType(packet))
103 };
104 lines.Add(payload.Length >= 8
105 ? $" RND.A (ACU random): {Hex(payload.Slice(0, 8))}"
106 : $" Payload: {Hex(payload)}");
107 return string.Join(Environment.NewLine, lines);
108 }
109
110 private static string FormatCrypticData(Packet packet)
111 {
112 var payload = packet.RawPayloadData;
113 var lines = new List<string>
114 {
115 " Secure Channel Handshake: osdp_CCRYPT (Step 2 of 4 - PD response)",
116 FormatSecurityBlockLine(packet, DescribeKeyType(packet))
117 };
118 if (payload.Length >= 32)
119 {
120 lines.Add($" cUID (PD unique ID): {Hex(payload.Slice(0, 8))}");
121 lines.Add($" RND.B (PD random): {Hex(payload.Slice(8, 8))}");
122 lines.Add($" Client cryptogram: {Hex(payload.Slice(16, 16))}");
123 }
124 else
125 {
126 lines.Add($" Payload: {Hex(payload)}");
127 }
128 return string.Join(Environment.NewLine, lines);
129 }
130
131 private static string FormatServerCryptogram(Packet packet)
132 {
133 return string.Join(Environment.NewLine,
134 " Secure Channel Handshake: osdp_SCRYPT (Step 3 of 4 - ACU server cryptogram)",
135 FormatSecurityBlockLine(packet, DescribeKeyType(packet)),
136 $" Server cryptogram: {Hex(packet.RawPayloadData)}");
137 }
138
139 private static string FormatInitialRMac(Packet packet)
140 {
141 return string.Join(Environment.NewLine,
142 " Secure Channel Handshake: osdp_RMAC_I (Step 4 of 4 - secure channel established)",
143 FormatSecurityBlockLine(packet, DescribeCryptogramAcceptance(packet)),
144 $" Initial R-MAC: {Hex(packet.RawPayloadData)}");
145 }
146
151 private static string FormatSecurityBlockLine(Packet packet, string interpretation)
152 {
153 string scsType = DescribeSecurityBlockType(packet.IncomingMessage.SecurityBlockType);
154 string data = FormatSecureBlockData(packet.IncomingMessage.SecureBlockData);
155 string suffix = string.IsNullOrEmpty(interpretation) ? string.Empty : $" ({interpretation})";
156 return $" Security Block: {scsType}, SEC_BLK_DATA: {data}{suffix}";
157 }
158
159 private static string DescribeSecurityBlockType(byte type)
160 {
161 return type switch
162 {
163 0x11 => "SCS_11",
164 0x12 => "SCS_12",
165 0x13 => "SCS_13",
166 0x14 => "SCS_14",
167 0x15 => "SCS_15",
168 0x16 => "SCS_16",
169 0x17 => "SCS_17",
170 0x18 => "SCS_18",
171 _ => $"0x{type:X2}"
172 };
173 }
174
179 private static string DescribeKeyType(Packet packet)
180 {
181 var secureBlockData = packet.IncomingMessage.SecureBlockData;
182 if (secureBlockData == null || secureBlockData.Length == 0)
183 {
184 return null;
185 }
186
187 return secureBlockData[0] == 0x00 ? "Default key (SCBK-D)" : "Configured key (SCBK)";
188 }
189
195 private static string DescribeCryptogramAcceptance(Packet packet)
196 {
197 var secureBlockData = packet.IncomingMessage.SecureBlockData;
198 if (secureBlockData == null || secureBlockData.Length == 0)
199 {
200 return null;
201 }
202
203 return secureBlockData[0] == 0x01
204 ? "Server cryptogram accepted"
205 : "Server cryptogram rejected";
206 }
207
208 private static string FormatSecureBlockData(byte[] data) =>
209 data == null || data.Length == 0 ? "(none)" : BitConverter.ToString(data);
210
211 private static string Hex(ReadOnlySpan<byte> data) => BitConverter.ToString(data.ToArray());
212
215 public string FormatError(byte[] rawData, DateTime timestamp, TimeSpan? timeDelta, string errorMessage)
216 {
217 if (rawData == null)
218 throw new ArgumentNullException(nameof(rawData));
219
220 var sb = new StringBuilder();
221 string deltaString = FormatTimeDelta(timeDelta);
222
223 sb.AppendLine($"{FormatTimestamp(timestamp)}{deltaString}");
224 sb.AppendLine($"*** Error parsing packet: {errorMessage} ***");
225 sb.AppendLine($" Raw data: {BitConverter.ToString(rawData)}");
226 sb.AppendLine();
227 return sb.ToString();
228 }
229
230 // Invariant so the trace reads the same on every machine, whatever its date and time separators
231 private static string FormatTimestamp(DateTime timestamp) =>
232 timestamp.ToString("yy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
233
234 private static string FormatTimeDelta(TimeSpan? timeDelta)
235 {
236 return timeDelta.HasValue ? $" [ {timeDelta.Value:g} ]" : string.Empty;
237 }
238}
byte SecurityBlockType
Type of the security block, if there is one.
byte[] SecureBlockData
Raw security block bytes.
Information details of a message packet.
Definition Packet.cs:14
CommandType? CommandType
The type of command sent or null it is a reply.
Definition Packet.cs:62
bool IsPayloadDecrypted
Indicates whether the payload was successfully decrypted.
Definition Packet.cs:82
ReplyType? ReplyType
The type of reply sent or null it is a command.
Definition Packet.cs:67
bool IsSecureMessage
Indicates if the message was sent via an established secure channel.
Definition Packet.cs:87
ReadOnlySpan< byte > RawPayloadData
Raw bytes of the payload data.
Definition Packet.cs:215
object ParsePayloadData()
Parse the payload data into an object.
Definition Packet.cs:98
IncomingMessage IncomingMessage
The underlying incoming message.
Definition Packet.cs:47
bool IsUsingDefaultKey
Indicates if the secure channel is using the default key.
Definition Packet.cs:92
Default implementation of IPacketTextFormatter for formatting OSDP packets as human-readable text.
string FormatError(byte[] rawData, DateTime timestamp, TimeSpan? timeDelta, string errorMessage)
Formats a packet that failed to parse due to an error.Formatted text with error information and raw d...
string FormatPacket(Packet packet, DateTime timestamp, TimeSpan? timeDelta=null)
Formats a successfully parsed packet as text.Formatted text representation of the packet.
Interface for formatting OSDP packets as human-readable text.
ReplyType
Identifies the type of OSDP protocol reply (PD -> ACU) message.
Definition ReplyType.cs:7
CommandType
Identifies the type of OSDP protocol command (ACU -> PD) message.
Definition CommandType.cs:7