radsecproxy.c 88.9 KB
Newer Older
venaas's avatar
 
venaas committed
1
/*
2
 * Copyright (C) 2006-2009 Stig Venaas <venaas@uninett.no>
venaas's avatar
 
venaas committed
3
4
5
6
7
8
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 */

9
10
11
/* Code contributions from:
 *
 * Arne Schwabe <schwabe at uni-paderborn.de>
kolla's avatar
kolla committed
12
13
 * Maja Wolniewicz <mgw@umk.pl>
 * Simon Leinen <simon.leinen@switch.ch>
kolla's avatar
Credits    
kolla committed
14
 * Stefan Winter <stefan.winter@restena.lu>
15
16
 */

venaas's avatar
 
venaas committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* For UDP there is one server instance consisting of udpserverrd and udpserverth
 *              rd is responsible for init and launching wr
 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
 *          each tlsserverrd launches tlsserverwr
 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
 *          for init and launching rd
 *
 * serverrd will receive a request, processes it and puts it in the requestq of
 *          the appropriate clientwr
 * clientwr monitors its requestq and sends requests
 * clientrd looks for responses, processes them and puts them in the replyq of
 *          the peer the request came from
 * serverwr monitors its reply and sends replies
 *
 * In addition to the main thread, we have:
 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
 * For each TLS peer connecting to us there will be 2 more TLS threads
 *       This is only for connected peers
36
 * Example: With 3 UDP peers and 30 TLS peers, there will be a max of
venaas's avatar
 
venaas committed
37
 *          1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
38
 */
venaas's avatar
 
venaas committed
39

venaas's avatar
venaas committed
40
/* Bugs:
venaas's avatar
venaas committed
41
 * May segfault when dtls connections go down? More testing needed
42
 * Remove expired stuff from clients request list?
venaas's avatar
venaas committed
43
44
 * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
 * Useful for TCP accounting? Now we require separate server config for alt port
venaas's avatar
venaas committed
45
46
 */

venaas's avatar
venaas committed
47
#include <signal.h>
venaas's avatar
venaas committed
48
49
#include <sys/socket.h>
#include <netinet/in.h>
venaas's avatar
 
venaas committed
50
#include <netdb.h>
venaas's avatar
venaas committed
51
#include <string.h>
venaas's avatar
 
venaas committed
52
#include <unistd.h>
venaas's avatar
venaas committed
53
#include <limits.h>
venaas's avatar
venaas committed
54
55
56
#ifdef SYS_SOLARIS9
#include <fcntl.h>
#endif
venaas's avatar
venaas committed
57
#include <sys/time.h>
58
#include <sys/types.h>
59
#include <ctype.h>
60
#include <sys/wait.h>
61
#include <arpa/inet.h>
venaas's avatar
venaas committed
62
#include <regex.h>
venaas's avatar
venaas committed
63
#include <libgen.h>
venaas's avatar
 
venaas committed
64
#include <pthread.h>
65
#include <errno.h>
venaas's avatar
 
venaas committed
66
67
68
69
#include <openssl/ssl.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include <openssl/md5.h>
venaas's avatar
venaas committed
70
#include "debug.h"
venaas's avatar
venaas committed
71
#include "list.h"
72
#include "hash.h"
73
#include "util.h"
74
#include "hostport.h"
venaas's avatar
venaas committed
75
#include "radsecproxy.h"
venaas's avatar
venaas committed
76
#include "udp.h"
venaas's avatar
venaas committed
77
78
#include "tcp.h"
#include "tls.h"
venaas's avatar
venaas committed
79
#include "dtls.h"
venaas's avatar
 
venaas committed
80

81
static struct options options;
venaas's avatar
venaas committed
82
static struct list *clconfs, *srvconfs;
83
84
static struct list *realms;
static struct hash *rewriteconfs;
85

venaas's avatar
venaas committed
86
static pthread_mutex_t *ssl_locks = NULL;
venaas's avatar
 
venaas committed
87
88
89
static long *ssl_lock_count;
extern int optind;
extern char *optarg;
venaas's avatar
venaas committed
90
static const struct protodefs *protodefs[RAD_PROTOCOUNT];
venaas's avatar
 
venaas committed
91

venaas's avatar
venaas committed
92
/* minimum required declarations to avoid reordering code */
93
struct realm *adddynamicrealmserver(struct realm *realm, char *id);
94
int dynamicconfig(struct server *server);
95
int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
96
97
void freerealm(struct realm *realm);
void freeclsrvconf(struct clsrvconf *conf);
98
99
void freerq(struct request *rq);
void freerqoutdata(struct rqout *rqout);
venaas's avatar
venaas committed
100
void rmclientrq(struct request *rq, uint8_t id);
101

