radsecproxy.c 95.2 KB
Newer Older
1
/*
2
 * Copyright (C) 2006-2009 Stig Venaas <venaas@uninett.no>
Linus Nordberg's avatar
Linus Nordberg committed
3
 * Copyright (C) 2010,2011,2012 NORDUnet A/S
4 5 6 7 8 9
 *
 * 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.
 */

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

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
/* 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
37
 * Example: With 3 UDP peers and 30 TLS peers, there will be a max of
38
 *          1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
39
 */
40

venaas's avatar
venaas committed
41
/* Bugs:
venaas's avatar
venaas committed
42
 * May segfault when dtls connections go down? More testing needed
43
 * Remove expired stuff from clients request list?
venaas's avatar
venaas committed
44 45
 * 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
46 47
 */

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

85
static struct options options;
venaas's avatar
venaas committed
86
static struct list *clconfs, *srvconfs;
87 88
static struct list *realms;
static struct hash *rewriteconfs;
89

venaas's avatar
venaas committed
90
static pthread_mutex_t *ssl_locks = NULL;
91 92 93
static long *ssl_lock_count;
extern int optind;
extern char *optarg;
venaas's avatar
venaas committed
94
static const struct protodefs *protodefs[RAD_PROTOCOUNT];
95

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

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

108
uint8_t protoname2int(const char *name) {
venaas's avatar
venaas committed
109
    uint8_t i;
110

venaas's avatar
venaas committed
111 112 113 114
    for (i = 0; i < RAD_PROTOCOUNT; i++)
	if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
	    return i;
    return 255;
115
}
116

117 118
/* callbacks for making OpenSSL thread safe */
unsigned long ssl_thread_id() {
119
    return (unsigned long)pthread_self();
120
}
121 122 123 124 125 126 127 128 129

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]);
}

130 131 132
/* 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
133
    uint8_t r, l = len / 8;
134 135 136 137 138 139 140 141
    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]);
}

142
/* returns next config with matching address, or NULL */
143
struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur, uint8_t server_p) {
144 145
    struct list_node *entry;
    struct clsrvconf *conf;
146

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

venaas's avatar
venaas committed
158
struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
159
    return find_conf(type, addr, clconfs, cur, 0);
venaas's avatar
venaas committed
160 161 162
}

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

166
/* returns next config of given type, or NULL */
venaas's avatar
venaas committed
167
struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
168 169
    struct list_node *entry;
    struct clsrvconf *conf;
170

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

182 183
struct gqueue *newqueue() {
    struct gqueue *q;
184

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

196
void removequeue(struct gqueue *q) {
197
    struct list_node *entry;
198 199 200

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

211
void freebios(struct gqueue *q) {
212
    BIO *bio;
213

214 215 216 217 218
    pthread_mutex_lock(&q->mutex);
    while ((bio = (BIO *)list_shift(q->entries)))
	BIO_free(bio);
    pthread_mutex_unlock(&q->mutex);
    removequeue(q);
219 220
}

221
struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
222
    struct client *new = malloc(sizeof(struct client));
223

224 225 226
    if (!new) {
	debug(DBG_ERR, "malloc failed");
	return NULL;
227
    }
228 229 230

    if (lock)
	pthread_mutex_lock(conf->lock);
231
    if (!conf->clients) {
232 233
	conf->clients = list_create();
	if (!conf->clients) {
234 235
	    if (lock)
		pthread_mutex_unlock(conf->lock);
236 237 238
	    debug(DBG_ERR, "malloc failed");
	    return NULL;
	}
239
    }
240

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

253 254 255 256 257 258 259 260
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);
}
261

262 263 264 265 266
void removeclientrqs(struct client *client) {
    struct request *rq;
    struct rqout *rqout;
    int i;

267
    removeclientrqs_sendrq_freeserver_lock(1);
268 269 270 271
    for (i = 0; i < MAX_REQUESTS; i++) {
	rq = client->rqs[i];
	if (!rq)
	    continue;
272 273 274 275 276 277 278
	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);
	}
279 280
	freerq(rq);
    }
281
    removeclientrqs_sendrq_freeserver_lock(0);
282 283
}

