radsecproxy.c 97 KB
Newer Older
venaas's avatar
 
venaas committed
1
/*
2
 * Copyright (C) 2006-2009 Stig Venaas <venaas@uninett.no>
Linus Nordberg's avatar
Linus Nordberg committed
3
 * Copyright (C) 2010-2013,2015 NORDUnet A/S
venaas's avatar
 
venaas committed
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
Credits  
kolla committed
15
 * Stefan Winter <stefan.winter@restena.lu>
16 17
 */

venaas's avatar
 
venaas committed
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
venaas's avatar
 
venaas committed
38
 *          1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
39
 */
venaas's avatar
 
venaas committed
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>
venaas's avatar
 
venaas committed
51
#include <netdb.h>
venaas's avatar
venaas committed
52
#include <string.h>
venaas's avatar
 
venaas committed
53
#include <unistd.h>
venaas's avatar
venaas committed
54
#include <limits.h>
55 56 57
#if defined(HAVE_MALLOPT)
#include <malloc.h>
#endif
venaas's avatar
venaas committed
58 59 60
#ifdef SYS_SOLARIS9
#include <fcntl.h>
#endif
venaas's avatar
venaas committed
61
#include <sys/time.h>
62
#include <sys/types.h>
63
#include <ctype.h>
64
#include <sys/wait.h>
65
#include <arpa/inet.h>
venaas's avatar
venaas committed
66
#include <regex.h>
venaas's avatar
venaas committed
67
#include <libgen.h>
venaas's avatar
 
venaas committed
68
#include <pthread.h>
69
#include <errno.h>
70
#include <assert.h>
venaas's avatar
 
venaas committed
71 72 73 74
#include <openssl/ssl.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include <openssl/md5.h>
venaas's avatar
venaas committed
75
#include "debug.h"
76
#include "hash.h"
77
#include "util.h"
78
#include "hostport.h"
venaas's avatar
venaas committed
79
#include "radsecproxy.h"
venaas's avatar
venaas committed
80
#include "udp.h"
venaas's avatar
venaas committed
81 82
#include "tcp.h"
#include "tls.h"
venaas's avatar
venaas committed
83
#include "dtls.h"
84
#if defined(WANT_FTICKS)
Linus Nordberg's avatar
Linus Nordberg committed
85
#include "fticks.h"
86
#endif
venaas's avatar
 
venaas committed
87

88
static struct options options;
venaas's avatar
venaas committed
89
static struct list *clconfs, *srvconfs;
90 91
static struct list *realms;
static struct hash *rewriteconfs;
92

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

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

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

venaas's avatar
venaas committed
111
uint8_t protoname2int(const char *name) {
venaas's avatar
venaas committed
112
    uint8_t i;
venaas's avatar
venaas committed
113

venaas's avatar
venaas committed
114 115 116 117
    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
118
}
119

venaas's avatar
 
venaas committed
120 121
/* callbacks for making OpenSSL thread safe */
unsigned long ssl_thread_id() {
122
    return (unsigned long)pthread_self();
venaas's avatar
venaas committed
123
}
venaas's avatar
 
venaas committed
124 125 126 127 128 129 130 131 132

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

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

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

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

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

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

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

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

185 186
struct gqueue *newqueue() {
    struct gqueue *q;
187

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

199
void removequeue(struct gqueue *q) {
200
    struct list_node *entry;
201 202 203

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

214
void freebios(struct gqueue *q) {
215
    BIO *bio;
216

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

224
struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
225
    struct client *new = malloc(sizeof(struct client));
226

227 228 229
    if (!new) {
	debug(DBG_ERR, "malloc failed");
	return NULL;
230
    }
231 232 233

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

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

256 257 258 259 260 261 262 263
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);
}
264

265 266 267 268 269
void removeclientrqs(struct client *client) {
    struct request *rq;
    struct rqout *rqout;
    int i;

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

venaas's avatar
venaas committed
287
void removelockedclient(struct client *client) {
288
    struct clsrvconf *conf;
289

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

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

venaas's avatar
venaas committed
303 304 305 306 307 308
    if (!client)
	return;

    conf = client->conf;
    pthread_mutex_lock(conf->lock);
    removelockedclient(client);
309
    pthread_mutex_unlock(conf->lock);
310 311
}

venaas's avatar
venaas committed
312
void freeserver(struct server *server, uint8_t destroymutex) {
313
    struct rqout *rqout, *end;
314

venaas's avatar
venaas committed
315 316
    if (!server)
	return;
317

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

int addserver(struct clsrvconf *conf) {
350
    int i;
351

venaas's avatar
venaas committed
352 353 354 355
    if (conf->servers) {
	debug(DBG_ERR, "addserver: currently works with just one server per conf");
	return 0;
    }
356
    conf->servers = malloc(sizeof(struct server));
venaas's avatar
venaas committed
357 358 359 360
    if (!conf->servers) {
	debug(DBG_ERR, "malloc failed");
	return 0;
    }
361 362 363
    memset(conf->servers, 0, sizeof(struct server));
    conf->servers->conf = conf;

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

venaas's avatar
venaas committed
370 371 372
    conf->servers->sock = -1;
    if (conf->pdef->addserverextra)
	conf->pdef->addserverextra(conf);
373

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

    return 1;
410 411

errexit:
venaas's avatar
venaas committed
412 413 414
    freeserver(conf->servers, 0);
    conf->servers = NULL;
    return 0;
415 416
}

417
unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
418
    while (length > 1) {
venaas's avatar
venaas committed
419
	if (ATTRTYPE(attrs) == type)
420
	    return attrs;
venaas's avatar
venaas committed
421 422
	length -= ATTRLEN(attrs);
	attrs += ATTRLEN(attrs);
423 424 425 426
    }
    return NULL;
}

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

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

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

465
void sendrq(struct request *rq) {
466
    int i, start;
467 468 469 470 471 472
    struct server *to;

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

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

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

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

532
    pthread_mutex_unlock(&to->newrq_mutex);
533
    removeclientrqs_sendrq_freeserver_lock(0);
534 535
    return;

536
errexit:
537 538
    if (rq->from)
	rmclientrq(rq, rq->msg->id);
539
    freerq(rq);
venaas's avatar
 
venaas committed
540
    pthread_mutex_unlock(&to->newrq_mutex);
541
    removeclientrqs_sendrq_freeserver_lock(0);
venaas's avatar
 
venaas committed
542 543
}

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

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

    pthread_mutex_lock(&to->replyq->mutex);
559
    first = list_first(to->replyq->entries) == NULL;
560

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

568
    if (first) {
569
	debug(DBG_DBG, "signalling server writer");
570
	pthread_cond_signal(&to->replyq->cond);
venaas's avatar
 
venaas committed
571
    }
572
    pthread_mutex_unlock(&to->replyq->mutex);
venaas's avatar
 
venaas committed
573 574
}

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

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

venaas's avatar
venaas committed
614 615 616 617 618 619 620
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;
621

venaas's avatar
venaas committed
622 623 624 625 626 627
    pthread_mutex_lock(&lock);
    if (first) {
	EVP_MD_CTX_init(&mdctx);
	first = 0;
    }

628 629 630 631
#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
632
#endif
633

venaas's avatar
venaas committed
634 635 636 637 638 639 640 641 642
    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;
    }

643
#if 0
644
    printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
venaas's avatar
venaas committed
645
#endif
646

venaas's avatar
venaas committed
647 648
    for (i = 0; i < 16; i++)
	text[i] ^= hash[i];
649

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

venaas's avatar
venaas committed
667 668 669
	for (i = 0; i < 16; i++)
	    text[offset + i] ^= hash[i];
    }
670

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

venaas's avatar
venaas committed
688 689 690 691 692 693
    pthread_mutex_lock(&lock);
    if (first) {
	EVP_MD_CTX_init(&mdctx);
	first = 0;
    }

694 695 696 697
#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
698
#endif
699

venaas's avatar
venaas committed
700 701 702 703 704 705 706 707 708
    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;
    }

709
#if 0
710
    printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
venaas's avatar
venaas committed
711
#endif
712

