1 /* packet-zbee-security.c
2 * Dissector helper routines for encrypted ZigBee frames.
3 * By Owen Kirby <osk@exegin.com>
4 * Copyright 2009 Exegin Technologies Limited
8 * Wireshark - Network traffic analyzer
9 * By Gerald Combs <gerald@wireshark.org>
10 * Copyright 1998 Gerald Combs
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
30 #endif /* HAVEHCONFIG_H */
36 #include <epan/proto.h>
37 #include <epan/packet.h>
38 #include <epan/prefs.h>
39 #include <epan/expert.h>
41 /* We require libgcrpyt in order to decrypt ZigBee packets. Without it the best
42 * we can do is parse the security header and give up.
46 #endif /* HAVE_LIBGCRYPT */
48 #include "packet-zbee.h"
49 #include "packet-zbee-security.h"
51 /* Helper Functions */
53 static gboolean zbee_sec_ccm_decrypt(const gchar *, const gchar *, const gchar *, const gchar *, gchar *, guint, guint, guint);
54 static guint8 * zbee_sec_key_hash(guint8 *, guint8, packet_info *);
55 static void zbee_sec_make_nonce (guint8 *, zbee_security_packet *);
57 static void zbee_security_parse_prefs(void);
60 static int hf_zbee_sec_level = -1;
61 static int hf_zbee_sec_key = -1;
62 static int hf_zbee_sec_nonce = -1;
63 static int hf_zbee_sec_counter = -1;
64 static int hf_zbee_sec_src = -1;
65 static int hf_zbee_sec_key_seqno = -1;
66 static int hf_zbee_sec_mic = -1;
68 /* Subtree pointers. */
69 static gint ett_zbee_sec = -1;
70 static gint ett_zbee_sec_control = -1;
72 static dissector_handle_t data_handle;
74 static const value_string zbee_sec_key_names[] = {
75 { ZBEE_SEC_KEY_LINK, "Link Key" },
76 { ZBEE_SEC_KEY_NWK, "Network Key" },
77 { ZBEE_SEC_KEY_TRANSPORT, "Key-Transport Key" },
78 { ZBEE_SEC_KEY_LOAD, "Key-Load Key" },
82 /* These aren't really used anymore, as ZigBee no longer includes them in the
83 * security control field. If we were to display them all we would ever see is
86 static const value_string zbee_sec_level_names[] = {
87 { ZBEE_SEC_NONE, "None" },
88 { ZBEE_SEC_MIC32, "No Encryption, 32-bit MIC" },
89 { ZBEE_SEC_MIC64, "No Encryption, 64-bit MIC" },
90 { ZBEE_SEC_MIC128, "No Encryption, 128-bit MIC" },
91 { ZBEE_SEC_ENC, "Encryption, No MIC" },
92 { ZBEE_SEC_ENC_MIC32, "Encryption, 32-bit MIC" },
93 { ZBEE_SEC_ENC_MIC64, "Encryption, 64-bit MIC" },
94 { ZBEE_SEC_ENC_MIC128, "Encryption, 128-bit MIC" },
98 /* The ZigBee security level, in enum_val_t for the security preferences. */
99 static enum_val_t zbee_sec_level_enums[] = {
100 { "None", "No Security", ZBEE_SEC_NONE },
101 { "MIC32", "No Encryption, 32-bit Integrity Protection", ZBEE_SEC_MIC32 },
102 { "MIC64", "No Encryption, 64-bit Integrity Protection", ZBEE_SEC_MIC64 },
103 { "MIC128", "No Encryption, 128-bit Integrity Protection", ZBEE_SEC_MIC128 },
104 { "ENC", "AES-128 Encryption, No Integrity Protection", ZBEE_SEC_ENC },
105 { "ENC-MIC32", "AES-128 Encryption, 32-bit Integrity Protection", ZBEE_SEC_ENC_MIC32 },
106 { "ENC-MIC64", "AES-128 Encryption, 64-bit Integrity Protection", ZBEE_SEC_ENC_MIC64 },
107 { "ENC-MIC128", "AES-128 Encryption, 128-bit Integrity Protection", ZBEE_SEC_ENC_MIC128 },
112 static gboolean zbee_sec_have_nwk_key = FALSE;
113 static guint8 zbee_sec_nwk_key[ZBEE_SEC_CONST_KEYSIZE];
115 /* Trust-Center Link Key. */
116 static gboolean zbee_sec_have_tclink_key = FALSE;
117 static guint8 zbee_sec_tclink_key[ZBEE_SEC_CONST_KEYSIZE];
119 /* Trust-Center Extended Address */
120 static guint64 zbee_sec_tcaddr = 0;
122 /* ZigBee Security Preferences. */
123 static gint gPREF_zbee_sec_level = ZBEE_SEC_ENC_MIC32;
124 static const gchar * gPREF_zbee_sec_nwk_key = NULL;
125 static const gchar * gPREF_zbee_sec_tcaddr = NULL;
126 static const gchar * gPREF_zbee_sec_tclink_key = NULL;
129 * Enable this macro to use libgcrypt's CBC_MAC mode for the authentication
130 * phase. Unfortunately, this is broken, and I don't know why. However, using
131 * the messier EBC mode (to emulate CCM*) still works fine.
134 #define ZBEE_SEC_USE_GCRYPT_CBC_MAC
136 /*FUNCTION:------------------------------------------------------
138 * zbee_security_register
140 * Called to initialize the security dissectors. Roughly the
141 * equivalent of proto_register_*
143 * module_t zbee_prefs - Prefs module to load preferences under.
146 *---------------------------------------------------------------
148 void zbee_security_register(module_t *zbee_prefs, int proto)
150 static hf_register_info hf[] = {
151 { &hf_zbee_sec_level,
152 { "Level", "zbee.sec.level", FT_UINT8, BASE_HEX, VALS(zbee_sec_level_names), ZBEE_SEC_CONTROL_LEVEL,
156 { "Key", "zbee.sec.key", FT_UINT8, BASE_HEX, VALS(zbee_sec_key_names), ZBEE_SEC_CONTROL_KEY,
159 { &hf_zbee_sec_nonce,
160 { "Extended Nonce", "zbee.sec.ext_nonce", FT_BOOLEAN, 8, NULL, ZBEE_SEC_CONTROL_NONCE,
163 { &hf_zbee_sec_counter,
164 { "Frame Counter", "zbee.sec.counter", FT_UINT32, BASE_DEC, NULL, 0x0,
168 { "Source", "zbee.sec.src", FT_UINT64, BASE_HEX, NULL, 0x0,
171 { &hf_zbee_sec_key_seqno,
172 { "Key Sequence Number", "zbee.sec.key_seqno", FT_UINT8, BASE_DEC, NULL, 0x0,
176 { "Message Integrity Code", "zbee.sec.mic", FT_BYTES, BASE_NONE, NULL, 0x0,
180 static gint *ett[] = {
182 &ett_zbee_sec_control
185 /* If no prefs module was supplied, register our own. */
186 if (zbee_prefs == NULL) {
187 zbee_prefs = prefs_register_protocol(proto, zbee_security_parse_prefs);
190 /* Register preferences */
191 prefs_register_enum_preference(zbee_prefs, "seclevel", "Security Level",
192 "Specifies the security level to use in the decryption process. This value is ignored for ZigBee 2004 and unsecured networks.",
193 &gPREF_zbee_sec_level, zbee_sec_level_enums, FALSE);
194 prefs_register_string_preference(zbee_prefs, "nwkkey", "Network Key",
195 "Specifies the network key to use for decryption.",
196 &gPREF_zbee_sec_nwk_key);
197 prefs_register_string_preference(zbee_prefs, "tcaddr", "Trust Center Address",
198 "The Extended address of the trust center.",
199 &gPREF_zbee_sec_tcaddr);
200 prefs_register_string_preference(zbee_prefs, "tclinkkey", "Trust Center Link Key",
201 "Specifies the trust center link key to use for decryption.",
202 &gPREF_zbee_sec_tclink_key);
204 proto_register_field_array(proto, hf, array_length(hf));
205 proto_register_subtree_array(ett, array_length(ett));
206 } /* zbee_security_register */
208 /*FUNCTION:------------------------------------------------------
210 * zbee_security_parse_key
212 * Parses a key string into a buffer.
214 * const gchar * key_str;
218 *---------------------------------------------------------------
221 zbee_security_parse_key(const gchar *key_str, guint8 *key_buf)
227 memset(key_buf, 0, ZBEE_SEC_CONST_KEYSIZE);
228 if (key_str == NULL) {
232 * Attempt to parse the key string. The key string must represent
233 * exactly 16 bytes in hexadecimal format with the following
234 * separators: ':', '-', " ", or no separator at all. Start by
235 * getting the first character.
238 for (i=ZBEE_SEC_CONST_KEYSIZE-1; i>=0; i--) {
239 /* If this character is a separator, skip it. */
240 if ((temp == ':') || (temp == '-') || (temp == ' ')) temp = *(key_str++);
241 /* Process this nibble. */
242 if (('0' <= temp) && (temp <= '9')) key_buf[i] |= ((temp-'0')<<4);
243 else if (('a' <= temp) && (temp <= 'f')) key_buf[i] |= ((temp-'a'+0x0a)<<4);
244 else if (('A' <= temp) && (temp <= 'F')) key_buf[i] |= ((temp-'A'+0x0A)<<4);
246 /* Get the next nibble. */
248 /* Process this nibble. */
249 if (('0' <= temp) && (temp <= '9')) key_buf[i] |= (temp-'0');
250 else if (('a' <= temp) && (temp <= 'f')) key_buf[i] |= (temp-'a'+0x0a);
251 else if (('A' <= temp) && (temp <= 'F')) key_buf[i] |= (temp-'A'+0x0A);
253 /* Get the next nibble. */
256 /* If we get this far, then the key was good. */
258 } /* zbee_security_parse_key */
260 /*FUNCTION:------------------------------------------------------
262 * zbee_security_parse_prefs
264 * Parses the security preferences into the parameters needed
270 *---------------------------------------------------------------
273 zbee_security_parse_prefs(void)
276 const gchar * str_ptr;
279 /* Get the network key. */
280 zbee_sec_have_nwk_key = zbee_security_parse_key(gPREF_zbee_sec_nwk_key, zbee_sec_nwk_key);
281 /* Get the trust-center link key. */
282 zbee_sec_have_tclink_key = zbee_security_parse_key(gPREF_zbee_sec_tclink_key, zbee_sec_tclink_key);
283 /* Get the trust-center address. */
285 str_ptr = gPREF_zbee_sec_tcaddr;
287 for (i=0;i<(int)sizeof(guint64);i++) {
288 /* Except for the first octet, ensure the next character is a
289 * separator and skip over it.
291 if ((temp == ':') || (temp == '-')) temp = *(str_ptr++);
292 else if (i!=0) goto bad_tcaddr;
293 /* Process this nibble. */
294 if (('0' <= temp) && (temp <= '9')) zbee_sec_tcaddr |= ((guint64)(temp-'0'+0x00)<<(8*(sizeof(guint64)-i)-4));
295 else if (('a' <= temp) && (temp <= 'f')) zbee_sec_tcaddr |= ((guint64)(temp-'a'+0x0a)<<(8*(sizeof(guint64)-i)-4));
296 else if (('A' <= temp) && (temp <= 'F')) zbee_sec_tcaddr |= ((guint64)(temp-'A'+0x0A)<<(8*(sizeof(guint64)-i)-4));
297 else goto bad_tcaddr;
298 /* Get the next nibble. */
300 /* Process this nibble. */
301 if (('0' <= temp) && (temp <= '9')) zbee_sec_tcaddr |= ((guint64)(temp-'0'+0x00)<<(8*(sizeof(guint64)-i)-8));
302 else if (('a' <= temp) && (temp <= 'f')) zbee_sec_tcaddr |= ((guint64)(temp-'a'+0x0a)<<(8*(sizeof(guint64)-i)-8));
303 else if (('A' <= temp) && (temp <= 'F')) zbee_sec_tcaddr |= ((guint64)(temp-'A'+0x0A)<<(8*(sizeof(guint64)-i)-8));
304 else goto bad_tcaddr;
305 /* Get the next nibble. */
313 } /* zbee_security_parse_prefs */
315 /*FUNCTION:------------------------------------------------------
317 * zbee_security_handoff
319 * Hands off the security dissector.
324 *---------------------------------------------------------------
327 zbee_security_handoff(void)
329 /* Lookup the data dissector. */
330 data_handle = find_dissector("data");
331 /* Parse the security prefs. */
332 zbee_security_parse_prefs();
333 } /* zbee_security_handoff */
335 /*FUNCTION:------------------------------------------------------
337 * dissect_zbee_secure
339 * Dissects and decrypts secured ZigBee frames.
341 * Will return a valid tvbuff only if security processing was
342 * successful. If processing fails, then this function will
343 * handle internally and return NULL.
345 * tvbuff_t *tvb - pointer to buffer containing raw packet.
346 * packet_into *pinfo - pointer to packet information fields
347 * proto_tree *tree - pointer to data tree Wireshark uses to display packet.
348 * guint offset - pointer to the start of the auxilliary security header.
349 * guint64 src - extended source address, or 0 if unknown.
352 *---------------------------------------------------------------
355 dissect_zbee_secure(tvbuff_t *tvb, packet_info *pinfo, proto_tree* tree, guint offset, guint64 src)
357 proto_tree * sec_tree = NULL;
358 proto_item * sec_root;
359 proto_tree * field_tree;
362 zbee_security_packet packet;
365 tvbuff_t * payload_tvb;
367 #ifdef HAVE_LIBGCRYPT
368 const guint8 * enc_buffer;
371 guint8 nonce[ZBEE_SEC_CONST_NONCE_LEN];
374 /* Create a substree for the security information. */
376 sec_root = proto_tree_add_text(tree, tvb, offset, tvb_length_remaining(tvb, offset), "ZigBee Security Header");
377 sec_tree = proto_item_add_subtree(sec_root, ett_zbee_sec);
380 /* Get and display the Security control field */
381 packet.control = tvb_get_guint8(tvb, offset);
382 /* Patch the security level. */
383 packet.control &= ~ZBEE_SEC_CONTROL_LEVEL;
384 packet.control |= (ZBEE_SEC_CONTROL_LEVEL & gPREF_zbee_sec_level);
386 * Eww, I think I just threw up a little... ZigBee requires this field
387 * to be patched before computing the MIC, but we don't have write-access
388 * to the tvbuff. So we need to allocate a copy of the whole thing just
389 * so we can fix these 3 bits.
391 #ifdef HAVE_LIBGCRYPT
392 enc_buffer = ep_tvb_memdup(tvb, 0, tvb_length(tvb));
394 * Override the const qualifiers and patch the security level field, we
395 * know it is safe to overide the const qualifiers because we just
396 * allocated this memory via ep_tvb_memdup().
398 ((guint8 *)(enc_buffer))[offset] = packet.control;
399 #endif /* HAVE_LIBGCRYPT */
400 packet.level = zbee_get_bit_field(packet.control, ZBEE_SEC_CONTROL_LEVEL);
401 packet.key = zbee_get_bit_field(packet.control, ZBEE_SEC_CONTROL_KEY);
402 packet.nonce = zbee_get_bit_field(packet.control, ZBEE_SEC_CONTROL_NONCE);
404 ti = proto_tree_add_text(sec_tree, tvb, offset, sizeof(guint8), "Security Control Field");
405 field_tree = proto_item_add_subtree(ti, ett_zbee_sec_control);
407 proto_tree_add_uint(field_tree, hf_zbee_sec_key, tvb, offset, sizeof(guint8), packet.control & ZBEE_SEC_CONTROL_KEY);
408 proto_tree_add_boolean(field_tree, hf_zbee_sec_nonce, tvb, offset, sizeof(guint8), packet.control & ZBEE_SEC_CONTROL_NONCE);
410 offset += sizeof(guint8);
412 /* Get and display the frame counter field. */
413 packet.counter = tvb_get_letohl(tvb, offset);
415 proto_tree_add_uint(sec_tree, hf_zbee_sec_counter, tvb, offset, sizeof(guint32), packet.counter);
417 offset += sizeof(guint32);
420 /* Get and display the source address. */
421 packet.src = tvb_get_letoh64(tvb, offset);
423 proto_tree_add_eui64(sec_tree, hf_zbee_sec_src, tvb, offset, sizeof(guint64), packet.src);
425 offset += sizeof(guint64);
428 /* This field is required in the security decryption process, so
429 * fill it in in case the higher layer provided it.
434 if (packet.key == ZBEE_SEC_KEY_NWK) {
435 /* Get and display the key sequence number. */
436 packet.key_seqno = tvb_get_guint8(tvb, offset);
438 proto_tree_add_uint(sec_tree, hf_zbee_sec_key_seqno, tvb, offset, sizeof(guint8), packet.key_seqno);
440 offset += sizeof(guint8);
443 /* Determine the length of the MIC. */
444 switch (packet.level){
451 case ZBEE_SEC_ENC_MIC32:
456 case ZBEE_SEC_ENC_MIC64:
461 case ZBEE_SEC_ENC_MIC128:
462 case ZBEE_SEC_MIC128:
467 /* Ensure that the payload exists (length >= 1) for this length. */
468 payload_len = tvb_ensure_length_remaining(tvb, offset+mic_len+1)+1;
470 /* Get and display the MIC. */
472 /* Display the MIC. */
474 ti = proto_tree_add_bytes(sec_tree, hf_zbee_sec_mic, tvb, tvb_length(tvb)-mic_len, mic_len, ep_tvb_memdup(tvb, tvb_length(tvb)-mic_len, mic_len));
478 /**********************************************
479 * Perform Security Operations on the Frame *
480 **********************************************
482 if ((packet.level == ZBEE_SEC_NONE) ||
483 (packet.level == ZBEE_SEC_MIC32) ||
484 (packet.level == ZBEE_SEC_MIC64) ||
485 (packet.level == ZBEE_SEC_MIC128)) {
486 /* Payload is only integrity protected. Just return the sub-tvbuff. */
487 return tvb_new_subset(tvb, offset, payload_len, payload_len);
490 #ifdef HAVE_LIBGCRYPT
491 /* Ensure we have enough security material to decrypt this payload. */
492 switch (packet.key) {
493 /* Network Keys use the shared network key. */
494 case ZBEE_SEC_KEY_NWK:
495 if (!zbee_sec_have_nwk_key) {
496 /* Without a key we can't decrypt (if we could what good would security be?)*/
499 if (packet.src == 0) {
500 /* Without the extended source address, we can't create the nonce. */
503 /* The key, is the network key. */
504 key_buffer = zbee_sec_nwk_key;
507 /* Link Key might use the trust center link key. */
508 case ZBEE_SEC_KEY_LINK:
509 if (!zbee_sec_have_tclink_key) {
510 /* Without a key we can't decrypt. */
513 if ((packet.src == 0) && (zbee_sec_tcaddr == 0)){
514 /* Without the extended source address, we can't create the nonce. */
517 else if (packet.src == 0) {
518 packet.src = zbee_sec_tcaddr;
520 key_buffer = zbee_sec_tclink_key;
523 /* Key-Transport Key should use the trust center link key. */
524 case ZBEE_SEC_KEY_TRANSPORT:
525 if (!zbee_sec_have_tclink_key) {
526 /* Without a key we can't decrypt. */
529 if ((packet.src == 0) && (zbee_sec_tcaddr == 0)){
530 /* Without the extended source address, we can't create the nonce. */
533 else if (packet.src == 0) {
534 packet.src = zbee_sec_tcaddr;
536 key_buffer = zbee_sec_key_hash(zbee_sec_tclink_key, 0x00, pinfo);
539 /* Key-Load Key should use the trust center link key. */
540 case ZBEE_SEC_KEY_LOAD:
541 if (!zbee_sec_have_tclink_key) {
542 /* Without a key we can't decrypt. */
545 if ((packet.src == 0) && (zbee_sec_tcaddr == 0)){
546 /* Without the extended source address, we can't create the nonce. */
549 else if (packet.src == 0) {
550 packet.src = zbee_sec_tcaddr;
552 key_buffer = zbee_sec_key_hash(zbee_sec_tclink_key, 0x02, pinfo);
559 /* Create the nonce. */
560 zbee_sec_make_nonce(nonce, &packet);
561 /* Allocate memory to decrypt the payload into. */
562 dec_buffer = g_malloc(payload_len);
563 /* Perform Decryption. */
564 if (!zbee_sec_ccm_decrypt(key_buffer, /* key */
566 enc_buffer, /* a, length l(a) */
567 enc_buffer+offset, /* c, length l(c) = l(m) + M */
568 dec_buffer, /* m, length l(m) */
570 payload_len, /* l(m) */
572 /* Decryption Failed! */
577 /* Setup the new tvbuff_t and return */
578 payload_tvb = tvb_new_child_real_data(tvb, dec_buffer, payload_len, payload_len);
579 tvb_set_free_cb(payload_tvb, g_free);
580 add_new_data_source(pinfo, payload_tvb, "Decrypted ZigBee Payload");
585 #endif /* HAVE_LIBGCRYPT */
587 /* Add expert info. */
588 expert_add_info_format(pinfo, sec_tree, PI_UNDECODED, PI_WARN, "Encrypted Payload");
589 /* Create a buffer for the undecrypted payload. */
590 payload_tvb = tvb_new_subset(tvb, offset, payload_len, -1);
591 /* Dump the payload to the data dissector. */
592 call_dissector(data_handle, payload_tvb, pinfo, tree);
593 /* Couldn't decrypt, so return NULL. */
596 } /* dissect_zbee_secure */
598 #ifdef HAVE_LIBGCRYPT
599 /*FUNCTION:------------------------------------------------------
601 * zbee_sec_make_nonce
603 * Fills in the ZigBee security nonce from the provided security
606 * gchar *nonce - Nonce Buffer.
607 * zbee_security_packet *packet - Security information.
610 *---------------------------------------------------------------
613 zbee_sec_make_nonce(guint8 *nonce, zbee_security_packet *packet)
615 /* First 8 bytes are the extended source address (little endian). */
616 *(nonce++) = (guint8)((packet->src)>>0 & 0xff);
617 *(nonce++) = (guint8)((packet->src)>>8 & 0xff);
618 *(nonce++) = (guint8)((packet->src)>>16 & 0xff);
619 *(nonce++) = (guint8)((packet->src)>>24 & 0xff);
620 *(nonce++) = (guint8)((packet->src)>>32 & 0xff);
621 *(nonce++) = (guint8)((packet->src)>>40 & 0xff);
622 *(nonce++) = (guint8)((packet->src)>>48 & 0xff);
623 *(nonce++) = (guint8)((packet->src)>>56 & 0xff);
624 /* Next 4 bytes are the frame counter (little endian). */
625 *(nonce++) = (guint8)((packet->counter)>>0 & 0xff);
626 *(nonce++) = (guint8)((packet->counter)>>8 & 0xff);
627 *(nonce++) = (guint8)((packet->counter)>>16 & 0xff);
628 *(nonce++) = (guint8)((packet->counter)>>24 & 0xff);
629 /* Next byte is the security control field. */
630 *(nonce++) = packet->control;
631 } /* zbee_sec_make_nonce */
634 #ifdef HAVE_LIBGCRYPT
635 /*FUNCTION:------------------------------------------------------
637 * zbee_sec_ccm_decrypt
639 * Performs the Reverse CCM* Transformation (specified in
640 * section A.3 of ZigBee Specification (053474r17).
642 * The length of parameter c (l(c)) is derived from the length
643 * of the payload and length of the MIC tag. Input buffer a
644 * will NOT be modified.
646 * When l_m is 0, then there is no payload to encrypt (ie: the
647 * payload is in plaintext), and this function will perform
648 * MIC verification only. When l_m is 0, m may be NULL.
650 * gchar *key - ZigBee Security Key (must be ZBEE_SEC_CONST_KEYSIZE) in length.
651 * gchar *nonce - ZigBee CCM* Nonce (must be ZBEE_SEC_CONST_NONCE_LEN) in length.
652 * gchar *a - CCM* Parameter a (must be l(a) in length). Additional data covered
653 * by the authentication process.
654 * gchar *c - CCM* Parameter c (must be l(c) = l(m) + M in length). Encrypted
655 * payload + encrypted authentication tag U.
656 * gchar *m - CCM* Output (must be l(m) in length). Decrypted Payload.
657 * guint l_a - l(a), length of CCM* parameter a.
658 * guint l_m - l(m), length of expected payload.
659 * guint M - M, length of CCM* authentication tag.
661 * gboolean - TRUE if successful.
662 *---------------------------------------------------------------
665 zbee_sec_ccm_decrypt(const gchar *key, /* Input */
666 const gchar *nonce, /* Input */
667 const gchar *a, /* Input */
668 const gchar *c, /* Input */
669 gchar *m, /* Output */
670 guint l_a, /* sizeof(a) */
671 guint l_m, /* sizeof(m) */
672 guint M) /* sizeof(c) - sizeof(m) = sizeof(MIC) */
674 guint8 cipher_in[ZBEE_SEC_CONST_BLOCKSIZE];
675 guint8 cipher_out[ZBEE_SEC_CONST_BLOCKSIZE];
676 guint8 decrypted_mic[ZBEE_SEC_CONST_BLOCKSIZE];
678 /* Cipher Instance. */
679 gcry_cipher_hd_t cipher_hd;
682 if (M > ZBEE_SEC_CONST_BLOCKSIZE) return FALSE;
684 * The CCM* counter is L bytes in length, ensure that the payload
685 * isn't long enough to overflow it.
687 if ((1 + (l_a/ZBEE_SEC_CONST_BLOCKSIZE)) > (1<<(ZBEE_SEC_CONST_L*8))) return FALSE;
689 /******************************************************
690 * Step 1: Encryption/Decryption Transformation
691 ******************************************************
693 /* Create the CCM* counter block A0 */
694 memset(cipher_in, 0, ZBEE_SEC_CONST_BLOCKSIZE);
695 cipher_in[0] = ZBEE_SEC_CCM_FLAG_L;
696 memcpy(cipher_in + 1, nonce, ZBEE_SEC_CONST_NONCE_LEN);
698 * The encryption/decryption process of CCM* works in CTR mode. Open a CTR
699 * mode cipher for this phase. NOTE: The 'counter' part of the CCM* counter
700 * block is the last two bytes, and is big-endian.
702 if (gcry_cipher_open(&cipher_hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CTR, 0)) {
706 if (gcry_cipher_setkey(cipher_hd, key, ZBEE_SEC_CONST_KEYSIZE)) {
707 gcry_cipher_close(cipher_hd);
710 /* Set the counter. */
711 if (gcry_cipher_setctr(cipher_hd, cipher_in, ZBEE_SEC_CONST_BLOCKSIZE)) {
712 gcry_cipher_close(cipher_hd);
716 * Copy the MIC into the stack buffer. We need to feed the cipher a full
717 * block when decrypting the MIC (so that the payload starts on the second
718 * block). However, the MIC may be less than a full block so use a fixed
719 * size buffer to store the MIC, letting the CTR cipher overstep the MIC
722 memset(decrypted_mic, 0, ZBEE_SEC_CONST_BLOCKSIZE);
723 memcpy(decrypted_mic, c + l_m, M);
724 /* Encrypt/Decrypt the MIC in-place. */
725 if (gcry_cipher_encrypt(cipher_hd, decrypted_mic, ZBEE_SEC_CONST_BLOCKSIZE, decrypted_mic, ZBEE_SEC_CONST_BLOCKSIZE)) {
726 gcry_cipher_close(cipher_hd);
729 /* Encrypt/Decrypt the payload. */
730 if (gcry_cipher_encrypt(cipher_hd, m, l_m, c, l_m)) {
731 gcry_cipher_close(cipher_hd);
734 /* Done with the CTR Cipher. */
735 gcry_cipher_close(cipher_hd);
737 /******************************************************
738 * Step 3: Authentication Transformation
739 ******************************************************
742 /* There is no authentication tag. We're done! */
746 * The authentication process in CCM* operates in CBC-MAC mode, but
747 * unfortunately, the input to the CBC-MAC process needs some substantial
748 * transformation and padding before we can feed it into the CBC-MAC
749 * algorithm. Instead we will operate in ECB mode and perform the
750 * transformation and padding on the fly.
752 * I also think that libgcrypt requires the input to be memory-aligned
753 * when using CBC-MAC mode, in which case can't just feed it with data
754 * from the packet buffer. All things considered it's just a lot easier
755 * to use ECB mode and do CBC-MAC manually.
757 /* Re-open the cipher in ECB mode. */
758 if (gcry_cipher_open(&cipher_hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, 0)) {
761 /* Re-load the key. */
762 if (gcry_cipher_setkey(cipher_hd, key, ZBEE_SEC_CONST_KEYSIZE)) {
763 gcry_cipher_close(cipher_hd);
766 /* Generate the first cipher block B0. */
767 cipher_in[0] = ZBEE_SEC_CCM_FLAG_M(M) |
768 ZBEE_SEC_CCM_FLAG_ADATA(l_a) |
770 memcpy(cipher_in+sizeof(gchar), nonce, ZBEE_SEC_CONST_NONCE_LEN);
771 for (i=0;i<ZBEE_SEC_CONST_L; i++) {
772 cipher_in[(ZBEE_SEC_CONST_BLOCKSIZE-1)-i] = (l_m >> (8*i)) & 0xff;
774 /* Generate the first cipher block, X1 = E(Key, 0^128 XOR B0). */
775 if (gcry_cipher_encrypt(cipher_hd, cipher_out, ZBEE_SEC_CONST_BLOCKSIZE, cipher_in, ZBEE_SEC_CONST_BLOCKSIZE)) {
776 gcry_cipher_close(cipher_hd);
780 * We avoid mallocing() big chunks of memory by recycling small stack
781 * buffers for the encryption process. Throughout this process, j is always
782 * pointed to the position within the current buffer.
785 /* AuthData = L(a) || a || Padding || m || Padding
787 * - an empty string if l(a) == 0.
788 * - 2-octet encoding of l(a) if 0 < l(a) < (2^16 - 2^8)
789 * - 0xff || 0xfe || 4-octet encoding of l(a) if (2^16 - 2^8) <= l(a) < 2^32
790 * - 0xff || 0xff || 8-octet encoding of l(a)
791 * But for ZigBee, the largest packet size we should ever see is 2^7, so we
792 * are only really concerned with the first two cases.
794 * To generate the MIC tag CCM* operates similar to CBC-MAC mode. Each block
795 * of AuthData is XOR'd with the last block of cipher output to produce the
796 * next block of cipher output. Padding sections have the minimum non-negative
797 * length such that the padding ends on a block boundary. Padded bytes are 0.
800 /* Process L(a) into the cipher block. */
801 cipher_in[j] = cipher_out[j] ^ ((l_a >> 8) & 0xff);
803 cipher_in[j] = cipher_out[j] ^ ((l_a >> 0) & 0xff);
805 /* Process a into the cipher block. */
806 for (i=0;i<l_a;i++,j++) {
807 if (j>=ZBEE_SEC_CONST_BLOCKSIZE) {
808 /* Generate the next cipher block. */
809 if (gcry_cipher_encrypt(cipher_hd, cipher_out, ZBEE_SEC_CONST_BLOCKSIZE, cipher_in, ZBEE_SEC_CONST_BLOCKSIZE)) {
810 gcry_cipher_close(cipher_hd);
813 /* Reset j to point back to the start of the new cipher block. */
816 /* Cipher in = cipher_out ^ a */
817 cipher_in[j] = cipher_out[j] ^ a[i];
819 /* Process padding into the cipher block. */
820 for (;j<ZBEE_SEC_CONST_BLOCKSIZE;j++)
821 cipher_in[j] = cipher_out[j];
823 /* Process m into the cipher block. */
824 for (i=0; i<l_m; i++, j++) {
825 if (j>=ZBEE_SEC_CONST_BLOCKSIZE) {
826 /* Generate the next cipher block. */
827 if (gcry_cipher_encrypt(cipher_hd, cipher_out, ZBEE_SEC_CONST_BLOCKSIZE, cipher_in, ZBEE_SEC_CONST_BLOCKSIZE)) {
828 gcry_cipher_close(cipher_hd);
831 /* Reset j to point back to the start of the new cipher block. */
834 /* Cipher in = cipher out ^ m */
835 cipher_in[j] = cipher_out[j] ^ m[i];
838 for (;j<ZBEE_SEC_CONST_BLOCKSIZE;j++)
839 cipher_in[j] = cipher_out[j];
840 /* Generate the last cipher block, which will be the MIC tag. */
841 if (gcry_cipher_encrypt(cipher_hd, cipher_out, ZBEE_SEC_CONST_BLOCKSIZE, cipher_in, ZBEE_SEC_CONST_BLOCKSIZE)) {
842 gcry_cipher_close(cipher_hd);
845 /* Done with the Cipher. */
846 gcry_cipher_close(cipher_hd);
848 /* Compare the MIC's */
849 return (memcmp(cipher_out, decrypted_mic, M) == 0);
850 } /* zbee_ccm_decrypt */
852 /*FUNCTION:------------------------------------------------------
856 * ZigBee Cryptographic Hash Function, described in ZigBee
857 * specification sections B.1.3 and B.6.
859 * This is a Matyas-Meyer-Oseas hash function using the AES-128
860 * cipher. We use the ECB mode of libgcrypt to get a raw block
863 * Input may be any length, and the output must be exactly 1-block in length.
865 * Implements the function:
866 * Hash(text) = Hash[t];
867 * Hash[0] = 0^(blocksize).
868 * Hash[i] = E(Hash[i-1], M[i]) XOR M[j];
869 * M[i] = i'th block of text, with some padding and flags concatenated.
871 * guint8 * input - Hash Input (any length).
872 * guint8 input_len - Hash Input Length.
873 * guint8 * output - Hash Output (exactly one block in length).
876 *---------------------------------------------------------------
879 zbee_sec_hash(guint8 *input, guint input_len, guint8 *output)
881 guint8 cipher_in[ZBEE_SEC_CONST_BLOCKSIZE];
883 /* Cipher Instance. */
884 gcry_cipher_hd_t cipher_hd;
886 /* Clear the first hash block (Hash0). */
887 memset(output, 0, ZBEE_SEC_CONST_BLOCKSIZE);
888 /* Create the cipher instance in ECB mode. */
889 if (gcry_cipher_open(&cipher_hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, 0)) {
890 return; /* Failed. */
892 /* Create the subsequent hash blocks using the formula: Hash[i] = E(Hash[i-1], M[i]) XOR M[i]
894 * because we can't garauntee that M will be exactly a multiple of the
895 * block size, we will need to copy it into local buffers and pad it.
897 * Note that we check for the next cipher block at the end of the loop
898 * rather than the start. This is so that if the input happens to end
899 * on a block boundary, the next cipher block will be generated for the
900 * start of the padding to be placed into.
904 while (i<input_len) {
905 /* Copy data into the cipher input. */
906 cipher_in[j++] = input[i++];
907 /* Check if this cipher block is done. */
908 if (j >= ZBEE_SEC_CONST_BLOCKSIZE) {
909 /* We have reached the end of this block. Process it with the
910 * cipher, note that the Key input to the cipher is actually
911 * the previous hash block, which we are keeping in output.
913 (void)gcry_cipher_setkey(cipher_hd, output, ZBEE_SEC_CONST_BLOCKSIZE);
914 (void)gcry_cipher_encrypt(cipher_hd, output, ZBEE_SEC_CONST_BLOCKSIZE, cipher_in, ZBEE_SEC_CONST_BLOCKSIZE);
915 /* Now we have to XOR the input into the hash block. */
916 for (j=0;j<ZBEE_SEC_CONST_BLOCKSIZE;j++) output[j] ^= cipher_in[j];
917 /* Reset j to start again at the beginning at the next block. */
921 /* Need to append the bit '1', followed by '0' padding long enough to end
922 * the hash input on a block boundary. However, because 'n' is 16, and 'l'
923 * will be a multiple of 8, the padding will be >= 7-bits, and we can just
924 * append the byte 0x80.
926 cipher_in[j++] = 0x80;
927 /* Pad with '0' until the the current block is exactly 'n' bits from the
930 while (j!=(ZBEE_SEC_CONST_BLOCKSIZE-2)) {
931 if (j >= ZBEE_SEC_CONST_BLOCKSIZE) {
932 /* We have reached the end of this block. Process it with the
933 * cipher, note that the Key input to the cipher is actually
934 * the previous hash block, which we are keeping in output.
936 (void)gcry_cipher_setkey(cipher_hd, output, ZBEE_SEC_CONST_BLOCKSIZE);
937 (void)gcry_cipher_encrypt(cipher_hd, output, ZBEE_SEC_CONST_BLOCKSIZE, cipher_in, ZBEE_SEC_CONST_BLOCKSIZE);
938 /* Now we have to XOR the input into the hash block. */
939 for (j=0;j<ZBEE_SEC_CONST_BLOCKSIZE;j++) output[j] ^= cipher_in[j];
940 /* Reset j to start again at the beginning at the next block. */
943 /* Pad the input with 0. */
944 cipher_in[j++] = 0x00;
946 /* Add the 'n'-bit representation of 'l' to the end of the block. */
947 cipher_in[j++] = ((input_len * 8) >> 8) & 0xff;
948 cipher_in[j++] = ((input_len * 8) >> 0) & 0xff;
949 /* Process the last cipher block. */
950 (void)gcry_cipher_setkey(cipher_hd, output, ZBEE_SEC_CONST_BLOCKSIZE);
951 (void)gcry_cipher_encrypt(cipher_hd, output, ZBEE_SEC_CONST_BLOCKSIZE, cipher_in, ZBEE_SEC_CONST_BLOCKSIZE);
952 /* XOR the last input block back into the cipher output to get the hash. */
953 for (j=0;j<ZBEE_SEC_CONST_BLOCKSIZE;j++) output[j] ^= cipher_in[j];
954 /* Cleanup the cipher. */
955 gcry_cipher_close(cipher_hd);
957 } /* zbee_sec_hash */
959 /*FUNCTION:------------------------------------------------------
963 * ZigBee Keyed Hash Function. Described in ZigBee specification
964 * section B.1.4, and in FIPS Publication 198. Strictly speaking
965 * there is nothing about the Keyed Hash Function which restricts
966 * it to only a single byte input, but that's all ZigBee ever uses.
968 * This function implements the hash function:
969 * Hash(Key, text) = H((Key XOR opad) || H((Key XOR ipad) || text));
970 * ipad = 0x36 repeated.
971 * opad = 0x5c repeated.
972 * H() = ZigBee Cryptographic Hash (B.1.3 and B.6).
974 * The output of this function is an ep_alloced buffer containing
975 * the key-hashed output, and is garaunteed never to return NULL.
977 * guint8 *key - ZigBee Security Key (must be ZBEE_SEC_CONST_KEYSIZE) in length.
978 * guint8 input - ZigBee CCM* Nonce (must be ZBEE_SEC_CONST_NONCE_LEN) in length.
981 *---------------------------------------------------------------
984 zbee_sec_key_hash(guint8 *key, guint8 input, packet_info *pinfo _U_)
986 guint8 hash_in[2*ZBEE_SEC_CONST_BLOCKSIZE];
987 guint8 * hash_out = ep_alloc(ZBEE_SEC_CONST_BLOCKSIZE+1);
989 static const guint8 ipad = 0x36;
990 static const guint8 opad = 0x5c;
992 /* Copy the key into hash_in and XOR with opad to form: (Key XOR opad) */
993 for (i=0; i<ZBEE_SEC_CONST_KEYSIZE; i++) hash_in[i] = key[i] ^ opad;
994 /* Copy the Key into hash_out and XOR with ipad to form: (Key XOR ipad) */
995 for (i=0; i<ZBEE_SEC_CONST_KEYSIZE; i++) hash_out[i] = key[i] ^ ipad;
996 /* Append the input byte to form: (Key XOR ipad) || text. */
997 hash_out[ZBEE_SEC_CONST_BLOCKSIZE] = input;
998 /* Hash the contents of hash_out and append the contents to hash_in to
999 * form: (Key XOR opad) || H((Key XOR ipad) || text).
1001 zbee_sec_hash(hash_out, ZBEE_SEC_CONST_BLOCKSIZE+1, hash_in+ZBEE_SEC_CONST_BLOCKSIZE);
1002 /* Hash the contents of hash_in to get the final result. */
1003 zbee_sec_hash(hash_in, 2*ZBEE_SEC_CONST_BLOCKSIZE, hash_out);
1005 } /* zbee_sec_key_hash */
1006 #endif /* HAVE_LIBGCRYPT */