venaas's avatar
venaas committed
284
void removelockedclient(struct client *client) {
285
    struct clsrvconf *conf;
286

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

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

venaas's avatar
venaas committed
300 301 302 303 304 305
    if (!client)
	return;

    conf = client->conf;
    pthread_mutex_lock(conf->lock);
    removelockedclient(client);
306
    pthread_mutex_unlock(conf->lock);
307 308
}

309
void freeserver(struct server *server, uint8_t destroymutex) {
310
    struct rqout *rqout, *end;
311

312 313
    if (!server)
	return;
314

315
    removeclientrqs_sendrq_freeserver_lock(1);
316
    if (server->requests) {
317
	rqout = server->requests;
318
	for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
319 320
	    if (rqout->rq)
		rqout->rq->to = NULL;
321
	    freerqoutdata(rqout);
322 323 324
	    pthread_mutex_destroy(rqout->lock);
	    free(rqout->lock);
	}
325 326
	free(server->requests);
    }
327 328
    if (server->rbios)
	freebios(server->rbios);
329
    free(server->dynamiclookuparg);
330 331 332 333 334 335 336
    if (server->ssl) {
#if defined ENABLE_EXPERIMENTAL_DYNDISC
        if (server->sock >= 0)
            close(server->sock);
#endif
        SSL_free(server->ssl);
    }
337 338 339 340 341
    if (destroymutex) {
	pthread_mutex_destroy(&server->lock);
	pthread_cond_destroy(&server->newrq_cond);
	pthread_mutex_destroy(&server->newrq_mutex);
    }
342
    removeclientrqs_sendrq_freeserver_lock(0);
343 344 345 346
    free(server);
}

int addserver(struct clsrvconf *conf) {
347
    int i;
348

349 350 351 352
    if (conf->servers) {
	debug(DBG_ERR, "addserver: currently works with just one server per conf");
	return 0;
    }
353
    conf->servers = malloc(sizeof(struct server));
354 355 356 357
    if (!conf->servers) {
	debug(DBG_ERR, "malloc failed");
	return 0;
    }
358 359 360
    memset(conf->servers, 0, sizeof(struct server));
    conf->servers->conf = conf;

361
#ifdef RADPROT_DTLS
362
    if (conf->type == RAD_DTLS)
363
	conf->servers->rbios = newqueue();
364
#endif
venaas's avatar
venaas committed
365
    conf->pdef->setsrcres();
venaas's avatar
venaas committed
366

venaas's avatar
venaas committed
367 368 369
    conf->servers->sock = -1;
    if (conf->pdef->addserverextra)
	conf->pdef->addserverextra(conf);
370

371
    conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
372 373 374 375
    if (!conf->servers->requests) {
	debug(DBG_ERR, "malloc failed");
	goto errexit;
    }
376 377 378 379 380 381 382
    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)) {
383
	    debugerrno(errno, DBG_ERR, "mutex init failed");
384 385 386 387 388
	    free(conf->servers->requests[i].lock);
	    conf->servers->requests[i].lock = NULL;
	    goto errexit;
	}
    }
389
    if (pthread_mutex_init(&conf->servers->lock, NULL)) {
390
	debugerrno(errno, DBG_ERR, "mutex init failed");
391 392
	goto errexit;
    }
393
    conf->servers->newrq = 0;
394
    if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
395
	debugerrno(errno, DBG_ERR, "mutex init failed");
396 397 398 399
	pthread_mutex_destroy(&conf->servers->lock);
	goto errexit;
    }
    if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
400
	debugerrno(errno, DBG_ERR, "mutex init failed");
401 402 403 404 405 406
	pthread_mutex_destroy(&conf->servers->newrq_mutex);
	pthread_mutex_destroy(&conf->servers->lock);
	goto errexit;
    }

    return 1;
407 408

errexit:
409 410 411
    freeserver(conf->servers, 0);
    conf->servers = NULL;
    return 0;
412 413
}

414
unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
415
    while (length > 1) {
416
	if (ATTRTYPE(attrs) == type)
417
	    return attrs;
418 419
	length -= ATTRLEN(attrs);
	attrs += ATTRLEN(attrs);
420 421 422 423
    }
    return NULL;
}

