Revert "TODO epan/dissectors/asn1/kerberos/packet-kerberos-template.c new GSS flags"
[wireshark-sm.git] / epan / dissectors / packet-zbee-security.c
blobb4b28fc9a4e64dd6915d0032d5b4ecc6969e1da0
1 /* packet-zbee-security.c
2 * Dissector helper routines for encrypted ZigBee frames.
3 * By Owen Kirby <osk@exegin.com>; portions by Fred Fierling <fff@exegin.com>
4 * Copyright 2009 Exegin Technologies Limited
6 * Wireshark - Network traffic analyzer
7 * By Gerald Combs <gerald@wireshark.org>
8 * Copyright 1998 Gerald Combs
10 * SPDX-License-Identifier: GPL-2.0-or-later
13 /* Include Files */
14 #include "config.h"
17 #include <epan/packet.h>
18 #include <epan/exceptions.h>
20 #include <epan/prefs.h>
21 #include <epan/expert.h>
22 #include <epan/uat.h>
23 #include <epan/proto_data.h>
25 /* We require libgcrpyt in order to decrypt ZigBee packets. Without it the best
26 * we can do is parse the security header and give up.
28 #include <wsutil/wsgcrypt.h>
29 #include <wsutil/pint.h>
31 #include "packet-ieee802154.h"
32 #include "packet-zbee.h"
33 #include "packet-zbee-nwk.h"
34 #include "packet-zbee-aps.h" /* for ZBEE_APS_CMD_KEY_LENGTH */
35 #include "packet-zbee-security.h"
37 /* Helper Functions */
38 static void zbee_sec_key_hash(uint8_t *, uint8_t, uint8_t *);
39 static void zbee_sec_make_nonce (zbee_security_packet *, uint8_t *);
40 static bool zbee_sec_decrypt_payload(zbee_security_packet *, const char *, const char, uint8_t *,
41 unsigned, unsigned, uint8_t *);
42 static bool zbee_security_parse_key(const char *, uint8_t *, bool);
44 /* Field pointers. */
45 static int hf_zbee_sec_field;
46 static int hf_zbee_sec_level;
47 static int hf_zbee_sec_key_id;
48 static int hf_zbee_sec_nonce;
49 static int hf_zbee_sec_verified_fc;
50 static int hf_zbee_sec_counter;
51 static int hf_zbee_sec_src64;
52 static int hf_zbee_sec_key_seqno;
53 static int hf_zbee_sec_mic;
54 static int hf_zbee_sec_key;
55 static int hf_zbee_sec_key_origin;
56 static int hf_zbee_sec_decryption_key;
58 /* Subtree pointers. */
59 static int ett_zbee_sec;
60 static int ett_zbee_sec_control;
62 static expert_field ei_zbee_sec_encrypted_payload;
63 static expert_field ei_zbee_sec_encrypted_payload_sliced;
64 static expert_field ei_zbee_sec_extended_source_unknown;
66 static const value_string zbee_sec_key_names[] = {
67 { ZBEE_SEC_KEY_LINK, "Link Key" },
68 { ZBEE_SEC_KEY_NWK, "Network Key" },
69 { ZBEE_SEC_KEY_TRANSPORT, "Key-Transport Key" },
70 { ZBEE_SEC_KEY_LOAD, "Key-Load Key" },
71 { 0, NULL }
74 #if 0
75 /* These aren't really used anymore, as ZigBee no longer includes them in the
76 * security control field. If we were to display them all we would ever see is
77 * security level 0.
79 static const value_string zbee_sec_level_names[] = {
80 { ZBEE_SEC_NONE, "None" },
81 { ZBEE_SEC_MIC32, "No Encryption, 32-bit MIC" },
82 { ZBEE_SEC_MIC64, "No Encryption, 64-bit MIC" },
83 { ZBEE_SEC_MIC128, "No Encryption, 128-bit MIC" },
84 { ZBEE_SEC_ENC, "Encryption, No MIC" },
85 { ZBEE_SEC_ENC_MIC32, "Encryption, 32-bit MIC" },
86 { ZBEE_SEC_ENC_MIC64, "Encryption, 64-bit MIC" },
87 { ZBEE_SEC_ENC_MIC128, "Encryption, 128-bit MIC" },
88 { 0, NULL }
90 #endif
92 /* The ZigBee security level, in enum_val_t for the security preferences. */
93 static const enum_val_t zbee_sec_level_enums[] = {
94 { "None", "No Security", ZBEE_SEC_NONE },
95 { "MIC32", "No Encryption, 32-bit Integrity Protection", ZBEE_SEC_MIC32 },
96 { "MIC64", "No Encryption, 64-bit Integrity Protection", ZBEE_SEC_MIC64 },
97 { "MIC128", "No Encryption, 128-bit Integrity Protection", ZBEE_SEC_MIC128 },
98 { "ENC", "AES-128 Encryption, No Integrity Protection", ZBEE_SEC_ENC },
99 { "ENC-MIC32", "AES-128 Encryption, 32-bit Integrity Protection", ZBEE_SEC_ENC_MIC32 },
100 { "ENC-MIC64", "AES-128 Encryption, 64-bit Integrity Protection", ZBEE_SEC_ENC_MIC64 },
101 { "ENC-MIC128", "AES-128 Encryption, 128-bit Integrity Protection", ZBEE_SEC_ENC_MIC128 },
102 { NULL, NULL, 0 }
105 static int gPREF_zbee_sec_level = ZBEE_SEC_ENC_MIC32;
106 static uat_t *zbee_sec_key_table_uat;
108 static const value_string byte_order_vals[] = {
109 { 0, "Normal"},
110 { 1, "Reverse"},
111 { 0, NULL }
114 /* UAT Key Entry */
115 typedef struct _uat_key_record_t {
116 char *string;
117 uint8_t byte_order;
118 char *label;
119 } uat_key_record_t;
121 UAT_CSTRING_CB_DEF(uat_key_records, string, uat_key_record_t)
122 UAT_VS_DEF(uat_key_records, byte_order, uat_key_record_t, uint8_t, 0, "Normal")
123 UAT_CSTRING_CB_DEF(uat_key_records, label, uat_key_record_t)
125 static GSList *zbee_pc_keyring;
126 static uat_key_record_t *uat_key_records;
127 static unsigned num_uat_key_records;
129 static void* uat_key_record_copy_cb(void* n, const void* o, size_t siz _U_) {
130 uat_key_record_t* new_key = (uat_key_record_t *)n;
131 const uat_key_record_t* old_key = (const uat_key_record_t *)o;
133 new_key->string = g_strdup(old_key->string);
134 new_key->label = g_strdup(old_key->label);
135 new_key->byte_order = old_key->byte_order;
137 return new_key;
140 static bool uat_key_record_update_cb(void* r, char** err) {
141 uat_key_record_t* rec = (uat_key_record_t *)r;
142 uint8_t key[ZBEE_SEC_CONST_KEYSIZE];
144 if (rec->string == NULL) {
145 *err = g_strdup("Key can't be blank");
146 return false;
147 } else {
148 g_strstrip(rec->string);
150 if (rec->string[0] != 0) {
151 *err = NULL;
152 if ( !zbee_security_parse_key(rec->string, key, rec->byte_order) ) {
153 *err = ws_strdup_printf("Expecting %d hexadecimal bytes or\n"
154 "a %d character double-quoted string", ZBEE_SEC_CONST_KEYSIZE, ZBEE_SEC_CONST_KEYSIZE);
155 return false;
157 } else {
158 *err = g_strdup("Key can't be blank");
159 return false;
162 return true;
165 static void uat_key_record_free_cb(void*r) {
166 uat_key_record_t* key = (uat_key_record_t *)r;
168 g_free(key->string);
169 g_free(key->label);
172 static void zbee_free_key_record(void *ptr)
174 key_record_t *k = (key_record_t *)ptr;
176 g_free(k->label);
177 g_free(k);
180 static void uat_key_record_post_update(void) {
181 unsigned i;
182 key_record_t key_record;
183 uint8_t key[ZBEE_SEC_CONST_KEYSIZE];
185 /* empty the key ring */
186 if (zbee_pc_keyring) {
187 g_slist_free_full(zbee_pc_keyring, zbee_free_key_record);
188 zbee_pc_keyring = NULL;
191 /* Load the pre-configured slist from the UAT. */
192 for (i=0; (uat_key_records) && (i<num_uat_key_records) ; i++) {
193 if (zbee_security_parse_key(uat_key_records[i].string, key, uat_key_records[i].byte_order)) {
194 key_record.frame_num = ZBEE_SEC_PC_KEY; /* means it's a user PC key */
195 key_record.label = g_strdup(uat_key_records[i].label);
196 memcpy(key_record.key, key, ZBEE_SEC_CONST_KEYSIZE);
197 zbee_pc_keyring = g_slist_prepend(zbee_pc_keyring, g_memdup2(&key_record, sizeof(key_record_t)));
203 * Enable this macro to use libgcrypt's CBC_MAC mode for the authentication
204 * phase. Unfortunately, this is broken, and I don't know why. However, using
205 * the messier EBC mode (to emulate CCM*) still works fine.
207 #if 0
208 #define ZBEE_SEC_USE_GCRYPT_CBC_MAC
209 #endif
210 /*FUNCTION:------------------------------------------------------
211 * NAME
212 * zbee_security_register
213 * DESCRIPTION
214 * Called by proto_register_zbee_nwk() to initialize the security
215 * dissectors.
216 * PARAMETERS
217 * module_t zbee_prefs - Prefs module to load preferences under.
218 * RETURNS
219 * none
220 *---------------------------------------------------------------
222 void zbee_security_register(module_t *zbee_prefs, int proto)
224 static hf_register_info hf[] = {
225 { &hf_zbee_sec_field,
226 { "Security Control Field", "zbee.sec.field", FT_UINT8, BASE_HEX, NULL,
227 0x0, NULL, HFILL }},
229 { &hf_zbee_sec_level,
230 { "Security Level", "zbee.sec.sec_level", FT_UINT8, BASE_HEX, NULL,
231 ZBEE_SEC_CONTROL_LEVEL, NULL, HFILL }},
233 { &hf_zbee_sec_key_id,
234 { "Key Id", "zbee.sec.key_id", FT_UINT8, BASE_HEX, VALS(zbee_sec_key_names),
235 ZBEE_SEC_CONTROL_KEY, NULL, HFILL }},
237 { &hf_zbee_sec_nonce,
238 { "Extended Nonce", "zbee.sec.ext_nonce", FT_BOOLEAN, 8, NULL, ZBEE_SEC_CONTROL_NONCE,
239 NULL, HFILL }},
241 { &hf_zbee_sec_verified_fc,
242 { "Require Verified Frame Counter", "zbee.sec.verified_fc", FT_UINT8, BASE_HEX, NULL,
243 ZBEE_SEC_CONTROL_VERIFIED_FC, NULL, HFILL }},
245 { &hf_zbee_sec_counter,
246 { "Frame Counter", "zbee.sec.counter", FT_UINT32, BASE_DEC, NULL, 0x0,
247 NULL, HFILL }},
249 { &hf_zbee_sec_src64,
250 { "Extended Source", "zbee.sec.src64", FT_EUI64, BASE_NONE, NULL, 0x0,
251 NULL, HFILL }},
253 { &hf_zbee_sec_key_seqno,
254 { "Key Sequence Number", "zbee.sec.key_seqno", FT_UINT8, BASE_DEC, NULL, 0x0,
255 NULL, HFILL }},
257 { &hf_zbee_sec_mic,
258 { "Message Integrity Code", "zbee.sec.mic", FT_BYTES, BASE_NONE, NULL, 0x0,
259 NULL, HFILL }},
261 { &hf_zbee_sec_key,
262 { "Key", "zbee.sec.key", FT_BYTES, BASE_NONE, NULL, 0x0,
263 NULL, HFILL }},
265 { &hf_zbee_sec_key_origin,
266 { "Key Origin", "zbee.sec.key.origin", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
267 NULL, HFILL }},
269 { &hf_zbee_sec_decryption_key,
270 { "Key Label", "zbee.sec.decryption_key", FT_STRING, BASE_NONE, NULL, 0x0,
271 NULL, HFILL }}
274 static int *ett[] = {
275 &ett_zbee_sec,
276 &ett_zbee_sec_control
279 static ei_register_info ei[] = {
280 { &ei_zbee_sec_encrypted_payload, { "zbee_sec.encrypted_payload", PI_UNDECODED, PI_WARN, "Encrypted Payload", EXPFILL }},
281 { &ei_zbee_sec_encrypted_payload_sliced, { "zbee_sec.encrypted_payload_sliced", PI_UNDECODED, PI_WARN, "Encrypted payload, cut short when capturing - can't decrypt", EXPFILL }},
282 { &ei_zbee_sec_extended_source_unknown, { "zbee_sec.extended_source_unknown", PI_PROTOCOL, PI_NOTE, "Extended Source: Unknown", EXPFILL }},
285 expert_module_t* expert_zbee_sec;
287 static uat_field_t key_uat_fields[] = {
288 UAT_FLD_CSTRING(uat_key_records, string, "Key",
289 "A 16-byte key in hexadecimal with optional dash-,\n"
290 "colon-, or space-separator characters, or a\n"
291 "a 16-character string in double-quotes."),
292 UAT_FLD_VS(uat_key_records, byte_order, "Byte Order", byte_order_vals,
293 "Byte order of key."),
294 UAT_FLD_CSTRING(uat_key_records, label, "Label", "User label for key."),
295 UAT_END_FIELDS
298 /* If no prefs module was supplied, register our own. */
299 if (zbee_prefs == NULL) {
300 zbee_prefs = prefs_register_protocol(proto, NULL);
303 /* Register preferences */
304 prefs_register_enum_preference(zbee_prefs, "seclevel", "Security Level",
305 "Specifies the security level to use in the\n"
306 "decryption process. This value is ignored\n"
307 "for ZigBee 2004 and unsecured networks.",
308 &gPREF_zbee_sec_level, zbee_sec_level_enums, false);
310 zbee_sec_key_table_uat = uat_new("Pre-configured Keys",
311 sizeof(uat_key_record_t),
312 "zigbee_pc_keys",
313 true,
314 &uat_key_records,
315 &num_uat_key_records,
316 UAT_AFFECTS_DISSECTION, /* affects dissection of packets, but not set of named fields */
317 NULL, /* TODO: ptr to help manual? */
318 uat_key_record_copy_cb,
319 uat_key_record_update_cb,
320 uat_key_record_free_cb,
321 uat_key_record_post_update,
322 NULL,
323 key_uat_fields );
325 prefs_register_uat_preference(zbee_prefs,
326 "key_table",
327 "Pre-configured Keys",
328 "Pre-configured link or network keys.",
329 zbee_sec_key_table_uat);
331 proto_register_field_array(proto, hf, array_length(hf));
332 proto_register_subtree_array(ett, array_length(ett));
333 expert_zbee_sec = expert_register_protocol(proto);
334 expert_register_field_array(expert_zbee_sec, ei, array_length(ei));
336 } /* zbee_security_register */
338 /*FUNCTION:------------------------------------------------------
339 * NAME
340 * zbee_security_parse_key
341 * DESCRIPTION
342 * Parses a key string from left to right into a buffer with
343 * increasing (normal byte order) or decreasing (reverse byte
344 * order) address.
345 * PARAMETERS
346 * const char *key_str - pointer to the string
347 * uint8_t *key_buf - destination buffer in memory
348 * bool big_end - fill key_buf with incrementing address
349 * RETURNS
350 * bool
351 *---------------------------------------------------------------
353 static bool
354 zbee_security_parse_key(const char *key_str, uint8_t *key_buf, bool byte_order)
356 int i, j;
357 char temp;
358 bool string_mode = false;
360 /* Clear the key. */
361 memset(key_buf, 0, ZBEE_SEC_CONST_KEYSIZE);
362 if (key_str == NULL) {
363 return false;
367 * Attempt to parse the key string. The key string must
368 * be at least 16 pairs of hexidecimal digits with the
369 * following optional separators: ':', '-', " ", or 16
370 * alphanumeric characters after a double-quote.
372 if ( (temp = *key_str++) == '"') {
373 string_mode = true;
374 temp = *key_str++;
377 j = byte_order?ZBEE_SEC_CONST_KEYSIZE-1:0;
378 for (i=ZBEE_SEC_CONST_KEYSIZE-1; i>=0; i--) {
379 if ( string_mode ) {
380 if ( g_ascii_isprint(temp) ) {
381 key_buf[j] = temp;
382 temp = *key_str++;
383 } else {
384 return false;
387 else {
388 /* If this character is a separator, skip it. */
389 if ( (temp == ':') || (temp == '-') || (temp == ' ') ) temp = *(key_str++);
391 /* Process a nibble. */
392 if ( g_ascii_isxdigit (temp) ) key_buf[j] = g_ascii_xdigit_value(temp)<<4;
393 else return false;
395 /* Get the next nibble. */
396 temp = *(key_str++);
398 /* Process another nibble. */
399 if ( g_ascii_isxdigit (temp) ) key_buf[j] |= g_ascii_xdigit_value(temp);
400 else return false;
402 /* Get the next nibble. */
403 temp = *(key_str++);
406 /* Move key_buf pointer */
407 if ( byte_order ) {
408 j--;
409 } else {
410 j++;
413 } /* for */
415 /* If we get this far, then the key was good. */
416 return true;
417 } /* zbee_security_parse_key */
419 /*FUNCTION:------------------------------------------------------
420 * NAME
421 * dissect_zbee_secure
422 * DESCRIPTION
423 * Dissects and decrypts secured ZigBee frames.
425 * Will return a valid tvbuff only if security processing was
426 * successful. If processing fails, then this function will
427 * handle internally and return NULL.
428 * PARAMETERS
429 * tvbuff_t *tvb - pointer to buffer containing raw packet.
430 * packet_info *pinfo - pointer to packet information fields
431 * proto_tree *tree - pointer to data tree Wireshark uses to display packet.
432 * unsigned offset - pointer to the start of the auxiliary security header.
433 * uint64_t src64 - extended source address, or 0 if unknown.
434 * RETURNS
435 * tvbuff_t *
436 *---------------------------------------------------------------
438 tvbuff_t *
439 dissect_zbee_secure(tvbuff_t *tvb, packet_info *pinfo, proto_tree* tree, unsigned offset)
441 proto_tree *sec_tree;
443 zbee_security_packet packet;
444 unsigned mic_len;
445 int payload_len;
446 tvbuff_t *payload_tvb;
448 proto_item *ti;
449 proto_item *key_item;
450 uint8_t *enc_buffer;
451 uint8_t *dec_buffer;
452 bool decrypted;
453 GSList **nwk_keyring;
454 GSList *GSList_i;
455 key_record_t *key_rec = NULL;
456 zbee_nwk_hints_t *nwk_hints;
457 ieee802154_hints_t *ieee_hints;
458 ieee802154_map_rec *map_rec = NULL;
460 static int * const sec_flags[] = {
461 &hf_zbee_sec_level,
462 &hf_zbee_sec_key_id,
463 &hf_zbee_sec_nonce,
464 &hf_zbee_sec_verified_fc,
465 NULL
468 /* Init */
469 memset(&packet, 0, sizeof(zbee_security_packet));
471 /* Get pointers to any useful frame data from lower layers */
472 nwk_hints = (zbee_nwk_hints_t *)p_get_proto_data(wmem_file_scope(), pinfo,
473 proto_get_id_by_filter_name(ZBEE_PROTOABBREV_NWK), 0);
474 ieee_hints = (ieee802154_hints_t *)p_get_proto_data(wmem_file_scope(), pinfo,
475 proto_get_id_by_filter_name(IEEE802154_PROTOABBREV_WPAN), 0);
477 /* Create a subtree for the security information. */
478 sec_tree = proto_tree_add_subtree(tree, tvb, offset, -1, ett_zbee_sec, NULL, "ZigBee Security Header");
480 /* Get and display the Security control field */
481 packet.control = tvb_get_uint8(tvb, offset);
483 /* Patch the security level. */
484 packet.control &= ~ZBEE_SEC_CONTROL_LEVEL;
485 packet.control |= (ZBEE_SEC_CONTROL_LEVEL & gPREF_zbee_sec_level);
488 * Eww, I think I just threw up a little... ZigBee requires this field
489 * to be patched before computing the MIC, but we don't have write-access
490 * to the tvbuff. So we need to allocate a copy of the whole thing just
491 * so we can fix these 3 bits. Memory allocated by tvb_memdup(pinfo->pool,...)
492 * is automatically freed before the next packet is processed.
494 enc_buffer = (uint8_t *)tvb_memdup(pinfo->pool, tvb, 0, tvb_captured_length(tvb));
496 * Override the const qualifiers and patch the security level field, we
497 * know it is safe to overide the const qualifiers because we just
498 * allocated this memory via tvb_memdup(pinfo->pool,...).
500 enc_buffer[offset] = packet.control;
501 packet.level = zbee_get_bit_field(packet.control, ZBEE_SEC_CONTROL_LEVEL);
502 packet.key_id = zbee_get_bit_field(packet.control, ZBEE_SEC_CONTROL_KEY);
503 packet.nonce = zbee_get_bit_field(packet.control, ZBEE_SEC_CONTROL_NONCE);
505 proto_tree_add_bitmask(sec_tree, tvb, offset, hf_zbee_sec_field, ett_zbee_sec_control, sec_flags, ENC_NA);
506 offset += 1;
508 /* Get and display the frame counter field. */
509 packet.counter = tvb_get_letohl(tvb, offset);
510 proto_tree_add_uint(sec_tree, hf_zbee_sec_counter, tvb, offset, 4, packet.counter);
511 offset += 4;
513 if (packet.nonce) {
514 /* Get and display the source address of the device that secured this payload. */
515 packet.src64 = tvb_get_letoh64(tvb, offset);
516 proto_tree_add_item(sec_tree, hf_zbee_sec_src64, tvb, offset, 8, ENC_LITTLE_ENDIAN);
517 #if 1
518 if (!pinfo->fd->visited) {
519 switch ( packet.key_id ) {
520 case ZBEE_SEC_KEY_LINK:
521 if (nwk_hints && ieee_hints) {
522 /* Map this long address with the nwk layer short address. */
523 nwk_hints->map_rec = ieee802154_addr_update(&zbee_nwk_map, nwk_hints->src,
524 ieee_hints->src_pan, packet.src64, pinfo->current_proto, pinfo->num);
526 break;
528 case ZBEE_SEC_KEY_NWK:
529 if (ieee_hints) {
530 /* Map this long address with the ieee short address. */
531 ieee_hints->map_rec = ieee802154_addr_update(&zbee_nwk_map, ieee_hints->src16,
532 ieee_hints->src_pan, packet.src64, pinfo->current_proto, pinfo->num);
533 if (nwk_hints && !nwk_hints->map_rec) {
534 /* Map this long address with the nwk layer short address. */
535 nwk_hints->map_rec = ieee802154_addr_update(&zbee_nwk_map, nwk_hints->src,
536 ieee_hints->src_pan, packet.src64, pinfo->current_proto, pinfo->num);
539 break;
541 /* We ignore the extended source addresses used to encrypt payloads with these
542 * types of keys, because they can emerge from APS tunnels created by nodes whose
543 * short address is not recorded in the packet. */
544 case ZBEE_SEC_KEY_TRANSPORT:
545 case ZBEE_SEC_KEY_LOAD:
546 break;
549 #endif
550 offset += 8;
552 else {
553 /* Look for a source address in hints */
554 switch ( packet.key_id ) {
555 case ZBEE_SEC_KEY_NWK:
556 /* use the ieee extended source address for NWK decryption */
557 if ( ieee_hints && (map_rec = ieee_hints->map_rec) )
558 packet.src64 = map_rec->addr64;
559 else
560 proto_tree_add_expert(sec_tree, pinfo, &ei_zbee_sec_extended_source_unknown, tvb, 0, 0);
561 break;
563 default:
564 /* use the nwk extended source address for APS decryption */
565 if ( nwk_hints && (map_rec = nwk_hints->map_rec) )
567 switch (nwk_hints->relay_type)
569 case ZBEE_APS_RELAY_DOWNSTREAM:
571 ieee802154_short_addr addr16;
572 /* In case of downstream Relay must use long address
573 * of ZC. Seek for it in the address translation
574 * table. */
575 addr16.addr = 0;
576 addr16.pan = ieee_hints->src_pan;
577 map_rec = (ieee802154_map_rec *) g_hash_table_lookup(zbee_nwk_map.short_table, &addr16);
578 if (map_rec)
580 packet.src64 = map_rec->addr64;
583 break;
584 case ZBEE_APS_RELAY_UPSTREAM:
585 /* In case of downstream Relay must use long address of Joiner from the Relay message */
586 packet.src64 = nwk_hints->joiner_addr64;
587 break;
588 default:
589 packet.src64 = map_rec->addr64;
590 break;
593 else
594 proto_tree_add_expert(sec_tree, pinfo, &ei_zbee_sec_extended_source_unknown, tvb, 0, 0);
595 break;
599 if (packet.key_id == ZBEE_SEC_KEY_NWK) {
600 /* Get and display the key sequence number. */
601 packet.key_seqno = tvb_get_uint8(tvb, offset);
602 proto_tree_add_uint(sec_tree, hf_zbee_sec_key_seqno, tvb, offset, 1, packet.key_seqno);
603 offset += 1;
606 /* Determine the length of the MIC. */
607 switch (packet.level) {
608 case ZBEE_SEC_ENC:
609 case ZBEE_SEC_NONE:
610 default:
611 mic_len=0;
612 break;
614 case ZBEE_SEC_ENC_MIC32:
615 case ZBEE_SEC_MIC32:
616 mic_len=4;
617 break;
619 case ZBEE_SEC_ENC_MIC64:
620 case ZBEE_SEC_MIC64:
621 mic_len=8;
622 break;
624 case ZBEE_SEC_ENC_MIC128:
625 case ZBEE_SEC_MIC128:
626 mic_len=16;
627 break;
628 } /* switch */
630 /* Empty payload has to be security checked as well,
631 * since it contains MIC authentication tag */
632 payload_len = tvb_reported_length_remaining(tvb, offset+mic_len);
634 /**********************************************
635 * Perform Security Operations on the Frame *
636 **********************************************
638 if ((packet.level == ZBEE_SEC_NONE) ||
639 (packet.level == ZBEE_SEC_MIC32) ||
640 (packet.level == ZBEE_SEC_MIC64) ||
641 (packet.level == ZBEE_SEC_MIC128)) {
643 /* Payload is only integrity protected. Just return the sub-tvbuff. */
644 return tvb_new_subset_length(tvb, offset, payload_len);
647 /* Have we captured all the payload? */
648 if (tvb_captured_length_remaining(tvb, offset+mic_len) < payload_len
649 || !tvb_bytes_exist(tvb, offset+payload_len, mic_len) /* there are at least enough bytes for MIC */ ) {
651 * No - don't try to decrypt it.
653 * XXX - it looks as if the decryption code is assuming we have the
654 * MIC, which won't be the case if the packet was cut short. Is
655 * that in fact that case, or can we still make this work with a
656 * partially-captured packet?
658 /* Add expert info. */
659 expert_add_info(pinfo, sec_tree, &ei_zbee_sec_encrypted_payload_sliced);
660 /* Create a buffer for the undecrypted payload. */
661 payload_tvb = tvb_new_subset_length(tvb, offset, payload_len);
662 /* Dump the payload to the data dissector. */
663 call_data_dissector(payload_tvb, pinfo, tree);
664 /* Couldn't decrypt, so return NULL. */
665 return NULL;
668 /* Get and display the MIC. */
669 if (mic_len) {
670 /* Display the MIC. */
671 proto_tree_add_item(sec_tree, hf_zbee_sec_mic, tvb, (int)(tvb_reported_length(tvb)-mic_len),
672 mic_len, ENC_NA);
675 /* Allocate memory to decrypt the payload into.
676 * If there is no payload, dec_buffer will be NULL */
677 dec_buffer = (uint8_t *)wmem_alloc(pinfo->pool, payload_len);
679 decrypted = false;
680 if ( packet.src64 ) {
681 if (pinfo->fd->visited) {
682 if ( nwk_hints ) {
683 /* Use previously found key */
684 switch ( packet.key_id ) {
685 case ZBEE_SEC_KEY_NWK:
686 if ( (key_rec = nwk_hints->nwk) ) {
687 decrypted = zbee_sec_decrypt_payload( &packet, enc_buffer, offset, dec_buffer,
688 payload_len, mic_len, nwk_hints->nwk->key);
690 break;
692 default:
693 if ( (key_rec = nwk_hints->link) ) {
694 decrypted = zbee_sec_decrypt_payload( &packet, enc_buffer, offset, dec_buffer,
695 payload_len, mic_len, nwk_hints->link->key);
697 break;
700 } /* ( !pinfo->fd->visited ) */
701 else {
702 /* We only search for sniffed keys in the first pass,
703 * to save time, and because decrypting with keys
704 * transported in future packets is cheating */
706 /* Lookup NWK and link key in hash for this pan. */
707 /* This overkill approach is a placeholder for a hash that looks up
708 * a key ring for a link key associated with a pair of devices.
710 if ( nwk_hints ) {
711 nwk_keyring = (GSList **)g_hash_table_lookup(zbee_table_nwk_keyring, &nwk_hints->src_pan);
713 if ( nwk_keyring ) {
714 GSList_i = *nwk_keyring;
715 while ( GSList_i && !decrypted ) {
716 decrypted = zbee_sec_decrypt_payload( &packet, enc_buffer, offset, dec_buffer,
717 payload_len, mic_len, ((key_record_t *)(GSList_i->data))->key);
719 if (decrypted) {
720 /* save pointer to the successful key record */
721 switch (packet.key_id) {
722 case ZBEE_SEC_KEY_NWK:
723 key_rec = nwk_hints->nwk = (key_record_t *)(GSList_i->data);
724 break;
726 default:
727 key_rec = nwk_hints->link = (key_record_t *)(GSList_i->data);
728 break;
730 } else {
731 GSList_i = g_slist_next(GSList_i);
736 /* Loop through user's password table for preconfigured keys, our last resort */
737 GSList_i = zbee_pc_keyring;
738 while ( GSList_i && !decrypted ) {
739 decrypted = zbee_sec_decrypt_payload( &packet, enc_buffer, offset, dec_buffer,
740 payload_len, mic_len, ((key_record_t *)(GSList_i->data))->key);
742 if (decrypted) {
743 /* save pointer to the successful key record */
744 switch (packet.key_id) {
745 case ZBEE_SEC_KEY_NWK:
746 key_rec = nwk_hints->nwk = (key_record_t *)(GSList_i->data);
747 break;
749 default:
750 key_rec = nwk_hints->link = (key_record_t *)(GSList_i->data);
751 break;
753 } else {
754 GSList_i = g_slist_next(GSList_i);
758 } /* ( ! pinfo->fd->visited ) */
759 } /* ( packet.src64 ) */
761 if ( decrypted ) {
762 if ( tree && key_rec ) {
763 /* Key is not present in decrypted payload, so its length may not match bytes length */
764 key_item = proto_tree_add_bytes_with_length(sec_tree, hf_zbee_sec_key, tvb, 0, 0, key_rec->key, ZBEE_SEC_CONST_KEYSIZE);
765 proto_item_set_generated(key_item);
767 if ( key_rec->frame_num == ZBEE_SEC_PC_KEY ) {
768 ti = proto_tree_add_string(sec_tree, hf_zbee_sec_decryption_key, tvb, 0, 0, key_rec->label);
769 } else {
770 ti = proto_tree_add_uint(sec_tree, hf_zbee_sec_key_origin, tvb, 0, 0,
771 key_rec->frame_num);
773 proto_item_set_generated(ti);
776 /* Found a key that worked, setup the new tvbuff_t and return */
777 if(dec_buffer != NULL) {
778 payload_tvb = tvb_new_child_real_data(tvb, dec_buffer, payload_len, payload_len);
779 add_new_data_source(pinfo, payload_tvb, "Decrypted ZigBee Payload");
781 else {
782 /* Only MIC authentication tag was checked */
783 payload_tvb = NULL;
786 /* Done! */
787 return payload_tvb;
790 /* Add expert info. */
791 expert_add_info(pinfo, sec_tree, &ei_zbee_sec_encrypted_payload);
792 /* Create a buffer for the undecrypted payload. */
793 payload_tvb = tvb_new_subset_length(tvb, offset, payload_len);
794 /* Dump the payload to the data dissector. */
795 call_data_dissector(payload_tvb, pinfo, tree);
796 /* Couldn't decrypt, so return NULL. */
797 return NULL;
798 } /* dissect_zbee_secure */
800 /*FUNCTION:------------------------------------------------------
801 * NAME
802 * zbee_sec_decrypt_payload
803 * DESCRIPTION
804 * Creates a nonce and decrypts a secured payload.
805 * PARAMETERS
806 * char *nonce - Nonce Buffer.
807 * zbee_security_packet *packet - Security information.
808 * RETURNS
809 * void
810 *---------------------------------------------------------------
812 static bool
813 zbee_sec_decrypt_payload(zbee_security_packet *packet, const char *enc_buffer, const char offset, uint8_t *dec_buffer,
814 unsigned payload_len, unsigned mic_len, uint8_t *key)
816 uint8_t nonce[ZBEE_SEC_CONST_NONCE_LEN];
817 uint8_t buffer[ZBEE_SEC_CONST_BLOCKSIZE+1];
818 uint8_t *key_buffer = buffer;
820 switch (packet->key_id) {
821 case ZBEE_SEC_KEY_NWK:
822 /* Decrypt with the PAN's current network key */
823 case ZBEE_SEC_KEY_LINK:
824 /* Decrypt with the unhashed link key assigned by the trust center to this
825 * source/destination pair */
826 key_buffer = key;
827 break;
829 case ZBEE_SEC_KEY_TRANSPORT:
830 /* Decrypt with a Key-Transport key, a hashed link key that protects network
831 * keys sent from the trust center */
832 zbee_sec_key_hash(key, 0x00, buffer);
833 key_buffer = buffer;
834 break;
836 case ZBEE_SEC_KEY_LOAD:
837 /* Decrypt with a Key-Load key, a hashed link key that protects link keys
838 * sent from the trust center. */
839 zbee_sec_key_hash(key, 0x02, buffer);
840 key_buffer = buffer;
841 break;
843 default:
844 break;
845 } /* switch */
847 /* Perform Decryption. */
848 zbee_sec_make_nonce(packet, nonce);
850 if ( zbee_sec_ccm_decrypt(key_buffer, /* key */
851 nonce, /* Nonce */
852 enc_buffer, /* a, length l(a) */
853 enc_buffer+offset, /* c, length l(c) = l(m) + M */
854 dec_buffer, /* m, length l(m) */
855 offset, /* l(a) */
856 payload_len, /* l(m) */
857 mic_len) ) { /* M */
858 return true;
860 else return false;
863 /*FUNCTION:------------------------------------------------------
864 * NAME
865 * zbee_sec_make_nonce
866 * DESCRIPTION
867 * Fills in the ZigBee security nonce from the provided security
868 * packet structure.
869 * PARAMETERS
870 * zbee_security_packet *packet - Security information.
871 * char *nonce - Nonce Buffer.
872 * RETURNS
873 * void
874 *---------------------------------------------------------------
876 static void
877 zbee_sec_make_nonce(zbee_security_packet *packet, uint8_t *nonce)
879 /* First 8 bytes are the extended source address (little endian). */
880 phtole64(nonce, packet->src64);
881 nonce += 8;
882 /* Next 4 bytes are the frame counter (little endian). */
883 phtole32(nonce, packet->counter);
884 nonce += 4;
885 /* Next byte is the security control field. */
886 *(nonce) = packet->control;
887 } /* zbee_sec_make_nonce */
889 /*FUNCTION:------------------------------------------------------
890 * NAME
891 * zbee_sec_ccm_decrypt
892 * DESCRIPTION
893 * Performs the Reverse CCM* Transformation (specified in
894 * section A.3 of ZigBee Specification (053474r17).
896 * The length of parameter c (l(c)) is derived from the length
897 * of the payload and length of the MIC tag. Input buffer a
898 * will NOT be modified.
900 * When l_m is 0, then there is no payload to encrypt (ie: the
901 * payload is in plaintext), and this function will perform
902 * MIC verification only. When l_m is 0, m may be NULL.
903 * PARAMETERS
904 * char *key - ZigBee Security Key (must be ZBEE_SEC_CONST_KEYSIZE) in length.
905 * char *nonce - ZigBee CCM* Nonce (must be ZBEE_SEC_CONST_NONCE_LEN) in length.
906 * char *a - CCM* Parameter a (must be l(a) in length). Additional data covered
907 * by the authentication process.
908 * char *c - CCM* Parameter c (must be l(c) = l(m) + M in length). Encrypted
909 * payload + encrypted authentication tag U.
910 * char *m - CCM* Output (must be l(m) in length). Decrypted Payload.
911 * unsigned l_a - l(a), length of CCM* parameter a.
912 * unsigned l_m - l(m), length of expected payload.
913 * unsigned M - M, length of CCM* authentication tag.
914 * RETURNS
915 * bool - true if successful.
916 *---------------------------------------------------------------
918 bool
919 zbee_sec_ccm_decrypt(const char *key, /* Input */
920 const char *nonce, /* Input */
921 const char *a, /* Input */
922 const char *c, /* Input */
923 char *m, /* Output */
924 unsigned l_a, /* sizeof(a) */
925 unsigned l_m, /* sizeof(m) */
926 unsigned M) /* sizeof(c) - sizeof(m) = sizeof(MIC) */
928 uint8_t cipher_in[ZBEE_SEC_CONST_BLOCKSIZE];
929 uint8_t cipher_out[ZBEE_SEC_CONST_BLOCKSIZE];
930 uint8_t decrypted_mic[ZBEE_SEC_CONST_BLOCKSIZE];
931 unsigned i, j;
932 /* Cipher Instance. */
933 gcry_cipher_hd_t cipher_hd;
935 /* Sanity-Check. */
936 if (M > ZBEE_SEC_CONST_BLOCKSIZE) return false;
938 * The CCM* counter is L bytes in length, ensure that the payload
939 * isn't long enough to overflow it.
941 if ((1 + (l_a/ZBEE_SEC_CONST_BLOCKSIZE)) > (1<<(ZBEE_SEC_CONST_L*8))) return false;
943 /******************************************************
944 * Step 1: Encryption/Decryption Transformation
945 ******************************************************
947 /* Create the CCM* counter block A0 */
948 memset(cipher_in, 0, ZBEE_SEC_CONST_BLOCKSIZE);
949 cipher_in[0] = ZBEE_SEC_CCM_FLAG_L;
950 memcpy(cipher_in + 1, nonce, ZBEE_SEC_CONST_NONCE_LEN);
952 * The encryption/decryption process of CCM* works in CTR mode. Open a CTR
953 * mode cipher for this phase. NOTE: The 'counter' part of the CCM* counter
954 * block is the last two bytes, and is big-endian.
956 if (gcry_cipher_open(&cipher_hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CTR, 0)) {
957 return false;
959 /* Set the Key. */
960 if (gcry_cipher_setkey(cipher_hd, key, ZBEE_SEC_CONST_KEYSIZE)) {
961 gcry_cipher_close(cipher_hd);
962 return false;
964 /* Set the counter. */
965 if (gcry_cipher_setctr(cipher_hd, cipher_in, ZBEE_SEC_CONST_BLOCKSIZE)) {
966 gcry_cipher_close(cipher_hd);
967 return false;
970 * Copy the MIC into the stack buffer. We need to feed the cipher a full
971 * block when decrypting the MIC (so that the payload starts on the second
972 * block). However, the MIC may be less than a full block so use a fixed
973 * size buffer to store the MIC, letting the CTR cipher overstep the MIC
974 * if need be.
976 memset(decrypted_mic, 0, ZBEE_SEC_CONST_BLOCKSIZE);
977 memcpy(decrypted_mic, c + l_m, M);
978 /* Encrypt/Decrypt the MIC in-place. */
979 if (gcry_cipher_encrypt(cipher_hd, decrypted_mic, ZBEE_SEC_CONST_BLOCKSIZE, decrypted_mic, ZBEE_SEC_CONST_BLOCKSIZE)) {
980 gcry_cipher_close(cipher_hd);
981 return false;
983 /* Encrypt/Decrypt the payload. */
984 if (gcry_cipher_encrypt(cipher_hd, m, l_m, c, l_m)) {
985 gcry_cipher_close(cipher_hd);
986 return false;
988 /* Done with the CTR Cipher. */
989 gcry_cipher_close(cipher_hd);
991 /******************************************************
992 * Step 3: Authentication Transformation
993 ******************************************************
995 if (M == 0) {
996 /* There is no authentication tag. We're done! */
997 return true;
1000 * The authentication process in CCM* operates in CBC-MAC mode, but
1001 * unfortunately, the input to the CBC-MAC process needs some substantial
1002 * transformation and padding before we can feed it into the CBC-MAC
1003 * algorithm. Instead we will operate in ECB mode and perform the
1004 * transformation and padding on the fly.
1006 * I also think that libgcrypt requires the input to be memory-aligned
1007 * when using CBC-MAC mode, in which case can't just feed it with data
1008 * from the packet buffer. All things considered it's just a lot easier
1009 * to use ECB mode and do CBC-MAC manually.
1011 /* Re-open the cipher in ECB mode. */
1012 if (gcry_cipher_open(&cipher_hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, 0)) {
1013 return false;
1015 /* Re-load the key. */
1016 if (gcry_cipher_setkey(cipher_hd, key, ZBEE_SEC_CONST_KEYSIZE)) {
1017 gcry_cipher_close(cipher_hd);
1018 return false;
1020 /* Generate the first cipher block B0. */
1021 cipher_in[0] = ZBEE_SEC_CCM_FLAG_M(M) |
1022 ZBEE_SEC_CCM_FLAG_ADATA(l_a) |
1023 ZBEE_SEC_CCM_FLAG_L;
1024 memcpy(cipher_in+sizeof(char), nonce, ZBEE_SEC_CONST_NONCE_LEN);
1025 for (i=0;i<ZBEE_SEC_CONST_L; i++) {
1026 cipher_in[(ZBEE_SEC_CONST_BLOCKSIZE-1)-i] = (l_m >> (8*i)) & 0xff;
1027 } /* for */
1028 /* Generate the first cipher block, X1 = E(Key, 0^128 XOR B0). */
1029 if (gcry_cipher_encrypt(cipher_hd, cipher_out, ZBEE_SEC_CONST_BLOCKSIZE, cipher_in, ZBEE_SEC_CONST_BLOCKSIZE)) {
1030 gcry_cipher_close(cipher_hd);
1031 return false;
1034 * We avoid mallocing() big chunks of memory by recycling small stack
1035 * buffers for the encryption process. Throughout this process, j is always
1036 * pointed to the position within the current buffer.
1038 j = 0;
1039 /* AuthData = L(a) || a || Padding || m || Padding
1040 * Where L(a) =
1041 * - an empty string if l(a) == 0.
1042 * - 2-octet encoding of l(a) if 0 < l(a) < (2^16 - 2^8)
1043 * - 0xff || 0xfe || 4-octet encoding of l(a) if (2^16 - 2^8) <= l(a) < 2^32
1044 * - 0xff || 0xff || 8-octet encoding of l(a)
1045 * But for ZigBee, the largest packet size we should ever see is 2^7, so we
1046 * are only really concerned with the first two cases.
1048 * To generate the MIC tag CCM* operates similar to CBC-MAC mode. Each block
1049 * of AuthData is XOR'd with the last block of cipher output to produce the
1050 * next block of cipher output. Padding sections have the minimum non-negative
1051 * length such that the padding ends on a block boundary. Padded bytes are 0.
1053 if (l_a > 0) {
1054 /* Process L(a) into the cipher block. */
1055 cipher_in[j] = cipher_out[j] ^ ((l_a >> 8) & 0xff);
1056 j++;
1057 cipher_in[j] = cipher_out[j] ^ ((l_a >> 0) & 0xff);
1058 j++;
1059 /* Process a into the cipher block. */
1060 for (i=0;i<l_a;i++,j++) {
1061 if (j>=ZBEE_SEC_CONST_BLOCKSIZE) {
1062 /* Generate the next cipher block. */
1063 if (gcry_cipher_encrypt(cipher_hd, cipher_out, ZBEE_SEC_CONST_BLOCKSIZE, cipher_in,
1064 ZBEE_SEC_CONST_BLOCKSIZE)) {
1065 gcry_cipher_close(cipher_hd);
1066 return false;
1068 /* Reset j to point back to the start of the new cipher block. */
1069 j = 0;
1071 /* Cipher in = cipher_out ^ a */
1072 cipher_in[j] = cipher_out[j] ^ a[i];
1073 } /* for */
1074 /* Process padding into the cipher block. */
1075 for (;j<ZBEE_SEC_CONST_BLOCKSIZE;j++)
1076 cipher_in[j] = cipher_out[j];
1078 /* Process m into the cipher block. */
1079 for (i=0; i<l_m; i++, j++) {
1080 if (j>=ZBEE_SEC_CONST_BLOCKSIZE) {
1081 /* Generate the next cipher block. */
1082 if (gcry_cipher_encrypt(cipher_hd, cipher_out, ZBEE_SEC_CONST_BLOCKSIZE, cipher_in,
1083 ZBEE_SEC_CONST_BLOCKSIZE)) {
1084 gcry_cipher_close(cipher_hd);
1085 return false;
1087 /* Reset j to point back to the start of the new cipher block. */
1088 j = 0;
1090 /* Cipher in = cipher out ^ m */
1091 cipher_in[j] = cipher_out[j] ^ m[i];
1092 } /* for */
1093 /* Padding. */
1094 for (;j<ZBEE_SEC_CONST_BLOCKSIZE;j++)
1095 cipher_in[j] = cipher_out[j];
1096 /* Generate the last cipher block, which will be the MIC tag. */
1097 if (gcry_cipher_encrypt(cipher_hd, cipher_out, ZBEE_SEC_CONST_BLOCKSIZE, cipher_in, ZBEE_SEC_CONST_BLOCKSIZE)) {
1098 gcry_cipher_close(cipher_hd);
1099 return false;
1101 /* Done with the Cipher. */
1102 gcry_cipher_close(cipher_hd);
1104 /* Compare the MIC's */
1105 return (memcmp(cipher_out, decrypted_mic, M) == 0);
1106 } /* zbee_ccm_decrypt */
1108 /*FUNCTION:------------------------------------------------------
1109 * NAME
1110 * zbee_sec_hash
1111 * DESCRIPTION
1112 * ZigBee Cryptographic Hash Function, described in ZigBee
1113 * specification sections B.1.3 and B.6.
1115 * This is a Matyas-Meyer-Oseas hash function using the AES-128
1116 * cipher. We use the ECB mode of libgcrypt to get a raw block
1117 * cipher.
1119 * Input may be any length, and the output must be exactly 1-block in length.
1121 * Implements the function:
1122 * Hash(text) = Hash[t];
1123 * Hash[0] = 0^(blocksize).
1124 * Hash[i] = E(Hash[i-1], M[i]) XOR M[j];
1125 * M[i] = i'th block of text, with some padding and flags concatenated.
1126 * PARAMETERS
1127 * uint8_t * input - Hash Input (any length).
1128 * uint8_t input_len - Hash Input Length.
1129 * uint8_t * output - Hash Output (exactly one block in length).
1130 * RETURNS
1131 * void
1132 *---------------------------------------------------------------
1134 static void
1135 zbee_sec_hash(uint8_t *input, unsigned input_len, uint8_t *output)
1137 uint8_t cipher_in[ZBEE_SEC_CONST_BLOCKSIZE];
1138 unsigned i, j;
1139 /* Cipher Instance. */
1140 gcry_cipher_hd_t cipher_hd;
1142 /* Clear the first hash block (Hash0). */
1143 memset(output, 0, ZBEE_SEC_CONST_BLOCKSIZE);
1144 /* Create the cipher instance in ECB mode. */
1145 if (gcry_cipher_open(&cipher_hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, 0)) {
1146 return; /* Failed. */
1148 /* Create the subsequent hash blocks using the formula: Hash[i] = E(Hash[i-1], M[i]) XOR M[i]
1150 * because we can't guarantee that M will be exactly a multiple of the
1151 * block size, we will need to copy it into local buffers and pad it.
1153 * Note that we check for the next cipher block at the end of the loop
1154 * rather than the start. This is so that if the input happens to end
1155 * on a block boundary, the next cipher block will be generated for the
1156 * start of the padding to be placed into.
1158 i = 0;
1159 j = 0;
1160 while (i<input_len) {
1161 /* Copy data into the cipher input. */
1162 cipher_in[j++] = input[i++];
1163 /* Check if this cipher block is done. */
1164 if (j >= ZBEE_SEC_CONST_BLOCKSIZE) {
1165 /* We have reached the end of this block. Process it with the
1166 * cipher, note that the Key input to the cipher is actually
1167 * the previous hash block, which we are keeping in output.
1169 (void)gcry_cipher_setkey(cipher_hd, output, ZBEE_SEC_CONST_BLOCKSIZE);
1170 (void)gcry_cipher_encrypt(cipher_hd, output, ZBEE_SEC_CONST_BLOCKSIZE, cipher_in, ZBEE_SEC_CONST_BLOCKSIZE);
1171 /* Now we have to XOR the input into the hash block. */
1172 for (j=0;j<ZBEE_SEC_CONST_BLOCKSIZE;j++) output[j] ^= cipher_in[j];
1173 /* Reset j to start again at the beginning at the next block. */
1174 j = 0;
1176 } /* for */
1177 /* Need to append the bit '1', followed by '0' padding long enough to end
1178 * the hash input on a block boundary. However, because 'n' is 16, and 'l'
1179 * will be a multiple of 8, the padding will be >= 7-bits, and we can just
1180 * append the byte 0x80.
1182 cipher_in[j++] = 0x80;
1183 /* Pad with '0' until the current block is exactly 'n' bits from the
1184 * end.
1186 while (j!=(ZBEE_SEC_CONST_BLOCKSIZE-2)) {
1187 if (j >= ZBEE_SEC_CONST_BLOCKSIZE) {
1188 /* We have reached the end of this block. Process it with the
1189 * cipher, note that the Key input to the cipher is actually
1190 * the previous hash block, which we are keeping in output.
1192 (void)gcry_cipher_setkey(cipher_hd, output, ZBEE_SEC_CONST_BLOCKSIZE);
1193 (void)gcry_cipher_encrypt(cipher_hd, output, ZBEE_SEC_CONST_BLOCKSIZE, cipher_in, ZBEE_SEC_CONST_BLOCKSIZE);
1194 /* Now we have to XOR the input into the hash block. */
1195 for (j=0;j<ZBEE_SEC_CONST_BLOCKSIZE;j++) output[j] ^= cipher_in[j];
1196 /* Reset j to start again at the beginning at the next block. */
1197 j = 0;
1199 /* Pad the input with 0. */
1200 cipher_in[j++] = 0x00;
1201 } /* while */
1202 /* Add the 'n'-bit representation of 'l' to the end of the block. */
1203 cipher_in[j++] = ((input_len * 8) >> 8) & 0xff;
1204 cipher_in[j] = ((input_len * 8) >> 0) & 0xff;
1205 /* Process the last cipher block. */
1206 (void)gcry_cipher_setkey(cipher_hd, output, ZBEE_SEC_CONST_BLOCKSIZE);
1207 (void)gcry_cipher_encrypt(cipher_hd, output, ZBEE_SEC_CONST_BLOCKSIZE, cipher_in, ZBEE_SEC_CONST_BLOCKSIZE);
1208 /* XOR the last input block back into the cipher output to get the hash. */
1209 for (j=0;j<ZBEE_SEC_CONST_BLOCKSIZE;j++) output[j] ^= cipher_in[j];
1210 /* Cleanup the cipher. */
1211 gcry_cipher_close(cipher_hd);
1212 /* Done */
1213 } /* zbee_sec_hash */
1215 /*FUNCTION:------------------------------------------------------
1216 * NAME
1217 * zbee_sec_key_hash
1218 * DESCRIPTION
1219 * ZigBee Keyed Hash Function. Described in ZigBee specification
1220 * section B.1.4, and in FIPS Publication 198. Strictly speaking
1221 * there is nothing about the Keyed Hash Function which restricts
1222 * it to only a single byte input, but that's all ZigBee ever uses.
1224 * This function implements the hash function:
1225 * Hash(Key, text) = H((Key XOR opad) || H((Key XOR ipad) || text));
1226 * ipad = 0x36 repeated.
1227 * opad = 0x5c repeated.
1228 * H() = ZigBee Cryptographic Hash (B.1.3 and B.6).
1229 * PARAMETERS
1230 * uint8_t *key - ZigBee Security Key (must be ZBEE_SEC_CONST_KEYSIZE) in length.
1231 * uint8_t input - ZigBee CCM* Nonce (must be ZBEE_SEC_CONST_NONCE_LEN) in length.
1232 * uint8_t *hash_out - buffer into which the key-hashed output is placed
1233 * RETURNS
1234 * void
1235 *---------------------------------------------------------------
1237 static void
1238 zbee_sec_key_hash(uint8_t *key, uint8_t input, uint8_t *hash_out)
1240 uint8_t hash_in[2*ZBEE_SEC_CONST_BLOCKSIZE];
1241 int i;
1242 static const uint8_t ipad = 0x36;
1243 static const uint8_t opad = 0x5c;
1245 /* Copy the key into hash_in and XOR with opad to form: (Key XOR opad) */
1246 for (i=0; i<ZBEE_SEC_CONST_KEYSIZE; i++) hash_in[i] = key[i] ^ opad;
1247 /* Copy the Key into hash_out and XOR with ipad to form: (Key XOR ipad) */
1248 for (i=0; i<ZBEE_SEC_CONST_KEYSIZE; i++) hash_out[i] = key[i] ^ ipad;
1249 /* Append the input byte to form: (Key XOR ipad) || text. */
1250 hash_out[ZBEE_SEC_CONST_BLOCKSIZE] = input;
1251 /* Hash the contents of hash_out and append the contents to hash_in to
1252 * form: (Key XOR opad) || H((Key XOR ipad) || text).
1254 zbee_sec_hash(hash_out, ZBEE_SEC_CONST_BLOCKSIZE+1, hash_in+ZBEE_SEC_CONST_BLOCKSIZE);
1255 /* Hash the contents of hash_in to get the final result. */
1256 zbee_sec_hash(hash_in, 2*ZBEE_SEC_CONST_BLOCKSIZE, hash_out);
1257 } /* zbee_sec_key_hash */
1260 *Add NWK or APS key into NWK keyring
1262 *@param pinfo pointer to packet information fields
1263 *@param key APS or NWK key
1265 void zbee_sec_add_key_to_keyring(packet_info *pinfo, const uint8_t *key)
1267 GSList **nwk_keyring;
1268 key_record_t key_record;
1269 zbee_nwk_hints_t *nwk_hints;
1271 /* Update the key ring for this pan */
1272 if ( !pinfo->fd->visited && (nwk_hints = (zbee_nwk_hints_t *)p_get_proto_data(wmem_file_scope(), pinfo,
1273 proto_get_id_by_filter_name(ZBEE_PROTOABBREV_NWK), 0))) {
1274 nwk_keyring = (GSList **)g_hash_table_lookup(zbee_table_nwk_keyring, &nwk_hints->src_pan);
1275 if ( !nwk_keyring ) {
1276 nwk_keyring = (GSList **)g_malloc0(sizeof(GSList*));
1277 g_hash_table_insert(zbee_table_nwk_keyring,
1278 g_memdup2(&nwk_hints->src_pan, sizeof(nwk_hints->src_pan)), nwk_keyring);
1281 if ( nwk_keyring ) {
1282 if ( !*nwk_keyring ||
1283 memcmp( ((key_record_t *)((GSList *)(*nwk_keyring))->data)->key, key,
1284 ZBEE_APS_CMD_KEY_LENGTH) ) {
1285 /* Store a new or different key in the key ring */
1286 key_record.frame_num = pinfo->num;
1287 key_record.label = NULL;
1288 memcpy(&key_record.key, key, ZBEE_APS_CMD_KEY_LENGTH);
1289 *nwk_keyring = g_slist_prepend(*nwk_keyring, g_memdup2(&key_record, sizeof(key_record_t)));
1293 } /* nwk_add_key_to_keyring */
1296 * Editor modelines - https://www.wireshark.org/tools/modelines.html
1298 * Local variables:
1299 * c-basic-offset: 4
1300 * tab-width: 8
1301 * indent-tabs-mode: nil
1302 * End:
1304 * vi: set shiftwidth=4 tabstop=8 expandtab:
1305 * :indentSize=4:tabSize=8:noTabs=true: