OSDN Git Service

wpa_supplicant: Update to 07-Jul-2012 TOT
[android-x86/external-wpa_supplicant_8.git] / src / radius / radius.c
1 /*
2  * RADIUS message processing
3  * Copyright (c) 2002-2009, 2011-2012, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8
9 #include "utils/includes.h"
10
11 #include "utils/common.h"
12 #include "utils/wpabuf.h"
13 #include "crypto/md5.h"
14 #include "crypto/crypto.h"
15 #include "radius.h"
16
17
18 /**
19  * struct radius_msg - RADIUS message structure for new and parsed messages
20  */
21 struct radius_msg {
22         /**
23          * buf - Allocated buffer for RADIUS message
24          */
25         struct wpabuf *buf;
26
27         /**
28          * hdr - Pointer to the RADIUS header in buf
29          */
30         struct radius_hdr *hdr;
31
32         /**
33          * attr_pos - Array of indexes to attributes
34          *
35          * The values are number of bytes from buf to the beginning of
36          * struct radius_attr_hdr.
37          */
38         size_t *attr_pos;
39
40         /**
41          * attr_size - Total size of the attribute pointer array
42          */
43         size_t attr_size;
44
45         /**
46          * attr_used - Total number of attributes in the array
47          */
48         size_t attr_used;
49 };
50
51
52 struct radius_hdr * radius_msg_get_hdr(struct radius_msg *msg)
53 {
54         return msg->hdr;
55 }
56
57
58 struct wpabuf * radius_msg_get_buf(struct radius_msg *msg)
59 {
60         return msg->buf;
61 }
62
63
64 static struct radius_attr_hdr *
65 radius_get_attr_hdr(struct radius_msg *msg, int idx)
66 {
67         return (struct radius_attr_hdr *)
68                 (wpabuf_mhead_u8(msg->buf) + msg->attr_pos[idx]);
69 }
70
71
72 static void radius_msg_set_hdr(struct radius_msg *msg, u8 code, u8 identifier)
73 {
74         msg->hdr->code = code;
75         msg->hdr->identifier = identifier;
76 }
77
78
79 static int radius_msg_initialize(struct radius_msg *msg)
80 {
81         msg->attr_pos =
82                 os_zalloc(RADIUS_DEFAULT_ATTR_COUNT * sizeof(*msg->attr_pos));
83         if (msg->attr_pos == NULL)
84                 return -1;
85
86         msg->attr_size = RADIUS_DEFAULT_ATTR_COUNT;
87         msg->attr_used = 0;
88
89         return 0;
90 }
91
92
93 /**
94  * radius_msg_new - Create a new RADIUS message
95  * @code: Code for RADIUS header
96  * @identifier: Identifier for RADIUS header
97  * Returns: Context for RADIUS message or %NULL on failure
98  *
99  * The caller is responsible for freeing the returned data with
100  * radius_msg_free().
101  */
102 struct radius_msg * radius_msg_new(u8 code, u8 identifier)
103 {
104         struct radius_msg *msg;
105
106         msg = os_zalloc(sizeof(*msg));
107         if (msg == NULL)
108                 return NULL;
109
110         msg->buf = wpabuf_alloc(RADIUS_DEFAULT_MSG_SIZE);
111         if (msg->buf == NULL || radius_msg_initialize(msg)) {
112                 radius_msg_free(msg);
113                 return NULL;
114         }
115         msg->hdr = wpabuf_put(msg->buf, sizeof(struct radius_hdr));
116
117         radius_msg_set_hdr(msg, code, identifier);
118
119         return msg;
120 }
121
122
123 /**
124  * radius_msg_free - Free a RADIUS message
125  * @msg: RADIUS message from radius_msg_new() or radius_msg_parse()
126  */
127 void radius_msg_free(struct radius_msg *msg)
128 {
129         if (msg == NULL)
130                 return;
131
132         wpabuf_free(msg->buf);
133         os_free(msg->attr_pos);
134         os_free(msg);
135 }
136
137
138 static const char *radius_code_string(u8 code)
139 {
140         switch (code) {
141         case RADIUS_CODE_ACCESS_REQUEST: return "Access-Request";
142         case RADIUS_CODE_ACCESS_ACCEPT: return "Access-Accept";
143         case RADIUS_CODE_ACCESS_REJECT: return "Access-Reject";
144         case RADIUS_CODE_ACCOUNTING_REQUEST: return "Accounting-Request";
145         case RADIUS_CODE_ACCOUNTING_RESPONSE: return "Accounting-Response";
146         case RADIUS_CODE_ACCESS_CHALLENGE: return "Access-Challenge";
147         case RADIUS_CODE_STATUS_SERVER: return "Status-Server";
148         case RADIUS_CODE_STATUS_CLIENT: return "Status-Client";
149         case RADIUS_CODE_RESERVED: return "Reserved";
150         case RADIUS_CODE_DISCONNECT_REQUEST: return "Disconnect-Request";
151         case RADIUS_CODE_DISCONNECT_ACK: return "Disconnect-ACK";
152         case RADIUS_CODE_DISCONNECT_NAK: return "Disconnect-NAK";
153         case RADIUS_CODE_COA_REQUEST: return "CoA-Request";
154         case RADIUS_CODE_COA_ACK: return "CoA-ACK";
155         case RADIUS_CODE_COA_NAK: return "CoA-NAK";
156         default: return "?Unknown?";
157         }
158 }
159
160
161 struct radius_attr_type {
162         u8 type;
163         char *name;
164         enum {
165                 RADIUS_ATTR_UNDIST, RADIUS_ATTR_TEXT, RADIUS_ATTR_IP,
166                 RADIUS_ATTR_HEXDUMP, RADIUS_ATTR_INT32, RADIUS_ATTR_IPV6
167         } data_type;
168 };
169
170 static struct radius_attr_type radius_attrs[] =
171 {
172         { RADIUS_ATTR_USER_NAME, "User-Name", RADIUS_ATTR_TEXT },
173         { RADIUS_ATTR_USER_PASSWORD, "User-Password", RADIUS_ATTR_UNDIST },
174         { RADIUS_ATTR_NAS_IP_ADDRESS, "NAS-IP-Address", RADIUS_ATTR_IP },
175         { RADIUS_ATTR_NAS_PORT, "NAS-Port", RADIUS_ATTR_INT32 },
176         { RADIUS_ATTR_FRAMED_MTU, "Framed-MTU", RADIUS_ATTR_INT32 },
177         { RADIUS_ATTR_REPLY_MESSAGE, "Reply-Message", RADIUS_ATTR_TEXT },
178         { RADIUS_ATTR_STATE, "State", RADIUS_ATTR_UNDIST },
179         { RADIUS_ATTR_CLASS, "Class", RADIUS_ATTR_UNDIST },
180         { RADIUS_ATTR_VENDOR_SPECIFIC, "Vendor-Specific", RADIUS_ATTR_UNDIST },
181         { RADIUS_ATTR_SESSION_TIMEOUT, "Session-Timeout", RADIUS_ATTR_INT32 },
182         { RADIUS_ATTR_IDLE_TIMEOUT, "Idle-Timeout", RADIUS_ATTR_INT32 },
183         { RADIUS_ATTR_TERMINATION_ACTION, "Termination-Action",
184           RADIUS_ATTR_INT32 },
185         { RADIUS_ATTR_CALLED_STATION_ID, "Called-Station-Id",
186           RADIUS_ATTR_TEXT },
187         { RADIUS_ATTR_CALLING_STATION_ID, "Calling-Station-Id",
188           RADIUS_ATTR_TEXT },
189         { RADIUS_ATTR_NAS_IDENTIFIER, "NAS-Identifier", RADIUS_ATTR_TEXT },
190         { RADIUS_ATTR_PROXY_STATE, "Proxy-State", RADIUS_ATTR_UNDIST },
191         { RADIUS_ATTR_ACCT_STATUS_TYPE, "Acct-Status-Type",
192           RADIUS_ATTR_INT32 },
193         { RADIUS_ATTR_ACCT_DELAY_TIME, "Acct-Delay-Time", RADIUS_ATTR_INT32 },
194         { RADIUS_ATTR_ACCT_INPUT_OCTETS, "Acct-Input-Octets",
195           RADIUS_ATTR_INT32 },
196         { RADIUS_ATTR_ACCT_OUTPUT_OCTETS, "Acct-Output-Octets",
197           RADIUS_ATTR_INT32 },
198         { RADIUS_ATTR_ACCT_SESSION_ID, "Acct-Session-Id", RADIUS_ATTR_TEXT },
199         { RADIUS_ATTR_ACCT_AUTHENTIC, "Acct-Authentic", RADIUS_ATTR_INT32 },
200         { RADIUS_ATTR_ACCT_SESSION_TIME, "Acct-Session-Time",
201           RADIUS_ATTR_INT32 },
202         { RADIUS_ATTR_ACCT_INPUT_PACKETS, "Acct-Input-Packets",
203           RADIUS_ATTR_INT32 },
204         { RADIUS_ATTR_ACCT_OUTPUT_PACKETS, "Acct-Output-Packets",
205           RADIUS_ATTR_INT32 },
206         { RADIUS_ATTR_ACCT_TERMINATE_CAUSE, "Acct-Terminate-Cause",
207           RADIUS_ATTR_INT32 },
208         { RADIUS_ATTR_ACCT_MULTI_SESSION_ID, "Acct-Multi-Session-Id",
209           RADIUS_ATTR_TEXT },
210         { RADIUS_ATTR_ACCT_LINK_COUNT, "Acct-Link-Count", RADIUS_ATTR_INT32 },
211         { RADIUS_ATTR_ACCT_INPUT_GIGAWORDS, "Acct-Input-Gigawords", 
212           RADIUS_ATTR_INT32 },
213         { RADIUS_ATTR_ACCT_OUTPUT_GIGAWORDS, "Acct-Output-Gigawords",
214           RADIUS_ATTR_INT32 },
215         { RADIUS_ATTR_EVENT_TIMESTAMP, "Event-Timestamp",
216           RADIUS_ATTR_INT32 },
217         { RADIUS_ATTR_NAS_PORT_TYPE, "NAS-Port-Type", RADIUS_ATTR_INT32 },
218         { RADIUS_ATTR_TUNNEL_TYPE, "Tunnel-Type", RADIUS_ATTR_HEXDUMP },
219         { RADIUS_ATTR_TUNNEL_MEDIUM_TYPE, "Tunnel-Medium-Type",
220           RADIUS_ATTR_HEXDUMP },
221         { RADIUS_ATTR_TUNNEL_PASSWORD, "Tunnel-Password",
222           RADIUS_ATTR_UNDIST },
223         { RADIUS_ATTR_CONNECT_INFO, "Connect-Info", RADIUS_ATTR_TEXT },
224         { RADIUS_ATTR_EAP_MESSAGE, "EAP-Message", RADIUS_ATTR_UNDIST },
225         { RADIUS_ATTR_MESSAGE_AUTHENTICATOR, "Message-Authenticator",
226           RADIUS_ATTR_UNDIST },
227         { RADIUS_ATTR_TUNNEL_PRIVATE_GROUP_ID, "Tunnel-Private-Group-Id",
228           RADIUS_ATTR_HEXDUMP },
229         { RADIUS_ATTR_ACCT_INTERIM_INTERVAL, "Acct-Interim-Interval",
230           RADIUS_ATTR_INT32 },
231         { RADIUS_ATTR_CHARGEABLE_USER_IDENTITY, "Chargeable-User-Identity",
232           RADIUS_ATTR_TEXT },
233         { RADIUS_ATTR_NAS_IPV6_ADDRESS, "NAS-IPv6-Address", RADIUS_ATTR_IPV6 },
234         { RADIUS_ATTR_ERROR_CAUSE, "Error-Cause", RADIUS_ATTR_INT32 }
235 };
236 #define RADIUS_ATTRS (sizeof(radius_attrs) / sizeof(radius_attrs[0]))
237
238
239 static struct radius_attr_type *radius_get_attr_type(u8 type)
240 {
241         size_t i;
242
243         for (i = 0; i < RADIUS_ATTRS; i++) {
244                 if (type == radius_attrs[i].type)
245                         return &radius_attrs[i];
246         }
247
248         return NULL;
249 }
250
251
252 static void print_char(char c)
253 {
254         if (c >= 32 && c < 127)
255                 printf("%c", c);
256         else
257                 printf("<%02x>", c);
258 }
259
260
261 static void radius_msg_dump_attr(struct radius_attr_hdr *hdr)
262 {
263         struct radius_attr_type *attr;
264         int i, len;
265         unsigned char *pos;
266
267         attr = radius_get_attr_type(hdr->type);
268
269         printf("   Attribute %d (%s) length=%d\n",
270                hdr->type, attr ? attr->name : "?Unknown?", hdr->length);
271
272         if (attr == NULL)
273                 return;
274
275         len = hdr->length - sizeof(struct radius_attr_hdr);
276         pos = (unsigned char *) (hdr + 1);
277
278         switch (attr->data_type) {
279         case RADIUS_ATTR_TEXT:
280                 printf("      Value: '");
281                 for (i = 0; i < len; i++)
282                         print_char(pos[i]);
283                 printf("'\n");
284                 break;
285
286         case RADIUS_ATTR_IP:
287                 if (len == 4) {
288                         struct in_addr addr;
289                         os_memcpy(&addr, pos, 4);
290                         printf("      Value: %s\n", inet_ntoa(addr));
291                 } else
292                         printf("      Invalid IP address length %d\n", len);
293                 break;
294
295 #ifdef CONFIG_IPV6
296         case RADIUS_ATTR_IPV6:
297                 if (len == 16) {
298                         char buf[128];
299                         const char *atxt;
300                         struct in6_addr *addr = (struct in6_addr *) pos;
301                         atxt = inet_ntop(AF_INET6, addr, buf, sizeof(buf));
302                         printf("      Value: %s\n", atxt ? atxt : "?");
303                 } else
304                         printf("      Invalid IPv6 address length %d\n", len);
305                 break;
306 #endif /* CONFIG_IPV6 */
307
308         case RADIUS_ATTR_HEXDUMP:
309         case RADIUS_ATTR_UNDIST:
310                 printf("      Value:");
311                 for (i = 0; i < len; i++)
312                         printf(" %02x", pos[i]);
313                 printf("\n");
314                 break;
315
316         case RADIUS_ATTR_INT32:
317                 if (len == 4)
318                         printf("      Value: %u\n", WPA_GET_BE32(pos));
319                 else
320                         printf("      Invalid INT32 length %d\n", len);
321                 break;
322
323         default:
324                 break;
325         }
326 }
327
328
329 void radius_msg_dump(struct radius_msg *msg)
330 {
331         size_t i;
332
333         printf("RADIUS message: code=%d (%s) identifier=%d length=%d\n",
334                msg->hdr->code, radius_code_string(msg->hdr->code),
335                msg->hdr->identifier, ntohs(msg->hdr->length));
336
337         for (i = 0; i < msg->attr_used; i++) {
338                 struct radius_attr_hdr *attr = radius_get_attr_hdr(msg, i);
339                 radius_msg_dump_attr(attr);
340         }
341 }
342
343
344 int radius_msg_finish(struct radius_msg *msg, const u8 *secret,
345                       size_t secret_len)
346 {
347         if (secret) {
348                 u8 auth[MD5_MAC_LEN];
349                 struct radius_attr_hdr *attr;
350
351                 os_memset(auth, 0, MD5_MAC_LEN);
352                 attr = radius_msg_add_attr(msg,
353                                            RADIUS_ATTR_MESSAGE_AUTHENTICATOR,
354                                            auth, MD5_MAC_LEN);
355                 if (attr == NULL) {
356                         wpa_printf(MSG_WARNING, "RADIUS: Could not add "
357                                    "Message-Authenticator");
358                         return -1;
359                 }
360                 msg->hdr->length = htons(wpabuf_len(msg->buf));
361                 hmac_md5(secret, secret_len, wpabuf_head(msg->buf),
362                          wpabuf_len(msg->buf), (u8 *) (attr + 1));
363         } else
364                 msg->hdr->length = htons(wpabuf_len(msg->buf));
365
366         if (wpabuf_len(msg->buf) > 0xffff) {
367                 wpa_printf(MSG_WARNING, "RADIUS: Too long message (%lu)",
368                            (unsigned long) wpabuf_len(msg->buf));
369                 return -1;
370         }
371         return 0;
372 }
373
374
375 int radius_msg_finish_srv(struct radius_msg *msg, const u8 *secret,
376                           size_t secret_len, const u8 *req_authenticator)
377 {
378         u8 auth[MD5_MAC_LEN];
379         struct radius_attr_hdr *attr;
380         const u8 *addr[4];
381         size_t len[4];
382
383         os_memset(auth, 0, MD5_MAC_LEN);
384         attr = radius_msg_add_attr(msg, RADIUS_ATTR_MESSAGE_AUTHENTICATOR,
385                                    auth, MD5_MAC_LEN);
386         if (attr == NULL) {
387                 printf("WARNING: Could not add Message-Authenticator\n");
388                 return -1;
389         }
390         msg->hdr->length = htons(wpabuf_len(msg->buf));
391         os_memcpy(msg->hdr->authenticator, req_authenticator,
392                   sizeof(msg->hdr->authenticator));
393         hmac_md5(secret, secret_len, wpabuf_head(msg->buf),
394                  wpabuf_len(msg->buf), (u8 *) (attr + 1));
395
396         /* ResponseAuth = MD5(Code+ID+Length+RequestAuth+Attributes+Secret) */
397         addr[0] = (u8 *) msg->hdr;
398         len[0] = 1 + 1 + 2;
399         addr[1] = req_authenticator;
400         len[1] = MD5_MAC_LEN;
401         addr[2] = wpabuf_head_u8(msg->buf) + sizeof(struct radius_hdr);
402         len[2] = wpabuf_len(msg->buf) - sizeof(struct radius_hdr);
403         addr[3] = secret;
404         len[3] = secret_len;
405         md5_vector(4, addr, len, msg->hdr->authenticator);
406
407         if (wpabuf_len(msg->buf) > 0xffff) {
408                 wpa_printf(MSG_WARNING, "RADIUS: Too long message (%lu)",
409                            (unsigned long) wpabuf_len(msg->buf));
410                 return -1;
411         }
412         return 0;
413 }
414
415
416 int radius_msg_finish_das_resp(struct radius_msg *msg, const u8 *secret,
417                                size_t secret_len,
418                                const struct radius_hdr *req_hdr)
419 {
420         const u8 *addr[2];
421         size_t len[2];
422         u8 auth[MD5_MAC_LEN];
423         struct radius_attr_hdr *attr;
424
425         os_memset(auth, 0, MD5_MAC_LEN);
426         attr = radius_msg_add_attr(msg, RADIUS_ATTR_MESSAGE_AUTHENTICATOR,
427                                    auth, MD5_MAC_LEN);
428         if (attr == NULL) {
429                 wpa_printf(MSG_WARNING, "Could not add Message-Authenticator");
430                 return -1;
431         }
432
433         msg->hdr->length = htons(wpabuf_len(msg->buf));
434         os_memcpy(msg->hdr->authenticator, req_hdr->authenticator, 16);
435         hmac_md5(secret, secret_len, wpabuf_head(msg->buf),
436                  wpabuf_len(msg->buf), (u8 *) (attr + 1));
437
438         /* ResponseAuth = MD5(Code+ID+Length+RequestAuth+Attributes+Secret) */
439         addr[0] = wpabuf_head_u8(msg->buf);
440         len[0] = wpabuf_len(msg->buf);
441         addr[1] = secret;
442         len[1] = secret_len;
443         if (md5_vector(2, addr, len, msg->hdr->authenticator) < 0)
444                 return -1;
445
446         if (wpabuf_len(msg->buf) > 0xffff) {
447                 wpa_printf(MSG_WARNING, "RADIUS: Too long message (%lu)",
448                            (unsigned long) wpabuf_len(msg->buf));
449                 return -1;
450         }
451         return 0;
452 }
453
454
455 void radius_msg_finish_acct(struct radius_msg *msg, const u8 *secret,
456                             size_t secret_len)
457 {
458         const u8 *addr[2];
459         size_t len[2];
460
461         msg->hdr->length = htons(wpabuf_len(msg->buf));
462         os_memset(msg->hdr->authenticator, 0, MD5_MAC_LEN);
463         addr[0] = wpabuf_head(msg->buf);
464         len[0] = wpabuf_len(msg->buf);
465         addr[1] = secret;
466         len[1] = secret_len;
467         md5_vector(2, addr, len, msg->hdr->authenticator);
468
469         if (wpabuf_len(msg->buf) > 0xffff) {
470                 wpa_printf(MSG_WARNING, "RADIUS: Too long messages (%lu)",
471                            (unsigned long) wpabuf_len(msg->buf));
472         }
473 }
474
475
476 int radius_msg_verify_acct_req(struct radius_msg *msg, const u8 *secret,
477                                size_t secret_len)
478 {
479         const u8 *addr[4];
480         size_t len[4];
481         u8 zero[MD5_MAC_LEN];
482         u8 hash[MD5_MAC_LEN];
483
484         os_memset(zero, 0, sizeof(zero));
485         addr[0] = (u8 *) msg->hdr;
486         len[0] = sizeof(struct radius_hdr) - MD5_MAC_LEN;
487         addr[1] = zero;
488         len[1] = MD5_MAC_LEN;
489         addr[2] = (u8 *) (msg->hdr + 1);
490         len[2] = wpabuf_len(msg->buf) - sizeof(struct radius_hdr);
491         addr[3] = secret;
492         len[3] = secret_len;
493         md5_vector(4, addr, len, hash);
494         return os_memcmp(msg->hdr->authenticator, hash, MD5_MAC_LEN) != 0;
495 }
496
497
498 int radius_msg_verify_das_req(struct radius_msg *msg, const u8 *secret,
499                               size_t secret_len)
500 {
501         const u8 *addr[4];
502         size_t len[4];
503         u8 zero[MD5_MAC_LEN];
504         u8 hash[MD5_MAC_LEN];
505         u8 auth[MD5_MAC_LEN], orig[MD5_MAC_LEN];
506         u8 orig_authenticator[16];
507
508         struct radius_attr_hdr *attr = NULL, *tmp;
509         size_t i;
510
511         os_memset(zero, 0, sizeof(zero));
512         addr[0] = (u8 *) msg->hdr;
513         len[0] = sizeof(struct radius_hdr) - MD5_MAC_LEN;
514         addr[1] = zero;
515         len[1] = MD5_MAC_LEN;
516         addr[2] = (u8 *) (msg->hdr + 1);
517         len[2] = wpabuf_len(msg->buf) - sizeof(struct radius_hdr);
518         addr[3] = secret;
519         len[3] = secret_len;
520         md5_vector(4, addr, len, hash);
521         if (os_memcmp(msg->hdr->authenticator, hash, MD5_MAC_LEN) != 0)
522                 return 1;
523
524         for (i = 0; i < msg->attr_used; i++) {
525                 tmp = radius_get_attr_hdr(msg, i);
526                 if (tmp->type == RADIUS_ATTR_MESSAGE_AUTHENTICATOR) {
527                         if (attr != NULL) {
528                                 wpa_printf(MSG_WARNING, "Multiple "
529                                            "Message-Authenticator attributes "
530                                            "in RADIUS message");
531                                 return 1;
532                         }
533                         attr = tmp;
534                 }
535         }
536
537         if (attr == NULL) {
538                 /* Message-Authenticator is MAY; not required */
539                 return 0;
540         }
541
542         os_memcpy(orig, attr + 1, MD5_MAC_LEN);
543         os_memset(attr + 1, 0, MD5_MAC_LEN);
544         os_memcpy(orig_authenticator, msg->hdr->authenticator,
545                   sizeof(orig_authenticator));
546         os_memset(msg->hdr->authenticator, 0,
547                   sizeof(msg->hdr->authenticator));
548         hmac_md5(secret, secret_len, wpabuf_head(msg->buf),
549                  wpabuf_len(msg->buf), auth);
550         os_memcpy(attr + 1, orig, MD5_MAC_LEN);
551         os_memcpy(msg->hdr->authenticator, orig_authenticator,
552                   sizeof(orig_authenticator));
553
554         return os_memcmp(orig, auth, MD5_MAC_LEN) != 0;
555 }
556
557
558 static int radius_msg_add_attr_to_array(struct radius_msg *msg,
559                                         struct radius_attr_hdr *attr)
560 {
561         if (msg->attr_used >= msg->attr_size) {
562                 size_t *nattr_pos;
563                 int nlen = msg->attr_size * 2;
564
565                 nattr_pos = os_realloc(msg->attr_pos,
566                                        nlen * sizeof(*msg->attr_pos));
567                 if (nattr_pos == NULL)
568                         return -1;
569
570                 msg->attr_pos = nattr_pos;
571                 msg->attr_size = nlen;
572         }
573
574         msg->attr_pos[msg->attr_used++] =
575                 (unsigned char *) attr - wpabuf_head_u8(msg->buf);
576
577         return 0;
578 }
579
580
581 struct radius_attr_hdr *radius_msg_add_attr(struct radius_msg *msg, u8 type,
582                                             const u8 *data, size_t data_len)
583 {
584         size_t buf_needed;
585         struct radius_attr_hdr *attr;
586
587         if (data_len > RADIUS_MAX_ATTR_LEN) {
588                 printf("radius_msg_add_attr: too long attribute (%lu bytes)\n",
589                        (unsigned long) data_len);
590                 return NULL;
591         }
592
593         buf_needed = sizeof(*attr) + data_len;
594
595         if (wpabuf_tailroom(msg->buf) < buf_needed) {
596                 /* allocate more space for message buffer */
597                 if (wpabuf_resize(&msg->buf, buf_needed) < 0)
598                         return NULL;
599                 msg->hdr = wpabuf_mhead(msg->buf);
600         }
601
602         attr = wpabuf_put(msg->buf, sizeof(struct radius_attr_hdr));
603         attr->type = type;
604         attr->length = sizeof(*attr) + data_len;
605         wpabuf_put_data(msg->buf, data, data_len);
606
607         if (radius_msg_add_attr_to_array(msg, attr))
608                 return NULL;
609
610         return attr;
611 }
612
613
614 /**
615  * radius_msg_parse - Parse a RADIUS message
616  * @data: RADIUS message to be parsed
617  * @len: Length of data buffer in octets
618  * Returns: Parsed RADIUS message or %NULL on failure
619  *
620  * This parses a RADIUS message and makes a copy of its data. The caller is
621  * responsible for freeing the returned data with radius_msg_free().
622  */
623 struct radius_msg * radius_msg_parse(const u8 *data, size_t len)
624 {
625         struct radius_msg *msg;
626         struct radius_hdr *hdr;
627         struct radius_attr_hdr *attr;
628         size_t msg_len;
629         unsigned char *pos, *end;
630
631         if (data == NULL || len < sizeof(*hdr))
632                 return NULL;
633
634         hdr = (struct radius_hdr *) data;
635
636         msg_len = ntohs(hdr->length);
637         if (msg_len < sizeof(*hdr) || msg_len > len) {
638                 wpa_printf(MSG_INFO, "RADIUS: Invalid message length");
639                 return NULL;
640         }
641
642         if (msg_len < len) {
643                 wpa_printf(MSG_DEBUG, "RADIUS: Ignored %lu extra bytes after "
644                            "RADIUS message", (unsigned long) len - msg_len);
645         }
646
647         msg = os_zalloc(sizeof(*msg));
648         if (msg == NULL)
649                 return NULL;
650
651         msg->buf = wpabuf_alloc_copy(data, msg_len);
652         if (msg->buf == NULL || radius_msg_initialize(msg)) {
653                 radius_msg_free(msg);
654                 return NULL;
655         }
656         msg->hdr = wpabuf_mhead(msg->buf);
657
658         /* parse attributes */
659         pos = wpabuf_mhead_u8(msg->buf) + sizeof(struct radius_hdr);
660         end = wpabuf_mhead_u8(msg->buf) + wpabuf_len(msg->buf);
661         while (pos < end) {
662                 if ((size_t) (end - pos) < sizeof(*attr))
663                         goto fail;
664
665                 attr = (struct radius_attr_hdr *) pos;
666
667                 if (pos + attr->length > end || attr->length < sizeof(*attr))
668                         goto fail;
669
670                 /* TODO: check that attr->length is suitable for attr->type */
671
672                 if (radius_msg_add_attr_to_array(msg, attr))
673                         goto fail;
674
675                 pos += attr->length;
676         }
677
678         return msg;
679
680  fail:
681         radius_msg_free(msg);
682         return NULL;
683 }
684
685
686 int radius_msg_add_eap(struct radius_msg *msg, const u8 *data, size_t data_len)
687 {
688         const u8 *pos = data;
689         size_t left = data_len;
690
691         while (left > 0) {
692                 int len;
693                 if (left > RADIUS_MAX_ATTR_LEN)
694                         len = RADIUS_MAX_ATTR_LEN;
695                 else
696                         len = left;
697
698                 if (!radius_msg_add_attr(msg, RADIUS_ATTR_EAP_MESSAGE,
699                                          pos, len))
700                         return 0;
701
702                 pos += len;
703                 left -= len;
704         }
705
706         return 1;
707 }
708
709
710 u8 *radius_msg_get_eap(struct radius_msg *msg, size_t *eap_len)
711 {
712         u8 *eap, *pos;
713         size_t len, i;
714         struct radius_attr_hdr *attr;
715
716         if (msg == NULL)
717                 return NULL;
718
719         len = 0;
720         for (i = 0; i < msg->attr_used; i++) {
721                 attr = radius_get_attr_hdr(msg, i);
722                 if (attr->type == RADIUS_ATTR_EAP_MESSAGE)
723                         len += attr->length - sizeof(struct radius_attr_hdr);
724         }
725
726         if (len == 0)
727                 return NULL;
728
729         eap = os_malloc(len);
730         if (eap == NULL)
731                 return NULL;
732
733         pos = eap;
734         for (i = 0; i < msg->attr_used; i++) {
735                 attr = radius_get_attr_hdr(msg, i);
736                 if (attr->type == RADIUS_ATTR_EAP_MESSAGE) {
737                         int flen = attr->length - sizeof(*attr);
738                         os_memcpy(pos, attr + 1, flen);
739                         pos += flen;
740                 }
741         }
742
743         if (eap_len)
744                 *eap_len = len;
745
746         return eap;
747 }
748
749
750 int radius_msg_verify_msg_auth(struct radius_msg *msg, const u8 *secret,
751                                size_t secret_len, const u8 *req_auth)
752 {
753         u8 auth[MD5_MAC_LEN], orig[MD5_MAC_LEN];
754         u8 orig_authenticator[16];
755         struct radius_attr_hdr *attr = NULL, *tmp;
756         size_t i;
757
758         for (i = 0; i < msg->attr_used; i++) {
759                 tmp = radius_get_attr_hdr(msg, i);
760                 if (tmp->type == RADIUS_ATTR_MESSAGE_AUTHENTICATOR) {
761                         if (attr != NULL) {
762                                 printf("Multiple Message-Authenticator "
763                                        "attributes in RADIUS message\n");
764                                 return 1;
765                         }
766                         attr = tmp;
767                 }
768         }
769
770         if (attr == NULL) {
771                 printf("No Message-Authenticator attribute found\n");
772                 return 1;
773         }
774
775         os_memcpy(orig, attr + 1, MD5_MAC_LEN);
776         os_memset(attr + 1, 0, MD5_MAC_LEN);
777         if (req_auth) {
778                 os_memcpy(orig_authenticator, msg->hdr->authenticator,
779                           sizeof(orig_authenticator));
780                 os_memcpy(msg->hdr->authenticator, req_auth,
781                           sizeof(msg->hdr->authenticator));
782         }
783         hmac_md5(secret, secret_len, wpabuf_head(msg->buf),
784                  wpabuf_len(msg->buf), auth);
785         os_memcpy(attr + 1, orig, MD5_MAC_LEN);
786         if (req_auth) {
787                 os_memcpy(msg->hdr->authenticator, orig_authenticator,
788                           sizeof(orig_authenticator));
789         }
790
791         if (os_memcmp(orig, auth, MD5_MAC_LEN) != 0) {
792                 printf("Invalid Message-Authenticator!\n");
793                 return 1;
794         }
795
796         return 0;
797 }
798
799
800 int radius_msg_verify(struct radius_msg *msg, const u8 *secret,
801                       size_t secret_len, struct radius_msg *sent_msg, int auth)
802 {
803         const u8 *addr[4];
804         size_t len[4];
805         u8 hash[MD5_MAC_LEN];
806
807         if (sent_msg == NULL) {
808                 printf("No matching Access-Request message found\n");
809                 return 1;
810         }
811
812         if (auth &&
813             radius_msg_verify_msg_auth(msg, secret, secret_len,
814                                        sent_msg->hdr->authenticator)) {
815                 return 1;
816         }
817
818         /* ResponseAuth = MD5(Code+ID+Length+RequestAuth+Attributes+Secret) */
819         addr[0] = (u8 *) msg->hdr;
820         len[0] = 1 + 1 + 2;
821         addr[1] = sent_msg->hdr->authenticator;
822         len[1] = MD5_MAC_LEN;
823         addr[2] = wpabuf_head_u8(msg->buf) + sizeof(struct radius_hdr);
824         len[2] = wpabuf_len(msg->buf) - sizeof(struct radius_hdr);
825         addr[3] = secret;
826         len[3] = secret_len;
827         md5_vector(4, addr, len, hash);
828         if (os_memcmp(hash, msg->hdr->authenticator, MD5_MAC_LEN) != 0) {
829                 printf("Response Authenticator invalid!\n");
830                 return 1;
831         }
832
833         return 0;
834 }
835
836
837 int radius_msg_copy_attr(struct radius_msg *dst, struct radius_msg *src,
838                          u8 type)
839 {
840         struct radius_attr_hdr *attr;
841         size_t i;
842         int count = 0;
843
844         for (i = 0; i < src->attr_used; i++) {
845                 attr = radius_get_attr_hdr(src, i);
846                 if (attr->type == type) {
847                         if (!radius_msg_add_attr(dst, type, (u8 *) (attr + 1),
848                                                  attr->length - sizeof(*attr)))
849                                 return -1;
850                         count++;
851                 }
852         }
853
854         return count;
855 }
856
857
858 /* Create Request Authenticator. The value should be unique over the lifetime
859  * of the shared secret between authenticator and authentication server.
860  * Use one-way MD5 hash calculated from current timestamp and some data given
861  * by the caller. */
862 void radius_msg_make_authenticator(struct radius_msg *msg,
863                                    const u8 *data, size_t len)
864 {
865         struct os_time tv;
866         long int l;
867         const u8 *addr[3];
868         size_t elen[3];
869
870         os_get_time(&tv);
871         l = os_random();
872         addr[0] = (u8 *) &tv;
873         elen[0] = sizeof(tv);
874         addr[1] = data;
875         elen[1] = len;
876         addr[2] = (u8 *) &l;
877         elen[2] = sizeof(l);
878         md5_vector(3, addr, elen, msg->hdr->authenticator);
879 }
880
881
882 /* Get Vendor-specific RADIUS Attribute from a parsed RADIUS message.
883  * Returns the Attribute payload and sets alen to indicate the length of the
884  * payload if a vendor attribute with subtype is found, otherwise returns NULL.
885  * The returned payload is allocated with os_malloc() and caller must free it
886  * by calling os_free().
887  */
888 static u8 *radius_msg_get_vendor_attr(struct radius_msg *msg, u32 vendor,
889                                       u8 subtype, size_t *alen)
890 {
891         u8 *data, *pos;
892         size_t i, len;
893
894         if (msg == NULL)
895                 return NULL;
896
897         for (i = 0; i < msg->attr_used; i++) {
898                 struct radius_attr_hdr *attr = radius_get_attr_hdr(msg, i);
899                 size_t left;
900                 u32 vendor_id;
901                 struct radius_attr_vendor *vhdr;
902
903                 if (attr->type != RADIUS_ATTR_VENDOR_SPECIFIC)
904                         continue;
905
906                 left = attr->length - sizeof(*attr);
907                 if (left < 4)
908                         continue;
909
910                 pos = (u8 *) (attr + 1);
911
912                 os_memcpy(&vendor_id, pos, 4);
913                 pos += 4;
914                 left -= 4;
915
916                 if (ntohl(vendor_id) != vendor)
917                         continue;
918
919                 while (left >= sizeof(*vhdr)) {
920                         vhdr = (struct radius_attr_vendor *) pos;
921                         if (vhdr->vendor_length > left ||
922                             vhdr->vendor_length < sizeof(*vhdr)) {
923                                 left = 0;
924                                 break;
925                         }
926                         if (vhdr->vendor_type != subtype) {
927                                 pos += vhdr->vendor_length;
928                                 left -= vhdr->vendor_length;
929                                 continue;
930                         }
931
932                         len = vhdr->vendor_length - sizeof(*vhdr);
933                         data = os_malloc(len);
934                         if (data == NULL)
935                                 return NULL;
936                         os_memcpy(data, pos + sizeof(*vhdr), len);
937                         if (alen)
938                                 *alen = len;
939                         return data;
940                 }
941         }
942
943         return NULL;
944 }
945
946
947 static u8 * decrypt_ms_key(const u8 *key, size_t len,
948                            const u8 *req_authenticator,
949                            const u8 *secret, size_t secret_len, size_t *reslen)
950 {
951         u8 *plain, *ppos, *res;
952         const u8 *pos;
953         size_t left, plen;
954         u8 hash[MD5_MAC_LEN];
955         int i, first = 1;
956         const u8 *addr[3];
957         size_t elen[3];
958
959         /* key: 16-bit salt followed by encrypted key info */
960
961         if (len < 2 + 16)
962                 return NULL;
963
964         pos = key + 2;
965         left = len - 2;
966         if (left % 16) {
967                 printf("Invalid ms key len %lu\n", (unsigned long) left);
968                 return NULL;
969         }
970
971         plen = left;
972         ppos = plain = os_malloc(plen);
973         if (plain == NULL)
974                 return NULL;
975         plain[0] = 0;
976
977         while (left > 0) {
978                 /* b(1) = MD5(Secret + Request-Authenticator + Salt)
979                  * b(i) = MD5(Secret + c(i - 1)) for i > 1 */
980
981                 addr[0] = secret;
982                 elen[0] = secret_len;
983                 if (first) {
984                         addr[1] = req_authenticator;
985                         elen[1] = MD5_MAC_LEN;
986                         addr[2] = key;
987                         elen[2] = 2; /* Salt */
988                 } else {
989                         addr[1] = pos - MD5_MAC_LEN;
990                         elen[1] = MD5_MAC_LEN;
991                 }
992                 md5_vector(first ? 3 : 2, addr, elen, hash);
993                 first = 0;
994
995                 for (i = 0; i < MD5_MAC_LEN; i++)
996                         *ppos++ = *pos++ ^ hash[i];
997                 left -= MD5_MAC_LEN;
998         }
999
1000         if (plain[0] == 0 || plain[0] > plen - 1) {
1001                 printf("Failed to decrypt MPPE key\n");
1002                 os_free(plain);
1003                 return NULL;
1004         }
1005
1006         res = os_malloc(plain[0]);
1007         if (res == NULL) {
1008                 os_free(plain);
1009                 return NULL;
1010         }
1011         os_memcpy(res, plain + 1, plain[0]);
1012         if (reslen)
1013                 *reslen = plain[0];
1014         os_free(plain);
1015         return res;
1016 }
1017
1018
1019 static void encrypt_ms_key(const u8 *key, size_t key_len, u16 salt,
1020                            const u8 *req_authenticator,
1021                            const u8 *secret, size_t secret_len,
1022                            u8 *ebuf, size_t *elen)
1023 {
1024         int i, len, first = 1;
1025         u8 hash[MD5_MAC_LEN], saltbuf[2], *pos;
1026         const u8 *addr[3];
1027         size_t _len[3];
1028
1029         WPA_PUT_BE16(saltbuf, salt);
1030
1031         len = 1 + key_len;
1032         if (len & 0x0f) {
1033                 len = (len & 0xf0) + 16;
1034         }
1035         os_memset(ebuf, 0, len);
1036         ebuf[0] = key_len;
1037         os_memcpy(ebuf + 1, key, key_len);
1038
1039         *elen = len;
1040
1041         pos = ebuf;
1042         while (len > 0) {
1043                 /* b(1) = MD5(Secret + Request-Authenticator + Salt)
1044                  * b(i) = MD5(Secret + c(i - 1)) for i > 1 */
1045                 addr[0] = secret;
1046                 _len[0] = secret_len;
1047                 if (first) {
1048                         addr[1] = req_authenticator;
1049                         _len[1] = MD5_MAC_LEN;
1050                         addr[2] = saltbuf;
1051                         _len[2] = sizeof(saltbuf);
1052                 } else {
1053                         addr[1] = pos - MD5_MAC_LEN;
1054                         _len[1] = MD5_MAC_LEN;
1055                 }
1056                 md5_vector(first ? 3 : 2, addr, _len, hash);
1057                 first = 0;
1058
1059                 for (i = 0; i < MD5_MAC_LEN; i++)
1060                         *pos++ ^= hash[i];
1061
1062                 len -= MD5_MAC_LEN;
1063         }
1064 }
1065
1066
1067 struct radius_ms_mppe_keys *
1068 radius_msg_get_ms_keys(struct radius_msg *msg, struct radius_msg *sent_msg,
1069                        const u8 *secret, size_t secret_len)
1070 {
1071         u8 *key;
1072         size_t keylen;
1073         struct radius_ms_mppe_keys *keys;
1074
1075         if (msg == NULL || sent_msg == NULL)
1076                 return NULL;
1077
1078         keys = os_zalloc(sizeof(*keys));
1079         if (keys == NULL)
1080                 return NULL;
1081
1082         key = radius_msg_get_vendor_attr(msg, RADIUS_VENDOR_ID_MICROSOFT,
1083                                          RADIUS_VENDOR_ATTR_MS_MPPE_SEND_KEY,
1084                                          &keylen);
1085         if (key) {
1086                 keys->send = decrypt_ms_key(key, keylen,
1087                                             sent_msg->hdr->authenticator,
1088                                             secret, secret_len,
1089                                             &keys->send_len);
1090                 os_free(key);
1091         }
1092
1093         key = radius_msg_get_vendor_attr(msg, RADIUS_VENDOR_ID_MICROSOFT,
1094                                          RADIUS_VENDOR_ATTR_MS_MPPE_RECV_KEY,
1095                                          &keylen);
1096         if (key) {
1097                 keys->recv = decrypt_ms_key(key, keylen,
1098                                             sent_msg->hdr->authenticator,
1099                                             secret, secret_len,
1100                                             &keys->recv_len);
1101                 os_free(key);
1102         }
1103
1104         return keys;
1105 }
1106
1107
1108 struct radius_ms_mppe_keys *
1109 radius_msg_get_cisco_keys(struct radius_msg *msg, struct radius_msg *sent_msg,
1110                           const u8 *secret, size_t secret_len)
1111 {
1112         u8 *key;
1113         size_t keylen;
1114         struct radius_ms_mppe_keys *keys;
1115
1116         if (msg == NULL || sent_msg == NULL)
1117                 return NULL;
1118
1119         keys = os_zalloc(sizeof(*keys));
1120         if (keys == NULL)
1121                 return NULL;
1122
1123         key = radius_msg_get_vendor_attr(msg, RADIUS_VENDOR_ID_CISCO,
1124                                          RADIUS_CISCO_AV_PAIR, &keylen);
1125         if (key && keylen == 51 &&
1126             os_memcmp(key, "leap:session-key=", 17) == 0) {
1127                 keys->recv = decrypt_ms_key(key + 17, keylen - 17,
1128                                             sent_msg->hdr->authenticator,
1129                                             secret, secret_len,
1130                                             &keys->recv_len);
1131         }
1132         os_free(key);
1133
1134         return keys;
1135 }
1136
1137
1138 int radius_msg_add_mppe_keys(struct radius_msg *msg,
1139                              const u8 *req_authenticator,
1140                              const u8 *secret, size_t secret_len,
1141                              const u8 *send_key, size_t send_key_len,
1142                              const u8 *recv_key, size_t recv_key_len)
1143 {
1144         struct radius_attr_hdr *attr;
1145         u32 vendor_id = htonl(RADIUS_VENDOR_ID_MICROSOFT);
1146         u8 *buf;
1147         struct radius_attr_vendor *vhdr;
1148         u8 *pos;
1149         size_t elen;
1150         int hlen;
1151         u16 salt;
1152
1153         hlen = sizeof(vendor_id) + sizeof(*vhdr) + 2;
1154
1155         /* MS-MPPE-Send-Key */
1156         buf = os_malloc(hlen + send_key_len + 16);
1157         if (buf == NULL) {
1158                 return 0;
1159         }
1160         pos = buf;
1161         os_memcpy(pos, &vendor_id, sizeof(vendor_id));
1162         pos += sizeof(vendor_id);
1163         vhdr = (struct radius_attr_vendor *) pos;
1164         vhdr->vendor_type = RADIUS_VENDOR_ATTR_MS_MPPE_SEND_KEY;
1165         pos = (u8 *) (vhdr + 1);
1166         salt = os_random() | 0x8000;
1167         WPA_PUT_BE16(pos, salt);
1168         pos += 2;
1169         encrypt_ms_key(send_key, send_key_len, salt, req_authenticator, secret,
1170                        secret_len, pos, &elen);
1171         vhdr->vendor_length = hlen + elen - sizeof(vendor_id);
1172
1173         attr = radius_msg_add_attr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
1174                                    buf, hlen + elen);
1175         os_free(buf);
1176         if (attr == NULL) {
1177                 return 0;
1178         }
1179
1180         /* MS-MPPE-Recv-Key */
1181         buf = os_malloc(hlen + send_key_len + 16);
1182         if (buf == NULL) {
1183                 return 0;
1184         }
1185         pos = buf;
1186         os_memcpy(pos, &vendor_id, sizeof(vendor_id));
1187         pos += sizeof(vendor_id);
1188         vhdr = (struct radius_attr_vendor *) pos;
1189         vhdr->vendor_type = RADIUS_VENDOR_ATTR_MS_MPPE_RECV_KEY;
1190         pos = (u8 *) (vhdr + 1);
1191         salt ^= 1;
1192         WPA_PUT_BE16(pos, salt);
1193         pos += 2;
1194         encrypt_ms_key(recv_key, recv_key_len, salt, req_authenticator, secret,
1195                        secret_len, pos, &elen);
1196         vhdr->vendor_length = hlen + elen - sizeof(vendor_id);
1197
1198         attr = radius_msg_add_attr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
1199                                    buf, hlen + elen);
1200         os_free(buf);
1201         if (attr == NULL) {
1202                 return 0;
1203         }
1204
1205         return 1;
1206 }
1207
1208
1209 /* Add User-Password attribute to a RADIUS message and encrypt it as specified
1210  * in RFC 2865, Chap. 5.2 */
1211 struct radius_attr_hdr *
1212 radius_msg_add_attr_user_password(struct radius_msg *msg,
1213                                   const u8 *data, size_t data_len,
1214                                   const u8 *secret, size_t secret_len)
1215 {
1216         u8 buf[128];
1217         size_t padlen, i, buf_len, pos;
1218         const u8 *addr[2];
1219         size_t len[2];
1220         u8 hash[16];
1221
1222         if (data_len > 128)
1223                 return NULL;
1224
1225         os_memcpy(buf, data, data_len);
1226         buf_len = data_len;
1227
1228         padlen = data_len % 16;
1229         if (padlen && data_len < sizeof(buf)) {
1230                 padlen = 16 - padlen;
1231                 os_memset(buf + data_len, 0, padlen);
1232                 buf_len += padlen;
1233         }
1234
1235         addr[0] = secret;
1236         len[0] = secret_len;
1237         addr[1] = msg->hdr->authenticator;
1238         len[1] = 16;
1239         md5_vector(2, addr, len, hash);
1240
1241         for (i = 0; i < 16; i++)
1242                 buf[i] ^= hash[i];
1243         pos = 16;
1244
1245         while (pos < buf_len) {
1246                 addr[0] = secret;
1247                 len[0] = secret_len;
1248                 addr[1] = &buf[pos - 16];
1249                 len[1] = 16;
1250                 md5_vector(2, addr, len, hash);
1251
1252                 for (i = 0; i < 16; i++)
1253                         buf[pos + i] ^= hash[i];
1254
1255                 pos += 16;
1256         }
1257
1258         return radius_msg_add_attr(msg, RADIUS_ATTR_USER_PASSWORD,
1259                                    buf, buf_len);
1260 }
1261
1262
1263 int radius_msg_get_attr(struct radius_msg *msg, u8 type, u8 *buf, size_t len)
1264 {
1265         struct radius_attr_hdr *attr = NULL, *tmp;
1266         size_t i, dlen;
1267
1268         for (i = 0; i < msg->attr_used; i++) {
1269                 tmp = radius_get_attr_hdr(msg, i);
1270                 if (tmp->type == type) {
1271                         attr = tmp;
1272                         break;
1273                 }
1274         }
1275
1276         if (!attr)
1277                 return -1;
1278
1279         dlen = attr->length - sizeof(*attr);
1280         if (buf)
1281                 os_memcpy(buf, (attr + 1), dlen > len ? len : dlen);
1282         return dlen;
1283 }
1284
1285
1286 int radius_msg_get_attr_ptr(struct radius_msg *msg, u8 type, u8 **buf,
1287                             size_t *len, const u8 *start)
1288 {
1289         size_t i;
1290         struct radius_attr_hdr *attr = NULL, *tmp;
1291
1292         for (i = 0; i < msg->attr_used; i++) {
1293                 tmp = radius_get_attr_hdr(msg, i);
1294                 if (tmp->type == type &&
1295                     (start == NULL || (u8 *) tmp > start)) {
1296                         attr = tmp;
1297                         break;
1298                 }
1299         }
1300
1301         if (!attr)
1302                 return -1;
1303
1304         *buf = (u8 *) (attr + 1);
1305         *len = attr->length - sizeof(*attr);
1306         return 0;
1307 }
1308
1309
1310 int radius_msg_count_attr(struct radius_msg *msg, u8 type, int min_len)
1311 {
1312         size_t i;
1313         int count;
1314
1315         for (count = 0, i = 0; i < msg->attr_used; i++) {
1316                 struct radius_attr_hdr *attr = radius_get_attr_hdr(msg, i);
1317                 if (attr->type == type &&
1318                     attr->length >= sizeof(struct radius_attr_hdr) + min_len)
1319                         count++;
1320         }
1321
1322         return count;
1323 }
1324
1325
1326 struct radius_tunnel_attrs {
1327         int tag_used;
1328         int type; /* Tunnel-Type */
1329         int medium_type; /* Tunnel-Medium-Type */
1330         int vlanid;
1331 };
1332
1333
1334 /**
1335  * radius_msg_get_vlanid - Parse RADIUS attributes for VLAN tunnel information
1336  * @msg: RADIUS message
1337  * Returns: VLAN ID for the first tunnel configuration of -1 if none is found
1338  */
1339 int radius_msg_get_vlanid(struct radius_msg *msg)
1340 {
1341         struct radius_tunnel_attrs tunnel[RADIUS_TUNNEL_TAGS], *tun;
1342         size_t i;
1343         struct radius_attr_hdr *attr = NULL;
1344         const u8 *data;
1345         char buf[10];
1346         size_t dlen;
1347
1348         os_memset(&tunnel, 0, sizeof(tunnel));
1349
1350         for (i = 0; i < msg->attr_used; i++) {
1351                 attr = radius_get_attr_hdr(msg, i);
1352                 data = (const u8 *) (attr + 1);
1353                 dlen = attr->length - sizeof(*attr);
1354                 if (attr->length < 3)
1355                         continue;
1356                 if (data[0] >= RADIUS_TUNNEL_TAGS)
1357                         tun = &tunnel[0];
1358                 else
1359                         tun = &tunnel[data[0]];
1360
1361                 switch (attr->type) {
1362                 case RADIUS_ATTR_TUNNEL_TYPE:
1363                         if (attr->length != 6)
1364                                 break;
1365                         tun->tag_used++;
1366                         tun->type = WPA_GET_BE24(data + 1);
1367                         break;
1368                 case RADIUS_ATTR_TUNNEL_MEDIUM_TYPE:
1369                         if (attr->length != 6)
1370                                 break;
1371                         tun->tag_used++;
1372                         tun->medium_type = WPA_GET_BE24(data + 1);
1373                         break;
1374                 case RADIUS_ATTR_TUNNEL_PRIVATE_GROUP_ID:
1375                         if (data[0] < RADIUS_TUNNEL_TAGS) {
1376                                 data++;
1377                                 dlen--;
1378                         }
1379                         if (dlen >= sizeof(buf))
1380                                 break;
1381                         os_memcpy(buf, data, dlen);
1382                         buf[dlen] = '\0';
1383                         tun->tag_used++;
1384                         tun->vlanid = atoi(buf);
1385                         break;
1386                 }
1387         }
1388
1389         for (i = 0; i < RADIUS_TUNNEL_TAGS; i++) {
1390                 tun = &tunnel[i];
1391                 if (tun->tag_used &&
1392                     tun->type == RADIUS_TUNNEL_TYPE_VLAN &&
1393                     tun->medium_type == RADIUS_TUNNEL_MEDIUM_TYPE_802 &&
1394                     tun->vlanid > 0)
1395                         return tun->vlanid;
1396         }
1397
1398         return -1;
1399 }
1400
1401
1402 /**
1403  * radius_msg_get_tunnel_password - Parse RADIUS attribute Tunnel-Password
1404  * @msg: Received RADIUS message
1405  * @keylen: Length of returned password
1406  * @secret: RADIUS shared secret
1407  * @secret_len: Length of secret
1408  * @sent_msg: Sent RADIUS message
1409  * Returns: pointer to password (free with os_free) or %NULL
1410  */
1411 char * radius_msg_get_tunnel_password(struct radius_msg *msg, int *keylen,
1412                                       const u8 *secret, size_t secret_len,
1413                                       struct radius_msg *sent_msg)
1414 {
1415         u8 *buf = NULL;
1416         size_t buflen;
1417         const u8 *salt;
1418         u8 *str;
1419         const u8 *addr[3];
1420         size_t len[3];
1421         u8 hash[16];
1422         u8 *pos;
1423         size_t i;
1424         struct radius_attr_hdr *attr;
1425         const u8 *data;
1426         size_t dlen;
1427         const u8 *fdata = NULL; /* points to found item */
1428         size_t fdlen = -1;
1429         char *ret = NULL;
1430
1431         /* find attribute with lowest tag and check it */
1432         for (i = 0; i < msg->attr_used; i++) {
1433                 attr = radius_get_attr_hdr(msg, i);
1434                 if (attr == NULL ||
1435                     attr->type != RADIUS_ATTR_TUNNEL_PASSWORD) {
1436                         continue;
1437                 }
1438                 if (attr->length <= 5)
1439                         continue;
1440                 data = (const u8 *) (attr + 1);
1441                 dlen = attr->length - sizeof(*attr);
1442                 if (dlen <= 3 || dlen % 16 != 3)
1443                         continue;
1444                 if (fdata != NULL && fdata[0] <= data[0])
1445                         continue;
1446
1447                 fdata = data;
1448                 fdlen = dlen;
1449         }
1450         if (fdata == NULL)
1451                 goto out;
1452
1453         /* alloc writable memory for decryption */
1454         buf = os_malloc(fdlen);
1455         if (buf == NULL)
1456                 goto out;
1457         os_memcpy(buf, fdata, fdlen);
1458         buflen = fdlen;
1459
1460         /* init pointers */
1461         salt = buf + 1;
1462         str = buf + 3;
1463
1464         /* decrypt blocks */
1465         pos = buf + buflen - 16; /* last block */
1466         while (pos >= str + 16) { /* all but the first block */
1467                 addr[0] = secret;
1468                 len[0] = secret_len;
1469                 addr[1] = pos - 16;
1470                 len[1] = 16;
1471                 md5_vector(2, addr, len, hash);
1472
1473                 for (i = 0; i < 16; i++)
1474                         pos[i] ^= hash[i];
1475
1476                 pos -= 16;
1477         }
1478
1479         /* decrypt first block */
1480         if (str != pos)
1481                 goto out;
1482         addr[0] = secret;
1483         len[0] = secret_len;
1484         addr[1] = sent_msg->hdr->authenticator;
1485         len[1] = 16;
1486         addr[2] = salt;
1487         len[2] = 2;
1488         md5_vector(3, addr, len, hash);
1489
1490         for (i = 0; i < 16; i++)
1491                 pos[i] ^= hash[i];
1492
1493         /* derive plaintext length from first subfield */
1494         *keylen = (unsigned char) str[0];
1495         if ((u8 *) (str + *keylen) >= (u8 *) (buf + buflen)) {
1496                 /* decryption error - invalid key length */
1497                 goto out;
1498         }
1499         if (*keylen == 0) {
1500                 /* empty password */
1501                 goto out;
1502         }
1503
1504         /* copy passphrase into new buffer */
1505         ret = os_malloc(*keylen);
1506         if (ret)
1507                 os_memcpy(ret, str + 1, *keylen);
1508
1509 out:
1510         /* return new buffer */
1511         os_free(buf);
1512         return ret;
1513 }
1514
1515
1516 void radius_free_class(struct radius_class_data *c)
1517 {
1518         size_t i;
1519         if (c == NULL)
1520                 return;
1521         for (i = 0; i < c->count; i++)
1522                 os_free(c->attr[i].data);
1523         os_free(c->attr);
1524         c->attr = NULL;
1525         c->count = 0;
1526 }
1527
1528
1529 int radius_copy_class(struct radius_class_data *dst,
1530                       const struct radius_class_data *src)
1531 {
1532         size_t i;
1533
1534         if (src->attr == NULL)
1535                 return 0;
1536
1537         dst->attr = os_zalloc(src->count * sizeof(struct radius_attr_data));
1538         if (dst->attr == NULL)
1539                 return -1;
1540
1541         dst->count = 0;
1542
1543         for (i = 0; i < src->count; i++) {
1544                 dst->attr[i].data = os_malloc(src->attr[i].len);
1545                 if (dst->attr[i].data == NULL)
1546                         break;
1547                 dst->count++;
1548                 os_memcpy(dst->attr[i].data, src->attr[i].data,
1549                           src->attr[i].len);
1550                 dst->attr[i].len = src->attr[i].len;
1551         }
1552
1553         return 0;
1554 }
1555
1556
1557 u8 radius_msg_find_unlisted_attr(struct radius_msg *msg, u8 *attrs)
1558 {
1559         size_t i, j;
1560         struct radius_attr_hdr *attr;
1561
1562         for (i = 0; i < msg->attr_used; i++) {
1563                 attr = radius_get_attr_hdr(msg, i);
1564
1565                 for (j = 0; attrs[j]; j++) {
1566                         if (attr->type == attrs[j])
1567                                 break;
1568                 }
1569
1570                 if (attrs[j] == 0)
1571                         return attr->type; /* unlisted attr */
1572         }
1573
1574         return 0;
1575 }