venaas's avatar
venaas committed
424
struct request *newrqref(struct request *rq) {
425 426
    if (rq)
	rq->refcount++;
venaas's avatar
venaas committed
427 428 429
    return rq;
}

430 431 432 433 434 435
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
436 437 438 439
    if (rq->origusername)
	free(rq->origusername);
    if (rq->buf)
	free(rq->buf);
venaas's avatar
venaas committed
440 441 442
    if (rq->replybuf)
	free(rq->replybuf);
    if (rq->msg)
venaas's avatar
venaas committed
443
	radmsg_free(rq->msg);
444 445 446 447 448 449
    free(rq);
}

void freerqoutdata(struct rqout *rqout) {
    if (!rqout)
	return;
450
    if (rqout->rq) {
451 452 453 454
	if (rqout->rq->buf) {
	    free(rqout->rq->buf);
	    rqout->rq->buf = NULL;
	}
455
	freerq(rqout->rq);
456 457 458 459
	rqout->rq = NULL;
    }
    rqout->tries = 0;
    memset(&rqout->expiry, 0, sizeof(struct timeval));
460 461
}

462
void sendrq(struct request *rq) {
463
    int i, start;
464 465 466 467 468 469
    struct server *to;

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

471
    start = to->conf->statusserver ? 1 : 0;
472
    pthread_mutex_lock(&to->newrq_mutex);
473 474 475 476
    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);
477
	    debug(DBG_INFO, "sendrq: status server already in queue, dropping request");
478
	    goto errexit;
479
	}
480 481 482 483 484 485
	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
486
	    if (!to->requests[i].rq) {
487
		pthread_mutex_lock(to->requests[i].lock);
venaas's avatar
venaas committed
488
		if (!to->requests[i].rq)
489 490 491 492
		    break;
		pthread_mutex_unlock(to->requests[i].lock);
	    }
	}
493 494 495 496 497 498 499 500 501 502
	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) {
503
		debug(DBG_INFO, "sendrq: no room in queue, dropping request");
504 505
		goto errexit;
	    }
venaas's avatar
venaas committed
506
	}
507
    }
508
    rq->newid = (uint8_t)i;
venaas's avatar
venaas committed
509 510 511
    rq->msg->id = (uint8_t)i;
    rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
    if (!rq->buf) {
512
	pthread_mutex_unlock(to->requests[i].lock);
venaas's avatar
venaas committed
513
	debug(DBG_ERR, "sendrq: radmsg2buf failed");
514
	goto errexit;
venaas's avatar
venaas committed
515
    }
516

517
    debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->name);
venaas's avatar
venaas committed
518
    to->requests[i].rq = rq;
519
    pthread_mutex_unlock(to->requests[i].lock);
520 521
    if (i >= start) /* i is not reserved for statusserver */
	to->nextid = i + 1;
522 523 524

    if (!to->newrq) {
	to->newrq = 1;
venaas's avatar
venaas committed
525
	debug(DBG_DBG, "sendrq: signalling client writer");
526 527
	pthread_cond_signal(&to->newrq_cond);
    }
venaas's avatar
venaas committed
528

529
    pthread_mutex_unlock(&to->newrq_mutex);
530
    removeclientrqs_sendrq_freeserver_lock(0);
531 532
    return;

533
errexit:
534 535
    if (rq->from)
	rmclientrq(rq, rq->msg->id);
536
    freerq(rq);
537
    pthread_mutex_unlock(&to->newrq_mutex);
538
    removeclientrqs_sendrq_freeserver_lock(0);
539 540
}

venaas's avatar
venaas committed
541
void sendreply(struct request *rq) {
542
    uint8_t first;
venaas's avatar
venaas committed
543
    struct client *to = rq->from;
544

venaas's avatar
venaas committed
545 546 547 548 549 550
    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
551
	debug(DBG_ERR, "sendreply: radmsg2buf failed");
venaas's avatar
venaas committed
552 553
	return;
    }
554 555

    pthread_mutex_lock(&to->replyq->mutex);
556
    first = list_first(to->replyq->entries) == NULL;
557

