-
Notifications
You must be signed in to change notification settings - Fork 5
/
libLdap.py
577 lines (523 loc) · 16.5 KB
/
libLdap.py
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
#!/usr/bin/env python
##################################################################
# Copyright (c) 2012, Sergej Srepfler <[email protected]>
# February 2012 -
# Version 0.3.1, Last change on Nov 15, 2012
# This software is distributed under the terms of BSD license.
##################################################################
# All functions needed to build/decode LDAP messages
import struct
import socket
import sys
ERROR = -1
# Encoding structure: CLASS(bit 7,8)+PC(bit 5)+Tag (bit 0-4)
dict_class={'UNIVERSAL':0x00,
'APPLICATION':0x40,
'CONTEXT_SPECIFIC':0x80,
'PRIVATE':0xC0}
dict_pc={'PRIMITIVE':0,
'CONSTRUCTED':0x20}
dict_tag={'EOC':0,
'BOOLEAN':1,
'INTEGER':2,
'BIT_STRING':3,
'OCTET_STRING':4,
'NULL':5,
'OBJECT_IDENTIFIER':6,
'OBJECT_DESCRIPTOR':7,
'EXTERNAL':8,
'FLOAT':9,
'ENUMERATED':10,
'EMBEDDED':11,
'UTF8':12,
'RELATIVE_OID':13,
'SEQUENCE':16,
'SET':17,
'NUMERIC_STRING':18,
'PRINTABLE_STRING':19,
'T61STRING':20,
'VIDEOTEXT_STRING':21,
'IA5STRING':22,
'UTC_TIME':23,
'GENERALIZED_TIME':24,
'GRAPHIC_STRING':25,
'VISIBLE_STRING':26,
'GENERAL_STRING':27,
'UNIVERSAL_STRING':28,
'CHARACTER_STRING':29,
'BMP_STRING':30,
'LONG_FORM':31}
dict_RES={'success':0,
'operationsError':1,
'protocolError':2,
'timeLimitExceeded':3,
'sizeLimitExceeded':4,
'compareFalse':5,
'compareTrue':6,
'authMethodNotSupported':7,
'strongerAuthRequired':8,
'referral':10,
'adminLimitExceeded':11,
'unavailableCriticalExtension':12,
'confidentialityRequired':13,
'saslBindInProgress':14,
'noSuchAttribute':16,
'undefinedAttributeType':17,
'inappropriateMatching':18,
'constraintViolation':19,
'attributeOrValueExists':20,
'invalidAttributeSyntax':21,
'noSuchObject':32,
'aliasProblem':33,
'invalidDNSyntax':34,
'aliasDereferencingProblem':36,
'inappropriateAuthentication':48,
'invalidCredentials':49,
'insufficientAccessRights':50,
'busy':51,
'unavailable':52,
'unavailable':52,
'unwillingToPerform':53,
'loopDetect':54,
'namingViolation':64,
'objectClassViolation':65,
'notAllowedOnNonLeaf':66,
'notAllowedOnRDN':67,
'entryAlreadyExists':68,
'objectClassModsProhibited':69,
'affectsMultipleDSAs':71,
'other':80 }
dict_APP= {'bindRequest': 0,
'bindResponse':1,
'unbindRequest':2,
'searchRequest':3,
'searchResultEntry':4,
'searchResultDone':5,
'modifyRequest':6,
'modifyResponse':7,
'addRequest':8,
'addResponse':9,
'delRequest':10,
'delResponse':11,
'modifyDNRequest':12,
'modifyDNResponse':13,
'compareRequest':15,
'compareResponse':16,
'abandonRequest':17,
'extendedRequest':18,
'extendedResponse':19,
'intermediateResponse':20 }
class bindReq:
def __init__(self):
self.messageId=0
self.code=0
self.version=3
self.name=""
self.authentication=""
class LDAPResult:
def __init__(self):
self.messageId=0
self.code=0
self.result=0
self.matchedDN=""
self.errorMSG=""
class searchReq:
def __init__(self):
self.messageId=0
self.code=0
self.objectName=0
self.scope=3
self.derefAliases=0
self.sizeLimit=1
self.timeLimit=0
self.typesOnly=False
self.filter=[]
class searchRes:
def __init__(self):
self.messageId=0
self.code=0
self.objectName=""
self.attributes=[]
class modifyReq:
def __init__(self):
self.messageId=0
self.code=0
self.objectName=""
self.operation=[]
self.modification=[]
self.controls=[]
class addReq:
def __init__(self):
self.messageId=0
self.code=0
self.objectName=""
self.attributes=""
class delReq:
def __init__(self):
self.messageId=0
self.code=0
self.objectName=""
#-----------------------------------------------------------------------------
# From RFC:
#- Only the definite form of length encoding is used.
#- OCTET STRING values are encoded in the primitive form only.
#- If the value of a BOOLEAN type is true, the encoding of the value octet is
# set to hex "FF".
#- If a value of a type is its default value, it is absent. Only some BOOLEAN
# and INTEGER types have default values
#- These restrictions do not apply to ASN.1 types encapsulated inside of
# OCTET STRING values, such as attribute values, unless otherwise stated.
#-----------------------------------------------------------------------------
#Encoding section
#-----------------------------------------------------------------------------
# Pack according to ASN.1 (Abstract Syntax Notation One)
# Basic Encoding Rules to get identifier from Class(cls), Variable-Type(pc) and Data-Type (tag)
# see dict_class, dict_pc, dict_tag for values
def BERencode(cls,pc,tag):
enc=cls+pc+tag
return "%02X"%int(enc)
# Encode <value> as int with <op> identifier
# Reduce len if possible
def encodeInt(op,value):
ilen=4
r=struct.pack("!I",int(value)).encode("hex")
while r[:2]=='00':
r=r[2:]
ilen-=1
if ilen==1:
break
ret=op+'%02X'%ilen+r
return ret
# Encode <value> as string with <op> identifier
def encodeStr(op,value):
ret=op
if len(value)<128:
ret=ret+"%02X"%len(value)
else:
ret=ret+"82"+"%04X"%len(value)
ret=ret+value.encode("hex")
return ret
# Encode Value
def encodeValue(op,value):
cls,pc,tag=BERdecode(op.decode("hex"))
if tag in [1,2,10]:
# Encode integer
return encodeInt(op,value)
else:
return encodeStr(op,value)
# Encode key=value pair (everything is as string from LDIF)
def encodeKeyValue(key,value):
k=encodeStr('04',key).decode('hex')
if isinstance(value,list):
v=''
for vv in value:
v=v+encodeStr('04',vv).decode('hex')
else:
v=encodeStr('04',value).decode('hex')
ret=encodeStr('30',k+encodeStr('31',v).decode('hex'))
return ret
#-----------------------------------------------------------------------------
#Decoding section
#-----------------------------------------------------------------------------
# Decode according to ASN.1
def BERdecode(byte):
cls=ord(byte)>>6
pc=(ord(byte)>>5)&1
tag=ord(byte)&0x1F
return cls<<6,pc<<5,tag
# Decode Integer value
def decodeToInt(msg):
while len(msg)<8:
msg="00"+msg
ret=struct.unpack("!I",msg.decode("hex"))[0]
return ret
# Decode msg header of LDAP message till msg specific stuff
def decodeHDR(msg):
# Remove main envelope #30
op,msg,x=chop_BER(msg)
# get msgId
op,msgId,msg=chop_BER(msg)
#get appId
appId,msg,x=chop_BER(msg)
return msgId,appId,msg,x
# For tuple (t) decode value (default decoding method is as string)
def decodeValue(t):
if isinstance(t,tuple):
(op,value)=t
else:
return ''
cls,pc,tag=BERdecode(op.decode("hex"))
if tag in [1,2,10]:
# Decode Integer
return decodeToInt(value)
else:
return value.decode("hex")
# Decode application-specific attributes (hex message-undecoded) into tuples
def decodeParams(msg):
ret=[]
while msg!='':
#print "I",msg
op,value,msg=chop_BER(msg)
cls,pc,tag=BERdecode(op.decode("hex"))
#print "D",op,value,msg
if pc==0: #PRIMITIVE
ret.append((op,value))
else:
ret.append(decodeParams(value))
#print "R",ret
return ret
# Decode key=[multiple values] from list
def decodeList(list):
vRet=''
#print "DL",list
if len(list)==0:
return ERROR
key=decodeValue(list[0])
for v in list[1]:
if vRet=='':
vRet=decodeValue(v)
else:
vRet+=','+decodeValue(v)
return key+'='+str(vRet)
# Decode to proper object (match option to attribute)
def decodeFinal(msgId,appId,rest,unknown):
cls,pc,tag=BERdecode(appId.decode("hex"))
if tag==0: # bindReq
return decode_bindReq(msgId,appId,rest)
if tag==1: # bindRes
return decode_bindRes(msgId,appId,rest)
if tag==2: # unbindReq
return decode_unbindReq(msgId,appId,rest)
if tag==3: # searchReq
return decode_searchReq(msgId,appId,rest)
if tag==4: # searchResEntry
return decode_searchResEntry(msgId,appId,rest)
if tag in [5,7,9,11]: # generic LDAP response
return decode_LDAPResult(msgId,appId,rest)
if tag==6: # modifyReq
return decode_modifyReq(msgId,appId,rest,unknown)
if tag==8: # addReq
return decode_addReq(msgId,appId,rest,unknown)
if tag==10: # deleteReq
return decode_deleteReq(msgId,appId,rest,unknown)
dbg="Don't know how to process AppId",tag
bailOut(dbg)
def decode_bindReq(msgId,appId,rest):
L=bindReq()
L.messageId=msgId
L.code=appId
#split options
list=decodeParams(rest)
# And place them into matching variables
L.version=decodeValue(list.pop(0))
L.name=decodeValue(list.pop(0))
L.authentication=decodeValue(list.pop(0))
return L
def decode_bindRes(msgId,appId,rest):
L=LDAPResult()
L.messageId=msgId
L.code=appId
#split options
list=decodeParams(rest)
# And place them into matching variables
L.result=decodeValue(list.pop(0))
L.matchedDN=decodeValue(list.pop(0))
L.errorMSG=decodeValue(list.pop(0))
return L
def decode_unbindReq(msgId,appId,rest):
L=LDAPResult()
L.messageId=msgId
L.code=appId
return L
def decode_searchReq(msgId,appId,rest):
L=searchReq()
L.messageId=msgId
L.code=appId
#print "R",rest
# get operation parameters
op,value,msg=chop_BER(rest)
L.objectName=decodeValue((op,value))
op,value,msg=chop_BER(msg)
L.scope=decodeValue((op,value))
op,value,msg=chop_BER(msg)
L.derefAliases=decodeValue((op,value))
op,value,msg=chop_BER(msg)
L.sizeLimit=decodeValue((op,value))
op,value,msg=chop_BER(msg)
L.timeLimit=decodeValue((op,value))
op,value,msg=chop_BER(msg)
L.typesOnly=decodeValue((op,value))
# Filter is something I never used, so - not implemented/tested
list=decodeParams(msg)
#print "FL",len(list),list
if isinstance(list[0],tuple):
L.filter.append(decodeList(list))
else:
for l in list:
r=decodeList(l)
if r!=ERROR:
L.filter.append(r)
return L
def decode_searchResEntry(msgId,appId,rest):
L=searchRes()
L.messageId=msgId
L.code=appId
#get objectName
op,value,msg=chop_BER(rest)
L.objectName=decodeValue((op,value))
#print "I",msg
# get operation parameters
op,msg,x=chop_BER(msg)
#print "M",msg
#print "X",x
# Finally split options
list=decodeParams(msg)
#print "L",list
# And place them into matching variables
for l in list:
L.attributes.append(decodeList(l))
return L
def decode_LDAPResult(msgId,appId,rest):
L=LDAPResult()
L.messageId=msgId
L.code=appId
#split options
list=decodeParams(rest)
# And place them into matching variables
L.result=decodeValue(list.pop(0))
L.matchedDN=decodeValue(list.pop(0))
L.errorMSG=decodeValue(list.pop(0))
return L
def decode_modifyReq(msgId,appId,rest,unknown):
L=modifyReq()
L.messageId=msgId
L.code=appId
#get objectName
op,op,msg=chop_BER(rest)
L.objectName=op.decode("hex")
# get operation parameters
op,msg,x=chop_BER(msg)
# Finally split options
list=decodeParams(msg)
#print "L",list
# And place them into matching variables
for l in list:
op=decodeValue(l.pop(0))
L.operation.append(op)
L.modification.append(decodeList(l.pop(0)))
# I have no idea if this controls works as it should
if len(unknown)>0:
list=decodeParams(unknown)
#print "CL",list
for l in list[0]:
L.controls.append(decodeValue(l.pop(0)))
return L
def decode_addReq(msgId,appId,rest,unknown):
L=addReq()
L.messageId=msgId
L.code=appId
#get objectName
op,op,msg=chop_BER(rest)
L.objectName=op.decode("hex")
# get operation parameters
op,msg,x=chop_BER(msg)
# Finally split options
list=decodeParams(msg)
print "L",list
# And place them into matching variables
return L
def decode_deleteReq(msgId,appId,rest,unknown):
L=searchReq()
L.messageId=msgId
L.code=appId
#get objectName
op,op,msg=chop_BER(rest)
L.objectName=op.decode("hex")
# get operation parameters
op,msg,x=chop_BER(msg)
# Finally split options
list=decodeParams(msg)
print "L",list
return L
#-----------------------------------------------------------------------------
#Misc section
#-----------------------------------------------------------------------------
# Calculate object len (currently supports up to 64K)
def calc_len(len):
if len<=127:
#short form
ret="%02X"%int(len)
else:
#long form limited to 2 bytes (64K)
if len<256:
ret="0x81"+"%02X"%int(len)
else:
ret="0x82"+"%04X"%int(len)
return ret
# Quit program with error
def bailOut(msg):
print msg
sys.exit(1)
# Split message into parts (remove field from remaining body)
def chop_msg(msg,size):
return (msg[0:size],msg[size:])
# Chop len from message
def chop_len(msg):
(mlen,msg)=chop_msg(msg,2)
if mlen>"80":
# Multibyte
nlen=ord(mlen.decode("hex"))&0x7f
(mlen,msg)=chop_msg(msg,2*nlen)
return (decodeToInt(mlen),msg)
# get BER encoded option from message
def chop_BER(msg):
(op,msg)=chop_msg(msg,2)
(oplen,msg)=chop_len(msg)
(val,msg)=chop_msg(msg,2*oplen)
return op,val,msg
# Connect to host:port (TCP)
def Connect(host,port):
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
return sock
# From dict_* (dictionary) find index for value
def dictCmd2Name(dictionary,value):
keys=dictionary.keys()
values=dictionary.values()
index=[i for i,x in enumerate(values) if x == value]
return keys[index[0]]
#-----------------------------------------------------------------------------
#Create section
#-----------------------------------------------------------------------------
# Create generic Response message
def create_LDAPResult(msgId,code,result,matchedDN,errorMSG):
# Adding from end to the beginning
# LDAPResult ::= SEQUENCE {
# resultCode ENUMERATED,
# matchedDN LDAPDN,
# diagnosticMessage LDAPString,
# referral [3] Referral OPTIONAL }
# 04="%02X"%dict_tag['OCTET_STRING']
# 0A="%02X"%dict_tag['ENUMERATED']
ret=''
ret=encodeValue('04',errorMSG)+ret
ret=encodeValue('04',matchedDN)+ret
ret=encodeValue('0A',result)+ret
ret=encodeStr(code,ret.decode("hex"))
ret=encodeStr('02',msgId.decode("hex"))+ret
ret=encodeStr('30',ret.decode("hex"))
return ret
######################################################
# History
# 0.2.9 - Oct 11, 2012 - initial version
# 0.3.0 - Oct 26, 2012 - finally got it working
# - Oct 29, 2012 - msgId encoding fixed, reuseaddr fixed
# - encodeTo<Type> renamed to encode<Type> (more logical)
# - multiple values for key now supported
# - int len now not fixed
# 0.3.1 - Nov 05, 2012 - comments added, code cleanup
# - logging removed because it conflicts with threaded
# LDAP simulator
# - add/delete/modify support
# Nov 17, 2012 - decode rewrite