ldap3_client 0.3.1

LDAP Client Library for Tokio
Documentation
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
#![deny(warnings)]
#![warn(unused_extern_crates)]
#![deny(clippy::todo)]
#![deny(clippy::unimplemented)]
#![deny(clippy::unwrap_used)]
#![deny(clippy::panic)]
#![deny(clippy::unreachable)]
#![deny(clippy::await_holding_lock)]
#![deny(clippy::needless_pass_by_value)]
#![deny(clippy::trivially_copy_pass_by_ref)]
// We allow expect since it forces good error messages at the least.
#![allow(clippy::expect_used)]

use serde::{Deserialize, Serialize};
use std::pin::Pin;
use tokio::io::{ReadHalf, WriteHalf};
use tokio::net::TcpStream;
use tokio::time;
pub use tokio::time::Duration;
pub use tracing::{debug, error, info, span, trace, warn};

use futures_util::sink::SinkExt;
use futures_util::stream::StreamExt;

use ldap3_proto::proto::*;
use ldap3_proto::LdapCodec;
use openssl::ssl::{Ssl, SslConnector, SslMethod, SslVerifyMode};
use openssl::x509::X509;
use std::collections::{BTreeMap, BTreeSet};
use std::fs::File;
use std::io::Read;
use std::path::Path;
use tokio_openssl::SslStream;
use tokio_util::codec::{FramedRead, FramedWrite};

use std::fmt;
use url::Url;
use uuid::Uuid;

pub use ldap3_proto::filter;
pub use ldap3_proto::proto;

mod addirsync;
mod search;
mod syncrepl;

pub use syncrepl::{LdapSyncRepl, LdapSyncReplEntry, LdapSyncStateValue};

#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
#[repr(i32)]
pub enum LdapError {
    InvalidUrl = -1,
    LdapiNotSupported = -2,
    UseCldapTool = -3,
    ResolverError = -4,
    ConnectError = -5,
    TlsError = -6,
    PasswordNotFound = -7,
    AnonymousInvalidState = -8,
    TransportWriteError = -9,
    TransportReadError = -10,
    InvalidProtocolState = -11,
    FileIOError = -12,

    UnavailableCriticalExtension = 12,
    InvalidCredentials = 49,
    InsufficentAccessRights = 50,
    EsyncRefreshRequired = 4096,
}

impl From<LdapResultCode> for LdapError {
    fn from(code: LdapResultCode) -> Self {
        match code {
            LdapResultCode::InvalidCredentials => LdapError::InvalidCredentials,
            LdapResultCode::InsufficentAccessRights => LdapError::InsufficentAccessRights,
            LdapResultCode::EsyncRefreshRequired => LdapError::EsyncRefreshRequired,
            LdapResultCode::UnavailableCriticalExtension => LdapError::UnavailableCriticalExtension,
            err => {
                trace!(?err);
                unimplemented!()
            }
        }
    }
}

impl fmt::Display for LdapError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LdapError::InvalidUrl => write!(f, "Invalid URL"),
            LdapError::LdapiNotSupported => write!(f, "Ldapi Not Supported"),
            LdapError::UseCldapTool => write!(f, "Use cldap tool for cldap:// urls"),
            LdapError::ResolverError => write!(f, "Failed to resolve hostname or invalid ip"),
            LdapError::ConnectError => write!(f, "Failed to connect to host"),
            LdapError::TlsError => write!(f, "Failed to establish TLS"),
            LdapError::PasswordNotFound => write!(f, "No password available for bind"),
            LdapError::AnonymousInvalidState => write!(f, "Invalid Anonymous bind state"),
            LdapError::InvalidProtocolState => {
                write!(f, "The LDAP server sent a response we did not expect")
            }
            LdapError::FileIOError => {
                write!(f, "An error occured while accessing a file")
            }
            LdapError::TransportReadError => {
                write!(f, "An error occured reading from the transport")
            }
            LdapError::TransportWriteError => {
                write!(f, "An error occured writing to the transport")
            }
            LdapError::UnavailableCriticalExtension => write!(f, "An extension marked as critical was not available"),
            LdapError::InvalidCredentials => write!(f, "Invalid DN or Password"),
            LdapError::InsufficentAccessRights => write!(f, "Insufficent Access"),
            LdapError::EsyncRefreshRequired => write!(f, "An initial content sync is required. The current cookie should be considered invalid."),
        }
    }
}

pub type LdapResult<T> = Result<T, LdapError>;

enum LdapReadTransport {
    Plain(FramedRead<ReadHalf<TcpStream>, LdapCodec>),
    Tls(FramedRead<ReadHalf<SslStream<TcpStream>>, LdapCodec>),
}

impl fmt::Debug for LdapReadTransport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LdapReadTransport::Plain(_) => f
                .debug_struct("LdapReadTransport")
                .field("type", &"plain")
                .finish(),
            LdapReadTransport::Tls(_) => f
                .debug_struct("LdapReadTransport")
                .field("type", &"tls")
                .finish(),
        }
    }
}