venaas's avatar
venaas committed
558
    if (!list_push(to->replyq->entries, rq)) {
559
	pthread_mutex_unlock(&to->replyq->mutex);
venaas's avatar
venaas committed
560
	freerq(rq);
561 562 563
	debug(DBG_ERR, "sendreply: malloc failed");
	return;
    }
564

565
    if (first) {
566
	debug(DBG_DBG, "signalling server writer");
567
	pthread_cond_signal(&to->replyq->cond);
568
    }
569
    pthread_mutex_unlock(&to->replyq->mutex);
570 571
}

572
int pwdcrypt(char encrypt_flag, uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
venaas's avatar
venaas committed
573 574 575 576 577
    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
578
    uint8_t i, offset = 0, out[128];
579

venaas's avatar
venaas committed
580 581 582 583 584 585 586 587 588
    pthread_mutex_lock(&lock);
    if (first) {
	EVP_MD_CTX_init(&mdctx);
	first = 0;
    }

    input = auth;
    for (;;) {
	if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
589
	    !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
venaas's avatar
venaas committed
590 591 592 593 594 595 596 597
	    !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];
598 599 600 601
	if (encrypt_flag)
	    input = out + offset;
	else
	    input = in + offset;
602
	offset += 16;
venaas's avatar
venaas committed
603
	if (offset == len)
604 605
	    break;
    }
venaas's avatar
venaas committed
606
    memcpy(in, out, len);
607 608 609 610
    pthread_mutex_unlock(&lock);
    return 1;
}

venaas's avatar
venaas committed
611 612 613 614 615 616 617
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;
618

venaas's avatar
venaas committed
619 620 621 622 623 624
    pthread_mutex_lock(&lock);
    if (first) {
	EVP_MD_CTX_init(&mdctx);
	first = 0;
    }

625 626 627 628
#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
629
#endif
630

venaas's avatar
venaas committed
631 632 633 634 635 636 637 638 639
    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;
    }

640
#if 0
641
    printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
venaas's avatar
venaas committed
642
#endif
643

venaas's avatar
venaas committed
644 645
    for (i = 0; i < 16; i++)
	text[i] ^= hash[i];
646

venaas's avatar
venaas committed
647
    for (offset = 16; offset < len; offset += 16) {
648
#if 0
venaas's avatar
venaas committed
649
	printf("text + offset - 16 c(%d): ", offset / 16);
650
	printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
venaas's avatar
venaas committed
651
#endif
venaas's avatar
venaas committed
652 653 654 655 656 657 658 659
	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;
	}
660 661
#if 0
	printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
662 663
#endif

venaas's avatar
venaas committed
664 665 666
	for (i = 0; i < 16; i++)
	    text[offset + i] ^= hash[i];
    }
667

venaas's avatar
venaas committed
668
#if 0
669
    printfchars(NULL, "msppencrypt out", "%02x ", text, len);
venaas's avatar
venaas committed
670 671 672 673 674 675 676 677 678 679 680 681 682 683
#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];
684

venaas's avatar
venaas committed
685 686 687 688 689 690
    pthread_mutex_lock(&lock);
    if (first) {
	EVP_MD_CTX_init(&mdctx);
	first = 0;
    }

691 692 693 694
#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
695
#endif
696

venaas's avatar
venaas committed
697 698 699 700 701 702 703 704 705
    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;
    }

706
#if 0
707
    printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
venaas's avatar
venaas committed
708
#endif
709

venaas's avatar
venaas committed
710 711
    for (i = 0; i < 16; i++)
	plain[i] = text[i] ^ hash[i];
712

venaas's avatar
venaas committed
713
    for (offset = 16; offset < len; offset += 16) {
714
#if 0
venaas's avatar
venaas committed
715
	printf("text + offset - 16 c(%d): ", offset / 16);
716
	printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
venaas's avatar
venaas committed
717 718 719 720 721 722 723 724 725
#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;
	}
726 727
#if 0
	printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
728
#endif
venaas's avatar
venaas committed
729

730 731
	for (i = 0; i < 16; i++)
	    plain[offset + i] = text[offset + i] ^ hash[i];
venaas's avatar
venaas committed
732 733 734 735
    }

    memcpy(text, plain, len);
