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;
160 * Add SQL-User-Name attribute just in case it is needed
161 * We could search the string fmt for SQL-User-Name to see if this is
164 sql_set_user(inst, request, NULL);
166 handle = fr_connection_get(inst->pool);
171 rlm_sql_query_log(inst, request, NULL, query);
174 * If the query starts with any of the following prefixes,
175 * then return the number of rows affected
177 if ((strncasecmp(query, "insert", 6) == 0) ||
178 (strncasecmp(query, "update", 6) == 0) ||
179 (strncasecmp(query, "delete", 6) == 0)) {
181 char buffer[21]; /* 64bit max is 20 decimal chars + null byte */
183 if (rlm_sql_query(inst, request, &handle, query) != RLM_SQL_OK) {
184 RERROR("SQL query failed");
190 numaffected = (inst->module->sql_affected_rows)(handle, inst->config);
191 if (numaffected < 1) {
192 RDEBUG("SQL query affected no rows");
198 * Don't chop the returned number if freespace is
199 * too small. This hack is necessary because
200 * some implementations of snprintf return the
201 * size of the written data, and others return
202 * the size of the data they *would* have written
203 * if the output buffer was large enough.
205 snprintf(buffer, sizeof(buffer), "%d", numaffected);
207 len = strlen(buffer);
208 if (len >= freespace){
209 RDEBUG("rlm_sql (%s): Can't write result, insufficient string space", inst->name);
211 (inst->module->sql_finish_query)(handle, inst->config);
217 memcpy(out, buffer, len + 1); /* we did bounds checking above */
220 (inst->module->sql_finish_query)(handle, inst->config);
223 } /* else it's a SELECT statement */
225 if (rlm_sql_select_query(inst, request, &handle, query) != RLM_SQL_OK) {
226 ret = -1; /* error handled by rlm_sql_select_query */
231 ret = rlm_sql_fetch_row(inst, request, &handle);
233 REDEBUG("SQL query failed");
234 (inst->module->sql_finish_select_query)(handle, inst->config);
242 RDEBUG("SQL query returned no results");
243 (inst->module->sql_finish_select_query)(handle, inst->config);
250 RDEBUG("NULL value in first column of result");
251 (inst->module->sql_finish_select_query)(handle, inst->config);
257 len = strlen(row[0]);
258 if (len >= freespace){
259 RDEBUG("Insufficient string space");
260 (inst->module->sql_finish_select_query)(handle, inst->config);
266 strlcpy(out, row[0], freespace);
269 (inst->module->sql_finish_select_query)(handle, inst->config);
272 fr_connection_release(inst->pool, handle);
277 static int generate_sql_clients(rlm_sql_t *inst)
279 rlm_sql_handle_t *handle;
284 DEBUG("rlm_sql (%s): Processing generate_sql_clients",
287 DEBUG("rlm_sql (%s) in generate_sql_clients: query is %s",
288 inst->name, inst->config->client_query);
290 handle = fr_connection_get(inst->pool);
295 if (rlm_sql_select_query(inst, NULL, &handle, inst->config->client_query) != RLM_SQL_OK) return -1;
297 while ((rlm_sql_fetch_row(inst, NULL, &handle) == 0) && (row = handle->row)) {
302 * The return data for each row MUST be in the following order:
304 * 0. Row ID (currently unused)
305 * 1. Name (or IP address)
309 * 5. Virtual Server (optional)
312 ERROR("rlm_sql (%s): No row id found on pass %d",inst->name,i);
316 ERROR("rlm_sql (%s): No nasname found for row %s",inst->name,row[0]);
320 ERROR("rlm_sql (%s): No short name found for row %s",inst->name,row[0]);
324 ERROR("rlm_sql (%s): No secret found for row %s",inst->name,row[0]);
328 if (((inst->module->sql_num_fields)(handle, inst->config) > 5) && (row[5] != NULL) && *row[5]) {
332 DEBUG("rlm_sql (%s): Adding client %s (%s) to %s clients list",
334 row[1], row[2], server ? server : "global");
336 /* FIXME: We should really pass a proper ctx */
337 c = client_afrom_query(NULL,
338 row[1], /* identifier */
340 row[2], /* shortname */
343 false); /* require message authenticator */
348 if (!client_add(NULL, c)) {
349 WARN("Failed to add client, possible duplicate?");
355 DEBUG("rlm_sql (%s): Client \"%s\" (%s) added", c->longname, c->shortname,
359 (inst->module->sql_finish_select_query)(handle, inst->config);
360 fr_connection_release(inst->pool, handle);
367 * Translate the SQL queries.
369 static size_t sql_escape_func(UNUSED REQUEST *request, char *out, size_t outlen,
370 char const *in, void *arg)
372 rlm_sql_t *inst = arg;
379 * Allow all multi-byte UTF8 characters.
381 utf8_len = fr_utf8_char((uint8_t const *) in);
383 if (outlen <= utf8_len) break;
385 memcpy(out, in, utf8_len);
395 * Because we register our own escape function
396 * we're now responsible for escaping all special
397 * chars in an xlat expansion or attribute value.
401 if (outlen <= 2) break;
412 if (outlen <= 2) break;
423 if (outlen <= 2) break;
435 * Non-printable characters get replaced with their
436 * mime-encoded equivalents.
439 strchr(inst->config->allowed_chars, *in) == NULL) {
441 * Only 3 or less bytes available.
447 snprintf(out, outlen, "=%02X", (unsigned char) in[0]);
456 * Only one byte left.
476 * Set the SQL user name.
478 * We don't call the escape function here. The resulting string
479 * will be escaped later in the queries xlat so we don't need to
480 * escape it twice. (it will make things wrong if we have an
481 * escape candidate character in the username)
483 int sql_set_user(rlm_sql_t *inst, REQUEST *request, char const *username)
485 char *expanded = NULL;
486 VALUE_PAIR *vp = NULL;
490 rad_assert(request->packet != NULL);
492 if (username != NULL) {
494 } else if (inst->config->query_user[0] != '\0') {
495 sqluser = inst->config->query_user;
500 len = radius_axlat(&expanded, request, sqluser, NULL, NULL);
505 vp = pairalloc(request->packet, inst->sql_user);
507 talloc_free(expanded);
511 pairstrsteal(vp, expanded);
512 RDEBUG2("SQL-User-Name set to '%s'", vp->vp_strvalue);
514 radius_pairmove(request, &request->packet->vps, vp, false); /* needs to be pair move else op is not respected */
520 * Do a set/unset user, so it's a bit clearer what's going on.
522 #define sql_unset_user(_i, _r) pairdelete(&_r->packet->vps, _i->sql_user->attr, _i->sql_user->vendor, TAG_ANY)
524 static int sql_get_grouplist(rlm_sql_t *inst, rlm_sql_handle_t **handle, REQUEST *request,
525 rlm_sql_grouplist_t **phead)
527 char *expanded = NULL;
530 rlm_sql_grouplist_t *entry;
533 /* NOTE: sql_set_user should have been run before calling this function */
535 entry = *phead = NULL;
537 if (!inst->config->groupmemb_query) return 0;
539 if (radius_axlat(&expanded, request, inst->config->groupmemb_query, sql_escape_func, inst) < 0) return -1;
541 ret = rlm_sql_select_query(inst, request, handle, expanded);
542 talloc_free(expanded);
543 if (ret != RLM_SQL_OK) return -1;
545 while (rlm_sql_fetch_row(inst, request, handle) == 0) {
546 row = (*handle)->row;
551 RDEBUG("row[0] returned NULL");
552 (inst->module->sql_finish_select_query)(*handle, inst->config);
558 *phead = talloc_zero(*handle, rlm_sql_grouplist_t);
561 entry->next = talloc_zero(*phead, rlm_sql_grouplist_t);
565 entry->name = talloc_typed_strdup(entry, row[0]);
570 (inst->module->sql_finish_select_query)(*handle, inst->config);
577 * sql groupcmp function. That way we can do group comparisons (in the users file for example)
578 * with the group memberships reciding in sql
579 * The group membership query should only return one element which is the username. The returned
580 * username will then be checked with the passed check string.
583 static int CC_HINT(nonnull (1, 2, 4)) sql_groupcmp(void *instance, REQUEST *request, UNUSED VALUE_PAIR *request_vp,
584 VALUE_PAIR *check, UNUSED VALUE_PAIR *check_pairs,
585 UNUSED VALUE_PAIR **reply_pairs)
587 rlm_sql_handle_t *handle;
588 rlm_sql_t *inst = instance;
589 rlm_sql_grouplist_t *head, *entry;
591 RDEBUG("sql_groupcmp");
593 if (check->vp_length == 0){
594 RDEBUG("sql_groupcmp: Illegal group name");
599 * Set, escape, and check the user attr here
601 if (sql_set_user(inst, request, NULL) < 0)
605 * Get a socket for this lookup
607 handle = fr_connection_get(inst->pool);
613 * Get the list of groups this user is a member of
615 if (sql_get_grouplist(inst, &handle, request, &head) < 0) {
616 REDEBUG("Error getting group membership");
617 fr_connection_release(inst->pool, handle);
621 for (entry = head; entry != NULL; entry = entry->next) {
622 if (strcmp(entry->name, check->vp_strvalue) == 0){
623 RDEBUG("sql_groupcmp finished: User is a member of group %s",
626 fr_connection_release(inst->pool, handle);
631 /* Free the grouplist */
633 fr_connection_release(inst->pool, handle);
635 RDEBUG("sql_groupcmp finished: User is NOT a member of group %s", check->vp_strvalue);
640 static rlm_rcode_t rlm_sql_process_groups(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle,
641 sql_fall_through_t *do_fall_through)
643 rlm_rcode_t rcode = RLM_MODULE_NOOP;
644 VALUE_PAIR *check_tmp = NULL, *reply_tmp = NULL, *sql_group = NULL;
645 rlm_sql_grouplist_t *head = NULL, *entry = NULL;
647 char *expanded = NULL;
650 rad_assert(request->packet != NULL);
653 * Get the list of groups this user is a member of
655 rows = sql_get_grouplist(inst, handle, request, &head);
657 REDEBUG("Error retrieving group list");
659 return RLM_MODULE_FAIL;
662 RDEBUG2("User not found in any groups");
663 rcode = RLM_MODULE_NOTFOUND;
664 *do_fall_through = FALL_THROUGH_DEFAULT;
670 RDEBUG2("User found in the group table");
673 * Add the Sql-Group attribute to the request list so we know
674 * which group we're retrieving attributes for
676 sql_group = pairmake_packet("Sql-Group", NULL, T_OP_EQ);
678 REDEBUG("Error creating Sql-Group attribute");
679 rcode = RLM_MODULE_FAIL;
686 rad_assert(entry != NULL);
687 pairstrcpy(sql_group, entry->name);
689 if (inst->config->authorize_group_check_query) {
694 * Expand the group query
696 if (radius_axlat(&expanded, request, inst->config->authorize_group_check_query,
697 sql_escape_func, inst) < 0) {
698 REDEBUG("Error generating query");
699 rcode = RLM_MODULE_FAIL;
703 rows = sql_getvpdata(request, inst, request, handle, &check_tmp, expanded);
704 TALLOC_FREE(expanded);
706 REDEBUG("Error retrieving check pairs for group %s", entry->name);
707 rcode = RLM_MODULE_FAIL;
712 * If we got check rows we need to process them before we decide to
713 * process the reply rows
716 (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) != 0)) {
717 pairfree(&check_tmp);
720 goto next; /* != continue */
723 RDEBUG2("Group \"%s\": Conditional check items matched", entry->name);
724 rcode = RLM_MODULE_OK;
726 RDEBUG2("Group \"%s\": Merging assignment check items", entry->name);
728 for (vp = fr_cursor_init(&cursor, &check_tmp);
730 vp = fr_cursor_next(&cursor)) {
731 if (!fr_assignment_op[vp->op]) continue;
733 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
736 radius_pairmove(request, &request->config_items, check_tmp, true);
740 if (inst->config->authorize_group_reply_query) {
742 * Now get the reply pairs since the paircompare matched
744 if (radius_axlat(&expanded, request, inst->config->authorize_group_reply_query,
745 sql_escape_func, inst) < 0) {
746 REDEBUG("Error generating query");
747 rcode = RLM_MODULE_FAIL;
751 rows = sql_getvpdata(request->reply, inst, request, handle, &reply_tmp, expanded);
752 TALLOC_FREE(expanded);
754 REDEBUG("Error retrieving reply pairs for group %s", entry->name);
755 rcode = RLM_MODULE_FAIL;
758 *do_fall_through = fall_through(reply_tmp);
760 RDEBUG2("Group \"%s\": Merging reply items", entry->name);
761 rcode = RLM_MODULE_OK;
763 rdebug_pair_list(L_DBG_LVL_2, request, reply_tmp, NULL);
765 radius_pairmove(request, &request->reply->vps, reply_tmp, true);
768 * If there's no reply query configured, then we assume
769 * FALL_THROUGH_NO, which is the same as the users file if you
770 * had no reply attributes.
773 *do_fall_through = FALL_THROUGH_DEFAULT;
777 } while (entry != NULL && (*do_fall_through == FALL_THROUGH_YES));
781 pairdelete(&request->packet->vps, PW_SQL_GROUP, 0, TAG_ANY);
787 static int mod_detach(void *instance)
789 rlm_sql_t *inst = instance;
791 if (inst->pool) fr_connection_pool_delete(inst->pool);
794 * We need to explicitly free all children, so if the driver
795 * parented any memory off the instance, their destructors
796 * run before we unload the bytecode for them.
798 * If we don't do this, we get a SEGV deep inside the talloc code
799 * when it tries to call a destructor that no longer exists.
801 talloc_free_children(inst);
804 * Decrements the reference count. The driver object won't be unloaded
805 * until all instances of rlm_sql that use it have been destroyed.
807 if (inst->handle) dlclose(inst->handle);
812 static int mod_instantiate(CONF_SECTION *conf, void *instance)
814 rlm_sql_t *inst = instance;
819 inst->config = &inst->myconfig;
822 inst->name = cf_section_name2(conf);
824 inst->name = cf_section_name1(conf);
831 * Allocate room for <instance>-SQL-Group
833 group_name = talloc_typed_asprintf(inst, "%s-SQL-Group", inst->name);
834 DEBUG("rlm_sql (%s): Creating new attribute %s",
835 inst->name, group_name);
837 memset(&flags, 0, sizeof(flags));
838 if (dict_addattr(group_name, -1, 0, PW_TYPE_STRING, flags) < 0) {
839 ERROR("rlm_sql (%s): Failed to create "
840 "attribute %s: %s", inst->name, group_name,
845 da = dict_attrbyname(group_name);
847 ERROR("rlm_sql (%s): Failed to create "
848 "attribute %s", inst->name, group_name);
852 if (inst->config->groupmemb_query) {
853 DEBUG("rlm_sql (%s): Registering sql_groupcmp for %s",
854 inst->name, group_name);
855 paircompare_register(da, dict_attrbyvalue(PW_USER_NAME, 0),
856 false, sql_groupcmp, inst);
860 rad_assert(inst->name);
863 * Complain if the strings exist, but are empty.
865 #define CHECK_STRING(_x) if (inst->config->_x && !inst->config->_x[0]) \
867 WARN("rlm_sql (%s): " STRINGIFY(_x) " is empty. Please delete it from the configuration", inst->name);\
868 inst->config->_x = NULL;\
871 CHECK_STRING(groupmemb_query);
872 CHECK_STRING(authorize_check_query);
873 CHECK_STRING(authorize_reply_query);
874 CHECK_STRING(authorize_group_check_query);
875 CHECK_STRING(authorize_group_reply_query);
876 CHECK_STRING(simul_count_query);
877 CHECK_STRING(simul_verify_query);
878 CHECK_STRING(connect_query);
879 CHECK_STRING(client_query);
880 if (strncmp(inst->config->sql_driver_name, "rlm_sql_", 8) != 0) {
881 ERROR("rlm_sql (%s): \"%s\" is NOT an SQL driver!", inst->name, inst->config->sql_driver_name);
886 * We need authorize_group_check_query or authorize_group_reply_query
887 * if group_membership_query is set.
889 * Or we need group_membership_query if authorize_group_check_query or
890 * authorize_group_reply_query is set.
892 if (!inst->config->groupmemb_query) {
893 if (inst->config->authorize_group_check_query) {
894 WARN("rlm_sql (%s): Ignoring authorize_group_reply_query as group_membership_query "
895 "is not configured", inst->name);
898 if (inst->config->authorize_group_reply_query) {
899 WARN("rlm_sql (%s): Ignoring authorize_group_check_query as group_membership_query "
900 "is not configured", inst->name);
903 if (!inst->config->authorize_group_check_query) {
904 ERROR("rlm_sql (%s): authorize_group_check_query must be configured as group_membership_query "
905 "is configured", inst->name);
909 if (!inst->config->authorize_group_reply_query) {
910 ERROR("rlm_sql (%s): authorize_group_reply_query must be configured as group_membership_query "
911 "is configured", inst->name);
917 * This will always exist, as cf_section_parse_init()
918 * will create it if it doesn't exist. However, the
919 * "reference" config item won't exist in an auto-created
920 * configuration. So if that doesn't exist, we ignore
921 * the whole subsection.
923 inst->config->accounting.cs = cf_section_sub_find(conf, "accounting");
924 inst->config->accounting.reference_cp = (cf_pair_find(inst->config->accounting.cs, "reference") != NULL);
926 inst->config->postauth.cs = cf_section_sub_find(conf, "post-auth");
927 inst->config->postauth.reference_cp = (cf_pair_find(inst->config->postauth.cs, "reference") != NULL);
930 * Cache the SQL-User-Name DICT_ATTR, so we can be slightly
931 * more efficient about creating SQL-User-Name attributes.
933 inst->sql_user = dict_attrbyname("SQL-User-Name");
934 if (!inst->sql_user) {
939 * Export these methods, too. This avoids RTDL_GLOBAL.
941 inst->sql_set_user = sql_set_user;
942 inst->sql_escape_func = sql_escape_func;
943 inst->sql_query = rlm_sql_query;
944 inst->sql_select_query = rlm_sql_select_query;
945 inst->sql_fetch_row = rlm_sql_fetch_row;
948 * Register the SQL xlat function
950 xlat_register(inst->name, sql_xlat, sql_escape_func, inst);
953 * Load the appropriate driver for our database
955 inst->handle = lt_dlopenext(inst->config->sql_driver_name);
957 ERROR("Could not link driver %s: %s", inst->config->sql_driver_name, dlerror());
958 ERROR("Make sure it (and all its dependent libraries!) are in the search path of your system's ld");
962 inst->module = (rlm_sql_module_t *) dlsym(inst->handle,
963 inst->config->sql_driver_name);
965 ERROR("Could not link symbol %s: %s", inst->config->sql_driver_name, dlerror());
969 if (inst->module->mod_instantiate) {
973 name = strrchr(inst->config->sql_driver_name, '_');
975 name = inst->config->sql_driver_name;
980 cs = cf_section_sub_find(conf, name);
982 cs = cf_section_alloc(conf, name, NULL);
989 * It's up to the driver to register a destructor
991 if (inst->module->mod_instantiate(cs, inst->config) < 0) {
996 inst->ef = exfile_init(inst, 64, 30);
998 cf_log_err_cs(conf, "Failed creating log file context");
1002 INFO("rlm_sql (%s): Driver %s (module %s) loaded and linked", inst->name,
1003 inst->config->sql_driver_name, inst->module->name);
1006 * Initialise the connection pool for this instance
1008 INFO("rlm_sql (%s): Attempting to connect to database \"%s\"", inst->name, inst->config->sql_db);
1010 inst->pool = fr_connection_pool_module_init(inst->cs, inst, mod_conn_create, NULL, NULL);
1011 if (!inst->pool) return -1;
1013 if (inst->config->groupmemb_query) {
1014 paircompare_register(dict_attrbyvalue(PW_SQL_GROUP, 0),
1015 dict_attrbyvalue(PW_USER_NAME, 0), false, sql_groupcmp, inst);
1018 if (inst->config->do_clients) {
1019 if (generate_sql_clients(inst) == -1){
1020 ERROR("Failed to load clients from SQL");
1025 return RLM_MODULE_OK;
1029 static rlm_rcode_t CC_HINT(nonnull) mod_authorize(void *instance, REQUEST *request)
1031 rlm_rcode_t rcode = RLM_MODULE_NOOP;
1033 rlm_sql_t *inst = instance;
1034 rlm_sql_handle_t *handle;
1036 VALUE_PAIR *check_tmp = NULL;
1037 VALUE_PAIR *reply_tmp = NULL;
1038 VALUE_PAIR *user_profile = NULL;
1040 bool user_found = false;
1042 sql_fall_through_t do_fall_through = FALL_THROUGH_DEFAULT;
1046 char *expanded = NULL;
1048 rad_assert(request->packet != NULL);
1049 rad_assert(request->reply != NULL);
1051 if (!inst->config->authorize_check_query && !inst->config->authorize_reply_query &&
1052 !inst->config->read_groups && !inst->config->read_profiles) {
1053 RWDEBUG("No authorization checks configured, returning noop");
1055 return RLM_MODULE_NOOP;
1059 * Set, escape, and check the user attr here
1061 if (sql_set_user(inst, request, NULL) < 0) {
1062 return RLM_MODULE_FAIL;
1068 * After this point use goto error or goto release to cleanup socket temporary pairlists and
1069 * temporary attributes.
1071 handle = fr_connection_get(inst->pool);
1073 rcode = RLM_MODULE_FAIL;
1078 * Query the check table to find any conditions associated with this user/realm/whatever...
1080 if (inst->config->authorize_check_query) {
1084 if (radius_axlat(&expanded, request, inst->config->authorize_check_query,
1085 sql_escape_func, inst) < 0) {
1086 REDEBUG("Error generating query");
1087 rcode = RLM_MODULE_FAIL;
1091 rows = sql_getvpdata(request, inst, request, &handle, &check_tmp, expanded);
1092 TALLOC_FREE(expanded);
1094 REDEBUG("Error getting check attributes");
1095 rcode = RLM_MODULE_FAIL;
1099 if (rows == 0) goto skipreply; /* Don't need to free VPs we don't have */
1102 * Only do this if *some* check pairs were returned
1104 RDEBUG2("User found in radcheck table");
1106 if (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) != 0) {
1107 pairfree(&check_tmp);
1112 RDEBUG2("Conditional check items matched, merging assignment check items");
1114 for (vp = fr_cursor_init(&cursor, &check_tmp);
1116 vp = fr_cursor_next(&cursor)) {
1117 if (!fr_assignment_op[vp->op]) continue;
1119 rdebug_pair(2, request, vp, NULL);
1122 radius_pairmove(request, &request->config_items, check_tmp, true);
1124 rcode = RLM_MODULE_OK;
1128 if (inst->config->authorize_reply_query) {
1130 * Now get the reply pairs since the paircompare matched
1132 if (radius_axlat(&expanded, request, inst->config->authorize_reply_query,
1133 sql_escape_func, inst) < 0) {
1134 REDEBUG("Error generating query");
1135 rcode = RLM_MODULE_FAIL;
1139 rows = sql_getvpdata(request->reply, inst, request, &handle, &reply_tmp, expanded);
1140 TALLOC_FREE(expanded);
1142 REDEBUG("SQL query error getting reply attributes");
1143 rcode = RLM_MODULE_FAIL;
1147 if (rows == 0) goto skipreply;
1149 do_fall_through = fall_through(reply_tmp);
1151 RDEBUG2("User found in radreply table, merging reply items");
1154 rdebug_pair_list(L_DBG_LVL_2, request, reply_tmp, NULL);
1156 radius_pairmove(request, &request->reply->vps, reply_tmp, true);
1158 rcode = RLM_MODULE_OK;
1163 * Neither group checks or profiles will work without
1164 * a group membership query.
1166 if (!inst->config->groupmemb_query) goto release;
1169 if ((do_fall_through == FALL_THROUGH_YES) ||
1170 (inst->config->read_groups && (do_fall_through == FALL_THROUGH_DEFAULT))) {
1173 RDEBUG3("... falling-through to group processing");
1174 ret = rlm_sql_process_groups(inst, request, &handle, &do_fall_through);
1177 * Nothing bad happened, continue...
1179 case RLM_MODULE_UPDATED:
1180 rcode = RLM_MODULE_UPDATED;
1183 if (rcode != RLM_MODULE_UPDATED) {
1184 rcode = RLM_MODULE_OK;
1187 case RLM_MODULE_NOOP:
1191 case RLM_MODULE_NOTFOUND:
1201 * Repeat the above process with the default profile or User-Profile
1203 if ((do_fall_through == FALL_THROUGH_YES) ||
1204 (inst->config->read_profiles && (do_fall_through == FALL_THROUGH_DEFAULT))) {
1208 * Check for a default_profile or for a User-Profile.
1210 RDEBUG3("... falling-through to profile processing");
1211 user_profile = pairfind(request->config_items, PW_USER_PROFILE, 0, TAG_ANY);
1213 char const *profile = user_profile ?
1214 user_profile->vp_strvalue :
1215 inst->config->default_profile;
1217 if (!profile || !*profile) {
1221 RDEBUG2("Checking profile %s", profile);
1223 if (sql_set_user(inst, request, profile) < 0) {
1224 REDEBUG("Error setting profile");
1225 rcode = RLM_MODULE_FAIL;
1229 ret = rlm_sql_process_groups(inst, request, &handle, &do_fall_through);
1232 * Nothing bad happened, continue...
1234 case RLM_MODULE_UPDATED:
1235 rcode = RLM_MODULE_UPDATED;
1238 if (rcode != RLM_MODULE_UPDATED) {
1239 rcode = RLM_MODULE_OK;
1242 case RLM_MODULE_NOOP:
1246 case RLM_MODULE_NOTFOUND:
1256 * At this point the key (user) hasn't be found in the check table, the reply table
1257 * or the group mapping table, and there was no matching profile.
1261 rcode = RLM_MODULE_NOTFOUND;
1264 fr_connection_release(inst->pool, handle);
1265 sql_unset_user(inst, request);
1270 pairfree(&check_tmp);
1271 pairfree(&reply_tmp);
1272 sql_unset_user(inst, request);
1274 fr_connection_release(inst->pool, handle);
1280 * Generic function for failing between a bunch of queries.
1282 * Uses the same principle as rlm_linelog, expanding the 'reference' config
1283 * item using xlat to figure out what query it should execute.
1285 * If the reference matches multiple config items, and a query fails or
1286 * doesn't update any rows, the next matching config item is used.
1289 static int acct_redundant(rlm_sql_t *inst, REQUEST *request, sql_acct_section_t *section)
1291 rlm_rcode_t rcode = RLM_MODULE_OK;
1293 rlm_sql_handle_t *handle = NULL;
1295 int numaffected = 0;
1299 char const *attr = NULL;
1302 char path[MAX_STRING_LEN];
1304 char *expanded = NULL;
1306 rad_assert(section);
1308 if (section->reference[0] != '.') {
1312 if (radius_xlat(p, sizeof(path) - (p - path), request, section->reference, NULL, NULL) < 0) {
1313 rcode = RLM_MODULE_FAIL;
1318 item = cf_reference_item(NULL, section->cs, path);
1320 rcode = RLM_MODULE_FAIL;
1325 if (cf_item_is_section(item)){
1326 REDEBUG("Sections are not supported as references");
1327 rcode = RLM_MODULE_FAIL;
1332 pair = cf_item_to_pair(item);
1333 attr = cf_pair_attr(pair);
1335 RDEBUG2("Using query template '%s'", attr);
1337 handle = fr_connection_get(inst->pool);
1339 rcode = RLM_MODULE_FAIL;
1344 sql_set_user(inst, request, NULL);
1347 value = cf_pair_value(pair);
1349 RDEBUG("Ignoring null query");
1350 rcode = RLM_MODULE_NOOP;
1355 if (radius_axlat(&expanded, request, value, sql_escape_func, inst) < 0) {
1356 rcode = RLM_MODULE_FAIL;
1362 RDEBUG("Ignoring null query");
1363 rcode = RLM_MODULE_NOOP;
1364 talloc_free(expanded);
1369 rlm_sql_query_log(inst, request, section, expanded);
1371 sql_ret = rlm_sql_query(inst, request, &handle, expanded);
1372 TALLOC_FREE(expanded);
1376 * Query was a success! Now we just need to check if it did anything.
1382 * A general, unrecoverable server fault.
1386 * If we get RLM_SQL_RECONNECT it means all connections in the pool
1387 * were exhausted, and we couldn't create a new connection,
1388 * so we do not need to call fr_connection_release.
1390 case RLM_SQL_RECONNECT:
1394 * Query was invalid, this is a terminal error, but we still need
1395 * to do cleanup, as the connection handle is still valid.
1397 case RLM_SQL_QUERY_INVALID:
1398 rcode = RLM_MODULE_INVALID;
1399 (inst->module->sql_finish_query)(handle, inst->config);
1403 * Driver found an error (like a unique key constraint violation)
1404 * that hinted it might be a good idea to try an alternative query.
1406 case RLM_SQL_ALT_QUERY:
1412 * Assume all other errors are incidental, and just meant our
1413 * operation failed and its not a client or SQL syntax error.
1415 if (sql_ret == RLM_SQL_OK) {
1416 numaffected = (inst->module->sql_affected_rows)(handle, inst->config);
1417 if (numaffected > 0) break; /* A query succeeded, were done! */
1419 RDEBUG("No records updated");
1423 (inst->module->sql_finish_query)(handle, inst->config);
1426 * We assume all entries with the same name form a redundant
1429 pair = cf_pair_find_next(section->cs, pair, attr);
1432 RDEBUG("No additional queries configured");
1433 rcode = RLM_MODULE_NOOP;
1438 RDEBUG("Trying next query...");
1440 (inst->module->sql_finish_query)(handle, inst->config);
1443 talloc_free(expanded);
1444 fr_connection_release(inst->pool, handle);
1445 sql_unset_user(inst, request);
1450 #ifdef WITH_ACCOUNTING
1453 * Accounting: Insert or update session data in our sql table
1455 static rlm_rcode_t CC_HINT(nonnull) mod_accounting(void *instance, REQUEST * request) {
1456 rlm_sql_t *inst = instance;
1458 if (inst->config->accounting.reference_cp) {
1459 return acct_redundant(inst, request, &inst->config->accounting);
1462 return RLM_MODULE_NOOP;
1467 #ifdef WITH_SESSION_MGMT
1469 * See if a user is already logged in. Sets request->simul_count to the
1470 * current session count for this user.
1472 * Check twice. If on the first pass the user exceeds his
1473 * max. number of logins, do a second pass and validate all
1474 * logins by querying the terminal server (using eg. SNMP).
1477 static rlm_rcode_t CC_HINT(nonnull) mod_checksimul(void *instance, REQUEST * request) {
1478 rlm_rcode_t rcode = RLM_MODULE_OK;
1479 rlm_sql_handle_t *handle = NULL;
1480 rlm_sql_t *inst = instance;
1484 char const *call_num = NULL;
1487 uint32_t nas_addr = 0;
1488 uint32_t nas_port = 0;
1490 char *expanded = NULL;
1492 /* If simul_count_query is not defined, we don't do any checking */
1493 if (!inst->config->simul_count_query) {
1494 return RLM_MODULE_NOOP;
1497 if ((!request->username) || (request->username->vp_length == '\0')) {
1498 REDEBUG("Zero Length username not permitted");
1500 return RLM_MODULE_INVALID;
1504 if(sql_set_user(inst, request, NULL) < 0) {
1505 return RLM_MODULE_FAIL;
1508 if (radius_axlat(&expanded, request, inst->config->simul_count_query, sql_escape_func, inst) < 0) {
1509 sql_unset_user(inst, request);
1510 return RLM_MODULE_FAIL;
1513 /* initialize the sql socket */
1514 handle = fr_connection_get(inst->pool);
1516 talloc_free(expanded);
1517 sql_unset_user(inst, request);
1518 return RLM_MODULE_FAIL;
1521 if (rlm_sql_select_query(inst, request, &handle, expanded) != RLM_SQL_OK) {
1522 rcode = RLM_MODULE_FAIL;
1526 ret = rlm_sql_fetch_row(inst, request, &handle);
1528 rcode = RLM_MODULE_FAIL;
1534 rcode = RLM_MODULE_FAIL;
1538 request->simul_count = atoi(row[0]);
1540 (inst->module->sql_finish_select_query)(handle, inst->config);
1541 TALLOC_FREE(expanded);
1543 if (request->simul_count < request->simul_max) {
1544 rcode = RLM_MODULE_OK;
1549 * Looks like too many sessions, so let's start verifying
1550 * them, unless told to rely on count query only.
1552 if (!inst->config->simul_verify_query) {
1553 rcode = RLM_MODULE_OK;
1558 if (radius_axlat(&expanded, request, inst->config->simul_verify_query, sql_escape_func, inst) < 0) {
1559 rcode = RLM_MODULE_FAIL;
1564 if (rlm_sql_select_query(inst, request, &handle, expanded) != RLM_SQL_OK) goto finish;
1567 * Setup some stuff, like for MPP detection.
1569 request->simul_count = 0;
1571 if ((vp = pairfind(request->packet->vps, PW_FRAMED_IP_ADDRESS, 0, TAG_ANY)) != NULL) {
1572 ipno = vp->vp_ipaddr;
1575 if ((vp = pairfind(request->packet->vps, PW_CALLING_STATION_ID, 0, TAG_ANY)) != NULL) {
1576 call_num = vp->vp_strvalue;
1579 while (rlm_sql_fetch_row(inst, request, &handle) == 0) {
1586 RDEBUG("Cannot zap stale entry. No username present in entry");
1587 rcode = RLM_MODULE_FAIL;
1593 RDEBUG("Cannot zap stale entry. No session id in entry");
1594 rcode = RLM_MODULE_FAIL;
1600 nas_addr = inet_addr(row[3]);
1604 nas_port = atoi(row[4]);
1607 check = rad_check_ts(nas_addr, nas_port, row[2], row[1]);
1610 * Stale record - zap it.
1612 if (inst->config->delete_stale_sessions == true) {
1613 uint32_t framed_addr = 0;
1618 framed_addr = inet_addr(row[5]);
1620 if (strcmp(row[7], "PPP") == 0)
1622 else if (strcmp(row[7], "SLIP") == 0)
1626 sess_time = atoi(row[8]);
1627 session_zap(request, nas_addr, nas_port,
1628 row[2], row[1], framed_addr,
1632 else if (check == 1) {
1634 * User is still logged in.
1636 ++request->simul_count;
1639 * Does it look like a MPP attempt?
1641 if (row[5] && ipno && inet_addr(row[5]) == ipno) {
1642 request->simul_mpp = 2;
1643 } else if (row[6] && call_num && !strncmp(row[6],call_num,16)) {
1644 request->simul_mpp = 2;
1648 * Failed to check the terminal server for
1649 * duplicate logins: return an error.
1651 REDEBUG("Failed to check the terminal server for user '%s'.", row[2]);
1653 rcode = RLM_MODULE_FAIL;
1660 (inst->module->sql_finish_select_query)(handle, inst->config);
1661 fr_connection_release(inst->pool, handle);
1662 talloc_free(expanded);
1663 sql_unset_user(inst, request);
1666 * The Auth module apparently looks at request->simul_count,
1667 * not the return value of this module when deciding to deny
1668 * a call for too many sessions.
1675 * Postauth: Write a record of the authentication attempt
1677 static rlm_rcode_t CC_HINT(nonnull) mod_post_auth(void *instance, REQUEST * request) {
1678 rlm_sql_t *inst = instance;
1680 if (inst->config->postauth.reference_cp) {
1681 return acct_redundant(inst, request, &inst->config->postauth);
1684 return RLM_MODULE_NOOP;
1688 * Execute postauth_query after authentication
1692 /* globally exported name */
1693 extern module_t rlm_sql;
1694 module_t rlm_sql = {
1697 RLM_TYPE_THREAD_SAFE, /* type: reserved */
1700 mod_instantiate, /* instantiation */
1701 mod_detach, /* detach */
1703 NULL, /* authentication */
1704 mod_authorize, /* authorization */
1705 NULL, /* preaccounting */
1706 #ifdef WITH_ACCOUNTING
1707 mod_accounting, /* accounting */
1711 #ifdef WITH_SESSION_MGMT
1712 mod_checksimul, /* checksimul */
1716 NULL, /* pre-proxy */
1717 NULL, /* post-proxy */
1718 mod_post_auth /* post-auth */