Merge tag 'release_3_0_12' into branch moonshot-fr-3.0.12-upgrade.
[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)
546 {
547         FR_MD5_CTX context;
548         int          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 < AUTH_VECTOR_LEN; 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 != 16) return 0;
1014                 make_secret(ptr, packet->vector, secret, data);
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->vendor && (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
2348         /*
2349          *      Check for packets smaller than the packet header.
2350          *
2351          *      RFC 2865, Section 3., subsection 'length' says:
2352          *
2353          *      "The minimum length is 20 ..."
2354          */
2355         if (packet->data_len < RADIUS_HDR_LEN) {
2356                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (received %zu < minimum %d)",
2357                            inet_ntop(packet->src_ipaddr.af,
2358                                      &packet->src_ipaddr.ipaddr,
2359                                      host_ipaddr, sizeof(host_ipaddr)),
2360                                      packet->data_len, RADIUS_HDR_LEN);
2361                 failure = DECODE_FAIL_MIN_LENGTH_PACKET;
2362                 goto finish;
2363         }
2364
2365
2366         /*
2367          *      Check for packets with mismatched size.
2368          *      i.e. We've received 128 bytes, and the packet header
2369          *      says it's 256 bytes long.
2370          */
2371         totallen = (packet->data[2] << 8) | packet->data[3];
2372         hdr = (radius_packet_t *)packet->data;
2373
2374         /*
2375          *      Code of 0 is not understood.
2376          *      Code of 16 or greate is not understood.
2377          */
2378         if ((hdr->code == 0) ||
2379             (hdr->code >= FR_MAX_PACKET_CODE)) {
2380                 FR_DEBUG_STRERROR_PRINTF("Bad RADIUS packet from host %s: unknown packet code %d",
2381                            inet_ntop(packet->src_ipaddr.af,
2382                                      &packet->src_ipaddr.ipaddr,
2383                                      host_ipaddr, sizeof(host_ipaddr)),
2384                            hdr->code);
2385                 failure = DECODE_FAIL_UNKNOWN_PACKET_CODE;
2386                 goto finish;
2387         }
2388
2389         /*
2390          *      Message-Authenticator is required in Status-Server
2391          *      packets, otherwise they can be trivially forged.
2392          */
2393         if (hdr->code == PW_CODE_STATUS_SERVER) require_ma = true;
2394
2395         /*
2396          *      It's also required if the caller asks for it.
2397          */
2398         if (flags) require_ma = true;
2399
2400         /*
2401          *      Repeat the length checks.  This time, instead of
2402          *      looking at the data we received, look at the value
2403          *      of the 'length' field inside of the packet.
2404          *
2405          *      Check for packets smaller than the packet header.
2406          *
2407          *      RFC 2865, Section 3., subsection 'length' says:
2408          *
2409          *      "The minimum length is 20 ..."
2410          */
2411         if (totallen < RADIUS_HDR_LEN) {
2412                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (length %zu < minimum %d)",
2413                            inet_ntop(packet->src_ipaddr.af,
2414                                      &packet->src_ipaddr.ipaddr,
2415                                      host_ipaddr, sizeof(host_ipaddr)),
2416                                      totallen, RADIUS_HDR_LEN);
2417                 failure = DECODE_FAIL_MIN_LENGTH_FIELD;
2418                 goto finish;
2419         }
2420
2421         /*
2422          *      And again, for the value of the 'length' field.
2423          *
2424          *      RFC 2865, Section 3., subsection 'length' says:
2425          *
2426          *      " ... and maximum length is 4096."
2427          *
2428          *      HOWEVER.  This requirement is for the network layer.
2429          *      If the code gets here, we assume that a well-formed
2430          *      packet is an OK packet.
2431          *
2432          *      We allow both the UDP data length, and the RADIUS
2433          *      "length" field to contain up to 64K of data.
2434          */
2435
2436         /*
2437          *      RFC 2865, Section 3., subsection 'length' says:
2438          *
2439          *      "If the packet is shorter than the Length field
2440          *      indicates, it MUST be silently discarded."
2441          *
2442          *      i.e. No response to the NAS.
2443          */
2444         if (packet->data_len < totallen) {
2445                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: received %zu octets, packet length says %zu",
2446                            inet_ntop(packet->src_ipaddr.af,
2447                                      &packet->src_ipaddr.ipaddr,
2448                                      host_ipaddr, sizeof(host_ipaddr)),
2449                                      packet->data_len, totallen);
2450                 failure = DECODE_FAIL_MIN_LENGTH_MISMATCH;
2451                 goto finish;
2452         }
2453
2454         /*
2455          *      RFC 2865, Section 3., subsection 'length' says:
2456          *
2457          *      "Octets outside the range of the Length field MUST be
2458          *      treated as padding and ignored on reception."
2459          */
2460         if (packet->data_len > totallen) {
2461                 /*
2462                  *      We're shortening the packet below, but just
2463                  *      to be paranoid, zero out the extra data.
2464                  */
2465                 memset(packet->data + totallen, 0, packet->data_len - totallen);
2466                 packet->data_len = totallen;
2467         }
2468
2469         /*
2470          *      Walk through the packet's attributes, ensuring that
2471          *      they add up EXACTLY to the size of the packet.
2472          *
2473          *      If they don't, then the attributes either under-fill
2474          *      or over-fill the packet.  Any parsing of the packet
2475          *      is impossible, and will result in unknown side effects.
2476          *
2477          *      This would ONLY happen with buggy RADIUS implementations,
2478          *      or with an intentional attack.  Either way, we do NOT want
2479          *      to be vulnerable to this problem.
2480          */
2481         attr = hdr->data;
2482         count = totallen - RADIUS_HDR_LEN;
2483         num_attributes = 0;
2484
2485         while (count > 0) {
2486                 /*
2487                  *      We need at least 2 bytes to check the
2488                  *      attribute header.
2489                  */
2490                 if (count < 2) {
2491                         FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute header overflows the packet",
2492                                    inet_ntop(packet->src_ipaddr.af,
2493                                              &packet->src_ipaddr.ipaddr,
2494                                              host_ipaddr, sizeof(host_ipaddr)));
2495                         failure = DECODE_FAIL_HEADER_OVERFLOW;
2496                         goto finish;
2497                 }
2498
2499                 /*
2500                  *      Attribute number zero is NOT defined.
2501                  */
2502                 if (attr[0] == 0) {
2503                         FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Invalid attribute 0",
2504                                    inet_ntop(packet->src_ipaddr.af,
2505                                              &packet->src_ipaddr.ipaddr,
2506                                              host_ipaddr, sizeof(host_ipaddr)));
2507                         failure = DECODE_FAIL_INVALID_ATTRIBUTE;
2508                         goto finish;
2509                 }
2510
2511                 /*
2512                  *      Attributes are at LEAST as long as the ID & length
2513                  *      fields.  Anything shorter is an invalid attribute.
2514                  */
2515                 if (attr[1] < 2) {
2516                         FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u too short",
2517                                    inet_ntop(packet->src_ipaddr.af,
2518                                              &packet->src_ipaddr.ipaddr,
2519                                              host_ipaddr, sizeof(host_ipaddr)),
2520                                    attr[0]);
2521                         failure = DECODE_FAIL_ATTRIBUTE_TOO_SHORT;
2522                         goto finish;
2523                 }
2524
2525                 /*
2526                  *      If there are fewer bytes in the packet than in the
2527                  *      attribute, it's a bad packet.
2528                  */
2529                 if (count < attr[1]) {
2530                         FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
2531                                    inet_ntop(packet->src_ipaddr.af,
2532                                              &packet->src_ipaddr.ipaddr,
2533                                              host_ipaddr, sizeof(host_ipaddr)),
2534                                            attr[0]);
2535                         failure = DECODE_FAIL_ATTRIBUTE_OVERFLOW;
2536                         goto finish;
2537                 }
2538
2539                 /*
2540                  *      Sanity check the attributes for length.
2541                  */
2542                 switch (attr[0]) {
2543                 default:        /* don't do anything by default */
2544                         break;
2545
2546                         /*
2547                          *      If there's an EAP-Message, we require
2548                          *      a Message-Authenticator.
2549                          */
2550                 case PW_EAP_MESSAGE:
2551                         require_ma = true;
2552                         break;
2553
2554                 case PW_MESSAGE_AUTHENTICATOR:
2555                         if (attr[1] != 2 + AUTH_VECTOR_LEN) {
2556                                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
2557                                            inet_ntop(packet->src_ipaddr.af,
2558                                                      &packet->src_ipaddr.ipaddr,
2559                                                      host_ipaddr, sizeof(host_ipaddr)),
2560                                            attr[1] - 2);
2561                                 failure = DECODE_FAIL_MA_INVALID_LENGTH;
2562                                 goto finish;
2563                         }
2564                         seen_ma = true;
2565                         break;
2566                 }
2567
2568                 /*
2569                  *      FIXME: Look up the base 255 attributes in the
2570                  *      dictionary, and switch over their type.  For
2571                  *      integer/date/ip, the attribute length SHOULD
2572                  *      be 6.
2573                  */
2574                 count -= attr[1];       /* grab the attribute length */
2575                 attr += attr[1];
2576                 num_attributes++;       /* seen one more attribute */
2577         }
2578
2579         /*
2580          *      If the attributes add up to a packet, it's allowed.
2581          *
2582          *      If not, we complain, and throw the packet away.
2583          */
2584         if (count != 0) {
2585                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
2586                            inet_ntop(packet->src_ipaddr.af,
2587                                      &packet->src_ipaddr.ipaddr,
2588                                      host_ipaddr, sizeof(host_ipaddr)));
2589                 failure = DECODE_FAIL_ATTRIBUTE_UNDERFLOW;
2590                 goto finish;
2591         }
2592
2593         /*
2594          *      If we're configured to look for a maximum number of
2595          *      attributes, and we've seen more than that maximum,
2596          *      then throw the packet away, as a possible DoS.
2597          */
2598         if ((fr_max_attributes > 0) &&
2599             (num_attributes > fr_max_attributes)) {
2600                 FR_DEBUG_STRERROR_PRINTF("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2601                            inet_ntop(packet->src_ipaddr.af,
2602                                      &packet->src_ipaddr.ipaddr,
2603                                      host_ipaddr, sizeof(host_ipaddr)),
2604                            num_attributes, fr_max_attributes);
2605                 failure = DECODE_FAIL_TOO_MANY_ATTRIBUTES;
2606                 goto finish;
2607         }
2608
2609         /*
2610          *      http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
2611          *
2612          *      A packet with an EAP-Message attribute MUST also have
2613          *      a Message-Authenticator attribute.
2614          *
2615          *      A Message-Authenticator all by itself is OK, though.
2616          *
2617          *      Similarly, Status-Server packets MUST contain
2618          *      Message-Authenticator attributes.
2619          */
2620         if (require_ma && !seen_ma) {
2621                 FR_DEBUG_STRERROR_PRINTF("Insecure packet from host %s:  Packet does not contain required Message-Authenticator attribute",
2622                            inet_ntop(packet->src_ipaddr.af,
2623                                      &packet->src_ipaddr.ipaddr,
2624                                      host_ipaddr, sizeof(host_ipaddr)));
2625                 failure = DECODE_FAIL_MA_MISSING;
2626                 goto finish;
2627         }
2628
2629         /*
2630          *      Fill RADIUS header fields
2631          */
2632         packet->code = hdr->code;
2633         packet->id = hdr->id;
2634         memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
2635
2636
2637         finish:
2638
2639         if (reason) {
2640                 *reason = failure;
2641         }
2642         return (failure == DECODE_FAIL_NONE);
2643 }
2644
2645
2646 /** Receive UDP client requests, and fill in the basics of a RADIUS_PACKET structure
2647  *
2648  */
2649 RADIUS_PACKET *rad_recv(TALLOC_CTX *ctx, int fd, int flags)
2650 {
2651         int sock_flags = 0;
2652         ssize_t data_len;
2653         RADIUS_PACKET           *packet;
2654
2655         /*
2656          *      Allocate the new request data structure
2657          */
2658         packet = rad_alloc(ctx, false);
2659         if (!packet) {
2660                 fr_strerror_printf("out of memory");
2661                 return NULL;
2662         }
2663
2664         if (flags & 0x02) {
2665                 sock_flags = MSG_PEEK;
2666                 flags &= ~0x02;
2667         }
2668
2669         data_len = rad_recvfrom(fd, packet, sock_flags,
2670                                 &packet->src_ipaddr, &packet->src_port,
2671                                 &packet->dst_ipaddr, &packet->dst_port);
2672
2673         /*
2674          *      Check for socket errors.
2675          */
2676         if (data_len < 0) {
2677                 FR_DEBUG_STRERROR_PRINTF("Error receiving packet: %s", fr_syserror(errno));
2678                 /* packet->data is NULL */
2679                 rad_free(&packet);
2680                 return NULL;
2681         }
2682         packet->data_len = data_len; /* unsigned vs signed */
2683
2684         /*
2685          *      If the packet is too big, then rad_recvfrom did NOT
2686          *      allocate memory.  Instead, it just discarded the
2687          *      packet.
2688          */
2689         if (packet->data_len > MAX_PACKET_LEN) {
2690                 FR_DEBUG_STRERROR_PRINTF("Discarding packet: Larger than RFC limitation of 4096 bytes");
2691                 /* packet->data is NULL */
2692                 rad_free(&packet);
2693                 return NULL;
2694         }
2695
2696         /*
2697          *      Read no data.  Continue.
2698          *      This check is AFTER the MAX_PACKET_LEN check above, because
2699          *      if the packet is larger than MAX_PACKET_LEN, we also have
2700          *      packet->data == NULL
2701          */
2702         if ((packet->data_len == 0) || !packet->data) {
2703                 FR_DEBUG_STRERROR_PRINTF("Empty packet: Socket is not ready");
2704                 rad_free(&packet);
2705                 return NULL;
2706         }
2707
2708         /*
2709          *      See if it's a well-formed RADIUS packet.
2710          */
2711         if (!rad_packet_ok(packet, flags, NULL)) {
2712                 rad_free(&packet);
2713                 return NULL;
2714         }
2715
2716         /*
2717          *      Remember which socket we read the packet from.
2718          */
2719         packet->sockfd = fd;
2720
2721         /*
2722          *      FIXME: Do even more filtering by only permitting
2723          *      certain IP's.  The problem is that we don't know
2724          *      how to do this properly for all possible clients...
2725          */
2726
2727         /*
2728          *      Explicitely set the VP list to empty.
2729          */
2730         packet->vps = NULL;
2731
2732 #ifndef NDEBUG
2733         if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2734 #endif
2735
2736         return packet;
2737 }
2738
2739
2740 /** Verify the Request/Response Authenticator (and Message-Authenticator if present) of a packet
2741  *
2742  */
2743 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original, char const *secret)
2744 {
2745         uint8_t         *ptr;
2746         int             length;
2747         int             attrlen;
2748         int             rcode;
2749         char            buffer[32];
2750
2751         if (!packet || !packet->data) return -1;
2752
2753         /*
2754          *      Before we allocate memory for the attributes, do more
2755          *      sanity checking.
2756          */
2757         ptr = packet->data + RADIUS_HDR_LEN;
2758         length = packet->data_len - RADIUS_HDR_LEN;
2759         while (length > 0) {
2760                 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2761                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2762
2763                 attrlen = ptr[1];
2764
2765                 switch (ptr[0]) {
2766                 default:        /* don't do anything. */
2767                         break;
2768
2769                         /*
2770                          *      Note that more than one Message-Authenticator
2771                          *      attribute is invalid.
2772                          */
2773                 case PW_MESSAGE_AUTHENTICATOR:
2774                         memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2775                         memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2776
2777                         switch (packet->code) {
2778                         default:
2779                                 break;
2780
2781                         case PW_CODE_ACCOUNTING_RESPONSE:
2782                                 if (original &&
2783                                     (original->code == PW_CODE_STATUS_SERVER)) {
2784                                         goto do_ack;
2785                                 }
2786
2787                         case PW_CODE_ACCOUNTING_REQUEST:
2788                         case PW_CODE_DISCONNECT_REQUEST:
2789                         case PW_CODE_COA_REQUEST:
2790                                 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2791                                 break;
2792
2793                         do_ack:
2794                         case PW_CODE_ACCESS_ACCEPT:
2795                         case PW_CODE_ACCESS_REJECT:
2796                         case PW_CODE_ACCESS_CHALLENGE:
2797                         case PW_CODE_DISCONNECT_ACK:
2798                         case PW_CODE_DISCONNECT_NAK:
2799                         case PW_CODE_COA_ACK:
2800                         case PW_CODE_COA_NAK:
2801                                 if (!original) {
2802                                         fr_strerror_printf("Cannot validate Message-Authenticator in response "
2803                                                            "packet without a request packet");
2804                                         return -1;
2805                                 }
2806                                 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2807                                 break;
2808                         }
2809
2810                         fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
2811                                     (uint8_t const *) secret, strlen(secret));
2812                         if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2813                                    sizeof(calc_auth_vector)) != 0) {
2814                                 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator!  "
2815                                                    "(Shared secret is incorrect.)",
2816                                                    inet_ntop(packet->src_ipaddr.af,
2817                                                              &packet->src_ipaddr.ipaddr,
2818                                                              buffer, sizeof(buffer)));
2819                                 /* Silently drop packet, according to RFC 3579 */
2820                                 return -1;
2821                         } /* else the message authenticator was good */
2822
2823                         /*
2824                          *      Reinitialize Authenticators.
2825                          */
2826                         memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2827                         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2828                         break;
2829                 } /* switch over the attributes */
2830
2831                 ptr += attrlen;
2832                 length -= attrlen;
2833         } /* loop over the packet, sanity checking the attributes */
2834
2835         /*
2836          *      It looks like a RADIUS packet, but we don't know what it is
2837          *      so can't validate the authenticators.
2838          */
2839         if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2840                 fr_strerror_printf("Received Unknown packet code %d "
2841                                    "from client %s port %d: Cannot validate Request/Response Authenticator.",
2842                                    packet->code,
2843                                    inet_ntop(packet->src_ipaddr.af,
2844                                              &packet->src_ipaddr.ipaddr,
2845                                              buffer, sizeof(buffer)),
2846                                    packet->src_port);
2847                 return -1;
2848         }
2849
2850         /*
2851          *      Calculate and/or verify Request or Response Authenticator.
2852          */
2853         switch (packet->code) {
2854         case PW_CODE_ACCESS_REQUEST:
2855         case PW_CODE_STATUS_SERVER:
2856                 /*
2857                  *      The authentication vector is random
2858                  *      nonsense, invented by the client.
2859                  */
2860                 break;
2861
2862         case PW_CODE_COA_REQUEST:
2863         case PW_CODE_DISCONNECT_REQUEST:
2864         case PW_CODE_ACCOUNTING_REQUEST:
2865                 if (calc_acctdigest(packet, secret) > 1) {
2866                         fr_strerror_printf("Received %s packet "
2867                                            "from client %s with invalid Request Authenticator!  "
2868                                            "(Shared secret is incorrect.)",
2869                                            fr_packet_codes[packet->code],
2870                                            inet_ntop(packet->src_ipaddr.af,
2871                                                      &packet->src_ipaddr.ipaddr,
2872                                                      buffer, sizeof(buffer)));
2873                         return -1;
2874                 }
2875                 break;
2876
2877                 /* Verify the reply digest */
2878         case PW_CODE_ACCESS_ACCEPT:
2879         case PW_CODE_ACCESS_REJECT:
2880         case PW_CODE_ACCESS_CHALLENGE:
2881         case PW_CODE_ACCOUNTING_RESPONSE:
2882         case PW_CODE_DISCONNECT_ACK:
2883         case PW_CODE_DISCONNECT_NAK:
2884         case PW_CODE_COA_ACK:
2885         case PW_CODE_COA_NAK:
2886                 rcode = calc_replydigest(packet, original, secret);
2887                 if (rcode > 1) {
2888                         fr_strerror_printf("Received %s packet "
2889                                            "from home server %s port %d with invalid Response Authenticator!  "
2890                                            "(Shared secret is incorrect.)",
2891                                            fr_packet_codes[packet->code],
2892                                            inet_ntop(packet->src_ipaddr.af,
2893                                                      &packet->src_ipaddr.ipaddr,
2894                                                      buffer, sizeof(buffer)),
2895                                            packet->src_port);
2896                         return -1;
2897                 }
2898                 break;
2899
2900         default:
2901                 fr_strerror_printf("Received Unknown packet code %d "
2902                                    "from client %s port %d: Cannot validate Request/Response Authenticator",
2903                                    packet->code,
2904                                    inet_ntop(packet->src_ipaddr.af,
2905                                              &packet->src_ipaddr.ipaddr,
2906                                              buffer, sizeof(buffer)),
2907                                    packet->src_port);
2908                 return -1;
2909         }
2910
2911         return 0;
2912 }
2913
2914
2915 /** Convert a "concatenated" attribute to one long VP
2916  *
2917  */
2918 static ssize_t data2vp_concat(TALLOC_CTX *ctx,
2919                               DICT_ATTR const *da, uint8_t const *start,
2920                               size_t const packetlen, VALUE_PAIR **pvp)
2921 {
2922         size_t total;
2923         uint8_t attr;
2924         uint8_t const *ptr = start;
2925         uint8_t const *end = start + packetlen;
2926         uint8_t *p;
2927         VALUE_PAIR *vp;
2928
2929         total = 0;
2930         attr = ptr[0];
2931
2932         /*
2933          *      The packet has already been sanity checked, so we
2934          *      don't care about walking off of the end of it.
2935          */
2936         while (ptr < end) {
2937                 total += ptr[1] - 2;
2938
2939                 ptr += ptr[1];
2940
2941                 /*
2942                  *      Attributes MUST be consecutive.
2943                  */
2944                 if (ptr[0] != attr) break;
2945         }
2946
2947         vp = fr_pair_afrom_da(ctx, da);
2948         if (!vp) return -1;
2949
2950         vp->vp_length = total;
2951         vp->vp_octets = p = talloc_array(vp, uint8_t, vp->vp_length);
2952         if (!p) {
2953                 fr_pair_list_free(&vp);
2954                 return -1;
2955         }
2956
2957         total = 0;
2958         ptr = start;
2959         while (total < vp->vp_length) {
2960                 memcpy(p, ptr + 2, ptr[1] - 2);
2961                 p += ptr[1] - 2;
2962                 total += ptr[1] - 2;
2963                 ptr += ptr[1];
2964         }
2965
2966         *pvp = vp;
2967         return ptr - start;
2968 }
2969
2970
2971 /** Convert TLVs to one or more VPs
2972  *
2973  */
2974 ssize_t rad_data2vp_tlvs(TALLOC_CTX *ctx,
2975                             RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2976                             char const *secret, DICT_ATTR const *da,
2977                             uint8_t const *start, size_t length,
2978                             VALUE_PAIR **pvp)
2979 {
2980         uint8_t const *data = start;
2981         DICT_ATTR const *child;
2982         VALUE_PAIR *head, **tail;
2983
2984         if (length < 3) return -1; /* type, length, value */
2985
2986         VP_HEXDUMP("tlvs", data, length);
2987
2988         if (rad_tlv_ok(data, length, 1, 1) < 0) return -1;
2989
2990         head = NULL;
2991         tail = &head;
2992
2993         while (data < (start + length)) {
2994                 ssize_t tlv_len;
2995
2996                 child = dict_attrbyparent(da, data[0], da->vendor);
2997                 if (!child) {
2998                         unsigned int my_attr, my_vendor;
2999
3000                         VP_TRACE("Failed to find child %u of TLV %s\n",
3001                                  data[0], da->name);
3002
3003                         /*
3004                          *      Get child attr/vendor so that
3005                          *      we can call unknown attr.
3006                          */
3007                         my_attr = data[0];
3008                         my_vendor = da->vendor;
3009
3010                         if (!dict_attr_child(da, &my_attr, &my_vendor)) {
3011                                 fr_pair_list_free(&head);
3012                                 return -1;
3013                         }
3014
3015                         child = dict_unknown_afrom_fields(ctx, my_attr, my_vendor);
3016                         if (!child) {
3017                                 fr_pair_list_free(&head);
3018                                 return -1;
3019                         }
3020                 }
3021
3022                 tlv_len = data2vp(ctx, packet, original, secret, child,
3023                                   data + 2, data[1] - 2, data[1] - 2, tail);
3024                 if (tlv_len < 0) {
3025                         fr_pair_list_free(&head);
3026                         return -1;
3027                 }
3028                 if (*tail) tail = &((*tail)->next);
3029                 data += data[1];
3030         }
3031
3032         *pvp = head;
3033         return length;
3034 }
3035
3036 /** Convert a top-level VSA to a VP.
3037  *
3038  * "length" can be LONGER than just this sub-vsa.
3039  */
3040 static ssize_t data2vp_vsa(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3041                            RADIUS_PACKET const *original,
3042                            char const *secret, DICT_VENDOR *dv,
3043                            uint8_t const *data, size_t length,
3044                            VALUE_PAIR **pvp)
3045 {
3046         unsigned int attribute;
3047         ssize_t attrlen, my_len;
3048         DICT_ATTR const *da;
3049
3050         VP_TRACE("data2vp_vsa: length %u\n", (unsigned int) length);
3051
3052 #ifndef NDEBUG
3053         if (length <= (dv->type + dv->length)) {
3054                 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
3055                 return -1;
3056         }
3057 #endif
3058
3059         switch (dv->type) {
3060         case 4:
3061                 /* data[0] must be zero */
3062                 attribute = data[1] << 16;
3063                 attribute |= data[2] << 8;
3064                 attribute |= data[3];
3065                 break;
3066
3067         case 2:
3068                 attribute = data[0] << 8;
3069                 attribute |= data[1];
3070                 break;
3071
3072         case 1:
3073                 attribute = data[0];
3074                 break;
3075
3076         default:
3077                 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3078                 return -1;
3079         }
3080
3081         switch (dv->length) {
3082         case 2:
3083                 /* data[dv->type] must be zero, from rad_tlv_ok() */
3084                 attrlen = data[dv->type + 1];
3085                 break;
3086
3087         case 1:
3088                 attrlen = data[dv->type];
3089                 break;
3090
3091         case 0:
3092                 attrlen = length;
3093                 break;
3094
3095         default:
3096                 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3097                 return -1;
3098         }
3099
3100         /*
3101          *      See if the VSA is known.
3102          */
3103         da = dict_attrbyvalue(attribute, dv->vendorpec);
3104         if (!da) da = dict_unknown_afrom_fields(ctx, attribute, dv->vendorpec);
3105         if (!da) return -1;
3106
3107         my_len = data2vp(ctx, packet, original, secret, da,
3108                          data + dv->type + dv->length,
3109                          attrlen - (dv->type + dv->length),
3110                          attrlen - (dv->type + dv->length),
3111                          pvp);
3112         if (my_len < 0) return my_len;
3113
3114         return attrlen;
3115 }
3116
3117
3118 /** Convert a fragmented extended attr to a VP
3119  *
3120  * Format is:
3121  *
3122  * attr
3123  * length
3124  * extended-attr
3125  * flag
3126  * data...
3127  *
3128  * But for the first fragment, we get passed a pointer to the "extended-attr"
3129  */
3130 static ssize_t data2vp_extended(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3131                                 RADIUS_PACKET const *original,
3132                                 char const *secret, DICT_ATTR const *da,
3133                                 uint8_t const *data,
3134                                 size_t attrlen, size_t packetlen,
3135                                 VALUE_PAIR **pvp)
3136 {
3137         ssize_t rcode;
3138         size_t fraglen;
3139         uint8_t *head, *tail;
3140         uint8_t const *frag, *end;
3141         uint8_t const *attr;
3142         int fragments;
3143         bool last_frag;
3144
3145         if (attrlen < 3) return -1;
3146
3147         /*
3148          *      Calculate the length of all of the fragments.  For
3149          *      now, they MUST be contiguous in the packet, and they
3150          *      MUST be all of the same TYPE and EXTENDED-TYPE
3151          */
3152         attr = data - 2;
3153         fraglen = attrlen - 2;
3154         frag = data + attrlen;
3155         end = data + packetlen;
3156         fragments = 1;
3157         last_frag = false;
3158
3159         while (frag < end) {
3160                 if (last_frag ||
3161                     (frag[0] != attr[0]) ||
3162                     (frag[1] < 4) ||                   /* too short for long-extended */
3163                     (frag[2] != attr[2]) ||
3164                     ((frag + frag[1]) > end)) {         /* overflow */
3165                         end = frag;
3166                         break;
3167                 }
3168
3169                 last_frag = ((frag[3] & 0x80) == 0);
3170
3171                 fraglen += frag[1] - 4;
3172                 frag += frag[1];
3173                 fragments++;
3174         }
3175
3176         head = tail = malloc(fraglen);
3177         if (!head) return -1;
3178
3179         VP_TRACE("Fragments %d, total length %d\n", fragments, (int) fraglen);
3180
3181         /*
3182          *      And again, but faster and looser.
3183          *
3184          *      We copy the first fragment, followed by the rest of
3185          *      the fragments.
3186          */
3187         frag = attr;
3188
3189         while (fragments >  0) {
3190                 memcpy(tail, frag + 4, frag[1] - 4);
3191                 tail += frag[1] - 4;
3192                 frag += frag[1];
3193                 fragments--;
3194         }
3195
3196         VP_HEXDUMP("long-extended fragments", head, fraglen);
3197
3198         rcode = data2vp(ctx, packet, original, secret, da,
3199                         head, fraglen, fraglen, pvp);
3200         free(head);
3201         if (rcode < 0) return rcode;
3202
3203         return end - data;
3204 }
3205
3206 /** Convert a Vendor-Specific WIMAX to vps
3207  *
3208  * @note Called ONLY for Vendor-Specific
3209  */
3210 static ssize_t data2vp_wimax(TALLOC_CTX *ctx,
3211                              RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3212                              char const *secret, uint32_t vendor,
3213                              uint8_t const *data,
3214                              size_t attrlen, size_t packetlen,
3215                              VALUE_PAIR **pvp)
3216 {
3217         ssize_t rcode;
3218         size_t fraglen;
3219         bool last_frag;
3220         uint8_t *head, *tail;
3221         uint8_t const *frag, *end;
3222         DICT_ATTR const *child;
3223
3224         if (attrlen < 8) return -1;
3225
3226         if (((size_t) (data[5] + 4)) != attrlen) return -1;
3227
3228         child = dict_attrbyvalue(data[4], vendor);
3229         if (!child) return -1;
3230
3231         if ((data[6] & 0x80) == 0) {
3232                 rcode = data2vp(ctx, packet, original, secret, child,
3233                                 data + 7, data[5] - 3, data[5] - 3,
3234                                 pvp);
3235                 if (rcode < 0) return -1;
3236                 return 7 + rcode;
3237         }
3238
3239         /*
3240          *      Calculate the length of all of the fragments.  For
3241          *      now, they MUST be contiguous in the packet, and they
3242          *      MUST be all of the same VSA, WiMAX, and WiMAX-attr.
3243          *
3244          *      The first fragment doesn't have a RADIUS attribute
3245          *      header, so it needs to be treated a little special.
3246          */
3247         fraglen = data[5] - 3;
3248         frag = data + attrlen;
3249         end = data + packetlen;
3250         last_frag = false;
3251
3252         while (frag < end) {
3253                 if (last_frag ||
3254                     (frag[0] != PW_VENDOR_SPECIFIC) ||
3255                     (frag[1] < 9) ||                   /* too short for wimax */
3256                     ((frag + frag[1]) > end) ||         /* overflow */
3257                     (memcmp(frag + 2, data, 4) != 0) || /* not wimax */
3258                     (frag[6] != data[4]) || /* not the same wimax attr */
3259                     ((frag[7] + 6) != frag[1])) { /* doesn't fill the attr */
3260                         end = frag;
3261                         break;
3262                 }
3263
3264                 last_frag = ((frag[8] & 0x80) == 0);
3265
3266                 fraglen += frag[7] - 3;
3267                 frag += frag[1];
3268         }
3269
3270         head = tail = malloc(fraglen);
3271         if (!head) return -1;
3272
3273         /*
3274          *      And again, but faster and looser.
3275          *
3276          *      We copy the first fragment, followed by the rest of
3277          *      the fragments.
3278          */
3279         frag = data;
3280
3281         memcpy(tail, frag + 4 + 3, frag[4 + 1] - 3);
3282         tail += frag[4 + 1] - 3;
3283         frag += attrlen;        /* should be frag[1] - 7 */
3284
3285         /*
3286          *      frag now points to RADIUS attributes
3287          */
3288         do {
3289                 memcpy(tail, frag + 2 + 4 + 3, frag[2 + 4 + 1] - 3);
3290                 tail += frag[2 + 4 + 1] - 3;
3291                 frag += frag[1];
3292         } while (frag < end);
3293
3294         VP_HEXDUMP("wimax fragments", head, fraglen);
3295
3296         rcode = data2vp(ctx, packet, original, secret, child,
3297                         head, fraglen, fraglen, pvp);
3298         free(head);
3299         if (rcode < 0) return rcode;
3300
3301         return end - data;
3302 }
3303
3304
3305 /** Convert a top-level VSA to one or more VPs
3306  *
3307  */
3308 static ssize_t data2vp_vsas(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3309                             RADIUS_PACKET const *original,
3310                             char const *secret, uint8_t const *data,
3311                             size_t attrlen, size_t packetlen,
3312                             VALUE_PAIR **pvp)
3313 {
3314         size_t total;
3315         ssize_t rcode;
3316         uint32_t vendor;
3317         DICT_VENDOR *dv;
3318         VALUE_PAIR *head, **tail;
3319         DICT_VENDOR my_dv;
3320
3321         if (attrlen > packetlen) return -1;
3322         if (attrlen < 5) return -1; /* vid, value */
3323         if (data[0] != 0) return -1; /* we require 24-bit VIDs */
3324
3325         VP_TRACE("data2vp_vsas\n");
3326
3327         memcpy(&vendor, data, 4);
3328         vendor = ntohl(vendor);
3329         dv = dict_vendorbyvalue(vendor);
3330         if (!dv) {
3331                 /*
3332                  *      RFC format is 1 octet type, 1 octet length
3333                  */
3334                 if (rad_tlv_ok(data + 4, attrlen - 4, 1, 1) < 0) {
3335                         VP_TRACE("data2vp_vsas: unknown tlvs not OK: %s\n", fr_strerror());
3336                         return -1;
3337                 }
3338
3339                 /*
3340                  *      It's a known unknown.
3341                  */
3342                 memset(&my_dv, 0, sizeof(my_dv));
3343                 dv = &my_dv;
3344
3345                 /*
3346                  *      Fill in the fields.  Note that the name is empty!
3347                  */
3348                 dv->vendorpec = vendor;
3349                 dv->type = 1;
3350                 dv->length = 1;
3351
3352                 goto create_attrs;
3353         }
3354
3355         /*
3356          *      WiMAX craziness
3357          */
3358         if ((vendor == VENDORPEC_WIMAX) && dv->flags) {
3359                 rcode = data2vp_wimax(ctx, packet, original, secret, vendor,
3360                                       data, attrlen, packetlen, pvp);
3361                 return rcode;
3362         }
3363
3364         /*
3365          *      VSAs should normally be in TLV format.
3366          */
3367         if (rad_tlv_ok(data + 4, attrlen - 4,
3368                        dv->type, dv->length) < 0) {
3369                 VP_TRACE("data2vp_vsas: tlvs not OK: %s\n", fr_strerror());
3370                 return -1;
3371         }
3372
3373         /*
3374          *      There may be more than one VSA in the
3375          *      Vendor-Specific.  If so, loop over them all.
3376          */
3377 create_attrs:
3378         data += 4;
3379         attrlen -= 4;
3380         packetlen -= 4;
3381         total = 4;
3382         head = NULL;
3383         tail = &head;
3384
3385         while (attrlen > 0) {
3386                 ssize_t vsa_len;
3387
3388                 vsa_len = data2vp_vsa(ctx, packet, original, secret, dv,
3389                                       data, attrlen, tail);
3390                 if (vsa_len < 0) {
3391                         fr_pair_list_free(&head);
3392                         fr_strerror_printf("Internal sanity check %d", __LINE__);
3393                         return -1;
3394                 }
3395
3396                 /*
3397                  *      Vendors can send zero-length VSAs.
3398                  */
3399                 if (*tail) tail = &((*tail)->next);
3400
3401                 data += vsa_len;
3402                 attrlen -= vsa_len;
3403                 packetlen -= vsa_len;
3404                 total += vsa_len;
3405         }
3406
3407         *pvp = head;
3408         return total;
3409 }
3410
3411 /** Create any kind of VP from the attribute contents
3412  *
3413  * "length" is AT LEAST the length of this attribute, as we
3414  * expect the caller to have verified the data with
3415  * rad_packet_ok().  "length" may be up to the length of the
3416  * packet.
3417  *
3418  * @return -1 on error, or "length".
3419  */
3420 ssize_t data2vp(TALLOC_CTX *ctx,
3421                 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3422                 char const *secret,
3423                 DICT_ATTR const *da, uint8_t const *start,
3424                 size_t const attrlen, size_t const packetlen,
3425                 VALUE_PAIR **pvp)
3426 {
3427         int8_t tag = TAG_NONE;
3428         size_t datalen;
3429         ssize_t rcode;
3430         uint32_t vendor;
3431         DICT_ATTR const *child;
3432         VALUE_PAIR *vp;
3433         uint8_t const *data = start;
3434         char *p;
3435         uint8_t buffer[256];
3436
3437         /*
3438          *      FIXME: Attrlen can be larger than 253 for extended attrs!
3439          */
3440         if (!da || (attrlen > packetlen) ||
3441             ((attrlen > 253) && (attrlen != packetlen)) ||
3442             (attrlen > 128*1024)) {
3443                 fr_strerror_printf("data2vp: invalid arguments");
3444                 return -1;
3445         }
3446
3447         VP_HEXDUMP("data2vp", start, attrlen);
3448
3449         VP_TRACE("parent %s len %zu ... %zu\n", da->name, attrlen, packetlen);
3450
3451         datalen = attrlen;
3452
3453         /*
3454          *      Hacks for CUI.  The WiMAX spec says that it can be
3455          *      zero length, even though this is forbidden by the
3456          *      RADIUS specs.  So... we make a special case for it.
3457          */
3458         if (attrlen == 0) {
3459                 if (!((da->vendor == 0) &&
3460                       (da->attr == PW_CHARGEABLE_USER_IDENTITY))) {
3461                         *pvp = NULL;
3462                         return 0;
3463                 }
3464
3465 #ifndef NDEBUG
3466                 /*
3467                  *      Hacks for Coverity.  Editing the dictionary
3468                  *      will break assumptions about CUI.  We know
3469                  *      this, but Coverity doesn't.
3470                  */
3471                 if (da->type != PW_TYPE_OCTETS) return -1;
3472 #endif
3473
3474                 data = NULL;
3475                 datalen = 0;
3476                 goto alloc_cui; /* skip everything */
3477         }
3478
3479         /*
3480          *      Hacks for tags.  If the attribute is capable of
3481          *      encoding a tag, and there's room for the tag, and
3482          *      there is a tag, or it's encrypted with Tunnel-Password,
3483          *      then decode the tag.
3484          */
3485         if (da->flags.has_tag && (datalen > 1) &&
3486             ((data[0] < 0x20) ||
3487              (da->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
3488                 /*
3489                  *      Only "short" attributes can be encrypted.
3490                  */
3491                 if (datalen >= sizeof(buffer)) return -1;
3492
3493                 if (da->type == PW_TYPE_STRING) {
3494                         memcpy(buffer, data + 1, datalen - 1);
3495                         tag = data[0];
3496                         datalen -= 1;
3497
3498                 } else if (da->type == PW_TYPE_INTEGER) {
3499                         memcpy(buffer, data, attrlen);
3500                         tag = buffer[0];
3501                         buffer[0] = 0;
3502
3503                 } else {
3504                         return -1; /* only string and integer can have tags */
3505                 }
3506
3507                 data = buffer;
3508         }
3509
3510         /*
3511          *      Decrypt the attribute.
3512          */
3513         if (secret && packet && (da->flags.encrypt != FLAG_ENCRYPT_NONE)) {
3514                 VP_TRACE("data2vp: decrypting type %u\n", da->flags.encrypt);
3515                 /*
3516                  *      Encrypted attributes can only exist for the
3517                  *      old-style format.  Extended attributes CANNOT
3518                  *      be encrypted.
3519                  */
3520                 if (attrlen > 253) {
3521                         return -1;
3522                 }
3523
3524                 if (data == start) {
3525                         memcpy(buffer, data, attrlen);
3526                 }
3527                 data = buffer;
3528
3529                 switch (da->flags.encrypt) { /* can't be tagged */
3530                 /*
3531                  *  User-Password
3532                  */
3533                 case FLAG_ENCRYPT_USER_PASSWORD:
3534                         if (original) {
3535                                 rad_pwdecode((char *) buffer,
3536                                              attrlen, secret,
3537                                              original->vector);
3538                         } else {
3539                                 rad_pwdecode((char *) buffer,
3540                                              attrlen, secret,
3541                                              packet->vector);
3542                         }
3543                         buffer[253] = '\0';
3544
3545                         /*
3546                          *      MS-CHAP-MPPE-Keys are 24 octets, and
3547                          *      encrypted.  Since it's binary, we can't
3548                          *      look for trailing zeros.
3549                          */
3550                         if (da->flags.length) {
3551                                 if (datalen > da->flags.length) {
3552                                         datalen = da->flags.length;
3553                                 } /* else leave datalen alone */
3554                         } else {
3555                                 /*
3556                                  *      Take off trailing zeros from the END.
3557                                  *      This allows passwords to have zeros in
3558                                  *      the middle of a field.
3559                                  *
3560                                  *      However, if the password has a zero at
3561                                  *      the end, it will get mashed by this
3562                                  *      code.  There's really no way around
3563                                  *      that.
3564                                  */
3565                                 while ((datalen > 0) && (buffer[datalen - 1] == '\0')) datalen--;
3566                         }
3567                         break;
3568
3569                 /*
3570                  *      Tunnel-Password's may go ONLY in response
3571                  *      packets.  They can have a tag, so datalen is
3572                  *      not the same as attrlen.
3573                  */
3574                 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
3575                         if (rad_tunnel_pwdecode(buffer, &datalen, secret,
3576                                                 original ? original->vector : nullvector) < 0) {
3577                                 goto raw;
3578                         }
3579                         break;
3580
3581                 /*
3582                  *  Ascend-Send-Secret
3583                  *  Ascend-Receive-Secret
3584                  */
3585                 case FLAG_ENCRYPT_ASCEND_SECRET:
3586                         if (!original) {
3587                                 goto raw;
3588                         } else {
3589                                 uint8_t my_digest[AUTH_VECTOR_LEN];
3590                                 make_secret(my_digest,
3591                                             original->vector,
3592                                             secret, data);
3593                                 memcpy(buffer, my_digest,
3594                                        AUTH_VECTOR_LEN );
3595                                 buffer[AUTH_VECTOR_LEN] = '\0';
3596                                 datalen = strlen((char *) buffer);
3597                         }
3598                         break;
3599
3600                 default:
3601                         break;
3602                 } /* switch over encryption flags */
3603         }
3604
3605         /*
3606          *      Double-check the length after decrypting the
3607          *      attribute.
3608          */
3609         VP_TRACE("data2vp: type %u\n", da->type);
3610         switch (da->type) {
3611         case PW_TYPE_STRING:
3612         case PW_TYPE_OCTETS:
3613                 break;
3614
3615         case PW_TYPE_ABINARY:
3616                 if (datalen > sizeof(vp->vp_filter)) goto raw;
3617                 break;
3618
3619         case PW_TYPE_INTEGER:
3620         case PW_TYPE_IPV4_ADDR:
3621         case PW_TYPE_DATE:
3622         case PW_TYPE_SIGNED:
3623                 if (datalen != 4) goto raw;
3624                 break;
3625
3626         case PW_TYPE_INTEGER64:
3627         case PW_TYPE_IFID:
3628                 if (datalen != 8) goto raw;
3629                 break;
3630
3631         case PW_TYPE_IPV6_ADDR:
3632                 if (datalen != 16) goto raw;
3633                 break;
3634
3635         case PW_TYPE_IPV6_PREFIX:
3636                 if ((datalen < 2) || (datalen > 18)) goto raw;
3637                 if (data[1] > 128) goto raw;
3638                 break;
3639
3640         case PW_TYPE_BYTE:
3641                 if (datalen != 1) goto raw;
3642                 break;
3643
3644         case PW_TYPE_SHORT:
3645                 if (datalen != 2) goto raw;
3646                 break;
3647
3648         case PW_TYPE_ETHERNET:
3649                 if (datalen != 6) goto raw;
3650                 break;
3651
3652         case PW_TYPE_COMBO_IP_ADDR:
3653                 if (datalen == 4) {
3654                         child = dict_attrbytype(da->attr, da->vendor,
3655                                                 PW_TYPE_IPV4_ADDR);
3656                 } else if (datalen == 16) {
3657                         child = dict_attrbytype(da->attr, da->vendor,
3658                                              PW_TYPE_IPV6_ADDR);
3659                 } else {
3660                         goto raw;
3661                 }
3662                 if (!child) goto raw;
3663                 da = child;     /* re-write it */
3664                 break;
3665
3666         case PW_TYPE_IPV4_PREFIX:
3667                 if (datalen != 6) goto raw;
3668                 if ((data[1] & 0x3f) > 32) goto raw;
3669                 break;
3670
3671                 /*
3672                  *      The rest of the data types can cause
3673                  *      recursion!  Ask yourself, "is recursion OK?"
3674                  */
3675
3676         case PW_TYPE_EXTENDED:
3677                 if (datalen < 2) goto raw; /* etype, value */
3678
3679                 child = dict_attrbyparent(da, data[0], 0);
3680                 if (!child) goto raw;
3681
3682                 /*
3683                  *      Recurse to decode the contents, which could be
3684                  *      a TLV, IPaddr, etc.  Note that we decode only
3685                  *      the current attribute, and we ignore any extra
3686                  *      data after it.
3687                  */
3688                 rcode = data2vp(ctx, packet, original, secret, child,
3689                                 data + 1, attrlen - 1, attrlen - 1, pvp);
3690                 if (rcode < 0) goto raw;
3691                 return 1 + rcode;
3692
3693         case PW_TYPE_LONG_EXTENDED:
3694                 if (datalen < 3) goto raw; /* etype, flags, value */
3695
3696                 child = dict_attrbyparent(da, data[0], 0);
3697                 if (!child) {
3698                         if ((data[0] != PW_VENDOR_SPECIFIC) ||
3699                             (datalen < (3 + 4 + 1))) {
3700                                 /* da->attr < 255, da->vendor == 0 */
3701                                 child = dict_unknown_afrom_fields(ctx, data[0], da->attr * FR_MAX_VENDOR);
3702                         } else {
3703                                 /*
3704                                  *      Try to find the VSA.
3705                                  */
3706                                 memcpy(&vendor, data + 3, 4);
3707                                 vendor = ntohl(vendor);
3708
3709                                 if (vendor == 0) goto raw;
3710
3711                                 child = dict_unknown_afrom_fields(ctx, data[7], vendor | (da->attr * FR_MAX_VENDOR));
3712                         }
3713
3714                         if (!child) {
3715                                 fr_strerror_printf("Internal sanity check %d", __LINE__);
3716                                 return -1;
3717                         }
3718                 }
3719
3720                 /*
3721                  *      If there no more fragments, then the contents
3722                  *      have to be a well-known data type.
3723                  *
3724                  */
3725                 if ((data[1] & 0x80) == 0) {
3726                         rcode = data2vp(ctx, packet, original, secret, child,
3727                                         data + 2, attrlen - 2, attrlen - 2,
3728                                         pvp);
3729                         if (rcode < 0) goto raw;
3730                         return 2 + rcode;
3731                 }
3732
3733                 /*
3734                  *      This requires a whole lot more work.
3735                  */
3736                 return data2vp_extended(ctx, packet, original, secret, child,
3737                                         start, attrlen, packetlen, pvp);
3738
3739         case PW_TYPE_EVS:
3740                 if (datalen < 6) goto raw; /* vid, vtype, value */
3741
3742                 if (data[0] != 0) goto raw; /* we require 24-bit VIDs */
3743
3744                 memcpy(&vendor, data, 4);
3745                 vendor = ntohl(vendor);
3746                 vendor |= da->vendor;
3747
3748                 child = dict_attrbyvalue(data[4], vendor);
3749                 if (!child) {
3750                         /*
3751                          *      Create a "raw" attribute from the
3752                          *      contents of the EVS VSA.
3753                          */
3754                         da = dict_unknown_afrom_fields(ctx, data[4], vendor);
3755                         data += 5;
3756                         datalen -= 5;
3757                         break;
3758                 }
3759
3760                 rcode = data2vp(ctx, packet, original, secret, child,
3761                                 data + 5, attrlen - 5, attrlen - 5, pvp);
3762                 if (rcode < 0) goto raw;
3763                 return 5 + rcode;
3764
3765         case PW_TYPE_TLV:
3766                 /*
3767                  *      We presume that the TLVs all fit into one
3768                  *      attribute, OR they've already been grouped
3769                  *      into a contiguous memory buffer.
3770                  */
3771                 rcode = rad_data2vp_tlvs(ctx, packet, original, secret, da,
3772                                          data, attrlen, pvp);
3773                 if (rcode < 0) goto raw;
3774                 return rcode;
3775
3776         case PW_TYPE_VSA:
3777                 /*
3778                  *      VSAs can be WiMAX, in which case they don't
3779                  *      fit into one attribute.
3780                  */
3781                 rcode = data2vp_vsas(ctx, packet, original, secret,
3782                                      data, attrlen, packetlen, pvp);
3783                 if (rcode < 0) goto raw;
3784                 return rcode;
3785
3786         default:
3787         raw:
3788                 /*
3789                  *      Re-write the attribute to be "raw".  It is
3790                  *      therefore of type "octets", and will be
3791                  *      handled below.
3792                  */
3793                 da = dict_unknown_afrom_fields(ctx, da->attr, da->vendor);
3794                 if (!da) {
3795                         fr_strerror_printf("Internal sanity check %d", __LINE__);
3796                         return -1;
3797                 }
3798                 tag = TAG_NONE;
3799 #ifndef NDEBUG
3800                 /*
3801                  *      Fix for Coverity.
3802                  */
3803                 if (da->type != PW_TYPE_OCTETS) {
3804                         dict_attr_free(&da);
3805                         return -1;
3806                 }
3807 #endif
3808                 break;
3809         }
3810
3811         /*
3812          *      And now that we've verified the basic type
3813          *      information, decode the actual data.
3814          */
3815  alloc_cui:
3816         vp = fr_pair_afrom_da(ctx, da);
3817         if (!vp) return -1;
3818
3819         vp->vp_length = datalen;
3820         vp->tag = tag;
3821
3822         switch (da->type) {
3823         case PW_TYPE_STRING:
3824                 p = talloc_array(vp, char, vp->vp_length + 1);
3825                 memcpy(p, data, vp->vp_length);
3826                 p[vp->vp_length] = '\0';
3827                 vp->vp_strvalue = p;
3828                 break;
3829
3830         case PW_TYPE_OCTETS:
3831                 fr_pair_value_memcpy(vp, data, vp->vp_length);
3832                 break;
3833
3834         case PW_TYPE_ABINARY:
3835                 if (vp->vp_length > sizeof(vp->vp_filter)) {
3836                         vp->vp_length = sizeof(vp->vp_filter);
3837                 }
3838                 memcpy(vp->vp_filter, data, vp->vp_length);
3839                 break;
3840
3841         case PW_TYPE_BYTE:
3842                 vp->vp_byte = data[0];
3843                 break;
3844
3845         case PW_TYPE_SHORT:
3846                 vp->vp_short = (data[0] << 8) | data[1];
3847                 break;
3848
3849         case PW_TYPE_INTEGER:
3850                 memcpy(&vp->vp_integer, data, 4);
3851                 vp->vp_integer = ntohl(vp->vp_integer);
3852                 break;
3853
3854         case PW_TYPE_INTEGER64:
3855                 memcpy(&vp->vp_integer64, data, 8);
3856                 vp->vp_integer64 = ntohll(vp->vp_integer64);
3857                 break;
3858
3859         case PW_TYPE_DATE:
3860                 memcpy(&vp->vp_date, data, 4);
3861                 vp->vp_date = ntohl(vp->vp_date);
3862                 break;
3863
3864         case PW_TYPE_ETHERNET:
3865                 memcpy(vp->vp_ether, data, 6);
3866                 break;
3867
3868         case PW_TYPE_IPV4_ADDR:
3869                 memcpy(&vp->vp_ipaddr, data, 4);
3870                 break;
3871
3872         case PW_TYPE_IFID:
3873                 memcpy(vp->vp_ifid, data, 8);
3874                 break;
3875
3876         case PW_TYPE_IPV6_ADDR:
3877                 memcpy(&vp->vp_ipv6addr, data, 16);
3878                 break;
3879
3880         case PW_TYPE_IPV6_PREFIX:
3881                 /*
3882                  *      FIXME: double-check that
3883                  *      (vp->vp_octets[1] >> 3) matches vp->vp_length + 2
3884                  */
3885                 memcpy(vp->vp_ipv6prefix, data, vp->vp_length);
3886                 if (vp->vp_length < 18) {
3887                         memset(((uint8_t *)vp->vp_ipv6prefix) + vp->vp_length, 0,
3888                                18 - vp->vp_length);
3889                 }
3890                 break;
3891
3892         case PW_TYPE_IPV4_PREFIX:
3893                 /* FIXME: do the same double-check as for IPv6Prefix */
3894                 memcpy(vp->vp_ipv4prefix, data, vp->vp_length);
3895
3896                 /*
3897                  *      /32 means "keep all bits".  Otherwise, mask
3898                  *      them out.
3899                  */
3900                 if ((data[1] & 0x3f) > 32) {
3901                         uint32_t addr, mask;
3902
3903                         memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
3904                         mask = 1;
3905                         mask <<= (32 - (data[1] & 0x3f));
3906                         mask--;
3907                         mask = ~mask;
3908                         mask = htonl(mask);
3909                         addr &= mask;
3910                         memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
3911                 }
3912                 break;
3913
3914         case PW_TYPE_SIGNED:    /* overloaded with vp_integer */
3915                 memcpy(&vp->vp_integer, buffer, 4);
3916                 vp->vp_integer = ntohl(vp->vp_integer);
3917                 break;
3918
3919         default:
3920                 fr_pair_list_free(&vp);
3921                 fr_strerror_printf("Internal sanity check %d", __LINE__);
3922                 return -1;
3923         }
3924         vp->type = VT_DATA;
3925         *pvp = vp;
3926
3927         return attrlen;
3928 }
3929
3930
3931 /** Create a "normal" VALUE_PAIR from the given data
3932  *
3933  */
3934 ssize_t rad_attr2vp(TALLOC_CTX *ctx,
3935                     RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3936                     char const *secret,
3937                     uint8_t const *data, size_t length,
3938                     VALUE_PAIR **pvp)
3939 {
3940         ssize_t rcode;
3941
3942         DICT_ATTR const *da;
3943
3944         if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3945                 fr_strerror_printf("rad_attr2vp: Insufficient data");
3946                 return -1;
3947         }
3948
3949         da = dict_attrbyvalue(data[0], 0);
3950         if (!da) {
3951                 VP_TRACE("attr2vp: unknown attribute %u\n", data[0]);
3952                 da = dict_unknown_afrom_fields(ctx, data[0], 0);
3953         }
3954         if (!da) return -1;
3955
3956         /*
3957          *      Pass the entire thing to the decoding function
3958          */
3959         if (da->flags.concat) {
3960                 VP_TRACE("attr2vp: concat attribute\n");
3961                 return data2vp_concat(ctx, da, data, length, pvp);
3962         }
3963
3964         /*
3965          *      Note that we pass the entire length, not just the
3966          *      length of this attribute.  The Extended or WiMAX
3967          *      attributes may have the "continuation" bit set, and
3968          *      will thus be more than one attribute in length.
3969          */
3970         rcode = data2vp(ctx, packet, original, secret, da,
3971                         data + 2, data[1] - 2, length - 2, pvp);
3972         if (rcode < 0) return rcode;
3973
3974         return 2 + rcode;
3975 }
3976
3977 fr_thread_local_setup(uint8_t *, rad_vp2data_buff)
3978
3979 /** Converts vp_data to network byte order
3980  *
3981  * Provide a pointer to a buffer which contains the value of the VALUE_PAIR
3982  * in an architecture independent format.
3983  *
3984  * The pointer is only guaranteed to be valid between calls to rad_vp2data, and so long
3985  * as the source VALUE_PAIR is not freed.
3986  *
3987  * @param out where to write the pointer to the value.
3988  * @param vp to get the value from.
3989  * @return -1 on error, or the length of the value
3990  */
3991 ssize_t rad_vp2data(uint8_t const **out, VALUE_PAIR const *vp)
3992 {
3993         uint8_t         *buffer;
3994         uint32_t        lvalue;
3995         uint64_t        lvalue64;
3996
3997         *out = NULL;
3998
3999         buffer = fr_thread_local_init(rad_vp2data_buff, free);
4000         if (!buffer) {
4001                 int ret;
4002
4003                 buffer = malloc(sizeof(uint8_t) * sizeof(value_data_t));
4004                 if (!buffer) {
4005                         fr_strerror_printf("Failed allocating memory for rad_vp2data buffer");
4006                         return -1;
4007                 }
4008
4009                 ret = fr_thread_local_set(rad_vp2data_buff, buffer);
4010                 if (ret != 0) {
4011                         fr_strerror_printf("Failed setting up TLS for rad_vp2data buffer: %s", strerror(errno));
4012                         free(buffer);
4013                         return -1;
4014                 }
4015         }
4016
4017         VERIFY_VP(vp);
4018
4019         switch (vp->da->type) {
4020         case PW_TYPE_STRING:
4021         case PW_TYPE_OCTETS:
4022                 memcpy(out, &vp->data.ptr, sizeof(*out));
4023                 break;
4024
4025         /*
4026          *      All of these values are at the same location.
4027          */
4028         case PW_TYPE_IFID:
4029         case PW_TYPE_IPV4_ADDR:
4030         case PW_TYPE_IPV6_ADDR:
4031         case PW_TYPE_IPV6_PREFIX:
4032         case PW_TYPE_IPV4_PREFIX:
4033         case PW_TYPE_ABINARY:
4034         case PW_TYPE_ETHERNET:
4035         case PW_TYPE_COMBO_IP_ADDR:
4036         case PW_TYPE_COMBO_IP_PREFIX:
4037         {
4038                 void const *p = &vp->data;
4039                 memcpy(out, &p, sizeof(*out));
4040                 break;
4041         }
4042
4043         case PW_TYPE_BOOLEAN:
4044                 buffer[0] = vp->vp_byte & 0x01;
4045                 *out = buffer;
4046                 break;
4047
4048         case PW_TYPE_BYTE:
4049                 buffer[0] = vp->vp_byte & 0xff;
4050                 *out = buffer;
4051                 break;
4052
4053         case PW_TYPE_SHORT:
4054                 buffer[0] = (vp->vp_short >> 8) & 0xff;
4055                 buffer[1] = vp->vp_short & 0xff;
4056                 *out = buffer;
4057                 break;
4058
4059         case PW_TYPE_INTEGER:
4060                 lvalue = htonl(vp->vp_integer);
4061                 memcpy(buffer, &lvalue, sizeof(lvalue));
4062                 *out = buffer;
4063                 break;
4064
4065         case PW_TYPE_INTEGER64:
4066                 lvalue64 = htonll(vp->vp_integer64);
4067                 memcpy(buffer, &lvalue64, sizeof(lvalue64));
4068                 *out = buffer;
4069                 break;
4070
4071         case PW_TYPE_DATE:
4072                 lvalue = htonl(vp->vp_date);
4073                 memcpy(buffer, &lvalue, sizeof(lvalue));
4074                 *out = buffer;
4075                 break;
4076
4077         case PW_TYPE_SIGNED:
4078         {
4079                 int32_t slvalue = htonl(vp->vp_signed);
4080                 memcpy(buffer, &slvalue, sizeof(slvalue));
4081                 *out = buffer;
4082                 break;
4083         }
4084
4085         case PW_TYPE_INVALID:
4086         case PW_TYPE_EXTENDED:
4087         case PW_TYPE_LONG_EXTENDED:
4088         case PW_TYPE_EVS:
4089         case PW_TYPE_VSA:
4090         case PW_TYPE_TLV:
4091         case PW_TYPE_TIMEVAL:
4092         case PW_TYPE_MAX:
4093                 fr_strerror_printf("Cannot get data for VALUE_PAIR type %i", vp->da->type);
4094                 return -1;
4095
4096         /* Don't add default */
4097         }
4098
4099         return vp->vp_length;
4100 }
4101
4102 /** Calculate/check digest, and decode radius attributes
4103  *
4104  * @return -1 on decoding error, 0 on success
4105  */
4106 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
4107                char const *secret)
4108 {
4109         int                     packet_length;
4110         uint32_t                num_attributes;
4111         uint8_t                 *ptr;
4112         radius_packet_t         *hdr;
4113         VALUE_PAIR *head, **tail, *vp;
4114
4115         /*
4116          *      Extract attribute-value pairs
4117          */
4118         hdr = (radius_packet_t *)packet->data;
4119         ptr = hdr->data;
4120         packet_length = packet->data_len - RADIUS_HDR_LEN;
4121
4122         head = NULL;
4123         tail = &head;
4124         num_attributes = 0;
4125
4126         /*
4127          *      Loop over the attributes, decoding them into VPs.
4128          */
4129         while (packet_length > 0) {
4130                 ssize_t my_len;
4131
4132                 /*
4133                  *      This may return many VPs
4134                  */
4135                 my_len = rad_attr2vp(packet, packet, original, secret,
4136                                      ptr, packet_length, &vp);
4137                 if (my_len < 0) {
4138                         fr_pair_list_free(&head);
4139                         return -1;
4140                 }
4141
4142                 *tail = vp;
4143                 while (vp) {
4144                         num_attributes++;
4145                         tail = &(vp->next);
4146                         vp = vp->next;
4147                 }
4148
4149                 /*
4150                  *      VSA's may not have been counted properly in
4151                  *      rad_packet_ok() above, as it is hard to count
4152                  *      then without using the dictionary.  We
4153                  *      therefore enforce the limits here, too.
4154                  */
4155                 if ((fr_max_attributes > 0) &&
4156                     (num_attributes > fr_max_attributes)) {
4157                         char host_ipaddr[128];
4158
4159                         fr_pair_list_free(&head);
4160                         fr_strerror_printf("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
4161                                    inet_ntop(packet->src_ipaddr.af,
4162                                              &packet->src_ipaddr.ipaddr,
4163                                              host_ipaddr, sizeof(host_ipaddr)),
4164                                    num_attributes, fr_max_attributes);
4165                         return -1;
4166                 }
4167
4168                 ptr += my_len;
4169                 packet_length -= my_len;
4170         }
4171
4172         /*
4173          *      Merge information from the outside world into our
4174          *      random pool.
4175          */
4176         fr_rand_seed(packet->data, RADIUS_HDR_LEN);
4177
4178         /*
4179          *      There may be VP's already in the packet.  Don't
4180          *      destroy them.  Instead, add the decoded attributes to
4181          *      the tail of the list.
4182          */
4183         for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
4184                 /* nothing */
4185         }
4186         *tail = head;
4187
4188         return 0;
4189 }
4190
4191
4192 /** Encode password
4193  *
4194  * We assume that the passwd buffer passed is big enough.
4195  * RFC2138 says the password is max 128 chars, so the size
4196  * of the passwd buffer must be at least 129 characters.
4197  * Preferably it's just MAX_STRING_LEN.
4198  *
4199  * int *pwlen is updated to the new length of the encrypted
4200  * password - a multiple of 16 bytes.
4201  */
4202 int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
4203                  uint8_t const *vector)
4204 {
4205         FR_MD5_CTX context, old;
4206         uint8_t digest[AUTH_VECTOR_LEN];
4207         int     i, n, secretlen;
4208         int     len;
4209
4210         /*
4211          *      RFC maximum is 128 bytes.
4212          *
4213          *      If length is zero, pad it out with zeros.
4214          *
4215          *      If the length isn't aligned to 16 bytes,
4216          *      zero out the extra data.
4217          */
4218         len = *pwlen;
4219
4220         if (len > 128) len = 128;
4221
4222         if (len == 0) {
4223                 memset(passwd, 0, AUTH_PASS_LEN);
4224                 len = AUTH_PASS_LEN;
4225         } else if ((len % AUTH_PASS_LEN) != 0) {
4226                 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
4227                 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
4228         }
4229         *pwlen = len;
4230
4231         /*
4232          *      Use the secret to setup the decryption digest
4233          */
4234         secretlen = strlen(secret);
4235
4236         fr_md5_init(&context);
4237         fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4238         old = context;          /* save intermediate work */
4239
4240         /*
4241          *      Encrypt it in place.  Don't bother checking
4242          *      len, as we've ensured above that it's OK.
4243          */
4244         for (n = 0; n < len; n += AUTH_PASS_LEN) {
4245                 if (n == 0) {
4246                         fr_md5_update(&context, vector, AUTH_PASS_LEN);
4247                         fr_md5_final(digest, &context);
4248                 } else {
4249                         context = old;
4250                         fr_md5_update(&context,
4251                                      (uint8_t *) passwd + n - AUTH_PASS_LEN,
4252                                      AUTH_PASS_LEN);
4253                         fr_md5_final(digest, &context);
4254                 }
4255
4256                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4257                         passwd[i + n] ^= digest[i];
4258                 }
4259         }
4260
4261         return 0;
4262 }
4263
4264 /** Decode password
4265  *
4266  */
4267 int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
4268                  uint8_t const *vector)
4269 {
4270         FR_MD5_CTX context, old;
4271         uint8_t digest[AUTH_VECTOR_LEN];
4272         int     i;
4273         size_t  n, secretlen;
4274
4275         /*
4276          *      The RFC's say that the maximum is 128.
4277          *      The buffer we're putting it into above is 254, so
4278          *      we don't need to do any length checking.
4279          */
4280         if (pwlen > 128) pwlen = 128;
4281
4282         /*
4283          *      Catch idiots.
4284          */
4285         if (pwlen == 0) goto done;
4286
4287         /*
4288          *      Use the secret to setup the decryption digest
4289          */
4290         secretlen = strlen(secret);
4291
4292         fr_md5_init(&context);
4293         fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4294         old = context;          /* save intermediate work */
4295
4296         /*
4297          *      The inverse of the code above.
4298          */
4299         for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
4300                 if (n == 0) {
4301                         fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4302                         fr_md5_final(digest, &context);
4303
4304                         context = old;
4305                         if (pwlen > AUTH_PASS_LEN) {
4306                                 fr_md5_update(&context, (uint8_t *) passwd,
4307                                              AUTH_PASS_LEN);
4308                         }
4309                 } else {
4310                         fr_md5_final(digest, &context);
4311
4312                         context = old;
4313                         if (pwlen > (n + AUTH_PASS_LEN)) {
4314                                 fr_md5_update(&context, (uint8_t *) passwd + n,
4315                                              AUTH_PASS_LEN);
4316                         }
4317                 }
4318
4319                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4320                         passwd[i + n] ^= digest[i];
4321                 }
4322         }
4323
4324  done:
4325         passwd[pwlen] = '\0';
4326         return strlen(passwd);
4327 }
4328
4329
4330 /** Encode Tunnel-Password attributes when sending them out on the wire
4331  *
4332  * int *pwlen is updated to the new length of the encrypted
4333  * password - a multiple of 16 bytes.
4334  *
4335  * This is per RFC-2868 which adds a two char SALT to the initial intermediate
4336  * value MD5 hash.
4337  */
4338 ssize_t rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret, uint8_t const *vector)
4339 {
4340         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
4341         unsigned char   digest[AUTH_VECTOR_LEN];
4342         char*   salt;
4343         int     i, n, secretlen;
4344         unsigned len, n2;
4345
4346         len = *pwlen;
4347
4348         if (len > 127) len = 127;
4349
4350         /*
4351          *      Shift the password 3 positions right to place a salt and original
4352          *      length, tag will be added automatically on packet send.
4353          */
4354         for (n = len ; n >= 0 ; n--) passwd[n + 3] = passwd[n];
4355         salt = passwd;
4356         passwd += 2;
4357
4358         /*
4359          *      save original password length as first password character;
4360          */
4361         *passwd = len;
4362         len += 1;
4363
4364
4365         /*
4366          *      Generate salt.  The RFC's say:
4367          *
4368          *      The high bit of salt[0] must be set, each salt in a
4369          *      packet should be unique, and they should be random
4370          *
4371          *      So, we set the high bit, add in a counter, and then
4372          *      add in some CSPRNG data.  should be OK..
4373          */
4374         salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
4375                    (fr_rand() & 0x07));
4376         salt[1] = fr_rand();
4377
4378         /*
4379          *      Padd password to multiple of AUTH_PASS_LEN bytes.
4380          */
4381         n = len % AUTH_PASS_LEN;
4382         if (n) {
4383                 n = AUTH_PASS_LEN - n;
4384                 for (; n > 0; n--, len++)
4385                         passwd[len] = 0;
4386         }
4387         /* set new password length */
4388         *pwlen = len + 2;
4389
4390         /*
4391          *      Use the secret to setup the decryption digest
4392          */
4393         secretlen = strlen(secret);
4394         memcpy(buffer, secret, secretlen);
4395
4396         for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
4397                 if (!n2) {
4398                         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
4399                         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
4400                         fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
4401                 } else {
4402                         memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4403                         fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4404                 }
4405
4406                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4407                         passwd[i + n2] ^= digest[i];
4408                 }
4409         }
4410         passwd[n2] = 0;
4411         return 0;
4412 }
4413
4414 /** Decode Tunnel-Password encrypted attributes
4415  *
4416  * Defined in RFC-2868, this uses a two char SALT along with the
4417  * initial intermediate value, to differentiate it from the
4418  * above.
4419  */
4420 ssize_t rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret, uint8_t const *vector)
4421 {
4422         FR_MD5_CTX  context, old;
4423         uint8_t         digest[AUTH_VECTOR_LEN];
4424         int             secretlen;
4425         size_t          i, n, encrypted_len, reallen;
4426
4427         encrypted_len = *pwlen;
4428
4429         /*
4430          *      We need at least a salt.
4431          */
4432         if (encrypted_len < 2) {
4433                 fr_strerror_printf("tunnel password is too short");
4434                 return -1;
4435         }
4436
4437         /*
4438          *      There's a salt, but no password.  Or, there's a salt
4439          *      and a 'data_len' octet.  It's wrong, but at least we
4440          *      can figure out what it means: the password is empty.
4441          *
4442          *      Note that this means we ignore the 'data_len' field,
4443          *      if the attribute length tells us that there's no
4444          *      more data.  So the 'data_len' field may be wrong,
4445          *      but that's ok...
4446          */
4447         if (encrypted_len <= 3) {
4448                 passwd[0] = 0;
4449                 *pwlen = 0;
4450                 return 0;
4451         }
4452
4453         encrypted_len -= 2;             /* discount the salt */
4454
4455         /*
4456          *      Use the secret to setup the decryption digest
4457          */
4458         secretlen = strlen(secret);
4459
4460         fr_md5_init(&context);
4461         fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4462         old = context;          /* save intermediate work */
4463
4464         /*
4465          *      Set up the initial key:
4466          *
4467          *       b(1) = MD5(secret + vector + salt)
4468          */
4469         fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4470         fr_md5_update(&context, passwd, 2);
4471
4472         reallen = 0;
4473         for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
4474                 size_t base;
4475                 size_t block_len = AUTH_PASS_LEN;
4476
4477                 /*
4478                  *      Ensure we don't overflow the input on MD5
4479                  */
4480                 if ((n + 2 + AUTH_PASS_LEN) > *pwlen) {
4481                         block_len = *pwlen - n - 2;
4482                 }
4483
4484                 if (n == 0) {
4485                         base = 1;
4486
4487                         fr_md5_final(digest, &context);
4488
4489                         context = old;
4490
4491                         /*
4492                          *      A quick check: decrypt the first octet
4493                          *      of the password, which is the
4494                          *      'data_len' field.  Ensure it's sane.
4495                          */
4496                         reallen = passwd[2] ^ digest[0];
4497                         if (reallen > encrypted_len) {
4498                                 fr_strerror_printf("tunnel password is too long for the attribute");
4499                                 return -1;
4500                         }
4501
4502                         fr_md5_update(&context, passwd + 2, block_len);
4503
4504                 } else {
4505                         base = 0;
4506
4507                         fr_md5_final(digest, &context);
4508
4509                         context = old;
4510                         fr_md5_update(&context, passwd + n + 2, block_len);
4511                 }
4512
4513                 for (i = base; i < block_len; i++) {
4514                         passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4515                 }
4516         }
4517
4518         *pwlen = reallen;
4519         passwd[reallen] = 0;
4520
4521         return reallen;
4522 }
4523
4524 /** Encode a CHAP password
4525  *
4526  * @bug FIXME: might not work with Ascend because
4527  * we use vp->vp_length, and Ascend gear likes
4528  * to send an extra '\0' in the string!
4529  */
4530 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4531                     VALUE_PAIR *password)
4532 {
4533         int             i;
4534         uint8_t         *ptr;
4535         uint8_t         string[MAX_STRING_LEN * 2 + 1];
4536         VALUE_PAIR      *challenge;
4537
4538         /*
4539          *      Sanity check the input parameters
4540          */
4541         if ((packet == NULL) || (password == NULL)) {
4542                 return -1;
4543         }
4544
4545         /*
4546          *      Note that the password VP can be EITHER
4547          *      a User-Password attribute (from a check-item list),
4548          *      or a CHAP-Password attribute (the client asking
4549          *      the library to encode it).
4550          */
4551
4552         i = 0;
4553         ptr = string;
4554         *ptr++ = id;
4555
4556         i++;
4557         memcpy(ptr, password->vp_strvalue, password->vp_length);
4558         ptr += password->vp_length;
4559         i += password->vp_length;
4560
4561         /*
4562          *      Use Chap-Challenge pair if present,
4563          *      Request Authenticator otherwise.
4564          */
4565         challenge = fr_pair_find_by_num(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
4566         if (challenge) {
4567                 memcpy(ptr, challenge->vp_strvalue, challenge->vp_length);
4568                 i += challenge->vp_length;
4569         } else {
4570                 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4571                 i += AUTH_VECTOR_LEN;
4572         }
4573
4574         *output = id;
4575         fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4576
4577         return 0;
4578 }
4579
4580
4581 /** Seed the random number generator
4582  *
4583  * May be called any number of times.
4584  */
4585 void fr_rand_seed(void const *data, size_t size)
4586 {
4587         uint32_t hash;
4588
4589         /*
4590          *      Ensure that the pool is initialized.
4591          */
4592         if (!fr_rand_initialized) {
4593                 int fd;
4594
4595                 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4596
4597                 fd = open("/dev/urandom", O_RDONLY);
4598                 if (fd >= 0) {
4599                         size_t total;
4600                         ssize_t this;
4601
4602                         total = 0;
4603                         while (total < sizeof(fr_rand_pool.randrsl)) {
4604                                 this = read(fd, fr_rand_pool.randrsl,
4605                                             sizeof(fr_rand_pool.randrsl) - total);
4606                                 if ((this < 0) && (errno != EINTR)) break;
4607                                 if (this > 0) total += this;
4608                         }
4609                         close(fd);
4610                 } else {
4611                         fr_rand_pool.randrsl[0] = fd;
4612                         fr_rand_pool.randrsl[1] = time(NULL);
4613                         fr_rand_pool.randrsl[2] = errno;
4614                 }
4615
4616                 fr_randinit(&fr_rand_pool, 1);
4617                 fr_rand_pool.randcnt = 0;
4618                 fr_rand_initialized = 1;
4619         }
4620
4621         if (!data) return;
4622
4623         /*
4624          *      Hash the user data
4625          */
4626         hash = fr_rand();
4627         if (!hash) hash = fr_rand();
4628         hash = fr_hash_update(data, size, hash);
4629
4630         fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4631 }
4632
4633
4634 /** Return a 32-bit random number
4635  *
4636  */
4637 uint32_t fr_rand(void)
4638 {
4639         uint32_t num;
4640
4641         /*
4642          *      Ensure that the pool is initialized.
4643          */
4644         if (!fr_rand_initialized) {
4645                 fr_rand_seed(NULL, 0);
4646         }
4647
4648         num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4649         if (fr_rand_pool.randcnt >= 256) {
4650                 fr_rand_pool.randcnt = 0;
4651                 fr_isaac(&fr_rand_pool);
4652         }
4653
4654         return num;
4655 }
4656
4657
4658 /** Allocate a new RADIUS_PACKET
4659  *
4660  * @param ctx the context in which the packet is allocated. May be NULL if
4661  *      the packet is not associated with a REQUEST.
4662  * @param new_vector if true a new request authenticator will be generated.
4663  * @return a new RADIUS_PACKET or NULL on error.
4664  */
4665 RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, bool new_vector)
4666 {
4667         RADIUS_PACKET   *rp;
4668
4669         rp = talloc_zero(ctx, RADIUS_PACKET);
4670         if (!rp) {
4671                 fr_strerror_printf("out of memory");
4672                 return NULL;
4673         }
4674         rp->id = -1;
4675         rp->offset = -1;
4676
4677         if (new_vector) {
4678                 int i;
4679                 uint32_t hash, base;
4680
4681                 /*
4682                  *      Don't expose the actual contents of the random
4683                  *      pool.
4684                  */
4685                 base = fr_rand();
4686                 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4687                         hash = fr_rand() ^ base;
4688                         memcpy(rp->vector + i, &hash, sizeof(hash));
4689                 }
4690         }
4691         fr_rand();              /* stir the pool again */
4692
4693         return rp;
4694 }
4695
4696 /** Allocate a new RADIUS_PACKET response
4697  *
4698  * @param ctx the context in which the packet is allocated. May be NULL if
4699  *      the packet is not associated with a REQUEST.
4700  * @param packet The request packet.
4701  * @return a new RADIUS_PACKET or NULL on error.
4702  */
4703 RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
4704 {
4705         RADIUS_PACKET *reply;
4706
4707         if (!packet) return NULL;
4708
4709         reply = rad_alloc(ctx, false);
4710         if (!reply) return NULL;
4711
4712         /*
4713          *      Initialize the fields from the request.
4714          */
4715         reply->sockfd = packet->sockfd;
4716         reply->dst_ipaddr = packet->src_ipaddr;
4717         reply->src_ipaddr = packet->dst_ipaddr;
4718         reply->dst_port = packet->src_port;
4719         reply->src_port = packet->dst_port;
4720         reply->id = packet->id;
4721         reply->code = 0; /* UNKNOWN code */
4722         memcpy(reply->vector, packet->vector,
4723                sizeof(reply->vector));
4724         reply->vps = NULL;
4725         reply->data = NULL;
4726         reply->data_len = 0;
4727
4728 #ifdef WITH_TCP
4729         reply->proto = packet->proto;
4730 #endif
4731         return reply;
4732 }
4733
4734
4735 /** Free a RADIUS_PACKET
4736  *
4737  */
4738 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4739 {
4740         RADIUS_PACKET *radius_packet;
4741
4742         if (!radius_packet_ptr || !*radius_packet_ptr) return;
4743         radius_packet = *radius_packet_ptr;
4744
4745         VERIFY_PACKET(radius_packet);
4746
4747         fr_pair_list_free(&radius_packet->vps);
4748
4749         talloc_free(radius_packet);
4750         *radius_packet_ptr = NULL;
4751 }
4752
4753 /** Duplicate a RADIUS_PACKET
4754  *
4755  * @param ctx the context in which the packet is allocated. May be NULL if
4756  *      the packet is not associated with a REQUEST.
4757  * @param in The packet to copy
4758  * @return a new RADIUS_PACKET or NULL on error.
4759  */
4760 RADIUS_PACKET *rad_copy_packet(TALLOC_CTX *ctx, RADIUS_PACKET const *in)
4761 {
4762         RADIUS_PACKET *out;
4763
4764         out = rad_alloc(ctx, false);
4765         if (!out) return NULL;
4766
4767         /*
4768          *      Bootstrap by copying everything.
4769          */
4770         memcpy(out, in, sizeof(*out));
4771
4772         /*
4773          *      Then reset necessary fields
4774          */
4775         out->sockfd = -1;
4776
4777         out->data = NULL;
4778         out->data_len = 0;
4779
4780         out->vps = fr_pair_list_copy(out, in->vps);
4781         out->offset = 0;
4782
4783         return out;
4784 }