FR-GV-301 - handle malformed WiMAX attributes
[freeradius.git] / src / lib / radius.c
1 /*
2  *   This library is free software; you can redistribute it and/or
3  *   modify it under the terms of the GNU Lesser General Public
4  *   License as published by the Free Software Foundation; either
5  *   version 2.1 of the License, or (at your option) any later version.
6  *
7  *   This library is distributed in the hope that it will be useful,
8  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10  *   Lesser General Public License for more details.
11  *
12  *   You should have received a copy of the GNU Lesser General Public
13  *   License along with this library; if not, write to the Free Software
14  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15  */
16
17 /**
18  * $Id$
19  *
20  * @file radius.c
21  * @brief Functions to send/receive radius packets.
22  *
23  * @copyright 2000-2003,2006  The FreeRADIUS server project
24  */
25
26 RCSID("$Id$")
27
28 #include        <freeradius-devel/libradius.h>
29
30 #include        <freeradius-devel/md5.h>
31
32 #include        <fcntl.h>
33 #include        <ctype.h>
34
35 #ifdef WITH_UDPFROMTO
36 #include        <freeradius-devel/udpfromto.h>
37 #endif
38
39 /*
40  *      Some messages get printed out only in debugging mode.
41  */
42 #define FR_DEBUG_STRERROR_PRINTF if (fr_debug_lvl) fr_strerror_printf
43
44 #if 0
45 #define VP_TRACE printf
46
47 static void VP_HEXDUMP(char const *msg, uint8_t const *data, size_t len)
48 {
49         size_t i;
50
51         printf("--- %s ---\n", msg);
52         for (i = 0; i < len; i++) {
53                 if ((i & 0x0f) == 0) printf("%04x: ", (unsigned int) i);
54                 printf("%02x ", data[i]);
55                 if ((i & 0x0f) == 0x0f) printf("\n");
56         }
57         if ((len == 0x0f) || ((len & 0x0f) != 0x0f)) printf("\n");
58         fflush(stdout);
59 }
60
61 #else
62 #define VP_TRACE(_x, ...)
63 #define VP_HEXDUMP(_x, _y, _z)
64 #endif
65
66
67 /*
68  *      The maximum number of attributes which we allow in an incoming
69  *      request.  If there are more attributes than this, the request
70  *      is rejected.
71  *
72  *      This helps to minimize the potential for a DoS, when an
73  *      attacker spoofs Access-Request packets, which don't have a
74  *      Message-Authenticator attribute.  This means that the packet
75  *      is unsigned, and the attacker can use resources on the server,
76  *      even if the end request is rejected.
77  */
78 uint32_t fr_max_attributes = 0;
79 FILE *fr_log_fp = NULL;
80
81 typedef struct radius_packet_t {
82   uint8_t       code;
83   uint8_t       id;
84   uint8_t       length[2];
85   uint8_t       vector[AUTH_VECTOR_LEN];
86   uint8_t       data[1];
87 } radius_packet_t;
88
89 static fr_randctx fr_rand_pool; /* across multiple calls */
90 static int fr_rand_initialized = 0;
91 static unsigned int salt_offset = 0;
92 static uint8_t nullvector[AUTH_VECTOR_LEN] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* for CoA decode */
93
94 char const *fr_packet_codes[FR_MAX_PACKET_CODE] = {
95   "",                                   //!< 0
96   "Access-Request",
97   "Access-Accept",
98   "Access-Reject",
99   "Accounting-Request",
100   "Accounting-Response",
101   "Accounting-Status",
102   "Password-Request",
103   "Password-Accept",
104   "Password-Reject",
105   "Accounting-Message",                 //!< 10
106   "Access-Challenge",
107   "Status-Server",
108   "Status-Client",
109   "14",
110   "15",
111   "16",
112   "17",
113   "18",
114   "19",
115   "20",                                 //!< 20
116   "Resource-Free-Request",
117   "Resource-Free-Response",
118   "Resource-Query-Request",
119   "Resource-Query-Response",
120   "Alternate-Resource-Reclaim-Request",
121   "NAS-Reboot-Request",
122   "NAS-Reboot-Response",
123   "28",
124   "Next-Passcode",
125   "New-Pin",                            //!< 30
126   "Terminate-Session",
127   "Password-Expired",
128   "Event-Request",
129   "Event-Response",
130   "35",
131   "36",
132   "37",
133   "38",
134   "39",
135   "Disconnect-Request",                 //!< 40
136   "Disconnect-ACK",
137   "Disconnect-NAK",
138   "CoA-Request",
139   "CoA-ACK",
140   "CoA-NAK",
141   "46",
142   "47",
143   "48",
144   "49",
145   "IP-Address-Allocate",
146   "IP-Address-Release",                 //!< 50
147 };
148
149
150 void fr_printf_log(char const *fmt, ...)
151 {
152         va_list ap;
153
154         va_start(ap, fmt);
155         if ((fr_debug_lvl == 0) || !fr_log_fp) {
156                 va_end(ap);
157                 return;
158         }
159
160         vfprintf(fr_log_fp, fmt, ap);
161         va_end(ap);
162
163         return;
164 }
165
166 static char const tabs[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
167
168 static void print_hex_data(uint8_t const *ptr, int attrlen, int depth)
169 {
170         int i;
171
172         for (i = 0; i < attrlen; i++) {
173                 if ((i > 0) && ((i & 0x0f) == 0x00))
174                         fprintf(fr_log_fp, "%.*s", depth, tabs);
175                 fprintf(fr_log_fp, "%02x ", ptr[i]);
176                 if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
177         }
178         if ((i & 0x0f) != 0) fprintf(fr_log_fp, "\n");
179 }
180
181
182 void rad_print_hex(RADIUS_PACKET const *packet)
183 {
184         int i;
185
186         if (!packet->data || !fr_log_fp) return;
187
188         fprintf(fr_log_fp, "  Socket:\t%d\n", packet->sockfd);
189 #ifdef WITH_TCP
190         fprintf(fr_log_fp, "  Proto:\t%d\n", packet->proto);
191 #endif
192
193         if (packet->src_ipaddr.af == AF_INET) {
194                 char buffer[32];
195
196                 fprintf(fr_log_fp, "  Src IP:\t%s\n",
197                         inet_ntop(packet->src_ipaddr.af,
198                                   &packet->src_ipaddr.ipaddr,
199                                   buffer, sizeof(buffer)));
200                 fprintf(fr_log_fp, "    port:\t%u\n", packet->src_port);
201
202                 fprintf(fr_log_fp, "  Dst IP:\t%s\n",
203                         inet_ntop(packet->dst_ipaddr.af,
204                                   &packet->dst_ipaddr.ipaddr,
205                                   buffer, sizeof(buffer)));
206                 fprintf(fr_log_fp, "    port:\t%u\n", packet->dst_port);
207         }
208
209         if (packet->data[0] < FR_MAX_PACKET_CODE) {
210                 fprintf(fr_log_fp, "  Code:\t\t(%d) %s\n", packet->data[0], fr_packet_codes[packet->data[0]]);
211         } else {
212                 fprintf(fr_log_fp, "  Code:\t\t%u\n", packet->data[0]);
213         }
214         fprintf(fr_log_fp, "  Id:\t\t%u\n", packet->data[1]);
215         fprintf(fr_log_fp, "  Length:\t%u\n", ((packet->data[2] << 8) |
216                                    (packet->data[3])));
217         fprintf(fr_log_fp, "  Vector:\t");
218         for (i = 4; i < 20; i++) {
219                 fprintf(fr_log_fp, "%02x", packet->data[i]);
220         }
221         fprintf(fr_log_fp, "\n");
222
223         if (packet->data_len > 20) {
224                 int total;
225                 uint8_t const *ptr;
226                 fprintf(fr_log_fp, "  Data:");
227
228                 total = packet->data_len - 20;
229                 ptr = packet->data + 20;
230
231                 while (total > 0) {
232                         int attrlen;
233                         unsigned int vendor = 0;
234
235                         fprintf(fr_log_fp, "\t\t");
236                         if (total < 2) { /* too short */
237                                 fprintf(fr_log_fp, "%02x\n", *ptr);
238                                 break;
239                         }
240
241                         if (ptr[1] > total) { /* too long */
242                                 for (i = 0; i < total; i++) {
243                                         fprintf(fr_log_fp, "%02x ", ptr[i]);
244                                 }
245                                 break;
246                         }
247
248                         fprintf(fr_log_fp, "%02x  %02x  ", ptr[0], ptr[1]);
249                         attrlen = ptr[1] - 2;
250
251                         if ((ptr[0] == PW_VENDOR_SPECIFIC) &&
252                             (attrlen > 4)) {
253                                 vendor = (ptr[3] << 16) | (ptr[4] << 8) | ptr[5];
254                                 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u)  ",
255                                        ptr[2], ptr[3], ptr[4], ptr[5], vendor);
256                                 attrlen -= 4;
257                                 ptr += 6;
258                                 total -= 6;
259
260                         } else {
261                                 ptr += 2;
262                                 total -= 2;
263                         }
264
265                         print_hex_data(ptr, attrlen, 3);
266
267                         ptr += attrlen;
268                         total -= attrlen;
269                 }
270         }
271         fflush(stdout);
272 }
273
274 /** Wrapper for sendto which handles sendfromto, IPv6, and all possible combinations
275  *
276  */
277 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
278 #ifdef WITH_UDPFROMTO
279                       fr_ipaddr_t *src_ipaddr, uint16_t src_port,
280 #else
281                       UNUSED fr_ipaddr_t *src_ipaddr, UNUSED uint16_t src_port,
282 #endif
283                       fr_ipaddr_t *dst_ipaddr, uint16_t dst_port)
284 {
285         int rcode;
286         struct sockaddr_storage dst;
287         socklen_t               sizeof_dst;
288
289 #ifdef WITH_UDPFROMTO
290         struct sockaddr_storage src;
291         socklen_t               sizeof_src;
292
293         fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
294 #endif
295
296         if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
297                 return -1;
298         }
299
300 #ifdef WITH_UDPFROMTO
301         /*
302          *      And if they don't specify a source IP address, don't
303          *      use udpfromto.
304          */
305         if (((dst_ipaddr->af == AF_INET) || (dst_ipaddr->af == AF_INET6)) &&
306             (src_ipaddr->af != AF_UNSPEC) &&
307             !fr_inaddr_any(src_ipaddr)) {
308                 rcode = sendfromto(sockfd, data, data_len, flags,
309                                    (struct sockaddr *)&src, sizeof_src,
310                                    (struct sockaddr *)&dst, sizeof_dst);
311                 goto done;
312         }
313 #endif
314
315         /*
316          *      No udpfromto, fail gracefully.
317          */
318         rcode = sendto(sockfd, data, data_len, flags,
319                        (struct sockaddr *) &dst, sizeof_dst);
320 #ifdef WITH_UDPFROMTO
321 done:
322 #endif
323         if (rcode < 0) {
324                 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
325         }
326
327         return rcode;
328 }
329
330
331 void rad_recv_discard(int sockfd)
332 {
333         uint8_t                 header[4];
334         struct sockaddr_storage src;
335         socklen_t               sizeof_src = sizeof(src);
336
337         (void) recvfrom(sockfd, header, sizeof(header), 0,
338                         (struct sockaddr *)&src, &sizeof_src);
339 }
340
341 /** Basic validation of RADIUS packet header
342  *
343  * @note fr_strerror errors are only available if fr_debug_lvl > 0. This is to reduce CPU time
344  *      consumed when discarding malformed packet.
345  *
346  * @param[in] sockfd we're reading from.
347  * @param[out] src_ipaddr of the packet.
348  * @param[out] src_port of the packet.
349  * @param[out] code Pointer to where to write the packet code.
350  * @return
351  *      - -1 on failure.
352  *      - 1 on decode error.
353  *      - >= RADIUS_HDR_LEN on success. This is the packet length as specified in the header.
354  */
355 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, uint16_t *src_port, int *code)
356 {
357         ssize_t                 data_len, packet_len;
358         uint8_t                 header[4];
359         struct sockaddr_storage src;
360         socklen_t               sizeof_src = sizeof(src);
361
362         data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK, (struct sockaddr *)&src, &sizeof_src);
363         if (data_len < 0) {
364                 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
365                 return -1;
366         }
367
368         /*
369          *      Convert AF.  If unknown, discard packet.
370          */
371         if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
372                 FR_DEBUG_STRERROR_PRINTF("Unknown address family");
373                 rad_recv_discard(sockfd);
374
375                 return 1;
376         }
377
378         /*
379          *      Too little data is available, discard the packet.
380          */
381         if (data_len < 4) {
382                 FR_DEBUG_STRERROR_PRINTF("Expected at least 4 bytes of header data, got %zu bytes", data_len);
383 invalid:
384                 FR_DEBUG_STRERROR_PRINTF("Invalid data from %s: %s",
385                                          fr_inet_ntop(src_ipaddr->af, &src_ipaddr->ipaddr),
386                                          fr_strerror());
387                 rad_recv_discard(sockfd);
388
389                 return 1;
390         }
391
392         /*
393          *      See how long the packet says it is.
394          */
395         packet_len = (header[2] * 256) + header[3];
396
397         /*
398          *      The length in the packet says it's less than
399          *      a RADIUS header length: discard it.
400          */
401         if (packet_len < RADIUS_HDR_LEN) {
402                 FR_DEBUG_STRERROR_PRINTF("Expected at least " STRINGIFY(RADIUS_HDR_LEN)  " bytes of packet "
403                                          "data, got %zu bytes", packet_len);
404                 goto invalid;
405         }
406
407         /*
408          *      Enforce RFC requirements, for sanity.
409          *      Anything after 4k will be discarded.
410          */
411         if (packet_len > MAX_PACKET_LEN) {
412                 FR_DEBUG_STRERROR_PRINTF("Length field value too large, expected maximum of "
413                                          STRINGIFY(MAX_PACKET_LEN) " bytes, got %zu bytes", packet_len);
414                 goto invalid;
415         }
416
417         *code = header[0];
418
419         /*
420          *      The packet says it's this long, but the actual UDP
421          *      size could still be smaller.
422          */
423         return packet_len;
424 }
425
426
427 /** Wrapper for recvfrom, which handles recvfromto, IPv6, and all possible combinations
428  *
429  */
430 static ssize_t rad_recvfrom(int sockfd, RADIUS_PACKET *packet, int flags,
431                             fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
432                             fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
433 {
434         struct sockaddr_storage src;
435         struct sockaddr_storage dst;
436         socklen_t               sizeof_src = sizeof(src);
437         socklen_t               sizeof_dst = sizeof(dst);
438         ssize_t                 data_len;
439         uint8_t                 header[4];
440         size_t                  len;
441         uint16_t                port;
442
443         memset(&src, 0, sizeof_src);
444         memset(&dst, 0, sizeof_dst);
445
446         /*
447          *      Read the length of the packet, from the packet.
448          *      This lets us allocate the buffer to use for
449          *      reading the rest of the packet.
450          */
451         data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
452                             (struct sockaddr *)&src, &sizeof_src);
453         if (data_len < 0) {
454                 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
455                 return -1;
456         }
457
458         /*
459          *      Too little data is available, discard the packet.
460          */
461         if (data_len < 4) {
462                 rad_recv_discard(sockfd);
463
464                 return 0;
465
466         } else {                /* we got 4 bytes of data. */
467                 /*
468                  *      See how long the packet says it is.
469                  */
470                 len = (header[2] * 256) + header[3];
471
472                 /*
473                  *      The length in the packet says it's less than
474                  *      a RADIUS header length: discard it.
475                  */
476                 if (len < RADIUS_HDR_LEN) {
477                         recvfrom(sockfd, header, sizeof(header), flags,
478                                  (struct sockaddr *)&src, &sizeof_src);
479                         return 0;
480
481                         /*
482                          *      Enforce RFC requirements, for sanity.
483                          *      Anything after 4k will be discarded.
484                          */
485                 } else if (len > MAX_PACKET_LEN) {
486                         recvfrom(sockfd, header, sizeof(header), flags,
487                                  (struct sockaddr *)&src, &sizeof_src);
488                         return len;
489                 }
490         }
491
492         packet->data = talloc_array(packet, uint8_t, len);
493         if (!packet->data) return -1;
494
495         /*
496          *      Receive the packet.  The OS will discard any data in the
497          *      packet after "len" bytes.
498          */
499 #ifdef WITH_UDPFROMTO
500         data_len = recvfromto(sockfd, packet->data, len, flags,
501                               (struct sockaddr *)&src, &sizeof_src,
502                               (struct sockaddr *)&dst, &sizeof_dst);
503 #else
504         data_len = recvfrom(sockfd, packet->data, len, flags,
505                             (struct sockaddr *)&src, &sizeof_src);
506
507         /*
508          *      Get the destination address, too.
509          */
510         if (getsockname(sockfd, (struct sockaddr *)&dst,
511                         &sizeof_dst) < 0) return -1;
512 #endif
513         if (data_len < 0) {
514                 return data_len;
515         }
516
517         if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
518                 return -1;      /* Unknown address family, Die Die Die! */
519         }
520         *src_port = port;
521
522         fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
523         *dst_port = port;
524
525         /*
526          *      Different address families should never happen.
527          */
528         if (src.ss_family != dst.ss_family) {
529                 return -1;
530         }
531
532         return data_len;
533 }
534
535
536 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
537 /** Build an encrypted secret value to return in a reply packet
538  *
539  * The secret is hidden by xoring with a MD5 digest created from
540  * the shared secret and the authentication vector.
541  * We put them into MD5 in the reverse order from that used when
542  * encrypting passwords to RADIUS.
543  */
544 static void make_secret(uint8_t *digest, uint8_t const *vector,
545                         char const *secret, uint8_t const *value, size_t length)
546 {
547         FR_MD5_CTX context;
548         size_t       i;
549
550         fr_md5_init(&context);
551         fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
552         fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
553         fr_md5_final(digest, &context);
554
555         for ( i = 0; i < length; i++ ) {
556                 digest[i] ^= value[i];
557         }
558 }
559
560 #define MAX_PASS_LEN (128)
561 static void make_passwd(uint8_t *output, ssize_t *outlen,
562                         uint8_t const *input, size_t inlen,
563                         char const *secret, uint8_t const *vector)
564 {
565         FR_MD5_CTX context, old;
566         uint8_t digest[AUTH_VECTOR_LEN];
567         uint8_t passwd[MAX_PASS_LEN];
568         size_t  i, n;
569         size_t  len;
570
571         /*
572          *      If the length is zero, round it up.
573          */
574         len = inlen;
575
576         if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
577
578         memcpy(passwd, input, len);
579         if (len < sizeof(passwd)) memset(passwd + len, 0, sizeof(passwd) - len);
580
581         if (len == 0) {
582                 len = AUTH_PASS_LEN;
583         }
584
585         else if ((len & 0x0f) != 0) {
586                 len += 0x0f;
587                 len &= ~0x0f;
588         }
589         *outlen = len;
590
591         fr_md5_init(&context);
592         fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
593         old = context;
594
595         /*
596          *      Do first pass.
597          */
598         fr_md5_update(&context, vector, AUTH_PASS_LEN);
599
600         for (n = 0; n < len; n += AUTH_PASS_LEN) {
601                 if (n > 0) {
602                         context = old;
603                         fr_md5_update(&context,
604                                        passwd + n - AUTH_PASS_LEN,
605                                        AUTH_PASS_LEN);
606                 }
607
608                 fr_md5_final(digest, &context);
609                 for (i = 0; i < AUTH_PASS_LEN; i++) {
610                         passwd[i + n] ^= digest[i];
611                 }
612         }
613
614         memcpy(output, passwd, len);
615 }
616
617
618 static void make_tunnel_passwd(uint8_t *output, ssize_t *outlen,
619                                uint8_t const *input, size_t inlen, size_t room,
620                                char const *secret, uint8_t const *vector)
621 {
622         FR_MD5_CTX context, old;
623         uint8_t digest[AUTH_VECTOR_LEN];
624         size_t  i, n;
625         size_t  encrypted_len;
626
627         /*
628          *      The password gets encoded with a 1-byte "length"
629          *      field.  Ensure that it doesn't overflow.
630          */
631         if (room > 253) room = 253;
632
633         /*
634          *      Limit the maximum size of the input password.  2 bytes
635          *      are taken up by the salt, and one by the encoded
636          *      "length" field.  Note that if we have a tag, the
637          *      "room" will be 252 octets, not 253 octets.
638          */
639         if (inlen > (room - 3)) inlen = room - 3;
640
641         /*
642          *      Length of the encrypted data is the clear-text
643          *      password length plus one byte which encodes the length
644          *      of the password.  We round up to the nearest encoding
645          *      block.  Note that this can result in the encoding
646          *      length being more than 253 octets.
647          */
648         encrypted_len = inlen + 1;
649         if ((encrypted_len & 0x0f) != 0) {
650                 encrypted_len += 0x0f;
651                 encrypted_len &= ~0x0f;
652         }
653
654         /*
655          *      We need 2 octets for the salt, followed by the actual
656          *      encrypted data.
657          */
658         if (encrypted_len > (room - 2)) encrypted_len = room - 2;
659
660         *outlen = encrypted_len + 2;    /* account for the salt */
661
662         /*
663          *      Copy the password over, and zero-fill the remainder.
664          */
665         memcpy(output + 3, input, inlen);
666         memset(output + 3 + inlen, 0, *outlen - 3 - inlen);
667
668         /*
669          *      Generate salt.  The RFCs say:
670          *
671          *      The high bit of salt[0] must be set, each salt in a
672          *      packet should be unique, and they should be random
673          *
674          *      So, we set the high bit, add in a counter, and then
675          *      add in some CSPRNG data.  should be OK..
676          */
677         output[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
678                      (fr_rand() & 0x07));
679         output[1] = fr_rand();
680         output[2] = inlen;      /* length of the password string */
681
682         fr_md5_init(&context);
683         fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
684         old = context;
685
686         fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
687         fr_md5_update(&context, &output[0], 2);
688
689         for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
690                 size_t block_len;
691
692                 if (n > 0) {
693                         context = old;
694                         fr_md5_update(&context,
695                                        output + 2 + n - AUTH_PASS_LEN,
696                                        AUTH_PASS_LEN);
697                 }
698
699                 fr_md5_final(digest, &context);
700
701                 if ((2 + n + AUTH_PASS_LEN) < room) {
702                         block_len = AUTH_PASS_LEN;
703                 } else {
704                         block_len = room - 2 - n;
705                 }
706
707                 for (i = 0; i < block_len; i++) {
708                         output[i + 2 + n] ^= digest[i];
709                 }
710         }
711 }
712
713 static int do_next_tlv(VALUE_PAIR const *vp, VALUE_PAIR const *next, int nest)
714 {
715         unsigned int tlv1, tlv2;
716
717         if (nest > fr_attr_max_tlv) return 0;
718
719         if (!vp) return 0;
720
721         /*
722          *      Keep encoding TLVs which have the same scope.
723          *      e.g. two attributes of:
724          *              ATTR.TLV1.TLV2.TLV3 = data1
725          *              ATTR.TLV1.TLV2.TLV4 = data2
726          *      both get put into a container of "ATTR.TLV1.TLV2"
727          */
728
729         /*
730          *      Nothing to follow, we're done.
731          */
732         if (!next) return 0;
733
734         /*
735          *      Not from the same vendor, skip it.
736          */
737         if (vp->da->vendor != next->da->vendor) return 0;
738
739         /*
740          *      In a different TLV space, skip it.
741          */
742         tlv1 = vp->da->attr;
743         tlv2 = next->da->attr;
744
745         tlv1 &= ((1 << fr_attr_shift[nest]) - 1);
746         tlv2 &= ((1 << fr_attr_shift[nest]) - 1);
747
748         if (tlv1 != tlv2) return 0;
749
750         return 1;
751 }
752
753
754 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
755                            RADIUS_PACKET const *original,
756                            char const *secret, int nest,
757                            VALUE_PAIR const **pvp,
758                            uint8_t *start, size_t room);
759
760 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
761                            RADIUS_PACKET const *original,
762                            char const *secret, VALUE_PAIR const **pvp,
763                            unsigned int attribute, uint8_t *ptr, size_t room);
764
765 /** Encode the *data* portion of the TLV
766  *
767  * This is really a sub-function of vp2data_any().  It encodes the *data* portion
768  * of the TLV, and assumes that the encapsulating attribute has already been encoded.
769  */
770 static ssize_t vp2data_tlvs(RADIUS_PACKET const *packet,
771                             RADIUS_PACKET const *original,
772                             char const *secret, int nest,
773                             VALUE_PAIR const **pvp,
774                             uint8_t *start, size_t room)
775 {
776         ssize_t len;
777         size_t my_room;
778         uint8_t *ptr = start;
779         VALUE_PAIR const *vp = *pvp;
780         VALUE_PAIR const *svp = vp;
781
782         if (!svp) return 0;
783
784 #ifndef NDEBUG
785         if (nest > fr_attr_max_tlv) {
786                 fr_strerror_printf("vp2data_tlvs: attribute nesting overflow");
787                 return -1;
788         }
789 #endif
790
791         while (vp) {
792                 VERIFY_VP(vp);
793
794                 if (room <= 2) return ptr - start;
795
796                 ptr[0] = (vp->da->attr >> fr_attr_shift[nest]) & fr_attr_mask[nest];
797                 ptr[1] = 2;
798
799                 my_room = room;
800                 if (room > 255) my_room = 255;
801
802                 len = vp2data_any(packet, original, secret, nest,
803                                   &vp, ptr + 2, my_room - 2);
804                 if (len < 0) return len;
805                 if (len == 0) return ptr - start;
806                 /* len can NEVER be more than 253 */
807
808                 ptr[1] += len;
809
810 #ifndef NDEBUG
811                 if ((fr_debug_lvl > 3) && fr_log_fp) {
812                         fprintf(fr_log_fp, "\t\t%02x %02x  ", ptr[0], ptr[1]);
813                         print_hex_data(ptr + 2, len, 3);
814                 }
815 #endif
816
817                 room -= ptr[1];
818                 ptr += ptr[1];
819                 *pvp = vp;
820
821                 if (!do_next_tlv(svp, vp, nest)) break;
822         }
823
824 #ifndef NDEBUG
825         if ((fr_debug_lvl > 3) && fr_log_fp) {
826                 DICT_ATTR const *da;
827
828                 da = dict_attrbyvalue(svp->da->attr & ((1 << fr_attr_shift[nest ]) - 1), svp->da->vendor);
829                 if (da) fprintf(fr_log_fp, "\t%s = ...\n", da->name);
830         }
831 #endif
832
833         return ptr - start;
834 }
835
836 /** Encodes the data portion of an attribute
837  *
838  * @return -1 on error, or the length of the data portion.
839  */
840 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
841                            RADIUS_PACKET const *original,
842                            char const *secret, int nest,
843                            VALUE_PAIR const **pvp,
844                            uint8_t *start, size_t room)
845 {
846         uint32_t lvalue;
847         ssize_t len;
848         uint8_t const *data;
849         uint8_t *ptr = start;
850         uint8_t array[4];
851         uint64_t lvalue64;
852         VALUE_PAIR const *vp = *pvp;
853
854         VERIFY_VP(vp);
855
856         /*
857          *      See if we need to encode a TLV.  The low portion of
858          *      the attribute has already been placed into the packer.
859          *      If there are still attribute bytes left, then go
860          *      encode them as TLVs.
861          *
862          *      If we cared about the stack, we could unroll the loop.
863          */
864         if (vp->da->flags.is_tlv && (nest < fr_attr_max_tlv) &&
865             ((vp->da->attr >> fr_attr_shift[nest + 1]) != 0)) {
866                 return vp2data_tlvs(packet, original, secret, nest + 1, pvp,
867                                     start, room);
868         }
869
870         /*
871          *      Set up the default sources for the data.
872          */
873         len = vp->vp_length;
874
875         switch (vp->da->type) {
876         case PW_TYPE_STRING:
877         case PW_TYPE_OCTETS:
878                 data = vp->data.ptr;
879                 if (!data) return 0;
880                 break;
881
882         case PW_TYPE_IFID:
883         case PW_TYPE_IPV4_ADDR:
884         case PW_TYPE_IPV6_ADDR:
885         case PW_TYPE_IPV6_PREFIX:
886         case PW_TYPE_IPV4_PREFIX:
887         case PW_TYPE_ABINARY:
888         case PW_TYPE_ETHERNET:  /* just in case */
889                 data = (uint8_t const *) &vp->data;
890                 break;
891
892         case PW_TYPE_BYTE:
893                 len = 1;        /* just in case */
894                 array[0] = vp->vp_byte;
895                 data = array;
896                 break;
897
898         case PW_TYPE_SHORT:
899                 len = 2;        /* just in case */
900                 array[0] = (vp->vp_short >> 8) & 0xff;
901                 array[1] = vp->vp_short & 0xff;
902                 data = array;
903                 break;
904
905         case PW_TYPE_INTEGER:
906                 len = 4;        /* just in case */
907                 lvalue = htonl(vp->vp_integer);
908                 memcpy(array, &lvalue, sizeof(lvalue));
909                 data = array;
910                 break;
911
912         case PW_TYPE_INTEGER64:
913                 len = 8;        /* just in case */
914                 lvalue64 = htonll(vp->vp_integer64);
915                 data = (uint8_t *) &lvalue64;
916                 break;
917
918                 /*
919                  *  There are no tagged date attributes.
920                  */
921         case PW_TYPE_DATE:
922                 lvalue = htonl(vp->vp_date);
923                 data = (uint8_t const *) &lvalue;
924                 len = 4;        /* just in case */
925                 break;
926
927         case PW_TYPE_SIGNED:
928         {
929                 int32_t slvalue;
930
931                 len = 4;        /* just in case */
932                 slvalue = htonl(vp->vp_signed);
933                 memcpy(array, &slvalue, sizeof(slvalue));
934                 data = array;
935                 break;
936         }
937
938         default:                /* unknown type: ignore it */
939                 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->da->type);
940                 return -1;
941         }
942
943         /*
944          *      No data: skip it.
945          */
946         if (len == 0) {
947                 *pvp = vp->next;
948                 return 0;
949         }
950
951         /*
952          *      Bound the data to the calling size
953          */
954         if (len > (ssize_t) room) len = room;
955
956         /*
957          *      Encrypt the various password styles
958          *
959          *      Attributes with encrypted values MUST be less than
960          *      128 bytes long.
961          */
962         switch (vp->da->flags.encrypt) {
963         case FLAG_ENCRYPT_USER_PASSWORD:
964                 make_passwd(ptr, &len, data, len,
965                             secret, packet->vector);
966                 break;
967
968         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
969                 lvalue = 0;
970                 if (vp->da->flags.has_tag) lvalue = 1;
971
972                 /*
973                  *      Check if there's enough room.  If there isn't,
974                  *      we discard the attribute.
975                  *
976                  *      This is ONLY a problem if we have multiple VSA's
977                  *      in one Vendor-Specific, though.
978                  */
979                 if (room < (18 + lvalue)) return 0;
980
981                 switch (packet->code) {
982                 case PW_CODE_ACCESS_ACCEPT:
983                 case PW_CODE_ACCESS_REJECT:
984                 case PW_CODE_ACCESS_CHALLENGE:
985                 default:
986                         if (!original) {
987                                 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->da->name);
988                                 return -1;
989                         }
990
991                         if (lvalue) ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
992                         make_tunnel_passwd(ptr + lvalue, &len, data, len,
993                                            room - lvalue,
994                                            secret, original->vector);
995                         len += lvalue;
996                         break;
997                 case PW_CODE_ACCOUNTING_REQUEST:
998                 case PW_CODE_DISCONNECT_REQUEST:
999                 case PW_CODE_COA_REQUEST:
1000                         ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
1001                         make_tunnel_passwd(ptr + 1, &len, data, len, room - 1,
1002                                            secret, packet->vector);
1003                         len += lvalue;
1004                         break;
1005                 }
1006                 break;
1007
1008                 /*
1009                  *      The code above ensures that this attribute
1010                  *      always fits.
1011                  */
1012         case FLAG_ENCRYPT_ASCEND_SECRET:
1013                 if (len > AUTH_VECTOR_LEN) len = AUTH_VECTOR_LEN;
1014                 make_secret(ptr, packet->vector, secret, data, len);
1015                 len = AUTH_VECTOR_LEN;
1016                 break;
1017
1018
1019         default:
1020                 if (vp->da->flags.has_tag && TAG_VALID(vp->tag)) {
1021                         if (vp->da->type == PW_TYPE_STRING) {
1022                                 if (len > ((ssize_t) (room - 1))) len = room - 1;
1023                                 ptr[0] = vp->tag;
1024                                 ptr++;
1025                         } else if (vp->da->type == PW_TYPE_INTEGER) {
1026                                 array[0] = vp->tag;
1027                         } /* else it can't be any other type */
1028                 }
1029                 memcpy(ptr, data, len);
1030                 break;
1031         } /* switch over encryption flags */
1032
1033         *pvp = vp->next;
1034         return len + (ptr - start);
1035 }
1036
1037 static ssize_t attr_shift(uint8_t const *start, uint8_t const *end,
1038                           uint8_t *ptr, int hdr_len, ssize_t len,
1039                           int flag_offset, int vsa_offset)
1040 {
1041         int check_len = len - ptr[1];
1042         int total = len + hdr_len;
1043
1044         /*
1045          *      Pass 1: Check if the addition of the headers
1046          *      overflows the available room.  If so, return
1047          *      what we were capable of encoding.
1048          */
1049
1050         while (check_len > (255 - hdr_len)) {
1051                 total += hdr_len;
1052                 check_len -= (255 - hdr_len);
1053         }
1054
1055         /*
1056          *      Note that this results in a number of attributes maybe
1057          *      being marked as "encoded", but which aren't in the
1058          *      packet.  Oh well.  The solution is to fix the
1059          *      "vp2data_any" function to take into account the header
1060          *      lengths.
1061          */
1062         if ((ptr + ptr[1] + total) > end) {
1063                 return (ptr + ptr[1]) - start;
1064         }
1065
1066         /*
1067          *      Pass 2: Now that we know there's enough room,
1068          *      re-arrange the data to form a set of valid
1069          *      RADIUS attributes.
1070          */
1071         while (1) {
1072                 int sublen = 255 - ptr[1];
1073
1074                 if (len <= sublen) {
1075                         break;
1076                 }
1077
1078                 len -= sublen;
1079                 memmove(ptr + 255 + hdr_len, ptr + 255, sublen);
1080                 memmove(ptr + 255, ptr, hdr_len);
1081                 ptr[1] += sublen;
1082                 if (vsa_offset) ptr[vsa_offset] += sublen;
1083                 ptr[flag_offset] |= 0x80;
1084
1085                 ptr += 255;
1086                 ptr[1] = hdr_len;
1087                 if (vsa_offset) ptr[vsa_offset] = 3;
1088         }
1089
1090         ptr[1] += len;
1091         if (vsa_offset) ptr[vsa_offset] += len;
1092
1093         return (ptr + ptr[1]) - start;
1094 }
1095
1096
1097 /** Encode an "extended" attribute
1098  */
1099 int rad_vp2extended(RADIUS_PACKET const *packet,
1100                     RADIUS_PACKET const *original,
1101                     char const *secret, VALUE_PAIR const **pvp,
1102                     uint8_t *ptr, size_t room)
1103 {
1104         int len;
1105         int hdr_len;
1106         uint8_t *start = ptr;
1107         VALUE_PAIR const *vp = *pvp;
1108
1109         VERIFY_VP(vp);
1110
1111         if (!vp->da->flags.extended) {
1112                 fr_strerror_printf("rad_vp2extended called for non-extended attribute");
1113                 return -1;
1114         }
1115
1116         /*
1117          *      The attribute number is encoded into the upper 8 bits
1118          *      of the vendor ID.
1119          */
1120         ptr[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1121
1122         if (!vp->da->flags.long_extended) {
1123                 if (room < 3) return 0;
1124
1125                 ptr[1] = 3;
1126                 ptr[2] = vp->da->attr & fr_attr_mask[0];
1127
1128         } else {
1129                 if (room < 4) return 0;
1130
1131                 ptr[1] = 4;
1132                 ptr[2] = vp->da->attr & fr_attr_mask[0];
1133                 ptr[3] = 0;
1134         }
1135
1136         /*
1137          *      Only "flagged" attributes can be longer than one
1138          *      attribute.
1139          */
1140         if (!vp->da->flags.long_extended && (room > 255)) {
1141                 room = 255;
1142         }
1143
1144         /*
1145          *      Handle EVS VSAs.
1146          */
1147         if (vp->da->flags.evs) {
1148                 uint8_t *evs = ptr + ptr[1];
1149
1150                 if (room < (size_t) (ptr[1] + 5)) return 0;
1151
1152                 ptr[2] = 26;
1153
1154                 evs[0] = 0;     /* always zero */
1155                 evs[1] = (vp->da->vendor >> 16) & 0xff;
1156                 evs[2] = (vp->da->vendor >> 8) & 0xff;
1157                 evs[3] = vp->da->vendor & 0xff;
1158                 evs[4] = vp->da->attr & fr_attr_mask[0];
1159
1160                 ptr[1] += 5;
1161         }
1162         hdr_len = ptr[1];
1163
1164         len = vp2data_any(packet, original, secret, 0,
1165                           pvp, ptr + ptr[1], room - hdr_len);
1166         if (len <= 0) return len;
1167
1168         /*
1169          *      There may be more than 252 octets of data encoded in
1170          *      the attribute.  If so, move the data up in the packet,
1171          *      and copy the existing header over.  Set the "M" flag ONLY
1172          *      after copying the rest of the data.
1173          */
1174         if (vp->da->flags.long_extended && (len > (255 - ptr[1]))) {
1175                 return attr_shift(start, start + room, ptr, 4, len, 3, 0);
1176         }
1177
1178         ptr[1] += len;
1179
1180 #ifndef NDEBUG
1181         if ((fr_debug_lvl > 3) && fr_log_fp) {
1182                 int jump = 3;
1183
1184                 fprintf(fr_log_fp, "\t\t%02x %02x  ", ptr[0], ptr[1]);
1185                 if (!vp->da->flags.long_extended) {
1186                         fprintf(fr_log_fp, "%02x  ", ptr[2]);
1187
1188                 } else {
1189                         fprintf(fr_log_fp, "%02x %02x  ", ptr[2], ptr[3]);
1190                         jump = 4;
1191                 }
1192
1193                 if (vp->da->flags.evs) {
1194                         fprintf(fr_log_fp, "%02x%02x%02x%02x (%u)  %02x  ",
1195                                 ptr[jump], ptr[jump + 1],
1196                                 ptr[jump + 2], ptr[jump + 3],
1197                                 ((ptr[jump + 1] << 16) |
1198                                  (ptr[jump + 2] << 8) |
1199                                  ptr[jump + 3]),
1200                                 ptr[jump + 4]);
1201                         jump += 5;
1202                 }
1203
1204                 print_hex_data(ptr + jump, len, 3);
1205         }
1206 #endif
1207
1208         return (ptr + ptr[1]) - start;
1209 }
1210
1211
1212 /** Encode a WiMAX attribute
1213  *
1214  */
1215 int rad_vp2wimax(RADIUS_PACKET const *packet,
1216                  RADIUS_PACKET const *original,
1217                  char const *secret, VALUE_PAIR const **pvp,
1218                  uint8_t *ptr, size_t room)
1219 {
1220         int len;
1221         uint32_t lvalue;
1222         int hdr_len;
1223         uint8_t *start = ptr;
1224         VALUE_PAIR const *vp = *pvp;
1225
1226         VERIFY_VP(vp);
1227
1228         /*
1229          *      Double-check for WiMAX format.
1230          */
1231         if (!vp->da->flags.wimax) {
1232                 fr_strerror_printf("rad_vp2wimax called for non-WIMAX VSA");
1233                 return -1;
1234         }
1235
1236         /*
1237          *      Not enough room for:
1238          *              attr, len, vendor-id, vsa, vsalen, continuation
1239          */
1240         if (room < 9) return 0;
1241
1242         /*
1243          *      Build the Vendor-Specific header
1244          */
1245         ptr = start;
1246         ptr[0] = PW_VENDOR_SPECIFIC;
1247         ptr[1] = 9;
1248         lvalue = htonl(vp->da->vendor);
1249         memcpy(ptr + 2, &lvalue, 4);
1250         ptr[6] = (vp->da->attr & fr_attr_mask[1]);
1251         ptr[7] = 3;
1252         ptr[8] = 0;             /* continuation byte */
1253
1254         hdr_len = 9;
1255
1256         len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1],
1257                           room - hdr_len);
1258         if (len <= 0) return len;
1259
1260         /*
1261          *      There may be more than 252 octets of data encoded in
1262          *      the attribute.  If so, move the data up in the packet,
1263          *      and copy the existing header over.  Set the "C" flag
1264          *      ONLY after copying the rest of the data.
1265          */
1266         if (len > (255 - ptr[1])) {
1267                 return attr_shift(start, start + room, ptr, hdr_len, len, 8, 7);
1268         }
1269
1270         ptr[1] += len;
1271         ptr[7] += len;
1272
1273 #ifndef NDEBUG
1274         if ((fr_debug_lvl > 3) && fr_log_fp) {
1275                 fprintf(fr_log_fp, "\t\t%02x %02x  %02x%02x%02x%02x (%u)  %02x %02x %02x   ",
1276                        ptr[0], ptr[1],
1277                        ptr[2], ptr[3], ptr[4], ptr[5],
1278                        (ptr[3] << 16) | (ptr[4] << 8) | ptr[5],
1279                        ptr[6], ptr[7], ptr[8]);
1280                 print_hex_data(ptr + 9, len, 3);
1281         }
1282 #endif
1283
1284         return (ptr + ptr[1]) - start;
1285 }
1286
1287 /** Encode an RFC format attribute, with the "concat" flag set
1288  *
1289  * If there isn't enough room in the packet, the data is
1290  * truncated to fit.
1291  */
1292 static ssize_t vp2attr_concat(UNUSED RADIUS_PACKET const *packet,
1293                               UNUSED RADIUS_PACKET const *original,
1294                               UNUSED char const *secret, VALUE_PAIR const **pvp,
1295                               unsigned int attribute, uint8_t *start, size_t room)
1296 {
1297         uint8_t *ptr = start;
1298         uint8_t const *p;
1299         size_t len, left;
1300         VALUE_PAIR const *vp = *pvp;
1301
1302         VERIFY_VP(vp);
1303
1304         p = vp->vp_octets;
1305         len = vp->vp_length;
1306
1307         while (len > 0) {
1308                 if (room <= 2) break;
1309
1310                 ptr[0] = attribute;
1311                 ptr[1] = 2;
1312
1313                 left = len;
1314
1315                 /* no more than 253 octets */
1316                 if (left > 253) left = 253;
1317
1318                 /* no more than "room" octets */
1319                 if (room < (left + 2)) left = room - 2;
1320
1321                 memcpy(ptr + 2, p, left);
1322
1323 #ifndef NDEBUG
1324                 if ((fr_debug_lvl > 3) && fr_log_fp) {
1325                         fprintf(fr_log_fp, "\t\t%02x %02x  ", ptr[0], ptr[1]);
1326                         print_hex_data(ptr + 2, len, 3);
1327                 }
1328 #endif
1329                 ptr[1] += left;
1330                 ptr += ptr[1];
1331                 p += left;
1332                 room -= left;
1333                 len -= left;
1334         }
1335
1336         *pvp = vp->next;
1337         return ptr - start;
1338 }
1339
1340 /** Encode an RFC format TLV.
1341  *
1342  * This could be a standard attribute, or a TLV data type.
1343  * If it's a standard attribute, then vp->da->attr == attribute.
1344  * Otherwise, attribute may be something else.
1345  */
1346 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
1347                            RADIUS_PACKET const *original,
1348                            char const *secret, VALUE_PAIR const **pvp,
1349                            unsigned int attribute, uint8_t *ptr, size_t room)
1350 {
1351         ssize_t len;
1352
1353         if (room <= 2) return 0;
1354
1355         ptr[0] = attribute & 0xff;
1356         ptr[1] = 2;
1357
1358         if (room > 255) room = 255;
1359
1360         len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1], room - ptr[1]);
1361         if (len <= 0) return len;
1362
1363         ptr[1] += len;
1364
1365 #ifndef NDEBUG
1366         if ((fr_debug_lvl > 3) && fr_log_fp) {
1367                 fprintf(fr_log_fp, "\t\t%02x %02x  ", ptr[0], ptr[1]);
1368                 print_hex_data(ptr + 2, len, 3);
1369         }
1370 #endif
1371
1372         return ptr[1];
1373 }
1374
1375
1376 /** Encode a VSA which is a TLV
1377  *
1378  * If it's in the RFC format, call vp2attr_rfc.  Otherwise, encode it here.
1379  */
1380 static ssize_t vp2attr_vsa(RADIUS_PACKET const *packet,
1381                            RADIUS_PACKET const *original,
1382                            char const *secret, VALUE_PAIR const **pvp,
1383                            unsigned int attribute, unsigned int vendor,
1384                            uint8_t *ptr, size_t room)
1385 {
1386         ssize_t len;
1387         DICT_VENDOR *dv;
1388         VALUE_PAIR const *vp = *pvp;
1389
1390         VERIFY_VP(vp);
1391         /*
1392          *      Unknown vendor: RFC format.
1393          *      Known vendor and RFC format: go do that.
1394          */
1395         dv = dict_vendorbyvalue(vendor);
1396         if (!dv ||
1397             (!vp->da->flags.is_tlv && (dv->type == 1) && (dv->length == 1))) {
1398                 return vp2attr_rfc(packet, original, secret, pvp,
1399                                    attribute, ptr, room);
1400         }
1401
1402         switch (dv->type) {
1403         default:
1404                 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1405                                    " type %u", (unsigned) dv->type);
1406                 return -1;
1407
1408         case 4:
1409                 ptr[0] = 0;     /* attr must be 24-bit */
1410                 ptr[1] = (attribute >> 16) & 0xff;
1411                 ptr[2] = (attribute >> 8) & 0xff;
1412                 ptr[3] = attribute & 0xff;
1413                 break;
1414
1415         case 2:
1416                 ptr[0] = (attribute >> 8) & 0xff;
1417                 ptr[1] = attribute & 0xff;
1418                 break;
1419
1420         case 1:
1421                 ptr[0] = attribute & 0xff;
1422                 break;
1423         }
1424
1425         switch (dv->length) {
1426         default:
1427                 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1428                                    " length %u", (unsigned) dv->length);
1429                 return -1;
1430
1431         case 0:
1432                 break;
1433
1434         case 2:
1435                 ptr[dv->type] = 0;
1436                 ptr[dv->type + 1] = dv->type + 2;
1437                 break;
1438
1439         case 1:
1440                 ptr[dv->type] = dv->type + 1;
1441                 break;
1442
1443         }
1444
1445         if (room > 255) room = 255;
1446
1447         len = vp2data_any(packet, original, secret, 0, pvp,
1448                           ptr + dv->type + dv->length, room - (dv->type + dv->length));
1449         if (len <= 0) return len;
1450
1451         if (dv->length) ptr[dv->type + dv->length - 1] += len;
1452
1453 #ifndef NDEBUG
1454         if ((fr_debug_lvl > 3) && fr_log_fp) {
1455                 switch (dv->type) {
1456                 default:
1457                         break;
1458
1459                 case 4:
1460                         if ((fr_debug_lvl > 3) && fr_log_fp)
1461                                 fprintf(fr_log_fp, "\t\t%02x%02x%02x%02x ",
1462                                         ptr[0], ptr[1], ptr[2], ptr[3]);
1463                         break;
1464
1465                 case 2:
1466                         if ((fr_debug_lvl > 3) && fr_log_fp)
1467                                 fprintf(fr_log_fp, "\t\t%02x%02x ",
1468                                         ptr[0], ptr[1]);
1469                 break;
1470
1471                 case 1:
1472                         if ((fr_debug_lvl > 3) && fr_log_fp)
1473                                 fprintf(fr_log_fp, "\t\t%02x ", ptr[0]);
1474                         break;
1475                 }
1476
1477                 switch (dv->length) {
1478                 default:
1479                         break;
1480
1481                 case 0:
1482                         fprintf(fr_log_fp, "  ");
1483                         break;
1484
1485                 case 1:
1486                         fprintf(fr_log_fp, "%02x  ",
1487                                 ptr[dv->type]);
1488                         break;
1489
1490                 case 2:
1491                         fprintf(fr_log_fp, "%02x%02x  ",
1492                                 ptr[dv->type], ptr[dv->type] + 1);
1493                         break;
1494                 }
1495
1496                 print_hex_data(ptr + dv->type + dv->length, len, 3);
1497         }
1498 #endif
1499
1500         return dv->type + dv->length + len;
1501 }
1502
1503
1504 /** Encode a Vendor-Specific attribute
1505  *
1506  */
1507 int rad_vp2vsa(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1508                 char const *secret, VALUE_PAIR const **pvp, uint8_t *ptr,
1509                 size_t room)
1510 {
1511         ssize_t len;
1512         uint32_t lvalue;
1513         VALUE_PAIR const *vp = *pvp;
1514
1515         VERIFY_VP(vp);
1516
1517         if (vp->da->vendor == 0) {
1518                 fr_strerror_printf("rad_vp2vsa called with rfc attribute");
1519                 return -1;
1520         }
1521
1522         /*
1523          *      Double-check for WiMAX format.
1524          */
1525         if (vp->da->flags.wimax) {
1526                 return rad_vp2wimax(packet, original, secret, pvp, ptr, room);
1527         }
1528
1529         if (vp->da->vendor > FR_MAX_VENDOR) {
1530                 fr_strerror_printf("rad_vp2vsa: Invalid arguments");
1531                 return -1;
1532         }
1533
1534         /*
1535          *      Not enough room for:
1536          *              attr, len, vendor-id
1537          */
1538         if (room < 6) return 0;
1539
1540         /*
1541          *      Build the Vendor-Specific header
1542          */
1543         ptr[0] = PW_VENDOR_SPECIFIC;
1544         ptr[1] = 6;
1545         lvalue = htonl(vp->da->vendor);
1546         memcpy(ptr + 2, &lvalue, 4);
1547
1548         if (room > 255) room = 255;
1549
1550         len = vp2attr_vsa(packet, original, secret, pvp,
1551                           vp->da->attr, vp->da->vendor,
1552                           ptr + ptr[1], room - ptr[1]);
1553         if (len < 0) return len;
1554
1555 #ifndef NDEBUG
1556         if ((fr_debug_lvl > 3) && fr_log_fp) {
1557                 fprintf(fr_log_fp, "\t\t%02x %02x  %02x%02x%02x%02x (%u)  ",
1558                        ptr[0], ptr[1],
1559                        ptr[2], ptr[3], ptr[4], ptr[5],
1560                        (ptr[3] << 16) | (ptr[4] << 8) | ptr[5]);
1561                 print_hex_data(ptr + 6, len, 3);
1562         }
1563 #endif
1564
1565         ptr[1] += len;
1566
1567         return ptr[1];
1568 }
1569
1570
1571 /** Encode an RFC standard attribute 1..255
1572  *
1573  */
1574 int rad_vp2rfc(RADIUS_PACKET const *packet,
1575                RADIUS_PACKET const *original,
1576                char const *secret, VALUE_PAIR const **pvp,
1577                uint8_t *ptr, size_t room)
1578 {
1579         VALUE_PAIR const *vp = *pvp;
1580
1581         VERIFY_VP(vp);
1582
1583         if (vp->da->vendor != 0) {
1584                 fr_strerror_printf("rad_vp2rfc called with VSA");
1585                 return -1;
1586         }
1587
1588         if ((vp->da->attr == 0) || (vp->da->attr > 255)) {
1589                 fr_strerror_printf("rad_vp2rfc called with non-standard attribute %u", vp->da->attr);
1590                 return -1;
1591         }
1592
1593         /*
1594          *      Only CUI is allowed to have zero length.
1595          *      Thank you, WiMAX!
1596          */
1597         if ((vp->vp_length == 0) &&
1598             (vp->da->attr == PW_CHARGEABLE_USER_IDENTITY)) {
1599                 ptr[0] = PW_CHARGEABLE_USER_IDENTITY;
1600                 ptr[1] = 2;
1601
1602                 *pvp = vp->next;
1603                 return 2;
1604         }
1605
1606         /*
1607          *      Message-Authenticator is hard-coded.
1608          */
1609         if (vp->da->attr == PW_MESSAGE_AUTHENTICATOR) {
1610                 if (room < 18) return -1;
1611
1612                 ptr[0] = PW_MESSAGE_AUTHENTICATOR;
1613                 ptr[1] = 18;
1614                 memset(ptr + 2, 0, 16);
1615 #ifndef NDEBUG
1616                 if ((fr_debug_lvl > 3) && fr_log_fp) {
1617                         fprintf(fr_log_fp, "\t\t50 12 ...\n");
1618                 }
1619 #endif
1620
1621                 *pvp = (*pvp)->next;
1622                 return 18;
1623         }
1624
1625         /*
1626          *      EAP-Message is special.
1627          */
1628         if (vp->da->flags.concat && (vp->vp_length > 253)) {
1629                 return vp2attr_concat(packet, original, secret, pvp, vp->da->attr,
1630                                       ptr, room);
1631         }
1632
1633         return vp2attr_rfc(packet, original, secret, pvp, vp->da->attr,
1634                            ptr, room);
1635 }
1636
1637 static ssize_t rad_vp2rfctlv(RADIUS_PACKET const *packet,
1638                              RADIUS_PACKET const *original,
1639                              char const *secret, VALUE_PAIR const **pvp,
1640                              uint8_t *start, size_t room)
1641 {
1642         ssize_t len;
1643         VALUE_PAIR const *vp = *pvp;
1644
1645         VERIFY_VP(vp);
1646
1647         if (!vp->da->flags.is_tlv) {
1648                 fr_strerror_printf("rad_vp2rfctlv: attr is not a TLV");
1649                 return -1;
1650         }
1651
1652         if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) != 0) {
1653                 fr_strerror_printf("rad_vp2rfctlv: attr is not an RFC TLV");
1654                 return -1;
1655         }
1656
1657         if (room < 5) return 0;
1658
1659         /*
1660          *      Encode the first level of TLVs
1661          */
1662         start[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1663         start[1] = 4;
1664         start[2] = vp->da->attr & fr_attr_mask[0];
1665         start[3] = 2;
1666
1667         len = vp2data_any(packet, original, secret, 0, pvp,
1668                           start + 4, room - 4);
1669         if (len <= 0) return len;
1670
1671         if (len > 253) {
1672                 return -1;
1673         }
1674
1675         start[1] += len;
1676         start[3] += len;
1677
1678         return start[1];
1679 }
1680
1681 /** Parse a data structure into a RADIUS attribute
1682  *
1683  */
1684 int rad_vp2attr(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1685                 char const *secret, VALUE_PAIR const **pvp, uint8_t *start,
1686                 size_t room)
1687 {
1688         VALUE_PAIR const *vp;
1689
1690         if (!pvp || !*pvp || !start || (room <= 2)) return -1;
1691
1692         vp = *pvp;
1693
1694         VERIFY_VP(vp);
1695
1696         /*
1697          *      RFC format attributes take the fast path.
1698          */
1699         if (!vp->da->vendor) {
1700                 if (vp->da->attr > 255) {
1701                         *pvp = vp->next;
1702                         return 0;
1703                 }
1704
1705                 return rad_vp2rfc(packet, original, secret, pvp,
1706                                   start, room);
1707         }
1708
1709         if (vp->da->flags.extended) {
1710                 return rad_vp2extended(packet, original, secret, pvp,
1711                                        start, room);
1712         }
1713
1714         /*
1715          *      The upper 8 bits of the vendor number are the standard
1716          *      space attribute which is a TLV.
1717          */
1718         if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) == 0) {
1719                 return rad_vp2rfctlv(packet, original, secret, pvp,
1720                                      start, room);
1721         }
1722
1723         if (vp->da->flags.wimax) {
1724                 return rad_vp2wimax(packet, original, secret, pvp,
1725                                     start, room);
1726         }
1727
1728         return rad_vp2vsa(packet, original, secret, pvp, start, room);
1729 }
1730
1731
1732 /** Encode a packet
1733  *
1734  */
1735 int rad_encode(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1736                char const *secret)
1737 {
1738         radius_packet_t         *hdr;
1739         uint8_t                 *ptr;
1740         uint16_t                total_length;
1741         int                     len;
1742         VALUE_PAIR const        *reply;
1743
1744         /*
1745          *      A 4K packet, aligned on 64-bits.
1746          */
1747         uint64_t        data[MAX_PACKET_LEN / sizeof(uint64_t)];
1748
1749         /*
1750          *      Double-check some things based on packet code.
1751          */
1752         switch (packet->code) {
1753         case PW_CODE_ACCESS_ACCEPT:
1754         case PW_CODE_ACCESS_REJECT:
1755         case PW_CODE_ACCESS_CHALLENGE:
1756                 if (!original) {
1757                         fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1758                         return -1;
1759                 }
1760                 break;
1761
1762                 /*
1763                  *      These packet vectors start off as all zero.
1764                  */
1765         case PW_CODE_ACCOUNTING_REQUEST:
1766         case PW_CODE_DISCONNECT_REQUEST:
1767         case PW_CODE_COA_REQUEST:
1768                 memset(packet->vector, 0, sizeof(packet->vector));
1769                 break;
1770
1771         default:
1772                 break;
1773         }
1774
1775         /*
1776          *      Use memory on the stack, until we know how
1777          *      large the packet will be.
1778          */
1779         hdr = (radius_packet_t *) data;
1780
1781         /*
1782          *      Build standard header
1783          */
1784         hdr->code = packet->code;
1785         hdr->id = packet->id;
1786
1787         memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1788
1789         total_length = RADIUS_HDR_LEN;
1790
1791         /*
1792          *      Load up the configuration values for the user
1793          */
1794         ptr = hdr->data;
1795         packet->offset = 0;
1796
1797         /*
1798          *      FIXME: Loop twice over the reply list.  The first time,
1799          *      calculate the total length of data.  The second time,
1800          *      allocate the memory, and fill in the VP's.
1801          *
1802          *      Hmm... this may be slower than just doing a small
1803          *      memcpy.
1804          */
1805
1806         /*
1807          *      Loop over the reply attributes for the packet.
1808          */
1809         reply = packet->vps;
1810         while (reply) {
1811                 size_t last_len, room;
1812                 char const *last_name = NULL;
1813
1814                 VERIFY_VP(reply);
1815
1816                 /*
1817                  *      Ignore non-wire attributes, but allow extended
1818                  *      attributes.
1819                  */
1820                 if ((reply->da->vendor == 0) &&
1821                     ((reply->da->attr & 0xFFFF) >= 256) &&
1822                     !reply->da->flags.extended && !reply->da->flags.long_extended) {
1823 #ifndef NDEBUG
1824                         /*
1825                          *      Permit the admin to send BADLY formatted
1826                          *      attributes with a debug build.
1827                          */
1828                         if (reply->da->attr == PW_RAW_ATTRIBUTE) {
1829                                 memcpy(ptr, reply->vp_octets, reply->vp_length);
1830                                 len = reply->vp_length;
1831                                 reply = reply->next;
1832                                 goto next;
1833                         }
1834 #endif
1835                         reply = reply->next;
1836                         continue;
1837                 }
1838
1839                 /*
1840                  *      We allow zero-length strings in "unlang", but
1841                  *      skip them (except for CUI, thanks WiMAX!) on
1842                  *      all other attributes.
1843                  */
1844                 if (reply->vp_length == 0) {
1845                         if ((reply->da->vendor != 0) ||
1846                             ((reply->da->attr != PW_CHARGEABLE_USER_IDENTITY) &&
1847                              (reply->da->attr != PW_MESSAGE_AUTHENTICATOR))) {
1848                                 reply = reply->next;
1849                                 continue;
1850                         }
1851                 }
1852
1853                 /*
1854                  *      Set the Message-Authenticator to the correct
1855                  *      length and initial value.
1856                  */
1857                 if (!reply->da->vendor && (reply->da->attr == PW_MESSAGE_AUTHENTICATOR)) {
1858                         /*
1859                          *      Cache the offset to the
1860                          *      Message-Authenticator
1861                          */
1862                         packet->offset = total_length;
1863                         last_len = 16;
1864                 } else {
1865                         last_len = reply->vp_length;
1866                 }
1867                 last_name = reply->da->name;
1868
1869                 room = ((uint8_t *) data) + sizeof(data) - ptr;
1870
1871                 if (room <= 2) break;
1872
1873                 len = rad_vp2attr(packet, original, secret, &reply, ptr, room);
1874                 if (len < 0) return -1;
1875
1876                 /*
1877                  *      Failed to encode the attribute, likely because
1878                  *      the packet is full.
1879                  */
1880                 if (len == 0) {
1881                         if (last_len != 0) {
1882                                 fr_strerror_printf("WARNING: Failed encoding attribute %s\n", last_name);
1883                                 break;
1884                         } else {
1885                                 fr_strerror_printf("WARNING: Skipping zero-length attribute %s\n", last_name);
1886                         }
1887                 }
1888
1889 #ifndef NDEBUG
1890         next:                   /* Used only for Raw-Attribute */
1891 #endif
1892                 ptr += len;
1893                 total_length += len;
1894         } /* done looping over all attributes */
1895
1896         /*
1897          *      Fill in the rest of the fields, and copy the data over
1898          *      from the local stack to the newly allocated memory.
1899          *
1900          *      Yes, all this 'memcpy' is slow, but it means
1901          *      that we only allocate the minimum amount of
1902          *      memory for a request.
1903          */
1904         packet->data_len = total_length;
1905         packet->data = talloc_array(packet, uint8_t, packet->data_len);
1906         if (!packet->data) {
1907                 fr_strerror_printf("Out of memory");
1908                 return -1;
1909         }
1910
1911         memcpy(packet->data, hdr, packet->data_len);
1912         hdr = (radius_packet_t *) packet->data;
1913
1914         total_length = htons(total_length);
1915         memcpy(hdr->length, &total_length, sizeof(total_length));
1916
1917         return 0;
1918 }
1919
1920
1921 /** Sign a previously encoded packet
1922  *
1923  */
1924 int rad_sign(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1925              char const *secret)
1926 {
1927         radius_packet_t *hdr = (radius_packet_t *)packet->data;
1928
1929         /*
1930          *      It wasn't assigned an Id, this is bad!
1931          */
1932         if (packet->id < 0) {
1933                 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id");
1934                 return -1;
1935         }
1936
1937         if (!packet->data || (packet->data_len < RADIUS_HDR_LEN) ||
1938             (packet->offset < 0)) {
1939                 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1940                 return -1;
1941         }
1942
1943         /*
1944          *      Set up the authentication vector with zero, or with
1945          *      the original vector, prior to signing.
1946          */
1947         switch (packet->code) {
1948         case PW_CODE_ACCOUNTING_REQUEST:
1949         case PW_CODE_DISCONNECT_REQUEST:
1950         case PW_CODE_COA_REQUEST:
1951                 memset(packet->vector, 0, AUTH_VECTOR_LEN);
1952                 break;
1953
1954         case PW_CODE_ACCESS_ACCEPT:
1955         case PW_CODE_ACCESS_REJECT:
1956         case PW_CODE_ACCESS_CHALLENGE:
1957         case PW_CODE_ACCOUNTING_RESPONSE:
1958         case PW_CODE_DISCONNECT_ACK:
1959         case PW_CODE_DISCONNECT_NAK:
1960         case PW_CODE_COA_ACK:
1961         case PW_CODE_COA_NAK:
1962                 if (!original) {
1963                         fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1964                         return -1;
1965                 }
1966                 memcpy(packet->vector, original->vector, AUTH_VECTOR_LEN);
1967                 break;
1968
1969         case PW_CODE_ACCESS_REQUEST:
1970         case PW_CODE_STATUS_SERVER:
1971         default:
1972                 break;          /* packet->vector is already random bytes */
1973         }
1974
1975 #ifndef NDEBUG
1976         if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
1977 #endif
1978
1979         /*
1980          *      If there's a Message-Authenticator, update it
1981          *      now.
1982          */
1983         if (packet->offset > 0) {
1984                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1985
1986                 switch (packet->code) {
1987                 case PW_CODE_ACCOUNTING_RESPONSE:
1988                         if (original && original->code == PW_CODE_STATUS_SERVER) {
1989                                 goto do_ack;
1990                         }
1991
1992                 case PW_CODE_ACCOUNTING_REQUEST:
1993                 case PW_CODE_DISCONNECT_REQUEST:
1994                 case PW_CODE_DISCONNECT_ACK:
1995                 case PW_CODE_DISCONNECT_NAK:
1996                 case PW_CODE_COA_REQUEST:
1997                 case PW_CODE_COA_ACK:
1998                 case PW_CODE_COA_NAK:
1999                         memset(hdr->vector, 0, AUTH_VECTOR_LEN);
2000                         break;
2001
2002                 do_ack:
2003                 case PW_CODE_ACCESS_ACCEPT:
2004                 case PW_CODE_ACCESS_REJECT:
2005                 case PW_CODE_ACCESS_CHALLENGE:
2006                         memcpy(hdr->vector, original->vector, AUTH_VECTOR_LEN);
2007                         break;
2008
2009                 default:
2010                         break;
2011                 }
2012
2013                 /*
2014                  *      Set the authentication vector to zero,
2015                  *      calculate the HMAC, and put it
2016                  *      into the Message-Authenticator
2017                  *      attribute.
2018                  */
2019                 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
2020                             (uint8_t const *) secret, strlen(secret));
2021                 memcpy(packet->data + packet->offset + 2,
2022                        calc_auth_vector, AUTH_VECTOR_LEN);
2023         }
2024
2025         /*
2026          *      Copy the request authenticator over to the packet.
2027          */
2028         memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
2029
2030         /*
2031          *      Switch over the packet code, deciding how to
2032          *      sign the packet.
2033          */
2034         switch (packet->code) {
2035                 /*
2036                  *      Request packets are not signed, but
2037                  *      have a random authentication vector.
2038                  */
2039         case PW_CODE_ACCESS_REQUEST:
2040         case PW_CODE_STATUS_SERVER:
2041                 break;
2042
2043                 /*
2044                  *      Reply packets are signed with the
2045                  *      authentication vector of the request.
2046                  */
2047         default:
2048                 {
2049                         uint8_t digest[16];
2050
2051                         FR_MD5_CTX      context;
2052                         fr_md5_init(&context);
2053                         fr_md5_update(&context, packet->data, packet->data_len);
2054                         fr_md5_update(&context, (uint8_t const *) secret,
2055                                      strlen(secret));
2056                         fr_md5_final(digest, &context);
2057
2058                         memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
2059                         memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
2060                         break;
2061                 }
2062         }/* switch over packet codes */
2063
2064         return 0;
2065 }
2066
2067 /** Reply to the request
2068  *
2069  * Also attach reply attribute value pairs and any user message provided.
2070  */
2071 int rad_send(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2072              char const *secret)
2073 {
2074         /*
2075          *      Maybe it's a fake packet.  Don't send it.
2076          */
2077         if (!packet || (packet->sockfd < 0)) {
2078                 return 0;
2079         }
2080
2081         /*
2082          *  First time through, allocate room for the packet
2083          */
2084         if (!packet->data) {
2085                 /*
2086                  *      Encode the packet.
2087                  */
2088                 if (rad_encode(packet, original, secret) < 0) {
2089                         return -1;
2090                 }
2091
2092                 /*
2093                  *      Re-sign it, including updating the
2094                  *      Message-Authenticator.
2095                  */
2096                 if (rad_sign(packet, original, secret) < 0) {
2097                         return -1;
2098                 }
2099
2100                 /*
2101                  *      If packet->data points to data, then we print out
2102                  *      the VP list again only for debugging.
2103                  */
2104         }
2105
2106 #ifndef NDEBUG
2107         if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2108 #endif
2109
2110 #ifdef WITH_TCP
2111         /*
2112          *      If the socket is TCP, call write().  Calling sendto()
2113          *      is allowed on some platforms, but it's not nice.  Even
2114          *      worse, if UDPFROMTO is defined, we *can't* use it on
2115          *      TCP sockets.  So... just call write().
2116          */
2117         if (packet->proto == IPPROTO_TCP) {
2118                 ssize_t rcode;
2119
2120                 rcode = write(packet->sockfd, packet->data, packet->data_len);
2121                 if (rcode >= 0) return rcode;
2122
2123                 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
2124                 return -1;
2125         }
2126 #endif
2127
2128         /*
2129          *      And send it on it's way.
2130          */
2131         return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
2132                           &packet->src_ipaddr, packet->src_port,
2133                           &packet->dst_ipaddr, packet->dst_port);
2134 }
2135
2136 /** Do a comparison of two authentication digests by comparing the FULL digest
2137  *
2138  * Otherwise, the server can be subject to timing attacks that allow attackers
2139  * find a valid message authenticator.
2140  *
2141  * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
2142  */
2143 int rad_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
2144 {
2145         int result = 0;
2146         size_t i;
2147
2148         for (i = 0; i < length; i++) {
2149                 result |= a[i] ^ b[i];
2150         }
2151
2152         return result;          /* 0 is OK, !0 is !OK, just like memcmp */
2153 }
2154
2155
2156 /** Validates the requesting client NAS
2157  *
2158  * Calculates the request Authenticator based on the clients private key.
2159  */
2160 static int calc_acctdigest(RADIUS_PACKET *packet, char const *secret)
2161 {
2162         uint8_t         digest[AUTH_VECTOR_LEN];
2163         FR_MD5_CTX              context;
2164
2165         /*
2166          *      Zero out the auth_vector in the received packet.
2167          *      Then append the shared secret to the received packet,
2168          *      and calculate the MD5 sum. This must be the same
2169          *      as the original MD5 sum (packet->vector).
2170          */
2171         memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2172
2173         /*
2174          *  MD5(packet + secret);
2175          */
2176         fr_md5_init(&context);
2177         fr_md5_update(&context, packet->data, packet->data_len);
2178         fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2179         fr_md5_final(digest, &context);
2180
2181         /*
2182          *      Return 0 if OK, 2 if not OK.
2183          */
2184         if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
2185         return 0;
2186 }
2187
2188
2189 /** Validates the requesting client NAS
2190  *
2191  * Calculates the response Authenticator based on the clients
2192  * private key.
2193  */
2194 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2195                             char const *secret)
2196 {
2197         uint8_t         calc_digest[AUTH_VECTOR_LEN];
2198         FR_MD5_CTX              context;
2199
2200         /*
2201          *      Very bad!
2202          */
2203         if (original == NULL) {
2204                 return 3;
2205         }
2206
2207         /*
2208          *  Copy the original vector in place.
2209          */
2210         memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2211
2212         /*
2213          *  MD5(packet + secret);
2214          */
2215         fr_md5_init(&context);
2216         fr_md5_update(&context, packet->data, packet->data_len);
2217         fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2218         fr_md5_final(calc_digest, &context);
2219
2220         /*
2221          *  Copy the packet's vector back to the packet.
2222          */
2223         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2224
2225         /*
2226          *      Return 0 if OK, 2 if not OK.
2227          */
2228         if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
2229         return 0;
2230 }
2231
2232 /** Check if a set of RADIUS formatted TLVs are OK
2233  *
2234  */
2235 int rad_tlv_ok(uint8_t const *data, size_t length,
2236                size_t dv_type, size_t dv_length)
2237 {
2238         uint8_t const *end = data + length;
2239
2240         VP_TRACE("checking TLV %u/%u\n", (unsigned int) dv_type, (unsigned int) dv_length);
2241
2242         VP_HEXDUMP("tlv_ok", data, length);
2243
2244         if ((dv_length > 2) || (dv_type == 0) || (dv_type > 4)) {
2245                 fr_strerror_printf("rad_tlv_ok: Invalid arguments");
2246                 return -1;
2247         }
2248
2249         while (data < end) {
2250                 size_t attrlen;
2251
2252                 if ((data + dv_type + dv_length) > end) {
2253                         fr_strerror_printf("Attribute header overflow");
2254                         return -1;
2255                 }
2256
2257                 switch (dv_type) {
2258                 case 4:
2259                         if ((data[0] == 0) && (data[1] == 0) &&
2260                             (data[2] == 0) && (data[3] == 0)) {
2261                         zero:
2262                                 fr_strerror_printf("Invalid attribute 0");
2263                                 return -1;
2264                         }
2265
2266                         if (data[0] != 0) {
2267                                 fr_strerror_printf("Invalid attribute > 2^24");
2268                                 return -1;
2269                         }
2270                         break;
2271
2272                 case 2:
2273                         if ((data[0] == 0) && (data[1] == 0)) goto zero;
2274                         break;
2275
2276                 case 1:
2277                         /*
2278                          *      Zero is allowed, because the Colubris
2279                          *      people are dumb and use it.
2280                          */
2281                         break;
2282
2283                 default:
2284                         fr_strerror_printf("Internal sanity check failed");
2285                         return -1;
2286                 }
2287
2288                 switch (dv_length) {
2289                 case 0:
2290                         return 0;
2291
2292                 case 2:
2293                         if (data[dv_type] != 0) {
2294                                 fr_strerror_printf("Attribute is longer than 256 octets");
2295                                 return -1;
2296                         }
2297                         /* FALL-THROUGH */
2298                 case 1:
2299                         attrlen = data[dv_type + dv_length - 1];
2300                         break;
2301
2302
2303                 default:
2304                         fr_strerror_printf("Internal sanity check failed");
2305                         return -1;
2306                 }
2307
2308                 if (attrlen < (dv_type + dv_length)) {
2309                         fr_strerror_printf("Attribute header has invalid length");
2310                         return -1;
2311                 }
2312
2313                 if (attrlen > length) {
2314                         fr_strerror_printf("Attribute overflows container");
2315                         return -1;
2316                 }
2317
2318                 data += attrlen;
2319                 length -= attrlen;
2320         }
2321
2322         return 0;
2323 }
2324
2325
2326 /** See if the data pointed to by PTR is a valid RADIUS packet.
2327  *
2328  * Packet is not 'const * const' because we may update data_len, if there's more data
2329  * in the UDP packet than in the RADIUS packet.
2330  *
2331  * @param packet to check
2332  * @param flags to control decoding
2333  * @param reason if not NULL, will have the failure reason written to where it points.
2334  * @return bool, true on success, false on failure.
2335  */
2336 bool rad_packet_ok(RADIUS_PACKET *packet, int flags, decode_fail_t *reason)
2337 {
2338         uint8_t                 *attr;
2339         size_t                  totallen;
2340         int                     count;
2341         radius_packet_t         *hdr;
2342         char                    host_ipaddr[128];
2343         bool                    require_ma = false;
2344         bool                    seen_ma = false;
2345         uint32_t                num_attributes;
2346         decode_fail_t           failure = DECODE_FAIL_NONE;
2347         bool                    eap = false;
2348         bool                    non_eap = false;
2349
2350         /*
2351          *      Check for packets smaller than the packet header.
2352          *
2353          *      RFC 2865, Section 3., subsection 'length' says:
2354          *
2355          *      "The minimum length is 20 ..."
2356          */
2357         if (packet->data_len < RADIUS_HDR_LEN) {
2358                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (received %zu < minimum %d)",
2359                            inet_ntop(packet->src_ipaddr.af,
2360                                      &packet->src_ipaddr.ipaddr,
2361                                      host_ipaddr, sizeof(host_ipaddr)),
2362                                      packet->data_len, RADIUS_HDR_LEN);
2363                 failure = DECODE_FAIL_MIN_LENGTH_PACKET;
2364                 goto finish;
2365         }
2366
2367
2368         /*
2369          *      Check for packets with mismatched size.
2370          *      i.e. We've received 128 bytes, and the packet header
2371          *      says it's 256 bytes long.
2372          */
2373         totallen = (packet->data[2] << 8) | packet->data[3];
2374         hdr = (radius_packet_t *)packet->data;
2375
2376         /*
2377          *      Code of 0 is not understood.
2378          *      Code of 16 or greate is not understood.
2379          */
2380         if ((hdr->code == 0) ||
2381             (hdr->code >= FR_MAX_PACKET_CODE)) {
2382                 FR_DEBUG_STRERROR_PRINTF("Bad RADIUS packet from host %s: unknown packet code %d",
2383                            inet_ntop(packet->src_ipaddr.af,
2384                                      &packet->src_ipaddr.ipaddr,
2385                                      host_ipaddr, sizeof(host_ipaddr)),
2386                            hdr->code);
2387                 failure = DECODE_FAIL_UNKNOWN_PACKET_CODE;
2388                 goto finish;
2389         }
2390
2391         /*
2392          *      Message-Authenticator is required in Status-Server
2393          *      packets, otherwise they can be trivially forged.
2394          */
2395         if (hdr->code == PW_CODE_STATUS_SERVER) require_ma = true;
2396
2397         /*
2398          *      It's also required if the caller asks for it.
2399          */
2400         if (flags) require_ma = true;
2401
2402         /*
2403          *      Repeat the length checks.  This time, instead of
2404          *      looking at the data we received, look at the value
2405          *      of the 'length' field inside of the packet.
2406          *
2407          *      Check for packets smaller than the packet header.
2408          *
2409          *      RFC 2865, Section 3., subsection 'length' says:
2410          *
2411          *      "The minimum length is 20 ..."
2412          */
2413         if (totallen < RADIUS_HDR_LEN) {
2414                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (length %zu < minimum %d)",
2415                            inet_ntop(packet->src_ipaddr.af,
2416                                      &packet->src_ipaddr.ipaddr,
2417                                      host_ipaddr, sizeof(host_ipaddr)),
2418                                      totallen, RADIUS_HDR_LEN);
2419                 failure = DECODE_FAIL_MIN_LENGTH_FIELD;
2420                 goto finish;
2421         }
2422
2423         /*
2424          *      And again, for the value of the 'length' field.
2425          *
2426          *      RFC 2865, Section 3., subsection 'length' says:
2427          *
2428          *      " ... and maximum length is 4096."
2429          *
2430          *      HOWEVER.  This requirement is for the network layer.
2431          *      If the code gets here, we assume that a well-formed
2432          *      packet is an OK packet.
2433          *
2434          *      We allow both the UDP data length, and the RADIUS
2435          *      "length" field to contain up to 64K of data.
2436          */
2437
2438         /*
2439          *      RFC 2865, Section 3., subsection 'length' says:
2440          *
2441          *      "If the packet is shorter than the Length field
2442          *      indicates, it MUST be silently discarded."
2443          *
2444          *      i.e. No response to the NAS.
2445          */
2446         if (packet->data_len < totallen) {
2447                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: received %zu octets, packet length says %zu",
2448                            inet_ntop(packet->src_ipaddr.af,
2449                                      &packet->src_ipaddr.ipaddr,
2450                                      host_ipaddr, sizeof(host_ipaddr)),
2451                                      packet->data_len, totallen);
2452                 failure = DECODE_FAIL_MIN_LENGTH_MISMATCH;
2453                 goto finish;
2454         }
2455
2456         /*
2457          *      RFC 2865, Section 3., subsection 'length' says:
2458          *
2459          *      "Octets outside the range of the Length field MUST be
2460          *      treated as padding and ignored on reception."
2461          */
2462         if (packet->data_len > totallen) {
2463                 /*
2464                  *      We're shortening the packet below, but just
2465                  *      to be paranoid, zero out the extra data.
2466                  */
2467                 memset(packet->data + totallen, 0, packet->data_len - totallen);
2468                 packet->data_len = totallen;
2469         }
2470
2471         /*
2472          *      Walk through the packet's attributes, ensuring that
2473          *      they add up EXACTLY to the size of the packet.
2474          *
2475          *      If they don't, then the attributes either under-fill
2476          *      or over-fill the packet.  Any parsing of the packet
2477          *      is impossible, and will result in unknown side effects.
2478          *
2479          *      This would ONLY happen with buggy RADIUS implementations,
2480          *      or with an intentional attack.  Either way, we do NOT want
2481          *      to be vulnerable to this problem.
2482          */
2483         attr = hdr->data;
2484         count = totallen - RADIUS_HDR_LEN;
2485         num_attributes = 0;
2486
2487         while (count > 0) {
2488                 /*
2489                  *      We need at least 2 bytes to check the
2490                  *      attribute header.
2491                  */
2492                 if (count < 2) {
2493                         FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute header overflows the packet",
2494                                    inet_ntop(packet->src_ipaddr.af,
2495                                              &packet->src_ipaddr.ipaddr,
2496                                              host_ipaddr, sizeof(host_ipaddr)));
2497                         failure = DECODE_FAIL_HEADER_OVERFLOW;
2498                         goto finish;
2499                 }
2500
2501                 /*
2502                  *      Attribute number zero is NOT defined.
2503                  */
2504                 if (attr[0] == 0) {
2505                         FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Invalid attribute 0",
2506                                    inet_ntop(packet->src_ipaddr.af,
2507                                              &packet->src_ipaddr.ipaddr,
2508                                              host_ipaddr, sizeof(host_ipaddr)));
2509                         failure = DECODE_FAIL_INVALID_ATTRIBUTE;
2510                         goto finish;
2511                 }
2512
2513                 /*
2514                  *      Attributes are at LEAST as long as the ID & length
2515                  *      fields.  Anything shorter is an invalid attribute.
2516                  */
2517                 if (attr[1] < 2) {
2518                         FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u too short",
2519                                    inet_ntop(packet->src_ipaddr.af,
2520                                              &packet->src_ipaddr.ipaddr,
2521                                              host_ipaddr, sizeof(host_ipaddr)),
2522                                    attr[0]);
2523                         failure = DECODE_FAIL_ATTRIBUTE_TOO_SHORT;
2524                         goto finish;
2525                 }
2526
2527                 /*
2528                  *      If there are fewer bytes in the packet than in the
2529                  *      attribute, it's a bad packet.
2530                  */
2531                 if (count < attr[1]) {
2532                         FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
2533                                    inet_ntop(packet->src_ipaddr.af,
2534                                              &packet->src_ipaddr.ipaddr,
2535                                              host_ipaddr, sizeof(host_ipaddr)),
2536                                            attr[0]);
2537                         failure = DECODE_FAIL_ATTRIBUTE_OVERFLOW;
2538                         goto finish;
2539                 }
2540
2541                 /*
2542                  *      Sanity check the attributes for length.
2543                  */
2544                 switch (attr[0]) {
2545                 default:        /* don't do anything by default */
2546                         break;
2547
2548                         /*
2549                          *      If there's an EAP-Message, we require
2550                          *      a Message-Authenticator.
2551                          */
2552                 case PW_EAP_MESSAGE:
2553                         require_ma = true;
2554                         eap = true;
2555                         break;
2556
2557                 case PW_USER_PASSWORD:
2558                 case PW_CHAP_PASSWORD:
2559                 case PW_ARAP_PASSWORD:
2560                         non_eap = true;
2561                         break;
2562
2563                 case PW_MESSAGE_AUTHENTICATOR:
2564                         if (attr[1] != 2 + AUTH_VECTOR_LEN) {
2565                                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
2566                                            inet_ntop(packet->src_ipaddr.af,
2567                                                      &packet->src_ipaddr.ipaddr,
2568                                                      host_ipaddr, sizeof(host_ipaddr)),
2569                                            attr[1] - 2);
2570                                 failure = DECODE_FAIL_MA_INVALID_LENGTH;
2571                                 goto finish;
2572                         }
2573                         seen_ma = true;
2574                         break;
2575                 }
2576
2577                 /*
2578                  *      FIXME: Look up the base 255 attributes in the
2579                  *      dictionary, and switch over their type.  For
2580                  *      integer/date/ip, the attribute length SHOULD
2581                  *      be 6.
2582                  */
2583                 count -= attr[1];       /* grab the attribute length */
2584                 attr += attr[1];
2585                 num_attributes++;       /* seen one more attribute */
2586         }
2587
2588         /*
2589          *      If the attributes add up to a packet, it's allowed.
2590          *
2591          *      If not, we complain, and throw the packet away.
2592          */
2593         if (count != 0) {
2594                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
2595                            inet_ntop(packet->src_ipaddr.af,
2596                                      &packet->src_ipaddr.ipaddr,
2597                                      host_ipaddr, sizeof(host_ipaddr)));
2598                 failure = DECODE_FAIL_ATTRIBUTE_UNDERFLOW;
2599                 goto finish;
2600         }
2601
2602         /*
2603          *      If we're configured to look for a maximum number of
2604          *      attributes, and we've seen more than that maximum,
2605          *      then throw the packet away, as a possible DoS.
2606          */
2607         if ((fr_max_attributes > 0) &&
2608             (num_attributes > fr_max_attributes)) {
2609                 FR_DEBUG_STRERROR_PRINTF("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2610                            inet_ntop(packet->src_ipaddr.af,
2611                                      &packet->src_ipaddr.ipaddr,
2612                                      host_ipaddr, sizeof(host_ipaddr)),
2613                            num_attributes, fr_max_attributes);
2614                 failure = DECODE_FAIL_TOO_MANY_ATTRIBUTES;
2615                 goto finish;
2616         }
2617
2618         /*
2619          *      http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
2620          *
2621          *      A packet with an EAP-Message attribute MUST also have
2622          *      a Message-Authenticator attribute.
2623          *
2624          *      A Message-Authenticator all by itself is OK, though.
2625          *
2626          *      Similarly, Status-Server packets MUST contain
2627          *      Message-Authenticator attributes.
2628          */
2629         if (require_ma && !seen_ma) {
2630                 FR_DEBUG_STRERROR_PRINTF("Insecure packet from host %s:  Packet does not contain required Message-Authenticator attribute",
2631                            inet_ntop(packet->src_ipaddr.af,
2632                                      &packet->src_ipaddr.ipaddr,
2633                                      host_ipaddr, sizeof(host_ipaddr)));
2634                 failure = DECODE_FAIL_MA_MISSING;
2635                 goto finish;
2636         }
2637
2638         if (eap && non_eap) {
2639                 FR_DEBUG_STRERROR_PRINTF("Bad packet from host %s:  Packet contains EAP-Message and non-EAP authentication attribute",
2640                            inet_ntop(packet->src_ipaddr.af,
2641                                      &packet->src_ipaddr.ipaddr,
2642                                      host_ipaddr, sizeof(host_ipaddr)));
2643                 failure = DECODE_FAIL_TOO_MANY_AUTH;
2644                 goto finish;
2645         }
2646
2647         /*
2648          *      Fill RADIUS header fields
2649          */
2650         packet->code = hdr->code;
2651         packet->id = hdr->id;
2652         memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
2653
2654
2655         finish:
2656
2657         if (reason) {
2658                 *reason = failure;
2659         }
2660         return (failure == DECODE_FAIL_NONE);
2661 }
2662
2663
2664 /** Receive UDP client requests, and fill in the basics of a RADIUS_PACKET structure
2665  *
2666  */
2667 RADIUS_PACKET *rad_recv(TALLOC_CTX *ctx, int fd, int flags)
2668 {
2669         int sock_flags = 0;
2670         ssize_t data_len;
2671         RADIUS_PACKET           *packet;
2672
2673         /*
2674          *      Allocate the new request data structure
2675          */
2676         packet = rad_alloc(ctx, false);
2677         if (!packet) {
2678                 fr_strerror_printf("out of memory");
2679                 return NULL;
2680         }
2681
2682         if (flags & 0x02) {
2683                 sock_flags = MSG_PEEK;
2684                 flags &= ~0x02;
2685         }
2686
2687         data_len = rad_recvfrom(fd, packet, sock_flags,
2688                                 &packet->src_ipaddr, &packet->src_port,
2689                                 &packet->dst_ipaddr, &packet->dst_port);
2690
2691         /*
2692          *      Check for socket errors.
2693          */
2694         if (data_len < 0) {
2695                 FR_DEBUG_STRERROR_PRINTF("Error receiving packet: %s", fr_syserror(errno));
2696                 /* packet->data is NULL */
2697                 rad_free(&packet);
2698                 return NULL;
2699         }
2700         packet->data_len = data_len; /* unsigned vs signed */
2701
2702         /*
2703          *      If the packet is too big, then rad_recvfrom did NOT
2704          *      allocate memory.  Instead, it just discarded the
2705          *      packet.
2706          */
2707         if (packet->data_len > MAX_PACKET_LEN) {
2708                 FR_DEBUG_STRERROR_PRINTF("Discarding packet: Larger than RFC limitation of 4096 bytes");
2709                 /* packet->data is NULL */
2710                 rad_free(&packet);
2711                 return NULL;
2712         }
2713
2714         /*
2715          *      Read no data.  Continue.
2716          *      This check is AFTER the MAX_PACKET_LEN check above, because
2717          *      if the packet is larger than MAX_PACKET_LEN, we also have
2718          *      packet->data == NULL
2719          */
2720         if ((packet->data_len == 0) || !packet->data) {
2721                 FR_DEBUG_STRERROR_PRINTF("Empty packet: Socket is not ready");
2722                 rad_free(&packet);
2723                 return NULL;
2724         }
2725
2726         /*
2727          *      See if it's a well-formed RADIUS packet.
2728          */
2729         if (!rad_packet_ok(packet, flags, NULL)) {
2730                 rad_free(&packet);
2731                 return NULL;
2732         }
2733
2734         /*
2735          *      Remember which socket we read the packet from.
2736          */
2737         packet->sockfd = fd;
2738
2739         /*
2740          *      FIXME: Do even more filtering by only permitting
2741          *      certain IP's.  The problem is that we don't know
2742          *      how to do this properly for all possible clients...
2743          */
2744
2745         /*
2746          *      Explicitely set the VP list to empty.
2747          */
2748         packet->vps = NULL;
2749
2750 #ifndef NDEBUG
2751         if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2752 #endif
2753
2754         return packet;
2755 }
2756
2757
2758 /** Verify the Request/Response Authenticator (and Message-Authenticator if present) of a packet
2759  *
2760  */
2761 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original, char const *secret)
2762 {
2763         uint8_t         *ptr;
2764         int             length;
2765         int             attrlen;
2766         int             rcode;
2767         char            buffer[32];
2768
2769         if (!packet || !packet->data) return -1;
2770
2771         /*
2772          *      Before we allocate memory for the attributes, do more
2773          *      sanity checking.
2774          */
2775         ptr = packet->data + RADIUS_HDR_LEN;
2776         length = packet->data_len - RADIUS_HDR_LEN;
2777         while (length > 0) {
2778                 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2779                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2780
2781                 attrlen = ptr[1];
2782
2783                 switch (ptr[0]) {
2784                 default:        /* don't do anything. */
2785                         break;
2786
2787                         /*
2788                          *      Note that more than one Message-Authenticator
2789                          *      attribute is invalid.
2790                          */
2791                 case PW_MESSAGE_AUTHENTICATOR:
2792                         memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2793                         memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2794
2795                         switch (packet->code) {
2796                         default:
2797                                 break;
2798
2799                         case PW_CODE_ACCOUNTING_RESPONSE:
2800                                 if (original &&
2801                                     (original->code == PW_CODE_STATUS_SERVER)) {
2802                                         goto do_ack;
2803                                 }
2804
2805                         case PW_CODE_ACCOUNTING_REQUEST:
2806                         case PW_CODE_DISCONNECT_REQUEST:
2807                         case PW_CODE_COA_REQUEST:
2808                                 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2809                                 break;
2810
2811                         do_ack:
2812                         case PW_CODE_ACCESS_ACCEPT:
2813                         case PW_CODE_ACCESS_REJECT:
2814                         case PW_CODE_ACCESS_CHALLENGE:
2815                         case PW_CODE_DISCONNECT_ACK:
2816                         case PW_CODE_DISCONNECT_NAK:
2817                         case PW_CODE_COA_ACK:
2818                         case PW_CODE_COA_NAK:
2819                                 if (!original) {
2820                                         fr_strerror_printf("Cannot validate Message-Authenticator in response "
2821                                                            "packet without a request packet");
2822                                         return -1;
2823                                 }
2824                                 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2825                                 break;
2826                         }
2827
2828                         fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
2829                                     (uint8_t const *) secret, strlen(secret));
2830                         if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2831                                    sizeof(calc_auth_vector)) != 0) {
2832                                 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator!  "
2833                                                    "(Shared secret is incorrect.)",
2834                                                    inet_ntop(packet->src_ipaddr.af,
2835                                                              &packet->src_ipaddr.ipaddr,
2836                                                              buffer, sizeof(buffer)));
2837                                 /* Silently drop packet, according to RFC 3579 */
2838                                 return -1;
2839                         } /* else the message authenticator was good */
2840
2841                         /*
2842                          *      Reinitialize Authenticators.
2843                          */
2844                         memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2845                         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2846                         break;
2847                 } /* switch over the attributes */
2848
2849                 ptr += attrlen;
2850                 length -= attrlen;
2851         } /* loop over the packet, sanity checking the attributes */
2852
2853         /*
2854          *      It looks like a RADIUS packet, but we don't know what it is
2855          *      so can't validate the authenticators.
2856          */
2857         if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2858                 fr_strerror_printf("Received Unknown packet code %d "
2859                                    "from client %s port %d: Cannot validate Request/Response Authenticator.",
2860                                    packet->code,
2861                                    inet_ntop(packet->src_ipaddr.af,
2862                                              &packet->src_ipaddr.ipaddr,
2863                                              buffer, sizeof(buffer)),
2864                                    packet->src_port);
2865                 return -1;
2866         }
2867
2868         /*
2869          *      Calculate and/or verify Request or Response Authenticator.
2870          */
2871         switch (packet->code) {
2872         case PW_CODE_ACCESS_REQUEST:
2873         case PW_CODE_STATUS_SERVER:
2874                 /*
2875                  *      The authentication vector is random
2876                  *      nonsense, invented by the client.
2877                  */
2878                 break;
2879
2880         case PW_CODE_COA_REQUEST:
2881         case PW_CODE_DISCONNECT_REQUEST:
2882         case PW_CODE_ACCOUNTING_REQUEST:
2883                 if (calc_acctdigest(packet, secret) > 1) {
2884                         fr_strerror_printf("Received %s packet "
2885                                            "from client %s with invalid Request Authenticator!  "
2886                                            "(Shared secret is incorrect.)",
2887                                            fr_packet_codes[packet->code],
2888                                            inet_ntop(packet->src_ipaddr.af,
2889                                                      &packet->src_ipaddr.ipaddr,
2890                                                      buffer, sizeof(buffer)));
2891                         return -1;
2892                 }
2893                 break;
2894
2895                 /* Verify the reply digest */
2896         case PW_CODE_ACCESS_ACCEPT:
2897         case PW_CODE_ACCESS_REJECT:
2898         case PW_CODE_ACCESS_CHALLENGE:
2899         case PW_CODE_ACCOUNTING_RESPONSE:
2900         case PW_CODE_DISCONNECT_ACK:
2901         case PW_CODE_DISCONNECT_NAK:
2902         case PW_CODE_COA_ACK:
2903         case PW_CODE_COA_NAK:
2904                 rcode = calc_replydigest(packet, original, secret);
2905                 if (rcode > 1) {
2906                         fr_strerror_printf("Received %s packet "
2907                                            "from home server %s port %d with invalid Response Authenticator!  "
2908                                            "(Shared secret is incorrect.)",
2909                                            fr_packet_codes[packet->code],
2910                                            inet_ntop(packet->src_ipaddr.af,
2911                                                      &packet->src_ipaddr.ipaddr,
2912                                                      buffer, sizeof(buffer)),
2913                                            packet->src_port);
2914                         return -1;
2915                 }
2916                 break;
2917
2918         default:
2919                 fr_strerror_printf("Received Unknown packet code %d "
2920                                    "from client %s port %d: Cannot validate Request/Response Authenticator",
2921                                    packet->code,
2922                                    inet_ntop(packet->src_ipaddr.af,
2923                                              &packet->src_ipaddr.ipaddr,
2924                                              buffer, sizeof(buffer)),
2925                                    packet->src_port);
2926                 return -1;
2927         }
2928
2929         return 0;
2930 }
2931
2932
2933 /** Convert a "concatenated" attribute to one long VP
2934  *
2935  */
2936 static ssize_t data2vp_concat(TALLOC_CTX *ctx,
2937                               DICT_ATTR const *da, uint8_t const *start,
2938                               size_t const packetlen, VALUE_PAIR **pvp)
2939 {
2940         size_t total;
2941         uint8_t attr;
2942         uint8_t const *ptr = start;
2943         uint8_t const *end = start + packetlen;
2944         uint8_t *p;
2945         VALUE_PAIR *vp;
2946
2947         total = 0;
2948         attr = ptr[0];
2949
2950         /*
2951          *      The packet has already been sanity checked, so we
2952          *      don't care about walking off of the end of it.
2953          */
2954         while (ptr < end) {
2955                 total += ptr[1] - 2;
2956
2957                 ptr += ptr[1];
2958
2959                 /*
2960                  *      Attributes MUST be consecutive.
2961                  */
2962                 if (ptr[0] != attr) break;
2963         }
2964
2965         vp = fr_pair_afrom_da(ctx, da);
2966         if (!vp) return -1;
2967
2968         vp->vp_length = total;
2969         vp->vp_octets = p = talloc_array(vp, uint8_t, vp->vp_length);
2970         if (!p) {
2971                 fr_pair_list_free(&vp);
2972                 return -1;
2973         }
2974
2975         total = 0;
2976         ptr = start;
2977         while (total < vp->vp_length) {
2978                 memcpy(p, ptr + 2, ptr[1] - 2);
2979                 p += ptr[1] - 2;
2980                 total += ptr[1] - 2;
2981                 ptr += ptr[1];
2982         }
2983
2984         *pvp = vp;
2985         return ptr - start;
2986 }
2987
2988
2989 /** Convert TLVs to one or more VPs
2990  *
2991  */
2992 ssize_t rad_data2vp_tlvs(TALLOC_CTX *ctx,
2993                             RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2994                             char const *secret, DICT_ATTR const *da,
2995                             uint8_t const *start, size_t length,
2996                             VALUE_PAIR **pvp)
2997 {
2998         uint8_t const *data = start;
2999         DICT_ATTR const *child;
3000         VALUE_PAIR *head, **tail;
3001
3002         if (length < 3) return -1; /* type, length, value */
3003
3004         VP_HEXDUMP("tlvs", data, length);
3005
3006         if (rad_tlv_ok(data, length, 1, 1) < 0) return -1;
3007
3008         head = NULL;
3009         tail = &head;
3010
3011         while (data < (start + length)) {
3012                 ssize_t tlv_len;
3013
3014                 child = dict_attrbyparent(da, data[0], da->vendor);
3015                 if (!child) {
3016                         unsigned int my_attr, my_vendor;
3017
3018                         VP_TRACE("Failed to find child %u of TLV %s\n",
3019                                  data[0], da->name);
3020
3021                         /*
3022                          *      Get child attr/vendor so that
3023                          *      we can call unknown attr.
3024                          */
3025                         my_attr = data[0];
3026                         my_vendor = da->vendor;
3027
3028                         if (!dict_attr_child(da, &my_attr, &my_vendor)) {
3029                                 fr_pair_list_free(&head);
3030                                 return -1;
3031                         }
3032
3033                         child = dict_unknown_afrom_fields(ctx, my_attr, my_vendor);
3034                         if (!child) {
3035                                 fr_pair_list_free(&head);
3036                                 return -1;
3037                         }
3038                 }
3039
3040                 tlv_len = data2vp(ctx, packet, original, secret, child,
3041                                   data + 2, data[1] - 2, data[1] - 2, tail);
3042                 if (tlv_len < 0) {
3043                         fr_pair_list_free(&head);
3044                         return -1;
3045                 }
3046                 if (*tail) tail = &((*tail)->next);
3047                 data += data[1];
3048         }
3049
3050         *pvp = head;
3051         return length;
3052 }
3053
3054 /** Convert a top-level VSA to a VP.
3055  *
3056  * "length" can be LONGER than just this sub-vsa.
3057  */
3058 static ssize_t data2vp_vsa(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3059                            RADIUS_PACKET const *original,
3060                            char const *secret, DICT_VENDOR *dv,
3061                            uint8_t const *data, size_t length,
3062                            VALUE_PAIR **pvp)
3063 {
3064         unsigned int attribute;
3065         ssize_t attrlen, my_len;
3066         DICT_ATTR const *da;
3067
3068         VP_TRACE("data2vp_vsa: length %u\n", (unsigned int) length);
3069
3070 #ifndef NDEBUG
3071         if (length <= (dv->type + dv->length)) {
3072                 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
3073                 return -1;
3074         }
3075 #endif
3076
3077         switch (dv->type) {
3078         case 4:
3079                 /* data[0] must be zero */
3080                 attribute = data[1] << 16;
3081                 attribute |= data[2] << 8;
3082                 attribute |= data[3];
3083                 break;
3084
3085         case 2:
3086                 attribute = data[0] << 8;
3087                 attribute |= data[1];
3088                 break;
3089
3090         case 1:
3091                 attribute = data[0];
3092                 break;
3093
3094         default:
3095                 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3096                 return -1;
3097         }
3098
3099         switch (dv->length) {
3100         case 2:
3101                 /* data[dv->type] must be zero, from rad_tlv_ok() */
3102                 attrlen = data[dv->type + 1];
3103                 break;
3104
3105         case 1:
3106                 attrlen = data[dv->type];
3107                 break;
3108
3109         case 0:
3110                 attrlen = length;
3111                 break;
3112
3113         default:
3114                 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3115                 return -1;
3116         }
3117
3118         /*
3119          *      See if the VSA is known.
3120          */
3121         da = dict_attrbyvalue(attribute, dv->vendorpec);
3122         if (!da) da = dict_unknown_afrom_fields(ctx, attribute, dv->vendorpec);
3123         if (!da) return -1;
3124
3125         my_len = data2vp(ctx, packet, original, secret, da,
3126                          data + dv->type + dv->length,
3127                          attrlen - (dv->type + dv->length),
3128                          attrlen - (dv->type + dv->length),
3129                          pvp);
3130         if (my_len < 0) return my_len;
3131
3132         return attrlen;
3133 }
3134
3135
3136 /** Convert a fragmented extended attr to a VP
3137  *
3138  * Format is:
3139  *
3140  * attr
3141  * length
3142  * extended-attr
3143  * flag
3144  * data...
3145  *
3146  * But for the first fragment, we get passed a pointer to the "extended-attr"
3147  */
3148 static ssize_t data2vp_extended(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3149                                 RADIUS_PACKET const *original,
3150                                 char const *secret, DICT_ATTR const *da,
3151                                 uint8_t const *data,
3152                                 size_t attrlen, size_t packetlen,
3153                                 VALUE_PAIR **pvp)
3154 {
3155         ssize_t rcode;
3156         size_t fraglen;
3157         uint8_t *head, *tail;
3158         uint8_t const *frag, *end;
3159         uint8_t const *attr;
3160         int fragments;
3161         bool last_frag;
3162
3163         if (attrlen < 3) return -1;
3164
3165         /*
3166          *      Calculate the length of all of the fragments.  For
3167          *      now, they MUST be contiguous in the packet, and they
3168          *      MUST be all of the same TYPE and EXTENDED-TYPE
3169          */
3170         attr = data - 2;
3171         fraglen = attrlen - 2;
3172         frag = data + attrlen;
3173         end = data + packetlen;
3174         fragments = 1;
3175         last_frag = false;
3176
3177         while (frag < end) {
3178                 if (last_frag ||
3179                     (frag[0] != attr[0]) ||
3180                     (frag[1] < 4) ||                   /* too short for long-extended */
3181                     (frag[2] != attr[2]) ||
3182                     ((frag + frag[1]) > end)) {         /* overflow */
3183                         end = frag;
3184                         break;
3185                 }
3186
3187                 last_frag = ((frag[3] & 0x80) == 0);
3188
3189                 fraglen += frag[1] - 4;
3190                 frag += frag[1];
3191                 fragments++;
3192         }
3193
3194         head = tail = malloc(fraglen);
3195         if (!head) return -1;
3196
3197         VP_TRACE("Fragments %d, total length %d\n", fragments, (int) fraglen);
3198
3199         /*
3200          *      And again, but faster and looser.
3201          *
3202          *      We copy the first fragment, followed by the rest of
3203          *      the fragments.
3204          */
3205         frag = attr;
3206
3207         while (fragments >  0) {
3208                 memcpy(tail, frag + 4, frag[1] - 4);
3209                 tail += frag[1] - 4;
3210                 frag += frag[1];
3211                 fragments--;
3212         }
3213
3214         VP_HEXDUMP("long-extended fragments", head, fraglen);
3215
3216         rcode = data2vp(ctx, packet, original, secret, da,
3217                         head, fraglen, fraglen, pvp);
3218         free(head);
3219         if (rcode < 0) return rcode;
3220
3221         return end - data;
3222 }
3223
3224 /** Convert a Vendor-Specific WIMAX to VPs
3225  *
3226  * @note Called ONLY for Vendor-Specific
3227  */
3228 static ssize_t data2vp_wimax(TALLOC_CTX *ctx,
3229                              RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3230                              char const *secret, uint32_t vendor,
3231                              uint8_t const *data,
3232                              size_t attrlen, size_t packetlen,
3233                              VALUE_PAIR **pvp)
3234 {
3235         ssize_t rcode;
3236         size_t wimax_len;
3237         bool more;
3238         uint8_t *head, *tail;
3239         uint8_t const *attr, *end;
3240         DICT_ATTR const *child;
3241
3242         /*
3243          *      data = VID VID VID VID WiMAX-Attr WimAX-Len Continuation ...
3244          */
3245
3246         /*
3247          *      Not enough room for WiMAX Vendor + Wimax attr + length
3248          *      + continuation, it's a bad attribute.
3249          */
3250         if (attrlen < 8) {
3251         raw:            
3252                 /*
3253                  *      It's not a Vendor-Specific, it's unknown...
3254                  */
3255                 child = dict_unknown_afrom_fields(ctx, PW_VENDOR_SPECIFIC, 0);
3256                 if (!child) {
3257                         fr_strerror_printf("Internal sanity check %d", __LINE__);
3258                         return -1;
3259                 }
3260
3261                 rcode = data2vp(ctx, packet, original, secret, child,
3262                                 data, attrlen, attrlen, pvp);
3263                 if (rcode < 0) return rcode;
3264                 return attrlen;
3265         }
3266
3267         if (data[5] < 3) goto raw;              /* WiMAX-Length is too small */
3268
3269         child = dict_attrbyvalue(data[4], vendor);
3270         if (!child) goto raw;
3271
3272         /*
3273          *      No continued data, just decode the attribute in place.
3274          */
3275         if ((data[6] & 0x80) == 0) {
3276                 if ((data[5] + 4) != attrlen) goto raw; /* WiMAX attribute doesn't fill Vendor-Specific */
3277
3278                 rcode = data2vp(ctx, packet, original, secret, child,
3279                                 data + 7, data[5] - 3, data[5] - 3,
3280                                 pvp);
3281
3282                 if ((rcode < 0) || (((size_t) rcode + 7) != attrlen)) goto raw; /* didn't decode all of the data */
3283                 return attrlen;
3284         }
3285
3286         /*
3287          *      Calculate the length of all of the fragments.  For
3288          *      now, they MUST be contiguous in the packet, and they
3289          *      MUST be all of the same VSA, WiMAX, and WiMAX-attr.
3290          *
3291          *      The first fragment doesn't have a RADIUS attribute
3292          *      header.
3293          */
3294         wimax_len = 0;
3295         attr = data + 4;
3296         end = data + packetlen;
3297
3298         while (attr < end) {
3299                 /*
3300                  *      Not enough room for Attribute + length +
3301                  *      continuation, it's bad.
3302                  */
3303                 if ((end - attr) < 3) goto raw;
3304
3305                 /*
3306                  *      Must have non-zero data in the attribute.
3307                  */
3308                 if (attr[1] <= 3) goto raw;
3309
3310                 /*
3311                  *      If the WiMAX attribute overflows the packet,
3312                  *      it's bad.
3313                  */
3314                 if ((attr + attr[1]) > end) goto raw;
3315
3316                 /*
3317                  *      Check the continuation flag.
3318                  */
3319                 more = ((attr[2] & 0x80) != 0);
3320
3321                 /*
3322                  *      Or, there's no more data, in which case we
3323                  *      shorten "end" to finish at this attribute.
3324                  */
3325                 if (!more) end = attr + attr[1];
3326
3327                 /*
3328                  *      There's more data, but we're at the end of the
3329                  *      packet.  The attribute is malformed!
3330                  */
3331                 if (more && ((attr + attr[1]) == end)) goto raw;
3332
3333                 /*
3334                  *      Add in the length of the data we need to
3335                  *      concatenate together.
3336                  */
3337                 wimax_len += attr[1] - 3;
3338
3339                 /*
3340                  *      Go to the next attribute, and stop if there's
3341                  *      no more.
3342                  */
3343                 attr += attr[1];
3344                 if (!more) break;
3345
3346                 /*
3347                  *      data = VID VID VID VID WiMAX-Attr WimAX-Len Continuation ...
3348                  *
3349                  *      attr = Vendor-Specific VSA-Length VID VID VID VID WiMAX-Attr WimAX-Len Continuation ...
3350                  *
3351                  */
3352
3353                 /*
3354                  *      No room for Vendor-Specific + length +
3355                  *      Vendor(4) + attr + length + continuation + data
3356                  */
3357                 if ((end - attr) < 9) goto raw;
3358
3359                 if (attr[0] != PW_VENDOR_SPECIFIC) goto raw;
3360                 if (attr[1] < 9) goto raw;
3361                 if ((attr + attr[1]) > end) goto raw;
3362                 if (memcmp(data, attr + 2, 4) != 0) goto raw; /* not WiMAX Vendor ID */
3363
3364                 if (attr[1] != (attr[7] + 6)) goto raw; /* WiMAX attr doesn't exactly fill the VSA */
3365
3366                 if (data[4] != attr[6]) goto raw; /* different WiMAX attribute */
3367
3368                 /*
3369                  *      Skip over the Vendor-Specific header, and
3370                  *      continue with the WiMAX attributes.
3371                  */
3372                 attr += 6;
3373         }
3374
3375         /*
3376          *      No data in the WiMAX attribute, make a "raw" one.
3377          */
3378         if (!wimax_len) goto raw;
3379
3380         head = tail = malloc(wimax_len);
3381         if (!head) return -1;
3382
3383         /*
3384          *      Copy the data over, this time trusting the attribute
3385          *      contents.
3386          */
3387         attr = data;
3388         while (attr < end) {
3389                 memcpy(tail, attr + 4 + 3, attr[4 + 1] - 3);
3390                 tail += attr[4 + 1] - 3;
3391                 attr += 4 + attr[4 + 1]; /* skip VID+WiMax header */
3392                 attr += 2;               /* skip Vendor-Specific header */
3393         }
3394
3395         VP_HEXDUMP("wimax fragments", head, wimax_len);
3396
3397         rcode = data2vp(ctx, packet, original, secret, child,
3398                         head, wimax_len, wimax_len, pvp);
3399         free(head);
3400         if (rcode < 0) goto raw;
3401
3402         return end - data;
3403 }
3404
3405
3406 /** Convert a top-level VSA to one or more VPs
3407  *
3408  */
3409 static ssize_t data2vp_vsas(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3410                             RADIUS_PACKET const *original,
3411                             char const *secret, uint8_t const *data,
3412                             size_t attrlen, size_t packetlen,
3413                             VALUE_PAIR **pvp)
3414 {
3415         size_t total;
3416         ssize_t rcode;
3417         uint32_t vendor;
3418         DICT_VENDOR *dv;
3419         VALUE_PAIR *head, **tail;
3420         DICT_VENDOR my_dv;
3421
3422         if (attrlen > packetlen) return -1;
3423         if (attrlen < 5) return -1; /* vid, value */
3424         if (data[0] != 0) return -1; /* we require 24-bit VIDs */
3425
3426         VP_TRACE("data2vp_vsas\n");
3427
3428         memcpy(&vendor, data, 4);
3429         vendor = ntohl(vendor);
3430         dv = dict_vendorbyvalue(vendor);
3431         if (!dv) {
3432                 /*
3433                  *      RFC format is 1 octet type, 1 octet length
3434                  */
3435                 if (rad_tlv_ok(data + 4, attrlen - 4, 1, 1) < 0) {
3436                         VP_TRACE("data2vp_vsas: unknown tlvs not OK: %s\n", fr_strerror());
3437                         return -1;
3438                 }
3439
3440                 /*
3441                  *      It's a known unknown.
3442                  */
3443                 memset(&my_dv, 0, sizeof(my_dv));
3444                 dv = &my_dv;
3445
3446                 /*
3447                  *      Fill in the fields.  Note that the name is empty!
3448                  */
3449                 dv->vendorpec = vendor;
3450                 dv->type = 1;
3451                 dv->length = 1;
3452
3453                 goto create_attrs;
3454         }
3455
3456         /*
3457          *      WiMAX craziness
3458          */
3459         if ((vendor == VENDORPEC_WIMAX) && dv->flags) {
3460                 rcode = data2vp_wimax(ctx, packet, original, secret, vendor,
3461                                       data, attrlen, packetlen, pvp);
3462                 return rcode;
3463         }
3464
3465         /*
3466          *      VSAs should normally be in TLV format.
3467          */
3468         if (rad_tlv_ok(data + 4, attrlen - 4,
3469                        dv->type, dv->length) < 0) {
3470                 VP_TRACE("data2vp_vsas: tlvs not OK: %s\n", fr_strerror());
3471                 return -1;
3472         }
3473
3474         /*
3475          *      There may be more than one VSA in the
3476          *      Vendor-Specific.  If so, loop over them all.
3477          */
3478 create_attrs:
3479         data += 4;
3480         attrlen -= 4;
3481         packetlen -= 4;
3482         total = 4;
3483         head = NULL;
3484         tail = &head;
3485
3486         while (attrlen > 0) {
3487                 ssize_t vsa_len;
3488
3489                 vsa_len = data2vp_vsa(ctx, packet, original, secret, dv,
3490                                       data, attrlen, tail);
3491                 if (vsa_len < 0) {
3492                         fr_pair_list_free(&head);
3493                         fr_strerror_printf("Internal sanity check %d", __LINE__);
3494                         return -1;
3495                 }
3496
3497                 /*
3498                  *      Vendors can send zero-length VSAs.
3499                  */
3500                 if (*tail) tail = &((*tail)->next);
3501
3502                 data += vsa_len;
3503                 attrlen -= vsa_len;
3504                 packetlen -= vsa_len;
3505                 total += vsa_len;
3506         }
3507
3508         *pvp = head;
3509         return total;
3510 }
3511
3512 /** Create any kind of VP from the attribute contents
3513  *
3514  * "length" is AT LEAST the length of this attribute, as we
3515  * expect the caller to have verified the data with
3516  * rad_packet_ok().  "length" may be up to the length of the
3517  * packet.
3518  *
3519  * @return -1 on error, or "length".
3520  */
3521 ssize_t data2vp(TALLOC_CTX *ctx,
3522                 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3523                 char const *secret,
3524                 DICT_ATTR const *da, uint8_t const *start,
3525                 size_t const attrlen, size_t const packetlen,
3526                 VALUE_PAIR **pvp)
3527 {
3528         int8_t tag = TAG_NONE;
3529         size_t datalen;
3530         ssize_t rcode;
3531         uint32_t vendor;
3532         DICT_ATTR const *child;
3533         VALUE_PAIR *vp;
3534         uint8_t const *data = start;
3535         char *p;
3536         uint8_t buffer[256];
3537
3538         /*
3539          *      FIXME: Attrlen can be larger than 253 for extended attrs!
3540          */
3541         if (!da || (attrlen > packetlen) ||
3542             ((attrlen > 253) && (attrlen != packetlen)) ||
3543             (attrlen > 128*1024)) {
3544                 fr_strerror_printf("data2vp: invalid arguments");
3545                 return -1;
3546         }
3547
3548         VP_HEXDUMP("data2vp", start, attrlen);
3549
3550         VP_TRACE("parent %s len %zu ... %zu\n", da->name, attrlen, packetlen);
3551
3552         datalen = attrlen;
3553
3554         /*
3555          *      Hacks for CUI.  The WiMAX spec says that it can be
3556          *      zero length, even though this is forbidden by the
3557          *      RADIUS specs.  So... we make a special case for it.
3558          */
3559         if (attrlen == 0) {
3560                 if (!((da->vendor == 0) &&
3561                       (da->attr == PW_CHARGEABLE_USER_IDENTITY))) {
3562                         *pvp = NULL;
3563                         return 0;
3564                 }
3565
3566 #ifndef NDEBUG
3567                 /*
3568                  *      Hacks for Coverity.  Editing the dictionary
3569                  *      will break assumptions about CUI.  We know
3570                  *      this, but Coverity doesn't.
3571                  */
3572                 if (da->type != PW_TYPE_OCTETS) return -1;
3573 #endif
3574
3575                 data = NULL;
3576                 datalen = 0;
3577                 goto alloc_cui; /* skip everything */
3578         }
3579
3580         /*
3581          *      Hacks for tags.  If the attribute is capable of
3582          *      encoding a tag, and there's room for the tag, and
3583          *      there is a tag, or it's encrypted with Tunnel-Password,
3584          *      then decode the tag.
3585          */
3586         if (da->flags.has_tag && (datalen > 1) &&
3587             ((data[0] < 0x20) ||
3588              (da->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
3589                 /*
3590                  *      Only "short" attributes can be encrypted.
3591                  */
3592                 if (datalen >= sizeof(buffer)) return -1;
3593
3594                 if (da->type == PW_TYPE_STRING) {
3595                         memcpy(buffer, data + 1, datalen - 1);
3596                         tag = data[0];
3597                         datalen -= 1;
3598
3599                 } else if (da->type == PW_TYPE_INTEGER) {
3600                         memcpy(buffer, data, attrlen);
3601                         tag = buffer[0];
3602                         buffer[0] = 0;
3603
3604                 } else {
3605                         return -1; /* only string and integer can have tags */
3606                 }
3607
3608                 data = buffer;
3609         }
3610
3611         /*
3612          *      Decrypt the attribute.
3613          */
3614         if (secret && packet && (da->flags.encrypt != FLAG_ENCRYPT_NONE)) {
3615                 VP_TRACE("data2vp: decrypting type %u\n", da->flags.encrypt);
3616                 /*
3617                  *      Encrypted attributes can only exist for the
3618                  *      old-style format.  Extended attributes CANNOT
3619                  *      be encrypted.
3620                  */
3621                 if (attrlen > 253) {
3622                         return -1;
3623                 }
3624
3625                 if (data == start) {
3626                         memcpy(buffer, data, attrlen);
3627                 }
3628                 data = buffer;
3629
3630                 switch (da->flags.encrypt) { /* can't be tagged */
3631                 /*
3632                  *  User-Password
3633                  */
3634                 case FLAG_ENCRYPT_USER_PASSWORD:
3635                         if (original) {
3636                                 rad_pwdecode((char *) buffer,
3637                                              attrlen, secret,
3638                                              original->vector);
3639                         } else {
3640                                 rad_pwdecode((char *) buffer,
3641                                              attrlen, secret,
3642                                              packet->vector);
3643                         }
3644                         buffer[253] = '\0';
3645
3646                         /*
3647                          *      MS-CHAP-MPPE-Keys are 24 octets, and
3648                          *      encrypted.  Since it's binary, we can't
3649                          *      look for trailing zeros.
3650                          */
3651                         if (da->flags.length) {
3652                                 if (datalen > da->flags.length) {
3653                                         datalen = da->flags.length;
3654                                 } /* else leave datalen alone */
3655                         } else {
3656                                 /*
3657                                  *      Take off trailing zeros from the END.
3658                                  *      This allows passwords to have zeros in
3659                                  *      the middle of a field.
3660                                  *
3661                                  *      However, if the password has a zero at
3662                                  *      the end, it will get mashed by this
3663                                  *      code.  There's really no way around
3664                                  *      that.
3665                                  */
3666                                 while ((datalen > 0) && (buffer[datalen - 1] == '\0')) datalen--;
3667                         }
3668                         break;
3669
3670                 /*
3671                  *      Tunnel-Password's may go ONLY in response
3672                  *      packets.  They can have a tag, so datalen is
3673                  *      not the same as attrlen.
3674                  */
3675                 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
3676                         if (rad_tunnel_pwdecode(buffer, &datalen, secret,
3677                                                 original ? original->vector : nullvector) < 0) {
3678                                 goto raw;
3679                         }
3680                         break;
3681
3682                 /*
3683                  *  Ascend-Send-Secret
3684                  *  Ascend-Receive-Secret
3685                  */
3686                 case FLAG_ENCRYPT_ASCEND_SECRET:
3687                         if (!original) {
3688                                 goto raw;
3689                         } else {
3690                                 uint8_t my_digest[AUTH_VECTOR_LEN];
3691                                 size_t secret_len;
3692
3693                                 secret_len = datalen;
3694                                 if (secret_len > AUTH_VECTOR_LEN) secret_len = AUTH_VECTOR_LEN;
3695
3696                                 make_secret(my_digest,
3697                                             original->vector,
3698                                             secret, data, secret_len);
3699                                 memcpy(buffer, my_digest,
3700                                        AUTH_VECTOR_LEN );
3701                                 buffer[AUTH_VECTOR_LEN] = '\0';
3702                                 datalen = strlen((char *) buffer);
3703                         }
3704                         break;
3705
3706                 default:
3707                         break;
3708                 } /* switch over encryption flags */
3709         }
3710
3711         /*
3712          *      Double-check the length after decrypting the
3713          *      attribute.
3714          */
3715         VP_TRACE("data2vp: type %u\n", da->type);
3716         switch (da->type) {
3717         case PW_TYPE_STRING:
3718         case PW_TYPE_OCTETS:
3719                 break;
3720
3721         case PW_TYPE_ABINARY:
3722                 if (datalen > sizeof(vp->vp_filter)) goto raw;
3723                 break;
3724
3725         case PW_TYPE_INTEGER:
3726         case PW_TYPE_IPV4_ADDR:
3727         case PW_TYPE_DATE:
3728         case PW_TYPE_SIGNED:
3729                 if (datalen != 4) goto raw;
3730                 break;
3731
3732         case PW_TYPE_INTEGER64:
3733         case PW_TYPE_IFID:
3734                 if (datalen != 8) goto raw;
3735                 break;
3736
3737         case PW_TYPE_IPV6_ADDR:
3738                 if (datalen != 16) goto raw;
3739                 break;
3740
3741         case PW_TYPE_IPV6_PREFIX:
3742                 if ((datalen < 2) || (datalen > 18)) goto raw;
3743                 if (data[1] > 128) goto raw;
3744                 break;
3745
3746         case PW_TYPE_BYTE:
3747                 if (datalen != 1) goto raw;
3748                 break;
3749
3750         case PW_TYPE_SHORT:
3751                 if (datalen != 2) goto raw;
3752                 break;
3753
3754         case PW_TYPE_ETHERNET:
3755                 if (datalen != 6) goto raw;
3756                 break;
3757
3758         case PW_TYPE_COMBO_IP_ADDR:
3759                 if (datalen == 4) {
3760                         child = dict_attrbytype(da->attr, da->vendor,
3761                                                 PW_TYPE_IPV4_ADDR);
3762                 } else if (datalen == 16) {
3763                         child = dict_attrbytype(da->attr, da->vendor,
3764                                              PW_TYPE_IPV6_ADDR);
3765                 } else {
3766                         goto raw;
3767                 }
3768                 if (!child) goto raw;
3769                 da = child;     /* re-write it */
3770                 break;
3771
3772         case PW_TYPE_IPV4_PREFIX:
3773                 if (datalen != 6) goto raw;
3774                 if ((data[1] & 0x3f) > 32) goto raw;
3775                 break;
3776
3777                 /*
3778                  *      The rest of the data types can cause
3779                  *      recursion!  Ask yourself, "is recursion OK?"
3780                  */
3781
3782         case PW_TYPE_EXTENDED:
3783                 if (datalen < 2) goto raw; /* etype, value */
3784
3785                 child = dict_attrbyparent(da, data[0], 0);
3786                 if (!child) goto raw;
3787
3788                 /*
3789                  *      Recurse to decode the contents, which could be
3790                  *      a TLV, IPaddr, etc.  Note that we decode only
3791                  *      the current attribute, and we ignore any extra
3792                  *      data after it.
3793                  */
3794                 rcode = data2vp(ctx, packet, original, secret, child,
3795                                 data + 1, attrlen - 1, attrlen - 1, pvp);
3796                 if (rcode < 0) goto raw;
3797                 return 1 + rcode;
3798
3799         case PW_TYPE_LONG_EXTENDED:
3800                 if (datalen < 3) goto raw; /* etype, flags, value */
3801
3802                 child = dict_attrbyparent(da, data[0], 0);
3803                 if (!child) {
3804                         if ((data[0] != PW_VENDOR_SPECIFIC) ||
3805                             (datalen < (3 + 4 + 1))) {
3806                                 /* da->attr < 255, da->vendor == 0 */
3807                                 child = dict_unknown_afrom_fields(ctx, data[0], da->attr * FR_MAX_VENDOR);
3808                         } else {
3809                                 /*
3810                                  *      Try to find the VSA.
3811                                  */
3812                                 memcpy(&vendor, data + 3, 4);
3813                                 vendor = ntohl(vendor);
3814
3815                                 if (vendor == 0) goto raw;
3816
3817                                 child = dict_unknown_afrom_fields(ctx, data[7], vendor | (da->attr * FR_MAX_VENDOR));
3818                         }
3819
3820                         if (!child) {
3821                                 fr_strerror_printf("Internal sanity check %d", __LINE__);
3822                                 return -1;
3823                         }
3824                 }
3825
3826                 /*
3827                  *      If there no more fragments, then the contents
3828                  *      have to be a well-known data type.
3829                  *
3830                  */
3831                 if ((data[1] & 0x80) == 0) {
3832                         rcode = data2vp(ctx, packet, original, secret, child,
3833                                         data + 2, attrlen - 2, attrlen - 2,
3834                                         pvp);
3835                         if (rcode < 0) goto raw;
3836                         return 2 + rcode;
3837                 }
3838
3839                 /*
3840                  *      This requires a whole lot more work.
3841                  */
3842                 return data2vp_extended(ctx, packet, original, secret, child,
3843                                         start, attrlen, packetlen, pvp);
3844
3845         case PW_TYPE_EVS:
3846                 if (datalen < 6) goto raw; /* vid, vtype, value */
3847
3848                 if (data[0] != 0) goto raw; /* we require 24-bit VIDs */
3849
3850                 memcpy(&vendor, data, 4);
3851                 vendor = ntohl(vendor);
3852                 vendor |= da->vendor;
3853
3854                 child = dict_attrbyvalue(data[4], vendor);
3855                 if (!child) {
3856                         /*
3857                          *      Create a "raw" attribute from the
3858                          *      contents of the EVS VSA.
3859                          */
3860                         da = dict_unknown_afrom_fields(ctx, data[4], vendor);
3861                         data += 5;
3862                         datalen -= 5;
3863                         break;
3864                 }
3865
3866                 rcode = data2vp(ctx, packet, original, secret, child,
3867                                 data + 5, attrlen - 5, attrlen - 5, pvp);
3868                 if (rcode < 0) goto raw;
3869                 return 5 + rcode;
3870
3871         case PW_TYPE_TLV:
3872                 /*
3873                  *      We presume that the TLVs all fit into one
3874                  *      attribute, OR they've already been grouped
3875                  *      into a contiguous memory buffer.
3876                  */
3877                 rcode = rad_data2vp_tlvs(ctx, packet, original, secret, da,
3878                                          data, attrlen, pvp);
3879                 if (rcode < 0) goto raw;
3880                 return rcode;
3881
3882         case PW_TYPE_VSA:
3883                 /*
3884                  *      VSAs can be WiMAX, in which case they don't
3885                  *      fit into one attribute.
3886                  */
3887                 rcode = data2vp_vsas(ctx, packet, original, secret,
3888                                      data, attrlen, packetlen, pvp);
3889                 if (rcode < 0) goto raw;
3890                 return rcode;
3891
3892         default:
3893         raw:
3894                 /*
3895                  *      Re-write the attribute to be "raw".  It is
3896                  *      therefore of type "octets", and will be
3897                  *      handled below.
3898                  */
3899                 da = dict_unknown_afrom_fields(ctx, da->attr, da->vendor);
3900                 if (!da) {
3901                         fr_strerror_printf("Internal sanity check %d", __LINE__);
3902                         return -1;
3903                 }
3904                 tag = TAG_NONE;
3905 #ifndef NDEBUG
3906                 /*
3907                  *      Fix for Coverity.
3908                  */
3909                 if (da->type != PW_TYPE_OCTETS) {
3910                         dict_attr_free(&da);
3911                         return -1;
3912                 }
3913 #endif
3914                 break;
3915         }
3916
3917         /*
3918          *      And now that we've verified the basic type
3919          *      information, decode the actual data.
3920          */
3921  alloc_cui:
3922         vp = fr_pair_afrom_da(ctx, da);
3923         if (!vp) return -1;
3924
3925         vp->vp_length = datalen;
3926         vp->tag = tag;
3927
3928         switch (da->type) {
3929         case PW_TYPE_STRING:
3930                 p = talloc_array(vp, char, vp->vp_length + 1);
3931                 memcpy(p, data, vp->vp_length);
3932                 p[vp->vp_length] = '\0';
3933                 vp->vp_strvalue = p;
3934                 break;
3935
3936         case PW_TYPE_OCTETS:
3937                 fr_pair_value_memcpy(vp, data, vp->vp_length);
3938                 break;
3939
3940         case PW_TYPE_ABINARY:
3941                 if (vp->vp_length > sizeof(vp->vp_filter)) {
3942                         vp->vp_length = sizeof(vp->vp_filter);
3943                 }
3944                 memcpy(vp->vp_filter, data, vp->vp_length);
3945                 break;
3946
3947         case PW_TYPE_BYTE:
3948                 vp->vp_byte = data[0];
3949                 break;
3950
3951         case PW_TYPE_SHORT:
3952                 vp->vp_short = (data[0] << 8) | data[1];
3953                 break;
3954
3955         case PW_TYPE_INTEGER:
3956                 memcpy(&vp->vp_integer, data, 4);
3957                 vp->vp_integer = ntohl(vp->vp_integer);
3958                 break;
3959
3960         case PW_TYPE_INTEGER64:
3961                 memcpy(&vp->vp_integer64, data, 8);
3962                 vp->vp_integer64 = ntohll(vp->vp_integer64);
3963                 break;
3964
3965         case PW_TYPE_DATE:
3966                 memcpy(&vp->vp_date, data, 4);
3967                 vp->vp_date = ntohl(vp->vp_date);
3968                 break;
3969
3970         case PW_TYPE_ETHERNET:
3971                 memcpy(vp->vp_ether, data, 6);
3972                 break;
3973
3974         case PW_TYPE_IPV4_ADDR:
3975                 memcpy(&vp->vp_ipaddr, data, 4);
3976                 break;
3977
3978         case PW_TYPE_IFID:
3979                 memcpy(vp->vp_ifid, data, 8);
3980                 break;
3981
3982         case PW_TYPE_IPV6_ADDR:
3983                 memcpy(&vp->vp_ipv6addr, data, 16);
3984                 break;
3985
3986         case PW_TYPE_IPV6_PREFIX:
3987                 /*
3988                  *      FIXME: double-check that
3989                  *      (vp->vp_octets[1] >> 3) matches vp->vp_length + 2
3990                  */
3991                 memcpy(vp->vp_ipv6prefix, data, vp->vp_length);
3992                 if (vp->vp_length < 18) {
3993                         memset(((uint8_t *)vp->vp_ipv6prefix) + vp->vp_length, 0,
3994                                18 - vp->vp_length);
3995                 }
3996                 break;
3997
3998         case PW_TYPE_IPV4_PREFIX:
3999                 /* FIXME: do the same double-check as for IPv6Prefix */
4000                 memcpy(vp->vp_ipv4prefix, data, vp->vp_length);
4001
4002                 /*
4003                  *      /32 means "keep all bits".  Otherwise, mask
4004                  *      them out.
4005                  */
4006                 if ((data[1] & 0x3f) > 32) {
4007                         uint32_t addr, mask;
4008
4009                         memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
4010                         mask = 1;
4011                         mask <<= (32 - (data[1] & 0x3f));
4012                         mask--;
4013                         mask = ~mask;
4014                         mask = htonl(mask);
4015                         addr &= mask;
4016                         memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
4017                 }
4018                 break;
4019
4020         case PW_TYPE_SIGNED:    /* overloaded with vp_integer */
4021                 memcpy(&vp->vp_integer, buffer, 4);
4022                 vp->vp_integer = ntohl(vp->vp_integer);
4023                 break;
4024
4025         default:
4026                 fr_pair_list_free(&vp);
4027                 fr_strerror_printf("Internal sanity check %d", __LINE__);
4028                 return -1;
4029         }
4030         vp->type = VT_DATA;
4031         *pvp = vp;
4032
4033         return attrlen;
4034 }
4035
4036
4037 /** Create a "normal" VALUE_PAIR from the given data
4038  *
4039  */
4040 ssize_t rad_attr2vp(TALLOC_CTX *ctx,
4041                     RADIUS_PACKET *packet, RADIUS_PACKET const *original,
4042                     char const *secret,
4043                     uint8_t const *data, size_t length,
4044                     VALUE_PAIR **pvp)
4045 {
4046         ssize_t rcode;
4047
4048         DICT_ATTR const *da;
4049
4050         if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
4051                 fr_strerror_printf("rad_attr2vp: Insufficient data");
4052                 return -1;
4053         }
4054
4055         da = dict_attrbyvalue(data[0], 0);
4056         if (!da) {
4057                 VP_TRACE("attr2vp: unknown attribute %u\n", data[0]);
4058                 da = dict_unknown_afrom_fields(ctx, data[0], 0);
4059         }
4060         if (!da) return -1;
4061
4062         /*
4063          *      Pass the entire thing to the decoding function
4064          */
4065         if (da->flags.concat) {
4066                 VP_TRACE("attr2vp: concat attribute\n");
4067                 return data2vp_concat(ctx, da, data, length, pvp);
4068         }
4069
4070         /*
4071          *      Note that we pass the entire length, not just the
4072          *      length of this attribute.  The Extended or WiMAX
4073          *      attributes may have the "continuation" bit set, and
4074          *      will thus be more than one attribute in length.
4075          */
4076         rcode = data2vp(ctx, packet, original, secret, da,
4077                         data + 2, data[1] - 2, length - 2, pvp);
4078         if (rcode < 0) return rcode;
4079
4080         return 2 + rcode;
4081 }
4082
4083 fr_thread_local_setup(uint8_t *, rad_vp2data_buff)
4084
4085 /** Converts vp_data to network byte order
4086  *
4087  * Provide a pointer to a buffer which contains the value of the VALUE_PAIR
4088  * in an architecture independent format.
4089  *
4090  * The pointer is only guaranteed to be valid between calls to rad_vp2data, and so long
4091  * as the source VALUE_PAIR is not freed.
4092  *
4093  * @param out where to write the pointer to the value.
4094  * @param vp to get the value from.
4095  * @return -1 on error, or the length of the value
4096  */
4097 ssize_t rad_vp2data(uint8_t const **out, VALUE_PAIR const *vp)
4098 {
4099         uint8_t         *buffer;
4100         uint32_t        lvalue;
4101         uint64_t        lvalue64;
4102
4103         *out = NULL;
4104
4105         buffer = fr_thread_local_init(rad_vp2data_buff, free);
4106         if (!buffer) {
4107                 int ret;
4108
4109                 buffer = malloc(sizeof(uint8_t) * sizeof(value_data_t));
4110                 if (!buffer) {
4111                         fr_strerror_printf("Failed allocating memory for rad_vp2data buffer");
4112                         return -1;
4113                 }
4114
4115                 ret = fr_thread_local_set(rad_vp2data_buff, buffer);
4116                 if (ret != 0) {
4117                         fr_strerror_printf("Failed setting up TLS for rad_vp2data buffer: %s", strerror(errno));
4118                         free(buffer);
4119                         return -1;
4120                 }
4121         }
4122
4123         VERIFY_VP(vp);
4124
4125         switch (vp->da->type) {
4126         case PW_TYPE_STRING:
4127         case PW_TYPE_OCTETS:
4128                 memcpy(out, &vp->data.ptr, sizeof(*out));
4129                 break;
4130
4131         /*
4132          *      All of these values are at the same location.
4133          */
4134         case PW_TYPE_IFID:
4135         case PW_TYPE_IPV4_ADDR:
4136         case PW_TYPE_IPV6_ADDR:
4137         case PW_TYPE_IPV6_PREFIX:
4138         case PW_TYPE_IPV4_PREFIX:
4139         case PW_TYPE_ABINARY:
4140         case PW_TYPE_ETHERNET:
4141         case PW_TYPE_COMBO_IP_ADDR:
4142         case PW_TYPE_COMBO_IP_PREFIX:
4143         {
4144                 void const *p = &vp->data;
4145                 memcpy(out, &p, sizeof(*out));
4146                 break;
4147         }
4148
4149         case PW_TYPE_BOOLEAN:
4150                 buffer[0] = vp->vp_byte & 0x01;
4151                 *out = buffer;
4152                 break;
4153
4154         case PW_TYPE_BYTE:
4155                 buffer[0] = vp->vp_byte & 0xff;
4156                 *out = buffer;
4157                 break;
4158
4159         case PW_TYPE_SHORT:
4160                 buffer[0] = (vp->vp_short >> 8) & 0xff;
4161                 buffer[1] = vp->vp_short & 0xff;
4162                 *out = buffer;
4163                 break;
4164
4165         case PW_TYPE_INTEGER:
4166                 lvalue = htonl(vp->vp_integer);
4167                 memcpy(buffer, &lvalue, sizeof(lvalue));
4168                 *out = buffer;
4169                 break;
4170
4171         case PW_TYPE_INTEGER64:
4172                 lvalue64 = htonll(vp->vp_integer64);
4173                 memcpy(buffer, &lvalue64, sizeof(lvalue64));
4174                 *out = buffer;
4175                 break;
4176
4177         case PW_TYPE_DATE:
4178                 lvalue = htonl(vp->vp_date);
4179                 memcpy(buffer, &lvalue, sizeof(lvalue));
4180                 *out = buffer;
4181                 break;
4182
4183         case PW_TYPE_SIGNED:
4184         {
4185                 int32_t slvalue = htonl(vp->vp_signed);
4186                 memcpy(buffer, &slvalue, sizeof(slvalue));
4187                 *out = buffer;
4188                 break;
4189         }
4190
4191         case PW_TYPE_INVALID:
4192         case PW_TYPE_EXTENDED:
4193         case PW_TYPE_LONG_EXTENDED:
4194         case PW_TYPE_EVS:
4195         case PW_TYPE_VSA:
4196         case PW_TYPE_TLV:
4197         case PW_TYPE_TIMEVAL:
4198         case PW_TYPE_MAX:
4199                 fr_strerror_printf("Cannot get data for VALUE_PAIR type %i", vp->da->type);
4200                 return -1;
4201
4202         /* Don't add default */
4203         }
4204
4205         return vp->vp_length;
4206 }
4207
4208 /** Calculate/check digest, and decode radius attributes
4209  *
4210  * @return -1 on decoding error, 0 on success
4211  */
4212 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
4213                char const *secret)
4214 {
4215         int                     packet_length;
4216         uint32_t                num_attributes;
4217         uint8_t                 *ptr;
4218         radius_packet_t         *hdr;
4219         VALUE_PAIR *head, **tail, *vp;
4220
4221         /*
4222          *      Extract attribute-value pairs
4223          */
4224         hdr = (radius_packet_t *)packet->data;
4225         ptr = hdr->data;
4226         packet_length = packet->data_len - RADIUS_HDR_LEN;
4227
4228         head = NULL;
4229         tail = &head;
4230         num_attributes = 0;
4231
4232         /*
4233          *      Loop over the attributes, decoding them into VPs.
4234          */
4235         while (packet_length > 0) {
4236                 ssize_t my_len;
4237
4238                 /*
4239                  *      This may return many VPs
4240                  */
4241                 my_len = rad_attr2vp(packet, packet, original, secret,
4242                                      ptr, packet_length, &vp);
4243                 if (my_len < 0) {
4244                         fr_pair_list_free(&head);
4245                         return -1;
4246                 }
4247
4248                 *tail = vp;
4249                 while (vp) {
4250                         num_attributes++;
4251                         tail = &(vp->next);
4252                         vp = vp->next;
4253                 }
4254
4255                 /*
4256                  *      VSA's may not have been counted properly in
4257                  *      rad_packet_ok() above, as it is hard to count
4258                  *      then without using the dictionary.  We
4259                  *      therefore enforce the limits here, too.
4260                  */
4261                 if ((fr_max_attributes > 0) &&
4262                     (num_attributes > fr_max_attributes)) {
4263                         char host_ipaddr[128];
4264
4265                         fr_pair_list_free(&head);
4266                         fr_strerror_printf("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
4267                                    inet_ntop(packet->src_ipaddr.af,
4268                                              &packet->src_ipaddr.ipaddr,
4269                                              host_ipaddr, sizeof(host_ipaddr)),
4270                                    num_attributes, fr_max_attributes);
4271                         return -1;
4272                 }
4273
4274                 ptr += my_len;
4275                 packet_length -= my_len;
4276         }
4277
4278         /*
4279          *      Merge information from the outside world into our
4280          *      random pool.
4281          */
4282         fr_rand_seed(packet->data, RADIUS_HDR_LEN);
4283
4284         /*
4285          *      There may be VP's already in the packet.  Don't
4286          *      destroy them.  Instead, add the decoded attributes to
4287          *      the tail of the list.
4288          */
4289         for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
4290                 /* nothing */
4291         }
4292         *tail = head;
4293
4294         return 0;
4295 }
4296
4297
4298 /** Encode password
4299  *
4300  * We assume that the passwd buffer passed is big enough.
4301  * RFC2138 says the password is max 128 chars, so the size
4302  * of the passwd buffer must be at least 129 characters.
4303  * Preferably it's just MAX_STRING_LEN.
4304  *
4305  * int *pwlen is updated to the new length of the encrypted
4306  * password - a multiple of 16 bytes.
4307  */
4308 int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
4309                  uint8_t const *vector)
4310 {
4311         FR_MD5_CTX context, old;
4312         uint8_t digest[AUTH_VECTOR_LEN];
4313         int     i, n, secretlen;
4314         int     len;
4315
4316         /*
4317          *      RFC maximum is 128 bytes.
4318          *
4319          *      If length is zero, pad it out with zeros.
4320          *
4321          *      If the length isn't aligned to 16 bytes,
4322          *      zero out the extra data.
4323          */
4324         len = *pwlen;
4325
4326         if (len > 128) len = 128;
4327
4328         if (len == 0) {
4329                 memset(passwd, 0, AUTH_PASS_LEN);
4330                 len = AUTH_PASS_LEN;
4331         } else if ((len % AUTH_PASS_LEN) != 0) {
4332                 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
4333                 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
4334         }
4335         *pwlen = len;
4336
4337         /*
4338          *      Use the secret to setup the decryption digest
4339          */
4340         secretlen = strlen(secret);
4341
4342         fr_md5_init(&context);
4343         fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4344         old = context;          /* save intermediate work */
4345
4346         /*
4347          *      Encrypt it in place.  Don't bother checking
4348          *      len, as we've ensured above that it's OK.
4349          */
4350         for (n = 0; n < len; n += AUTH_PASS_LEN) {
4351                 if (n == 0) {
4352                         fr_md5_update(&context, vector, AUTH_PASS_LEN);
4353                         fr_md5_final(digest, &context);
4354                 } else {
4355                         context = old;
4356                         fr_md5_update(&context,
4357                                      (uint8_t *) passwd + n - AUTH_PASS_LEN,
4358                                      AUTH_PASS_LEN);
4359                         fr_md5_final(digest, &context);
4360                 }
4361
4362                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4363                         passwd[i + n] ^= digest[i];
4364                 }
4365         }
4366
4367         return 0;
4368 }
4369
4370 /** Decode password
4371  *
4372  */
4373 int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
4374                  uint8_t const *vector)
4375 {
4376         FR_MD5_CTX context, old;
4377         uint8_t digest[AUTH_VECTOR_LEN];
4378         int     i;
4379         size_t  n, secretlen;
4380
4381         /*
4382          *      The RFC's say that the maximum is 128.
4383          *      The buffer we're putting it into above is 254, so
4384          *      we don't need to do any length checking.
4385          */
4386         if (pwlen > 128) pwlen = 128;
4387
4388         /*
4389          *      Catch idiots.
4390          */
4391         if (pwlen == 0) goto done;
4392
4393         /*
4394          *      Use the secret to setup the decryption digest
4395          */
4396         secretlen = strlen(secret);
4397
4398         fr_md5_init(&context);
4399         fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4400         old = context;          /* save intermediate work */
4401
4402         /*
4403          *      The inverse of the code above.
4404          */
4405         for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
4406                 if (n == 0) {
4407                         fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4408                         fr_md5_final(digest, &context);
4409
4410                         context = old;
4411                         if (pwlen > AUTH_PASS_LEN) {
4412                                 fr_md5_update(&context, (uint8_t *) passwd,
4413                                              AUTH_PASS_LEN);
4414                         }
4415                 } else {
4416                         fr_md5_final(digest, &context);
4417
4418                         context = old;
4419                         if (pwlen > (n + AUTH_PASS_LEN)) {
4420                                 fr_md5_update(&context, (uint8_t *) passwd + n,
4421                                              AUTH_PASS_LEN);
4422                         }
4423                 }
4424
4425                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4426                         passwd[i + n] ^= digest[i];
4427                 }
4428         }
4429
4430  done:
4431         passwd[pwlen] = '\0';
4432         return strlen(passwd);
4433 }
4434
4435
4436 /** Encode Tunnel-Password attributes when sending them out on the wire
4437  *
4438  * int *pwlen is updated to the new length of the encrypted
4439  * password - a multiple of 16 bytes.
4440  *
4441  * This is per RFC-2868 which adds a two char SALT to the initial intermediate
4442  * value MD5 hash.
4443  */
4444 ssize_t rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret, uint8_t const *vector)
4445 {
4446         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
4447         unsigned char   digest[AUTH_VECTOR_LEN];
4448         char*   salt;
4449         int     i, n, secretlen;
4450         unsigned len, n2;
4451
4452         len = *pwlen;
4453
4454         if (len > 127) len = 127;
4455
4456         /*
4457          *      Shift the password 3 positions right to place a salt and original
4458          *      length, tag will be added automatically on packet send.
4459          */
4460         for (n = len ; n >= 0 ; n--) passwd[n + 3] = passwd[n];
4461         salt = passwd;
4462         passwd += 2;
4463
4464         /*
4465          *      save original password length as first password character;
4466          */
4467         *passwd = len;
4468         len += 1;
4469
4470
4471         /*
4472          *      Generate salt.  The RFC's say:
4473          *
4474          *      The high bit of salt[0] must be set, each salt in a
4475          *      packet should be unique, and they should be random
4476          *
4477          *      So, we set the high bit, add in a counter, and then
4478          *      add in some CSPRNG data.  should be OK..
4479          */
4480         salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
4481                    (fr_rand() & 0x07));
4482         salt[1] = fr_rand();
4483
4484         /*
4485          *      Padd password to multiple of AUTH_PASS_LEN bytes.
4486          */
4487         n = len % AUTH_PASS_LEN;
4488         if (n) {
4489                 n = AUTH_PASS_LEN - n;
4490                 for (; n > 0; n--, len++)
4491                         passwd[len] = 0;
4492         }
4493         /* set new password length */
4494         *pwlen = len + 2;
4495
4496         /*
4497          *      Use the secret to setup the decryption digest
4498          */
4499         secretlen = strlen(secret);
4500         memcpy(buffer, secret, secretlen);
4501
4502         for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
4503                 if (!n2) {
4504                         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
4505                         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
4506                         fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
4507                 } else {
4508                         memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4509                         fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4510                 }
4511
4512                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4513                         passwd[i + n2] ^= digest[i];
4514                 }
4515         }
4516         passwd[n2] = 0;
4517         return 0;
4518 }
4519
4520 /** Decode Tunnel-Password encrypted attributes
4521  *
4522  * Defined in RFC-2868, this uses a two char SALT along with the
4523  * initial intermediate value, to differentiate it from the
4524  * above.
4525  */
4526 ssize_t rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret, uint8_t const *vector)
4527 {
4528         FR_MD5_CTX  context, old;
4529         uint8_t         digest[AUTH_VECTOR_LEN];
4530         int             secretlen;
4531         size_t          i, n, encrypted_len, reallen;
4532
4533         encrypted_len = *pwlen;
4534
4535         /*
4536          *      We need at least a salt.
4537          */
4538         if (encrypted_len < 2) {
4539                 fr_strerror_printf("tunnel password is too short");
4540                 return -1;
4541         }
4542
4543         /*
4544          *      There's a salt, but no password.  Or, there's a salt
4545          *      and a 'data_len' octet.  It's wrong, but at least we
4546          *      can figure out what it means: the password is empty.
4547          *
4548          *      Note that this means we ignore the 'data_len' field,
4549          *      if the attribute length tells us that there's no
4550          *      more data.  So the 'data_len' field may be wrong,
4551          *      but that's ok...
4552          */
4553         if (encrypted_len <= 3) {
4554                 passwd[0] = 0;
4555                 *pwlen = 0;
4556                 return 0;
4557         }
4558
4559         encrypted_len -= 2;             /* discount the salt */
4560
4561         /*
4562          *      Use the secret to setup the decryption digest
4563          */
4564         secretlen = strlen(secret);
4565
4566         fr_md5_init(&context);
4567         fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4568         old = context;          /* save intermediate work */
4569
4570         /*
4571          *      Set up the initial key:
4572          *
4573          *       b(1) = MD5(secret + vector + salt)
4574          */
4575         fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4576         fr_md5_update(&context, passwd, 2);
4577
4578         reallen = 0;
4579         for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
4580                 size_t base;
4581                 size_t block_len = AUTH_PASS_LEN;
4582
4583                 /*
4584                  *      Ensure we don't overflow the input on MD5
4585                  */
4586                 if ((n + 2 + AUTH_PASS_LEN) > *pwlen) {
4587                         block_len = *pwlen - n - 2;
4588                 }
4589
4590                 if (n == 0) {
4591                         base = 1;
4592
4593                         fr_md5_final(digest, &context);
4594
4595                         context = old;
4596
4597                         /*
4598                          *      A quick check: decrypt the first octet
4599                          *      of the password, which is the
4600                          *      'data_len' field.  Ensure it's sane.
4601                          */
4602                         reallen = passwd[2] ^ digest[0];
4603                         if (reallen > encrypted_len) {
4604                                 fr_strerror_printf("tunnel password is too long for the attribute");
4605                                 return -1;
4606                         }
4607
4608                         fr_md5_update(&context, passwd + 2, block_len);
4609
4610                 } else {
4611                         base = 0;
4612
4613                         fr_md5_final(digest, &context);
4614
4615                         context = old;
4616                         fr_md5_update(&context, passwd + n + 2, block_len);
4617                 }
4618
4619                 for (i = base; i < block_len; i++) {
4620                         passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4621                 }
4622         }
4623
4624         *pwlen = reallen;
4625         passwd[reallen] = 0;
4626
4627         return reallen;
4628 }
4629
4630 /** Encode a CHAP password
4631  *
4632  * @bug FIXME: might not work with Ascend because
4633  * we use vp->vp_length, and Ascend gear likes
4634  * to send an extra '\0' in the string!
4635  */
4636 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4637                     VALUE_PAIR *password)
4638 {
4639         int             i;
4640         uint8_t         *ptr;
4641         uint8_t         string[MAX_STRING_LEN * 2 + 1];
4642         VALUE_PAIR      *challenge;
4643
4644         /*
4645          *      Sanity check the input parameters
4646          */
4647         if ((packet == NULL) || (password == NULL)) {
4648                 return -1;
4649         }
4650
4651         /*
4652          *      Note that the password VP can be EITHER
4653          *      a User-Password attribute (from a check-item list),
4654          *      or a CHAP-Password attribute (the client asking
4655          *      the library to encode it).
4656          */
4657
4658         i = 0;
4659         ptr = string;
4660         *ptr++ = id;
4661
4662         i++;
4663         memcpy(ptr, password->vp_strvalue, password->vp_length);
4664         ptr += password->vp_length;
4665         i += password->vp_length;
4666
4667         /*
4668          *      Use Chap-Challenge pair if present,
4669          *      Request Authenticator otherwise.
4670          */
4671         challenge = fr_pair_find_by_num(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
4672         if (challenge) {
4673                 memcpy(ptr, challenge->vp_strvalue, challenge->vp_length);
4674                 i += challenge->vp_length;
4675         } else {
4676                 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4677                 i += AUTH_VECTOR_LEN;
4678         }
4679
4680         *output = id;
4681         fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4682
4683         return 0;
4684 }
4685
4686
4687 /** Seed the random number generator
4688  *
4689  * May be called any number of times.
4690  */
4691 void fr_rand_seed(void const *data, size_t size)
4692 {
4693         uint32_t hash;
4694
4695         /*
4696          *      Ensure that the pool is initialized.
4697          */
4698         if (!fr_rand_initialized) {
4699                 int fd;
4700
4701                 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4702
4703                 fd = open("/dev/urandom", O_RDONLY);
4704                 if (fd >= 0) {
4705                         size_t total;
4706                         ssize_t this;
4707
4708                         total = 0;
4709                         while (total < sizeof(fr_rand_pool.randrsl)) {
4710                                 this = read(fd, fr_rand_pool.randrsl,
4711                                             sizeof(fr_rand_pool.randrsl) - total);
4712                                 if ((this < 0) && (errno != EINTR)) break;
4713                                 if (this > 0) total += this;
4714                         }
4715                         close(fd);
4716                 } else {
4717                         fr_rand_pool.randrsl[0] = fd;
4718                         fr_rand_pool.randrsl[1] = time(NULL);
4719                         fr_rand_pool.randrsl[2] = errno;
4720                 }
4721
4722                 fr_randinit(&fr_rand_pool, 1);
4723                 fr_rand_pool.randcnt = 0;
4724                 fr_rand_initialized = 1;
4725         }
4726
4727         if (!data) return;
4728
4729         /*
4730          *      Hash the user data
4731          */
4732         hash = fr_rand();
4733         if (!hash) hash = fr_rand();
4734         hash = fr_hash_update(data, size, hash);
4735
4736         fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4737 }
4738
4739
4740 /** Return a 32-bit random number
4741  *
4742  */
4743 uint32_t fr_rand(void)
4744 {
4745         uint32_t num;
4746
4747         /*
4748          *      Ensure that the pool is initialized.
4749          */
4750         if (!fr_rand_initialized) {
4751                 fr_rand_seed(NULL, 0);
4752         }
4753
4754         num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4755         if (fr_rand_pool.randcnt >= 256) {
4756                 fr_rand_pool.randcnt = 0;
4757                 fr_isaac(&fr_rand_pool);
4758         }
4759
4760         return num;
4761 }
4762
4763
4764 /** Allocate a new RADIUS_PACKET
4765  *
4766  * @param ctx the context in which the packet is allocated. May be NULL if
4767  *      the packet is not associated with a REQUEST.
4768  * @param new_vector if true a new request authenticator will be generated.
4769  * @return a new RADIUS_PACKET or NULL on error.
4770  */
4771 RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, bool new_vector)
4772 {
4773         RADIUS_PACKET   *rp;
4774
4775         rp = talloc_zero(ctx, RADIUS_PACKET);
4776         if (!rp) {
4777                 fr_strerror_printf("out of memory");
4778                 return NULL;
4779         }
4780         rp->id = -1;
4781         rp->offset = -1;
4782
4783         if (new_vector) {
4784                 int i;
4785                 uint32_t hash, base;
4786
4787                 /*
4788                  *      Don't expose the actual contents of the random
4789                  *      pool.
4790                  */
4791                 base = fr_rand();
4792                 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4793                         hash = fr_rand() ^ base;
4794                         memcpy(rp->vector + i, &hash, sizeof(hash));
4795                 }
4796         }
4797         fr_rand();              /* stir the pool again */
4798
4799         return rp;
4800 }
4801
4802 /** Allocate a new RADIUS_PACKET response
4803  *
4804  * @param ctx the context in which the packet is allocated. May be NULL if
4805  *      the packet is not associated with a REQUEST.
4806  * @param packet The request packet.
4807  * @return a new RADIUS_PACKET or NULL on error.
4808  */
4809 RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
4810 {
4811         RADIUS_PACKET *reply;
4812
4813         if (!packet) return NULL;
4814
4815         reply = rad_alloc(ctx, false);
4816         if (!reply) return NULL;
4817
4818         /*
4819          *      Initialize the fields from the request.
4820          */
4821         reply->sockfd = packet->sockfd;
4822         reply->dst_ipaddr = packet->src_ipaddr;
4823         reply->src_ipaddr = packet->dst_ipaddr;
4824         reply->dst_port = packet->src_port;
4825         reply->src_port = packet->dst_port;
4826         reply->id = packet->id;
4827         reply->code = 0; /* UNKNOWN code */
4828         memcpy(reply->vector, packet->vector,
4829                sizeof(reply->vector));
4830         reply->vps = NULL;
4831         reply->data = NULL;
4832         reply->data_len = 0;
4833
4834 #ifdef WITH_TCP
4835         reply->proto = packet->proto;
4836 #endif
4837         return reply;
4838 }
4839
4840
4841 /** Free a RADIUS_PACKET
4842  *
4843  */
4844 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4845 {
4846         RADIUS_PACKET *radius_packet;
4847
4848         if (!radius_packet_ptr || !*radius_packet_ptr) return;
4849         radius_packet = *radius_packet_ptr;
4850
4851         VERIFY_PACKET(radius_packet);
4852
4853         fr_pair_list_free(&radius_packet->vps);
4854
4855         talloc_free(radius_packet);
4856         *radius_packet_ptr = NULL;
4857 }
4858
4859 /** Duplicate a RADIUS_PACKET
4860  *
4861  * @param ctx the context in which the packet is allocated. May be NULL if
4862  *      the packet is not associated with a REQUEST.
4863  * @param in The packet to copy
4864  * @return a new RADIUS_PACKET or NULL on error.
4865  */
4866 RADIUS_PACKET *rad_copy_packet(TALLOC_CTX *ctx, RADIUS_PACKET const *in)
4867 {
4868         RADIUS_PACKET *out;
4869
4870         out = rad_alloc(ctx, false);
4871         if (!out) return NULL;
4872
4873         /*
4874          *      Bootstrap by copying everything.
4875          */
4876         memcpy(out, in, sizeof(*out));
4877
4878         /*
4879          *      Then reset necessary fields
4880          */
4881         out->sockfd = -1;
4882
4883         out->data = NULL;
4884         out->data_len = 0;
4885
4886         out->vps = fr_pair_list_copy(out, in->vps);
4887         out->offset = 0;
4888
4889         return out;
4890 }