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>
34 #include <freeradius-devel/exfile.h>
41 * So we can do pass2 xlat checks on the queries.
43 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[] = {
56 { "accounting-on", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) query_config },
57 { "accounting-off", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) query_config },
58 { "start", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) query_config },
59 { "interim-update", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) query_config },
60 { "stop", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) query_config },
62 {NULL, -1, 0, NULL, NULL}
67 static const CONF_PARSER acct_config[] = {
68 { "reference", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, accounting.reference), ".query" },
69 { "logfile", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, accounting.logfile), NULL },
71 { "type", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) type_config },
73 {NULL, -1, 0, NULL, NULL}
76 static const CONF_PARSER postauth_config[] = {
77 { "reference", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, postauth.reference), ".query" },
78 { "logfile", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, postauth.logfile), NULL },
80 { "query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT | PW_TYPE_MULTI, rlm_sql_config_t, postauth.query), NULL },
82 {NULL, -1, 0, NULL, NULL}
85 static const CONF_PARSER module_config[] = {
86 { "driver", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_driver_name), "rlm_sql_null" },
87 { "server", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_server), "localhost" },
88 { "port", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_port), "" },
89 { "login", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_login), "" },
90 { "password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, rlm_sql_config_t, sql_password), "" },
91 { "radius_db", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_db), "radius" },
92 { "read_groups", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_sql_config_t, read_groups), "yes" },
93 { "read_profiles", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_sql_config_t, read_profiles), "yes" },
94 { "readclients", FR_CONF_OFFSET(PW_TYPE_BOOLEAN | PW_TYPE_DEPRECATED, rlm_sql_config_t, do_clients), NULL },
95 { "read_clients", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_sql_config_t, do_clients), "no" },
96 { "deletestalesessions", FR_CONF_OFFSET(PW_TYPE_BOOLEAN | PW_TYPE_DEPRECATED, rlm_sql_config_t, deletestalesessions), NULL },
97 { "delete_stale_sessions", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_sql_config_t, deletestalesessions), "yes" },
98 { "sql_user_name", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, query_user), "" },
99 { "logfile", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, logfile), NULL },
100 { "default_user_profile", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, default_profile), "" },
101 { "nas_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_DEPRECATED, rlm_sql_config_t, client_query), NULL },
102 { "client_query", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, client_query), "SELECT id,nasname,shortname,type,secret FROM nas" },
103 { "open_query", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, open_query), NULL },
105 { "authorize_check_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, authorize_check_query), NULL },
106 { "authorize_reply_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, authorize_reply_query), NULL },
108 { "authorize_group_check_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, authorize_group_check_query), "" },
109 { "authorize_group_reply_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, authorize_group_reply_query), "" },
110 { "group_membership_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, groupmemb_query), NULL },
111 #ifdef WITH_SESSION_MGMT
112 { "simul_count_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, simul_count_query), "" },
113 { "simul_verify_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, simul_verify_query), "" },
115 { "safe-characters", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_DEPRECATED, rlm_sql_config_t, allowed_chars), NULL },
116 { "safe_characters", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, allowed_chars), "@abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_: /" },
119 * This only works for a few drivers.
121 { "query_timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, rlm_sql_config_t, query_timeout), NULL },
123 { "accounting", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) acct_config },
125 { "post-auth", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) postauth_config },
127 {NULL, -1, 0, NULL, NULL}
131 * Fall-Through checking function from rlm_files.c
133 static sql_fall_through_t fall_through(VALUE_PAIR *vp)
136 tmp = pairfind(vp, PW_FALL_THROUGH, 0, TAG_ANY);
138 return tmp ? tmp->vp_integer : FALL_THROUGH_DEFAULT;
144 static int generate_sql_clients(rlm_sql_t *inst);
145 static size_t sql_escape_func(REQUEST *, char *out, size_t outlen, char const *in, void *arg);
150 * For selects the first value of the first column will be returned,
151 * for inserts, updates and deletes the number of rows affected will be
154 static ssize_t sql_xlat(void *instance, REQUEST *request, char const *query, char *out, size_t freespace)
156 rlm_sql_handle_t *handle = NULL;
158 rlm_sql_t *inst = instance;
163 * Add SQL-User-Name attribute just in case it is needed
164 * We could search the string fmt for SQL-User-Name to see if this is
167 sql_set_user(inst, request, NULL);
169 handle = fr_connection_get(inst->pool);
174 rlm_sql_query_log(inst, request, NULL, query);
177 * If the query starts with any of the following prefixes,
178 * then return the number of rows affected
180 if ((strncasecmp(query, "insert", 6) == 0) ||
181 (strncasecmp(query, "update", 6) == 0) ||
182 (strncasecmp(query, "delete", 6) == 0)) {
184 char buffer[21]; /* 64bit max is 20 decimal chars + null byte */
186 if (rlm_sql_query(&handle, inst, query) != RLM_SQL_OK) {
187 char const *error = (inst->module->sql_error)(handle, inst->config);
188 REDEBUG("SQL query failed: %s", error);
194 numaffected = (inst->module->sql_affected_rows)(handle, inst->config);
195 if (numaffected < 1) {
196 RDEBUG("SQL query affected no rows");
202 * Don't chop the returned number if freespace is
203 * too small. This hack is necessary because
204 * some implementations of snprintf return the
205 * size of the written data, and others return
206 * the size of the data they *would* have written
207 * if the output buffer was large enough.
209 snprintf(buffer, sizeof(buffer), "%d", numaffected);
211 len = strlen(buffer);
212 if (len >= freespace){
213 RDEBUG("rlm_sql (%s): Can't write result, insufficient string space", inst->config->xlat_name);
215 (inst->module->sql_finish_query)(handle, inst->config);
221 memcpy(out, buffer, len + 1); /* we did bounds checking above */
224 (inst->module->sql_finish_query)(handle, inst->config);
227 } /* else it's a SELECT statement */
229 if (rlm_sql_select_query(&handle, inst, query) != RLM_SQL_OK) {
230 ret = -1; /* error handled by rlm_sql_select_query */
235 ret = rlm_sql_fetch_row(&handle, inst);
237 REDEBUG("SQL query failed");
238 (inst->module->sql_finish_select_query)(handle, inst->config);
246 RDEBUG("SQL query returned no results");
247 (inst->module->sql_finish_select_query)(handle, inst->config);
254 RDEBUG("NULL value in first column of result");
255 (inst->module->sql_finish_select_query)(handle, inst->config);
261 len = strlen(row[0]);
262 if (len >= freespace){
263 RDEBUG("Insufficient string space");
264 (inst->module->sql_finish_select_query)(handle, inst->config);
270 strlcpy(out, row[0], freespace);
273 (inst->module->sql_finish_select_query)(handle, inst->config);
276 fr_connection_release(inst->pool, handle);
281 static int generate_sql_clients(rlm_sql_t *inst)
283 rlm_sql_handle_t *handle;
288 DEBUG("rlm_sql (%s): Processing generate_sql_clients",
289 inst->config->xlat_name);
291 DEBUG("rlm_sql (%s) in generate_sql_clients: query is %s",
292 inst->config->xlat_name, inst->config->client_query);
294 handle = fr_connection_get(inst->pool);
299 if (rlm_sql_select_query(&handle, inst, inst->config->client_query) != RLM_SQL_OK) return -1;
301 while ((rlm_sql_fetch_row(&handle, inst) == 0) && (row = handle->row)) {
306 * The return data for each row MUST be in the following order:
308 * 0. Row ID (currently unused)
309 * 1. Name (or IP address)
313 * 5. Virtual Server (optional)
316 ERROR("rlm_sql (%s): No row id found on pass %d",inst->config->xlat_name,i);
320 ERROR("rlm_sql (%s): No nasname found for row %s",inst->config->xlat_name,row[0]);
324 ERROR("rlm_sql (%s): No short name found for row %s",inst->config->xlat_name,row[0]);
328 ERROR("rlm_sql (%s): No secret found for row %s",inst->config->xlat_name,row[0]);
332 if (((inst->module->sql_num_fields)(handle, inst->config) > 5) && (row[5] != NULL) && *row[5]) {
336 DEBUG("rlm_sql (%s): Adding client %s (%s) to %s clients list",
337 inst->config->xlat_name,
338 row[1], row[2], server ? server : "global");
340 /* FIXME: We should really pass a proper ctx */
341 c = client_afrom_query(NULL,
342 row[1], /* identifier */
344 row[2], /* shortname */
347 false); /* require message authenticator */
352 if (!client_add(NULL, c)) {
353 WARN("Failed to add client, possible duplicate?");
359 DEBUG("rlm_sql (%s): Client \"%s\" (%s) added", c->longname, c->shortname,
360 inst->config->xlat_name);
363 (inst->module->sql_finish_select_query)(handle, inst->config);
364 fr_connection_release(inst->pool, handle);
371 * Translate the SQL queries.
373 static size_t sql_escape_func(UNUSED REQUEST *request, char *out, size_t outlen,
374 char const *in, void *arg)
376 rlm_sql_t *inst = arg;
383 * Allow all multi-byte UTF8 characters.
385 utf8_len = fr_utf8_char((uint8_t const *) in);
387 if (outlen <= utf8_len) break;
389 memcpy(out, in, utf8_len);
399 * Because we register our own escape function
400 * we're now responsible for escaping all special
401 * chars in an xlat expansion or attribute value.
405 if (outlen <= 2) break;
416 if (outlen <= 2) break;
427 if (outlen <= 2) break;
439 * Non-printable characters get replaced with their
440 * mime-encoded equivalents.
443 strchr(inst->config->allowed_chars, *in) == NULL) {
445 * Only 3 or less bytes available.
451 snprintf(out, outlen, "=%02X", (unsigned char) in[0]);
460 * Only one byte left.
480 * Set the SQL user name.
482 * We don't call the escape function here. The resulting string
483 * will be escaped later in the queries xlat so we don't need to
484 * escape it twice. (it will make things wrong if we have an
485 * escape candidate character in the username)
487 int sql_set_user(rlm_sql_t *inst, REQUEST *request, char const *username)
489 char *expanded = NULL;
490 VALUE_PAIR *vp = NULL;
494 rad_assert(request->packet != NULL);
496 if (username != NULL) {
498 } else if (inst->config->query_user[0] != '\0') {
499 sqluser = inst->config->query_user;
504 len = radius_axlat(&expanded, request, sqluser, NULL, NULL);
509 vp = pairalloc(request->packet, inst->sql_user);
511 talloc_free(expanded);
515 pairstrsteal(vp, expanded);
516 RDEBUG2("SQL-User-Name set to '%s'", vp->vp_strvalue);
518 radius_pairmove(request, &request->packet->vps, vp, false); /* needs to be pair move else op is not respected */
524 * Do a set/unset user, so it's a bit clearer what's going on.
526 #define sql_unset_user(_i, _r) pairdelete(&_r->packet->vps, _i->sql_user->attr, _i->sql_user->vendor, TAG_ANY)
528 static int sql_get_grouplist(rlm_sql_t *inst, rlm_sql_handle_t **handle, REQUEST *request,
529 rlm_sql_grouplist_t **phead)
531 char *expanded = NULL;
534 rlm_sql_grouplist_t *entry;
537 /* NOTE: sql_set_user should have been run before calling this function */
539 entry = *phead = NULL;
541 if (!inst->config->groupmemb_query) return 0;
543 if (radius_axlat(&expanded, request, inst->config->groupmemb_query, sql_escape_func, inst) < 0) return -1;
545 ret = rlm_sql_select_query(handle, inst, expanded);
546 talloc_free(expanded);
547 if (ret != RLM_SQL_OK) return -1;
549 while (rlm_sql_fetch_row(handle, inst) == 0) {
550 row = (*handle)->row;
555 RDEBUG("row[0] returned NULL");
556 (inst->module->sql_finish_select_query)(*handle, inst->config);
562 *phead = talloc_zero(*handle, rlm_sql_grouplist_t);
565 entry->next = talloc_zero(*phead, rlm_sql_grouplist_t);
569 entry->name = talloc_typed_strdup(entry, row[0]);
574 (inst->module->sql_finish_select_query)(*handle, inst->config);
581 * sql groupcmp function. That way we can do group comparisons (in the users file for example)
582 * with the group memberships reciding in sql
583 * The group membership query should only return one element which is the username. The returned
584 * username will then be checked with the passed check string.
587 static int CC_HINT(nonnull (1, 2, 4)) sql_groupcmp(void *instance, REQUEST *request, UNUSED VALUE_PAIR *request_vp,
588 VALUE_PAIR *check, UNUSED VALUE_PAIR *check_pairs,
589 UNUSED VALUE_PAIR **reply_pairs)
591 rlm_sql_handle_t *handle;
592 rlm_sql_t *inst = instance;
593 rlm_sql_grouplist_t *head, *entry;
595 RDEBUG("sql_groupcmp");
597 if (check->vp_length == 0){
598 RDEBUG("sql_groupcmp: Illegal group name");
603 * Set, escape, and check the user attr here
605 if (sql_set_user(inst, request, NULL) < 0)
609 * Get a socket for this lookup
611 handle = fr_connection_get(inst->pool);
617 * Get the list of groups this user is a member of
619 if (sql_get_grouplist(inst, &handle, request, &head) < 0) {
620 REDEBUG("Error getting group membership");
621 fr_connection_release(inst->pool, handle);
625 for (entry = head; entry != NULL; entry = entry->next) {
626 if (strcmp(entry->name, check->vp_strvalue) == 0){
627 RDEBUG("sql_groupcmp finished: User is a member of group %s",
630 fr_connection_release(inst->pool, handle);
635 /* Free the grouplist */
637 fr_connection_release(inst->pool, handle);
639 RDEBUG("sql_groupcmp finished: User is NOT a member of group %s", check->vp_strvalue);
644 static rlm_rcode_t rlm_sql_process_groups(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle,
645 sql_fall_through_t *do_fall_through)
647 rlm_rcode_t rcode = RLM_MODULE_NOOP;
648 VALUE_PAIR *check_tmp = NULL, *reply_tmp = NULL, *sql_group = NULL;
649 rlm_sql_grouplist_t *head = NULL, *entry = NULL;
651 char *expanded = NULL;
654 rad_assert(request->packet != NULL);
657 * Get the list of groups this user is a member of
659 rows = sql_get_grouplist(inst, handle, request, &head);
661 REDEBUG("Error retrieving group list");
663 return RLM_MODULE_FAIL;
666 RDEBUG2("User not found in any groups");
667 rcode = RLM_MODULE_NOTFOUND;
668 *do_fall_through = FALL_THROUGH_DEFAULT;
674 RDEBUG2("User found in the group table");
677 * Add the Sql-Group attribute to the request list so we know
678 * which group we're retrieving attributes for
680 sql_group = pairmake_packet("Sql-Group", NULL, T_OP_EQ);
682 REDEBUG("Error creating Sql-Group attribute");
683 rcode = RLM_MODULE_FAIL;
690 rad_assert(entry != NULL);
691 pairstrcpy(sql_group, entry->name);
693 if (inst->config->authorize_group_check_query) {
698 * Expand the group query
700 if (radius_axlat(&expanded, request, inst->config->authorize_group_check_query,
701 sql_escape_func, inst) < 0) {
702 REDEBUG("Error generating query");
703 rcode = RLM_MODULE_FAIL;
707 rows = sql_getvpdata(request, inst, request, handle, &check_tmp, expanded);
708 TALLOC_FREE(expanded);
710 REDEBUG("Error retrieving check pairs for group %s", entry->name);
711 rcode = RLM_MODULE_FAIL;
716 * If we got check rows we need to process them before we decide to
717 * process the reply rows
720 (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) != 0)) {
721 pairfree(&check_tmp);
724 goto next; /* != continue */
727 RDEBUG2("Group \"%s\": Conditional check items matched", entry->name);
728 rcode = RLM_MODULE_OK;
730 RDEBUG2("Group \"%s\": Merging assignment check items", entry->name);
732 for (vp = fr_cursor_init(&cursor, &check_tmp);
734 vp = fr_cursor_next(&cursor)) {
735 if (!fr_assignment_op[vp->op]) continue;
737 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
740 radius_pairmove(request, &request->config_items, check_tmp, true);
744 if (inst->config->authorize_group_reply_query) {
746 * Now get the reply pairs since the paircompare matched
748 if (radius_axlat(&expanded, request, inst->config->authorize_group_reply_query,
749 sql_escape_func, inst) < 0) {
750 REDEBUG("Error generating query");
751 rcode = RLM_MODULE_FAIL;
755 rows = sql_getvpdata(request->reply, inst, request, handle, &reply_tmp, expanded);
756 TALLOC_FREE(expanded);
758 REDEBUG("Error retrieving reply pairs for group %s", entry->name);
759 rcode = RLM_MODULE_FAIL;
762 *do_fall_through = fall_through(reply_tmp);
764 RDEBUG2("Group \"%s\": Merging reply items", entry->name);
765 rcode = RLM_MODULE_OK;
767 rdebug_pair_list(L_DBG_LVL_2, request, reply_tmp, NULL);
769 radius_pairmove(request, &request->reply->vps, reply_tmp, true);
772 * If there's no reply query configured, then we assume
773 * FALL_THROUGH_NO, which is the same as the users file if you
774 * had no reply attributes.
777 *do_fall_through = FALL_THROUGH_DEFAULT;
781 } while (entry != NULL && (*do_fall_through == FALL_THROUGH_YES));
785 pairdelete(&request->packet->vps, PW_SQL_GROUP, 0, TAG_ANY);
791 static int mod_detach(void *instance)
793 rlm_sql_t *inst = instance;
795 if (inst->pool) fr_connection_pool_delete(inst->pool);
798 * We need to explicitly free all children, so if the driver
799 * parented any memory off the instance, their destructors
800 * run before we unload the bytecode for them.
802 * If we don't do this, we get a SEGV deep inside the talloc code
803 * when it tries to call a destructor that no longer exists.
805 talloc_free_children(inst);
808 * Decrements the reference count. The driver object won't be unloaded
809 * until all instances of rlm_sql that use it have been destroyed.
811 if (inst->handle) dlclose(inst->handle);
816 static int mod_instantiate(CONF_SECTION *conf, void *instance)
818 rlm_sql_t *inst = instance;
823 inst->config = &inst->myconfig;
826 inst->config->xlat_name = cf_section_name2(conf);
827 if (!inst->config->xlat_name) {
828 inst->config->xlat_name = cf_section_name1(conf);
835 * Allocate room for <instance>-SQL-Group
837 group_name = talloc_typed_asprintf(inst, "%s-SQL-Group", inst->config->xlat_name);
838 DEBUG("rlm_sql (%s): Creating new attribute %s",
839 inst->config->xlat_name, group_name);
841 memset(&flags, 0, sizeof(flags));
842 if (dict_addattr(group_name, -1, 0, PW_TYPE_STRING, flags) < 0) {
843 ERROR("rlm_sql (%s): Failed to create "
844 "attribute %s: %s", inst->config->xlat_name, group_name,
849 da = dict_attrbyname(group_name);
851 ERROR("rlm_sql (%s): Failed to create "
852 "attribute %s", inst->config->xlat_name, group_name);
856 if (inst->config->groupmemb_query) {
857 DEBUG("rlm_sql (%s): Registering sql_groupcmp for %s",
858 inst->config->xlat_name, group_name);
859 paircompare_register(da, dict_attrbyvalue(PW_USER_NAME, 0),
860 false, sql_groupcmp, inst);
864 rad_assert(inst->config->xlat_name);
867 * Complain if the strings exist, but are empty.
869 #define CHECK_STRING(_x) if (inst->config->_x && !inst->config->_x[0]) \
871 WARN("rlm_sql (%s): " STRINGIFY(_x) " is empty. Please delete it from the configuration", inst->config->xlat_name);\
872 inst->config->_x = NULL;\
875 CHECK_STRING(groupmemb_query);
876 CHECK_STRING(authorize_check_query);
877 CHECK_STRING(authorize_reply_query);
878 CHECK_STRING(authorize_group_check_query);
879 CHECK_STRING(authorize_group_reply_query);
880 CHECK_STRING(simul_count_query);
881 CHECK_STRING(simul_verify_query);
882 CHECK_STRING(open_query);
883 CHECK_STRING(client_query);
886 * Sanity check for crazy people.
888 if (strncmp(inst->config->sql_driver_name, "rlm_sql_", 8) != 0) {
889 ERROR("rlm_sql (%s): \"%s\" is NOT an SQL driver!", inst->config->xlat_name, inst->config->sql_driver_name);
894 * We need authorize_group_check_query or authorize_group_reply_query
895 * if group_membership_query is set.
897 * Or we need group_membership_query if authorize_group_check_query or
898 * authorize_group_reply_query is set.
900 if (!inst->config->groupmemb_query) {
901 if (inst->config->authorize_group_check_query) {
902 WARN("rlm_sql (%s): Ignoring authorize_group_reply_query as group_membership_query "
903 "is not configured", inst->config->xlat_name);
906 if (inst->config->authorize_group_reply_query) {
907 WARN("rlm_sql (%s): Ignoring authorize_group_check_query as group_membership_query "
908 "is not configured", inst->config->xlat_name);
911 if (!inst->config->authorize_group_check_query) {
912 ERROR("rlm_sql (%s): authorize_group_check_query must be configured as group_membership_query "
913 "is configured", inst->config->xlat_name);
917 if (!inst->config->authorize_group_reply_query) {
918 ERROR("rlm_sql (%s): authorize_group_reply_query must be configured as group_membership_query "
919 "is configured", inst->config->xlat_name);
925 * This will always exist, as cf_section_parse_init()
926 * will create it if it doesn't exist. However, the
927 * "reference" config item won't exist in an auto-created
928 * configuration. So if that doesn't exist, we ignore
929 * the whole subsection.
931 inst->config->accounting.cs = cf_section_sub_find(conf, "accounting");
932 inst->config->accounting.reference_cp = (cf_pair_find(inst->config->accounting.cs, "reference") != NULL);
934 inst->config->postauth.cs = cf_section_sub_find(conf, "post-auth");
935 inst->config->postauth.reference_cp = (cf_pair_find(inst->config->postauth.cs, "reference") != NULL);
938 * Cache the SQL-User-Name DICT_ATTR, so we can be slightly
939 * more efficient about creating SQL-User-Name attributes.
941 inst->sql_user = dict_attrbyname("SQL-User-Name");
942 if (!inst->sql_user) {
947 * Export these methods, too. This avoids RTDL_GLOBAL.
949 inst->sql_set_user = sql_set_user;
950 inst->sql_escape_func = sql_escape_func;
951 inst->sql_query = rlm_sql_query;
952 inst->sql_select_query = rlm_sql_select_query;
953 inst->sql_fetch_row = rlm_sql_fetch_row;
956 * Register the SQL xlat function
958 xlat_register(inst->config->xlat_name, sql_xlat, sql_escape_func, inst);
961 * Load the appropriate driver for our database
963 inst->handle = lt_dlopenext(inst->config->sql_driver_name);
965 ERROR("Could not link driver %s: %s", inst->config->sql_driver_name, dlerror());
966 ERROR("Make sure it (and all its dependent libraries!) are in the search path of your system's ld");
970 inst->module = (rlm_sql_module_t *) dlsym(inst->handle,
971 inst->config->sql_driver_name);
973 ERROR("Could not link symbol %s: %s", inst->config->sql_driver_name, dlerror());
977 if (inst->module->mod_instantiate) {
981 name = strrchr(inst->config->sql_driver_name, '_');
983 name = inst->config->sql_driver_name;
988 cs = cf_section_sub_find(conf, name);
990 cs = cf_section_alloc(conf, name, NULL);
997 * It's up to the driver to register a destructor
999 if (inst->module->mod_instantiate(cs, inst->config) < 0) {
1004 inst->ef = exfile_init(inst, 64, 30);
1006 cf_log_err_cs(conf, "Failed creating log file context");
1010 INFO("rlm_sql (%s): Driver %s (module %s) loaded and linked", inst->config->xlat_name,
1011 inst->config->sql_driver_name, inst->module->name);
1014 * Initialise the connection pool for this instance
1016 INFO("rlm_sql (%s): Attempting to connect to database \"%s\"", inst->config->xlat_name, inst->config->sql_db);
1018 inst->pool = fr_connection_pool_module_init(inst->cs, inst, mod_conn_create, NULL, NULL);
1019 if (!inst->pool) return -1;
1021 if (inst->config->groupmemb_query) {
1022 paircompare_register(dict_attrbyvalue(PW_SQL_GROUP, 0),
1023 dict_attrbyvalue(PW_USER_NAME, 0), false, sql_groupcmp, inst);
1026 if (inst->config->do_clients) {
1027 if (generate_sql_clients(inst) == -1){
1028 ERROR("Failed to load clients from SQL");
1033 return RLM_MODULE_OK;
1037 static rlm_rcode_t CC_HINT(nonnull) mod_authorize(void *instance, REQUEST *request)
1039 rlm_rcode_t rcode = RLM_MODULE_NOOP;
1041 rlm_sql_t *inst = instance;
1042 rlm_sql_handle_t *handle;
1044 VALUE_PAIR *check_tmp = NULL;
1045 VALUE_PAIR *reply_tmp = NULL;
1046 VALUE_PAIR *user_profile = NULL;
1048 bool user_found = false;
1050 sql_fall_through_t do_fall_through = FALL_THROUGH_DEFAULT;
1054 char *expanded = NULL;
1056 rad_assert(request->packet != NULL);
1057 rad_assert(request->reply != NULL);
1059 if (!inst->config->authorize_check_query && !inst->config->authorize_reply_query &&
1060 !inst->config->read_groups && !inst->config->read_profiles) {
1061 RWDEBUG("No authorization checks configured, returning noop");
1063 return RLM_MODULE_NOOP;
1067 * Set, escape, and check the user attr here
1069 if (sql_set_user(inst, request, NULL) < 0) {
1070 return RLM_MODULE_FAIL;
1076 * After this point use goto error or goto release to cleanup socket temporary pairlists and
1077 * temporary attributes.
1079 handle = fr_connection_get(inst->pool);
1081 rcode = RLM_MODULE_FAIL;
1086 * Query the check table to find any conditions associated with this user/realm/whatever...
1088 if (inst->config->authorize_check_query) {
1092 if (radius_axlat(&expanded, request, inst->config->authorize_check_query,
1093 sql_escape_func, inst) < 0) {
1094 REDEBUG("Error generating query");
1095 rcode = RLM_MODULE_FAIL;
1099 rows = sql_getvpdata(request, inst, request, &handle, &check_tmp, expanded);
1100 TALLOC_FREE(expanded);
1102 REDEBUG("SQL query error getting check attributes");
1103 rcode = RLM_MODULE_FAIL;
1107 if (rows == 0) goto skipreply; /* Don't need to free VPs we don't have */
1110 * Only do this if *some* check pairs were returned
1112 RDEBUG2("User found in radcheck table");
1114 if (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) != 0) {
1115 pairfree(&check_tmp);
1120 RDEBUG2("Conditional check items matched, merging assignment check items");
1122 for (vp = fr_cursor_init(&cursor, &check_tmp);
1124 vp = fr_cursor_next(&cursor)) {
1125 if (!fr_assignment_op[vp->op]) continue;
1127 rdebug_pair(2, request, vp, NULL);
1130 radius_pairmove(request, &request->config_items, check_tmp, true);
1132 rcode = RLM_MODULE_OK;
1136 if (inst->config->authorize_reply_query) {
1138 * Now get the reply pairs since the paircompare matched
1140 if (radius_axlat(&expanded, request, inst->config->authorize_reply_query,
1141 sql_escape_func, inst) < 0) {
1142 REDEBUG("Error generating query");
1143 rcode = RLM_MODULE_FAIL;
1147 rows = sql_getvpdata(request->reply, inst, request, &handle, &reply_tmp, expanded);
1148 TALLOC_FREE(expanded);
1150 REDEBUG("SQL query error getting reply attributes");
1151 rcode = RLM_MODULE_FAIL;
1155 if (rows == 0) goto skipreply;
1157 do_fall_through = fall_through(reply_tmp);
1159 RDEBUG2("User found in radreply table, merging reply items");
1162 rdebug_pair_list(L_DBG_LVL_2, request, reply_tmp, NULL);
1164 radius_pairmove(request, &request->reply->vps, reply_tmp, true);
1166 rcode = RLM_MODULE_OK;
1171 * Neither group checks or profiles will work without
1172 * a group membership query.
1174 if (!inst->config->groupmemb_query) goto release;
1177 if ((do_fall_through == FALL_THROUGH_YES) ||
1178 (inst->config->read_groups && (do_fall_through == FALL_THROUGH_DEFAULT))) {
1181 RDEBUG3("... falling-through to group processing");
1182 ret = rlm_sql_process_groups(inst, request, &handle, &do_fall_through);
1185 * Nothing bad happened, continue...
1187 case RLM_MODULE_UPDATED:
1188 rcode = RLM_MODULE_UPDATED;
1191 if (rcode != RLM_MODULE_UPDATED) {
1192 rcode = RLM_MODULE_OK;
1195 case RLM_MODULE_NOOP:
1199 case RLM_MODULE_NOTFOUND:
1209 * Repeat the above process with the default profile or User-Profile
1211 if ((do_fall_through == FALL_THROUGH_YES) ||
1212 (inst->config->read_profiles && (do_fall_through == FALL_THROUGH_DEFAULT))) {
1216 * Check for a default_profile or for a User-Profile.
1218 RDEBUG3("... falling-through to profile processing");
1219 user_profile = pairfind(request->config_items, PW_USER_PROFILE, 0, TAG_ANY);
1221 char const *profile = user_profile ?
1222 user_profile->vp_strvalue :
1223 inst->config->default_profile;
1225 if (!profile || !*profile) {
1229 RDEBUG2("Checking profile %s", profile);
1231 if (sql_set_user(inst, request, profile) < 0) {
1232 REDEBUG("Error setting profile");
1233 rcode = RLM_MODULE_FAIL;
1237 ret = rlm_sql_process_groups(inst, request, &handle, &do_fall_through);
1240 * Nothing bad happened, continue...
1242 case RLM_MODULE_UPDATED:
1243 rcode = RLM_MODULE_UPDATED;
1246 if (rcode != RLM_MODULE_UPDATED) {
1247 rcode = RLM_MODULE_OK;
1250 case RLM_MODULE_NOOP:
1254 case RLM_MODULE_NOTFOUND:
1264 * At this point the key (user) hasn't be found in the check table, the reply table
1265 * or the group mapping table, and there was no matching profile.
1269 rcode = RLM_MODULE_NOTFOUND;
1272 fr_connection_release(inst->pool, handle);
1273 sql_unset_user(inst, request);
1278 pairfree(&check_tmp);
1279 pairfree(&reply_tmp);
1280 sql_unset_user(inst, request);
1282 fr_connection_release(inst->pool, handle);
1288 * Generic function for failing between a bunch of queries.
1290 * Uses the same principle as rlm_linelog, expanding the 'reference' config
1291 * item using xlat to figure out what query it should execute.
1293 * If the reference matches multiple config items, and a query fails or
1294 * doesn't update any rows, the next matching config item is used.
1297 static int acct_redundant(rlm_sql_t *inst, REQUEST *request, sql_acct_section_t *section)
1299 rlm_rcode_t rcode = RLM_MODULE_OK;
1301 rlm_sql_handle_t *handle = NULL;
1303 int numaffected = 0;
1307 char const *attr = NULL;
1310 char path[MAX_STRING_LEN];
1312 char *expanded = NULL;
1314 rad_assert(section);
1316 if (section->reference[0] != '.') {
1320 if (radius_xlat(p, sizeof(path) - (p - path), request, section->reference, NULL, NULL) < 0) {
1321 rcode = RLM_MODULE_FAIL;
1326 item = cf_reference_item(NULL, section->cs, path);
1328 rcode = RLM_MODULE_FAIL;
1333 if (cf_item_is_section(item)){
1334 REDEBUG("Sections are not supported as references");
1335 rcode = RLM_MODULE_FAIL;
1340 pair = cf_item_to_pair(item);
1341 attr = cf_pair_attr(pair);
1343 RDEBUG2("Using query template '%s'", attr);
1345 handle = fr_connection_get(inst->pool);
1347 rcode = RLM_MODULE_FAIL;
1352 sql_set_user(inst, request, NULL);
1355 value = cf_pair_value(pair);
1357 RDEBUG("Ignoring null query");
1358 rcode = RLM_MODULE_NOOP;
1363 if (radius_axlat(&expanded, request, value, sql_escape_func, inst) < 0) {
1364 rcode = RLM_MODULE_FAIL;
1370 RDEBUG("Ignoring null query");
1371 rcode = RLM_MODULE_NOOP;
1372 talloc_free(expanded);
1377 rlm_sql_query_log(inst, request, section, expanded);
1380 * If rlm_sql_query cannot use the socket it'll try and
1381 * reconnect. Reconnecting will automatically release
1382 * the current socket, and try to select a new one.
1384 * If we get RLM_SQL_RECONNECT it means all connections in the pool
1385 * were exhausted, and we couldn't create a new connection,
1386 * so we do not need to call fr_connection_release.
1388 sql_ret = rlm_sql_query(&handle, inst, expanded);
1389 TALLOC_FREE(expanded);
1390 if (sql_ret == RLM_SQL_RECONNECT) {
1391 rcode = RLM_MODULE_FAIL;
1397 * Assume all other errors are incidental, and just meant our
1398 * operation failed and its not a client or SQL syntax error.
1400 * @fixme We should actually be able to distinguish between key
1401 * constraint violations (which we expect) and other errors.
1403 if (sql_ret == RLM_SQL_OK) {
1404 numaffected = (inst->module->sql_affected_rows)(handle, inst->config);
1405 if (numaffected > 0) {
1406 break; /* A query succeeded, were done! */
1409 RDEBUG("No records updated");
1412 (inst->module->sql_finish_query)(handle, inst->config);
1415 * We assume all entries with the same name form a redundant
1418 pair = cf_pair_find_next(section->cs, pair, attr);
1421 RDEBUG("No additional queries configured");
1422 rcode = RLM_MODULE_NOOP;
1427 RDEBUG("Trying next query...");
1430 (inst->module->sql_finish_query)(handle, inst->config);
1433 talloc_free(expanded);
1434 fr_connection_release(inst->pool, handle);
1435 sql_unset_user(inst, request);
1440 #ifdef WITH_ACCOUNTING
1443 * Accounting: Insert or update session data in our sql table
1445 static rlm_rcode_t CC_HINT(nonnull) mod_accounting(void *instance, REQUEST * request) {
1446 rlm_sql_t *inst = instance;
1448 if (inst->config->accounting.reference_cp) {
1449 return acct_redundant(inst, request, &inst->config->accounting);
1452 return RLM_MODULE_NOOP;
1457 #ifdef WITH_SESSION_MGMT
1459 * See if a user is already logged in. Sets request->simul_count to the
1460 * current session count for this user.
1462 * Check twice. If on the first pass the user exceeds his
1463 * max. number of logins, do a second pass and validate all
1464 * logins by querying the terminal server (using eg. SNMP).
1467 static rlm_rcode_t CC_HINT(nonnull) mod_checksimul(void *instance, REQUEST * request) {
1468 rlm_rcode_t rcode = RLM_MODULE_OK;
1469 rlm_sql_handle_t *handle = NULL;
1470 rlm_sql_t *inst = instance;
1474 char const *call_num = NULL;
1477 uint32_t nas_addr = 0;
1478 uint32_t nas_port = 0;
1480 char *expanded = NULL;
1482 /* If simul_count_query is not defined, we don't do any checking */
1483 if (!inst->config->simul_count_query) {
1484 return RLM_MODULE_NOOP;
1487 if ((!request->username) || (request->username->vp_length == '\0')) {
1488 REDEBUG("Zero Length username not permitted");
1490 return RLM_MODULE_INVALID;
1494 if(sql_set_user(inst, request, NULL) < 0) {
1495 return RLM_MODULE_FAIL;
1498 if (radius_axlat(&expanded, request, inst->config->simul_count_query, sql_escape_func, inst) < 0) {
1499 sql_unset_user(inst, request);
1500 return RLM_MODULE_FAIL;
1503 /* initialize the sql socket */
1504 handle = fr_connection_get(inst->pool);
1506 talloc_free(expanded);
1507 sql_unset_user(inst, request);
1508 return RLM_MODULE_FAIL;
1511 if (rlm_sql_select_query(&handle, inst, expanded) != RLM_SQL_OK) {
1512 rcode = RLM_MODULE_FAIL;
1516 ret = rlm_sql_fetch_row(&handle, inst);
1518 rcode = RLM_MODULE_FAIL;
1524 rcode = RLM_MODULE_FAIL;
1528 request->simul_count = atoi(row[0]);
1530 (inst->module->sql_finish_select_query)(handle, inst->config);
1531 TALLOC_FREE(expanded);
1533 if (request->simul_count < request->simul_max) {
1534 rcode = RLM_MODULE_OK;
1539 * Looks like too many sessions, so let's start verifying
1540 * them, unless told to rely on count query only.
1542 if (!inst->config->simul_verify_query) {
1543 rcode = RLM_MODULE_OK;
1548 if (radius_axlat(&expanded, request, inst->config->simul_verify_query, sql_escape_func, inst) < 0) {
1549 rcode = RLM_MODULE_FAIL;
1554 if (rlm_sql_select_query(&handle, inst, expanded) != RLM_SQL_OK) goto finish;
1557 * Setup some stuff, like for MPP detection.
1559 request->simul_count = 0;
1561 if ((vp = pairfind(request->packet->vps, PW_FRAMED_IP_ADDRESS, 0, TAG_ANY)) != NULL) {
1562 ipno = vp->vp_ipaddr;
1565 if ((vp = pairfind(request->packet->vps, PW_CALLING_STATION_ID, 0, TAG_ANY)) != NULL) {
1566 call_num = vp->vp_strvalue;
1569 while (rlm_sql_fetch_row(&handle, inst) == 0) {
1576 RDEBUG("Cannot zap stale entry. No username present in entry");
1577 rcode = RLM_MODULE_FAIL;
1583 RDEBUG("Cannot zap stale entry. No session id in entry");
1584 rcode = RLM_MODULE_FAIL;
1590 nas_addr = inet_addr(row[3]);
1594 nas_port = atoi(row[4]);
1597 check = rad_check_ts(nas_addr, nas_port, row[2], row[1]);
1600 * Stale record - zap it.
1602 if (inst->config->deletestalesessions == true) {
1603 uint32_t framed_addr = 0;
1608 framed_addr = inet_addr(row[5]);
1610 if (strcmp(row[7], "PPP") == 0)
1612 else if (strcmp(row[7], "SLIP") == 0)
1616 sess_time = atoi(row[8]);
1617 session_zap(request, nas_addr, nas_port,
1618 row[2], row[1], framed_addr,
1622 else if (check == 1) {
1624 * User is still logged in.
1626 ++request->simul_count;
1629 * Does it look like a MPP attempt?
1631 if (row[5] && ipno && inet_addr(row[5]) == ipno) {
1632 request->simul_mpp = 2;
1633 } else if (row[6] && call_num && !strncmp(row[6],call_num,16)) {
1634 request->simul_mpp = 2;
1638 * Failed to check the terminal server for
1639 * duplicate logins: return an error.
1641 REDEBUG("Failed to check the terminal server for user '%s'.", row[2]);
1643 rcode = RLM_MODULE_FAIL;
1650 (inst->module->sql_finish_select_query)(handle, inst->config);
1651 fr_connection_release(inst->pool, handle);
1652 talloc_free(expanded);
1653 sql_unset_user(inst, request);
1656 * The Auth module apparently looks at request->simul_count,
1657 * not the return value of this module when deciding to deny
1658 * a call for too many sessions.
1665 * Postauth: Write a record of the authentication attempt
1667 static rlm_rcode_t CC_HINT(nonnull) mod_post_auth(void *instance, REQUEST * request) {
1668 rlm_sql_t *inst = instance;
1670 if (inst->config->postauth.reference_cp) {
1671 return acct_redundant(inst, request, &inst->config->postauth);
1674 return RLM_MODULE_NOOP;
1678 * Execute postauth_query after authentication
1682 /* globally exported name */
1683 extern module_t rlm_sql;
1684 module_t rlm_sql = {
1687 RLM_TYPE_THREAD_SAFE, /* type: reserved */
1690 mod_instantiate, /* instantiation */
1691 mod_detach, /* detach */
1693 NULL, /* authentication */
1694 mod_authorize, /* authorization */
1695 NULL, /* preaccounting */
1696 #ifdef WITH_ACCOUNTING
1697 mod_accounting, /* accounting */
1701 #ifdef WITH_SESSION_MGMT
1702 mod_checksimul, /* checksimul */
1706 NULL, /* pre-proxy */
1707 NULL, /* post-proxy */
1708 mod_post_auth /* post-auth */