#if 0
736
    printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
venaas's avatar
venaas committed
737 738 739 740 741 742
#endif

    pthread_mutex_unlock(&lock);
    return 1;
}

743 744 745 746 747 748 749
struct realm *newrealmref(struct realm *r) {
    if (r)
	r->refcount++;
    return r;
}

/* returns with lock on realm */
750
struct realm *id2realm(struct list *realmlist, char *id) {
751
    struct list_node *entry;
752
    struct realm *realm, *subrealm;
753 754 755

    /* need to do locking for subrealms and check subrealm timers */
    for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
756 757
	realm = (struct realm *)entry->data;
	if (!regexec(&realm->regex, id, 0, NULL, 0)) {
758 759
	    pthread_mutex_lock(&realm->mutex);
	    if (realm->subrealms) {
760
		subrealm = id2realm(realm->subrealms, id);
761 762 763 764 765 766
		if (subrealm) {
		    pthread_mutex_unlock(&realm->mutex);
		    return subrealm;
		}
	    }
	    return newrealmref(realm);
venaas's avatar
venaas committed
767
	}
768
    }
venaas's avatar
venaas committed
769
    return NULL;
venaas's avatar
venaas committed
770 771
}

772 773 774 775
int hasdynamicserver(struct list *srvconfs) {
    struct list_node *entry;

    for (entry = list_first(srvconfs); entry; entry = list_next(entry))
776 777 778 779 780 781
#if defined ENABLE_EXPERIMENTAL_DYNDISC
        if (((struct clsrvconf *)entry->data)->dynamiclookupcommand
            || ((struct clsrvconf *)entry->data)->servers->in_use)
#else
        if (((struct clsrvconf *)entry->data)->dynamiclookupcommand)
#endif
782 783 784 785
	    return 1;
    return 0;
}

786 787
/* helper function, only used by removeserversubrealms() */
void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
788
    struct list_node *entry, *entry2;
789
    struct realm *realm;
790