enum LdapWriteTransport {
    Plain(FramedWrite<WriteHalf<TcpStream>, LdapCodec>),
    Tls(FramedWrite<WriteHalf<SslStream<TcpStream>>, LdapCodec>),
}

impl fmt::Debug for LdapWriteTransport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LdapWriteTransport::Plain(_) => f
                .debug_struct("LdapWriteTransport")
                .field("type", &"plain")
                .finish(),
            LdapWriteTransport::Tls(_) => f
                .debug_struct("LdapWriteTransport")
                .field("type", &"tls")
                .finish(),
        }
    }
}

impl LdapWriteTransport {
    async fn send(&mut self, msg: LdapMsg) -> LdapResult<()> {
        match self {
            LdapWriteTransport::Plain(f) => f.send(msg).await.map_err(|e| {
                info!(?e, "transport error");
                LdapError::TransportWriteError
            }),
            LdapWriteTransport::Tls(f) => f.send(msg).await.map_err(|e| {
                info!(?e, "transport error");
                LdapError::TransportWriteError
            }),
        }
    }
}

impl LdapReadTransport {
    async fn next(&mut self) -> LdapResult<LdapMsg> {
        match self {
            LdapReadTransport::Plain(f) => f.next().await.transpose().map_err(|e| {
                info!(?e, "transport error");
                LdapError::TransportReadError
            })?,
            LdapReadTransport::Tls(f) => f.next().await.transpose().map_err(|e| {
                info!(?e, "transport error");
                LdapError::TransportReadError
            })?,
        }
        .ok_or_else(|| {
            info!("connection closed");
            LdapError::TransportReadError
        })
    }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct LdapEntry {
    pub dn: String,
    pub attrs: BTreeMap<String, BTreeSet<String>>,
}

impl LdapEntry {
    pub fn remove_ava_single(&mut self, attr: &str) -> Option<String> {
        if let Some(ava) = self.attrs.remove(attr) {
            if ava.len() == 1 {
                ava.into_iter().next()
            } else {
                None
            }
        } else {
            None
        }
    }

    pub fn remove_ava(&mut self, attr: &str) -> Option<BTreeSet<String>> {
        self.attrs.remove(attr)
    }
}

impl From<LdapSearchResultEntry> for LdapEntry {
    fn from(ent: LdapSearchResultEntry) -> Self {
        let LdapSearchResultEntry { dn, attributes } = ent;

        let attrs = attributes
            .into_iter()
            .map(|LdapPartialAttribute { atype, vals }| {
                let atype = atype.to_lowercase();

                let lower = atype == "objectclass";

                let va = vals
                    .into_iter()
                    .map(|bin| {
                        std::str::from_utf8(&bin)
                            .map(|s| {
                                if lower {
                                    s.to_lowercase()
                                } else {
                                    s.to_string()
                                }
                            })
                            .unwrap_or_else(|_| {
                                base64::encode_config(&bin, base64::STANDARD_NO_PAD)
                            })
                    })
                    .collect();
                (atype, va)
            })
            .collect();

        LdapEntry { dn, attrs }
    }
}

pub struct LdapClientBuilder<'a> {
    url: &'a Url,
    timeout: Duration,
    cas: Vec<&'a Path>,
}

impl<'a> LdapClientBuilder<'a> {
    pub fn new(url: &'a Url) -> Self {
        LdapClientBuilder {
            url,
            timeout: Duration::from_secs(30),
            cas: Vec::new(),
        }
    }