venaas's avatar
venaas committed
102
103
static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };

venaas's avatar
venaas committed
104
uint8_t protoname2int(const char *name) {
venaas's avatar
venaas committed
105
    uint8_t i;
venaas's avatar
venaas committed
106

venaas's avatar
venaas committed
107
108
109
110
    for (i = 0; i < RAD_PROTOCOUNT; i++)
	if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
	    return i;
    return 255;
venaas's avatar
venaas committed
111
}
112

venaas's avatar
 
venaas committed
113
114
/* callbacks for making OpenSSL thread safe */
unsigned long ssl_thread_id() {
115
    return (unsigned long)pthread_self();
venaas's avatar
venaas committed
116
}
venaas's avatar
 
venaas committed
117
118
119
120
121
122
123
124
125

void ssl_locking_callback(int mode, int type, const char *file, int line) {
    if (mode & CRYPTO_LOCK) {
	pthread_mutex_lock(&ssl_locks[type]);
	ssl_lock_count[type]++;
    } else
	pthread_mutex_unlock(&ssl_locks[type]);
}

126
127
128
/* returns 1 if the len first bits are equal, else 0 */
int prefixmatch(void *a1, void *a2, uint8_t len) {
    static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
venaas's avatar
venaas committed
129
    uint8_t r, l = len / 8;
130
131
132
133
134
135
136
137
    if (l && memcmp(a1, a2, l))
	return 0;
    r = len % 8;
    if (!r)
	return 1;
    return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
}

138
/* returns next config with matching address, or NULL */
139
struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur, uint8_t server_p) {
140
141
    struct list_node *entry;
    struct clsrvconf *conf;
142

venaas's avatar
venaas committed
143
    for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
venaas's avatar
venaas committed
144
	conf = (struct clsrvconf *)entry->data;
145
	if (conf->type == type && addressmatches(conf->hostports, addr, server_p)) {
146
147
148
	    if (cur)
		*cur = entry;
	    return conf;
149
	}
150
    }
venaas's avatar
venaas committed
151
152
153
    return NULL;
}

venaas's avatar
venaas committed
154
struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
155
    return find_conf(type, addr, clconfs, cur, 0);
venaas's avatar
venaas committed
156
157
158
}

struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
159
    return find_conf(type, addr, srvconfs, cur, 1);
venaas's avatar
venaas committed
160
161
}

venaas's avatar
venaas committed
162
/* returns next config of given type, or NULL */
venaas's avatar
venaas committed
163
struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
venaas's avatar
venaas committed
164
165
    struct list_node *entry;
    struct clsrvconf *conf;
166

venaas's avatar
venaas committed
167
    for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
venaas's avatar
venaas committed
168
169
170
171
172
173
	conf = (struct clsrvconf *)entry->data;
	if (conf->type == type) {
	    if (cur)
		*cur = entry;
	    return conf;
	}
174
    }
venaas's avatar
venaas committed
175
176
177
    return NULL;
}

178
179
struct gqueue *newqueue() {
    struct gqueue *q;
180

181
    q = malloc(sizeof(struct gqueue));
182
    if (!q)
183
	debugx(1, DBG_ERR, "malloc failed");
184
185
    q->entries = list_create();
    if (!q->entries)
186
	debugx(1, DBG_ERR, "malloc failed");
187
188
189
190
191
    pthread_mutex_init(&q->mutex, NULL);
    pthread_cond_init(&q->cond, NULL);
    return q;
}

192
void removequeue(struct gqueue *q) {
193
    struct list_node *entry;
194
195
196

    if (!q)
	return;
197
198
    pthread_mutex_lock(&q->mutex);
    for (entry = list_first(q->entries); entry; entry = list_next(entry))
venaas's avatar
venaas committed
199
	freerq((struct request *)entry);
200
201
202
203
    list_destroy(q->entries);
    pthread_cond_destroy(&q->cond);
    pthread_mutex_unlock(&q->mutex);
    pthread_mutex_destroy(&q->mutex);
204
    free(q);
205
206
}

207
void freebios(struct gqueue *q) {
208
    BIO *bio;
209

210
211
212
213
214
    pthread_mutex_lock(&q->mutex);
    while ((bio = (BIO *)list_shift(q->entries)))
	BIO_free(bio);
    pthread_mutex_unlock(&q->mutex);
    removequeue(q);
215
216
}

