Merge from vendor branch AWK:
[dragonfly.git] / contrib / hostapd-0.4.9 / radius.c
1 /*
2  * Host AP (software wireless LAN access point) user space daemon for
3  * Host AP kernel driver / RADIUS client
4  * Copyright (c) 2002-2005, Jouni Malinen <jkmaline@cc.hut.fi>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  *
10  * Alternatively, this software may be distributed under the terms of BSD
11  * license.
12  *
13  * See README and COPYING for more details.
14  */
15
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <unistd.h>
19 #include <string.h>
20 #include <signal.h>
21 #include <sys/time.h>
22 #ifndef CONFIG_NATIVE_WINDOWS
23 #include <netinet/in.h>
24 #include <sys/ioctl.h>
25 #include <sys/socket.h>
26 #include <arpa/inet.h>
27 #endif /* CONFIG_NATIVE_WINDOWS */
28
29 #include "common.h"
30 #include "radius.h"
31 #include "md5.h"
32 #include "crypto.h"
33
34
35 struct radius_msg *radius_msg_new(u8 code, u8 identifier)
36 {
37         struct radius_msg *msg;
38
39         msg = (struct radius_msg *) malloc(sizeof(*msg));
40         if (msg == NULL)
41                 return NULL;
42
43         if (radius_msg_initialize(msg, RADIUS_DEFAULT_MSG_SIZE)) {
44                 free(msg);
45                 return NULL;
46         }
47
48         radius_msg_set_hdr(msg, code, identifier);
49
50         return msg;
51 }
52
53
54 int radius_msg_initialize(struct radius_msg *msg, size_t init_len)
55 {
56         if (msg == NULL || init_len < sizeof(struct radius_hdr))
57                 return -1;
58
59         memset(msg, 0, sizeof(*msg));
60         msg->buf = (unsigned char *) malloc(init_len);
61         if (msg->buf == NULL)
62                 return -1;
63         memset(msg->buf, 0, init_len);
64
65         msg->buf_size = init_len;
66         msg->hdr = (struct radius_hdr *) msg->buf;
67         msg->buf_used = sizeof(*msg->hdr);
68
69         msg->attrs = (struct radius_attr_hdr **)
70                 malloc(RADIUS_DEFAULT_ATTR_COUNT * sizeof(*msg->attrs));
71         if (msg->attrs == NULL) {
72                 free(msg->buf);
73                 msg->buf = NULL;
74                 msg->hdr = NULL;
75                 return -1;
76         }
77
78         msg->attr_size = RADIUS_DEFAULT_ATTR_COUNT;
79         msg->attr_used = 0;
80
81         return 0;
82 }
83
84
85 void radius_msg_set_hdr(struct radius_msg *msg, u8 code, u8 identifier)
86 {
87         msg->hdr->code = code;
88         msg->hdr->identifier = identifier;
89 }
90
91
92 void radius_msg_free(struct radius_msg *msg)
93 {
94         if (msg->buf != NULL) {
95                 free(msg->buf);
96                 msg->buf = NULL;
97                 msg->hdr = NULL;
98         }
99         msg->buf_size = msg->buf_used = 0;
100
101         if (msg->attrs != NULL) {
102                 free(msg->attrs);
103                 msg->attrs = NULL;
104         }
105         msg->attr_size = msg->attr_used = 0;
106 }
107
108
109 static const char *radius_code_string(u8 code)
110 {
111         switch (code) {
112         case RADIUS_CODE_ACCESS_REQUEST: return "Access-Request";
113         case RADIUS_CODE_ACCESS_ACCEPT: return "Access-Accept";
114         case RADIUS_CODE_ACCESS_REJECT: return "Access-Reject";
115         case RADIUS_CODE_ACCOUNTING_REQUEST: return "Accounting-Request";
116         case RADIUS_CODE_ACCOUNTING_RESPONSE: return "Accounting-Response";
117         case RADIUS_CODE_ACCESS_CHALLENGE: return "Access-Challenge";
118         case RADIUS_CODE_STATUS_SERVER: return "Status-Server";
119         case RADIUS_CODE_STATUS_CLIENT: return "Status-Client";
120         case RADIUS_CODE_RESERVED: return "Reserved";
121         default: return "?Unknown?";
122         }
123 }
124
125
126 struct radius_attr_type {
127         u8 type;
128         char *name;
129         enum {
130                 RADIUS_ATTR_UNDIST, RADIUS_ATTR_TEXT, RADIUS_ATTR_IP,
131                 RADIUS_ATTR_HEXDUMP, RADIUS_ATTR_INT32, RADIUS_ATTR_IPV6
132         } data_type;
133 };
134
135 static struct radius_attr_type radius_attrs[] =
136 {
137         { RADIUS_ATTR_USER_NAME, "User-Name", RADIUS_ATTR_TEXT },
138         { RADIUS_ATTR_USER_PASSWORD, "User-Password", RADIUS_ATTR_UNDIST },
139         { RADIUS_ATTR_NAS_IP_ADDRESS, "NAS-IP-Address", RADIUS_ATTR_IP },
140         { RADIUS_ATTR_NAS_PORT, "NAS-Port", RADIUS_ATTR_INT32 },
141         { RADIUS_ATTR_FRAMED_MTU, "Framed-MTU", RADIUS_ATTR_INT32 },
142         { RADIUS_ATTR_STATE, "State", RADIUS_ATTR_UNDIST },
143         { RADIUS_ATTR_CLASS, "Class", RADIUS_ATTR_UNDIST },
144         { RADIUS_ATTR_VENDOR_SPECIFIC, "Vendor-Specific", RADIUS_ATTR_UNDIST },
145         { RADIUS_ATTR_SESSION_TIMEOUT, "Session-Timeout", RADIUS_ATTR_INT32 },
146         { RADIUS_ATTR_IDLE_TIMEOUT, "Idle-Timeout", RADIUS_ATTR_INT32 },
147         { RADIUS_ATTR_TERMINATION_ACTION, "Termination-Action",
148           RADIUS_ATTR_INT32 },
149         { RADIUS_ATTR_CALLED_STATION_ID, "Called-Station-Id",
150           RADIUS_ATTR_TEXT },
151         { RADIUS_ATTR_CALLING_STATION_ID, "Calling-Station-Id",
152           RADIUS_ATTR_TEXT },
153         { RADIUS_ATTR_NAS_IDENTIFIER, "NAS-Identifier", RADIUS_ATTR_TEXT },
154         { RADIUS_ATTR_ACCT_STATUS_TYPE, "Acct-Status-Type",
155           RADIUS_ATTR_INT32 },
156         { RADIUS_ATTR_ACCT_DELAY_TIME, "Acct-Delay-Time", RADIUS_ATTR_INT32 },
157         { RADIUS_ATTR_ACCT_INPUT_OCTETS, "Acct-Input-Octets",
158           RADIUS_ATTR_INT32 },
159         { RADIUS_ATTR_ACCT_OUTPUT_OCTETS, "Acct-Output-Octets",
160           RADIUS_ATTR_INT32 },
161         { RADIUS_ATTR_ACCT_SESSION_ID, "Acct-Session-Id", RADIUS_ATTR_TEXT },
162         { RADIUS_ATTR_ACCT_AUTHENTIC, "Acct-Authentic", RADIUS_ATTR_INT32 },
163         { RADIUS_ATTR_ACCT_SESSION_TIME, "Acct-Session-Time",
164           RADIUS_ATTR_INT32 },
165         { RADIUS_ATTR_ACCT_INPUT_PACKETS, "Acct-Input-Packets",
166           RADIUS_ATTR_INT32 },
167         { RADIUS_ATTR_ACCT_OUTPUT_PACKETS, "Acct-Output-Packets",
168           RADIUS_ATTR_INT32 },
169         { RADIUS_ATTR_ACCT_TERMINATE_CAUSE, "Acct-Terminate-Cause",
170           RADIUS_ATTR_INT32 },
171         { RADIUS_ATTR_ACCT_MULTI_SESSION_ID, "Acct-Multi-Session-Id",
172           RADIUS_ATTR_TEXT },
173         { RADIUS_ATTR_ACCT_LINK_COUNT, "Acct-Link-Count", RADIUS_ATTR_INT32 },
174         { RADIUS_ATTR_ACCT_INPUT_GIGAWORDS, "Acct-Input-Gigawords", 
175           RADIUS_ATTR_INT32 },
176         { RADIUS_ATTR_ACCT_OUTPUT_GIGAWORDS, "Acct-Output-Gigawords",
177           RADIUS_ATTR_INT32 },
178         { RADIUS_ATTR_EVENT_TIMESTAMP, "Event-Timestamp",
179           RADIUS_ATTR_INT32 },
180         { RADIUS_ATTR_NAS_PORT_TYPE, "NAS-Port-Type", RADIUS_ATTR_INT32 },
181         { RADIUS_ATTR_CONNECT_INFO, "Connect-Info", RADIUS_ATTR_TEXT },
182         { RADIUS_ATTR_EAP_MESSAGE, "EAP-Message", RADIUS_ATTR_UNDIST },
183         { RADIUS_ATTR_MESSAGE_AUTHENTICATOR, "Message-Authenticator",
184           RADIUS_ATTR_UNDIST },
185         { RADIUS_ATTR_ACCT_INTERIM_INTERVAL, "Acct-Interim-Interval",
186           RADIUS_ATTR_INT32 },
187         { RADIUS_ATTR_NAS_IPV6_ADDRESS, "NAS-IPv6-Address", RADIUS_ATTR_IPV6 },
188 };
189 #define RADIUS_ATTRS (sizeof(radius_attrs) / sizeof(radius_attrs[0]))
190
191
192 static struct radius_attr_type *radius_get_attr_type(u8 type)
193 {
194         int i;
195
196         for (i = 0; i < RADIUS_ATTRS; i++) {
197                 if (type == radius_attrs[i].type)
198                         return &radius_attrs[i];
199         }
200
201         return NULL;
202 }
203
204
205 static void radius_msg_dump_attr(struct radius_attr_hdr *hdr)
206 {
207         struct radius_attr_type *attr;
208         int i, len;
209         unsigned char *pos;
210
211         attr = radius_get_attr_type(hdr->type);
212
213         printf("   Attribute %d (%s) length=%d\n",
214                hdr->type, attr ? attr->name : "?Unknown?", hdr->length);
215
216         if (attr == NULL)
217                 return;
218
219         len = hdr->length - sizeof(struct radius_attr_hdr);
220         pos = (unsigned char *) (hdr + 1);
221
222         switch (attr->data_type) {
223         case RADIUS_ATTR_TEXT:
224                 printf("      Value: '");
225                 for (i = 0; i < len; i++)
226                         print_char(pos[i]);
227                 printf("'\n");
228                 break;
229
230         case RADIUS_ATTR_IP:
231                 if (len == 4) {
232                         struct in_addr *addr = (struct in_addr *) pos;
233                         printf("      Value: %s\n", inet_ntoa(*addr));
234                 } else
235                         printf("      Invalid IP address length %d\n", len);
236                 break;
237
238 #ifdef CONFIG_IPV6
239         case RADIUS_ATTR_IPV6:
240                 if (len == 16) {
241                         char buf[128];
242                         const char *atxt;
243                         struct in6_addr *addr = (struct in6_addr *) pos;
244                         atxt = inet_ntop(AF_INET6, addr, buf, sizeof(buf));
245                         printf("      Value: %s\n", atxt ? atxt : "?");
246                 } else
247                         printf("      Invalid IPv6 address length %d\n", len);
248                 break;
249 #endif /* CONFIG_IPV6 */
250
251         case RADIUS_ATTR_HEXDUMP:
252         case RADIUS_ATTR_UNDIST:
253                 printf("      Value:");
254                 for (i = 0; i < len; i++)
255                         printf(" %02x", pos[i]);
256                 printf("\n");
257                 break;
258
259         case RADIUS_ATTR_INT32:
260                 if (len == 4)
261                         printf("      Value: %u\n", WPA_GET_BE32(pos));
262                 else
263                         printf("      Invalid INT32 length %d\n", len);
264                 break;
265
266         default:
267                 break;
268         }
269 }
270
271
272 void radius_msg_dump(struct radius_msg *msg)
273 {
274         int i;
275
276         printf("RADIUS message: code=%d (%s) identifier=%d length=%d\n",
277                msg->hdr->code, radius_code_string(msg->hdr->code),
278                msg->hdr->identifier, ntohs(msg->hdr->length));
279
280         for (i = 0; i < msg->attr_used; i++) {
281                 radius_msg_dump_attr(msg->attrs[i]);
282         }
283 }
284
285
286 int radius_msg_finish(struct radius_msg *msg, u8 *secret, size_t secret_len)
287 {
288         if (secret) {
289                 u8 auth[MD5_MAC_LEN];
290                 struct radius_attr_hdr *attr;
291
292                 memset(auth, 0, MD5_MAC_LEN);
293                 attr = radius_msg_add_attr(msg,
294                                            RADIUS_ATTR_MESSAGE_AUTHENTICATOR,
295                                            auth, MD5_MAC_LEN);
296                 if (attr == NULL) {
297                         printf("WARNING: Could not add "
298                                "Message-Authenticator\n");
299                         return -1;
300                 }
301                 msg->hdr->length = htons(msg->buf_used);
302                 hmac_md5(secret, secret_len, msg->buf, msg->buf_used,
303                          (u8 *) (attr + 1));
304         } else
305                 msg->hdr->length = htons(msg->buf_used);
306
307         if (msg->buf_used > 0xffff) {
308                 printf("WARNING: too long RADIUS message (%lu)\n",
309                        (unsigned long) msg->buf_used);
310                 return -1;
311         }
312         return 0;
313 }
314
315
316 int radius_msg_finish_srv(struct radius_msg *msg, const u8 *secret,
317                           size_t secret_len, const u8 *req_authenticator)
318 {
319         u8 auth[MD5_MAC_LEN];
320         struct radius_attr_hdr *attr;
321         const u8 *addr[4];
322         size_t len[4];
323
324         memset(auth, 0, MD5_MAC_LEN);
325         attr = radius_msg_add_attr(msg, RADIUS_ATTR_MESSAGE_AUTHENTICATOR,
326                                    auth, MD5_MAC_LEN);
327         if (attr == NULL) {
328                 printf("WARNING: Could not add Message-Authenticator\n");
329                 return -1;
330         }
331         msg->hdr->length = htons(msg->buf_used);
332         memcpy(msg->hdr->authenticator, req_authenticator,
333                sizeof(msg->hdr->authenticator));
334         hmac_md5(secret, secret_len, msg->buf, msg->buf_used,
335                  (u8 *) (attr + 1));
336
337         /* ResponseAuth = MD5(Code+ID+Length+RequestAuth+Attributes+Secret) */
338         addr[0] = (u8 *) msg->hdr;
339         len[0] = 1 + 1 + 2;
340         addr[1] = req_authenticator;
341         len[1] = MD5_MAC_LEN;
342         addr[2] = (u8 *) (msg->hdr + 1);
343         len[2] = msg->buf_used - sizeof(*msg->hdr);
344         addr[3] = secret;
345         len[3] = secret_len;
346         md5_vector(4, addr, len, msg->hdr->authenticator);
347
348         if (msg->buf_used > 0xffff) {
349                 printf("WARNING: too long RADIUS message (%lu)\n",
350                        (unsigned long) msg->buf_used);
351                 return -1;
352         }
353         return 0;
354 }
355
356
357 void radius_msg_finish_acct(struct radius_msg *msg, u8 *secret,
358                             size_t secret_len)
359 {
360         const u8 *addr[2];
361         size_t len[2];
362
363         msg->hdr->length = htons(msg->buf_used);
364         memset(msg->hdr->authenticator, 0, MD5_MAC_LEN);
365         addr[0] = msg->buf;
366         len[0] = msg->buf_used;
367         addr[1] = secret;
368         len[1] = secret_len;
369         md5_vector(2, addr, len, msg->hdr->authenticator);
370
371         if (msg->buf_used > 0xffff) {
372                 printf("WARNING: too long RADIUS messages (%lu)\n",
373                        (unsigned long) msg->buf_used);
374         }
375 }
376
377
378 static int radius_msg_add_attr_to_array(struct radius_msg *msg,
379                                         struct radius_attr_hdr *attr)
380 {
381         if (msg->attr_used >= msg->attr_size) {
382                 struct radius_attr_hdr **nattrs;
383                 int nlen = msg->attr_size * 2;
384
385                 nattrs = (struct radius_attr_hdr **)
386                         realloc(msg->attrs, nlen * sizeof(*msg->attrs));
387
388                 if (nattrs == NULL)
389                         return -1;
390
391                 msg->attrs = nattrs;
392                 msg->attr_size = nlen;
393         }
394
395         msg->attrs[msg->attr_used++] = attr;
396
397         return 0;
398 }
399
400
401 struct radius_attr_hdr *radius_msg_add_attr(struct radius_msg *msg, u8 type,
402                                             const u8 *data, size_t data_len)
403 {
404         size_t buf_needed;
405         struct radius_attr_hdr *attr;
406
407         if (data_len > RADIUS_MAX_ATTR_LEN) {
408                 printf("radius_msg_add_attr: too long attribute (%lu bytes)\n",
409                        (unsigned long) data_len);
410                 return NULL;
411         }
412
413         buf_needed = msg->buf_used + sizeof(*attr) + data_len;
414
415         if (msg->buf_size < buf_needed) {
416                 /* allocate more space for message buffer */
417                 unsigned char *nbuf;
418                 int nlen = msg->buf_size;
419                 int diff, i;
420
421                 while (nlen < buf_needed)
422                         nlen *= 2;
423                 nbuf = (unsigned char *) realloc(msg->buf, nlen);
424                 if (nbuf == NULL)
425                         return NULL;
426                 diff = nbuf - msg->buf;
427                 msg->buf = nbuf;
428                 msg->hdr = (struct radius_hdr *) msg->buf;
429                 /* adjust attr pointers to match with the new buffer */
430                 for (i = 0; i < msg->attr_used; i++)
431                         msg->attrs[i] = (struct radius_attr_hdr *)
432                                 (((u8 *) msg->attrs[i]) + diff);
433                 memset(msg->buf + msg->buf_size, 0, nlen - msg->buf_size);
434                 msg->buf_size = nlen;
435         }
436
437         attr = (struct radius_attr_hdr *) (msg->buf + msg->buf_used);
438         attr->type = type;
439         attr->length = sizeof(*attr) + data_len;
440         if (data_len > 0)
441                 memcpy(attr + 1, data, data_len);
442
443         msg->buf_used += sizeof(*attr) + data_len;
444
445         if (radius_msg_add_attr_to_array(msg, attr))
446                 return NULL;
447
448         return attr;
449 }
450
451
452 struct radius_msg *radius_msg_parse(const u8 *data, size_t len)
453 {
454         struct radius_msg *msg;
455         struct radius_hdr *hdr;
456         struct radius_attr_hdr *attr;
457         size_t msg_len;
458         unsigned char *pos, *end;
459
460         if (data == NULL || len < sizeof(*hdr))
461                 return NULL;
462
463         hdr = (struct radius_hdr *) data;
464
465         msg_len = ntohs(hdr->length);
466         if (msg_len < sizeof(*hdr) || msg_len > len) {
467                 printf("Invalid RADIUS message length\n");
468                 return NULL;
469         }
470
471         if (msg_len < len) {
472                 printf("Ignored %lu extra bytes after RADIUS message\n",
473                        (unsigned long) len - msg_len);
474         }
475
476         msg = (struct radius_msg *) malloc(sizeof(*msg));
477         if (msg == NULL)
478                 return NULL;
479
480         if (radius_msg_initialize(msg, msg_len)) {
481                 free(msg);
482                 return NULL;
483         }
484
485         memcpy(msg->buf, data, msg_len);
486         msg->buf_size = msg->buf_used = msg_len;
487
488         /* parse attributes */
489         pos = (unsigned char *) (msg->hdr + 1);
490         end = msg->buf + msg->buf_used;
491         while (pos < end) {
492                 if (end - pos < sizeof(*attr))
493                         goto fail;
494
495                 attr = (struct radius_attr_hdr *) pos;
496
497                 if (pos + attr->length > end || attr->length < sizeof(*attr))
498                         goto fail;
499
500                 /* TODO: check that attr->length is suitable for attr->type */
501
502                 if (radius_msg_add_attr_to_array(msg, attr))
503                         goto fail;
504
505                 pos += attr->length;
506         }
507
508         return msg;
509
510  fail:
511         radius_msg_free(msg);
512         free(msg);
513         return NULL;
514 }
515
516
517 int radius_msg_add_eap(struct radius_msg *msg, const u8 *data, size_t data_len)
518 {
519         const u8 *pos = data;
520         size_t left = data_len;
521
522         while (left > 0) {
523                 int len;
524                 if (left > RADIUS_MAX_ATTR_LEN)
525                         len = RADIUS_MAX_ATTR_LEN;
526                 else
527                         len = left;
528
529                 if (!radius_msg_add_attr(msg, RADIUS_ATTR_EAP_MESSAGE,
530                                          pos, len))
531                         return 0;
532
533                 pos += len;
534                 left -= len;
535         }
536
537         return 1;
538 }
539
540
541 u8 *radius_msg_get_eap(struct radius_msg *msg, size_t *eap_len)
542 {
543         u8 *eap, *pos;
544         size_t len;
545         int i;
546
547         if (msg == NULL)
548                 return NULL;
549
550         len = 0;
551         for (i = 0; i < msg->attr_used; i++) {
552                 if (msg->attrs[i]->type == RADIUS_ATTR_EAP_MESSAGE)
553                         len += msg->attrs[i]->length -
554                                 sizeof(struct radius_attr_hdr);
555         }
556
557         if (len == 0)
558                 return NULL;
559
560         eap = malloc(len);
561         if (eap == NULL)
562                 return NULL;
563
564         pos = eap;
565         for (i = 0; i < msg->attr_used; i++) {
566                 if (msg->attrs[i]->type == RADIUS_ATTR_EAP_MESSAGE) {
567                         struct radius_attr_hdr *attr = msg->attrs[i];
568                         int flen = attr->length - sizeof(*attr);
569                         memcpy(pos, attr + 1, flen);
570                         pos += flen;
571                 }
572         }
573
574         if (eap_len)
575                 *eap_len = len;
576
577         return eap;
578 }
579
580
581 int radius_msg_verify_msg_auth(struct radius_msg *msg, const u8 *secret,
582                                size_t secret_len, const u8 *req_auth)
583 {
584         u8 auth[MD5_MAC_LEN], orig[MD5_MAC_LEN];
585         u8 orig_authenticator[16];
586         struct radius_attr_hdr *attr = NULL;
587         int i;
588
589         for (i = 0; i < msg->attr_used; i++) {
590                 if (msg->attrs[i]->type == RADIUS_ATTR_MESSAGE_AUTHENTICATOR) {
591                         if (attr != NULL) {
592                                 printf("Multiple Message-Authenticator "
593                                        "attributes in RADIUS message\n");
594                                 return 1;
595                         }
596                         attr = msg->attrs[i];
597                 }
598         }
599
600         if (attr == NULL) {
601                 printf("No Message-Authenticator attribute found\n");
602                 return 1;
603         }
604
605         memcpy(orig, attr + 1, MD5_MAC_LEN);
606         memset(attr + 1, 0, MD5_MAC_LEN);
607         if (req_auth) {
608                 memcpy(orig_authenticator, msg->hdr->authenticator,
609                        sizeof(orig_authenticator));
610                 memcpy(msg->hdr->authenticator, req_auth,
611                        sizeof(msg->hdr->authenticator));
612         }
613         hmac_md5(secret, secret_len, msg->buf, msg->buf_used, auth);
614         memcpy(attr + 1, orig, MD5_MAC_LEN);
615         if (req_auth) {
616                 memcpy(msg->hdr->authenticator, orig_authenticator,
617                        sizeof(orig_authenticator));
618         }
619
620         if (memcmp(orig, auth, MD5_MAC_LEN) != 0) {
621                 printf("Invalid Message-Authenticator!\n");
622                 return 1;
623         }
624
625         return 0;
626 }
627
628
629 int radius_msg_verify(struct radius_msg *msg, const u8 *secret,
630                       size_t secret_len, struct radius_msg *sent_msg, int auth)
631 {
632         const u8 *addr[4];
633         size_t len[4];
634         u8 hash[MD5_MAC_LEN];
635
636         if (sent_msg == NULL) {
637                 printf("No matching Access-Request message found\n");
638                 return 1;
639         }
640
641         if (auth &&
642             radius_msg_verify_msg_auth(msg, secret, secret_len,
643                                        sent_msg->hdr->authenticator)) {
644                 return 1;
645         }
646
647         /* ResponseAuth = MD5(Code+ID+Length+RequestAuth+Attributes+Secret) */
648         addr[0] = (u8 *) msg->hdr;
649         len[0] = 1 + 1 + 2;
650         addr[1] = sent_msg->hdr->authenticator;
651         len[1] = MD5_MAC_LEN;
652         addr[2] = (u8 *) (msg->hdr + 1);
653         len[2] = msg->buf_used - sizeof(*msg->hdr);
654         addr[3] = secret;
655         len[3] = secret_len;
656         md5_vector(4, addr, len, hash);
657         if (memcmp(hash, msg->hdr->authenticator, MD5_MAC_LEN) != 0) {
658                 printf("Response Authenticator invalid!\n");
659                 return 1;
660         }
661
662         return 0;
663
664 }
665
666
667 int radius_msg_copy_attr(struct radius_msg *dst, struct radius_msg *src,
668                          u8 type)
669 {
670         struct radius_attr_hdr *attr = NULL;
671         int i;
672
673         for (i = 0; i < src->attr_used; i++) {
674                 if (src->attrs[i]->type == type) {
675                         attr = src->attrs[i];
676                         break;
677                 }
678         }
679
680         if (attr == NULL)
681                 return 0;
682
683         if (!radius_msg_add_attr(dst, type, (u8 *) (attr + 1),
684                                  attr->length - sizeof(*attr)))
685                 return -1;
686
687         return 1;
688 }
689
690
691 /* Create Request Authenticator. The value should be unique over the lifetime
692  * of the shared secret between authenticator and authentication server.
693  * Use one-way MD5 hash calculated from current timestamp and some data given
694  * by the caller. */
695 void radius_msg_make_authenticator(struct radius_msg *msg,
696                                    u8 *data, size_t len)
697 {
698         struct timeval tv;
699         long int l;
700         const u8 *addr[3];
701         size_t elen[3];
702
703         gettimeofday(&tv, NULL);
704         l = random();
705         addr[0] = (u8 *) &tv;
706         elen[0] = sizeof(tv);
707         addr[1] = data;
708         elen[1] = len;
709         addr[2] = (u8 *) &l;
710         elen[2] = sizeof(l);
711         md5_vector(3, addr, elen, msg->hdr->authenticator);
712 }
713
714
715 /* Get Vendor-specific RADIUS Attribute from a parsed RADIUS message.
716  * Returns the Attribute payload and sets alen to indicate the length of the
717  * payload if a vendor attribute with subtype is found, otherwise returns NULL.
718  * The returned payload is allocated with malloc() and caller must free it.
719  */
720 static u8 *radius_msg_get_vendor_attr(struct radius_msg *msg, u32 vendor,
721                                       u8 subtype, size_t *alen)
722 {
723         u8 *data, *pos;
724         int i;
725         size_t len;
726
727         if (msg == NULL)
728                 return NULL;
729
730         for (i = 0; i < msg->attr_used; i++) {
731                 struct radius_attr_hdr *attr = msg->attrs[i];
732                 int left;
733                 u32 vendor_id;
734                 struct radius_attr_vendor *vhdr;
735
736                 if (attr->type != RADIUS_ATTR_VENDOR_SPECIFIC)
737                         continue;
738
739                 left = attr->length - sizeof(*attr);
740                 if (left < 4)
741                         continue;
742
743                 pos = (u8 *) (attr + 1);
744
745                 memcpy(&vendor_id, pos, 4);
746                 pos += 4;
747                 left -= 4;
748
749                 if (ntohl(vendor_id) != vendor)
750                         continue;
751
752                 while (left >= sizeof(*vhdr)) {
753                         vhdr = (struct radius_attr_vendor *) pos;
754                         if (vhdr->vendor_length > left ||
755                             vhdr->vendor_length < sizeof(*vhdr)) {
756                                 left = 0;
757                                 break;
758                         }
759                         if (vhdr->vendor_type != subtype) {
760                                 pos += vhdr->vendor_length;
761                                 left -= vhdr->vendor_length;
762                                 continue;
763                         }
764
765                         len = vhdr->vendor_length - sizeof(*vhdr);
766                         data = malloc(len);
767                         if (data == NULL)
768                                 return NULL;
769                         memcpy(data, pos + sizeof(*vhdr), len);
770                         if (alen)
771                                 *alen = len;
772                         return data;
773                 }
774         }
775
776         return NULL;
777 }
778
779
780 static u8 * decrypt_ms_key(const u8 *key, size_t len,
781                            const u8 *req_authenticator,
782                            const u8 *secret, size_t secret_len, size_t *reslen)
783 {
784         u8 *plain, *ppos, *res;
785         const u8 *pos;
786         size_t left, plen;
787         u8 hash[MD5_MAC_LEN];
788         int i, first = 1;
789         const u8 *addr[3];
790         size_t elen[3];
791
792         /* key: 16-bit salt followed by encrypted key info */
793
794         if (len < 2 + 16)
795                 return NULL;
796
797         pos = key + 2;
798         left = len - 2;
799         if (left % 16) {
800                 printf("Invalid ms key len %lu\n", (unsigned long) left);
801                 return NULL;
802         }
803
804         plen = left;
805         ppos = plain = malloc(plen);
806         if (plain == NULL)
807                 return NULL;
808
809         while (left > 0) {
810                 /* b(1) = MD5(Secret + Request-Authenticator + Salt)
811                  * b(i) = MD5(Secret + c(i - 1)) for i > 1 */
812
813                 addr[0] = secret;
814                 elen[0] = secret_len;
815                 if (first) {
816                         addr[1] = req_authenticator;
817                         elen[1] = MD5_MAC_LEN;
818                         addr[2] = key;
819                         elen[2] = 2; /* Salt */
820                 } else {
821                         addr[1] = pos - MD5_MAC_LEN;
822                         elen[1] = MD5_MAC_LEN;
823                 }
824                 md5_vector(first ? 3 : 2, addr, elen, hash);
825                 first = 0;
826
827                 for (i = 0; i < MD5_MAC_LEN; i++)
828                         *ppos++ = *pos++ ^ hash[i];
829                 left -= MD5_MAC_LEN;
830         }
831
832         if (plain[0] > plen - 1) {
833                 printf("Failed to decrypt MPPE key\n");
834                 free(plain);
835                 return NULL;
836         }
837
838         res = malloc(plain[0]);
839         if (res == NULL) {
840                 free(plain);
841                 return NULL;
842         }
843         memcpy(res, plain + 1, plain[0]);
844         if (reslen)
845                 *reslen = plain[0];
846         free(plain);
847         return res;
848 }
849
850
851 static void encrypt_ms_key(const u8 *key, size_t key_len, u16 salt,
852                            const u8 *req_authenticator,
853                            const u8 *secret, size_t secret_len,
854                            u8 *ebuf, size_t *elen)
855 {
856         int i, len, first = 1;
857         u8 hash[MD5_MAC_LEN], saltbuf[2], *pos;
858         const u8 *addr[3];
859         size_t _len[3];
860
861         saltbuf[0] = salt >> 8;
862         saltbuf[1] = salt;
863
864         len = 1 + key_len;
865         if (len & 0x0f) {
866                 len = (len & 0xf0) + 16;
867         }
868         memset(ebuf, 0, len);
869         ebuf[0] = key_len;
870         memcpy(ebuf + 1, key, key_len);
871
872         *elen = len;
873
874         pos = ebuf;
875         while (len > 0) {
876                 /* b(1) = MD5(Secret + Request-Authenticator + Salt)
877                  * b(i) = MD5(Secret + c(i - 1)) for i > 1 */
878                 addr[0] = secret;
879                 _len[0] = secret_len;
880                 if (first) {
881                         addr[1] = req_authenticator;
882                         _len[1] = MD5_MAC_LEN;
883                         addr[2] = saltbuf;
884                         _len[2] = sizeof(saltbuf);
885                 } else {
886                         addr[1] = pos - MD5_MAC_LEN;
887                         _len[1] = MD5_MAC_LEN;
888                 }
889                 md5_vector(first ? 3 : 2, addr, _len, hash);
890                 first = 0;
891
892                 for (i = 0; i < MD5_MAC_LEN; i++)
893                         *pos++ ^= hash[i];
894
895                 len -= MD5_MAC_LEN;
896         }
897 }
898
899
900 struct radius_ms_mppe_keys *
901 radius_msg_get_ms_keys(struct radius_msg *msg, struct radius_msg *sent_msg,
902                        u8 *secret, size_t secret_len)
903 {
904         u8 *key;
905         size_t keylen;
906         struct radius_ms_mppe_keys *keys;
907
908         if (msg == NULL || sent_msg == NULL)
909                 return NULL;
910
911         keys = (struct radius_ms_mppe_keys *) malloc(sizeof(*keys));
912         if (keys == NULL)
913                 return NULL;
914
915         memset(keys, 0, sizeof(*keys));
916
917         key = radius_msg_get_vendor_attr(msg, RADIUS_VENDOR_ID_MICROSOFT,
918                                          RADIUS_VENDOR_ATTR_MS_MPPE_SEND_KEY,
919                                          &keylen);
920         if (key) {
921                 keys->send = decrypt_ms_key(key, keylen,
922                                             sent_msg->hdr->authenticator,
923                                             secret, secret_len,
924                                             &keys->send_len);
925                 free(key);
926         }
927
928         key = radius_msg_get_vendor_attr(msg, RADIUS_VENDOR_ID_MICROSOFT,
929                                          RADIUS_VENDOR_ATTR_MS_MPPE_RECV_KEY,
930                                          &keylen);
931         if (key) {
932                 keys->recv = decrypt_ms_key(key, keylen,
933                                             sent_msg->hdr->authenticator,
934                                             secret, secret_len,
935                                             &keys->recv_len);
936                 free(key);
937         }
938
939         return keys;
940 }
941
942
943 struct radius_ms_mppe_keys *
944 radius_msg_get_cisco_keys(struct radius_msg *msg, struct radius_msg *sent_msg,
945                           u8 *secret, size_t secret_len)
946 {
947         u8 *key;
948         size_t keylen;
949         struct radius_ms_mppe_keys *keys;
950
951         if (msg == NULL || sent_msg == NULL)
952                 return NULL;
953
954         keys = (struct radius_ms_mppe_keys *) malloc(sizeof(*keys));
955         if (keys == NULL)
956                 return NULL;
957
958         memset(keys, 0, sizeof(*keys));
959
960         key = radius_msg_get_vendor_attr(msg, RADIUS_VENDOR_ID_CISCO,
961                                          RADIUS_CISCO_AV_PAIR, &keylen);
962         if (key && keylen == 51 && memcmp(key, "leap:session-key=", 17) == 0) {
963                 keys->recv = decrypt_ms_key(key + 17, keylen - 17,
964                                             sent_msg->hdr->authenticator,
965                                             secret, secret_len,
966                                             &keys->recv_len);
967         }
968         free(key);
969
970         return keys;
971 }
972
973
974 int radius_msg_add_mppe_keys(struct radius_msg *msg,
975                              const u8 *req_authenticator,
976                              const u8 *secret, size_t secret_len,
977                              const u8 *send_key, size_t send_key_len,
978                              const u8 *recv_key, size_t recv_key_len)
979 {
980         struct radius_attr_hdr *attr;
981         u32 vendor_id = htonl(RADIUS_VENDOR_ID_MICROSOFT);
982         u8 *buf;
983         struct radius_attr_vendor *vhdr;
984         u8 *pos;
985         size_t elen;
986         int hlen;
987         u16 salt;
988
989         hlen = sizeof(vendor_id) + sizeof(*vhdr) + 2;
990
991         /* MS-MPPE-Send-Key */
992         buf = malloc(hlen + send_key_len + 16);
993         if (buf == NULL) {
994                 return 0;
995         }
996         pos = buf;
997         memcpy(pos, &vendor_id, sizeof(vendor_id));
998         pos += sizeof(vendor_id);
999         vhdr = (struct radius_attr_vendor *) pos;
1000         vhdr->vendor_type = RADIUS_VENDOR_ATTR_MS_MPPE_SEND_KEY;
1001         pos = (u8 *) (vhdr + 1);
1002         salt = random() | 0x8000;
1003         *pos++ = salt >> 8;
1004         *pos++ = salt;
1005         encrypt_ms_key(send_key, send_key_len, salt, req_authenticator, secret,
1006                        secret_len, pos, &elen);
1007         vhdr->vendor_length = hlen + elen - sizeof(vendor_id);
1008
1009         attr = radius_msg_add_attr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
1010                                    buf, hlen + elen);
1011         free(buf);
1012         if (attr == NULL) {
1013                 return 0;
1014         }
1015
1016         /* MS-MPPE-Recv-Key */
1017         buf = malloc(hlen + send_key_len + 16);
1018         if (buf == NULL) {
1019                 return 0;
1020         }
1021         pos = buf;
1022         memcpy(pos, &vendor_id, sizeof(vendor_id));
1023         pos += sizeof(vendor_id);
1024         vhdr = (struct radius_attr_vendor *) pos;
1025         vhdr->vendor_type = RADIUS_VENDOR_ATTR_MS_MPPE_RECV_KEY;
1026         pos = (u8 *) (vhdr + 1);
1027         salt ^= 1;
1028         *pos++ = salt >> 8;
1029         *pos++ = salt;
1030         encrypt_ms_key(recv_key, recv_key_len, salt, req_authenticator, secret,
1031                        secret_len, pos, &elen);
1032         vhdr->vendor_length = hlen + elen - sizeof(vendor_id);
1033
1034         attr = radius_msg_add_attr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
1035                                    buf, hlen + elen);
1036         free(buf);
1037         if (attr == NULL) {
1038                 return 0;
1039         }
1040
1041         return 1;
1042 }
1043
1044
1045 /* Add User-Password attribute to a RADIUS message and encrypt it as specified
1046  * in RFC 2865, Chap. 5.2 */
1047 struct radius_attr_hdr *
1048 radius_msg_add_attr_user_password(struct radius_msg *msg,
1049                                   u8 *data, size_t data_len,
1050                                   u8 *secret, size_t secret_len)
1051 {
1052         u8 buf[128];
1053         int padlen, i, pos;
1054         size_t buf_len;
1055         const u8 *addr[2];
1056         size_t len[2];
1057         u8 hash[16];
1058
1059         if (data_len > 128)
1060                 return NULL;
1061
1062         memcpy(buf, data, data_len);
1063         buf_len = data_len;
1064
1065         padlen = data_len % 16;
1066         if (padlen) {
1067                 padlen = 16 - padlen;
1068                 memset(buf + data_len, 0, padlen);
1069                 buf_len += padlen;
1070         }
1071
1072         addr[0] = secret;
1073         len[0] = secret_len;
1074         addr[1] = msg->hdr->authenticator;
1075         len[1] = 16;
1076         md5_vector(2, addr, len, hash);
1077
1078         for (i = 0; i < 16; i++)
1079                 buf[i] ^= hash[i];
1080         pos = 16;
1081
1082         while (pos < buf_len) {
1083                 addr[0] = secret;
1084                 len[0] = secret_len;
1085                 addr[1] = &buf[pos - 16];
1086                 len[1] = 16;
1087                 md5_vector(2, addr, len, hash);
1088
1089                 for (i = 0; i < 16; i++)
1090                         buf[pos + i] ^= hash[i];
1091
1092                 pos += 16;
1093         }
1094
1095         return radius_msg_add_attr(msg, RADIUS_ATTR_USER_PASSWORD,
1096                                    buf, buf_len);
1097 }
1098
1099
1100 int radius_msg_get_attr(struct radius_msg *msg, u8 type, u8 *buf, size_t len)
1101 {
1102         int i;
1103         struct radius_attr_hdr *attr = NULL;
1104         size_t dlen;
1105
1106         for (i = 0; i < msg->attr_used; i++) {
1107                 if (msg->attrs[i]->type == type) {
1108                         attr = msg->attrs[i];
1109                         break;
1110                 }
1111         }
1112
1113         if (!attr)
1114                 return -1;
1115
1116         dlen = attr->length - sizeof(*attr);
1117         if (buf)
1118                 memcpy(buf, (attr + 1), dlen > len ? len : dlen);
1119         return dlen;
1120 }
1121
1122
1123 int radius_msg_get_attr_ptr(struct radius_msg *msg, u8 type, u8 **buf,
1124                             size_t *len, const u8 *start)
1125 {
1126         int i;
1127         struct radius_attr_hdr *attr = NULL;
1128
1129         for (i = 0; i < msg->attr_used; i++) {
1130                 if (msg->attrs[i]->type == type &&
1131                     (start == NULL || (u8 *) msg->attrs[i] > start)) {
1132                         attr = msg->attrs[i];
1133                         break;
1134                 }
1135         }
1136
1137         if (!attr)
1138                 return -1;
1139
1140         *buf = (u8 *) (attr + 1);
1141         *len = attr->length - sizeof(*attr);
1142         return 0;
1143 }
1144
1145
1146 int radius_msg_count_attr(struct radius_msg *msg, u8 type, int min_len)
1147 {
1148         int i, count;
1149
1150         for (count = 0, i = 0; i < msg->attr_used; i++) {
1151                 if (msg->attrs[i]->type == type &&
1152                     msg->attrs[i]->length >=
1153                     sizeof(struct radius_attr_hdr) + min_len)
1154                         count++;
1155         }
1156
1157         return count;
1158 }