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, TAG_ANY);
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, TAG_ANY);
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, TAG_ANY);
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, TAG_ANY);
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, TAG_ANY);
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, TAG_ANY);
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, TAG_ANY);
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, TAG_ANY);
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,
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, "rlm_sql (%s): Couldn't find configuration for "
826 "%s, will return NOOP for calls from this section",
827 inst->config->xlat_name, name);
832 *config = rad_calloc(sizeof(**config));
833 if (cf_section_parse(cs, *config, acct_section_config) < 0) {
834 radlog(L_ERR, "rlm_sql (%s): Couldn't find configuration for "
835 "%s, will return NOOP for calls from this section",
836 inst->config->xlat_name, name);
849 static int rlm_sql_instantiate(CONF_SECTION * conf, void **instance)
852 const char *xlat_name;
854 inst = rad_calloc(sizeof(SQL_INST));
857 * Export these methods, too. This avoids RTDL_GLOBAL.
859 inst->sql_set_user = sql_set_user;
860 inst->sql_get_socket = sql_get_socket;
861 inst->sql_release_socket = sql_release_socket;
862 inst->sql_escape_func = sql_escape_func;
863 inst->sql_query = rlm_sql_query;
864 inst->sql_select_query = rlm_sql_select_query;
865 inst->sql_fetch_row = rlm_sql_fetch_row;
867 inst->config = rad_calloc(sizeof(SQL_CONFIG));
870 xlat_name = cf_section_name2(conf);
871 if (xlat_name == NULL) {
872 xlat_name = cf_section_name1(conf);
879 * Allocate room for <instance>-SQL-Group
881 group_name = rad_malloc((strlen(xlat_name) + 1 + 11) * sizeof(char));
882 sprintf(group_name,"%s-SQL-Group", xlat_name);
883 DEBUG("rlm_sql (%s): Creating new attribute %s",
884 xlat_name, group_name);
886 memset(&flags, 0, sizeof(flags));
887 dict_addattr(group_name, 0, PW_TYPE_STRING, -1, flags);
888 dattr = dict_attrbyname(group_name);
890 radlog(L_ERR, "rlm_sql (%s): Failed to create "
891 "attribute %s", xlat_name, group_name);
898 if (inst->config->groupmemb_query &&
899 inst->config->groupmemb_query[0]) {
900 DEBUG("rlm_sql (%s): Registering sql_groupcmp for %s",
901 xlat_name, group_name);
902 paircompare_register(dattr->attr, PW_USER_NAME,
909 rad_assert(xlat_name);
913 * Register the SQL xlat function
915 inst->config->xlat_name = strdup(xlat_name);
916 xlat_register(xlat_name, sql_xlat, inst);
919 * If the configuration parameters can't be parsed, then fail.
921 if ((cf_section_parse(conf, inst->config, module_config) < 0) ||
922 (parse_sub_section(conf, inst,
923 &inst->config->accounting,
924 RLM_COMPONENT_ACCT) < 0) ||
925 (parse_sub_section(conf, inst,
926 &inst->config->postauth,
927 RLM_COMPONENT_POST_AUTH) < 0)) {
928 radlog(L_ERR, "rlm_sql (%s): Failed parsing configuration",
929 inst->config->xlat_name);
934 * Sanity check for crazy people.
936 if (strncmp(inst->config->sql_driver, "rlm_sql_", 8) != 0) {
937 radlog(L_ERR, "rlm_sql (%s): \"%s\" is NOT an SQL driver!",
938 inst->config->xlat_name, inst->config->sql_driver);
943 * Load the appropriate driver for our database
945 inst->handle = lt_dlopenext(inst->config->sql_driver);
946 if (inst->handle == NULL) {
947 radlog(L_ERR, "Could not link driver %s: %s",
948 inst->config->sql_driver,
950 radlog(L_ERR, "Make sure it (and all its dependent libraries!)"
951 "are in the search path of your system's ld.");
956 inst->module = (rlm_sql_module_t *) lt_dlsym(inst->handle,
957 inst->config->sql_driver);
959 radlog(L_ERR, "Could not link symbol %s: %s",
960 inst->config->sql_driver,
966 radlog(L_INFO, "rlm_sql (%s): Driver %s (module %s) loaded and linked",
967 inst->config->xlat_name, inst->config->sql_driver,
971 * Initialise the connection pool for this instance
973 radlog(L_INFO, "rlm_sql (%s): Attempting to connect to %s@%s:%s/%s",
974 inst->config->xlat_name, inst->config->sql_login,
975 inst->config->sql_server, inst->config->sql_port,
976 inst->config->sql_db);
978 if (sql_init_socketpool(inst) < 0)
981 if (inst->config->groupmemb_query &&
982 inst->config->groupmemb_query[0]) {
983 paircompare_register(PW_SQL_GROUP, PW_USER_NAME, sql_groupcmp, inst);
986 if (inst->config->do_clients) {
987 if (generate_sql_clients(inst) == -1){
988 radlog(L_ERR, "Failed to load clients from SQL.");
996 return RLM_MODULE_OK;
999 rlm_sql_detach(inst);
1005 static rlm_rcode_t rlm_sql_authorize(void *instance, REQUEST * request)
1007 int ret = RLM_MODULE_NOTFOUND;
1009 SQL_INST *inst = instance;
1012 VALUE_PAIR *check_tmp = NULL;
1013 VALUE_PAIR *reply_tmp = NULL;
1014 VALUE_PAIR *user_profile = NULL;
1016 int dofallthrough = 1;
1019 char querystr[MAX_QUERY_LEN];
1022 * Set, escape, and check the user attr here
1024 if (sql_set_user(inst, request, NULL) < 0)
1025 return RLM_MODULE_FAIL;
1030 * After this point use goto error or goto release to cleanup sockets
1031 * temporary pairlists and temporary attributes.
1033 sqlsocket = sql_get_socket(inst);
1034 if (sqlsocket == NULL)
1038 * Query the check table to find any conditions associated with
1039 * this user/realm/whatever...
1041 if (inst->config->authorize_check_query &&
1042 *inst->config->authorize_check_query) {
1043 if (!radius_xlat(querystr, sizeof(querystr), inst->config->authorize_check_query, request, sql_escape_func, inst)) {
1044 radlog_request(L_ERR, 0, request, "Error generating query; rejecting user");
1049 rows = sql_getvpdata(inst, &sqlsocket, &check_tmp, querystr);
1051 radlog_request(L_ERR, 0, request, "SQL query error; rejecting user");
1057 * Only do this if *some* check pairs were returned
1060 (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) == 0)) {
1061 RDEBUG2("User found in radcheck table");
1063 pairxlatmove(request, &request->config_items, &check_tmp);
1065 ret = RLM_MODULE_OK;
1069 * We only process reply table items if check conditions
1076 if (inst->config->authorize_reply_query &&
1077 *inst->config->authorize_reply_query) {
1079 * Now get the reply pairs since the paircompare matched
1081 if (!radius_xlat(querystr, sizeof(querystr), inst->config->authorize_reply_query, request, sql_escape_func, inst)) {
1082 radlog_request(L_ERR, 0, request, "Error generating query; rejecting user");
1087 rows = sql_getvpdata(inst, &sqlsocket, &reply_tmp, querystr);
1089 radlog_request(L_ERR, 0, request, "SQL query error; rejecting user");
1095 if (!inst->config->read_groups)
1096 dofallthrough = fallthrough(reply_tmp);
1098 pairxlatmove(request, &request->reply->vps, &reply_tmp);
1100 ret = RLM_MODULE_OK;
1107 * Clear out the pairlists
1109 pairfree(&check_tmp);
1110 pairfree(&reply_tmp);
1113 * dofallthrough is set to 1 by default so that if the user information
1114 * is not found, we will still process groups. If the user information,
1115 * however, *is* found, Fall-Through must be set in order to process
1116 * the groups as well.
1118 if (dofallthrough) {
1119 rows = rlm_sql_process_groups(inst, request, sqlsocket, &dofallthrough);
1121 radlog_request(L_ERR, 0, request, "Error processing groups; rejecting user");
1127 ret = RLM_MODULE_OK;
1131 * Repeat the above process with the default profile or User-Profile
1133 if (dofallthrough) {
1135 * Check for a default_profile or for a User-Profile.
1137 user_profile = pairfind(request->config_items, PW_USER_PROFILE, 0, TAG_ANY);
1139 const char *profile = user_profile ?
1140 user_profile->vp_strvalue :
1141 inst->config->default_profile;
1143 if (!profile || !*profile)
1146 RDEBUG("Checking profile %s", profile);
1148 if (sql_set_user(inst, request, profile) < 0) {
1149 radlog_request(L_ERR, 0, request, "Error setting profile; rejecting user");
1154 rows = rlm_sql_process_groups(inst, request, sqlsocket, &dofallthrough);
1156 radlog_request(L_ERR, 0, request, "Error processing profile groups; rejecting user");
1162 ret = RLM_MODULE_OK;
1168 ret = RLM_MODULE_FAIL;
1171 sql_release_socket(inst, sqlsocket);
1173 pairfree(&check_tmp);
1174 pairfree(&reply_tmp);
1180 * Generic function for failing between a bunch of queries.
1182 * Uses the same principle as rlm_linelog, expanding the 'reference' config
1183 * item using xlat to figure out what query it should execute.
1185 * If the reference matches multiple config items, and a query fails or
1186 * doesn't update any rows, the next matching config item is used.
1189 static int acct_redundant(SQL_INST *inst, REQUEST *request,
1190 sql_acct_section_t *section)
1192 int ret = RLM_MODULE_OK;
1194 SQLSOCK *sqlsocket = NULL;
1196 int numaffected = 0;
1200 const char *attr = NULL;
1203 char path[MAX_STRING_LEN];
1204 char querystr[MAX_QUERY_LEN];
1208 rad_assert(section);
1210 if (section->reference[0] != '.')
1213 if (!radius_xlat(p, (sizeof(path) - (p - path)) - 1,
1214 section->reference, request, NULL, NULL))
1215 return RLM_MODULE_FAIL;
1217 item = cf_reference_item(NULL, section->cs, path);
1219 return RLM_MODULE_FAIL;
1221 if (cf_item_is_section(item)){
1222 radlog(L_ERR, "Sections are not supported as references");
1224 return RLM_MODULE_FAIL;
1227 pair = cf_itemtopair(item);
1228 attr = cf_pair_attr(pair);
1230 RDEBUG2("Using query template '%s'", attr);
1232 sqlsocket = sql_get_socket(inst);
1233 if (sqlsocket == NULL)
1234 return RLM_MODULE_FAIL;
1236 sql_set_user(inst, request, NULL);
1239 value = cf_pair_value(pair);
1241 RDEBUG("Ignoring null query");
1242 ret = RLM_MODULE_NOOP;
1247 radius_xlat(querystr, sizeof(querystr), value, request,
1248 sql_escape_func, inst);
1250 RDEBUG("Ignoring null query");
1251 ret = RLM_MODULE_NOOP;
1256 rlm_sql_query_log(inst, request, section, querystr);
1259 * If rlm_sql_query cannot use the socket it'll try and
1260 * reconnect. Reconnecting will automatically release
1261 * the current socket, and try to select a new one.
1263 * If we get SQL_DOWN it means all connections in the pool
1264 * were exhausted, and we couldn't create a new connection,
1265 * so we do not need to call sql_release_socket.
1267 sql_ret = rlm_sql_query(&sqlsocket, inst, querystr);
1268 if (sql_ret == SQL_DOWN)
1269 return RLM_MODULE_FAIL;
1271 rad_assert(sqlsocket);
1274 * Assume all other errors are incidental, and just meant our
1275 * operation failed and its not a client or SQL syntax error.
1278 numaffected = (inst->module->sql_affected_rows)
1279 (sqlsocket, inst->config);
1280 if (numaffected > 0)
1283 RDEBUG("No records updated");
1286 (inst->module->sql_finish_query)(sqlsocket, inst->config);
1289 * We assume all entries with the same name form a redundant
1292 pair = cf_pair_find_next(section->cs, pair, attr);
1295 RDEBUG("No additional queries configured");
1297 ret = RLM_MODULE_NOOP;
1302 RDEBUG("Trying next query...");
1305 (inst->module->sql_finish_query)(sqlsocket, inst->config);
1308 sql_release_socket(inst, sqlsocket);
1313 #ifdef WITH_ACCOUNTING
1316 * Accounting: Insert or update session data in our sql table
1318 static rlm_rcode_t rlm_sql_accounting(void *instance, REQUEST * request) {
1319 SQL_INST *inst = instance;
1321 if (inst->config->accounting) {
1322 return acct_redundant(inst, request, inst->config->accounting);
1325 return RLM_MODULE_NOOP;
1330 #ifdef WITH_SESSION_MGMT
1332 * See if a user is already logged in. Sets request->simul_count to the
1333 * current session count for this user.
1335 * Check twice. If on the first pass the user exceeds his
1336 * max. number of logins, do a second pass and validate all
1337 * logins by querying the terminal server (using eg. SNMP).
1340 static rlm_rcode_t rlm_sql_checksimul(void *instance, REQUEST * request) {
1342 SQL_INST *inst = instance;
1344 char querystr[MAX_QUERY_LEN];
1347 char *call_num = NULL;
1350 uint32_t nas_addr = 0;
1353 /* If simul_count_query is not defined, we don't do any checking */
1354 if (!inst->config->simul_count_query ||
1355 (inst->config->simul_count_query[0] == 0)) {
1356 return RLM_MODULE_NOOP;
1359 if((request->username == NULL) || (request->username->length == 0)) {
1360 radlog_request(L_ERR, 0, request,
1361 "Zero Length username not permitted\n");
1362 return RLM_MODULE_INVALID;
1366 if(sql_set_user(inst, request, NULL) < 0)
1367 return RLM_MODULE_FAIL;
1369 radius_xlat(querystr, sizeof(querystr), inst->config->simul_count_query, request, sql_escape_func, inst);
1371 /* initialize the sql socket */
1372 sqlsocket = sql_get_socket(inst);
1373 if(sqlsocket == NULL)
1374 return RLM_MODULE_FAIL;
1376 if(rlm_sql_select_query(&sqlsocket, inst, querystr)) {
1377 sql_release_socket(inst, sqlsocket);
1378 return RLM_MODULE_FAIL;
1381 ret = rlm_sql_fetch_row(&sqlsocket, inst);
1383 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1384 sql_release_socket(inst, sqlsocket);
1385 return RLM_MODULE_FAIL;
1388 row = sqlsocket->row;
1390 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1391 sql_release_socket(inst, sqlsocket);
1392 return RLM_MODULE_FAIL;
1395 request->simul_count = atoi(row[0]);
1396 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1398 if(request->simul_count < request->simul_max) {
1399 sql_release_socket(inst, sqlsocket);
1400 return RLM_MODULE_OK;
1404 * Looks like too many sessions, so let's start verifying
1405 * them, unless told to rely on count query only.
1407 if (!inst->config->simul_verify_query ||
1408 (inst->config->simul_verify_query[0] == '\0')) {
1409 sql_release_socket(inst, sqlsocket);
1410 return RLM_MODULE_OK;
1413 radius_xlat(querystr, sizeof(querystr), inst->config->simul_verify_query, request, sql_escape_func, inst);
1414 if(rlm_sql_select_query(&sqlsocket, inst, querystr)) {
1415 sql_release_socket(inst, sqlsocket);
1416 return RLM_MODULE_FAIL;
1420 * Setup some stuff, like for MPP detection.
1422 request->simul_count = 0;
1424 if ((vp = pairfind(request->packet->vps, PW_FRAMED_IP_ADDRESS, 0, TAG_ANY)) != NULL)
1425 ipno = vp->vp_ipaddr;
1426 if ((vp = pairfind(request->packet->vps, PW_CALLING_STATION_ID, 0, TAG_ANY)) != NULL)
1427 call_num = vp->vp_strvalue;
1430 while (rlm_sql_fetch_row(&sqlsocket, inst) == 0) {
1431 row = sqlsocket->row;
1435 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1436 sql_release_socket(inst, sqlsocket);
1437 RDEBUG("Cannot zap stale entry. No username present in entry.", inst->config->xlat_name);
1438 return RLM_MODULE_FAIL;
1441 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1442 sql_release_socket(inst, sqlsocket);
1443 RDEBUG("Cannot zap stale entry. No session id in entry.", inst->config->xlat_name);
1444 return RLM_MODULE_FAIL;
1447 nas_addr = inet_addr(row[3]);
1449 nas_port = atoi(row[4]);
1451 check = rad_check_ts(nas_addr, nas_port, row[2], row[1]);
1455 * Stale record - zap it.
1457 if (inst->config->deletestalesessions == TRUE) {
1458 uint32_t framed_addr = 0;
1463 framed_addr = inet_addr(row[5]);
1465 if (strcmp(row[7], "PPP") == 0)
1467 else if (strcmp(row[7], "SLIP") == 0)
1471 sess_time = atoi(row[8]);
1472 session_zap(request, nas_addr, nas_port,
1473 row[2], row[1], framed_addr,
1477 else if (check == 1) {
1479 * User is still logged in.
1481 ++request->simul_count;
1484 * Does it look like a MPP attempt?
1486 if (row[5] && ipno && inet_addr(row[5]) == ipno)
1487 request->simul_mpp = 2;
1488 else if (row[6] && call_num &&
1489 !strncmp(row[6],call_num,16))
1490 request->simul_mpp = 2;
1494 * Failed to check the terminal server for
1495 * duplicate logins: return an error.
1497 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1498 sql_release_socket(inst, sqlsocket);
1499 radlog_request(L_ERR, 0, request, "Failed to check the terminal server for user '%s'.", row[2]);
1500 return RLM_MODULE_FAIL;
1504 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1505 sql_release_socket(inst, sqlsocket);
1508 * The Auth module apparently looks at request->simul_count,
1509 * not the return value of this module when deciding to deny
1510 * a call for too many sessions.
1512 return RLM_MODULE_OK;
1517 * Postauth: Write a record of the authentication attempt
1519 static rlm_rcode_t rlm_sql_postauth(void *instance, REQUEST * request) {
1520 SQL_INST *inst = instance;
1522 if (inst->config->postauth) {
1523 return acct_redundant(inst, request, inst->config->postauth);
1526 return RLM_MODULE_NOOP;
1530 * Execute postauth_query after authentication
1534 /* globally exported name */
1535 module_t rlm_sql = {
1538 RLM_TYPE_THREAD_SAFE, /* type: reserved */
1539 rlm_sql_instantiate, /* instantiation */
1540 rlm_sql_detach, /* detach */
1542 NULL, /* authentication */
1543 rlm_sql_authorize, /* authorization */
1544 NULL, /* preaccounting */
1545 #ifdef WITH_ACCOUNTING
1546 rlm_sql_accounting, /* accounting */
1550 #ifdef WITH_SESSION_MGMT
1551 rlm_sql_checksimul, /* checksimul */
1555 NULL, /* pre-proxy */
1556 NULL, /* post-proxy */
1557 rlm_sql_postauth /* post-auth */