217
struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
218
    struct client *new = malloc(sizeof(struct client));
219

220
221
222
    if (!new) {
	debug(DBG_ERR, "malloc failed");
	return NULL;
223
    }
224
225
226

    if (lock)
	pthread_mutex_lock(conf->lock);
227
    if (!conf->clients) {
228
229
	conf->clients = list_create();
	if (!conf->clients) {
230
231
	    if (lock)
		pthread_mutex_unlock(conf->lock);
232
233
234
	    debug(DBG_ERR, "malloc failed");
	    return NULL;
	}
235
    }
236

237
238
    memset(new, 0, sizeof(struct client));
    new->conf = conf;
venaas's avatar
venaas committed
239
240
241
242
    if (conf->pdef->addclient)
	conf->pdef->addclient(new);
    else
	new->replyq = newqueue();
243
    list_push(conf->clients, new);
244
245
    if (lock)
	pthread_mutex_unlock(conf->lock);
246
247
248
    return new;
}

249
250
251
252
253
254
255
256
void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
    static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

    if (wantlock)
	pthread_mutex_lock(&lock);
    else
	pthread_mutex_unlock(&lock);
}
257

258
259
260
261
262
void removeclientrqs(struct client *client) {
    struct request *rq;
    struct rqout *rqout;
    int i;

263
    removeclientrqs_sendrq_freeserver_lock(1);
264
265
266
267
    for (i = 0; i < MAX_REQUESTS; i++) {
	rq = client->rqs[i];
	if (!rq)
	    continue;
268
269
270
271
272
273
274
	if (rq->to) {
	    rqout = rq->to->requests + rq->newid;
	    pthread_mutex_lock(rqout->lock);
	    if (rqout->rq == rq) /* still pointing to our request */
		freerqoutdata(rqout);
	    pthread_mutex_unlock(rqout->lock);
	}
275
276
	freerq(rq);
    }
277
    removeclientrqs_sendrq_freeserver_lock(0);
278
279
}

venaas's avatar
venaas committed
280
void removelockedclient(struct client *client) {
281
    struct clsrvconf *conf;
282

283
284
    conf = client->conf;
    if (conf->clients) {
285
	removeclientrqs(client);
286
	removequeue(client->replyq);
287
	list_removedata(conf->clients, client);
288
289
290
	free(client->addr);
	free(client);
    }
venaas's avatar
venaas committed
291
292
293
294
}

void removeclient(struct client *client) {
    struct clsrvconf *conf;
295

venaas's avatar
venaas committed
296
297
298
299
300
301
    if (!client)
	return;

    conf = client->conf;
    pthread_mutex_lock(conf->lock);
    removelockedclient(client);
302
    pthread_mutex_unlock(conf->lock);
303
304
}

venaas's avatar
venaas committed
305
void freeserver(struct server *server, uint8_t destroymutex) {
306
    struct rqout *rqout, *end;
307

venaas's avatar
venaas committed
308
309
    if (!server)
	return;
310

311
    removeclientrqs_sendrq_freeserver_lock(1);
312
    if (server->requests) {
313
	rqout = server->requests;
314
	for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
315
316
	    if (rqout->rq)
		rqout->rq->to = NULL;
317
	    freerqoutdata(rqout);
318
319
320
	    pthread_mutex_destroy(rqout->lock);
	    free(rqout->lock);
	}
321
322
	free(server->requests);
    }
323
324
    if (server->rbios)
	freebios(server->rbios);
325
    free(server->dynamiclookuparg);
326
327
    if (server->ssl)
	SSL_free(server->ssl);
venaas's avatar
venaas committed
328
329
330
331
332
    if (destroymutex) {
	pthread_mutex_destroy(&server->lock);
	pthread_cond_destroy(&server->newrq_cond);
	pthread_mutex_destroy(&server->newrq_mutex);
    }
333
    removeclientrqs_sendrq_freeserver_lock(0);
venaas's avatar
venaas committed
334
335
336
337
    free(server);
}

