RADIUS: Fix a possible memory leak on an error path
[mech_eap.git] / src / radius / radius.c
1 /*
2  * RADIUS message processing
3  * Copyright (c) 2002-2009, 2011-2015, 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 = os_calloc(RADIUS_DEFAULT_ATTR_COUNT,
82                                   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 const 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_SERVICE_TYPE, "Service-Type", RADIUS_ATTR_INT32 },
177         { RADIUS_ATTR_FRAMED_IP_ADDRESS, "Framed-IP-Address", RADIUS_ATTR_IP },
178         { RADIUS_ATTR_FRAMED_MTU, "Framed-MTU", RADIUS_ATTR_INT32 },
179         { RADIUS_ATTR_REPLY_MESSAGE, "Reply-Message", RADIUS_ATTR_TEXT },
180         { RADIUS_ATTR_STATE, "State", RADIUS_ATTR_UNDIST },
181         { RADIUS_ATTR_CLASS, "Class", RADIUS_ATTR_UNDIST },
182         { RADIUS_ATTR_VENDOR_SPECIFIC, "Vendor-Specific", RADIUS_ATTR_UNDIST },
183         { RADIUS_ATTR_SESSION_TIMEOUT, "Session-Timeout", RADIUS_ATTR_INT32 },
184         { RADIUS_ATTR_IDLE_TIMEOUT, "Idle-Timeout", RADIUS_ATTR_INT32 },
185         { RADIUS_ATTR_TERMINATION_ACTION, "Termination-Action",
186           RADIUS_ATTR_INT32 },
187         { RADIUS_ATTR_CALLED_STATION_ID, "Called-Station-Id",
188           RADIUS_ATTR_TEXT },
189         { RADIUS_ATTR_CALLING_STATION_ID, "Calling-Station-Id",
190           RADIUS_ATTR_TEXT },
191         { RADIUS_ATTR_NAS_IDENTIFIER, "NAS-Identifier", RADIUS_ATTR_TEXT },
192         { RADIUS_ATTR_PROXY_STATE, "Proxy-State", RADIUS_ATTR_UNDIST },
193         { RADIUS_ATTR_ACCT_STATUS_TYPE, "Acct-Status-Type",
194           RADIUS_ATTR_INT32 },
195         { RADIUS_ATTR_ACCT_DELAY_TIME, "Acct-Delay-Time", RADIUS_ATTR_INT32 },
196         { RADIUS_ATTR_ACCT_INPUT_OCTETS, "Acct-Input-Octets",
197           RADIUS_ATTR_INT32 },
198         { RADIUS_ATTR_ACCT_OUTPUT_OCTETS, "Acct-Output-Octets",
199           RADIUS_ATTR_INT32 },
200         { RADIUS_ATTR_ACCT_SESSION_ID, "Acct-Session-Id", RADIUS_ATTR_TEXT },
201         { RADIUS_ATTR_ACCT_AUTHENTIC, "Acct-Authentic", RADIUS_ATTR_INT32 },
202         { RADIUS_ATTR_ACCT_SESSION_TIME, "Acct-Session-Time",
203           RADIUS_ATTR_INT32 },
204         { RADIUS_ATTR_ACCT_INPUT_PACKETS, "Acct-Input-Packets",
205           RADIUS_ATTR_INT32 },
206         { RADIUS_ATTR_ACCT_OUTPUT_PACKETS, "Acct-Output-Packets",
207           RADIUS_ATTR_INT32 },
208         { RADIUS_ATTR_ACCT_TERMINATE_CAUSE, "Acct-Terminate-Cause",
209           RADIUS_ATTR_INT32 },
210         { RADIUS_ATTR_ACCT_MULTI_SESSION_ID, "Acct-Multi-Session-Id",
211           RADIUS_ATTR_TEXT },
212         { RADIUS_ATTR_ACCT_LINK_COUNT, "Acct-Link-Count", RADIUS_ATTR_INT32 },
213         { RADIUS_ATTR_ACCT_INPUT_GIGAWORDS, "Acct-Input-Gigawords", 
214           RADIUS_ATTR_INT32 },
215         { RADIUS_ATTR_ACCT_OUTPUT_GIGAWORDS, "Acct-Output-Gigawords",
216           RADIUS_ATTR_INT32 },
217         { RADIUS_ATTR_EVENT_TIMESTAMP, "Event-Timestamp",
218           RADIUS_ATTR_INT32 },
219         { RADIUS_ATTR_EGRESS_VLANID, "EGRESS-VLANID", RADIUS_ATTR_HEXDUMP },
220         { RADIUS_ATTR_NAS_PORT_TYPE, "NAS-Port-Type", RADIUS_ATTR_INT32 },
221         { RADIUS_ATTR_TUNNEL_TYPE, "Tunnel-Type", RADIUS_ATTR_HEXDUMP },
222         { RADIUS_ATTR_TUNNEL_MEDIUM_TYPE, "Tunnel-Medium-Type",
223           RADIUS_ATTR_HEXDUMP },
224         { RADIUS_ATTR_TUNNEL_PASSWORD, "Tunnel-Password",
225           RADIUS_ATTR_UNDIST },
226         { RADIUS_ATTR_CONNECT_INFO, "Connect-Info", RADIUS_ATTR_TEXT },
227         { RADIUS_ATTR_EAP_MESSAGE, "EAP-Message", RADIUS_ATTR_UNDIST },
228         { RADIUS_ATTR_MESSAGE_AUTHENTICATOR, "Message-Authenticator",
229           RADIUS_ATTR_UNDIST },
230         { RADIUS_ATTR_TUNNEL_PRIVATE_GROUP_ID, "Tunnel-Private-Group-Id",
231           RADIUS_ATTR_HEXDUMP },
232         { RADIUS_ATTR_ACCT_INTERIM_INTERVAL, "Acct-Interim-Interval",
233           RADIUS_ATTR_INT32 },
234         { RADIUS_ATTR_CHARGEABLE_USER_IDENTITY, "Chargeable-User-Identity",
235           RADIUS_ATTR_TEXT },
236         { RADIUS_ATTR_NAS_IPV6_ADDRESS, "NAS-IPv6-Address", RADIUS_ATTR_IPV6 },
237         { RADIUS_ATTR_ERROR_CAUSE, "Error-Cause", RADIUS_ATTR_INT32 },
238         { RADIUS_ATTR_EAP_KEY_NAME, "EAP-Key-Name", RADIUS_ATTR_HEXDUMP },
239         { RADIUS_ATTR_OPERATOR_NAME, "Operator-Name", RADIUS_ATTR_TEXT },
240         { RADIUS_ATTR_LOCATION_INFO, "Location-Information",
241           RADIUS_ATTR_HEXDUMP },
242         { RADIUS_ATTR_LOCATION_DATA, "Location-Data", RADIUS_ATTR_HEXDUMP },
243         { RADIUS_ATTR_BASIC_LOCATION_POLICY_RULES,
244           "Basic-Location-Policy-Rules", RADIUS_ATTR_HEXDUMP },
245         { RADIUS_ATTR_EXTENDED_LOCATION_POLICY_RULES,
246           "Extended-Location-Policy-Rules", RADIUS_ATTR_HEXDUMP },
247         { RADIUS_ATTR_LOCATION_CAPABLE, "Location-Capable", RADIUS_ATTR_INT32 },
248         { RADIUS_ATTR_REQUESTED_LOCATION_INFO, "Requested-Location-Info",
249           RADIUS_ATTR_INT32 },
250         { RADIUS_ATTR_MOBILITY_DOMAIN_ID, "Mobility-Domain-Id",
251           RADIUS_ATTR_INT32 },
252         { RADIUS_ATTR_WLAN_HESSID, "WLAN-HESSID", RADIUS_ATTR_TEXT },
253         { RADIUS_ATTR_WLAN_PAIRWISE_CIPHER, "WLAN-Pairwise-Cipher",
254           RADIUS_ATTR_HEXDUMP },
255         { RADIUS_ATTR_WLAN_GROUP_CIPHER, "WLAN-Group-Cipher",
256           RADIUS_ATTR_HEXDUMP },
257         { RADIUS_ATTR_WLAN_AKM_SUITE, "WLAN-AKM-Suite",
258           RADIUS_ATTR_HEXDUMP },
259         { RADIUS_ATTR_WLAN_GROUP_MGMT_CIPHER, "WLAN-Group-Mgmt-Pairwise-Cipher",
260           RADIUS_ATTR_HEXDUMP },
261 };
262 #define RADIUS_ATTRS ARRAY_SIZE(radius_attrs)
263
264
265 static const struct radius_attr_type *radius_get_attr_type(u8 type)
266 {
267         size_t i;
268
269         for (i = 0; i < RADIUS_ATTRS; i++) {
270                 if (type == radius_attrs[i].type)
271                         return &radius_attrs[i];
272         }
273
274         return NULL;
275 }
276
277
278 static void radius_msg_dump_attr(struct radius_attr_hdr *hdr)
279 {
280         const struct radius_attr_type *attr;
281         int len;
282         unsigned char *pos;
283         char buf[1000];
284
285         attr = radius_get_attr_type(hdr->type);
286
287         wpa_printf(MSG_INFO, "   Attribute %d (%s) length=%d",
288                    hdr->type, attr ? attr->name : "?Unknown?", hdr->length);
289
290         if (attr == NULL || hdr->length < sizeof(struct radius_attr_hdr))
291                 return;
292
293         len = hdr->length - sizeof(struct radius_attr_hdr);
294         pos = (unsigned char *) (hdr + 1);
295
296         switch (attr->data_type) {
297         case RADIUS_ATTR_TEXT:
298                 printf_encode(buf, sizeof(buf), pos, len);
299                 wpa_printf(MSG_INFO, "      Value: '%s'", buf);
300                 break;
301
302         case RADIUS_ATTR_IP:
303                 if (len == 4) {
304                         struct in_addr addr;
305                         os_memcpy(&addr, pos, 4);
306                         wpa_printf(MSG_INFO, "      Value: %s",
307                                    inet_ntoa(addr));
308                 } else {
309                         wpa_printf(MSG_INFO, "      Invalid IP address length %d",
310                                    len);
311                 }
312                 break;
313
314 #ifdef CONFIG_IPV6
315         case RADIUS_ATTR_IPV6:
316                 if (len == 16) {
317                         const char *atxt;
318                         struct in6_addr *addr = (struct in6_addr *) pos;
319                         atxt = inet_ntop(AF_INET6, addr, buf, sizeof(buf));
320                         wpa_printf(MSG_INFO, "      Value: %s",
321                                    atxt ? atxt : "?");
322                 } else {
323                         wpa_printf(MSG_INFO, "      Invalid IPv6 address length %d",
324                                    len);
325                 }
326                 break;
327 #endif /* CONFIG_IPV6 */
328
329         case RADIUS_ATTR_HEXDUMP:
330         case RADIUS_ATTR_UNDIST:
331                 wpa_snprintf_hex(buf, sizeof(buf), pos, len);
332                 wpa_printf(MSG_INFO, "      Value: %s", buf);
333                 break;
334
335         case RADIUS_ATTR_INT32:
336                 if (len == 4)
337                         wpa_printf(MSG_INFO, "      Value: %u",
338                                    WPA_GET_BE32(pos));
339                 else
340                         wpa_printf(MSG_INFO, "      Invalid INT32 length %d",
341                                    len);
342                 break;
343
344         default:
345                 break;
346         }
347 }
348
349
350 void radius_msg_dump(struct radius_msg *msg)
351 {
352         size_t i;
353
354         wpa_printf(MSG_INFO, "RADIUS message: code=%d (%s) identifier=%d length=%d",
355                    msg->hdr->code, radius_code_string(msg->hdr->code),
356                    msg->hdr->identifier, be_to_host16(msg->hdr->length));
357
358         for (i = 0; i < msg->attr_used; i++) {
359                 struct radius_attr_hdr *attr = radius_get_attr_hdr(msg, i);
360                 radius_msg_dump_attr(attr);
361         }
362 }
363
364
365 int radius_msg_finish(struct radius_msg *msg, const u8 *secret,
366                       size_t secret_len)
367 {
368         if (secret) {
369                 u8 auth[MD5_MAC_LEN];
370                 struct radius_attr_hdr *attr;
371
372                 os_memset(auth, 0, MD5_MAC_LEN);
373                 attr = radius_msg_add_attr(msg,
374                                            RADIUS_ATTR_MESSAGE_AUTHENTICATOR,
375                                            auth, MD5_MAC_LEN);
376                 if (attr == NULL) {
377                         wpa_printf(MSG_WARNING, "RADIUS: Could not add "
378                                    "Message-Authenticator");
379                         return -1;
380                 }
381                 msg->hdr->length = host_to_be16(wpabuf_len(msg->buf));
382                 hmac_md5(secret, secret_len, wpabuf_head(msg->buf),
383                          wpabuf_len(msg->buf), (u8 *) (attr + 1));
384         } else
385                 msg->hdr->length = host_to_be16(wpabuf_len(msg->buf));
386
387         if (wpabuf_len(msg->buf) > 0xffff) {
388                 wpa_printf(MSG_WARNING, "RADIUS: Too long message (%lu)",
389                            (unsigned long) wpabuf_len(msg->buf));
390                 return -1;
391         }
392         return 0;
393 }
394
395
396 int radius_msg_finish_srv(struct radius_msg *msg, const u8 *secret,
397                           size_t secret_len, const u8 *req_authenticator)
398 {
399         u8 auth[MD5_MAC_LEN];
400         struct radius_attr_hdr *attr;
401         const u8 *addr[4];
402         size_t len[4];
403
404         os_memset(auth, 0, MD5_MAC_LEN);
405         attr = radius_msg_add_attr(msg, RADIUS_ATTR_MESSAGE_AUTHENTICATOR,
406                                    auth, MD5_MAC_LEN);
407         if (attr == NULL) {
408                 wpa_printf(MSG_ERROR, "WARNING: Could not add Message-Authenticator");
409                 return -1;
410         }
411         msg->hdr->length = host_to_be16(wpabuf_len(msg->buf));
412         os_memcpy(msg->hdr->authenticator, req_authenticator,
413                   sizeof(msg->hdr->authenticator));
414         hmac_md5(secret, secret_len, wpabuf_head(msg->buf),
415                  wpabuf_len(msg->buf), (u8 *) (attr + 1));
416
417         /* ResponseAuth = MD5(Code+ID+Length+RequestAuth+Attributes+Secret) */
418         addr[0] = (u8 *) msg->hdr;
419         len[0] = 1 + 1 + 2;
420         addr[1] = req_authenticator;
421         len[1] = MD5_MAC_LEN;
422         addr[2] = wpabuf_head_u8(msg->buf) + sizeof(struct radius_hdr);
423         len[2] = wpabuf_len(msg->buf) - sizeof(struct radius_hdr);
424         addr[3] = secret;
425         len[3] = secret_len;
426         md5_vector(4, addr, len, msg->hdr->authenticator);
427
428         if (wpabuf_len(msg->buf) > 0xffff) {
429                 wpa_printf(MSG_WARNING, "RADIUS: Too long message (%lu)",
430                            (unsigned long) wpabuf_len(msg->buf));
431                 return -1;
432         }
433         return 0;
434 }
435
436
437 int radius_msg_finish_das_resp(struct radius_msg *msg, const u8 *secret,
438                                size_t secret_len,
439                                const struct radius_hdr *req_hdr)
440 {
441         const u8 *addr[2];
442         size_t len[2];
443         u8 auth[MD5_MAC_LEN];
444         struct radius_attr_hdr *attr;
445
446         os_memset(auth, 0, MD5_MAC_LEN);
447         attr = radius_msg_add_attr(msg, RADIUS_ATTR_MESSAGE_AUTHENTICATOR,
448                                    auth, MD5_MAC_LEN);
449         if (attr == NULL) {
450                 wpa_printf(MSG_WARNING, "Could not add Message-Authenticator");
451                 return -1;
452         }
453
454         msg->hdr->length = host_to_be16(wpabuf_len(msg->buf));
455         os_memcpy(msg->hdr->authenticator, req_hdr->authenticator, 16);
456         hmac_md5(secret, secret_len, wpabuf_head(msg->buf),
457                  wpabuf_len(msg->buf), (u8 *) (attr + 1));
458
459         /* ResponseAuth = MD5(Code+ID+Length+RequestAuth+Attributes+Secret) */
460         addr[0] = wpabuf_head_u8(msg->buf);
461         len[0] = wpabuf_len(msg->buf);
462         addr[1] = secret;
463         len[1] = secret_len;
464         if (md5_vector(2, addr, len, msg->hdr->authenticator) < 0)
465                 return -1;
466
467         if (wpabuf_len(msg->buf) > 0xffff) {
468                 wpa_printf(MSG_WARNING, "RADIUS: Too long message (%lu)",
469                            (unsigned long) wpabuf_len(msg->buf));
470                 return -1;
471         }
472         return 0;
473 }
474
475
476 void radius_msg_finish_acct(struct radius_msg *msg, const u8 *secret,
477                             size_t secret_len)
478 {
479         const u8 *addr[2];
480         size_t len[2];
481
482         msg->hdr->length = host_to_be16(wpabuf_len(msg->buf));
483         os_memset(msg->hdr->authenticator, 0, MD5_MAC_LEN);
484         addr[0] = wpabuf_head(msg->buf);
485         len[0] = wpabuf_len(msg->buf);
486         addr[1] = secret;
487         len[1] = secret_len;
488         md5_vector(2, addr, len, msg->hdr->authenticator);
489
490         if (wpabuf_len(msg->buf) > 0xffff) {
491                 wpa_printf(MSG_WARNING, "RADIUS: Too long messages (%lu)",
492                            (unsigned long) wpabuf_len(msg->buf));
493         }
494 }
495
496
497 void radius_msg_finish_acct_resp(struct radius_msg *msg, const u8 *secret,
498                                  size_t secret_len, const u8 *req_authenticator)
499 {
500         const u8 *addr[2];
501         size_t len[2];
502
503         msg->hdr->length = host_to_be16(wpabuf_len(msg->buf));
504         os_memcpy(msg->hdr->authenticator, req_authenticator, MD5_MAC_LEN);
505         addr[0] = wpabuf_head(msg->buf);
506         len[0] = wpabuf_len(msg->buf);
507         addr[1] = secret;
508         len[1] = secret_len;
509         md5_vector(2, addr, len, msg->hdr->authenticator);
510
511         if (wpabuf_len(msg->buf) > 0xffff) {
512                 wpa_printf(MSG_WARNING, "RADIUS: Too long messages (%lu)",
513                            (unsigned long) wpabuf_len(msg->buf));
514         }
515 }
516
517
518 int radius_msg_verify_acct_req(struct radius_msg *msg, const u8 *secret,
519                                size_t secret_len)
520 {
521         const u8 *addr[4];
522         size_t len[4];
523         u8 zero[MD5_MAC_LEN];
524         u8 hash[MD5_MAC_LEN];
525
526         os_memset(zero, 0, sizeof(zero));
527         addr[0] = (u8 *) msg->hdr;
528         len[0] = sizeof(struct radius_hdr) - MD5_MAC_LEN;
529         addr[1] = zero;
530         len[1] = MD5_MAC_LEN;
531         addr[2] = (u8 *) (msg->hdr + 1);
532         len[2] = wpabuf_len(msg->buf) - sizeof(struct radius_hdr);
533         addr[3] = secret;
534         len[3] = secret_len;
535         md5_vector(4, addr, len, hash);
536         return os_memcmp_const(msg->hdr->authenticator, hash, MD5_MAC_LEN) != 0;
537 }
538
539
540 int radius_msg_verify_das_req(struct radius_msg *msg, const u8 *secret,
541                               size_t secret_len)
542 {
543         const u8 *addr[4];
544         size_t len[4];
545         u8 zero[MD5_MAC_LEN];
546         u8 hash[MD5_MAC_LEN];
547         u8 auth[MD5_MAC_LEN], orig[MD5_MAC_LEN];
548         u8 orig_authenticator[16];
549
550         struct radius_attr_hdr *attr = NULL, *tmp;
551         size_t i;
552
553         os_memset(zero, 0, sizeof(zero));
554         addr[0] = (u8 *) msg->hdr;
555         len[0] = sizeof(struct radius_hdr) - MD5_MAC_LEN;
556         addr[1] = zero;
557         len[1] = MD5_MAC_LEN;
558         addr[2] = (u8 *) (msg->hdr + 1);
559         len[2] = wpabuf_len(msg->buf) - sizeof(struct radius_hdr);
560         addr[3] = secret;
561         len[3] = secret_len;
562         md5_vector(4, addr, len, hash);
563         if (os_memcmp_const(msg->hdr->authenticator, hash, MD5_MAC_LEN) != 0)
564                 return 1;
565
566         for (i = 0; i < msg->attr_used; i++) {
567                 tmp = radius_get_attr_hdr(msg, i);
568                 if (tmp->type == RADIUS_ATTR_MESSAGE_AUTHENTICATOR) {
569                         if (attr != NULL) {
570                                 wpa_printf(MSG_WARNING, "Multiple "
571                                            "Message-Authenticator attributes "
572                                            "in RADIUS message");
573                                 return 1;
574                         }
575                         attr = tmp;
576                 }
577         }
578
579         if (attr == NULL) {
580                 /* Message-Authenticator is MAY; not required */
581                 return 0;
582         }
583
584         os_memcpy(orig, attr + 1, MD5_MAC_LEN);
585         os_memset(attr + 1, 0, MD5_MAC_LEN);
586         os_memcpy(orig_authenticator, msg->hdr->authenticator,
587                   sizeof(orig_authenticator));
588         os_memset(msg->hdr->authenticator, 0,
589                   sizeof(msg->hdr->authenticator));
590         hmac_md5(secret, secret_len, wpabuf_head(msg->buf),
591                  wpabuf_len(msg->buf), auth);
592         os_memcpy(attr + 1, orig, MD5_MAC_LEN);
593         os_memcpy(msg->hdr->authenticator, orig_authenticator,
594                   sizeof(orig_authenticator));
595
596         return os_memcmp_const(orig, auth, MD5_MAC_LEN) != 0;
597 }
598
599
600 static int radius_msg_add_attr_to_array(struct radius_msg *msg,
601                                         struct radius_attr_hdr *attr)
602 {
603         if (msg->attr_used >= msg->attr_size) {
604                 size_t *nattr_pos;
605                 int nlen = msg->attr_size * 2;
606
607                 nattr_pos = os_realloc_array(msg->attr_pos, nlen,
608                                              sizeof(*msg->attr_pos));
609                 if (nattr_pos == NULL)
610                         return -1;
611
612                 msg->attr_pos = nattr_pos;
613                 msg->attr_size = nlen;
614         }
615
616         msg->attr_pos[msg->attr_used++] =
617                 (unsigned char *) attr - wpabuf_head_u8(msg->buf);
618
619         return 0;
620 }
621
622
623 struct radius_attr_hdr *radius_msg_add_attr(struct radius_msg *msg, u8 type,
624                                             const u8 *data, size_t data_len)
625 {
626         size_t buf_needed;
627         struct radius_attr_hdr *attr;
628
629         if (data_len > RADIUS_MAX_ATTR_LEN) {
630                 wpa_printf(MSG_ERROR, "radius_msg_add_attr: too long attribute (%lu bytes)",
631                        (unsigned long) data_len);
632                 return NULL;
633         }
634
635         buf_needed = sizeof(*attr) + data_len;
636
637         if (wpabuf_tailroom(msg->buf) < buf_needed) {
638                 /* allocate more space for message buffer */
639                 if (wpabuf_resize(&msg->buf, buf_needed) < 0)
640                         return NULL;
641                 msg->hdr = wpabuf_mhead(msg->buf);
642         }
643
644         attr = wpabuf_put(msg->buf, sizeof(struct radius_attr_hdr));
645         attr->type = type;
646         attr->length = sizeof(*attr) + data_len;
647         wpabuf_put_data(msg->buf, data, data_len);
648
649         if (radius_msg_add_attr_to_array(msg, attr))
650                 return NULL;
651
652         return attr;
653 }
654
655
656 /**
657  * radius_msg_parse - Parse a RADIUS message
658  * @data: RADIUS message to be parsed
659  * @len: Length of data buffer in octets
660  * Returns: Parsed RADIUS message or %NULL on failure
661  *
662  * This parses a RADIUS message and makes a copy of its data. The caller is
663  * responsible for freeing the returned data with radius_msg_free().
664  */
665 struct radius_msg * radius_msg_parse(const u8 *data, size_t len)
666 {
667         struct radius_msg *msg;
668         struct radius_hdr *hdr;
669         struct radius_attr_hdr *attr;
670         size_t msg_len;
671         unsigned char *pos, *end;
672
673         if (data == NULL || len < sizeof(*hdr))
674                 return NULL;
675
676         hdr = (struct radius_hdr *) data;
677
678         msg_len = be_to_host16(hdr->length);
679         if (msg_len < sizeof(*hdr) || msg_len > len) {
680                 wpa_printf(MSG_INFO, "RADIUS: Invalid message length");
681                 return NULL;
682         }
683
684         if (msg_len < len) {
685                 wpa_printf(MSG_DEBUG, "RADIUS: Ignored %lu extra bytes after "
686                            "RADIUS message", (unsigned long) len - msg_len);
687         }
688
689         msg = os_zalloc(sizeof(*msg));
690         if (msg == NULL)
691                 return NULL;
692
693         msg->buf = wpabuf_alloc_copy(data, msg_len);
694         if (msg->buf == NULL || radius_msg_initialize(msg)) {
695                 radius_msg_free(msg);
696                 return NULL;
697         }
698         msg->hdr = wpabuf_mhead(msg->buf);
699
700         /* parse attributes */
701         pos = wpabuf_mhead_u8(msg->buf) + sizeof(struct radius_hdr);
702         end = wpabuf_mhead_u8(msg->buf) + wpabuf_len(msg->buf);
703         while (pos < end) {
704                 if ((size_t) (end - pos) < sizeof(*attr))
705                         goto fail;
706
707                 attr = (struct radius_attr_hdr *) pos;
708
709                 if (attr->length > end - pos || attr->length < sizeof(*attr))
710                         goto fail;
711
712                 /* TODO: check that attr->length is suitable for attr->type */
713
714                 if (radius_msg_add_attr_to_array(msg, attr))
715                         goto fail;
716
717                 pos += attr->length;
718         }
719
720         return msg;
721
722  fail:
723         radius_msg_free(msg);
724         return NULL;
725 }
726
727
728 int radius_msg_add_eap(struct radius_msg *msg, const u8 *data, size_t data_len)
729 {
730         const u8 *pos = data;
731         size_t left = data_len;
732
733         while (left > 0) {
734                 int len;
735                 if (left > RADIUS_MAX_ATTR_LEN)
736                         len = RADIUS_MAX_ATTR_LEN;
737                 else
738                         len = left;
739
740                 if (!radius_msg_add_attr(msg, RADIUS_ATTR_EAP_MESSAGE,
741                                          pos, len))
742                         return 0;
743
744                 pos += len;
745                 left -= len;
746         }
747
748         return 1;
749 }
750
751
752 struct wpabuf * radius_msg_get_eap(struct radius_msg *msg)
753 {
754         struct wpabuf *eap;
755         size_t len, i;
756         struct radius_attr_hdr *attr;
757
758         if (msg == NULL)
759                 return NULL;
760
761         len = 0;
762         for (i = 0; i < msg->attr_used; i++) {
763                 attr = radius_get_attr_hdr(msg, i);
764                 if (attr->type == RADIUS_ATTR_EAP_MESSAGE &&
765                     attr->length > sizeof(struct radius_attr_hdr))
766                         len += attr->length - sizeof(struct radius_attr_hdr);
767         }
768
769         if (len == 0)
770                 return NULL;
771
772         eap = wpabuf_alloc(len);
773         if (eap == NULL)
774                 return NULL;
775
776         for (i = 0; i < msg->attr_used; i++) {
777                 attr = radius_get_attr_hdr(msg, i);
778                 if (attr->type == RADIUS_ATTR_EAP_MESSAGE &&
779                     attr->length > sizeof(struct radius_attr_hdr)) {
780                         int flen = attr->length - sizeof(*attr);
781                         wpabuf_put_data(eap, attr + 1, flen);
782                 }
783         }
784
785         return eap;
786 }
787
788
789 int radius_msg_verify_msg_auth(struct radius_msg *msg, const u8 *secret,
790                                size_t secret_len, const u8 *req_auth)
791 {
792         u8 auth[MD5_MAC_LEN], orig[MD5_MAC_LEN];
793         u8 orig_authenticator[16];
794         struct radius_attr_hdr *attr = NULL, *tmp;
795         size_t i;
796
797         for (i = 0; i < msg->attr_used; i++) {
798                 tmp = radius_get_attr_hdr(msg, i);
799                 if (tmp->type == RADIUS_ATTR_MESSAGE_AUTHENTICATOR) {
800                         if (attr != NULL) {
801                                 wpa_printf(MSG_INFO, "Multiple Message-Authenticator attributes in RADIUS message");
802                                 return 1;
803                         }
804                         attr = tmp;
805                 }
806         }
807
808         if (attr == NULL) {
809                 wpa_printf(MSG_INFO, "No Message-Authenticator attribute found");
810                 return 1;
811         }
812
813         os_memcpy(orig, attr + 1, MD5_MAC_LEN);
814         os_memset(attr + 1, 0, MD5_MAC_LEN);
815         if (req_auth) {
816                 os_memcpy(orig_authenticator, msg->hdr->authenticator,
817                           sizeof(orig_authenticator));
818                 os_memcpy(msg->hdr->authenticator, req_auth,
819                           sizeof(msg->hdr->authenticator));
820         }
821         hmac_md5(secret, secret_len, wpabuf_head(msg->buf),
822                  wpabuf_len(msg->buf), auth);
823         os_memcpy(attr + 1, orig, MD5_MAC_LEN);
824         if (req_auth) {
825                 os_memcpy(msg->hdr->authenticator, orig_authenticator,
826                           sizeof(orig_authenticator));
827         }
828
829         if (os_memcmp_const(orig, auth, MD5_MAC_LEN) != 0) {
830                 wpa_printf(MSG_INFO, "Invalid Message-Authenticator!");
831                 return 1;
832         }
833
834         return 0;
835 }
836
837
838 int radius_msg_verify(struct radius_msg *msg, const u8 *secret,
839                       size_t secret_len, struct radius_msg *sent_msg, int auth)
840 {
841         const u8 *addr[4];
842         size_t len[4];
843         u8 hash[MD5_MAC_LEN];
844
845         if (sent_msg == NULL) {
846                 wpa_printf(MSG_INFO, "No matching Access-Request message found");
847                 return 1;
848         }
849
850         if (auth &&
851             radius_msg_verify_msg_auth(msg, secret, secret_len,
852                                        sent_msg->hdr->authenticator)) {
853                 return 1;
854         }
855
856         /* ResponseAuth = MD5(Code+ID+Length+RequestAuth+Attributes+Secret) */
857         addr[0] = (u8 *) msg->hdr;
858         len[0] = 1 + 1 + 2;
859         addr[1] = sent_msg->hdr->authenticator;
860         len[1] = MD5_MAC_LEN;
861         addr[2] = wpabuf_head_u8(msg->buf) + sizeof(struct radius_hdr);
862         len[2] = wpabuf_len(msg->buf) - sizeof(struct radius_hdr);
863         addr[3] = secret;
864         len[3] = secret_len;
865         md5_vector(4, addr, len, hash);
866         if (os_memcmp_const(hash, msg->hdr->authenticator, MD5_MAC_LEN) != 0) {
867                 wpa_printf(MSG_INFO, "Response Authenticator invalid!");
868                 return 1;
869         }
870
871         return 0;
872 }
873
874
875 int radius_msg_copy_attr(struct radius_msg *dst, struct radius_msg *src,
876                          u8 type)
877 {
878         struct radius_attr_hdr *attr;
879         size_t i;
880         int count = 0;
881
882         for (i = 0; i < src->attr_used; i++) {
883                 attr = radius_get_attr_hdr(src, i);
884                 if (attr->type == type && attr->length >= sizeof(*attr)) {
885                         if (!radius_msg_add_attr(dst, type, (u8 *) (attr + 1),
886                                                  attr->length - sizeof(*attr)))
887                                 return -1;
888                         count++;
889                 }
890         }
891
892         return count;
893 }
894
895
896 /* Create Request Authenticator. The value should be unique over the lifetime
897  * of the shared secret between authenticator and authentication server.
898  */
899 int radius_msg_make_authenticator(struct radius_msg *msg)
900 {
901         return os_get_random((u8 *) &msg->hdr->authenticator,
902                              sizeof(msg->hdr->authenticator));
903 }
904
905
906 /* Get Vendor-specific RADIUS Attribute from a parsed RADIUS message.
907  * Returns the Attribute payload and sets alen to indicate the length of the
908  * payload if a vendor attribute with subtype is found, otherwise returns NULL.
909  * The returned payload is allocated with os_malloc() and caller must free it
910  * by calling os_free().
911  */
912 static u8 *radius_msg_get_vendor_attr(struct radius_msg *msg, u32 vendor,
913                                       u8 subtype, size_t *alen)
914 {
915         u8 *data, *pos;
916         size_t i, len;
917
918         if (msg == NULL)
919                 return NULL;
920
921         for (i = 0; i < msg->attr_used; i++) {
922                 struct radius_attr_hdr *attr = radius_get_attr_hdr(msg, i);
923                 size_t left;
924                 u32 vendor_id;
925                 struct radius_attr_vendor *vhdr;
926
927                 if (attr->type != RADIUS_ATTR_VENDOR_SPECIFIC ||
928                     attr->length < sizeof(*attr))
929                         continue;
930
931                 left = attr->length - sizeof(*attr);
932                 if (left < 4)
933                         continue;
934
935                 pos = (u8 *) (attr + 1);
936
937                 os_memcpy(&vendor_id, pos, 4);
938                 pos += 4;
939                 left -= 4;
940
941                 if (ntohl(vendor_id) != vendor)
942                         continue;
943
944                 while (left >= sizeof(*vhdr)) {
945                         vhdr = (struct radius_attr_vendor *) pos;
946                         if (vhdr->vendor_length > left ||
947                             vhdr->vendor_length < sizeof(*vhdr)) {
948                                 break;
949                         }
950                         if (vhdr->vendor_type != subtype) {
951                                 pos += vhdr->vendor_length;
952                                 left -= vhdr->vendor_length;
953                                 continue;
954                         }
955
956                         len = vhdr->vendor_length - sizeof(*vhdr);
957                         data = os_malloc(len);
958                         if (data == NULL)
959                                 return NULL;
960                         os_memcpy(data, pos + sizeof(*vhdr), len);
961                         if (alen)
962                                 *alen = len;
963                         return data;
964                 }
965         }
966
967         return NULL;
968 }
969
970
971 static u8 * decrypt_ms_key(const u8 *key, size_t len,
972                            const u8 *req_authenticator,
973                            const u8 *secret, size_t secret_len, size_t *reslen)
974 {
975         u8 *plain, *ppos, *res;
976         const u8 *pos;
977         size_t left, plen;
978         u8 hash[MD5_MAC_LEN];
979         int i, first = 1;
980         const u8 *addr[3];
981         size_t elen[3];
982
983         /* key: 16-bit salt followed by encrypted key info */
984
985         if (len < 2 + 16) {
986                 wpa_printf(MSG_DEBUG, "RADIUS: %s: Len is too small: %d",
987                            __func__, (int) len);
988                 return NULL;
989         }
990
991         pos = key + 2;
992         left = len - 2;
993         if (left % 16) {
994                 wpa_printf(MSG_INFO, "RADIUS: Invalid ms key len %lu",
995                            (unsigned long) left);
996                 return NULL;
997         }
998
999         plen = left;
1000         ppos = plain = os_malloc(plen);
1001         if (plain == NULL)
1002                 return NULL;
1003         plain[0] = 0;
1004
1005         while (left > 0) {
1006                 /* b(1) = MD5(Secret + Request-Authenticator + Salt)
1007                  * b(i) = MD5(Secret + c(i - 1)) for i > 1 */
1008
1009                 addr[0] = secret;
1010                 elen[0] = secret_len;
1011                 if (first) {
1012                         addr[1] = req_authenticator;
1013                         elen[1] = MD5_MAC_LEN;
1014                         addr[2] = key;
1015                         elen[2] = 2; /* Salt */
1016                 } else {
1017                         addr[1] = pos - MD5_MAC_LEN;
1018                         elen[1] = MD5_MAC_LEN;
1019                 }
1020                 md5_vector(first ? 3 : 2, addr, elen, hash);
1021                 first = 0;
1022
1023                 for (i = 0; i < MD5_MAC_LEN; i++)
1024                         *ppos++ = *pos++ ^ hash[i];
1025                 left -= MD5_MAC_LEN;
1026         }
1027
1028         if (plain[0] == 0 || plain[0] > plen - 1) {
1029                 wpa_printf(MSG_INFO, "RADIUS: Failed to decrypt MPPE key");
1030                 os_free(plain);
1031                 return NULL;
1032         }
1033
1034         res = os_malloc(plain[0]);
1035         if (res == NULL) {
1036                 os_free(plain);
1037                 return NULL;
1038         }
1039         os_memcpy(res, plain + 1, plain[0]);
1040         if (reslen)
1041                 *reslen = plain[0];
1042         os_free(plain);
1043         return res;
1044 }
1045
1046
1047 static void encrypt_ms_key(const u8 *key, size_t key_len, u16 salt,
1048                            const u8 *req_authenticator,
1049                            const u8 *secret, size_t secret_len,
1050                            u8 *ebuf, size_t *elen)
1051 {
1052         int i, len, first = 1;
1053         u8 hash[MD5_MAC_LEN], saltbuf[2], *pos;
1054         const u8 *addr[3];
1055         size_t _len[3];
1056
1057         WPA_PUT_BE16(saltbuf, salt);
1058
1059         len = 1 + key_len;
1060         if (len & 0x0f) {
1061                 len = (len & 0xf0) + 16;
1062         }
1063         os_memset(ebuf, 0, len);
1064         ebuf[0] = key_len;
1065         os_memcpy(ebuf + 1, key, key_len);
1066
1067         *elen = len;
1068
1069         pos = ebuf;
1070         while (len > 0) {
1071                 /* b(1) = MD5(Secret + Request-Authenticator + Salt)
1072                  * b(i) = MD5(Secret + c(i - 1)) for i > 1 */
1073                 addr[0] = secret;
1074                 _len[0] = secret_len;
1075                 if (first) {
1076                         addr[1] = req_authenticator;
1077                         _len[1] = MD5_MAC_LEN;
1078                         addr[2] = saltbuf;
1079                         _len[2] = sizeof(saltbuf);
1080                 } else {
1081                         addr[1] = pos - MD5_MAC_LEN;
1082                         _len[1] = MD5_MAC_LEN;
1083                 }
1084                 md5_vector(first ? 3 : 2, addr, _len, hash);
1085                 first = 0;
1086
1087                 for (i = 0; i < MD5_MAC_LEN; i++)
1088                         *pos++ ^= hash[i];
1089
1090                 len -= MD5_MAC_LEN;
1091         }
1092 }
1093
1094
1095 struct radius_ms_mppe_keys *
1096 radius_msg_get_ms_keys(struct radius_msg *msg, struct radius_msg *sent_msg,
1097                        const u8 *secret, size_t secret_len)
1098 {
1099         u8 *key;
1100         size_t keylen;
1101         struct radius_ms_mppe_keys *keys;
1102
1103         if (msg == NULL || sent_msg == NULL)
1104                 return NULL;
1105
1106         keys = os_zalloc(sizeof(*keys));
1107         if (keys == NULL)
1108                 return NULL;
1109
1110         key = radius_msg_get_vendor_attr(msg, RADIUS_VENDOR_ID_MICROSOFT,
1111                                          RADIUS_VENDOR_ATTR_MS_MPPE_SEND_KEY,
1112                                          &keylen);
1113         if (key) {
1114                 keys->send = decrypt_ms_key(key, keylen,
1115                                             sent_msg->hdr->authenticator,
1116                                             secret, secret_len,
1117                                             &keys->send_len);
1118                 if (!keys->send) {
1119                         wpa_printf(MSG_DEBUG,
1120                                    "RADIUS: Failed to decrypt send key");
1121                 }
1122                 os_free(key);
1123         }
1124
1125         key = radius_msg_get_vendor_attr(msg, RADIUS_VENDOR_ID_MICROSOFT,
1126                                          RADIUS_VENDOR_ATTR_MS_MPPE_RECV_KEY,
1127                                          &keylen);
1128         if (key) {
1129                 keys->recv = decrypt_ms_key(key, keylen,
1130                                             sent_msg->hdr->authenticator,
1131                                             secret, secret_len,
1132                                             &keys->recv_len);
1133                 if (!keys->recv) {
1134                         wpa_printf(MSG_DEBUG,
1135                                    "RADIUS: Failed to decrypt recv key");
1136                 }
1137                 os_free(key);
1138         }
1139
1140         return keys;
1141 }
1142
1143
1144 struct radius_ms_mppe_keys *
1145 radius_msg_get_cisco_keys(struct radius_msg *msg, struct radius_msg *sent_msg,
1146                           const u8 *secret, size_t secret_len)
1147 {
1148         u8 *key;
1149         size_t keylen;
1150         struct radius_ms_mppe_keys *keys;
1151
1152         if (msg == NULL || sent_msg == NULL)
1153                 return NULL;
1154
1155         keys = os_zalloc(sizeof(*keys));
1156         if (keys == NULL)
1157                 return NULL;
1158
1159         key = radius_msg_get_vendor_attr(msg, RADIUS_VENDOR_ID_CISCO,
1160                                          RADIUS_CISCO_AV_PAIR, &keylen);
1161         if (key && keylen == 51 &&
1162             os_memcmp(key, "leap:session-key=", 17) == 0) {
1163                 keys->recv = decrypt_ms_key(key + 17, keylen - 17,
1164                                             sent_msg->hdr->authenticator,
1165                                             secret, secret_len,
1166                                             &keys->recv_len);
1167         }
1168         os_free(key);
1169
1170         return keys;
1171 }
1172
1173
1174 int radius_msg_add_mppe_keys(struct radius_msg *msg,
1175                              const u8 *req_authenticator,
1176                              const u8 *secret, size_t secret_len,
1177                              const u8 *send_key, size_t send_key_len,
1178                              const u8 *recv_key, size_t recv_key_len)
1179 {
1180         struct radius_attr_hdr *attr;
1181         u32 vendor_id = htonl(RADIUS_VENDOR_ID_MICROSOFT);
1182         u8 *buf;
1183         struct radius_attr_vendor *vhdr;
1184         u8 *pos;
1185         size_t elen;
1186         int hlen;
1187         u16 salt;
1188
1189         hlen = sizeof(vendor_id) + sizeof(*vhdr) + 2;
1190
1191         /* MS-MPPE-Send-Key */
1192         buf = os_malloc(hlen + send_key_len + 16);
1193         if (buf == NULL) {
1194                 return 0;
1195         }
1196         pos = buf;
1197         os_memcpy(pos, &vendor_id, sizeof(vendor_id));
1198         pos += sizeof(vendor_id);
1199         vhdr = (struct radius_attr_vendor *) pos;
1200         vhdr->vendor_type = RADIUS_VENDOR_ATTR_MS_MPPE_SEND_KEY;
1201         pos = (u8 *) (vhdr + 1);
1202         if (os_get_random((u8 *) &salt, sizeof(salt)) < 0) {
1203                 os_free(buf);
1204                 return 0;
1205         }
1206         salt |= 0x8000;
1207         WPA_PUT_BE16(pos, salt);
1208         pos += 2;
1209         encrypt_ms_key(send_key, send_key_len, salt, req_authenticator, secret,
1210                        secret_len, pos, &elen);
1211         vhdr->vendor_length = hlen + elen - sizeof(vendor_id);
1212
1213         attr = radius_msg_add_attr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
1214                                    buf, hlen + elen);
1215         os_free(buf);
1216         if (attr == NULL) {
1217                 return 0;
1218         }
1219
1220         /* MS-MPPE-Recv-Key */
1221         buf = os_malloc(hlen + recv_key_len + 16);
1222         if (buf == NULL) {
1223                 return 0;
1224         }
1225         pos = buf;
1226         os_memcpy(pos, &vendor_id, sizeof(vendor_id));
1227         pos += sizeof(vendor_id);
1228         vhdr = (struct radius_attr_vendor *) pos;
1229         vhdr->vendor_type = RADIUS_VENDOR_ATTR_MS_MPPE_RECV_KEY;
1230         pos = (u8 *) (vhdr + 1);
1231         salt ^= 1;
1232         WPA_PUT_BE16(pos, salt);
1233         pos += 2;
1234         encrypt_ms_key(recv_key, recv_key_len, salt, req_authenticator, secret,
1235                        secret_len, pos, &elen);
1236         vhdr->vendor_length = hlen + elen - sizeof(vendor_id);
1237
1238         attr = radius_msg_add_attr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
1239                                    buf, hlen + elen);
1240         os_free(buf);
1241         if (attr == NULL) {
1242                 return 0;
1243         }
1244
1245         return 1;
1246 }
1247
1248
1249 int radius_msg_add_wfa(struct radius_msg *msg, u8 subtype, const u8 *data,
1250                        size_t len)
1251 {
1252         struct radius_attr_hdr *attr;
1253         u8 *buf, *pos;
1254         size_t alen;
1255
1256         alen = 4 + 2 + len;
1257         buf = os_malloc(alen);
1258         if (buf == NULL)
1259                 return 0;
1260         pos = buf;
1261         WPA_PUT_BE32(pos, RADIUS_VENDOR_ID_WFA);
1262         pos += 4;
1263         *pos++ = subtype;
1264         *pos++ = 2 + len;
1265         os_memcpy(pos, data, len);
1266         attr = radius_msg_add_attr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
1267                                    buf, alen);
1268         os_free(buf);
1269         if (attr == NULL)
1270                 return 0;
1271
1272         return 1;
1273 }
1274
1275
1276 int radius_user_password_hide(struct radius_msg *msg,
1277                               const u8 *data, size_t data_len,
1278                               const u8 *secret, size_t secret_len,
1279                               u8 *buf, size_t buf_len)
1280 {
1281         size_t padlen, i, pos;
1282         const u8 *addr[2];
1283         size_t len[2];
1284         u8 hash[16];
1285
1286         if (data_len + 16 > buf_len)
1287                 return -1;
1288
1289         os_memcpy(buf, data, data_len);
1290
1291         padlen = data_len % 16;
1292         if (padlen && data_len < buf_len) {
1293                 padlen = 16 - padlen;
1294                 os_memset(buf + data_len, 0, padlen);
1295                 buf_len = data_len + padlen;
1296         } else {
1297                 buf_len = data_len;
1298         }
1299
1300         addr[0] = secret;
1301         len[0] = secret_len;
1302         addr[1] = msg->hdr->authenticator;
1303         len[1] = 16;
1304         md5_vector(2, addr, len, hash);
1305
1306         for (i = 0; i < 16; i++)
1307                 buf[i] ^= hash[i];
1308         pos = 16;
1309
1310         while (pos < buf_len) {
1311                 addr[0] = secret;
1312                 len[0] = secret_len;
1313                 addr[1] = &buf[pos - 16];
1314                 len[1] = 16;
1315                 md5_vector(2, addr, len, hash);
1316
1317                 for (i = 0; i < 16; i++)
1318                         buf[pos + i] ^= hash[i];
1319
1320                 pos += 16;
1321         }
1322
1323         return buf_len;
1324 }
1325
1326
1327 /* Add User-Password attribute to a RADIUS message and encrypt it as specified
1328  * in RFC 2865, Chap. 5.2 */
1329 struct radius_attr_hdr *
1330 radius_msg_add_attr_user_password(struct radius_msg *msg,
1331                                   const u8 *data, size_t data_len,
1332                                   const u8 *secret, size_t secret_len)
1333 {
1334         u8 buf[128];
1335         int res;
1336
1337         res = radius_user_password_hide(msg, data, data_len,
1338                                         secret, secret_len, buf, sizeof(buf));
1339         if (res < 0)
1340                 return NULL;
1341
1342         return radius_msg_add_attr(msg, RADIUS_ATTR_USER_PASSWORD,
1343                                    buf, res);
1344 }
1345
1346
1347 int radius_msg_get_attr(struct radius_msg *msg, u8 type, u8 *buf, size_t len)
1348 {
1349         struct radius_attr_hdr *attr = NULL, *tmp;
1350         size_t i, dlen;
1351
1352         for (i = 0; i < msg->attr_used; i++) {
1353                 tmp = radius_get_attr_hdr(msg, i);
1354                 if (tmp->type == type) {
1355                         attr = tmp;
1356                         break;
1357                 }
1358         }
1359
1360         if (!attr || attr->length < sizeof(*attr))
1361                 return -1;
1362
1363         dlen = attr->length - sizeof(*attr);
1364         if (buf)
1365                 os_memcpy(buf, (attr + 1), dlen > len ? len : dlen);
1366         return dlen;
1367 }
1368
1369
1370 int radius_msg_get_attr_ptr(struct radius_msg *msg, u8 type, u8 **buf,
1371                             size_t *len, const u8 *start)
1372 {
1373         size_t i;
1374         struct radius_attr_hdr *attr = NULL, *tmp;
1375
1376         for (i = 0; i < msg->attr_used; i++) {
1377                 tmp = radius_get_attr_hdr(msg, i);
1378                 if (tmp->type == type &&
1379                     (start == NULL || (u8 *) tmp > start)) {
1380                         attr = tmp;
1381                         break;
1382                 }
1383         }
1384
1385         if (!attr || attr->length < sizeof(*attr))
1386                 return -1;
1387
1388         *buf = (u8 *) (attr + 1);
1389         *len = attr->length - sizeof(*attr);
1390         return 0;
1391 }
1392
1393
1394 int radius_msg_count_attr(struct radius_msg *msg, u8 type, int min_len)
1395 {
1396         size_t i;
1397         int count;
1398
1399         for (count = 0, i = 0; i < msg->attr_used; i++) {
1400                 struct radius_attr_hdr *attr = radius_get_attr_hdr(msg, i);
1401                 if (attr->type == type &&
1402                     attr->length >= sizeof(struct radius_attr_hdr) + min_len)
1403                         count++;
1404         }
1405
1406         return count;
1407 }
1408
1409
1410 struct radius_tunnel_attrs {
1411         int tag_used;
1412         int type; /* Tunnel-Type */
1413         int medium_type; /* Tunnel-Medium-Type */
1414         int vlanid;
1415 };
1416
1417
1418 static int cmp_int(const void *a, const void *b)
1419 {
1420         int x, y;
1421
1422         x = *((int *) a);
1423         y = *((int *) b);
1424         return (x - y);
1425 }
1426
1427
1428 /**
1429  * radius_msg_get_vlanid - Parse RADIUS attributes for VLAN tunnel information
1430  * The k tagged vlans found are sorted by vlan_id and stored in the first k
1431  * items of tagged.
1432  *
1433  * @msg: RADIUS message
1434  * @untagged: Pointer to store untagged vid
1435  * @numtagged: Size of tagged
1436  * @tagged: Pointer to store tagged list
1437  *
1438  * Returns: 0 if neither tagged nor untagged configuration is found, 1 otherwise
1439  */
1440 int radius_msg_get_vlanid(struct radius_msg *msg, int *untagged, int numtagged,
1441                           int *tagged)
1442 {
1443         struct radius_tunnel_attrs tunnel[RADIUS_TUNNEL_TAGS], *tun;
1444         size_t i;
1445         struct radius_attr_hdr *attr = NULL;
1446         const u8 *data;
1447         char buf[10];
1448         size_t dlen;
1449         int j, taggedidx = 0, vlan_id;
1450
1451         os_memset(&tunnel, 0, sizeof(tunnel));
1452         for (j = 0; j < numtagged; j++)
1453                 tagged[j] = 0;
1454         *untagged = 0;
1455
1456         for (i = 0; i < msg->attr_used; i++) {
1457                 attr = radius_get_attr_hdr(msg, i);
1458                 if (attr->length < sizeof(*attr))
1459                         return -1;
1460                 data = (const u8 *) (attr + 1);
1461                 dlen = attr->length - sizeof(*attr);
1462                 if (attr->length < 3)
1463                         continue;
1464                 if (data[0] >= RADIUS_TUNNEL_TAGS)
1465                         tun = &tunnel[0];
1466                 else
1467                         tun = &tunnel[data[0]];
1468
1469                 switch (attr->type) {
1470                 case RADIUS_ATTR_TUNNEL_TYPE:
1471                         if (attr->length != 6)
1472                                 break;
1473                         tun->tag_used++;
1474                         tun->type = WPA_GET_BE24(data + 1);
1475                         break;
1476                 case RADIUS_ATTR_TUNNEL_MEDIUM_TYPE:
1477                         if (attr->length != 6)
1478                                 break;
1479                         tun->tag_used++;
1480                         tun->medium_type = WPA_GET_BE24(data + 1);
1481                         break;
1482                 case RADIUS_ATTR_TUNNEL_PRIVATE_GROUP_ID:
1483                         if (data[0] < RADIUS_TUNNEL_TAGS) {
1484                                 data++;
1485                                 dlen--;
1486                         }
1487                         if (dlen >= sizeof(buf))
1488                                 break;
1489                         os_memcpy(buf, data, dlen);
1490                         buf[dlen] = '\0';
1491                         vlan_id = atoi(buf);
1492                         if (vlan_id <= 0)
1493                                 break;
1494                         tun->tag_used++;
1495                         tun->vlanid = vlan_id;
1496                         break;
1497                 case RADIUS_ATTR_EGRESS_VLANID: /* RFC 4675 */
1498                         if (attr->length != 6)
1499                                 break;
1500                         vlan_id = WPA_GET_BE24(data + 1);
1501                         if (vlan_id <= 0)
1502                                 break;
1503                         if (data[0] == 0x32)
1504                                 *untagged = vlan_id;
1505                         else if (data[0] == 0x31 && tagged &&
1506                                  taggedidx < numtagged)
1507                                 tagged[taggedidx++] = vlan_id;
1508                         break;
1509                 }
1510         }
1511
1512         /* Use tunnel with the lowest tag for untagged VLAN id */
1513         for (i = 0; i < RADIUS_TUNNEL_TAGS; i++) {
1514                 tun = &tunnel[i];
1515                 if (tun->tag_used &&
1516                     tun->type == RADIUS_TUNNEL_TYPE_VLAN &&
1517                     tun->medium_type == RADIUS_TUNNEL_MEDIUM_TYPE_802 &&
1518                     tun->vlanid > 0) {
1519                         *untagged = tun->vlanid;
1520                         break;
1521                 }
1522         }
1523
1524         if (taggedidx)
1525                 qsort(tagged, taggedidx, sizeof(int), cmp_int);
1526
1527         if (*untagged > 0 || taggedidx)
1528                 return 1;
1529         return 0;
1530 }
1531
1532
1533 /**
1534  * radius_msg_get_tunnel_password - Parse RADIUS attribute Tunnel-Password
1535  * @msg: Received RADIUS message
1536  * @keylen: Length of returned password
1537  * @secret: RADIUS shared secret
1538  * @secret_len: Length of secret
1539  * @sent_msg: Sent RADIUS message
1540  * @n: Number of password attribute to return (starting with 0)
1541  * Returns: Pointer to n-th password (free with os_free) or %NULL
1542  */
1543 char * radius_msg_get_tunnel_password(struct radius_msg *msg, int *keylen,
1544                                       const u8 *secret, size_t secret_len,
1545                                       struct radius_msg *sent_msg, size_t n)
1546 {
1547         u8 *buf = NULL;
1548         size_t buflen;
1549         const u8 *salt;
1550         u8 *str;
1551         const u8 *addr[3];
1552         size_t len[3];
1553         u8 hash[16];
1554         u8 *pos;
1555         size_t i, j = 0;
1556         struct radius_attr_hdr *attr;
1557         const u8 *data;
1558         size_t dlen;
1559         const u8 *fdata = NULL; /* points to found item */
1560         size_t fdlen = -1;
1561         char *ret = NULL;
1562
1563         /* find n-th valid Tunnel-Password attribute */
1564         for (i = 0; i < msg->attr_used; i++) {
1565                 attr = radius_get_attr_hdr(msg, i);
1566                 if (attr == NULL ||
1567                     attr->type != RADIUS_ATTR_TUNNEL_PASSWORD) {
1568                         continue;
1569                 }
1570                 if (attr->length <= 5)
1571                         continue;
1572                 data = (const u8 *) (attr + 1);
1573                 dlen = attr->length - sizeof(*attr);
1574                 if (dlen <= 3 || dlen % 16 != 3)
1575                         continue;
1576                 j++;
1577                 if (j <= n)
1578                         continue;
1579
1580                 fdata = data;
1581                 fdlen = dlen;
1582                 break;
1583         }
1584         if (fdata == NULL)
1585                 goto out;
1586
1587         /* alloc writable memory for decryption */
1588         buf = os_malloc(fdlen);
1589         if (buf == NULL)
1590                 goto out;
1591         os_memcpy(buf, fdata, fdlen);
1592         buflen = fdlen;
1593
1594         /* init pointers */
1595         salt = buf + 1;
1596         str = buf + 3;
1597
1598         /* decrypt blocks */
1599         pos = buf + buflen - 16; /* last block */
1600         while (pos >= str + 16) { /* all but the first block */
1601                 addr[0] = secret;
1602                 len[0] = secret_len;
1603                 addr[1] = pos - 16;
1604                 len[1] = 16;
1605                 md5_vector(2, addr, len, hash);
1606
1607                 for (i = 0; i < 16; i++)
1608                         pos[i] ^= hash[i];
1609
1610                 pos -= 16;
1611         }
1612
1613         /* decrypt first block */
1614         if (str != pos)
1615                 goto out;
1616         addr[0] = secret;
1617         len[0] = secret_len;
1618         addr[1] = sent_msg->hdr->authenticator;
1619         len[1] = 16;
1620         addr[2] = salt;
1621         len[2] = 2;
1622         md5_vector(3, addr, len, hash);
1623
1624         for (i = 0; i < 16; i++)
1625                 pos[i] ^= hash[i];
1626
1627         /* derive plaintext length from first subfield */
1628         *keylen = (unsigned char) str[0];
1629         if ((u8 *) (str + *keylen) >= (u8 *) (buf + buflen)) {
1630                 /* decryption error - invalid key length */
1631                 goto out;
1632         }
1633         if (*keylen == 0) {
1634                 /* empty password */
1635                 goto out;
1636         }
1637
1638         /* copy passphrase into new buffer */
1639         ret = os_malloc(*keylen);
1640         if (ret)
1641                 os_memcpy(ret, str + 1, *keylen);
1642
1643 out:
1644         /* return new buffer */
1645         os_free(buf);
1646         return ret;
1647 }
1648
1649
1650 void radius_free_class(struct radius_class_data *c)
1651 {
1652         size_t i;
1653         if (c == NULL)
1654                 return;
1655         for (i = 0; i < c->count; i++)
1656                 os_free(c->attr[i].data);
1657         os_free(c->attr);
1658         c->attr = NULL;
1659         c->count = 0;
1660 }
1661
1662
1663 int radius_copy_class(struct radius_class_data *dst,
1664                       const struct radius_class_data *src)
1665 {
1666         size_t i;
1667
1668         if (src->attr == NULL)
1669                 return 0;
1670
1671         dst->attr = os_calloc(src->count, sizeof(struct radius_attr_data));
1672         if (dst->attr == NULL)
1673                 return -1;
1674
1675         dst->count = 0;
1676
1677         for (i = 0; i < src->count; i++) {
1678                 dst->attr[i].data = os_malloc(src->attr[i].len);
1679                 if (dst->attr[i].data == NULL)
1680                         break;
1681                 dst->count++;
1682                 os_memcpy(dst->attr[i].data, src->attr[i].data,
1683                           src->attr[i].len);
1684                 dst->attr[i].len = src->attr[i].len;
1685         }
1686
1687         return 0;
1688 }
1689
1690
1691 u8 radius_msg_find_unlisted_attr(struct radius_msg *msg, u8 *attrs)
1692 {
1693         size_t i, j;
1694         struct radius_attr_hdr *attr;
1695
1696         for (i = 0; i < msg->attr_used; i++) {
1697                 attr = radius_get_attr_hdr(msg, i);
1698
1699                 for (j = 0; attrs[j]; j++) {
1700                         if (attr->type == attrs[j])
1701                                 break;
1702                 }
1703
1704                 if (attrs[j] == 0)
1705                         return attr->type; /* unlisted attr */
1706         }
1707
1708         return 0;
1709 }
1710
1711
1712 int radius_gen_session_id(u8 *id, size_t len)
1713 {
1714         /*
1715          * Acct-Session-Id and Acct-Multi-Session-Id should be globally and
1716          * temporarily unique. A high quality random number is required
1717          * therefore. This could be be improved by switching to a GUID.
1718          */
1719         return os_get_random(id, len);
1720 }