venaas's avatar
venaas committed
713 714
    for (i = 0; i < 16; i++)
	plain[i] = text[i] ^ hash[i];
715

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

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

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

    pthread_mutex_unlock(&lock);
    return 1;
}

746 747 748 749 750 751 752
struct realm *newrealmref(struct realm *r) {
    if (r)
	r->refcount++;
    return r;
}

/* returns with lock on realm */
venaas's avatar
venaas committed
753
struct realm *id2realm(struct list *realmlist, char *id) {
venaas's avatar
venaas committed
754
    struct list_node *entry;
755
    struct realm *realm, *subrealm;
venaas's avatar
venaas committed
756 757 758

    /* 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
759 760
	realm = (struct realm *)entry->data;
	if (!regexec(&realm->regex, id, 0, NULL, 0)) {
761 762
	    pthread_mutex_lock(&realm->mutex);
	    if (realm->subrealms) {
venaas's avatar
venaas committed
763
		subrealm = id2realm(realm->subrealms, id);
764 765 766 767 768 769
		if (subrealm) {
		    pthread_mutex_unlock(&realm->mutex);
		    return subrealm;
		}
	    }
	    return newrealmref(realm);
venaas's avatar
venaas committed
770
	}
venaas's avatar
venaas committed
771
    }
venaas's avatar
venaas committed
772
    return NULL;
venaas's avatar
venaas committed
773 774
}

775 776 777 778
int hasdynamicserver(struct list *srvconfs) {
    struct list_node *entry;

    for (entry = list_first(srvconfs); entry; entry = list_next(entry))
779 780 781 782 783 784
#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
785 786 787 788
	    return 1;
    return 0;
}

789 790
/* helper function, only used by removeserversubrealms() */
void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
791
    struct list_node *entry, *entry2;
792
    struct realm *realm;
793
    struct list *srvconfs;
794

795
    for (entry = list_first(realmlist); entry;) {
796 797
	realm = newrealmref((struct realm *)entry->data);
	pthread_mutex_lock(&realm->mutex);
798
	entry = list_next(entry);
799

800
	if (realm->srvconfs) {
801
	    srvconfs = realm->srvconfs;
802 803 804
	    for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
		if (entry2->data == srv)
		    freerealm(realm);
805
	    list_removedata(srvconfs, srv);
806 807
	}
	if (realm->accsrvconfs) {
808
	    srvconfs = realm->accsrvconfs;
809 810 811
	    for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
		if (entry2->data == srv)
		    freerealm(realm);
812
	    list_removedata(srvconfs, srv);
813 814
	}

815 816 817 818 819 820 821 822 823 824
	/* 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;
825
	    list_removedata(realmlist, realm);
826
	}
827 828
	pthread_mutex_unlock(&realm->mutex);
	freerealm(realm);
829 830 831 832 833 834
    }
}

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

836 837
    for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
	realm = (struct realm *)entry->data;
838
	pthread_mutex_lock(&realm->mutex);
839 840 841 842 843 844 845
	if (realm->subrealms) {
	    _internal_removeserversubrealms(realm->subrealms, srv);
	    if (!list_first(realm->subrealms)) {
		list_destroy(realm->subrealms);
		realm->subrealms = NULL;
	    }
	}
846
	pthread_mutex_unlock(&realm->mutex);
847 848
    }
}
849

850 851
int attrvalidate(unsigned char *attrs, int length) {
    while (length > 1) {
venaas's avatar
venaas committed
852
	if (ATTRLEN(attrs) < 2) {
853
	    debug(DBG_INFO, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
854 855
	    return 0;
	}
venaas's avatar
venaas committed
856
	length -= ATTRLEN(attrs);
857
	if (length < 0) {
858
	    debug(DBG_INFO, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
859 860
	    return 0;
	}
venaas's avatar
venaas committed
861
	attrs += ATTRLEN(attrs);
862 863
    }
    if (length)
864
	debug(DBG_INFO, "attrvalidate: malformed packet? remaining byte after last attribute");
865 866 867
    return 1;
}

venaas's avatar
venaas committed
868 869 870 871 872
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;
    }
873

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

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