/
ldapServer.cs
740 lines (638 loc) · 21.5 KB
/
ldapServer.cs
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
/*
* BlackArrow - https://www.tarlogic.com/blog/linked-servers-adsi-passwords/
*
* heavily ripped from https://github.com/vforteli/Flexinets.Ldap.Server
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Linq;
namespace ldapAssembly
{
public static class LdapSrv
{
public static string listen(int port)
{
string res = "";
try
{
TcpListener listener = new TcpListener(IPAddress.Loopback, port);
listener.Start();
TcpClient client = listener.AcceptTcpClient();
NetworkStream stream = client.GetStream();
LdapPacket requestPacket;
String username = "<unknown>";
String password = "<unknown>";
LdapPacket.TryParsePacket(stream, out requestPacket);
if (requestPacket.ChildAttributes.Any(o => o.LdapOperation == LdapOperation.BindRequest))
{
var bindrequest = requestPacket.ChildAttributes.SingleOrDefault(o => o.LdapOperation == LdapOperation.BindRequest);
username = bindrequest.ChildAttributes[1].GetValue<String>();
password = bindrequest.ChildAttributes[2].GetValue<String>();
}
client.Close();
listener.Stop();
res = String.Format("{0}:{1}", username, password);
}
catch(Exception e)
{
res = e.ToString();
}
return res;
}
}
public enum TagClass
{
Universal = 0,
Application = 1,
Context = 2,
Private = 3
}
public enum UniversalDataType
{
EndOfContent = 0,
Boolean = 1,
Integer = 2,
BitString = 3,
OctetString = 4,
Null = 5,
ObjectIdentifier = 6,
ObjectDescriptor = 7,
External = 8,
Real = 9,
Enumerated = 10,
EmbeddedPDV = 11,
UTF8String = 12,
Relative = 13,
Reserved = 14,
Reserved2 = 15,
Sequence = 16,
Set = 17,
NumericString = 18,
PrintableString = 19,
T61String = 20,
VideotexString = 21,
IA5String = 22,
UTCTime = 23,
GeneralizedTime = 24,
GraphicString = 25,
VisibleString = 26,
GeneralString = 27,
UniversalString = 28,
CharacterString = 29,
BMPString = 30
}
public enum LdapOperation
{
BindRequest = 0,
BindResponse = 1,
UnbindRequest = 2,
SearchRequest = 3,
SearchResultEntry = 4,
SearchResultDone = 5,
SearchResultReference = 19,
ModifyRequest = 6,
ModifyResponse = 7,
AddRequest = 8,
AddResponse = 9,
DelRequest = 10,
DelResponse = 11,
ModifyDNRequest = 12,
ModifyDNResponse = 13,
CompareRequest = 14,
CompareResponse = 15,
AbandonRequest = 16,
ExtendedRequest = 23,
ExtendedResponse = 24,
IntermediateResponse = 25
}
public static class Utils
{
public static Byte[] StringToByteArray(String hex, Boolean trimWhitespace = true)
{
if (trimWhitespace)
{
hex = hex.Replace(" ", "");
}
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
public static String ByteArrayToString(Byte[] bytes)
{
var hex = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
hex.Append(String.Format("{0:x2}", b));
}
return hex.ToString();
}
/// <summary>
/// Used for debugging and testing...
/// </summary>
/// <param name="bits"></param>
/// <returns></returns>
public static String BitsToString(BitArray bits)
{
int i = 1;
var derp = "";
foreach (var bit in bits)
{
derp += Convert.ToInt32(bit);
if (i % 8 == 0)
{
derp += " ";
}
i++;
}
return derp.Trim();
}
/// <summary>
/// Convert integer length to a byte array with BER encoding
/// https://en.wikipedia.org/wiki/X.690#BER_encoding
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public static Byte[] IntToBerLength(Int32 length)
{
// Short notation
if (length <= 127)
{
return new byte[] { (byte)length };
}
// Long notation
else
{
var intbytes = BitConverter.GetBytes(length);
byte intbyteslength = (byte)intbytes.Length;
// Get the actual number of bytes needed
while (intbyteslength >= 0)
{
intbyteslength--;
if (intbytes[intbyteslength - 1] != 0)
{
break;
}
}
var lengthByte = intbyteslength + 128;
var berBytes = new byte[1 + intbyteslength];
berBytes[0] = (byte)lengthByte;
Buffer.BlockCopy(intbytes, 0, berBytes, 1, intbyteslength);
return berBytes;
}
}
/// <summary>
/// Convert BER encoded length at offset to an integer
/// </summary>
/// <param name="bytes">Byte array</param>
/// <param name="offset">Offset where the BER encoded length is located</param>
/// <param name="berByteCount">Number of bytes used to represent BER encoded length</param>
/// <returns></returns>
public static Int32 BerLengthToInt(Byte[] bytes, Int32 offset, out Int32 berByteCount)
{
berByteCount = 1; // The minimum length of a ber encoded length is 1 byte
int attributeLength = 0;
if (bytes[offset] >> 7 == 1) // Long notation
{
var lengthoflengthbytes = bytes[offset] & 127;
var lengthBytes = new Byte[4];
Buffer.BlockCopy(bytes, offset + 1, lengthBytes, 0, lengthoflengthbytes);
attributeLength = BitConverter.ToInt32(lengthBytes.Reverse().ToArray(), 0);
berByteCount += lengthoflengthbytes;
}
else // Short notation
{
attributeLength = bytes[offset] & 127;
}
return attributeLength;
}
/// <summary>
/// Get a BER length from a stream
/// </summary>
/// <param name="stream">Stream at position where BER length should be found</param>
/// <param name="berByteCount">Number of bytes used to represent BER encoded length</param>
/// <returns></returns>
public static Int32 BerLengthToInt(Stream stream, out Int32 berByteCount)
{
berByteCount = 1; // The minimum length of a ber encoded length is 1 byte
int attributeLength = 0;
var berByte = new Byte[1];
stream.Read(berByte, 0, 1);
if (berByte[0] >> 7 == 1) // Long notation, first byte tells us how many bytes are used for the length
{
var lengthoflengthbytes = berByte[0] & 127;
var lengthBytes = new Byte[lengthoflengthbytes];
stream.Read(lengthBytes, 0, lengthoflengthbytes);
attributeLength = BitConverter.ToInt32(lengthBytes.Reverse().ToArray(), 0);
berByteCount += lengthoflengthbytes;
}
else // Short notation, length contained in the first byte
{
attributeLength = berByte[0] & 127;
}
return attributeLength;
}
public static String Repeat(String stuff, Int32 n)
{
return String.Concat(Enumerable.Repeat(stuff, n));
}
}
public class Tag
{
/// <summary>
/// Tag in byte form
/// </summary>
public Byte TagByte { get; internal set; }
public Boolean IsConstructed
{
get
{
return new BitArray(new byte[] { TagByte }).Get(5);
}
}
public TagClass Class
{
get
{
return (TagClass)(TagByte >> 6);
}
}
public UniversalDataType DataType
{
get
{
return (UniversalDataType)(TagByte & 31);
}
}
public LdapOperation LdapOperation
{
get
{
return (LdapOperation)(TagByte & 31);
}
}
public Byte ContextType
{
get
{
return (byte)(TagByte & 31);
}
}
/// <summary>
/// Create an application tag
/// </summary>
/// <param name="operation"></param>
/// <param name="isSequence"></param>
public Tag(LdapOperation operation, Boolean isSequence)
{
TagByte = (byte)((byte)operation + (Convert.ToByte(isSequence) << 5) + ((byte)TagClass.Application << 6));
}
/// <summary>
/// Create a universal tag
/// </summary>
/// <param name="isSequence"></param>
/// <param name="operation"></param>
public Tag(UniversalDataType dataType, Boolean isSequence)
{
TagByte = (byte)((byte)dataType + (Convert.ToByte(isSequence) << 5) + ((byte)TagClass.Universal << 6));
}
/// <summary>
/// Create a context tag
/// </summary>
/// <param name="isSequence"></param>
/// <param name="operation"></param>
public Tag(Byte context, Boolean isSequence)
{
TagByte = (byte)((byte)context + (Convert.ToByte(isSequence) << 5) + ((byte)TagClass.Context << 6));
}
/// <summary>
/// Parses a raw tag byte
/// </summary>
/// <param name="tagByte"></param>
/// <returns></returns>
public static Tag Parse(Byte tagByte)
{
return new Tag(tagByte);
}
private Tag(Byte tagByte)
{
TagByte = tagByte;
}
}
public class LdapAttribute
{
private Tag _tag;
protected Byte[] Value = new Byte[0];
public List<LdapAttribute> ChildAttributes = new List<LdapAttribute>();
public TagClass Class
{
get
{
return _tag.Class;
}
}
public Boolean IsConstructed
{
get { return _tag.IsConstructed; }
}
public LdapOperation? LdapOperation
{
get
{
if (_tag.Class == TagClass.Application)
{
return _tag.LdapOperation;
}
return null;
}
}
public UniversalDataType? DataType
{
get
{
if (_tag.Class == TagClass.Universal)
{
return _tag.DataType;
}
return null;
}
}
public Byte? ContextType
{
get
{
if (_tag.Class == TagClass.Context)
{
return _tag.ContextType;
}
return null;
}
}
/// <summary>
/// Create an application attribute
/// </summary>
/// <param name="operation"></param>
/// <param name="isConstructed"></param>
public LdapAttribute(LdapOperation operation, Boolean isConstructed)
{
_tag = new Tag(operation, isConstructed);
}
/// <summary>
/// Create an application attribute
/// </summary>
/// <param name="operation"></param>
/// <param name="isConstructed"></param>
/// <param name="value"></param>
public LdapAttribute(LdapOperation operation, Boolean isConstructed, Object value)
{
_tag = new Tag(operation, isConstructed);
Value = GetBytes(value);
}
/// <summary>
/// Create a universal attribute
/// </summary>
/// <param name="dataType"></param>
/// <param name="isConstructed"></param>
public LdapAttribute(UniversalDataType dataType, Boolean isConstructed)
{
_tag = new Tag(dataType, isConstructed);
}
/// <summary>
/// Create a universal attribute
/// </summary>
/// <param name="dataType"></param>
/// <param name="isConstructed"></param>
/// <param name="value"></param>
public LdapAttribute(UniversalDataType dataType, Boolean isConstructed, Object value)
{
_tag = new Tag(dataType, isConstructed);
Value = GetBytes(value);
}
/// <summary>
/// Create a context attribute
/// </summary>
/// <param name="contextType"></param>
/// <param name="isConstructed"></param>
public LdapAttribute(Byte contextType, Boolean isConstructed)
{
_tag = new Tag(contextType, isConstructed);
}
/// <summary>
/// Create a context attribute
/// </summary>
/// <param name="contextType"></param>
/// <param name="isConstructed"></param>
/// <param name="value"></param>
public LdapAttribute(Byte contextType, Boolean isConstructed, Object value)
{
_tag = new Tag(contextType, isConstructed);
Value = GetBytes(value);
}
/// <summary>
/// Create an attribute with tag
/// </summary>
/// <param name="tag"></param>
protected LdapAttribute(Tag tag)
{
_tag = tag;
}
/// <summary>
/// Get the byte representation of the attribute and its children
/// </summary>
/// <returns></returns>
public Byte[] GetBytes()
{
var list = new List<Byte>();
if (_tag.IsConstructed)
{
ChildAttributes.ForEach(o => list.AddRange(o.GetBytes()));
}
else
{
list.AddRange(Value);
}
var lengthBytes = Utils.IntToBerLength(list.Count);
var attributeBytes = new byte[1 + lengthBytes.Length + list.Count];
attributeBytes[0] = _tag.TagByte;
Buffer.BlockCopy(lengthBytes, 0, attributeBytes, 1, lengthBytes.Length);
Buffer.BlockCopy(list.ToArray(), 0, attributeBytes, 1 + lengthBytes.Length, list.Count);
return attributeBytes;
}
/// <summary>
/// Get a typed value
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T GetValue<T>()
{
return (T)Convert.ChangeType(GetValue(), typeof(T));
}
/// <summary>
/// Get an object value
/// </summary>
/// <returns></returns>
public object GetValue()
{
if (_tag.Class == TagClass.Universal)
{
if (_tag.DataType == UniversalDataType.Boolean)
{
return BitConverter.ToBoolean(Value, 0);
}
else if (_tag.DataType == UniversalDataType.Integer)
{
var intbytes = new Byte[4];
Buffer.BlockCopy(Value, 0, intbytes, 4 - Value.Length, Value.Length);
return BitConverter.ToInt32(intbytes.Reverse().ToArray(), 0);
}
else
{
return Encoding.UTF8.GetString(Value, 0, Value.Length);
}
}
else
{
// todo add rest...
return Encoding.UTF8.GetString(Value, 0, Value.Length);
}
}
/// <summary>
/// Convert the value to its byte form
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private Byte[] GetBytes(Object value)
{
if (value.GetType() == typeof(String))
{
return Encoding.UTF8.GetBytes((String)value);
}
else if (value.GetType() == typeof(Int32))
{
return BitConverter.GetBytes((Int32)value).Reverse().ToArray();
}
else if (value.GetType() == typeof(Boolean))
{
return BitConverter.GetBytes((Boolean)value);
}
else if (value.GetType() == typeof(Byte))
{
return new Byte[] { (Byte)value };
}
else if (value.GetType() == typeof(Byte[]))
{
return (Byte[])value;
}
throw new InvalidOperationException(String.Format("Nothing found for {0}", value.GetType()));
}
}
public class LdapPacket : LdapAttribute
{
public Int32 MessageId
{
get
{
return ChildAttributes[0].GetValue<Int32>();
}
}
/// <summary>
/// Create a new Ldap packet with message id
/// </summary>
/// <param name="messageId"></param>
public LdapPacket(Int32 messageId) : base(UniversalDataType.Sequence, true)
{
ChildAttributes.Add(new LdapAttribute(UniversalDataType.Integer, false, messageId));
}
/// <summary>
/// Create a packet with tag
/// </summary>
/// <param name="tag"></param>
private LdapPacket(Tag tag) : base(tag)
{
}
/// <summary>
/// Parse an ldap packet from a byte array.
/// Must be the complete packet
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static LdapPacket ParsePacket(Byte[] bytes)
{
var tag = Tag.Parse(bytes[0]);
var lengthBytesCount = 0;
var contentLength = Utils.BerLengthToInt(bytes, 1, out lengthBytesCount);
return (LdapPacket)ParseAttributes(bytes, 0, contentLength + lengthBytesCount + 1)[0];
}
/// <summary>
/// Try parsing an ldap packet from a stream
/// </summary>
/// <param name="stream"></param>
/// <param name="packet"></param>
/// <returns>True if succesful. False if parsing fails or stream is empty</returns>
public static Boolean TryParsePacket(Stream stream, out LdapPacket packet)
{
try
{
var tagByte = new Byte[1];
var i = stream.Read(tagByte, 0, 1);
if (i != 0)
{
var tag = Tag.Parse(tagByte[0]);
int n = 0;
var contentLength = Utils.BerLengthToInt(stream, out n);
var contentBytes = new Byte[contentLength];
stream.Read(contentBytes, 0, contentLength);
packet = new LdapPacket(tag);
packet.ChildAttributes.AddRange(ParseAttributes(contentBytes, 0, contentLength));
return true;
}
}
catch (Exception)
{
//_log.Error("Could not parse packet from stream", ex);
}
packet = null;
return false;
}
/// <summary>
/// Parse the child attributes
/// </summary>
/// <param name="bytes"></param>
/// <param name="currentPosition"></param>
/// <param name="length"></param>
/// <returns></returns>
private static List<LdapAttribute> ParseAttributes(Byte[] bytes, Int32 currentPosition, Int32 length)
{
var list = new List<LdapAttribute>();
while (currentPosition < length)
{
var tag = Tag.Parse(bytes[currentPosition]);
currentPosition++;
int i = 0;
var attributeLength = Utils.BerLengthToInt(bytes, currentPosition, out i);
currentPosition += i;
var attribute = new LdapPacket(tag);
if (tag.IsConstructed && attributeLength > 0)
{
attribute.ChildAttributes = ParseAttributes(bytes, currentPosition, currentPosition + attributeLength);
}
else
{
attribute.Value = new Byte[attributeLength];
Buffer.BlockCopy(bytes, currentPosition, attribute.Value, 0, attributeLength);
}
list.Add(attribute);
currentPosition += attributeLength;
}
return list;
}
}
}