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 CONF_PARSER_TERMINATOR
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 CONF_PARSER_TERMINATOR
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 CONF_PARSER_TERMINATOR
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 },
78 CONF_PARSER_TERMINATOR
81 static const CONF_PARSER module_config[] = {
82 { "driver", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_driver_name), "rlm_sql_null" },
83 { "server", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_server), "" }, /* Must be zero length so drivers can determine if it was set */
84 { "port", FR_CONF_OFFSET(PW_TYPE_INTEGER, rlm_sql_config_t, sql_port), "0" },
85 { "login", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_login), "" },
86 { "password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, rlm_sql_config_t, sql_password), "" },
87 { "radius_db", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, sql_db), "radius" },
88 { "read_groups", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_sql_config_t, read_groups), "yes" },
89 { "read_profiles", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_sql_config_t, read_profiles), "yes" },
90 { "readclients", FR_CONF_OFFSET(PW_TYPE_BOOLEAN | PW_TYPE_DEPRECATED, rlm_sql_config_t, do_clients), NULL },
91 { "read_clients", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_sql_config_t, do_clients), "no" },
92 { "deletestalesessions", FR_CONF_OFFSET(PW_TYPE_BOOLEAN | PW_TYPE_DEPRECATED, rlm_sql_config_t, delete_stale_sessions), NULL },
93 { "delete_stale_sessions", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_sql_config_t, delete_stale_sessions), "yes" },
94 { "sql_user_name", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, query_user), "" },
95 { "logfile", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, logfile), NULL },
96 { "default_user_profile", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, default_profile), "" },
97 { "nas_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_DEPRECATED, rlm_sql_config_t, client_query), NULL },
98 { "client_query", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, client_query), "SELECT id,nasname,shortname,type,secret FROM nas" },
99 { "open_query", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, connect_query), NULL },
101 { "authorize_check_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, authorize_check_query), NULL },
102 { "authorize_reply_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, authorize_reply_query), NULL },
104 { "authorize_group_check_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, authorize_group_check_query), NULL },
105 { "authorize_group_reply_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, authorize_group_reply_query), NULL },
106 { "group_membership_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, groupmemb_query), NULL },
107 #ifdef WITH_SESSION_MGMT
108 { "simul_count_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, simul_count_query), NULL },
109 { "simul_verify_query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, simul_verify_query), NULL },
111 { "safe-characters", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_DEPRECATED, rlm_sql_config_t, allowed_chars), NULL },
112 { "safe_characters", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_sql_config_t, allowed_chars), "@abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_: /" },
115 * This only works for a few drivers.
117 { "query_timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, rlm_sql_config_t, query_timeout), NULL },
119 { "accounting", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) acct_config },
121 { "post-auth", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) postauth_config },
122 CONF_PARSER_TERMINATOR
126 * Fall-Through checking function from rlm_files.c
128 static sql_fall_through_t fall_through(VALUE_PAIR *vp)
131 tmp = fr_pair_find_by_num(vp, PW_FALL_THROUGH, 0, TAG_ANY);
133 return tmp ? tmp->vp_integer : FALL_THROUGH_DEFAULT;
139 static int generate_sql_clients(rlm_sql_t *inst);
140 static size_t sql_escape_func(REQUEST *, char *out, size_t outlen, char const *in, void *arg);
145 * For selects the first value of the first column will be returned,
146 * for inserts, updates and deletes the number of rows affected will be
149 static ssize_t sql_xlat(void *instance, REQUEST *request, char const *query, char *out, size_t freespace)
151 rlm_sql_handle_t *handle = NULL;
153 rlm_sql_t *inst = instance;
159 * Add SQL-User-Name attribute just in case it is needed
160 * We could search the string fmt for SQL-User-Name to see if this is
163 sql_set_user(inst, request, NULL);
165 handle = fr_connection_get(inst->pool); /* connection pool should produce error */
166 if (!handle) return 0;
168 rlm_sql_query_log(inst, request, NULL, query);
171 * If the query starts with any of the following prefixes,
172 * then return the number of rows affected
174 if ((strncasecmp(query, "insert", 6) == 0) ||
175 (strncasecmp(query, "update", 6) == 0) ||
176 (strncasecmp(query, "delete", 6) == 0)) {
178 char buffer[21]; /* 64bit max is 20 decimal chars + null byte */
180 rcode = rlm_sql_query(inst, request, &handle, query);
181 if (rcode != RLM_SQL_OK) {
183 if (rcode != RLM_SQL_NO_MORE_ROWS) {
184 RERROR("SQL query failed: %s", fr_int2str(sql_rcode_table, rcode, "<INVALID>"));
186 RDEBUG("No rows were returned.");
193 numaffected = (inst->module->sql_affected_rows)(handle, inst->config);
194 if (numaffected < 1) {
195 RDEBUG("SQL query affected no rows");
196 (inst->module->sql_finish_query)(handle, inst->config);
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->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 rcode = rlm_sql_select_query(inst, request, &handle, query);
230 if (rcode != RLM_SQL_OK) goto query_error;
232 rcode = rlm_sql_fetch_row(inst, request, &handle);
233 if (rcode != RLM_SQL_OK) {
234 (inst->module->sql_finish_select_query)(handle, inst->config);
240 RDEBUG("SQL query returned no results");
241 (inst->module->sql_finish_select_query)(handle, inst->config);
248 RDEBUG("NULL value in first column of result");
249 (inst->module->sql_finish_select_query)(handle, inst->config);
255 len = strlen(row[0]);
256 if (len >= freespace){
257 RDEBUG("Insufficient string space");
258 (inst->module->sql_finish_select_query)(handle, inst->config);
264 strlcpy(out, row[0], freespace);
267 (inst->module->sql_finish_select_query)(handle, inst->config);
270 fr_connection_release(inst->pool, handle);
275 static int generate_sql_clients(rlm_sql_t *inst)
277 rlm_sql_handle_t *handle;
282 DEBUG("rlm_sql (%s): Processing generate_sql_clients",
285 DEBUG("rlm_sql (%s) in generate_sql_clients: query is %s",
286 inst->name, inst->config->client_query);
288 handle = fr_connection_get(inst->pool);
289 if (!handle) return -1;
291 if (rlm_sql_select_query(inst, NULL, &handle, inst->config->client_query) != RLM_SQL_OK) return -1;
293 while ((rlm_sql_fetch_row(inst, NULL, &handle) == RLM_SQL_OK) && (row = handle->row)) {
299 num_rows = (inst->module->sql_num_fields)(handle, inst->config);
301 WARN("SELECT returned too few rows. Please do not edit 'client_query'");
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->name,i);
320 ERROR("rlm_sql (%s): No nasname found for row %s",inst->name,row[0]);
324 ERROR("rlm_sql (%s): No short name found for row %s",inst->name,row[0]);
328 ERROR("rlm_sql (%s): No secret found for row %s",inst->name,row[0]);
332 if ((num_rows > 5) && (row[5] != NULL) && *row[5]) {
336 DEBUG("rlm_sql (%s): Adding client %s (%s) to %s clients list",
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,
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, -1);
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 = fr_pair_afrom_da(request->packet, inst->sql_user);
511 talloc_free(expanded);
515 fr_pair_value_strsteal(vp, expanded);
516 RDEBUG2("SQL-User-Name set to '%s'", vp->vp_strvalue);
520 * Delete any existing SQL-User-Name, and replace it with ours.
522 fr_pair_delete_by_num(&request->packet->vps, vp->da->attr, vp->da->vendor, TAG_ANY);
523 fr_pair_add(&request->packet->vps, vp);
529 * Do a set/unset user, so it's a bit clearer what's going on.
531 #define sql_unset_user(_i, _r) fr_pair_delete_by_num(&_r->packet->vps, _i->sql_user->attr, _i->sql_user->vendor, TAG_ANY)
533 static int sql_get_grouplist(rlm_sql_t *inst, rlm_sql_handle_t **handle, REQUEST *request,
534 rlm_sql_grouplist_t **phead)
536 char *expanded = NULL;
539 rlm_sql_grouplist_t *entry;
542 /* NOTE: sql_set_user should have been run before calling this function */
544 entry = *phead = NULL;
546 if (!inst->config->groupmemb_query) return 0;
548 if (radius_axlat(&expanded, request, inst->config->groupmemb_query, sql_escape_func, inst) < 0) return -1;
550 ret = rlm_sql_select_query(inst, request, handle, expanded);
551 talloc_free(expanded);
552 if (ret != RLM_SQL_OK) return -1;
554 while (rlm_sql_fetch_row(inst, request, handle) == RLM_SQL_OK) {
555 row = (*handle)->row;
560 RDEBUG("row[0] returned NULL");
561 (inst->module->sql_finish_select_query)(*handle, inst->config);
567 *phead = talloc_zero(*handle, rlm_sql_grouplist_t);
570 entry->next = talloc_zero(*phead, rlm_sql_grouplist_t);
574 entry->name = talloc_typed_strdup(entry, row[0]);
579 (inst->module->sql_finish_select_query)(*handle, inst->config);
586 * sql groupcmp function. That way we can do group comparisons (in the users file for example)
587 * with the group memberships reciding in sql
588 * The group membership query should only return one element which is the username. The returned
589 * username will then be checked with the passed check string.
591 static int sql_groupcmp(void *instance, REQUEST *request, UNUSED VALUE_PAIR *request_vp,
592 VALUE_PAIR *check, UNUSED VALUE_PAIR *check_pairs,
593 UNUSED VALUE_PAIR **reply_pairs) CC_HINT(nonnull (1, 2, 4));
595 static int sql_groupcmp(void *instance, REQUEST *request, UNUSED VALUE_PAIR *request_vp,
596 VALUE_PAIR *check, UNUSED VALUE_PAIR *check_pairs,
597 UNUSED VALUE_PAIR **reply_pairs)
599 rlm_sql_handle_t *handle;
600 rlm_sql_t *inst = instance;
601 rlm_sql_grouplist_t *head, *entry;
604 * No group queries, don't do group comparisons.
606 if (!inst->config->groupmemb_query) {
607 RWARN("Cannot do group comparison when group_membership_query is not set");
611 RDEBUG("sql_groupcmp");
613 if (check->vp_length == 0){
614 RDEBUG("sql_groupcmp: Illegal group name");
619 * Set, escape, and check the user attr here
621 if (sql_set_user(inst, request, NULL) < 0)
625 * Get a socket for this lookup
627 handle = fr_connection_get(inst->pool);
633 * Get the list of groups this user is a member of
635 if (sql_get_grouplist(inst, &handle, request, &head) < 0) {
636 REDEBUG("Error getting group membership");
637 fr_connection_release(inst->pool, handle);
641 for (entry = head; entry != NULL; entry = entry->next) {
642 if (strcmp(entry->name, check->vp_strvalue) == 0){
643 RDEBUG("sql_groupcmp finished: User is a member of group %s",
646 fr_connection_release(inst->pool, handle);
651 /* Free the grouplist */
653 fr_connection_release(inst->pool, handle);
655 RDEBUG("sql_groupcmp finished: User is NOT a member of group %s", check->vp_strvalue);
660 static rlm_rcode_t rlm_sql_process_groups(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle,
661 sql_fall_through_t *do_fall_through)
663 rlm_rcode_t rcode = RLM_MODULE_NOOP;
664 VALUE_PAIR *check_tmp = NULL, *reply_tmp = NULL, *sql_group = NULL;
665 rlm_sql_grouplist_t *head = NULL, *entry = NULL;
667 char *expanded = NULL;
670 rad_assert(request->packet != NULL);
672 if (!inst->config->groupmemb_query) {
673 RWARN("Cannot do check groups when group_membership_query is not set");
676 *do_fall_through = FALL_THROUGH_DEFAULT;
679 * Didn't add group attributes or allocate
680 * memory, so don't do anything else.
682 return RLM_MODULE_NOTFOUND;
686 * Get the list of groups this user is a member of
688 rows = sql_get_grouplist(inst, handle, request, &head);
690 REDEBUG("Error retrieving group list");
692 return RLM_MODULE_FAIL;
695 RDEBUG2("User not found in any groups");
700 RDEBUG2("User found in the group table");
703 * Add the Sql-Group attribute to the request list so we know
704 * which group we're retrieving attributes for
706 sql_group = pair_make_request(inst->group_da->name, NULL, T_OP_EQ);
708 REDEBUG("Error creating %s attribute", inst->group_da->name);
709 rcode = RLM_MODULE_FAIL;
716 rad_assert(entry != NULL);
717 fr_pair_value_strcpy(sql_group, entry->name);
719 if (inst->config->authorize_group_check_query) {
724 * Expand the group query
726 if (radius_axlat(&expanded, request, inst->config->authorize_group_check_query,
727 sql_escape_func, inst) < 0) {
728 REDEBUG("Error generating query");
729 rcode = RLM_MODULE_FAIL;
733 rows = sql_getvpdata(request, inst, request, handle, &check_tmp, expanded);
734 TALLOC_FREE(expanded);
736 REDEBUG("Error retrieving check pairs for group %s", entry->name);
737 rcode = RLM_MODULE_FAIL;
742 * If we got check rows we need to process them before we decide to
743 * process the reply rows
746 (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) != 0)) {
747 fr_pair_list_free(&check_tmp);
752 goto next; /* != continue */
755 RDEBUG2("Group \"%s\": Conditional check items matched", entry->name);
756 rcode = RLM_MODULE_OK;
758 RDEBUG2("Group \"%s\": Merging assignment check items", entry->name);
760 for (vp = fr_cursor_init(&cursor, &check_tmp);
762 vp = fr_cursor_next(&cursor)) {
763 if (!fr_assignment_op[vp->op]) continue;
765 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
768 radius_pairmove(request, &request->config, check_tmp, true);
772 if (inst->config->authorize_group_reply_query) {
774 * Now get the reply pairs since the paircompare matched
776 if (radius_axlat(&expanded, request, inst->config->authorize_group_reply_query,
777 sql_escape_func, inst) < 0) {
778 REDEBUG("Error generating query");
779 rcode = RLM_MODULE_FAIL;
783 rows = sql_getvpdata(request->reply, inst, request, handle, &reply_tmp, expanded);
784 TALLOC_FREE(expanded);
786 REDEBUG("Error retrieving reply pairs for group %s", entry->name);
787 rcode = RLM_MODULE_FAIL;
790 *do_fall_through = fall_through(reply_tmp);
792 RDEBUG2("Group \"%s\": Merging reply items", entry->name);
793 rcode = RLM_MODULE_OK;
795 rdebug_pair_list(L_DBG_LVL_2, request, reply_tmp, NULL);
797 radius_pairmove(request, &request->reply->vps, reply_tmp, true);
800 * If there's no reply query configured, then we assume
801 * FALL_THROUGH_NO, which is the same as the users file if you
802 * had no reply attributes.
805 *do_fall_through = FALL_THROUGH_DEFAULT;
809 } while (entry != NULL && (*do_fall_through == FALL_THROUGH_YES));
813 fr_pair_delete_by_num(&request->packet->vps, inst->group_da->attr, 0, TAG_ANY);
819 static int mod_detach(void *instance)
821 rlm_sql_t *inst = instance;
823 if (inst->pool) fr_connection_pool_free(inst->pool);
826 * We need to explicitly free all children, so if the driver
827 * parented any memory off the instance, their destructors
828 * run before we unload the bytecode for them.
830 * If we don't do this, we get a SEGV deep inside the talloc code
831 * when it tries to call a destructor that no longer exists.
833 talloc_free_children(inst);
836 * Decrements the reference count. The driver object won't be unloaded
837 * until all instances of rlm_sql that use it have been destroyed.
839 if (inst->handle) dlclose(inst->handle);
844 static int mod_bootstrap(CONF_SECTION *conf, void *instance)
846 rlm_sql_t *inst = instance;
851 inst->config = &inst->myconfig;
854 inst->name = cf_section_name2(conf);
855 if (!inst->name) inst->name = cf_section_name1(conf);
858 * Load the appropriate driver for our database.
860 * We need this to check if the sql_fields callback is provided.
862 inst->handle = fr_dlopenext(inst->config->sql_driver_name);
864 ERROR("Could not link driver %s: %s", inst->config->sql_driver_name, fr_strerror());
865 ERROR("Make sure it (and all its dependent libraries!) are in the search path of your system's ld");
869 inst->module = (rlm_sql_module_t *) dlsym(inst->handle, inst->config->sql_driver_name);
871 ERROR("Could not link symbol %s: %s", inst->config->sql_driver_name, dlerror());
875 INFO("rlm_sql (%s): Driver %s (module %s) loaded and linked", inst->name,
876 inst->config->sql_driver_name, inst->module->name);
878 if (inst->config->groupmemb_query) {
879 if (cf_section_name2(conf)) {
882 snprintf(buffer, sizeof(buffer), "%s-SQL-Group", inst->name);
884 if (paircompare_register_byname(buffer, dict_attrbyvalue(PW_USER_NAME, 0),
885 false, sql_groupcmp, inst) < 0) {
886 ERROR("Error registering group comparison: %s", fr_strerror());
890 inst->group_da = dict_attrbyname(buffer);
893 * We're the default instance
896 if (paircompare_register_byname("SQL-Group", dict_attrbyvalue(PW_USER_NAME, 0),
897 false, sql_groupcmp, inst) < 0) {
898 ERROR("Error registering group comparison: %s", fr_strerror());
902 inst->group_da = dict_attrbyname("SQL-Group");
905 if (!inst->group_da) {
906 ERROR("Failed resolving group attribute");
912 * Register the SQL xlat function
914 xlat_register(inst->name, sql_xlat, sql_escape_func, inst);
920 static int mod_instantiate(CONF_SECTION *conf, void *instance)
922 rlm_sql_t *inst = instance;
925 * Complain if the strings exist, but are empty.
927 #define CHECK_STRING(_x) if (inst->config->_x && !inst->config->_x[0]) \
929 WARN("rlm_sql (%s): " STRINGIFY(_x) " is empty. Please delete it from the configuration", inst->name);\
930 inst->config->_x = NULL;\
933 CHECK_STRING(groupmemb_query);
934 CHECK_STRING(authorize_check_query);
935 CHECK_STRING(authorize_reply_query);
936 CHECK_STRING(authorize_group_check_query);
937 CHECK_STRING(authorize_group_reply_query);
938 CHECK_STRING(simul_count_query);
939 CHECK_STRING(simul_verify_query);
940 CHECK_STRING(connect_query);
941 CHECK_STRING(client_query);
942 if (strncmp(inst->config->sql_driver_name, "rlm_sql_", 8) != 0) {
943 ERROR("rlm_sql (%s): \"%s\" is NOT an SQL driver!", inst->name, inst->config->sql_driver_name);
948 * We need authorize_group_check_query or authorize_group_reply_query
949 * if group_membership_query is set.
951 * Or we need group_membership_query if authorize_group_check_query or
952 * authorize_group_reply_query is set.
954 if (!inst->config->groupmemb_query) {
955 if (inst->config->authorize_group_check_query) {
956 WARN("rlm_sql (%s): Ignoring authorize_group_reply_query as group_membership_query "
957 "is not configured", inst->name);
960 if (inst->config->authorize_group_reply_query) {
961 WARN("rlm_sql (%s): Ignoring authorize_group_check_query as group_membership_query "
962 "is not configured", inst->name);
965 if (!inst->config->read_groups) {
966 WARN("rlm_sql (%s): Ignoring read_groups as group_membership_query "
967 "is not configured", inst->name);
968 inst->config->read_groups = false;
970 } /* allow the group check / reply queries to be NULL */
973 * This will always exist, as cf_section_parse_init()
974 * will create it if it doesn't exist. However, the
975 * "reference" config item won't exist in an auto-created
976 * configuration. So if that doesn't exist, we ignore
977 * the whole subsection.
979 inst->config->accounting.cs = cf_section_sub_find(conf, "accounting");
980 inst->config->accounting.reference_cp = (cf_pair_find(inst->config->accounting.cs, "reference") != NULL);
982 inst->config->postauth.cs = cf_section_sub_find(conf, "post-auth");
983 inst->config->postauth.reference_cp = (cf_pair_find(inst->config->postauth.cs, "reference") != NULL);
986 * Cache the SQL-User-Name DICT_ATTR, so we can be slightly
987 * more efficient about creating SQL-User-Name attributes.
989 inst->sql_user = dict_attrbyname("SQL-User-Name");
990 if (!inst->sql_user) {
995 * Export these methods, too. This avoids RTDL_GLOBAL.
997 inst->sql_set_user = sql_set_user;
998 inst->sql_escape_func = sql_escape_func;
999 inst->sql_query = rlm_sql_query;
1000 inst->sql_select_query = rlm_sql_select_query;
1001 inst->sql_fetch_row = rlm_sql_fetch_row;
1003 if (inst->module->mod_instantiate) {
1007 name = strrchr(inst->config->sql_driver_name, '_');
1009 name = inst->config->sql_driver_name;
1014 cs = cf_section_sub_find(conf, name);
1016 cs = cf_section_alloc(conf, name, NULL);
1023 * It's up to the driver to register a destructor
1025 if (inst->module->mod_instantiate(cs, inst->config) < 0) {
1030 inst->ef = exfile_init(inst, 256, 30, true);
1032 cf_log_err_cs(conf, "Failed creating log file context");
1037 * Initialise the connection pool for this instance
1039 INFO("rlm_sql (%s): Attempting to connect to database \"%s\"", inst->name, inst->config->sql_db);
1041 inst->pool = fr_connection_pool_module_init(inst->cs, inst, mod_conn_create, NULL, NULL);
1042 if (!inst->pool) return -1;
1044 if (inst->config->do_clients) {
1045 if (generate_sql_clients(inst) == -1){
1046 ERROR("Failed to load clients from SQL");
1051 return RLM_MODULE_OK;
1054 static rlm_rcode_t mod_authorize(void *instance, REQUEST *request) CC_HINT(nonnull);
1055 static rlm_rcode_t mod_authorize(void *instance, REQUEST *request)
1057 rlm_rcode_t rcode = RLM_MODULE_NOOP;
1059 rlm_sql_t *inst = instance;
1060 rlm_sql_handle_t *handle;
1062 VALUE_PAIR *check_tmp = NULL;
1063 VALUE_PAIR *reply_tmp = NULL;
1064 VALUE_PAIR *user_profile = NULL;
1066 bool user_found = false;
1068 sql_fall_through_t do_fall_through = FALL_THROUGH_DEFAULT;
1072 char *expanded = NULL;
1074 rad_assert(request->packet != NULL);
1075 rad_assert(request->reply != NULL);
1077 if (!inst->config->authorize_check_query && !inst->config->authorize_reply_query &&
1078 !inst->config->read_groups && !inst->config->read_profiles) {
1079 RWDEBUG("No authorization checks configured, returning noop");
1081 return RLM_MODULE_NOOP;
1085 * Set, escape, and check the user attr here
1087 if (sql_set_user(inst, request, NULL) < 0) {
1088 return RLM_MODULE_FAIL;
1094 * After this point use goto error or goto release to cleanup socket temporary pairlists and
1095 * temporary attributes.
1097 handle = fr_connection_get(inst->pool);
1099 rcode = RLM_MODULE_FAIL;
1104 * Query the check table to find any conditions associated with this user/realm/whatever...
1106 if (inst->config->authorize_check_query) {
1110 if (radius_axlat(&expanded, request, inst->config->authorize_check_query,
1111 sql_escape_func, inst) < 0) {
1112 REDEBUG("Error generating query");
1113 rcode = RLM_MODULE_FAIL;
1117 rows = sql_getvpdata(request, inst, request, &handle, &check_tmp, expanded);
1118 TALLOC_FREE(expanded);
1120 REDEBUG("Error getting check attributes");
1121 rcode = RLM_MODULE_FAIL;
1125 if (rows == 0) goto skipreply; /* Don't need to free VPs we don't have */
1128 * Only do this if *some* check pairs were returned
1130 RDEBUG2("User found in radcheck table");
1132 if (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) != 0) {
1133 fr_pair_list_free(&check_tmp);
1138 RDEBUG2("Conditional check items matched, merging assignment check items");
1140 for (vp = fr_cursor_init(&cursor, &check_tmp);
1142 vp = fr_cursor_next(&cursor)) {
1143 if (!fr_assignment_op[vp->op]) continue;
1145 rdebug_pair(2, request, vp, NULL);
1148 radius_pairmove(request, &request->config, check_tmp, true);
1150 rcode = RLM_MODULE_OK;
1154 if (inst->config->authorize_reply_query) {
1156 * Now get the reply pairs since the paircompare matched
1158 if (radius_axlat(&expanded, request, inst->config->authorize_reply_query,
1159 sql_escape_func, inst) < 0) {
1160 REDEBUG("Error generating query");
1161 rcode = RLM_MODULE_FAIL;
1165 rows = sql_getvpdata(request->reply, inst, request, &handle, &reply_tmp, expanded);
1166 TALLOC_FREE(expanded);
1168 REDEBUG("SQL query error getting reply attributes");
1169 rcode = RLM_MODULE_FAIL;
1173 if (rows == 0) goto skipreply;
1175 do_fall_through = fall_through(reply_tmp);
1177 RDEBUG2("User found in radreply table, merging reply items");
1180 rdebug_pair_list(L_DBG_LVL_2, request, reply_tmp, NULL);
1182 radius_pairmove(request, &request->reply->vps, reply_tmp, true);
1184 rcode = RLM_MODULE_OK;
1189 * Neither group checks or profiles will work without
1190 * a group membership query.
1192 if (!inst->config->groupmemb_query) goto release;
1195 if ((do_fall_through == FALL_THROUGH_YES) ||
1196 (inst->config->read_groups && (do_fall_through == FALL_THROUGH_DEFAULT))) {
1199 RDEBUG3("... falling-through to group processing");
1200 ret = rlm_sql_process_groups(inst, request, &handle, &do_fall_through);
1203 * Nothing bad happened, continue...
1205 case RLM_MODULE_UPDATED:
1206 rcode = RLM_MODULE_UPDATED;
1209 if (rcode != RLM_MODULE_UPDATED) {
1210 rcode = RLM_MODULE_OK;
1213 case RLM_MODULE_NOOP:
1217 case RLM_MODULE_NOTFOUND:
1227 * Repeat the above process with the default profile or User-Profile
1229 if ((do_fall_through == FALL_THROUGH_YES) ||
1230 (inst->config->read_profiles && (do_fall_through == FALL_THROUGH_DEFAULT))) {
1234 * Check for a default_profile or for a User-Profile.
1236 RDEBUG3("... falling-through to profile processing");
1237 user_profile = fr_pair_find_by_num(request->config, PW_USER_PROFILE, 0, TAG_ANY);
1239 char const *profile = user_profile ?
1240 user_profile->vp_strvalue :
1241 inst->config->default_profile;
1243 if (!profile || !*profile) {
1247 RDEBUG2("Checking profile %s", profile);
1249 if (sql_set_user(inst, request, profile) < 0) {
1250 REDEBUG("Error setting profile");
1251 rcode = RLM_MODULE_FAIL;
1255 ret = rlm_sql_process_groups(inst, request, &handle, &do_fall_through);
1258 * Nothing bad happened, continue...
1260 case RLM_MODULE_UPDATED:
1261 rcode = RLM_MODULE_UPDATED;
1264 if (rcode != RLM_MODULE_UPDATED) {
1265 rcode = RLM_MODULE_OK;
1268 case RLM_MODULE_NOOP:
1272 case RLM_MODULE_NOTFOUND:
1282 * At this point the key (user) hasn't be found in the check table, the reply table
1283 * or the group mapping table, and there was no matching profile.
1287 rcode = RLM_MODULE_NOTFOUND;
1290 fr_connection_release(inst->pool, handle);
1291 sql_unset_user(inst, request);
1296 fr_pair_list_free(&check_tmp);
1297 fr_pair_list_free(&reply_tmp);
1298 sql_unset_user(inst, request);
1300 fr_connection_release(inst->pool, handle);
1306 * Generic function for failing between a bunch of queries.
1308 * Uses the same principle as rlm_linelog, expanding the 'reference' config
1309 * item using xlat to figure out what query it should execute.
1311 * If the reference matches multiple config items, and a query fails or
1312 * doesn't update any rows, the next matching config item is used.
1315 static int acct_redundant(rlm_sql_t *inst, REQUEST *request, sql_acct_section_t *section)
1317 rlm_rcode_t rcode = RLM_MODULE_OK;
1319 rlm_sql_handle_t *handle = NULL;
1321 int numaffected = 0;
1325 char const *attr = NULL;
1328 char path[MAX_STRING_LEN];
1330 char *expanded = NULL;
1332 rad_assert(section);
1334 if (section->reference[0] != '.') {
1338 if (radius_xlat(p, sizeof(path) - (p - path), request, section->reference, NULL, NULL) < 0) {
1339 rcode = RLM_MODULE_FAIL;
1345 * If we can't find a matching config item we do
1346 * nothing so return RLM_MODULE_NOOP.
1348 item = cf_reference_item(NULL, section->cs, path);
1350 RWDEBUG("No such configuration item %s", path);
1351 rcode = RLM_MODULE_NOOP;
1355 if (cf_item_is_section(item)){
1356 RWDEBUG("Sections are not supported as references");
1357 rcode = RLM_MODULE_NOOP;
1362 pair = cf_item_to_pair(item);
1363 attr = cf_pair_attr(pair);
1365 RDEBUG2("Using query template '%s'", attr);
1367 handle = fr_connection_get(inst->pool);
1369 rcode = RLM_MODULE_FAIL;
1374 sql_set_user(inst, request, NULL);
1377 value = cf_pair_value(pair);
1379 RDEBUG("Ignoring null query");
1380 rcode = RLM_MODULE_NOOP;
1385 if (radius_axlat(&expanded, request, value, sql_escape_func, inst) < 0) {
1386 rcode = RLM_MODULE_FAIL;
1392 RDEBUG("Ignoring null query");
1393 rcode = RLM_MODULE_NOOP;
1394 talloc_free(expanded);
1399 rlm_sql_query_log(inst, request, section, expanded);
1401 sql_ret = rlm_sql_query(inst, request, &handle, expanded);
1402 TALLOC_FREE(expanded);
1403 RDEBUG("SQL query returned: %s", fr_int2str(sql_rcode_table, sql_ret, "<INVALID>"));
1407 * Query was a success! Now we just need to check if it did anything.
1413 * A general, unrecoverable server fault.
1417 * If we get RLM_SQL_RECONNECT it means all connections in the pool
1418 * were exhausted, and we couldn't create a new connection,
1419 * so we do not need to call fr_connection_release.
1421 case RLM_SQL_RECONNECT:
1422 rcode = RLM_MODULE_FAIL;
1426 * Query was invalid, this is a terminal error, but we still need
1427 * to do cleanup, as the connection handle is still valid.
1429 case RLM_SQL_QUERY_INVALID:
1430 rcode = RLM_MODULE_INVALID;
1434 * Driver found an error (like a unique key constraint violation)
1435 * that hinted it might be a good idea to try an alternative query.
1437 case RLM_SQL_ALT_QUERY:
1443 * We need to have updated something for the query to have been
1444 * counted as successful.
1446 numaffected = (inst->module->sql_affected_rows)(handle, inst->config);
1447 (inst->module->sql_finish_query)(handle, inst->config);
1448 RDEBUG("%i record(s) updated", numaffected);
1450 if (numaffected > 0) break; /* A query succeeded, were done! */
1453 * We assume all entries with the same name form a redundant
1456 pair = cf_pair_find_next(section->cs, pair, attr);
1459 RDEBUG("No additional queries configured");
1460 rcode = RLM_MODULE_NOOP;
1465 RDEBUG("Trying next query...");
1470 talloc_free(expanded);
1471 fr_connection_release(inst->pool, handle);
1472 sql_unset_user(inst, request);
1477 #ifdef WITH_ACCOUNTING
1480 * Accounting: Insert or update session data in our sql table
1482 static rlm_rcode_t mod_accounting(void *instance, REQUEST *request) CC_HINT(nonnull);
1483 static rlm_rcode_t mod_accounting(void *instance, REQUEST *request)
1485 rlm_sql_t *inst = instance;
1487 if (inst->config->accounting.reference_cp) {
1488 return acct_redundant(inst, request, &inst->config->accounting);
1491 return RLM_MODULE_NOOP;
1496 #ifdef WITH_SESSION_MGMT
1498 * See if a user is already logged in. Sets request->simul_count to the
1499 * current session count for this user.
1501 * Check twice. If on the first pass the user exceeds his
1502 * max. number of logins, do a second pass and validate all
1503 * logins by querying the terminal server (using eg. SNMP).
1505 static rlm_rcode_t mod_checksimul(void *instance, REQUEST *request) CC_HINT(nonnull);
1506 static rlm_rcode_t mod_checksimul(void *instance, REQUEST * request)
1508 rlm_rcode_t rcode = RLM_MODULE_OK;
1509 rlm_sql_handle_t *handle = NULL;
1510 rlm_sql_t *inst = instance;
1514 char const *call_num = NULL;
1517 uint32_t nas_addr = 0;
1518 uint32_t nas_port = 0;
1520 char *expanded = NULL;
1522 /* If simul_count_query is not defined, we don't do any checking */
1523 if (!inst->config->simul_count_query) {
1524 RWDEBUG("Simultaneous-Use checking requires 'simul_count_query' to be configured");
1525 return RLM_MODULE_NOOP;
1528 if ((!request->username) || (request->username->vp_length == 0)) {
1529 REDEBUG("Zero Length username not permitted");
1531 return RLM_MODULE_INVALID;
1534 if (sql_set_user(inst, request, NULL) < 0) {
1535 return RLM_MODULE_FAIL;
1538 if (radius_axlat(&expanded, request, inst->config->simul_count_query, sql_escape_func, inst) < 0) {
1539 sql_unset_user(inst, request);
1540 return RLM_MODULE_FAIL;
1543 /* initialize the sql socket */
1544 handle = fr_connection_get(inst->pool);
1546 talloc_free(expanded);
1547 sql_unset_user(inst, request);
1548 return RLM_MODULE_FAIL;
1551 if (rlm_sql_select_query(inst, request, &handle, expanded) != RLM_SQL_OK) {
1552 rcode = RLM_MODULE_FAIL;
1553 goto release; /* handle may no longer be valid */
1556 ret = rlm_sql_fetch_row(inst, request, &handle);
1558 rcode = RLM_MODULE_FAIL;
1564 rcode = RLM_MODULE_FAIL;
1568 request->simul_count = atoi(row[0]);
1570 (inst->module->sql_finish_select_query)(handle, inst->config);
1571 TALLOC_FREE(expanded);
1573 if (request->simul_count < request->simul_max) {
1574 rcode = RLM_MODULE_OK;
1579 * Looks like too many sessions, so let's start verifying
1580 * them, unless told to rely on count query only.
1582 if (!inst->config->simul_verify_query) {
1583 rcode = RLM_MODULE_OK;
1588 if (radius_axlat(&expanded, request, inst->config->simul_verify_query, sql_escape_func, inst) < 0) {
1589 rcode = RLM_MODULE_FAIL;
1594 if (rlm_sql_select_query(inst, request, &handle, expanded) != RLM_SQL_OK) goto release;
1597 * Setup some stuff, like for MPP detection.
1599 request->simul_count = 0;
1601 if ((vp = fr_pair_find_by_num(request->packet->vps, PW_FRAMED_IP_ADDRESS, 0, TAG_ANY)) != NULL) {
1602 ipno = vp->vp_ipaddr;
1605 if ((vp = fr_pair_find_by_num(request->packet->vps, PW_CALLING_STATION_ID, 0, TAG_ANY)) != NULL) {
1606 call_num = vp->vp_strvalue;
1609 while (rlm_sql_fetch_row(inst, request, &handle) == RLM_SQL_OK) {
1617 num_rows = (inst->module->sql_num_fields)(handle, inst->config);
1619 RDEBUG("Too few rows returned. Please do not edit 'simul_verify_query'");
1620 rcode = RLM_MODULE_FAIL;
1626 RDEBUG("Cannot zap stale entry. No username present in entry");
1627 rcode = RLM_MODULE_FAIL;
1633 RDEBUG("Cannot zap stale entry. No session id in entry");
1634 rcode = RLM_MODULE_FAIL;
1640 nas_addr = inet_addr(row[3]);
1644 nas_port = atoi(row[4]);
1647 check = rad_check_ts(nas_addr, nas_port, row[2], row[1]);
1650 * Stale record - zap it.
1652 if (inst->config->delete_stale_sessions == true) {
1653 uint32_t framed_addr = 0;
1658 framed_addr = inet_addr(row[5]);
1660 if (strcmp(row[7], "PPP") == 0)
1662 else if (strcmp(row[7], "SLIP") == 0)
1665 if ((num_rows > 8) && row[8])
1666 sess_time = atoi(row[8]);
1667 session_zap(request, nas_addr, nas_port,
1668 row[2], row[1], framed_addr,
1672 else if (check == 1) {
1674 * User is still logged in.
1676 ++request->simul_count;
1679 * Does it look like a MPP attempt?
1681 if (row[5] && ipno && inet_addr(row[5]) == ipno) {
1682 request->simul_mpp = 2;
1683 } else if (row[6] && call_num && !strncmp(row[6],call_num,16)) {
1684 request->simul_mpp = 2;
1688 * Failed to check the terminal server for
1689 * duplicate logins: return an error.
1691 REDEBUG("Failed to check the terminal server for user '%s'.", row[2]);
1693 rcode = RLM_MODULE_FAIL;
1699 (inst->module->sql_finish_select_query)(handle, inst->config);
1701 fr_connection_release(inst->pool, handle);
1702 talloc_free(expanded);
1703 sql_unset_user(inst, request);
1706 * The Auth module apparently looks at request->simul_count,
1707 * not the return value of this module when deciding to deny
1708 * a call for too many sessions.
1715 * Postauth: Write a record of the authentication attempt
1717 static rlm_rcode_t mod_post_auth(void *instance, REQUEST *request) CC_HINT(nonnull);
1718 static rlm_rcode_t mod_post_auth(void *instance, REQUEST *request)
1720 rlm_sql_t *inst = instance;
1722 if (inst->config->postauth.reference_cp) {
1723 return acct_redundant(inst, request, &inst->config->postauth);
1726 return RLM_MODULE_NOOP;
1730 * Execute postauth_query after authentication
1734 /* globally exported name */
1735 extern module_t rlm_sql;
1736 module_t rlm_sql = {
1737 .magic = RLM_MODULE_INIT,
1739 .type = RLM_TYPE_THREAD_SAFE,
1740 .inst_size = sizeof(rlm_sql_t),
1741 .config = module_config,
1742 .bootstrap = mod_bootstrap,
1743 .instantiate = mod_instantiate,
1744 .detach = mod_detach,
1746 [MOD_AUTHORIZE] = mod_authorize,
1747 #ifdef WITH_ACCOUNTING
1748 [MOD_ACCOUNTING] = mod_accounting,
1750 #ifdef WITH_SESSION_MGMT
1751 [MOD_SESSION] = mod_checksimul,
1753 [MOD_POST_AUTH] = mod_post_auth