Debian Codegraph @

src/_bonsai/ldap-xplat.c

raw symbols SCIP
1 #include "ldap-xplat.h"
2
3 #include "utils.h"
4
5 #ifdef WIN32
6
7 /* It does what it says: no verification on the server cert. */
8 BOOLEAN _cdecl
9 noverify(PLDAP Connection, PCCERT_CONTEXT *ppServerCert) {
10 return 1;
11 }
12
13 static void
14 set_cert_policy(LDAP *ld, int cert_policy) {
15 const int tls_settings = SCH_CRED_MANUAL_CRED_VALIDATION | SCH_CRED_NO_SERVERNAME_CHECK;
16
17 DEBUG("set_cert_policy (ld:%p, cert_policy:%d)", ld, cert_policy);
18 switch (cert_policy) {
19 case -1:
20 /* Cert policy is not set, nothing to do.*/
21 break;
22 case 2:
23 case 4:
24 /* Cert policy is demand or try, then standard procedure. */
25 break;
26 case 0:
27 case 3:
28 /* Cert policy is never or allow, then set TLS settings. */
29 ldap_set_option(ld, 0x43, &tls_settings);
30 ldap_set_option(ld, LDAP_OPT_SERVER_CERTIFICATE, &noverify);
31 break;
32 }
33 }
34
35 /* Finish the initialisation by checking the result of the separate thread for TLS.
36 The `misc` parameter is a pointer to the thread's data structure that contains the
37 LDAP struct. The initialised LDAP struct is passed to the `ld` parameter. */
38 int
39 _ldap_finish_init_thread(char async, XTHREAD thread, int *timeout, void *misc, LDAP **ld) {
40 int rc = -1;
41 int retval = 0;
42 SYSTEMTIME st;
43 FILETIME ft;
44 ULONGLONG start_time;
45 ULONGLONG end_time;
46 ldapInitThreadData *val = (ldapInitThreadData *)misc;
47
48 GetSystemTime(&st);
49 SystemTimeToFileTime(&st, &ft);
50 /* Current time in 100-nanosec. */
51 start_time = (((ULONGLONG)ft.dwHighDateTime) << 32) + ft.dwLowDateTime;
52
53 /* Sanity check. */
54 if (val == NULL || thread == NULL) return -1;
55
56 DEBUG("_ldap_finish_init_thread (async:%d, thread:%p, timeout:%d, misc:%p)",
57 async, thread, *timeout, misc);
58 if (async) {
59 rc = WaitForSingleObject(thread, 10);
60 } else {
61 rc = WaitForSingleObject(thread, *timeout);
62 }
63
64 switch (rc) {
65 case WAIT_TIMEOUT:
66 if (async == 0) {
67 TerminateThread(thread, -1);
68 CloseHandle(thread);
69 set_exception(NULL, LDAP_TIMEOUT);
70 retval = -1;
71 goto end;
72 }
73 return 0;
74 case WAIT_OBJECT_0:
75 if (async == 0 && *timeout != -1) {
76 GetSystemTime(&st);
77 SystemTimeToFileTime(&st, &ft);
78 /* Current time in 100-nanosec. */
79 end_time = (((ULONGLONG)ft.dwHighDateTime) << 32) + ft.dwLowDateTime;
80 /* Deduct the passed time from the overall timeout. */
81 *timeout -= (int)((end_time - start_time) / 10000);
82 if (*timeout < 0) *timeout = 0;
83 }
84 if (val->retval != LDAP_SUCCESS) {
85 /* The ldap_connect is failed. Set a Python error. */
86 set_exception(NULL, val->retval);
87 retval = -1;
88 goto end;
89 }
90 /* Set the new LDAP struct. */
91 *ld = val->ld;
92 retval = 1;
93 goto end;
94 default:
95 /* The thread is failed. */
96 PyErr_BadInternalCall();
97 retval = -1;
98 goto end;
99 }
100 end:
101 /* Clean up the mess. */
102 CloseHandle(thread);
103 free(val->url);
104 free(val->sasl_sec_props);
105 free(val);
106 return retval;
107 }
108
109 static int WINAPI
110 ldap_thread_bind(void *params) {
111 int rc = 0;
112 char *binddn = NULL;
113 ldap_conndata_t *data = (ldap_conndata_t *)params;
114 sasl_defaults_t defaults;
115
116 DEBUG("ldap_thread_bind (params:%p)", params);
117 defaults.authcid = data->authcid;
118 defaults.passwd = data->passwd;
119 defaults.realm = data->realm;
120 defaults.authzid = data->authzid;
121
122 if (strcmp(data->mech, "SIMPLE") != 0) {
123 if (data->binddn == NULL) binddn = "";
124 else binddn = data->binddn;
125 rc = ldap_sasl_sspi_bind_s(data->ld, binddn, data->mech, NULL, NULL, &defaults);
126 } else {
127 rc = ldap_simple_bind_s(data->ld, data->binddn, data->passwd);
128 }
129 if (data->sock != -1) {
130 /* Send a signal through an internal socketpair. */
131 if (send(data->sock, "s", 1, 0) == -1) rc = -1;
132 }
133
134 return rc;
135 }
136
137 /* Create a separate thread for binding to the server. Results of asynchronous
138 SASL function call cannot be parsed (because of some kind of bug in WinLDAP). */
139 int
140 _ldap_bind(LDAP *ld, ldap_conndata_t *info, char ppolicy, LDAPMessage *result, int *msgid) {
141
142 DEBUG("_ldap_bind (ld:%p, info:%p, ppolicy:%d, result:%p, msgid:%d)",
143 ld, info, ppolicy, result, *msgid);
144 info->ld = ld;
145 info->thread = (void *)CreateThread(NULL, 0, ldap_thread_bind, (void *)info, 0, NULL);
146
147 return LDAP_SUCCESS;
148 }
149
150 int
151 _ldap_parse_passwordpolicy_control(LDAP *ld, LDAPControl **ctrls, ber_int_t *expire,
152 ber_int_t *grace, unsigned int *error) {
153 return ldap_parse_passwordpolicy_control(ld, ctrls, expire, grace, error);
154 }
155
156 void
157 _ldap_control_free(LDAPControl *ctrl) {
158 free(ctrl->ldctl_value.bv_val);
159 free(ctrl);
160 }
161
162 #else
163
164 #ifdef HAVE_KRB5
165
166 static int
167 create_krb5_cred(krb5_context ctx, char *realm, char *user, char *password,
168 char *ktname, krb5_ccache *ccache, gss_cred_id_t *gsscred,
169 char **errmsg) {
170 int rc = 0, len = 0;
171 unsigned int minor_stat = 0, major_stat = 0;
172 const char *errmsg_tmp = NULL;
173 const char *cctype = NULL;
174 char *cname = NULL;
175 krb5_ccache defcc = NULL;
176 int credsInitialized = 0;
177 krb5_creds creds;
178 krb5_principal princ = NULL;
179 krb5_keytab keytab = NULL;
180 gss_key_value_element_desc elems[2];
181 gss_key_value_set_desc store;
182 gss_name_t sname = NULL;
183 gss_buffer_desc pr_name;
184
185 pr_name.value = NULL;
186 pr_name.length = 0;
187
188 store.count = 0;
189 store.elements = elems;
190
191 if (user == NULL || realm == NULL) return 1;
192 len = strlen(realm);
193
194 if (len == 0 || strlen(user) == 0) return 0;
195
196 DEBUG("create_krb5_cred (ctx:%p, realm:%s, user:%s, password:%s, ktname: %s,"
197 " ccache:%p, gsscred:%p)", ctx, realm, user, "****", ktname, ccache, gsscred);
198
199 rc = krb5_cc_default(ctx, &defcc);
200 if (rc != 0) goto end;
201
202 cctype = krb5_cc_get_type(ctx, defcc);
203
204 rc = krb5_cc_new_unique(ctx, cctype, NULL, ccache);
205 if (rc != 0) goto end;
206
207 rc = krb5_build_principal(ctx, &princ, len, realm, user, NULL);
208 if (rc != 0) goto end;
209
210 rc = krb5_cc_initialize(ctx, *ccache, princ);
211 if (rc != 0) goto end;
212
213 if (password != NULL && strlen(password) > 0) {
214 rc = krb5_get_init_creds_password(ctx, &creds, princ, password,
215 0, NULL, 0, NULL, NULL);
216 if (rc != 0) goto end;
217 credsInitialized = 1;
218
219 rc = krb5_cc_store_cred(ctx, *ccache, &creds);
220 if (rc != 0) goto end;
221
222 rc = krb5_cc_get_full_name(ctx, *ccache, &cname);
223 if (rc != 0) goto end;
224
225 store.elements[store.count].key = "ccache";
226 store.elements[store.count].value = cname;
227 store.count++;
228 } else if (ktname != NULL && strlen(ktname) > 0) {
229 rc = krb5_kt_resolve(ctx, ktname, &keytab);
230 if (rc != 0) goto end;
231
232 rc = krb5_get_init_creds_keytab(ctx, &creds, princ, keytab, 0, NULL, NULL);
233 if (rc != 0) goto end;
234 credsInitialized = 1;
235
236 rc = krb5_cc_store_cred(ctx, *ccache, &creds);
237 if (rc != 0) goto end;
238
239 rc = krb5_cc_get_full_name(ctx, *ccache, &cname);
240 if (rc != 0) goto end;
241
242 store.elements[store.count].key = "client_keytab";
243 store.elements[store.count].value = ktname;
244 store.count++;
245
246 store.elements[store.count].key = "ccache";
247 store.elements[store.count].value = cname;
248 store.count++;
249
250 rc = krb5_unparse_name(ctx, princ, (char**)&pr_name.value);
251 if (rc != 0) goto end;
252 pr_name.length = strlen(pr_name.value);
253
254 major_stat = gss_import_name(&minor_stat, &pr_name,
255 GSS_KRB5_NT_PRINCIPAL_NAME, &sname);
256 if (major_stat != 0) goto end;
257 }
258
259 // Does not work with GSS-SPENGO.
260 //major_stat = gss_krb5_import_cred(&minor_stat, *ccache, princ, NULL, gsscred);
261 major_stat = gss_acquire_cred_from(&minor_stat, sname, 0, GSS_C_NO_OID_SET,
262 GSS_C_INITIATE, &store, gsscred,
263 NULL, NULL);
264
265 end:
266 if (keytab != NULL) krb5_kt_close(ctx, keytab);
267 if (princ != NULL) krb5_free_principal(ctx, princ);
268 if (credsInitialized) krb5_free_cred_contents(ctx, &creds);
269 if (defcc != NULL) krb5_cc_close(ctx, defcc);
270 if (cname != NULL) free(cname);
271 if (pr_name.value != NULL) krb5_free_unparsed_name(ctx, pr_name.value);
272 if (sname != NULL) {
273 major_stat = gss_release_name(&minor_stat, &sname);
274 }
275
276 if (rc != 0) {
277 /* Create error message with the error code. */
278 errmsg_tmp = krb5_get_error_message(ctx, rc);
279 if (errmsg != NULL && errmsg_tmp != NULL) {
280 len = strlen(errmsg_tmp) + 26;
281 *errmsg = (char *)malloc(len);
282 if (*errmsg == NULL) {
283 krb5_free_error_message(ctx, errmsg_tmp);
284 return -1;
285 }
286 snprintf(*errmsg, len,"%s. (KRB5_ERROR 0x%08x)", errmsg_tmp, rc);
287 }
288 krb5_free_error_message(ctx, errmsg_tmp);
289 }
290 if (major_stat != 0) return major_stat;
291 return rc;
292 }
293
294 static int
295 remove_krb5_cred(krb5_context ctx, krb5_ccache ccache, gss_cred_id_t *gsscred) {
296 int rc = 0;
297 unsigned int minor_stat = 0;
298
299 DEBUG("remove_krb5_cred (ctx:%p, cchache:%p, gsscred:%p)",
300 ctx, ccache, gsscred);
301 rc = gss_release_cred(&minor_stat, gsscred);
302 if (rc != 0) return minor_stat;
303
304 if (ccache != NULL) rc = krb5_cc_destroy(ctx, ccache);
305 if (ctx != NULL) krb5_free_context(ctx);
306
307 return rc;
308 }
309
310 #endif
311
312 static void
313 set_cert_policy(LDAP *ld, int cert_policy) {
314 DEBUG("set_cert_policy (ld:%p, cert_policy:%d)", ld, cert_policy);
315 ldap_set_option(ld, LDAP_OPT_X_TLS_REQUIRE_CERT, &cert_policy);
316 /* Set TLS option globally. */
317 ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &cert_policy);
318 }
319
320 #ifdef MACOSX
321
322 /* Drop in replacement for pthread_mutext_timedlock for Mac OS X system. */
323 static int
324 _pthread_mutex_timedlock(pthread_mutex_t *mutex, struct timespec *abs_timeout) {
325 int rc = -1;
326 struct timeval timenow;
327 struct timespec rest;
328
329 /* Set 10ms for sleeping time. */
330 rest.tv_sec = 0;
331 rest.tv_nsec = 10000000;
332
333 DEBUG("%s", "_pthread_mutex_timedlock");
334 while ((rc = pthread_mutex_trylock(mutex)) == EBUSY) {
335
336 gettimeofday(&timenow, NULL);
337
338 if (timenow.tv_sec > abs_timeout->tv_sec ||
339 (timenow.tv_sec == abs_timeout->tv_sec &&
340 (timenow.tv_usec * 1000) >= abs_timeout->tv_nsec)) {
341 return ETIMEDOUT;
342 }
343 /* Little sleep to avoid hammering on the lock. */
344 nanosleep(&rest, NULL);
345 }
346
347 return rc;
348 }
349 #else
350 static int
351 _pthread_mutex_timedlock(pthread_mutex_t *mutex, struct timespec *abs_timeout) {
352 DEBUG("%s", "_pthread_mutex_timedlock");
353 return pthread_mutex_timedlock(mutex, abs_timeout);
354 }
355 #endif
356
357 /* Check on the initialisation thread and set cert policy. The `misc`
358 parameter is never used (on Linux platform). The pointer of initialised
359 LDAP struct is passed to the `ld` parameter. Return 1 if the initialisation
360 thread is finished, 0 if it is still in progress, and -1 for error. */
361 int
362 _ldap_finish_init_thread(char async, XTHREAD thread, int *timeout, void *misc, LDAP **ld) {
363 int rc = 0;
364 ldapInitThreadData *val = (ldapInitThreadData *)misc;
365 struct timespec ts;
366 struct timeval now;
367 struct timespec rest;
368 int wait_msec = 100;
369 long long nanosecs = 0;
370 unsigned long long start_time, end_time;
371 int retval = 0;
372
373 /* Sanity check. */
374 if (val == NULL) return -1;
375
376 DEBUG("_ldap_finish_init_thread (async:%d, thread:%lu, timeout:%d, misc:%p)",
377 async, thread, *timeout, misc);
378 if (async) {
379 wait_msec = 100;
380 } else if (*timeout == -1) {
381 /* When no timeout is set, then set 60 seconds for waiting on thread. */
382 wait_msec = 60000;
383 } else {
384 wait_msec = *timeout;
385 }
386
387 /* Create absolute time. */
388 rc = gettimeofday(&now, NULL);
389 if (rc != 0) {
390 PyErr_BadInternalCall();
391 retval = -1;
392 goto end;
393 }
394 ts.tv_sec = now.tv_sec;
395 nanosecs = (now.tv_usec + 1000UL * wait_msec) * 1000UL;
396 while (nanosecs >= 1000000000) {
397 /* Nanosecs are over 1 second. */
398 ts.tv_sec += 1;
399 nanosecs -= 1000000000;
400 }
401 ts.tv_nsec = (long)nanosecs;
402
403 /* Waiting on thread to release the lock. */
404 rc = _pthread_mutex_timedlock(val->mux, &ts);
405
406 switch (rc) {
407 case ETIMEDOUT:
408 if (async == 0) {
409 pthread_cancel(thread);
410 set_exception(NULL, LDAP_TIMEOUT);
411 free(val->ld);
412 retval = -1;
413 goto end;
414 }
415 return 0;
416 case 0:
417 if (val->flag == 0) {
418 /* Premature locking, thread function is not finished. */
419 pthread_mutex_unlock(val->mux);
420 /* Set 5ms for sleeping time. */
421 rest.tv_sec = 0;
422 rest.tv_nsec = 5000000;
423 /* Take a nap, try to avoid constantly locking from the main thread. */
424 nanosleep(&rest, NULL);
425 if (*timeout != -1) {
426 *timeout -= 5;
427 if (*timeout < 0) *timeout = 0;
428 }
429 return 0;
430 }
431 /* Block until thread is finished, but if it's async already
432 waited enough on releasing the lock. */
433 rc = pthread_join(thread, NULL);
434 /* Thread is finished. */
435 if (val->retval != LDAP_SUCCESS) {
436 #ifdef HAVE_KRB5
437 if (val->info->errmsg != NULL) {
438 PyObject *error = get_error_by_code(0x31);
439 if (error == NULL) goto end;
440 PyErr_SetString(error, val->info->errmsg);
441 Py_DECREF(error);
442 } else {
443 set_exception(NULL, val->retval);
444 }
445 #else
446 set_exception(NULL, val->retval);
447 #endif
448 free(val->ld);
449 retval = -1;
450 goto end;
451 }
452 if (*timeout != -1) {
453 /* Calculate passed time in milliseconds. */
454 start_time = (unsigned long long)(now.tv_sec) * 1000
455 + (unsigned long long)(now.tv_usec) / 1000;
456
457 gettimeofday(&now, NULL);
458 end_time = (unsigned long long)(now.tv_sec) * 1000
459 + (unsigned long long)(now.tv_usec) / 1000;
460 /* Deduct the passed time from the overall timeout. */
461 *timeout -= (end_time - start_time);
462 if (*timeout < 0) *timeout = 0;
463 }
464 /* Set initialised LDAP struct pointer. */
465 *ld = val->ld;
466 retval = 1;
467 goto end;
468 default:
469 /* The thread is failed. */
470 PyErr_BadInternalCall();
471 retval = -1;
472 goto end;
473 }
474 end:
475 /* Clean-up. */
476 free(val->url);
477 free(val->sasl_sec_props);
478 pthread_mutex_destroy(val->mux);
479 free(val->mux);
480 free(val);
481 return retval;
482 }
483
484 int
485 _ldap_bind(LDAP *ld, ldap_conndata_t *info, char ppolicy, LDAPMessage *result, int *msgid) {
486 int rc;
487 LDAPControl **server_ctrls = NULL;
488 LDAPControl *ppolicy_ctrl = NULL;
489 struct berval passwd;
490
491 DEBUG("_ldap_bind (ld:%p, info:%p, ppolicy:%d, result:%p, msgid:%d)",
492 ld, info, ppolicy, result, *msgid);
493 if (ppolicy == 1) {
494 rc = ldap_create_passwordpolicy_control(ld, &ppolicy_ctrl);
495 if (rc != LDAP_SUCCESS) return rc;
496
497 server_ctrls = (LDAPControl **)malloc(sizeof(LDAPControl *) * (1 + 1));
498 if (server_ctrls == NULL) return LDAP_NO_MEMORY;
499
500 server_ctrls[0] = ppolicy_ctrl;
501 server_ctrls[1] = NULL;
502 }
503
504 /* Mechanism is set, use SASL interactive bind. */
505 if (strcmp(info->mech, "SIMPLE") != 0) {
506 if (info->passwd == NULL) info->passwd = "";
507 rc = ldap_sasl_interactive_bind(ld, info->binddn, info->mech, server_ctrls, NULL,
508 LDAP_SASL_QUIET, sasl_interact, info, result, &(info->rmech), msgid);
509 } else {
510 if (info->passwd == NULL) {
511 passwd.bv_len = 0;
512 } else {
513 passwd.bv_len = strlen(info->passwd);
514 }
515 passwd.bv_val = info->passwd;
516 rc = ldap_sasl_bind(ld, info->binddn, LDAP_SASL_SIMPLE, &passwd, server_ctrls,
517 NULL, msgid);
518 }
519
520 if (ppolicy_ctrl != NULL) ldap_control_free(ppolicy_ctrl);
521
522 free(server_ctrls);
523 ldap_msgfree(result);
524
525 return rc;
526 }
527
528 /* This function is based on the lutil_sasl_interact() function, which can
529 be found in the OpenLDAP liblutil's sasl.c source. I did some simplification
530 after some google and stackoverflow researches, and hoping to not cause
531 any problems. */
532 int
533 sasl_interact(LDAP *ld, unsigned flags, void *defs, void *in) {
534 sasl_interact_t *interact = (sasl_interact_t*)in;
535 const char *dflt = interact->defresult;
536 ldap_conndata_t *defaults = (ldap_conndata_t *)defs;
537
538 DEBUG("sasl_interact (ld:%p, flags:%u, defs:%p, in:%p)", ld, flags, defs, in);
539 #ifdef HAVE_KRB5
540 int rc = 0;
541 if (defaults->request_tgt == 1) {
542 rc = ldap_set_option(ld, LDAP_OPT_X_SASL_GSS_CREDS,
543 (void *)defaults->gsscred);
544 if (rc != 0) return -1;
545 }
546 #endif
547 while (interact->id != SASL_CB_LIST_END) {
548 switch(interact->id) {
549 case SASL_CB_GETREALM:
550 if (defaults) dflt = defaults->realm;
551 break;
552 case SASL_CB_AUTHNAME:
553 if (defaults) dflt = defaults->authcid;
554 break;
555 case SASL_CB_PASS:
556 if (defaults) dflt = defaults->passwd;
557 break;
558 case SASL_CB_USER:
559 if (defaults) dflt = defaults->authzid;
560 break;
561 case SASL_CB_NOECHOPROMPT:
562 break;
563 case SASL_CB_ECHOPROMPT:
564 break;
565 }
566
567 interact->result = (dflt && *dflt) ? dflt : (char*)"";
568 interact->len = strlen( (char*)interact->result );
569
570 interact++;
571 }
572 return LDAP_SUCCESS;
573 }
574
575 char *
576 _ldap_get_opt_errormsg(LDAP *ld) {
577 char *opt = NULL;
578
579 if (ld == NULL) return NULL;
580 ldap_get_option(ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, &opt);
581
582 return opt;
583 }
584
585 int
586 _ldap_parse_passwordpolicy_control(LDAP *ld, LDAPControl *ctrl,
587 ber_int_t *expire, ber_int_t *grace, unsigned int *error) {
588
589 if (ctrl == NULL) return LDAP_CONTROL_NOT_FOUND;
590
591 return ldap_parse_passwordpolicy_control(ld, ctrl, expire, grace, error);
592
593 }
594
595 void
596 _ldap_control_free(LDAPControl *ctrl) {
597 ldap_control_free(ctrl);
598 }
599
600 #endif
601
602 /* This function is based on the OpenLDAP liblutil's sasl.c source
603 file for creating a lutilSASLdefaults struct with default values based on
604 the given parameters or client's options. */
605 void *
606 create_conn_info(char *mech, SOCKET sock, PyObject *creds) {
607 ldap_conndata_t *defaults = NULL;
608 char *authcid = NULL;
609 char *authzid = NULL;
610 char *binddn = NULL;
611 char *passwd = NULL;
612 char *realm = NULL;
613 char *ktname = NULL;
614
615 DEBUG("create_conn_info (mech:%s, sock:%d, creds:%p)", mech, (int)sock, creds);
616 /* Get credential information, if it's given. */
617 if (PyDict_Check(creds)) {
618 if (strcmp(mech, "SIMPLE") == 0) {
619 binddn = PyObject2char(PyDict_GetItemString(creds, "user"));
620 } else {
621 authcid = PyObject2char(PyDict_GetItemString(creds, "user"));
622 realm = PyObject2char(PyDict_GetItemString(creds, "realm"));
623 authzid = PyObject2char(PyDict_GetItemString(creds, "authz_id"));
624 ktname = PyObject2char(PyDict_GetItemString(creds, "keytab"));
625 }
626 passwd = PyObject2char(PyDict_GetItemString(creds, "password"));
627 }
628
629 defaults = malloc(sizeof(ldap_conndata_t));
630 if (defaults == NULL) {
631 free(passwd);
632 free(binddn);
633 free(realm);
634 free(authcid);
635 free(authzid);
636 free(ktname);
637 return (void *)PyErr_NoMemory();
638 }
639
640 defaults->mech = mech ? strdup(mech) : NULL;
641 defaults->realm = realm;
642 defaults->authcid = authcid;
643 defaults->passwd = passwd;
644 defaults->authzid = authzid;
645
646 defaults->binddn = binddn;
647 #ifdef WIN32
648 defaults->thread = NULL;
649 defaults->ld = NULL;
650 defaults->sock = sock;
651 #else
652 defaults->resps = NULL;
653 defaults->nresps = 0;
654 defaults->rmech = NULL;
655 #ifdef HAVE_KRB5
656 defaults->ctx = NULL;
657 defaults->ccache = NULL;
658 defaults->gsscred = GSS_C_NO_CREDENTIAL;
659 defaults->errmsg = NULL;
660 defaults->request_tgt = 0;
661 defaults->ktname = ktname;
662 #endif
663 #endif
664
665 return defaults;
666 }
667
668 /* Dealloc an ldapConnectionInfo struct. */
669 void
670 dealloc_conn_info(ldap_conndata_t* info) {
671 DEBUG("dealloc_conn_info (info:%p)", info);
672 free(info->authcid);
673 free(info->authzid);
674 free(info->binddn);
675 free(info->mech);
676 free(info->passwd);
677 free(info->realm);
678 #ifdef HAVE_KRB5
679 if (info->gsscred != GSS_C_NO_CREDENTIAL || info->ctx != NULL) {
680 remove_krb5_cred(info->ctx, info->ccache, &(info->gsscred));
681 }
682 free(info->errmsg);
683 free(info->ktname);
684 #endif
685 free(info);
686 }
687
688 /* Thread function. The ldap_initialize function opens the LDAP client's
689 config file on Unix and ldap_start_tls_s blocks for create SSL context on Windows,
690 thus to avoid the I/O blocking in the main (Python) thread the initialisation
691 is done in a separate (POSIX and Windows) thread. A signal is sent through an
692 internal socketpair when the thread is finished, thus select() can be used on
693 the socket descriptor. */
694 #ifdef WIN32
695 static int WINAPI
696 #else
697 static void *
698 #endif
699 ldap_init_thread_func(void *params) {
700 int rc = -1;
701 const int version = LDAP_VERSION3;
702 ldapInitThreadData *data = (ldapInitThreadData *)params;
703 void *ref_opt = NULL;
704
705 DEBUG("ldap_init_thread_func (params:%p)", params);
706 if (data == NULL) {
707 #ifdef WIN32
708 return 0;
709 #else
710 return NULL;
711 #endif
712 }
713 #ifndef WIN32
714 pthread_mutex_lock(data->mux);
715 /* Lock already acquired by this thread, flag can be set now. */
716 data->flag = 1;
717 #endif
718 rc = ldap_initialize(&(data->ld), data->url);
719 if (rc != LDAP_SUCCESS) {
720 data->retval = rc;
721 goto end;
722 }
723 /* Set version to LDAPv3. */
724 ldap_set_option(data->ld, LDAP_OPT_PROTOCOL_VERSION, &version);
725 ref_opt = data->referrals ? LDAP_OPT_ON : LDAP_OPT_OFF;
726 ldap_set_option(data->ld, LDAP_OPT_REFERRALS, ref_opt);
727 if (data->cert_policy != -1) {
728 set_cert_policy(data->ld, data->cert_policy);
729 }
730 #ifndef WIN32
731 /* SASL security poperties settings on available on Unix. */
732 if (data->sasl_sec_props != NULL) {
733 DEBUG("set sasl sec properties: %s", data->sasl_sec_props);
734 rc = ldap_set_option(data->ld, LDAP_OPT_X_SASL_SECPROPS, (void *)data->sasl_sec_props);
735 if (rc != LDAP_SUCCESS) {
736 data->retval = rc;
737 goto end;
738 }
739 }
740 #endif
741
742 #if !defined(WIN32) && LDAP_VENDOR_VERSION > 20443
743 /* The asynchronous connection build only works on unix systems from
744 version 2.4.44 */
745 DEBUG("set connecting async: %d", _g_asyncmod);
746 if (_g_asyncmod) {
747 struct timeval tv;
748 tv.tv_sec = 0;
749 /* Set asynchronous connect for OpenLDAP. */
750 ldap_set_option(data->ld, LDAP_OPT_CONNECT_ASYNC, LDAP_OPT_ON);
751 ldap_set_option(data->ld, LDAP_OPT_NETWORK_TIMEOUT, &tv);
752 }
753 #endif
754
755 #ifdef HAVE_KRB5
756 if (data->info->request_tgt == 1) {
757 rc = create_krb5_cred(data->info->ctx, data->info->realm,
758 data->info->authcid, data->info->passwd, data->info->ktname,
759 &(data->info->ccache), &(data->info->gsscred),
760 &(data->info->errmsg));
761 if (rc != 0) {
762 data->retval = rc;
763 }
764 }
765 #endif
766 end:
767 if (data->sock != -1) {
768 /* Send a signal through an internal socketpair. */
769 if (send(data->sock, "s", 1, 0) == -1) {
770 /* Signalling is failed. */
771 data->retval = -1;
772 }
773 }
774 DEBUG("ldap_init_thread_func [retval:%d]", data->retval);
775 #ifdef WIN32
776 return 0;
777 #else
778 pthread_mutex_unlock(data->mux);
779 return NULL;
780 #endif
781 }
782
783 /* Create a platform-independent initialisation thread.
784 On success it returns 0 and sets the thread parameter,
785 on failure returns -1.
786 */
787 int
788 create_init_thread(void *param, ldap_conndata_t *info, XTHREAD *thread) {
789 int rc = 0;
790 ldapInitThreadData *data = (ldapInitThreadData *)param;
791
792 DEBUG("create_init_thread (ld:%p, info:%p, thread:%lu)", param, info, *thread);
793 #ifdef WIN32
794 *thread = CreateThread(NULL, 0, ldap_init_thread_func, (void *)data, 0, NULL);
795 if (*thread == NULL) rc = -1;
796 #else
797 data->mux = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
798 if (data->mux == NULL) {
799 PyErr_NoMemory();
800 return -1;
801 }
802
803 rc = pthread_mutex_init(data->mux, NULL);
804 if (rc != 0) {
805 PyErr_BadInternalCall();
806 return -1;
807 }
808 pthread_mutex_lock(data->mux);
809 data->flag = 0;
810 #ifdef HAVE_KRB5
811 data->info = info;
812 if (data->info->mech != NULL && (strcmp("GSSAPI", data->info->mech) == 0 ||
813 strcmp("GSS-SPNEGO", data->info->mech) == 0)
814 && data->info->realm != NULL && strlen(data->info->realm) != 0
815 && data->info->authcid != NULL && strlen(data->info->authcid) != 0) {
816 data->info->request_tgt = 1;
817 rc = krb5_init_context(&(data->info->ctx));
818 if (rc != 0) return -1;
819 }
820 #endif
821 pthread_mutex_unlock(data->mux);
822
823 rc = pthread_create(thread, NULL, ldap_init_thread_func, data);
824 #endif
825 if (rc != 0) return -1;
826
827 return 0;
828 }
829
830 /* Create an LDAP_SERVER_EXTENDED_DN control. */
831 int _ldap_create_extended_dn_control(LDAP *ld, int format, LDAPControl **edn_ctrl) {
832 int rc = -1;
833 BerElement *ber = NULL;
834 struct berval *value = NULL;
835 LDAPControl *ctrl = NULL;
836
837 ber = ber_alloc_t(LBER_USE_DER);
838 if (ber == NULL) return LDAP_NO_MEMORY;
839
840 /* Transcode the data into a berval struct. */
841 ber_printf(ber, "{i}", format);
842 rc = ber_flatten(ber, &value);
843 ber_free(ber, 1);
844 if (rc != 0) return rc;
845
846 rc = ldap_control_create(LDAP_SERVER_EXTENDED_DN_OID, 0, value, 1, &ctrl);
847 ber_bvfree(value);
848
849 if (rc != LDAP_SUCCESS) return rc;
850
851 *edn_ctrl = ctrl;
852 return LDAP_SUCCESS;
853 }
854
855 /* Create an LDAP_SERVER_SD_FLAGS control. */
856 int _ldap_create_sd_flags_control(LDAP *ld, int flags, LDAPControl **edn_ctrl) {
857 int rc = -1;
858 BerElement *ber = NULL;
859 struct berval *value = NULL;
860 LDAPControl *ctrl = NULL;
861
862 ber = ber_alloc_t(LBER_USE_DER);
863 if (ber == NULL) return LDAP_NO_MEMORY;
864
865 /* Transcode the data into a berval struct. */
866 ber_printf(ber, "{i}", flags);
867 rc = ber_flatten(ber, &value);
868 ber_free(ber, 1);
869 if (rc != 0) return rc;
870
871 rc = ldap_control_create(LDAP_SERVER_SD_FLAGS_OID, 0, value, 1, &ctrl);
872 ber_bvfree(value);
873
874 if (rc != LDAP_SUCCESS) return rc;
875
876 *edn_ctrl = ctrl;
877 return LDAP_SUCCESS;
878 }