int addserver(struct clsrvconf *conf) {
338
    int i;
339

venaas's avatar
venaas committed
340
341
342
343
    if (conf->servers) {
	debug(DBG_ERR, "addserver: currently works with just one server per conf");
	return 0;
    }
344
    conf->servers = malloc(sizeof(struct server));
venaas's avatar
venaas committed
345
346
347
348
    if (!conf->servers) {
	debug(DBG_ERR, "malloc failed");
	return 0;
    }
349
350
351
    memset(conf->servers, 0, sizeof(struct server));
    conf->servers->conf = conf;

352
#ifdef RADPROT_DTLS
353
    if (conf->type == RAD_DTLS)
354
	conf->servers->rbios = newqueue();
355
#endif
venaas's avatar
venaas committed
356
    conf->pdef->setsrcres();
venaas's avatar
venaas committed
357

venaas's avatar
venaas committed
358
359
360
    conf->servers->sock = -1;
    if (conf->pdef->addserverextra)
	conf->pdef->addserverextra(conf);
361

362
    conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
venaas's avatar
venaas committed
363
364
365
366
    if (!conf->servers->requests) {
	debug(DBG_ERR, "malloc failed");
	goto errexit;
    }
367
368
369
370
371
372
373
    for (i = 0; i < MAX_REQUESTS; i++) {
	conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
	if (!conf->servers->requests[i].lock) {
	    debug(DBG_ERR, "malloc failed");
	    goto errexit;
	}
	if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
374
	    debugerrno(errno, DBG_ERR, "mutex init failed");
375
376
377
378
379
	    free(conf->servers->requests[i].lock);
	    conf->servers->requests[i].lock = NULL;
	    goto errexit;
	}
    }
venaas's avatar
venaas committed
380
    if (pthread_mutex_init(&conf->servers->lock, NULL)) {
381
	debugerrno(errno, DBG_ERR, "mutex init failed");
venaas's avatar
venaas committed
382
383
	goto errexit;
    }
384
    conf->servers->newrq = 0;
venaas's avatar
venaas committed
385
    if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
386
	debugerrno(errno, DBG_ERR, "mutex init failed");
venaas's avatar
venaas committed
387
388
389
390
	pthread_mutex_destroy(&conf->servers->lock);
	goto errexit;
    }
    if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
391
	debugerrno(errno, DBG_ERR, "mutex init failed");
venaas's avatar
venaas committed
392
393
394
395
396
397
	pthread_mutex_destroy(&conf->servers->newrq_mutex);
	pthread_mutex_destroy(&conf->servers->lock);
	goto errexit;
    }

    return 1;
398
399

errexit:
venaas's avatar
venaas committed
400
401
402
    freeserver(conf->servers, 0);
    conf->servers = NULL;
    return 0;
403
404
}

405
unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
406
    while (length > 1) {
venaas's avatar
venaas committed
407
	if (ATTRTYPE(attrs) == type)
408
	    return attrs;
venaas's avatar
venaas committed
409
410
	length -= ATTRLEN(attrs);
	attrs += ATTRLEN(attrs);
411
412
413
414
    }
    return NULL;
}

venaas's avatar
venaas committed
415
struct request *newrqref(struct request *rq) {
416
417
    if (rq)
	rq->refcount++;
venaas's avatar
venaas committed
418
419
420
    return rq;
}

421
422
423
424
425
426
void freerq(struct request *rq) {
    if (!rq)
	return;
    debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
    if (--rq->refcount)
	return;
venaas's avatar
venaas committed
427
428
429
430
    if (rq->origusername)
	free(rq->origusername);
    if (rq->buf)
	free(rq->buf);
venaas's avatar
venaas committed
431
432
433
    if (rq->replybuf)
	free(rq->replybuf);
    if (rq->msg)
venaas's avatar
venaas committed
434
	radmsg_free(rq->msg);
435
436
437
438
439
440
    free(rq);
}

void freerqoutdata(struct rqout *rqout) {
    if (!rqout)
	return;
441
    if (rqout->rq) {
442
443
444
445
	if (rqout->rq->buf) {
	    free(rqout->rq->buf);
	    rqout->rq->buf = NULL;
	}
446
	freerq(rqout->rq);
447
448
449
450
	rqout->rq = NULL;
    }
    rqout->tries = 0;
    memset(&rqout->expiry, 0, sizeof(struct timeval));
451
452
}

