eliminate an anonymous enum.
[obnox/wireshark/wip.git] / asn1 / snmp / packet-snmp-template.c
1 /* packet-snmp.c
2  * Routines for SNMP (simple network management protocol)
3  * Copyright (C) 1998 Didier Jorand
4  *
5  * See RFC 1157 for SNMPv1.
6  *
7  * See RFCs 1901, 1905, and 1906 for SNMPv2c.
8  *
9  * See RFCs 1905, 1906, 1909, and 1910 for SNMPv2u [historic].
10  *
11  * See RFCs 2570-2576 for SNMPv3
12  * Updated to use the asn2wrs compiler made by Tomas Kukosa
13  * Copyright (C) 2005 - 2006 Anders Broman [AT] ericsson.com
14  *
15  * See RFC 3414 for User-based Security Model for SNMPv3
16  * See RFC 3826 for  (AES) Cipher Algorithm in the SNMP USM
17  * See RFC 2578 for Structure of Management Information Version 2 (SMIv2)
18  * Copyright (C) 2007 Luis E. Garcia Ontanon <luis.ontanon@gmail.com>
19  *
20  * $Id$
21  *
22  * Wireshark - Network traffic analyzer
23  * By Gerald Combs <gerald@wireshark.org>
24  * Copyright 1998 Gerald Combs
25  *
26  * Some stuff from:
27  *
28  * GXSNMP -- An snmp mangament application
29  * Copyright (C) 1998 Gregory McLean & Jochen Friedrich
30  * Beholder RMON ethernet network monitor,Copyright (C) 1993 DNPAP group
31  *
32  * This program is free software; you can redistribute it and/or
33  * modify it under the terms of the GNU General Public License
34  * as published by the Free Software Foundation; either version 2
35  * of the License, or (at your option) any later version.
36  *
37  * This program is distributed in the hope that it will be useful,
38  * but WITHOUT ANY WARRANTY; without even the implied warranty of
39  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
40  * GNU General Public License for more details.
41  *
42  * You should have received a copy of the GNU General Public License
43  * along with this program; if not, write to the Free Software
44  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
45  */
46
47 #define D(args) do {printf args; fflush(stdout); } while(0)
48
49 #ifdef HAVE_CONFIG_H
50 # include "config.h"
51 #endif
52
53 #include <stdio.h>
54 #include <string.h>
55 #include <ctype.h>
56
57 #include <glib.h>
58
59 #include <epan/packet.h>
60 #include <epan/strutil.h>
61 #include <epan/conversation.h>
62 #include "etypes.h"
63 #include <epan/prefs.h>
64 #include <epan/sminmpec.h>
65 #include <epan/emem.h>
66 #include <epan/next_tvb.h>
67 #include <epan/uat.h>
68 #include <epan/asn1.h>
69 #include "packet-ipx.h"
70 #include "packet-hpext.h"
71
72
73 #include "packet-ber.h"
74
75 #include "packet-snmp.h"
76
77 #include <epan/crypt/crypt-sha1.h>
78 #include <epan/crypt/crypt-md5.h>
79 #include <epan/expert.h>
80 #include <epan/report_err.h>
81 #include <epan/oids.h>
82
83 #ifdef _WIN32
84 #include <winposixtype.h>
85 #endif /* _WIN32 */
86
87 #ifdef HAVE_LIBGCRYPT
88 #include <gcrypt.h>
89 #endif
90
91 /* Take a pointer that may be null and return a pointer that's not null
92    by turning null pointers into pointers to the above null string,
93    and, if the argument pointer wasn't null, make sure we handle
94    non-printable characters in the string by escaping them. */
95 #define SAFE_STRING(s, l)       (((s) != NULL) ? format_text((s), (l)) : "")
96
97 #define PNAME  "Simple Network Management Protocol"
98 #define PSNAME "SNMP"
99 #define PFNAME "snmp"
100
101 #define UDP_PORT_SNMP           161
102 #define UDP_PORT_SNMP_TRAP      162
103 #define TCP_PORT_SNMP           161
104 #define TCP_PORT_SNMP_TRAP      162
105 #define TCP_PORT_SMUX           199
106 #define UDP_PORT_SNMP_PATROL 8161
107
108 /* Initialize the protocol and registered fields */
109 static int proto_snmp = -1;
110 static int proto_smux = -1;
111
112 static gboolean display_oid = TRUE;
113 static gboolean snmp_var_in_tree = TRUE; 
114
115 static gboolean snmp_usm_auth_md5(snmp_usm_params_t* p, guint8**, guint*, gchar const**);
116 static gboolean snmp_usm_auth_sha1(snmp_usm_params_t* p, guint8**, guint*, gchar const**);
117
118 static tvbuff_t* snmp_usm_priv_des(snmp_usm_params_t*, tvbuff_t*, gchar const**);
119 static tvbuff_t* snmp_usm_priv_aes(snmp_usm_params_t*, tvbuff_t*, gchar const**);
120
121
122 static void snmp_usm_password_to_key_md5(const guint8 *password, guint passwordlen, const guint8 *engineID, guint engineLength, guint8 *key);
123 static void snmp_usm_password_to_key_sha1(const guint8 *password, guint passwordlen, const guint8 *engineID, guint engineLength, guint8 *key);
124
125
126 static snmp_usm_auth_model_t model_md5 = {snmp_usm_password_to_key_md5, snmp_usm_auth_md5, 16};
127 static snmp_usm_auth_model_t model_sha1 = {snmp_usm_password_to_key_sha1, snmp_usm_auth_sha1, 20};
128
129 static value_string auth_types[] = {
130         {0,"MD5"},
131         {1,"SHA1"},
132         {0,NULL}
133 };
134 static snmp_usm_auth_model_t* auth_models[] = {&model_md5,&model_sha1};
135
136
137 static value_string priv_types[] = {
138         {0,"DES"},
139         {1,"AES"},
140         {0,NULL}
141 };
142 static snmp_usm_decoder_t priv_protos[] = {snmp_usm_priv_des, snmp_usm_priv_aes};
143
144 static snmp_ue_assoc_t* ueas = NULL;
145 static guint num_ueas = 0;
146 static uat_t* assocs_uat = NULL;
147 static snmp_ue_assoc_t* localized_ues = NULL;
148 static snmp_ue_assoc_t* unlocalized_ues = NULL;
149 /****/
150
151
152
153 static snmp_usm_params_t usm_p = {FALSE,FALSE,0,0,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL,FALSE};
154
155 #define TH_AUTH   0x01
156 #define TH_CRYPT  0x02
157 #define TH_REPORT 0x04
158
159 /* desegmentation of SNMP-over-TCP */
160 static gboolean snmp_desegment = TRUE;
161
162 /* Global variables */
163
164 guint32 MsgSecurityModel;
165 tvbuff_t *oid_tvb=NULL;
166 tvbuff_t *value_tvb=NULL;
167
168 static dissector_handle_t snmp_handle;
169 static dissector_handle_t data_handle;
170
171 static next_tvb_list_t var_list;
172
173 static int hf_snmp_v3_flags_auth = -1;
174 static int hf_snmp_v3_flags_crypt = -1;
175 static int hf_snmp_v3_flags_report = -1;
176
177 static int hf_snmp_engineid_conform = -1;
178 static int hf_snmp_engineid_enterprise = -1;
179 static int hf_snmp_engineid_format = -1;
180 static int hf_snmp_engineid_ipv4 = -1;
181 static int hf_snmp_engineid_ipv6 = -1;
182 static int hf_snmp_engineid_mac = -1;
183 static int hf_snmp_engineid_text = -1;
184 static int hf_snmp_engineid_time = -1;
185 static int hf_snmp_engineid_data = -1;
186 static int hf_snmp_decryptedPDU = -1;
187 static int hf_snmp_msgAuthentication = -1;
188
189 static int hf_snmp_noSuchObject = -1;
190 static int hf_snmp_noSuchInstance = -1;
191 static int hf_snmp_endOfMibView = -1;
192 static int hf_snmp_unSpecified = -1;
193
194 static int hf_snmp_integer32_value = -1;
195 static int hf_snmp_octestring_value = -1;
196 static int hf_snmp_oid_value = -1;
197 static int hf_snmp_null_value = -1;
198 static int hf_snmp_ipv4_value = -1;
199 static int hf_snmp_ipv6_value = -1;
200 static int hf_snmp_anyaddress_value = -1;
201 static int hf_snmp_unsigned32_value = -1;
202 static int hf_snmp_unknown_value = -1;
203 static int hf_snmp_opaque_value = -1;
204 static int hf_snmp_nsap_value = -1;
205 static int hf_snmp_counter_value = -1;
206 static int hf_snmp_timeticks_value = -1;
207 static int hf_snmp_big_counter_value = -1;
208 static int hf_snmp_gauge32_value = -1;
209
210 static int hf_snmp_objectname = -1;
211 static int hf_snmp_scalar_instance_index = -1;
212
213
214 #include "packet-snmp-hf.c"
215
216 static int hf_smux_version = -1;
217 static int hf_smux_pdutype = -1;
218
219 /* Initialize the subtree pointers */
220 static gint ett_smux = -1;
221 static gint ett_snmp = -1;
222 static gint ett_engineid = -1;
223 static gint ett_msgFlags = -1;
224 static gint ett_encryptedPDU = -1;
225 static gint ett_decrypted = -1;
226 static gint ett_authParameters = -1;
227 static gint ett_internet = -1;
228 static gint ett_varbind = -1;
229 static gint ett_name = -1;
230 static gint ett_value = -1;
231 static gint ett_decoding_error = -1;
232
233 #include "packet-snmp-ett.c"
234
235 static const true_false_string auth_flags = {
236         "OK",
237         "Failed"
238 };
239
240 /* defined in net-SNMP; include/net-snmp/library/snmp.h */
241 #undef SNMP_MSG_GET
242 #undef SNMP_MSG_SET
243 #undef SNMP_MSG_GETNEXT
244 #undef SNMP_MSG_RESPONSE
245 #undef SNMP_MSG_TRAP
246 #undef SNMP_MSG_GETBULK
247 #undef SNMP_MSG_INFORM
248 #undef SNMP_MSG_TRAP2
249 #undef SNMP_MSG_REPORT
250 #undef SNMP_NOSUCHOBJECT
251 #undef SNMP_NOSUCHINSTANCE
252 #undef SNMP_ENDOFMIBVIEW
253
254 /* Security Models */
255
256 #define SNMP_SEC_ANY                    0
257 #define SNMP_SEC_V1                             1
258 #define SNMP_SEC_V2C                    2
259 #define SNMP_SEC_USM                    3
260
261 static const value_string sec_models[] = {
262         { SNMP_SEC_ANY,                 "Any" },
263         { SNMP_SEC_V1,                  "V1" },
264         { SNMP_SEC_V2C,                 "V2C" },
265         { SNMP_SEC_USM,                 "USM" },
266         { 0,                            NULL }
267 };
268
269 /* SMUX PDU types */
270 #define SMUX_MSG_OPEN           0
271 #define SMUX_MSG_CLOSE          1
272 #define SMUX_MSG_RREQ           2
273 #define SMUX_MSG_RRSP           3
274 #define SMUX_MSG_SOUT           4
275
276 static const value_string smux_types[] = {
277         { SMUX_MSG_OPEN,        "Open" },
278         { SMUX_MSG_CLOSE,       "Close" },
279         { SMUX_MSG_RREQ,        "Registration Request" },
280         { SMUX_MSG_RRSP,        "Registration Response" },
281         { SMUX_MSG_SOUT,        "Commit Or Rollback" },
282         { 0,                    NULL }
283 };
284
285
286 #define SNMP_IPA    0           /* IP Address */
287 #define SNMP_CNT    1           /* Counter (Counter32) */
288 #define SNMP_GGE    2           /* Gauge (Gauge32) */
289 #define SNMP_TIT    3           /* TimeTicks */
290 #define SNMP_OPQ    4           /* Opaque */
291 #define SNMP_NSP    5           /* NsapAddress */
292 #define SNMP_C64    6           /* Counter64 */
293 #define SNMP_U32    7           /* Uinteger32 */
294
295 #define SERR_NSO    0
296 #define SERR_NSI    1
297 #define SERR_EOM    2
298
299
300 dissector_table_t value_sub_dissectors_table;
301
302 /*
303  *  dissect_snmp_VarBind
304  *  this routine dissects variable bindings, looking for the oid information in our oid reporsitory
305  *  to format and add the value adequatelly.
306  *
307  * The choice to handwrite this code instead of using the asn compiler is to avoid having tons
308  * of uses of global variables distributed in very different parts of the code.
309  * Other than that there's a cosmetic thing: the tree from ASN generated code would be so
310  * convoluted due to the nesting of CHOICEs in the definition of VarBind/value.
311  *
312  * XXX: the length of this function (~400 lines) is an aberration!
313  *  oid_key_t:key_type could become a series of callbacks instead of an enum
314  *  the (! oid_info_is_ok) switch could be made into an array (would be slower)
315  *  
316   
317         NetworkAddress ::=  CHOICE { internet IpAddress }
318         IpAddress ::= [APPLICATION 0] IMPLICIT OCTET STRING (SIZE (4))
319         TimeTicks ::= [APPLICATION 3] IMPLICIT INTEGER (0..4294967295)
320         Integer32 ::= INTEGER (-2147483648..2147483647)
321         ObjectName ::= OBJECT IDENTIFIER
322         Counter32 ::= [APPLICATION 1] IMPLICIT INTEGER (0..4294967295)
323         Gauge32 ::= [APPLICATION 2] IMPLICIT INTEGER (0..4294967295)
324         Unsigned32 ::= [APPLICATION 2] IMPLICIT INTEGER (0..4294967295)
325         Integer-value ::=  INTEGER (-2147483648..2147483647)
326         Integer32 ::= INTEGER (-2147483648..2147483647)
327         ObjectID-value ::= OBJECT IDENTIFIER
328         Empty ::= NULL
329         TimeTicks ::= [APPLICATION 3] IMPLICIT INTEGER (0..4294967295) 
330         Opaque ::= [APPLICATION 4] IMPLICIT OCTET STRING
331         Counter64 ::= [APPLICATION 6] IMPLICIT INTEGER (0..18446744073709551615)
332
333         ObjectSyntax ::= CHOICE {
334                  simple SimpleSyntax,
335                  application-wide ApplicationSyntax
336         }
337
338         SimpleSyntax ::= CHOICE {
339            integer-value Integer-value,
340            string-value String-value,
341            objectID-value ObjectID-value,
342            empty  Empty
343         }
344
345         ApplicationSyntax ::= CHOICE {
346            ipAddress-value IpAddress,
347            counter-value Counter32,
348            timeticks-value TimeTicks,
349            arbitrary-value Opaque,
350            big-counter-value Counter64,
351            unsigned-integer-value Unsigned32
352         }
353
354         ValueType ::=  CHOICE {
355            value ObjectSyntax,
356            unSpecified NULL,
357            noSuchObject[0] IMPLICIT NULL,
358            noSuchInstance[1] IMPLICIT NULL,
359            endOfMibView[2] IMPLICIT NULL
360         }
361
362         VarBind ::= SEQUENCE {
363            name ObjectName,
364            valueType ValueType
365         }
366  
367  */
368
369 extern int dissect_snmp_VarBind(gboolean implicit_tag _U_,
370                                                                 tvbuff_t *tvb,
371                                                                 int offset,
372                                                                 asn1_ctx_t *actx,
373                                                                 proto_tree *tree,
374                                                                 int hf_index _U_) {
375         int seq_offset, name_offset, value_offset, value_start;
376         guint32 seq_len, name_len, value_len;
377         gint8 ber_class;
378         gboolean pc;
379         gint32 tag;
380         gboolean ind;
381         guint32* subids;
382         guint8* oid_bytes;
383         oid_info_t* oid_info = NULL;
384         guint oid_matched, oid_left;
385         proto_item *pi_name, *pi_varbind, *pi_value = NULL;
386         proto_tree *pt, *pt_varbind, *pt_name, *pt_value;
387         char label[ITEM_LABEL_LENGTH];
388         char* repr = NULL;
389         char* valstr;
390         int hfid = -1;
391         int min_len = 0, max_len = 0;
392         gboolean oid_info_is_ok;
393         const char* oid_string = NULL;
394         enum _error_state { NO_ERROR, WRONG_LENGTH, WRONG_TAG};
395         enum _error_state format_error = NO_ERROR;
396
397         seq_offset = offset;
398         
399         /* first have the VarBind's sequence header */
400         offset = get_ber_identifier(tvb, offset, &ber_class, &pc, &tag);
401         offset = get_ber_length(tvb, offset, &seq_len, &ind);
402         
403         seq_len += offset - seq_offset;
404         
405         if (!pc && ber_class==BER_CLASS_UNI && tag==BER_UNI_TAG_SEQUENCE) {
406                 proto_item* pi = proto_tree_add_text(tree, tvb, seq_offset, seq_len,"VarBind must be an universal class sequence");
407                 pt = proto_item_add_subtree(pi,ett_decoding_error);
408                 expert_add_info_format(actx->pinfo, pi, PI_MALFORMED, PI_WARN, "VarBind is not an universal class sequence");
409                 return dissect_unknown_ber(actx->pinfo, tvb, seq_offset, pt);
410         }
411         
412         if (ind){
413                 proto_item* pi = proto_tree_add_text(tree, tvb, seq_offset, seq_len,"Indicator must be clear in VarBind");
414                 pt = proto_item_add_subtree(pi,ett_decoding_error);
415                 expert_add_info_format(actx->pinfo, pi, PI_MALFORMED, PI_WARN, "VarBind has indicator set");
416                 return dissect_unknown_ber(actx->pinfo, tvb, seq_offset, pt);
417         }
418         
419         /* then we have the ObjectName's header */
420         
421         offset = get_ber_identifier(tvb, offset, &ber_class, &pc, &tag);
422         name_offset = offset = get_ber_length(tvb, offset, &name_len, &ind);
423         
424         if (! ( !pc && ber_class==BER_CLASS_UNI && tag==BER_UNI_TAG_OID) ) {
425                 proto_item* pi = proto_tree_add_text(tree, tvb, seq_offset, seq_len,"ObjectName must be an OID in primitive encoding");
426                 pt = proto_item_add_subtree(pi,ett_decoding_error);
427                 expert_add_info_format(actx->pinfo, pi, PI_MALFORMED, PI_WARN, "ObjectName not an OID");
428                 return dissect_unknown_ber(actx->pinfo, tvb, seq_offset, pt);
429         }
430         
431         if (ind){
432                 proto_item* pi = proto_tree_add_text(tree, tvb, seq_offset, seq_len,"Indicator must be clear in ObjectName");
433                 pt = proto_item_add_subtree(pi,ett_decoding_error);
434                 expert_add_info_format(actx->pinfo, pi, PI_MALFORMED, PI_WARN, "ObjectName has indicator set");
435                 return dissect_unknown_ber(actx->pinfo, tvb, seq_offset, pt);
436         }
437         
438         offset += name_len;
439         value_start = offset;
440         
441         /* then we have the  value's header */
442         offset = get_ber_identifier(tvb, offset, &ber_class, &pc, &tag);
443         value_offset = offset = get_ber_length(tvb, offset, &value_len, &ind);
444         
445         if (! (!pc) ) {
446                 proto_item* pi = proto_tree_add_text(tree, tvb, seq_offset, seq_len,"the value must be in primitive encoding");
447                 pt = proto_item_add_subtree(pi,ett_decoding_error);
448                 expert_add_info_format(actx->pinfo, pi, PI_MALFORMED, PI_WARN, "value not in primitive encoding");
449                 return dissect_unknown_ber(actx->pinfo, tvb, seq_offset, pt);
450         }
451
452         /* Now, we know where everithing is */
453         
454
455
456         /* we add the varbind tree root with a dummy label we'll fill later on */
457         pi_varbind = proto_tree_add_text(tree,tvb,seq_offset,seq_len,"VarBind");
458         pt_varbind = proto_item_add_subtree(pi_varbind,ett_varbind);
459         *label = '\0';
460         
461         pi_name = proto_tree_add_item(pt_varbind,hf_snmp_objectname,tvb,name_offset,name_len,FALSE);
462         pt_name = proto_item_add_subtree(pi_name,ett_name);
463         
464         
465         
466         if (ber_class == BER_CLASS_CON) {
467                 /* if we have an error value just add it and get out the way ASAP */
468                 proto_item* pi;
469                 const char* note;
470                 
471                 if (value_len != 0) { 
472                         min_len = max_len = 0;
473                         format_error = WRONG_LENGTH;
474                 }
475                 
476                 switch (tag) {
477                         case SERR_NSO:
478                                 hfid = hf_snmp_noSuchObject;
479                                 note = "noSuchObject";
480                                 break;
481                         case SERR_NSI:
482                                 hfid = hf_snmp_noSuchInstance;
483                                 note = "noSuchInstance";
484                                 break;
485                         case SERR_EOM:
486                                 hfid = hf_snmp_endOfMibView;
487                                 note = "endOfMibView";
488                                 break;
489                         default: {
490                                 pi = proto_tree_add_text(pt_varbind,tvb,0,0,"Wrong tag for Error Value: expected 0, 1, or 2 but got: %d",tag);
491                                 pt = proto_item_add_subtree(pi,ett_decoding_error);
492                                 expert_add_info_format(actx->pinfo, pi, PI_MALFORMED, PI_WARN, "Wrong tag for SNMP VarBind error value");
493                                 return dissect_unknown_ber(actx->pinfo, tvb, value_start, pt);
494                         }                               
495                 }
496                 
497                 pi = proto_tree_add_item(pt_varbind,hfid,tvb,value_offset,value_len,FALSE);
498                 expert_add_info_format(actx->pinfo, pi, PI_RESPONSE_CODE, PI_NOTE, "%s",note);
499                 goto set_label;
500         }
501         
502         /* fetch ObjectName and its relative oid_info */
503         oid_bytes = ep_tvb_memdup(tvb, name_offset, name_len);
504         oid_info = oid_get_from_encoded(oid_bytes, name_len, &subids, &oid_matched, &oid_left);
505         
506         add_oid_debug_subtree(oid_info,pt_name);
507
508         if (subids && oid_matched+oid_left) {
509                 oid_string = oid_subid2string(subids,oid_matched+oid_left);
510         } 
511         
512         /* now we'll try to figure out which are the indexing sub-oids and whether the oid we know about is the one oid we have to use */
513         switch (oid_info->kind) {
514                 case OID_KIND_SCALAR:
515                         if (oid_left  == 1) {
516                                 /* OK: we got the instance sub-id */
517                                 proto_tree_add_uint64(pt_name,hf_snmp_scalar_instance_index,tvb,name_offset,name_len,subids[oid_matched]);
518                                 oid_info_is_ok = TRUE;
519                                 goto indexing_done;
520                         } else if (oid_left  == 0) {
521                                 if (ber_class == BER_CLASS_UNI && tag == BER_UNI_TAG_NULL) {
522                                         /* unSpecified  does not require an instance sub-id add the new value and get off the way! */
523                                         pi_value = proto_tree_add_item(pt_varbind,hf_snmp_unSpecified,tvb,value_offset,value_len,FALSE);
524                                         goto set_label;
525                                 } else {
526                                         proto_item* pi = proto_tree_add_text(pt_name,tvb,0,0,"A scalar should have one instance sub-id this one has none");
527                                         expert_add_info_format(actx->pinfo, pi, PI_MALFORMED, PI_WARN, "No instance sub-id in scalar value");
528                                         oid_info_is_ok = FALSE;
529                                         goto indexing_done;
530                                 }
531                         } else {
532                                 proto_item* pi = proto_tree_add_text(pt_name,tvb,0,0,"A scalar should have only one instance sub-id this has: %d",oid_left);
533                                 expert_add_info_format(actx->pinfo, pi, PI_MALFORMED, PI_WARN, "Wrong number of instance sub-ids in scalar value");
534                                 oid_info_is_ok = FALSE;
535                                 goto indexing_done;
536                         }
537                 break;
538                 case OID_KIND_COLUMN:
539                         if ( oid_info->parent->kind == OID_KIND_ROW) {
540                                 oid_key_t* k = oid_info->parent->key;
541                                 guint key_start = oid_matched;
542                                 guint key_len = oid_left;
543                                 oid_info_is_ok = TRUE;
544
545                                 if ( key_len == 0 && ber_class == BER_CLASS_UNI && tag == BER_UNI_TAG_NULL) {
546                                         /* unSpecified  does not require an instance sub-id add the new value and get off the way! */
547                                         pi_value = proto_tree_add_item(pt_varbind,hf_snmp_unSpecified,tvb,value_offset,value_len,FALSE);
548                                         goto set_label;
549                                 }
550                                 
551                                 if (k) {
552                                         for (;k;k = k->next) {
553                                                 guint suboid_len;
554                                                 
555                                                 if (key_start >= oid_matched+oid_left) {
556                                                         proto_item* pi = proto_tree_add_text(pt_name,tvb,0,0,"index sub-oid shorter than expected");
557                                                         expert_add_info_format(actx->pinfo, pi, PI_MALFORMED, PI_WARN, "index sub-oid shorter than expected");
558                                                         oid_info_is_ok = FALSE;
559                                                         goto indexing_done;
560                                                 }
561                                                 
562                                                 switch(k->key_type) {                                                   
563                                                         case OID_KEY_TYPE_WRONG: {
564                                                                 proto_item* pi = proto_tree_add_text(pt_name,tvb,0,0,"OID instaces not handled, if you want this implemented please contact the wireshark developpers");
565                                                                 expert_add_info_format(actx->pinfo, pi, PI_UNDECODED, PI_WARN, "Unimplemented instance index");
566                                                                 oid_info_is_ok = FALSE;
567                                                                 goto indexing_done;
568                                                         }
569                                                         case OID_KEY_TYPE_INTEGER: {
570                                                                 proto_tree_add_int(pt_name,k->hfid,tvb,name_offset,name_len,(guint)subids[key_start]);
571                                                                 key_start++;
572                                                                 key_len--;
573                                                                 continue; /* k->next */
574                                                         }
575                                                         case OID_KEY_TYPE_IMPLIED_OID:
576                                                                 suboid_len = key_len;
577
578                                                                 goto show_oid_index;
579                                                                 
580                                                         case OID_KEY_TYPE_OID: {
581                                                                 guint8* suboid_buf;
582                                                                 guint suboid_buf_len;
583                                                                 guint32* suboid;
584
585                                                                 suboid_len = subids[key_start++];
586                                                                 key_len--;
587                                                                 
588 show_oid_index:
589                                                                 suboid = &(subids[key_start]);
590
591                                                                 if( suboid_len == 0 ) {
592                                                                         proto_item* pi = proto_tree_add_text(pt_name,tvb,0,0,"an index sub-oid OID cannot be 0 bytes long!");
593                                                                         expert_add_info_format(actx->pinfo, pi, PI_MALFORMED, PI_WARN, "index sub-oid OID with len=0");
594                                                                         oid_info_is_ok = FALSE;
595                                                                         goto indexing_done;
596                                                                 }
597                                                                 
598                                                                 if( key_len < suboid_len ) {
599                                                                         proto_item* pi = proto_tree_add_text(pt_name,tvb,0,0,"index sub-oid should not be longer than remaining oid size");
600                                                                         expert_add_info_format(actx->pinfo, pi, PI_MALFORMED, PI_WARN, "index sub-oid longer than remaining oid size");
601                                                                         oid_info_is_ok = FALSE;
602                                                                         goto indexing_done;
603                                                                 }
604                                                                 
605                                                                 suboid_buf_len = oid_subid2encoded(suboid_len, suboid, &suboid_buf);
606                                                                 
607                                                                 DISSECTOR_ASSERT(suboid_buf_len);
608
609                                                                 proto_tree_add_oid(pt_name,k->hfid,tvb,name_offset, suboid_buf_len, suboid_buf);
610                                                                 
611                                                                 key_start += suboid_len;
612                                                                 key_len -= suboid_len + 1;
613                                                                 continue; /* k->next */
614                                                         }
615                                                         default: {
616                                                                 guint8* buf;
617                                                                 guint buf_len;
618                                                                 guint32* suboid;
619                                                                 guint i;
620                                                                 
621                                                                 
622                                                                 switch (k->key_type) {
623                                                                         case OID_KEY_TYPE_IPADDR:
624                                                                                 suboid = &(subids[key_start]);
625                                                                                 buf_len = 4;
626                                                                                 break;
627                                                                         case OID_KEY_TYPE_IMPLIED_STRING:
628                                                                         case OID_KEY_TYPE_IMPLIED_BYTES:
629                                                                                 suboid = &(subids[key_start]);
630                                                                                 buf_len = key_len;
631                                                                                 break;
632                                                                         default:
633                                                                                 buf_len = k->num_subids;
634                                                                                 suboid = &(subids[key_start]);
635                                                                                 
636                                                                                 if(!buf_len) {
637                                                                                         buf_len = *suboid++;
638                                                                                         key_len--;
639                                                                                         key_start++;
640                                                                                 }
641                                                                                 break;
642                                                                 } 
643                                                                 
644                                                                 if( key_len < buf_len ) {
645                                                                         proto_item* pi = proto_tree_add_text(pt_name,tvb,0,0,"index string should not be longer than remaining oid size");
646                                                                         expert_add_info_format(actx->pinfo, pi, PI_MALFORMED, PI_WARN, "index string longer than remaining oid size");
647                                                                         oid_info_is_ok = FALSE;
648                                                                         goto indexing_done;
649                                                                 }
650                                                                 
651                                                                 buf = ep_alloc(buf_len+1);
652                                                                 for (i = 0; i < buf_len; i++)
653                                                                         buf[i] = (guint8)suboid[i];
654                                                                 buf[i] = '\0';
655                                                                 
656                                                                 switch(k->key_type) {
657                                                                         case OID_KEY_TYPE_STRING:
658                                                                         case OID_KEY_TYPE_IMPLIED_STRING:
659                                                                                 proto_tree_add_string(pt_name,k->hfid,tvb,name_offset,buf_len, buf);
660                                                                                 break;
661                                                                         case OID_KEY_TYPE_BYTES:
662                                                                         case OID_KEY_TYPE_NSAP:
663                                                                         case OID_KEY_TYPE_IMPLIED_BYTES: 
664                                                                                 proto_tree_add_bytes(pt_name,k->hfid,tvb,name_offset,buf_len, buf);
665                                                                                 break;
666                                                                         case OID_KEY_TYPE_IPADDR: {
667                                                                                 guint32* ipv4_p = (void*)buf;
668                                                                                 proto_tree_add_ipv4(pt_name,k->hfid,tvb,name_offset,buf_len, *ipv4_p);
669                                                                                 break;
670                                                                         default:
671                                                                                 DISSECTOR_ASSERT_NOT_REACHED();
672                                                                                 break;
673                                                                         }
674                                                                 }
675                                                                 
676                                                                 key_start += buf_len;
677                                                                 key_len -= buf_len;
678                                                                 continue; /* k->next*/
679                                                         }
680                                                 }
681                                         }
682                                         goto indexing_done;
683                                 } else {
684                                         proto_item* pi = proto_tree_add_text(pt_name,tvb,0,0,"We do not know how to handle this OID, if you want this implemented please contact the wireshark developers");
685                                         expert_add_info_format(actx->pinfo, pi, PI_UNDECODED, PI_WARN, "Unimplemented instance index");
686                                         oid_info_is_ok = FALSE;
687                                         goto indexing_done;
688                                 }
689                         } else {
690                                 proto_item* pi = proto_tree_add_text(pt_name,tvb,0,0,"The COLUMS's parent is not a ROW. This is a BUG! please contact the wireshark developers.");
691                                 expert_add_info_format(actx->pinfo, pi, PI_MALFORMED, PI_ERROR, "COLUMS's parent is not a ROW");
692                                 oid_info_is_ok = FALSE;
693                                 goto indexing_done;
694                         }
695                 default: {
696 /*                      proto_item* pi = proto_tree_add_text(pt_name,tvb,0,0,"This kind OID should have no value");
697                         expert_add_info_format(actx->pinfo, pi, PI_MALFORMED, PI_WARN, "This kind OID should have no value"); */
698                         oid_info_is_ok = FALSE;
699                         goto indexing_done;
700                 }
701         }
702 indexing_done:
703         
704         if (oid_info_is_ok) {
705                 if (ber_class == BER_CLASS_UNI && tag == BER_UNI_TAG_NULL) {
706                         pi_value = proto_tree_add_item(pt_varbind,hf_snmp_unSpecified,tvb,value_offset,value_len,FALSE);
707                 }  else {
708                         if ((oid_info->value_type->ber_class != BER_CLASS_ANY) &&
709                                 (ber_class != oid_info->value_type->ber_class))
710                                 format_error = WRONG_TAG;
711                         
712                         if ((oid_info->value_type->ber_tag != BER_TAG_ANY) &&
713                                 (tag != oid_info->value_type->ber_tag))
714                                 format_error = WRONG_TAG;
715                         
716                         max_len = oid_info->value_type->max_len == -1 ? 0xffffff : oid_info->value_type->max_len;
717                         min_len  = oid_info->value_type->min_len;
718                         
719                         if ((int)value_len < min_len || (int)value_len > max_len)
720                                 format_error = WRONG_LENGTH;
721                         
722                         pi_value = proto_tree_add_item(pt_varbind,oid_info->value_hfid,tvb,value_offset,value_len,FALSE);
723                 }
724         } else {
725                 switch(ber_class|(tag<<4)) {
726                         case BER_CLASS_UNI|(BER_UNI_TAG_INTEGER<<4):
727                                 max_len = 4; min_len = 1;
728                                 if (value_len > (guint)max_len && value_len < (guint)min_len) format_error = WRONG_LENGTH; 
729                                 hfid = hf_snmp_integer32_value;
730                                 break;
731                         case BER_CLASS_UNI|(BER_UNI_TAG_OCTETSTRING<<4):
732                                 hfid = hf_snmp_octestring_value;
733                                 break;
734                         case BER_CLASS_UNI|(BER_UNI_TAG_OID<<4):
735                                 max_len = -1; min_len = 1;
736                                 if (value_len < (guint)min_len) format_error = WRONG_LENGTH; 
737                                 hfid = hf_snmp_oid_value;
738                                 break;
739                         case BER_CLASS_UNI|(BER_UNI_TAG_NULL<<4):
740                                 max_len = 0; min_len = 0;
741                                 if (value_len != 0) format_error = WRONG_LENGTH; 
742                                 hfid = hf_snmp_null_value;
743                                 break;
744                         case BER_CLASS_APP: /* | (SNMP_IPA<<4)*/
745                                 switch(value_len) {
746                                         case 4: hfid = hf_snmp_ipv4_value; break;
747                                         case 16: hfid = hf_snmp_ipv6_value; break;
748                                         default: hfid = hf_snmp_anyaddress_value; break;
749                                 }
750                                 break;
751                         case BER_CLASS_APP|(SNMP_U32<<4):
752                                 hfid = hf_snmp_unsigned32_value;
753                                 break;
754                         case BER_CLASS_APP|(SNMP_GGE<<4):
755                                 hfid = hf_snmp_gauge32_value;
756                                 break;
757                         case BER_CLASS_APP|(SNMP_CNT<<4):
758                                 hfid = hf_snmp_counter_value;
759                                 break;
760                         case BER_CLASS_APP|(SNMP_TIT<<4):
761                                 hfid = hf_snmp_timeticks_value;
762                                 break;
763                         case BER_CLASS_APP|(SNMP_OPQ<<4):
764                                 hfid = hf_snmp_opaque_value;
765                                 break;
766                         case BER_CLASS_APP|(SNMP_NSP<<4):
767                                 hfid = hf_snmp_nsap_value;
768                                 break;
769                         case BER_CLASS_APP|(SNMP_C64<<4):
770                                 hfid = hf_snmp_big_counter_value;
771                                 break;
772                         default: 
773                                 hfid = hf_snmp_unknown_value;
774                                 break;
775                 }
776                 
777                 pi_value = proto_tree_add_item(pt_varbind,hfid,tvb,value_offset,value_len,FALSE);
778                 expert_add_info_format(actx->pinfo, pi_value, PI_UNDECODED, PI_NOTE, "Unresolved value, Missing MIB");
779                 oid_info_is_ok = FALSE;
780         } 
781         
782         pt_value = proto_item_add_subtree(pi_value,ett_value);
783         
784         if (value_len > 0 && oid_string) {
785                 tvbuff_t* sub_tvb = tvb_new_subset(tvb, value_offset, value_len, value_len);
786                 
787                 next_tvb_add_string(&var_list, sub_tvb, (snmp_var_in_tree) ? pt_value : NULL, value_sub_dissectors_table, oid_string);
788         }
789         
790         
791 set_label:
792         if (pi_value) proto_item_fill_label(pi_value->finfo, label);
793         
794         if (oid_info && oid_info->name) {
795                 if (oid_left >= 1) {
796                         repr  = ep_strdup_printf("%s.%s (%s)",
797                                                                          oid_info->name,
798                                                                          oid_subid2string(&(subids[oid_matched]),oid_left),
799                                                                          oid_subid2string(subids,oid_matched+oid_left));
800                 } else {
801                         repr  = ep_strdup_printf("%s (%s)",
802                                                                          oid_info->name,
803                                                                          oid_subid2string(subids,oid_matched));
804                 }
805         } else {
806                 repr  = ep_strdup_printf("%s", oid_string);                     
807         }
808         
809         valstr = strstr(label,": ");
810         valstr = valstr ? valstr+2 : label;
811         
812         proto_item_set_text(pi_varbind,"%s: %s",repr,valstr);
813         
814         switch (format_error) {
815                 case WRONG_LENGTH: {
816                         proto_tree* pt = proto_item_add_subtree(pi_value,ett_decoding_error);
817                         proto_item* pi = proto_tree_add_text(pt,tvb,0,0,"Wrong value length: %u  expecting: %u <= len <= %u",
818                                                                                                  value_len,
819                                                                                                  min_len,
820                                                                                                  max_len == -1 ? 0xFFFFFF : max_len);
821                         pt = proto_item_add_subtree(pi,ett_decoding_error);
822                         expert_add_info_format(actx->pinfo, pi, PI_MALFORMED, PI_WARN, "Wrong length for SNMP VarBind/value");
823                         return dissect_unknown_ber(actx->pinfo, tvb, value_start, pt);
824                 }
825                 case WRONG_TAG: {
826                         proto_tree* pt = proto_item_add_subtree(pi_value,ett_decoding_error);
827                         proto_item* pi = proto_tree_add_text(pt,tvb,0,0,"Wrong class/tag for Value expected: %d,%d got: %d,%d",
828                                                                                                  oid_info->value_type->ber_class,
829                                                                                                  oid_info->value_type->ber_tag,
830                                                                                                  ber_class,
831                                                                                                  tag);
832                         pt = proto_item_add_subtree(pi,ett_decoding_error);
833                         expert_add_info_format(actx->pinfo, pi, PI_MALFORMED, PI_WARN, "Wrong class/tag for SNMP VarBind/value");
834                         return dissect_unknown_ber(actx->pinfo, tvb, value_start, pt);
835                 }
836                 default:
837                         break;
838         }
839         
840         return seq_offset + seq_len;
841 }
842
843
844 #define F_SNMP_ENGINEID_CONFORM 0x80
845 #define SNMP_ENGINEID_RFC1910 0x00
846 #define SNMP_ENGINEID_RFC3411 0x01
847
848 static const true_false_string tfs_snmp_engineid_conform = {
849   "RFC3411 (SNMPv3)",
850   "RFC1910 (Non-SNMPv3)"
851 };
852
853 #define SNMP_ENGINEID_FORMAT_IPV4 0x01
854 #define SNMP_ENGINEID_FORMAT_IPV6 0x02
855 #define SNMP_ENGINEID_FORMAT_MACADDRESS 0x03
856 #define SNMP_ENGINEID_FORMAT_TEXT 0x04
857 #define SNMP_ENGINEID_FORMAT_OCTETS 0x05
858
859 static const value_string snmp_engineid_format_vals[] = {
860         { SNMP_ENGINEID_FORMAT_IPV4,    "IPv4 address" },
861         { SNMP_ENGINEID_FORMAT_IPV6,    "IPv6 address" },
862         { SNMP_ENGINEID_FORMAT_MACADDRESS,      "MAC address" },
863         { SNMP_ENGINEID_FORMAT_TEXT,    "Text, administratively assigned" },
864         { SNMP_ENGINEID_FORMAT_OCTETS,  "Octets, administratively assigned" },
865         { 0,    NULL }
866 };
867
868 /*
869  * SNMP Engine ID dissection according to RFC 3411 (SnmpEngineID TC)
870  * or historic RFC 1910 (AgentID)
871  */
872 int dissect_snmp_engineid(proto_tree *tree, tvbuff_t *tvb, int offset, int len) {
873     proto_item *item = NULL;
874     guint8 conformance, format;
875     guint32 enterpriseid, seconds;
876     nstime_t ts;
877     int len_remain = len;
878
879     /* first bit: engine id conformance */
880     if (len_remain<4) return offset;
881     conformance = ((tvb_get_guint8(tvb, offset)>>7) && 0x01);
882     proto_tree_add_item(tree, hf_snmp_engineid_conform, tvb, offset, 1, FALSE);
883
884     /* 4-byte enterprise number/name */
885     if (len_remain<4) return offset;
886     enterpriseid = tvb_get_ntohl(tvb, offset);
887     if (conformance)
888       enterpriseid -= 0x80000000; /* ignore first bit */
889     proto_tree_add_uint(tree, hf_snmp_engineid_enterprise, tvb, offset, 4, enterpriseid);
890     offset+=4;
891     len_remain-=4;
892
893     switch(conformance) {
894
895     case SNMP_ENGINEID_RFC1910:
896       /* 12-byte AgentID w/ 8-byte trailer */
897       if (len_remain==8) {
898         proto_tree_add_text(tree, tvb, offset, 8, "AgentID Trailer: 0x%s",
899                             tvb_bytes_to_str(tvb, offset, 8));
900         offset+=8;
901         len_remain-=8;
902       } else {
903         proto_tree_add_text(tree, tvb, offset, len_remain, "<Data not conforming to RFC1910>");
904         return offset;
905       }
906       break;
907
908     case SNMP_ENGINEID_RFC3411: /* variable length: 5..32 */
909
910       /* 1-byte format specifier */
911       if (len_remain<1) return offset;
912       format = tvb_get_guint8(tvb, offset);
913       item = proto_tree_add_uint_format(tree, hf_snmp_engineid_format, tvb, offset, 1, format, "Engine ID Format: %s (%d)",
914                           val_to_str(format, snmp_engineid_format_vals, "Reserved/Enterprise-specific"), format);
915       offset+=1;
916       len_remain-=1;
917
918       switch(format) {
919       case SNMP_ENGINEID_FORMAT_IPV4:
920         /* 4-byte IPv4 address */
921         if (len_remain==4) {
922           proto_tree_add_item(tree, hf_snmp_engineid_ipv4, tvb, offset, 4, FALSE);
923           offset+=4;
924           len_remain=0;
925         }
926         break;
927       case SNMP_ENGINEID_FORMAT_IPV6:
928         /* 16-byte IPv6 address */
929         if (len_remain==16) {
930           proto_tree_add_item(tree, hf_snmp_engineid_ipv6, tvb, offset, 16, FALSE);
931           offset+=16;
932           len_remain=0;
933         }
934         break;
935       case SNMP_ENGINEID_FORMAT_MACADDRESS:
936         /* 6-byte MAC address */
937         if (len_remain==6) {
938           proto_tree_add_item(tree, hf_snmp_engineid_mac, tvb, offset, 6, FALSE);
939           offset+=6;
940           len_remain=0;
941         }
942         break;
943       case SNMP_ENGINEID_FORMAT_TEXT:
944         /* max. 27-byte string, administratively assigned */
945         if (len_remain<=27) {
946           proto_tree_add_item(tree, hf_snmp_engineid_text, tvb, offset, len_remain, FALSE);
947           offset+=len_remain;
948           len_remain=0;
949         }
950         break;
951       case 128:
952         /* most common enterprise-specific format: (ucd|net)-snmp random */
953         if ((enterpriseid==2021)||(enterpriseid==8072)) {
954           proto_item_append_text(item, (enterpriseid==2021) ? ": UCD-SNMP Random" : ": Net-SNMP Random");
955           /* demystify: 4B random, 4B epoch seconds */
956           if (len_remain==8) {
957             proto_tree_add_item(tree, hf_snmp_engineid_data, tvb, offset, 4, FALSE);
958             seconds = tvb_get_letohl(tvb, offset+4);
959             ts.secs = seconds;
960             proto_tree_add_time_format(tree, hf_snmp_engineid_time, tvb, offset+4, 4,
961                                   &ts, "Engine ID Data: Creation Time: %s",
962                                   abs_time_secs_to_str(seconds));
963             offset+=8;
964             len_remain=0;
965           }
966         }
967         break;
968       case SNMP_ENGINEID_FORMAT_OCTETS:
969       default:
970         /* max. 27 bytes, administratively assigned or unknown format */
971         if (len_remain<=27) {
972           proto_tree_add_item(tree, hf_snmp_engineid_data, tvb, offset, len_remain, FALSE);
973           offset+=len_remain;
974           len_remain=0;
975         }
976         break;
977       }
978     }
979
980     if (len_remain>0) {
981       proto_tree_add_text(tree, tvb, offset, len_remain, "<Data not conforming to RFC3411>");
982       offset+=len_remain;
983     }
984     return offset;
985 }
986
987
988 static void set_ue_keys(snmp_ue_assoc_t* n ) {
989         guint key_size = n->user.authModel->key_size;
990
991         n->user.authKey.data = se_alloc(key_size);
992         n->user.authKey.len = key_size;
993         n->user.authModel->pass2key(n->user.authPassword.data,
994                                                                 n->user.authPassword.len,
995                                                                 n->engine.data,
996                                                                 n->engine.len,
997                                                                 n->user.authKey.data);
998
999         n->user.privKey.data = se_alloc(key_size);
1000         n->user.privKey.len = key_size;
1001         n->user.authModel->pass2key(n->user.privPassword.data,
1002                                                                 n->user.privPassword.len,
1003                                                                 n->engine.data,
1004                                                                 n->engine.len,
1005                                                                 n->user.privKey.data);
1006 }
1007
1008 static snmp_ue_assoc_t* ue_se_dup(snmp_ue_assoc_t* o) {
1009         snmp_ue_assoc_t* d = se_memdup(o,sizeof(snmp_ue_assoc_t));
1010
1011         d->user.authModel = o->user.authModel;
1012
1013         d->user.privProtocol = o->user.privProtocol;
1014
1015         d->user.userName.data = se_memdup(o->user.userName.data,o->user.userName.len);
1016         d->user.userName.len = o->user.userName.len;
1017
1018         d->user.authPassword.data = o->user.authPassword.data ? se_memdup(o->user.authPassword.data,o->user.authPassword.len) : NULL;
1019         d->user.authPassword.len = o->user.authPassword.len;
1020
1021         d->user.privPassword.data = o->user.privPassword.data ? se_memdup(o->user.privPassword.data,o->user.privPassword.len) : NULL;
1022         d->user.privPassword.len = o->user.privPassword.len;
1023
1024         d->engine.len = o->engine.len;
1025
1026         if (d->engine.len) {
1027                 d->engine.data = se_memdup(o->engine.data,o->engine.len);
1028                 set_ue_keys(d);
1029         }
1030
1031         return d;
1032
1033 }
1034
1035
1036 #define CACHE_INSERT(c,a) if (c) { snmp_ue_assoc_t* t = c; c = a; c->next = t; } else { c = a; a->next = NULL; }
1037
1038 static void renew_ue_cache(void) {
1039         if (num_ueas) {
1040                 guint i;
1041
1042                 localized_ues = NULL;
1043                 unlocalized_ues = NULL;
1044
1045                 for(i = 0; i < num_ueas; i++) {
1046                         snmp_ue_assoc_t* a = ue_se_dup(&(ueas[i]));
1047
1048                         if (a->engine.len) {
1049                                 CACHE_INSERT(localized_ues,a);
1050
1051                         } else {
1052                                 CACHE_INSERT(unlocalized_ues,a);
1053                         }
1054
1055                 }
1056         } else {
1057                 localized_ues = NULL;
1058                 unlocalized_ues = NULL;
1059         }
1060 }
1061
1062
1063 static snmp_ue_assoc_t* localize_ue( snmp_ue_assoc_t* o, const guint8* engine, guint engine_len ) {
1064         snmp_ue_assoc_t* n = se_memdup(o,sizeof(snmp_ue_assoc_t));
1065
1066         n->engine.data = se_memdup(engine,engine_len);
1067         n->engine.len = engine_len;
1068
1069         set_ue_keys(n);
1070
1071         return n;
1072 }
1073
1074
1075 #define localized_match(a,u,ul,e,el) \
1076         ( a->user.userName.len == ul \
1077         && a->engine.len == el \
1078         && memcmp( a->user.userName.data, u, (a->user.userName.len < ul) ? a->user.userName.len : ul ) == 0 \
1079         && memcmp( a->engine.data,   e, (a->engine.len   < el) ? a->engine.len   : el ) == 0 )
1080
1081 #define unlocalized_match(a,u,l) \
1082         ( a->user.userName.len == l && memcmp( a->user.userName.data, u, a->user.userName.len < l ? a->user.userName.len : l) == 0 )
1083
1084 static snmp_ue_assoc_t* get_user_assoc(tvbuff_t* engine_tvb, tvbuff_t* user_tvb) {
1085         static snmp_ue_assoc_t* a;
1086         guint given_username_len;
1087         guint8* given_username;
1088         guint given_engine_len;
1089         guint8* given_engine;
1090
1091         if ( ! (localized_ues || unlocalized_ues ) ) return NULL;
1092
1093         if (! ( user_tvb && engine_tvb ) ) return NULL;
1094
1095         given_username_len = tvb_length_remaining(user_tvb,0);
1096         given_username = ep_tvb_memdup(user_tvb,0,-1);
1097         given_engine_len = tvb_length_remaining(engine_tvb,0);
1098         given_engine = ep_tvb_memdup(engine_tvb,0,-1);
1099
1100         for (a = localized_ues; a; a = a->next) {
1101                 if ( localized_match(a, given_username, given_username_len, given_engine, given_engine_len) ) {
1102                         return a;
1103                 }
1104         }
1105
1106         for (a = unlocalized_ues; a; a = a->next) {
1107                 if ( unlocalized_match(a, given_username, given_username_len) ) {
1108                         snmp_ue_assoc_t* n = localize_ue( a, given_engine, given_engine_len );
1109                         CACHE_INSERT(localized_ues,n);
1110                         return n;
1111                 }
1112         }
1113
1114         return NULL;
1115 }
1116
1117 static gboolean snmp_usm_auth_md5(snmp_usm_params_t* p, guint8** calc_auth_p, guint* calc_auth_len_p, gchar const** error) {
1118         guint msg_len;
1119         guint8* msg;
1120         guint auth_len;
1121         guint8* auth;
1122         guint8* key;
1123         guint key_len;
1124         guint8 calc_auth[16];
1125         guint start;
1126         guint end;
1127         guint i;
1128
1129         if (!p->auth_tvb) {
1130                 *error = "No Authenticator";
1131                 return FALSE;
1132         }
1133
1134         key = p->user_assoc->user.authKey.data;
1135         key_len = p->user_assoc->user.authKey.len;
1136
1137         if (! key ) {
1138                 *error = "User has no authKey";
1139                 return FALSE;
1140         }
1141
1142
1143         auth_len = tvb_length_remaining(p->auth_tvb,0);
1144
1145         if (auth_len != 12) {
1146                 *error = "Authenticator length wrong";
1147                 return FALSE;
1148         }
1149
1150         msg_len = tvb_length_remaining(p->msg_tvb,0);
1151         msg = ep_tvb_memdup(p->msg_tvb,0,msg_len);
1152
1153
1154         auth = ep_tvb_memdup(p->auth_tvb,0,auth_len);
1155
1156         start = p->auth_offset - p->start_offset;
1157         end =   start + auth_len;
1158
1159         /* fill the authenticator with zeros */
1160         for ( i = start ; i < end ; i++ ) {
1161                 msg[i] = '\0';
1162         }
1163
1164         md5_hmac(msg, msg_len, key, key_len, calc_auth);
1165
1166         if (calc_auth_p) *calc_auth_p = calc_auth;
1167         if (calc_auth_len_p) *calc_auth_len_p = 12;
1168
1169         return ( memcmp(auth,calc_auth,12) != 0 ) ? FALSE : TRUE;
1170 }
1171
1172
1173 static gboolean snmp_usm_auth_sha1(snmp_usm_params_t* p _U_, guint8** calc_auth_p, guint* calc_auth_len_p,  gchar const** error _U_) {
1174         guint msg_len;
1175         guint8* msg;
1176         guint auth_len;
1177         guint8* auth;
1178         guint8* key;
1179         guint key_len;
1180         guint8 calc_auth[20];
1181         guint start;
1182         guint end;
1183         guint i;
1184
1185         if (!p->auth_tvb) {
1186                 *error = "No Authenticator";
1187                 return FALSE;
1188         }
1189
1190         key = p->user_assoc->user.authKey.data;
1191         key_len = p->user_assoc->user.authKey.len;
1192
1193         if (! key ) {
1194                 *error = "User has no authKey";
1195                 return FALSE;
1196         }
1197
1198
1199         auth_len = tvb_length_remaining(p->auth_tvb,0);
1200
1201
1202         if (auth_len != 12) {
1203                 *error = "Authenticator length wrong";
1204                 return FALSE;
1205         }
1206
1207         msg_len = tvb_length_remaining(p->msg_tvb,0);
1208         msg = ep_tvb_memdup(p->msg_tvb,0,msg_len);
1209
1210         auth = ep_tvb_memdup(p->auth_tvb,0,auth_len);
1211
1212         start = p->auth_offset - p->start_offset;
1213         end =   start + auth_len;
1214
1215         /* fill the authenticator with zeros */
1216         for ( i = start ; i < end ; i++ ) {
1217                 msg[i] = '\0';
1218         }
1219
1220         sha1_hmac(key, key_len, msg, msg_len, calc_auth);
1221
1222         if (calc_auth_p) *calc_auth_p = calc_auth;
1223         if (calc_auth_len_p) *calc_auth_len_p = 12;
1224
1225         return ( memcmp(auth,calc_auth,12) != 0 ) ? FALSE : TRUE;
1226 }
1227
1228 static tvbuff_t* snmp_usm_priv_des(snmp_usm_params_t* p _U_, tvbuff_t* encryptedData _U_, gchar const** error _U_) {
1229 #ifdef HAVE_LIBGCRYPT
1230     gcry_error_t err;
1231     gcry_cipher_hd_t hd = NULL;
1232
1233         guint8* cleartext;
1234         guint8* des_key = p->user_assoc->user.privKey.data; /* first 8 bytes */
1235         guint8* pre_iv = &(p->user_assoc->user.privKey.data[8]); /* last 8 bytes */
1236         guint8* salt;
1237         gint salt_len;
1238         gint cryptgrm_len;
1239         guint8* cryptgrm;
1240         tvbuff_t* clear_tvb;
1241         guint8 iv[8];
1242         guint i;
1243
1244
1245         salt_len = tvb_length_remaining(p->priv_tvb,0);
1246
1247         if (salt_len != 8)  {
1248                 *error = "decryptionError: msgPrivacyParameters length != 8";
1249                 return NULL;
1250         }
1251
1252         salt = ep_tvb_memdup(p->priv_tvb,0,salt_len);
1253
1254         /*
1255          The resulting "salt" is XOR-ed with the pre-IV to obtain the IV.
1256          */
1257         for (i=0; i<8; i++) {
1258                 iv[i] = pre_iv[i] ^ salt[i];
1259         }
1260
1261         cryptgrm_len = tvb_length_remaining(encryptedData,0);
1262
1263         if (cryptgrm_len % 8) {
1264                 *error = "decryptionError: the length of the encrypted data is not a mutiple of 8 octets";
1265                 return NULL;
1266         }
1267
1268         cryptgrm = ep_tvb_memdup(encryptedData,0,-1);
1269
1270         cleartext = ep_alloc(cryptgrm_len);
1271
1272         err = gcry_cipher_open(&hd, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_CBC, 0);
1273         if (err != GPG_ERR_NO_ERROR) goto on_gcry_error;
1274
1275     err = gcry_cipher_setiv(hd, iv, 8);
1276         if (err != GPG_ERR_NO_ERROR) goto on_gcry_error;
1277
1278         err = gcry_cipher_setkey(hd,des_key,8);
1279         if (err != GPG_ERR_NO_ERROR) goto on_gcry_error;
1280
1281         err = gcry_cipher_decrypt(hd, cleartext, cryptgrm_len, cryptgrm, cryptgrm_len);
1282         if (err != GPG_ERR_NO_ERROR) goto on_gcry_error;
1283
1284         gcry_cipher_close(hd);
1285
1286         clear_tvb = tvb_new_real_data(cleartext, cryptgrm_len, cryptgrm_len);
1287
1288         return clear_tvb;
1289
1290 on_gcry_error:
1291         *error = (void*)gpg_strerror(err);
1292         if (hd) gcry_cipher_close(hd);
1293         return NULL;
1294 #else
1295         *error = "libgcrypt not present, cannot decrypt";
1296         return NULL;
1297 #endif
1298 }
1299
1300 static tvbuff_t* snmp_usm_priv_aes(snmp_usm_params_t* p _U_, tvbuff_t* encryptedData _U_, gchar const** error _U_) {
1301 #ifdef HAVE_LIBGCRYPT
1302     gcry_error_t err;
1303     gcry_cipher_hd_t hd = NULL;
1304
1305         guint8* cleartext;
1306         guint8* aes_key = p->user_assoc->user.privKey.data; /* first 16 bytes */
1307         guint8 iv[16];
1308         gint priv_len;
1309         gint cryptgrm_len;
1310         guint8* cryptgrm;
1311         tvbuff_t* clear_tvb;
1312
1313         priv_len = tvb_length_remaining(p->priv_tvb,0);
1314
1315         if (priv_len != 8)  {
1316                 *error = "decryptionError: msgPrivacyParameters length != 8";
1317                 return NULL;
1318         }
1319
1320         iv[0] = (p->boots & 0xff000000) >> 24;
1321         iv[1] = (p->boots & 0x00ff0000) >> 16;
1322         iv[2] = (p->boots & 0x0000ff00) >> 8;
1323         iv[3] = (p->boots & 0x000000ff);
1324         iv[4] = (p->time & 0xff000000) >> 24;
1325         iv[5] = (p->time & 0x00ff0000) >> 16;
1326         iv[6] = (p->time & 0x0000ff00) >> 8;
1327         iv[7] = (p->time & 0x000000ff);
1328         tvb_memcpy(p->priv_tvb,&(iv[8]),0,8);
1329
1330         cryptgrm_len = tvb_length_remaining(encryptedData,0);
1331         cryptgrm = ep_tvb_memdup(encryptedData,0,-1);
1332
1333         cleartext = ep_alloc(cryptgrm_len);
1334
1335         err = gcry_cipher_open(&hd, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CFB, 0);
1336         if (err != GPG_ERR_NO_ERROR) goto on_gcry_error;
1337
1338     err = gcry_cipher_setiv(hd, iv, 16);
1339         if (err != GPG_ERR_NO_ERROR) goto on_gcry_error;
1340
1341         err = gcry_cipher_setkey(hd,aes_key,16);
1342         if (err != GPG_ERR_NO_ERROR) goto on_gcry_error;
1343
1344         err = gcry_cipher_decrypt(hd, cleartext, cryptgrm_len, cryptgrm, cryptgrm_len);
1345         if (err != GPG_ERR_NO_ERROR) goto on_gcry_error;
1346
1347         gcry_cipher_close(hd);
1348
1349         clear_tvb = tvb_new_real_data(cleartext, cryptgrm_len, cryptgrm_len);
1350
1351         return clear_tvb;
1352
1353 on_gcry_error:
1354         *error = (void*)gpg_strerror(err);
1355         if (hd) gcry_cipher_close(hd);
1356         return NULL;
1357 #else
1358         *error = "libgcrypt not present, cannot decrypt";
1359         return NULL;
1360 #endif
1361 }
1362
1363
1364 gboolean check_ScopedPdu(tvbuff_t* tvb) {
1365         int offset;
1366         gint8 class;
1367         gboolean pc;
1368         gint32 tag;
1369         int hoffset, eoffset;
1370         guint32 len;
1371
1372         offset = get_ber_identifier(tvb, 0, &class, &pc, &tag);
1373         offset = get_ber_length(tvb, offset, NULL, NULL);
1374
1375         if ( ! (((class!=BER_CLASS_APP) && (class!=BER_CLASS_PRI) )
1376                         && ( (!pc) || (class!=BER_CLASS_UNI) || (tag!=BER_UNI_TAG_ENUMERATED) )
1377                         )) return FALSE;
1378
1379         if((tvb_get_guint8(tvb, offset)==0)&&(tvb_get_guint8(tvb, offset+1)==0))
1380                 return TRUE;
1381
1382         hoffset = offset;
1383
1384         offset = get_ber_identifier(tvb, offset, &class, &pc, &tag);
1385         offset = get_ber_length(tvb, offset, &len, NULL);
1386         eoffset = offset + len;
1387
1388         if (eoffset <= hoffset) return FALSE;
1389
1390         if ((class!=BER_CLASS_APP)&&(class!=BER_CLASS_PRI))
1391                 if( (class!=BER_CLASS_UNI)
1392                         ||((tag<BER_UNI_TAG_NumericString)&&(tag!=BER_UNI_TAG_OCTETSTRING)&&(tag!=BER_UNI_TAG_UTF8String)) )
1393                         return FALSE;
1394
1395         return TRUE;
1396
1397 }
1398
1399 #include "packet-snmp-fn.c"
1400
1401
1402 guint
1403 dissect_snmp_pdu(tvbuff_t *tvb, int offset, packet_info *pinfo,
1404     proto_tree *tree, int proto, gint ett, gboolean is_tcp)
1405 {
1406
1407         guint length_remaining;
1408         gint8 class;
1409         gboolean pc, ind = 0;
1410         gint32 tag;
1411         guint32 len;
1412         guint message_length;
1413         int start_offset = offset;
1414         guint32 version = 0;
1415
1416         proto_tree *snmp_tree = NULL;
1417         proto_item *item = NULL;
1418         asn1_ctx_t asn1_ctx;
1419         asn1_ctx_init(&asn1_ctx, ASN1_ENC_BER, TRUE, pinfo);
1420
1421
1422         usm_p.msg_tvb = tvb;
1423         usm_p.start_offset = offset_from_real_beginning(tvb,0) ;
1424         usm_p.engine_tvb = NULL;
1425         usm_p.user_tvb = NULL;
1426         usm_p.auth_item = NULL;
1427         usm_p.auth_tvb = NULL;
1428         usm_p.auth_offset = 0;
1429         usm_p.priv_tvb = NULL;
1430         usm_p.user_assoc = NULL;
1431         usm_p.authenticated = FALSE;
1432         usm_p.encrypted = FALSE;
1433         usm_p.boots = 0;
1434         usm_p.time = 0;
1435         usm_p.authOK = FALSE;
1436
1437         /*
1438          * This will throw an exception if we don't have any data left.
1439          * That's what we want.  (See "tcp_dissect_pdus()", which is
1440          * similar, but doesn't have to deal with ASN.1.
1441          * XXX - can we make "tcp_dissect_pdus()" provide enough
1442          * information to the "get_pdu_len" routine so that we could
1443          * have that routine deal with ASN.1, and just use
1444          * "tcp_dissect_pdus()"?)
1445          */
1446         length_remaining = tvb_ensure_length_remaining(tvb, offset);
1447
1448         /* NOTE: we have to parse the message piece by piece, since the
1449          * capture length may be less than the message length: a 'global'
1450          * parsing is likely to fail.
1451          */
1452
1453         /*
1454          * If this is SNMP-over-TCP, we might have to do reassembly
1455          * in order to read the "Sequence Of" header.
1456          */
1457         if (is_tcp && snmp_desegment && pinfo->can_desegment) {
1458                 /*
1459                  * This is TCP, and we should, and can, do reassembly.
1460                  *
1461                  * Is the "Sequence Of" header split across segment
1462                  * boundaries?  We requre at least 6 bytes for the
1463                  * header, which allows for a 4-byte length (ASN.1
1464                  * BER).
1465                  */
1466                 if (length_remaining < 6) {
1467                         pinfo->desegment_offset = offset;
1468                         pinfo->desegment_len = 6 - length_remaining;
1469
1470                         /*
1471                          * Return 0, which means "I didn't dissect anything
1472                          * because I don't have enough data - we need
1473                          * to desegment".
1474                          */
1475                         return 0;
1476                 }
1477         }
1478
1479         /*
1480          * OK, try to read the "Sequence Of" header; this gets the total
1481          * length of the SNMP message.
1482          */
1483         /* Set tree to 0 to not display internakl BER fields if option used.*/
1484         offset = dissect_ber_identifier(pinfo, 0, tvb, offset, &class, &pc, &tag);
1485         offset = dissect_ber_length(pinfo, 0, tvb, offset, &len, &ind);
1486
1487         message_length = len + 2;
1488         offset = dissect_ber_integer(FALSE, &asn1_ctx, 0, tvb, offset, -1, &version);
1489
1490
1491         /*
1492          * If this is SNMP-over-TCP, we might have to do reassembly
1493          * to get all of this message.
1494          */
1495         if (is_tcp && snmp_desegment && pinfo->can_desegment) {
1496                 /*
1497                  * Yes - is the message split across segment boundaries?
1498                  */
1499                 if (length_remaining < message_length) {
1500                         /*
1501                          * Yes.  Tell the TCP dissector where the data
1502                          * for this message starts in the data it handed
1503                          * us, and how many more bytes we need, and
1504                          * return.
1505                          */
1506                         pinfo->desegment_offset = start_offset;
1507                         pinfo->desegment_len =
1508                             message_length - length_remaining;
1509
1510                         /*
1511                          * Return 0, which means "I didn't dissect anything
1512                          * because I don't have enough data - we need
1513                          * to desegment".
1514                          */
1515                         return 0;
1516                 }
1517         }
1518
1519         next_tvb_init(&var_list);
1520
1521         if (check_col(pinfo->cinfo, COL_PROTOCOL)) {
1522                 col_set_str(pinfo->cinfo, COL_PROTOCOL,
1523                     proto_get_protocol_short_name(find_protocol_by_id(proto)));
1524         }
1525
1526         if (tree) {
1527                 item = proto_tree_add_item(tree, proto, tvb, offset,
1528                     message_length, FALSE);
1529                 snmp_tree = proto_item_add_subtree(item, ett);
1530         }
1531
1532         switch (version){
1533         case 0: /* v1 */
1534         case 1: /* v2c */
1535                 offset = dissect_snmp_Message(FALSE , tvb, start_offset, &asn1_ctx, snmp_tree, -1);
1536                 break;
1537         case 2: /* v2u */
1538                 offset = dissect_snmp_Messagev2u(FALSE , tvb, start_offset, &asn1_ctx, snmp_tree, -1);
1539                 break;
1540                         /* v3 */
1541         case 3:
1542                 offset = dissect_snmp_SNMPv3Message(FALSE , tvb, start_offset, &asn1_ctx, snmp_tree, -1);
1543                 break;
1544         default:
1545                 /*
1546                  * Return the length remaining in the tvbuff, so
1547                  * if this is SNMP-over-TCP, our caller thinks there's
1548                  * nothing left to dissect.
1549                  */
1550                 proto_tree_add_text(snmp_tree, tvb, offset, -1,"Unknown version");
1551                 return length_remaining;
1552                 break;
1553         }
1554
1555         next_tvb_call(&var_list, pinfo, tree, NULL, data_handle);
1556
1557         return offset;
1558 }
1559
1560 static gint
1561 dissect_snmp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
1562 {
1563         conversation_t  *conversation;
1564         int offset;
1565         gint8 tmp_class;
1566         gboolean tmp_pc;
1567         gint32 tmp_tag;
1568         guint32 tmp_length;
1569         gboolean tmp_ind;
1570
1571         /*
1572          * See if this looks like SNMP or not. if not, return 0 so
1573          * wireshark can try som other dissector instead.
1574          */
1575         /* All SNMP packets are BER encoded and consist of a SEQUENCE
1576          * that spans the entire PDU. The first item is an INTEGER that
1577          * has the values 0-2 (version 1-3).
1578          * if not it is not snmp.
1579          */
1580         /* SNMP starts with a SEQUENCE */
1581         offset = get_ber_identifier(tvb, 0, &tmp_class, &tmp_pc, &tmp_tag);
1582         if((tmp_class!=BER_CLASS_UNI)||(tmp_tag!=BER_UNI_TAG_SEQUENCE)){
1583                 return 0;
1584         }
1585         /* then comes a length which spans the rest of the tvb */
1586         offset = get_ber_length(tvb, offset, &tmp_length, &tmp_ind);
1587         if(tmp_length!=(guint32)tvb_reported_length_remaining(tvb, offset)){
1588                 return 0;
1589         }
1590         /* then comes an INTEGER (version)*/
1591         offset = get_ber_identifier(tvb, offset, &tmp_class, &tmp_pc, &tmp_tag);
1592         if((tmp_class!=BER_CLASS_UNI)||(tmp_tag!=BER_UNI_TAG_INTEGER)){
1593                 return 0;
1594         }
1595         /* do we need to test that version is 0 - 2 (version1-3) ? */
1596
1597
1598         /*
1599          * The first SNMP packet goes to the SNMP port; the second one
1600          * may come from some *other* port, but goes back to the same
1601          * IP address and port as the ones from which the first packet
1602          * came; all subsequent packets presumably go between those two
1603          * IP addresses and ports.
1604          *
1605          * If this packet went to the SNMP port, we check to see if
1606          * there's already a conversation with one address/port pair
1607          * matching the source IP address and port of this packet,
1608          * the other address matching the destination IP address of this
1609          * packet, and any destination port.
1610          *
1611          * If not, we create one, with its address 1/port 1 pair being
1612          * the source address/port of this packet, its address 2 being
1613          * the destination address of this packet, and its port 2 being
1614          * wildcarded, and give it the SNMP dissector as a dissector.
1615          */
1616         if (pinfo->destport == UDP_PORT_SNMP) {
1617           conversation = find_conversation(pinfo->fd->num, &pinfo->src, &pinfo->dst, PT_UDP,
1618                                            pinfo->srcport, 0, NO_PORT_B);
1619           if( (conversation == NULL) || (conversation->dissector_handle!=snmp_handle) ){
1620             conversation = conversation_new(pinfo->fd->num, &pinfo->src, &pinfo->dst, PT_UDP,
1621                                             pinfo->srcport, 0, NO_PORT2);
1622             conversation_set_dissector(conversation, snmp_handle);
1623           }
1624         }
1625
1626         return dissect_snmp_pdu(tvb, 0, pinfo, tree, proto_snmp, ett_snmp, FALSE);
1627 }
1628 static void
1629 dissect_snmp_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
1630 {
1631         int offset = 0;
1632         guint message_len;
1633
1634         while (tvb_reported_length_remaining(tvb, offset) > 0) {
1635                 message_len = dissect_snmp_pdu(tvb, 0, pinfo, tree,
1636                     proto_snmp, ett_snmp, TRUE);
1637                 if (message_len == 0) {
1638                         /*
1639                          * We don't have all the data for that message,
1640                          * so we need to do desegmentation;
1641                          * "dissect_snmp_pdu()" has set that up.
1642                          */
1643                         break;
1644                 }
1645                 offset += message_len;
1646         }
1647 }
1648
1649 static void
1650 dissect_smux(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
1651 {
1652         proto_tree *smux_tree = NULL;
1653         proto_item *item = NULL;
1654
1655         if (check_col(pinfo->cinfo, COL_PROTOCOL))
1656                 col_set_str(pinfo->cinfo, COL_PROTOCOL, "SMUX");
1657
1658         if (tree) {
1659                 item = proto_tree_add_item(tree, proto_smux, tvb, 0, -1, FALSE);
1660                 smux_tree = proto_item_add_subtree(item, ett_smux);
1661         }
1662
1663         dissect_SMUX_PDUs_PDU(tvb, pinfo, tree);
1664 }
1665
1666
1667 /*
1668   MD5 Password to Key Algorithm
1669   from RFC 3414 A.2.1
1670 */
1671 static void snmp_usm_password_to_key_md5(const guint8 *password,
1672                                                                   guint   passwordlen,
1673                                                                   const guint8 *engineID,
1674                                                                   guint   engineLength,
1675                                                                   guint8 *key)  {
1676         md5_state_t     MD;
1677         guint8     *cp, password_buf[64];
1678         guint32      password_index = 0;
1679         guint32      count = 0, i;
1680         guint8          key1[16];
1681         md5_init(&MD);   /* initialize MD5 */
1682
1683         /**********************************************/
1684         /* Use while loop until we've done 1 Megabyte */
1685         /**********************************************/
1686         while (count < 1048576) {
1687                 cp = password_buf;
1688                 for (i = 0; i < 64; i++) {
1689                         /*************************************************/
1690                         /* Take the next octet of the password, wrapping */
1691                         /* to the beginning of the password as necessary.*/
1692                         /*************************************************/
1693                         *cp++ = password[password_index++ % passwordlen];
1694                 }
1695                 md5_append(&MD, password_buf, 64);
1696                 count += 64;
1697         }
1698         md5_finish(&MD, key1);          /* tell MD5 we're done */
1699
1700         /*****************************************************/
1701         /* Now localize the key with the engineID and pass   */
1702         /* through MD5 to produce final key                  */
1703         /* May want to ensure that engineLength <= 32,       */
1704         /* otherwise need to use a buffer larger than 64     */
1705         /*****************************************************/
1706
1707         md5_init(&MD);
1708         md5_append(&MD, key1, 16);
1709         md5_append(&MD, engineID, engineLength);
1710         md5_append(&MD, key1, 16);
1711         md5_finish(&MD, key);
1712
1713         return;
1714 }
1715
1716
1717
1718
1719 /*
1720    SHA1 Password to Key Algorithm COPIED from RFC 3414 A.2.2
1721  */
1722
1723 static void snmp_usm_password_to_key_sha1(const guint8 *password,
1724                                                                    guint   passwordlen,
1725                                                                    const guint8 *engineID,
1726                                                                    guint   engineLength,
1727                                                                    guint8 *key ) {
1728         sha1_context     SH;
1729         guint8     *cp, password_buf[72];
1730         guint32      password_index = 0;
1731         guint32      count = 0, i;
1732
1733         sha1_starts(&SH);   /* initialize SHA */
1734
1735         /**********************************************/
1736         /* Use while loop until we've done 1 Megabyte */
1737         /**********************************************/
1738         while (count < 1048576) {
1739                 cp = password_buf;
1740                 for (i = 0; i < 64; i++) {
1741                         /*************************************************/
1742                         /* Take the next octet of the password, wrapping */
1743                         /* to the beginning of the password as necessary.*/
1744                         /*************************************************/
1745                         *cp++ = password[password_index++ % passwordlen];
1746                 }
1747                 sha1_update (&SH, password_buf, 64);
1748                 count += 64;
1749         }
1750         sha1_finish(&SH, key);
1751
1752         /*****************************************************/
1753         /* Now localize the key with the engineID and pass   */
1754         /* through SHA to produce final key                  */
1755         /* May want to ensure that engineLength <= 32,       */
1756         /* otherwise need to use a buffer larger than 72     */
1757         /*****************************************************/
1758         memcpy(password_buf, key, 20);
1759         memcpy(password_buf+20, engineID, engineLength);
1760         memcpy(password_buf+20+engineLength, key, 20);
1761
1762         sha1_starts(&SH);
1763         sha1_update(&SH, password_buf, 40+engineLength);
1764         sha1_finish(&SH, key);
1765         return;
1766  }
1767
1768
1769 static void process_prefs(void) {}
1770
1771 static void* snmp_users_copy_cb(void* dest, const void* orig, unsigned len _U_) {
1772         const snmp_ue_assoc_t* o = orig;
1773         snmp_ue_assoc_t* d = dest;
1774
1775         d->auth_model = o->auth_model;
1776         d->user.authModel = auth_models[o->auth_model];
1777
1778         d->priv_proto = o->priv_proto;
1779         d->user.privProtocol = priv_protos[o->priv_proto];
1780
1781         d->user.userName.data = g_memdup(o->user.userName.data,o->user.userName.len);
1782         d->user.userName.len = o->user.userName.len;
1783
1784         d->user.authPassword.data = o->user.authPassword.data ? g_memdup(o->user.authPassword.data,o->user.authPassword.len) : NULL;
1785         d->user.authPassword.len = o->user.authPassword.len;
1786
1787         d->user.privPassword.data = o->user.privPassword.data ? g_memdup(o->user.privPassword.data,o->user.privPassword.len) : NULL;
1788         d->user.privPassword.len = o->user.privPassword.len;
1789
1790         d->engine.len = o->engine.len;
1791         if (o->engine.data) {
1792                 d->engine.data = g_memdup(o->engine.data,o->engine.len);
1793         }
1794
1795         d->user.authKey.data = o->user.authKey.data ? g_memdup(o->user.authKey.data,o->user.authKey.len) : NULL;
1796         d->user.authKey.len = o->user.authKey.len;
1797
1798         d->user.privKey.data = o->user.privKey.data ? g_memdup(o->user.privKey.data,o->user.privKey.len) : NULL;
1799         d->user.privKey.len = o->user.privKey.len;
1800
1801         return d;
1802 }
1803
1804 static void snmp_users_free_cb(void* p) {
1805         snmp_ue_assoc_t* ue = p;
1806         if (ue->user.userName.data) g_free(ue->user.userName.data);
1807         if (ue->user.authPassword.data) g_free(ue->user.authPassword.data);
1808         if (ue->user.privPassword.data) g_free(ue->user.privPassword.data);
1809         if (ue->user.authKey.data) g_free(ue->user.authKey.data);
1810         if (ue->user.privKey.data) g_free(ue->user.privKey.data);
1811         if (ue->engine.data) g_free(ue->engine.data);
1812 }
1813
1814 static void snmp_users_update_cb(void* p _U_, const char** err) {
1815         snmp_ue_assoc_t* ue = p;
1816         GString* es = g_string_new("");
1817
1818         *err = NULL;
1819
1820         if (! ue->user.userName.len) g_string_append(es,"no userName, ");
1821         if (ue->user.authPassword.len < 8) g_string_sprintfa(es,"short authPassword (%d), ", ue->user.authPassword.len);
1822         if (ue->user.privPassword.len < 8) g_string_sprintfa(es,"short privPassword (%d), ", ue->user.privPassword.len);
1823
1824         if (es->len) {
1825                 g_string_truncate(es,es->len-2);
1826                 *err = ep_strdup(es->str);
1827         }
1828
1829         g_string_free(es,TRUE);
1830
1831         return;
1832 }
1833
1834 UAT_LSTRING_CB_DEF(snmp_users,userName,snmp_ue_assoc_t,user.userName.data,user.userName.len)
1835 UAT_LSTRING_CB_DEF(snmp_users,authPassword,snmp_ue_assoc_t,user.authPassword.data,user.authPassword.len)
1836 UAT_LSTRING_CB_DEF(snmp_users,privPassword,snmp_ue_assoc_t,user.privPassword.data,user.privPassword.len)
1837 UAT_BUFFER_CB_DEF(snmp_users,engine_id,snmp_ue_assoc_t,engine.data,engine.len)
1838 UAT_VS_DEF(snmp_users,auth_model,snmp_ue_assoc_t,0,"MD5")
1839 UAT_VS_DEF(snmp_users,priv_proto,snmp_ue_assoc_t,0,"DES")
1840
1841         /*--- proto_register_snmp -------------------------------------------*/
1842 void proto_register_snmp(void) {
1843   /* List of fields */
1844   static hf_register_info hf[] = {
1845                 { &hf_snmp_v3_flags_auth,
1846                 { "Authenticated", "snmp.v3.flags.auth", FT_BOOLEAN, 8,
1847                     TFS(&flags_set_truth), TH_AUTH, "", HFILL }},
1848                 { &hf_snmp_v3_flags_crypt,
1849                 { "Encrypted", "snmp.v3.flags.crypt", FT_BOOLEAN, 8,
1850                     TFS(&flags_set_truth), TH_CRYPT, "", HFILL }},
1851                 { &hf_snmp_v3_flags_report,
1852                 { "Reportable", "snmp.v3.flags.report", FT_BOOLEAN, 8,
1853                     TFS(&flags_set_truth), TH_REPORT, "", HFILL }},
1854                 { &hf_snmp_engineid_conform, {
1855                     "Engine ID Conformance", "snmp.engineid.conform", FT_BOOLEAN, 8,
1856                     TFS(&tfs_snmp_engineid_conform), F_SNMP_ENGINEID_CONFORM, "Engine ID RFC3411 Conformance", HFILL }},
1857                 { &hf_snmp_engineid_enterprise, {
1858                     "Engine Enterprise ID", "snmp.engineid.enterprise", FT_UINT32, BASE_DEC,
1859                     VALS(sminmpec_values), 0, "Engine Enterprise ID", HFILL }},
1860                 { &hf_snmp_engineid_format, {
1861                     "Engine ID Format", "snmp.engineid.format", FT_UINT8, BASE_DEC,
1862                     VALS(snmp_engineid_format_vals), 0, "Engine ID Format", HFILL }},
1863                 { &hf_snmp_engineid_ipv4, {
1864                     "Engine ID Data: IPv4 address", "snmp.engineid.ipv4", FT_IPv4, BASE_NONE,
1865                     NULL, 0, "Engine ID Data: IPv4 address", HFILL }},
1866                 { &hf_snmp_engineid_ipv6, {
1867                     "Engine ID Data: IPv6 address", "snmp.engineid.ipv6", FT_IPv6, BASE_NONE,
1868                     NULL, 0, "Engine ID Data: IPv6 address", HFILL }},
1869                 { &hf_snmp_engineid_mac, {
1870                     "Engine ID Data: MAC address", "snmp.engineid.mac", FT_ETHER, BASE_NONE,
1871                     NULL, 0, "Engine ID Data: MAC address", HFILL }},
1872                 { &hf_snmp_engineid_text, {
1873                     "Engine ID Data: Text", "snmp.engineid.text", FT_STRING, BASE_NONE,
1874                     NULL, 0, "Engine ID Data: Text", HFILL }},
1875                 { &hf_snmp_engineid_time, {
1876                     "Engine ID Data: Time", "snmp.engineid.time", FT_ABSOLUTE_TIME, BASE_NONE,
1877                     NULL, 0, "Engine ID Data: Time", HFILL }},
1878                 { &hf_snmp_engineid_data, {
1879                     "Engine ID Data", "snmp.engineid.data", FT_BYTES, BASE_HEX,
1880                     NULL, 0, "Engine ID Data", HFILL }},
1881                   { &hf_snmp_msgAuthentication,
1882                                 { "Authentication", "snmp.v3.auth", FT_BOOLEAN, 8,
1883                                         TFS(&auth_flags), 0, "", HFILL }},
1884                   { &hf_snmp_decryptedPDU, {
1885                                         "Decrypted ScopedPDU", "snmp.decrypted_pdu", FT_BYTES, BASE_HEX,
1886                                         NULL, 0, "Decrypted PDU", HFILL }},
1887   { &hf_snmp_noSuchObject, { "noSuchObject", "snmp.noSuchObject", FT_NONE, BASE_NONE,  NULL, 0, "", HFILL }},
1888   { &hf_snmp_noSuchInstance, { "noSuchInstance", "snmp.noSuchInstance", FT_NONE, BASE_DEC,  NULL, 0, "", HFILL }},
1889   { &hf_snmp_endOfMibView, { "endOfMibView", "snmp.endOfMibView", FT_NONE, BASE_DEC,  NULL, 0, "", HFILL }},
1890   { &hf_snmp_unSpecified, { "unSpecified", "snmp.unSpecified", FT_NONE, BASE_DEC,  NULL, 0, "", HFILL }},
1891           
1892   { &hf_snmp_integer32_value, { "Value (Integer32)", "snmp.value.int", FT_INT64, BASE_DEC,  NULL, 0, "", HFILL }},
1893   { &hf_snmp_octestring_value, { "Value (OctetString)", "snmp.value.octets", FT_BYTES, BASE_NONE,  NULL, 0, "", HFILL }},
1894   { &hf_snmp_oid_value, { "Value (OID)", "snmp.value.oid", FT_OID, BASE_NONE,  NULL, 0, "", HFILL }},
1895   { &hf_snmp_null_value, { "Value (Null)", "snmp.value.null", FT_NONE, BASE_NONE,  NULL, 0, "", HFILL }},
1896   { &hf_snmp_ipv4_value, { "Value (IpAddress)", "snmp.value.ipv4", FT_IPv4, BASE_NONE,  NULL, 0, "", HFILL }},
1897   { &hf_snmp_ipv6_value, { "Value (IpAddress)", "snmp.value.ipv6", FT_IPv6, BASE_NONE,  NULL, 0, "", HFILL }},
1898   { &hf_snmp_anyaddress_value, { "Value (IpAddress)", "snmp.value.addr", FT_BYTES, BASE_DEC,  NULL, 0, "", HFILL }},
1899   { &hf_snmp_unsigned32_value, { "Value (Unsigned32)", "snmp.value.u32", FT_INT64, BASE_DEC,  NULL, 0, "", HFILL }},
1900   { &hf_snmp_gauge32_value, { "Value (Gauge32)", "snmp.value.g32", FT_INT64, BASE_DEC,  NULL, 0, "", HFILL }},
1901   { &hf_snmp_unknown_value, { "Value (Unknown)", "snmp.value.unk", FT_BYTES, BASE_NONE,  NULL, 0, "", HFILL }},
1902   { &hf_snmp_counter_value, { "Value (Counter32)", "snmp.value.counter", FT_UINT64, BASE_DEC,  NULL, 0, "", HFILL }},
1903   { &hf_snmp_nsap_value, { "Value (NSAP)", "snmp.value.nsap", FT_UINT64, BASE_DEC,  NULL, 0, "", HFILL }},
1904   { &hf_snmp_timeticks_value, { "Value (Timeticks)", "snmp.value.timeticks", FT_UINT64, BASE_DEC,  NULL, 0, "", HFILL }},
1905   { &hf_snmp_opaque_value, { "Value (Opaque)", "snmp.value.opaque", FT_BYTES, BASE_NONE,  NULL, 0, "", HFILL }},
1906   { &hf_snmp_objectname, { "Object Name", "snmp.name", FT_OID, BASE_NONE,  NULL, 0, "", HFILL }},
1907   { &hf_snmp_scalar_instance_index, { "Scalar Instance Index", "snmp.name.index", FT_UINT64, BASE_DEC,  NULL, 0, "", HFILL }},
1908   
1909   
1910 #include "packet-snmp-hfarr.c"
1911   };
1912
1913   /* List of subtrees */
1914   static gint *ett[] = {
1915           &ett_snmp,
1916           &ett_engineid,
1917           &ett_msgFlags,
1918           &ett_encryptedPDU,
1919           &ett_decrypted,
1920           &ett_authParameters,
1921           &ett_internet,
1922           &ett_varbind,
1923           &ett_name,
1924           &ett_value,
1925           &ett_decoding_error,
1926 #include "packet-snmp-ettarr.c"
1927   };
1928   module_t *snmp_module;
1929   static uat_field_t users_fields[] = {
1930           UAT_FLD_BUFFER(snmp_users,engine_id,"Engine-id for this entry (empty = any)"),
1931           UAT_FLD_LSTRING(snmp_users,userName,"The username"),
1932           UAT_FLD_VS(snmp_users,auth_model,auth_types,"Algorithm to be used for authentication."),
1933           UAT_FLD_LSTRING(snmp_users,authPassword,"The password used for authenticating packets for this entry"),
1934           UAT_FLD_VS(snmp_users,priv_proto,priv_types,"Algorithm to be used for privacy."),
1935           UAT_FLD_LSTRING(snmp_users,privPassword,"The password used for encrypting packets for this entry"),
1936           UAT_END_FIELDS
1937   };
1938   
1939   assocs_uat = uat_new("SNMP Users",
1940                                            sizeof(snmp_ue_assoc_t),
1941                                            "snmp_users",
1942                                            (void**)&ueas,
1943                                            &num_ueas,
1944                                            UAT_CAT_CRYPTO,
1945                                            "ChSNMPUsersSection",
1946                                            snmp_users_copy_cb,
1947                                            snmp_users_update_cb,
1948                                            snmp_users_free_cb,
1949                                            users_fields);
1950   
1951   /* Register protocol */
1952   proto_snmp = proto_register_protocol(PNAME, PSNAME, PFNAME);
1953   new_register_dissector("snmp", dissect_snmp, proto_snmp);
1954
1955   /* Register fields and subtrees */
1956   proto_register_field_array(proto_snmp, hf, array_length(hf));
1957   proto_register_subtree_array(ett, array_length(ett));
1958
1959
1960         /* Register configuration preferences */
1961         snmp_module = prefs_register_protocol(proto_snmp, process_prefs);
1962         prefs_register_bool_preference(snmp_module, "display_oid",
1963                 "Show SNMP OID in info column",
1964                 "Whether the SNMP OID should be shown in the info column",
1965                 &display_oid);
1966
1967         prefs_register_obsolete_preference(snmp_module, "mib_modules");
1968         prefs_register_obsolete_preference(snmp_module, "users_file");
1969
1970         prefs_register_bool_preference(snmp_module, "desegment",
1971             "Reassemble SNMP-over-TCP messages\nspanning multiple TCP segments",
1972             "Whether the SNMP dissector should reassemble messages spanning multiple TCP segments."
1973             " To use this option, you must also enable \"Allow subdissectors to reassemble TCP streams\" in the TCP protocol settings.",
1974             &snmp_desegment);
1975
1976   prefs_register_bool_preference(snmp_module, "var_in_tree",
1977                 "Display dissected variables inside SNMP tree",
1978                 "ON - display dissected variables inside SNMP tree, OFF - display dissected variables in root tree after SNMP",
1979                 &snmp_var_in_tree); 
1980
1981   prefs_register_uat_preference(snmp_module, "users_table",
1982                                                                 "Users Table",
1983                                                                 "Table of engine-user associations used for authentication and decryption",
1984                                                                 assocs_uat);
1985   
1986   
1987         value_sub_dissectors_table = register_dissector_table("snmp.variable_oid","SNMP Variable OID", FT_STRING, BASE_NONE);
1988         
1989         register_init_routine(renew_ue_cache);
1990 }
1991
1992
1993 /*--- proto_reg_handoff_snmp ---------------------------------------*/
1994 void proto_reg_handoff_snmp(void) {
1995         dissector_handle_t snmp_tcp_handle;
1996
1997         snmp_handle = find_dissector("snmp");
1998
1999         dissector_add("udp.port", UDP_PORT_SNMP, snmp_handle);
2000         dissector_add("udp.port", UDP_PORT_SNMP_TRAP, snmp_handle);
2001         dissector_add("udp.port", UDP_PORT_SNMP_PATROL, snmp_handle);
2002         dissector_add("ethertype", ETHERTYPE_SNMP, snmp_handle);
2003         dissector_add("ipx.socket", IPX_SOCKET_SNMP_AGENT, snmp_handle);
2004         dissector_add("ipx.socket", IPX_SOCKET_SNMP_SINK, snmp_handle);
2005         dissector_add("hpext.dxsap", HPEXT_SNMP, snmp_handle);
2006
2007         snmp_tcp_handle = create_dissector_handle(dissect_snmp_tcp, proto_snmp);
2008         dissector_add("tcp.port", TCP_PORT_SNMP, snmp_tcp_handle);
2009         dissector_add("tcp.port", TCP_PORT_SNMP_TRAP, snmp_tcp_handle);
2010
2011         data_handle = find_dissector("data");
2012
2013         /*
2014          * Process preference settings.
2015          *
2016          * We can't do this in the register routine, as preferences aren't
2017          * read until all dissector register routines have been called (so
2018          * that all dissector preferences have been registered).
2019          */
2020         process_prefs();
2021
2022 }
2023
2024 void
2025 proto_register_smux(void)
2026 {
2027         static hf_register_info hf[] = {
2028                 { &hf_smux_version,
2029                 { "Version", "smux.version", FT_UINT8, BASE_DEC, NULL,
2030                     0x0, "", HFILL }},
2031                 { &hf_smux_pdutype,
2032                 { "PDU type", "smux.pdutype", FT_UINT8, BASE_DEC, VALS(smux_types),
2033                     0x0, "", HFILL }},
2034         };
2035         static gint *ett[] = {
2036                 &ett_smux,
2037         };
2038
2039         proto_smux = proto_register_protocol("SNMP Multiplex Protocol",
2040             "SMUX", "smux");
2041         proto_register_field_array(proto_smux, hf, array_length(hf));
2042         proto_register_subtree_array(ett, array_length(ett));
2043
2044 }
2045
2046 void
2047 proto_reg_handoff_smux(void)
2048 {
2049         dissector_handle_t smux_handle;
2050
2051         smux_handle = create_dissector_handle(dissect_smux, proto_smux);
2052         dissector_add("tcp.port", TCP_PORT_SMUX, smux_handle);
2053 }
2054
2055