    pub fn set_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    pub fn add_tls_ca<T>(mut self, ca: &'a T) -> Self
    where
        T: AsRef<Path>,
    {
        self.cas.push(ca.as_ref());
        self
    }

    #[tracing::instrument(level = "debug", skip_all)]
    pub async fn build(self) -> LdapResult<LdapClient> {
        let LdapClientBuilder { url, timeout, cas } = self;

        info!(%url);
        info!(?timeout);

        // Check the scheme is ldap or ldaps
        // for now, no ldapi support.
        let need_tls = match url.scheme() {
            "ldapi" => return Err(LdapError::LdapiNotSupported),
            "cldap" => return Err(LdapError::UseCldapTool),
            "ldap" => false,
            "ldaps" => true,
            _ => return Err(LdapError::InvalidUrl),
        };

        info!(%need_tls);
        // get domain + port

        // Do we have query params? Can we use them?
        // https://ldap.com/ldap-urls/

        // resolve to a set of socket addrs.
        let addrs = url
            .socket_addrs(|| Some(if need_tls { 636 } else { 389 }))
            .map_err(|e| {
                info!(?e, "resolver error");
                LdapError::ResolverError
            })?;

        if addrs.is_empty() {
            return Err(LdapError::ResolverError);
        }

        addrs.iter().for_each(|address| info!(?address));

        let mut aiter = addrs.into_iter();

        // Try for each to open, with a timeout.
        let tcpstream = loop {
            if let Some(addr) = aiter.next() {
                let sleep = time::sleep(timeout);
                tokio::pin!(sleep);
                tokio::select! {
                    maybe_stream = TcpStream::connect(addr) => {
                        match maybe_stream {
                            Ok(t) => {
                                info!(?addr, "connection established");
                                break t;
                            }
                            Err(e) => {
                                info!(?addr, ?e, "error");
                                continue;
                            }
                        }
                    }
                    _ = &mut sleep => {
                        info!(?addr, "timeout");
                        continue;
                    }
                }
            } else {
                return Err(LdapError::ConnectError);
            }
        };

        // If ldaps - start openssl
        let (write_transport, read_transport) = if need_tls {
            let mut tls_parms = SslConnector::builder(SslMethod::tls_client()).map_err(|e| {
                error!(?e, "openssl");
                LdapError::TlsError
            })?;

            let cert_store = tls_parms.cert_store_mut();
            for ca in cas.iter() {
                let mut file = File::open(ca).map_err(|e| {
                    error!(?e, "Unable to open {:?}", ca);
                    LdapError::FileIOError
                })?;

                let mut pem = Vec::new();
                file.read_to_end(&mut pem).map_err(|e| {
                    error!(?e, "Unable to read {:?}", ca);
                    LdapError::FileIOError
                })?;

                let ca_cert = X509::from_pem(pem.as_slice()).map_err(|e| {
                    error!(?e, "openssl");
                    LdapError::TlsError
                })?;

                cert_store
                    .add_cert(ca_cert)
                    .map(|()| {
                        info!("Added {:?} to cert store", ca);
                    })
                    .map_err(|e| {
                        error!(?e, "openssl");
                        LdapError::TlsError
                    })?;
            }

            tls_parms.set_verify(SslVerifyMode::PEER);
            let tls_parms = tls_parms.build();

            let mut tlsstream = Ssl::new(tls_parms.context())
                .and_then(|tls_obj| SslStream::new(tls_obj, tcpstream))
                .map_err(|e| {
                    error!(?e, "openssl");
                    LdapError::TlsError
                })?;

            let _ = SslStream::connect(Pin::new(&mut tlsstream))
                .await
                .map_err(|e| {
                    error!(?e, "openssl");
                    LdapError::TlsError
                })?;

            info!("tls configured");
            let (r, w) = tokio::io::split(tlsstream);
            (
                LdapWriteTransport::Tls(FramedWrite::new(w, LdapCodec)),
                LdapReadTransport::Tls(FramedRead::new(r, LdapCodec)),
            )
        } else {
            let (r, w) = tokio::io::split(tcpstream);
            (
                LdapWriteTransport::Plain(FramedWrite::new(w, LdapCodec)),
                LdapReadTransport::Plain(FramedRead::new(r, LdapCodec)),
            )
        };

        let msg_counter = 1;

        // Good to go - return ok!
        Ok(LdapClient {
            read_transport,
            write_transport,
            msg_counter,
        })
    }
}

#[derive(Debug)]
pub struct LdapClient {
    read_transport: LdapReadTransport,
    write_transport: LdapWriteTransport,
    msg_counter: i32,
}

impl LdapClient {
    fn get_next_msgid(&mut self) -> i32 {
        let msgid = self.msg_counter;
        self.msg_counter += 1;
        msgid
    }

    #[tracing::instrument(level = "debug", skip_all)]
    pub async fn bind(&mut self, dn: String, pw: String) -> LdapResult<()> {
        info!(%dn);
        let msgid = self.get_next_msgid();

        let msg = LdapMsg {
            msgid,
            op: LdapOp::BindRequest(LdapBindRequest {
                dn,
                cred: LdapBindCred::Simple(pw),
            }),
            ctrl: vec![],
        };

        self.write_transport.send(msg).await?;

        // Get the response
        self.read_transport
            .next()
            .await
            .and_then(|msg| match msg.op {
                LdapOp::BindResponse(res) => {
                    if res.res.code == LdapResultCode::Success {
                        info!("bind success");
                        Ok(())
                    } else {
                        info!(?res.res.code);
                        Err(LdapError::from(res.res.code))
                    }
                }
                op => {
                    trace!(?op);
                    Err(LdapError::InvalidProtocolState)
                }
            })
    }

    #[tracing::instrument(level = "debug", skip_all)]
    pub async fn whoami(&mut self) -> LdapResult<Option<String>> {
        let msgid = self.get_next_msgid();

        let msg = LdapMsg {
            msgid,
            op: LdapOp::ExtendedRequest(Into::into(LdapWhoamiRequest {})),
            ctrl: vec![],
        };

        self.write_transport.send(msg).await?;

        self.read_transport
            .next()
            .await
            .and_then(|msg| match msg.op {
                LdapOp::ExtendedResponse(ler) => LdapWhoamiResponse::try_from(&ler)
                    .map_err(|_| LdapError::InvalidProtocolState)
                    .map(|res| res.dn),
                op => {
                    trace!(?op);
                    Err(LdapError::InvalidProtocolState)
                }
            })
    }
}