2 * This program is is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License, version 2 if the
4 * License as published by the Free Software Foundation.
6 * This program is distributed in the hope that it will be useful,
7 * but WITHOUT ANY WARRANTY; without even the implied warranty of
8 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 * GNU General Public License for more details.
11 * You should have received a copy of the GNU General Public License
12 * along with this program; if not, write to the Free Software
13 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 * @brief Implements SQL 'users' file, and SQL accounting.
21 * @copyright 2012 Arran Cudbard-Bell <a.cudbardb@freeradius.org>
22 * @copyright 2000,2006 The FreeRADIUS server project
23 * @copyright 2000 Mike Machado <mike@innercite.com>
24 * @copyright 2000 Alan DeKok <aland@ox.org>
30 #include <freeradius-devel/radiusd.h>
31 #include <freeradius-devel/modules.h>
32 #include <freeradius-devel/token.h>
33 #include <freeradius-devel/rad_assert.h>
40 * So we can do pass2 xlat checks on the queries.
42 static const CONF_PARSER query_config[] = {
44 { "query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT | PW_TYPE_MULTI, rlm_sql_config_t, accounting.query), NULL },
46 {NULL, -1, 0, NULL, NULL}
50 * For now hard-code the subsections. This isn't perfect, but it
51 * helps the average case.
53 static const CONF_PARSER type_config[] = {
55 { "accounting-on", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) query_config },
56 { "accounting-off", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) query_config },
57 { "start", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) query_config },
58 { "interim-update", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) query_config },
59 { "stop", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) query_config },
61 {NULL, -1, 0, NULL, NULL}
66 static const CONF_PARSER acct_config[] = {
67 { "reference", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, accounting.reference), ".query" },
68 { "logfile", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, accounting.logfile), NULL },
70 { "type", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) type_config },
72 {NULL, -1, 0, NULL, NULL}
75 static const CONF_PARSER postauth_config[] = {
76 { "reference", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, postauth.reference), ".query" },
77 { "logfile", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, postauth.logfile), NULL },
79 { "query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT | PW_TYPE_MULTI, rlm_sql_config_t, postauth.query), NULL },
81 {NULL, -1, 0, NULL, NULL}
84 static const CONF_PARSER module_config[] = {
85 { "driver", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_driver_name), "rlm_sql_null" },
86 { "server", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_server), "localhost" },
87 { "port", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_port), "" },
88 { "login", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_login), "" },
89 { "password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, rlm_sql_config_t, sql_password), "" },
90 { "radius_db", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_db), "radius" },
91 { "read_groups", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_sql_config_t, read_groups), "yes" },
92 { "read_profiles", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_sql_config_t, read_profiles), "yes" },
93 { "readclients", FR_CONF_OFFSET(PW_TYPE_BOOLEAN | PW_TYPE_DEPRECATED, rlm_sql_config_t, do_clients), NULL },
94 { "read_clients", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_sql_config_t, do_clients), "no" },
95 { "deletestalesessions", FR_CONF_OFFSET(PW_TYPE_BOOLEAN | PW_TYPE_DEPRECATED, rlm_sql_config_t, deletestalesessions), NULL },
96 { "delete_stale_sessions", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_sql_config_t, deletestalesessions), "yes" },
97 { "sql_user_name", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, query_user), "" },
98 { "logfile", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, logfile), NULL },
99 { "default_user_profile", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, default_profile), "" },
100 { "nas_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_DEPRECATED, rlm_sql_config_t, client_query), NULL },
101 { "client_query", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, client_query), "SELECT id,nasname,shortname,type,secret FROM nas" },
102 { "open_query", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, open_query), NULL },
104 { "authorize_check_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, authorize_check_query), NULL },
105 { "authorize_reply_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, authorize_reply_query), NULL },
107 { "authorize_group_check_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, authorize_group_check_query), "" },
108 { "authorize_group_reply_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, authorize_group_reply_query), "" },
109 { "group_membership_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, groupmemb_query), NULL },
110 #ifdef WITH_SESSION_MGMT
111 { "simul_count_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, simul_count_query), "" },
112 { "simul_verify_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, simul_verify_query), "" },
114 { "safe-characters", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_DEPRECATED, rlm_sql_config_t, allowed_chars), NULL },
115 { "safe_characters", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, allowed_chars), "@abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_: /" },
118 * This only works for a few drivers.
120 { "query_timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, rlm_sql_config_t, query_timeout), NULL },
122 { "accounting", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) acct_config },
124 { "post-auth", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) postauth_config },
126 {NULL, -1, 0, NULL, NULL}
130 * Fall-Through checking function from rlm_files.c
132 static sql_fall_through_t fall_through(VALUE_PAIR *vp)
135 tmp = pairfind(vp, PW_FALL_THROUGH, 0, TAG_ANY);
137 return tmp ? tmp->vp_integer : FALL_THROUGH_DEFAULT;
143 static int generate_sql_clients(rlm_sql_t *inst);
144 static size_t sql_escape_func(REQUEST *, char *out, size_t outlen, char const *in, void *arg);
149 * For selects the first value of the first column will be returned,
150 * for inserts, updates and deletes the number of rows affected will be
153 static ssize_t sql_xlat(void *instance, REQUEST *request, char const *query, char *out, size_t freespace)
155 rlm_sql_handle_t *handle = NULL;
157 rlm_sql_t *inst = instance;
162 * Add SQL-User-Name attribute just in case it is needed
163 * We could search the string fmt for SQL-User-Name to see if this is
166 sql_set_user(inst, request, NULL);
168 handle = sql_get_socket(inst);
173 rlm_sql_query_log(inst, request, NULL, query);
176 * If the query starts with any of the following prefixes,
177 * then return the number of rows affected
179 if ((strncasecmp(query, "insert", 6) == 0) ||
180 (strncasecmp(query, "update", 6) == 0) ||
181 (strncasecmp(query, "delete", 6) == 0)) {
183 char buffer[21]; /* 64bit max is 20 decimal chars + null byte */
185 if (rlm_sql_query(&handle, inst, query) != RLM_SQL_OK) {
186 char const *error = (inst->module->sql_error)(handle, inst->config);
187 REDEBUG("SQL query failed: %s", error);
193 numaffected = (inst->module->sql_affected_rows)(handle, inst->config);
194 if (numaffected < 1) {
195 RDEBUG("SQL query affected no rows");
201 * Don't chop the returned number if freespace is
202 * too small. This hack is necessary because
203 * some implementations of snprintf return the
204 * size of the written data, and others return
205 * the size of the data they *would* have written
206 * if the output buffer was large enough.
208 snprintf(buffer, sizeof(buffer), "%d", numaffected);
210 len = strlen(buffer);
211 if (len >= freespace){
212 RDEBUG("rlm_sql (%s): Can't write result, insufficient string space", inst->config->xlat_name);
214 (inst->module->sql_finish_query)(handle, inst->config);
220 memcpy(out, buffer, len + 1); /* we did bounds checking above */
223 (inst->module->sql_finish_query)(handle, inst->config);
226 } /* else it's a SELECT statement */
228 if (rlm_sql_select_query(&handle, inst, query) != RLM_SQL_OK){
229 char const *error = (inst->module->sql_error)(handle, inst->config);
230 REDEBUG("SQL query failed: %s", error);
236 ret = rlm_sql_fetch_row(&handle, inst);
238 REDEBUG("SQL query failed");
239 (inst->module->sql_finish_select_query)(handle, inst->config);
247 RDEBUG("SQL query returned no results");
248 (inst->module->sql_finish_select_query)(handle, inst->config);
255 RDEBUG("NULL value in first column of result");
256 (inst->module->sql_finish_select_query)(handle, inst->config);
262 len = strlen(row[0]);
263 if (len >= freespace){
264 RDEBUG("Insufficient string space");
265 (inst->module->sql_finish_select_query)(handle, inst->config);
271 strlcpy(out, row[0], freespace);
274 (inst->module->sql_finish_select_query)(handle, inst->config);
277 sql_release_socket(inst, handle);
282 static int generate_sql_clients(rlm_sql_t *inst)
284 rlm_sql_handle_t *handle;
289 DEBUG("rlm_sql (%s): Processing generate_sql_clients",
290 inst->config->xlat_name);
292 DEBUG("rlm_sql (%s) in generate_sql_clients: query is %s",
293 inst->config->xlat_name, inst->config->client_query);
295 handle = sql_get_socket(inst);
300 if (rlm_sql_select_query(&handle, inst, inst->config->client_query) != RLM_SQL_OK){
304 while ((rlm_sql_fetch_row(&handle, inst) == 0) && (row = handle->row)) {
309 * The return data for each row MUST be in the following order:
311 * 0. Row ID (currently unused)
312 * 1. Name (or IP address)
316 * 5. Virtual Server (optional)
319 ERROR("rlm_sql (%s): No row id found on pass %d",inst->config->xlat_name,i);
323 ERROR("rlm_sql (%s): No nasname found for row %s",inst->config->xlat_name,row[0]);
327 ERROR("rlm_sql (%s): No short name found for row %s",inst->config->xlat_name,row[0]);
331 ERROR("rlm_sql (%s): No secret found for row %s",inst->config->xlat_name,row[0]);
335 if (((inst->module->sql_num_fields)(handle, inst->config) > 5) && (row[5] != NULL) && *row[5]) {
339 DEBUG("rlm_sql (%s): Adding client %s (%s) to %s clients list",
340 inst->config->xlat_name,
341 row[1], row[2], server ? server : "global");
343 /* FIXME: We should really pass a proper ctx */
344 c = client_from_query(NULL,
345 row[1], /* identifier */
347 row[2], /* shortname */
350 false); /* require message authenticator */
355 if (!client_add(NULL, c)) {
356 WARN("Failed to add client, possible duplicate?");
362 DEBUG("rlm_sql (%s): Client \"%s\" (%s) added", c->longname, c->shortname,
363 inst->config->xlat_name);
366 (inst->module->sql_finish_select_query)(handle, inst->config);
367 sql_release_socket(inst, handle);
374 * Translate the SQL queries.
376 static size_t sql_escape_func(UNUSED REQUEST *request, char *out, size_t outlen,
377 char const *in, void *arg)
379 rlm_sql_t *inst = arg;
384 * Non-printable characters get replaced with their
385 * mime-encoded equivalents.
388 strchr(inst->config->allowed_chars, *in) == NULL) {
390 * Only 3 or less bytes available.
396 snprintf(out, outlen, "=%02X", (unsigned char) in[0]);
405 * Only one byte left.
425 * Set the SQL user name.
427 * We don't call the escape function here. The resulting string
428 * will be escaped later in the queries xlat so we don't need to
429 * escape it twice. (it will make things wrong if we have an
430 * escape candidate character in the username)
432 int sql_set_user(rlm_sql_t *inst, REQUEST *request, char const *username)
434 char *expanded = NULL;
435 VALUE_PAIR *vp = NULL;
439 rad_assert(request->packet != NULL);
441 if (username != NULL) {
443 } else if (inst->config->query_user[0] != '\0') {
444 sqluser = inst->config->query_user;
449 len = radius_axlat(&expanded, request, sqluser, NULL, NULL);
454 vp = pairalloc(request->packet, inst->sql_user);
456 talloc_free(expanded);
460 pairstrsteal(vp, expanded);
461 RDEBUG2("SQL-User-Name set to '%s'", vp->vp_strvalue);
463 radius_pairmove(request, &request->packet->vps, vp, false); /* needs to be pair move else op is not respected */
469 * Do a set/unset user, so it's a bit clearer what's going on.
471 #define sql_unset_user(_i, _r) pairdelete(&_r->packet->vps, _i->sql_user->attr, _i->sql_user->vendor, TAG_ANY)
473 static int sql_get_grouplist(rlm_sql_t *inst, rlm_sql_handle_t **handle, REQUEST *request,
474 rlm_sql_grouplist_t **phead)
476 char *expanded = NULL;
479 rlm_sql_grouplist_t *entry;
482 /* NOTE: sql_set_user should have been run before calling this function */
484 entry = *phead = NULL;
486 if (!inst->config->groupmemb_query || (inst->config->groupmemb_query[0] == 0)) {
490 if (radius_axlat(&expanded, request, inst->config->groupmemb_query, sql_escape_func, inst) < 0) {
494 ret = rlm_sql_select_query(handle, inst, expanded);
495 talloc_free(expanded);
496 if (ret != RLM_SQL_OK) {
500 while (rlm_sql_fetch_row(handle, inst) == 0) {
501 row = (*handle)->row;
506 RDEBUG("row[0] returned NULL");
507 (inst->module->sql_finish_select_query)(*handle, inst->config);
513 *phead = talloc_zero(*handle, rlm_sql_grouplist_t);
516 entry->next = talloc_zero(*phead, rlm_sql_grouplist_t);
520 entry->name = talloc_typed_strdup(entry, row[0]);
525 (inst->module->sql_finish_select_query)(*handle, inst->config);
532 * sql groupcmp function. That way we can do group comparisons (in the users file for example)
533 * with the group memberships reciding in sql
534 * The group membership query should only return one element which is the username. The returned
535 * username will then be checked with the passed check string.
538 static int CC_HINT(nonnull (1 ,2, 4)) sql_groupcmp(void *instance, REQUEST *request, UNUSED VALUE_PAIR *request_vp,
539 VALUE_PAIR *check, UNUSED VALUE_PAIR *check_pairs,
540 UNUSED VALUE_PAIR **reply_pairs)
542 rlm_sql_handle_t *handle;
543 rlm_sql_t *inst = instance;
544 rlm_sql_grouplist_t *head, *entry;
546 RDEBUG("sql_groupcmp");
548 if (check->length == 0){
549 RDEBUG("sql_groupcmp: Illegal group name");
554 * Set, escape, and check the user attr here
556 if (sql_set_user(inst, request, NULL) < 0)
560 * Get a socket for this lookup
562 handle = sql_get_socket(inst);
568 * Get the list of groups this user is a member of
570 if (sql_get_grouplist(inst, &handle, request, &head) < 0) {
571 REDEBUG("Error getting group membership");
572 sql_release_socket(inst, handle);
576 for (entry = head; entry != NULL; entry = entry->next) {
577 if (strcmp(entry->name, check->vp_strvalue) == 0){
578 RDEBUG("sql_groupcmp finished: User is a member of group %s",
581 sql_release_socket(inst, handle);
586 /* Free the grouplist */
588 sql_release_socket(inst, handle);
590 RDEBUG("sql_groupcmp finished: User is NOT a member of group %s", check->vp_strvalue);
595 static rlm_rcode_t rlm_sql_process_groups(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle,
596 sql_fall_through_t *do_fall_through)
598 rlm_rcode_t rcode = RLM_MODULE_NOOP;
599 VALUE_PAIR *check_tmp = NULL, *reply_tmp = NULL, *sql_group = NULL;
600 rlm_sql_grouplist_t *head = NULL, *entry = NULL;
602 char *expanded = NULL;
605 rad_assert(request->packet != NULL);
608 * Get the list of groups this user is a member of
610 rows = sql_get_grouplist(inst, handle, request, &head);
612 REDEBUG("Error retrieving group list");
614 return RLM_MODULE_FAIL;
617 RDEBUG2("User not found in any groups");
618 rcode = RLM_MODULE_NOTFOUND;
623 RDEBUG2("User found in the group table");
628 * Add the Sql-Group attribute to the request list so we know
629 * which group we're retrieving attributes for
631 sql_group = pairmake_packet("Sql-Group", entry->name, T_OP_EQ);
633 REDEBUG("Error creating Sql-Group attribute");
634 rcode = RLM_MODULE_FAIL;
638 if (inst->config->authorize_group_check_query && (inst->config->authorize_group_check_query != '\0')) {
640 * Expand the group query
642 if (radius_axlat(&expanded, request, inst->config->authorize_group_check_query,
643 sql_escape_func, inst) < 0) {
644 REDEBUG("Error generating query");
645 rcode = RLM_MODULE_FAIL;
649 rows = sql_getvpdata(request, inst, handle, &check_tmp, expanded);
650 TALLOC_FREE(expanded);
652 REDEBUG("Error retrieving check pairs for group %s", entry->name);
653 rcode = RLM_MODULE_FAIL;
658 * If we got check rows we need to process them before we decide to process the reply rows
661 (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) != 0)) {
662 pairfree(&check_tmp);
663 pairdelete(&request->packet->vps, PW_SQL_GROUP, 0, TAG_ANY);
668 RDEBUG2("Group \"%s\" check items matched", entry->name);
669 rcode = RLM_MODULE_OK;
671 radius_pairmove(request, &request->config_items, check_tmp, true);
675 if (inst->config->authorize_group_reply_query && (inst->config->authorize_group_reply_query != '\0')) {
677 * Now get the reply pairs since the paircompare matched
679 if (radius_axlat(&expanded, request, inst->config->authorize_group_reply_query,
680 sql_escape_func, inst) < 0) {
681 REDEBUG("Error generating query");
682 rcode = RLM_MODULE_FAIL;
686 rows = sql_getvpdata(request->reply, inst, handle, &reply_tmp, expanded);
687 TALLOC_FREE(expanded);
689 REDEBUG("Error retrieving reply pairs for group %s", entry->name);
690 rcode = RLM_MODULE_FAIL;
694 *do_fall_through = fall_through(reply_tmp);
696 RDEBUG2("Group \"%s\" reply items processed", entry->name);
697 rcode = RLM_MODULE_OK;
699 radius_pairmove(request, &request->reply->vps, reply_tmp, true);
703 pairdelete(&request->packet->vps, PW_SQL_GROUP, 0, TAG_ANY);
705 } while (entry != NULL && (*do_fall_through == FALL_THROUGH_YES));
709 pairdelete(&request->packet->vps, PW_SQL_GROUP, 0, TAG_ANY);
715 static int mod_detach(void *instance)
717 rlm_sql_t *inst = instance;
720 if (inst->pool) sql_poolfree(inst);
726 * FIXME: Call the modules 'destroy' function?
728 dlclose(inst->handle); /* ignore any errors */
735 static int mod_instantiate(CONF_SECTION *conf, void *instance)
737 rlm_sql_t *inst = instance;
742 inst->config = &inst->myconfig;
745 inst->config->xlat_name = cf_section_name2(conf);
746 if (!inst->config->xlat_name) {
747 inst->config->xlat_name = cf_section_name1(conf);
754 * Allocate room for <instance>-SQL-Group
756 group_name = talloc_typed_asprintf(inst, "%s-SQL-Group", inst->config->xlat_name);
757 DEBUG("rlm_sql (%s): Creating new attribute %s",
758 inst->config->xlat_name, group_name);
760 memset(&flags, 0, sizeof(flags));
761 if (dict_addattr(group_name, -1, 0, PW_TYPE_STRING, flags) < 0) {
762 ERROR("rlm_sql (%s): Failed to create "
763 "attribute %s: %s", inst->config->xlat_name, group_name,
768 da = dict_attrbyname(group_name);
770 ERROR("rlm_sql (%s): Failed to create "
771 "attribute %s", inst->config->xlat_name, group_name);
775 if (inst->config->groupmemb_query &&
776 inst->config->groupmemb_query[0]) {
777 DEBUG("rlm_sql (%s): Registering sql_groupcmp for %s",
778 inst->config->xlat_name, group_name);
779 paircompare_register(da, dict_attrbyvalue(PW_USER_NAME, 0),
780 false, sql_groupcmp, inst);
784 rad_assert(inst->config->xlat_name);
787 * This will always exist, as cf_section_parse_init()
788 * will create it if it doesn't exist. However, the
789 * "reference" config item won't exist in an auto-created
790 * configuration. So if that doesn't exist, we ignore
791 * the whole subsection.
793 inst->config->accounting.cs = cf_section_sub_find(conf, "accounting");
794 inst->config->accounting.reference_cp = (cf_pair_find(inst->config->accounting.cs, "reference") != NULL);
796 inst->config->postauth.cs = cf_section_sub_find(conf, "post-auth");
797 inst->config->postauth.reference_cp = (cf_pair_find(inst->config->postauth.cs, "reference") != NULL);
800 * Cache the SQL-User-Name DICT_ATTR, so we can be slightly
801 * more efficient about creating SQL-User-Name attributes.
803 inst->sql_user = dict_attrbyname("SQL-User-Name");
804 if (!inst->sql_user) {
809 * Export these methods, too. This avoids RTDL_GLOBAL.
811 inst->sql_set_user = sql_set_user;
812 inst->sql_get_socket = sql_get_socket;
813 inst->sql_release_socket = sql_release_socket;
814 inst->sql_escape_func = sql_escape_func;
815 inst->sql_query = rlm_sql_query;
816 inst->sql_select_query = rlm_sql_select_query;
817 inst->sql_fetch_row = rlm_sql_fetch_row;
820 * Register the SQL xlat function
822 xlat_register(inst->config->xlat_name, sql_xlat, sql_escape_func, inst);
825 * Sanity check for crazy people.
827 if (strncmp(inst->config->sql_driver_name, "rlm_sql_", 8) != 0) {
828 ERROR("rlm_sql (%s): \"%s\" is NOT an SQL driver!",
829 inst->config->xlat_name, inst->config->sql_driver_name);
834 * Load the appropriate driver for our database
836 inst->handle = lt_dlopenext(inst->config->sql_driver_name);
838 ERROR("Could not link driver %s: %s",
839 inst->config->sql_driver_name,
841 ERROR("Make sure it (and all its dependent libraries!)"
842 "are in the search path of your system's ld");
846 inst->module = (rlm_sql_module_t *) dlsym(inst->handle,
847 inst->config->sql_driver_name);
849 ERROR("Could not link symbol %s: %s",
850 inst->config->sql_driver_name,
855 if (inst->module->mod_instantiate) {
859 name = strrchr(inst->config->sql_driver_name, '_');
861 name = inst->config->sql_driver_name;
866 cs = cf_section_sub_find(conf, name);
868 cs = cf_section_alloc(conf, name, NULL);
875 * It's up to the driver to register a destructor
877 if (inst->module->mod_instantiate(cs, inst->config) < 0) {
882 inst->lf = fr_logfile_init(inst);
884 cf_log_err_cs(conf, "Failed creating log file context");
888 INFO("rlm_sql (%s): Driver %s (module %s) loaded and linked",
889 inst->config->xlat_name, inst->config->sql_driver_name,
893 * Initialise the connection pool for this instance
895 INFO("rlm_sql (%s): Attempting to connect to database \"%s\"",
896 inst->config->xlat_name, inst->config->sql_db);
898 if (sql_socket_pool_init(inst) < 0) return -1;
900 if (inst->config->groupmemb_query &&
901 inst->config->groupmemb_query[0]) {
902 paircompare_register(dict_attrbyvalue(PW_SQL_GROUP, 0),
903 dict_attrbyvalue(PW_USER_NAME, 0), false, sql_groupcmp, inst);
906 if (inst->config->do_clients) {
907 if (generate_sql_clients(inst) == -1){
908 ERROR("Failed to load clients from SQL");
913 return RLM_MODULE_OK;
917 static rlm_rcode_t CC_HINT(nonnull) mod_authorize(void *instance, REQUEST *request)
919 rlm_rcode_t rcode = RLM_MODULE_NOOP;
921 rlm_sql_t *inst = instance;
922 rlm_sql_handle_t *handle;
924 VALUE_PAIR *check_tmp = NULL;
925 VALUE_PAIR *reply_tmp = NULL;
926 VALUE_PAIR *user_profile = NULL;
928 bool user_found = false;
930 sql_fall_through_t do_fall_through = FALL_THROUGH_DEFAULT;
934 char *expanded = NULL;
936 rad_assert(request->packet != NULL);
937 rad_assert(request->reply != NULL);
939 if (!inst->config->authorize_check_query && !inst->config->authorize_reply_query &&
940 !inst->config->read_groups && !inst->config->read_profiles) {
941 RWDEBUG("No authorization checks configured, returning noop");
943 return RLM_MODULE_NOOP;
947 * Set, escape, and check the user attr here
949 if (sql_set_user(inst, request, NULL) < 0) {
950 return RLM_MODULE_FAIL;
956 * After this point use goto error or goto release to cleanup socket temporary pairlists and
957 * temporary attributes.
959 handle = sql_get_socket(inst);
961 rcode = RLM_MODULE_FAIL;
966 * Query the check table to find any conditions associated with this user/realm/whatever...
968 if (inst->config->authorize_check_query) {
969 if (radius_axlat(&expanded, request, inst->config->authorize_check_query,
970 sql_escape_func, inst) < 0) {
971 REDEBUG("Error generating query");
972 rcode = RLM_MODULE_FAIL;
976 rows = sql_getvpdata(request, inst, &handle, &check_tmp, expanded);
977 TALLOC_FREE(expanded);
979 REDEBUG("SQL query error");
980 rcode = RLM_MODULE_FAIL;
984 if (rows == 0) goto skipreply; /* Don't need to free VPs we don't have */
987 * Only do this if *some* check pairs were returned
989 RDEBUG2("User found in radcheck table");
991 if (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) != 0) {
992 pairfree(&check_tmp);
997 RDEBUG2("Check items matched");
998 radius_pairmove(request, &request->config_items, check_tmp, true);
999 rcode = RLM_MODULE_OK;
1003 if (inst->config->authorize_reply_query) {
1005 * Now get the reply pairs since the paircompare matched
1007 if (radius_axlat(&expanded, request, inst->config->authorize_reply_query,
1008 sql_escape_func, inst) < 0) {
1009 REDEBUG("Error generating query");
1010 rcode = RLM_MODULE_FAIL;
1014 rows = sql_getvpdata(request->reply, inst, &handle, &reply_tmp, expanded);
1015 TALLOC_FREE(expanded);
1017 REDEBUG("SQL query error");
1018 rcode = RLM_MODULE_FAIL;
1022 if (rows == 0) goto skipreply;
1024 do_fall_through = fall_through(reply_tmp);
1026 RDEBUG2("User found in radreply table");
1028 radius_pairmove(request, &request->reply->vps, reply_tmp, true);
1029 rcode = RLM_MODULE_OK;
1034 if ((do_fall_through == FALL_THROUGH_YES) ||
1035 (inst->config->read_groups && (do_fall_through == FALL_THROUGH_DEFAULT))) {
1038 RDEBUG3("... falling-through to group processing");
1039 ret = rlm_sql_process_groups(inst, request, &handle, &do_fall_through);
1042 * Nothing bad happened, continue...
1044 case RLM_MODULE_UPDATED:
1045 rcode = RLM_MODULE_UPDATED;
1048 if (rcode != RLM_MODULE_UPDATED) {
1049 rcode = RLM_MODULE_OK;
1052 case RLM_MODULE_NOOP:
1056 case RLM_MODULE_NOTFOUND:
1066 * Repeat the above process with the default profile or User-Profile
1068 if ((do_fall_through == FALL_THROUGH_YES) ||
1069 (inst->config->read_profiles && (do_fall_through == FALL_THROUGH_DEFAULT))) {
1073 * Check for a default_profile or for a User-Profile.
1075 RDEBUG3("... falling-through to profile processing");
1076 user_profile = pairfind(request->config_items, PW_USER_PROFILE, 0, TAG_ANY);
1078 char const *profile = user_profile ?
1079 user_profile->vp_strvalue :
1080 inst->config->default_profile;
1082 if (!profile || !*profile) {
1086 RDEBUG2("Checking profile %s", profile);
1088 if (sql_set_user(inst, request, profile) < 0) {
1089 REDEBUG("Error setting profile");
1090 rcode = RLM_MODULE_FAIL;
1094 ret = rlm_sql_process_groups(inst, request, &handle, &do_fall_through);
1097 * Nothing bad happened, continue...
1099 case RLM_MODULE_UPDATED:
1100 rcode = RLM_MODULE_UPDATED;
1103 if (rcode != RLM_MODULE_UPDATED) {
1104 rcode = RLM_MODULE_OK;
1107 case RLM_MODULE_NOOP:
1111 case RLM_MODULE_NOTFOUND:
1121 * At this point the key (user) hasn't be found in the check table, the reply table
1122 * or the group mapping table, and there was no matching profile.
1126 rcode = RLM_MODULE_NOTFOUND;
1129 sql_release_socket(inst, handle);
1130 sql_unset_user(inst, request);
1135 pairfree(&check_tmp);
1136 pairfree(&reply_tmp);
1137 sql_unset_user(inst, request);
1139 sql_release_socket(inst, handle);
1145 * Generic function for failing between a bunch of queries.
1147 * Uses the same principle as rlm_linelog, expanding the 'reference' config
1148 * item using xlat to figure out what query it should execute.
1150 * If the reference matches multiple config items, and a query fails or
1151 * doesn't update any rows, the next matching config item is used.
1154 static int acct_redundant(rlm_sql_t *inst, REQUEST *request, sql_acct_section_t *section)
1156 rlm_rcode_t rcode = RLM_MODULE_OK;
1158 rlm_sql_handle_t *handle = NULL;
1160 int numaffected = 0;
1164 char const *attr = NULL;
1167 char path[MAX_STRING_LEN];
1169 char *expanded = NULL;
1171 rad_assert(section);
1173 if (section->reference[0] != '.') {
1177 if (radius_xlat(p, sizeof(path) - (p - path), request, section->reference, NULL, NULL) < 0) {
1178 rcode = RLM_MODULE_FAIL;
1183 item = cf_reference_item(NULL, section->cs, path);
1185 rcode = RLM_MODULE_FAIL;
1190 if (cf_item_is_section(item)){
1191 REDEBUG("Sections are not supported as references");
1192 rcode = RLM_MODULE_FAIL;
1197 pair = cf_itemtopair(item);
1198 attr = cf_pair_attr(pair);
1200 RDEBUG2("Using query template '%s'", attr);
1202 handle = sql_get_socket(inst);
1204 rcode = RLM_MODULE_FAIL;
1209 sql_set_user(inst, request, NULL);
1212 value = cf_pair_value(pair);
1214 RDEBUG("Ignoring null query");
1215 rcode = RLM_MODULE_NOOP;
1220 if (radius_axlat(&expanded, request, value, sql_escape_func, inst) < 0) {
1221 rcode = RLM_MODULE_FAIL;
1227 RDEBUG("Ignoring null query");
1228 rcode = RLM_MODULE_NOOP;
1229 talloc_free(expanded);
1234 rlm_sql_query_log(inst, request, section, expanded);
1237 * If rlm_sql_query cannot use the socket it'll try and
1238 * reconnect. Reconnecting will automatically release
1239 * the current socket, and try to select a new one.
1241 * If we get RLM_SQL_RECONNECT it means all connections in the pool
1242 * were exhausted, and we couldn't create a new connection,
1243 * so we do not need to call sql_release_socket.
1245 sql_ret = rlm_sql_query(&handle, inst, expanded);
1246 TALLOC_FREE(expanded);
1247 if (sql_ret == RLM_SQL_RECONNECT) {
1248 rcode = RLM_MODULE_FAIL;
1254 * Assume all other errors are incidental, and just meant our
1255 * operation failed and its not a client or SQL syntax error.
1257 * @fixme We should actually be able to distinguish between key
1258 * constraint violations (which we expect) and other errors.
1260 if (sql_ret == RLM_SQL_OK) {
1261 numaffected = (inst->module->sql_affected_rows)(handle, inst->config);
1262 if (numaffected > 0) {
1263 break; /* A query succeeded, were done! */
1266 RDEBUG("No records updated");
1269 (inst->module->sql_finish_query)(handle, inst->config);
1272 * We assume all entries with the same name form a redundant
1275 pair = cf_pair_find_next(section->cs, pair, attr);
1278 RDEBUG("No additional queries configured");
1279 rcode = RLM_MODULE_NOOP;
1284 RDEBUG("Trying next query...");
1287 (inst->module->sql_finish_query)(handle, inst->config);
1290 talloc_free(expanded);
1291 sql_release_socket(inst, handle);
1292 sql_unset_user(inst, request);
1297 #ifdef WITH_ACCOUNTING
1300 * Accounting: Insert or update session data in our sql table
1302 static rlm_rcode_t CC_HINT(nonnull) mod_accounting(void *instance, REQUEST * request) {
1303 rlm_sql_t *inst = instance;
1305 if (inst->config->accounting.reference_cp) {
1306 return acct_redundant(inst, request, &inst->config->accounting);
1309 return RLM_MODULE_NOOP;
1314 #ifdef WITH_SESSION_MGMT
1316 * See if a user is already logged in. Sets request->simul_count to the
1317 * current session count for this user.
1319 * Check twice. If on the first pass the user exceeds his
1320 * max. number of logins, do a second pass and validate all
1321 * logins by querying the terminal server (using eg. SNMP).
1324 static rlm_rcode_t CC_HINT(nonnull) mod_checksimul(void *instance, REQUEST * request) {
1325 rlm_rcode_t rcode = RLM_MODULE_OK;
1326 rlm_sql_handle_t *handle = NULL;
1327 rlm_sql_t *inst = instance;
1331 char const *call_num = NULL;
1334 uint32_t nas_addr = 0;
1335 uint32_t nas_port = 0;
1337 char *expanded = NULL;
1339 /* If simul_count_query is not defined, we don't do any checking */
1340 if (!inst->config->simul_count_query || (inst->config->simul_count_query[0] == '\0')) {
1341 return RLM_MODULE_NOOP;
1344 if((!request->username) || (request->username->length == '\0')) {
1345 REDEBUG("Zero Length username not permitted");
1347 return RLM_MODULE_INVALID;
1351 if(sql_set_user(inst, request, NULL) < 0) {
1352 return RLM_MODULE_FAIL;
1355 if (radius_axlat(&expanded, request, inst->config->simul_count_query, sql_escape_func, inst) < 0) {
1356 sql_unset_user(inst, request);
1357 return RLM_MODULE_FAIL;
1360 /* initialize the sql socket */
1361 handle = sql_get_socket(inst);
1363 talloc_free(expanded);
1364 sql_unset_user(inst, request);
1365 return RLM_MODULE_FAIL;
1368 if (rlm_sql_select_query(&handle, inst, expanded) != RLM_SQL_OK) {
1369 rcode = RLM_MODULE_FAIL;
1373 ret = rlm_sql_fetch_row(&handle, inst);
1375 rcode = RLM_MODULE_FAIL;
1381 rcode = RLM_MODULE_FAIL;
1385 request->simul_count = atoi(row[0]);
1387 (inst->module->sql_finish_select_query)(handle, inst->config);
1388 TALLOC_FREE(expanded);
1390 if (request->simul_count < request->simul_max) {
1391 rcode = RLM_MODULE_OK;
1396 * Looks like too many sessions, so let's start verifying
1397 * them, unless told to rely on count query only.
1399 if (!inst->config->simul_verify_query || (inst->config->simul_verify_query[0] == '\0')) {
1400 rcode = RLM_MODULE_OK;
1405 if (radius_axlat(&expanded, request, inst->config->simul_verify_query, sql_escape_func, inst) < 0) {
1406 rcode = RLM_MODULE_FAIL;
1411 if (rlm_sql_select_query(&handle, inst, expanded) != RLM_SQL_OK) {
1416 * Setup some stuff, like for MPP detection.
1418 request->simul_count = 0;
1420 if ((vp = pairfind(request->packet->vps, PW_FRAMED_IP_ADDRESS, 0, TAG_ANY)) != NULL) {
1421 ipno = vp->vp_ipaddr;
1424 if ((vp = pairfind(request->packet->vps, PW_CALLING_STATION_ID, 0, TAG_ANY)) != NULL) {
1425 call_num = vp->vp_strvalue;
1428 while (rlm_sql_fetch_row(&handle, inst) == 0) {
1435 RDEBUG("Cannot zap stale entry. No username present in entry");
1436 rcode = RLM_MODULE_FAIL;
1442 RDEBUG("Cannot zap stale entry. No session id in entry");
1443 rcode = RLM_MODULE_FAIL;
1449 nas_addr = inet_addr(row[3]);
1453 nas_port = atoi(row[4]);
1456 check = rad_check_ts(nas_addr, nas_port, row[2], row[1]);
1459 * Stale record - zap it.
1461 if (inst->config->deletestalesessions == true) {
1462 uint32_t framed_addr = 0;
1467 framed_addr = inet_addr(row[5]);
1469 if (strcmp(row[7], "PPP") == 0)
1471 else if (strcmp(row[7], "SLIP") == 0)
1475 sess_time = atoi(row[8]);
1476 session_zap(request, nas_addr, nas_port,
1477 row[2], row[1], framed_addr,
1481 else if (check == 1) {
1483 * User is still logged in.
1485 ++request->simul_count;
1488 * Does it look like a MPP attempt?
1490 if (row[5] && ipno && inet_addr(row[5]) == ipno) {
1491 request->simul_mpp = 2;
1492 } else if (row[6] && call_num && !strncmp(row[6],call_num,16)) {
1493 request->simul_mpp = 2;
1497 * Failed to check the terminal server for
1498 * duplicate logins: return an error.
1500 REDEBUG("Failed to check the terminal server for user '%s'.", row[2]);
1502 rcode = RLM_MODULE_FAIL;
1509 (inst->module->sql_finish_select_query)(handle, inst->config);
1510 sql_release_socket(inst, handle);
1511 talloc_free(expanded);
1512 sql_unset_user(inst, request);
1515 * The Auth module apparently looks at request->simul_count,
1516 * not the return value of this module when deciding to deny
1517 * a call for too many sessions.
1524 * Postauth: Write a record of the authentication attempt
1526 static rlm_rcode_t CC_HINT(nonnull) mod_post_auth(void *instance, REQUEST * request) {
1527 rlm_sql_t *inst = instance;
1529 if (inst->config->postauth.reference_cp) {
1530 return acct_redundant(inst, request, &inst->config->postauth);
1533 return RLM_MODULE_NOOP;
1537 * Execute postauth_query after authentication
1541 /* globally exported name */
1542 module_t rlm_sql = {
1545 RLM_TYPE_THREAD_SAFE, /* type: reserved */
1548 mod_instantiate, /* instantiation */
1549 mod_detach, /* detach */
1551 NULL, /* authentication */
1552 mod_authorize, /* authorization */
1553 NULL, /* preaccounting */
1554 #ifdef WITH_ACCOUNTING
1555 mod_accounting, /* accounting */
1559 #ifdef WITH_SESSION_MGMT
1560 mod_checksimul, /* checksimul */
1564 NULL, /* pre-proxy */
1565 NULL, /* post-proxy */
1566 mod_post_auth /* post-auth */