summaryrefslogtreecommitdiff
path: root/python/samba/tests/ldap_raw.py
blob: f4ea97d120e4b06080b7914e1fd55b53906ee98f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
# Integration tests for the ldap server, using raw socket IO
#
# Tests for handling of malformed or large packets.
#
# Copyright (C) Catalyst.Net Ltd 2020
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import socket
import ssl

import samba.tests
from samba.tests import TestCase


#
# LDAP Operations
#
DELETE = b'\x4a'
DELETE_RES = b'\x6b'

# Bind
BIND = b'\x60'
BIND_RES = b'\x61'
SIMPLE_AUTH = b'\x80'
SASL_AUTH = b'\xa3'

# Search
SEARCH = b'\x63'
SEARCH_RES = b'\x64'
EQUALS = b'\xa3'


#
# LDAP response codes.
#
SUCCESS = b'\x00'
OPERATIONS_ERROR = b'\x01'
INVALID_CREDENTIALS = b'\x31'
INVALID_DN_SYNTAX = b'\x22'

#
# ASN.1 Element types
#
BOOLEAN = b'\x01'
INTEGER = b'\x02'
OCTET_STRING = b'\x04'
NULL = b'\x05'
ENUMERATED = b'\x0a'
SEQUENCE = b'\x30'
SET = b'\x31'


#
# ASN.1 Helper functions.
#
def encode_element(ber_type, data):
    ''' Encode an ASN.1 BER element. '''
    if data is None:
        return ber_type + encode_length(0)
    return ber_type + encode_length(len(data)) + data


def encode_length(length):
    ''' Encode the length of an ASN.1 BER element.  '''

    if length > 0xFFFFFF:
        return b'\x84' + length.to_bytes(4, "big")
    if length > 0xFFFF:
        return b'\x83' + length.to_bytes(3, "big")
    if length > 0xFF:
        return b'\x82' + length.to_bytes(2, "big")
    if length > 0x7F:
        return b'\x81' + length.to_bytes(1, "big")
    return length.to_bytes(1, "big")


def encode_string(string):
    ''' Encode an octet string '''
    return encode_element(OCTET_STRING, string)


def encode_boolean(boolean):
    ''' Encode a boolean value '''
    if boolean:
        return encode_element(BOOLEAN, b'\xFF')
    return encode_element(BOOLEAN, b'\x00')


