-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
rlm_sql.c
1941 lines (1596 loc) · 51.3 KB
/
rlm_sql.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This program is is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
/**
* $Id$
* @file rlm_sql.c
* @brief Implements SQL 'users' file, and SQL accounting.
*
* @copyright 2012-2014 Arran Cudbard-Bell <a.cudbardb@freeradius.org>
* @copyright 2000,2006 The FreeRADIUS server project
* @copyright 2000 Mike Machado <mike@innercite.com>
* @copyright 2000 Alan DeKok <aland@ox.org>
*/
RCSID("$Id$")
#define LOG_PREFIX "rlm_sql (%s) - "
#define LOG_PREFIX_ARGS inst->name
#include <ctype.h>
#include <freeradius-devel/radiusd.h>
#include <freeradius-devel/modules.h>
#include <freeradius-devel/map_proc.h>
#include <freeradius-devel/token.h>
#include <freeradius-devel/rad_assert.h>
#include <freeradius-devel/exfile.h>
#include <sys/stat.h>
#include "rlm_sql.h"
extern rad_module_t rlm_sql;
/*
* So we can do pass2 xlat checks on the queries.
*/
static const CONF_PARSER query_config[] = {
{ FR_CONF_OFFSET("query", PW_TYPE_STRING | PW_TYPE_XLAT | PW_TYPE_MULTI, rlm_sql_config_t, accounting.query) },
CONF_PARSER_TERMINATOR
};
/*
* For now hard-code the subsections. This isn't perfect, but it
* helps the average case.
*/
static const CONF_PARSER type_config[] = {
{ FR_CONF_POINTER("accounting-on", PW_TYPE_SUBSECTION, NULL), .subcs = (void const *) query_config },
{ FR_CONF_POINTER("accounting-off", PW_TYPE_SUBSECTION, NULL), .subcs = (void const *) query_config },
{ FR_CONF_POINTER("start", PW_TYPE_SUBSECTION, NULL), .subcs = (void const *) query_config },
{ FR_CONF_POINTER("interim-update", PW_TYPE_SUBSECTION, NULL), .subcs = (void const *) query_config },
{ FR_CONF_POINTER("stop", PW_TYPE_SUBSECTION, NULL), .subcs = (void const *) query_config },
CONF_PARSER_TERMINATOR
};
static const CONF_PARSER acct_config[] = {
{ FR_CONF_OFFSET("reference", PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, accounting.reference), .dflt = ".query" },
{ FR_CONF_OFFSET("logfile", PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, accounting.logfile) },
{ FR_CONF_POINTER("type", PW_TYPE_SUBSECTION, NULL), .subcs = (void const *) type_config },
CONF_PARSER_TERMINATOR
};
static const CONF_PARSER postauth_config[] = {
{ FR_CONF_OFFSET("reference", PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, postauth.reference), .dflt = ".query" },
{ FR_CONF_OFFSET("logfile", PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, postauth.logfile) },
{ FR_CONF_OFFSET("query", PW_TYPE_STRING | PW_TYPE_XLAT | PW_TYPE_MULTI, rlm_sql_config_t, postauth.query) },
CONF_PARSER_TERMINATOR
};
static const CONF_PARSER module_config[] = {
{ FR_CONF_OFFSET("driver", PW_TYPE_STRING, rlm_sql_config_t, sql_driver_name), .dflt = "rlm_sql_null" },
{ FR_CONF_OFFSET("server", PW_TYPE_STRING, rlm_sql_config_t, sql_server), .dflt = "" }, /* Must be zero length so drivers can determine if it was set */
{ FR_CONF_OFFSET("port", PW_TYPE_INTEGER, rlm_sql_config_t, sql_port), .dflt = "0" },
{ FR_CONF_OFFSET("login", PW_TYPE_STRING, rlm_sql_config_t, sql_login), .dflt = "" },
{ FR_CONF_OFFSET("password", PW_TYPE_STRING | PW_TYPE_SECRET, rlm_sql_config_t, sql_password), .dflt = "" },
{ FR_CONF_OFFSET("radius_db", PW_TYPE_STRING, rlm_sql_config_t, sql_db), .dflt = "radius" },
{ FR_CONF_OFFSET("read_groups", PW_TYPE_BOOLEAN, rlm_sql_config_t, read_groups), .dflt = "yes" },
{ FR_CONF_OFFSET("read_profiles", PW_TYPE_BOOLEAN, rlm_sql_config_t, read_profiles), .dflt = "yes" },
{ FR_CONF_OFFSET("read_clients", PW_TYPE_BOOLEAN, rlm_sql_config_t, do_clients), .dflt = "no" },
{ FR_CONF_OFFSET("delete_stale_sessions", PW_TYPE_BOOLEAN, rlm_sql_config_t, delete_stale_sessions), .dflt = "yes" },
{ FR_CONF_OFFSET("sql_user_name", PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, query_user), .dflt = "" },
{ FR_CONF_OFFSET("group_attribute", PW_TYPE_STRING, rlm_sql_config_t, group_attribute) },
{ FR_CONF_OFFSET("logfile", PW_TYPE_STRING | PW_TYPE_XLAT, rlm_sql_config_t, logfile) },
{ FR_CONF_OFFSET("default_user_profile", PW_TYPE_STRING, rlm_sql_config_t, default_profile), .dflt = "" },
{ FR_CONF_OFFSET("client_query", PW_TYPE_STRING, rlm_sql_config_t, client_query), .dflt = "SELECT id,nasname,shortname,type,secret FROM nas" },
{ FR_CONF_OFFSET("open_query", PW_TYPE_STRING, rlm_sql_config_t, connect_query) },
{ FR_CONF_OFFSET("authorize_check_query", PW_TYPE_STRING | PW_TYPE_XLAT | PW_TYPE_NOT_EMPTY, rlm_sql_config_t, authorize_check_query) },
{ FR_CONF_OFFSET("authorize_reply_query", PW_TYPE_STRING | PW_TYPE_XLAT | PW_TYPE_NOT_EMPTY, rlm_sql_config_t, authorize_reply_query) },
{ FR_CONF_OFFSET("authorize_group_check_query", PW_TYPE_STRING | PW_TYPE_XLAT | PW_TYPE_NOT_EMPTY, rlm_sql_config_t, authorize_group_check_query) },
{ FR_CONF_OFFSET("authorize_group_reply_query", PW_TYPE_STRING | PW_TYPE_XLAT | PW_TYPE_NOT_EMPTY, rlm_sql_config_t, authorize_group_reply_query) },
{ FR_CONF_OFFSET("group_membership_query", PW_TYPE_STRING | PW_TYPE_XLAT | PW_TYPE_NOT_EMPTY, rlm_sql_config_t, groupmemb_query) },
#ifdef WITH_SESSION_MGMT
{ FR_CONF_OFFSET("simul_count_query", PW_TYPE_STRING | PW_TYPE_XLAT | PW_TYPE_NOT_EMPTY, rlm_sql_config_t, simul_count_query) },
{ FR_CONF_OFFSET("simul_verify_query", PW_TYPE_STRING | PW_TYPE_XLAT | PW_TYPE_NOT_EMPTY, rlm_sql_config_t, simul_verify_query) },
#endif
{ FR_CONF_OFFSET("safe_characters", PW_TYPE_STRING, rlm_sql_config_t, allowed_chars), .dflt = "@abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_: /" },
/*
* This only works for a few drivers.
*/
{ FR_CONF_OFFSET("query_timeout", PW_TYPE_INTEGER, rlm_sql_config_t, query_timeout) },
{ FR_CONF_POINTER("accounting", PW_TYPE_SUBSECTION, NULL), .subcs = (void const *) acct_config },
{ FR_CONF_POINTER("post-auth", PW_TYPE_SUBSECTION, NULL), .subcs = (void const *) postauth_config },
CONF_PARSER_TERMINATOR
};
static size_t sql_escape_for_xlat_func(REQUEST *request, char *out, size_t outlen, char const *in, void *arg);
/*
* Fall-Through checking function from rlm_files.c
*/
static sql_fall_through_t fall_through(VALUE_PAIR *vp)
{
VALUE_PAIR *tmp;
tmp = fr_pair_find_by_num(vp, 0, PW_FALL_THROUGH, TAG_ANY);
return tmp ? tmp->vp_integer : FALL_THROUGH_DEFAULT;
}
/*
* Yucky prototype.
*/
static int generate_sql_clients(rlm_sql_t *inst);
static size_t sql_escape_func(REQUEST *, char *out, size_t outlen, char const *in, void *arg);
/** Execute an arbitrary SQL query
*
* For selects the first value of the first column will be returned,
* for inserts, updates and deletes the number of rows affected will be
* returned instead.
*/
static ssize_t sql_xlat(UNUSED TALLOC_CTX *ctx, char **out, UNUSED size_t outlen,
void const *mod_inst, UNUSED void const *xlat_inst,
REQUEST *request, char const *fmt)
{
rlm_sql_handle_t *handle = NULL;
rlm_sql_row_t row;
rlm_sql_t const *inst = mod_inst;
sql_rcode_t rcode;
ssize_t ret = 0;
char const *p;
handle = fr_connection_get(inst->pool, request); /* connection pool should produce error */
if (!handle) return 0;
rlm_sql_query_log(inst, request, NULL, fmt);
/*
* Trim whitespace for the prefix check
*/
for (p = fmt; is_whitespace(p); p++);
/*
* If the query starts with any of the following prefixes,
* then return the number of rows affected
*/
if ((strncasecmp(p, "insert", 6) == 0) ||
(strncasecmp(p, "update", 6) == 0) ||
(strncasecmp(p, "delete", 6) == 0)) {
int numaffected;
rcode = rlm_sql_query(inst, request, &handle, fmt);
if (rcode != RLM_SQL_OK) {
query_error:
RERROR("SQL query failed: %s", fr_int2str(sql_rcode_table, rcode, "<INVALID>"));
ret = -1;
goto finish;
}
numaffected = (inst->driver->sql_affected_rows)(handle, inst->config);
if (numaffected < 1) {
RDEBUG("SQL query affected no rows");
(inst->driver->sql_finish_query)(handle, inst->config);
goto finish;
}
MEM(*out = talloc_asprintf(request, "%d", numaffected));
ret = talloc_array_length(*out) - 1;
(inst->driver->sql_finish_query)(handle, inst->config);
goto finish;
} /* else it's a SELECT statement */
rcode = rlm_sql_select_query(inst, request, &handle, fmt);
if (rcode != RLM_SQL_OK) goto query_error;
rcode = rlm_sql_fetch_row(&row, inst, request, &handle);
switch (rcode) {
case RLM_SQL_OK:
if (row[0]) break;
RDEBUG("NULL value in first column of result");
(inst->driver->sql_finish_select_query)(handle, inst->config);
ret = -1;
goto finish;
case RLM_SQL_NO_MORE_ROWS:
RDEBUG("SQL query returned no results");
(inst->driver->sql_finish_select_query)(handle, inst->config);
ret = -1;
goto finish;
default:
(inst->driver->sql_finish_select_query)(handle, inst->config);
goto query_error;
}
*out = talloc_bstrndup(request, row[0], strlen(row[0]));
ret = talloc_array_length(*out) - 1;
(inst->driver->sql_finish_select_query)(handle, inst->config);
finish:
fr_connection_release(inst->pool, request, handle);
return ret;
}
/** Converts a string value into a #VALUE_PAIR
*
* @param[in,out] ctx to allocate #VALUE_PAIR (s).
* @param[out] out where to write the resulting #VALUE_PAIR.
* @param[in] request The current request.
* @param[in] map to process.
* @param[in] uctx The value to parse.
* @return
* - 0 on success.
* - -1 on failure.
*/
static int _sql_map_proc_get_value(TALLOC_CTX *ctx, VALUE_PAIR **out, REQUEST *request, vp_map_t const *map, void *uctx)
{
VALUE_PAIR *vp;
char const *value = uctx;
vp = fr_pair_afrom_da(ctx, map->lhs->tmpl_da);
/*
* Buffer not always talloced, sometimes it's
* just a pointer to a field in a result struct.
*/
if (fr_pair_value_from_str(vp, value, strlen(value)) < 0) {
char *escaped;
escaped = fr_asprint(vp, value, talloc_array_length(value) - 1, '"');
REDEBUG("Failed parsing value \"%s\" for attribute %s: %s", escaped,
map->lhs->tmpl_da->name, fr_strerror());
talloc_free(vp); /* also frees escaped */
return -1;
}
vp->op = map->op;
*out = vp;
return 0;
}
/*
* Verify the result of the map.
*/
static int sql_map_verify(CONF_SECTION *cs, UNUSED void *mod_inst, UNUSED void *proc_inst,
vp_tmpl_t const *src, UNUSED vp_map_t const *maps)
{
if (!src) {
cf_log_err_cs(cs, "Missing SQL query");
return -1;
}
return 0;
}
/** Executes a SELECT query and maps the result to server attributes
*
* @param mod_inst #rlm_sql_t instance.
* @param proc_inst Instance data for this specific mod_proc call (unused).
* @param request The current request.
* @param query string to execute.
* @param maps Head of the map list.
* @return
* - #RLM_MODULE_NOOP no rows were returned or columns matched.
* - #RLM_MODULE_UPDATED if one or more #VALUE_PAIR were added to the #REQUEST.
* - #RLM_MODULE_FAIL if a fault occurred.
*/
static rlm_rcode_t mod_map_proc(void *mod_inst, UNUSED void *proc_inst, REQUEST *request,
vp_tmpl_t const *query, vp_map_t const *maps)
{
rlm_sql_t *inst = talloc_get_type_abort(mod_inst, rlm_sql_t);
rlm_sql_handle_t *handle = NULL;
int i, j;
rlm_rcode_t rcode = RLM_MODULE_UPDATED;
sql_rcode_t ret;
vp_map_t const *map;
rlm_sql_row_t row;
int rows = 0;
int field_cnt;
char const **fields = NULL, *map_rhs;
char map_rhs_buff[128];
char *query_str = NULL;
#define MAX_SQL_FIELD_INDEX (64)
int field_index[MAX_SQL_FIELD_INDEX];
bool found_field = false; /* Did we find any matching fields in the result set ? */
rad_assert(inst->driver->sql_fields); /* Should have been caught during validation... */
if (tmpl_aexpand(request, &query_str, request, query, sql_escape_for_xlat_func, inst) < 0) {
return RLM_MODULE_FAIL;
}
for (i = 0; i < MAX_SQL_FIELD_INDEX; i++) field_index[i] = -1;
/*
* Add SQL-User-Name attribute just in case it is needed
* We could search the string fmt for SQL-User-Name to see if this is
* needed or not
*/
sql_set_user(inst, request, NULL);
handle = fr_connection_get(inst->pool, request); /* connection pool should produce error */
if (!handle) {
rcode = RLM_MODULE_FAIL;
goto finish;
}
rlm_sql_query_log(inst, request, NULL, query_str);
ret = rlm_sql_select_query(inst, request, &handle, query_str);
if (ret != RLM_SQL_OK) {
RERROR("SQL query failed: %s", fr_int2str(sql_rcode_table, ret, "<INVALID>"));
rcode = RLM_MODULE_FAIL;
goto finish;
}
/*
* Not every driver provides an sql_num_rows function
*/
if (inst->driver->sql_num_rows) {
ret = inst->driver->sql_num_rows(handle, inst->config);
if (ret == 0) {
RDEBUG2("Server returned an empty result");
rcode = RLM_MODULE_NOOP;
(inst->driver->sql_finish_select_query)(handle, inst->config);
goto finish;
}
if (ret < 0) {
RERROR("Failed retrieving row count");
error:
rcode = RLM_MODULE_FAIL;
(inst->driver->sql_finish_select_query)(handle, inst->config);
goto finish;
}
}
/*
* Map proc only registered if driver provides an sql_fields function
*/
ret = (inst->driver->sql_fields)(&fields, handle, inst->config);
if (ret != RLM_SQL_OK) {
RERROR("Failed retrieving field names: %s", fr_int2str(sql_rcode_table, ret, "<INVALID>"));
goto error;
}
rad_assert(fields);
field_cnt = talloc_array_length(fields);
if (RDEBUG_ENABLED3) for (j = 0; j < field_cnt; j++) RDEBUG3("Got field: %s", fields[j]);
/*
* Iterate over the maps, it's O(N2)ish but probably
* faster than building a radix tree each time the
* map set is evaluated (map->rhs can be dynamic).
*/
for (map = maps, i = 0;
map && (i < MAX_SQL_FIELD_INDEX);
map = map->next, i++) {
/*
* Expand the RHS to get the name of the SQL field
*/
if (tmpl_expand(&map_rhs, map_rhs_buff, sizeof(map_rhs_buff),
request, map->rhs, NULL, NULL) < 0) {
RPERROR("Failed getting field name");
goto error;
}
for (j = 0; j < field_cnt; j++) {
if (strcmp(fields[j], map_rhs) != 0) continue;
field_index[i] = j;
found_field = true;
}
}
/*
* Couldn't resolve any map RHS values to fields
* in the result set.
*/
if (!found_field) {
RDEBUG("No fields matching map found in query result");
rcode = RLM_MODULE_NOOP;
(inst->driver->sql_finish_select_query)(handle, inst->config);
goto finish;
}
/*
* We've resolved all the maps to result indexes, now convert
* the values at those indexes into VALUE_PAIRs.
*
* Note: Not all SQL client libraries provide a row count,
* so we have to do the count here.
*/
while (((ret = rlm_sql_fetch_row(&row, inst, request, &handle)) == RLM_SQL_OK)) {
rows++;
for (map = maps, j = 0;
map && (j < MAX_SQL_FIELD_INDEX);
map = map->next, j++) {
if (field_index[j] < 0) continue; /* We didn't find the map RHS in the field set */
if (map_to_request(request, map, _sql_map_proc_get_value, row[field_index[j]]) < 0) goto error;
}
}
if (ret == RLM_SQL_ERROR) goto error;
if (rows == 0) {
RDEBUG("SQL query returned no results");
rcode = RLM_MODULE_NOOP;
}
(inst->driver->sql_finish_select_query)(handle, inst->config);
finish:
talloc_free(query_str);
talloc_free(fields);
fr_connection_release(inst->pool, request, handle);
return rcode;
}
static int generate_sql_clients(rlm_sql_t *inst)
{
rlm_sql_handle_t *handle;
rlm_sql_row_t row;
unsigned int i = 0;
int ret = 0;
RADCLIENT *c;
DEBUG("Processing generate_sql_clients");
DEBUG("Query is: %s", inst->config->client_query);
handle = fr_connection_get(inst->pool, NULL);
if (!handle) return -1;
if (rlm_sql_select_query(inst, NULL, &handle, inst->config->client_query) != RLM_SQL_OK) return -1;
while (rlm_sql_fetch_row(&row, inst, NULL, &handle) == RLM_SQL_OK) {
char *server = NULL;
i++;
/*
* The return data for each row MUST be in the following order:
*
* 0. Row ID (currently unused)
* 1. Name (or IP address)
* 2. Shortname
* 3. Type
* 4. Secret
* 5. Virtual Server (optional)
*/
if (!row[0]){
ERROR("No row id found on pass %d", i);
continue;
}
if (!row[1]){
ERROR("No nasname found for row %s", row[0]);
continue;
}
if (!row[2]){
ERROR("No short name found for row %s", row[0]);
continue;
}
if (!row[4]){
ERROR("No secret found for row %s", row[0]);
continue;
}
if (((inst->driver->sql_num_fields)(handle, inst->config) > 5) && (row[5] != NULL) && *row[5]) {
server = row[5];
}
DEBUG("Adding client %s (%s) to %s clients list",
row[1], row[2], server ? server : "global");
/* FIXME: We should really pass a proper ctx */
c = client_afrom_query(NULL,
row[1], /* identifier */
row[4], /* secret */
row[2], /* shortname */
row[3], /* type */
server, /* server */
false); /* require message authenticator */
if (!c) {
continue;
}
if (!client_add(NULL, c)) {
WARN("Failed to add client, possible duplicate?");
client_free(c);
ret = -1;
break;
}
DEBUG("Client \"%s\" (%s) added", c->longname, c->shortname);
}
(inst->driver->sql_finish_select_query)(handle, inst->config);
fr_connection_release(inst->pool, NULL, handle);
return ret;
}
/** xlat escape function for drivers which do not provide their own
*
*/
static size_t sql_escape_func(UNUSED REQUEST *request, char *out, size_t outlen, char const *in, void *arg)
{
rlm_sql_handle_t *handle = arg;
rlm_sql_t const *inst = handle->inst;
size_t len = 0;
while (in[0]) {
size_t utf8_len;
/*
* Allow all multi-byte UTF8 characters.
*/
utf8_len = fr_utf8_char((uint8_t const *) in, -1);
if (utf8_len > 1) {
if (outlen <= utf8_len) break;
memcpy(out, in, utf8_len);
in += utf8_len;
out += utf8_len;
outlen -= utf8_len;
len += utf8_len;
continue;
}
/*
* Because we register our own escape function
* we're now responsible for escaping all special
* chars in an xlat expansion or attribute value.
*/
switch (in[0]) {
case '\n':
if (outlen <= 2) break;
out[0] = '\\';
out[1] = 'n';
in++;
out += 2;
outlen -= 2;
len += 2;
break;
case '\r':
if (outlen <= 2) break;
out[0] = '\\';
out[1] = 'r';
in++;
out += 2;
outlen -= 2;
len += 2;
break;
case '\t':
if (outlen <= 2) break;
out[0] = '\\';
out[1] = 't';
in++;
out += 2;
outlen -= 2;
len += 2;
break;
}
/*
* Non-printable characters get replaced with their
* mime-encoded equivalents.
*/
if ((in[0] < 32) ||
strchr(inst->config->allowed_chars, *in) == NULL) {
/*
* Only 3 or less bytes available.
*/
if (outlen <= 3) {
break;
}
snprintf(out, outlen, "=%02X", (unsigned char) in[0]);
in++;
out += 3;
outlen -= 3;
len += 3;
continue;
}
/*
* Only one byte left.
*/
if (outlen <= 1) {
break;
}
/*
* Allowed character.
*/
*out = *in;
out++;
in++;
outlen--;
len++;
}
*out = '\0';
return len;
}
/** Passed as the escape function to map_proc and sql xlat methods
*
* The variant reserves a connection for the escape functions to use, and releases it after
* escaping is complete.
*/
static size_t sql_escape_for_xlat_func(REQUEST *request, char *out, size_t outlen, char const *in, void *arg)
{
size_t ret;
rlm_sql_t *inst = talloc_get_type_abort(arg, rlm_sql_t);
rlm_sql_handle_t *handle;
handle = fr_connection_get(inst->pool, request);
if (!handle) {
out[0] = '\0';
return 0;
}
ret = inst->sql_escape_func(request, out, outlen, in, handle);
fr_connection_release(inst->pool, request, handle);
return ret;
}
/*
* Set the SQL user name.
*
* We don't call the escape function here. The resulting string
* will be escaped later in the queries xlat so we don't need to
* escape it twice. (it will make things wrong if we have an
* escape candidate character in the username)
*/
int sql_set_user(rlm_sql_t const *inst, REQUEST *request, char const *username)
{
char *expanded = NULL;
VALUE_PAIR *vp = NULL;
char const *sqluser;
ssize_t len;
rad_assert(request->packet != NULL);
if (username != NULL) {
sqluser = username;
} else if (inst->config->query_user[0] != '\0') {
sqluser = inst->config->query_user;
} else {
return 0;
}
len = xlat_aeval(request, &expanded, request, sqluser, NULL, NULL);
if (len < 0) {
return -1;
}
vp = fr_pair_afrom_da(request->packet, inst->sql_user);
if (!vp) {
talloc_free(expanded);
return -1;
}
fr_pair_value_strsteal(vp, expanded);
RDEBUG2("SQL-User-Name set to '%s'", vp->vp_strvalue);
vp->op = T_OP_SET;
/*
* Delete any existing SQL-User-Name, and replace it with ours.
*/
fr_pair_delete_by_num(&request->packet->vps, vp->da->vendor, vp->da->attr, TAG_ANY);
fr_pair_add(&request->packet->vps, vp);
return 0;
}
/*
* Do a set/unset user, so it's a bit clearer what's going on.
*/
#define sql_unset_user(_i, _r) fr_pair_delete_by_num(&_r->packet->vps, _i->sql_user->vendor, _i->sql_user->attr, TAG_ANY)
static int sql_get_grouplist(rlm_sql_t const *inst, rlm_sql_handle_t **handle, REQUEST *request,
rlm_sql_grouplist_t **phead)
{
char *expanded = NULL;
int num_groups = 0;
rlm_sql_row_t row;
rlm_sql_grouplist_t *entry;
int ret;
/* NOTE: sql_set_user should have been run before calling this function */
entry = *phead = NULL;
if (!inst->config->groupmemb_query || !*inst->config->groupmemb_query) return 0;
if (xlat_aeval(request, &expanded, request, inst->config->groupmemb_query,
inst->sql_escape_func, *handle) < 0) return -1;
ret = rlm_sql_select_query(inst, request, handle, expanded);
talloc_free(expanded);
if (ret != RLM_SQL_OK) return -1;
while (rlm_sql_fetch_row(&row, inst, request, handle) == RLM_SQL_OK) {
if (!row[0]){
RDEBUG("row[0] returned NULL");
(inst->driver->sql_finish_select_query)(*handle, inst->config);
talloc_free(entry);
return -1;
}
if (!*phead) {
*phead = talloc_zero(*handle, rlm_sql_grouplist_t);
entry = *phead;
} else {
entry->next = talloc_zero(*phead, rlm_sql_grouplist_t);
entry = entry->next;
}
entry->next = NULL;
entry->name = talloc_typed_strdup(entry, row[0]);
num_groups++;
}
(inst->driver->sql_finish_select_query)(*handle, inst->config);
return num_groups;
}
/*
* sql groupcmp function. That way we can do group comparisons (in the users file for example)
* with the group memberships reciding in sql
* The group membership query should only return one element which is the username. The returned
* username will then be checked with the passed check string.
*/
static int sql_groupcmp(void *instance, REQUEST *request, UNUSED VALUE_PAIR *request_vp,
VALUE_PAIR *check, UNUSED VALUE_PAIR *check_pairs,
UNUSED VALUE_PAIR **reply_pairs) CC_HINT(nonnull (1, 2, 4));
static int sql_groupcmp(void *instance, REQUEST *request, UNUSED VALUE_PAIR *request_vp,
VALUE_PAIR *check, UNUSED VALUE_PAIR *check_pairs,
UNUSED VALUE_PAIR **reply_pairs)
{
rlm_sql_handle_t *handle;
rlm_sql_t const *inst = instance;
rlm_sql_grouplist_t *head, *entry;
/*
* No group queries, don't do group comparisons.
*/
if (!inst->config->groupmemb_query) {
RWARN("Cannot do group comparison when group_membership_query is not set");
return 1;
}
RDEBUG("sql_groupcmp");
if (check->vp_length == 0){
RDEBUG("sql_groupcmp: Illegal group name");
return 1;
}
/*
* Set, escape, and check the user attr here
*/
if (sql_set_user(inst, request, NULL) < 0)
return 1;
/*
* Get a socket for this lookup
*/
handle = fr_connection_get(inst->pool, request);
if (!handle) {
return 1;
}
/*
* Get the list of groups this user is a member of
*/
if (sql_get_grouplist(inst, &handle, request, &head) < 0) {
REDEBUG("Error getting group membership");
fr_connection_release(inst->pool, request, handle);
return 1;
}
for (entry = head; entry != NULL; entry = entry->next) {
if (strcmp(entry->name, check->vp_strvalue) == 0){
RDEBUG("sql_groupcmp finished: User is a member of group %s",
check->vp_strvalue);
talloc_free(head);
fr_connection_release(inst->pool, request, handle);
return 0;
}
}
/* Free the grouplist */
talloc_free(head);
fr_connection_release(inst->pool, request, handle);
RDEBUG("sql_groupcmp finished: User is NOT a member of group %s", check->vp_strvalue);
return 1;
}
static rlm_rcode_t rlm_sql_process_groups(rlm_sql_t const *inst, REQUEST *request, rlm_sql_handle_t **handle,
sql_fall_through_t *do_fall_through)
{
rlm_rcode_t rcode = RLM_MODULE_NOOP;
VALUE_PAIR *check_tmp = NULL, *reply_tmp = NULL, *sql_group = NULL;
rlm_sql_grouplist_t *head = NULL, *entry = NULL;
char *expanded = NULL;
int rows;
rad_assert(request->packet != NULL);
if (!inst->config->groupmemb_query) {
RWARN("Cannot do check groups when group_membership_query is not set");
do_nothing:
*do_fall_through = FALL_THROUGH_DEFAULT;
/*
* Didn't add group attributes or allocate
* memory, so don't do anything else.
*/
return RLM_MODULE_NOTFOUND;
}
/*
* Get the list of groups this user is a member of
*/
rows = sql_get_grouplist(inst, handle, request, &head);
if (rows < 0) {
REDEBUG("Error retrieving group list");
return RLM_MODULE_FAIL;
}
if (rows == 0) {
RDEBUG2("User not found in any groups");
goto do_nothing;
}
rad_assert(head);
RDEBUG2("User found in the group table");
/*
* Add the Sql-Group attribute to the request list so we know
* which group we're retrieving attributes for
*/
sql_group = pair_make_request(inst->group_da->name, NULL, T_OP_EQ);
if (!sql_group) {
REDEBUG("Error creating %s attribute", inst->group_da->name);
rcode = RLM_MODULE_FAIL;
goto finish;
}
entry = head;
do {
next:
rad_assert(entry != NULL);
fr_pair_value_strcpy(sql_group, entry->name);
if (inst->config->authorize_group_check_query) {
vp_cursor_t cursor;
VALUE_PAIR *vp;
/*
* Expand the group query
*/
if (xlat_aeval(request, &expanded, request, inst->config->authorize_group_check_query,
inst->sql_escape_func, *handle) < 0) {
REDEBUG("Error generating query");
rcode = RLM_MODULE_FAIL;
goto finish;
}
rows = sql_getvpdata(request, inst, request, handle, &check_tmp, expanded);
TALLOC_FREE(expanded);
if (rows < 0) {
REDEBUG("Error retrieving check pairs for group %s", entry->name);
rcode = RLM_MODULE_FAIL;
goto finish;
}
/*
* If we got check rows we need to process them before we decide to
* process the reply rows
*/
if ((rows > 0) &&
(paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) != 0)) {
fr_pair_list_free(&check_tmp);
entry = entry->next;
if (!entry) break;
goto next; /* != continue */
}
RDEBUG2("Group \"%s\": Conditional check items matched", entry->name);
rcode = RLM_MODULE_OK;
RDEBUG2("Group \"%s\": Merging assignment check items", entry->name);
RINDENT();
for (vp = fr_pair_cursor_init(&cursor, &check_tmp);
vp;
vp = fr_pair_cursor_next(&cursor)) {
if (!fr_assignment_op[vp->op]) continue;
rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
}
REXDENT();
radius_pairmove(request, &request->control, check_tmp, true);
check_tmp = NULL;
}
if (inst->config->authorize_group_reply_query) {
/*
* Now get the reply pairs since the paircompare matched
*/
if (xlat_aeval(request, &expanded, request, inst->config->authorize_group_reply_query,
inst->sql_escape_func, *handle) < 0) {
REDEBUG("Error generating query");
rcode = RLM_MODULE_FAIL;
goto finish;
}
rows = sql_getvpdata(request->reply, inst, request, handle, &reply_tmp, expanded);
TALLOC_FREE(expanded);
if (rows < 0) {
REDEBUG("Error retrieving reply pairs for group %s", entry->name);
rcode = RLM_MODULE_FAIL;
goto finish;
}
if (rows == 0) {
*do_fall_through = FALL_THROUGH_DEFAULT;
continue;
}
rad_assert(reply_tmp != NULL); /* coverity, among others */
*do_fall_through = fall_through(reply_tmp);
RDEBUG2("Group \"%s\": Merging reply items", entry->name);
rcode = RLM_MODULE_OK;
rdebug_pair_list(L_DBG_LVL_2, request, reply_tmp, NULL);