liquid_feedback_frontend
view lib/mldap/mldap.c @ 1640:15bde6a79d41
Added TLS support for ldap
author | bsw |
---|---|
date | Tue Feb 09 17:40:50 2021 +0100 (2021-02-09) |
parents | 39bf0af7f5e3 |
children | ab837b075cf7 |
line source
1 /*
2 * minimalistic Lua LDAP interface library
3 *
4 * The library does not set any global variable itself and must thus be
5 * loaded with
6 *
7 * mldap = require("mldap")
8 *
9 * or a similar statement.
10 *
11 * The library provides two functions, conn = bind{...} and unbind(conn)
12 * to connect to and disconnect from the LDAP server respectively. The
13 * unbind function is also provided as a method of the connection userdata
14 * object (see below).
15 *
16 * The arguments to the bind{...} function are documented in the source code
17 * (see C function mldap_bind). In case of success, the bind function returns
18 * a userdata object that provides two methods: query{...} and unbind(). In
19 * case of error, the bind function returns nil as first return value, an
20 * error string as second return value, and a numeric error code as third
21 * return value. A positive error code is an LDAP resultCode, a negative
22 * error code is an OpenLDAP API error code:
23 *
24 * connection, error_string, numeric_error_code = mldap.bind{...}
25 *
26 * For translating numeric error codes to an identifying (machine readable)
27 * string identifier, the library provides in addition to the two functions
28 * a table named 'errorcodes', for example:
29 *
30 * 49 == mldap.errorcodes["invalid_credentials"]
31 *
32 * and
33 *
34 * mldap.errorcodes[49] == "invalid_credentials"
35 *
36 * The arguments and return value of the query{...} method of the connection
37 * userdata object are also documented in the source code below (see
38 * C function mldap_query). Error conditions are reported the same way as the
39 * bind{...} function does.
40 *
41 * To close the connection, either the unbind() function of the library or
42 * the unbind() method can be called; it is allowed to call them multiple
43 * times, and they are also invoked by the garbage collector.
44 *
45 */
47 // Lua header inclusions:
48 #include <lua.h>
49 #include <lauxlib.h>
51 // OpenLDAP header inclusions:
52 #include <ldap.h>
54 // Standard C inclusions:
55 #include <stdlib.h>
56 #include <stdbool.h>
57 #include <unistd.h>
59 // Error code translation is included from separate C file:
60 #include "mldap_errorcodes.c"
62 // Provide compatibility with Lua 5.1:
63 #if LUA_VERSION_NUM < 502
64 #define luaL_newlib(L, t) lua_newtable((L)); luaL_register(L, NULL, t)
65 #define lua_rawlen lua_objlen
66 #define lua_len lua_objlen
67 #define luaL_setmetatable(L, regkey) \
68 lua_getfield((L), LUA_REGISTRYINDEX, (regkey)); \
69 lua_setmetatable((L), -2);
70 #endif
72 // prefix for all Lua registry entries of this library:
73 #define MLDAP_REGKEY "556aeaf3c864af2e_mldap_"
76 static const char *mldap_get_named_string_arg(
77 // gets a named argument of type "string" from a table at the given stack position
79 lua_State *L, // pointer to lua_State variable
80 int idx, // stack index of the table containing the named arguments
81 const char *argname, // name of the argument
82 int mandatory // if not 0, then the argument is mandatory and an error is raised if it isn't found
84 // leaves the string as new element on top of the stack
85 ) {
87 // pushes the table entry with the given argument name on top of the stack:
88 lua_getfield(L, idx, argname);
90 // check, if the entry is nil or false:
91 if (!lua_toboolean(L, -1)) {
93 // throw error, if named argument is mandatory:
94 if (mandatory) return luaL_error(L, "Named argument '%s' missing", argname), NULL;
96 // return NULL pointer, if named argument is not mandatory:
97 return NULL;
99 }
101 // throw error, if the value of the argument is not string:
102 if (lua_type(L, -1) != LUA_TSTRING) return luaL_error(L, "Named argument '%s' is not a string", argname), NULL;
104 // return a pointer to the string, leaving the string on top of the stack to avoid garbage collection:
105 return lua_tostring(L, -1);
107 // leaves one element on the stack
108 }
111 static int mldap_get_named_number_arg(
112 // gets a named argument of type "number" from a table at the given stack position
114 lua_State *L, // pointer to lua_State variable
115 int idx, // stack index of the table containing the named arguments
116 const char *argname, // name of the argument
117 int mandatory, // if not 0, then the argument is mandatory and an error is raised if it isn't found
118 lua_Number default_value // default value to return, if the argument is not mandatory and nil or false
120 // opposed to 'mldap_get_named_string_arg', this function leaves no element on the stack
121 ) {
123 lua_Number value; // value to return
125 // pushes the table entry with the given argument name on top of the stack:
126 lua_getfield(L, idx, argname);
128 // check, if the entry is nil or false:
129 if (lua_isnil(L, -1)) {
131 // throw error, if named argument is mandatory:
132 if (mandatory) return luaL_error(L, "Named argument '%s' missing", argname), 0;
134 // set default value as return value, if named argument is not mandatory:
135 value = default_value;
137 } else {
139 // throw error, if the value of the argument is not a number:
140 if (lua_type(L, -1) != LUA_TNUMBER) return luaL_error(L, "Named argument '%s' is not a number", argname), 0;
142 // set return value to the number:
143 value = lua_tonumber(L, -1);
145 }
147 // remove unnecessary element from stack (not needed to avoid garbage collection):
148 return value;
150 // leaves no new elements on the stack
151 }
154 static bool mldap_get_named_boolean_arg(
155 // gets a named argument of type "boolean" from a table at the given stack position
157 lua_State *L, // pointer to lua_State variable
158 int idx, // stack index of the table containing the named arguments
159 const char *argname, // name of the argument
160 int mandatory, // if not 0, then the argument is mandatory and an error is raised if it isn't found
161 bool default_value // default value to return, if the argument is not mandatory and nil
163 // opposed to 'mldap_get_named_string_arg', this function leaves no element on the stack
164 ) {
166 bool value; // value to return
168 // pushes the table entry with the given argument name on top of the stack:
169 lua_getfield(L, idx, argname);
171 // check, if the entry is nil:
172 if (lua_isnil(L, -1)) {
174 // throw error, if named argument is mandatory:
175 if (mandatory) return luaL_error(L, "Named argument '%s' missing", argname), 0;
177 // set default value as return value, if named argument is not mandatory:
178 value = default_value;
180 } else {
182 // throw error, if the value of the argument is not a number:
183 if (lua_type(L, -1) != LUA_TBOOLEAN) return luaL_error(L, "Named argument '%s' is not a boolean", argname), 0;
185 // set return value to the number:
186 value = lua_toboolean(L, -1);
188 }
190 // remove unnecessary element from stack (not needed to avoid garbage collection):
191 lua_pop(L, 1);
193 return value;
195 // leaves no new elements on the stack
196 }
199 static int mldap_scope(
200 // converts a string ("base", "onelevel", "subtree", "children") to an integer representing the LDAP scope
201 // and throws an error for any unknown string
203 lua_State *L, // pointer to lua_State variable (needed to throw errors)
204 const char *scope_string // string that is either ("base", "onelevel", "subtree", "children")
206 // does not affect or use the Lua stack at all
207 ) {
209 // return integer according to string value:
210 if (!strcmp(scope_string, "base")) return LDAP_SCOPE_BASE;
211 if (!strcmp(scope_string, "onelevel")) return LDAP_SCOPE_ONELEVEL;
212 if (!strcmp(scope_string, "subtree")) return LDAP_SCOPE_SUBTREE;
213 if (!strcmp(scope_string, "children")) return LDAP_SCOPE_CHILDREN;
215 // throw error for unknown string values:
216 return luaL_error(L, "Invalid LDAP scope: '%s'", scope_string), 0;
218 }
221 static int mldap_bind(lua_State *L) {
222 // Lua C function that takes named arguments as a table
223 // and returns a userdata object, representing the LDAP connection
224 // or returns nil, an error string, and an error code (integer) on error
226 // named arguments:
227 // "uri" (string) server URI to connect to
228 // "who" (string) DN to bind as
229 // "password" (string) password for DN to bind as
230 // "timeout" (number) timeout in seconds
231 // "tls" (boolean) use TLS
233 static const int ldap_version = LDAP_VERSION3; // providing a pointer (&ldap_version) to set LDAP protocol version 3
234 const char *uri; // C string for "uri" argument
235 bool tls; // boolean indicating if TLS is to be used
236 const char *who; // C string for "who" argument
237 struct berval cred; // credentials ("password") are stored as struct berval
238 lua_Number timeout_float; // float (lua_Number) for timeout
239 struct timeval timeout; // timeout is stored as struct timeval
240 int ldap_error; // LDAP error code (as returned by libldap calls)
241 LDAP *ldp; // pointer to an opaque OpenLDAP structure representing the connection
242 LDAP **ldp_ptr; // pointer to a Lua userdata structure (that only contains the 'ldp' pointer)
244 // throw error if first argument is not a table:
245 if (lua_type(L, 1) != LUA_TTABLE) {
246 luaL_error(L, "Argument to function 'bind' is not a table.");
247 }
249 // extract arguments:
250 uri = mldap_get_named_string_arg(L, 1, "uri", true);
251 tls = mldap_get_named_boolean_arg(L, 1, "tls", false, false);
252 who = mldap_get_named_string_arg(L, 1, "who", false);
253 cred.bv_val = (char *)mldap_get_named_string_arg(L, 1, "password", false);
254 // use (char *) cast to suppress compiler warning (should be const anyway)
255 if (cred.bv_val) cred.bv_len = strlen(cred.bv_val);
256 else cred.bv_len = 0;
257 timeout_float = mldap_get_named_number_arg(L, 1, "timeout", false, -1);
258 timeout.tv_sec = timeout_float;
259 timeout.tv_usec = (timeout_float - timeout.tv_sec) * 1000000;
261 // initialize OpenLDAP structure and provide URI for connection:
262 ldap_error = ldap_initialize(&ldp, uri);
263 // on error, jump to label "mldap_queryconn_error1", as no ldap_unbind_ext_s() is needed:
264 if (ldap_error != LDAP_SUCCESS) goto mldap_queryconn_error1;
266 // set LDAP protocol version 3:
267 ldap_error = ldap_set_option(ldp, LDAP_OPT_PROTOCOL_VERSION, &ldap_version);
268 // on error, jump to label "mldap_queryconn_error2", as ldap_unbind_ext_s() must be called:
269 if (ldap_error != LDAP_SUCCESS) goto mldap_queryconn_error2;
271 // set timeout for asynchronous OpenLDAP library calls:
272 ldap_error = ldap_set_option(ldp, LDAP_OPT_TIMEOUT, &timeout);
273 // on error, jump to label "mldap_queryconn_error2", as ldap_unbind_ext_s() must be called:
274 if (ldap_error != LDAP_SUCCESS) goto mldap_queryconn_error2;
276 // initiate TLS if requested
277 if (tls) {
278 ldap_error = ldap_start_tls_s(ldp, NULL, NULL);
279 if (ldap_error != LDAP_SUCCESS) goto mldap_queryconn_error2;
280 }
282 // connect to LDAP server:
283 ldap_error = ldap_sasl_bind_s(
284 ldp, // pointer to opaque OpenLDAP structure representing the connection
285 who, // DN to bind as
286 LDAP_SASL_SIMPLE, // SASL mechanism "simple" for password authentication
287 &cred, // password as struct berval
288 NULL, // no server controls
289 NULL, // no client controls
290 NULL // do not store server credentials
291 );
293 // error handling:
294 if (ldap_error != LDAP_SUCCESS) {
296 // error label to jump to, if a call of ldap_unbind_ext_s() is required:
297 mldap_queryconn_error2:
299 // close connection and free resources:
300 ldap_unbind_ext_s(ldp, NULL, NULL);
302 // error label to jump to, if no call of ldap_unbind_ext_s() is required:
303 mldap_queryconn_error1:
305 // return three values:
306 lua_pushnil(L); // return nil as first value
307 lua_pushstring(L, ldap_err2string(ldap_error)); // return error string as second value
308 lua_pushinteger(L, ldap_error); // return error code (integer) as third value
309 return 3;
311 }
313 // create new Lua userdata object (that will contain the 'ldp' pointer) on top of stack:
314 ldp_ptr = lua_newuserdata(L, sizeof(LDAP *));
316 // set metatable of Lua userdata object:
317 luaL_setmetatable(L, MLDAP_REGKEY "connection_metatable");
319 // write contents of Lua userdata object (the 'ldp' pointer):
320 *ldp_ptr = ldp;
322 // return Lua userdata object from top of stack:
323 return 1;
325 }
328 static int mldap_search(lua_State *L) {
329 // Lua C function used as "search" method of Lua userdata object representing the LDAP connection
330 // that takes a Lua userdata object (the LDAP connection) as first argument,
331 // a table with named arguments as second argument,
332 // and returns a result table on success (see below)
333 // or returns nil, an error string, and an error code (integer) on error
335 // named arguments:
336 // "base" (string) DN of the entry at which to start the search
337 // "scope" (string) scope of the search, one of:
338 // "base" to search the object itself
339 // "onelevel" to search the object's immediate children
340 // "subtree" to search the object and all its descendants
341 // "children" to search all of the descendants
342 // "filter" (string) string representation of the filter to apply in the search
343 // (conforming to RFC 4515 as extended in RFC 4526)
344 // "attrs" (table) list of attribute descriptions (each a string) to return from matching entries
346 // structure of result table:
347 // {
348 // { dn = <distinguished name (DN)>,
349 // <attr1> = { <value1>, <value2>, ... },
350 // <attr2> = { <value1>, <value2>, ... },
351 // ...
352 // },
353 // { dn = <distinguished name (DN)>,
354 // <attr1> = { <value1>, <value2>, ... },
355 // <attr2> = { <value1>, <value2>, ... },
356 // ...
357 // },
358 // ...
359 // }
361 const char *base; // C string for "base" argument
362 const char *scope_string; // C string for "scope" argument
363 int scope; // integer representing the scope
364 const char *filter; // C string for "filter" argument
365 size_t nattrs; // number of attributes in "attrs" argument
366 const char **attrs; // C string array of "attrs" argument
367 size_t attr_idx; // index variable for building the C string array of "attrs"
368 int ldap_error; // LDAP error code (as returned by libldap calls)
369 LDAP **ldp_ptr; // pointer to a pointer to the OpenLDAP structure representing the connection
370 LDAPMessage *res; // pointer to the result of ldap_search_ext_s() call
371 LDAPMessage *ent; // pointer to an entry in the result of ldap_search_ext_s() call
372 int i; // integer to fill the Lua table returned as result
374 // truncate the Lua stack to 2 elements:
375 lua_settop(L, 2);
377 // check if the first argument is a Lua userdata object with the correct metatable
378 // and get a C pointer to that userdata object:
379 ldp_ptr = luaL_checkudata(L, 1, MLDAP_REGKEY "connection_metatable");
381 // throw an error, if the connection has already been closed:
382 if (!*ldp_ptr) {
383 return luaL_error(L, "LDAP connection has already been closed");
384 }
386 // check if the second argument is a table, and throw an error if it's not a table:
387 if (lua_type(L, 2) != LUA_TTABLE) {
388 luaL_error(L, "Argument to function 'bind' is not a table.");
389 }
391 // extract named arguments (requires memory allocation for 'attrs'):
392 base = mldap_get_named_string_arg(L, 2, "base", true); // pushed to 3
393 scope_string = mldap_get_named_string_arg(L, 2, "scope", true); // pushed to 4
394 scope = mldap_scope(L, scope_string);
395 lua_pop(L, 1); // removes stack element 4
396 filter = mldap_get_named_string_arg(L, 2, "filter", false); // pushed to 4
397 lua_getfield(L, 2, "attrs"); // pushed to 5
398 nattrs = luaL_len(L, -1);
399 attrs = calloc(nattrs + 1, sizeof(char *)); // memory allocation, +1 for terminating NULL
400 if (!attrs) return luaL_error(L, "Memory allocation error in C function 'mldap_queryconn'");
401 for (attr_idx=0; attr_idx<nattrs; attr_idx++) {
402 lua_pushinteger(L, attr_idx+1);
403 lua_gettable(L, 5); // pushed onto variable stack position
404 if (lua_type(L, -1) != LUA_TSTRING) {
405 free(attrs);
406 return luaL_error(L, "Element in attribute list is not a string");
407 }
408 attrs[attr_idx] = lua_tostring(L, -1);
409 }
410 // attrs[nattrs] = NULL; // unnecessary due to calloc
412 // execute LDAP search and store pointer to the result in 'res':
413 ldap_error = ldap_search_ext_s(
414 *ldp_ptr, // pointer to the opaque OpenLDAP structure representing the connection
415 base, // DN of the entry at which to start the search
416 scope, // scope of the search
417 filter, // string representation of the filter to apply in the search
418 (char **)attrs, // array of attribute descriptions (array of strings)
419 // cast to suppress compiler warning (should be const anyway)
420 0, // do not only request attribute descriptions but also values
421 NULL, // no server controls
422 NULL, // no client controls
423 NULL, // do not set another timeout
424 0, // no sizelimit
425 &res // store result in 'res'
426 );
428 // free data structures that have been allocated for the 'attrs' array:
429 free(attrs);
431 // return nil, an error string, and an error code (integer) in case of error:
432 if (ldap_error != LDAP_SUCCESS) {
433 lua_pushnil(L);
434 lua_pushstring(L, ldap_err2string(ldap_error));
435 lua_pushinteger(L, ldap_error);
436 return 3;
437 }
439 // clear Lua stack:
440 lua_settop(L, 0);
442 // create result table for all entries at stack position 1:
443 lua_newtable(L);
445 // use ldap_first_entry() and ldap_next_entry() functions
446 // to iterate through all entries in the result 'res'
447 // and count 'i' from 1 up:
448 for (
449 ent=ldap_first_entry(*ldp_ptr, res), i=1;
450 ent;
451 ent=ldap_next_entry(*ldp_ptr, ent), i++
452 ) {
454 char *attr; // name of attribute
455 BerElement *ber; // structure to iterate through attributes
456 char *dn; // LDAP entry name (distinguished name)
458 // create result table for one entry at stack position 2:
459 lua_newtable(L);
461 // use ldap_first_attribute() and ldap_next_attribute()
462 // as well as 'BerElement *ber' to iterate through all attributes
463 // ('ber' must be free'd with ber_free(ber, 0) call later):
464 for (
465 attr=ldap_first_attribute(*ldp_ptr, ent, &ber);
466 attr;
467 attr=ldap_next_attribute(*ldp_ptr, ent, ber)
468 ) {
470 struct berval **vals; // pointer to (first element of) array of values
471 struct berval **val; // pointer to a value represented as 'struct berval' structure
472 int j; // integer to fill a Lua table
474 // push the attribute name to Lua stack position 3:
475 lua_pushstring(L, attr);
477 // create a new table for the attribute's values on Lua stack position 4:
478 lua_newtable(L);
480 // call ldap_get_values_len() to obtain the values
481 // (required to be free'd later with ldap_value_free_len()):
482 vals = ldap_get_values_len(*ldp_ptr, ent, attr);
484 // iterate through values and count 'j' from 1 up:
485 for (val=vals, j=1; *val; val++, j++) {
487 // push value to Lua stack position 5:
488 lua_pushlstring(L, (*val)->bv_val, (*val)->bv_len);
490 // pop value from Lua stack position 5
491 // and store it in table on Lua stack position 4:
492 lua_rawseti(L, 4, j);
494 }
496 // free data structure of values:
497 ldap_value_free_len(vals);
499 // pop attribute name from Lua stack position 3
500 // and pop value table from Lua stack position 4
501 // and store them in result table for entry at Lua stack position 2:
502 lua_settable(L, 2);
504 }
506 // free 'BerElement *ber' stucture that has been used to iterate through all attributes
507 // (second argument is zero due to manpage of ldap_first_attribute()):
508 ber_free(ber, 0);
510 // store distinguished name (DN) on Lua stack position 3
511 // (aquired memory is free'd with ldap_memfree()):
512 dn = ldap_get_dn(*ldp_ptr, ent);
513 lua_pushstring(L, dn);
514 ldap_memfree(dn);
516 // pop distinguished name (DN) from Lua stack position 3
517 // and store it in field "dn" of entry result table at stack position 2
518 lua_setfield(L, 2, "dn");
520 // pop entry result table from Lua stack position 2
521 // and store it in table at stack position 1:
522 lua_rawseti(L, 1, i);
524 }
526 // return result table from top of Lua stack (stack position 1):
527 return 1;
529 }
531 static int mldap_unbind(lua_State *L) {
532 // Lua C function used as "unbind" function of module and "unbind" method of Lua userdata object
533 // closing the LDAP connection (if still open)
534 // returning nothing
536 LDAP **ldp_ptr; // pointer to a pointer to the OpenLDAP structure representing the connection
538 // check if the first argument is a Lua userdata object with the correct metatable
539 // and get a C pointer to that userdata object:
540 ldp_ptr = luaL_checkudata(L, 1, MLDAP_REGKEY "connection_metatable");
542 // check if the Lua userdata object still contains a pointer:
543 if (*ldp_ptr) {
545 // if it does, then call ldap_unbind_ext_s():
546 ldap_unbind_ext_s(
547 *ldp_ptr, // pointer to the opaque OpenLDAP structure representing the connection
548 NULL, // no server controls
549 NULL // no client controls
550 );
552 // store NULL pointer in Lua userdata to mark connection as closed
553 *ldp_ptr = NULL;
554 }
556 // returning nothing:
557 return 0;
559 }
562 // registration information for library functions:
563 static const struct luaL_Reg mldap_module_functions[] = {
564 {"bind", mldap_bind},
565 {"unbind", mldap_unbind},
566 {NULL, NULL}
567 };
570 // registration information for methods of connection object:
571 static const struct luaL_Reg mldap_connection_methods[] = {
572 {"search", mldap_search},
573 {"unbind", mldap_unbind},
574 {NULL, NULL}
575 };
578 // registration information for connection metatable:
579 static const struct luaL_Reg mldap_connection_metamethods[] = {
580 {"__gc", mldap_unbind},
581 {NULL, NULL}
582 };
585 // luaopen function to initialize/register library:
586 int luaopen_mldap(lua_State *L) {
588 // clear Lua stack:
589 lua_settop(L, 0);
591 // create table with library functions on Lua stack position 1:
592 luaL_newlib(L, mldap_module_functions);
594 // create metatable for connection objects on Lua stack position 2:
595 luaL_newlib(L, mldap_connection_metamethods);
597 // create table with methods for connection object on Lua stack position 3:
598 luaL_newlib(L, mldap_connection_methods);
600 // pop table with methods for connection object from Lua stack position 3
601 // and store it as "__index" in metatable:
602 lua_setfield(L, 2, "__index");
604 // pop table with metatable for connection objects from Lua stack position 2
605 // and store it in the Lua registry:
606 lua_setfield(L, LUA_REGISTRYINDEX, MLDAP_REGKEY "connection_metatable");
608 // create table for error code mappings on Lua stack position 2:
609 lua_newtable(L);
611 // fill table for error code mappings
612 // that maps integer error codes to error code strings
613 // and vice versa:
614 mldap_set_errorcodes(L);
616 // pop table for error code mappings from Lua stack position 2
617 // and store it as "errorcodes" in table with library functions:
618 lua_setfield(L, 1, "errorcodes");
620 // return table with library functions from top of Lua stack:
621 return 1;
623 }