453
void sendrq(struct request *rq) {
454
    int i, start;
455
456
457
458
459
460
    struct server *to;

    removeclientrqs_sendrq_freeserver_lock(1);
    to = rq->to;
    if (!to)
	goto errexit;
461

462
    start = to->conf->statusserver ? 1 : 0;
venaas's avatar
 
venaas committed
463
    pthread_mutex_lock(&to->newrq_mutex);
464
465
466
467
    if (start && rq->msg->code == RAD_Status_Server) {
	pthread_mutex_lock(to->requests[0].lock);
	if (to->requests[0].rq) {
	    pthread_mutex_unlock(to->requests[0].lock);
468
	    debug(DBG_INFO, "sendrq: status server already in queue, dropping request");
469
	    goto errexit;
470
	}
471
472
473
474
475
476
	i = 0;
    } else {
	if (!to->nextid)
	    to->nextid = start;
	/* might simplify if only try nextid, might be ok */
	for (i = to->nextid; i < MAX_REQUESTS; i++) {
venaas's avatar
venaas committed
477
	    if (!to->requests[i].rq) {
478
		pthread_mutex_lock(to->requests[i].lock);
venaas's avatar
venaas committed
479
		if (!to->requests[i].rq)
480
481
482
483
		    break;
		pthread_mutex_unlock(to->requests[i].lock);
	    }
	}
484
485
486
487
488
489
490
491
492
493
	if (i == MAX_REQUESTS) {
	    for (i = start; i < to->nextid; i++) {
		if (!to->requests[i].rq) {
		    pthread_mutex_lock(to->requests[i].lock);
		    if (!to->requests[i].rq)
			break;
		    pthread_mutex_unlock(to->requests[i].lock);
		}
	    }
	    if (i == to->nextid) {
494
		debug(DBG_INFO, "sendrq: no room in queue, dropping request");
495
496
		goto errexit;
	    }
venaas's avatar
venaas committed
497
	}
venaas's avatar
 
venaas committed
498
    }
499
    rq->newid = (uint8_t)i;
venaas's avatar
venaas committed
500
501
502
    rq->msg->id = (uint8_t)i;
    rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
    if (!rq->buf) {
503
	pthread_mutex_unlock(to->requests[i].lock);
venaas's avatar
venaas committed
504
	debug(DBG_ERR, "sendrq: radmsg2buf failed");
505
	goto errexit;
venaas's avatar
venaas committed
506
    }
507

508
    debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->name);
venaas's avatar
venaas committed
509
    to->requests[i].rq = rq;
510
    pthread_mutex_unlock(to->requests[i].lock);
511
512
    if (i >= start) /* i is not reserved for statusserver */
	to->nextid = i + 1;
venaas's avatar
 
venaas committed
513
514
515

    if (!to->newrq) {
	to->newrq = 1;
venaas's avatar
venaas committed
516
	debug(DBG_DBG, "sendrq: signalling client writer");
venaas's avatar
 
venaas committed
517
518
	pthread_cond_signal(&to->newrq_cond);
    }
venaas's avatar
venaas committed
519

520
    pthread_mutex_unlock(&to->newrq_mutex);
521
    removeclientrqs_sendrq_freeserver_lock(0);
522
523
    return;

524
errexit:
525
526
    if (rq->from)
	rmclientrq(rq, rq->msg->id);
527
    freerq(rq);
venaas's avatar
 
venaas committed
528
    pthread_mutex_unlock(&to->newrq_mutex);
529
    removeclientrqs_sendrq_freeserver_lock(0);
venaas's avatar
 
venaas committed
530
531
}

venaas's avatar
venaas committed
532
void sendreply(struct request *rq) {
533
    uint8_t first;
venaas's avatar
venaas committed
534
    struct client *to = rq->from;
535

venaas's avatar
venaas committed
536
537
538
539
540
541
    if (!rq->replybuf)
	rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
    radmsg_free(rq->msg);
    rq->msg = NULL;
    if (!rq->replybuf) {
	freerq(rq);
venaas's avatar
venaas committed
542
	debug(DBG_ERR, "sendreply: radmsg2buf failed");
venaas's avatar
venaas committed
543
544
	return;
    }
545
546

    pthread_mutex_lock(&to->replyq->mutex);
547
    first = list_first(to->replyq->entries) == NULL;
548

venaas's avatar
venaas committed
549
    if (!list_push(to->replyq->entries, rq)) {
550
	pthread_mutex_unlock(&to->replyq->mutex);
venaas's avatar
venaas committed
551
	freerq(rq);
552
553
554
	debug(DBG_ERR, "sendreply: malloc failed");
	return;
    }
555

556
    if (first) {
557
	debug(DBG_DBG, "signalling server writer");
558
	pthread_cond_signal(&to->replyq->cond);
venaas's avatar
 
venaas committed
559
    }
560
    pthread_mutex_unlock(&to->replyq->mutex);
venaas's avatar
 
venaas committed
561
562
}