def encode_integer(integer):
    ''' Encode an integer value '''
    bit_len = integer.bit_length()
    byte_len = (bit_len // 8) + 1
    return encode_element(INTEGER, integer.to_bytes(byte_len, "big"))


def encode_enumerated(enum):
    ''' Encode an enumerated value '''
    return encode_element(ENUMERATED, enum.to_bytes(1, "big"))


def encode_sequence(sequence):
    ''' Encode a sequence '''
    return encode_element(SEQUENCE, sequence)


def decode_element(data):
    '''
    decode an ASN.1 element
    '''
    if data is None:
        return None

    if len(data) < 2:
        return None

    ber_type = data[0:1]
    enc = int.from_bytes(data[1:2], byteorder='big')
    if enc & 0x80:
        l_end = 2 + (enc & ~0x80)
        length = int.from_bytes(data[2:l_end], byteorder='big')
        element = data[l_end:l_end + length]
        rest = data[l_end + length:]
    else:
        length = enc
        element = data[2:2 + length]
        rest = data[2 + length:]

    return (ber_type, length, element, rest)


class RawLdapTest(TestCase):
    """
    A raw Ldap Test case.
    The ldap connections are made over https on port 636

    Uses the following environment variables:
        SERVER
        USERNAME
        PASSWORD
        DNSNAME
    """

    def setUp(self):
        super(RawLdapTest, self).setUp()

        self.host = samba.tests.env_get_var_value('SERVER')
        self.port = 636
        self.socket = None
        self.user = samba.tests.env_get_var_value('USERNAME')
        self.password = samba.tests.env_get_var_value('PASSWORD')
        self.dns_name = samba.tests.env_get_var_value('DNSNAME')
        self.connect()

    def tearDown(self):
        self.disconnect()
        super(RawLdapTest, self).tearDown()

    def disconnect(self):
        ''' Disconnect from and clean up the connection to the server '''
        if self.socket is None:
            return
        self.socket.close()
        self.socket = None

    def connect(self):
        ''' Establish an ldaps connection to the test server '''
        #
        # Disable host name and certificate verification
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE

        sock = None
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(10)
            sock.connect((self.host, self.port))
            self.socket = context.wrap_socket(sock, server_hostname=self.host)
        except socket.error:
            sock.close()
            if self.socket is not None:
                self.socket.close()
            raise

    def send(self, req):
        ''' Send the request to the server '''
        try:
            self.socket.sendall(req)
        except socket.error:
            self.disconnect()
            raise

    def recv(self, num_recv=0xffff, timeout=None):
        ''' receive an array of bytes from the server '''
        data = None
        try:
            if timeout is not None:
                self.socket.settimeout(timeout)
            data = self.socket.recv(num_recv, 0)
            self.socket.settimeout(10)
            if len(data) == 0:
                self.disconnect()
                return None
        except socket.timeout:
            # We ignore timeout's as the ldap server will drop the connection
            # on the errors we're testing. So returning None on a timeout is
            # the desired behaviour.
            self.socket.settimeout(10)
        except socket.error:
            self.disconnect()
            raise
        return data

    def bind(self):
        '''
            Perform a simple bind
        '''

        user = self.user.encode('UTF8')
        ou = self.dns_name.replace('.', ',dc=').encode('UTF8')
        dn = b'cn=' + user + b',cn=users,dc=' + ou

        password = self.password.encode('UTF8')

        # Lets build an simple bind request
        bind = encode_integer(3)                  # ldap version
        bind += encode_string(dn)
        bind += encode_element(SIMPLE_AUTH, password)

        bind_op = encode_element(BIND, bind)

        msg_no = encode_integer(1)
        packet = encode_sequence(msg_no + bind_op)

        self.send(packet)
        data = self.recv()
        self.assertIsNotNone(data)

        #
        # Decode and validate the response

        # Should be a sequence
        (ber_type, length, element, rest) = decode_element(data)
        self.assertEqual(SEQUENCE.hex(), ber_type.hex())
        self.assertTrue(length > 0)
        self.assertEqual(0, len(rest))

        # message id should be 1
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(INTEGER.hex(), ber_type.hex())
        msg_no = int.from_bytes(element, byteorder='big')
        self.assertEqual(1, msg_no)
        self.assertGreater(len(rest), 0)

        # Should have a Bind response element
        (ber_type, length, element, rest) = decode_element(rest)
        self.assertEqual(BIND_RES.hex(), ber_type.hex())
        self.assertEqual(0, len(rest))

        # Check the response code
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(ENUMERATED.hex(), ber_type.hex())
        self.assertEqual(SUCCESS.hex(), element.hex())
        self.assertGreater(len(rest), 0)

    def test_decode_element(self):
        ''' Tests for the decode_element method '''

        # Boolean true value
        data = b'\x01\x01\xff'
        (ber_type, length, element, rest) = decode_element(data)
        self.assertEqual(BOOLEAN.hex(), ber_type.hex())
        self.assertEqual(1, length)
        self.assertEqual(b'\xff'.hex(), element.hex())
        self.assertEqual(0, len(rest))

        # Boolean false value
        data = b'\x01\x01\x00'
        (ber_type, length, element, rest) = decode_element(data)
        self.assertEqual(BOOLEAN.hex(), ber_type.hex())
        self.assertEqual(1, length)
        self.assertEqual(b'\x00'.hex(), element.hex())
        self.assertEqual(0, len(rest))

        # Boolean true value with trailing data
        data = b'\x01\x01\xff\x05\x00'
        (ber_type, length, element, rest) = decode_element(data)
        self.assertEqual(BOOLEAN.hex(), ber_type.hex())
        self.assertEqual(1, length)
        self.assertEqual(b'\xff'.hex(), element.hex())
        self.assertEqual(b'\x05\x00'.hex(), rest.hex())

        # Octet string byte length encoding
        data = b'\x04\x02\xca\xfe\x05\x00'
        (ber_type, length, element, rest) = decode_element(data)
        self.assertEqual(OCTET_STRING.hex(), ber_type.hex())
        self.assertEqual(2, length)
        self.assertEqual(b'\xca\xfe'.hex(), element.hex())
        self.assertEqual(b'\x05\x00'.hex(), rest.hex())

        # Octet string 81 byte length encoding
        data = b'\x04\x81\x02\xca\xfe\x05\x00'
        (ber_type, length, element, rest) = decode_element(data)
        self.assertEqual(OCTET_STRING.hex(), ber_type.hex())
        self.assertEqual(2, length)
        self.assertEqual(b'\xca\xfe'.hex(), element.hex())
        self.assertEqual(b'\x05\x00'.hex(), rest.hex())

        # Octet string 82 byte length encoding
        data = b'\x04\x82\x00\x02\xca\xfe\x05\x00'
        (ber_type, length, element, rest) = decode_element(data)
        self.assertEqual(OCTET_STRING.hex(), ber_type.hex())
        self.assertEqual(2, length)
        self.assertEqual(b'\xca\xfe'.hex(), element.hex())
        self.assertEqual(b'\x05\x00'.hex(), rest.hex())

        # Octet string 85 byte length encoding
        # For Samba we limit the length encoding to 4 bytes, but it's useful
        # to be able to decode longer lengths in a test.
        data = b'\x04\x85\x00\x00\x00\x00\x02\xca\xfe\x05\x00'
        (ber_type, length, element, rest) = decode_element(data)
        self.assertEqual(OCTET_STRING.hex(), ber_type.hex())
        self.assertEqual(2, length)
        self.assertEqual(b'\xca\xfe'.hex(), element.hex())
        self.assertEqual(b'\x05\x00'.hex(), rest.hex())

    def test_search_equals_maximum_permitted_size(self):
        '''
        Check that an LDAP search request equal to the maximum size is accepted
        This test is done on a authenticated connection so that the maximum
        non search request is 16MiB.
        '''
        self.bind()

        # Lets build an ldap search packet to query the RootDSE
        header = encode_string(None)        # Base DN, ""
        header += encode_enumerated(0)      # Enumeration scope
        header += encode_enumerated(0)      # Enumeration dereference
        header += encode_integer(0)         # Integer size limit
        header += encode_integer(0)         # Integer time limit
        header += encode_boolean(False)     # Boolean attributes only

        #
        # build an equality search of the form x...x=y...y
        # With the length of x...x and y...y chosen to generate an
        # ldap request of 256000 bytes.
        x = encode_string(b'x' * 127974)
        y = encode_string(b'y' * 127979)
        equals = encode_element(EQUALS, x + y)
        trailer = encode_sequence(None)
        search = encode_element(SEARCH, header + equals + trailer)

        msg_no = encode_integer(2)
        packet = encode_sequence(msg_no + search)
        #
        # The length of the packet should be equal to the
        # Maximum length of a search query
        self.assertEqual(256000, len(packet))

        self.send(packet)
        data = self.recv()
        self.assertIsNotNone(data)

        #
        # Decode and validate the response

        # Should be a sequence
        (ber_type, length, element, rest) = decode_element(data)
        self.assertEqual(SEQUENCE.hex(), ber_type.hex())
        self.assertTrue(length > 0)
        self.assertEqual(0, len(rest))

        # message id should be 2
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(INTEGER.hex(), ber_type.hex())
        msg_no = int.from_bytes(element, byteorder='big')
        self.assertEqual(2, msg_no)
        self.assertGreater(len(rest), 0)

        # Should have a Search response element
        (ber_type, length, element, rest) = decode_element(rest)
        self.assertEqual(SEARCH_RES.hex(), ber_type.hex())
        self.assertEqual(0, len(rest))

        # Should have an empty matching DN
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(OCTET_STRING.hex(), ber_type.hex())
        self.assertEqual(0, len(element))
        self.assertGreater(len(rest), 0)

        # Then a sequence of attribute sequences
        (ber_type, length, element, rest) = decode_element(rest)
        self.assertEqual(SEQUENCE.hex(), ber_type.hex())
        self.assertEqual(0, len(rest))

        # Check the first attribute sequence, it should  be
        # "configurationNamingContext"
        # The remaining attribute sequences will be ignored but
        # check that they exist.
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(SEQUENCE.hex(), ber_type.hex())
        # Check that there are remaining attribute sequences.
        self.assertGreater(len(rest), 0)

        # Check the name of the first attribute
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(OCTET_STRING.hex(), ber_type.hex())
        self.assertGreater(len(rest), 0)
        self.assertEqual(b'configurationNamingContext', element)

        # And check that there is an attribute value set
        (ber_type, length, element, rest) = decode_element(rest)
        self.assertEqual(SET.hex(), ber_type.hex())
        self.assertGreater(len(element), 0)
        self.assertEqual(0, len(rest))

    def test_search_exceeds_maximum_permitted_size(self):
        '''
        Test that a search query longer than the maximum permitted
        size is rejected.
        This test is done on a authenticated connection so that the maximum
        non search request is 16MiB.
        '''

        self.bind()

        # Lets build an ldap search packet to query the RootDSE
        header = encode_string(None)        # Base DN, ""
        header += encode_enumerated(0)      # Enumeration scope
        header += encode_enumerated(0)      # Enumeration dereference
        header += encode_integer(0)         # Integer size limit
        header += encode_integer(0)         # Integer time limit
        header += encode_boolean(False)     # Boolean attributes only

        #
        # build an equality search of the form x...x=y...y
        # With the length of x...x and y...y chosen to generate an
        # ldap request of 256001 bytes.
        x = encode_string(b'x' * 127979)
        y = encode_string(b'y' * 127975)
        equals = encode_element(EQUALS, x + y)
        trailer = encode_sequence(None)
        search = encode_element(SEARCH, header + equals + trailer)

        msg_no = encode_integer(2)
        packet = encode_sequence(msg_no + search)
        #
        # The length of the sequence data should be one greater than the
        # Maximum length of a search query
        self.assertEqual(256001, len(packet))

        self.send(packet)
        data = self.recv()
        #
        # The connection should be closed by the server and we should not
        # see any data.
        self.assertIsNone(data)

    def test_simple_anonymous_bind(self):
        '''
            Test a simple anonymous bind
        '''

        # Lets build an anonymous simple bind request
        bind = encode_integer(3)                  # ldap version
        bind += encode_string(b'')                # Empty name
        bind += encode_element(SIMPLE_AUTH, b'')  # Empty password

        bind_op = encode_element(BIND, bind)

        msg_no = encode_integer(1)
        packet = encode_sequence(msg_no + bind_op)

        self.send(packet)
        data = self.recv()
        self.assertIsNotNone(data)

        #
        # Decode and validate the response

        # Should be a sequence
        (ber_type, length, element, rest) = decode_element(data)
        self.assertEqual(SEQUENCE.hex(), ber_type.hex())
        self.assertTrue(length > 0)
        self.assertEqual(0, len(rest))

        # message id should be 1
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(INTEGER.hex(), ber_type.hex())
        msg_no = int.from_bytes(element, byteorder='big')
        self.assertEqual(1, msg_no)
        self.assertGreater(len(rest), 0)

        # Should have a Bind response element
        (ber_type, length, element, rest) = decode_element(rest)
        self.assertEqual(BIND_RES.hex(), ber_type.hex())
        self.assertEqual(0, len(rest))

        # Check the response code
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(ENUMERATED.hex(), ber_type.hex())
        self.assertEqual(SUCCESS.hex(), element.hex())
        self.assertGreater(len(rest), 0)

    def test_simple_bind_at_limit(self):
        '''
            Test a simple bind, with a large invalid
            user name. As the resulting packet is equal
            to the maximum unauthenticated packet size we should see
            an INVALID_CREDENTIALS response
        '''

        # Lets build a simple bind request
        bind = encode_integer(3)                  # ldap version
        bind += encode_string(b' ' * 255977)      # large name
        bind += encode_element(SIMPLE_AUTH, b'')  # Empty password

        bind_op = encode_element(BIND, bind)

        msg_no = encode_integer(1)
        packet = encode_sequence(msg_no + bind_op)
        #
        # The length of the sequence data should be equal to the maximum
        # Unauthenticated packet length
        self.assertEqual(256000, len(packet))

        self.send(packet)
        data = self.recv()
        self.assertIsNotNone(data)

        #
        # Decode and validate the response

        # Should be a sequence
        (ber_type, length, element, rest) = decode_element(data)
        self.assertEqual(SEQUENCE.hex(), ber_type.hex())
        self.assertTrue(length > 0)
        self.assertEqual(0, len(rest))

        # message id should be 1
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(INTEGER.hex(), ber_type.hex())
        msg_no = int.from_bytes(element, byteorder='big')
        self.assertEqual(1, msg_no)
        self.assertGreater(len(rest), 0)

        # Should have a Bind response element
        (ber_type, length, element, rest) = decode_element(rest)
        self.assertEqual(BIND_RES.hex(), ber_type.hex())
        self.assertEqual(0, len(rest))

        # Check the response code
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(ENUMERATED.hex(), ber_type.hex())
        self.assertEqual(INVALID_CREDENTIALS.hex(), element.hex())
        self.assertGreater(len(rest), 0)

    def test_simple_bind_gt_limit(self):
        '''
            Test a simple bind, with a large invalid
            user name. As the resulting packet is one greater than
            the maximum unauthenticated packet size we should see
            the connection reset.
        '''

        # Lets build a simple bind request
        bind = encode_integer(3)                  # ldap version
        bind += encode_string(b' ' * 255978)      # large name
        bind += encode_element(SIMPLE_AUTH, b'')  # Empty password

        bind_op = encode_element(BIND, bind)

        msg_no = encode_integer(1)
        packet = encode_sequence(msg_no + bind_op)
        #
        # The length of the sequence data should be equal to the maximum
        # Unauthenticated packet length
        self.assertEqual(256001, len(packet))

        self.send(packet)
        data = self.recv()
        self.assertIsNone(data)

    def test_unauthenticated_delete_at_limit(self):
        '''
            Test a delete, with a large invalid DN
            As the resulting packet is equal to the maximum unauthenticated
            packet size we should see an INVALID_DN_SYNTAX response
        '''

        # Lets build a delete request, with a large invalid DN
        dn = b' ' * 255987
        del_op = encode_element(DELETE, dn)

        msg_no = encode_integer(1)
        packet = encode_sequence(msg_no + del_op)
        #
        # The length of the sequence data should be equal to the maximum
        # Unauthenticated packet length
        self.assertEqual(256000, len(packet))

        self.send(packet)
        data = self.recv()
        self.assertIsNotNone(data)

        #
        # Decode and validate the response

        # Should be a sequence
        (ber_type, length, element, rest) = decode_element(data)
        self.assertEqual(SEQUENCE.hex(), ber_type.hex())
        self.assertTrue(length > 0)
        self.assertEqual(0, len(rest))

        # message id should be 1
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(INTEGER.hex(), ber_type.hex())
        msg_no = int.from_bytes(element, byteorder='big')
        self.assertEqual(1, msg_no)
        self.assertGreater(len(rest), 0)

        # Should have a delete response element
        (ber_type, length, element, rest) = decode_element(rest)
        self.assertEqual(DELETE_RES.hex(), ber_type.hex())
        self.assertEqual(0, len(rest))

        # Check the response code
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(ENUMERATED.hex(), ber_type.hex())
        self.assertEqual(INVALID_DN_SYNTAX.hex(), element.hex())
        self.assertGreater(len(rest), 0)

    def test_unauthenticated_delete_gt_limit(self):
        '''
            Test a delete, with a large invalid DN
            As the resulting packet is greater than the maximum unauthenticated
            packet size we should see a connection reset
        '''

        # Lets build a delete request, with a large invalid DN
        dn = b' ' * 255988
        del_op = encode_element(DELETE, dn)

        msg_no = encode_integer(1)
        packet = encode_sequence(msg_no + del_op)
        #
        # The length of the sequence data should one greater than the maximum
        # unauthenticated packet length
        self.assertEqual(256001, len(packet))

        self.send(packet)
        data = self.recv()
        self.assertIsNone(data)

    def test_authenticated_delete_at_limit(self):
        '''
            Test a delete, with a large invalid DN
            As the resulting packet is equal to the maximum authenticated
            packet size we should see an INVALID_DN_SYNTAX response
        '''

        # Lets build a delete request, with a large invalid DN
        dn = b' ' * 16777203
        del_op = encode_element(DELETE, dn)

        self.bind()

        msg_no = encode_integer(2)
        packet = encode_sequence(msg_no + del_op)
        #
        # The length of the sequence data should be equal to the maximum
        # authenticated packet length currently 16MiB
        self.assertEqual(16 * 1024 * 1024, len(packet))

        self.send(packet)
        data = self.recv()
        self.assertIsNotNone(data)

        #
        # Decode and validate the response

        # Should be a sequence
        (ber_type, length, element, rest) = decode_element(data)
        self.assertEqual(SEQUENCE.hex(), ber_type.hex())
        self.assertTrue(length > 0)
        self.assertEqual(0, len(rest))

        # message id should be 2
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(INTEGER.hex(), ber_type.hex())
        msg_no = int.from_bytes(element, byteorder='big')
        self.assertEqual(2, msg_no)
        self.assertGreater(len(rest), 0)

        # Should have a delete response element
        (ber_type, length, element, rest) = decode_element(rest)
        self.assertEqual(DELETE_RES.hex(), ber_type.hex())
        self.assertEqual(0, len(rest))

        # Check the response code
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(ENUMERATED.hex(), ber_type.hex())
        self.assertEqual(INVALID_DN_SYNTAX.hex(), element.hex())
        self.assertGreater(len(rest), 0)

    def test_authenticated_delete_gt_limit(self):
        '''
            Test a delete, with a large invalid DN
            As the resulting packet is one greater than the maximum
            authenticated packet size we should see a connection reset
        '''

        # Lets build a delete request, with a large invalid DN
        dn = b' ' * 16777204
        del_op = encode_element(DELETE, dn)

        self.bind()

        msg_no = encode_integer(2)
        packet = encode_sequence(msg_no + del_op)
        #
        # The length of the sequence data should be one greater than the
        # maximum authenticated packet length currently 16MiB
        self.assertEqual(16 * 1024 * 1024 + 1, len(packet))

        self.send(packet)
        data = self.recv()
        self.assertIsNone(data)


class RawCldapTest(TestCase):
    """
    A raw cldap Test case.
    The ldap connections are made over UDP port 389

    Uses the following environment variables:
        SERVER
    """

    def setUp(self):
        super(RawCldapTest, self).setUp()

        self.host = samba.tests.env_get_var_value('SERVER')
        self.port = 389
        self.socket = None
        self.connect()

    def tearDown(self):
        self.disconnect()
        super(RawCldapTest, self).tearDown()

    def disconnect(self):
        ''' Disconnect from and clean up the connection to the server '''
        if self.socket is None:
            return
        self.socket.close()
        self.socket = None

    def connect(self):
        ''' Establish an UDP connection to the test server '''

        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.socket.settimeout(10)
            self.socket.connect((self.host, self.port))
        except socket.error:
            if self.socket is not None:
                self.socket.close()
            raise

    def send(self, req):
        ''' Send the request to the server '''
        try:
            self.socket.sendall(req)
        except socket.error:
            self.disconnect()
            raise

    def recv(self, num_recv=0xffff, timeout=None):
        ''' receive an array of bytes from the server '''
        data = None
        try:
            if timeout is not None:
                self.socket.settimeout(timeout)
            data = self.socket.recv(num_recv, 0)
            self.socket.settimeout(10)
            if len(data) == 0:
                self.disconnect()
                return None
        except socket.timeout:
            # We ignore timeout's as the ldap server will drop the connection
            # on the errors we're testing. So returning None on a timeout is
            # the desired behaviour.
            self.socket.settimeout(10)
        except socket.error:
            self.disconnect()
            raise
        return data

    def test_search_equals_maximum_permitted_size(self):
        '''
        Check that an CLDAP search request equal to the maximum size is
        accepted
        '''

        # Lets build an ldap search packet to query the RootDSE
        header = encode_string(None)        # Base DN, ""
        header += encode_enumerated(0)      # Enumeration scope
        header += encode_enumerated(0)      # Enumeration dereference
        header += encode_integer(0)         # Integer size limit
        header += encode_integer(0)         # Integer time limit
        header += encode_boolean(False)     # Boolean attributes only

        #
        # build an equality search of the form x...x=y...y
        # With the length of x...x and y...y chosen to generate an
        # cldap request of 4096 bytes.
        x = encode_string(b'x' * 2027)
        y = encode_string(b'y' * 2027)
        equals = encode_element(EQUALS, x + y)
        trailer = encode_sequence(None)
        search = encode_element(SEARCH, header + equals + trailer)

        msg_no = encode_integer(2)
        packet = encode_sequence(msg_no + search)
        #
        # The length of the packet should be equal to the
        # Maximum length of a cldap packet
        self.assertEqual(4096, len(packet))

        self.send(packet)
        data = self.recv()
        self.assertIsNotNone(data)

        #
        # Decode and validate the response

        # Should be a sequence
        (ber_type, length, element, rest) = decode_element(data)
        self.assertEqual(SEQUENCE.hex(), ber_type.hex())
        self.assertTrue(length > 0)
        self.assertGreater(len(rest), 0)
        # rest should contain a Search request done element, but it's
        # not validated in this test.

        # message id should be 2
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(INTEGER.hex(), ber_type.hex())
        msg_no = int.from_bytes(element, byteorder='big')
        self.assertEqual(2, msg_no)
        self.assertGreater(len(rest), 0)

        # Should have a Search response element
        (ber_type, length, element, rest) = decode_element(rest)
        self.assertEqual(SEARCH_RES.hex(), ber_type.hex())
        self.assertEqual(0, len(rest))

        # Should have an empty matching DN
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(OCTET_STRING.hex(), ber_type.hex())
        self.assertEqual(0, len(element))
        self.assertGreater(len(rest), 0)

        # Then a sequence of attribute sequences
        (ber_type, length, element, rest) = decode_element(rest)
        self.assertEqual(SEQUENCE.hex(), ber_type.hex())
        self.assertEqual(0, len(rest))

        # Check the first attribute sequence, it should  be
        # "configurationNamingContext"
        # The remaining attribute sequences will be ignored but
        # check that they exist.
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(SEQUENCE.hex(), ber_type.hex())
        # Check that there are remaining attribute sequences.
        self.assertGreater(len(rest), 0)

        # Check the name of the first attribute
        (ber_type, length, element, rest) = decode_element(element)
        self.assertEqual(OCTET_STRING.hex(), ber_type.hex())
        self.assertGreater(len(rest), 0)
        self.assertEqual(b'configurationNamingContext', element)

        # And check that there is an attribute value set
        (ber_type, length, element, rest) = decode_element(rest)
        self.assertEqual(SET.hex(), ber_type.hex())
        self.assertGreater(len(element), 0)
        self.assertEqual(0, len(rest))

    def test_search_exceeds_maximum_permitted_size(self):
        '''
        Test that a cldap request longer than the maximum permitted
        size is rejected.
        '''

        # Lets build an ldap search packet to query the RootDSE
        header = encode_string(None)        # Base DN, ""
        header += encode_enumerated(0)      # Enumeration scope
        header += encode_enumerated(0)      # Enumeration dereference
        header += encode_integer(0)         # Integer size limit
        header += encode_integer(0)         # Integer time limit
        header += encode_boolean(False)     # Boolean attributes only

        #
        # build an equality search of the form x...x=y...y
        # With the length of x...x and y...y chosen to generate an
        # cldap request of 4097 bytes.
        x = encode_string(b'x' * 2027)
        y = encode_string(b'y' * 2028)
        equals = encode_element(EQUALS, x + y)
        trailer = encode_sequence(None)
        search = encode_element(SEARCH, header + equals + trailer)

        msg_no = encode_integer(2)
        packet = encode_sequence(msg_no + search)
        #
        # The length of the sequence data should be one greater than the
        # Maximum length of a cldap packet
        self.assertEqual(4097, len(packet))

        self.send(packet)
        data = self.recv()
        #
        # The connection should be closed by the server and we should not
        # see any data.
        self.assertIsNone(data)