/
rlm_python.c
775 lines (659 loc) · 17.9 KB
/
rlm_python.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
/*
* rlm_python.c
*
*
* This program 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
*
* Copyright 2000,2006 The FreeRADIUS server project
* Copyright 2002 Miguel A.L. Paraz <mparaz@mparaz.com>
* Copyright 2002 Imperium Technology, Inc.
* - rewritten by Paul P. Komkoff Jr <i@stingr.net>
*/
#include <freeradius-devel/ident.h>
RCSID("$Id$")
#include <freeradius-devel/radiusd.h>
#include <freeradius-devel/modules.h>
#include <Python.h>
#ifdef HAVE_PTHREAD_H
#define Pyx_BLOCK_THREADS {PyGILState_STATE __gstate = PyGILState_Ensure();
#define Pyx_UNBLOCK_THREADS PyGILState_Release(__gstate);}
#else
#define Pyx_BLOCK_THREADS
#define Pyx_UNBLOCK_THREADS
#endif
/*
* TODO: The only needed thing here is function. Anything else is
* required for initialization only. I will remove it, putting a
* symbolic constant here instead.
*/
struct py_function_def {
PyObject *module;
PyObject *function;
char *module_name;
char *function_name;
};
typedef struct rlm_python_t {
PyThreadState *main_thread_state;
struct py_function_def
instantiate,
authorize,
authenticate,
preacct,
accounting,
checksimul,
pre_proxy,
post_proxy,
post_auth,
#ifdef WITH_COA
recv_coa,
send_coa,
#endif
detach;
} rlm_python_t;
/*
* A mapping of configuration file names to internal variables.
*
* Note that the string is dynamically allocated, so it MUST
* be freed. When the configuration file parse re-reads the string,
* it free's the old one, and strdup's the new one, placing the pointer
* to the strdup'd string into 'config.string'. This gets around
* buffer over-flows.
*/
static CONF_PARSER module_config[] = {
#define A(x) { "mod_" #x, PW_TYPE_STRING_PTR, offsetof(rlm_python_t, x.module_name), NULL, NULL }, \
{ "func_" #x, PW_TYPE_STRING_PTR, offsetof(rlm_python_t, x.function_name), NULL, NULL },
A(instantiate)
A(authorize)
A(authenticate)
A(preacct)
A(accounting)
A(checksimul)
A(pre_proxy)
A(post_proxy)
A(post_auth)
#ifdef WITH_COA
A(recv_coa)
A(send_coa)
#endif
A(detach)
#undef A
{ NULL, -1, 0, NULL, NULL } /* end the list */
};
static struct {
const char *name;
int value;
} radiusd_constants[] = {
#define A(x) { #x, x },
A(L_DBG)
A(L_AUTH)
A(L_INFO)
A(L_ERR)
A(L_PROXY)
A(L_CONS)
A(RLM_MODULE_REJECT)
A(RLM_MODULE_FAIL)
A(RLM_MODULE_OK)
A(RLM_MODULE_HANDLED)
A(RLM_MODULE_INVALID)
A(RLM_MODULE_USERLOCK)
A(RLM_MODULE_NOTFOUND)
A(RLM_MODULE_NOOP)
A(RLM_MODULE_UPDATED)
A(RLM_MODULE_NUMCODES)
#undef A
{ NULL, 0 },
};
/*
* This allows us to initialise PyThreadState on a per thread basis
*/
fr_thread_local_setup(PyThreadState *, local_thread_state); /* macro */
/*
* Let assume that radiusd module is only one since we have only
* one intepreter
*/
static PyObject *radiusd_module = NULL;
/*
* radiusd Python functions
*/
/* radlog wrapper */
static PyObject *python_radlog(UNUSED PyObject *module, PyObject *args)
{
int status;
char *msg;
if (!PyArg_ParseTuple(args, "is", &status, &msg)) {
return NULL;
}
radlog(status, "%s", msg);
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef radiusd_methods[] = {
{ "radlog", &python_radlog, METH_VARARGS,
"radiusd.radlog(level, msg)\n\n" \
"Print a message using radiusd logging system. level should be one of the\n" \
"constants L_DBG, L_AUTH, L_INFO, L_ERR, L_PROXY, L_CONS\n"
},
{ NULL, NULL, 0, NULL },
};
static void python_error(void)
{
PyObject
*pType = NULL,
*pValue = NULL,
*pTraceback = NULL,
*pStr1 = NULL,
*pStr2 = NULL;
/* This will be called with the GIL lock held */
PyErr_Fetch(&pType, &pValue, &pTraceback);
if (pType == NULL || pValue == NULL)
goto failed;
if (((pStr1 = PyObject_Str(pType)) == NULL) ||
((pStr2 = PyObject_Str(pValue)) == NULL))
goto failed;
radlog(L_ERR, "rlm_python:EXCEPT:%s: %s", PyString_AsString(pStr1), PyString_AsString(pStr2));
failed:
Py_XDECREF(pStr1);
Py_XDECREF(pStr2);
Py_XDECREF(pType);
Py_XDECREF(pValue);
Py_XDECREF(pTraceback);
}
static int python_init(rlm_python_t *inst)
{
int i;
static char name[] = "radiusd";
if (radiusd_module) return 0;
Py_SetProgramName(name);
#ifdef HAVE_PTHREAD_H
Py_InitializeEx(0); /* Don't override signal handlers */
PyEval_InitThreads(); /* This also grabs a lock */
inst->main_thread_state = PyThreadState_Get(); /* We need this for setting up thread local stuff */
#endif
if ((radiusd_module = Py_InitModule3("radiusd", radiusd_methods,
"FreeRADIUS Module.")) == NULL)
goto failed;
for (i = 0; radiusd_constants[i].name; i++)
if ((PyModule_AddIntConstant(radiusd_module,
radiusd_constants[i].name,
radiusd_constants[i].value)) < 0)
goto failed;
#ifdef HAVE_PTHREAD_H
PyThreadState_Swap(NULL); /* We have to swap out the current thread else we get deadlocks */
PyEval_ReleaseLock(); /* Drop lock grabbed by InitThreads */
#endif
radlog(L_DBG, "python_init done");
return 0;
failed:
Py_XDECREF(radiusd_module);
#ifdef HAVE_PTHREAD_H
PyEval_ReleaseLock();
#endif
Pyx_BLOCK_THREADS
python_error();
Pyx_UNBLOCK_THREADS
radiusd_module = NULL;
Py_Finalize();
return -1;
}
#if 0
static int python_destroy(void)
{
Pyx_BLOCK_THREADS
Py_XDECREF(radiusd_module);
Py_Finalize();
Pyx_UNBLOCK_THREADS
return 0;
}
/*
* This will need reconsidering in a future. Maybe we'll need to
* have our own reference counting for radiusd_module
*/
#endif
/* TODO: Convert this function to accept any iterable objects? */
static void python_vptuple(VALUE_PAIR **vpp, PyObject *pValue,
const char *funcname)
{
int i;
int tuplesize;
VALUE_PAIR *vp;
/*
* If the Python function gave us None for the tuple,
* then just return.
*/
if (pValue == Py_None)
return;
if (!PyTuple_CheckExact(pValue)) {
radlog(L_ERR, "rlm_python:%s: non-tuple passed", funcname);
return;
}
/* Get the tuple tuplesize. */
tuplesize = PyTuple_GET_SIZE(pValue);
for (i = 0; i < tuplesize; i++) {
PyObject *pTupleElement = PyTuple_GET_ITEM(pValue, i);
PyObject *pStr1;
PyObject *pStr2;
PyObject *pOp;
int pairsize;
const char *s1;
const char *s2;
long op;
if (!PyTuple_CheckExact(pTupleElement)) {
radlog(L_ERR, "rlm_python:%s: tuple element %d is not a tuple", funcname, i);
continue;
}
/* Check if it's a pair */
pairsize = PyTuple_GET_SIZE(pTupleElement);
if ((pairsize < 2) || (pairsize > 3)) {
radlog(L_ERR, "rlm_python:%s: tuple element %d is a tuple of size %d. Must be 2 or 3.", funcname, i, pairsize);
continue;
}
if (pairsize == 2) {
pStr1 = PyTuple_GET_ITEM(pTupleElement, 0);
pStr2 = PyTuple_GET_ITEM(pTupleElement, 1);
op = T_OP_EQ;
} else {
pStr1 = PyTuple_GET_ITEM(pTupleElement, 0);
pStr2 = PyTuple_GET_ITEM(pTupleElement, 2);
pOp = PyTuple_GET_ITEM(pTupleElement, 1);
op = PyInt_AsLong(pOp);
}
if ((!PyString_CheckExact(pStr1)) || (!PyString_CheckExact(pStr2))) {
radlog(L_ERR, "rlm_python:%s: tuple element %d must be as (str, str)", funcname, i);
continue;
}
s1 = PyString_AsString(pStr1);
s2 = PyString_AsString(pStr2);
vp = pairmake(s1, s2, op);
if (vp != NULL) {
pairadd(vpp, vp);
radlog(L_DBG, "rlm_python:%s: '%s' = '%s'", funcname, s1, s2);
} else {
radlog(L_DBG, "rlm_python:%s: Failed: '%s' = '%s'", funcname, s1, s2);
}
}
}
/*
* This is the core Python function that the others wrap around.
* Pass the value-pair print strings in a tuple.
*
* FIXME: We're not checking the errors. If we have errors, what
* do we do?
*/
static int python_populate_vptuple(PyObject *pPair, VALUE_PAIR *vp)
{
PyObject *pStr = NULL;
char buf[1024];
/* Look at the vp_print_name? */
if (vp->flags.has_tag)
pStr = PyString_FromFormat("%s:%d", vp->name, vp->flags.tag);
else
pStr = PyString_FromString(vp->name);
if (pStr == NULL)
goto failed;
PyTuple_SET_ITEM(pPair, 0, pStr);
vp_prints_value(buf, sizeof(buf), vp, 1);
if ((pStr = PyString_FromString(buf)) == NULL)
goto failed;
PyTuple_SET_ITEM(pPair, 1, pStr);
return 0;
failed:
return -1;
}
#ifdef HAVE_PTHREAD_H
/** Cleanup any thread local storage on pthread_exit()
*/
static void do_python_cleanup(void *arg)
{
PyThreadState *my_thread_state = arg;
PyEval_AcquireLock();
PyThreadState_Swap(NULL); /* Not entirely sure this is needed */
PyThreadState_Clear(my_thread_state);
PyThreadState_Delete(my_thread_state);
PyEval_ReleaseLock();
}
#endif
static int do_python(rlm_python_t *inst, REQUEST *request, PyObject *pFunc, char const *funcname, int worker)
{
VALUE_PAIR *vp;
PyObject *pRet = NULL;
PyObject *pArgs = NULL;
int tuplelen;
int ret;
PyGILState_STATE gstate;
PyThreadState *prev_thread_state = NULL; /* -Wuninitialized */
memset(&gstate, 0, sizeof(gstate)); /* -Wuninitialized */
/* Return with "OK, continue" if the function is not defined. */
if (!pFunc)
return RLM_MODULE_NOOP;
#ifdef HAVE_PTHREAD_H
gstate = PyGILState_Ensure();
if (worker) {
PyThreadState *my_thread_state;
my_thread_state = fr_thread_local_init(local_thread_state, do_python_cleanup);
if (!my_thread_state) {
my_thread_state = PyThreadState_New(inst->main_thread_state->interp);
if (!my_thread_state) {
radlog(L_ERR, "Failed initialising local PyThreadState on first run");
PyGILState_Release(gstate);
return RLM_MODULE_FAIL;
}
ret = fr_thread_local_set(local_thread_state, my_thread_state);
if (ret != 0) {
radlog(L_ERR, "Failed storing PyThreadState in TLS: %s", strerror(ret));
PyThreadState_Clear(my_thread_state);
PyThreadState_Delete(my_thread_state);
PyGILState_Release(gstate);
return RLM_MODULE_FAIL;
}
}
prev_thread_state = PyThreadState_Swap(my_thread_state); /* Swap in our local thread state */
}
#endif
/* Default return value is "OK, continue" */
ret = RLM_MODULE_OK;
/*
* We will pass a tuple containing (name, value) tuples
* We can safely use the Python function to build up a
* tuple, since the tuple is not used elsewhere.
*
* Determine the size of our tuple by walking through the packet.
* If request is NULL, pass None.
*/
tuplelen = 0;
if (request != NULL) {
for (vp = request->packet->vps; vp; vp = vp->next)
tuplelen++;
}
if (tuplelen == 0) {
Py_INCREF(Py_None);
pArgs = Py_None;
} else {
int i = 0;
if ((pArgs = PyTuple_New(tuplelen)) == NULL) {
ret = RLM_MODULE_FAIL;
goto finish;
}
for (vp = request->packet->vps;
vp != NULL;
vp = vp->next, i++) {
PyObject *pPair;
/* The inside tuple has two only: */
if ((pPair = PyTuple_New(2)) == NULL) {
ret = RLM_MODULE_FAIL;
goto finish;
}
if (python_populate_vptuple(pPair, vp) == 0) {
/* Put the tuple inside the container */
PyTuple_SET_ITEM(pArgs, i, pPair);
} else {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(pArgs, i, Py_None);
Py_DECREF(pPair);
}
}
}
/* Call Python function. */
pRet = PyObject_CallFunctionObjArgs(pFunc, pArgs, NULL);
if (!pRet) {
ret = RLM_MODULE_FAIL;
goto finish;
}
if (!request) {
ret = RLM_MODULE_FAIL;
goto finish;
}
/*
* The function returns either:
* 1. (returnvalue, replyTuple, configTuple), where
* - returnvalue is one of the constants RLM_*
* - replyTuple and configTuple are tuples of string
* tuples of size 2
*
* 2. the function return value alone
*
* 3. None - default return value is set
*
* xxx This code is messy!
*/
if (PyTuple_CheckExact(pRet)) {
PyObject *pTupleInt;
if (PyTuple_GET_SIZE(pRet) != 3) {
radlog(L_ERR, "rlm_python:%s: tuple must be (return, replyTuple, configTuple)", funcname);
ret = RLM_MODULE_FAIL;
goto finish;
}
pTupleInt = PyTuple_GET_ITEM(pRet, 0);
if (!PyInt_CheckExact(pTupleInt)) {
radlog(L_ERR, "rlm_python:%s: first tuple element not an integer", funcname);
ret = RLM_MODULE_FAIL;
goto finish;
}
/* Now have the return value */
ret = PyInt_AsLong(pTupleInt);
/* Reply item tuple */
python_vptuple(&request->reply->vps,
PyTuple_GET_ITEM(pRet, 1), funcname);
/* Config item tuple */
python_vptuple(&request->config_items,
PyTuple_GET_ITEM(pRet, 2), funcname);
} else if (PyInt_CheckExact(pRet)) {
/* Just an integer */
ret = PyInt_AsLong(pRet);
} else if (pRet == Py_None) {
/* returned 'None', return value defaults to "OK, continue." */
ret = RLM_MODULE_OK;
} else {
/* Not tuple or None */
radlog(L_ERR, "rlm_python:%s: function did not return a tuple or None", funcname);
ret = RLM_MODULE_FAIL;
goto finish;
}
finish:
Py_XDECREF(pArgs);
Py_XDECREF(pRet);
#ifdef HAVE_PTHREAD_H
if (worker) {
PyThreadState_Swap(prev_thread_state);
}
PyGILState_Release(gstate);
#endif
return ret;
}
/*
* Import a user module and load a function from it
*/
static int python_load_function(struct py_function_def *def)
{
const char *funcname = "python_load_function";
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
if (def->module_name != NULL && def->function_name != NULL) {
if ((def->module = PyImport_ImportModule(def->module_name)) == NULL) {
radlog(L_ERR, "rlm_python:%s: module '%s' is not found", funcname, def->module_name);
goto failed;
}
if ((def->function = PyObject_GetAttrString(def->module, def->function_name)) == NULL) {
radlog(L_ERR, "rlm_python:%s: function '%s.%s' is not found", funcname, def->module_name, def->function_name);
goto failed;
}
if (!PyCallable_Check(def->function)) {
radlog(L_ERR, "rlm_python:%s: function '%s.%s' is not callable", funcname, def->module_name, def->function_name);
goto failed;
}
}
PyGILState_Release(gstate);
return 0;
failed:
python_error();
radlog(L_ERR, "rlm_python:%s: failed to import python function '%s.%s'", funcname, def->module_name, def->function_name);
Py_XDECREF(def->function);
def->function = NULL;
Py_XDECREF(def->module);
def->module = NULL;
PyGILState_Release(gstate);
return -1;
}
static void python_objclear(PyObject **ob)
{
if (*ob != NULL) {
Pyx_BLOCK_THREADS
Py_DECREF(*ob);
Pyx_UNBLOCK_THREADS
*ob = NULL;
}
}
static void free_and_null(char **p)
{
if (*p != NULL) {
free(*p);
*p = NULL;
}
}
static void python_funcdef_clear(struct py_function_def *def)
{
python_objclear(&def->function);
python_objclear(&def->module);
free_and_null(&def->function_name);
free_and_null(&def->module_name);
}
static void python_instance_clear(struct rlm_python_t *data)
{
#define A(x) python_funcdef_clear(&data->x)
A(instantiate);
A(authorize);
A(authenticate);
A(preacct);
A(accounting);
A(checksimul);
A(detach);
#undef A
}
/*
* Do any per-module initialization that is separate to each
* configured instance of the module. e.g. set up connections
* to external databases, read configuration files, set up
* dictionary entries, etc.
*
* If configuration information is given in the config section
* that must be referenced in later calls, store a handle to it
* in *instance otherwise put a null pointer there.
*
*/
static int python_instantiate(CONF_SECTION *conf, void **instance)
{
struct rlm_python_t *data = NULL;
/*
* Set up a storage area for instance data
*/
if ((data = malloc(sizeof(*data))) == NULL)
return -1;
memset(data, 0, sizeof(*data));
if (python_init(data) != 0) {
free(data);
return -1;
}
/*
* If the configuration parameters can't be parsed, then
* fail.
*/
if (cf_section_parse(conf, data, module_config) < 0) {
free(data);
return -1;
}
#define A(x) if (python_load_function(&data->x) < 0) goto failed
A(instantiate);
A(authenticate);
A(authorize);
A(preacct);
A(accounting);
A(checksimul);
A(pre_proxy);
A(post_proxy);
A(post_auth);
#ifdef WITH_COA
A(recv_coa);
A(send_coa);
#endif
A(detach);
#undef A
*instance = data;
/*
* Call the instantiate function. No request. Use the
* return value.
*/
return do_python(data, NULL, data->instantiate.function, "instantiate", 0);
failed:
Pyx_BLOCK_THREADS
python_error();
Pyx_UNBLOCK_THREADS
python_instance_clear(data);
free(data);
return -1;
}
static int python_detach(void *instance)
{
struct rlm_python_t *data = (struct rlm_python_t *) instance;
int ret;
ret = do_python(data, NULL, data->detach.function, "detach", 0);
python_instance_clear(data);
free(data);
return ret;
}
#define A(x) static int python_##x(void *instance, REQUEST *request) { \
return do_python((rlm_python_t *)instance, request, ((struct rlm_python_t *)instance)->x.function, #x, 1); \
}
A(authenticate)
A(authorize)
A(preacct)
A(accounting)
A(checksimul)
A(pre_proxy)
A(post_proxy)
A(post_auth)
#ifdef WITH_COA
A(recv_coa)
A(send_coa)
#endif
#undef A
/*
* The module name should be the only globally exported symbol.
* That is, everything else should be 'static'.
*
* If the module needs to temporarily modify it's instantiation
* data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
* The server will then take care of ensuring that the module
* is single-threaded.
*/
module_t rlm_python = {
RLM_MODULE_INIT,
"python",
RLM_TYPE_THREAD_UNSAFE, /* type */
python_instantiate, /* instantiation */
python_detach,
{
python_authenticate, /* authentication */
python_authorize, /* authorization */
python_preacct, /* preaccounting */
python_accounting, /* accounting */
python_checksimul, /* checksimul */
python_pre_proxy, /* pre-proxy */
python_post_proxy, /* post-proxy */
python_post_auth /* post-auth */
#ifdef WITH_COA
, python_recv_coa,
python_send_coa
#endif
}
};