Define some fcns & vars as static...
[metze/wireshark/wip.git] / epan / dissectors / packet-zbee-security.c
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
5  *
6  * $Id$
7  *
8  * Wireshark - Network traffic analyzer
9  * By Gerald Combs <gerald@wireshark.org>
10  * Copyright 1998 Gerald Combs
11  *
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.
16  *
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.
21  *
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.
25  */
26
27 /*  Include Files */
28 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif /* HAVEHCONFIG_H */
31
32 #include <string.h>
33 #include <stdlib.h>
34 #include <glib.h>
35 #include <gmodule.h>
36 #include <epan/proto.h>
37 #include <epan/packet.h>
38 #include <epan/prefs.h>
39 #include <epan/expert.h>
40
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.
43  */
44 #ifdef HAVE_LIBGCRYPT
45 #include <gcrypt.h>
46 #endif /* HAVE_LIBGCRYPT */
47
48 #include "packet-zbee.h"
49 #include "packet-zbee-security.h"
50
51 /* Helper Functions */
52 #ifdef HAVE_LIBGCRYPT
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 *);
56 #endif
57 static void        zbee_security_parse_prefs(void);
58
59 /* Field pointers. */
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;
67
68 /* Subtree pointers. */
69 static gint ett_zbee_sec = -1;
70 static gint ett_zbee_sec_control = -1;
71
72 static dissector_handle_t   data_handle;
73
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" },
79     { 0, NULL }
80 };
81
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
84  * security level 0.
85  */
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" },
95     { 0, NULL }
96 };
97
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 },
108     { NULL, NULL, 0 }
109 };
110
111 /* Network Key. */
112 static gboolean zbee_sec_have_nwk_key = FALSE;
113 static guint8   zbee_sec_nwk_key[ZBEE_SEC_CONST_KEYSIZE];
114
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];
118
119 /* Trust-Center Extended Address */
120 static guint64  zbee_sec_tcaddr = 0;
121
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;
127
128 /*
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.
132  */
133 #if 0
134 #define ZBEE_SEC_USE_GCRYPT_CBC_MAC
135 #endif
136 /*FUNCTION:------------------------------------------------------
137  *  NAME
138  *      zbee_security_register
139  *  DESCRIPTION
140  *      Called to initialize the security dissectors. Roughly the
141  *      equivalent of proto_register_*
142  *  PARAMETERS
143  *      module_t    zbee_prefs   - Prefs module to load preferences under.
144  *  RETURNS
145  *      none
146  *---------------------------------------------------------------
147  */
148 void zbee_security_register(module_t *zbee_prefs, int proto)
149 {
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,
153                 NULL, HFILL }},
154
155             { &hf_zbee_sec_key,
156             { "Key",                    "zbee.sec.key", FT_UINT8, BASE_HEX, VALS(zbee_sec_key_names), ZBEE_SEC_CONTROL_KEY,
157                 NULL, HFILL }},
158
159             { &hf_zbee_sec_nonce,
160             { "Extended Nonce",         "zbee.sec.ext_nonce", FT_BOOLEAN, 8, NULL, ZBEE_SEC_CONTROL_NONCE,
161                 NULL, HFILL }},
162
163             { &hf_zbee_sec_counter,
164             { "Frame Counter",          "zbee.sec.counter", FT_UINT32, BASE_DEC, NULL, 0x0,
165                 NULL, HFILL }},
166
167             { &hf_zbee_sec_src,
168             { "Source",                 "zbee.sec.src", FT_UINT64, BASE_HEX, NULL, 0x0,
169                 NULL, HFILL }},
170
171             { &hf_zbee_sec_key_seqno,
172             { "Key Sequence Number",    "zbee.sec.key_seqno", FT_UINT8, BASE_DEC, NULL, 0x0,
173                 NULL, HFILL }},
174
175             { &hf_zbee_sec_mic,
176             { "Message Integrity Code", "zbee.sec.mic", FT_BYTES, BASE_NONE, NULL, 0x0,
177                 NULL, HFILL }}
178     };
179
180     static gint *ett[] = {
181         &ett_zbee_sec,
182         &ett_zbee_sec_control
183     };
184
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);
188     }
189
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);
203
204     proto_register_field_array(proto, hf, array_length(hf));
205     proto_register_subtree_array(ett, array_length(ett));
206 } /* zbee_security_register */
207
208 /*FUNCTION:------------------------------------------------------
209  *  NAME
210  *      zbee_security_parse_key
211  *  DESCRIPTION
212  *      Parses a key string into a buffer.
213  *  PARAMETERS
214  *      const gchar *   key_str;
215  *      guint8          key_buf;
216  *  RETURNS
217  *      gboolean
218  *---------------------------------------------------------------
219  */
220 static gboolean
221 zbee_security_parse_key(const gchar *key_str, guint8 *key_buf)
222 {
223     int             i;
224     gchar           temp;
225
226     /* Clear the key. */
227     memset(key_buf, 0, ZBEE_SEC_CONST_KEYSIZE);
228     if (key_str == NULL) {
229         return FALSE;
230     }
231     /*
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.
236      */
237     temp = *(key_str++);
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);
245         else return FALSE;
246         /* Get the next nibble. */
247         temp = *(key_str++);
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);
252         else return FALSE;
253         /* Get the next nibble. */
254         temp = *(key_str++);
255     } /* for */
256     /* If we get this far, then the key was good. */
257     return TRUE;
258 } /* zbee_security_parse_key */
259
260 /*FUNCTION:------------------------------------------------------
261  *  NAME
262  *      zbee_security_parse_prefs
263  *  DESCRIPTION
264  *      Parses the security preferences into the parameters needed
265  *      for decryption.
266  *  PARAMETERS
267  *      none
268  *  RETURNS
269  *      void
270  *---------------------------------------------------------------
271  */
272 static void
273 zbee_security_parse_prefs(void)
274 {
275     int             i;
276     const gchar *   str_ptr;
277     gchar           temp;
278
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. */
284     zbee_sec_tcaddr = 0;
285     str_ptr = gPREF_zbee_sec_tcaddr;
286     temp = *(str_ptr++);
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.
290          */
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. */
299         temp = *(str_ptr++);
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. */
306         temp = *(str_ptr++);
307     } /* for */
308     /* Done */
309     return;
310
311 bad_tcaddr:
312     zbee_sec_tcaddr = 0;
313 } /* zbee_security_parse_prefs */
314
315 /*FUNCTION:------------------------------------------------------
316  *  NAME
317  *      zbee_security_handoff
318  *  DESCRIPTION
319  *      Hands off the security dissector.
320  *  PARAMETERS
321  *      none
322  *  RETURNS
323  *      tvbuff_t *
324  *---------------------------------------------------------------
325  */
326 void
327 zbee_security_handoff(void)
328 {
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 */
334
335 /*FUNCTION:------------------------------------------------------
336  *  NAME
337  *      dissect_zbee_secure
338  *  DESCRIPTION
339  *      Dissects and decrypts secured ZigBee frames.
340  *
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.
344  *  PARAMETERS
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.
350  *  RETURNS
351  *      tvbuff_t *
352  *---------------------------------------------------------------
353  */
354 tvbuff_t *
355 dissect_zbee_secure(tvbuff_t *tvb, packet_info *pinfo, proto_tree* tree, guint offset, guint64 src)
356 {
357     proto_tree *    sec_tree = NULL;
358     proto_item *    sec_root;
359     proto_tree *    field_tree;
360     proto_item *    ti;
361
362     zbee_security_packet    packet;
363     guint           mic_len;
364     guint           payload_len;
365     tvbuff_t *      payload_tvb;
366
367 #ifdef HAVE_LIBGCRYPT
368     const guint8 *  enc_buffer;
369     guint8 *        dec_buffer;
370     guint8 *        key_buffer;
371     guint8          nonce[ZBEE_SEC_CONST_NONCE_LEN];
372 #endif
373
374     /* Create a substree for the security information. */
375     if (tree) {
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);
378     }
379
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);
385     /*
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.
390      */
391 #ifdef HAVE_LIBGCRYPT
392     enc_buffer = ep_tvb_memdup(tvb, 0, tvb_length(tvb));
393     /*
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().
397      */
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);
403     if (tree) {
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);
406
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);
409     }
410     offset += sizeof(guint8);
411
412     /* Get and display the frame counter field. */
413     packet.counter = tvb_get_letohl(tvb, offset);
414     if (tree) {
415         proto_tree_add_uint(sec_tree, hf_zbee_sec_counter, tvb, offset, sizeof(guint32), packet.counter);
416     }
417     offset += sizeof(guint32);
418
419     if (packet.nonce) {
420         /* Get and display the source address. */
421         packet.src = tvb_get_letoh64(tvb, offset);
422         if (tree) {
423             proto_tree_add_eui64(sec_tree, hf_zbee_sec_src, tvb, offset, sizeof(guint64), packet.src);
424         }
425         offset += sizeof(guint64);
426     }
427     else {
428         /* This field is required in the security decryption process, so
429          * fill it in in case the higher layer provided it.
430          */
431         packet.src = src;
432     }
433
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);
437         if (tree) {
438             proto_tree_add_uint(sec_tree, hf_zbee_sec_key_seqno, tvb, offset, sizeof(guint8), packet.key_seqno);
439         }
440         offset += sizeof(guint8);
441     }
442
443     /* Determine the length of the MIC. */
444     switch (packet.level){
445         case ZBEE_SEC_ENC:
446         case ZBEE_SEC_NONE:
447         default:
448             mic_len=0;
449             break;
450
451         case ZBEE_SEC_ENC_MIC32:
452         case ZBEE_SEC_MIC32:
453             mic_len=4;
454             break;
455
456         case ZBEE_SEC_ENC_MIC64:
457         case ZBEE_SEC_MIC64:
458             mic_len=8;
459             break;
460
461         case ZBEE_SEC_ENC_MIC128:
462         case ZBEE_SEC_MIC128:
463             mic_len=16;
464             break;
465     } /* switch */
466
467     /* Ensure that the payload exists (length >= 1) for this length. */
468     payload_len = tvb_ensure_length_remaining(tvb, offset+mic_len+1)+1;
469
470     /* Get and display the MIC. */
471     if (mic_len) {
472         /* Display the MIC. */
473         if (tree) {
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));
475         }
476     }
477
478     /**********************************************
479      *  Perform Security Operations on the Frame  *
480      **********************************************
481      */
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);
488     }
489
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?)*/
497                 goto decrypt_failed;
498             }
499             if (packet.src == 0) {
500                 /* Without the extended source address, we can't create the nonce. */
501                 goto decrypt_failed;
502             }
503             /* The key, is the network key. */
504             key_buffer = zbee_sec_nwk_key;
505             break;
506
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. */
511                 goto decrypt_failed;
512             }
513             if ((packet.src == 0) && (zbee_sec_tcaddr == 0)){
514                 /* Without the extended source address, we can't create the nonce. */
515                 goto decrypt_failed;
516             }
517             else if (packet.src == 0) {
518                 packet.src = zbee_sec_tcaddr;
519             }
520             key_buffer = zbee_sec_tclink_key;
521             break;
522
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. */
527                 goto decrypt_failed;
528             }
529             if ((packet.src == 0) && (zbee_sec_tcaddr == 0)){
530                 /* Without the extended source address, we can't create the nonce. */
531                 goto decrypt_failed;
532             }
533             else if (packet.src == 0) {
534                 packet.src = zbee_sec_tcaddr;
535             }
536             key_buffer = zbee_sec_key_hash(zbee_sec_tclink_key, 0x00, pinfo);
537             break;
538
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. */
543                 goto decrypt_failed;
544             }
545             if ((packet.src == 0) && (zbee_sec_tcaddr == 0)){
546                 /* Without the extended source address, we can't create the nonce. */
547                 goto decrypt_failed;
548             }
549             else if (packet.src == 0) {
550                 packet.src = zbee_sec_tcaddr;
551             }
552             key_buffer = zbee_sec_key_hash(zbee_sec_tclink_key, 0x02, pinfo);
553             break;
554
555         default:
556             goto decrypt_failed;
557     } /* switch */
558
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 */
565                 nonce,              /* Nonce */
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) */
569                 offset,             /* l(a) */
570                 payload_len,        /* l(m) */
571                 mic_len)) {         /* M */
572         /* Decryption Failed! */
573         g_free(dec_buffer);
574         goto decrypt_failed;
575     }
576
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");
581     /* Done! */
582     return payload_tvb;
583
584 decrypt_failed:
585 #endif /* HAVE_LIBGCRYPT */
586
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. */
594     return NULL;
595
596 } /* dissect_zbee_secure */
597
598 #ifdef HAVE_LIBGCRYPT
599 /*FUNCTION:------------------------------------------------------
600  *  NAME
601  *      zbee_sec_make_nonce
602  *  DESCRIPTION
603  *      Fills in the ZigBee security nonce from the provided security
604  *      packet structure.
605  *  PARAMETERS
606  *      gchar           *nonce  - Nonce Buffer.
607  *      zbee_security_packet *packet - Security information.
608  *  RETURNS
609  *      void
610  *---------------------------------------------------------------
611  */
612 static void
613 zbee_sec_make_nonce(guint8 *nonce, zbee_security_packet *packet)
614 {
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 */
632 #endif
633
634 #ifdef HAVE_LIBGCRYPT
635 /*FUNCTION:------------------------------------------------------
636  *  NAME
637  *      zbee_sec_ccm_decrypt
638  *  DESCRIPTION
639  *      Performs the Reverse CCM* Transformation (specified in
640  *      section A.3 of ZigBee Specification (053474r17).
641  *
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.
645  *
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.
649  *  PARAMETERS
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.
660  *  RETURNS
661  *      gboolean        - TRUE if successful.
662  *---------------------------------------------------------------
663  */
664 static gboolean
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) */
673 {
674     guint8              cipher_in[ZBEE_SEC_CONST_BLOCKSIZE];
675     guint8              cipher_out[ZBEE_SEC_CONST_BLOCKSIZE];
676     guint8              decrypted_mic[ZBEE_SEC_CONST_BLOCKSIZE];
677     guint               i, j;
678     /* Cipher Instance. */
679     gcry_cipher_hd_t    cipher_hd;
680
681     /* Sanity-Check. */
682     if (M > ZBEE_SEC_CONST_BLOCKSIZE) return FALSE;
683     /*
684      * The CCM* counter is L bytes in length, ensure that the payload
685      * isn't long enough to overflow it.
686      */
687     if ((1 + (l_a/ZBEE_SEC_CONST_BLOCKSIZE)) > (1<<(ZBEE_SEC_CONST_L*8))) return FALSE;
688
689     /******************************************************
690      * Step 1: Encryption/Decryption Transformation
691      ******************************************************
692      */
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);
697     /*
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.
701      */
702     if (gcry_cipher_open(&cipher_hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CTR, 0)) {
703         return FALSE;
704     }
705     /* Set the Key. */
706     if (gcry_cipher_setkey(cipher_hd, key, ZBEE_SEC_CONST_KEYSIZE)) {
707         gcry_cipher_close(cipher_hd);
708         return FALSE;
709     }
710     /* Set the counter. */
711     if (gcry_cipher_setctr(cipher_hd, cipher_in, ZBEE_SEC_CONST_BLOCKSIZE)) {
712         gcry_cipher_close(cipher_hd);
713         return FALSE;
714     }
715     /*
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
720      * if need be.
721      */
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);
727         return FALSE;
728     }
729     /* Encrypt/Decrypt the payload. */
730     if (gcry_cipher_encrypt(cipher_hd, m, l_m, c, l_m)) {
731         gcry_cipher_close(cipher_hd);
732         return FALSE;
733     }
734     /* Done with the CTR Cipher. */
735     gcry_cipher_close(cipher_hd);
736
737     /******************************************************
738      * Step 3: Authentication Transformation
739      ******************************************************
740      */
741     if (M == 0) {
742         /* There is no authentication tag. We're done! */
743         return TRUE;
744     }
745     /*
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.
751      *
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.
756      */
757     /* Re-open the cipher in ECB mode. */
758     if (gcry_cipher_open(&cipher_hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, 0)) {
759         return FALSE;
760     }
761     /* Re-load the key. */
762     if (gcry_cipher_setkey(cipher_hd, key, ZBEE_SEC_CONST_KEYSIZE)) {
763         gcry_cipher_close(cipher_hd);
764         return FALSE;
765     }
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) |
769                     ZBEE_SEC_CCM_FLAG_L;
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;
773     } /* for */
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);
777         return FALSE;
778     }
779     /*
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.
783      */
784     j = 0;
785     /* AuthData = L(a) || a || Padding || m || Padding
786      * Where L(a) =
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.
793      *
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.
798      */
799     if (l_a > 0) {
800         /* Process L(a) into the cipher block. */
801         cipher_in[j] = cipher_out[j] ^ ((l_a >> 8) & 0xff);
802         j++;
803         cipher_in[j] = cipher_out[j] ^ ((l_a >> 0) & 0xff);
804         j++;
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);
811                     return FALSE;
812                 }
813                 /* Reset j to point back to the start of the new cipher block. */
814                 j = 0;
815             }
816             /* Cipher in = cipher_out ^ a */
817             cipher_in[j] = cipher_out[j] ^ a[i];
818         } /* for */
819         /* Process padding into the cipher block. */
820         for (;j<ZBEE_SEC_CONST_BLOCKSIZE;j++)
821             cipher_in[j] = cipher_out[j];
822     }
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);
829                 return FALSE;
830             }
831             /* Reset j to point back to the start of the new cipher block. */
832             j = 0;
833         }
834         /* Cipher in = cipher out ^ m */
835         cipher_in[j] = cipher_out[j] ^ m[i];
836     } /* for */
837     /* Padding. */
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);
843         return FALSE;
844     }
845     /* Done with the Cipher. */
846     gcry_cipher_close(cipher_hd);
847
848     /* Compare the MIC's */
849     return (memcmp(cipher_out, decrypted_mic, M) == 0);
850 } /* zbee_ccm_decrypt */
851
852 /*FUNCTION:------------------------------------------------------
853  *  NAME
854  *      zbee_sec_hash
855  *  DESCRIPTION
856  *      ZigBee Cryptographic Hash Function, described in ZigBee
857  *      specification sections B.1.3 and B.6.
858  *
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
861  *      cipher.
862  *
863  *      Input may be any length, and the output must be exactly 1-block in length.
864  *
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.
870  *  PARAMETERS
871  *      guint8 *    input       - Hash Input (any length).
872  *      guint8      input_len   - Hash Input Length.
873  *      guint8 *    output      - Hash Output (exactly one block in length).
874  *  RETURNS
875  *      void
876  *---------------------------------------------------------------
877  */
878 static void
879 zbee_sec_hash(guint8 *input, guint input_len, guint8 *output)
880 {
881     guint8              cipher_in[ZBEE_SEC_CONST_BLOCKSIZE];
882     guint               i, j;
883     /* Cipher Instance. */
884     gcry_cipher_hd_t    cipher_hd;
885
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. */
891     }
892     /* Create the subsequent hash blocks using the formula: Hash[i] = E(Hash[i-1], M[i]) XOR M[i]
893      *
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.
896      *
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.
901      */
902     i = 0;
903     j = 0;
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.
912              */
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. */
918             j = 0;
919         }
920     } /* for */
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.
925      */
926     cipher_in[j++] = 0x80;
927     /* Pad with '0' until the the current block is exactly 'n' bits from the
928      * end.
929      */
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.
935              */
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. */
941             j = 0;
942         }
943         /* Pad the input with 0. */
944         cipher_in[j++] = 0x00;
945     } /* while */
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);
956     /* Done */
957 } /* zbee_sec_hash */
958
959 /*FUNCTION:------------------------------------------------------
960  *  NAME
961  *      zbee_sec_key_hash
962  *  DESCRIPTION
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.
967  *
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).
973  *
974  *      The output of this function is an ep_alloced buffer containing
975  *      the key-hashed output, and is garaunteed never to return NULL.
976  *  PARAMETERS
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.
979  *  RETURNS
980  *      guint8*
981  *---------------------------------------------------------------
982  */
983 static guint8 *
984 zbee_sec_key_hash(guint8 *key, guint8 input, packet_info *pinfo _U_)
985 {
986     guint8              hash_in[2*ZBEE_SEC_CONST_BLOCKSIZE];
987     guint8 *            hash_out = ep_alloc(ZBEE_SEC_CONST_BLOCKSIZE+1);
988     int                 i;
989     static const guint8 ipad = 0x36;
990     static const guint8 opad = 0x5c;
991
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).
1000      */
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);
1004     return hash_out;
1005 } /* zbee_sec_key_hash */
1006 #endif  /* HAVE_LIBGCRYPT */