Check hmac_md5() result in radius_msg_verify_msg_auth()
[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         if (hmac_md5(secret, secret_len, wpabuf_head(msg->buf),
822                      wpabuf_len(msg->buf), auth) < 0)
823                 return 1;
824         os_memcpy(attr + 1, orig, MD5_MAC_LEN);
825         if (req_auth) {
826                 os_memcpy(msg->hdr->authenticator, orig_authenticator,
827                           sizeof(orig_authenticator));
828         }
829
830         if (os_memcmp_const(orig, auth, MD5_MAC_LEN) != 0) {
831                 wpa_printf(MSG_INFO, "Invalid Message-Authenticator!");
832                 return 1;
833         }
834
835         return 0;
836 }
837
838
839 int radius_msg_verify(struct radius_msg *msg, const u8 *secret,
840                       size_t secret_len, struct radius_msg *sent_msg, int auth)
841 {
842         const u8 *addr[4];
843         size_t len[4];
844         u8 hash[MD5_MAC_LEN];
845
846         if (sent_msg == NULL) {
847                 wpa_printf(MSG_INFO, "No matching Access-Request message found");
848                 return 1;
849         }
850
851         if (auth &&
852             radius_msg_verify_msg_auth(msg, secret, secret_len,
853                                        sent_msg->hdr->authenticator)) {
854                 return 1;
855         }
856
857         /* ResponseAuth = MD5(Code+ID+Length+RequestAuth+Attributes+Secret) */
858         addr[0] = (u8 *) msg->hdr;
859         len[0] = 1 + 1 + 2;
860         addr[1] = sent_msg->hdr->authenticator;
861         len[1] = MD5_MAC_LEN;
862         addr[2] = wpabuf_head_u8(msg->buf) + sizeof(struct radius_hdr);
863         len[2] = wpabuf_len(msg->buf) - sizeof(struct radius_hdr);
864         addr[3] = secret;
865         len[3] = secret_len;
866         if (md5_vector(4, addr, len, hash) < 0 ||
867             os_memcmp_const(hash, msg->hdr->authenticator, MD5_MAC_LEN) != 0) {
868                 wpa_printf(MSG_INFO, "Response Authenticator invalid!");
869                 return 1;
870         }
871
872         return 0;
873 }
874
875
876 int radius_msg_copy_attr(struct radius_msg *dst, struct radius_msg *src,
877                          u8 type)
878 {
879         struct radius_attr_hdr *attr;
880         size_t i;
881         int count = 0;
882
883         for (i = 0; i < src->attr_used; i++) {
884                 attr = radius_get_attr_hdr(src, i);
885                 if (attr->type == type && attr->length >= sizeof(*attr)) {
886                         if (!radius_msg_add_attr(dst, type, (u8 *) (attr + 1),
887                                                  attr->length - sizeof(*attr)))
888                                 return -1;
889                         count++;
890                 }
891         }
892
893         return count;
894 }
895
896
897 /* Create Request Authenticator. The value should be unique over the lifetime
898  * of the shared secret between authenticator and authentication server.
899  */
900 int radius_msg_make_authenticator(struct radius_msg *msg)
901 {
902         return os_get_random((u8 *) &msg->hdr->authenticator,
903                              sizeof(msg->hdr->authenticator));
904 }
905
906
907 /* Get Vendor-specific RADIUS Attribute from a parsed RADIUS message.
908  * Returns the Attribute payload and sets alen to indicate the length of the
909  * payload if a vendor attribute with subtype is found, otherwise returns NULL.
910  * The returned payload is allocated with os_malloc() and caller must free it
911  * by calling os_free().
912  */
913 static u8 *radius_msg_get_vendor_attr(struct radius_msg *msg, u32 vendor,
914                                       u8 subtype, size_t *alen)
915 {
916         u8 *data, *pos;
917         size_t i, len;
918
919         if (msg == NULL)
920                 return NULL;
921
922         for (i = 0; i < msg->attr_used; i++) {
923                 struct radius_attr_hdr *attr = radius_get_attr_hdr(msg, i);
924                 size_t left;
925                 u32 vendor_id;
926                 struct radius_attr_vendor *vhdr;
927
928                 if (attr->type != RADIUS_ATTR_VENDOR_SPECIFIC ||
929                     attr->length < sizeof(*attr))
930                         continue;
931
932                 left = attr->length - sizeof(*attr);
933                 if (left < 4)
934                         continue;
935
936                 pos = (u8 *) (attr + 1);
937
938                 os_memcpy(&vendor_id, pos, 4);
939                 pos += 4;
940                 left -= 4;
941
942                 if (ntohl(vendor_id) != vendor)
943                         continue;
944
945                 while (left >= sizeof(*vhdr)) {
946                         vhdr = (struct radius_attr_vendor *) pos;
947                         if (vhdr->vendor_length > left ||
948                             vhdr->vendor_length < sizeof(*vhdr)) {
949                                 break;
950                         }
951                         if (vhdr->vendor_type != subtype) {
952                                 pos += vhdr->vendor_length;
953                                 left -= vhdr->vendor_length;
954                                 continue;
955                         }
956
957                         len = vhdr->vendor_length - sizeof(*vhdr);
958                         data = os_malloc(len);
959                         if (data == NULL)
960                                 return NULL;
961                         os_memcpy(data, pos + sizeof(*vhdr), len);
962                         if (alen)
963                                 *alen = len;
964                         return data;
965                 }
966         }
967
968         return NULL;
969 }
970
971
972 static u8 * decrypt_ms_key(const u8 *key, size_t len,
973                            const u8 *req_authenticator,
974                            const u8 *secret, size_t secret_len, size_t *reslen)
975 {
976         u8 *plain, *ppos, *res;
977         const u8 *pos;
978         size_t left, plen;
979         u8 hash[MD5_MAC_LEN];
980         int i, first = 1;
981         const u8 *addr[3];
982         size_t elen[3];
983
984         /* key: 16-bit salt followed by encrypted key info */
985
986         if (len < 2 + 16) {
987                 wpa_printf(MSG_DEBUG, "RADIUS: %s: Len is too small: %d",
988                            __func__, (int) len);
989                 return NULL;
990         }
991
992         pos = key + 2;
993         left = len - 2;
994         if (left % 16) {
995                 wpa_printf(MSG_INFO, "RADIUS: Invalid ms key len %lu",
996                            (unsigned long) left);
997                 return NULL;
998         }
999
1000         plen = left;
1001         ppos = plain = os_malloc(plen);
1002         if (plain == NULL)
1003                 return NULL;
1004         plain[0] = 0;
1005
1006         while (left > 0) {
1007                 /* b(1) = MD5(Secret + Request-Authenticator + Salt)
1008                  * b(i) = MD5(Secret + c(i - 1)) for i > 1 */
1009
1010                 addr[0] = secret;
1011                 elen[0] = secret_len;
1012                 if (first) {
1013                         addr[1] = req_authenticator;
1014                         elen[1] = MD5_MAC_LEN;
1015                         addr[2] = key;
1016                         elen[2] = 2; /* Salt */
1017                 } else {
1018                         addr[1] = pos - MD5_MAC_LEN;
1019                         elen[1] = MD5_MAC_LEN;
1020                 }
1021                 md5_vector(first ? 3 : 2, addr, elen, hash);
1022                 first = 0;
1023
1024                 for (i = 0; i < MD5_MAC_LEN; i++)
1025                         *ppos++ = *pos++ ^ hash[i];
1026                 left -= MD5_MAC_LEN;
1027         }
1028
1029         if (plain[0] == 0 || plain[0] > plen - 1) {
1030                 wpa_printf(MSG_INFO, "RADIUS: Failed to decrypt MPPE key");
1031                 os_free(plain);
1032                 return NULL;
1033         }
1034
1035         res = os_malloc(plain[0]);
1036         if (res == NULL) {
1037                 os_free(plain);
1038                 return NULL;
1039         }
1040         os_memcpy(res, plain + 1, plain[0]);
1041         if (reslen)
1042                 *reslen = plain[0];
1043         os_free(plain);
1044         return res;
1045 }
1046
1047
1048 static void encrypt_ms_key(const u8 *key, size_t key_len, u16 salt,
1049                            const u8 *req_authenticator,
1050                            const u8 *secret, size_t secret_len,
1051                            u8 *ebuf, size_t *elen)
1052 {
1053         int i, len, first = 1;
1054         u8 hash[MD5_MAC_LEN], saltbuf[2], *pos;
1055         const u8 *addr[3];
1056         size_t _len[3];
1057
1058         WPA_PUT_BE16(saltbuf, salt);
1059
1060         len = 1 + key_len;
1061         if (len & 0x0f) {
1062                 len = (len & 0xf0) + 16;
1063         }
1064         os_memset(ebuf, 0, len);
1065         ebuf[0] = key_len;
1066         os_memcpy(ebuf + 1, key, key_len);
1067
1068         *elen = len;
1069
1070         pos = ebuf;
1071         while (len > 0) {
1072                 /* b(1) = MD5(Secret + Request-Authenticator + Salt)
1073                  * b(i) = MD5(Secret + c(i - 1)) for i > 1 */
1074                 addr[0] = secret;
1075                 _len[0] = secret_len;
1076                 if (first) {
1077                         addr[1] = req_authenticator;
1078                         _len[1] = MD5_MAC_LEN;
1079                         addr[2] = saltbuf;
1080                         _len[2] = sizeof(saltbuf);
1081                 } else {
1082                         addr[1] = pos - MD5_MAC_LEN;
1083                         _len[1] = MD5_MAC_LEN;
1084                 }
1085                 md5_vector(first ? 3 : 2, addr, _len, hash);
1086                 first = 0;
1087
1088                 for (i = 0; i < MD5_MAC_LEN; i++)
1089                         *pos++ ^= hash[i];
1090
1091                 len -= MD5_MAC_LEN;
1092         }
1093 }
1094
1095
1096 struct radius_ms_mppe_keys *
1097 radius_msg_get_ms_keys(struct radius_msg *msg, struct radius_msg *sent_msg,
1098                        const u8 *secret, size_t secret_len)
1099 {
1100         u8 *key;
1101         size_t keylen;
1102         struct radius_ms_mppe_keys *keys;
1103
1104         if (msg == NULL || sent_msg == NULL)
1105                 return NULL;
1106
1107         keys = os_zalloc(sizeof(*keys));
1108         if (keys == NULL)
1109                 return NULL;
1110
1111         key = radius_msg_get_vendor_attr(msg, RADIUS_VENDOR_ID_MICROSOFT,
1112                                          RADIUS_VENDOR_ATTR_MS_MPPE_SEND_KEY,
1113                                          &keylen);
1114         if (key) {
1115                 keys->send = decrypt_ms_key(key, keylen,
1116                                             sent_msg->hdr->authenticator,
1117                                             secret, secret_len,
1118                                             &keys->send_len);
1119                 if (!keys->send) {
1120                         wpa_printf(MSG_DEBUG,
1121                                    "RADIUS: Failed to decrypt send key");
1122                 }
1123                 os_free(key);
1124         }
1125
1126         key = radius_msg_get_vendor_attr(msg, RADIUS_VENDOR_ID_MICROSOFT,
1127                                          RADIUS_VENDOR_ATTR_MS_MPPE_RECV_KEY,
1128                                          &keylen);
1129         if (key) {
1130                 keys->recv = decrypt_ms_key(key, keylen,
1131                                             sent_msg->hdr->authenticator,
1132                                             secret, secret_len,
1133                                             &keys->recv_len);
1134                 if (!keys->recv) {
1135                         wpa_printf(MSG_DEBUG,
1136                                    "RADIUS: Failed to decrypt recv key");
1137                 }
1138                 os_free(key);
1139         }
1140
1141         return keys;
1142 }
1143
1144
1145 struct radius_ms_mppe_keys *
1146 radius_msg_get_cisco_keys(struct radius_msg *msg, struct radius_msg *sent_msg,
1147                           const u8 *secret, size_t secret_len)
1148 {
1149         u8 *key;
1150         size_t keylen;
1151         struct radius_ms_mppe_keys *keys;
1152
1153         if (msg == NULL || sent_msg == NULL)
1154                 return NULL;
1155
1156         keys = os_zalloc(sizeof(*keys));
1157         if (keys == NULL)
1158                 return NULL;
1159
1160         key = radius_msg_get_vendor_attr(msg, RADIUS_VENDOR_ID_CISCO,
1161                                          RADIUS_CISCO_AV_PAIR, &keylen);
1162         if (key && keylen == 51 &&
1163             os_memcmp(key, "leap:session-key=", 17) == 0) {
1164                 keys->recv = decrypt_ms_key(key + 17, keylen - 17,
1165                                             sent_msg->hdr->authenticator,
1166                                             secret, secret_len,
1167                                             &keys->recv_len);
1168         }
1169         os_free(key);
1170
1171         return keys;
1172 }
1173
1174
1175 int radius_msg_add_mppe_keys(struct radius_msg *msg,
1176                              const u8 *req_authenticator,
1177                              const u8 *secret, size_t secret_len,
1178                              const u8 *send_key, size_t send_key_len,
1179                              const u8 *recv_key, size_t recv_key_len)
1180 {
1181         struct radius_attr_hdr *attr;
1182         u32 vendor_id = htonl(RADIUS_VENDOR_ID_MICROSOFT);
1183         u8 *buf;
1184         struct radius_attr_vendor *vhdr;
1185         u8 *pos;
1186         size_t elen;
1187         int hlen;
1188         u16 salt;
1189
1190         hlen = sizeof(vendor_id) + sizeof(*vhdr) + 2;
1191
1192         /* MS-MPPE-Send-Key */
1193         buf = os_malloc(hlen + send_key_len + 16);
1194         if (buf == NULL) {
1195                 return 0;
1196         }
1197         pos = buf;
1198         os_memcpy(pos, &vendor_id, sizeof(vendor_id));
1199         pos += sizeof(vendor_id);
1200         vhdr = (struct radius_attr_vendor *) pos;
1201         vhdr->vendor_type = RADIUS_VENDOR_ATTR_MS_MPPE_SEND_KEY;
1202         pos = (u8 *) (vhdr + 1);
1203         if (os_get_random((u8 *) &salt, sizeof(salt)) < 0) {
1204                 os_free(buf);
1205                 return 0;
1206         }
1207         salt |= 0x8000;
1208         WPA_PUT_BE16(pos, salt);
1209         pos += 2;
1210         encrypt_ms_key(send_key, send_key_len, salt, req_authenticator, secret,
1211                        secret_len, pos, &elen);
1212         vhdr->vendor_length = hlen + elen - sizeof(vendor_id);
1213
1214         attr = radius_msg_add_attr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
1215                                    buf, hlen + elen);
1216         os_free(buf);
1217         if (attr == NULL) {
1218                 return 0;
1219         }
1220
1221         /* MS-MPPE-Recv-Key */
1222         buf = os_malloc(hlen + recv_key_len + 16);
1223         if (buf == NULL) {
1224                 return 0;
1225         }
1226         pos = buf;
1227         os_memcpy(pos, &vendor_id, sizeof(vendor_id));
1228         pos += sizeof(vendor_id);
1229         vhdr = (struct radius_attr_vendor *) pos;
1230         vhdr->vendor_type = RADIUS_VENDOR_ATTR_MS_MPPE_RECV_KEY;
1231         pos = (u8 *) (vhdr + 1);
1232         salt ^= 1;
1233         WPA_PUT_BE16(pos, salt);
1234         pos += 2;
1235         encrypt_ms_key(recv_key, recv_key_len, salt, req_authenticator, secret,
1236                        secret_len, pos, &elen);
1237         vhdr->vendor_length = hlen + elen - sizeof(vendor_id);
1238
1239         attr = radius_msg_add_attr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
1240                                    buf, hlen + elen);
1241         os_free(buf);
1242         if (attr == NULL) {
1243                 return 0;
1244         }
1245
1246         return 1;
1247 }
1248
1249
1250 int radius_msg_add_wfa(struct radius_msg *msg, u8 subtype, const u8 *data,
1251                        size_t len)
1252 {
1253         struct radius_attr_hdr *attr;
1254         u8 *buf, *pos;
1255         size_t alen;
1256
1257         alen = 4 + 2 + len;
1258         buf = os_malloc(alen);
1259         if (buf == NULL)
1260                 return 0;
1261         pos = buf;
1262         WPA_PUT_BE32(pos, RADIUS_VENDOR_ID_WFA);
1263         pos += 4;
1264         *pos++ = subtype;
1265         *pos++ = 2 + len;
1266         os_memcpy(pos, data, len);
1267         attr = radius_msg_add_attr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
1268                                    buf, alen);
1269         os_free(buf);
1270         if (attr == NULL)
1271                 return 0;
1272
1273         return 1;
1274 }
1275
1276
1277 int radius_user_password_hide(struct radius_msg *msg,
1278                               const u8 *data, size_t data_len,
1279                               const u8 *secret, size_t secret_len,
1280                               u8 *buf, size_t buf_len)
1281 {
1282         size_t padlen, i, pos;
1283         const u8 *addr[2];
1284         size_t len[2];
1285         u8 hash[16];
1286
1287         if (data_len + 16 > buf_len)
1288                 return -1;
1289
1290         os_memcpy(buf, data, data_len);
1291
1292         padlen = data_len % 16;
1293         if (padlen && data_len < buf_len) {
1294                 padlen = 16 - padlen;
1295                 os_memset(buf + data_len, 0, padlen);
1296                 buf_len = data_len + padlen;
1297         } else {
1298                 buf_len = data_len;
1299         }
1300
1301         addr[0] = secret;
1302         len[0] = secret_len;
1303         addr[1] = msg->hdr->authenticator;
1304         len[1] = 16;
1305         md5_vector(2, addr, len, hash);
1306
1307         for (i = 0; i < 16; i++)
1308                 buf[i] ^= hash[i];
1309         pos = 16;
1310
1311         while (pos < buf_len) {
1312                 addr[0] = secret;
1313                 len[0] = secret_len;
1314                 addr[1] = &buf[pos - 16];
1315                 len[1] = 16;
1316                 md5_vector(2, addr, len, hash);
1317
1318                 for (i = 0; i < 16; i++)
1319                         buf[pos + i] ^= hash[i];
1320
1321                 pos += 16;
1322         }
1323
1324         return buf_len;
1325 }
1326
1327
1328 /* Add User-Password attribute to a RADIUS message and encrypt it as specified
1329  * in RFC 2865, Chap. 5.2 */
1330 struct radius_attr_hdr *
1331 radius_msg_add_attr_user_password(struct radius_msg *msg,
1332                                   const u8 *data, size_t data_len,
1333                                   const u8 *secret, size_t secret_len)
1334 {
1335         u8 buf[128];
1336         int res;
1337
1338         res = radius_user_password_hide(msg, data, data_len,
1339                                         secret, secret_len, buf, sizeof(buf));
1340         if (res < 0)
1341                 return NULL;
1342
1343         return radius_msg_add_attr(msg, RADIUS_ATTR_USER_PASSWORD,
1344                                    buf, res);
1345 }
1346
1347
1348 int radius_msg_get_attr(struct radius_msg *msg, u8 type, u8 *buf, size_t len)
1349 {
1350         struct radius_attr_hdr *attr = NULL, *tmp;
1351         size_t i, dlen;
1352
1353         for (i = 0; i < msg->attr_used; i++) {
1354                 tmp = radius_get_attr_hdr(msg, i);
1355                 if (tmp->type == type) {
1356                         attr = tmp;
1357                         break;
1358                 }
1359         }
1360
1361         if (!attr || attr->length < sizeof(*attr))
1362                 return -1;
1363
1364         dlen = attr->length - sizeof(*attr);
1365         if (buf)
1366                 os_memcpy(buf, (attr + 1), dlen > len ? len : dlen);
1367         return dlen;
1368 }
1369
1370
1371 int radius_msg_get_attr_ptr(struct radius_msg *msg, u8 type, u8 **buf,
1372                             size_t *len, const u8 *start)
1373 {
1374         size_t i;
1375         struct radius_attr_hdr *attr = NULL, *tmp;
1376
1377         for (i = 0; i < msg->attr_used; i++) {
1378                 tmp = radius_get_attr_hdr(msg, i);
1379                 if (tmp->type == type &&
1380                     (start == NULL || (u8 *) tmp > start)) {
1381                         attr = tmp;
1382                         break;
1383                 }
1384         }
1385
1386         if (!attr || attr->length < sizeof(*attr))
1387                 return -1;
1388
1389         *buf = (u8 *) (attr + 1);
1390         *len = attr->length - sizeof(*attr);
1391         return 0;
1392 }
1393
1394
1395 int radius_msg_count_attr(struct radius_msg *msg, u8 type, int min_len)
1396 {
1397         size_t i;
1398         int count;
1399
1400         for (count = 0, i = 0; i < msg->attr_used; i++) {
1401                 struct radius_attr_hdr *attr = radius_get_attr_hdr(msg, i);
1402                 if (attr->type == type &&
1403                     attr->length >= sizeof(struct radius_attr_hdr) + min_len)
1404                         count++;
1405         }
1406
1407         return count;
1408 }
1409
1410
1411 struct radius_tunnel_attrs {
1412         int tag_used;
1413         int type; /* Tunnel-Type */
1414         int medium_type; /* Tunnel-Medium-Type */
1415         int vlanid;
1416 };
1417
1418
1419 static int cmp_int(const void *a, const void *b)
1420 {
1421         int x, y;
1422
1423         x = *((int *) a);
1424         y = *((int *) b);
1425         return (x - y);
1426 }
1427
1428
1429 /**
1430  * radius_msg_get_vlanid - Parse RADIUS attributes for VLAN tunnel information
1431  * The k tagged vlans found are sorted by vlan_id and stored in the first k
1432  * items of tagged.
1433  *
1434  * @msg: RADIUS message
1435  * @untagged: Pointer to store untagged vid
1436  * @numtagged: Size of tagged
1437  * @tagged: Pointer to store tagged list
1438  *
1439  * Returns: 0 if neither tagged nor untagged configuration is found, 1 otherwise
1440  */
1441 int radius_msg_get_vlanid(struct radius_msg *msg, int *untagged, int numtagged,
1442                           int *tagged)
1443 {
1444         struct radius_tunnel_attrs tunnel[RADIUS_TUNNEL_TAGS], *tun;
1445         size_t i;
1446         struct radius_attr_hdr *attr = NULL;
1447         const u8 *data;
1448         char buf[10];
1449         size_t dlen;
1450         int j, taggedidx = 0, vlan_id;
1451
1452         os_memset(&tunnel, 0, sizeof(tunnel));
1453         for (j = 0; j < numtagged; j++)
1454                 tagged[j] = 0;
1455         *untagged = 0;
1456
1457         for (i = 0; i < msg->attr_used; i++) {
1458                 attr = radius_get_attr_hdr(msg, i);
1459                 if (attr->length < sizeof(*attr))
1460                         return -1;
1461                 data = (const u8 *) (attr + 1);
1462                 dlen = attr->length - sizeof(*attr);
1463                 if (attr->length < 3)
1464                         continue;
1465                 if (data[0] >= RADIUS_TUNNEL_TAGS)
1466                         tun = &tunnel[0];
1467                 else
1468                         tun = &tunnel[data[0]];
1469
1470                 switch (attr->type) {
1471                 case RADIUS_ATTR_TUNNEL_TYPE:
1472                         if (attr->length != 6)
1473                                 break;
1474                         tun->tag_used++;
1475                         tun->type = WPA_GET_BE24(data + 1);
1476                         break;
1477                 case RADIUS_ATTR_TUNNEL_MEDIUM_TYPE:
1478                         if (attr->length != 6)
1479                                 break;
1480                         tun->tag_used++;
1481                         tun->medium_type = WPA_GET_BE24(data + 1);
1482                         break;
1483                 case RADIUS_ATTR_TUNNEL_PRIVATE_GROUP_ID:
1484                         if (data[0] < RADIUS_TUNNEL_TAGS) {
1485                                 data++;
1486                                 dlen--;
1487                         }
1488                         if (dlen >= sizeof(buf))
1489                                 break;
1490                         os_memcpy(buf, data, dlen);
1491                         buf[dlen] = '\0';
1492                         vlan_id = atoi(buf);
1493                         if (vlan_id <= 0)
1494                                 break;
1495                         tun->tag_used++;
1496                         tun->vlanid = vlan_id;
1497                         break;
1498                 case RADIUS_ATTR_EGRESS_VLANID: /* RFC 4675 */
1499                         if (attr->length != 6)
1500                                 break;
1501                         vlan_id = WPA_GET_BE24(data + 1);
1502                         if (vlan_id <= 0)
1503                                 break;
1504                         if (data[0] == 0x32)
1505                                 *untagged = vlan_id;
1506                         else if (data[0] == 0x31 && tagged &&
1507                                  taggedidx < numtagged)
1508                                 tagged[taggedidx++] = vlan_id;
1509                         break;
1510                 }
1511         }
1512
1513         /* Use tunnel with the lowest tag for untagged VLAN id */
1514         for (i = 0; i < RADIUS_TUNNEL_TAGS; i++) {
1515                 tun = &tunnel[i];
1516                 if (tun->tag_used &&
1517                     tun->type == RADIUS_TUNNEL_TYPE_VLAN &&
1518                     tun->medium_type == RADIUS_TUNNEL_MEDIUM_TYPE_802 &&
1519                     tun->vlanid > 0) {
1520                         *untagged = tun->vlanid;
1521                         break;
1522                 }
1523         }
1524
1525         if (taggedidx)
1526                 qsort(tagged, taggedidx, sizeof(int), cmp_int);
1527
1528         if (*untagged > 0 || taggedidx)
1529                 return 1;
1530         return 0;
1531 }
1532
1533
1534 /**
1535  * radius_msg_get_tunnel_password - Parse RADIUS attribute Tunnel-Password
1536  * @msg: Received RADIUS message
1537  * @keylen: Length of returned password
1538  * @secret: RADIUS shared secret
1539  * @secret_len: Length of secret
1540  * @sent_msg: Sent RADIUS message
1541  * @n: Number of password attribute to return (starting with 0)
1542  * Returns: Pointer to n-th password (free with os_free) or %NULL
1543  */
1544 char * radius_msg_get_tunnel_password(struct radius_msg *msg, int *keylen,
1545                                       const u8 *secret, size_t secret_len,
1546                                       struct radius_msg *sent_msg, size_t n)
1547 {
1548         u8 *buf = NULL;
1549         size_t buflen;
1550         const u8 *salt;
1551         u8 *str;
1552         const u8 *addr[3];
1553         size_t len[3];
1554         u8 hash[16];
1555         u8 *pos;
1556         size_t i, j = 0;
1557         struct radius_attr_hdr *attr;
1558         const u8 *data;
1559         size_t dlen;
1560         const u8 *fdata = NULL; /* points to found item */
1561         size_t fdlen = -1;
1562         char *ret = NULL;
1563
1564         /* find n-th valid Tunnel-Password attribute */
1565         for (i = 0; i < msg->attr_used; i++) {
1566                 attr = radius_get_attr_hdr(msg, i);
1567                 if (attr == NULL ||
1568                     attr->type != RADIUS_ATTR_TUNNEL_PASSWORD) {
1569                         continue;
1570                 }
1571                 if (attr->length <= 5)
1572                         continue;
1573                 data = (const u8 *) (attr + 1);
1574                 dlen = attr->length - sizeof(*attr);
1575                 if (dlen <= 3 || dlen % 16 != 3)
1576                         continue;
1577                 j++;
1578                 if (j <= n)
1579                         continue;
1580
1581                 fdata = data;
1582                 fdlen = dlen;
1583                 break;
1584         }
1585         if (fdata == NULL)
1586                 goto out;
1587
1588         /* alloc writable memory for decryption */
1589         buf = os_malloc(fdlen);
1590         if (buf == NULL)
1591                 goto out;
1592         os_memcpy(buf, fdata, fdlen);
1593         buflen = fdlen;
1594
1595         /* init pointers */
1596         salt = buf + 1;
1597         str = buf + 3;
1598
1599         /* decrypt blocks */
1600         pos = buf + buflen - 16; /* last block */
1601         while (pos >= str + 16) { /* all but the first block */
1602                 addr[0] = secret;
1603                 len[0] = secret_len;
1604                 addr[1] = pos - 16;
1605                 len[1] = 16;
1606                 md5_vector(2, addr, len, hash);
1607
1608                 for (i = 0; i < 16; i++)
1609                         pos[i] ^= hash[i];
1610
1611                 pos -= 16;
1612         }
1613
1614         /* decrypt first block */
1615         if (str != pos)
1616                 goto out;
1617         addr[0] = secret;
1618         len[0] = secret_len;
1619         addr[1] = sent_msg->hdr->authenticator;
1620         len[1] = 16;
1621         addr[2] = salt;
1622         len[2] = 2;
1623         md5_vector(3, addr, len, hash);
1624
1625         for (i = 0; i < 16; i++)
1626                 pos[i] ^= hash[i];
1627
1628         /* derive plaintext length from first subfield */
1629         *keylen = (unsigned char) str[0];
1630         if ((u8 *) (str + *keylen) >= (u8 *) (buf + buflen)) {
1631                 /* decryption error - invalid key length */
1632                 goto out;
1633         }
1634         if (*keylen == 0) {
1635                 /* empty password */
1636                 goto out;
1637         }
1638
1639         /* copy passphrase into new buffer */
1640         ret = os_malloc(*keylen);
1641         if (ret)
1642                 os_memcpy(ret, str + 1, *keylen);
1643
1644 out:
1645         /* return new buffer */
1646         os_free(buf);
1647         return ret;
1648 }
1649
1650
1651 void radius_free_class(struct radius_class_data *c)
1652 {
1653         size_t i;
1654         if (c == NULL)
1655                 return;
1656         for (i = 0; i < c->count; i++)
1657                 os_free(c->attr[i].data);
1658         os_free(c->attr);
1659         c->attr = NULL;
1660         c->count = 0;
1661 }
1662
1663
1664 int radius_copy_class(struct radius_class_data *dst,
1665                       const struct radius_class_data *src)
1666 {
1667         size_t i;
1668
1669         if (src->attr == NULL)
1670                 return 0;
1671
1672         dst->attr = os_calloc(src->count, sizeof(struct radius_attr_data));
1673         if (dst->attr == NULL)
1674                 return -1;
1675
1676         dst->count = 0;
1677
1678         for (i = 0; i < src->count; i++) {
1679                 dst->attr[i].data = os_malloc(src->attr[i].len);
1680                 if (dst->attr[i].data == NULL)
1681                         break;
1682                 dst->count++;
1683                 os_memcpy(dst->attr[i].data, src->attr[i].data,
1684                           src->attr[i].len);
1685                 dst->attr[i].len = src->attr[i].len;
1686         }
1687
1688         return 0;
1689 }
1690
1691
1692 u8 radius_msg_find_unlisted_attr(struct radius_msg *msg, u8 *attrs)
1693 {
1694         size_t i, j;
1695         struct radius_attr_hdr *attr;
1696
1697         for (i = 0; i < msg->attr_used; i++) {
1698                 attr = radius_get_attr_hdr(msg, i);
1699
1700                 for (j = 0; attrs[j]; j++) {
1701                         if (attr->type == attrs[j])
1702                                 break;
1703                 }
1704
1705                 if (attrs[j] == 0)
1706                         return attr->type; /* unlisted attr */
1707         }
1708
1709         return 0;
1710 }
1711
1712
1713 int radius_gen_session_id(u8 *id, size_t len)
1714 {
1715         /*
1716          * Acct-Session-Id and Acct-Multi-Session-Id should be globally and
1717          * temporarily unique. A high quality random number is required
1718          * therefore. This could be be improved by switching to a GUID.
1719          */
1720         return os_get_random(id, len);
1721 }