563
int pwdcrypt(char encrypt_flag, uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
venaas's avatar
venaas committed
564
565
566
567
568
    static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
    static unsigned char first = 1;
    static EVP_MD_CTX mdctx;
    unsigned char hash[EVP_MAX_MD_SIZE], *input;
    unsigned int md_len;
venaas's avatar
venaas committed
569
    uint8_t i, offset = 0, out[128];
570

venaas's avatar
venaas committed
571
572
573
574
575
576
577
578
579
    pthread_mutex_lock(&lock);
    if (first) {
	EVP_MD_CTX_init(&mdctx);
	first = 0;
    }

    input = auth;
    for (;;) {
	if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
venaas's avatar
venaas committed
580
	    !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
venaas's avatar
venaas committed
581
582
583
584
585
586
587
588
	    !EVP_DigestUpdate(&mdctx, input, 16) ||
	    !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
	    md_len != 16) {
	    pthread_mutex_unlock(&lock);
	    return 0;
	}
	for (i = 0; i < 16; i++)
	    out[offset + i] = hash[i] ^ in[offset + i];
589
590
591
592
	if (encrypt_flag)
	    input = out + offset;
	else
	    input = in + offset;
venaas's avatar
 
venaas committed
593
	offset += 16;
venaas's avatar
venaas committed
594
	if (offset == len)
venaas's avatar
 
venaas committed
595
596
	    break;
    }
venaas's avatar
venaas committed
597
    memcpy(in, out, len);
venaas's avatar
 
venaas committed
598
599
600
601
    pthread_mutex_unlock(&lock);
    return 1;
}

venaas's avatar
venaas committed
602
603
604
605
606
607
608
int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
    static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
    static unsigned char first = 1;
    static EVP_MD_CTX mdctx;
    unsigned char hash[EVP_MAX_MD_SIZE];
    unsigned int md_len;
    uint8_t i, offset;
609

venaas's avatar
venaas committed
610
611
612
613
614
615
    pthread_mutex_lock(&lock);
    if (first) {
	EVP_MD_CTX_init(&mdctx);
	first = 0;
    }

616
617
618
619
#if 0
    printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
    printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
    printfchars(NULL, "msppencrypt in", "%02x ", text, len);
venaas's avatar
venaas committed
620
#endif
621

venaas's avatar
venaas committed
622
623
624
625
626
627
628
629
630
    if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
	!EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
	!EVP_DigestUpdate(&mdctx, auth, 16) ||
	!EVP_DigestUpdate(&mdctx, salt, 2) ||
	!EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
	pthread_mutex_unlock(&lock);
	return 0;
    }

631
#if 0
632
    printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
venaas's avatar
venaas committed
633
#endif
634

venaas's avatar
venaas committed
635
636
    for (i = 0; i < 16; i++)
	text[i] ^= hash[i];
637

venaas's avatar
venaas committed
638
    for (offset = 16; offset < len; offset += 16) {
639
#if 0
venaas's avatar
venaas committed
640
	printf("text + offset - 16 c(%d): ", offset / 16);
641
	printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
venaas's avatar
venaas committed
642
#endif
venaas's avatar
venaas committed
643
644
645
646
647
648
649
650
	if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
	    !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
	    !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
	    !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
	    md_len != 16) {
	    pthread_mutex_unlock(&lock);
	    return 0;
	}
651
652
#if 0
	printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
653
654
#endif

venaas's avatar
venaas committed
655
656
657
	for (i = 0; i < 16; i++)
	    text[offset + i] ^= hash[i];
    }
658

venaas's avatar
venaas committed
659
#if 0
660
    printfchars(NULL, "msppencrypt out", "%02x ", text, len);
venaas's avatar
venaas committed
661
662
663
664
665
666
667
668
669
670
671
672
673
674
#endif

    pthread_mutex_unlock(&lock);
    return 1;
}

int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
    static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
    static unsigned char first = 1;
    static EVP_MD_CTX mdctx;
    unsigned char hash[EVP_MAX_MD_SIZE];
    unsigned int md_len;
    uint8_t i, offset;
    char plain[255];
675

venaas's avatar
venaas committed
676
677
678
679
680
681
    pthread_mutex_lock(&lock);
    if (first) {
	EVP_MD_CTX_init(&mdctx);
	first = 0;
    }

682
683
684
685
#if 0
    printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
    printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
    printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
venaas's avatar
venaas committed
686
#endif
687

venaas's avatar
venaas committed
688
689
690
691
692
693
694
695
696
    if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
	!EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
	!EVP_DigestUpdate(&mdctx, auth, 16) ||
	!EVP_DigestUpdate(&mdctx, salt, 2) ||
	!EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
	pthread_mutex_unlock(&lock);
	return 0;
    }

