done:
[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   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     static char *dnString = "dn";
781     int ret;
782     guint length;
783     char *filterp;
784     guint seq_len;
785     guint header_bytes;
786     guint string_length;
787     guint end;
788     guchar *matchingRule, *type, *matchValue;
789     gboolean dnAttributes;
790
791     /* ASN.1 parsing vars ... */
792     guint cls;
793     guint con;
794     guint tag;
795     gboolean def;
796     
797     /*
798      *  MatchingRuleAssertion ::= SEQUENCE {
799      *    matchingRule [1] MatchingRuleId OPTIONAL,
800      *    type         [2] AttributeDescription OPTIONAL,
801      *    matchValue   [3] AssertionValue,
802      *    dnAttributes [4] BOOLEAN DEFAULT FALSE
803      *  }
804      *  Of course, SEQUENCE is merged with the filter
805      *  so there is no separate 30 ...
806      */
807
808     /*
809     * Decode byte_length of stuff ... as per above
810     * But we assemble the strings and the boolean
811     * if present, and then assemble the filter
812     * expression
813     */
814     matchingRule = type = matchValue = NULL;
815     dnAttributes = FALSE;
816     end = a->offset + byte_length;
817
818     while ((guint)a->offset < end) {
819         /*
820          * Now, parse out each of those items
821          * There will be up to four of them.
822          */
823         ret = asn1_header_decode(a, &cls, &con, &tag, &def, &string_length);
824         if (ret != ASN1_ERR_NOERROR) {
825             return ret;
826         }
827
828         /*
829          * Now, check the tag ...
830          */
831         if (cls != ASN1_CTX || con != ASN1_PRI) {
832             return ASN1_ERR_WRONG_TYPE;
833         }
834         if (!def) {
835             return ASN1_ERR_LENGTH_NOT_DEFINITE;
836         }
837
838         switch (tag) {
839         case 0x01:  /* Parse Matching Rule Id */
840             if (matchingRule != NULL) {
841                 g_free(matchingRule);
842                 matchingRule = NULL;
843             }
844             ret = asn1_string_value_decode(a, (int) string_length, &matchingRule);
845             if (ret != ASN1_ERR_NOERROR) {
846                 return ret;
847             }
848             break;
849
850         case 0x02:  /* Parse attributeDescription */
851             if (type != NULL) {
852                 g_free(type);
853                 type = NULL;
854             }
855             ret = asn1_string_value_decode(a, (int) string_length, &type);
856             if (ret != ASN1_ERR_NOERROR) {
857                 return ret;
858             }
859             break;
860
861         case 0x03:  /* Parse the matchValue */
862             if (matchValue != NULL) {
863                 g_free(matchValue);
864                 matchValue = NULL;
865             }
866             ret = asn1_string_value_decode(a, (int) string_length, &matchValue);
867             if (ret != ASN1_ERR_NOERROR) {
868                 return ret;
869             }
870             break;
871
872         case 0x04:  /* Parse dnAttributes boolean */
873             ret = asn1_bool_decode(a, (int)string_length, &dnAttributes);
874             if (ret != ASN1_ERR_NOERROR) {
875                 return ret;
876             }
877             break;
878
879         default:
880             return ASN1_ERR_WRONG_TYPE;
881         }
882
883     }
884     
885     /*
886      * Now, fill in the filter string.
887      * First, calc how much space is needed and then realloc.
888      */
889     *filter_length += 1; /* For the ( */
890     if (type) *filter_length += strlen(type) + 1;
891     if (dnAttributes) *filter_length += strlen(dnString) + 1;
892     if (matchingRule) *filter_length += strlen(matchingRule) + 1;
893     if (matchValue) *filter_length += strlen(matchValue) + 1;
894     *filter_length += 1; /* for the ) */
895     
896     *filter = g_realloc(*filter, *filter_length);
897     filterp = *filter + strlen(*filter);
898     *filterp++ = '(';
899
900     if (type) {
901         if (strlen(type) > 0) {
902             memcpy(filterp, type, strlen(type));
903             filterp += strlen(type);
904             *filterp++ = ':';
905
906             /*
907              * Add in dn if needed ...
908              */
909             if (dnAttributes) {
910                 memcpy(filterp, dnString, strlen(dnString));
911                 filterp += strlen(dnString);
912                 *filterp++ = ':';
913             }
914         }
915         g_free(type);
916     }
917
918     if (matchingRule) {
919         if (strlen(matchingRule) > 0) {
920             memcpy(filterp, matchingRule, strlen(matchingRule));
921             filterp += strlen(matchingRule);
922             *filterp++ = ':';
923         }
924         g_free(matchingRule);
925     }
926
927     if (matchValue) {
928         if (strlen(matchValue) > 0) {
929             memcpy(filterp, matchValue, strlen(matchValue));
930             filterp += strlen(matchValue);
931         }
932         g_free(matchValue);
933     }
934    
935     *filterp++ = ')';
936     *filterp = '\0';   /* There had better be space */
937     
938     return ASN1_ERR_NOERROR;
939 }
940
941 /* Returns -1 if we're at the end, returns an ASN1_ERR value otherwise. */
942 static int parse_filter(ASN1_SCK *a, char **filter, guint *filter_length,
943                         int *end)
944 {
945   guint cls, con, tag;
946   guint length;
947   gboolean def;
948   int ret;
949
950   ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
951   if (ret != ASN1_ERR_NOERROR)
952     return ret;
953
954   if (*end == 0)
955   {
956     *end = a->offset + length;
957     *filter_length = 1;
958     *filter = g_malloc0(*filter_length);
959   }
960
961   if (cls == ASN1_CTX)  /* XXX - handle other types as errors? */
962   {
963     switch (tag)
964     {
965      case LDAP_FILTER_AND:
966       {
967         int add_end;
968
969         if (con != ASN1_CON)
970           return ASN1_ERR_WRONG_TYPE;
971         add_end = a->offset + length;
972         *filter_length += 3;
973         *filter = g_realloc(*filter, *filter_length);
974         strcat(*filter, "(&");
975         while ((ret = parse_filter(a, filter, filter_length, &add_end))
976                 == ASN1_ERR_NOERROR)
977           continue;
978         if (ret != -1)
979           return ret;
980         strcat(*filter, ")");
981       }
982       break;
983      case LDAP_FILTER_OR:
984       {
985         int or_end;
986
987         if (con != ASN1_CON)
988           return ASN1_ERR_WRONG_TYPE;
989         or_end = a->offset + length;
990         *filter_length += 3;
991         *filter = g_realloc(*filter, *filter_length);
992         strcat(*filter, "(|");
993         while ((ret = parse_filter(a, filter, filter_length, &or_end))
994                 == ASN1_ERR_NOERROR)
995           continue;
996         if (ret != -1)
997           return ret;
998         strcat(*filter, ")");
999       }
1000       break;
1001      case LDAP_FILTER_NOT:
1002       {
1003         int not_end;
1004
1005         if (con != ASN1_CON)
1006           return ASN1_ERR_WRONG_TYPE;
1007         not_end = a->offset + length;
1008         *filter_length += 3;
1009         *filter = g_realloc(*filter, *filter_length);
1010         strcat(*filter, "(!");
1011         ret = parse_filter(a, filter, filter_length, &not_end);
1012         if (ret != -1 && ret != ASN1_ERR_NOERROR)
1013           return ret;
1014         strcat(*filter, ")");
1015       }
1016       break;
1017      case LDAP_FILTER_EQUALITY:
1018       if (con != ASN1_CON)
1019         return ASN1_ERR_WRONG_TYPE;
1020       ret = parse_filter_strings(a, filter, filter_length, "=");
1021       if (ret != ASN1_ERR_NOERROR)
1022         return ret;
1023       break;
1024      case LDAP_FILTER_GE:
1025       if (con != ASN1_CON)
1026         return ASN1_ERR_WRONG_TYPE;
1027       ret = parse_filter_strings(a, filter, filter_length, ">=");
1028       if (ret != ASN1_ERR_NOERROR)
1029         return ret;
1030       break;
1031      case LDAP_FILTER_LE:
1032       if (con != ASN1_CON)
1033         return ASN1_ERR_WRONG_TYPE;
1034       ret = parse_filter_strings(a, filter, filter_length, "<=");
1035       if (ret != -1 && ret != ASN1_ERR_NOERROR)
1036         return ret;
1037       break;
1038      case LDAP_FILTER_APPROX:
1039       if (con != ASN1_CON)
1040         return ASN1_ERR_WRONG_TYPE;
1041       ret = parse_filter_strings(a, filter, filter_length, "~=");
1042       if (ret != ASN1_ERR_NOERROR)
1043         return ret;
1044       break;
1045      case LDAP_FILTER_PRESENT:
1046       {
1047         guchar *string;
1048         char *filterp;
1049
1050         if (con != ASN1_PRI)
1051           return ASN1_ERR_WRONG_TYPE;
1052         ret = asn1_string_value_decode(a, length, &string);
1053         if (ret != ASN1_ERR_NOERROR)
1054           return ret;
1055         *filter_length += 4 + length;
1056         *filter = g_realloc(*filter, *filter_length);
1057         filterp = *filter + strlen(*filter);
1058         *filterp++ = '(';
1059         if (length != 0) {
1060           memcpy(filterp, string, length);
1061           filterp += length;
1062         }
1063         *filterp++ = '=';
1064         *filterp++ = '*';
1065         *filterp++ = ')';
1066         *filterp = '\0';
1067         g_free(string);
1068       }
1069       break;
1070      case LDAP_FILTER_SUBSTRINGS:
1071       if (con != ASN1_CON)
1072         return ASN1_ERR_WRONG_TYPE;
1073       /* Richard Dawe: Handle substrings */
1074       ret = parse_filter_substrings(a, filter, filter_length);
1075       if (ret != ASN1_ERR_NOERROR)
1076         return ret;
1077       break;
1078      case LDAP_FILTER_EXTENSIBLE:
1079       if (con != ASN1_CON)
1080         return ASN1_ERR_WRONG_TYPE;
1081       ret = parse_filter_extensibleMatch(a, filter, filter_length, length);
1082       if (ret != ASN1_ERR_NOERROR) {
1083         return ret;
1084       }
1085       break;
1086      default:
1087       return ASN1_ERR_WRONG_TYPE;
1088     }
1089   }
1090
1091   if (a->offset == *end)
1092     return -1;
1093   else
1094     return ASN1_ERR_NOERROR;
1095 }
1096
1097 static gboolean read_filter(ASN1_SCK *a, proto_tree *tree, int hf_id)
1098 {
1099   int start = a->offset;
1100   char *filter = 0;
1101   guint filter_length = 0;
1102   int end = 0;
1103   int ret;
1104
1105   while ((ret = parse_filter(a, &filter, &filter_length, &end))
1106         == ASN1_ERR_NOERROR)
1107     continue;
1108
1109   if (tree) {
1110     if (ret != -1) {
1111       proto_tree_add_text(tree, a->tvb, start, 0,
1112         "%s: ERROR: Can't parse filter: %s",
1113         proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
1114     } else
1115       proto_tree_add_string(tree, hf_id, a->tvb, start, a->offset-start, filter);
1116   }
1117
1118   g_free(filter);
1119
1120   return (ret == -1) ? TRUE : FALSE;
1121 }
1122
1123 /********************************************************************************************/
1124
1125 static void dissect_ldap_result(ASN1_SCK *a, proto_tree *tree, packet_info *pinfo)
1126 {
1127   guint resultCode = 0;
1128   int ret;
1129   if (read_integer(a, tree, hf_ldap_message_result, 0, &resultCode, ASN1_ENUM) != ASN1_ERR_NOERROR)
1130     return;
1131
1132   if (resultCode != 0) {
1133           if (check_col(pinfo->cinfo, COL_INFO))
1134                   col_append_fstr(pinfo->cinfo, COL_INFO, ", %s", 
1135                                   val_to_str(resultCode, LDAPResultCode_vals,
1136                                              "Unknown (%u)"));
1137   }
1138
1139   if (read_string(a, tree, hf_ldap_message_result_matcheddn, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1140     return;
1141   if (read_string(a, tree, hf_ldap_message_result_errormsg, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1142     return;
1143
1144   if (resultCode == 10)         /* Referral */
1145   {
1146     int start = a->offset;
1147     int end;
1148     guint length;
1149     proto_item *ti;
1150     proto_tree *referralTree;
1151
1152     ret = read_sequence(a, &length);
1153     if (ret != ASN1_ERR_NOERROR) {
1154       if (tree) {
1155         proto_tree_add_text(tree, a->tvb, start, 0,
1156             "ERROR: Couldn't parse referral URL sequence header: %s",
1157             asn1_err_to_str(ret));
1158       }
1159       return;
1160     }
1161     ti = proto_tree_add_text(tree, a->tvb, start, length, "Referral URLs");
1162     referralTree = proto_item_add_subtree(ti, ett_ldap_referrals);
1163
1164     end = a->offset + length;
1165     while (a->offset < end) {
1166       if (read_string(a, referralTree, hf_ldap_message_result_referral, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1167         return;
1168     }
1169   }
1170 }
1171
1172 static void dissect_ldap_request_bind(ASN1_SCK *a, proto_tree *tree,
1173     tvbuff_t *tvb, packet_info *pinfo, ldap_conv_info_t *ldap_info)
1174 {
1175   guint cls, con, tag;
1176   gboolean def;
1177   guint length;
1178   int start;
1179   int end;
1180   int ret;
1181   char *mechanism, *s = NULL;
1182   int token_offset;
1183   gint available_length, reported_length;
1184   tvbuff_t *new_tvb;
1185
1186   if (read_integer(a, tree, hf_ldap_message_bind_version, 0, 0, ASN1_INT) != ASN1_ERR_NOERROR)
1187     return;
1188   if (read_string(a, tree, hf_ldap_message_bind_dn, 0, &s, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1189     return;
1190
1191   if (check_col(pinfo->cinfo, COL_INFO))
1192     col_append_fstr(pinfo->cinfo, COL_INFO, ", DN=%s", s != NULL ? s : "(null)");
1193   g_free(s);
1194
1195   start = a->offset;
1196   ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
1197   if (ret == ASN1_ERR_NOERROR) {
1198     if (cls != ASN1_CTX) {
1199       /* RFCs 1777 and 2251 say these are context-specific types */
1200       ret = ASN1_ERR_WRONG_TYPE;
1201     }
1202   }
1203   if (ret != ASN1_ERR_NOERROR) {
1204     proto_tree_add_text(tree, a->tvb, start, 0,
1205       "%s: ERROR: Couldn't parse header: %s",
1206       proto_registrar_get_name(hf_ldap_message_bind_auth),
1207       asn1_err_to_str(ret));
1208     return;
1209   }
1210   proto_tree_add_uint(tree, hf_ldap_message_bind_auth, a->tvb, start,
1211                         a->offset - start, tag);
1212   end = a->offset + length;
1213   switch (tag)
1214   {
1215    case LDAP_AUTH_SIMPLE:
1216     if (read_string_value(a, tree, hf_ldap_message_bind_auth_password, NULL,
1217                           NULL, start, length) != ASN1_ERR_NOERROR)
1218       return;
1219     break;
1220
1221     /* For Kerberos V4, dissect it as a ticket. */
1222
1223    case LDAP_AUTH_SASL:
1224     mechanism = NULL;
1225     if (read_string(a, tree, hf_ldap_message_bind_auth_mechanism, NULL,
1226                     &mechanism, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1227       return;
1228
1229     /*
1230      * We need to remember the authentication type and mechanism for this
1231      * conversation.
1232      *
1233      * XXX - actually, we might need to remember more than one
1234      * type and mechanism, if you can unbind and rebind with a
1235      * different type and/or mechanism.
1236      */
1237     ldap_info->auth_type = tag;
1238     ldap_info->auth_mech = mechanism;
1239     ldap_info->first_auth_frame = 0;    /* not known until we see the bind reply */
1240     /*
1241      * If the mechanism in this request is an empty string (which is
1242      * returned as a null pointer), use the saved mechanism instead.
1243      * Otherwise, if the saved mechanism is an empty string (null),
1244      * save this mechanism.
1245      */
1246     if (mechanism == NULL)
1247         mechanism = ldap_info->auth_mech;
1248     else {
1249       if (ldap_info->auth_mech == NULL) {
1250         g_free(ldap_info->auth_mech);
1251       }
1252       ldap_info->auth_mech = mechanism;
1253     }
1254
1255     if (a->offset < end) {
1256       if (mechanism != NULL && strcmp(mechanism, "GSS-SPNEGO") == 0) {
1257         /*
1258          * This is a GSS-API token ancapsulated within GSS-SPNEGO.
1259          * Find out how big it is by parsing the ASN.1 header for the
1260          * OCTET STREAM that contains it.
1261          */
1262         token_offset = a->offset;
1263         ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
1264         if (ret != ASN1_ERR_NOERROR) {
1265           proto_tree_add_text(tree, a->tvb, token_offset, 0,
1266             "%s: ERROR: Couldn't parse header: %s",
1267             proto_registrar_get_name(hf_ldap_message_bind_auth_credentials),
1268             asn1_err_to_str(ret));
1269           return;
1270         }
1271         available_length = tvb_length_remaining(tvb, token_offset);
1272         reported_length = tvb_reported_length_remaining(tvb, token_offset);
1273         DISSECTOR_ASSERT(available_length >= 0);
1274         DISSECTOR_ASSERT(reported_length >= 0);
1275         if (available_length > reported_length)
1276           available_length = reported_length;
1277         if ((guint)available_length > length)
1278           available_length = length;
1279         if ((guint)reported_length > length)
1280           reported_length = length;
1281         new_tvb = tvb_new_subset(tvb, a->offset, available_length, reported_length);
1282         call_dissector(gssapi_handle, new_tvb, pinfo, tree);
1283         a->offset += length;
1284       } else if (mechanism != NULL && strcmp(mechanism, "GSSAPI") == 0) {
1285         /*
1286          * This is a raw GSS-API token.
1287          * Find out how big it is by parsing the ASN.1 header for the
1288          * OCTET STREAM that contains it.
1289          */
1290         token_offset = a->offset;
1291         ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
1292         if (ret != ASN1_ERR_NOERROR) {
1293           proto_tree_add_text(tree, a->tvb, token_offset, 0,
1294             "%s: ERROR: Couldn't parse header: %s",
1295             proto_registrar_get_name(hf_ldap_message_bind_auth_credentials),
1296             asn1_err_to_str(ret));
1297           return;
1298         }
1299         if(length==0){
1300           /* for GSSAPI the third pdu will sometimes be "empty" */
1301           return;
1302         }
1303         available_length = tvb_length_remaining(tvb, token_offset);
1304         reported_length = tvb_reported_length_remaining(tvb, token_offset);
1305         DISSECTOR_ASSERT(available_length >= 0);
1306         DISSECTOR_ASSERT(reported_length >= 0);
1307         if (available_length > reported_length)
1308           available_length = reported_length;
1309         if ((guint)available_length > length)
1310           available_length = length;
1311         if ((guint)reported_length > length)
1312           reported_length = length;
1313         new_tvb = tvb_new_subset(tvb, a->offset, available_length, reported_length);
1314         call_dissector(gssapi_handle, new_tvb, pinfo, tree);
1315         a->offset += length;
1316       } else {
1317         if (read_bytestring(a, tree, hf_ldap_message_bind_auth_credentials,
1318                             NULL, NULL, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1319           return;
1320       }
1321     }
1322     break;
1323   }
1324 }
1325
1326 static void dissect_ldap_response_bind(ASN1_SCK *a, proto_tree *tree,
1327                 int start, guint length, tvbuff_t *tvb, packet_info *pinfo, ldap_conv_info_t *ldap_info)
1328 {
1329   guint cls, con, tag;
1330   gboolean def;
1331   guint cred_length;
1332   int end;
1333   int ret;
1334   int token_offset;
1335   gint available_length, reported_length;
1336   tvbuff_t *new_tvb;
1337
1338   end = start + length;
1339   dissect_ldap_result(a, tree, pinfo);
1340   if (a->offset < end) {
1341     switch (ldap_info->auth_type) {
1342
1343       /* For Kerberos V4, dissect it as a ticket. */
1344       /* XXX - what about LDAP_AUTH_SIMPLE? */
1345
1346     case LDAP_AUTH_SASL:
1347       /*
1348        * All frames after this are assumed to use a security layer.
1349        *
1350        * XXX - won't work if there's another reply, with the security
1351        * layer, starting in the same TCP segment that ends this
1352        * reply, but as LDAP is a request/response protocol, and
1353        * as the client probably can't start using authentication until
1354        * it gets the bind reply and the server won't send a reply until
1355        * it gets a request, that probably won't happen.
1356        *
1357        * XXX - that assumption is invalid; it's not clear where the
1358        * hell you find out whether there's any security layer.  In
1359        * one capture, we have two GSS-SPNEGO negotiations, both of
1360        * which select MS KRB5, and the only differences in the tokens
1361        * is in the RC4-HMAC ciphertext.  The various
1362        * draft-ietf--cat-sasl-gssapi-NN.txt drafts seem to imply
1363        * that the RFC 2222 spoo with the bitmask and maximum
1364        * output message size stuff is done - but where does that
1365        * stuff show up?  Is it in the ciphertext, which means it's
1366        * presumably encrypted?
1367        *
1368        * Grrr.  We have to do a gross heuristic, checking whether the
1369        * putative LDAP message begins with 0x00 or not, making the
1370        * assumption that we won't have more than 2^24 bytes of
1371        * encapsulated stuff.
1372        */
1373       ldap_info->first_auth_frame = pinfo->fd->num + 1;
1374       if (ldap_info->auth_mech != NULL &&
1375           strcmp(ldap_info->auth_mech, "GSS-SPNEGO") == 0) {
1376         /*
1377          * This is a GSS-API token.
1378          * Find out how big it is by parsing the ASN.1 header for the
1379          * OCTET STREAM that contains it.
1380          */
1381         token_offset = a->offset;
1382         ret = asn1_header_decode(a, &cls, &con, &tag, &def, &cred_length);
1383         if (ret != ASN1_ERR_NOERROR) {
1384           proto_tree_add_text(tree, a->tvb, token_offset, 0,
1385             "%s: ERROR: Couldn't parse header: %s",
1386             proto_registrar_get_name(hf_ldap_message_bind_auth_credentials),
1387             asn1_err_to_str(ret));
1388           return;
1389         }
1390         available_length = tvb_length_remaining(tvb, token_offset);
1391         reported_length = tvb_reported_length_remaining(tvb, token_offset);
1392         DISSECTOR_ASSERT(available_length >= 0);
1393         DISSECTOR_ASSERT(reported_length >= 0);
1394         if (available_length > reported_length)
1395           available_length = reported_length;
1396         if ((guint)available_length > cred_length)
1397           available_length = cred_length;
1398         if ((guint)reported_length > cred_length)
1399           reported_length = cred_length;
1400         new_tvb = tvb_new_subset(tvb, a->offset, available_length, reported_length);
1401         call_dissector(gssapi_handle, new_tvb, pinfo, tree);
1402         a->offset += cred_length;
1403       } else if (ldap_info->auth_mech != NULL &&
1404           strcmp(ldap_info->auth_mech, "GSSAPI") == 0) {
1405         /*
1406          * This is a GSS-API token.
1407          * Find out how big it is by parsing the ASN.1 header for the
1408          * OCTET STREAM that contains it.
1409          */
1410         token_offset = a->offset;
1411         ret = asn1_header_decode(a, &cls, &con, &tag, &def, &cred_length);
1412         if (ret != ASN1_ERR_NOERROR) {
1413           proto_tree_add_text(tree, a->tvb, token_offset, 0,
1414             "%s: ERROR: Couldn't parse header: %s",
1415             proto_registrar_get_name(hf_ldap_message_bind_auth_credentials),
1416             asn1_err_to_str(ret));
1417           return;
1418         }
1419         available_length = tvb_length_remaining(tvb, token_offset);
1420         reported_length = tvb_reported_length_remaining(tvb, token_offset);
1421         DISSECTOR_ASSERT(available_length >= 0);
1422         DISSECTOR_ASSERT(reported_length >= 0);
1423         if (available_length > reported_length)
1424           available_length = reported_length;
1425         if ((guint)available_length > cred_length)
1426           available_length = cred_length;
1427         if ((guint)reported_length > cred_length)
1428           reported_length = cred_length;
1429         new_tvb = tvb_new_subset(tvb, a->offset, available_length, reported_length);
1430         call_dissector(gssapi_handle, new_tvb, pinfo, tree);
1431         a->offset += cred_length;
1432       } else {
1433         if (read_bytestring(a, tree, hf_ldap_message_bind_server_credentials,
1434                             NULL, NULL, ASN1_CTX, 7) != ASN1_ERR_NOERROR)
1435           return;
1436       }
1437       break;
1438     }
1439   }
1440 }
1441
1442 static void dissect_ldap_request_search(ASN1_SCK *a, proto_tree *tree, packet_info *pinfo)
1443 {
1444   guint seq_length;
1445   int end;
1446   int ret;
1447   char *s = NULL;
1448
1449   if (read_string(a, tree, hf_ldap_message_search_base, 0, &s, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1450     return;
1451
1452   if (check_col(pinfo->cinfo, COL_INFO))
1453     col_append_fstr(pinfo->cinfo, COL_INFO, ", Base DN=%s", s != NULL ? s : "(null)");
1454   g_free(s);
1455
1456   if (read_integer(a, tree, hf_ldap_message_search_scope, 0, 0, ASN1_ENUM) != ASN1_ERR_NOERROR)
1457     return;
1458   if (read_integer(a, tree, hf_ldap_message_search_deref, 0, 0, ASN1_ENUM) != ASN1_ERR_NOERROR)
1459     return;
1460   if (read_integer(a, tree, hf_ldap_message_search_sizeLimit, 0, 0, ASN1_INT) != ASN1_ERR_NOERROR)
1461     return;
1462   if (read_integer(a, tree, hf_ldap_message_search_timeLimit, 0, 0, ASN1_INT) != ASN1_ERR_NOERROR)
1463     return;
1464   if (read_boolean(a, tree, hf_ldap_message_search_typesOnly, 0, 0) != ASN1_ERR_NOERROR)
1465     return;
1466   if (!read_filter(a, tree, hf_ldap_message_search_filter))
1467     return;
1468   ret = read_sequence(a, &seq_length);
1469   if (ret != ASN1_ERR_NOERROR) {
1470     if (tree) {
1471       proto_tree_add_text(tree, a->tvb, a->offset, 0,
1472           "ERROR: Couldn't parse LDAP attribute sequence header: %s",
1473           asn1_err_to_str(ret));
1474     }
1475     return;
1476   }
1477   end = a->offset + seq_length;
1478   while (a->offset < end) {
1479     if (read_string(a, tree, hf_ldap_message_attribute, 0, 0, 0, ASN1_UNI,
1480                     ASN1_OTS) != ASN1_ERR_NOERROR)
1481       return;
1482   }
1483 }
1484
1485 static int dissect_mscldap_string(tvbuff_t *tvb, int offset, char *str, int maxlen, gboolean prepend_dot)
1486 {
1487   guint8 len;
1488
1489   len=tvb_get_guint8(tvb, offset);
1490   offset+=1;
1491   *str=0;
1492
1493   while(len){
1494     /* add potential field separation dot */
1495     if(prepend_dot){
1496       if(!maxlen){
1497         *str=0;
1498         return offset;
1499       }
1500       maxlen--;
1501       *str++='.';
1502       *str=0;
1503     }
1504
1505     if(len==0xc0){
1506       int new_offset;
1507       /* ops its a mscldap compressed string */
1508
1509       new_offset=tvb_get_guint8(tvb, offset);
1510       if (new_offset == offset - 1)
1511         THROW(ReportedBoundsError);
1512       offset+=1;
1513
1514       dissect_mscldap_string(tvb, new_offset, str, maxlen, FALSE);
1515
1516       return offset;
1517     }
1518
1519     prepend_dot=TRUE;
1520
1521     if(maxlen<=len){
1522       if(maxlen>3){
1523         *str++='.';
1524         *str++='.';
1525         *str++='.';
1526       }
1527       *str=0;
1528       return offset; /* will mess up offset in caller, is unlikely */
1529     }
1530     tvb_memcpy(tvb, str, offset, len);
1531     str+=len;
1532     *str=0;
1533     maxlen-=len;
1534     offset+=len;
1535
1536
1537     len=tvb_get_guint8(tvb, offset);
1538     offset+=1;
1539   }
1540   *str=0;
1541   return offset;
1542 }
1543
1544
1545 /* These flag bits were found to be defined in the samba sources.
1546  * I hope they are correct (but have serious doubts about the CLOSEST
1547  * bit being used or being meaningful).
1548  */
1549 static const true_false_string tfs_ads_pdc = {
1550         "This is a PDC",
1551         "This is NOT a pdc"
1552 };
1553 static const true_false_string tfs_ads_gc = {
1554         "This is a GLOBAL CATALOGUE of forest",
1555         "This is NOT a global catalog of forest"
1556 };
1557 static const true_false_string tfs_ads_ldap = {
1558         "This is an LDAP server",
1559         "This is NOT an ldap server"
1560 };
1561 static const true_false_string tfs_ads_ds = {
1562         "This dc supports DS",
1563         "This dc does NOT support ds"
1564 };
1565 static const true_false_string tfs_ads_kdc = {
1566         "This is a KDC (kerberos)",
1567         "This is NOT a kdc (kerberos)"
1568 };
1569 static const true_false_string tfs_ads_timeserv = {
1570         "This dc is running TIME SERVICES (ntp)",
1571         "This dc is NOT running time services (ntp)"
1572 };
1573 static const true_false_string tfs_ads_closest = {
1574         "This is the CLOSEST dc (unreliable?)",
1575         "This is NOT the closest dc"
1576 };
1577 static const true_false_string tfs_ads_writable = {
1578         "This dc is WRITABLE",
1579         "This dc is NOT writable"
1580 };
1581 static const true_false_string tfs_ads_good_timeserv = {
1582         "This dc has a GOOD TIME SERVICE (i.e. hardware clock)",
1583         "This dc does NOT have a good time service (i.e. no hardware clock)"
1584 };
1585 static const true_false_string tfs_ads_ndnc = {
1586         "Domain is NON-DOMAIN NC serviced by ldap server",
1587         "Domain is NOT non-domain nc serviced by ldap server"
1588 };
1589 static int dissect_mscldap_netlogon_flags(proto_tree *parent_tree, tvbuff_t *tvb, int offset)
1590 {
1591   guint32 flags;
1592   proto_item *item;
1593   proto_tree *tree=NULL;
1594
1595   flags=tvb_get_letohl(tvb, offset);
1596   item=proto_tree_add_item(parent_tree, hf_mscldap_netlogon_flags, tvb, offset, 4, TRUE);
1597   if(parent_tree){
1598     tree = proto_item_add_subtree(item, ett_mscldap_netlogon_flags);
1599   }
1600
1601   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_ndnc,
1602     tvb, offset, 4, flags);
1603   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_good_timeserv,
1604     tvb, offset, 4, flags);
1605   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_writable,
1606     tvb, offset, 4, flags);
1607   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_closest,
1608     tvb, offset, 4, flags);
1609   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_timeserv,
1610     tvb, offset, 4, flags);
1611   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_kdc,
1612     tvb, offset, 4, flags);
1613   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_ds,
1614     tvb, offset, 4, flags);
1615   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_ldap,
1616     tvb, offset, 4, flags);
1617   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_gc,
1618     tvb, offset, 4, flags);
1619   proto_tree_add_boolean(tree, hf_mscldap_netlogon_flags_pdc,
1620     tvb, offset, 4, flags);
1621
1622   offset += 4;
1623
1624   return offset;
1625 }
1626
1627 static void dissect_mscldap_response_netlogon(proto_tree *tree, tvbuff_t *tvb)
1628 {
1629   int old_offset, offset=0;
1630   char str[256];
1631
1632 /*qqq*/
1633
1634   /* Type */
1635   /*XXX someone that knows what the type means should add that knowledge here*/
1636   proto_tree_add_item(tree, hf_mscldap_netlogon_type, tvb, offset, 4, TRUE);
1637   offset += 4;
1638
1639   /* Flags */
1640   offset = dissect_mscldap_netlogon_flags(tree, tvb, offset);
1641
1642   /* Domain GUID */
1643   proto_tree_add_item(tree, hf_mscldap_domain_guid, tvb, offset, 16, TRUE);
1644   offset += 16;
1645
1646   /* Forest */
1647   old_offset=offset;
1648   offset=dissect_mscldap_string(tvb, offset, str, 255, FALSE);
1649   proto_tree_add_string(tree, hf_mscldap_forest, tvb, old_offset, offset-old_offset, str);
1650   
1651   /* Domain */
1652   old_offset=offset;
1653   offset=dissect_mscldap_string(tvb, offset, str, 255, FALSE);
1654   proto_tree_add_string(tree, hf_mscldap_domain, tvb, old_offset, offset-old_offset, str);
1655   
1656   /* Hostname */
1657   old_offset=offset;
1658   offset=dissect_mscldap_string(tvb, offset, str, 255, FALSE);
1659   proto_tree_add_string(tree, hf_mscldap_hostname, tvb, old_offset, offset-old_offset, str);
1660   
1661   /* NetBios Domain */
1662   old_offset=offset;
1663   offset=dissect_mscldap_string(tvb, offset, str, 255, FALSE);
1664   proto_tree_add_string(tree, hf_mscldap_nb_domain, tvb, old_offset, offset-old_offset, str);
1665   
1666   /* NetBios Hostname */
1667   old_offset=offset;
1668   offset=dissect_mscldap_string(tvb, offset, str, 255, FALSE);
1669   proto_tree_add_string(tree, hf_mscldap_nb_hostname, tvb, old_offset, offset-old_offset, str);
1670   
1671   /* User */
1672   old_offset=offset;
1673   offset=dissect_mscldap_string(tvb, offset, str, 255, FALSE);
1674   proto_tree_add_string(tree, hf_mscldap_username, tvb, old_offset, offset-old_offset, str);
1675   
1676   /* Site */
1677   old_offset=offset;
1678   offset=dissect_mscldap_string(tvb, offset, str, 255, FALSE);
1679   proto_tree_add_string(tree, hf_mscldap_sitename, tvb, old_offset, offset-old_offset, str);
1680   
1681   /* Client Site */
1682   old_offset=offset;
1683   offset=dissect_mscldap_string(tvb, offset, str, 255, FALSE);
1684   proto_tree_add_string(tree, hf_mscldap_clientsitename, tvb, old_offset, offset-old_offset, str);
1685   
1686   /* Version */
1687   proto_tree_add_item(tree, hf_mscldap_netlogon_version, tvb, offset, 4, TRUE);
1688   offset += 4;
1689
1690   /* LM Token */
1691   proto_tree_add_item(tree, hf_mscldap_netlogon_lm_token, tvb, offset, 2, TRUE);
1692   offset += 2;
1693
1694   /* NT Token */
1695   proto_tree_add_item(tree, hf_mscldap_netlogon_nt_token, tvb, offset, 2, TRUE);
1696   offset += 2;
1697
1698 }
1699
1700 static void dissect_mscldap_response(proto_tree *tree, tvbuff_t *tvb, guint32 rpc)
1701 {
1702   switch(rpc){
1703   case MSCLDAP_RPC_NETLOGON:
1704     dissect_mscldap_response_netlogon(tree, tvb);
1705     break;
1706   default:
1707     proto_tree_add_text(tree, tvb, 0, tvb_length(tvb),
1708       "ERROR: Unknown type of MS-CLDAP RPC call");
1709   }
1710 }
1711
1712
1713 static void dissect_ldap_response_search_entry(ASN1_SCK *a, proto_tree *tree,
1714                 gboolean is_mscldap)
1715 {
1716   guint seq_length;
1717   int end_of_sequence;
1718   int ret;
1719   char *str=NULL;
1720   guint32 len;
1721   guint32 mscldap_rpc;
1722
1723   if (read_string(a, tree, hf_ldap_message_dn, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1724     return;
1725   ret = read_sequence(a, &seq_length);
1726   if (ret != ASN1_ERR_NOERROR) {
1727     if (tree) {
1728       proto_tree_add_text(tree, a->tvb, a->offset, 0,
1729           "ERROR: Couldn't parse search entry response sequence header: %s",
1730           asn1_err_to_str(ret));
1731     }
1732     return;
1733   }
1734
1735   end_of_sequence = a->offset + seq_length;
1736   while (a->offset < end_of_sequence)
1737   {
1738     proto_item *ti;
1739     proto_tree *attr_tree;
1740     guint set_length;
1741     int end_of_set;
1742
1743     ret = read_sequence(a, 0);
1744     if (ret != ASN1_ERR_NOERROR) {
1745       if (tree) {
1746         proto_tree_add_text(tree, a->tvb, a->offset, 0,
1747             "ERROR: Couldn't parse LDAP attribute sequence header: %s",
1748             asn1_err_to_str(ret));
1749       }
1750       return;
1751     }
1752     if (read_string(a, tree, hf_ldap_message_attribute, &ti, &str, &len, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1753       return;
1754
1755     mscldap_rpc=0;
1756     if(is_mscldap){
1757           if(str && !strncmp(str, "netlogon", 8)){
1758                 mscldap_rpc=MSCLDAP_RPC_NETLOGON;
1759           }
1760     }
1761     g_free(str);
1762     str=NULL;
1763
1764
1765     attr_tree = proto_item_add_subtree(ti, ett_ldap_attribute);
1766
1767     ret = read_set(a, &set_length);
1768     if (ret != ASN1_ERR_NOERROR) {
1769       if (tree) {
1770         proto_tree_add_text(attr_tree, a->tvb, a->offset, 0,
1771             "ERROR: Couldn't parse LDAP value set header: %s",
1772             asn1_err_to_str(ret));
1773       }
1774       return;
1775     }
1776     end_of_set = a->offset + set_length;
1777     while (a->offset < end_of_set) {
1778       if(!is_mscldap){
1779         if (read_string(a, attr_tree, hf_ldap_message_value, 0, 0, 0, ASN1_UNI,
1780                         ASN1_OTS) != ASN1_ERR_NOERROR){
1781           return;
1782         }
1783       } else {
1784         guint cls, con, tag;
1785         gboolean def;
1786         guint len;
1787         int start = a->offset;
1788         int ret;
1789         tvbuff_t *mscldap_tvb=NULL;
1790
1791         ret = asn1_header_decode(a, &cls, &con, &tag, &def, &len);
1792         if (ret == ASN1_ERR_NOERROR) {
1793           if (cls != ASN1_UNI || con != ASN1_PRI || tag != ASN1_OTS)
1794             ret = ASN1_ERR_WRONG_TYPE;
1795         }
1796         if (ret != ASN1_ERR_NOERROR) {
1797           if (tree) {
1798             proto_tree_add_text(tree, a->tvb, start, 0,
1799               "%s: ERROR: Couldn't parse header: %s",
1800             proto_registrar_get_name(hf_ldap_message_value), asn1_err_to_str(ret));
1801           }
1802           return;
1803         }
1804         mscldap_tvb=tvb_new_subset(a->tvb, a->offset, len, len);
1805         dissect_mscldap_response(attr_tree, mscldap_tvb, mscldap_rpc);
1806         a->offset+=len;
1807       }
1808
1809     }
1810   }
1811 }
1812
1813 static void dissect_ldap_response_search_ref(ASN1_SCK *a, proto_tree *tree)
1814 {
1815   read_string(a, tree, hf_ldap_message_search_reference, 0, 0, 0, ASN1_UNI, ASN1_OTS);
1816 }
1817
1818 static void dissect_ldap_request_add(ASN1_SCK *a, proto_tree *tree, packet_info *pinfo)
1819 {
1820   guint seq_length;
1821   int end_of_sequence;
1822   int ret;
1823   char *s = NULL;
1824
1825   if (read_string(a, tree, hf_ldap_message_dn, 0, &s, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1826     return;
1827
1828   if (check_col(pinfo->cinfo, COL_INFO))
1829     col_append_fstr(pinfo->cinfo, COL_INFO, ", DN=%s", s != NULL ? s : "(null)");
1830   g_free(s);  
1831
1832   ret = read_sequence(a, &seq_length);
1833   if (ret != ASN1_ERR_NOERROR) {
1834     if (tree) {
1835       proto_tree_add_text(tree, a->tvb, a->offset, 0,
1836           "ERROR: Couldn't parse add request sequence header: %s",
1837           asn1_err_to_str(ret));
1838     }
1839     return;
1840   }
1841
1842   end_of_sequence = a->offset + seq_length;
1843   while (a->offset < end_of_sequence)
1844   {
1845     proto_item *ti;
1846     proto_tree *attr_tree;
1847     guint set_length;
1848     int end_of_set;
1849
1850     ret = read_sequence(a, 0);
1851     if (ret != ASN1_ERR_NOERROR) {
1852       if (tree) {
1853         proto_tree_add_text(tree, a->tvb, a->offset, 0,
1854             "ERROR: Couldn't parse LDAP attribute sequence header: %s",
1855             asn1_err_to_str(ret));
1856       }
1857       return;
1858     }
1859     if (read_string(a, tree, hf_ldap_message_attribute, &ti, 0, 0, ASN1_UNI,
1860                     ASN1_OTS) != ASN1_ERR_NOERROR)
1861       return;
1862     attr_tree = proto_item_add_subtree(ti, ett_ldap_attribute);
1863
1864     ret = read_set(a, &set_length);
1865     if (ret != ASN1_ERR_NOERROR) {
1866       if (tree) {
1867         proto_tree_add_text(attr_tree, a->tvb, a->offset, 0,
1868             "ERROR: Couldn't parse LDAP value set header: %s",
1869             asn1_err_to_str(ret));
1870       }
1871       return;
1872     }
1873     end_of_set = a->offset + set_length;
1874     while (a->offset < end_of_set) {
1875       if (read_string(a, attr_tree, hf_ldap_message_value, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1876         return;
1877     }
1878   }
1879 }
1880
1881 static void dissect_ldap_request_delete(ASN1_SCK *a, proto_tree *tree,
1882                 int start, guint length)
1883 {
1884   read_string_value(a, tree, hf_ldap_message_dn, NULL, NULL, start, length);
1885 }
1886
1887 static void dissect_ldap_request_modifyrdn(ASN1_SCK *a, proto_tree *tree,
1888                 guint length)
1889 {
1890   int start = a->offset;
1891
1892   if (read_string(a, tree, hf_ldap_message_dn, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1893     return;
1894   if (read_string(a, tree, hf_ldap_message_modrdn_name, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1895     return;
1896   if (read_boolean(a, tree, hf_ldap_message_modrdn_delete, 0, 0) != ASN1_ERR_NOERROR)
1897     return;
1898
1899   if (a->offset < (int) (start + length)) {
1900     /* LDAP V3 Modify DN operation, with newSuperior */
1901     /*      "newSuperior     [0] LDAPDN OPTIONAL" (0x80) */
1902     if (read_string(a, tree, hf_ldap_message_modrdn_superior, 0, 0, 0, ASN1_CTX, 0) != ASN1_ERR_NOERROR)
1903       return;
1904   }
1905 }
1906
1907 static void dissect_ldap_request_compare(ASN1_SCK *a, proto_tree *tree)
1908 {
1909   int start;
1910   int length;
1911   char *string1 = NULL;
1912   char *string2 = NULL;
1913   const char *s1, *s2;
1914   char *compare;
1915   int ret;
1916
1917   if (read_string(a, tree, hf_ldap_message_dn, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1918     return;
1919   ret = read_sequence(a, 0);
1920   if (ret != ASN1_ERR_NOERROR) {
1921     if (tree) {
1922       proto_tree_add_text(tree, a->tvb, a->offset, 0,
1923           "ERROR: Couldn't parse compare request sequence header: %s",
1924           asn1_err_to_str(ret));
1925     }
1926     return;
1927   }
1928
1929   start = a->offset;
1930   ret = read_string(a, 0, -1, 0, &string1, 0, ASN1_UNI, ASN1_OTS);
1931   if (ret != ASN1_ERR_NOERROR) {
1932     if (tree) {
1933       proto_tree_add_text(tree, a->tvb, start, 0,
1934         "ERROR: Couldn't parse compare type: %s", asn1_err_to_str(ret));
1935     }
1936     return;
1937   }
1938   ret = read_string(a, 0, -1, 0, &string2, 0, ASN1_UNI, ASN1_OTS);
1939   if (ret != ASN1_ERR_NOERROR) {
1940     if (tree) {
1941       proto_tree_add_text(tree, a->tvb, start, 0,
1942         "ERROR: Couldn't parse compare value: %s", asn1_err_to_str(ret));
1943     }
1944     g_free(string1);
1945     return;
1946   }
1947
1948   s1 = (string1 == NULL) ? "(null)" : string1;
1949   s2 = (string2 == NULL) ? "(null)" : string2;
1950   length = 2 + strlen(s1) + strlen(s2);
1951   compare = g_malloc0(length);
1952   g_snprintf(compare, length, "%s=%s", s1, s2);
1953   proto_tree_add_string(tree, hf_ldap_message_compare, a->tvb, start,
1954       a->offset-start, compare);
1955
1956   g_free(string1);
1957   g_free(string2);
1958   g_free(compare);
1959
1960   return;
1961 }
1962
1963 static void dissect_ldap_request_modify(ASN1_SCK *a, proto_tree *tree)
1964 {
1965   guint seq_length;
1966   int end_of_sequence;
1967   int ret;
1968
1969   if (read_string(a, tree, hf_ldap_message_dn, 0, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
1970     return;
1971   ret = read_sequence(a, &seq_length);
1972   if (ret != ASN1_ERR_NOERROR) {
1973     if (tree) {
1974       proto_tree_add_text(tree, a->tvb, a->offset, 0,
1975           "ERROR: Couldn't parse modify request sequence header: %s",
1976           asn1_err_to_str(ret));
1977     }
1978     return;
1979   }
1980   end_of_sequence = a->offset + seq_length;
1981   while (a->offset < end_of_sequence)
1982   {
1983     proto_item *ti;
1984     proto_tree *attr_tree;
1985     guint set_length;
1986     int end_of_set;
1987     guint operation;
1988
1989     ret = read_sequence(a, 0);
1990     if (ret != ASN1_ERR_NOERROR) {
1991       if (tree) {
1992         proto_tree_add_text(tree, a->tvb, a->offset, 0,
1993             "ERROR: Couldn't parse modify request item sequence header: %s",
1994             asn1_err_to_str(ret));
1995       }
1996       return;
1997     }
1998     ret = read_integer(a, 0, -1, 0, &operation, ASN1_ENUM);
1999     if (ret != ASN1_ERR_NOERROR) {
2000       if (tree) {
2001         proto_tree_add_text(tree, a->tvb, a->offset, 0,
2002           "ERROR: Couldn't parse modify operation: %s",
2003           asn1_err_to_str(ret));
2004         return;
2005       }
2006     }
2007     ret = read_sequence(a, 0);
2008     if (ret != ASN1_ERR_NOERROR) {
2009       if (tree) {
2010         proto_tree_add_text(tree, a->tvb, a->offset, 0,
2011             "ERROR: Couldn't parse modify request operation sequence header: %s",
2012             asn1_err_to_str(ret));
2013       }
2014       return;
2015     }
2016
2017     switch (operation)
2018     {
2019      case LDAP_MOD_ADD:
2020       if (read_string(a, tree, hf_ldap_message_modify_add, &ti, 0, 0, ASN1_UNI,
2021                       ASN1_OTS) != ASN1_ERR_NOERROR)
2022         return;
2023       break;
2024
2025      case LDAP_MOD_REPLACE:
2026       if (read_string(a, tree, hf_ldap_message_modify_replace, &ti, 0, 0,
2027                       ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
2028         return;
2029       break;
2030
2031      case LDAP_MOD_DELETE:
2032       if (read_string(a, tree, hf_ldap_message_modify_delete, &ti, 0, 0,
2033                       ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
2034         return;
2035       break;
2036
2037      default:
2038        proto_tree_add_text(tree, a->tvb, a->offset, 0,
2039             "Unknown LDAP modify operation (%u)", operation);
2040        return;
2041     }
2042     attr_tree = proto_item_add_subtree(ti, ett_ldap_attribute);
2043
2044     ret = read_set(a, &set_length);
2045     if (ret != ASN1_ERR_NOERROR) {
2046       if (tree) {
2047         proto_tree_add_text(attr_tree, a->tvb, a->offset, 0,
2048             "ERROR: Couldn't parse LDAP value set header: %s",
2049             asn1_err_to_str(ret));
2050       }
2051       return;
2052     }
2053     end_of_set = a->offset + set_length;
2054     while (a->offset < end_of_set) {
2055       if (read_string(a, attr_tree, hf_ldap_message_value, 0, 0, 0, ASN1_UNI,
2056                       ASN1_OTS) != ASN1_ERR_NOERROR)
2057         return;
2058     }
2059   }
2060 }
2061
2062 static void dissect_ldap_request_abandon(ASN1_SCK *a, proto_tree *tree,
2063                 int start, guint length)
2064 {
2065   read_integer_value(a, tree, hf_ldap_message_abandon_msgid, NULL, NULL,
2066                             start, length);
2067 }
2068
2069 static void dissect_ldap_controls(ASN1_SCK *a, proto_tree *tree)
2070 {
2071   guint cls, con, tag;
2072   gboolean def;
2073   guint length;
2074   int ret;
2075   proto_item *ctrls_item = NULL;
2076   proto_tree *ctrls_tree = NULL;
2077   int start = a->offset;
2078   int end;
2079   guint ctrls_length;
2080
2081   ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
2082   if (ret != ASN1_ERR_NOERROR) {
2083     proto_tree_add_text(tree, a->tvb, a->offset, 0,
2084                         "ERROR: Couldn't parse LDAP Controls: %s",
2085                         asn1_err_to_str(ret));
2086     return;
2087   }
2088   if (cls != ASN1_CTX || con != ASN1_CON || tag != ASN1_EOC) {
2089     proto_tree_add_text(tree, a->tvb, a->offset, 0,
2090                         "ERROR: Couldn't parse LDAP Controls: %s",
2091                         asn1_err_to_str(ASN1_ERR_WRONG_TYPE));
2092     return;
2093   }
2094
2095   ctrls_length = (a->offset - start) + length;
2096   ctrls_item = proto_tree_add_text(tree, a->tvb, start, ctrls_length, "LDAP Controls");
2097   ctrls_tree = proto_item_add_subtree(ctrls_item, ett_ldap_controls);
2098
2099   end = a->offset + length;
2100   while (a->offset < end) {
2101     proto_item *ctrl_item = NULL;
2102     proto_tree *ctrl_tree = NULL;
2103     guint seq_length;
2104     int seq_start = a->offset;
2105     int seq_end;
2106     guint ctrl_length;
2107
2108     ret = read_sequence(a, &seq_length);
2109     if (ret != ASN1_ERR_NOERROR) {
2110       proto_tree_add_text(ctrls_tree, a->tvb, a->offset, 0,
2111                           "ERROR: Couldn't parse LDAP Control: %s",
2112                           asn1_err_to_str(ret));
2113       return;
2114     }
2115
2116     ctrl_length = (a->offset - seq_start) + seq_length;
2117     ctrl_item = proto_tree_add_text(ctrls_tree, a->tvb, seq_start, ctrl_length, "LDAP Control");
2118     ctrl_tree = proto_item_add_subtree(ctrl_item, ett_ldap_control);
2119
2120     seq_end = a->offset + seq_length;
2121
2122     ret = read_string(a, ctrl_tree, hf_ldap_message_controls_oid, 0, 0, 0, ASN1_UNI, ASN1_OTS);
2123     if (ret != ASN1_ERR_NOERROR) {
2124       return;
2125     }
2126
2127     if (a->offset >= seq_end) {
2128       /* skip optional data */
2129       break;
2130     }
2131
2132     ret = check_optional_tag(a, ASN1_UNI, ASN1_PRI, ASN1_BOL);
2133     if (ret == ASN1_ERR_NOERROR) {
2134       ret = read_boolean(a, ctrl_tree, hf_ldap_message_controls_critical, 0, 0);
2135       if (ret != ASN1_ERR_NOERROR) {
2136         return;
2137       }
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_OTS);
2146     if (ret == ASN1_ERR_NOERROR) {
2147       ret = read_bytestring(a, ctrl_tree, hf_ldap_message_controls_value, NULL, NULL, ASN1_UNI, ASN1_OTS);
2148       if (ret != ASN1_ERR_NOERROR) {
2149         return;
2150       }
2151     }
2152   }
2153 }
2154
2155 static ldap_call_response_t *
2156 ldap_match_call_response(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, ldap_conv_info_t *ldap_info, guint messageId, guint protocolOpTag)
2157 {
2158   ldap_call_response_t lcr, *lcrp=NULL;
2159
2160   if (!pinfo->fd->flags.visited) {
2161     switch(protocolOpTag){
2162       case LDAP_REQ_BIND:
2163       case LDAP_REQ_SEARCH:
2164       case LDAP_REQ_MODIFY:
2165       case LDAP_REQ_ADD:
2166       case LDAP_REQ_DELETE:
2167       case LDAP_REQ_MODRDN:
2168       case LDAP_REQ_COMPARE:
2169       /*case LDAP_REQ_ABANDON: we dont match for this one*/
2170       /*case LDAP_REQ_UNBIND: we dont match for this one*/
2171         /* check that we dont already have one of those in the
2172            unmatched list and if so remove it */
2173         lcr.messageId=messageId;
2174         lcrp=g_hash_table_lookup(ldap_info->unmatched, &lcr);
2175         if(lcrp){
2176           g_hash_table_remove(ldap_info->unmatched, lcrp);
2177         }
2178         /* if we cant reuse the old one, grab a new chunk */
2179         if(!lcrp){
2180           lcrp=se_alloc(sizeof(ldap_call_response_t));
2181         }
2182         lcrp->messageId=messageId;
2183         lcrp->req_frame=pinfo->fd->num;
2184         lcrp->req_time=pinfo->fd->abs_ts;
2185         lcrp->rep_frame=0;
2186         lcrp->protocolOpTag=protocolOpTag;
2187         lcrp->is_request=TRUE;
2188         g_hash_table_insert(ldap_info->unmatched, lcrp, lcrp);
2189         return NULL;
2190         break;
2191       case LDAP_RES_BIND:
2192       case LDAP_RES_SEARCH_ENTRY:
2193       case LDAP_RES_SEARCH_REF:
2194       case LDAP_RES_SEARCH_RESULT:
2195       case LDAP_RES_MODIFY:
2196       case LDAP_RES_ADD:
2197       case LDAP_RES_DELETE:
2198       case LDAP_RES_MODRDN:
2199       case LDAP_RES_COMPARE:
2200         lcr.messageId=messageId;
2201         lcrp=g_hash_table_lookup(ldap_info->unmatched, &lcr);
2202         if(lcrp){
2203           if(!lcrp->rep_frame){
2204             g_hash_table_remove(ldap_info->unmatched, lcrp);
2205             lcrp->rep_frame=pinfo->fd->num;
2206             lcrp->is_request=FALSE;
2207             g_hash_table_insert(ldap_info->matched, lcrp, lcrp);
2208           }
2209         }
2210     }
2211   }
2212
2213   if(!lcrp){
2214     lcr.messageId=messageId;
2215     switch(protocolOpTag){
2216       case LDAP_REQ_BIND:
2217       case LDAP_REQ_SEARCH:
2218       case LDAP_REQ_MODIFY:
2219       case LDAP_REQ_ADD:
2220       case LDAP_REQ_DELETE:
2221       case LDAP_REQ_MODRDN:
2222       case LDAP_REQ_COMPARE:
2223       /*case LDAP_REQ_ABANDON: we dont match for this one*/
2224       /*case LDAP_REQ_UNBIND: we dont match for this one*/
2225         lcr.is_request=TRUE;
2226         lcr.req_frame=pinfo->fd->num;
2227         lcr.rep_frame=0;
2228         break;
2229       case LDAP_RES_BIND:
2230       case LDAP_RES_SEARCH_ENTRY:
2231       case LDAP_RES_SEARCH_REF:
2232       case LDAP_RES_SEARCH_RESULT:
2233       case LDAP_RES_MODIFY:
2234       case LDAP_RES_ADD:
2235       case LDAP_RES_DELETE:
2236       case LDAP_RES_MODRDN:
2237       case LDAP_RES_COMPARE:
2238         lcr.is_request=FALSE;
2239         lcr.req_frame=0;
2240         lcr.rep_frame=pinfo->fd->num;
2241         break;
2242     }
2243     lcrp=g_hash_table_lookup(ldap_info->matched, &lcr);
2244     if(lcrp){
2245       lcrp->is_request=lcr.is_request;
2246     }
2247   }
2248   if(lcrp){
2249     if(lcrp->is_request){
2250       proto_tree_add_uint(tree, hf_ldap_response_in, tvb, 0, 0, lcrp->rep_frame);
2251     } else {
2252       nstime_t ns;
2253       proto_tree_add_uint(tree, hf_ldap_response_to, tvb, 0, 0, lcrp->req_frame);
2254       nstime_delta(&ns, &pinfo->fd->abs_ts, &lcrp->req_time);
2255       proto_tree_add_time(tree, hf_ldap_time, tvb, 0, 0, &ns);
2256     }
2257     return lcrp;
2258   }
2259   return NULL;
2260 }
2261
2262
2263 static void
2264 dissect_ldap_message(tvbuff_t *tvb, int offset, packet_info *pinfo,
2265                 proto_tree *ldap_tree, proto_item *ldap_item, 
2266                 gboolean first_time, ldap_conv_info_t *ldap_info,
2267                 gboolean is_mscldap)
2268 {
2269   int message_id_start;
2270   int message_id_length;
2271   guint messageLength;
2272   guint messageId;
2273   int next_offset;
2274   guint protocolOpCls, protocolOpCon, protocolOpTag;
2275   const gchar *typestr;
2276   guint opLen;
2277   ASN1_SCK a;
2278   int start;
2279   int ret;
2280   ldap_call_response_t *lcrp;
2281
2282   asn1_open(&a, tvb, offset);
2283
2284   ret = read_sequence(&a, &messageLength);
2285   if (ret != ASN1_ERR_NOERROR)
2286   {
2287     if (first_time)
2288     {
2289       if (check_col(pinfo->cinfo, COL_INFO))
2290       {
2291         col_add_fstr(pinfo->cinfo, COL_INFO,
2292                     "Invalid LDAP message (Can't parse sequence header: %s)",
2293                     asn1_err_to_str(ret));
2294       }
2295     }
2296     if (ldap_tree)
2297     {
2298       proto_tree_add_text(ldap_tree, tvb, offset, -1,
2299                           "Invalid LDAP message (Can't parse sequence header: %s)",
2300                           asn1_err_to_str(ret));
2301     }
2302     return;
2303   }
2304
2305   message_id_start = a.offset;
2306   ret = read_integer(&a, 0, hf_ldap_message_id, 0, &messageId, ASN1_INT);
2307   if (ret != ASN1_ERR_NOERROR)
2308   {
2309     if (first_time && check_col(pinfo->cinfo, COL_INFO))
2310       col_add_fstr(pinfo->cinfo, COL_INFO, "Invalid LDAP packet (Can't parse Message ID: %s)",
2311                    asn1_err_to_str(ret));
2312     if (ldap_tree)
2313       proto_tree_add_text(ldap_tree, tvb, message_id_start, 1,
2314                           "Invalid LDAP packet (Can't parse Message ID: %s)",
2315                           asn1_err_to_str(ret));
2316       return;
2317   }
2318   message_id_length = a.offset - message_id_start;
2319
2320   start = a.offset;
2321   asn1_id_decode(&a, &protocolOpCls, &protocolOpCon, &protocolOpTag);
2322   if (protocolOpCls != ASN1_APL)
2323     typestr = "Bad message type (not Application)";
2324   else
2325     typestr = val_to_str(protocolOpTag, msgTypes, "Unknown message type (%u)");
2326
2327   if (first_time)
2328   {
2329     if (check_col(pinfo->cinfo, COL_INFO))
2330       col_add_fstr(pinfo->cinfo, COL_INFO, "MsgId=%u %s",
2331                    messageId, typestr);
2332   }
2333
2334   if (ldap_item)
2335           proto_item_append_text(ldap_item, ", %s", 
2336                                  val_to_str(protocolOpTag, msgTypes,
2337                                             "Unknown message type (%u)"));
2338
2339   if (ldap_tree)
2340   {
2341     proto_tree_add_uint(ldap_tree, hf_ldap_message_id, tvb, message_id_start, message_id_length, messageId);
2342     if (protocolOpCls == ASN1_APL)
2343     {
2344       proto_tree_add_uint(ldap_tree, hf_ldap_message_type, tvb,
2345                           start, a.offset - start, protocolOpTag);
2346     }
2347     else
2348     {
2349       proto_tree_add_text(ldap_tree, tvb, start, a.offset - start,
2350                           "%s", typestr);
2351     }
2352   }
2353   start = a.offset;
2354   if (read_length(&a, ldap_tree, hf_ldap_message_length, &opLen) != ASN1_ERR_NOERROR)
2355     return;
2356
2357   if (protocolOpCls == ASN1_APL)
2358   {
2359     lcrp=ldap_match_call_response(tvb, pinfo, ldap_tree, ldap_info, messageId, protocolOpTag);
2360     if(lcrp){
2361       tap_queue_packet(ldap_tap, pinfo, lcrp);
2362     }
2363
2364     /*
2365      * XXX - we should check for errors from these routines (and they
2366      * should return errors), and not try to dissect the LDAP controls
2367      * if they get an error.
2368      */
2369     switch (protocolOpTag)
2370     {
2371      case LDAP_REQ_BIND:
2372       dissect_ldap_request_bind(&a, ldap_tree, tvb, pinfo, ldap_info);
2373       break;
2374      case LDAP_REQ_UNBIND:
2375       /* Nothing to dissect */
2376       break;
2377      case LDAP_REQ_SEARCH:
2378       dissect_ldap_request_search(&a, ldap_tree, pinfo);
2379       break;
2380      case LDAP_REQ_MODIFY:
2381       dissect_ldap_request_modify(&a, ldap_tree);
2382       break;
2383      case LDAP_REQ_ADD:
2384       dissect_ldap_request_add(&a, ldap_tree, pinfo);
2385       break;
2386      case LDAP_REQ_DELETE:
2387       dissect_ldap_request_delete(&a, ldap_tree, start, opLen);
2388       break;
2389      case LDAP_REQ_MODRDN:
2390       dissect_ldap_request_modifyrdn(&a, ldap_tree, opLen);
2391       break;
2392      case LDAP_REQ_COMPARE:
2393       dissect_ldap_request_compare(&a, ldap_tree);
2394       break;
2395      case LDAP_REQ_ABANDON:
2396       dissect_ldap_request_abandon(&a, ldap_tree, start, opLen);
2397       break;
2398      case LDAP_RES_BIND:
2399       dissect_ldap_response_bind(&a, ldap_tree, start, opLen, tvb, pinfo, ldap_info);
2400       break;
2401      case LDAP_RES_SEARCH_ENTRY: {
2402             /*
2403              * XXX - this assumes that the LDAP_RES_SEARCH_ENTRY and
2404              * LDAP_RES_SEARCH_RESULT appear in the same frame.
2405              */
2406             guint32 *num_results = p_get_proto_data(pinfo->fd, proto_ldap);
2407
2408             if (!num_results) {
2409                     num_results = g_malloc(sizeof(guint32));
2410                     *num_results = 0;
2411                     p_add_proto_data(pinfo->fd, proto_ldap, num_results);
2412             }
2413
2414             *num_results += 1;
2415             dissect_ldap_response_search_entry(&a, ldap_tree, is_mscldap);
2416
2417             break;
2418      }
2419      case LDAP_RES_SEARCH_REF:
2420       dissect_ldap_response_search_ref(&a, ldap_tree);
2421       break;
2422
2423      case LDAP_RES_SEARCH_RESULT: {
2424              guint32 *num_results = p_get_proto_data(pinfo->fd, proto_ldap);
2425
2426              if (num_results) {
2427                      if (check_col(pinfo->cinfo, COL_INFO))
2428                              col_append_fstr(pinfo->cinfo, COL_INFO, ", %d result%s", 
2429                                              *num_results, *num_results == 1 ? "" : "s");
2430                      g_free(num_results);
2431                      p_rem_proto_data(pinfo->fd, proto_ldap);
2432              }
2433
2434              dissect_ldap_result(&a, ldap_tree, pinfo);
2435
2436              break;
2437      }
2438
2439      case LDAP_RES_MODIFY:
2440      case LDAP_RES_ADD:
2441      case LDAP_RES_DELETE:
2442      case LDAP_RES_MODRDN:
2443      case LDAP_RES_COMPARE:
2444         dissect_ldap_result(&a, ldap_tree, pinfo);
2445       break;
2446      default:
2447       if (ldap_tree)
2448       {
2449         proto_tree_add_text(ldap_tree, a.tvb, a.offset, opLen,
2450                             "Unknown LDAP operation (%u)", protocolOpTag);
2451       }
2452       break;
2453     }
2454   }
2455
2456   if ((int)messageLength > 0 && (message_id_start + (int)messageLength) > a.offset) {
2457     dissect_ldap_controls(&a, ldap_tree);
2458   }
2459
2460   /*
2461    * XXX - what if "next_offset" is past the offset of the next top-level
2462    * sequence?  Show that as an error?
2463    */
2464   asn1_close(&a, &next_offset); /* XXX - use the new value of next_offset? */
2465 }
2466
2467 static void
2468 dissect_ldap_payload(tvbuff_t *tvb, packet_info *pinfo,
2469                      proto_tree *tree, ldap_conv_info_t *ldap_info,
2470                      gboolean rest_is_pad, gboolean is_mscldap)
2471 {
2472   int offset = 0;
2473   gboolean first_time = TRUE;
2474   guint length_remaining;
2475   ASN1_SCK a;
2476   int ret;
2477   guint msg_len = 0;
2478   int messageOffset = 0;
2479   guint headerLength = 0;
2480   guint length = 0;
2481   tvbuff_t *msg_tvb = NULL;
2482   proto_item *msg_item = NULL;
2483   proto_tree *msg_tree = NULL;
2484
2485   while (tvb_reported_length_remaining(tvb, offset) > 0) {
2486     /*
2487      * This will throw an exception if we don't have any data left.
2488      * That's what we want.  (See "tcp_dissect_pdus()", which is
2489      * similar)
2490      */
2491     length_remaining = tvb_ensure_length_remaining(tvb, offset);
2492
2493     if (rest_is_pad && length_remaining < 6) return;
2494
2495     /*
2496      * The frame begins
2497      * with a "Sequence Of" header.
2498      * Can we do reassembly?
2499      */
2500     if (ldap_desegment && pinfo->can_desegment) {
2501         /*
2502          * Yes - is the "Sequence Of" header split across segment
2503          * boundaries?  We require at least 6 bytes for the header
2504          * which allows for a 4 byte length (ASN.1 BER).
2505          */
2506         if (length_remaining < 6) {
2507           /* stop if the caller says that we are given all data and the rest is padding
2508            * this is for the SASL GSSAPI case when the data is only signed and not sealed
2509            */
2510           pinfo->desegment_offset = offset;
2511           pinfo->desegment_len = 6 - length_remaining;
2512           return;
2513         }
2514     }
2515
2516     /*
2517      * OK, try to read the "Sequence Of" header; this gets the total
2518      * length of the LDAP message.
2519      */
2520     asn1_open(&a, tvb, offset);
2521     ret = read_sequence(&a, &msg_len);
2522     asn1_close(&a, &messageOffset);
2523
2524     if (ret == ASN1_ERR_NOERROR) {
2525         /*
2526          * Add the length of the "Sequence Of" header to the message
2527          * length.
2528          */
2529         headerLength = messageOffset - offset;
2530         msg_len += headerLength;
2531         if (msg_len < headerLength) {
2532             /*
2533              * The message length was probably so large that the total length
2534              * overflowed.
2535              *
2536              * Report this as an error.
2537              */
2538             show_reported_bounds_error(tvb, pinfo, tree);
2539             return;
2540         }
2541     } else {
2542         /*
2543          * We couldn't parse the header; just make it the amount of data
2544          * remaining in the tvbuff, so we'll give up on this segment
2545          * after attempting to parse the message - there's nothing more
2546          * we can do.  "dissect_ldap_message()" will display the error.
2547          */
2548         msg_len = length_remaining;
2549     }
2550
2551     /*
2552      * Is the message split across segment boundaries?
2553      */
2554     if (length_remaining < msg_len) {
2555         /* provide a hint to TCP where the next PDU starts */
2556         pinfo->want_pdu_tracking=2;
2557         pinfo->bytes_until_next_pdu= msg_len - length_remaining;
2558         /*
2559          * Can we do reassembly?
2560          */
2561         if (ldap_desegment && pinfo->can_desegment) {
2562             /*
2563              * Yes.  Tell the TCP dissector where the data for this message
2564              * starts in the data it handed us, and how many more bytes
2565              * we need, and return.
2566              */
2567             pinfo->desegment_offset = offset;
2568             pinfo->desegment_len = msg_len - length_remaining;
2569             return;
2570         }
2571     }
2572
2573     /*
2574      * Construct a tvbuff containing the amount of the payload we have
2575      * available.  Make its reported length the amount of data in the
2576      * LDAP message.
2577      *
2578      * XXX - if reassembly isn't enabled. the subdissector will throw a
2579      * BoundsError exception, rather than a ReportedBoundsError exception.
2580      * We really want a tvbuff where the length is "length", the reported
2581      * length is "plen", and the "if the snapshot length were infinite"
2582      * length is the minimum of the reported length of the tvbuff handed
2583      * to us and "plen", with a new type of exception thrown if the offset
2584      * is within the reported length but beyond that third length, with
2585      * that exception getting the "Unreassembled Packet" error.
2586      */
2587     length = length_remaining;
2588     if (length > msg_len) length = msg_len;
2589     msg_tvb = tvb_new_subset(tvb, offset, length, msg_len);
2590
2591     /*
2592      * Now dissect the LDAP message.
2593      */
2594     if (tree) {
2595         msg_item = proto_tree_add_text(tree, msg_tvb, 0, msg_len, "LDAP Message");
2596         msg_tree = proto_item_add_subtree(msg_item, ett_ldap_msg);
2597     }
2598
2599     dissect_ldap_message(msg_tvb, 0, pinfo, msg_tree, msg_item, first_time, ldap_info, is_mscldap);
2600
2601     offset += msg_len;
2602
2603     first_time = FALSE;
2604   }
2605 }
2606
2607
2608 static void
2609 dissect_ldap_pdu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gboolean is_mscldap)
2610 {
2611   int offset = 0;
2612   conversation_t *conversation;
2613   gboolean doing_sasl_security = FALSE;
2614   guint length_remaining;
2615   ldap_conv_info_t *ldap_info = NULL;
2616   proto_item *ldap_item = NULL;
2617   proto_tree *ldap_tree = NULL;
2618
2619   /*
2620    * Do we have a conversation for this connection?
2621    */
2622   conversation = find_conversation(pinfo->fd->num, &pinfo->src, &pinfo->dst,
2623                                    pinfo->ptype, pinfo->srcport,
2624                                    pinfo->destport, 0);
2625   if (conversation == NULL) {
2626     /* We don't yet have a conversation, so create one. */
2627     conversation = conversation_new(pinfo->fd->num, &pinfo->src, &pinfo->dst,
2628                                     pinfo->ptype, pinfo->srcport,
2629                                     pinfo->destport, 0);
2630   }
2631
2632   /*
2633    * Do we already have a type and mechanism?
2634    */
2635   ldap_info = conversation_get_proto_data(conversation, proto_ldap);
2636   if (ldap_info == NULL) {
2637     /* No.  Attach that information to the conversation, and add
2638      * it to the list of information structures.
2639      */
2640     ldap_info = se_alloc(sizeof(ldap_conv_info_t));
2641     ldap_info->auth_type = 0;
2642     ldap_info->auth_mech = 0;
2643     ldap_info->first_auth_frame = 0;
2644     ldap_info->matched=g_hash_table_new(ldap_info_hash_matched, ldap_info_equal_matched);
2645     ldap_info->unmatched=g_hash_table_new(ldap_info_hash_unmatched, ldap_info_equal_unmatched);
2646     conversation_add_proto_data(conversation, proto_ldap, ldap_info);
2647     ldap_info->next = ldap_info_items;
2648     ldap_info_items = ldap_info;
2649   } 
2650
2651   switch (ldap_info->auth_type) {
2652     case LDAP_AUTH_SASL:
2653     /*
2654      * It's SASL; are we using a security layer?
2655      */
2656     if (ldap_info->first_auth_frame != 0 &&
2657        pinfo->fd->num >= ldap_info->first_auth_frame) {
2658         doing_sasl_security = TRUE;     /* yes */
2659     }
2660   }
2661
2662   while (tvb_reported_length_remaining(tvb, offset) > 0) {
2663
2664     /*
2665      * This will throw an exception if we don't have any data left.
2666      * That's what we want.  (See "tcp_dissect_pdus()", which is
2667      * similar, but doesn't have to deal with the SASL issues.
2668      * XXX - can we make "tcp_dissect_pdus()" provide enough information
2669      * to the "get_pdu_len" routine so that we could have one dealing
2670      * with the SASL issues, have that routine deal with SASL and
2671      * ASN.1, and just use "tcp_dissect_pdus()"?)
2672      */
2673     length_remaining = tvb_ensure_length_remaining(tvb, offset);
2674
2675     /*
2676      * Try to find out if we have a plain LDAP buffer
2677      * with a "Sequence Of" header or a SASL buffer with
2678      * Can we do reassembly?
2679      */
2680     if (ldap_desegment && pinfo->can_desegment) {
2681         /*
2682          * Yes - is the "Sequence Of" header split across segment
2683          * boundaries?  We require at least 6 bytes for the header
2684          * which allows for a 4 byte length (ASN.1 BER).
2685          * For the SASL case we need at least 4 bytes, so this is 
2686          * no problem here because we check for 6 bytes ans sasl buffers
2687          * with less than 2 bytes should not exist...
2688          */
2689         if (length_remaining < 6) {
2690             pinfo->desegment_offset = offset;
2691             pinfo->desegment_len = 6 - length_remaining;
2692             return;
2693         }
2694     }
2695
2696     /* It might still be a packet containing a SASL security layer
2697      * but its just that we never saw the BIND packet.
2698      * check if it looks like it could be a SASL blob here
2699      * and in that case just assume it is GSS-SPNEGO
2700      */
2701     if(!doing_sasl_security && (tvb_bytes_exist(tvb, offset, 5))
2702       &&(tvb_get_ntohl(tvb, offset)<=(guint)(tvb_reported_length_remaining(tvb, offset)-4))
2703       &&(tvb_get_guint8(tvb, offset+4)==0x60) ){
2704         ldap_info->auth_type=LDAP_AUTH_SASL;
2705         ldap_info->first_auth_frame=pinfo->fd->num;
2706         ldap_info->auth_mech=g_strdup("GSS-SPNEGO");
2707         doing_sasl_security=TRUE;
2708     }
2709
2710     /*
2711      * This is the first PDU, set the Protocol column and clear the
2712      * Info column.
2713      */
2714     if (check_col(pinfo->cinfo, COL_PROTOCOL)) col_set_str(pinfo->cinfo, COL_PROTOCOL, pinfo->current_proto);
2715     if (check_col(pinfo->cinfo, COL_INFO)) col_clear(pinfo->cinfo, COL_INFO);
2716
2717     ldap_item = proto_tree_add_item(tree, proto_ldap, tvb, 0, -1, FALSE);
2718     ldap_tree = proto_item_add_subtree(ldap_item, ett_ldap);
2719
2720     /*
2721      * Might we be doing a SASL security layer and, if so, *are* we doing
2722      * one?
2723      *
2724      * Just because we've seen a bind reply for SASL, that doesn't mean
2725      * that we're using a SASL security layer; I've seen captures in
2726      * which some SASL negotiations lead to a security layer being used
2727      * and other negotiations don't, and it's not obvious what's different
2728      * in the two negotiations.  Therefore, we assume that if the first
2729      * byte is 0, it's a length for a SASL security layer (that way, we
2730      * never reassemble more than 16 megabytes, protecting us from
2731      * chewing up *too* much memory), and otherwise that it's an LDAP
2732      * message (actually, if it's an LDAP message it should begin with 0x30,
2733      * but we want to parse garbage as LDAP messages rather than really
2734      * huge lengths).
2735      */
2736
2737     if (doing_sasl_security && tvb_get_guint8(tvb, offset) == 0) {
2738       proto_item *sasl_item = NULL;
2739       proto_tree *sasl_tree = NULL;
2740       tvbuff_t *sasl_tvb;
2741       guint sasl_len, sasl_msg_len, length;
2742       /*
2743        * Yes.  The frame begins with a 4-byte big-endian length.
2744        * And we know we have at least 6 bytes
2745        */
2746
2747       /*
2748        * Get the SASL length, which is the length of data in the buffer
2749        * following the length (i.e., it's 4 less than the total length).
2750        *
2751        * XXX - do we need to reassemble buffers?  For now, we
2752        * assume that each LDAP message is entirely contained within
2753        * a buffer.
2754        */
2755       sasl_len = tvb_get_ntohl(tvb, offset);
2756       sasl_msg_len = sasl_len + 4;
2757       if (sasl_msg_len < 4) {
2758         /*
2759          * The message length was probably so large that the total length
2760          * overflowed.
2761          *
2762          * Report this as an error.
2763          */
2764         show_reported_bounds_error(tvb, pinfo, tree);
2765         return;
2766       }
2767
2768       /*
2769        * Is the buffer split across segment boundaries?
2770        */
2771       if (length_remaining < sasl_msg_len) {
2772         /* provide a hint to TCP where the next PDU starts */
2773         pinfo->want_pdu_tracking = 2;
2774         pinfo->bytes_until_next_pdu= sasl_msg_len - length_remaining;
2775         /*
2776          * Can we do reassembly?
2777          */
2778         if (ldap_desegment && pinfo->can_desegment) {
2779           /*
2780            * Yes.  Tell the TCP dissector where the data for this message
2781            * starts in the data it handed us, and how many more bytes we
2782            * need, and return.
2783            */
2784           pinfo->desegment_offset = offset;
2785           pinfo->desegment_len = sasl_msg_len - length_remaining;
2786           return;
2787         }
2788       }
2789
2790       /*
2791        * Construct a tvbuff containing the amount of the payload we have
2792        * available.  Make its reported length the amount of data in the PDU.
2793        *
2794        * XXX - if reassembly isn't enabled. the subdissector will throw a
2795        * BoundsError exception, rather than a ReportedBoundsError exception.
2796        * We really want a tvbuff where the length is "length", the reported
2797        * length is "plen", and the "if the snapshot length were infinite"
2798        * length is the minimum of the reported length of the tvbuff handed
2799        * to us and "plen", with a new type of exception thrown if the offset
2800        * is within the reported length but beyond that third length, with
2801        * that exception getting the "Unreassembled Packet" error.
2802        */
2803       length = length_remaining;
2804       if (length > sasl_msg_len) length = sasl_msg_len;
2805       sasl_tvb = tvb_new_subset(tvb, offset, length, sasl_msg_len);
2806
2807       if (ldap_tree) {
2808         proto_tree_add_uint(ldap_tree, hf_ldap_sasl_buffer_length, sasl_tvb, 0, 4,
2809                             sasl_len);
2810
2811         sasl_item = proto_tree_add_text(ldap_tree, sasl_tvb, 0,  sasl_msg_len, "SASL buffer");
2812         sasl_tree = proto_item_add_subtree(sasl_item, ett_ldap_sasl_blob);
2813       }
2814
2815       if (ldap_info->auth_mech != NULL &&
2816           strcmp(ldap_info->auth_mech, "GSS-SPNEGO") == 0) {
2817           tvbuff_t *gssapi_tvb, *plain_tvb = NULL, *decr_tvb= NULL;
2818           int ver_len;
2819           int length;
2820
2821           /*
2822            * This is GSS-API (using SPNEGO, but we should be done with
2823            * the negotiation by now).
2824            *
2825            * Dissect the GSS_Wrap() token; it'll return the length of
2826            * the token, from which we compute the offset in the tvbuff at
2827            * which the plaintext data, i.e. the LDAP message, begins.
2828            */
2829           length = tvb_length_remaining(sasl_tvb, 4);
2830           if ((guint)length > sasl_len)
2831               length = sasl_len;
2832           gssapi_tvb = tvb_new_subset(sasl_tvb, 4, length, sasl_len);
2833
2834           /* Attempt decryption of the GSSAPI wrapped data if possible */
2835           pinfo->decrypt_gssapi_tvb=DECRYPT_GSSAPI_NORMAL;
2836           pinfo->gssapi_wrap_tvb=NULL;
2837           pinfo->gssapi_encrypted_tvb=NULL;
2838           pinfo->gssapi_decrypted_tvb=NULL;
2839           ver_len = call_dissector(gssapi_wrap_handle, gssapi_tvb, pinfo, sasl_tree);
2840           /* if we could unwrap, do a tvb shuffle */
2841           if(pinfo->gssapi_decrypted_tvb){
2842                 decr_tvb=pinfo->gssapi_decrypted_tvb;
2843           }
2844           /* tidy up */
2845           pinfo->decrypt_gssapi_tvb=0;
2846           pinfo->gssapi_wrap_tvb=NULL;
2847           pinfo->gssapi_encrypted_tvb=NULL;
2848           pinfo->gssapi_decrypted_tvb=NULL;
2849
2850           /*
2851            * if len is 0 it probably mean that we got a PDU that is not
2852            * aligned to the start of the segment.
2853            */
2854           if(ver_len==0){
2855              return;
2856           }
2857
2858           /*
2859            * if we don't have unwrapped data,
2860            * see if the wrapping involved encryption of the
2861            * data; if not, just use the plaintext data.
2862            */
2863           if (!decr_tvb) {
2864             if(!pinfo->gssapi_data_encrypted){
2865               plain_tvb = tvb_new_subset(gssapi_tvb,  ver_len, -1, -1);
2866             }
2867           }
2868
2869           if (decr_tvb) {
2870             proto_item *enc_item = NULL;
2871             proto_tree *enc_tree = NULL;
2872
2873             /*
2874              * The LDAP message was encrypted in the packet, and has
2875              * been decrypted; dissect the decrypted LDAP message.
2876              */
2877             if (sasl_tree) {
2878               enc_item = proto_tree_add_text(sasl_tree, gssapi_tvb, ver_len, -1,
2879                                 "GSS-API Encrypted payload (%d byte%s)",
2880                                 sasl_len - ver_len,
2881                                 plurality(sasl_len - ver_len, "", "s"));
2882               enc_tree = proto_item_add_subtree(enc_item, ett_ldap_payload);
2883             }
2884             dissect_ldap_payload(decr_tvb, pinfo, enc_tree, ldap_info, TRUE, is_mscldap);
2885           } else if (plain_tvb) {
2886             proto_item *plain_item = NULL;
2887             proto_tree *plain_tree = NULL;
2888
2889             /*
2890              * The LDAP message wasn't encrypted in the packet;
2891              * dissect the plain LDAP message.
2892              */
2893             if (sasl_tree) {
2894               plain_item = proto_tree_add_text(sasl_tree, gssapi_tvb, ver_len, -1,
2895                                 "GSS-API payload (%d byte%s)",
2896                                 sasl_len - ver_len,
2897                                 plurality(sasl_len - ver_len, "", "s"));
2898               plain_tree = proto_item_add_subtree(plain_item, ett_ldap_payload);
2899             }
2900             dissect_ldap_payload(plain_tvb, pinfo, plain_tree, ldap_info, TRUE, is_mscldap);
2901           } else {
2902             /*
2903              * The LDAP message was encrypted in the packet, and was
2904              * not decrypted; just show it as encrypted data.
2905              */
2906             if (check_col(pinfo->cinfo, COL_INFO)) {
2907                     col_add_fstr(pinfo->cinfo, COL_INFO, "LDAP GSS-API Encrypted payload (%d byte%s)",
2908                                  sasl_len - ver_len,
2909                                  plurality(sasl_len - ver_len, "", "s"));
2910             }
2911             if (sasl_tree) {
2912               proto_tree_add_text(sasl_tree, gssapi_tvb, ver_len, -1,
2913                                 "GSS-API Encrypted payload (%d byte%s)",
2914                                 sasl_len - ver_len,
2915                                 plurality(sasl_len - ver_len, "", "s"));
2916             }
2917           }
2918       }
2919       offset += sasl_msg_len;
2920     } else {
2921         /* plain LDAP, so dissect the payload */
2922         dissect_ldap_payload(tvb, pinfo, ldap_tree, ldap_info, FALSE, is_mscldap);
2923         /* dissect_ldap_payload() has it's own loop so go out here */
2924         break;
2925     }
2926   }
2927 }
2928
2929
2930 static void
2931 dissect_ldap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
2932 {
2933         dissect_ldap_pdu(tvb, pinfo, tree, FALSE);
2934         return;
2935 }
2936
2937 static void
2938 dissect_mscldap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
2939 {
2940         dissect_ldap_pdu(tvb, pinfo, tree, TRUE);
2941         return;
2942 }
2943
2944 static void
2945 ldap_reinit(void)
2946 {
2947   ldap_conv_info_t *ldap_info;
2948
2949   /* Free up state attached to the ldap_info structures */
2950   for (ldap_info = ldap_info_items; ldap_info != NULL; ldap_info = ldap_info->next) {
2951     if (ldap_info->auth_mech != NULL) {
2952       g_free(ldap_info->auth_mech);
2953       ldap_info->auth_mech=NULL;
2954     }
2955     g_hash_table_destroy(ldap_info->matched);
2956     ldap_info->matched=NULL;
2957     g_hash_table_destroy(ldap_info->unmatched);
2958     ldap_info->unmatched=NULL;
2959   }
2960
2961   ldap_info_items = NULL;
2962
2963 }
2964
2965 void
2966 proto_register_ldap(void)
2967 {
2968   static value_string auth_types[] = {
2969     {LDAP_AUTH_SIMPLE,    "Simple"},
2970     {LDAP_AUTH_KRBV4LDAP, "Kerberos V4 to the LDAP server"},
2971     {LDAP_AUTH_KRBV4DSA,  "Kerberos V4 to the DSA"},
2972     {LDAP_AUTH_SASL,      "SASL"},
2973     {0, NULL},
2974   };
2975
2976   static value_string search_scope[] = {
2977     {0x00, "Base"},
2978     {0x01, "Single"},
2979     {0x02, "Subtree"},
2980     {0x00, NULL},
2981   };
2982
2983   static value_string search_dereference[] = {
2984     {0x00, "Never"},
2985     {0x01, "Searching"},
2986     {0x02, "Base Object"},
2987     {0x03, "Always"},
2988     {0x00, NULL},
2989   };
2990
2991   static hf_register_info hf[] = {
2992     { &hf_ldap_response_in,
2993       { "Response In", "ldap.response_in",
2994         FT_FRAMENUM, BASE_DEC, NULL, 0x0,
2995         "The response to this packet is in this frame", HFILL }},
2996
2997     { &hf_ldap_response_to,
2998       { "Response To", "ldap.response_to",
2999         FT_FRAMENUM, BASE_DEC, NULL, 0x0,
3000         "This is a response to the LDAP command in this frame", HFILL }},
3001
3002     { &hf_ldap_time,
3003       { "Time", "ldap.time",
3004         FT_RELATIVE_TIME, BASE_NONE, NULL, 0x0,
3005         "The time between the Call and the Reply", HFILL }},
3006
3007     { &hf_ldap_sasl_buffer_length,
3008       { "SASL Buffer Length",   "ldap.sasl_buffer_length",
3009         FT_UINT32, BASE_DEC, NULL, 0x0,
3010         "SASL Buffer Length", HFILL }},
3011
3012     { &hf_ldap_length,
3013       { "Length",               "ldap.length",
3014         FT_UINT32, BASE_DEC, NULL, 0x0,
3015         "LDAP Length", HFILL }},
3016
3017     { &hf_ldap_message_id,
3018       { "Message Id",           "ldap.message_id",
3019         FT_UINT32, BASE_DEC, NULL, 0x0,
3020         "LDAP Message Id", HFILL }},
3021     { &hf_ldap_message_type,
3022       { "Message Type",         "ldap.message_type",
3023         FT_UINT8, BASE_HEX, &msgTypes, 0x0,
3024         "LDAP Message Type", HFILL }},
3025     { &hf_ldap_message_length,
3026       { "Message Length",               "ldap.message_length",
3027         FT_UINT32, BASE_DEC, NULL, 0x0,
3028         "LDAP Message Length", HFILL }},
3029
3030     { &hf_ldap_message_result,
3031       { "Result Code",          "ldap.result.code",
3032         FT_UINT8, BASE_HEX, VALS(LDAPResultCode_vals), 0x0,
3033         "LDAP Result Code", HFILL }},
3034     { &hf_ldap_message_result_matcheddn,
3035       { "Matched DN",           "ldap.result.matcheddn",
3036         FT_STRING, BASE_NONE, NULL, 0x0,
3037         "LDAP Result Matched DN", HFILL }},
3038     { &hf_ldap_message_result_errormsg,
3039       { "Error Message",                "ldap.result.errormsg",
3040         FT_STRING, BASE_NONE, NULL, 0x0,
3041         "LDAP Result Error Message", HFILL }},
3042     { &hf_ldap_message_result_referral,
3043       { "Referral",             "ldap.result.referral",
3044         FT_STRING, BASE_NONE, NULL, 0x0,
3045         "LDAP Result Referral URL", HFILL }},
3046
3047     { &hf_ldap_message_bind_version,
3048       { "Version",              "ldap.bind.version",
3049         FT_UINT32, BASE_DEC, NULL, 0x0,
3050         "LDAP Bind Version", HFILL }},
3051     { &hf_ldap_message_bind_dn,
3052       { "DN",                   "ldap.bind.dn",
3053         FT_STRING, BASE_NONE, NULL, 0x0,
3054         "LDAP Bind Distinguished Name", HFILL }},
3055     { &hf_ldap_message_bind_auth,
3056       { "Auth Type",            "ldap.bind.auth_type",
3057         FT_UINT8, BASE_HEX, auth_types, 0x0,
3058         "LDAP Bind Auth Type", HFILL }},
3059     { &hf_ldap_message_bind_auth_password,
3060       { "Password",             "ldap.bind.password",
3061         FT_STRING, BASE_NONE, NULL, 0x0,
3062         "LDAP Bind Password", HFILL }},
3063     { &hf_ldap_message_bind_auth_mechanism,
3064       { "Mechanism",            "ldap.bind.mechanism",
3065         FT_STRING, BASE_NONE, NULL, 0x0,
3066         "LDAP Bind Mechanism", HFILL }},
3067     { &hf_ldap_message_bind_auth_credentials,
3068       { "Credentials",          "ldap.bind.credentials",
3069         FT_BYTES, BASE_NONE, NULL, 0x0,
3070         "LDAP Bind Credentials", HFILL }},
3071     { &hf_ldap_message_bind_server_credentials,
3072       { "Server Credentials",   "ldap.bind.server_credentials",
3073         FT_BYTES, BASE_NONE, NULL, 0x0,
3074         "LDAP Bind Server Credentials", HFILL }},
3075
3076     { &hf_ldap_message_search_base,
3077       { "Base DN",              "ldap.search.basedn",
3078         FT_STRING, BASE_NONE, NULL, 0x0,
3079         "LDAP Search Base Distinguished Name", HFILL }},
3080     { &hf_ldap_message_search_scope,
3081       { "Scope",                        "ldap.search.scope",
3082         FT_UINT8, BASE_HEX, search_scope, 0x0,
3083         "LDAP Search Scope", HFILL }},
3084     { &hf_ldap_message_search_deref,
3085       { "Dereference",          "ldap.search.dereference",
3086         FT_UINT8, BASE_HEX, search_dereference, 0x0,
3087         "LDAP Search Dereference", HFILL }},
3088     { &hf_ldap_message_search_sizeLimit,
3089       { "Size Limit",           "ldap.search.sizelimit",
3090         FT_UINT32, BASE_DEC, NULL, 0x0,
3091         "LDAP Search Size Limit", HFILL }},
3092     { &hf_ldap_message_search_timeLimit,
3093       { "Time Limit",           "ldap.search.timelimit",
3094         FT_UINT32, BASE_DEC, NULL, 0x0,
3095         "LDAP Search Time Limit", HFILL }},
3096     { &hf_ldap_message_search_typesOnly,
3097       { "Attributes Only",      "ldap.search.typesonly",
3098         FT_BOOLEAN, BASE_NONE, NULL, 0x0,
3099         "LDAP Search Attributes Only", HFILL }},
3100     { &hf_ldap_message_search_filter,
3101       { "Filter",               "ldap.search.filter",
3102         FT_STRING, BASE_NONE, NULL, 0x0,
3103         "LDAP Search Filter", HFILL }},
3104     { &hf_ldap_message_search_reference,
3105       { "Reference URL",        "ldap.search.reference",
3106         FT_STRING, BASE_NONE, NULL, 0x0,
3107         "LDAP Search Reference URL", HFILL }},
3108     { &hf_ldap_message_dn,
3109       { "Distinguished Name",   "ldap.dn",
3110         FT_STRING, BASE_NONE, NULL, 0x0,
3111         "LDAP Distinguished Name", HFILL }},
3112     { &hf_ldap_message_attribute,
3113       { "Attribute",            "ldap.attribute",
3114         FT_STRING, BASE_NONE, NULL, 0x0,
3115         "LDAP Attribute", HFILL }},
3116     /*
3117      * XXX - not all LDAP values are text strings; we'd need a file
3118      * describing which values (by name) are text strings and which are
3119      * binary.
3120      *
3121      * Some values that are, at least in Microsoft's schema, binary
3122      * are:
3123      *
3124      *  invocationId
3125      *  nTSecurityDescriptor
3126      *  objectGUID
3127      */
3128     { &hf_ldap_message_value,
3129       { "Value",                "ldap.value",
3130         FT_STRING, BASE_NONE, NULL, 0x0,
3131         "LDAP Value", HFILL }},
3132
3133     { &hf_ldap_message_modrdn_name,
3134       { "New Name",             "ldap.modrdn.name",
3135         FT_STRING, BASE_NONE, NULL, 0x0,
3136         "LDAP New Name", HFILL }},
3137     { &hf_ldap_message_modrdn_delete,
3138       { "Delete Values",        "ldap.modrdn.delete",
3139         FT_BOOLEAN, BASE_NONE, NULL, 0x0,
3140         "LDAP Modify RDN - Delete original values", HFILL }},
3141     { &hf_ldap_message_modrdn_superior,
3142       { "New Location",         "ldap.modrdn.superior",
3143         FT_STRING, BASE_NONE, NULL, 0x0,
3144         "LDAP Modify RDN - New Location", HFILL }},
3145
3146     { &hf_ldap_message_compare,
3147       { "Test",         "ldap.compare.test",
3148         FT_STRING, BASE_NONE, NULL, 0x0,
3149         "LDAP Compare Test", HFILL }},
3150
3151     { &hf_ldap_message_modify_add,
3152       { "Add",                  "ldap.modify.add",
3153         FT_STRING, BASE_NONE, NULL, 0x0,
3154         "LDAP Add", HFILL }},
3155     { &hf_ldap_message_modify_replace,
3156       { "Replace",              "ldap.modify.replace",
3157         FT_STRING, BASE_NONE, NULL, 0x0,
3158         "LDAP Replace", HFILL }},
3159     { &hf_ldap_message_modify_delete,
3160       { "Delete",               "ldap.modify.delete",
3161         FT_STRING, BASE_NONE, NULL, 0x0,
3162         "LDAP Delete", HFILL }},
3163
3164     { &hf_ldap_message_abandon_msgid,
3165       { "Abandon Msg Id",       "ldap.abandon.msgid",
3166         FT_UINT32, BASE_DEC, NULL, 0x0,
3167         "LDAP Abandon Msg Id", HFILL }},
3168
3169     { &hf_ldap_message_controls_oid,
3170       { "Control OID",  "ldap.controls.oid",
3171         FT_STRING, BASE_NONE, NULL, 0x0,
3172         "LDAP Control OID", HFILL }},
3173
3174     { &hf_ldap_message_controls_critical,
3175       { "Control Critical",     "ldap.controls.critical",
3176         FT_BOOLEAN, BASE_NONE, NULL, 0x0,
3177         "LDAP Control Critical", HFILL }},
3178
3179     { &hf_ldap_message_controls_value,
3180       { "Control Value",        "ldap.controls.value",
3181         FT_BYTES, BASE_NONE, NULL, 0x0,
3182         "LDAP Control Value", HFILL }},
3183
3184     { &hf_mscldap_netlogon_type,
3185       { "Type", "mscldap.netlogon.type",
3186         FT_UINT32, BASE_DEC, NULL, 0x0,
3187         "Type of <please tell ethereal developers what this type is>", HFILL }},
3188
3189     { &hf_mscldap_netlogon_version,
3190       { "Version", "mscldap.netlogon.version",
3191         FT_UINT32, BASE_DEC, NULL, 0x0,
3192         "Version of <please tell ethereal developers what this type is>", HFILL }},
3193
3194     { &hf_mscldap_netlogon_lm_token,
3195       { "LM Token", "mscldap.netlogon.lm_token",
3196         FT_UINT16, BASE_HEX, NULL, 0x0,
3197         "LM Token", HFILL }},
3198
3199     { &hf_mscldap_netlogon_nt_token,
3200       { "NT Token", "mscldap.netlogon.nt_token",
3201         FT_UINT16, BASE_HEX, NULL, 0x0,
3202         "NT Token", HFILL }},
3203
3204     { &hf_mscldap_netlogon_flags,
3205       { "Flags", "mscldap.netlogon.flags",
3206         FT_UINT32, BASE_HEX, NULL, 0x0,
3207         "Netlogon flags describing the DC properties", HFILL }},
3208
3209     { &hf_mscldap_domain_guid,
3210       { "Domain GUID", "mscldap.domain.guid",
3211         FT_BYTES, BASE_HEX, NULL, 0x0,
3212         "Domain GUID", HFILL }},
3213
3214     { &hf_mscldap_forest,
3215       { "Forest", "mscldap.forest",
3216         FT_STRING, BASE_NONE, NULL, 0x0,
3217         "Forest", HFILL }},
3218
3219     { &hf_mscldap_domain,
3220       { "Domain", "mscldap.domain",
3221         FT_STRING, BASE_NONE, NULL, 0x0,
3222         "Domainname", HFILL }},
3223
3224     { &hf_mscldap_hostname,
3225       { "Hostname", "mscldap.hostname",
3226         FT_STRING, BASE_NONE, NULL, 0x0,
3227         "Hostname", HFILL }},
3228
3229     { &hf_mscldap_nb_domain,
3230       { "NetBios Domain", "mscldap.nb_domain",
3231         FT_STRING, BASE_NONE, NULL, 0x0,
3232         "NetBios Domainname", HFILL }},
3233
3234     { &hf_mscldap_nb_hostname,
3235       { "NetBios Hostname", "mscldap.nb_hostname",
3236         FT_STRING, BASE_NONE, NULL, 0x0,
3237         "NetBios Hostname", HFILL }},
3238
3239     { &hf_mscldap_username,
3240       { "User", "mscldap.username",
3241         FT_STRING, BASE_NONE, NULL, 0x0,
3242         "User name", HFILL }},
3243
3244     { &hf_mscldap_sitename,
3245       { "Site", "mscldap.sitename",
3246         FT_STRING, BASE_NONE, NULL, 0x0,
3247         "Site name", HFILL }},
3248
3249     { &hf_mscldap_clientsitename,
3250       { "Client Site", "mscldap.clientsitename",
3251         FT_STRING, BASE_NONE, NULL, 0x0,
3252         "Client Site name", HFILL }},
3253
3254     { &hf_mscldap_netlogon_flags_pdc,
3255       { "PDC", "mscldap.netlogon.flags.pdc", FT_BOOLEAN, 32,
3256         TFS(&tfs_ads_pdc), 0x00000001, "Is this DC a PDC or not?", HFILL }},
3257
3258     { &hf_mscldap_netlogon_flags_gc,
3259       { "GC", "mscldap.netlogon.flags.gc", FT_BOOLEAN, 32,
3260         TFS(&tfs_ads_gc), 0x00000004, "Does this dc service as a GLOBAL CATALOGUE?", HFILL }},
3261
3262     { &hf_mscldap_netlogon_flags_ldap,
3263       { "LDAP", "mscldap.netlogon.flags.ldap", FT_BOOLEAN, 32,
3264         TFS(&tfs_ads_ldap), 0x00000008, "Does this DC act as an LDAP server?", HFILL }},
3265
3266     { &hf_mscldap_netlogon_flags_ds,
3267       { "DS", "mscldap.netlogon.flags.ds", FT_BOOLEAN, 32,
3268         TFS(&tfs_ads_ds), 0x00000010, "Does this dc provide DS services?", HFILL }},
3269
3270     { &hf_mscldap_netlogon_flags_kdc,
3271       { "KDC", "mscldap.netlogon.flags.kdc", FT_BOOLEAN, 32,
3272         TFS(&tfs_ads_kdc), 0x00000020, "Does this dc act as a KDC?", HFILL }},
3273
3274     { &hf_mscldap_netlogon_flags_timeserv,
3275       { "Time Serv", "mscldap.netlogon.flags.timeserv", FT_BOOLEAN, 32,
3276         TFS(&tfs_ads_timeserv), 0x00000040, "Does this dc provide time services (ntp) ?", HFILL }},
3277
3278     { &hf_mscldap_netlogon_flags_closest,
3279       { "Closest", "mscldap.netlogon.flags.closest", FT_BOOLEAN, 32,
3280         TFS(&tfs_ads_closest), 0x00000080, "Is this the closest dc? (is this used at all?)", HFILL }},
3281
3282     { &hf_mscldap_netlogon_flags_writable,
3283       { "Writable", "mscldap.netlogon.flags.writable", FT_BOOLEAN, 32,
3284         TFS(&tfs_ads_writable), 0x00000100, "Is this dc writable? (i.e. can it update the AD?)", HFILL }},
3285
3286     { &hf_mscldap_netlogon_flags_good_timeserv,
3287       { "Good Time Serv", "mscldap.netlogon.flags.good_timeserv", FT_BOOLEAN, 32,
3288         TFS(&tfs_ads_good_timeserv), 0x00000200, "Is this a Good Time Server? (i.e. does it have a hardware clock)", HFILL }},
3289
3290     { &hf_mscldap_netlogon_flags_ndnc,
3291       { "NDNC", "mscldap.netlogon.flags.ndnc", FT_BOOLEAN, 32,
3292         TFS(&tfs_ads_ndnc), 0x00000400, "Is this an NDNC dc?", HFILL }},
3293
3294   };
3295
3296   static gint *ett[] = {
3297     &ett_ldap,
3298     &ett_ldap_msg,
3299     &ett_ldap_payload,
3300     &ett_ldap_sasl_blob,
3301     &ett_ldap_referrals,
3302     &ett_ldap_attribute,
3303     &ett_ldap_controls,
3304     &ett_ldap_control,
3305     &ett_mscldap_netlogon_flags
3306   };
3307   module_t *ldap_module;
3308
3309   proto_ldap = proto_register_protocol("Lightweight Directory Access Protocol",
3310                                        "LDAP", "ldap");
3311   proto_register_field_array(proto_ldap, hf, array_length(hf));
3312   proto_register_subtree_array(ett, array_length(ett));
3313
3314   ldap_module = prefs_register_protocol(proto_ldap, NULL);
3315   prefs_register_bool_preference(ldap_module, "desegment_ldap_messages",
3316     "Reassemble LDAP messages spanning multiple TCP segments",
3317     "Whether the LDAP dissector should reassemble messages spanning multiple TCP segments."
3318     " To use this option, you must also enable \"Allow subdissectors to reassemble TCP streams\" in the TCP protocol settings.",
3319     &ldap_desegment);
3320
3321   proto_cldap = proto_register_protocol(
3322           "Connectionless Lightweight Directory Access Protocol",
3323           "CLDAP", "cldap");
3324
3325   register_init_routine(ldap_reinit);
3326   ldap_tap=register_tap("ldap");
3327 }
3328
3329 void
3330 proto_reg_handoff_ldap(void)
3331 {
3332   dissector_handle_t ldap_handle, cldap_handle;
3333
3334   ldap_handle = create_dissector_handle(dissect_ldap, proto_ldap);
3335   dissector_add("tcp.port", TCP_PORT_LDAP, ldap_handle);
3336   dissector_add("tcp.port", TCP_PORT_GLOBALCAT_LDAP, ldap_handle);
3337
3338   cldap_handle = create_dissector_handle(dissect_mscldap, proto_cldap);
3339   dissector_add("udp.port", UDP_PORT_CLDAP, cldap_handle);
3340
3341   gssapi_handle = find_dissector("gssapi");
3342   gssapi_wrap_handle = find_dissector("gssapi_verf");
3343
3344 /*  http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dsml/dsml/ldap_controls_and_session_support.asp */
3345 register_ber_oid_name("1.2.840.113556.1.4.319","LDAP_PAGED_RESULT_OID_STRING"); 
3346 register_ber_oid_name("1.2.840.113556.1.4.417","LDAP_SERVER_SHOW_DELETED_OID"); 
3347 register_ber_oid_name("1.2.840.113556.1.4.473","LDAP_SERVER_SORT_OID"); 
3348 register_ber_oid_name("1.2.840.113556.1.4.521","LDAP_SERVER_CROSSDOM_MOVE_TARGET_OID"); 
3349 register_ber_oid_name("1.2.840.113556.1.4.528","LDAP_SERVER_NOTIFICATION_OID"); 
3350 register_ber_oid_name("1.2.840.113556.1.4.529","LDAP_SERVER_EXTENDED_DN_OID"); 
3351 register_ber_oid_name("1.2.840.113556.1.4.619","LDAP_SERVER_LAZY_COMMIT_OID"); 
3352 register_ber_oid_name("1.2.840.113556.1.4.801","LDAP_SERVER_SD_FLAGS_OID"); 
3353 register_ber_oid_name("1.2.840.113556.1.4.805","LDAP_SERVER_TREE_DELETE_OID"); 
3354 register_ber_oid_name("1.2.840.113556.1.4.841","LDAP_SERVER_DIRSYNC_OID"); 
3355 register_ber_oid_name("1.2.840.113556.1.4.970 ","None"); 
3356 register_ber_oid_name("1.2.840.113556.1.4.1338","LDAP_SERVER_VERIFY_NAME_OID"); 
3357 register_ber_oid_name("1.2.840.113556.1.4.1339","LDAP_SERVER_DOMAIN_SCOPE_OID"); 
3358 register_ber_oid_name("1.2.840.113556.1.4.1340","LDAP_SERVER_SEARCH_OPTIONS_OID"); 
3359 register_ber_oid_name("1.2.840.113556.1.4.1413","LDAP_SERVER_PERMISSIVE_MODIFY_OID"); 
3360 register_ber_oid_name("1.2.840.113556.1.4.1504","LDAP_SERVER_ASQ_OID"); 
3361 register_ber_oid_name("1.2.840.113556.1.4.1781","LDAP_SERVER_FAST_BIND_OID"); 
3362 register_ber_oid_name("1.3.6.1.4.1.1466.101.119.1","None"); 
3363 register_ber_oid_name("1.3.6.1.4.1.1466.20037","LDAP_START_TLS_OID"); 
3364 register_ber_oid_name("2.16.840.1.113730.3.4.9","LDAP_CONTROL_VLVREQUEST VLV");
3365 }