791
    for (entry = list_first(realmlist); entry;) {
792 793
	realm = newrealmref((struct realm *)entry->data);
	pthread_mutex_lock(&realm->mutex);
794
	entry = list_next(entry);
795

796
	if (realm->srvconfs) {
797 798 799
	    for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
		if (entry2->data == srv)
		    freerealm(realm);
800 801 802
	    list_removedata(realm->srvconfs, srv);
	}
	if (realm->accsrvconfs) {
803 804 805
	    for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
		if (entry2->data == srv)
		    freerealm(realm);
806 807 808
	    list_removedata(realm->accsrvconfs, srv);
	}

809 810 811 812 813 814 815 816 817 818
	/* 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;
819
	    list_removedata(realmlist, realm);
820
	}
821 822
	pthread_mutex_unlock(&realm->mutex);
	freerealm(realm);
823 824 825 826 827 828
    }
}

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

830 831
    for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
	realm = (struct realm *)entry->data;
832
	pthread_mutex_lock(&realm->mutex);
833 834 835 836 837 838 839
	if (realm->subrealms) {
	    _internal_removeserversubrealms(realm->subrealms, srv);
	    if (!list_first(realm->subrealms)) {
		list_destroy(realm->subrealms);
		realm->subrealms = NULL;
	    }
	}
840
	pthread_mutex_unlock(&realm->mutex);
841 842
    }
}
843

844 845
int attrvalidate(unsigned char *attrs, int length) {
    while (length > 1) {
846
	if (ATTRLEN(attrs) < 2) {
847
	    debug(DBG_INFO, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
848 849
	    return 0;
	}
850
	length -= ATTRLEN(attrs);
851
	if (length < 0) {
852
	    debug(DBG_INFO, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
853 854
	    return 0;
	}
855
	attrs += ATTRLEN(attrs);
856 857
    }
    if (length)
858
	debug(DBG_INFO, "attrvalidate: malformed packet? remaining byte after last attribute");
859 860 861
    return 1;
}

venaas's avatar
venaas committed
862 863 864 865 866
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;
    }
867

868
    if (!pwdcrypt(0, pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
venaas's avatar
venaas committed
869 870 871 872
	debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
	return 0;
    }
#ifdef DEBUG
873
    printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
874
#endif
875
    if (!pwdcrypt(1, pwd, len, newsecret, strlen(newsecret), newauth)) {
venaas's avatar
venaas committed
876 877 878 879 880 881
	debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
	return 0;
    }
    return 1;
}

882
int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
venaas's avatar
venaas committed
883 884
    if (len < 18)
	return 0;
885
    if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
venaas's avatar
venaas committed
886 887 888
	debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
	return 0;
    }
889
    if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
venaas's avatar
venaas committed
890 891 892 893 894 895
	debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
	return 0;
    }
    return 1;
}

venaas's avatar
venaas committed
896
int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
venaas's avatar
venaas committed
897 898
	   char *oldsecret, char *newsecret) {
    unsigned char *attr;
899

venaas's avatar
venaas committed
900 901
    for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
	debug(DBG_DBG, "msmppe: Got %s", attrtxt);
902
	if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
venaas's avatar
venaas committed
903 904 905 906 907
	    return 0;
    }
    return 1;
}

908
int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
venaas's avatar
venaas committed
909 910
    if (!attrs)
	return 0;
911

venaas's avatar
venaas committed
912 913 914 915 916 917
    for (; attrs[0]; attrs += 2)
	if (attrs[0] == vendor && attrs[1] == subattr)
	    return 1;
    return 0;
}

918 919 920 921
/* 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
922
    uint8_t *subattrs;
923

venaas's avatar
venaas committed
924 925 926
    if (!removevendorattrs)
	return 0;

927 928
    memcpy(&vendor, attr->v, 4);
    vendor = ntohl(vendor);
venaas's avatar
venaas committed
929 930 931 932
    while (*removevendorattrs && *removevendorattrs != vendor)
	removevendorattrs += 2;
    if (!*removevendorattrs)
	return 0;
933

934
    if (findvendorsubattr(removevendorattrs, vendor, 256))
935
	return 1; /* remove entire vendor attribute */
venaas's avatar
venaas committed
936

937 938
    sublen = attr->l - 4;
    subattrs = attr->v + 4;
939

venaas's avatar
venaas committed
940
    if (!attrvalidate(subattrs, sublen)) {
941
	debug(DBG_INFO, "dovendorrewrite: vendor attribute validation failed, no rewrite");
venaas's avatar
venaas committed
942 943 944 945 946 947 948
	return 0;
    }

    while (sublen > 1) {
	alen = ATTRLEN(subattrs);
	sublen -= alen;
	if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
949 950
	    memmove(subattrs, subattrs + alen, sublen);
	    attr->l -= alen;
venaas's avatar
venaas committed
951 952 953
	} else
	    subattrs += alen;
    }
954
    return 0;
venaas's avatar
venaas committed
955 956
}

957 958 959 960 961 962 963
void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
    struct list_node *n, *p;
    struct tlv *attr;

    p = NULL;
    n = list_first(msg->attrs);
    while (n) {
964 965 966 967 968 969 970 971 972 973
	attr = (struct tlv *)n->data;
	if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
	    (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
	    list_removedata(msg->attrs, attr);
	    freetlv(attr);
	    n = p ? list_next(p) : list_first(msg->attrs);
	} else {
	    p = n;
	    n = list_next(n);
	}
974 975 976
    }
}

977
int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
978
    struct list_node *n;
979
    struct tlv *a;
980

981
    for (n = list_first(addattrs); n; n = list_next(n)) {
982 983 984 985 986 987 988 989
	a = copytlv((struct tlv *)n->data);
	if (!a)
	    return 0;
	if (!radmsg_add(msg, a)) {
	    freetlv(a);
	    return 0;
	}
    }
990 991 992
    return 1;
}

venaas's avatar
venaas committed
993
int resizeattr(struct tlv *attr, uint8_t newlen) {
994
    uint8_t *newv;
995

996 997 998 999 1000 1001
    if (newlen != attr->l) {
	newv = realloc(attr->v, newlen);
	if (!newv)
	    return 0;
	attr->v = newv;
	attr->l = newlen;
1002
    }
1003
    return 1;
1004
}
1005

1006
int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {