Debian Codegraph @

docs/advanced.rst

raw
1 Advanced Usage
2 **************
3
4 .. module:: bonsai
5 :noindex:
6
7 This document covers some of the more advanced features of Bonsai.
8
9 .. _auth-mechs:
10
11 Authentication mechanisms
12 =========================
13
14 There are several authentication mechanisms, which can be used with Bonsai. The selected mechanism
15 with the necessary credentials can be set with the :meth:`LDAPClient.set_credentials` method.
16
17 Simple bind
18 -----------
19
20 The simplest way to authenticate with an LDAP server is using the SIMPLE mechanism which requires a
21 bind DN and a password::
22
23 >>> import bonsai
24 >>> client = bonsai.LDAPClient()
25 >>> client.set_credentials("SIMPLE", user="cn=user,dc=bonsai,dc=test", password="secret")
26 >>> client.connect()
27 <bonsai.ldapconnection.LDAPConnection object at 0x7fed62b19828>
28
29 .. warning::
30 Be aware that during the authentication the password is sent to the server in clear text form.
31 It is ill-advised to use simple bind without secure channel (TLS/SSL) in production.
32
33 Simple Authentication and Security Layer
34 ----------------------------------------
35
36 The OpenLDAP library uses the Simple Authentication and Security Layer (`SASL`_) (while the WinLDAP
37 uses the similar `SSPI`_) to provide different authentication mechanisms. Of course to use a
38 certain mechanism it has to be supported both the client and the server. To learn which mechanisms
39 are accessible from the server, check the root DSE's `supportedSASLMechanisms` value::
40
41 >>> client.get_rootDSE()['supportedSASLMechanisms']
42 ['GSS-SPNEGO', 'GSSAPI', 'DIGEST-MD5', 'NTLM']
43
44 .. note::
45 On Unix systems, make sure that the necessary libraries of the certain mechanism are also
46 installed on the client (e.g. `libsasl2-modules-gssapi-mit` or `cyrus-sasl-gssapi` for GSSAPI
47 support).
48
49 .. _SASL: https://tools.ietf.org/html/rfc4422
50 .. _SSPI: https://msdn.microsoft.com/en-us/library/windows/desktop/aa380493%28v=vs.85%29.aspx
51
52
53 DIGEST-MD5 and NTLM
54 ^^^^^^^^^^^^^^^^^^^
55
56 The DIGEST-MD5 and the NTLM mechanisms are challenge-response based authentications. Nowadays they
57 are considered as weak security protocols, but still popular ones. An example of using NTLM::
58
59 >>> client.set_credentials("NTLM", "user", "secret")
60 >>> client.connect().whoami()
61 "dn:cn=user,dc=bonsai,dc=test"
62
63 The credentials consist of a username and a password, just like for the simple authentication.
64 When using DIGEST-MD5 you can also use an authorization ID during the bind to perform operation
65 under the authority of a different identity afterwards, if the necessary rights are granted for you.
66 NTLM does not support this functionality.
67
68 >>> client.set_credentials("DIGEST-MD5", "user", "secret", authz_id="u:root")
69 >>> client.connect().whoami()
70 "dn:cn=admin,dc=bonsai,dc=test"
71
72 GSSAPI and GSS-SPNEGO
73 ^^^^^^^^^^^^^^^^^^^^^
74
75 GSSAPI uses Kerberos tickets to authenticate to the server. To use GSSAPI or GSS-SPNEGO the client
76 must be Kerberos-aware, which means the necessary Kerberos tools and libraries have to be
77 installed, and the proper configuration has to be set. (Typically, the configuration is in the
78 `/etc/krb5.conf` on a Unix system). GSS-SPNEGO mechanism can negotiate a common authentication
79 method between server and client.
80
81 Basically, to start a GSSAPI authentication a ticket granting ticket (TGT) needs to be already
82 acquired by the client with the help of the command-line `kinit` tool::
83
84 [[email protected] ~]$ kinit [email protected]
85 Password for [email protected]:
86
87 The acquired TGT can be listed with `klist`::
88
89 [[email protected] ~]$ klist
90 Ticket cache: FILE:/tmp/krb5cc_1000
91 Default principal: [email protected]
92
93 Valid starting Expires Service principal
94 22/02/16 22:06:14 23/02/16 08:06:14 krbtgt/[email protected]
95 renew until 23/02/16 22:06:12
96
97 After successfully acquire a TGT, the module can used it for authenticating:
98
99 >>> import bonsai
100 >>> client = bonsai.LDAPClient("ldap://bonsai.test")
101 >>> client.set_credentials("GSSAPI")
102 >>> client.connect().whoami()
103 'dn:cn=admin,dc=bonsai,dc=test'
104
105 In normal case the passed credentials with the exception of the authorization ID are irrelevant
106 -- at least on a Unix system, the underlying SASL library figures it out on its own. The
107 module's client can only interfere with the authorization ID:
108
109 >>> client.set_credentials("GSSAPI", authz_id="u:chuck")
110 >>> client.connect().whoami()
111 'dn:cn=chuck,ou=nerdherd,dc=bonsai,dc=test'
112
113 But on a Windows system (by default) or if Bonsai is built with the optional Kerberos headers, then
114 it is possible to requesting a TGT with the module's client if username, password and realm name
115 are all provided:
116
117 >>> client = bonsai.LDAPClient("ldap://bonsai.test")
118 >>> client.set_credentials("GSSAPI", "admin", "secret", "BONSAI.TEST")
119 >>> client.connect().whoami()
120 'dn:cn=admin,dc=bonsai,dc=test'
121
122 It is also possible to use Kerberos keytabs when the module is built with Kerberos support:
123
124 >>> client.set_credentials("GSSAPI", user="chuck", realm="BONSAI.TEST", keytab="./user.keytab")
125 >>> client.connect().whoami()
126 'dn:cn=chuck,ou=nerdherd,dc=bonsai,dc=test'
127
128 Please note that the Kerberos realm names are typically uppercase with few exceptions.
129
130 .. note::
131 Automatic TGT requesting only accessible on Unix systems if the optional Kerberos headers are
132 provided during the module's build.
133
134 EXTERNAL
135 ^^^^^^^^
136
137 With EXTERNAL mechanism TLS certifications are used to authenticate the user. In certain cases (e.g
138 the remote server is an OpenLDAP directory) the EXTERNAL option is presented as an available SASL
139 mechanism only when the client have built up a TLS connection with the server and already set a
140 client cert.
141
142 >>> client = bonsai.LDAPClient("ldap://bonsai.test", tls=True)
143 >>> client.set_ca_cert_dir('/etc/openldap/certs')
144 >>> client.set_ca_cert("RootCACert")
145 >>> client.set_client_cert("BonsaiTestUser")
146 >>> client.set_client_key("./key.txt")
147 >>> client.get_rootDSE()['supportedSASLMechanisms']
148 ['GSS-SPNEGO', 'GSSAPI', 'DIGEST-MD5', 'EXTERNAL', 'NTLM']
149 >>> client.set_credentials("EXTERNAL")
150 >>> client.connect()
151 <bonsai.ldapconnection.LDAPConnection object at 0x7f006ad3d888>
152
153 For EXTERNAL mechanism only the authorization ID is used in as credential information.
154
155 >>> client.set_credentials("EXTERNAL", authz_id=u:chuck")
156 >>> client.connect()
157 >>> client.connect().whoami()
158 'dn:cn=chuck,ou=nerdherd,dc=bonsai,dc=test'
159
160
161 The proper way of setting the certifications is depend on the TLS implementation that the LDAP
162 library uses. Please for more information see :ref:`tls-settings`.
163
164 .. _tls-settings:
165
166 TLS settings
167 ============
168
169 There are two practices to use secure connection:
170
171 * Either use the `ldaps://` scheme in the LDAP URL, then the client will use
172 the LDAP over SSL protocol (similar to HTTPS).
173 * Or set the tls parameter of the :class:`LDAPClient` to True, which will
174 instruct the client to preform a `StartTLS` operation after connected to the
175 LDAP server.
176
177 Both practices rely on well-set credentials with the TLS related methods --
178 :meth:`LDAPClient.set_ca_cert_dir`, :meth:`LDAPClient.set_ca_cert`,
179 :meth:`LDAPClient.set_client_cert` and :meth:`LDAPClient.set_client_key`.
180
181 These are expecting different inputs depending on which TLS library is used by
182 the LDAP library. To find out which TLS library is used call
183 :func:`bonsai.get_tls_impl_name`.
184
185 .. rubric:: GnuTLS and OpenSSL
186
187 For GnuTLS and OpenSSL the :meth:`LDAPClient.set_ca_cert` and :meth:`LDAPClient.set_client_cert`
188 are expecting file paths that link to certification files in PEM-format.
189
190 The :meth:`LDAPClient.set_ca_cert_dir` works only for OpenSSL if the content of provided
191 directory is symbolic links of certifications that are generated by the `c_rehash` utility.
192
193 .. rubric:: Mozilla NSS
194
195 When using Mozilla NSS the input of :meth:`LDAPClient.set_ca_cert_dir` is the path of the directory
196 containing the NSS certificate database (that is created with the `certutil` command).
197
198 The :meth:`LDAPClient.set_ca_cert` and :meth:`LDAPClient.set_client_cert` can be used to select the
199 certificate with their names in the certificate database.
200
201 If the client certificate is password protected, then the input of
202 :meth:`LDAPClient.set_client_key` should be a path to the file that contains the password in clear
203 text format.
204
205 .. rubric:: Microsoft Schannel
206
207 Unfortunately, none of the listed TLS modules are effective on Microsoft Windows. The WinLDAP
208 library automatically searches for the corresponding certificates in the cert store. All of the
209 necessary certificates have to be loaded manually before the client tries to use them.
210
211 .. _ldap-controls:
212
213 LDAP controls
214 =============
215
216 Several LDAP controls can be used to extend and improve the basic LDAP operations. Bonsai is
217 supporting the following controls. Always check (the root DSE's `supportedControls`) that the
218 server also supports the selected control.
219
220 Server side sort
221 ----------------
222
223 Using the server side sort control the result of the search is ordered based on the selected
224 attributes. To invoke the control simply set the `sort_order` parameter of the
225 :meth:`LDAPConnection.search` method:
226
227 >>> conn = client.connect()
228 >>> conn.search("ou=nerdherd,dc=bonsai,dc=test", 2, sort_order=["-cn", "gn"])
229
230 Attributes that start with `-` are used for descending order.
231
232 .. warning::
233 Even if the server side sort control is supported by the server there is no guarantee that the
234 results will be sorted for multiple attributes.
235
236 .. note::
237 The OID of server side sort control is: 1.2.840.113556.1.4.473.
238
239 Paged search result
240 -------------------
241
242 Paged search can be used to reduce large search result into smaller pages. Page result can be used
243 with the :meth:`LDAPConnection.paged_search` method and the size of the page can be set with the
244 `page_size` parameter:
245
246 >>> conn = client.connect()
247 >>> conn.paged_search("ou=nerdherd,dc=bonsai,dc=test", 2, page_size=3)
248 <_bonsai.ldapsearchiter object at 0x7f006ad455d0>
249
250 Please note that the return value of :meth:`LDAPConnection.paged_search` is an :class:`ldapsearchiter`.
251 This object can be iterated over the entries of the page. By default the next page of results is
252 acquired automatically during the iteration. This behaviour can be changed by setting the
253 :attr:`LDAPClient.auto_page_acquire` to `False` and using the :meth:`ldapsearchiter.acquire_next_page`
254 method which explicitly initiates a new search request to get the next page.
255
256 .. warning::
257 Avoid using server-side referral chasing with paged search. It's likely to fail with invalid
258 cookie error.
259
260 .. note::
261 The OID of paged search control is: 1.2.840.113556.1.4.319.
262
263 Virtual list view
264 -----------------
265
266 Virtual list view (VLV) is also for reducing large search result, but with a more specific manner.
267 Virtual list view mimics the scrolling view of an application: it can select a target entry of a
268 large list (ordered search result) with an offset or an attribute value and receiving only a
269 given number of entries before and after it as a partial result of the entire search.
270
271 The :meth:`LDAPConnection.virtual_list_search` method's `offset` or `attrvalue` can be used to select
272 the target, the `before_count` and `after_count` for specifying the number of entries before and after
273 the target.
274
275 Also need to set the `est_list_count` parameter: the estimated size of the entire list by the
276 client. The server will adjust the position of the target entry based on the real list size,
277 estimated size and the offset.
278
279 Virtual list view control cannot be used without a server side sort control thus a sort order
280 always has to be set.
281
282 >>> conn.virtual_list_search("ou=nerdherd,dc=bonsai,dc=test", 2, attrlist=['cn', 'uidNumber'], sort_order=['-uidNumber'], offset=4, before_count=1, after_count=1, est_list_count=6)
283 ([{'dn': <LDAPDN cn=sam,ou=nerdherd,dc=bonsai,dc=test>, 'cn': ['sam'], 'uidNumber': [4]},
284 {'dn': <LDAPDN cn=skip,ou=nerdherd,dc=bonsai,dc=test>, 'cn': ['skip'], 'uidNumber': [3]},
285 {'dn': <LDAPDN cn=jeff,ou=nerdherd,dc=bonsai,dc=test>, 'cn': ['jeff'], 'uidNumber': [2]}],
286 {'oid': '2.16.840.1.113730.3.4.10', 'target_position': 4, 'list_count': 7})
287
288 The return value of the search is a tuple of a list and a dictionary. The dictionary contains
289 the VLV server response: the target position and the real list size.
290
291 .. note::
292 The OID of virtual list view control is: 2.16.840.1.113730.3.4.9.
293
294 Password policy
295 ---------------
296
297 Password policy defines a set of rules about accounts and modification of passwords. It allows
298 for the system administrator to set expiration time for passwords and a maximal number of failed
299 login attempts before the account become locked. Is also specifies rules about the quality of
300 password.
301
302 Enabling the password policy control with :meth:`LDAPClient.set_password_policy` method, the client
303 can receive additional information during connecting to a server or modifying a user's password.
304 Setting this control will change the return value of :meth:`LDAPClient.connect` and
305 :meth:`LDAPConnection.open` to a tuple of :class:`LDAPConnection` and a dictionary that contains
306 the remaining seconds until the password's expiration and the remaining grace logins. The client
307 can also receive new exceptions related to password modifications.
308
309 >>> import bonsai
310 >>> client = bonsai.LDAPClient()
311 >>> client.set_credentials("SIMPLE", "cn=user,dc=bonsai,dc=test", "secret")
312 >>> client.set_password_policy(True)
313 >>> conn, ctrl = client.connect()
314 >>> conn
315 <bonsai.ldapconnection.LDAPConnection object at 0x7fa552ab4e28>
316 >>> ctrl
317 {'grace': 1, 'expire': 3612, 'oid': '1.3.6.1.4.1.42.2.27.8.5.1'})
318
319 If the server does not support password policy control or the given credentials does not have
320 policies (like anonymous or administrator user) the second item in the tuple will be `None`.
321
322 .. note::
323 Because the password policy is not standardized, it is not listed by the server among
324 the `supportedControls` even if it is available.
325
326 .. note::
327 Password policy control cannot be used on MS Windows with WinLDAP. In this case after
328 opening a connection the control dictionary will always be `None`.
329
330 Extended DN
331 -----------
332
333 Setting LDAP_SERVER_EXTENDED_DN control with :meth:`LDAPClient.set_extended_dn` will extend the
334 standard DN format with the SID and GUID attributes to `<GUID=xxxxxxxx>;<SID=yyyyyyyyy>;distinguishedName`
335 during the LDAP search. The method's parameter can be either 0 which means that the GUID and SID
336 strings will be in a hexadecimal string format or 1 for receiving the extended dn in a standard
337 string format. This control is only supported by Microsoft's Active Directory.
338
339 Regardless of setting the control, the :attr:`LDAPEntry.dn` still remains a simple :class:`LDAPDN`
340 object without the SID or GUID extensions. The extended DN will be set to the :attr:`LDAPEntry.extended_dn`
341 as a string. The extended DN control also affects other LDAP attributes that use distinguished names
342 (e.g. `memberOf` attribute).
343
344 >>> client = bonsai.LDAPClient()
345 >>> client.set_extended_dn(1)
346 >>> result = conn.search("ou=nerdherd,dc=bonsai,dc=test", 1)
347 >>> result[0].extended_dn
348 <GUID=899e4e01-e88d-4dea-ba64-119ed386b61c>;<SID=S-1-5-21-101232111302-1767724339-724445543-12345>;cn=chuck,ou=nerdherd,dc=bonsai,dc=test
349 >>> result[0].dn
350 <LDAPDN cn=chuck,ou=nerdherd,dc=bonsai,dc=test>
351
352 .. note::
353 The OID of extended DN control is: 1.2.840.113556.1.4.529.
354
355 Server tree delete
356 ------------------
357
358 Server tree delete control allows the client to remove entire subtree with a single request if
359 the user has appropriate permissions to remove every corresponding entry. Setting the `recursive`
360 parameter of :meth:`LDAPConnection.delete` and :meth:`LDAPEntry.delete` to `True` will send
361 the control with the delete request automatically, no further settings are required.
362
363 .. note::
364 The OID of server tree delete control is: 1.2.840.113556.1.4.805
365
366 ManageDsaIT
367 -----------
368
369 The ManageDsaIT control can be used to work with LDAP referrals as simple LDAP entries. After
370 setting it with the :meth:`LDAPClient.set_managedsait` method, the referrals can be added
371 removed, and modified just like entries.
372
373 >>> client = bonsai.LDAPClient()
374 >>> client.set_managedsait(True)
375 >>> conn = client.connect()
376 >>> ref = conn.search("o=admin-ref,ou=nerdherd,dc=bonsai,dc=test", 0)[0]
377 >>> ref
378 {'dn': <LDAPDN o=admin-ref,ou=nerdherd,dc=bonsai,dc=test>, 'objectClass': ['referral',
379 'extensibleObject'], 'o': ['admin-ref']}
380 >>> type(ref)
381 <class 'bonsai.ldapentry.LDAPEntry'>
382
383 .. note::
384 The OID of ManageDsaIT control is: 2.16.840.1.113730.3.4.2
385
386 SD Flags
387 --------
388
389 The SD Flags control can be used to manage the portion of a Windows security descriptor
390 to retrieve. The flag can be the combination of the following:
391
392 * 0x1 - Get the owner identifier of the object.
393 * 0x2 - Get the primary group identifier.
394 * 0x4 . Get the discretionary access control list (DACL) of the object.
395 * 0x8 - Get the system access control list (SACL) of the object.
396
397 Use :meth:`LDAPClient.set_sd_flags` method to set the value of the flag.
398
399 .. note::
400 The OID of SD_FLAGS control is: 1.2.840.113556.1.4.801
401
402 Using connection pools
403 ======================
404
405 When your application requires to use multiple open LDAP connections, Bonsai
406 provides you connection pools to help you creating and accessing them. This way
407 you can acquire an opened connection, do some operations and put it back into
408 the pool for other threads/tasks to use.
409
410 .. code-block:: python3
411
412 import bonsai
413 import threading
414 from bonsai.pool import ThreadedConnectionPool
415
416 def work(pool):
417 with pool.spawn() as conn:
418 print(conn.whoami())
419 # Some other operations...
420
421 client = bonsai.LDAPClient()
422 pool = ThreadedConnectionPool(client, minconn=5, maxconn=10)
423 thr = threading.Thread(target=work, args=(pool,))
424 thr.start()
425 conn = pool.get()
426 res = conn.search()
427 # After finishing up...
428 pool.put(conn)
429
430 Connections in a pool are opened when the pool is created or when a connection
431 is requested from the pool with :meth:`bonsai.pool.ConnectionPool.get`. They
432 then remain open until the entire pool is closed.
433
434 Connection timeouts
435 -------------------
436
437 Some LDAP servers, or some firewalls between a program and the LDAP server,
438 will cut off connections if they have been idle for too long. Sometimes this is
439 done silently and the only sign is that the next request will time out. You
440 may therefore want to set a timeout when using connections from a pool so that
441 your program doesn't wait for a TCP timeout (which can take a very long time).
442
443 Bonsai does not detect that a connection has timed out or is otherwise in an
444 error state and should not be used again. However, you can close the connection
445 before returning it to the pool, and Bonsai will then discard it and not reuse
446 it and will open a new replacement connection as needed.
447
448 One possible pattern for using a connection pool with an LDAP server that may
449 silently time out connections is to close connections on failure and retry one
450 more time than there are idle connections in the pool. In the worst case where
451 all idle connections have been timed out, each of those idle connections will
452 fail and be closed and then you'll get a fresh connection that should not have
453 timed out (and if that still fails, there is some deeper problem).
454
455 .. code-block:: python3
456
457 def work(pool, base, scope, filter_exp, attrlist):
458 idle_count = pool.idle_connection
459 for try in range(idle_count + 1):
460 with pool.spawn() as conn:
461 try:
462 result = conn.search(
463 base, scope, filter_exp, attrlist, timeout=10
464 )
465 # Use the results somehow....
466 except bonsai.ConnectionError as e:
467 conn.close()
468 # If all of the idle connections have been tried and the
469 # call still failed, there is something deeper wrong.
470 if try == idle_count:
471 raise
472
473 When using :class:`bonsai.asyncio.AIOConnectionPool`, also catch
474 :class:`asyncio.TimeoutError`, which may be raised by a connection timeout.
475
476 Reading and writing LDIF files
477 ==============================
478
479 Bonsai has a limited support to read and write LDIF files. LDIF (LDAP Data Interchange Format)
480 is a plain text file format for representing LDAP changes and updates. It can be used to exchange
481 data between directory servers.
482
483 To read an LDIF file, simply open the file in read-mode, pass it to the :class:`LDIFReader`,
484 then the reader object can be used as an iterator to get the entries from the LDIF file.
485
486 .. code-block:: python3
487
488 from bonsai import LDIFReader
489
490 with open("users.ldif", "r") as data:
491 reader = LDIFReader(data)
492 for ent in reader:
493 print(ent)
494
495
496 Writing LDIF files is similar. The :class:`LDIFWriter` needs an open file-object in write-mode,
497 and the :meth:`LDIFWriter.write_entry` expects an :class:`LDAPEntry` object whose attributes will be
498 serialised. It also possible to serialise the changes of an entry with :meth:`LDIFWriter.write_changes`.
499
500 .. code-block:: python3
501
502 from bonsai import LDAPClient
503 from bonsai import LDIFWriter
504
505 client = LDAPClient("ldap://bonsai.test")
506 with client.connect() as conn:
507 res = conn.search("cn=jeff,ou=nerdherd,dc=bonsai,dc=test", 0)
508 with open("user.ldif", "w") as data:
509 writer = LDIFWriter(data)
510 writer.write_entry(res[0])
511 # Make some changes on the entry.
512 res[0]["mail"].append("[email protected]")
513 res[0]["homeDirectory"] = "/opt/jeff"
514 with open("changes.ldif", "w") as data:
515 writer = LDIFWriter(data)
516 writer.write_changes(res[0])
517
518 .. note::
519
520 As mentioned above :class:`LDIFReader` and :class:`LDIFWriter` have their limitations. They
521 can handle basic attribute changes (adding, modifying and removing), serialising attributes,
522 but they're not capable to cope with deleting and renaming entries, or processing LDAP controls
523 that are presented in the LDIF file.
524
525 Asynchronous operations
526 =======================
527
528 Asynchronous operations are first-class citizens in the underlying C API that Bonsai is built on.
529 That makes relatively easy to integrate the module with popular Python async libraries. Bonsai is
530 shipped with support to some: `asyncio`_, `gevent`_, `Tornado`_ and `trio`_.
531
532 .. _asyncio: https://docs.python.org/3/library/asyncio.html
533 .. _gevent: http://www.gevent.org/
534 .. _Tornado: http://www.tornadoweb.org/en/stable/
535 .. _trio: https://trio.readthedocs.io/en/stable/
536
537 Using async out-of-the-box
538 --------------------------
539
540 To start asynchronous operations set the :meth:`LDAPClient.connect` method's `is_async` parameter
541 to True. By default the returned connection object can be used with Python's `asyncio` library.
542 For further details about how to use `asyncio` see the `official documentation`_.
543
544 .. _official documentation: https://docs.python.org/3/library/asyncio.html
545
546 An example for asynchronous search and modify with `asyncio`:
547
548 .. code-block:: python3
549
550 import asyncio
551 import sys
552
553 import bonsai
554
555 if sys.platform == 'win32':
556 # The current asyncio connection implementation requires
557 # the old selector event loop when running on Windows.
558 asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
559
560 async def do():
561 cli = bonsai.LDAPClient("ldap://localhost")
562 async with cli.connect(is_async=True) as conn:
563 results = await conn.search("ou=nerdherd,dc=bonsai,dc=test", 1)
564 for res in results:
565 print(res['givenName'][0])
566 search = await conn.search("cn=chuck,ou=nerdherd,dc=bonsai,dc=test", 0)
567 entry = search[0]
568 entry['mail'] = "[email protected]"
569 await entry.modify()
570
571 asyncio.run(do())
572
573 To work with other non-blocking I/O modules the default asynchronous class has to be set to a
574 different one with :meth:`LDAPClient.set_async_connection_class`.
575
576 .. note::
577 The default asyncio event loop is changed with Python 3.8 on Windows to
578 `ProactorEventLoop`. Unfortunately, bonsai's asyncio connection requires
579 the old `SelectorEventLoop`. Make sure to change it like in the example
580 before using the module. Otherwise the ``add_reader`` method will raise
581 ``NotImplementedError``.
582
583 For example changing it to `GeventLDAPConnection` makes it possible to use the module with
584 gevent:
585
586 .. code-block:: python
587
588 import gevent
589
590 import bonsai
591 from bonsai.gevent import GeventLDAPConnection
592
593 def do():
594 cli = bonsai.LDAPClient("ldap://localhost")
595 # Change the default async conn class.
596 cli.set_async_connection_class(GeventLDAPConnection)
597 with cli.connect(True) as conn:
598 results = conn.search("ou=nerdherd,dc=bonsai,dc=test", 1)
599 for res in results:
600 print(res['givenName'][0])
601 search = conn.search("cn=chuck,ou=nerdherd,dc=bonsai,dc=test", 0)
602 entry = search[0]
603 entry['mail'] = "[email protected]"
604 entry.modify()
605
606 gevent.joinall([gevent.spawn(do)])
607
608 .. note::
609 Since 1.2.1, to achieve non-blocking socket connection, the `bonsai.set_connect_async(True)`
610 has to be called before connecting the server. But setting it and using TLS can cause errors
611 even on newer Ubuntu releases (18.04+), thus it has been turned off by default on every
612 platform.
613
614 Create your own async class
615 ---------------------------
616
617 If you would like to use an asynchronous library that is currently not supported by Bonsai,
618 then you have to work a little bit more to make it possible. The following example will help
619 you to achieve that by showing how to create a new async class for `Curio`_. Inspecting the
620 implementations of the supported libraries can also help.
621
622 .. warning::
623 This class is just for education purposes, the implementation is made after just scraping the
624 surface of Curio. It's far from perfect and not meant to use in production.
625
626 The C API's asynchronous functions are designed to return a message ID immediately after calling
627 them, and then polling the state of the executed operations. The `BaseLDAPConnection` class exposes
628 the same functionality of the C API. Therefore it makes possible to start an operation then poll
629 the result with :meth:`LDAPConnection.get_result()` periodically in the `_evaluate` method which
630 happens to be called in every other method that evaluates an LDAP operation.
631
632 .. code-block:: python3
633
634 from typing import Optional
635 import bonsai
636 import curio
637
638 from bonsai.ldapconnection import BaseLDAPConnection
639
640 # You have to inherit from BaseLDAPConnection.
641 class CurioLDAPConnection(BaseLDAPConnection):
642 def __init__(self, client: "LDAPClient"):
643 super().__init__(client, is_async=True)
644
645 async def _evaluate(self, msg_id: int, timeout: Optional[float] = None):
646 while True:
647 res = self.get_result(msg_id)
648 if res is not None:
649 return res
650 await curio.sleep(1)
651
652 The constant polling can be avoided with voluntarily sleep, but it's more efficient to register to an
653 I/O event that will notify when the data is available. The :meth:`LDAPConnection.fileno()` method
654 returns the socket's file descriptor that can be used with the OS's default I/O monitoring function
655 (e.g select or epoll) for this purpose. In Curio you can wait until a socket becomes writable with
656 `curio.traps._write_wait`:
657
658 .. code-block:: python3
659
660 async def _evaluate(self, msg_id: int, timeout: Optional[float] = None):
661 while True:
662 await curio.traps._write_wait(self.fileno())
663 res = self.get_result(msg_id)
664 if res is not None:
665 return res
666
667
668 The following code is a simple litmus test for proving that the created class plays nice with other
669 coroutines:
670
671 .. code-block:: python3
672
673 async def countdown(n):
674 while n > 0:
675 print(f"T-minus {n}")
676 await curio.sleep(1)
677 n -= 1
678
679 async def search():
680 cli = bonsai.LDAPClient()
681 cli.set_async_connection_class(CurioLDAPConnection)
682 conn = await cli.connect(is_async=True)
683 res = await conn.search("ou=nerdherd,dc=bonsai,dc=test", 1)
684 for ent in res:
685 print(ent.dn)
686
687 async def tasks():
688 tsk1 = await curio.spawn(countdown, 20)
689 tsk2 = await curio.spawn(search)
690 await tsk1.join()
691 await tsk2.join()
692
693 if __name__ == "__main__":
694 curio.run(tasks)
695
696 This example class has the minimal functionalities only but hopefully gives you the basic idea how
697 the asynchronous integration works.
698
699 .. _Curio: https://curio.readthedocs.io/en/latest/
700
701 Utilities for Active Directory
702 ==============================
703
704 .. module:: bonsai.active_directory
705 :noindex:
706
707 Bonsai has some helper classes to work with Windows-specific attributes in Active Directory.
708
709 Security descriptor
710 -------------------
711
712 The Windows security descriptor is a data structure containing the security information associated
713 with a securable object. It's stored in the `ntSecurityDescriptor` attribute as a binary data.
714 To parse it use the :meth:`SecurityDescriptor.from_binary()` method::
715
716 >>> import bonsai
717 >>> from bonsai.active_directory import SecurityDescriptor
718 >>> client = LDAPClient("ldap://localhost")
719 >>> client.set_credentials("SIMPLE", user="cn=chuck,ou=nerdherd,dc=bonsai,dc=test", password="secret")
720 >>> conn = client.connect()
721 >>> entry = conn.search("cn=chuck,ou=nerdherd,dc=bonsai,dc=test", 0, attrlist=["ntSecurityDescriptor"])[0]
722 >>> sec_desc = SecurityDescriptor.from_binary(entry["ntSecurityDescriptor"][0])
723 >>> print(sec_desc.owner_sid)
724 <SID: S-1-5-21-3623811015-3361044348-30300820-1013>
725 >>> print(sec_desc.dacl)
726 <bonsai.active_directory.acl.ACL object at 0x7f388bc4d6a0>
727
728 UserAccountControl
729 ------------------
730
731 The UserAccountControl attribute contains a range of flags which define some important basic
732 properties of a user object like whether the account is active or locked, whether the option
733 of password change at the next logon is enabled, etc. The :class:`UserAccountControl` helps
734 to parse this information::
735
736 >>> from bonsai.active_directory import UserAccountControl
737 >>> uac = UserAccountControl(entry['userAccountControl'][0])
738 >>> uac
739 <bonsai.active_directory.UserAccountControl object at 0x00FC38D0>
740 >>> uac.properties
741 {'script': False, 'accountdisable': False, 'homedir_required': False, 'lockout': False, 'passwd_notreqd': False, 'passwd_cant_change': False, 'encrypted_text_pwd_allowed': False, 'temp_duplicate_account': False, 'normal_account': True, 'interdomain_trust_account': False, 'workstation_trust_account': False, 'server_trust_account': False, 'dont_expire_password': True, 'mns_logon_account': False, 'smartcard_required': False, 'trusted_for_delegation': False, 'not_delegated': False, 'use_des_key_only': False, 'dont_req_preauth': False, 'password_expired': False, 'trusted_to_auth_for_delegation': False, 'partial_secrets_account': False}