forked from pwestrich/rust-cldap
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlib.rs
784 lines (702 loc) · 27.2 KB
/
lib.rs
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
//! Objects for connecting and querying LDAP servers using `OpenLDAP`.
//!
//! Current support includes connection, initializing, binding, configuring, and search against an
//! LDAP directory.
//!
extern crate libc;
use errors::LDAPError;
use libc::{c_char, c_int, c_void, timeval};
use std::boxed;
use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::ptr;
use std::slice;
pub mod codes;
pub mod errors;
#[repr(C)]
struct LDAP;
#[repr(C)]
struct LDAPMessage;
#[repr(C)]
pub struct LDAPControl;
#[repr(C)]
struct BerElement;
unsafe impl Sync for LDAP {}
unsafe impl Send for LDAP {}
#[link(name = "lber")]
#[allow(improper_ctypes)]
extern "C" {
fn ber_free(ber: *const BerElement, freebuf: c_int);
}
#[link(name = "ldap_r")]
#[allow(improper_ctypes)]
extern "C" {
static ber_pvt_opt_on: c_char;
fn ldap_initialize(ldap: *mut *mut LDAP, uri: *const c_char) -> c_int;
fn ldap_memfree(p: *mut c_void);
fn ldap_msgfree(msg: *mut LDAPMessage) -> c_int;
fn ldap_err2string(err: c_int) -> *const c_char;
fn ldap_first_entry(ldap: *mut LDAP, result: *mut LDAPMessage) -> *mut LDAPMessage;
fn ldap_next_entry(ldap: *mut LDAP, entry: *mut LDAPMessage) -> *mut LDAPMessage;
fn ldap_get_dn(ldap: *mut LDAP, entry: *mut LDAPMessage) -> *const c_char;
fn ldap_get_values(
ldap: *mut LDAP,
entry: *mut LDAPMessage,
attr: *const c_char,
) -> *const *const c_char;
fn ldap_count_values(vals: *const *const c_char) -> c_int;
fn ldap_value_free(vals: *const *const c_char);
fn ldap_set_option(ldap: *const LDAP, option: c_int, invalue: *const c_void) -> c_int;
fn ldap_simple_bind_s(ldap: *mut LDAP, who: *const c_char, pass: *const c_char) -> c_int;
fn ldap_first_attribute(
ldap: *mut LDAP,
entry: *mut LDAPMessage,
berptr: *mut *mut BerElement,
) -> *const c_char;
fn ldap_next_attribute(
ldap: *mut LDAP,
entry: *mut LDAPMessage,
berptr: *mut BerElement,
) -> *const c_char;
fn ldap_search_ext_s(
ldap: *mut LDAP,
base: *const c_char,
scope: c_int,
filter: *const c_char,
attrs: *const *const c_char,
attrsonly: c_int,
serverctrls: *mut *mut LDAPControl,
clientctrls: *mut *mut LDAPControl,
timeout: *mut timeval,
sizelimit: c_int,
res: *mut *mut LDAPMessage,
) -> c_int;
fn ldap_unbind_ext_s(
ldap: *mut LDAP,
sctrls: *mut *mut LDAPControl,
cctrls: *mut *mut LDAPControl,
) -> c_int;
fn ldap_start_tls_s(
ldap: *mut LDAP,
scrtrls: *mut *mut LDAPControl,
cctrls: *mut *mut LDAPControl,
) -> c_int;
}
/// A typedef for an `LDAPResponse` type.
///
/// LDAP responses are organized as vectors of mached entities. Typically, each entity is
/// represented as a map of attributes to list of values.
///
pub type LDAPResponse = Vec<HashMap<String, Vec<String>>>;
/// A high level abstraction over the raw `OpenLDAP` functions.
///
/// A `RustLDAP` object hides raw `OpenLDAP` complexities and exposes a simple object that is
/// created, configured, and queried. Methods that call underlying `OpenLDAP` calls that can fail
/// will raise an `errors::LDAPError` with additional details.
///
/// Using a `RustLDAP` object is easy!
///
pub struct RustLDAP {
/// A pointer to the underlying `OpenLDAP` object.
ldap_ptr: *mut LDAP,
}
unsafe impl Sync for RustLDAP {}
unsafe impl Send for RustLDAP {}
impl Drop for RustLDAP {
fn drop(&mut self) {
// Unbind the LDAP connection, making the C library free the LDAP*.
let rc = unsafe { ldap_unbind_ext_s(self.ldap_ptr, ptr::null_mut(), ptr::null_mut()) };
// Make sure it actually happened.
if rc != codes::results::LDAP_SUCCESS {
unsafe {
// Hopefully this never happens.
let raw_estr = ldap_err2string(rc as c_int);
panic!(CStr::from_ptr(raw_estr).to_owned().into_string().unwrap());
}
}
}
}
/// A trait for types that can be passed as LDAP option values.
///
/// Underlying `OpenLDAP` implementation calls for option values to be passed in as `*const c_void`,
/// while allowing values to be `i32` or `String`. Using traits, we implement function overloading to
/// handle `i32` and `String` option value types.
///
/// This trait allocates memory that a caller must free using `std::boxed::Box::from_raw`. This
/// helps guarantee that there is not a use after free bug (in Rust) while providing the appearance
/// of opaque memory to `OpenLDAP` (in C). In pure C, we would've accomplished this by casting a
/// local variable to a `const void *`. In Rust, we must do this on the heap to ensure Rust's
/// ownership system does not free the memory used to store the option value between now and when
/// the option is actually set.
///
pub trait LDAPOptionValue {
fn as_cvoid_ptr(&self) -> *const c_void;
}
impl LDAPOptionValue for str {
fn as_cvoid_ptr(&self) -> *const c_void {
let string = CString::new(self).unwrap();
string.into_raw() as *const c_void
}
}
impl LDAPOptionValue for i32 {
fn as_cvoid_ptr(&self) -> *const c_void {
let mem = boxed::Box::new(*self);
boxed::Box::into_raw(mem) as *const c_void
}
}
impl LDAPOptionValue for bool {
fn as_cvoid_ptr(&self) -> *const c_void {
if *self {
let mem = unsafe { boxed::Box::new(&ber_pvt_opt_on) };
boxed::Box::into_raw(mem) as *const c_void
} else {
let mem = boxed::Box::new(0);
boxed::Box::into_raw(mem) as *const c_void
}
}
}
impl RustLDAP {
/// Create a new `RustLDAP`.
///
/// Creates a new `RustLDAP` and initializes underlying `OpenLDAP` library. Upon creation, a
/// subsequent calls to `set_option` and `simple_bind` are possible. Before calling a search
/// related function, one must bind to the server by calling `simple_bind`. See module usage
/// information for more details on using a `RustLDAP` object.
///
/// # Parameters
///
/// * uri - URI of the LDAP server to connect to. E.g., ldaps://localhost:636.
///
pub fn new(uri: &str) -> Result<RustLDAP, errors::LDAPError> {
// Create some space for the LDAP pointer.
let mut cldap = ptr::null_mut();
let uri_cstring = CString::new(uri).unwrap();
unsafe {
let res = ldap_initialize(&mut cldap, uri_cstring.as_ptr());
if res != codes::results::LDAP_SUCCESS {
let raw_estr = ldap_err2string(res as c_int);
return Err(errors::LDAPError::NativeError(
CStr::from_ptr(raw_estr).to_owned().into_string().unwrap(),
));
}
}
Ok(RustLDAP { ldap_ptr: cldap })
}
/// Sets an option on the LDAP connection.
///
/// When setting an option to _ON_ or _OFF_ one may use the boolean values `true` or `false`,
/// respectively.
///
/// # Parameters
///
/// * option - An option identifier from `cldap::codes`.
/// * value - The value to set for the option.
///
pub fn set_option<T: LDAPOptionValue + ?Sized>(&self, option: i32, value: &T) -> bool {
let ptr: *const c_void = value.as_cvoid_ptr();
unsafe {
let res: i32;
res = ldap_set_option(self.ldap_ptr, option, ptr);
// Allows for memory to be dropped when this binding goes away.
let _ = boxed::Box::from_raw(ptr as *mut c_void);
res == 0
}
}
/// Bind to the LDAP server.
///
/// If you wish to configure options on the LDAP server, be sure to set required options using
///`set_option` _before_ binding to the LDAP server. In some advanced cases, it may be required
/// to set multiple options for an option to be made available. Refer to the `OpenLDAP`
/// documentation for information on available options and how to use them.
///
/// # Parameters
///
/// * who - The user's name to bind with.
/// * pass - The user's password to bind with.
///
pub fn simple_bind(&self, who: &str, pass: &str) -> Result<i32, errors::LDAPError> {
let who_cstr = CString::new(who).unwrap();
let pass_cstr = CString::new(pass).unwrap();
let who_ptr = who_cstr.as_ptr();
let pass_ptr = pass_cstr.as_ptr();
unsafe {
let res = ldap_simple_bind_s(self.ldap_ptr, who_ptr, pass_ptr);
if res < 0 {
let raw_estr = ldap_err2string(res as c_int);
return Err(errors::LDAPError::NativeError(
CStr::from_ptr(raw_estr).to_owned().into_string().unwrap(),
));
}
Ok(res)
}
}
/// Simple synchronous search.
///
/// Performs a simple search with only the base, returning all attributes found.
///
/// # Parameters
///
/// * base - The LDAP base.
/// * scope - The search scope. See `cldap::codes::scopes`.
///
pub fn simple_search(&self, base: &str, scope: i32) -> Result<LDAPResponse, errors::LDAPError> {
self.ldap_search(
base,
scope,
None,
None,
false,
None,
None,
ptr::null_mut(),
-1,
)
}
/// Installs TLS handlers on the session
///
/// # Examples
///
/// ```should_panic
/// use openldap::RustLDAP;
/// let ldap = RustLDAP::new(&"ldaps://myserver:636").unwrap();
///
/// ldap.set_option(
/// openldap::codes::options::LDAP_OPT_PROTOCOL_VERSION,
/// &openldap::codes::versions::LDAP_VERSION3,
/// );
///
/// ldap.set_option(
/// openldap::codes::options::LDAP_OPT_X_TLS_REQUIRE_CERT,
/// &openldap::codes::options::LDAP_OPT_X_TLS_ALLOW,
/// );
///
/// ldap.set_option(openldap::codes::options::LDAP_OPT_X_TLS_NEWCTX, &0);
///
/// ldap.start_tls(None, None);
/// ldap.simple_bind("some-dn", "some-password").unwrap();
/// ```
pub fn start_tls(
&self,
serverctrls: Option<*mut *mut LDAPControl>,
clientctrls: Option<*mut *mut LDAPControl>,
) -> Result<i32, errors::LDAPError> {
let r_serverctrls = match serverctrls {
Some(sc) => sc,
None => ptr::null_mut(),
};
let r_clientctrls = match clientctrls {
Some(cc) => cc,
None => ptr::null_mut(),
};
unsafe {
let res = ldap_start_tls_s(self.ldap_ptr, r_serverctrls, r_clientctrls);
if res < 0 {
let raw_estr = ldap_err2string(res as c_int);
return Err(errors::LDAPError::NativeError(
CStr::from_ptr(raw_estr).to_owned().into_string().unwrap(),
));
}
Ok(res)
}
}
/// Advanced synchronous search.
///
/// Exposes a raw API around the underlying `ldap_search_ext_s` function from `OpenLDAP`.
/// Wherever possible, use provided wrappers.
///
/// # Parameters
///
/// * base - The base domain.
/// * scope - The search scope. See `cldap::codes::scopes`.
/// * filter - An optional filter.
/// * attrs - An optional set of attrs.
/// * attrsonly - True if should return only the attrs specified in `attrs`.
/// * serverctrls - Optional sever controls.
/// * clientctrls - Optional client controls.
/// * timeout - A timeout.
/// * sizelimit - The maximum number of entities to return, or -1 for no limit.
///
pub fn ldap_search(
&self,
base: &str,
scope: i32,
filter: Option<&str>,
attrs: Option<Vec<&str>>,
attrsonly: bool,
serverctrls: Option<*mut *mut LDAPControl>,
clientctrls: Option<*mut *mut LDAPControl>,
timeout: *mut timeval,
sizelimit: i32,
) -> Result<LDAPResponse, errors::LDAPError> {
// Make room for the LDAPMessage, being sure to delete this before we return.
let mut ldap_msg = ptr::null_mut();
// Convert the passed in filter sting to either a C-string or null if one is not passed.
let filter_cstr: CString;
let r_filter = match filter {
Some(fs) => {
filter_cstr = CString::new(fs).unwrap();
filter_cstr.as_ptr()
}
None => ptr::null(),
};
// Convert the vec of attributes into the null-terminated array that the library expects.
let mut r_attrs: *const *const c_char = ptr::null();
let mut c_strs: Vec<CString> = Vec::new();
let mut r_attrs_ptrs: Vec<*const c_char> = Vec::new();
if let Some(strs) = attrs {
for string in strs {
// Create new CString and take ownership of it in c_strs.
c_strs.push(CString::new(string).unwrap());
// Create a pointer to that CString's raw data and store it in r_attrs.
r_attrs_ptrs.push(c_strs[c_strs.len() - 1].as_ptr());
}
// Ensure that there is a null value at the end of the vector.
r_attrs_ptrs.push(ptr::null());
r_attrs = r_attrs_ptrs.as_ptr();
}
let r_serverctrls = match serverctrls {
Some(sc) => sc,
None => ptr::null_mut(),
};
let r_clientctrls = match clientctrls {
Some(cc) => cc,
None => ptr::null_mut(),
};
let base = CString::new(base).unwrap();
unsafe {
let res: i32 = ldap_search_ext_s(
self.ldap_ptr,
base.as_ptr(),
scope as c_int,
r_filter,
r_attrs,
attrsonly as c_int,
r_serverctrls,
r_clientctrls,
timeout,
sizelimit as c_int,
&mut ldap_msg,
);
if res != codes::results::LDAP_SUCCESS {
let raw_estr = ldap_err2string(res as c_int);
return Err(errors::LDAPError::NativeError(
CStr::from_ptr(raw_estr).to_owned().into_string().unwrap(),
));
}
}
// We now have to parse the results, copying the C-strings into Rust ones making sure to
// free the C-strings afterwards
let mut resvec: Vec<HashMap<String, Vec<String>>> = vec![];
let mut entry = unsafe { ldap_first_entry(self.ldap_ptr, ldap_msg) };
while !entry.is_null() {
// Make the map holding the attribute : value pairs as well as the BerElement that keeps
// track of what position we're in
let mut map: HashMap<String, Vec<String>> = HashMap::new();
let mut ber: *mut BerElement = ptr::null_mut();
unsafe {
// Populate the "DN" of the user
let raw_dn = ldap_get_dn(self.ldap_ptr, entry);
let mut dn: Vec<String> = Vec::new();
dn.push(
CStr::from_ptr(raw_dn)
.to_owned()
.into_string()
.unwrap_or("<Invalid DN>".to_string()),
);
map.insert("dn".to_string(), dn);
ldap_memfree(raw_dn as *mut c_void);
let mut attr: *const c_char = ldap_first_attribute(self.ldap_ptr, entry, &mut ber);
while !attr.is_null() {
// Convert the attribute into a Rust string.
let key = CStr::from_ptr(attr).to_owned().into_string().unwrap();
// Get the attribute values from LDAP.
let raw_vals: *const *const c_char =
ldap_get_values(self.ldap_ptr, entry, attr);
let raw_vals_len = ldap_count_values(raw_vals) as usize;
let val_slice: &[*const c_char] = slice::from_raw_parts(raw_vals, raw_vals_len);
// Map these into a vector of Strings.
let values: Vec<String> = val_slice
.iter()
.map(|ptr| {
// TODO(sholsapp): If this contains binary data this will fail.
CStr::from_ptr(*ptr)
.to_owned()
.into_string()
.unwrap_or("<cannot parse binary data yet.>".to_string())
})
.collect();
// Insert newly constructed Rust key-value strings.
map.insert(key, values);
// Free the attr and value, then get next attr.
ldap_value_free(raw_vals);
ldap_memfree(attr as *mut c_void);
attr = ldap_next_attribute(self.ldap_ptr, entry, ber)
}
// Free the BerElement and advance to the next entry.
ber_free(ber, 0);
entry = ldap_next_entry(self.ldap_ptr, entry);
}
// Push this entry into the vector.
resvec.push(map);
}
// Make sure we free the message and return the parsed results.
unsafe { ldap_msgfree(ldap_msg) };
Ok(resvec)
}
}
/// This method properly escapes a value to be placed in a search filter,
/// to avoid LDAP injection attacks, according to https://tools.ietf.org/search/rfc4515#section-3 UTF1SUBSET
///
/// # Examples
/// ```
/// use openldap::escape_filter_assertion_value;
///
/// fn make_a_search_filter() {
/// // This value would be provided by a malicious user
/// let malicious_input = r"doesnotmatter)(isMemberOf=cn=admins,ou=groups,ou=example,ou=org)(doesnotmatter=";
/// let safe_filter_value = escape_filter_assertion_value(malicious_input).unwrap();
///
/// // This will now be safe, as it is not possible to perform an LDAP injection attack
/// // using the filter value
/// let filter = format!("(|(uid={})(mail={}))", safe_filter_value, safe_filter_value);
///
/// assert_eq!(safe_filter_value, r"doesnotmatter\29\28isMemberOf=cn=admins,ou=groups,ou=example,ou=org\29\28doesnotmatter=")
/// }
/// ```
pub fn escape_filter_assertion_value(input: &str) -> Result<String, LDAPError> {
String::from_utf8(
input
.escape_default()
.to_string()
.bytes()
.flat_map(|c| match c {
b'\0' => vec![b'\\', b'0', b'0'],
b'(' => vec![b'\\', b'2', b'8'],
b')' => vec![b'\\', b'2', b'9'],
b'*' => vec![b'\\', b'2', b'a'],
b'\\' => vec![b'\\', b'5', b'c'],
_ => vec![c],
})
.collect(),
)
.map_err(|_e| LDAPError::NativeError("Error while escaping filter argument".into()))
}
#[cfg(test)]
mod tests {
use std::ptr;
use {codes, escape_filter_assertion_value};
const TEST_ADDRESS: &'static str = "ldap://ldap.forumsys.com";
const TEST_BIND_DN: &'static str = "cn=read-only-admin,dc=example,dc=com";
const TEST_BIND_PASS: &'static str = "password";
const TEST_SIMPLE_SEARCH_QUERY: &'static str = "uid=tesla,dc=example,dc=com";
const TEST_SEARCH_BASE: &'static str = "dc=example,dc=com";
const TEST_SEARCH_FILTER: &'static str = "(uid=euler)";
const TEST_SEARCH_INVALID_FILTER: &'static str = "(uid=INVALID)";
/// Test creating a RustLDAP struct with a valid uri.
#[test]
fn test_ldap_new() {
let _ = super::RustLDAP::new(TEST_ADDRESS).unwrap();
}
/// Test creating a RustLDAP struct with an invalid uri.
#[test]
fn test_invalid_ldap_new() {
if let Err(e) = super::RustLDAP::new("lda://localhost") {
assert_eq!(
super::errors::LDAPError::NativeError(
"Bad parameter to an ldap routine".to_string()
),
e
);
} else {
assert!(false);
}
}
#[test]
#[should_panic]
fn test_invalid_cstring_ldap_new() {
let _ = super::RustLDAP::new("INVALID\0CSTRING").unwrap();
}
#[test]
fn test_simple_bind() {
let ldap = super::RustLDAP::new(TEST_ADDRESS).unwrap();
assert!(ldap.set_option(codes::options::LDAP_OPT_PROTOCOL_VERSION, &3));
let res = ldap.simple_bind(TEST_BIND_DN, TEST_BIND_PASS).unwrap();
assert_eq!(codes::results::LDAP_SUCCESS, res);
println!("Bind result: {:?}", res);
}
#[test]
#[should_panic] // the TEST_ADDRESS being used doesn't support LDAPS, only LDAP
fn test_simple_bind_with_start_tls() {
let ldap = super::RustLDAP::new(TEST_ADDRESS).unwrap();
assert!(ldap.set_option(codes::options::LDAP_OPT_PROTOCOL_VERSION, &3));
ldap.start_tls(None, None).unwrap();
ldap.set_option(
codes::options::LDAP_OPT_PROTOCOL_VERSION,
&codes::versions::LDAP_VERSION3,
);
ldap.set_option(
codes::options::LDAP_OPT_X_TLS_REQUIRE_CERT,
&codes::options::LDAP_OPT_X_TLS_ALLOW,
);
ldap.set_option(codes::options::LDAP_OPT_X_TLS_NEWCTX, &0);
let res = ldap.simple_bind(TEST_BIND_DN, TEST_BIND_PASS).unwrap();
assert_eq!(codes::results::LDAP_SUCCESS, res);
println!("Bind result: {:?}", res);
}
#[test]
fn test_simple_search() {
println!("Testing simple search");
let ldap = super::RustLDAP::new(TEST_ADDRESS).unwrap();
assert!(ldap.set_option(codes::options::LDAP_OPT_PROTOCOL_VERSION, &3));
let res = ldap.simple_bind(TEST_BIND_DN, TEST_BIND_PASS).unwrap();
assert_eq!(codes::results::LDAP_SUCCESS, res);
let search_res = ldap
.simple_search(TEST_SIMPLE_SEARCH_QUERY, codes::scopes::LDAP_SCOPE_BASE)
.unwrap();
//make sure we got something back
assert!(search_res.len() == 1);
// make sure the DN is searched and returned correctly
assert_eq!(search_res[0]["dn"][0], "uid=tesla,dc=example,dc=com");
for result in search_res {
println!("simple search result: {:?}", result);
for (key, value) in result {
println!("- key: {:?}", key);
for res_val in value {
println!("- - res_val: {:?}", res_val);
}
}
}
}
#[test]
fn test_search() {
println!("Testing search");
let ldap = super::RustLDAP::new(TEST_ADDRESS).unwrap();
assert!(ldap.set_option(codes::options::LDAP_OPT_PROTOCOL_VERSION, &3));
let res = ldap.simple_bind(TEST_BIND_DN, TEST_BIND_PASS).unwrap();
assert_eq!(codes::results::LDAP_SUCCESS, res);
let search_res = ldap
.ldap_search(
TEST_SEARCH_BASE,
codes::scopes::LDAP_SCOPE_SUB,
Some(TEST_SEARCH_FILTER),
None,
false,
None,
None,
ptr::null_mut(),
-1,
)
.unwrap();
//make sure we got something back
assert!(search_res.len() == 1);
// make sure the DN is searched and returned correctly
assert_eq!(search_res[0]["dn"][0], "uid=euler,dc=example,dc=com");
for result in search_res {
println!("search result: {:?}", result);
for (key, value) in result {
println!("- key: {:?}", key);
for res_val in value {
println!("- - res_val: {:?}", res_val);
}
}
}
}
#[test]
fn test_invalid_search() {
println!("Testing invalid search");
let ldap = super::RustLDAP::new(TEST_ADDRESS).unwrap();
assert!(ldap.set_option(codes::options::LDAP_OPT_PROTOCOL_VERSION, &3));
let res = ldap.simple_bind(TEST_BIND_DN, TEST_BIND_PASS).unwrap();
assert_eq!(codes::results::LDAP_SUCCESS, res);
let search_res = ldap
.ldap_search(
TEST_SEARCH_BASE,
codes::scopes::LDAP_SCOPE_SUB,
Some(TEST_SEARCH_INVALID_FILTER),
None,
false,
None,
None,
ptr::null_mut(),
-1,
)
.unwrap();
//make sure we got something back
assert!(search_res.len() == 0);
}
#[test]
fn test_search_attrs() {
println!("Testing search with attrs");
let test_search_attrs_vec = vec!["cn", "sn", "mail"];
let ldap = super::RustLDAP::new(TEST_ADDRESS).unwrap();
assert!(ldap.set_option(codes::options::LDAP_OPT_PROTOCOL_VERSION, &3));
let res = ldap.simple_bind(TEST_BIND_DN, TEST_BIND_PASS).unwrap();
assert_eq!(codes::results::LDAP_SUCCESS, res);
let search_res = ldap
.ldap_search(
TEST_SEARCH_BASE,
codes::scopes::LDAP_SCOPE_SUB,
Some(TEST_SEARCH_FILTER),
Some(test_search_attrs_vec),
false,
None,
None,
ptr::null_mut(),
-1,
)
.unwrap();
//make sure we got something back
assert!(search_res.len() == 1);
for result in search_res {
println!("attrs search result: {:?}", result);
for (key, value) in result {
println!("- key: {:?}", key);
for res_val in value {
println!("- - res_val: {:?}", res_val);
}
}
}
}
#[test]
fn test_search_invalid_attrs() {
println!("Testing search with invalid attrs");
let test_search_attrs_vec = vec!["cn", "sn", "mail", "INVALID"];
let ldap = super::RustLDAP::new(TEST_ADDRESS).unwrap();
assert!(ldap.set_option(codes::options::LDAP_OPT_PROTOCOL_VERSION, &3));
let res = ldap.simple_bind(TEST_BIND_DN, TEST_BIND_PASS).unwrap();
assert_eq!(codes::results::LDAP_SUCCESS, res);
let search_res = ldap
.ldap_search(
TEST_SEARCH_BASE,
codes::scopes::LDAP_SCOPE_SUB,
Some(TEST_SEARCH_FILTER),
Some(test_search_attrs_vec),
false,
None,
None,
ptr::null_mut(),
-1,
)
.unwrap();
for result in search_res {
println!("attrs search result: {:?}", result);
for (key, value) in result {
println!("- key: {:?}", key);
for res_val in value {
println!("- - res_val: {:?}", res_val);
}
}
}
}
#[test]
fn test_search_filter_escapation() {
let input_a =
r"*\doesnotmatter)(isMemberOf=cn=admins,ou=groups,ou=example,ou=org)(doesnotmatter=";
let expected_filtered_a = r"\2a\5c\5cdoesnotmatter\29\28isMemberOf=cn=admins,ou=groups,ou=example,ou=org\29\28doesnotmatter=";
let input_b = "thisshouldnotbealtered...[][]---,;;;";
let filtered_input_a = escape_filter_assertion_value(input_a).unwrap();
let filtered_input_b = escape_filter_assertion_value(input_b).unwrap();
assert_eq!(expected_filtered_a, filtered_input_a);
assert_eq!(input_b, filtered_input_b);
}
}