4 * Main SQL module file. Most ICRADIUS code is located in sql.c
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 * Copyright 2012 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>
28 #include <freeradius-devel/ident.h>
33 #include <freeradius-devel/radiusd.h>
34 #include <freeradius-devel/modules.h>
35 #include <freeradius-devel/token.h>
36 #include <freeradius-devel/rad_assert.h>
42 static const CONF_PARSER acct_section_config[] = {
43 {"reference", PW_TYPE_STRING_PTR,
44 offsetof(sql_acct_section_t, reference), NULL, ".query"},
46 {"logfile", PW_TYPE_STRING_PTR,
47 offsetof(sql_acct_section_t, logfile), NULL, NULL},
48 {NULL, -1, 0, NULL, NULL}
51 static const CONF_PARSER module_config[] = {
52 {"driver", PW_TYPE_STRING_PTR,
53 offsetof(SQL_CONFIG,sql_driver), NULL, "mysql"},
54 {"server", PW_TYPE_STRING_PTR,
55 offsetof(SQL_CONFIG,sql_server), NULL, "localhost"},
56 {"port", PW_TYPE_STRING_PTR,
57 offsetof(SQL_CONFIG,sql_port), NULL, ""},
58 {"login", PW_TYPE_STRING_PTR,
59 offsetof(SQL_CONFIG,sql_login), NULL, ""},
60 {"password", PW_TYPE_STRING_PTR,
61 offsetof(SQL_CONFIG,sql_password), NULL, ""},
62 {"radius_db", PW_TYPE_STRING_PTR,
63 offsetof(SQL_CONFIG,sql_db), NULL, "radius"},
64 {"filename", PW_TYPE_FILENAME, /* for sqlite */
65 offsetof(SQL_CONFIG,sql_file), NULL, NULL},
66 {"read_groups", PW_TYPE_BOOLEAN,
67 offsetof(SQL_CONFIG,read_groups), NULL, "yes"},
68 {"readclients", PW_TYPE_BOOLEAN,
69 offsetof(SQL_CONFIG,do_clients), NULL, "no"},
70 {"deletestalesessions", PW_TYPE_BOOLEAN,
71 offsetof(SQL_CONFIG,deletestalesessions), NULL, "yes"},
72 {"sql_user_name", PW_TYPE_STRING_PTR,
73 offsetof(SQL_CONFIG,query_user), NULL, ""},
74 {"logfile", PW_TYPE_STRING_PTR,
75 offsetof(SQL_CONFIG,logfile), NULL, NULL},
76 {"default_user_profile", PW_TYPE_STRING_PTR,
77 offsetof(SQL_CONFIG,default_profile), NULL, ""},
78 {"nas_query", PW_TYPE_STRING_PTR,
79 offsetof(SQL_CONFIG,nas_query), NULL,
80 "SELECT id,nasname,shortname,type,secret FROM nas"},
81 {"authorize_check_query", PW_TYPE_STRING_PTR,
82 offsetof(SQL_CONFIG,authorize_check_query), NULL, ""},
83 {"authorize_reply_query", PW_TYPE_STRING_PTR,
84 offsetof(SQL_CONFIG,authorize_reply_query), NULL, NULL},
85 {"authorize_group_check_query", PW_TYPE_STRING_PTR,
86 offsetof(SQL_CONFIG,authorize_group_check_query), NULL, ""},
87 {"authorize_group_reply_query", PW_TYPE_STRING_PTR,
88 offsetof(SQL_CONFIG,authorize_group_reply_query), NULL, ""},
89 {"group_membership_query", PW_TYPE_STRING_PTR,
90 offsetof(SQL_CONFIG,groupmemb_query), NULL, NULL},
91 #ifdef WITH_SESSION_MGMT
92 {"simul_count_query", PW_TYPE_STRING_PTR,
93 offsetof(SQL_CONFIG,simul_count_query), NULL, ""},
94 {"simul_verify_query", PW_TYPE_STRING_PTR,
95 offsetof(SQL_CONFIG,simul_verify_query), NULL, ""},
97 {"safe-characters", PW_TYPE_STRING_PTR,
98 offsetof(SQL_CONFIG,allowed_chars), NULL,
99 "@abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_: /"},
102 * This only works for a few drivers.
104 {"query_timeout", PW_TYPE_INTEGER,
105 offsetof(SQL_CONFIG,query_timeout), NULL, NULL},
107 {NULL, -1, 0, NULL, NULL}
111 * Fall-Through checking function from rlm_files.c
113 static int fallthrough(VALUE_PAIR *vp)
116 tmp = pairfind(vp, PW_FALL_THROUGH, 0);
118 return tmp ? tmp->vp_integer : 0;
126 static int generate_sql_clients(SQL_INST *inst);
127 static size_t sql_escape_func(REQUEST *, char *out, size_t outlen, const char *in, void *arg);
132 * For selects the first value of the first column will be returned,
133 * for inserts, updates and deletes the number of rows afftected will be
136 static size_t sql_xlat(void *instance, REQUEST *request,
137 const char *fmt, char *out, size_t freespace)
141 SQL_INST *inst = instance;
142 char querystr[MAX_QUERY_LEN];
148 * Add SQL-User-Name attribute just in case it is needed
149 * We could search the string fmt for SQL-User-Name to see if this is
152 sql_set_user(inst, request, NULL);
154 * Do an xlat on the provided string (nice recursive operation).
156 if (!radius_xlat(querystr, sizeof(querystr), fmt, request, sql_escape_func, inst)) {
157 radlog(L_ERR, "rlm_sql (%s): xlat failed.",
158 inst->config->xlat_name);
162 sqlsocket = sql_get_socket(inst);
163 if (sqlsocket == NULL)
166 rlm_sql_query_log(inst, request, NULL, querystr);
169 * If the query starts with any of the following prefixes,
170 * then return the number of rows affected
172 if ((strncasecmp(querystr, "insert", 6) == 0) ||
173 (strncasecmp(querystr, "update", 6) == 0) ||
174 (strncasecmp(querystr, "delete", 6) == 0)) {
176 char buffer[21]; /* 64bit max is 20 decimal chars + null byte */
178 if (rlm_sql_query(&sqlsocket,inst,querystr)) {
179 sql_release_socket(inst,sqlsocket);
184 numaffected = (inst->module->sql_affected_rows)(sqlsocket,
186 if (numaffected < 1) {
187 RDEBUG("rlm_sql (%s): SQL query affected no rows",
188 inst->config->xlat_name);
192 * Don't chop the returned number if freespace is
193 * too small. This hack is necessary because
194 * some implementations of snprintf return the
195 * size of the written data, and others return
196 * the size of the data they *would* have written
197 * if the output buffer was large enough.
199 snprintf(buffer, sizeof(buffer), "%d", numaffected);
200 ret = strlen(buffer);
201 if (ret >= freespace){
202 RDEBUG("rlm_sql (%s): Can't write result, insufficient string space",
203 inst->config->xlat_name);
204 (inst->module->sql_finish_query)(sqlsocket,
206 sql_release_socket(inst,sqlsocket);
210 memcpy(out, buffer, ret + 1); /* we did bounds checking above */
212 (inst->module->sql_finish_query)(sqlsocket, inst->config);
213 sql_release_socket(inst,sqlsocket);
215 } /* else it's a SELECT statement */
217 if (rlm_sql_select_query(&sqlsocket,inst,querystr)){
218 sql_release_socket(inst,sqlsocket);
222 ret = rlm_sql_fetch_row(&sqlsocket, inst);
224 RDEBUG("SQL query did not succeed");
225 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
226 sql_release_socket(inst,sqlsocket);
230 row = sqlsocket->row;
232 RDEBUG("SQL query did not return any results");
233 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
234 sql_release_socket(inst,sqlsocket);
239 RDEBUG("Null value in first column");
240 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
241 sql_release_socket(inst,sqlsocket);
244 ret = strlen(row[0]);
245 if (ret >= freespace){
246 RDEBUG("Insufficient string space");
247 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
248 sql_release_socket(inst,sqlsocket);
252 strlcpy(out,row[0],freespace);
254 RDEBUG("sql_xlat finished");
256 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
257 sql_release_socket(inst,sqlsocket);
261 static int generate_sql_clients(SQL_INST *inst)
265 char querystr[MAX_QUERY_LEN];
267 char *prefix_ptr = NULL;
271 DEBUG("rlm_sql (%s): Processing generate_sql_clients",
272 inst->config->xlat_name);
274 /* NAS query isn't xlat'ed */
275 strlcpy(querystr, inst->config->nas_query, sizeof(querystr));
276 DEBUG("rlm_sql (%s) in generate_sql_clients: query is %s",
277 inst->config->xlat_name, querystr);
279 sqlsocket = sql_get_socket(inst);
280 if (sqlsocket == NULL)
282 if (rlm_sql_select_query(&sqlsocket,inst,querystr)){
286 while(rlm_sql_fetch_row(&sqlsocket, inst) == 0) {
288 row = sqlsocket->row;
292 * The return data for each row MUST be in the following order:
294 * 0. Row ID (currently unused)
295 * 1. Name (or IP address)
299 * 5. Virtual Server (optional)
302 radlog(L_ERR, "rlm_sql (%s): No row id found on pass %d",inst->config->xlat_name,i);
306 radlog(L_ERR, "rlm_sql (%s): No nasname found for row %s",inst->config->xlat_name,row[0]);
310 radlog(L_ERR, "rlm_sql (%s): No short name found for row %s",inst->config->xlat_name,row[0]);
314 radlog(L_ERR, "rlm_sql (%s): No secret found for row %s",inst->config->xlat_name,row[0]);
318 DEBUG("rlm_sql (%s): Read entry nasname=%s,shortname=%s,secret=%s",inst->config->xlat_name,
319 row[1],row[2],row[4]);
321 c = rad_malloc(sizeof(*c));
322 memset(c, 0, sizeof(*c));
324 #ifdef WITH_DYNAMIC_CLIENTS
332 prefix_ptr = strchr(row[1], '/');
334 c->prefix = atoi(prefix_ptr + 1);
335 if ((c->prefix < 0) || (c->prefix > 128)) {
336 radlog(L_ERR, "rlm_sql (%s): Invalid Prefix value '%s' for IP.",
337 inst->config->xlat_name, prefix_ptr + 1);
341 /* Replace '/' with '\0' */
346 * Always get the numeric representation of IP
348 if (ip_hton(row[1], AF_UNSPEC, &c->ipaddr) < 0) {
349 radlog(L_CONS|L_ERR, "rlm_sql (%s): Failed to look up hostname %s: %s",
350 inst->config->xlat_name,
351 row[1], fr_strerror());
356 ip_ntoh(&c->ipaddr, buffer, sizeof(buffer));
357 c->longname = strdup(buffer);
360 if (c->prefix < 0) switch (c->ipaddr.af) {
372 * Other values (secret, shortname, nastype, virtual_server)
374 c->secret = strdup(row[4]);
375 c->shortname = strdup(row[2]);
377 c->nastype = strdup(row[3]);
379 numf = (inst->module->sql_num_fields)(sqlsocket, inst->config);
380 if ((numf > 5) && (row[5] != NULL) && *row[5]) c->server = strdup(row[5]);
382 DEBUG("rlm_sql (%s): Adding client %s (%s, server=%s) to clients list",
383 inst->config->xlat_name,
384 c->longname,c->shortname, c->server ? c->server : "<none>");
385 if (!client_add(NULL, c)) {
386 sql_release_socket(inst, sqlsocket);
387 DEBUG("rlm_sql (%s): Failed to add client %s (%s) to clients list. Maybe there's a duplicate?",
388 inst->config->xlat_name,
389 c->longname,c->shortname);
394 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
395 sql_release_socket(inst, sqlsocket);
402 * Translate the SQL queries.
404 static size_t sql_escape_func(UNUSED REQUEST *request, char *out, size_t outlen,
405 const char *in, void *arg)
407 SQL_INST *inst = arg;
412 * Non-printable characters get replaced with their
413 * mime-encoded equivalents.
416 strchr(inst->config->allowed_chars, *in) == NULL) {
418 * Only 3 or less bytes available.
424 snprintf(out, outlen, "=%02X", (unsigned char) in[0]);
433 * Only one byte left.
453 * Set the SQL user name.
455 * We don't call the escape function here. The resulting string
456 * will be escaped later in the queries xlat so we don't need to
457 * escape it twice. (it will make things wrong if we have an
458 * escape candidate character in the username)
460 int sql_set_user(SQL_INST *inst, REQUEST *request, const char *username)
462 VALUE_PAIR *vp = NULL;
465 if (username != NULL) {
467 } else if (*inst->config->query_user) {
468 sqluser = inst->config->query_user;
473 vp = pairmake_xlat("SQL-User-Name", sqluser, T_OP_SET);
478 pairxlatmove(request, &(request->packet->vps), &vp);
479 pairfree(&vp); /* Free the VP if for some reason it wasn't moved */
481 RDEBUG2("SQL-User-Name updated");
487 static void sql_grouplist_free (SQL_GROUPLIST **group_list)
493 *group_list = (*group_list)->next;
499 static int sql_get_grouplist (SQL_INST *inst, SQLSOCK *sqlsocket, REQUEST *request, SQL_GROUPLIST **group_list)
501 char querystr[MAX_QUERY_LEN];
504 SQL_GROUPLIST *group_list_tmp;
506 /* NOTE: sql_set_user should have been run before calling this function */
508 group_list_tmp = *group_list = NULL;
510 if (!inst->config->groupmemb_query ||
511 (inst->config->groupmemb_query[0] == 0))
514 if (!radius_xlat(querystr, sizeof(querystr), inst->config->groupmemb_query, request, sql_escape_func, inst)) {
515 radlog_request(L_ERR, 0, request, "xlat \"%s\" failed.",
516 inst->config->groupmemb_query);
520 if (rlm_sql_select_query(&sqlsocket, inst, querystr) < 0) {
523 while (rlm_sql_fetch_row(&sqlsocket, inst) == 0) {
524 row = sqlsocket->row;
528 RDEBUG("row[0] returned NULL");
529 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
530 sql_grouplist_free(group_list);
533 if (*group_list == NULL) {
534 *group_list = rad_malloc(sizeof(SQL_GROUPLIST));
535 group_list_tmp = *group_list;
537 rad_assert(group_list_tmp != NULL);
538 group_list_tmp->next = rad_malloc(sizeof(SQL_GROUPLIST));
539 group_list_tmp = group_list_tmp->next;
541 group_list_tmp->next = NULL;
542 strlcpy(group_list_tmp->groupname, row[0], MAX_STRING_LEN);
545 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
552 * sql groupcmp function. That way we can do group comparisons (in the users file for example)
553 * with the group memberships reciding in sql
554 * The group membership query should only return one element which is the username. The returned
555 * username will then be checked with the passed check string.
558 static int sql_groupcmp(void *instance, REQUEST *request, VALUE_PAIR *request_vp, VALUE_PAIR *check,
559 VALUE_PAIR *check_pairs, VALUE_PAIR **reply_pairs)
562 SQL_INST *inst = instance;
563 SQL_GROUPLIST *group_list, *group_list_tmp;
565 check_pairs = check_pairs;
566 reply_pairs = reply_pairs;
567 request_vp = request_vp;
569 RDEBUG("sql_groupcmp");
570 if (!check || !check->vp_strvalue || !check->length){
571 RDEBUG("sql_groupcmp: Illegal group name");
575 RDEBUG("sql_groupcmp: NULL request");
579 * Set, escape, and check the user attr here
581 if (sql_set_user(inst, request, NULL) < 0)
585 * Get a socket for this lookup
587 sqlsocket = sql_get_socket(inst);
588 if (sqlsocket == NULL) {
593 * Get the list of groups this user is a member of
595 if (sql_get_grouplist(inst, sqlsocket, request, &group_list) < 0) {
596 radlog_request(L_ERR, 0, request,
597 "Error getting group membership");
598 sql_release_socket(inst, sqlsocket);
602 for (group_list_tmp = group_list; group_list_tmp != NULL; group_list_tmp = group_list_tmp->next) {
603 if (strcmp(group_list_tmp->groupname, check->vp_strvalue) == 0){
604 RDEBUG("sql_groupcmp finished: User is a member of group %s",
606 /* Free the grouplist */
607 sql_grouplist_free(&group_list);
608 sql_release_socket(inst, sqlsocket);
613 /* Free the grouplist */
614 sql_grouplist_free(&group_list);
615 sql_release_socket(inst,sqlsocket);
617 RDEBUG("sql_groupcmp finished: User is NOT a member of group %s",
625 static int rlm_sql_process_groups(SQL_INST *inst, REQUEST *request, SQLSOCK *sqlsocket, int *dofallthrough)
627 VALUE_PAIR *check_tmp = NULL;
628 VALUE_PAIR *reply_tmp = NULL;
629 SQL_GROUPLIST *group_list, *group_list_tmp;
630 VALUE_PAIR *sql_group = NULL;
631 char querystr[MAX_QUERY_LEN];
636 * Get the list of groups this user is a member of
638 if (sql_get_grouplist(inst, sqlsocket, request, &group_list) < 0) {
639 radlog_request(L_ERR, 0, request, "Error retrieving group list");
643 for (group_list_tmp = group_list; group_list_tmp != NULL && *dofallthrough != 0; group_list_tmp = group_list_tmp->next) {
645 * Add the Sql-Group attribute to the request list so we know
646 * which group we're retrieving attributes for
648 sql_group = pairmake("Sql-Group", group_list_tmp->groupname, T_OP_EQ);
650 radlog_request(L_ERR, 0, request,
651 "Error creating Sql-Group attribute");
652 sql_grouplist_free(&group_list);
655 pairadd(&request->packet->vps, sql_group);
656 if (!radius_xlat(querystr, sizeof(querystr), inst->config->authorize_group_check_query, request, sql_escape_func, inst)) {
657 radlog_request(L_ERR, 0, request,
658 "Error generating query; rejecting user");
659 /* Remove the grouup we added above */
660 pairdelete(&request->packet->vps, PW_SQL_GROUP, 0, -1);
661 sql_grouplist_free(&group_list);
664 rows = sql_getvpdata(inst, &sqlsocket, &check_tmp, querystr);
666 radlog_request(L_ERR, 0, request, "Error retrieving check pairs for group %s",
667 group_list_tmp->groupname);
668 /* Remove the grouup we added above */
669 pairdelete(&request->packet->vps, PW_SQL_GROUP, 0, -1);
670 pairfree(&check_tmp);
671 sql_grouplist_free(&group_list);
673 } else if (rows > 0) {
675 * Only do this if *some* check pairs were returned
677 if (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) == 0) {
679 RDEBUG2("User found in group %s",
680 group_list_tmp->groupname);
682 * Now get the reply pairs since the paircompare matched
684 if (!radius_xlat(querystr, sizeof(querystr), inst->config->authorize_group_reply_query, request, sql_escape_func, inst)) {
685 radlog_request(L_ERR, 0, request, "Error generating query; rejecting user");
686 /* Remove the grouup we added above */
687 pairdelete(&request->packet->vps, PW_SQL_GROUP, 0, -1);
688 pairfree(&check_tmp);
689 sql_grouplist_free(&group_list);
692 if (sql_getvpdata(inst, &sqlsocket, &reply_tmp, querystr) < 0) {
693 radlog_request(L_ERR, 0, request, "Error retrieving reply pairs for group %s",
694 group_list_tmp->groupname);
695 /* Remove the grouup we added above */
696 pairdelete(&request->packet->vps, PW_SQL_GROUP, 0, -1);
697 pairfree(&check_tmp);
698 pairfree(&reply_tmp);
699 sql_grouplist_free(&group_list);
702 *dofallthrough = fallthrough(reply_tmp);
703 pairxlatmove(request, &request->reply->vps, &reply_tmp);
704 pairxlatmove(request, &request->config_items, &check_tmp);
708 * rows == 0. This is like having the username on a line
709 * in the user's file with no check vp's. As such, we treat
710 * it as found and add the reply attributes, so that we
711 * match expected behavior
714 RDEBUG2("User found in group %s",
715 group_list_tmp->groupname);
717 * Now get the reply pairs since the paircompare matched
719 if (!radius_xlat(querystr, sizeof(querystr), inst->config->authorize_group_reply_query, request, sql_escape_func, inst)) {
720 radlog_request(L_ERR, 0, request, "Error generating query; rejecting user");
721 /* Remove the grouup we added above */
722 pairdelete(&request->packet->vps, PW_SQL_GROUP, 0, -1);
723 pairfree(&check_tmp);
724 sql_grouplist_free(&group_list);
727 if (sql_getvpdata(inst, &sqlsocket, &reply_tmp, querystr) < 0) {
728 radlog_request(L_ERR, 0, request, "Error retrieving reply pairs for group %s",
729 group_list_tmp->groupname);
730 /* Remove the grouup we added above */
731 pairdelete(&request->packet->vps, PW_SQL_GROUP, 0, -1);
732 pairfree(&check_tmp);
733 pairfree(&reply_tmp);
734 sql_grouplist_free(&group_list);
737 *dofallthrough = fallthrough(reply_tmp);
738 pairxlatmove(request, &request->reply->vps, &reply_tmp);
739 pairxlatmove(request, &request->config_items, &check_tmp);
743 * Delete the Sql-Group we added above
744 * And clear out the pairlists
746 pairdelete(&request->packet->vps, PW_SQL_GROUP, 0, -1);
747 pairfree(&check_tmp);
748 pairfree(&reply_tmp);
751 sql_grouplist_free(&group_list);
756 static int rlm_sql_detach(void *instance)
758 SQL_INST *inst = instance;
760 paircompare_unregister(PW_SQL_GROUP, sql_groupcmp);
762 if (inst->config->postauth) free(inst->config->postauth);
763 if (inst->config->accounting) free(inst->config->accounting);
768 if (inst->pool) sql_poolfree(inst);
770 if (inst->config->xlat_name) {
771 xlat_unregister(inst->config->xlat_name, sql_xlat, instance);
772 rad_cfree(inst->config->xlat_name);
776 * Free up dynamically allocated string pointers.
778 for (i = 0; module_config[i].name != NULL; i++) {
780 if (module_config[i].type != PW_TYPE_STRING_PTR) {
785 * Treat 'config' as an opaque array of bytes,
786 * and take the offset into it. There's a
787 * (char*) pointer at that offset, and we want
790 p = (char **) (((char *)inst->config) + module_config[i].offset);
791 if (!*p) { /* nothing allocated */
804 * FIXME: Call the modules 'destroy' function?
806 lt_dlclose(inst->handle); /* ignore any errors */
814 static int parse_sub_section(CONF_SECTION *parent,
815 UNUSED SQL_INST *inst,
816 sql_acct_section_t **config,
817 rlm_components_t comp)
821 const char *name = section_type_value[comp].section;
823 cs = cf_section_sub_find(parent, name);
825 radlog(L_INFO, "Couldn't find configuration for %s. "
826 "Will return NOOP for calls from this section.", name);
831 *config = rad_calloc(sizeof(**config));
832 if (cf_section_parse(cs, *config, acct_section_config) < 0) {
833 radlog(L_ERR, "Failed parsing configuration for section %s",
847 static int rlm_sql_instantiate(CONF_SECTION * conf, void **instance)
850 const char *xlat_name;
852 inst = rad_calloc(sizeof(SQL_INST));
855 * Export these methods, too. This avoids RTDL_GLOBAL.
857 inst->sql_set_user = sql_set_user;
858 inst->sql_get_socket = sql_get_socket;
859 inst->sql_release_socket = sql_release_socket;
860 inst->sql_escape_func = sql_escape_func;
861 inst->sql_query = rlm_sql_query;
862 inst->sql_select_query = rlm_sql_select_query;
863 inst->sql_fetch_row = rlm_sql_fetch_row;
865 inst->config = rad_calloc(sizeof(SQL_CONFIG));
868 xlat_name = cf_section_name2(conf);
869 if (xlat_name == NULL) {
870 xlat_name = cf_section_name1(conf);
877 * Allocate room for <instance>-SQL-Group
879 group_name = rad_malloc((strlen(xlat_name) + 1 + 11) * sizeof(char));
880 sprintf(group_name,"%s-SQL-Group", xlat_name);
881 DEBUG("rlm_sql (%s): Creating new attribute %s",
882 xlat_name, group_name);
884 memset(&flags, 0, sizeof(flags));
885 dict_addattr(group_name, 0, PW_TYPE_STRING, -1, flags);
886 dattr = dict_attrbyname(group_name);
888 radlog(L_ERR, "rlm_sql (%s): Failed to create "
889 "attribute %s", xlat_name, group_name);
896 if (inst->config->groupmemb_query &&
897 inst->config->groupmemb_query[0]) {
898 DEBUG("rlm_sql (%s): Registering sql_groupcmp for %s",
899 xlat_name, group_name);
900 paircompare_register(dattr->attr, PW_USER_NAME,
907 rad_assert(xlat_name);
911 * Register the SQL xlat function
913 inst->config->xlat_name = strdup(xlat_name);
914 xlat_register(xlat_name, sql_xlat, inst);
917 * If the configuration parameters can't be parsed, then fail.
919 if ((cf_section_parse(conf, inst->config, module_config) < 0) ||
920 (parse_sub_section(conf, inst,
921 &inst->config->accounting,
922 RLM_COMPONENT_ACCT) < 0) ||
923 (parse_sub_section(conf, inst,
924 &inst->config->postauth,
925 RLM_COMPONENT_POST_AUTH) < 0)) {
926 radlog(L_ERR, "rlm_sql (%s): Failed parsing configuration",
927 inst->config->xlat_name);
932 * Sanity check for crazy people.
934 if (strncmp(inst->config->sql_driver, "rlm_sql_", 8) != 0) {
935 radlog(L_ERR, "rlm_sql (%s): \"%s\" is NOT an SQL driver!",
936 inst->config->xlat_name, inst->config->sql_driver);
941 * Load the appropriate driver for our database
943 inst->handle = lt_dlopenext(inst->config->sql_driver);
944 if (inst->handle == NULL) {
945 radlog(L_ERR, "Could not link driver %s: %s",
946 inst->config->sql_driver,
948 radlog(L_ERR, "Make sure it (and all its dependent libraries!)"
949 "are in the search path of your system's ld.");
954 inst->module = (rlm_sql_module_t *) lt_dlsym(inst->handle,
955 inst->config->sql_driver);
957 radlog(L_ERR, "Could not link symbol %s: %s",
958 inst->config->sql_driver,
964 radlog(L_INFO, "rlm_sql (%s): Driver %s (module %s) loaded and linked",
965 inst->config->xlat_name, inst->config->sql_driver,
969 * Initialise the connection pool for this instance
971 radlog(L_INFO, "rlm_sql (%s): Attempting to connect to %s@%s:%s/%s",
972 inst->config->xlat_name, inst->config->sql_login,
973 inst->config->sql_server, inst->config->sql_port,
974 inst->config->sql_db);
976 if (sql_init_socketpool(inst) < 0)
979 if (inst->config->groupmemb_query &&
980 inst->config->groupmemb_query[0]) {
981 paircompare_register(PW_SQL_GROUP, PW_USER_NAME, sql_groupcmp, inst);
984 if (inst->config->do_clients) {
985 if (generate_sql_clients(inst) == -1){
986 radlog(L_ERR, "Failed to load clients from SQL.");
994 return RLM_MODULE_OK;
997 rlm_sql_detach(inst);
1003 static int rlm_sql_authorize(void *instance, REQUEST * request)
1005 int ret = RLM_MODULE_NOTFOUND;
1007 SQL_INST *inst = instance;
1010 VALUE_PAIR *check_tmp = NULL;
1011 VALUE_PAIR *reply_tmp = NULL;
1012 VALUE_PAIR *user_profile = NULL;
1014 int dofallthrough = 1;
1017 char querystr[MAX_QUERY_LEN];
1020 * Set, escape, and check the user attr here
1022 if (sql_set_user(inst, request, NULL) < 0)
1023 return RLM_MODULE_FAIL;
1028 * After this point use goto error or goto release to cleanup sockets
1029 * temporary pairlists and temporary attributes.
1031 sqlsocket = sql_get_socket(inst);
1032 if (sqlsocket == NULL)
1036 * Query the check table to find any conditions associated with
1037 * this user/realm/whatever...
1039 if (inst->config->authorize_check_query &&
1040 *inst->config->authorize_check_query) {
1041 if (!radius_xlat(querystr, sizeof(querystr), inst->config->authorize_check_query, request, sql_escape_func, inst)) {
1042 radlog_request(L_ERR, 0, request, "Error generating query; rejecting user");
1047 rows = sql_getvpdata(inst, &sqlsocket, &check_tmp, querystr);
1049 radlog_request(L_ERR, 0, request, "SQL query error; rejecting user");
1055 * Only do this if *some* check pairs were returned
1058 (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) == 0)) {
1059 RDEBUG2("User found in radcheck table");
1061 pairxlatmove(request, &request->config_items, &check_tmp);
1063 ret = RLM_MODULE_OK;
1067 * We only process reply table items if check conditions
1074 if (inst->config->authorize_reply_query &&
1075 *inst->config->authorize_reply_query) {
1077 * Now get the reply pairs since the paircompare matched
1079 if (!radius_xlat(querystr, sizeof(querystr), inst->config->authorize_reply_query, request, sql_escape_func, inst)) {
1080 radlog_request(L_ERR, 0, request, "Error generating query; rejecting user");
1085 rows = sql_getvpdata(inst, &sqlsocket, &reply_tmp, querystr);
1087 radlog_request(L_ERR, 0, request, "SQL query error; rejecting user");
1093 if (!inst->config->read_groups)
1094 dofallthrough = fallthrough(reply_tmp);
1096 pairxlatmove(request, &request->reply->vps, &reply_tmp);
1098 ret = RLM_MODULE_OK;
1105 * Clear out the pairlists
1107 pairfree(&check_tmp);
1108 pairfree(&reply_tmp);
1111 * dofallthrough is set to 1 by default so that if the user information
1112 * is not found, we will still process groups. If the user information,
1113 * however, *is* found, Fall-Through must be set in order to process
1114 * the groups as well.
1116 if (dofallthrough) {
1117 rows = rlm_sql_process_groups(inst, request, sqlsocket, &dofallthrough);
1119 radlog_request(L_ERR, 0, request, "Error processing groups; rejecting user");
1125 ret = RLM_MODULE_OK;
1129 * Repeat the above process with the default profile or User-Profile
1131 if (dofallthrough) {
1133 * Check for a default_profile or for a User-Profile.
1135 user_profile = pairfind(request->config_items, PW_USER_PROFILE, 0);
1137 const char *profile = user_profile ?
1138 user_profile->vp_strvalue :
1139 inst->config->default_profile;
1141 if (!profile || !*profile)
1144 RDEBUG("Checking profile %s", profile);
1146 if (sql_set_user(inst, request, profile) < 0) {
1147 radlog_request(L_ERR, 0, request, "Error setting profile; rejecting user");
1152 rows = rlm_sql_process_groups(inst, request, sqlsocket, &dofallthrough);
1154 radlog_request(L_ERR, 0, request, "Error processing profile groups; rejecting user");
1160 ret = RLM_MODULE_OK;
1166 ret = RLM_MODULE_FAIL;
1169 sql_release_socket(inst, sqlsocket);
1171 pairfree(&check_tmp);
1172 pairfree(&reply_tmp);
1178 * Generic function for failing between a bunch of queries.
1180 * Uses the same principle as rlm_linelog, expanding the 'reference' config
1181 * item using xlat to figure out what query it should execute.
1183 * If the reference matches multiple config items, and a query fails or
1184 * doesn't update any rows, the next matching config item is used.
1187 static int acct_redundant(SQL_INST *inst, REQUEST *request,
1188 sql_acct_section_t *section)
1190 int ret = RLM_MODULE_OK;
1192 SQLSOCK *sqlsocket = NULL;
1194 int numaffected = 0;
1198 const char *attr = NULL;
1201 char path[MAX_STRING_LEN];
1202 char querystr[MAX_QUERY_LEN];
1206 rad_assert(section);
1208 if (section->reference[0] != '.')
1211 if (!radius_xlat(p, (sizeof(path) - (p - path)) - 1,
1212 section->reference, request, NULL, NULL))
1213 return RLM_MODULE_FAIL;
1215 item = cf_reference_item(NULL, section->cs, path);
1217 return RLM_MODULE_FAIL;
1219 if (cf_item_is_section(item)){
1220 radlog(L_ERR, "Sections are not supported as references");
1222 return RLM_MODULE_FAIL;
1225 pair = cf_itemtopair(item);
1226 attr = cf_pair_attr(pair);
1228 RDEBUG2("Using query template '%s'", attr);
1230 sqlsocket = sql_get_socket(inst);
1231 if (sqlsocket == NULL)
1232 return RLM_MODULE_FAIL;
1234 sql_set_user(inst, request, NULL);
1237 value = cf_pair_value(pair);
1239 RDEBUG("Ignoring null query");
1240 ret = RLM_MODULE_NOOP;
1245 radius_xlat(querystr, sizeof(querystr), value, request,
1246 sql_escape_func, inst);
1248 RDEBUG("Ignoring null query");
1249 ret = RLM_MODULE_NOOP;
1254 rlm_sql_query_log(inst, request, section, querystr);
1257 * If rlm_sql_query cannot use the socket it'll try and
1258 * reconnect. Reconnecting will automatically release
1259 * the current socket, and try to select a new one.
1261 * If we get SQL_DOWN it means all connections in the pool
1262 * were exhausted, and we couldn't create a new connection,
1263 * so we do not need to call sql_release_socket.
1265 sql_ret = rlm_sql_query(&sqlsocket, inst, querystr);
1266 if (sql_ret == SQL_DOWN)
1267 return RLM_MODULE_FAIL;
1269 rad_assert(sqlsocket);
1272 * Assume all other errors are incidental, and just meant our
1273 * operation failed and its not a client or SQL syntax error.
1276 numaffected = (inst->module->sql_affected_rows)
1277 (sqlsocket, inst->config);
1278 if (numaffected > 0)
1281 RDEBUG("No records updated");
1284 (inst->module->sql_finish_query)(sqlsocket, inst->config);
1287 * We assume all entries with the same name form a redundant
1290 pair = cf_pair_find_next(section->cs, pair, attr);
1293 RDEBUG("No additional queries configured");
1295 ret = RLM_MODULE_NOOP;
1300 RDEBUG("Trying next query...");
1303 (inst->module->sql_finish_query)(sqlsocket, inst->config);
1306 sql_release_socket(inst, sqlsocket);
1311 #ifdef WITH_ACCOUNTING
1314 * Accounting: Insert or update session data in our sql table
1316 static int rlm_sql_accounting(void *instance, REQUEST * request) {
1317 SQL_INST *inst = instance;
1319 if (inst->config->accounting) {
1320 return acct_redundant(inst, request, inst->config->accounting);
1323 return RLM_MODULE_NOOP;
1328 #ifdef WITH_SESSION_MGMT
1330 * See if a user is already logged in. Sets request->simul_count to the
1331 * current session count for this user.
1333 * Check twice. If on the first pass the user exceeds his
1334 * max. number of logins, do a second pass and validate all
1335 * logins by querying the terminal server (using eg. SNMP).
1338 static int rlm_sql_checksimul(void *instance, REQUEST * request) {
1340 SQL_INST *inst = instance;
1342 char querystr[MAX_QUERY_LEN];
1345 char *call_num = NULL;
1348 uint32_t nas_addr = 0;
1351 /* If simul_count_query is not defined, we don't do any checking */
1352 if (!inst->config->simul_count_query ||
1353 (inst->config->simul_count_query[0] == 0)) {
1354 return RLM_MODULE_NOOP;
1357 if((request->username == NULL) || (request->username->length == 0)) {
1358 radlog_request(L_ERR, 0, request,
1359 "Zero Length username not permitted\n");
1360 return RLM_MODULE_INVALID;
1364 if(sql_set_user(inst, request, NULL) < 0)
1365 return RLM_MODULE_FAIL;
1367 radius_xlat(querystr, sizeof(querystr), inst->config->simul_count_query, request, sql_escape_func, inst);
1369 /* initialize the sql socket */
1370 sqlsocket = sql_get_socket(inst);
1371 if(sqlsocket == NULL)
1372 return RLM_MODULE_FAIL;
1374 if(rlm_sql_select_query(&sqlsocket, inst, querystr)) {
1375 sql_release_socket(inst, sqlsocket);
1376 return RLM_MODULE_FAIL;
1379 ret = rlm_sql_fetch_row(&sqlsocket, inst);
1381 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1382 sql_release_socket(inst, sqlsocket);
1383 return RLM_MODULE_FAIL;
1386 row = sqlsocket->row;
1388 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1389 sql_release_socket(inst, sqlsocket);
1390 return RLM_MODULE_FAIL;
1393 request->simul_count = atoi(row[0]);
1394 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1396 if(request->simul_count < request->simul_max) {
1397 sql_release_socket(inst, sqlsocket);
1398 return RLM_MODULE_OK;
1402 * Looks like too many sessions, so let's start verifying
1403 * them, unless told to rely on count query only.
1405 if (!inst->config->simul_verify_query ||
1406 (inst->config->simul_verify_query[0] == '\0')) {
1407 sql_release_socket(inst, sqlsocket);
1408 return RLM_MODULE_OK;
1411 radius_xlat(querystr, sizeof(querystr), inst->config->simul_verify_query, request, sql_escape_func, inst);
1412 if(rlm_sql_select_query(&sqlsocket, inst, querystr)) {
1413 sql_release_socket(inst, sqlsocket);
1414 return RLM_MODULE_FAIL;
1418 * Setup some stuff, like for MPP detection.
1420 request->simul_count = 0;
1422 if ((vp = pairfind(request->packet->vps, PW_FRAMED_IP_ADDRESS, 0)) != NULL)
1423 ipno = vp->vp_ipaddr;
1424 if ((vp = pairfind(request->packet->vps, PW_CALLING_STATION_ID, 0)) != NULL)
1425 call_num = vp->vp_strvalue;
1428 while (rlm_sql_fetch_row(&sqlsocket, inst) == 0) {
1429 row = sqlsocket->row;
1433 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1434 sql_release_socket(inst, sqlsocket);
1435 RDEBUG("Cannot zap stale entry. No username present in entry.", inst->config->xlat_name);
1436 return RLM_MODULE_FAIL;
1439 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1440 sql_release_socket(inst, sqlsocket);
1441 RDEBUG("Cannot zap stale entry. No session id in entry.", inst->config->xlat_name);
1442 return RLM_MODULE_FAIL;
1445 nas_addr = inet_addr(row[3]);
1447 nas_port = atoi(row[4]);
1449 check = rad_check_ts(nas_addr, nas_port, row[2], row[1]);
1453 * Stale record - zap it.
1455 if (inst->config->deletestalesessions == TRUE) {
1456 uint32_t framed_addr = 0;
1461 framed_addr = inet_addr(row[5]);
1463 if (strcmp(row[7], "PPP") == 0)
1465 else if (strcmp(row[7], "SLIP") == 0)
1469 sess_time = atoi(row[8]);
1470 session_zap(request, nas_addr, nas_port,
1471 row[2], row[1], framed_addr,
1475 else if (check == 1) {
1477 * User is still logged in.
1479 ++request->simul_count;
1482 * Does it look like a MPP attempt?
1484 if (row[5] && ipno && inet_addr(row[5]) == ipno)
1485 request->simul_mpp = 2;
1486 else if (row[6] && call_num &&
1487 !strncmp(row[6],call_num,16))
1488 request->simul_mpp = 2;
1492 * Failed to check the terminal server for
1493 * duplicate logins: return an error.
1495 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1496 sql_release_socket(inst, sqlsocket);
1497 radlog_request(L_ERR, 0, request, "Failed to check the terminal server for user '%s'.", row[2]);
1498 return RLM_MODULE_FAIL;
1502 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1503 sql_release_socket(inst, sqlsocket);
1506 * The Auth module apparently looks at request->simul_count,
1507 * not the return value of this module when deciding to deny
1508 * a call for too many sessions.
1510 return RLM_MODULE_OK;
1515 * Postauth: Write a record of the authentication attempt
1517 static int rlm_sql_postauth(void *instance, REQUEST * request) {
1518 SQL_INST *inst = instance;
1520 if (inst->config->postauth) {
1521 return acct_redundant(inst, request, inst->config->postauth);
1524 return RLM_MODULE_NOOP;
1528 * Execute postauth_query after authentication
1532 /* globally exported name */
1533 module_t rlm_sql = {
1536 RLM_TYPE_THREAD_SAFE, /* type: reserved */
1537 rlm_sql_instantiate, /* instantiation */
1538 rlm_sql_detach, /* detach */
1540 NULL, /* authentication */
1541 rlm_sql_authorize, /* authorization */
1542 NULL, /* preaccounting */
1543 #ifdef WITH_ACCOUNTING
1544 rlm_sql_accounting, /* accounting */
1548 #ifdef WITH_SESSION_MGMT
1549 rlm_sql_checksimul, /* checksimul */
1553 NULL, /* pre-proxy */
1554 NULL, /* post-proxy */
1555 rlm_sql_postauth /* post-auth */