697
#if 0
698
    printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
venaas's avatar
venaas committed
699
#endif
700

venaas's avatar
venaas committed
701
702
    for (i = 0; i < 16; i++)
	plain[i] = text[i] ^ hash[i];
703

venaas's avatar
venaas committed
704
    for (offset = 16; offset < len; offset += 16) {
705
#if 0
venaas's avatar
venaas committed
706
	printf("text + offset - 16 c(%d): ", offset / 16);
707
	printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
venaas's avatar
venaas committed
708
709
710
711
712
713
714
715
716
#endif
	if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
	    !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
	    !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
	    !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
	    md_len != 16) {
	    pthread_mutex_unlock(&lock);
	    return 0;
	}
717
718
#if 0
	printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
719
#endif
venaas's avatar
venaas committed
720

721
722
	for (i = 0; i < 16; i++)
	    plain[offset + i] = text[offset + i] ^ hash[i];
venaas's avatar
venaas committed
723
724
725
726
    }

    memcpy(text, plain, len);
#if 0
727
    printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
venaas's avatar
venaas committed
728
729
730
731
732
733
#endif

    pthread_mutex_unlock(&lock);
    return 1;
}

734
735
736
737
738
739
740
struct realm *newrealmref(struct realm *r) {
    if (r)
	r->refcount++;
    return r;
}

/* returns with lock on realm */
venaas's avatar
venaas committed
741
struct realm *id2realm(struct list *realmlist, char *id) {
venaas's avatar
venaas committed
742
    struct list_node *entry;
743
    struct realm *realm, *subrealm;
venaas's avatar
venaas committed
744
745
746

    /* need to do locking for subrealms and check subrealm timers */
    for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
venaas's avatar
venaas committed
747
748
	realm = (struct realm *)entry->data;
	if (!regexec(&realm->regex, id, 0, NULL, 0)) {
749
750
	    pthread_mutex_lock(&realm->mutex);
	    if (realm->subrealms) {
venaas's avatar
venaas committed
751
		subrealm = id2realm(realm->subrealms, id);
752
753
754
755
756
757
		if (subrealm) {
		    pthread_mutex_unlock(&realm->mutex);
		    return subrealm;
		}
	    }
	    return newrealmref(realm);
venaas's avatar
venaas committed
758
	}
venaas's avatar
venaas committed
759
    }
venaas's avatar
venaas committed
760
    return NULL;
venaas's avatar
venaas committed
761
762
}

763
764
765
766
767
768
769
770
771
int hasdynamicserver(struct list *srvconfs) {
    struct list_node *entry;

    for (entry = list_first(srvconfs); entry; entry = list_next(entry))
	if (((struct clsrvconf *)entry->data)->dynamiclookupcommand)
	    return 1;
    return 0;
}

772
773
/* helper function, only used by removeserversubrealms() */
void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
774
    struct list_node *entry, *entry2;
775
    struct realm *realm;
776

777
    for (entry = list_first(realmlist); entry;) {
778
779
	realm = newrealmref((struct realm *)entry->data);
	pthread_mutex_lock(&realm->mutex);
780
	entry = list_next(entry);
781

782
	if (realm->srvconfs) {
783
784
785
	    for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
		if (entry2->data == srv)
		    freerealm(realm);
786
787
788
	    list_removedata(realm->srvconfs, srv);
	}
	if (realm->accsrvconfs) {
789
790
791
	    for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
		if (entry2->data == srv)
		    freerealm(realm);
792
793
794
	    list_removedata(realm->accsrvconfs, srv);
	}

795
796
797
798
799
800
801
802
803
804
	/* remove subrealm if no dynamic servers left */
	if (!hasdynamicserver(realm->srvconfs) && !hasdynamicserver(realm->accsrvconfs)) {
	    while (list_shift(realm->srvconfs))
		freerealm(realm);
	    list_destroy(realm->srvconfs);
	    realm->srvconfs = NULL;
	    while (list_shift(realm->accsrvconfs))
		freerealm(realm);
	    list_destroy(realm->accsrvconfs);
	    realm->accsrvconfs = NULL;
805
	    list_removedata(realmlist, realm);
806
	}
807
808
	pthread_mutex_unlock(&realm->mutex);
	freerealm(realm);
809
810
811
812
813
814
    }
}

void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
    struct list_node *entry;
    struct realm *realm;
815

816
817
    for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
	realm = (struct realm *)entry->data;
