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 as published by
4 * the Free Software Foundation; either version 2 of the License, or (at
5 * your option) any later version.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * @brief Implements SQL 'users' file, and SQL accounting.
22 * @copyright 2012-2014 Arran Cudbard-Bell <a.cudbardb@freeradius.org>
23 * @copyright 2000,2006 The FreeRADIUS server project
24 * @copyright 2000 Mike Machado <mike@innercite.com>
25 * @copyright 2000 Alan DeKok <aland@ox.org>
31 #include <freeradius-devel/radiusd.h>
32 #include <freeradius-devel/modules.h>
33 #include <freeradius-devel/token.h>
34 #include <freeradius-devel/rad_assert.h>
35 #include <freeradius-devel/exfile.h>
42 * So we can do pass2 xlat checks on the queries.
44 static const CONF_PARSER query_config[] = {
45 { "query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT | PW_TYPE_MULTI, rlm_sql_config_t, accounting.query), NULL },
47 {NULL, -1, 0, NULL, NULL}
51 * For now hard-code the subsections. This isn't perfect, but it
52 * helps the average case.
54 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}
64 static const CONF_PARSER acct_config[] = {
65 { "reference", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, accounting.reference), ".query" },
66 { "logfile", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, accounting.logfile), NULL },
68 { "type", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) type_config },
70 {NULL, -1, 0, NULL, NULL}
73 static const CONF_PARSER postauth_config[] = {
74 { "reference", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, postauth.reference), ".query" },
75 { "logfile", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, postauth.logfile), NULL },
77 { "query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT | PW_TYPE_MULTI, rlm_sql_config_t, postauth.query), NULL },
79 {NULL, -1, 0, NULL, NULL}
82 static const CONF_PARSER module_config[] = {
83 { "driver", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_driver_name), "rlm_sql_null" },
84 { "server", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_server), "localhost" },
85 { "port", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_port), "" },
86 { "login", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_login), "" },
87 { "password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, rlm_sql_config_t, sql_password), "" },
88 { "radius_db", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_db), "radius" },
89 { "read_groups", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_sql_config_t, read_groups), "yes" },
90 { "read_profiles", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_sql_config_t, read_profiles), "yes" },
91 { "readclients", FR_CONF_OFFSET(PW_TYPE_BOOLEAN | PW_TYPE_DEPRECATED, rlm_sql_config_t, do_clients), NULL },
92 { "read_clients", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_sql_config_t, do_clients), "no" },
93 { "deletestalesessions", FR_CONF_OFFSET(PW_TYPE_BOOLEAN | PW_TYPE_DEPRECATED, rlm_sql_config_t, delete_stale_sessions), NULL },
94 { "delete_stale_sessions", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_sql_config_t, delete_stale_sessions), "yes" },
95 { "sql_user_name", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, query_user), "" },
96 { "logfile", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, logfile), NULL },
97 { "default_user_profile", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, default_profile), "" },
98 { "nas_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_DEPRECATED, rlm_sql_config_t, client_query), NULL },
99 { "client_query", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, client_query), "SELECT id,nasname,shortname,type,secret FROM nas" },
100 { "open_query", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, connect_query), NULL },
102 { "authorize_check_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, authorize_check_query), NULL },
103 { "authorize_reply_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, authorize_reply_query), NULL },
105 { "authorize_group_check_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, authorize_group_check_query), NULL },
106 { "authorize_group_reply_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, authorize_group_reply_query), NULL },
107 { "group_membership_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, groupmemb_query), NULL },
108 #ifdef WITH_SESSION_MGMT
109 { "simul_count_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, simul_count_query), NULL },
110 { "simul_verify_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, simul_verify_query), NULL },
112 { "safe-characters", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_DEPRECATED, rlm_sql_config_t, allowed_chars), NULL },
113 { "safe_characters", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, allowed_chars), "@abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_: /" },
116 * This only works for a few drivers.
118 { "query_timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, rlm_sql_config_t, query_timeout), NULL },
120 { "accounting", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) acct_config },
122 { "post-auth", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) postauth_config },
124 {NULL, -1, 0, NULL, NULL}
128 * Fall-Through checking function from rlm_files.c
130 static sql_fall_through_t fall_through(VALUE_PAIR *vp)
133 tmp = pairfind(vp, PW_FALL_THROUGH, 0, TAG_ANY);
135 return tmp ? tmp->vp_integer : FALL_THROUGH_DEFAULT;
141 static int generate_sql_clients(rlm_sql_t *inst);
142 static size_t sql_escape_func(REQUEST *, char *out, size_t outlen, char const *in, void *arg);
147 * For selects the first value of the first column will be returned,
148 * for inserts, updates and deletes the number of rows affected will be
151 static ssize_t sql_xlat(void *instance, REQUEST *request, char const *query, char *out, size_t freespace)
153 rlm_sql_handle_t *handle = NULL;
155 rlm_sql_t *inst = instance;
161 * Add SQL-User-Name attribute just in case it is needed
162 * We could search the string fmt for SQL-User-Name to see if this is
165 sql_set_user(inst, request, NULL);
167 handle = fr_connection_get(inst->pool); /* connection pool should produce error */
168 if (!handle) return 0;
170 rlm_sql_query_log(inst, request, NULL, query);
173 * If the query starts with any of the following prefixes,
174 * then return the number of rows affected
176 if ((strncasecmp(query, "insert", 6) == 0) ||
177 (strncasecmp(query, "update", 6) == 0) ||
178 (strncasecmp(query, "delete", 6) == 0)) {
180 char buffer[21]; /* 64bit max is 20 decimal chars + null byte */
182 rcode = rlm_sql_query(inst, request, &handle, query);
183 if (rcode != RLM_SQL_OK) {
185 RERROR("SQL query failed: %s", fr_int2str(sql_rcode_table, rcode, "<INVALID>"));
191 numaffected = (inst->module->sql_affected_rows)(handle, inst->config);
192 if (numaffected < 1) {
193 RDEBUG("SQL query affected no rows");
199 * Don't chop the returned number if freespace is
200 * too small. This hack is necessary because
201 * some implementations of snprintf return the
202 * size of the written data, and others return
203 * the size of the data they *would* have written
204 * if the output buffer was large enough.
206 snprintf(buffer, sizeof(buffer), "%d", numaffected);
208 len = strlen(buffer);
209 if (len >= freespace){
210 RDEBUG("rlm_sql (%s): Can't write result, insufficient string space", inst->name);
212 (inst->module->sql_finish_query)(handle, inst->config);
218 memcpy(out, buffer, len + 1); /* we did bounds checking above */
221 (inst->module->sql_finish_query)(handle, inst->config);
224 } /* else it's a SELECT statement */
226 rcode = rlm_sql_select_query(inst, request, &handle, query);
227 if (rcode != RLM_SQL_OK) goto query_error;
229 rcode = rlm_sql_fetch_row(inst, request, &handle);
231 (inst->module->sql_finish_select_query)(handle, inst->config);
237 RDEBUG("SQL query returned no results");
238 (inst->module->sql_finish_select_query)(handle, inst->config);
245 RDEBUG("NULL value in first column of result");
246 (inst->module->sql_finish_select_query)(handle, inst->config);
252 len = strlen(row[0]);
253 if (len >= freespace){
254 RDEBUG("Insufficient string space");
255 (inst->module->sql_finish_select_query)(handle, inst->config);
261 strlcpy(out, row[0], freespace);
264 (inst->module->sql_finish_select_query)(handle, inst->config);
267 fr_connection_release(inst->pool, handle);
272 static int generate_sql_clients(rlm_sql_t *inst)
274 rlm_sql_handle_t *handle;
279 DEBUG("rlm_sql (%s): Processing generate_sql_clients",
282 DEBUG("rlm_sql (%s) in generate_sql_clients: query is %s",
283 inst->name, inst->config->client_query);
285 handle = fr_connection_get(inst->pool);
286 if (!handle) return -1;
288 if (rlm_sql_select_query(inst, NULL, &handle, inst->config->client_query) != RLM_SQL_OK) return -1;
290 while ((rlm_sql_fetch_row(inst, NULL, &handle) == 0) && (row = handle->row)) {
295 * The return data for each row MUST be in the following order:
297 * 0. Row ID (currently unused)
298 * 1. Name (or IP address)
302 * 5. Virtual Server (optional)
305 ERROR("rlm_sql (%s): No row id found on pass %d",inst->name,i);
309 ERROR("rlm_sql (%s): No nasname found for row %s",inst->name,row[0]);
313 ERROR("rlm_sql (%s): No short name found for row %s",inst->name,row[0]);
317 ERROR("rlm_sql (%s): No secret found for row %s",inst->name,row[0]);
321 if (((inst->module->sql_num_fields)(handle, inst->config) > 5) && (row[5] != NULL) && *row[5]) {
325 DEBUG("rlm_sql (%s): Adding client %s (%s) to %s clients list",
327 row[1], row[2], server ? server : "global");
329 /* FIXME: We should really pass a proper ctx */
330 c = client_afrom_query(NULL,
331 row[1], /* identifier */
333 row[2], /* shortname */
336 false); /* require message authenticator */
341 if (!client_add(NULL, c)) {
342 WARN("Failed to add client, possible duplicate?");
348 DEBUG("rlm_sql (%s): Client \"%s\" (%s) added", c->longname, c->shortname,
352 (inst->module->sql_finish_select_query)(handle, inst->config);
353 fr_connection_release(inst->pool, handle);
360 * Translate the SQL queries.
362 static size_t sql_escape_func(UNUSED REQUEST *request, char *out, size_t outlen,
363 char const *in, void *arg)
365 rlm_sql_t *inst = arg;
372 * Allow all multi-byte UTF8 characters.
374 utf8_len = fr_utf8_char((uint8_t const *) in);
376 if (outlen <= utf8_len) break;
378 memcpy(out, in, utf8_len);
388 * Because we register our own escape function
389 * we're now responsible for escaping all special
390 * chars in an xlat expansion or attribute value.
394 if (outlen <= 2) break;
405 if (outlen <= 2) break;
416 if (outlen <= 2) break;
428 * Non-printable characters get replaced with their
429 * mime-encoded equivalents.
432 strchr(inst->config->allowed_chars, *in) == NULL) {
434 * Only 3 or less bytes available.
440 snprintf(out, outlen, "=%02X", (unsigned char) in[0]);
449 * Only one byte left.
469 * Set the SQL user name.
471 * We don't call the escape function here. The resulting string
472 * will be escaped later in the queries xlat so we don't need to
473 * escape it twice. (it will make things wrong if we have an
474 * escape candidate character in the username)
476 int sql_set_user(rlm_sql_t *inst, REQUEST *request, char const *username)
478 char *expanded = NULL;
479 VALUE_PAIR *vp = NULL;
483 rad_assert(request->packet != NULL);
485 if (username != NULL) {
487 } else if (inst->config->query_user[0] != '\0') {
488 sqluser = inst->config->query_user;
493 len = radius_axlat(&expanded, request, sqluser, NULL, NULL);
498 vp = pairalloc(request->packet, inst->sql_user);
500 talloc_free(expanded);
504 pairstrsteal(vp, expanded);
505 RDEBUG2("SQL-User-Name set to '%s'", vp->vp_strvalue);
507 radius_pairmove(request, &request->packet->vps, vp, false); /* needs to be pair move else op is not respected */
513 * Do a set/unset user, so it's a bit clearer what's going on.
515 #define sql_unset_user(_i, _r) pairdelete(&_r->packet->vps, _i->sql_user->attr, _i->sql_user->vendor, TAG_ANY)
517 static int sql_get_grouplist(rlm_sql_t *inst, rlm_sql_handle_t **handle, REQUEST *request,
518 rlm_sql_grouplist_t **phead)
520 char *expanded = NULL;
523 rlm_sql_grouplist_t *entry;
526 /* NOTE: sql_set_user should have been run before calling this function */
528 entry = *phead = NULL;
530 if (!inst->config->groupmemb_query) return 0;
532 if (radius_axlat(&expanded, request, inst->config->groupmemb_query, sql_escape_func, inst) < 0) return -1;
534 ret = rlm_sql_select_query(inst, request, handle, expanded);
535 talloc_free(expanded);
536 if (ret != RLM_SQL_OK) return -1;
538 while (rlm_sql_fetch_row(inst, request, handle) == 0) {
539 row = (*handle)->row;
544 RDEBUG("row[0] returned NULL");
545 (inst->module->sql_finish_select_query)(*handle, inst->config);
551 *phead = talloc_zero(*handle, rlm_sql_grouplist_t);
554 entry->next = talloc_zero(*phead, rlm_sql_grouplist_t);
558 entry->name = talloc_typed_strdup(entry, row[0]);
563 (inst->module->sql_finish_select_query)(*handle, inst->config);
570 * sql groupcmp function. That way we can do group comparisons (in the users file for example)
571 * with the group memberships reciding in sql
572 * The group membership query should only return one element which is the username. The returned
573 * username will then be checked with the passed check string.
575 static int sql_groupcmp(void *instance, REQUEST *request, UNUSED VALUE_PAIR *request_vp,
576 VALUE_PAIR *check, UNUSED VALUE_PAIR *check_pairs,
577 UNUSED VALUE_PAIR **reply_pairs) CC_HINT(nonnull (1, 2, 4));
579 static int sql_groupcmp(void *instance, REQUEST *request, UNUSED VALUE_PAIR *request_vp,
580 VALUE_PAIR *check, UNUSED VALUE_PAIR *check_pairs,
581 UNUSED VALUE_PAIR **reply_pairs)
583 rlm_sql_handle_t *handle;
584 rlm_sql_t *inst = instance;
585 rlm_sql_grouplist_t *head, *entry;
587 RDEBUG("sql_groupcmp");
589 if (check->vp_length == 0){
590 RDEBUG("sql_groupcmp: Illegal group name");
595 * Set, escape, and check the user attr here
597 if (sql_set_user(inst, request, NULL) < 0)
601 * Get a socket for this lookup
603 handle = fr_connection_get(inst->pool);
609 * Get the list of groups this user is a member of
611 if (sql_get_grouplist(inst, &handle, request, &head) < 0) {
612 REDEBUG("Error getting group membership");
613 fr_connection_release(inst->pool, handle);
617 for (entry = head; entry != NULL; entry = entry->next) {
618 if (strcmp(entry->name, check->vp_strvalue) == 0){
619 RDEBUG("sql_groupcmp finished: User is a member of group %s",
622 fr_connection_release(inst->pool, handle);
627 /* Free the grouplist */
629 fr_connection_release(inst->pool, handle);
631 RDEBUG("sql_groupcmp finished: User is NOT a member of group %s", check->vp_strvalue);
636 static rlm_rcode_t rlm_sql_process_groups(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle,
637 sql_fall_through_t *do_fall_through)
639 rlm_rcode_t rcode = RLM_MODULE_NOOP;
640 VALUE_PAIR *check_tmp = NULL, *reply_tmp = NULL, *sql_group = NULL;
641 rlm_sql_grouplist_t *head = NULL, *entry = NULL;
643 char *expanded = NULL;
646 rad_assert(request->packet != NULL);
649 * Get the list of groups this user is a member of
651 rows = sql_get_grouplist(inst, handle, request, &head);
653 REDEBUG("Error retrieving group list");
655 return RLM_MODULE_FAIL;
658 RDEBUG2("User not found in any groups");
659 rcode = RLM_MODULE_NOTFOUND;
660 *do_fall_through = FALL_THROUGH_DEFAULT;
666 RDEBUG2("User found in the group table");
669 * Add the Sql-Group attribute to the request list so we know
670 * which group we're retrieving attributes for
672 sql_group = pairmake_packet("Sql-Group", NULL, T_OP_EQ);
674 REDEBUG("Error creating Sql-Group attribute");
675 rcode = RLM_MODULE_FAIL;
682 rad_assert(entry != NULL);
683 pairstrcpy(sql_group, entry->name);
685 if (inst->config->authorize_group_check_query) {
690 * Expand the group query
692 if (radius_axlat(&expanded, request, inst->config->authorize_group_check_query,
693 sql_escape_func, inst) < 0) {
694 REDEBUG("Error generating query");
695 rcode = RLM_MODULE_FAIL;
699 rows = sql_getvpdata(request, inst, request, handle, &check_tmp, expanded);
700 TALLOC_FREE(expanded);
702 REDEBUG("Error retrieving check pairs for group %s", entry->name);
703 rcode = RLM_MODULE_FAIL;
708 * If we got check rows we need to process them before we decide to
709 * process the reply rows
712 (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) != 0)) {
713 pairfree(&check_tmp);
716 goto next; /* != continue */
719 RDEBUG2("Group \"%s\": Conditional check items matched", entry->name);
720 rcode = RLM_MODULE_OK;
722 RDEBUG2("Group \"%s\": Merging assignment check items", entry->name);
724 for (vp = fr_cursor_init(&cursor, &check_tmp);
726 vp = fr_cursor_next(&cursor)) {
727 if (!fr_assignment_op[vp->op]) continue;
729 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
732 radius_pairmove(request, &request->config, check_tmp, true);
736 if (inst->config->authorize_group_reply_query) {
738 * Now get the reply pairs since the paircompare matched
740 if (radius_axlat(&expanded, request, inst->config->authorize_group_reply_query,
741 sql_escape_func, inst) < 0) {
742 REDEBUG("Error generating query");
743 rcode = RLM_MODULE_FAIL;
747 rows = sql_getvpdata(request->reply, inst, request, handle, &reply_tmp, expanded);
748 TALLOC_FREE(expanded);
750 REDEBUG("Error retrieving reply pairs for group %s", entry->name);
751 rcode = RLM_MODULE_FAIL;
754 *do_fall_through = fall_through(reply_tmp);
756 RDEBUG2("Group \"%s\": Merging reply items", entry->name);
757 rcode = RLM_MODULE_OK;
759 rdebug_pair_list(L_DBG_LVL_2, request, reply_tmp, NULL);
761 radius_pairmove(request, &request->reply->vps, reply_tmp, true);
764 * If there's no reply query configured, then we assume
765 * FALL_THROUGH_NO, which is the same as the users file if you
766 * had no reply attributes.
769 *do_fall_through = FALL_THROUGH_DEFAULT;
773 } while (entry != NULL && (*do_fall_through == FALL_THROUGH_YES));
777 pairdelete(&request->packet->vps, PW_SQL_GROUP, 0, TAG_ANY);
783 static int mod_detach(void *instance)
785 rlm_sql_t *inst = instance;
787 if (inst->pool) fr_connection_pool_free(inst->pool);
790 * We need to explicitly free all children, so if the driver
791 * parented any memory off the instance, their destructors
792 * run before we unload the bytecode for them.
794 * If we don't do this, we get a SEGV deep inside the talloc code
795 * when it tries to call a destructor that no longer exists.
797 talloc_free_children(inst);
800 * Decrements the reference count. The driver object won't be unloaded
801 * until all instances of rlm_sql that use it have been destroyed.
803 if (inst->handle) dlclose(inst->handle);
808 static int mod_instantiate(CONF_SECTION *conf, void *instance)
810 rlm_sql_t *inst = instance;
815 inst->config = &inst->myconfig;
818 inst->name = cf_section_name2(conf);
820 inst->name = cf_section_name1(conf);
827 * Allocate room for <instance>-SQL-Group
829 group_name = talloc_typed_asprintf(inst, "%s-SQL-Group", inst->name);
830 DEBUG("rlm_sql (%s): Creating new attribute %s",
831 inst->name, group_name);
833 memset(&flags, 0, sizeof(flags));
834 if (dict_addattr(group_name, -1, 0, PW_TYPE_STRING, flags) < 0) {
835 ERROR("rlm_sql (%s): Failed to create "
836 "attribute %s: %s", inst->name, group_name,
841 da = dict_attrbyname(group_name);
843 ERROR("rlm_sql (%s): Failed to create "
844 "attribute %s", inst->name, group_name);
848 if (inst->config->groupmemb_query) {
849 DEBUG("rlm_sql (%s): Registering sql_groupcmp for %s",
850 inst->name, group_name);
851 paircompare_register(da, dict_attrbyvalue(PW_USER_NAME, 0),
852 false, sql_groupcmp, inst);
856 rad_assert(inst->name);
859 * Complain if the strings exist, but are empty.
861 #define CHECK_STRING(_x) if (inst->config->_x && !inst->config->_x[0]) \
863 WARN("rlm_sql (%s): " STRINGIFY(_x) " is empty. Please delete it from the configuration", inst->name);\
864 inst->config->_x = NULL;\
867 CHECK_STRING(groupmemb_query);
868 CHECK_STRING(authorize_check_query);
869 CHECK_STRING(authorize_reply_query);
870 CHECK_STRING(authorize_group_check_query);
871 CHECK_STRING(authorize_group_reply_query);
872 CHECK_STRING(simul_count_query);
873 CHECK_STRING(simul_verify_query);
874 CHECK_STRING(connect_query);
875 CHECK_STRING(client_query);
876 if (strncmp(inst->config->sql_driver_name, "rlm_sql_", 8) != 0) {
877 ERROR("rlm_sql (%s): \"%s\" is NOT an SQL driver!", inst->name, inst->config->sql_driver_name);
882 * We need authorize_group_check_query or authorize_group_reply_query
883 * if group_membership_query is set.
885 * Or we need group_membership_query if authorize_group_check_query or
886 * authorize_group_reply_query is set.
888 if (!inst->config->groupmemb_query) {
889 if (inst->config->authorize_group_check_query) {
890 WARN("rlm_sql (%s): Ignoring authorize_group_reply_query as group_membership_query "
891 "is not configured", inst->name);
894 if (inst->config->authorize_group_reply_query) {
895 WARN("rlm_sql (%s): Ignoring authorize_group_check_query as group_membership_query "
896 "is not configured", inst->name);
898 } /* allow the group check / reply queries to be NULL */
901 * This will always exist, as cf_section_parse_init()
902 * will create it if it doesn't exist. However, the
903 * "reference" config item won't exist in an auto-created
904 * configuration. So if that doesn't exist, we ignore
905 * the whole subsection.
907 inst->config->accounting.cs = cf_section_sub_find(conf, "accounting");
908 inst->config->accounting.reference_cp = (cf_pair_find(inst->config->accounting.cs, "reference") != NULL);
910 inst->config->postauth.cs = cf_section_sub_find(conf, "post-auth");
911 inst->config->postauth.reference_cp = (cf_pair_find(inst->config->postauth.cs, "reference") != NULL);
914 * Cache the SQL-User-Name DICT_ATTR, so we can be slightly
915 * more efficient about creating SQL-User-Name attributes.
917 inst->sql_user = dict_attrbyname("SQL-User-Name");
918 if (!inst->sql_user) {
923 * Export these methods, too. This avoids RTDL_GLOBAL.
925 inst->sql_set_user = sql_set_user;
926 inst->sql_escape_func = sql_escape_func;
927 inst->sql_query = rlm_sql_query;
928 inst->sql_select_query = rlm_sql_select_query;
929 inst->sql_fetch_row = rlm_sql_fetch_row;
932 * Register the SQL xlat function
934 xlat_register(inst->name, sql_xlat, sql_escape_func, inst);
937 * Load the appropriate driver for our database
939 inst->handle = lt_dlopenext(inst->config->sql_driver_name);
941 ERROR("Could not link driver %s: %s", inst->config->sql_driver_name, dlerror());
942 ERROR("Make sure it (and all its dependent libraries!) are in the search path of your system's ld");
946 inst->module = (rlm_sql_module_t *) dlsym(inst->handle,
947 inst->config->sql_driver_name);
949 ERROR("Could not link symbol %s: %s", inst->config->sql_driver_name, dlerror());
953 if (inst->module->mod_instantiate) {
957 name = strrchr(inst->config->sql_driver_name, '_');
959 name = inst->config->sql_driver_name;
964 cs = cf_section_sub_find(conf, name);
966 cs = cf_section_alloc(conf, name, NULL);
973 * It's up to the driver to register a destructor
975 if (inst->module->mod_instantiate(cs, inst->config) < 0) {
980 inst->ef = exfile_init(inst, 64, 30);
982 cf_log_err_cs(conf, "Failed creating log file context");
986 INFO("rlm_sql (%s): Driver %s (module %s) loaded and linked", inst->name,
987 inst->config->sql_driver_name, inst->module->name);
990 * Initialise the connection pool for this instance
992 INFO("rlm_sql (%s): Attempting to connect to database \"%s\"", inst->name, inst->config->sql_db);
994 inst->pool = fr_connection_pool_module_init(inst->cs, inst, mod_conn_create, NULL, NULL);
995 if (!inst->pool) return -1;
997 if (inst->config->groupmemb_query) {
998 paircompare_register(dict_attrbyvalue(PW_SQL_GROUP, 0),
999 dict_attrbyvalue(PW_USER_NAME, 0), false, sql_groupcmp, inst);
1002 if (inst->config->do_clients) {
1003 if (generate_sql_clients(inst) == -1){
1004 ERROR("Failed to load clients from SQL");
1009 return RLM_MODULE_OK;
1012 static rlm_rcode_t mod_authorize(void *instance, REQUEST *request) CC_HINT(nonnull);
1013 static rlm_rcode_t mod_authorize(void *instance, REQUEST *request)
1015 rlm_rcode_t rcode = RLM_MODULE_NOOP;
1017 rlm_sql_t *inst = instance;
1018 rlm_sql_handle_t *handle;
1020 VALUE_PAIR *check_tmp = NULL;
1021 VALUE_PAIR *reply_tmp = NULL;
1022 VALUE_PAIR *user_profile = NULL;
1024 bool user_found = false;
1026 sql_fall_through_t do_fall_through = FALL_THROUGH_DEFAULT;
1030 char *expanded = NULL;
1032 rad_assert(request->packet != NULL);
1033 rad_assert(request->reply != NULL);
1035 if (!inst->config->authorize_check_query && !inst->config->authorize_reply_query &&
1036 !inst->config->read_groups && !inst->config->read_profiles) {
1037 RWDEBUG("No authorization checks configured, returning noop");
1039 return RLM_MODULE_NOOP;
1043 * Set, escape, and check the user attr here
1045 if (sql_set_user(inst, request, NULL) < 0) {
1046 return RLM_MODULE_FAIL;
1052 * After this point use goto error or goto release to cleanup socket temporary pairlists and
1053 * temporary attributes.
1055 handle = fr_connection_get(inst->pool);
1057 rcode = RLM_MODULE_FAIL;
1062 * Query the check table to find any conditions associated with this user/realm/whatever...
1064 if (inst->config->authorize_check_query) {
1068 if (radius_axlat(&expanded, request, inst->config->authorize_check_query,
1069 sql_escape_func, inst) < 0) {
1070 REDEBUG("Error generating query");
1071 rcode = RLM_MODULE_FAIL;
1075 rows = sql_getvpdata(request, inst, request, &handle, &check_tmp, expanded);
1076 TALLOC_FREE(expanded);
1078 REDEBUG("Error getting check attributes");
1079 rcode = RLM_MODULE_FAIL;
1083 if (rows == 0) goto skipreply; /* Don't need to free VPs we don't have */
1086 * Only do this if *some* check pairs were returned
1088 RDEBUG2("User found in radcheck table");
1090 if (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) != 0) {
1091 pairfree(&check_tmp);
1096 RDEBUG2("Conditional check items matched, merging assignment check items");
1098 for (vp = fr_cursor_init(&cursor, &check_tmp);
1100 vp = fr_cursor_next(&cursor)) {
1101 if (!fr_assignment_op[vp->op]) continue;
1103 rdebug_pair(2, request, vp, NULL);
1106 radius_pairmove(request, &request->config, check_tmp, true);
1108 rcode = RLM_MODULE_OK;
1112 if (inst->config->authorize_reply_query) {
1114 * Now get the reply pairs since the paircompare matched
1116 if (radius_axlat(&expanded, request, inst->config->authorize_reply_query,
1117 sql_escape_func, inst) < 0) {
1118 REDEBUG("Error generating query");
1119 rcode = RLM_MODULE_FAIL;
1123 rows = sql_getvpdata(request->reply, inst, request, &handle, &reply_tmp, expanded);
1124 TALLOC_FREE(expanded);
1126 REDEBUG("SQL query error getting reply attributes");
1127 rcode = RLM_MODULE_FAIL;
1131 if (rows == 0) goto skipreply;
1133 do_fall_through = fall_through(reply_tmp);
1135 RDEBUG2("User found in radreply table, merging reply items");
1138 rdebug_pair_list(L_DBG_LVL_2, request, reply_tmp, NULL);
1140 radius_pairmove(request, &request->reply->vps, reply_tmp, true);
1142 rcode = RLM_MODULE_OK;
1147 * Neither group checks or profiles will work without
1148 * a group membership query.
1150 if (!inst->config->groupmemb_query) goto release;
1153 if ((do_fall_through == FALL_THROUGH_YES) ||
1154 (inst->config->read_groups && (do_fall_through == FALL_THROUGH_DEFAULT))) {
1157 RDEBUG3("... falling-through to group processing");
1158 ret = rlm_sql_process_groups(inst, request, &handle, &do_fall_through);
1161 * Nothing bad happened, continue...
1163 case RLM_MODULE_UPDATED:
1164 rcode = RLM_MODULE_UPDATED;
1167 if (rcode != RLM_MODULE_UPDATED) {
1168 rcode = RLM_MODULE_OK;
1171 case RLM_MODULE_NOOP:
1175 case RLM_MODULE_NOTFOUND:
1185 * Repeat the above process with the default profile or User-Profile
1187 if ((do_fall_through == FALL_THROUGH_YES) ||
1188 (inst->config->read_profiles && (do_fall_through == FALL_THROUGH_DEFAULT))) {
1192 * Check for a default_profile or for a User-Profile.
1194 RDEBUG3("... falling-through to profile processing");
1195 user_profile = pairfind(request->config, PW_USER_PROFILE, 0, TAG_ANY);
1197 char const *profile = user_profile ?
1198 user_profile->vp_strvalue :
1199 inst->config->default_profile;
1201 if (!profile || !*profile) {
1205 RDEBUG2("Checking profile %s", profile);
1207 if (sql_set_user(inst, request, profile) < 0) {
1208 REDEBUG("Error setting profile");
1209 rcode = RLM_MODULE_FAIL;
1213 ret = rlm_sql_process_groups(inst, request, &handle, &do_fall_through);
1216 * Nothing bad happened, continue...
1218 case RLM_MODULE_UPDATED:
1219 rcode = RLM_MODULE_UPDATED;
1222 if (rcode != RLM_MODULE_UPDATED) {
1223 rcode = RLM_MODULE_OK;
1226 case RLM_MODULE_NOOP:
1230 case RLM_MODULE_NOTFOUND:
1240 * At this point the key (user) hasn't be found in the check table, the reply table
1241 * or the group mapping table, and there was no matching profile.
1245 rcode = RLM_MODULE_NOTFOUND;
1248 fr_connection_release(inst->pool, handle);
1249 sql_unset_user(inst, request);
1254 pairfree(&check_tmp);
1255 pairfree(&reply_tmp);
1256 sql_unset_user(inst, request);
1258 fr_connection_release(inst->pool, handle);
1264 * Generic function for failing between a bunch of queries.
1266 * Uses the same principle as rlm_linelog, expanding the 'reference' config
1267 * item using xlat to figure out what query it should execute.
1269 * If the reference matches multiple config items, and a query fails or
1270 * doesn't update any rows, the next matching config item is used.
1273 static int acct_redundant(rlm_sql_t *inst, REQUEST *request, sql_acct_section_t *section)
1275 rlm_rcode_t rcode = RLM_MODULE_OK;
1277 rlm_sql_handle_t *handle = NULL;
1279 int numaffected = 0;
1283 char const *attr = NULL;
1286 char path[MAX_STRING_LEN];
1288 char *expanded = NULL;
1290 rad_assert(section);
1292 if (section->reference[0] != '.') {
1296 if (radius_xlat(p, sizeof(path) - (p - path), request, section->reference, NULL, NULL) < 0) {
1297 rcode = RLM_MODULE_FAIL;
1303 * If we can't find a matching config item we do
1304 * nothing so return RLM_MODULE_NOOP.
1306 item = cf_reference_item(NULL, section->cs, path);
1308 RWDEBUG("No such configuration item %s", path);
1309 rcode = RLM_MODULE_NOOP;
1313 if (cf_item_is_section(item)){
1314 RWDEBUG("Sections are not supported as references");
1315 rcode = RLM_MODULE_NOOP;
1320 pair = cf_item_to_pair(item);
1321 attr = cf_pair_attr(pair);
1323 RDEBUG2("Using query template '%s'", attr);
1325 handle = fr_connection_get(inst->pool);
1327 rcode = RLM_MODULE_FAIL;
1332 sql_set_user(inst, request, NULL);
1335 value = cf_pair_value(pair);
1337 RDEBUG("Ignoring null query");
1338 rcode = RLM_MODULE_NOOP;
1343 if (radius_axlat(&expanded, request, value, sql_escape_func, inst) < 0) {
1344 rcode = RLM_MODULE_FAIL;
1350 RDEBUG("Ignoring null query");
1351 rcode = RLM_MODULE_NOOP;
1352 talloc_free(expanded);
1357 rlm_sql_query_log(inst, request, section, expanded);
1359 sql_ret = rlm_sql_query(inst, request, &handle, expanded);
1360 TALLOC_FREE(expanded);
1361 RDEBUG("SQL query returned: %s", fr_int2str(sql_rcode_table, sql_ret, "<INVALID>"));
1365 * Query was a success! Now we just need to check if it did anything.
1371 * A general, unrecoverable server fault.
1375 * If we get RLM_SQL_RECONNECT it means all connections in the pool
1376 * were exhausted, and we couldn't create a new connection,
1377 * so we do not need to call fr_connection_release.
1379 case RLM_SQL_RECONNECT:
1380 rcode = RLM_MODULE_FAIL;
1384 * Query was invalid, this is a terminal error, but we still need
1385 * to do cleanup, as the connection handle is still valid.
1387 case RLM_SQL_QUERY_INVALID:
1388 rcode = RLM_MODULE_INVALID;
1392 * Driver found an error (like a unique key constraint violation)
1393 * that hinted it might be a good idea to try an alternative query.
1395 case RLM_SQL_ALT_QUERY:
1401 * We need to have updated something for the query to have been
1402 * counted as successful.
1404 numaffected = (inst->module->sql_affected_rows)(handle, inst->config);
1405 (inst->module->sql_finish_query)(handle, inst->config);
1406 RDEBUG("%i record(s) updated", numaffected);
1408 if (numaffected > 0) break; /* A query succeeded, were done! */
1411 * We assume all entries with the same name form a redundant
1414 pair = cf_pair_find_next(section->cs, pair, attr);
1417 RDEBUG("No additional queries configured");
1418 rcode = RLM_MODULE_NOOP;
1423 RDEBUG("Trying next query...");
1428 talloc_free(expanded);
1429 fr_connection_release(inst->pool, handle);
1430 sql_unset_user(inst, request);
1435 #ifdef WITH_ACCOUNTING
1438 * Accounting: Insert or update session data in our sql table
1440 static rlm_rcode_t mod_accounting(void *instance, REQUEST *request) CC_HINT(nonnull);
1441 static rlm_rcode_t mod_accounting(void *instance, REQUEST *request)
1443 rlm_sql_t *inst = instance;
1445 if (inst->config->accounting.reference_cp) {
1446 return acct_redundant(inst, request, &inst->config->accounting);
1449 return RLM_MODULE_NOOP;
1454 #ifdef WITH_SESSION_MGMT
1456 * See if a user is already logged in. Sets request->simul_count to the
1457 * current session count for this user.
1459 * Check twice. If on the first pass the user exceeds his
1460 * max. number of logins, do a second pass and validate all
1461 * logins by querying the terminal server (using eg. SNMP).
1463 static rlm_rcode_t mod_checksimul(void *instance, REQUEST *request) CC_HINT(nonnull);
1464 static rlm_rcode_t mod_checksimul(void *instance, REQUEST * request)
1466 rlm_rcode_t rcode = RLM_MODULE_OK;
1467 rlm_sql_handle_t *handle = NULL;
1468 rlm_sql_t *inst = instance;
1472 char const *call_num = NULL;
1475 uint32_t nas_addr = 0;
1476 uint32_t nas_port = 0;
1478 char *expanded = NULL;
1480 /* If simul_count_query is not defined, we don't do any checking */
1481 if (!inst->config->simul_count_query) {
1482 return RLM_MODULE_NOOP;
1485 if ((!request->username) || (request->username->vp_length == '\0')) {
1486 REDEBUG("Zero Length username not permitted");
1488 return RLM_MODULE_INVALID;
1491 if (sql_set_user(inst, request, NULL) < 0) {
1492 return RLM_MODULE_FAIL;
1495 if (radius_axlat(&expanded, request, inst->config->simul_count_query, sql_escape_func, inst) < 0) {
1496 sql_unset_user(inst, request);
1497 return RLM_MODULE_FAIL;
1500 /* initialize the sql socket */
1501 handle = fr_connection_get(inst->pool);
1503 talloc_free(expanded);
1504 sql_unset_user(inst, request);
1505 return RLM_MODULE_FAIL;
1508 if (rlm_sql_select_query(inst, request, &handle, expanded) != RLM_SQL_OK) {
1509 rcode = RLM_MODULE_FAIL;
1513 ret = rlm_sql_fetch_row(inst, request, &handle);
1515 rcode = RLM_MODULE_FAIL;
1521 rcode = RLM_MODULE_FAIL;
1525 request->simul_count = atoi(row[0]);
1527 (inst->module->sql_finish_select_query)(handle, inst->config);
1528 TALLOC_FREE(expanded);
1530 if (request->simul_count < request->simul_max) {
1531 rcode = RLM_MODULE_OK;
1536 * Looks like too many sessions, so let's start verifying
1537 * them, unless told to rely on count query only.
1539 if (!inst->config->simul_verify_query) {
1540 rcode = RLM_MODULE_OK;
1545 if (radius_axlat(&expanded, request, inst->config->simul_verify_query, sql_escape_func, inst) < 0) {
1546 rcode = RLM_MODULE_FAIL;
1551 if (rlm_sql_select_query(inst, request, &handle, expanded) != RLM_SQL_OK) goto release;
1554 * Setup some stuff, like for MPP detection.
1556 request->simul_count = 0;
1558 if ((vp = pairfind(request->packet->vps, PW_FRAMED_IP_ADDRESS, 0, TAG_ANY)) != NULL) {
1559 ipno = vp->vp_ipaddr;
1562 if ((vp = pairfind(request->packet->vps, PW_CALLING_STATION_ID, 0, TAG_ANY)) != NULL) {
1563 call_num = vp->vp_strvalue;
1566 while (rlm_sql_fetch_row(inst, request, &handle) == 0) {
1573 RDEBUG("Cannot zap stale entry. No username present in entry");
1574 rcode = RLM_MODULE_FAIL;
1580 RDEBUG("Cannot zap stale entry. No session id in entry");
1581 rcode = RLM_MODULE_FAIL;
1587 nas_addr = inet_addr(row[3]);
1591 nas_port = atoi(row[4]);
1594 check = rad_check_ts(nas_addr, nas_port, row[2], row[1]);
1597 * Stale record - zap it.
1599 if (inst->config->delete_stale_sessions == true) {
1600 uint32_t framed_addr = 0;
1605 framed_addr = inet_addr(row[5]);
1607 if (strcmp(row[7], "PPP") == 0)
1609 else if (strcmp(row[7], "SLIP") == 0)
1613 sess_time = atoi(row[8]);
1614 session_zap(request, nas_addr, nas_port,
1615 row[2], row[1], framed_addr,
1619 else if (check == 1) {
1621 * User is still logged in.
1623 ++request->simul_count;
1626 * Does it look like a MPP attempt?
1628 if (row[5] && ipno && inet_addr(row[5]) == ipno) {
1629 request->simul_mpp = 2;
1630 } else if (row[6] && call_num && !strncmp(row[6],call_num,16)) {
1631 request->simul_mpp = 2;
1635 * Failed to check the terminal server for
1636 * duplicate logins: return an error.
1638 REDEBUG("Failed to check the terminal server for user '%s'.", row[2]);
1640 rcode = RLM_MODULE_FAIL;
1646 (inst->module->sql_finish_select_query)(handle, inst->config);
1648 fr_connection_release(inst->pool, handle);
1649 talloc_free(expanded);
1650 sql_unset_user(inst, request);
1653 * The Auth module apparently looks at request->simul_count,
1654 * not the return value of this module when deciding to deny
1655 * a call for too many sessions.
1662 * Postauth: Write a record of the authentication attempt
1664 static rlm_rcode_t mod_post_auth(void *instance, REQUEST *request) CC_HINT(nonnull);
1665 static rlm_rcode_t mod_post_auth(void *instance, REQUEST *request)
1667 rlm_sql_t *inst = instance;
1669 if (inst->config->postauth.reference_cp) {
1670 return acct_redundant(inst, request, &inst->config->postauth);
1673 return RLM_MODULE_NOOP;
1677 * Execute postauth_query after authentication
1681 /* globally exported name */
1682 extern module_t rlm_sql;
1683 module_t rlm_sql = {
1686 RLM_TYPE_THREAD_SAFE, /* type: reserved */
1689 mod_instantiate, /* instantiation */
1690 mod_detach, /* detach */
1692 NULL, /* authentication */
1693 mod_authorize, /* authorization */
1694 NULL, /* preaccounting */
1695 #ifdef WITH_ACCOUNTING
1696 mod_accounting, /* accounting */
1700 #ifdef WITH_SESSION_MGMT
1701 mod_checksimul, /* checksimul */
1705 NULL, /* pre-proxy */
1706 NULL, /* post-proxy */
1707 mod_post_auth /* post-auth */