Make sure that we reset the filter pointer after we realloc the filter.
[obnox/wireshark/wip.git] / epan / dissectors / packet-ldap.c
1 /* packet-ldap.c
2  * Routines for ldap packet dissection
3  *
4  * See RFC 1777 (LDAP v2), RFC 2251 (LDAP v3), and RFC 2222 (SASL).
5  *
6  * $Id$
7  *
8  * Ethereal - Network traffic analyzer
9  * By Gerald Combs <gerald@ethereal.com>
10  * Copyright 1998 Gerald Combs
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25  */
26
27 /*
28  * This is not a complete implementation. It doesn't handle the full version 3, more specifically,
29  * it handles only the commands of version 2, but any additional characteristics of the ver3 command are supported.
30  *
31  * There should probably be alot more error checking, I simply assume that if we have a full packet, it will be a complete
32  * and correct packet.
33  *
34  * AFAIK, it will handle all messages used by the OpenLDAP 1.2.9 server and libraries which was my goal. I do plan to add
35  * the remaining commands as time permits but this is not a priority to me. Send me an email if you need it and I'll see what
36  * I can do.
37  *
38  * Doug Nazar
39  * nazard@dragoninc.on.ca
40  */
41
42 /*
43  * 11/11/2002 - Fixed problem when decoding LDAP with desegmentation enabled and the
44  *              ASN.1 BER Universal Class Tag: "Sequence Of" header is encapsulated across 2
45  *              TCP segments.
46  *
47  * Ronald W. Henderson
48  * ronald.henderson@cognicaseusa.com
49  */
50
51 /*
52  * 20-JAN-2004 - added decoding of MS-CLDAP netlogon RPC
53  *               using information from the SNIA 2003 conference paper :
54  *               Active Directory Domain Controller Location Service
55  *                    by Anthony Liguori
56  * ronnie sahlberg
57  */
58
59 /*
60  * 17-DEC-2004 - added basic decoding for LDAP Controls
61  * 20-DEC-2004 - added handling for GSS-API encrypted blobs
62  *
63  * Stefan Metzmacher <metze@samba.org>
64  */
65
66 #ifdef HAVE_CONFIG_H
67 # include "config.h"
68 #endif
69
70 #include <stdio.h>
71
72 #include <string.h>
73 #include <glib.h>
74
75 #include <epan/packet.h>
76
77 #include <epan/asn1.h>
78 #include <epan/prefs.h>
79 #include <epan/conversation.h>
80 #include "packet-frame.h"
81 #include <epan/tap.h>
82 #include "packet-ber.h"
83 #include "packet-ldap.h"
84 #include <epan/emem.h>
85
86 static int proto_ldap = -1;
87 static int proto_cldap = -1;
88 static int hf_ldap_response_to = -1;
89 static int hf_ldap_response_in = -1;
90 static int hf_ldap_time = -1;
91 static int hf_ldap_sasl_buffer_length = -1;
92 static int hf_ldap_length = -1;
93 static int hf_ldap_message_id = -1;
94 static int hf_ldap_message_type = -1;
95 static int hf_ldap_message_length = -1;
96
97 static int hf_ldap_message_result = -1;
98 static int hf_ldap_message_result_matcheddn = -1;
99 static int hf_ldap_message_result_errormsg = -1;
100 static int hf_ldap_message_result_referral = -1;
101
102 static int hf_ldap_message_bind_version = -1;
103 static int hf_ldap_message_bind_dn = -1;
104 static int hf_ldap_message_bind_auth = -1;
105 static int hf_ldap_message_bind_auth_password = -1;
106 static int hf_ldap_message_bind_auth_mechanism = -1;
107 static int hf_ldap_message_bind_auth_credentials = -1;
108 static int hf_ldap_message_bind_server_credentials = -1;
109
110 static int hf_ldap_message_search_base = -1;
111 static int hf_ldap_message_search_scope = -1;
112 static int hf_ldap_message_search_deref = -1;
113 static int hf_ldap_message_search_sizeLimit = -1;
114 static int hf_ldap_message_search_timeLimit = -1;
115 static int hf_ldap_message_search_typesOnly = -1;
116 static int hf_ldap_message_search_filter = -1;
117 static int hf_ldap_message_search_reference = -1;
118
119 static int hf_ldap_message_dn = -1;
120 static int hf_ldap_message_attribute = -1;
121 static int hf_ldap_message_value = -1;
122
123 static int hf_ldap_message_modrdn_name = -1;
124 static int hf_ldap_message_modrdn_delete = -1;
125 static int hf_ldap_message_modrdn_superior = -1;
126
127 static int hf_ldap_message_compare = -1;
128
129 static int hf_ldap_message_modify_add = -1;
130 static int hf_ldap_message_modify_replace = -1;
131 static int hf_ldap_message_modify_delete = -1;
132
133 static int hf_ldap_message_abandon_msgid = -1;
134
135 static int hf_ldap_message_controls_oid = -1;
136 static int hf_ldap_message_controls_critical = -1;
137 static int hf_ldap_message_controls_value = -1;
138
139 static int hf_mscldap_netlogon_type = -1;
140 static int hf_mscldap_netlogon_flags = -1;
141 static int hf_mscldap_netlogon_flags_pdc = -1;
142 static int hf_mscldap_netlogon_flags_gc = -1;
143 static int hf_mscldap_netlogon_flags_ldap = -1;
144 static int hf_mscldap_netlogon_flags_ds = -1;
145 static int hf_mscldap_netlogon_flags_kdc = -1;
146 static int hf_mscldap_netlogon_flags_timeserv = -1;
147 static int hf_mscldap_netlogon_flags_closest = -1;
148 static int hf_mscldap_netlogon_flags_writable = -1;
149 static int hf_mscldap_netlogon_flags_good_timeserv = -1;
150 static int hf_mscldap_netlogon_flags_ndnc = -1;
151 static int hf_mscldap_domain_guid = -1;
152 static int hf_mscldap_forest = -1;
153 static int hf_mscldap_domain = -1;
154 static int hf_mscldap_hostname = -1;
155 static int hf_mscldap_nb_domain = -1;
156 static int hf_mscldap_nb_hostname = -1;
157 static int hf_mscldap_username = -1;
158 static int hf_mscldap_sitename = -1;
159 static int hf_mscldap_clientsitename = -1;
160 static int hf_mscldap_netlogon_version = -1;
161 static int hf_mscldap_netlogon_lm_token = -1;
162 static int hf_mscldap_netlogon_nt_token = -1;
163
164 static gint ett_ldap = -1;
165 static gint ett_ldap_msg = -1;
166 static gint ett_ldap_payload = -1;
167 static gint ett_ldap_sasl_blob = -1;
168 static gint ett_ldap_referrals = -1;
169 static gint ett_ldap_attribute = -1;
170 static gint ett_ldap_controls = -1;
171 static gint ett_ldap_control = -1;
172 static gint ett_mscldap_netlogon_flags = -1;
173
174 static int ldap_tap = -1;
175
176 /* desegmentation of LDAP */
177 static gboolean ldap_desegment = TRUE;
178
179 #define TCP_PORT_LDAP                   389
180 #define UDP_PORT_CLDAP                  389
181 #define TCP_PORT_GLOBALCAT_LDAP         3268 /* Windows 2000 Global Catalog */
182
183 static dissector_handle_t gssapi_handle;
184 static dissector_handle_t gssapi_wrap_handle;
185
186
187 /* different types of rpc calls ontop of ms cldap */
188 #define MSCLDAP_RPC_NETLOGON    1
189
190
191 /*
192  * Data structure attached to a conversation, giving authentication
193  * information from a bind request.
194  * We keep a linked list of them, so that we can free up all the
195  * authentication mechanism strings.
196  */
197 typedef struct ldap_conv_info_t {
198   struct ldap_conv_info_t *next;
199   guint auth_type;              /* authentication type */
200   char *auth_mech;              /* authentication mechanism */
201   guint32 first_auth_frame;     /* first frame that would use a security layer */
202   GHashTable *unmatched;
203   GHashTable *matched;
204 } ldap_conv_info_t;
205 static ldap_conv_info_t *ldap_info_items;
206
207 static guint
208 ldap_info_hash_matched(gconstpointer k)
209 {
210   const ldap_call_response_t *key = k;
211
212   return key->messageId;
213 }
214
215 static gint
216 ldap_info_equal_matched(gconstpointer k1, gconstpointer k2)
217 {
218   const ldap_call_response_t *key1 = k1;
219   const ldap_call_response_t *key2 = k2;
220
221   if( key1->req_frame && key2->req_frame && (key1->req_frame!=key2->req_frame) ){
222     return 0;
223   }
224   if( key1->rep_frame && key2->rep_frame && (key1->rep_frame!=key2->rep_frame) ){
225     return 0;
226   }
227
228   return key1->messageId==key2->messageId;
229 }
230
231 static guint
232 ldap_info_hash_unmatched(gconstpointer k)
233 {
234   const ldap_call_response_t *key = k;
235
236   return key->messageId;
237 }
238
239 static gint
240 ldap_info_equal_unmatched(gconstpointer k1, gconstpointer k2)
241 {
242   const ldap_call_response_t *key1 = k1;
243   const ldap_call_response_t *key2 = k2;
244
245   return key1->messageId==key2->messageId;
246 }
247
248
249 static value_string msgTypes [] = {
250   {LDAP_REQ_BIND, "Bind Request"},
251   {LDAP_REQ_UNBIND, "Unbind Request"},
252   {LDAP_REQ_SEARCH, "Search Request"},
253   {LDAP_REQ_MODIFY, "Modify Request"},
254   {LDAP_REQ_ADD, "Add Request"},
255   {LDAP_REQ_DELETE, "Delete Request"},
256   {LDAP_REQ_MODRDN, "Modify RDN Request"},
257   {LDAP_REQ_COMPARE, "Compare Request"},
258   {LDAP_REQ_ABANDON, "Abandon Request"},
259   {LDAP_REQ_EXTENDED, "Extended Request"},
260
261   {LDAP_RES_BIND, "Bind Result"},
262   {LDAP_RES_SEARCH_ENTRY, "Search Entry"},
263   {LDAP_RES_SEARCH_RESULT, "Search Result"},
264   {LDAP_RES_SEARCH_REF, "Search Result Reference"},
265   {LDAP_RES_MODIFY, "Modify Result"},
266   {LDAP_RES_ADD, "Add Result"},
267   {LDAP_RES_DELETE, "Delete Result"},
268   {LDAP_RES_MODRDN, "Modify RDN Result"},
269   {LDAP_RES_COMPARE, "Compare Result"},
270   {LDAP_RES_EXTENDED, "Extended Response"},
271   {0, NULL},
272 };
273
274 static const value_string LDAPResultCode_vals[] = {
275   {   0, "success" },
276   {   1, "operationsError" },
277   {   2, "protocolError" },
278   {   3, "timeLimitExceeded" },
279   {   4, "sizeLimitExceeded" },
280   {   5, "compareFalse" },
281   {   6, "compareTrue" },
282   {   7, "authMethodNotSupported" },
283   {   8, "strongAuthRequired" },
284   {  10, "referral" },
285   {  11, "adminLimitExceeded" },
286   {  12, "unavailableCriticalExtension" },
287   {  13, "confidentialityRequired" },
288   {  14, "saslBindInProgress" },
289   {  16, "noSuchAttribute" },
290   {  17, "undefinedAttributeType" },
291   {  18, "inappropriateMatching" },
292   {  19, "constraintViolation" },
293   {  20, "attributeOrValueExists" },
294   {  21, "invalidAttributeSyntax" },
295   {  32, "noSuchObject" },
296   {  33, "aliasProblem" },
297   {  34, "invalidDNSyntax" },
298   {  36, "aliasDereferencingProblem" },
299   {  48, "inappropriateAuthentication" },
300   {  49, "invalidCredentials" },
301   {  50, "insufficientAccessRights" },
302   {  51, "busy" },
303   {  52, "unavailable" },
304   {  53, "unwillingToPerform" },
305   {  54, "loopDetect" },
306   {  64, "namingViolation" },
307   {  65, "objectClassViolation" },
308   {  66, "notAllowedOnNonLeaf" },
309   {  67, "notAllowedOnRDN" },
310   {  68, "entryAlreadyExists" },
311   {  69, "objectClassModsProhibited" },
312   {  71, "affectsMultipleDSAs" },
313   {  80, "other" },
314   { 0, NULL }
315 };
316
317 static int read_length(ASN1_SCK *a, proto_tree *tree, int hf_id, guint *len)
318 {
319   guint length = 0;
320   gboolean def = FALSE;
321   int start = a->offset;
322   int ret;
323
324   ret = asn1_length_decode(a, &def, &length);
325   if (ret != ASN1_ERR_NOERROR) {
326     if (tree) {
327       proto_tree_add_text(tree, a->tvb, start, 0,
328         "%s: ERROR: Couldn't parse length: %s",
329         proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
330     }
331     return ret;
332   }
333
334   if (len)
335     *len = length;
336
337   if (tree)
338     proto_tree_add_uint(tree, hf_id, a->tvb, start, a->offset-start, length);
339
340   return ASN1_ERR_NOERROR;
341 }
342
343 static int read_sequence(ASN1_SCK *a, guint *len)
344 {
345   guint cls, con, tag;
346   gboolean def;
347   guint length = 0;
348   int ret;
349
350   ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
351   if (ret != ASN1_ERR_NOERROR)
352     return ret;
353   if (cls != ASN1_UNI || con != ASN1_CON || tag != ASN1_SEQ)
354     return ASN1_ERR_WRONG_TYPE;
355
356   if (len)
357     *len = length;
358
359   return ASN1_ERR_NOERROR;
360 }
361
362 static int read_set(ASN1_SCK *a, guint *len)
363 {
364   guint cls, con, tag;
365   gboolean def;
366   guint length;
367   int ret;
368
369   ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
370   if (ret != ASN1_ERR_NOERROR)
371     return ret;
372   if (cls != ASN1_UNI || con != ASN1_CON || tag != ASN1_SET)
373     return ASN1_ERR_WRONG_TYPE;
374
375   if (len)
376     *len = length;
377
378   return ASN1_ERR_NOERROR;
379 }
380
381 static int read_integer_value(ASN1_SCK *a, proto_tree *tree, int hf_id,
382         proto_item **new_item, guint *i, int start, guint length)
383 {
384   guint integer = 0;
385   proto_item *temp_item = NULL;
386   int ret;
387
388   ret = asn1_uint32_value_decode(a, length, &integer);
389   if (ret != ASN1_ERR_NOERROR) {
390     if (tree) {
391       proto_tree_add_text(tree, a->tvb, start, 0,
392        "%s: ERROR: Couldn't parse value: %s",
393         proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
394     }
395     return ret;
396   }
397
398   if (i)
399     *i = integer;
400
401   if (tree)
402     temp_item = proto_tree_add_uint(tree, hf_id, a->tvb, start, a->offset-start, integer);
403
404   if (new_item)
405     *new_item = temp_item;
406
407   return ASN1_ERR_NOERROR;
408 }
409
410 static int read_integer(ASN1_SCK *a, proto_tree *tree, int hf_id,
411         proto_item **new_item, guint *i, guint expected_tag)
412 {
413   guint cls, con, tag;
414   gboolean def;
415   guint length;
416   int start = a->offset;
417   int ret;
418
419   ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
420   if (ret == ASN1_ERR_NOERROR) {
421     if (cls != ASN1_UNI || con != ASN1_PRI || tag != expected_tag)
422       ret = ASN1_ERR_WRONG_TYPE;
423   }
424   if (ret != ASN1_ERR_NOERROR) {
425     if (tree) {
426       proto_tree_add_text(tree, a->tvb, start, 0,
427         "%s: ERROR: Couldn't parse header: %s",
428         (hf_id != -1) ? proto_registrar_get_name(hf_id) : "LDAP message",
429         asn1_err_to_str(ret));
430     }
431     return ret;
432   }
433
434   return read_integer_value(a, tree, hf_id, new_item, i, start, length);
435 }
436
437 static int read_boolean_value(ASN1_SCK *a, proto_tree *tree, int hf_id,
438         proto_item **new_item, guint *i, int start, guint length)
439 {
440   guint integer = 0;
441   proto_item *temp_item = NULL;
442   int ret;
443
444   ret = asn1_uint32_value_decode(a, length, &integer);
445   if (ret != ASN1_ERR_NOERROR) {
446     if (tree) {
447       proto_tree_add_text(tree, a->tvb, start, 0,
448         "%s: ERROR: Couldn't parse value: %s",
449         proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
450     }
451     return ret;
452   }
453
454   if (i)
455     *i = integer;
456
457   if (tree)
458     temp_item = proto_tree_add_boolean(tree, hf_id, a->tvb, start, a->offset-start, integer);
459   if (new_item)
460     *new_item = temp_item;
461
462   return ASN1_ERR_NOERROR;
463 }
464
465 static int read_boolean(ASN1_SCK *a, proto_tree *tree, int hf_id,
466         proto_item **new_item, guint *i)
467 {
468   guint cls, con, tag;
469   gboolean def;
470   guint length;
471   int start = a->offset;
472   int ret;
473
474   ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
475   if (ret == ASN1_ERR_NOERROR) {
476     if (cls != ASN1_UNI || con != ASN1_PRI || tag != ASN1_BOL)
477       ret = ASN1_ERR_WRONG_TYPE;
478   }
479   if (ret != ASN1_ERR_NOERROR) {
480     if (tree) {
481       proto_tree_add_text(tree, a->tvb, start, 0,
482         "%s: ERROR: Couldn't parse header: %s",
483         proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
484     }
485     return ret;
486   }
487
488   return read_boolean_value(a, tree, hf_id, new_item, i, start, length);
489 }
490
491 static int read_string_value(ASN1_SCK *a, proto_tree *tree, int hf_id,
492         proto_item **new_item, char **s, int start, guint length)
493 {
494   guchar *string;
495   proto_item *temp_item = NULL;
496   int ret;
497
498   if (length)
499   {
500     ret = asn1_string_value_decode(a, length, &string);
501     if (ret != ASN1_ERR_NOERROR) {
502       if (tree) {
503         proto_tree_add_text(tree, a->tvb, start, 0,
504           "%s: ERROR: Couldn't parse value: %s",
505           proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
506       }
507       return ret;
508     }
509     string = g_realloc(string, length + 1);
510     string[length] = '\0';
511   }
512   else
513     string = g_strdup("(null)");
514
515   if (tree)
516     temp_item = proto_tree_add_string(tree, hf_id, a->tvb, start, a->offset - start, string);
517   if (new_item)
518     *new_item = temp_item;
519
520   if (s && length)
521     *s = string;
522   else
523     g_free(string);
524
525   return ASN1_ERR_NOERROR;
526 }
527
528 static int read_string(ASN1_SCK *a, proto_tree *tree, int hf_id,
529         proto_item **new_item, char **s, guint *length,
530         guint expected_cls, guint expected_tag)
531 {
532   guint cls, con, tag;
533   gboolean def;
534   guint tmplen;
535   int start = a->offset;
536   int ret;
537
538   ret = asn1_header_decode(a, &cls, &con, &tag, &def, &tmplen);
539   if (ret == ASN1_ERR_NOERROR) {
540     if (cls != expected_cls || con != ASN1_PRI || tag != expected_tag)
541       ret = ASN1_ERR_WRONG_TYPE;
542   }
543   if (ret != ASN1_ERR_NOERROR) {
544     if (tree) {
545       proto_tree_add_text(tree, a->tvb, start, 0,
546         "%s: ERROR: Couldn't parse header: %s",
547         proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
548     }
549     return ret;
550   }
551
552   if(length){
553      *length=tmplen;
554   }
555   return read_string_value(a, tree, hf_id, new_item, s, start, tmplen);
556 }
557
558 static int read_bytestring_value(ASN1_SCK *a, proto_tree *tree, int hf_id,
559         proto_item **new_item, char **s, int start, guint length)
560 {
561   guchar *string;
562   proto_item *temp_item = NULL;
563   int ret;
564
565   if (length)
566   {
567     ret = asn1_string_value_decode(a, length, &string);
568     if (ret != ASN1_ERR_NOERROR) {
569       if (tree) {
570         proto_tree_add_text(tree, a->tvb, start, 0,
571           "%s: ERROR: Couldn't parse value: %s",
572           proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
573       }
574       return ret;
575     }
576     string = g_realloc(string, length + 1);
577     string[length] = '\0';
578   }
579   else
580     string = "(null)";
581
582   if (tree && length > 0) {
583     temp_item = proto_tree_add_bytes(tree, hf_id, a->tvb, start, a->offset - start, string);
584 }
585   if (new_item)
586     *new_item = temp_item;
587
588   if (s && length)
589     *s = string;
590   else if (length)
591     g_free(string);
592
593   return ASN1_ERR_NOERROR;
594 }
595
596 static int read_bytestring(ASN1_SCK *a, proto_tree *tree, int hf_id,
597         proto_item **new_item, char **s, guint expected_cls, guint expected_tag)
598 {
599   guint cls, con, tag;
600   gboolean def;
601   guint length;
602   int start = a->offset;
603   int ret;
604
605   ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
606   if (ret == ASN1_ERR_NOERROR) {
607     if (cls != expected_cls || con != ASN1_PRI || tag != expected_tag)
608       ret = ASN1_ERR_WRONG_TYPE;
609   }
610   if (ret != ASN1_ERR_NOERROR) {
611     if (tree) {
612       proto_tree_add_text(tree, a->tvb, start, 0,
613         "%s: ERROR: Couldn't parse header: %s",
614         proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
615     }
616     return ret;
617   }
618
619   return read_bytestring_value(a, tree, hf_id, new_item, s, start, length);
620 }
621
622 static int check_optional_tag(ASN1_SCK *a, guint expected_cls, guint expected_con, guint expected_tag)
623 {
624   guint cls, con, tag;
625   gboolean def;
626   guint length;
627   int ret;
628   int replay_offset;
629
630   replay_offset = a->offset;
631
632   ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
633   if (ret == ASN1_ERR_NOERROR) {
634     if (cls != expected_cls || con != expected_con || tag != expected_tag) {
635       ret = ASN1_ERR_WRONG_TYPE;
636     }
637   }
638
639   a->offset = replay_offset;
640
641   return ret;
642 }
643
644 static int parse_filter_strings(ASN1_SCK *a, char **filter, guint *filter_length, const guchar *operation)
645 {
646   guchar *string;
647   guchar *string2;
648   guint string_length;
649   guint string2_length;
650   guint string_bytes;
651   char *filterp;
652   int ret;
653
654   ret = asn1_octet_string_decode(a, &string, &string_length, &string_bytes);
655   if (ret != ASN1_ERR_NOERROR)
656     return ret;
657   ret = asn1_octet_string_decode(a, &string2, &string2_length, &string_bytes);
658   if (ret != ASN1_ERR_NOERROR)
659     return ret;
660   *filter_length += 2 + strlen(operation) + string_length + string2_length;
661   *filter = g_realloc(*filter, *filter_length);
662   filterp = *filter + strlen(*filter);
663
664   filterp += g_snprintf(filterp, (*filter_length)-(filterp-*filter), "(%s%s%s)", string, operation, string2);
665
666   g_free(string);
667   g_free(string2);
668   return ASN1_ERR_NOERROR;
669 }
670
671 /* Richard Dawe: To parse substring filters, I added this function. */
672 static int parse_filter_substrings(ASN1_SCK *a, char **filter, guint *filter_length)
673 {
674   int end;
675   guchar *string;
676   char *filterp;
677   guint string_length;
678   guint string_bytes;
679   guint seq_len;
680   guint header_bytes;
681   int ret, any_valued;
682
683   /* For ASN.1 parsing of octet strings */
684   guint        cls;
685   guint        con;
686   guint        tag;
687   gboolean     def;
688
689   ret = asn1_octet_string_decode(a, &string, &string_length, &string_bytes);
690   if (ret != ASN1_ERR_NOERROR)
691     return ret;
692
693   ret = asn1_sequence_decode(a, &seq_len, &header_bytes);
694   if (ret != ASN1_ERR_NOERROR)
695     return ret;
696
697   *filter_length += 2 + 1 + string_length;
698   *filter = g_realloc(*filter, *filter_length);
699
700   filterp = *filter + strlen(*filter);
701   *filterp++ = '(';
702   if (string_length != 0) {
703     memcpy(filterp, string, string_length);
704     filterp += string_length;
705   }
706   *filterp++ = '=';
707   *filterp = '\0';
708   g_free(string);
709
710   /* Now decode seq_len's worth of octet strings. */
711   any_valued = 0;
712   end = a->offset + seq_len;
713
714   while (a->offset < end) {
715     /* Octet strings here are context-specific, which
716      * asn1_octet_string_decode() barfs on. Emulate it, but don't barf. */
717     ret = asn1_header_decode (a, &cls, &con, &tag, &def, &string_length);
718     if (ret != ASN1_ERR_NOERROR)
719       return ret;
720
721     /* XXX - check the tag? */
722     if (cls != ASN1_CTX || con != ASN1_PRI) {
723         /* XXX - handle the constructed encoding? */
724         return ASN1_ERR_WRONG_TYPE;
725     }
726     if (!def)
727         return ASN1_ERR_LENGTH_NOT_DEFINITE;
728
729     ret = asn1_string_value_decode(a, (int) string_length, &string);
730     if (ret != ASN1_ERR_NOERROR)
731       return ret;
732
733     /* If we have an 'any' component with a string value, we need to append
734      * an extra asterisk before final component. */
735     if ((tag == 1) && (string_length != 0))
736       any_valued = 1;
737
738     if ( (tag == 1) || ((tag == 2) && any_valued) )
739       (*filter_length)++;
740     *filter_length += string_length;
741     *filter = g_realloc(*filter, *filter_length);
742
743     filterp = *filter + strlen(*filter);
744     if ( (tag == 1) || ((tag == 2) && any_valued) )
745       *filterp++ = '*';
746     if (tag == 2)
747       any_valued = 0;
748     if (string_length != 0) {
749       memcpy(filterp, string, string_length);
750       filterp += string_length;
751     }
752     *filterp = '\0';
753     g_free(string);
754   }
755
756   if (any_valued)
757   {
758     (*filter_length)++;
759     *filter = g_realloc(*filter, *filter_length);
760     filterp = *filter + strlen(*filter);
761     *filterp++ = '*';
762   }
763
764   /* NB: Allocated byte for this earlier */
765   *filterp++ = ')';
766   *filterp = '\0';
767
768   return ASN1_ERR_NOERROR;
769 }
770
771 /*
772  * Richard Sharpe: Add parsing of extensibleMatch filters.
773  * It's real easy to provoke ldapsearch into producing requests that allow us
774  * to see what is being produced:
775  * ldapsearch '(departmentNumber:2.16.840.1.113730.3.3.2.46.1:=>=N4709)' -x \ 
776  * cn sn telephoneNumber
777  */
778 static int parse_filter_extensibleMatch(ASN1_SCK *a, char **filter, guint *filter_length, guint byte_length)
779 {
780     int ret;
781     guint length;
782     char *filterp;
783     guint seq_len;
784     guint header_bytes;
785     guint string_length;
786     guint end;
787     guchar *matchingRule, *type, *matchValue;
788     gboolean dnAttributes;
789
790     /* ASN.1 parsing vars ... */
791     guint cls;
792     guint con;
793     guint tag;
794     gboolean def;
795     
796     /*
797      *  MatchingRuleAssertion ::= SEQUENCE {
798      *    matchingRule [1] MatchingRuleId OPTIONAL,
799      *    type         [2] AttributeDescription OPTIONAL,
800      *    matchValue   [3] AssertionValue,
801      *    dnAttributes [4] BOOLEAN DEFAULT FALSE
802      *  }
803      *  Of course, SEQUENCE is merged with the filter
804      *  so there is no separate 30 ...
805      */
806
807     /*
808     * Decode byte_length of stuff ... as per above
809     * But we assemble the strings and the boolean
810     * if present, and then assemble the filter
811     * expression
812     */
813     matchingRule = type = matchValue = NULL;
814     dnAttributes = FALSE;
815     end = a->offset + byte_length;
816
817     while (a->offset < end) {
818         /*
819          * Now, parse out each of those items
820          * There will be up to four of them.
821          */
822         ret = asn1_header_decode(a, &cls, &con, &tag, &def, &string_length);
823         if (ret != ASN1_ERR_NOERROR) {
824             return ret;
825         }
826
827         /*
828          * Now, check the tag ...
829          */
830         if (cls != ASN1_CTX || con != ASN1_PRI) {
831             return ASN1_ERR_WRONG_TYPE;
832         }
833         if (!def) {
834             return ASN1_ERR_LENGTH_NOT_DEFINITE;
835         }
836
837         switch (tag) {
838         case 0x01:  /* Parse Matching Rule Id */
839             if (matchingRule != NULL) {
840                 g_free(matchingRule);
841                 matchingRule = NULL;
842             }
843             ret = asn1_string_value_decode(a, (int) string_length, &matchingRule);
844             if (ret != ASN1_ERR_NOERROR) {
845                 return ret;
846             }
847             break;
848
849         case 0x02:  /* Parse attributeDescription */
850             if (type != NULL) {
851                 g_free(type);
852                 type = NULL;
853             }
854             ret = asn1_string_value_decode(a, (int) string_length, &type);
855             if (ret != ASN1_ERR_NOERROR) {
856                 return ret;
857             }
858             break;
859
860         case 0x03:  /* Parse the matchValue */
861             if (matchValue != NULL) {
862                 g_free(matchValue);
863                 matchValue = NULL;
864             }
865             ret = asn1_string_value_decode(a, (int) string_length, &matchValue);
866             if (ret != ASN1_ERR_NOERROR) {
867                 return ret;
868             }
869             break;
870
871         case 0x04:  /* Parse dnAttributes boolean */
872             ret = asn1_bool_decode(a, (int)string_length, &dnAttributes);
873             if (ret != ASN1_ERR_NOERROR) {
874                 return ret;
875             }
876             break;
877
878         default:
879             return ASN1_ERR_WRONG_TYPE;
880         }
881
882     }
883     
884     /*
885      * Now, fill in the filter string
886      */
887     filterp = *filter + strlen(*filter);
888     *filter_length += 1; /* For the ( */
889     *filter = g_realloc(*filter, *filter_length);
890     *filterp++ = '(';
891     *filterp = '\0';
892
893     if (type) {
894         if (strlen(type) > 0) {
895             *filter_length += 1 + strlen(type);
896             *filter = g_realloc(*filter, *filter_length);
897             filterp = *filter + strlen(*filter);
898             memcpy(filterp, type, strlen(type));
899             filterp += strlen(type);
900             *filterp++ = ':';
901             *filterp = '\0';
902
903             /*
904              * Add in dn if needed ...
905              */
906             if (dnAttributes) {
907                 static char *dnString = "dn";
908                 *filter_length += 1 + strlen(dnString);
909                 *filter = g_realloc(*filter, *filter_length);
910                 filterp = *filter + strlen(*filter);
911                 memcpy(filterp, dnString, strlen(dnString));
912                 filterp += strlen(dnString);
913                 *filterp++ = ':';
914                 *filterp = '\0';
915             }
916         }
917         g_free(type);
918     }
919
920     if (matchingRule) {
921         if (strlen(matchingRule) > 0) {
922             *filter_length += 1 + strlen(matchingRule);
923             *filter = g_realloc(*filter, *filter_length);
924             filterp = *filter + strlen(*filter);
925             memcpy(filterp, matchingRule, strlen(matchingRule));
926             filterp += strlen(matchingRule);
927             *filterp++ = ':';
928             *filterp = '\0';
929         }
930         g_free(matchingRule);
931     }
932
933     if (matchValue) {
934         if (strlen(matchValue) > 0) {
935             *filter_length += strlen(matchValue);
936             *filter = g_realloc(*filter, *filter_length);
937             filterp = *filter + strlen(*filter);
938             memcpy(filterp, matchValue, strlen(matchValue));
939             filterp += strlen(matchValue);
940             *filterp = '\0';
941         }
942         g_free(matchValue);
943     }
944    
945     *filter_length +=1;
946     *filter = g_realloc(*filter, *filter_length);
947     filterp = *filter + strlen(*filter);
948     *filterp++ = ')';
949     *filterp = '\0';   /* There had better be space */
950     
951     return ASN1_ERR_NOERROR;
952 }
953
954 /* Returns -1 if we're at the end, returns an ASN1_ERR value otherwise. */
955 static int parse_filter(ASN1_SCK *a, char **filter, guint *filter_length,
956                         int *end)
957 {
958   guint cls, con, tag;
959   guint length;
960   gboolean def;
961   int ret;
962
963   ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
964   if (ret != ASN1_ERR_NOERROR)
965     return ret;
966
967   if (*end == 0)
968   {
969     *end = a->offset + length;
970     *filter_length = 1;
971     *filter = g_malloc0(*filter_length);
972   }
973
974   if (cls == ASN1_CTX)  /* XXX - handle other types as errors? */
975   {
976     switch (tag)
977     {
978      case LDAP_FILTER_AND:
979       {
980         int add_end;
981
982         if (con != ASN1_CON)
983           return ASN1_ERR_WRONG_TYPE;
984         add_end = a->offset + length;
985         *filter_length += 3;
986         *filter = g_realloc(*filter, *filter_length);
987         strcat(*filter, "(&");
988         while ((ret = parse_filter(a, filter, filter_length, &add_end))
989                 == ASN1_ERR_NOERROR)
990           continue;
991         if (ret != -1)
992           return ret;
993         strcat(*filter, ")");
994       }
995       break;
996      case LDAP_FILTER_OR:
997       {
998         int or_end;
999
1000         if (con != ASN1_CON)
1001           return ASN1_ERR_WRONG_TYPE;
1002         or_end = a->offset + length;
1003         *filter_length += 3;
1004         *filter = g_realloc(*filter, *filter_length);
1005         strcat(*filter, "(|");
1006         while ((ret = parse_filter(a, filter, filter_length, &or_end))
1007                 == ASN1_ERR_NOERROR)
1008           continue;
1009         if (ret != -1)
1010           return ret;
1011         strcat(*filter, ")");
1012       }
1013       break;
1014      case LDAP_FILTER_NOT:
1015       {
1016         int not_end;
1017
1018         if (con != ASN1_CON)
1019           return ASN1_ERR_WRONG_TYPE;
1020         not_end = a->offset + length;
1021         *filter_length += 3;
1022         *filter = g_realloc(*filter, *filter_length);
1023         strcat(*filter, "(!");
1024         ret = parse_filter(a, filter, filter_length, &not_end);
1025         if (ret != -1 && ret != ASN1_ERR_NOERROR)
1026           return ret;
1027         strcat(*filter, ")");
1028       }
1029       break;
1030      case LDAP_FILTER_EQUALITY:
1031       if (con != ASN1_CON)
1032         return ASN1_ERR_WRONG_TYPE;
1033       ret = parse_filter_strings(a, filter, filter_length, "=");
1034       if (ret != ASN1_ERR_NOERROR)
1035         return ret;
1036       break;
1037      case LDAP_FILTER_GE:
1038       if (con != ASN1_CON)
1039         return ASN1_ERR_WRONG_TYPE;
1040       ret = parse_filter_strings(a, filter, filter_length, ">=");
1041       if (ret != ASN1_ERR_NOERROR)
1042         return ret;
1043       break;
1044      case LDAP_FILTER_LE:
1045       if (con != ASN1_CON)
1046         return ASN1_ERR_WRONG_TYPE;
1047       ret = parse_filter_strings(a, filter, filter_length, "<=");
1048       if (ret != -1 && ret != ASN1_ERR_NOERROR)
1049         return ret;
1050       break;
1051      case LDAP_FILTER_APPROX:
1052       if (con != ASN1_CON)
1053         return ASN1_ERR_WRONG_TYPE;
1054       ret = parse_filter_strings(a, filter, filter_length, "~=");
1055       if (ret != ASN1_ERR_NOERROR)
1056         return ret;
1057       break;
1058      case LDAP_FILTER_PRESENT:
1059       {
1060         guchar *string;
1061         char *filterp;
1062
1063         if (con != ASN1_PRI)
1064           return ASN1_ERR_WRONG_TYPE;
1065         ret = asn1_string_value_decode(a, length, &string);
1066         if (ret != ASN1_ERR_NOERROR)
1067           return ret;
1068         *filter_length += 4 + length;
1069         *filter = g_realloc(*filter, *filter_length);
1070         filterp = *filter + strlen(*filter);
1071         *filterp++ = '(';
1072         if (length != 0) {
1073           memcpy(filterp, string, length);
1074           filterp += length;
1075         }
1076         *filterp++ = '=';
1077         *filterp++ = '*';
1078         *filterp++ = ')';
1079         *filterp = '\0';
1080         g_free(string);
1081       }
1082       break;
1083      case LDAP_FILTER_SUBSTRINGS:
1084       if (con != ASN1_CON)
1085         return ASN1_ERR_WRONG_TYPE;
1086       /* Richard Dawe: Handle substrings */
1087       ret = parse_filter_substrings(a, filter, filter_length);
1088       if (ret != ASN1_ERR_NOERROR)
1089         return ret;
1090       break;
1091      case LDAP_FILTER_EXTENSIBLE:
1092       if (con != ASN1_CON)
1093         return ASN1_ERR_WRONG_TYPE;
1094       ret = parse_filter_extensibleMatch(a, filter, filter_length, length);
1095       if (ret != ASN1_ERR_NOERROR) {
1096         return ret;
1097       }
1098       break;
1099      default:
1100       return ASN1_ERR_WRONG_TYPE;
1101     }
1102   }
1103
1104   if (a->offset == *end)
1105     return -1;
1106   else
1107     return ASN1_ERR_NOERROR;
1108 }
1109
1110 static gboolean read_filter(ASN1_SCK *a, proto_tree *tree, int hf_id)
1111 {
1112   int start = a->offset;
1113   char *filter = 0;
1114   guint filter_length = 0;
1115   int end = 0;
1116   int ret;
1117
1118   while ((ret = parse_filter(a, &filter, &filter_length, &end))
1119         == ASN1_ERR_NOERROR)
1120     continue;
1121
1122   if (tree) {
1123     if (ret != -1) {
1124       proto_tree_add_text(tree, a->tvb, start, 0,
1125         "%s: ERROR: Can't parse filter: %s",
1126         proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
1127     } else
1128       proto_tree_add_string(tree, hf_id, a->tvb, start, a->offset-start, filter);
1129   }
1130
1131   g_free(filter);
1132
1133   return (ret == -1) ? TRUE : FALSE;
1134 }
1135
1136 /********************************************************************************************/
1137
1138 static void dissect_ldap_result(ASN1_SCK *a, proto_tree *tree, packet_info *pinfo)
1139 {
1140   guint resultCode = 0;
1141   int ret;
1142   if (read_integer(a, tree, hf_ldap_message_result, 0, &resultCode, ASN1_ENUM) != ASN1_ERR_NOERROR)
1143     return;
1144
1145   if (resultCode != 0) {
1146           if (check_col(pinfo->cinfo, COL_INFO))
1147                   col_append_fstr(pinfo->cinfo, COL_INFO, ", %s", 
1148                                   val_to_str(resultCode, LDAPResultCode_vals,
1149                                              "Unknown (%u)"));
1150   }
1151
1152   if (read_string(a, tree, hf_ldap_message_result_matcheddn, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1153     return;
1154   if (read_string(a, tree, hf_ldap_message_result_errormsg, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1155     return;
1156
1157   if (resultCode == 10)         /* Referral */
1158   {
1159     int start = a->offset;
1160     int end;
1161     guint length;
1162     proto_item *ti;
1163     proto_tree *referralTree;
1164
1165     ret = read_sequence(a, &length);
1166     if (ret != ASN1_ERR_NOERROR) {
1167       if (tree) {
1168         proto_tree_add_text(tree, a->tvb, start, 0,
1169             "ERROR: Couldn't parse referral URL sequence header: %s",
1170             asn1_err_to_str(ret));
1171       }
1172       return;
1173     }
1174     ti = proto_tree_add_text(tree, a->tvb, start, length, "Referral URLs");
1175     referralTree = proto_item_add_subtree(ti, ett_ldap_referrals);
1176
1177     end = a->offset + length;
1178     while (a->offset < end) {
1179       if (read_string(a, referralTree, hf_ldap_message_result_referral, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1180         return;
1181     }
1182   }
1183 }
1184
1185 static void dissect_ldap_request_bind(ASN1_SCK *a, proto_tree *tree,
1186     tvbuff_t *tvb, packet_info *pinfo, ldap_conv_info_t *ldap_info)
1187 {
1188   guint cls, con, tag;
1189   gboolean def;
1190   guint length;
1191   int start;
1192   int end;
1193   int ret;
1194   char *mechanism, *s = NULL;
1195   int token_offset;
1196   gint available_length, reported_length;
1197   tvbuff_t *new_tvb;
1198
1199   if (read_integer(a, tree, hf_ldap_message_bind_version, 0, 0, ASN1_INT) != ASN1_ERR_NOERROR)
1200     return;
1201   if (read_string(a, tree, hf_ldap_message_bind_dn, 0, &s, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1202     return;
1203
1204   if (check_col(pinfo->cinfo, COL_INFO))
1205     col_append_fstr(pinfo->cinfo, COL_INFO, ", DN=%s", s != NULL ? s : "(null)");
1206   g_free(s);
1207
1208   start = a->offset;
1209   ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
1210   if (ret == ASN1_ERR_NOERROR) {
1211     if (cls != ASN1_CTX) {
1212       /* RFCs 1777 and 2251 say these are context-specific types */
1213       ret = ASN1_ERR_WRONG_TYPE;
1214     }
1215   }
1216   if (ret != ASN1_ERR_NOERROR) {
1217     proto_tree_add_text(tree, a->tvb, start, 0,
1218       "%s: ERROR: Couldn't parse header: %s",
1219       proto_registrar_get_name(hf_ldap_message_bind_auth),
1220       asn1_err_to_str(ret));
1221     return;
1222   }
1223   proto_tree_add_uint(tree, hf_ldap_message_bind_auth, a->tvb, start,
1224                         a->offset - start, tag);
1225   end = a->offset + length;
1226   switch (tag)
1227   {
1228    case LDAP_AUTH_SIMPLE:
1229     if (read_string_value(a, tree, hf_ldap_message_bind_auth_password, NULL,
1230                           NULL, start, length) != ASN1_ERR_NOERROR)
1231       return;
1232     break;
1233
1234     /* For Kerberos V4, dissect it as a ticket. */
1235
1236    case LDAP_AUTH_SASL:
1237     mechanism = NULL;
1238     if (read_string(a, tree, hf_ldap_message_bind_auth_mechanism, NULL,
1239                     &mechanism, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1240       return;
1241
1242     /*
1243      * We need to remember the authentication type and mechanism for this
1244      * conversation.
1245      *
1246      * XXX - actually, we might need to remember more than one
1247      * type and mechanism, if you can unbind and rebind with a
1248      * different type and/or mechanism.
1249      */
1250     ldap_info->auth_type = tag;
1251     ldap_info->auth_mech = mechanism;
1252     ldap_info->first_auth_frame = 0;    /* not known until we see the bind reply */
1253     /*
1254      * If the mechanism in this request is an empty string (which is
1255      * returned as a null pointer), use the saved mechanism instead.
1256      * Otherwise, if the saved mechanism is an empty string (null),
1257      * save this mechanism.
1258      */
1259     if (mechanism == NULL)
1260         mechanism = ldap_info->auth_mech;
1261     else {
1262       if (ldap_info->auth_mech == NULL) {
1263         g_free(ldap_info->auth_mech);
1264       }
1265       ldap_info->auth_mech = mechanism;
1266     }
1267
1268     if (a->offset < end) {
1269       if (mechanism != NULL && strcmp(mechanism, "GSS-SPNEGO") == 0) {
1270         /*
1271          * This is a GSS-API token ancapsulated within GSS-SPNEGO.
1272          * Find out how big it is by parsing the ASN.1 header for the
1273          * OCTET STREAM that contains it.
1274          */
1275         token_offset = a->offset;
1276         ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
1277         if (ret != ASN1_ERR_NOERROR) {
1278           proto_tree_add_text(tree, a->tvb, token_offset, 0,
1279             "%s: ERROR: Couldn't parse header: %s",
1280             proto_registrar_get_name(hf_ldap_message_bind_auth_credentials),
1281             asn1_err_to_str(ret));
1282           return;
1283         }
1284         available_length = tvb_length_remaining(tvb, token_offset);
1285         reported_length = tvb_reported_length_remaining(tvb, token_offset);
1286         DISSECTOR_ASSERT(available_length >= 0);
1287         DISSECTOR_ASSERT(reported_length >= 0);
1288         if (available_length > reported_length)
1289           available_length = reported_length;
1290         if ((guint)available_length > length)
1291           available_length = length;
1292         if ((guint)reported_length > length)
1293           reported_length = length;
1294         new_tvb = tvb_new_subset(tvb, a->offset, available_length, reported_length);
1295         call_dissector(gssapi_handle, new_tvb, pinfo, tree);
1296         a->offset += length;
1297       } else if (mechanism != NULL && strcmp(mechanism, "GSSAPI") == 0) {
1298         /*
1299          * This is a raw GSS-API token.
1300          * Find out how big it is by parsing the ASN.1 header for the
1301          * OCTET STREAM that contains it.
1302          */
1303         token_offset = a->offset;
1304         ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
1305         if (ret != ASN1_ERR_NOERROR) {
1306           proto_tree_add_text(tree, a->tvb, token_offset, 0,
1307             "%s: ERROR: Couldn't parse header: %s",
1308             proto_registrar_get_name(hf_ldap_message_bind_auth_credentials),
1309             asn1_err_to_str(ret));
1310           return;
1311         }
1312         if(length==0){
1313           /* for GSSAPI the third pdu will sometimes be "empty" */
1314           return;
1315         }
1316         available_length = tvb_length_remaining(tvb, token_offset);
1317         reported_length = tvb_reported_length_remaining(tvb, token_offset);
1318         DISSECTOR_ASSERT(available_length >= 0);
1319         DISSECTOR_ASSERT(reported_length >= 0);
1320         if (available_length > reported_length)
1321           available_length = reported_length;
1322         if ((guint)available_length > length)
1323           available_length = length;
1324         if ((guint)reported_length > length)
1325           reported_length = length;
1326         new_tvb = tvb_new_subset(tvb, a->offset, available_length, reported_length);
1327         call_dissector(gssapi_handle, new_tvb, pinfo, tree);
1328         a->offset += length;
1329       } else {
1330         if (read_bytestring(a, tree, hf_ldap_message_bind_auth_credentials,
1331                             NULL, NULL, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1332           return;
1333       }
1334     }
1335     break;
1336   }
1337 }
1338
1339 static void dissect_ldap_response_bind(ASN1_SCK *a, proto_tree *tree,
1340                 int start, guint length, tvbuff_t *tvb, packet_info *pinfo, ldap_conv_info_t *ldap_info)
1341 {
1342   guint cls, con, tag;
1343   gboolean def;
1344   guint cred_length;
1345   int end;
1346   int ret;
1347   int token_offset;
1348   gint available_length, reported_length;
1349   tvbuff_t *new_tvb;
1350
1351   end = start + length;
1352   dissect_ldap_result(a, tree, pinfo);
1353   if (a->offset < end) {
1354     switch (ldap_info->auth_type) {
1355
1356       /* For Kerberos V4, dissect it as a ticket. */
1357       /* XXX - what about LDAP_AUTH_SIMPLE? */
1358
1359     case LDAP_AUTH_SASL:
1360       /*
1361        * All frames after this are assumed to use a security layer.
1362        *
1363        * XXX - won't work if there's another reply, with the security
1364        * layer, starting in the same TCP segment that ends this
1365        * reply, but as LDAP is a request/response protocol, and
1366        * as the client probably can't start using authentication until
1367        * it gets the bind reply and the server won't send a reply until
1368        * it gets a request, that probably won't happen.
1369        *
1370        * XXX - that assumption is invalid; it's not clear where the
1371        * hell you find out whether there's any security layer.  In
1372        * one capture, we have two GSS-SPNEGO negotiations, both of
1373        * which select MS KRB5, and the only differences in the tokens
1374        * is in the RC4-HMAC ciphertext.  The various
1375        * draft-ietf--cat-sasl-gssapi-NN.txt drafts seem to imply
1376        * that the RFC 2222 spoo with the bitmask and maximum
1377        * output message size stuff is done - but where does that
1378        * stuff show up?  Is it in the ciphertext, which means it's
1379        * presumably encrypted?
1380        *
1381        * Grrr.  We have to do a gross heuristic, checking whether the
1382        * putative LDAP message begins with 0x00 or not, making the
1383        * assumption that we won't have more than 2^24 bytes of
1384        * encapsulated stuff.
1385        */
1386       ldap_info->first_auth_frame = pinfo->fd->num + 1;
1387       if (ldap_info->auth_mech != NULL &&
1388           strcmp(ldap_info->auth_mech, "GSS-SPNEGO") == 0) {
1389         /*
1390          * This is a GSS-API token.
1391          * Find out how big it is by parsing the ASN.1 header for the
1392          * OCTET STREAM that contains it.
1393          */
1394         token_offset = a->offset;
1395         ret = asn1_header_decode(a, &cls, &con, &tag, &def, &cred_length);
1396         if (ret != ASN1_ERR_NOERROR) {
1397           proto_tree_add_text(tree, a->tvb, token_offset, 0,
1398             "%s: ERROR: Couldn't parse header: %s",
1399             proto_registrar_get_name(hf_ldap_message_bind_auth_credentials),
1400             asn1_err_to_str(ret));
1401           return;
1402         }
1403         available_length = tvb_length_remaining(tvb, token_offset);
1404         reported_length = tvb_reported_length_remaining(tvb, token_offset);
1405         DISSECTOR_ASSERT(available_length >= 0);
1406         DISSECTOR_ASSERT(reported_length >= 0);
1407         if (available_length > reported_length)
1408           available_length = reported_length;
1409         if ((guint)available_length > cred_length)
1410           available_length = cred_length;
1411         if ((guint)reported_length > cred_length)
1412           reported_length = cred_length;
1413         new_tvb = tvb_new_subset(tvb, a->offset, available_length, reported_length);
1414         call_dissector(gssapi_handle, new_tvb, pinfo, tree);
1415         a->offset += cred_length;
1416       } else if (ldap_info->auth_mech != NULL &&
1417           strcmp(ldap_info->auth_mech, "GSSAPI") == 0) {
1418         /*
1419          * This is a GSS-API token.
1420          * Find out how big it is by parsing the ASN.1 header for the
1421          * OCTET STREAM that contains it.
1422          */
1423         token_offset = a->offset;
1424         ret = asn1_header_decode(a, &cls, &con, &tag, &def, &cred_length);
1425         if (ret != ASN1_ERR_NOERROR) {
1426           proto_tree_add_text(tree, a->tvb, token_offset, 0,
1427             "%s: ERROR: Couldn't parse header: %s",
1428             proto_registrar_get_name(hf_ldap_message_bind_auth_credentials),
1429             asn1_err_to_str(ret));
1430           return;
1431         }
1432         available_length = tvb_length_remaining(tvb, token_offset);
1433         reported_length = tvb_reported_length_remaining(tvb, token_offset);
1434         DISSECTOR_ASSERT(available_length >= 0);
1435         DISSECTOR_ASSERT(reported_length >= 0);
1436         if (available_length > reported_length)
1437           available_length = reported_length;
1438         if ((guint)available_length > cred_length)
1439           available_length = cred_length;
1440         if ((guint)reported_length > cred_length)
1441           reported_length = cred_length;
1442         new_tvb = tvb_new_subset(tvb, a->offset, available_length, reported_length);
1443         call_dissector(gssapi_handle, new_tvb, pinfo, tree);
1444         a->offset += cred_length;
1445       } else {
1446         if (read_bytestring(a, tree, hf_ldap_message_bind_server_credentials,
1447                             NULL, NULL, ASN1_CTX, 7) != ASN1_ERR_NOERROR)
1448           return;
1449       }
1450       break;
1451     }
1452   }
1453 }
1454
1455 static void dissect_ldap_request_search(ASN1_SCK *a, proto_tree *tree, packet_info *pinfo)
1456 {
1457   guint seq_length;
1458   int end;
1459   int ret;
1460   char *s = NULL;
1461
1462   if (read_string(a, tree, hf_ldap_message_search_base, 0, &s, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1463     return;
1464
1465   if (check_col(pinfo->cinfo, COL_INFO))
1466     col_append_fstr(pinfo->cinfo, COL_INFO, ", Base DN=%s", s != NULL ? s : "(null)");
1467   g_free(s);
1468
1469   if (read_integer(a, tree, hf_ldap_message_search_scope, 0, 0, ASN1_ENUM) != ASN1_ERR_NOERROR)
1470     return;
1471   if (read_integer(a, tree, hf_ldap_message_search_deref, 0, 0, ASN1_ENUM) != ASN1_ERR_NOERROR)
1472     return;
1473   if (read_integer(a, tree, hf_ldap_message_search_sizeLimit, 0, 0, ASN1_INT) != ASN1_ERR_NOERROR)
1474     return;
1475   if (read_integer(a, tree, hf_ldap_message_search_timeLimit, 0, 0, ASN1_INT) != ASN1_ERR_NOERROR)
1476     return;
1477   if (read_boolean(a, tree, hf_ldap_message_search_typesOnly, 0, 0) != ASN1_ERR_NOERROR)
1478     return;
1479   if (!read_filter(a, tree, hf_ldap_message_search_filter))
1480     return;
1481   ret = read_sequence(a, &seq_length);
1482   if (ret != ASN1_ERR_NOERROR) {
1483     if (tree) {
1484       proto_tree_add_text(tree, a->tvb, a->offset, 0,
1485           "ERROR: Couldn't parse LDAP attribute sequence header: %s",
1486           asn1_err_to_str(ret));
1487     }
1488     return;
1489   }
1490   end = a->offset + seq_length;
1491   while (a->offset < end) {
1492     if (read_string(a, tree, hf_ldap_message_attribute, 0, 0, 0, ASN1_UNI,
1493                     ASN1_OTS) != ASN1_ERR_NOERROR)
1494       return;
1495   }
1496 }
1497
1498 static int dissect_mscldap_string(tvbuff_t *tvb, int offset, char *str, int maxlen, gboolean prepend_dot)
1499 {
1500   guint8 len;
1501
1502   len=tvb_get_guint8(tvb, offset);
1503   offset+=1;
1504   *str=0;
1505
1506   while(len){
1507     /* add potential field separation dot */
1508     if(prepend_dot){
1509       if(!maxlen){
1510         *str=0;
1511         return offset;
1512       }
1513       maxlen--;
1514       *str++='.';
1515       *str=0;
1516     }
1517
1518     if(len==0xc0){
1519       int new_offset;
1520       /* ops its a mscldap compressed string */
1521
1522       new_offset=tvb_get_guint8(tvb, offset);
1523       if (new_offset == offset - 1)
1524         THROW(ReportedBoundsError);
1525       offset+=1;
1526
1527       dissect_mscldap_string(tvb, new_offset, str, maxlen, FALSE);
1528
1529       return offset;
1530     }
1531
1532     prepend_dot=TRUE;
1533
1534     if(maxlen<=len){
1535       if(maxlen>3){
1536         *str++='.';
1537         *str++='.';
1538         *str++='.';
1539       }
1540       *str=0;
1541       return offset; /* will mess up offset in caller, is unlikely */
1542     }
1543     tvb_memcpy(tvb, str, offset, len);
1544     str+=len;
1545     *str=0;
1546     maxlen-=len;
1547     offset+=len;
1548
1549
1550     len=tvb_get_guint8(tvb, offset);
1551     offset+=1;
1552   }
1553   *str=0;
1554   return offset;
1555 }
1556
1557
1558 /* These flag bits were found to be defined in the samba sources.
1559  * I hope they are correct (but have serious doubts about the CLOSEST
1560  * bit being used or being meaningful).
1561  */
1562 static const true_false_string tfs_ads_pdc = {
1563         "This is a PDC",
1564         "This is NOT a pdc"
1565 };
1566 static const true_false_string tfs_ads_gc = {
1567         "This is a GLOBAL CATALOGUE of forest",
1568         "This is NOT a global catalog of forest"
1569 };
1570 static const true_false_string tfs_ads_ldap = {
1571         "This is an LDAP server",
1572         "This is NOT an ldap server"
1573 };
1574 static const true_false_string tfs_ads_ds = {
1575         "This dc supports DS",
1576         "This dc does NOT support ds"
1577 };
1578 static const true_false_string tfs_ads_kdc = {
1579         "This is a KDC (kerberos)",
1580         "This is NOT a kdc (kerberos)"
1581 };
1582 static const true_false_string tfs_ads_timeserv = {
1583         "This dc is running TIME SERVICES (ntp)",
1584         "This dc is NOT running time services (ntp)"
1585 };
1586 static const true_false_string tfs_ads_closest = {
1587         "This is the CLOSEST dc (unreliable?)",
1588         "This is NOT the closest dc"
1589 };
1590 static const true_false_string tfs_ads_writable = {
1591         "This dc is WRITABLE",
1592         "This dc is NOT writable"
1593 };
1594 static const true_false_string tfs_ads_good_timeserv = {
1595         "This dc has a GOOD TIME SERVICE (i.e. hardware clock)",
1596         "This dc does NOT have a good time service (i.e. no hardware clock)"
1597 };
1598 static const true_false_string tfs_ads_ndnc = {
1599         "Domain is NON-DOMAIN NC serviced by ldap server",
1600         "Domain is NOT non-domain nc serviced by ldap server"
1601 };
1602 static int dissect_mscldap_netlogon_flags(proto_tree *parent_tree, tvbuff_t *tvb, int offset)
1603 {
1604   guint32 flags;
1605   proto_item *item;
1606   proto_tree *tree=NULL;
1607
1608   flags=tvb_get_letohl(tvb, offset);
1609   item=proto_tree_add_item(parent_tree, hf_mscldap_netlogon_flags, tvb, offset, 4, TRUE);
1610   if(parent_tree){
1611     tree = proto_item_add_subtree(item, ett_mscldap_netlogon_flags);
1612   }
1613
1614   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_ndnc,
1615     tvb, offset, 4, flags);
1616   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_good_timeserv,
1617     tvb, offset, 4, flags);
1618   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_writable,
1619     tvb, offset, 4, flags);
1620   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_closest,
1621     tvb, offset, 4, flags);
1622   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_timeserv,
1623     tvb, offset, 4, flags);
1624   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_kdc,
1625     tvb, offset, 4, flags);
1626   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_ds,
1627     tvb, offset, 4, flags);
1628   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_ldap,
1629     tvb, offset, 4, flags);
1630   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_gc,
1631     tvb, offset, 4, flags);
1632   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_pdc,
1633     tvb, offset, 4, flags);
1634
1635   offset += 4;
1636
1637   return offset;
1638 }
1639
1640 static void dissect_mscldap_response_netlogon(proto_tree *tree, tvbuff_t *tvb)
1641 {
1642   int old_offset, offset=0;
1643   char str[256];
1644
1645 /*qqq*/
1646
1647   /* Type */
1648   /*XXX someone that knows what the type means should add that knowledge here*/
1649   proto_tree_add_item(tree, hf_mscldap_netlogon_type, tvb, offset, 4, TRUE);
1650   offset += 4;
1651
1652   /* Flags */
1653   offset = dissect_mscldap_netlogon_flags(tree, tvb, offset);
1654
1655   /* Domain GUID */
1656   proto_tree_add_item(tree, hf_mscldap_domain_guid, tvb, offset, 16, TRUE);
1657   offset += 16;
1658
1659   /* Forest */
1660   old_offset=offset;
1661   offset=dissect_mscldap_string(tvb, offset, str, 255, FALSE);
1662   proto_tree_add_string(tree, hf_mscldap_forest, tvb, old_offset, offset-old_offset, str);
1663   
1664   /* Domain */
1665   old_offset=offset;
1666   offset=dissect_mscldap_string(tvb, offset, str, 255, FALSE);
1667   proto_tree_add_string(tree, hf_mscldap_domain, tvb, old_offset, offset-old_offset, str);
1668   
1669   /* Hostname */
1670   old_offset=offset;
1671   offset=dissect_mscldap_string(tvb, offset, str, 255, FALSE);
1672   proto_tree_add_string(tree, hf_mscldap_hostname, tvb, old_offset, offset-old_offset, str);
1673   
1674   /* NetBios Domain */
1675   old_offset=offset;
1676   offset=dissect_mscldap_string(tvb, offset, str, 255, FALSE);
1677   proto_tree_add_string(tree, hf_mscldap_nb_domain, tvb, old_offset, offset-old_offset, str);
1678   
1679   /* NetBios Hostname */
1680   old_offset=offset;
1681   offset=dissect_mscldap_string(tvb, offset, str, 255, FALSE);
1682   proto_tree_add_string(tree, hf_mscldap_nb_hostname, tvb, old_offset, offset-old_offset, str);
1683   
1684   /* User */
1685   old_offset=offset;
1686   offset=dissect_mscldap_string(tvb, offset, str, 255, FALSE);
1687   proto_tree_add_string(tree, hf_mscldap_username, tvb, old_offset, offset-old_offset, str);
1688   
1689   /* Site */
1690   old_offset=offset;
1691   offset=dissect_mscldap_string(tvb, offset, str, 255, FALSE);
1692   proto_tree_add_string(tree, hf_mscldap_sitename, tvb, old_offset, offset-old_offset, str);
1693   
1694   /* Client Site */
1695   old_offset=offset;
1696   offset=dissect_mscldap_string(tvb, offset, str, 255, FALSE);
1697   proto_tree_add_string(tree, hf_mscldap_clientsitename, tvb, old_offset, offset-old_offset, str);
1698   
1699   /* Version */
1700   proto_tree_add_item(tree, hf_mscldap_netlogon_version, tvb, offset, 4, TRUE);
1701   offset += 4;
1702
1703   /* LM Token */
1704   proto_tree_add_item(tree, hf_mscldap_netlogon_lm_token, tvb, offset, 2, TRUE);
1705   offset += 2;
1706
1707   /* NT Token */
1708   proto_tree_add_item(tree, hf_mscldap_netlogon_nt_token, tvb, offset, 2, TRUE);
1709   offset += 2;
1710
1711 }
1712
1713 static void dissect_mscldap_response(proto_tree *tree, tvbuff_t *tvb, guint32 rpc)
1714 {
1715   switch(rpc){
1716   case MSCLDAP_RPC_NETLOGON:
1717     dissect_mscldap_response_netlogon(tree, tvb);
1718     break;
1719   default:
1720     proto_tree_add_text(tree, tvb, 0, tvb_length(tvb),
1721       "ERROR: Unknown type of MS-CLDAP RPC call");
1722   }
1723 }
1724
1725
1726 static void dissect_ldap_response_search_entry(ASN1_SCK *a, proto_tree *tree,
1727                 gboolean is_mscldap)
1728 {
1729   guint seq_length;
1730   int end_of_sequence;
1731   int ret;
1732   char *str=NULL;
1733   guint32 len;
1734   guint32 mscldap_rpc;
1735
1736   if (read_string(a, tree, hf_ldap_message_dn, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1737     return;
1738   ret = read_sequence(a, &seq_length);
1739   if (ret != ASN1_ERR_NOERROR) {
1740     if (tree) {
1741       proto_tree_add_text(tree, a->tvb, a->offset, 0,
1742           "ERROR: Couldn't parse search entry response sequence header: %s",
1743           asn1_err_to_str(ret));
1744     }
1745     return;
1746   }
1747
1748   end_of_sequence = a->offset + seq_length;
1749   while (a->offset < end_of_sequence)
1750   {
1751     proto_item *ti;
1752     proto_tree *attr_tree;
1753     guint set_length;
1754     int end_of_set;
1755
1756     ret = read_sequence(a, 0);
1757     if (ret != ASN1_ERR_NOERROR) {
1758       if (tree) {
1759         proto_tree_add_text(tree, a->tvb, a->offset, 0,
1760             "ERROR: Couldn't parse LDAP attribute sequence header: %s",
1761             asn1_err_to_str(ret));
1762       }
1763       return;
1764     }
1765     if (read_string(a, tree, hf_ldap_message_attribute, &ti, &str, &len, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1766       return;
1767
1768     mscldap_rpc=0;
1769     if(is_mscldap){
1770           if(str && !strncmp(str, "netlogon", 8)){
1771                 mscldap_rpc=MSCLDAP_RPC_NETLOGON;
1772           }
1773     }
1774     g_free(str);
1775     str=NULL;
1776
1777
1778     attr_tree = proto_item_add_subtree(ti, ett_ldap_attribute);
1779
1780     ret = read_set(a, &set_length);
1781     if (ret != ASN1_ERR_NOERROR) {
1782       if (tree) {
1783         proto_tree_add_text(attr_tree, a->tvb, a->offset, 0,
1784             "ERROR: Couldn't parse LDAP value set header: %s",
1785             asn1_err_to_str(ret));
1786       }
1787       return;
1788     }
1789     end_of_set = a->offset + set_length;
1790     while (a->offset < end_of_set) {
1791       if(!is_mscldap){
1792         if (read_string(a, attr_tree, hf_ldap_message_value, 0, 0, 0, ASN1_UNI,
1793                         ASN1_OTS) != ASN1_ERR_NOERROR){
1794           return;
1795         }
1796       } else {
1797         guint cls, con, tag;
1798         gboolean def;
1799         guint len;
1800         int start = a->offset;
1801         int ret;
1802         tvbuff_t *mscldap_tvb=NULL;
1803
1804         ret = asn1_header_decode(a, &cls, &con, &tag, &def, &len);
1805         if (ret == ASN1_ERR_NOERROR) {
1806           if (cls != ASN1_UNI || con != ASN1_PRI || tag != ASN1_OTS)
1807             ret = ASN1_ERR_WRONG_TYPE;
1808         }
1809         if (ret != ASN1_ERR_NOERROR) {
1810           if (tree) {
1811             proto_tree_add_text(tree, a->tvb, start, 0,
1812               "%s: ERROR: Couldn't parse header: %s",
1813             proto_registrar_get_name(hf_ldap_message_value), asn1_err_to_str(ret));
1814           }
1815           return;
1816         }
1817         mscldap_tvb=tvb_new_subset(a->tvb, a->offset, len, len);
1818         dissect_mscldap_response(attr_tree, mscldap_tvb, mscldap_rpc);
1819         a->offset+=len;
1820       }
1821
1822     }
1823   }
1824 }
1825
1826 static void dissect_ldap_response_search_ref(ASN1_SCK *a, proto_tree *tree)
1827 {
1828   read_string(a, tree, hf_ldap_message_search_reference, 0, 0, 0, ASN1_UNI, ASN1_OTS);
1829 }
1830
1831 static void dissect_ldap_request_add(ASN1_SCK *a, proto_tree *tree, packet_info *pinfo)
1832 {
1833   guint seq_length;
1834   int end_of_sequence;
1835   int ret;
1836   char *s = NULL;
1837
1838   if (read_string(a, tree, hf_ldap_message_dn, 0, &s, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1839     return;
1840
1841   if (check_col(pinfo->cinfo, COL_INFO))
1842     col_append_fstr(pinfo->cinfo, COL_INFO, ", DN=%s", s != NULL ? s : "(null)");
1843   g_free(s);  
1844
1845   ret = read_sequence(a, &seq_length);
1846   if (ret != ASN1_ERR_NOERROR) {
1847     if (tree) {
1848       proto_tree_add_text(tree, a->tvb, a->offset, 0,
1849           "ERROR: Couldn't parse add request sequence header: %s",
1850           asn1_err_to_str(ret));
1851     }
1852     return;
1853   }
1854
1855   end_of_sequence = a->offset + seq_length;
1856   while (a->offset < end_of_sequence)
1857   {
1858     proto_item *ti;
1859     proto_tree *attr_tree;
1860     guint set_length;
1861     int end_of_set;
1862
1863     ret = read_sequence(a, 0);
1864     if (ret != ASN1_ERR_NOERROR) {
1865       if (tree) {
1866         proto_tree_add_text(tree, a->tvb, a->offset, 0,
1867             "ERROR: Couldn't parse LDAP attribute sequence header: %s",
1868             asn1_err_to_str(ret));
1869       }
1870       return;
1871     }
1872     if (read_string(a, tree, hf_ldap_message_attribute, &ti, 0, 0, ASN1_UNI,
1873                     ASN1_OTS) != ASN1_ERR_NOERROR)
1874       return;
1875     attr_tree = proto_item_add_subtree(ti, ett_ldap_attribute);
1876
1877     ret = read_set(a, &set_length);
1878     if (ret != ASN1_ERR_NOERROR) {
1879       if (tree) {
1880         proto_tree_add_text(attr_tree, a->tvb, a->offset, 0,
1881             "ERROR: Couldn't parse LDAP value set header: %s",
1882             asn1_err_to_str(ret));
1883       }
1884       return;
1885     }
1886     end_of_set = a->offset + set_length;
1887     while (a->offset < end_of_set) {
1888       if (read_string(a, attr_tree, hf_ldap_message_value, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1889         return;
1890     }
1891   }
1892 }
1893
1894 static void dissect_ldap_request_delete(ASN1_SCK *a, proto_tree *tree,
1895                 int start, guint length)
1896 {
1897   read_string_value(a, tree, hf_ldap_message_dn, NULL, NULL, start, length);
1898 }
1899
1900 static void dissect_ldap_request_modifyrdn(ASN1_SCK *a, proto_tree *tree,
1901                 guint length)
1902 {
1903   int start = a->offset;
1904
1905   if (read_string(a, tree, hf_ldap_message_dn, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1906     return;
1907   if (read_string(a, tree, hf_ldap_message_modrdn_name, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1908     return;
1909   if (read_boolean(a, tree, hf_ldap_message_modrdn_delete, 0, 0) != ASN1_ERR_NOERROR)
1910     return;
1911
1912   if (a->offset < (int) (start + length)) {
1913     /* LDAP V3 Modify DN operation, with newSuperior */
1914     /*      "newSuperior     [0] LDAPDN OPTIONAL" (0x80) */
1915     if (read_string(a, tree, hf_ldap_message_modrdn_superior, 0, 0, 0, ASN1_CTX, 0) != ASN1_ERR_NOERROR)
1916       return;
1917   }
1918 }
1919
1920 static void dissect_ldap_request_compare(ASN1_SCK *a, proto_tree *tree)
1921 {
1922   int start;
1923   int length;
1924   char *string1 = NULL;
1925   char *string2 = NULL;
1926   const char *s1, *s2;
1927   char *compare;
1928   int ret;
1929
1930   if (read_string(a, tree, hf_ldap_message_dn, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1931     return;
1932   ret = read_sequence(a, 0);
1933   if (ret != ASN1_ERR_NOERROR) {
1934     if (tree) {
1935       proto_tree_add_text(tree, a->tvb, a->offset, 0,
1936           "ERROR: Couldn't parse compare request sequence header: %s",
1937           asn1_err_to_str(ret));
1938     }
1939     return;
1940   }
1941
1942   start = a->offset;
1943   ret = read_string(a, 0, -1, 0, &string1, 0, ASN1_UNI, ASN1_OTS);
1944   if (ret != ASN1_ERR_NOERROR) {
1945     if (tree) {
1946       proto_tree_add_text(tree, a->tvb, start, 0,
1947         "ERROR: Couldn't parse compare type: %s", asn1_err_to_str(ret));
1948     }
1949     return;
1950   }
1951   ret = read_string(a, 0, -1, 0, &string2, 0, ASN1_UNI, ASN1_OTS);
1952   if (ret != ASN1_ERR_NOERROR) {
1953     if (tree) {
1954       proto_tree_add_text(tree, a->tvb, start, 0,
1955         "ERROR: Couldn't parse compare value: %s", asn1_err_to_str(ret));
1956     }
1957     g_free(string1);
1958     return;
1959   }
1960
1961   s1 = (string1 == NULL) ? "(null)" : string1;
1962   s2 = (string2 == NULL) ? "(null)" : string2;
1963   length = 2 + strlen(s1) + strlen(s2);
1964   compare = g_malloc0(length);
1965   g_snprintf(compare, length, "%s=%s", s1, s2);
1966   proto_tree_add_string(tree, hf_ldap_message_compare, a->tvb, start,
1967       a->offset-start, compare);
1968
1969   g_free(string1);
1970   g_free(string2);
1971   g_free(compare);
1972
1973   return;
1974 }
1975
1976 static void dissect_ldap_request_modify(ASN1_SCK *a, proto_tree *tree)
1977 {
1978   guint seq_length;
1979   int end_of_sequence;
1980   int ret;
1981
1982   if (read_string(a, tree, hf_ldap_message_dn, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1983     return;
1984   ret = read_sequence(a, &seq_length);
1985   if (ret != ASN1_ERR_NOERROR) {
1986     if (tree) {
1987       proto_tree_add_text(tree, a->tvb, a->offset, 0,
1988           "ERROR: Couldn't parse modify request sequence header: %s",
1989           asn1_err_to_str(ret));
1990     }
1991     return;
1992   }
1993   end_of_sequence = a->offset + seq_length;
1994   while (a->offset < end_of_sequence)
1995   {
1996     proto_item *ti;
1997     proto_tree *attr_tree;
1998     guint set_length;
1999     int end_of_set;
2000     guint operation;
2001
2002     ret = read_sequence(a, 0);
2003     if (ret != ASN1_ERR_NOERROR) {
2004       if (tree) {
2005         proto_tree_add_text(tree, a->tvb, a->offset, 0,
2006             "ERROR: Couldn't parse modify request item sequence header: %s",
2007             asn1_err_to_str(ret));
2008       }
2009       return;
2010     }
2011     ret = read_integer(a, 0, -1, 0, &operation, ASN1_ENUM);
2012     if (ret != ASN1_ERR_NOERROR) {
2013       if (tree) {
2014         proto_tree_add_text(tree, a->tvb, a->offset, 0,
2015           "ERROR: Couldn't parse modify operation: %s",
2016           asn1_err_to_str(ret));
2017         return;
2018       }
2019     }
2020     ret = read_sequence(a, 0);
2021     if (ret != ASN1_ERR_NOERROR) {
2022       if (tree) {
2023         proto_tree_add_text(tree, a->tvb, a->offset, 0,
2024             "ERROR: Couldn't parse modify request operation sequence header: %s",
2025             asn1_err_to_str(ret));
2026       }
2027       return;
2028     }
2029
2030     switch (operation)
2031     {
2032      case LDAP_MOD_ADD:
2033       if (read_string(a, tree, hf_ldap_message_modify_add, &ti, 0, 0, ASN1_UNI,
2034                       ASN1_OTS) != ASN1_ERR_NOERROR)
2035         return;
2036       break;
2037
2038      case LDAP_MOD_REPLACE:
2039       if (read_string(a, tree, hf_ldap_message_modify_replace, &ti, 0, 0,
2040                       ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
2041         return;
2042       break;
2043
2044      case LDAP_MOD_DELETE:
2045       if (read_string(a, tree, hf_ldap_message_modify_delete, &ti, 0, 0,
2046                       ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
2047         return;
2048       break;
2049
2050      default:
2051        proto_tree_add_text(tree, a->tvb, a->offset, 0,
2052             "Unknown LDAP modify operation (%u)", operation);
2053        return;
2054     }
2055     attr_tree = proto_item_add_subtree(ti, ett_ldap_attribute);
2056
2057     ret = read_set(a, &set_length);
2058     if (ret != ASN1_ERR_NOERROR) {
2059       if (tree) {
2060         proto_tree_add_text(attr_tree, a->tvb, a->offset, 0,
2061             "ERROR: Couldn't parse LDAP value set header: %s",
2062             asn1_err_to_str(ret));
2063       }
2064       return;
2065     }
2066     end_of_set = a->offset + set_length;
2067     while (a->offset < end_of_set) {
2068       if (read_string(a, attr_tree, hf_ldap_message_value, 0, 0, 0, ASN1_UNI,
2069                       ASN1_OTS) != ASN1_ERR_NOERROR)
2070         return;
2071     }
2072   }
2073 }
2074
2075 static void dissect_ldap_request_abandon(ASN1_SCK *a, proto_tree *tree,
2076                 int start, guint length)
2077 {
2078   read_integer_value(a, tree, hf_ldap_message_abandon_msgid, NULL, NULL,
2079                             start, length);
2080 }
2081
2082 static void dissect_ldap_controls(ASN1_SCK *a, proto_tree *tree)
2083 {
2084   guint cls, con, tag;
2085   gboolean def;
2086   guint length;
2087   int ret;
2088   proto_item *ctrls_item = NULL;
2089   proto_tree *ctrls_tree = NULL;
2090   int start = a->offset;
2091   int end;
2092   guint ctrls_length;
2093
2094   ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
2095   if (ret != ASN1_ERR_NOERROR) {
2096     proto_tree_add_text(tree, a->tvb, a->offset, 0,
2097                         "ERROR: Couldn't parse LDAP Controls: %s",
2098                         asn1_err_to_str(ret));
2099     return;
2100   }
2101   if (cls != ASN1_CTX || con != ASN1_CON || tag != ASN1_EOC) {
2102     proto_tree_add_text(tree, a->tvb, a->offset, 0,
2103                         "ERROR: Couldn't parse LDAP Controls: %s",
2104                         asn1_err_to_str(ASN1_ERR_WRONG_TYPE));
2105     return;
2106   }
2107
2108   ctrls_length = (a->offset - start) + length;
2109   ctrls_item = proto_tree_add_text(tree, a->tvb, start, ctrls_length, "LDAP Controls");
2110   ctrls_tree = proto_item_add_subtree(ctrls_item, ett_ldap_controls);
2111
2112   end = a->offset + length;
2113   while (a->offset < end) {
2114     proto_item *ctrl_item = NULL;
2115     proto_tree *ctrl_tree = NULL;
2116     guint seq_length;
2117     int seq_start = a->offset;
2118     int seq_end;
2119     guint ctrl_length;
2120
2121     ret = read_sequence(a, &seq_length);
2122     if (ret != ASN1_ERR_NOERROR) {
2123       proto_tree_add_text(ctrls_tree, a->tvb, a->offset, 0,
2124                           "ERROR: Couldn't parse LDAP Control: %s",
2125                           asn1_err_to_str(ret));
2126       return;
2127     }
2128
2129     ctrl_length = (a->offset - seq_start) + seq_length;
2130     ctrl_item = proto_tree_add_text(ctrls_tree, a->tvb, seq_start, ctrl_length, "LDAP Control");
2131     ctrl_tree = proto_item_add_subtree(ctrl_item, ett_ldap_control);
2132
2133     seq_end = a->offset + seq_length;
2134
2135     ret = read_string(a, ctrl_tree, hf_ldap_message_controls_oid, 0, 0, 0, ASN1_UNI, ASN1_OTS);
2136     if (ret != ASN1_ERR_NOERROR) {
2137       return;
2138     }
2139
2140     if (a->offset >= seq_end) {
2141       /* skip optional data */
2142       break;
2143     }
2144
2145     ret = check_optional_tag(a, ASN1_UNI, ASN1_PRI, ASN1_BOL);
2146     if (ret == ASN1_ERR_NOERROR) {
2147       ret = read_boolean(a, ctrl_tree, hf_ldap_message_controls_critical, 0, 0);
2148       if (ret != ASN1_ERR_NOERROR) {
2149         return;
2150       }
2151     }
2152
2153     if (a->offset >= seq_end) {
2154       /* skip optional data */
2155       break;
2156     }
2157
2158     ret = check_optional_tag(a, ASN1_UNI, ASN1_PRI, ASN1_OTS);
2159     if (ret == ASN1_ERR_NOERROR) {
2160       ret = read_bytestring(a, ctrl_tree, hf_ldap_message_controls_value, NULL, NULL, ASN1_UNI, ASN1_OTS);
2161       if (ret != ASN1_ERR_NOERROR) {
2162         return;
2163       }
2164     }
2165   }
2166 }
2167
2168 static ldap_call_response_t *
2169 ldap_match_call_response(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, ldap_conv_info_t *ldap_info, guint messageId, guint protocolOpTag)
2170 {
2171   ldap_call_response_t lcr, *lcrp=NULL;
2172
2173   if (!pinfo->fd->flags.visited) {
2174     switch(protocolOpTag){
2175       case LDAP_REQ_BIND:
2176       case LDAP_REQ_SEARCH:
2177       case LDAP_REQ_MODIFY:
2178       case LDAP_REQ_ADD:
2179       case LDAP_REQ_DELETE:
2180       case LDAP_REQ_MODRDN:
2181       case LDAP_REQ_COMPARE:
2182       /*case LDAP_REQ_ABANDON: we dont match for this one*/
2183       /*case LDAP_REQ_UNBIND: we dont match for this one*/
2184         /* check that we dont already have one of those in the
2185            unmatched list and if so remove it */
2186         lcr.messageId=messageId;
2187         lcrp=g_hash_table_lookup(ldap_info->unmatched, &lcr);
2188         if(lcrp){
2189           g_hash_table_remove(ldap_info->unmatched, lcrp);
2190         }
2191         /* if we cant reuse the old one, grab a new chunk */
2192         if(!lcrp){
2193           lcrp=se_alloc(sizeof(ldap_call_response_t));
2194         }
2195         lcrp->messageId=messageId;
2196         lcrp->req_frame=pinfo->fd->num;
2197         lcrp->req_time=pinfo->fd->abs_ts;
2198         lcrp->rep_frame=0;
2199         lcrp->protocolOpTag=protocolOpTag;
2200         lcrp->is_request=TRUE;
2201         g_hash_table_insert(ldap_info->unmatched, lcrp, lcrp);
2202         return NULL;
2203         break;
2204       case LDAP_RES_BIND:
2205       case LDAP_RES_SEARCH_ENTRY:
2206       case LDAP_RES_SEARCH_REF:
2207       case LDAP_RES_SEARCH_RESULT:
2208       case LDAP_RES_MODIFY:
2209       case LDAP_RES_ADD:
2210       case LDAP_RES_DELETE:
2211       case LDAP_RES_MODRDN:
2212       case LDAP_RES_COMPARE:
2213         lcr.messageId=messageId;
2214         lcrp=g_hash_table_lookup(ldap_info->unmatched, &lcr);
2215         if(lcrp){
2216           if(!lcrp->rep_frame){
2217             g_hash_table_remove(ldap_info->unmatched, lcrp);
2218             lcrp->rep_frame=pinfo->fd->num;
2219             lcrp->is_request=FALSE;
2220             g_hash_table_insert(ldap_info->matched, lcrp, lcrp);
2221           }
2222         }
2223     }
2224   }
2225
2226   if(!lcrp){
2227     lcr.messageId=messageId;
2228     switch(protocolOpTag){
2229       case LDAP_REQ_BIND:
2230       case LDAP_REQ_SEARCH:
2231       case LDAP_REQ_MODIFY:
2232       case LDAP_REQ_ADD:
2233       case LDAP_REQ_DELETE:
2234       case LDAP_REQ_MODRDN:
2235       case LDAP_REQ_COMPARE:
2236       /*case LDAP_REQ_ABANDON: we dont match for this one*/
2237       /*case LDAP_REQ_UNBIND: we dont match for this one*/
2238         lcr.is_request=TRUE;
2239         lcr.req_frame=pinfo->fd->num;
2240         lcr.rep_frame=0;
2241         break;
2242       case LDAP_RES_BIND:
2243       case LDAP_RES_SEARCH_ENTRY:
2244       case LDAP_RES_SEARCH_REF:
2245       case LDAP_RES_SEARCH_RESULT:
2246       case LDAP_RES_MODIFY:
2247       case LDAP_RES_ADD:
2248       case LDAP_RES_DELETE:
2249       case LDAP_RES_MODRDN:
2250       case LDAP_RES_COMPARE:
2251         lcr.is_request=FALSE;
2252         lcr.req_frame=0;
2253         lcr.rep_frame=pinfo->fd->num;
2254         break;
2255     }
2256     lcrp=g_hash_table_lookup(ldap_info->matched, &lcr);
2257     if(lcrp){
2258       lcrp->is_request=lcr.is_request;
2259     }
2260   }
2261   if(lcrp){
2262     if(lcrp->is_request){
2263       proto_tree_add_uint(tree, hf_ldap_response_in, tvb, 0, 0, lcrp->rep_frame);
2264     } else {
2265       nstime_t ns;
2266       proto_tree_add_uint(tree, hf_ldap_response_to, tvb, 0, 0, lcrp->req_frame);
2267       nstime_delta(&ns, &pinfo->fd->abs_ts, &lcrp->req_time);
2268       proto_tree_add_time(tree, hf_ldap_time, tvb, 0, 0, &ns);
2269     }
2270     return lcrp;
2271   }
2272   return NULL;
2273 }
2274
2275
2276 static void
2277 dissect_ldap_message(tvbuff_t *tvb, int offset, packet_info *pinfo,
2278                 proto_tree *ldap_tree, proto_item *ldap_item, 
2279                 gboolean first_time, ldap_conv_info_t *ldap_info,
2280                 gboolean is_mscldap)
2281 {
2282   int message_id_start;
2283   int message_id_length;
2284   guint messageLength;
2285   guint messageId;
2286   int next_offset;
2287   guint protocolOpCls, protocolOpCon, protocolOpTag;
2288   const gchar *typestr;
2289   guint opLen;
2290   ASN1_SCK a;
2291   int start;
2292   int ret;
2293   ldap_call_response_t *lcrp;
2294
2295   asn1_open(&a, tvb, offset);
2296
2297   ret = read_sequence(&a, &messageLength);
2298   if (ret != ASN1_ERR_NOERROR)
2299   {
2300     if (first_time)
2301     {
2302       if (check_col(pinfo->cinfo, COL_INFO))
2303       {
2304         col_add_fstr(pinfo->cinfo, COL_INFO,
2305                     "Invalid LDAP message (Can't parse sequence header: %s)",
2306                     asn1_err_to_str(ret));
2307       }
2308     }
2309     if (ldap_tree)
2310     {
2311       proto_tree_add_text(ldap_tree, tvb, offset, -1,
2312                           "Invalid LDAP message (Can't parse sequence header: %s)",
2313                           asn1_err_to_str(ret));
2314     }
2315     return;
2316   }
2317
2318   message_id_start = a.offset;
2319   ret = read_integer(&a, 0, hf_ldap_message_id, 0, &messageId, ASN1_INT);
2320   if (ret != ASN1_ERR_NOERROR)
2321   {
2322     if (first_time && check_col(pinfo->cinfo, COL_INFO))
2323       col_add_fstr(pinfo->cinfo, COL_INFO, "Invalid LDAP packet (Can't parse Message ID: %s)",
2324                    asn1_err_to_str(ret));
2325     if (ldap_tree)
2326       proto_tree_add_text(ldap_tree, tvb, message_id_start, 1,
2327                           "Invalid LDAP packet (Can't parse Message ID: %s)",
2328                           asn1_err_to_str(ret));
2329       return;
2330   }
2331   message_id_length = a.offset - message_id_start;
2332
2333   start = a.offset;
2334   asn1_id_decode(&a, &protocolOpCls, &protocolOpCon, &protocolOpTag);
2335   if (protocolOpCls != ASN1_APL)
2336     typestr = "Bad message type (not Application)";
2337   else
2338     typestr = val_to_str(protocolOpTag, msgTypes, "Unknown message type (%u)");
2339
2340   if (first_time)
2341   {
2342     if (check_col(pinfo->cinfo, COL_INFO))
2343       col_add_fstr(pinfo->cinfo, COL_INFO, "MsgId=%u %s",
2344                    messageId, typestr);
2345   }
2346
2347   if (ldap_item)
2348           proto_item_append_text(ldap_item, ", %s", 
2349                                  val_to_str(protocolOpTag, msgTypes,
2350                                             "Unknown message type (%u)"));
2351
2352   if (ldap_tree)
2353   {
2354     proto_tree_add_uint(ldap_tree, hf_ldap_message_id, tvb, message_id_start, message_id_length, messageId);
2355     if (protocolOpCls == ASN1_APL)
2356     {
2357       proto_tree_add_uint(ldap_tree, hf_ldap_message_type, tvb,
2358                           start, a.offset - start, protocolOpTag);
2359     }
2360     else
2361     {
2362       proto_tree_add_text(ldap_tree, tvb, start, a.offset - start,
2363                           "%s", typestr);
2364     }
2365   }
2366   start = a.offset;
2367   if (read_length(&a, ldap_tree, hf_ldap_message_length, &opLen) != ASN1_ERR_NOERROR)
2368     return;
2369
2370   if (protocolOpCls == ASN1_APL)
2371   {
2372     lcrp=ldap_match_call_response(tvb, pinfo, ldap_tree, ldap_info, messageId, protocolOpTag);
2373     if(lcrp){
2374       tap_queue_packet(ldap_tap, pinfo, lcrp);
2375     }
2376
2377     /*
2378      * XXX - we should check for errors from these routines (and they
2379      * should return errors), and not try to dissect the LDAP controls
2380      * if they get an error.
2381      */
2382     switch (protocolOpTag)
2383     {
2384      case LDAP_REQ_BIND:
2385       dissect_ldap_request_bind(&a, ldap_tree, tvb, pinfo, ldap_info);
2386       break;
2387      case LDAP_REQ_UNBIND:
2388       /* Nothing to dissect */
2389       break;
2390      case LDAP_REQ_SEARCH:
2391       dissect_ldap_request_search(&a, ldap_tree, pinfo);
2392       break;
2393      case LDAP_REQ_MODIFY:
2394       dissect_ldap_request_modify(&a, ldap_tree);
2395       break;
2396      case LDAP_REQ_ADD:
2397       dissect_ldap_request_add(&a, ldap_tree, pinfo);
2398       break;
2399      case LDAP_REQ_DELETE:
2400       dissect_ldap_request_delete(&a, ldap_tree, start, opLen);
2401       break;
2402      case LDAP_REQ_MODRDN:
2403       dissect_ldap_request_modifyrdn(&a, ldap_tree, opLen);
2404       break;
2405      case LDAP_REQ_COMPARE:
2406       dissect_ldap_request_compare(&a, ldap_tree);
2407       break;
2408      case LDAP_REQ_ABANDON:
2409       dissect_ldap_request_abandon(&a, ldap_tree, start, opLen);
2410       break;
2411      case LDAP_RES_BIND:
2412       dissect_ldap_response_bind(&a, ldap_tree, start, opLen, tvb, pinfo, ldap_info);
2413       break;
2414      case LDAP_RES_SEARCH_ENTRY: {
2415             /*
2416              * XXX - this assumes that the LDAP_RES_SEARCH_ENTRY and
2417              * LDAP_RES_SEARCH_RESULT appear in the same frame.
2418              */
2419             guint32 *num_results = p_get_proto_data(pinfo->fd, proto_ldap);
2420
2421             if (!num_results) {
2422                     num_results = g_malloc(sizeof(guint32));
2423                     *num_results = 0;
2424                     p_add_proto_data(pinfo->fd, proto_ldap, num_results);
2425             }
2426
2427             *num_results += 1;
2428             dissect_ldap_response_search_entry(&a, ldap_tree, is_mscldap);
2429
2430             break;
2431      }
2432      case LDAP_RES_SEARCH_REF:
2433       dissect_ldap_response_search_ref(&a, ldap_tree);
2434       break;
2435
2436      case LDAP_RES_SEARCH_RESULT: {
2437              guint32 *num_results = p_get_proto_data(pinfo->fd, proto_ldap);
2438
2439              if (num_results) {
2440                      if (check_col(pinfo->cinfo, COL_INFO))
2441                              col_append_fstr(pinfo->cinfo, COL_INFO, ", %d result%s", 
2442                                              *num_results, *num_results == 1 ? "" : "s");
2443                      g_free(num_results);
2444                      p_rem_proto_data(pinfo->fd, proto_ldap);
2445              }
2446
2447              dissect_ldap_result(&a, ldap_tree, pinfo);
2448
2449              break;
2450      }
2451
2452      case LDAP_RES_MODIFY:
2453      case LDAP_RES_ADD:
2454      case LDAP_RES_DELETE:
2455      case LDAP_RES_MODRDN:
2456      case LDAP_RES_COMPARE:
2457         dissect_ldap_result(&a, ldap_tree, pinfo);
2458       break;
2459      default:
2460       if (ldap_tree)
2461       {
2462         proto_tree_add_text(ldap_tree, a.tvb, a.offset, opLen,
2463                             "Unknown LDAP operation (%u)", protocolOpTag);
2464       }
2465       break;
2466     }
2467   }
2468
2469   if ((int)messageLength > 0 && (message_id_start + (int)messageLength) > a.offset) {
2470     dissect_ldap_controls(&a, ldap_tree);
2471   }
2472
2473   /*
2474    * XXX - what if "next_offset" is past the offset of the next top-level
2475    * sequence?  Show that as an error?
2476    */
2477   asn1_close(&a, &next_offset); /* XXX - use the new value of next_offset? */
2478 }
2479
2480 static void
2481 dissect_ldap_payload(tvbuff_t *tvb, packet_info *pinfo,
2482                      proto_tree *tree, ldap_conv_info_t *ldap_info,
2483                      gboolean rest_is_pad, gboolean is_mscldap)
2484 {
2485   int offset = 0;
2486   gboolean first_time = TRUE;
2487   guint length_remaining;
2488   ASN1_SCK a;
2489   int ret;
2490   guint msg_len = 0;
2491   int messageOffset = 0;
2492   guint headerLength = 0;
2493   guint length = 0;
2494   tvbuff_t *msg_tvb = NULL;
2495   proto_item *msg_item = NULL;
2496   proto_tree *msg_tree = NULL;
2497
2498   while (tvb_reported_length_remaining(tvb, offset) > 0) {
2499     /*
2500      * This will throw an exception if we don't have any data left.
2501      * That's what we want.  (See "tcp_dissect_pdus()", which is
2502      * similar)
2503      */
2504     length_remaining = tvb_ensure_length_remaining(tvb, offset);
2505
2506     if (rest_is_pad && length_remaining < 6) return;
2507
2508     /*
2509      * The frame begins
2510      * with a "Sequence Of" header.
2511      * Can we do reassembly?
2512      */
2513     if (ldap_desegment && pinfo->can_desegment) {
2514         /*
2515          * Yes - is the "Sequence Of" header split across segment
2516          * boundaries?  We require at least 6 bytes for the header
2517          * which allows for a 4 byte length (ASN.1 BER).
2518          */
2519         if (length_remaining < 6) {
2520           /* stop if the caller says that we are given all data and the rest is padding
2521            * this is for the SASL GSSAPI case when the data is only signed and not sealed
2522            */
2523           pinfo->desegment_offset = offset;
2524           pinfo->desegment_len = 6 - length_remaining;
2525           return;
2526         }
2527     }
2528
2529     /*
2530      * OK, try to read the "Sequence Of" header; this gets the total
2531      * length of the LDAP message.
2532      */
2533     asn1_open(&a, tvb, offset);
2534     ret = read_sequence(&a, &msg_len);
2535     asn1_close(&a, &messageOffset);
2536
2537     if (ret == ASN1_ERR_NOERROR) {
2538         /*
2539          * Add the length of the "Sequence Of" header to the message
2540          * length.
2541          */
2542         headerLength = messageOffset - offset;
2543         msg_len += headerLength;
2544         if (msg_len < headerLength) {
2545             /*
2546              * The message length was probably so large that the total length
2547              * overflowed.
2548              *
2549              * Report this as an error.
2550              */
2551             show_reported_bounds_error(tvb, pinfo, tree);
2552             return;
2553         }
2554     } else {
2555         /*
2556          * We couldn't parse the header; just make it the amount of data
2557          * remaining in the tvbuff, so we'll give up on this segment
2558          * after attempting to parse the message - there's nothing more
2559          * we can do.  "dissect_ldap_message()" will display the error.
2560          */
2561         msg_len = length_remaining;
2562     }
2563
2564     /*
2565      * Is the message split across segment boundaries?
2566      */
2567     if (length_remaining < msg_len) {
2568         /* provide a hint to TCP where the next PDU starts */
2569         pinfo->want_pdu_tracking=2;
2570         pinfo->bytes_until_next_pdu= msg_len - length_remaining;
2571         /*
2572          * Can we do reassembly?
2573          */
2574         if (ldap_desegment && pinfo->can_desegment) {
2575             /*
2576              * Yes.  Tell the TCP dissector where the data for this message
2577              * starts in the data it handed us, and how many more bytes
2578              * we need, and return.
2579              */
2580             pinfo->desegment_offset = offset;
2581             pinfo->desegment_len = msg_len - length_remaining;
2582             return;
2583         }
2584     }
2585
2586     /*
2587      * Construct a tvbuff containing the amount of the payload we have
2588      * available.  Make its reported length the amount of data in the
2589      * LDAP message.
2590      *
2591      * XXX - if reassembly isn't enabled. the subdissector will throw a
2592      * BoundsError exception, rather than a ReportedBoundsError exception.
2593      * We really want a tvbuff where the length is "length", the reported
2594      * length is "plen", and the "if the snapshot length were infinite"
2595      * length is the minimum of the reported length of the tvbuff handed
2596      * to us and "plen", with a new type of exception thrown if the offset
2597      * is within the reported length but beyond that third length, with
2598      * that exception getting the "Unreassembled Packet" error.
2599      */
2600     length = length_remaining;
2601     if (length > msg_len) length = msg_len;
2602     msg_tvb = tvb_new_subset(tvb, offset, length, msg_len);
2603
2604     /*
2605      * Now dissect the LDAP message.
2606      */
2607     if (tree) {
2608         msg_item = proto_tree_add_text(tree, msg_tvb, 0, msg_len, "LDAP Message");
2609         msg_tree = proto_item_add_subtree(msg_item, ett_ldap_msg);
2610     }
2611
2612     dissect_ldap_message(msg_tvb, 0, pinfo, msg_tree, msg_item, first_time, ldap_info, is_mscldap);
2613
2614     offset += msg_len;
2615
2616     first_time = FALSE;
2617   }
2618 }
2619
2620
2621 static void
2622 dissect_ldap_pdu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gboolean is_mscldap)
2623 {
2624   int offset = 0;
2625   conversation_t *conversation;
2626   gboolean doing_sasl_security = FALSE;
2627   guint length_remaining;
2628   ldap_conv_info_t *ldap_info = NULL;
2629   proto_item *ldap_item = NULL;
2630   proto_tree *ldap_tree = NULL;
2631
2632   /*
2633    * Do we have a conversation for this connection?
2634    */
2635   conversation = find_conversation(pinfo->fd->num, &pinfo->src, &pinfo->dst,
2636                                    pinfo->ptype, pinfo->srcport,
2637                                    pinfo->destport, 0);
2638   if (conversation == NULL) {
2639     /* We don't yet have a conversation, so create one. */
2640     conversation = conversation_new(pinfo->fd->num, &pinfo->src, &pinfo->dst,
2641                                     pinfo->ptype, pinfo->srcport,
2642                                     pinfo->destport, 0);
2643   }
2644
2645   /*
2646    * Do we already have a type and mechanism?
2647    */
2648   ldap_info = conversation_get_proto_data(conversation, proto_ldap);
2649   if (ldap_info == NULL) {
2650     /* No.  Attach that information to the conversation, and add
2651      * it to the list of information structures.
2652      */
2653     ldap_info = se_alloc(sizeof(ldap_conv_info_t));
2654     ldap_info->auth_type = 0;
2655     ldap_info->auth_mech = 0;
2656     ldap_info->first_auth_frame = 0;
2657     ldap_info->matched=g_hash_table_new(ldap_info_hash_matched, ldap_info_equal_matched);
2658     ldap_info->unmatched=g_hash_table_new(ldap_info_hash_unmatched, ldap_info_equal_unmatched);
2659     conversation_add_proto_data(conversation, proto_ldap, ldap_info);
2660     ldap_info->next = ldap_info_items;
2661     ldap_info_items = ldap_info;
2662   } 
2663
2664   switch (ldap_info->auth_type) {
2665     case LDAP_AUTH_SASL:
2666     /*
2667      * It's SASL; are we using a security layer?
2668      */
2669     if (ldap_info->first_auth_frame != 0 &&
2670        pinfo->fd->num >= ldap_info->first_auth_frame) {
2671         doing_sasl_security = TRUE;     /* yes */
2672     }
2673   }
2674
2675   while (tvb_reported_length_remaining(tvb, offset) > 0) {
2676
2677     /*
2678      * This will throw an exception if we don't have any data left.
2679      * That's what we want.  (See "tcp_dissect_pdus()", which is
2680      * similar, but doesn't have to deal with the SASL issues.
2681      * XXX - can we make "tcp_dissect_pdus()" provide enough information
2682      * to the "get_pdu_len" routine so that we could have one dealing
2683      * with the SASL issues, have that routine deal with SASL and
2684      * ASN.1, and just use "tcp_dissect_pdus()"?)
2685      */
2686     length_remaining = tvb_ensure_length_remaining(tvb, offset);
2687
2688     /*
2689      * Try to find out if we have a plain LDAP buffer
2690      * with a "Sequence Of" header or a SASL buffer with
2691      * Can we do reassembly?
2692      */
2693     if (ldap_desegment && pinfo->can_desegment) {
2694         /*
2695          * Yes - is the "Sequence Of" header split across segment
2696          * boundaries?  We require at least 6 bytes for the header
2697          * which allows for a 4 byte length (ASN.1 BER).
2698          * For the SASL case we need at least 4 bytes, so this is 
2699          * no problem here because we check for 6 bytes ans sasl buffers
2700          * with less than 2 bytes should not exist...
2701          */
2702         if (length_remaining < 6) {
2703             pinfo->desegment_offset = offset;
2704             pinfo->desegment_len = 6 - length_remaining;
2705             return;
2706         }
2707     }
2708
2709     /* It might still be a packet containing a SASL security layer
2710      * but its just that we never saw the BIND packet.
2711      * check if it looks like it could be a SASL blob here
2712      * and in that case just assume it is GSS-SPNEGO
2713      */
2714     if(!doing_sasl_security && (tvb_bytes_exist(tvb, offset, 5))
2715       &&(tvb_get_ntohl(tvb, offset)<=(guint)(tvb_reported_length_remaining(tvb, offset)-4))
2716       &&(tvb_get_guint8(tvb, offset+4)==0x60) ){
2717         ldap_info->auth_type=LDAP_AUTH_SASL;
2718         ldap_info->first_auth_frame=pinfo->fd->num;
2719         ldap_info->auth_mech=g_strdup("GSS-SPNEGO");
2720         doing_sasl_security=TRUE;
2721     }
2722
2723     /*
2724      * This is the first PDU, set the Protocol column and clear the
2725      * Info column.
2726      */
2727     if (check_col(pinfo->cinfo, COL_PROTOCOL)) col_set_str(pinfo->cinfo, COL_PROTOCOL, pinfo->current_proto);
2728     if (check_col(pinfo->cinfo, COL_INFO)) col_clear(pinfo->cinfo, COL_INFO);
2729
2730     ldap_item = proto_tree_add_item(tree, proto_ldap, tvb, 0, -1, FALSE);
2731     ldap_tree = proto_item_add_subtree(ldap_item, ett_ldap);
2732
2733     /*
2734      * Might we be doing a SASL security layer and, if so, *are* we doing
2735      * one?
2736      *
2737      * Just because we've seen a bind reply for SASL, that doesn't mean
2738      * that we're using a SASL security layer; I've seen captures in
2739      * which some SASL negotiations lead to a security layer being used
2740      * and other negotiations don't, and it's not obvious what's different
2741      * in the two negotiations.  Therefore, we assume that if the first
2742      * byte is 0, it's a length for a SASL security layer (that way, we
2743      * never reassemble more than 16 megabytes, protecting us from
2744      * chewing up *too* much memory), and otherwise that it's an LDAP
2745      * message (actually, if it's an LDAP message it should begin with 0x30,
2746      * but we want to parse garbage as LDAP messages rather than really
2747      * huge lengths).
2748      */
2749
2750     if (doing_sasl_security && tvb_get_guint8(tvb, offset) == 0) {
2751       proto_item *sasl_item = NULL;
2752       proto_tree *sasl_tree = NULL;
2753       tvbuff_t *sasl_tvb;
2754       guint sasl_len, sasl_msg_len, length;
2755       /*
2756        * Yes.  The frame begins with a 4-byte big-endian length.
2757        * And we know we have at least 6 bytes
2758        */
2759
2760       /*
2761        * Get the SASL length, which is the length of data in the buffer
2762        * following the length (i.e., it's 4 less than the total length).
2763        *
2764        * XXX - do we need to reassemble buffers?  For now, we
2765        * assume that each LDAP message is entirely contained within
2766        * a buffer.
2767        */
2768       sasl_len = tvb_get_ntohl(tvb, offset);
2769       sasl_msg_len = sasl_len + 4;
2770       if (sasl_msg_len < 4) {
2771         /*
2772          * The message length was probably so large that the total length
2773          * overflowed.
2774          *
2775          * Report this as an error.
2776          */
2777         show_reported_bounds_error(tvb, pinfo, tree);
2778         return;
2779       }
2780
2781       /*
2782        * Is the buffer split across segment boundaries?
2783        */
2784       if (length_remaining < sasl_msg_len) {
2785         /* provide a hint to TCP where the next PDU starts */
2786         pinfo->want_pdu_tracking = 2;
2787         pinfo->bytes_until_next_pdu= sasl_msg_len - length_remaining;
2788         /*
2789          * Can we do reassembly?
2790          */
2791         if (ldap_desegment && pinfo->can_desegment) {
2792           /*
2793            * Yes.  Tell the TCP dissector where the data for this message
2794            * starts in the data it handed us, and how many more bytes we
2795            * need, and return.
2796            */
2797           pinfo->desegment_offset = offset;
2798           pinfo->desegment_len = sasl_msg_len - length_remaining;
2799           return;
2800         }
2801       }
2802
2803       /*
2804        * Construct a tvbuff containing the amount of the payload we have
2805        * available.  Make its reported length the amount of data in the PDU.
2806        *
2807        * XXX - if reassembly isn't enabled. the subdissector will throw a
2808        * BoundsError exception, rather than a ReportedBoundsError exception.
2809        * We really want a tvbuff where the length is "length", the reported
2810        * length is "plen", and the "if the snapshot length were infinite"
2811        * length is the minimum of the reported length of the tvbuff handed
2812        * to us and "plen", with a new type of exception thrown if the offset
2813        * is within the reported length but beyond that third length, with
2814        * that exception getting the "Unreassembled Packet" error.
2815        */
2816       length = length_remaining;
2817       if (length > sasl_msg_len) length = sasl_msg_len;
2818       sasl_tvb = tvb_new_subset(tvb, offset, length, sasl_msg_len);
2819
2820       if (ldap_tree) {
2821         proto_tree_add_uint(ldap_tree, hf_ldap_sasl_buffer_length, sasl_tvb, 0, 4,
2822                             sasl_len);
2823
2824         sasl_item = proto_tree_add_text(ldap_tree, sasl_tvb, 0,  sasl_msg_len, "SASL buffer");
2825         sasl_tree = proto_item_add_subtree(sasl_item, ett_ldap_sasl_blob);
2826       }
2827
2828       if (ldap_info->auth_mech != NULL &&
2829           strcmp(ldap_info->auth_mech, "GSS-SPNEGO") == 0) {
2830           tvbuff_t *gssapi_tvb, *plain_tvb = NULL, *decr_tvb= NULL;
2831           int ver_len;
2832           int length;
2833
2834           /*
2835            * This is GSS-API (using SPNEGO, but we should be done with
2836            * the negotiation by now).
2837            *
2838            * Dissect the GSS_Wrap() token; it'll return the length of
2839            * the token, from which we compute the offset in the tvbuff at
2840            * which the plaintext data, i.e. the LDAP message, begins.
2841            */
2842           length = tvb_length_remaining(sasl_tvb, 4);
2843           if ((guint)length > sasl_len)
2844               length = sasl_len;
2845           gssapi_tvb = tvb_new_subset(sasl_tvb, 4, length, sasl_len);
2846
2847           /* Attempt decryption of the GSSAPI wrapped data if possible */
2848           pinfo->decrypt_gssapi_tvb=DECRYPT_GSSAPI_NORMAL;
2849           pinfo->gssapi_wrap_tvb=NULL;
2850           pinfo->gssapi_encrypted_tvb=NULL;
2851           pinfo->gssapi_decrypted_tvb=NULL;
2852           ver_len = call_dissector(gssapi_wrap_handle, gssapi_tvb, pinfo, sasl_tree);
2853           /* if we could unwrap, do a tvb shuffle */
2854           if(pinfo->gssapi_decrypted_tvb){
2855                 decr_tvb=pinfo->gssapi_decrypted_tvb;
2856           }
2857           /* tidy up */
2858           pinfo->decrypt_gssapi_tvb=0;
2859           pinfo->gssapi_wrap_tvb=NULL;
2860           pinfo->gssapi_encrypted_tvb=NULL;
2861           pinfo->gssapi_decrypted_tvb=NULL;
2862
2863           /*
2864            * if len is 0 it probably mean that we got a PDU that is not
2865            * aligned to the start of the segment.
2866            */
2867           if(ver_len==0){
2868              return;
2869           }
2870
2871           /*
2872            * if we don't have unwrapped data,
2873            * see if the wrapping involved encryption of the
2874            * data; if not, just use the plaintext data.
2875            */
2876           if (!decr_tvb) {
2877             if(!pinfo->gssapi_data_encrypted){
2878               plain_tvb = tvb_new_subset(gssapi_tvb,  ver_len, -1, -1);
2879             }
2880           }
2881
2882           if (decr_tvb) {
2883             proto_item *enc_item = NULL;
2884             proto_tree *enc_tree = NULL;
2885
2886             /*
2887              * The LDAP message was encrypted in the packet, and has
2888              * been decrypted; dissect the decrypted LDAP message.
2889              */
2890             if (sasl_tree) {
2891               enc_item = proto_tree_add_text(sasl_tree, gssapi_tvb, ver_len, -1,
2892                                 "GSS-API Encrypted payload (%d byte%s)",
2893                                 sasl_len - ver_len,
2894                                 plurality(sasl_len - ver_len, "", "s"));
2895               enc_tree = proto_item_add_subtree(enc_item, ett_ldap_payload);
2896             }
2897             dissect_ldap_payload(decr_tvb, pinfo, enc_tree, ldap_info, TRUE, is_mscldap);
2898           } else if (plain_tvb) {
2899             proto_item *plain_item = NULL;
2900             proto_tree *plain_tree = NULL;
2901
2902             /*
2903              * The LDAP message wasn't encrypted in the packet;
2904              * dissect the plain LDAP message.
2905              */
2906             if (sasl_tree) {
2907               plain_item = proto_tree_add_text(sasl_tree, gssapi_tvb, ver_len, -1,
2908                                 "GSS-API payload (%d byte%s)",
2909                                 sasl_len - ver_len,
2910                                 plurality(sasl_len - ver_len, "", "s"));
2911               plain_tree = proto_item_add_subtree(plain_item, ett_ldap_payload);
2912             }
2913             dissect_ldap_payload(plain_tvb, pinfo, plain_tree, ldap_info, TRUE, is_mscldap);
2914           } else {
2915             /*
2916              * The LDAP message was encrypted in the packet, and was
2917              * not decrypted; just show it as encrypted data.
2918              */
2919             if (check_col(pinfo->cinfo, COL_INFO)) {
2920                     col_add_fstr(pinfo->cinfo, COL_INFO, "LDAP GSS-API Encrypted payload (%d byte%s)",
2921                                  sasl_len - ver_len,
2922                                  plurality(sasl_len - ver_len, "", "s"));
2923             }
2924             if (sasl_tree) {
2925               proto_tree_add_text(sasl_tree, gssapi_tvb, ver_len, -1,
2926                                 "GSS-API Encrypted payload (%d byte%s)",
2927                                 sasl_len - ver_len,
2928                                 plurality(sasl_len - ver_len, "", "s"));
2929             }
2930           }
2931       }
2932       offset += sasl_msg_len;
2933     } else {
2934         /* plain LDAP, so dissect the payload */
2935         dissect_ldap_payload(tvb, pinfo, ldap_tree, ldap_info, FALSE, is_mscldap);
2936         /* dissect_ldap_payload() has it's own loop so go out here */
2937         break;
2938     }
2939   }
2940 }
2941
2942
2943 static void
2944 dissect_ldap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
2945 {
2946         dissect_ldap_pdu(tvb, pinfo, tree, FALSE);
2947         return;
2948 }
2949
2950 static void
2951 dissect_mscldap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
2952 {
2953         dissect_ldap_pdu(tvb, pinfo, tree, TRUE);
2954         return;
2955 }
2956
2957 static void
2958 ldap_reinit(void)
2959 {
2960   ldap_conv_info_t *ldap_info;
2961
2962   /* Free up state attached to the ldap_info structures */
2963   for (ldap_info = ldap_info_items; ldap_info != NULL; ldap_info = ldap_info->next) {
2964     if (ldap_info->auth_mech != NULL) {
2965       g_free(ldap_info->auth_mech);
2966       ldap_info->auth_mech=NULL;
2967     }
2968     g_hash_table_destroy(ldap_info->matched);
2969     ldap_info->matched=NULL;
2970     g_hash_table_destroy(ldap_info->unmatched);
2971     ldap_info->unmatched=NULL;
2972   }
2973
2974   ldap_info_items = NULL;
2975
2976 }
2977
2978 void
2979 proto_register_ldap(void)
2980 {
2981   static value_string auth_types[] = {
2982     {LDAP_AUTH_SIMPLE,    "Simple"},
2983     {LDAP_AUTH_KRBV4LDAP, "Kerberos V4 to the LDAP server"},
2984     {LDAP_AUTH_KRBV4DSA,  "Kerberos V4 to the DSA"},
2985     {LDAP_AUTH_SASL,      "SASL"},
2986     {0, NULL},
2987   };
2988
2989   static value_string search_scope[] = {
2990     {0x00, "Base"},
2991     {0x01, "Single"},
2992     {0x02, "Subtree"},
2993     {0x00, NULL},
2994   };
2995
2996   static value_string search_dereference[] = {
2997     {0x00, "Never"},
2998     {0x01, "Searching"},
2999     {0x02, "Base Object"},
3000     {0x03, "Always"},
3001     {0x00, NULL},
3002   };
3003
3004   static hf_register_info hf[] = {
3005     { &hf_ldap_response_in,
3006       { "Response In", "ldap.response_in",
3007         FT_FRAMENUM, BASE_DEC, NULL, 0x0,
3008         "The response to this packet is in this frame", HFILL }},
3009
3010     { &hf_ldap_response_to,
3011       { "Response To", "ldap.response_to",
3012         FT_FRAMENUM, BASE_DEC, NULL, 0x0,
3013         "This is a response to the LDAP command in this frame", HFILL }},
3014
3015     { &hf_ldap_time,
3016       { "Time", "ldap.time",
3017         FT_RELATIVE_TIME, BASE_NONE, NULL, 0x0,
3018         "The time between the Call and the Reply", HFILL }},
3019
3020     { &hf_ldap_sasl_buffer_length,
3021       { "SASL Buffer Length",   "ldap.sasl_buffer_length",
3022         FT_UINT32, BASE_DEC, NULL, 0x0,
3023         "SASL Buffer Length", HFILL }},
3024
3025     { &hf_ldap_length,
3026       { "Length",               "ldap.length",
3027         FT_UINT32, BASE_DEC, NULL, 0x0,
3028         "LDAP Length", HFILL }},
3029
3030     { &hf_ldap_message_id,
3031       { "Message Id",           "ldap.message_id",
3032         FT_UINT32, BASE_DEC, NULL, 0x0,
3033         "LDAP Message Id", HFILL }},
3034     { &hf_ldap_message_type,
3035       { "Message Type",         "ldap.message_type",
3036         FT_UINT8, BASE_HEX, &msgTypes, 0x0,
3037         "LDAP Message Type", HFILL }},
3038     { &hf_ldap_message_length,
3039       { "Message Length",               "ldap.message_length",
3040         FT_UINT32, BASE_DEC, NULL, 0x0,
3041         "LDAP Message Length", HFILL }},
3042
3043     { &hf_ldap_message_result,
3044       { "Result Code",          "ldap.result.code",
3045         FT_UINT8, BASE_HEX, VALS(LDAPResultCode_vals), 0x0,
3046         "LDAP Result Code", HFILL }},
3047     { &hf_ldap_message_result_matcheddn,
3048       { "Matched DN",           "ldap.result.matcheddn",
3049         FT_STRING, BASE_NONE, NULL, 0x0,
3050         "LDAP Result Matched DN", HFILL }},
3051     { &hf_ldap_message_result_errormsg,
3052       { "Error Message",                "ldap.result.errormsg",
3053         FT_STRING, BASE_NONE, NULL, 0x0,
3054         "LDAP Result Error Message", HFILL }},
3055     { &hf_ldap_message_result_referral,
3056       { "Referral",             "ldap.result.referral",
3057         FT_STRING, BASE_NONE, NULL, 0x0,
3058         "LDAP Result Referral URL", HFILL }},
3059
3060     { &hf_ldap_message_bind_version,
3061       { "Version",              "ldap.bind.version",
3062         FT_UINT32, BASE_DEC, NULL, 0x0,
3063         "LDAP Bind Version", HFILL }},
3064     { &hf_ldap_message_bind_dn,
3065       { "DN",                   "ldap.bind.dn",
3066         FT_STRING, BASE_NONE, NULL, 0x0,
3067         "LDAP Bind Distinguished Name", HFILL }},
3068     { &hf_ldap_message_bind_auth,
3069       { "Auth Type",            "ldap.bind.auth_type",
3070         FT_UINT8, BASE_HEX, auth_types, 0x0,
3071         "LDAP Bind Auth Type", HFILL }},
3072     { &hf_ldap_message_bind_auth_password,
3073       { "Password",             "ldap.bind.password",
3074         FT_STRING, BASE_NONE, NULL, 0x0,
3075         "LDAP Bind Password", HFILL }},
3076     { &hf_ldap_message_bind_auth_mechanism,
3077       { "Mechanism",            "ldap.bind.mechanism",
3078         FT_STRING, BASE_NONE, NULL, 0x0,
3079         "LDAP Bind Mechanism", HFILL }},
3080     { &hf_ldap_message_bind_auth_credentials,
3081       { "Credentials",          "ldap.bind.credentials",
3082         FT_BYTES, BASE_NONE, NULL, 0x0,
3083         "LDAP Bind Credentials", HFILL }},
3084     { &hf_ldap_message_bind_server_credentials,
3085       { "Server Credentials",   "ldap.bind.server_credentials",
3086         FT_BYTES, BASE_NONE, NULL, 0x0,
3087         "LDAP Bind Server Credentials", HFILL }},
3088
3089     { &hf_ldap_message_search_base,
3090       { "Base DN",              "ldap.search.basedn",
3091         FT_STRING, BASE_NONE, NULL, 0x0,
3092         "LDAP Search Base Distinguished Name", HFILL }},
3093     { &hf_ldap_message_search_scope,
3094       { "Scope",                        "ldap.search.scope",
3095         FT_UINT8, BASE_HEX, search_scope, 0x0,
3096         "LDAP Search Scope", HFILL }},
3097     { &hf_ldap_message_search_deref,
3098       { "Dereference",          "ldap.search.dereference",
3099         FT_UINT8, BASE_HEX, search_dereference, 0x0,
3100         "LDAP Search Dereference", HFILL }},
3101     { &hf_ldap_message_search_sizeLimit,
3102       { "Size Limit",           "ldap.search.sizelimit",
3103         FT_UINT32, BASE_DEC, NULL, 0x0,
3104         "LDAP Search Size Limit", HFILL }},
3105     { &hf_ldap_message_search_timeLimit,
3106       { "Time Limit",           "ldap.search.timelimit",
3107         FT_UINT32, BASE_DEC, NULL, 0x0,
3108         "LDAP Search Time Limit", HFILL }},
3109     { &hf_ldap_message_search_typesOnly,
3110       { "Attributes Only",      "ldap.search.typesonly",
3111         FT_BOOLEAN, BASE_NONE, NULL, 0x0,
3112         "LDAP Search Attributes Only", HFILL }},
3113     { &hf_ldap_message_search_filter,
3114       { "Filter",               "ldap.search.filter",
3115         FT_STRING, BASE_NONE, NULL, 0x0,
3116         "LDAP Search Filter", HFILL }},
3117     { &hf_ldap_message_search_reference,
3118       { "Reference URL",        "ldap.search.reference",
3119         FT_STRING, BASE_NONE, NULL, 0x0,
3120         "LDAP Search Reference URL", HFILL }},
3121     { &hf_ldap_message_dn,
3122       { "Distinguished Name",   "ldap.dn",
3123         FT_STRING, BASE_NONE, NULL, 0x0,
3124         "LDAP Distinguished Name", HFILL }},
3125     { &hf_ldap_message_attribute,
3126       { "Attribute",            "ldap.attribute",
3127         FT_STRING, BASE_NONE, NULL, 0x0,
3128         "LDAP Attribute", HFILL }},
3129     /*
3130      * XXX - not all LDAP values are text strings; we'd need a file
3131      * describing which values (by name) are text strings and which are
3132      * binary.
3133      *
3134      * Some values that are, at least in Microsoft's schema, binary
3135      * are:
3136      *
3137      *  invocationId
3138      *  nTSecurityDescriptor
3139      *  objectGUID
3140      */
3141     { &hf_ldap_message_value,
3142       { "Value",                "ldap.value",
3143         FT_STRING, BASE_NONE, NULL, 0x0,
3144         "LDAP Value", HFILL }},
3145
3146     { &hf_ldap_message_modrdn_name,
3147       { "New Name",             "ldap.modrdn.name",
3148         FT_STRING, BASE_NONE, NULL, 0x0,
3149         "LDAP New Name", HFILL }},
3150     { &hf_ldap_message_modrdn_delete,
3151       { "Delete Values",        "ldap.modrdn.delete",
3152         FT_BOOLEAN, BASE_NONE, NULL, 0x0,
3153         "LDAP Modify RDN - Delete original values", HFILL }},
3154     { &hf_ldap_message_modrdn_superior,
3155       { "New Location",         "ldap.modrdn.superior",
3156         FT_STRING, BASE_NONE, NULL, 0x0,
3157         "LDAP Modify RDN - New Location", HFILL }},
3158
3159     { &hf_ldap_message_compare,
3160       { "Test",         "ldap.compare.test",
3161         FT_STRING, BASE_NONE, NULL, 0x0,
3162         "LDAP Compare Test", HFILL }},
3163
3164     { &hf_ldap_message_modify_add,
3165       { "Add",                  "ldap.modify.add",
3166         FT_STRING, BASE_NONE, NULL, 0x0,
3167         "LDAP Add", HFILL }},
3168     { &hf_ldap_message_modify_replace,
3169       { "Replace",              "ldap.modify.replace",
3170         FT_STRING, BASE_NONE, NULL, 0x0,
3171         "LDAP Replace", HFILL }},
3172     { &hf_ldap_message_modify_delete,
3173       { "Delete",               "ldap.modify.delete",
3174         FT_STRING, BASE_NONE, NULL, 0x0,
3175         "LDAP Delete", HFILL }},
3176
3177     { &hf_ldap_message_abandon_msgid,
3178       { "Abandon Msg Id",       "ldap.abandon.msgid",
3179         FT_UINT32, BASE_DEC, NULL, 0x0,
3180         "LDAP Abandon Msg Id", HFILL }},
3181
3182     { &hf_ldap_message_controls_oid,
3183       { "Control OID",  "ldap.controls.oid",
3184         FT_STRING, BASE_NONE, NULL, 0x0,
3185         "LDAP Control OID", HFILL }},
3186
3187     { &hf_ldap_message_controls_critical,
3188       { "Control Critical",     "ldap.controls.critical",
3189         FT_BOOLEAN, BASE_NONE, NULL, 0x0,
3190         "LDAP Control Critical", HFILL }},
3191
3192     { &hf_ldap_message_controls_value,
3193       { "Control Value",        "ldap.controls.value",
3194         FT_BYTES, BASE_NONE, NULL, 0x0,
3195         "LDAP Control Value", HFILL }},
3196
3197     { &hf_mscldap_netlogon_type,
3198       { "Type", "mscldap.netlogon.type",
3199         FT_UINT32, BASE_DEC, NULL, 0x0,
3200         "Type of <please tell ethereal developers what this type is>", HFILL }},
3201
3202     { &hf_mscldap_netlogon_version,
3203       { "Version", "mscldap.netlogon.version",
3204         FT_UINT32, BASE_DEC, NULL, 0x0,
3205         "Version of <please tell ethereal developers what this type is>", HFILL }},
3206
3207     { &hf_mscldap_netlogon_lm_token,
3208       { "LM Token", "mscldap.netlogon.lm_token",
3209         FT_UINT16, BASE_HEX, NULL, 0x0,
3210         "LM Token", HFILL }},
3211
3212     { &hf_mscldap_netlogon_nt_token,
3213       { "NT Token", "mscldap.netlogon.nt_token",
3214         FT_UINT16, BASE_HEX, NULL, 0x0,
3215         "NT Token", HFILL }},
3216
3217     { &hf_mscldap_netlogon_flags,
3218       { "Flags", "mscldap.netlogon.flags",
3219         FT_UINT32, BASE_HEX, NULL, 0x0,
3220         "Netlogon flags describing the DC properties", HFILL }},
3221
3222     { &hf_mscldap_domain_guid,
3223       { "Domain GUID", "mscldap.domain.guid",
3224         FT_BYTES, BASE_HEX, NULL, 0x0,
3225         "Domain GUID", HFILL }},
3226
3227     { &hf_mscldap_forest,
3228       { "Forest", "mscldap.forest",
3229         FT_STRING, BASE_NONE, NULL, 0x0,
3230         "Forest", HFILL }},
3231
3232     { &hf_mscldap_domain,
3233       { "Domain", "mscldap.domain",
3234         FT_STRING, BASE_NONE, NULL, 0x0,
3235         "Domainname", HFILL }},
3236
3237     { &hf_mscldap_hostname,
3238       { "Hostname", "mscldap.hostname",
3239         FT_STRING, BASE_NONE, NULL, 0x0,
3240         "Hostname", HFILL }},
3241
3242     { &hf_mscldap_nb_domain,
3243       { "NetBios Domain", "mscldap.nb_domain",
3244         FT_STRING, BASE_NONE, NULL, 0x0,
3245         "NetBios Domainname", HFILL }},
3246
3247     { &hf_mscldap_nb_hostname,
3248       { "NetBios Hostname", "mscldap.nb_hostname",
3249         FT_STRING, BASE_NONE, NULL, 0x0,
3250         "NetBios Hostname", HFILL }},
3251
3252     { &hf_mscldap_username,
3253       { "User", "mscldap.username",
3254         FT_STRING, BASE_NONE, NULL, 0x0,
3255         "User name", HFILL }},
3256
3257     { &hf_mscldap_sitename,
3258       { "Site", "mscldap.sitename",
3259         FT_STRING, BASE_NONE, NULL, 0x0,
3260         "Site name", HFILL }},
3261
3262     { &hf_mscldap_clientsitename,
3263       { "Client Site", "mscldap.clientsitename",
3264         FT_STRING, BASE_NONE, NULL, 0x0,
3265         "Client Site name", HFILL }},
3266
3267     { &hf_mscldap_netlogon_flags_pdc,
3268       { "PDC", "mscldap.netlogon.flags.pdc", FT_BOOLEAN, 32,
3269         TFS(&tfs_ads_pdc), 0x00000001, "Is this DC a PDC or not?", HFILL }},
3270
3271     { &hf_mscldap_netlogon_flags_gc,
3272       { "GC", "mscldap.netlogon.flags.gc", FT_BOOLEAN, 32,
3273         TFS(&tfs_ads_gc), 0x00000004, "Does this dc service as a GLOBAL CATALOGUE?", HFILL }},
3274
3275     { &hf_mscldap_netlogon_flags_ldap,
3276       { "LDAP", "mscldap.netlogon.flags.ldap", FT_BOOLEAN, 32,
3277         TFS(&tfs_ads_ldap), 0x00000008, "Does this DC act as an LDAP server?", HFILL }},
3278
3279     { &hf_mscldap_netlogon_flags_ds,
3280       { "DS", "mscldap.netlogon.flags.ds", FT_BOOLEAN, 32,
3281         TFS(&tfs_ads_ds), 0x00000010, "Does this dc provide DS services?", HFILL }},
3282
3283     { &hf_mscldap_netlogon_flags_kdc,
3284       { "KDC", "mscldap.netlogon.flags.kdc", FT_BOOLEAN, 32,
3285         TFS(&tfs_ads_kdc), 0x00000020, "Does this dc act as a KDC?", HFILL }},
3286
3287     { &hf_mscldap_netlogon_flags_timeserv,
3288       { "Time Serv", "mscldap.netlogon.flags.timeserv", FT_BOOLEAN, 32,
3289         TFS(&tfs_ads_timeserv), 0x00000040, "Does this dc provide time services (ntp) ?", HFILL }},
3290
3291     { &hf_mscldap_netlogon_flags_closest,
3292       { "Closest", "mscldap.netlogon.flags.closest", FT_BOOLEAN, 32,
3293         TFS(&tfs_ads_closest), 0x00000080, "Is this the closest dc? (is this used at all?)", HFILL }},
3294
3295     { &hf_mscldap_netlogon_flags_writable,
3296       { "Writable", "mscldap.netlogon.flags.writable", FT_BOOLEAN, 32,
3297         TFS(&tfs_ads_writable), 0x00000100, "Is this dc writable? (i.e. can it update the AD?)", HFILL }},
3298
3299     { &hf_mscldap_netlogon_flags_good_timeserv,
3300       { "Good Time Serv", "mscldap.netlogon.flags.good_timeserv", FT_BOOLEAN, 32,
3301         TFS(&tfs_ads_good_timeserv), 0x00000200, "Is this a Good Time Server? (i.e. does it have a hardware clock)", HFILL }},
3302
3303     { &hf_mscldap_netlogon_flags_ndnc,
3304       { "NDNC", "mscldap.netlogon.flags.ndnc", FT_BOOLEAN, 32,
3305         TFS(&tfs_ads_ndnc), 0x00000400, "Is this an NDNC dc?", HFILL }},
3306
3307   };
3308
3309   static gint *ett[] = {
3310     &ett_ldap,
3311     &ett_ldap_msg,
3312     &ett_ldap_payload,
3313     &ett_ldap_sasl_blob,
3314     &ett_ldap_referrals,
3315     &ett_ldap_attribute,
3316     &ett_ldap_controls,
3317     &ett_ldap_control,
3318     &ett_mscldap_netlogon_flags
3319   };
3320   module_t *ldap_module;
3321
3322   proto_ldap = proto_register_protocol("Lightweight Directory Access Protocol",
3323                                        "LDAP", "ldap");
3324   proto_register_field_array(proto_ldap, hf, array_length(hf));
3325   proto_register_subtree_array(ett, array_length(ett));
3326
3327   ldap_module = prefs_register_protocol(proto_ldap, NULL);
3328   prefs_register_bool_preference(ldap_module, "desegment_ldap_messages",
3329     "Reassemble LDAP messages spanning multiple TCP segments",
3330     "Whether the LDAP dissector should reassemble messages spanning multiple TCP segments."
3331     " To use this option, you must also enable \"Allow subdissectors to reassemble TCP streams\" in the TCP protocol settings.",
3332     &ldap_desegment);
3333
3334   proto_cldap = proto_register_protocol(
3335           "Connectionless Lightweight Directory Access Protocol",
3336           "CLDAP", "cldap");
3337
3338   register_init_routine(ldap_reinit);
3339   ldap_tap=register_tap("ldap");
3340 }
3341
3342 void
3343 proto_reg_handoff_ldap(void)
3344 {
3345   dissector_handle_t ldap_handle, cldap_handle;
3346
3347   ldap_handle = create_dissector_handle(dissect_ldap, proto_ldap);
3348   dissector_add("tcp.port", TCP_PORT_LDAP, ldap_handle);
3349   dissector_add("tcp.port", TCP_PORT_GLOBALCAT_LDAP, ldap_handle);
3350
3351   cldap_handle = create_dissector_handle(dissect_mscldap, proto_cldap);
3352   dissector_add("udp.port", UDP_PORT_CLDAP, cldap_handle);
3353
3354   gssapi_handle = find_dissector("gssapi");
3355   gssapi_wrap_handle = find_dissector("gssapi_verf");
3356
3357 /*  http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dsml/dsml/ldap_controls_and_session_support.asp */
3358 register_ber_oid_name("1.2.840.113556.1.4.319","LDAP_PAGED_RESULT_OID_STRING"); 
3359 register_ber_oid_name("1.2.840.113556.1.4.417","LDAP_SERVER_SHOW_DELETED_OID"); 
3360 register_ber_oid_name("1.2.840.113556.1.4.473","LDAP_SERVER_SORT_OID"); 
3361 register_ber_oid_name("1.2.840.113556.1.4.521","LDAP_SERVER_CROSSDOM_MOVE_TARGET_OID"); 
3362 register_ber_oid_name("1.2.840.113556.1.4.528","LDAP_SERVER_NOTIFICATION_OID"); 
3363 register_ber_oid_name("1.2.840.113556.1.4.529","LDAP_SERVER_EXTENDED_DN_OID"); 
3364 register_ber_oid_name("1.2.840.113556.1.4.619","LDAP_SERVER_LAZY_COMMIT_OID"); 
3365 register_ber_oid_name("1.2.840.113556.1.4.801","LDAP_SERVER_SD_FLAGS_OID"); 
3366 register_ber_oid_name("1.2.840.113556.1.4.805","LDAP_SERVER_TREE_DELETE_OID"); 
3367 register_ber_oid_name("1.2.840.113556.1.4.841","LDAP_SERVER_DIRSYNC_OID"); 
3368 register_ber_oid_name("1.2.840.113556.1.4.970 ","None"); 
3369 register_ber_oid_name("1.2.840.113556.1.4.1338","LDAP_SERVER_VERIFY_NAME_OID"); 
3370 register_ber_oid_name("1.2.840.113556.1.4.1339","LDAP_SERVER_DOMAIN_SCOPE_OID"); 
3371 register_ber_oid_name("1.2.840.113556.1.4.1340","LDAP_SERVER_SEARCH_OPTIONS_OID"); 
3372 register_ber_oid_name("1.2.840.113556.1.4.1413","LDAP_SERVER_PERMISSIVE_MODIFY_OID"); 
3373 register_ber_oid_name("1.2.840.113556.1.4.1504","LDAP_SERVER_ASQ_OID"); 
3374 register_ber_oid_name("1.2.840.113556.1.4.1781","LDAP_SERVER_FAST_BIND_OID"); 
3375 register_ber_oid_name("1.3.6.1.4.1.1466.101.119.1","None"); 
3376 register_ber_oid_name("1.3.6.1.4.1.1466.20037","LDAP_START_TLS_OID"); 
3377 register_ber_oid_name("2.16.840.1.113730.3.4.9","LDAP_CONTROL_VLVREQUEST VLV");
3378 }