818
	pthread_mutex_lock(&realm->mutex);
819
820
821
822
823
824
825
	if (realm->subrealms) {
	    _internal_removeserversubrealms(realm->subrealms, srv);
	    if (!list_first(realm->subrealms)) {
		list_destroy(realm->subrealms);
		realm->subrealms = NULL;
	    }
	}
826
	pthread_mutex_unlock(&realm->mutex);
827
828
    }
}
829

830
831
int attrvalidate(unsigned char *attrs, int length) {
    while (length > 1) {
venaas's avatar
venaas committed
832
	if (ATTRLEN(attrs) < 2) {
833
	    debug(DBG_INFO, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
834
835
	    return 0;
	}
venaas's avatar
venaas committed
836
	length -= ATTRLEN(attrs);
837
	if (length < 0) {
838
	    debug(DBG_INFO, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
839
840
	    return 0;
	}
venaas's avatar
venaas committed
841
	attrs += ATTRLEN(attrs);
842
843
    }
    if (length)
844
	debug(DBG_INFO, "attrvalidate: malformed packet? remaining byte after last attribute");
845
846
847
    return 1;
}

venaas's avatar
venaas committed
848
849
850
851
852
int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
    if (len < 16 || len > 128 || len % 16) {
	debug(DBG_WARN, "pwdrecrypt: invalid password length");
	return 0;
    }
853

854
    if (!pwdcrypt(0, pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
venaas's avatar
venaas committed
855
856
857
858
	debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
	return 0;
    }
#ifdef DEBUG
859
    printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
860
#endif
861
    if (!pwdcrypt(1, pwd, len, newsecret, strlen(newsecret), newauth)) {
venaas's avatar
venaas committed
862
863
864
865
866
867
	debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
	return 0;
    }
    return 1;
}

868
int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
venaas's avatar
venaas committed
869
870
    if (len < 18)
	return 0;
871
    if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
venaas's avatar
venaas committed
872
873
874
	debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
	return 0;
    }
875
    if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
venaas's avatar
venaas committed
876
877
878
879
880
881
	debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
	return 0;
    }
    return 1;
}

venaas's avatar
venaas committed
882
int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
venaas's avatar
venaas committed
883
884
	   char *oldsecret, char *newsecret) {
    unsigned char *attr;
885

venaas's avatar
venaas committed
886
887
    for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
	debug(DBG_DBG, "msmppe: Got %s", attrtxt);
888
	if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
venaas's avatar
venaas committed
889
890
891
892
893
	    return 0;
    }
    return 1;
}

894
int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
venaas's avatar
venaas committed
895
896
    if (!attrs)
	return 0;
897

venaas's avatar
venaas committed
898
899
900
901
902
903
    for (; attrs[0]; attrs += 2)
	if (attrs[0] == vendor && attrs[1] == subattr)
	    return 1;
    return 0;
}

904
905
906
907
/* returns 1 if entire element is to be removed, else 0 */
int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
    uint8_t alen, sublen;
    uint32_t vendor;
venaas's avatar
venaas committed
908
    uint8_t *subattrs;
909

venaas's avatar
venaas committed
910
911
912
    if (!removevendorattrs)
	return 0;

913
914
    memcpy(&vendor, attr->v, 4);
    vendor = ntohl(vendor);
venaas's avatar
venaas committed
915
916
917
918
    while (*removevendorattrs && *removevendorattrs != vendor)
	removevendorattrs += 2;
    if (!*removevendorattrs)
	return 0;
919

920
    if (findvendorsubattr(removevendorattrs, vendor, 256))
921
	return 1; /* remove entire vendor attribute */
venaas's avatar
venaas committed
922

923
924
    sublen = attr->l - 4;
    subattrs = attr->v + 4;
925

venaas's avatar
venaas committed
926
    if (!attrvalidate(subattrs, sublen)) {
927
	debug(DBG_INFO, "dovendorrewrite: vendor attribute validation failed, no rewrite");
venaas's avatar
venaas committed
928
929
930
931
932
933
934
	return 0;
    }

    while (sublen > 1) {
	alen = ATTRLEN(subattrs);
	sublen -= alen;
	if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
935
936
	    memmove(subattrs, subattrs + alen, sublen);
	    attr->l -= alen;
venaas's avatar
venaas committed
937
938
939
	} else
	    subattrs += alen;
    }
940
    return 0;
venaas's avatar
venaas committed
941
942
}

943
944
945
946
947
948
949
void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
    struct list_node *n, *p