remove redundant check. Found by PVS-Studio
[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->attr == PW_MESSAGE_AUTHENTICATOR) {
1610                 if (room < 18) return -1;
1611
1612                 ptr[0] = PW_MESSAGE_AUTHENTICATOR;
1613                 ptr[1] = 18;
1614                 memset(ptr + 2, 0, 16);
1615 #ifndef NDEBUG
1616                 if ((fr_debug_lvl > 3) && fr_log_fp) {
1617                         fprintf(fr_log_fp, "\t\t50 12 ...\n");
1618                 }
1619 #endif
1620
1621                 *pvp = (*pvp)->next;
1622                 return 18;
1623         }
1624
1625         /*
1626          *      EAP-Message is special.
1627          */
1628         if (vp->da->flags.concat && (vp->vp_length > 253)) {
1629                 return vp2attr_concat(packet, original, secret, pvp, vp->da->attr,
1630                                       ptr, room);
1631         }
1632
1633         return vp2attr_rfc(packet, original, secret, pvp, vp->da->attr,
1634                            ptr, room);
1635 }
1636
1637 static ssize_t rad_vp2rfctlv(RADIUS_PACKET const *packet,
1638                              RADIUS_PACKET const *original,
1639                              char const *secret, VALUE_PAIR const **pvp,
1640                              uint8_t *start, size_t room)
1641 {
1642         ssize_t len;
1643         VALUE_PAIR const *vp = *pvp;
1644
1645         VERIFY_VP(vp);
1646
1647         if (!vp->da->flags.is_tlv) {
1648                 fr_strerror_printf("rad_vp2rfctlv: attr is not a TLV");
1649                 return -1;
1650         }
1651
1652         if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) != 0) {
1653                 fr_strerror_printf("rad_vp2rfctlv: attr is not an RFC TLV");
1654                 return -1;
1655         }
1656
1657         if (room < 5) return 0;
1658
1659         /*
1660          *      Encode the first level of TLVs
1661          */
1662         start[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1663         start[1] = 4;
1664         start[2] = vp->da->attr & fr_attr_mask[0];
1665         start[3] = 2;
1666
1667         len = vp2data_any(packet, original, secret, 0, pvp,
1668                           start + 4, room - 4);
1669         if (len <= 0) return len;
1670
1671         if (len > 253) {
1672                 return -1;
1673         }
1674
1675         start[1] += len;
1676         start[3] += len;
1677
1678         return start[1];
1679 }
1680
1681 /** Parse a data structure into a RADIUS attribute
1682  *
1683  */
1684 int rad_vp2attr(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1685                 char const *secret, VALUE_PAIR const **pvp, uint8_t *start,
1686                 size_t room)
1687 {
1688         VALUE_PAIR const *vp;
1689
1690         if (!pvp || !*pvp || !start || (room <= 2)) return -1;
1691
1692         vp = *pvp;
1693
1694         VERIFY_VP(vp);
1695
1696         /*
1697          *      RFC format attributes take the fast path.
1698          */
1699         if (!vp->da->vendor) {
1700                 if (vp->da->attr > 255) {
1701                         *pvp = vp->next;
1702                         return 0;
1703                 }
1704
1705                 return rad_vp2rfc(packet, original, secret, pvp,
1706                                   start, room);
1707         }
1708
1709         if (vp->da->flags.extended) {
1710                 return rad_vp2extended(packet, original, secret, pvp,
1711                                        start, room);
1712         }
1713
1714         /*
1715          *      The upper 8 bits of the vendor number are the standard
1716          *      space attribute which is a TLV.
1717          */
1718         if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) == 0) {
1719                 return rad_vp2rfctlv(packet, original, secret, pvp,
1720                                      start, room);
1721         }
1722
1723         if (vp->da->flags.wimax) {
1724                 return rad_vp2wimax(packet, original, secret, pvp,
1725                                     start, room);
1726         }
1727
1728         return rad_vp2vsa(packet, original, secret, pvp, start, room);
1729 }
1730
1731
1732 /** Encode a packet
1733  *
1734  */
1735 int rad_encode(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1736                char const *secret)
1737 {
1738         radius_packet_t         *hdr;
1739         uint8_t                 *ptr;
1740         uint16_t                total_length;
1741         int                     len;
1742         VALUE_PAIR const        *reply;
1743
1744         /*
1745          *      A 4K packet, aligned on 64-bits.
1746          */
1747         uint64_t        data[MAX_PACKET_LEN / sizeof(uint64_t)];
1748
1749         /*
1750          *      Double-check some things based on packet code.
1751          */
1752         switch (packet->code) {
1753         case PW_CODE_ACCESS_ACCEPT:
1754         case PW_CODE_ACCESS_REJECT:
1755         case PW_CODE_ACCESS_CHALLENGE:
1756                 if (!original) {
1757                         fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1758                         return -1;
1759                 }
1760                 break;
1761
1762                 /*
1763                  *      These packet vectors start off as all zero.
1764                  */
1765         case PW_CODE_ACCOUNTING_REQUEST:
1766         case PW_CODE_DISCONNECT_REQUEST:
1767         case PW_CODE_COA_REQUEST:
1768                 memset(packet->vector, 0, sizeof(packet->vector));
1769                 break;
1770
1771         default:
1772                 break;
1773         }
1774
1775         /*
1776          *      Use memory on the stack, until we know how
1777          *      large the packet will be.
1778          */
1779         hdr = (radius_packet_t *) data;
1780
1781         /*
1782          *      Build standard header
1783          */
1784         hdr->code = packet->code;
1785         hdr->id = packet->id;
1786
1787         memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1788
1789         total_length = RADIUS_HDR_LEN;
1790
1791         /*
1792          *      Load up the configuration values for the user
1793          */
1794         ptr = hdr->data;
1795         packet->offset = 0;
1796
1797         /*
1798          *      FIXME: Loop twice over the reply list.  The first time,
1799          *      calculate the total length of data.  The second time,
1800          *      allocate the memory, and fill in the VP's.
1801          *
1802          *      Hmm... this may be slower than just doing a small
1803          *      memcpy.
1804          */
1805
1806         /*
1807          *      Loop over the reply attributes for the packet.
1808          */
1809         reply = packet->vps;
1810         while (reply) {
1811                 size_t last_len, room;
1812                 char const *last_name = NULL;
1813
1814                 VERIFY_VP(reply);
1815
1816                 /*
1817                  *      Ignore non-wire attributes, but allow extended
1818                  *      attributes.
1819                  */
1820                 if ((reply->da->vendor == 0) &&
1821                     ((reply->da->attr & 0xFFFF) >= 256) &&
1822                     !reply->da->flags.extended && !reply->da->flags.long_extended) {
1823 #ifndef NDEBUG
1824                         /*
1825                          *      Permit the admin to send BADLY formatted
1826                          *      attributes with a debug build.
1827                          */
1828                         if (reply->da->attr == PW_RAW_ATTRIBUTE) {
1829                                 memcpy(ptr, reply->vp_octets, reply->vp_length);
1830                                 len = reply->vp_length;
1831                                 reply = reply->next;
1832                                 goto next;
1833                         }
1834 #endif
1835                         reply = reply->next;
1836                         continue;
1837                 }
1838
1839                 /*
1840                  *      We allow zero-length strings in "unlang", but
1841                  *      skip them (except for CUI, thanks WiMAX!) on
1842                  *      all other attributes.
1843                  */
1844                 if (reply->vp_length == 0) {
1845                         if ((reply->da->vendor != 0) ||
1846                             ((reply->da->attr != PW_CHARGEABLE_USER_IDENTITY) &&
1847                              (reply->da->attr != PW_MESSAGE_AUTHENTICATOR))) {
1848                                 reply = reply->next;
1849                                 continue;
1850                         }
1851                 }
1852
1853                 /*
1854                  *      Set the Message-Authenticator to the correct
1855                  *      length and initial value.
1856                  */
1857                 if (!reply->da->vendor && (reply->da->attr == PW_MESSAGE_AUTHENTICATOR)) {
1858                         /*
1859                          *      Cache the offset to the
1860                          *      Message-Authenticator
1861                          */
1862                         packet->offset = total_length;
1863                         last_len = 16;
1864                 } else {
1865                         last_len = reply->vp_length;
1866                 }
1867                 last_name = reply->da->name;
1868
1869                 room = ((uint8_t *) data) + sizeof(data) - ptr;
1870
1871                 if (room <= 2) break;
1872
1873                 len = rad_vp2attr(packet, original, secret, &reply, ptr, room);
1874                 if (len < 0) return -1;
1875
1876                 /*
1877                  *      Failed to encode the attribute, likely because
1878                  *      the packet is full.
1879                  */
1880                 if (len == 0) {
1881                         if (last_len != 0) {
1882                                 fr_strerror_printf("WARNING: Failed encoding attribute %s\n", last_name);
1883                                 break;
1884                         } else {
1885                                 fr_strerror_printf("WARNING: Skipping zero-length attribute %s\n", last_name);
1886                         }
1887                 }
1888
1889 #ifndef NDEBUG
1890         next:                   /* Used only for Raw-Attribute */
1891 #endif
1892                 ptr += len;
1893                 total_length += len;
1894         } /* done looping over all attributes */
1895
1896         /*
1897          *      Fill in the rest of the fields, and copy the data over
1898          *      from the local stack to the newly allocated memory.
1899          *
1900          *      Yes, all this 'memcpy' is slow, but it means
1901          *      that we only allocate the minimum amount of
1902          *      memory for a request.
1903          */
1904         packet->data_len = total_length;
1905         packet->data = talloc_array(packet, uint8_t, packet->data_len);
1906         if (!packet->data) {
1907                 fr_strerror_printf("Out of memory");
1908                 return -1;
1909         }
1910
1911         memcpy(packet->data, hdr, packet->data_len);
1912         hdr = (radius_packet_t *) packet->data;
1913
1914         total_length = htons(total_length);
1915         memcpy(hdr->length, &total_length, sizeof(total_length));
1916
1917         return 0;
1918 }
1919
1920
1921 /** Sign a previously encoded packet
1922  *
1923  */
1924 int rad_sign(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1925              char const *secret)
1926 {
1927         radius_packet_t *hdr = (radius_packet_t *)packet->data;
1928
1929         /*
1930          *      It wasn't assigned an Id, this is bad!
1931          */
1932         if (packet->id < 0) {
1933                 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id");
1934                 return -1;
1935         }
1936
1937         if (!packet->data || (packet->data_len < RADIUS_HDR_LEN) ||
1938             (packet->offset < 0)) {
1939                 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1940                 return -1;
1941         }
1942
1943         /*
1944          *      Set up the authentication vector with zero, or with
1945          *      the original vector, prior to signing.
1946          */
1947         switch (packet->code) {
1948         case PW_CODE_ACCOUNTING_REQUEST:
1949         case PW_CODE_DISCONNECT_REQUEST:
1950         case PW_CODE_COA_REQUEST:
1951                 memset(packet->vector, 0, AUTH_VECTOR_LEN);
1952                 break;
1953
1954         case PW_CODE_ACCESS_ACCEPT:
1955         case PW_CODE_ACCESS_REJECT:
1956         case PW_CODE_ACCESS_CHALLENGE:
1957         case PW_CODE_ACCOUNTING_RESPONSE:
1958         case PW_CODE_DISCONNECT_ACK:
1959         case PW_CODE_DISCONNECT_NAK:
1960         case PW_CODE_COA_ACK:
1961         case PW_CODE_COA_NAK:
1962                 if (!original) {
1963                         fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1964                         return -1;
1965                 }
1966                 memcpy(packet->vector, original->vector, AUTH_VECTOR_LEN);
1967                 break;
1968
1969         case PW_CODE_ACCESS_REQUEST:
1970         case PW_CODE_STATUS_SERVER:
1971         default:
1972                 break;          /* packet->vector is already random bytes */
1973         }
1974
1975 #ifndef NDEBUG
1976         if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
1977 #endif
1978
1979         /*
1980          *      If there's a Message-Authenticator, update it
1981          *      now.
1982          */
1983         if (packet->offset > 0) {
1984                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1985
1986                 switch (packet->code) {
1987                 case PW_CODE_ACCOUNTING_RESPONSE:
1988                         if (original && original->code == PW_CODE_STATUS_SERVER) {
1989                                 goto do_ack;
1990                         }
1991
1992                 case PW_CODE_ACCOUNTING_REQUEST:
1993                 case PW_CODE_DISCONNECT_REQUEST:
1994                 case PW_CODE_DISCONNECT_ACK:
1995                 case PW_CODE_DISCONNECT_NAK:
1996                 case PW_CODE_COA_REQUEST:
1997                 case PW_CODE_COA_ACK:
1998                 case PW_CODE_COA_NAK:
1999                         memset(hdr->vector, 0, AUTH_VECTOR_LEN);
2000                         break;
2001
2002                 do_ack:
2003                 case PW_CODE_ACCESS_ACCEPT:
2004                 case PW_CODE_ACCESS_REJECT:
2005                 case PW_CODE_ACCESS_CHALLENGE:
2006                         memcpy(hdr->vector, original->vector, AUTH_VECTOR_LEN);
2007                         break;
2008
2009                 default:
2010                         break;
2011                 }
2012
2013                 /*
2014                  *      Set the authentication vector to zero,
2015                  *      calculate the HMAC, and put it
2016                  *      into the Message-Authenticator
2017                  *      attribute.
2018                  */
2019                 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
2020                             (uint8_t const *) secret, strlen(secret));
2021                 memcpy(packet->data + packet->offset + 2,
2022                        calc_auth_vector, AUTH_VECTOR_LEN);
2023         }
2024
2025         /*
2026          *      Copy the request authenticator over to the packet.
2027          */
2028         memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
2029
2030         /*
2031          *      Switch over the packet code, deciding how to
2032          *      sign the packet.
2033          */
2034         switch (packet->code) {
2035                 /*
2036                  *      Request packets are not signed, but
2037                  *      have a random authentication vector.
2038                  */
2039         case PW_CODE_ACCESS_REQUEST:
2040         case PW_CODE_STATUS_SERVER:
2041                 break;
2042
2043                 /*
2044                  *      Reply packets are signed with the
2045                  *      authentication vector of the request.
2046                  */
2047         default:
2048                 {
2049                         uint8_t digest[16];
2050
2051                         FR_MD5_CTX      context;
2052                         fr_md5_init(&context);
2053                         fr_md5_update(&context, packet->data, packet->data_len);
2054                         fr_md5_update(&context, (uint8_t const *) secret,
2055                                      strlen(secret));
2056                         fr_md5_final(digest, &context);
2057
2058                         memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
2059                         memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
2060                         break;
2061                 }
2062         }/* switch over packet codes */
2063
2064         return 0;
2065 }
2066
2067 /** Reply to the request
2068  *
2069  * Also attach reply attribute value pairs and any user message provided.
2070  */
2071 int rad_send(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2072              char const *secret)
2073 {
2074         /*
2075          *      Maybe it's a fake packet.  Don't send it.
2076          */
2077         if (!packet || (packet->sockfd < 0)) {
2078                 return 0;
2079         }
2080
2081         /*
2082          *  First time through, allocate room for the packet
2083          */
2084         if (!packet->data) {
2085                 /*
2086                  *      Encode the packet.
2087                  */
2088                 if (rad_encode(packet, original, secret) < 0) {
2089                         return -1;
2090                 }
2091
2092                 /*
2093                  *      Re-sign it, including updating the
2094                  *      Message-Authenticator.
2095                  */
2096                 if (rad_sign(packet, original, secret) < 0) {
2097                         return -1;
2098                 }
2099
2100                 /*
2101                  *      If packet->data points to data, then we print out
2102                  *      the VP list again only for debugging.
2103                  */
2104         }
2105
2106 #ifndef NDEBUG
2107         if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2108 #endif
2109
2110 #ifdef WITH_TCP
2111         /*
2112          *      If the socket is TCP, call write().  Calling sendto()
2113          *      is allowed on some platforms, but it's not nice.  Even
2114          *      worse, if UDPFROMTO is defined, we *can't* use it on
2115          *      TCP sockets.  So... just call write().
2116          */
2117         if (packet->proto == IPPROTO_TCP) {
2118                 ssize_t rcode;
2119
2120                 rcode = write(packet->sockfd, packet->data, packet->data_len);
2121                 if (rcode >= 0) return rcode;
2122
2123                 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
2124                 return -1;
2125         }
2126 #endif
2127
2128         /*
2129          *      And send it on it's way.
2130          */
2131         return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
2132                           &packet->src_ipaddr, packet->src_port,
2133                           &packet->dst_ipaddr, packet->dst_port);
2134 }
2135
2136 /** Do a comparison of two authentication digests by comparing the FULL digest
2137  *
2138  * Otherwise, the server can be subject to timing attacks that allow attackers
2139  * find a valid message authenticator.
2140  *
2141  * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
2142  */
2143 int rad_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
2144 {
2145         int result = 0;
2146         size_t i;
2147
2148         for (i = 0; i < length; i++) {
2149                 result |= a[i] ^ b[i];
2150         }
2151
2152         return result;          /* 0 is OK, !0 is !OK, just like memcmp */
2153 }
2154
2155
2156 /** Validates the requesting client NAS
2157  *
2158  * Calculates the request Authenticator based on the clients private key.
2159  */
2160 static int calc_acctdigest(RADIUS_PACKET *packet, char const *secret)
2161 {
2162         uint8_t         digest[AUTH_VECTOR_LEN];
2163         FR_MD5_CTX              context;
2164
2165         /*
2166          *      Zero out the auth_vector in the received packet.
2167          *      Then append the shared secret to the received packet,
2168          *      and calculate the MD5 sum. This must be the same
2169          *      as the original MD5 sum (packet->vector).
2170          */
2171         memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2172
2173         /*
2174          *  MD5(packet + secret);
2175          */
2176         fr_md5_init(&context);
2177         fr_md5_update(&context, packet->data, packet->data_len);
2178         fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2179         fr_md5_final(digest, &context);
2180
2181         /*
2182          *      Return 0 if OK, 2 if not OK.
2183          */
2184         if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
2185         return 0;
2186 }
2187
2188
2189 /** Validates the requesting client NAS
2190  *
2191  * Calculates the response Authenticator based on the clients
2192  * private key.
2193  */
2194 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2195                             char const *secret)
2196 {
2197         uint8_t         calc_digest[AUTH_VECTOR_LEN];
2198         FR_MD5_CTX              context;
2199
2200         /*
2201          *      Very bad!
2202          */
2203         if (original == NULL) {
2204                 return 3;
2205         }
2206
2207         /*
2208          *  Copy the original vector in place.
2209          */
2210         memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2211
2212         /*
2213          *  MD5(packet + secret);
2214          */
2215         fr_md5_init(&context);
2216         fr_md5_update(&context, packet->data, packet->data_len);
2217         fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2218         fr_md5_final(calc_digest, &context);
2219
2220         /*
2221          *  Copy the packet's vector back to the packet.
2222          */
2223         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2224
2225         /*
2226          *      Return 0 if OK, 2 if not OK.
2227          */
2228         if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
2229         return 0;
2230 }
2231
2232 /** Check if a set of RADIUS formatted TLVs are OK
2233  *
2234  */
2235 int rad_tlv_ok(uint8_t const *data, size_t length,
2236                size_t dv_type, size_t dv_length)
2237 {
2238         uint8_t const *end = data + length;
2239
2240         VP_TRACE("checking TLV %u/%u\n", (unsigned int) dv_type, (unsigned int) dv_length);
2241
2242         VP_HEXDUMP("tlv_ok", data, length);
2243
2244         if ((dv_length > 2) || (dv_type == 0) || (dv_type > 4)) {
2245                 fr_strerror_printf("rad_tlv_ok: Invalid arguments");
2246                 return -1;
2247         }
2248
2249         while (data < end) {
2250                 size_t attrlen;
2251
2252                 if ((data + dv_type + dv_length) > end) {
2253                         fr_strerror_printf("Attribute header overflow");
2254                         return -1;
2255                 }
2256
2257                 switch (dv_type) {
2258                 case 4:
2259                         if ((data[0] == 0) && (data[1] == 0) &&
2260                             (data[2] == 0) && (data[3] == 0)) {
2261                         zero:
2262                                 fr_strerror_printf("Invalid attribute 0");
2263                                 return -1;
2264                         }
2265
2266                         if (data[0] != 0) {
2267                                 fr_strerror_printf("Invalid attribute > 2^24");
2268                                 return -1;
2269                         }
2270                         break;
2271
2272                 case 2:
2273                         if ((data[0] == 0) && (data[1] == 0)) goto zero;
2274                         break;
2275
2276                 case 1:
2277                         /*
2278                          *      Zero is allowed, because the Colubris
2279                          *      people are dumb and use it.
2280                          */
2281                         break;
2282
2283                 default:
2284                         fr_strerror_printf("Internal sanity check failed");
2285                         return -1;
2286                 }
2287
2288                 switch (dv_length) {
2289                 case 0:
2290                         return 0;
2291
2292                 case 2:
2293                         if (data[dv_type] != 0) {
2294                                 fr_strerror_printf("Attribute is longer than 256 octets");
2295                                 return -1;
2296                         }
2297                         /* FALL-THROUGH */
2298                 case 1:
2299                         attrlen = data[dv_type + dv_length - 1];
2300                         break;
2301
2302
2303                 default:
2304                         fr_strerror_printf("Internal sanity check failed");
2305                         return -1;
2306                 }
2307
2308                 if (attrlen < (dv_type + dv_length)) {
2309                         fr_strerror_printf("Attribute header has invalid length");
2310                         return -1;
2311                 }
2312
2313                 if (attrlen > length) {
2314                         fr_strerror_printf("Attribute overflows container");
2315                         return -1;
2316                 }
2317
2318                 data += attrlen;
2319                 length -= attrlen;
2320         }
2321
2322         return 0;
2323 }
2324
2325
2326 /** See if the data pointed to by PTR is a valid RADIUS packet.
2327  *
2328  * Packet is not 'const * const' because we may update data_len, if there's more data
2329  * in the UDP packet than in the RADIUS packet.
2330  *
2331  * @param packet to check
2332  * @param flags to control decoding
2333  * @param reason if not NULL, will have the failure reason written to where it points.
2334  * @return bool, true on success, false on failure.
2335  */
2336 bool rad_packet_ok(RADIUS_PACKET *packet, int flags, decode_fail_t *reason)
2337 {
2338         uint8_t                 *attr;
2339         size_t                  totallen;
2340         int                     count;
2341         radius_packet_t         *hdr;
2342         char                    host_ipaddr[128];
2343         bool                    require_ma = false;
2344         bool                    seen_ma = false;
2345         uint32_t                num_attributes;
2346         decode_fail_t           failure = DECODE_FAIL_NONE;
2347         bool                    eap = false;
2348         bool                    non_eap = false;
2349
2350         /*
2351          *      Check for packets smaller than the packet header.
2352          *
2353          *      RFC 2865, Section 3., subsection 'length' says:
2354          *
2355          *      "The minimum length is 20 ..."
2356          */
2357         if (packet->data_len < RADIUS_HDR_LEN) {
2358                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (received %zu < minimum %d)",
2359                            inet_ntop(packet->src_ipaddr.af,
2360                                      &packet->src_ipaddr.ipaddr,
2361                                      host_ipaddr, sizeof(host_ipaddr)),
2362                                      packet->data_len, RADIUS_HDR_LEN);
2363                 failure = DECODE_FAIL_MIN_LENGTH_PACKET;
2364                 goto finish;
2365         }
2366
2367
2368         /*
2369          *      Check for packets with mismatched size.
2370          *      i.e. We've received 128 bytes, and the packet header
2371          *      says it's 256 bytes long.
2372          */
2373         totallen = (packet->data[2] << 8) | packet->data[3];
2374         hdr = (radius_packet_t *)packet->data;
2375
2376         /*
2377          *      Code of 0 is not understood.
2378          *      Code of 16 or greate is not understood.
2379          */
2380         if ((hdr->code == 0) ||
2381             (hdr->code >= FR_MAX_PACKET_CODE)) {
2382                 FR_DEBUG_STRERROR_PRINTF("Bad RADIUS packet from host %s: unknown packet code %d",
2383                            inet_ntop(packet->src_ipaddr.af,
2384                                      &packet->src_ipaddr.ipaddr,
2385                                      host_ipaddr, sizeof(host_ipaddr)),
2386                            hdr->code);
2387                 failure = DECODE_FAIL_UNKNOWN_PACKET_CODE;
2388                 goto finish;
2389         }
2390
2391         /*
2392          *      Message-Authenticator is required in Status-Server
2393          *      packets, otherwise they can be trivially forged.
2394          */
2395         if (hdr->code == PW_CODE_STATUS_SERVER) require_ma = true;
2396
2397         /*
2398          *      It's also required if the caller asks for it.
2399          */
2400         if (flags) require_ma = true;
2401
2402         /*
2403          *      Repeat the length checks.  This time, instead of
2404          *      looking at the data we received, look at the value
2405          *      of the 'length' field inside of the packet.
2406          *
2407          *      Check for packets smaller than the packet header.
2408          *
2409          *      RFC 2865, Section 3., subsection 'length' says:
2410          *
2411          *      "The minimum length is 20 ..."
2412          */
2413         if (totallen < RADIUS_HDR_LEN) {
2414                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (length %zu < minimum %d)",
2415                            inet_ntop(packet->src_ipaddr.af,
2416                                      &packet->src_ipaddr.ipaddr,
2417                                      host_ipaddr, sizeof(host_ipaddr)),
2418                                      totallen, RADIUS_HDR_LEN);
2419                 failure = DECODE_FAIL_MIN_LENGTH_FIELD;
2420                 goto finish;
2421         }
2422
2423         /*
2424          *      And again, for the value of the 'length' field.
2425          *
2426          *      RFC 2865, Section 3., subsection 'length' says:
2427          *
2428          *      " ... and maximum length is 4096."
2429          *
2430          *      HOWEVER.  This requirement is for the network layer.
2431          *      If the code gets here, we assume that a well-formed
2432          *      packet is an OK packet.
2433          *
2434          *      We allow both the UDP data length, and the RADIUS
2435          *      "length" field to contain up to 64K of data.
2436          */
2437
2438         /*
2439          *      RFC 2865, Section 3., subsection 'length' says:
2440          *
2441          *      "If the packet is shorter than the Length field
2442          *      indicates, it MUST be silently discarded."
2443          *
2444          *      i.e. No response to the NAS.
2445          */
2446         if (packet->data_len < totallen) {
2447                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: received %zu octets, packet length says %zu",
2448                            inet_ntop(packet->src_ipaddr.af,
2449                                      &packet->src_ipaddr.ipaddr,
2450                                      host_ipaddr, sizeof(host_ipaddr)),
2451                                      packet->data_len, totallen);
2452                 failure = DECODE_FAIL_MIN_LENGTH_MISMATCH;
2453                 goto finish;
2454         }
2455
2456         /*
2457          *      RFC 2865, Section 3., subsection 'length' says:
2458          *
2459          *      "Octets outside the range of the Length field MUST be
2460          *      treated as padding and ignored on reception."
2461          */
2462         if (packet->data_len > totallen) {
2463                 /*
2464                  *      We're shortening the packet below, but just
2465                  *      to be paranoid, zero out the extra data.
2466                  */
2467                 memset(packet->data + totallen, 0, packet->data_len - totallen);
2468                 packet->data_len = totallen;
2469         }
2470
2471         /*
2472          *      Walk through the packet's attributes, ensuring that
2473          *      they add up EXACTLY to the size of the packet.
2474          *
2475          *      If they don't, then the attributes either under-fill
2476          *      or over-fill the packet.  Any parsing of the packet
2477          *      is impossible, and will result in unknown side effects.
2478          *
2479          *      This would ONLY happen with buggy RADIUS implementations,
2480          *      or with an intentional attack.  Either way, we do NOT want
2481          *      to be vulnerable to this problem.
2482          */
2483         attr = hdr->data;
2484         count = totallen - RADIUS_HDR_LEN;
2485         num_attributes = 0;
2486
2487         while (count > 0) {
2488                 /*
2489                  *      We need at least 2 bytes to check the
2490                  *      attribute header.
2491                  */
2492                 if (count < 2) {
2493                         FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute header overflows the packet",
2494                                    inet_ntop(packet->src_ipaddr.af,
2495                                              &packet->src_ipaddr.ipaddr,
2496                                              host_ipaddr, sizeof(host_ipaddr)));
2497                         failure = DECODE_FAIL_HEADER_OVERFLOW;
2498                         goto finish;
2499                 }
2500
2501                 /*
2502                  *      Attribute number zero is NOT defined.
2503                  */
2504                 if (attr[0] == 0) {
2505                         FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Invalid attribute 0",
2506                                    inet_ntop(packet->src_ipaddr.af,
2507                                              &packet->src_ipaddr.ipaddr,
2508                                              host_ipaddr, sizeof(host_ipaddr)));
2509                         failure = DECODE_FAIL_INVALID_ATTRIBUTE;
2510                         goto finish;
2511                 }
2512
2513                 /*
2514                  *      Attributes are at LEAST as long as the ID & length
2515                  *      fields.  Anything shorter is an invalid attribute.
2516                  */
2517                 if (attr[1] < 2) {
2518                         FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u too short",
2519                                    inet_ntop(packet->src_ipaddr.af,
2520                                              &packet->src_ipaddr.ipaddr,
2521                                              host_ipaddr, sizeof(host_ipaddr)),
2522                                    attr[0]);
2523                         failure = DECODE_FAIL_ATTRIBUTE_TOO_SHORT;
2524                         goto finish;
2525                 }
2526
2527                 /*
2528                  *      If there are fewer bytes in the packet than in the
2529                  *      attribute, it's a bad packet.
2530                  */
2531                 if (count < attr[1]) {
2532                         FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
2533                                    inet_ntop(packet->src_ipaddr.af,
2534                                              &packet->src_ipaddr.ipaddr,
2535                                              host_ipaddr, sizeof(host_ipaddr)),
2536                                            attr[0]);
2537                         failure = DECODE_FAIL_ATTRIBUTE_OVERFLOW;
2538                         goto finish;
2539                 }
2540
2541                 /*
2542                  *      Sanity check the attributes for length.
2543                  */
2544                 switch (attr[0]) {
2545                 default:        /* don't do anything by default */
2546                         break;
2547
2548                         /*
2549                          *      If there's an EAP-Message, we require
2550                          *      a Message-Authenticator.
2551                          */
2552                 case PW_EAP_MESSAGE:
2553                         require_ma = true;
2554                         eap = true;
2555                         break;
2556
2557                 case PW_USER_PASSWORD:
2558                 case PW_CHAP_PASSWORD:
2559                 case PW_ARAP_PASSWORD:
2560                         non_eap = true;
2561                         break;
2562
2563                 case PW_MESSAGE_AUTHENTICATOR:
2564                         if (attr[1] != 2 + AUTH_VECTOR_LEN) {
2565                                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
2566                                            inet_ntop(packet->src_ipaddr.af,
2567                                                      &packet->src_ipaddr.ipaddr,
2568                                                      host_ipaddr, sizeof(host_ipaddr)),
2569                                            attr[1] - 2);
2570                                 failure = DECODE_FAIL_MA_INVALID_LENGTH;
2571                                 goto finish;
2572                         }
2573                         seen_ma = true;
2574                         break;
2575                 }
2576
2577                 /*
2578                  *      FIXME: Look up the base 255 attributes in the
2579                  *      dictionary, and switch over their type.  For
2580                  *      integer/date/ip, the attribute length SHOULD
2581                  *      be 6.
2582                  */
2583                 count -= attr[1];       /* grab the attribute length */
2584                 attr += attr[1];
2585                 num_attributes++;       /* seen one more attribute */
2586         }
2587
2588         /*
2589          *      If the attributes add up to a packet, it's allowed.
2590          *
2591          *      If not, we complain, and throw the packet away.
2592          */
2593         if (count != 0) {
2594                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
2595                            inet_ntop(packet->src_ipaddr.af,
2596                                      &packet->src_ipaddr.ipaddr,
2597                                      host_ipaddr, sizeof(host_ipaddr)));
2598                 failure = DECODE_FAIL_ATTRIBUTE_UNDERFLOW;
2599                 goto finish;
2600         }
2601
2602         /*
2603          *      If we're configured to look for a maximum number of
2604          *      attributes, and we've seen more than that maximum,
2605          *      then throw the packet away, as a possible DoS.
2606          */
2607         if ((fr_max_attributes > 0) &&
2608             (num_attributes > fr_max_attributes)) {
2609                 FR_DEBUG_STRERROR_PRINTF("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2610                            inet_ntop(packet->src_ipaddr.af,
2611                                      &packet->src_ipaddr.ipaddr,
2612                                      host_ipaddr, sizeof(host_ipaddr)),
2613                            num_attributes, fr_max_attributes);
2614                 failure = DECODE_FAIL_TOO_MANY_ATTRIBUTES;
2615                 goto finish;
2616         }
2617
2618         /*
2619          *      http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
2620          *
2621          *      A packet with an EAP-Message attribute MUST also have
2622          *      a Message-Authenticator attribute.
2623          *
2624          *      A Message-Authenticator all by itself is OK, though.
2625          *
2626          *      Similarly, Status-Server packets MUST contain
2627          *      Message-Authenticator attributes.
2628          */
2629         if (require_ma && !seen_ma) {
2630                 FR_DEBUG_STRERROR_PRINTF("Insecure packet from host %s:  Packet does not contain required Message-Authenticator attribute",
2631                            inet_ntop(packet->src_ipaddr.af,
2632                                      &packet->src_ipaddr.ipaddr,
2633                                      host_ipaddr, sizeof(host_ipaddr)));
2634                 failure = DECODE_FAIL_MA_MISSING;
2635                 goto finish;
2636         }
2637
2638         if (eap && non_eap) {
2639                 FR_DEBUG_STRERROR_PRINTF("Bad packet from host %s:  Packet contains EAP-Message and non-EAP authentication attribute",
2640                            inet_ntop(packet->src_ipaddr.af,
2641                                      &packet->src_ipaddr.ipaddr,
2642                                      host_ipaddr, sizeof(host_ipaddr)));
2643                 failure = DECODE_FAIL_TOO_MANY_AUTH;
2644                 goto finish;
2645         }
2646
2647         /*
2648          *      Fill RADIUS header fields
2649          */
2650         packet->code = hdr->code;
2651         packet->id = hdr->id;
2652         memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
2653
2654
2655         finish:
2656
2657         if (reason) {
2658                 *reason = failure;
2659         }
2660         return (failure == DECODE_FAIL_NONE);
2661 }
2662
2663
2664 /** Receive UDP client requests, and fill in the basics of a RADIUS_PACKET structure
2665  *
2666  */
2667 RADIUS_PACKET *rad_recv(TALLOC_CTX *ctx, int fd, int flags)
2668 {
2669         int sock_flags = 0;
2670         ssize_t data_len;
2671         RADIUS_PACKET           *packet;
2672
2673         /*
2674          *      Allocate the new request data structure
2675          */
2676         packet = rad_alloc(ctx, false);
2677         if (!packet) {
2678                 fr_strerror_printf("out of memory");
2679                 return NULL;
2680         }
2681
2682         if (flags & 0x02) {
2683                 sock_flags = MSG_PEEK;
2684                 flags &= ~0x02;
2685         }
2686
2687         data_len = rad_recvfrom(fd, packet, sock_flags,
2688                                 &packet->src_ipaddr, &packet->src_port,
2689                                 &packet->dst_ipaddr, &packet->dst_port);
2690
2691         /*
2692          *      Check for socket errors.
2693          */
2694         if (data_len < 0) {
2695                 FR_DEBUG_STRERROR_PRINTF("Error receiving packet: %s", fr_syserror(errno));
2696                 /* packet->data is NULL */
2697                 rad_free(&packet);
2698                 return NULL;
2699         }
2700         packet->data_len = data_len; /* unsigned vs signed */
2701
2702         /*
2703          *      If the packet is too big, then rad_recvfrom did NOT
2704          *      allocate memory.  Instead, it just discarded the
2705          *      packet.
2706          */
2707         if (packet->data_len > MAX_PACKET_LEN) {
2708                 FR_DEBUG_STRERROR_PRINTF("Discarding packet: Larger than RFC limitation of 4096 bytes");
2709                 /* packet->data is NULL */
2710                 rad_free(&packet);
2711                 return NULL;
2712         }
2713
2714         /*
2715          *      Read no data.  Continue.
2716          *      This check is AFTER the MAX_PACKET_LEN check above, because
2717          *      if the packet is larger than MAX_PACKET_LEN, we also have
2718          *      packet->data == NULL
2719          */
2720         if ((packet->data_len == 0) || !packet->data) {
2721                 FR_DEBUG_STRERROR_PRINTF("Empty packet: Socket is not ready");
2722                 rad_free(&packet);
2723                 return NULL;
2724         }
2725
2726         /*
2727          *      See if it's a well-formed RADIUS packet.
2728          */
2729         if (!rad_packet_ok(packet, flags, NULL)) {
2730                 rad_free(&packet);
2731                 return NULL;
2732         }
2733
2734         /*
2735          *      Remember which socket we read the packet from.
2736          */
2737         packet->sockfd = fd;
2738
2739         /*
2740          *      FIXME: Do even more filtering by only permitting
2741          *      certain IP's.  The problem is that we don't know
2742          *      how to do this properly for all possible clients...
2743          */
2744
2745         /*
2746          *      Explicitely set the VP list to empty.
2747          */
2748         packet->vps = NULL;
2749
2750 #ifndef NDEBUG
2751         if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2752 #endif
2753
2754         return packet;
2755 }
2756
2757
2758 /** Verify the Request/Response Authenticator (and Message-Authenticator if present) of a packet
2759  *
2760  */
2761 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original, char const *secret)
2762 {
2763         uint8_t         *ptr;
2764         int             length;
2765         int             attrlen;
2766         int             rcode;
2767         char            buffer[32];
2768
2769         if (!packet || !packet->data) return -1;
2770
2771         /*
2772          *      Before we allocate memory for the attributes, do more
2773          *      sanity checking.
2774          */
2775         ptr = packet->data + RADIUS_HDR_LEN;
2776         length = packet->data_len - RADIUS_HDR_LEN;
2777         while (length > 0) {
2778                 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2779                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2780
2781                 attrlen = ptr[1];
2782
2783                 switch (ptr[0]) {
2784                 default:        /* don't do anything. */
2785                         break;
2786
2787                         /*
2788                          *      Note that more than one Message-Authenticator
2789                          *      attribute is invalid.
2790                          */
2791                 case PW_MESSAGE_AUTHENTICATOR:
2792                         memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2793                         memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2794
2795                         switch (packet->code) {
2796                         default:
2797                                 break;
2798
2799                         case PW_CODE_ACCOUNTING_RESPONSE:
2800                                 if (original &&
2801                                     (original->code == PW_CODE_STATUS_SERVER)) {
2802                                         goto do_ack;
2803                                 }
2804
2805                         case PW_CODE_ACCOUNTING_REQUEST:
2806                         case PW_CODE_DISCONNECT_REQUEST:
2807                         case PW_CODE_COA_REQUEST:
2808                                 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2809                                 break;
2810
2811                         do_ack:
2812                         case PW_CODE_ACCESS_ACCEPT:
2813                         case PW_CODE_ACCESS_REJECT:
2814                         case PW_CODE_ACCESS_CHALLENGE:
2815                         case PW_CODE_DISCONNECT_ACK:
2816                         case PW_CODE_DISCONNECT_NAK:
2817                         case PW_CODE_COA_ACK:
2818                         case PW_CODE_COA_NAK:
2819                                 if (!original) {
2820                                         fr_strerror_printf("Cannot validate Message-Authenticator in response "
2821                                                            "packet without a request packet");
2822                                         return -1;
2823                                 }
2824                                 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2825                                 break;
2826                         }
2827
2828                         fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
2829                                     (uint8_t const *) secret, strlen(secret));
2830                         if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2831                                    sizeof(calc_auth_vector)) != 0) {
2832                                 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator!  "
2833                                                    "(Shared secret is incorrect.)",
2834                                                    inet_ntop(packet->src_ipaddr.af,
2835                                                              &packet->src_ipaddr.ipaddr,
2836                                                              buffer, sizeof(buffer)));
2837                                 /* Silently drop packet, according to RFC 3579 */
2838                                 return -1;
2839                         } /* else the message authenticator was good */
2840
2841                         /*
2842                          *      Reinitialize Authenticators.
2843                          */
2844                         memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2845                         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2846                         break;
2847                 } /* switch over the attributes */
2848
2849                 ptr += attrlen;
2850                 length -= attrlen;
2851         } /* loop over the packet, sanity checking the attributes */
2852
2853         /*
2854          *      It looks like a RADIUS packet, but we don't know what it is
2855          *      so can't validate the authenticators.
2856          */
2857         if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2858                 fr_strerror_printf("Received Unknown packet code %d "
2859                                    "from client %s port %d: Cannot validate Request/Response Authenticator.",
2860                                    packet->code,
2861                                    inet_ntop(packet->src_ipaddr.af,
2862                                              &packet->src_ipaddr.ipaddr,
2863                                              buffer, sizeof(buffer)),
2864                                    packet->src_port);
2865                 return -1;
2866         }
2867
2868         /*
2869          *      Calculate and/or verify Request or Response Authenticator.
2870          */
2871         switch (packet->code) {
2872         case PW_CODE_ACCESS_REQUEST:
2873         case PW_CODE_STATUS_SERVER:
2874                 /*
2875                  *      The authentication vector is random
2876                  *      nonsense, invented by the client.
2877                  */
2878                 break;
2879
2880         case PW_CODE_COA_REQUEST:
2881         case PW_CODE_DISCONNECT_REQUEST:
2882         case PW_CODE_ACCOUNTING_REQUEST:
2883                 if (calc_acctdigest(packet, secret) > 1) {
2884                         fr_strerror_printf("Received %s packet "
2885                                            "from client %s with invalid Request Authenticator!  "
2886                                            "(Shared secret is incorrect.)",
2887                                            fr_packet_codes[packet->code],
2888                                            inet_ntop(packet->src_ipaddr.af,
2889                                                      &packet->src_ipaddr.ipaddr,
2890                                                      buffer, sizeof(buffer)));
2891                         return -1;
2892                 }
2893                 break;
2894
2895                 /* Verify the reply digest */
2896         case PW_CODE_ACCESS_ACCEPT:
2897         case PW_CODE_ACCESS_REJECT:
2898         case PW_CODE_ACCESS_CHALLENGE:
2899         case PW_CODE_ACCOUNTING_RESPONSE:
2900         case PW_CODE_DISCONNECT_ACK:
2901         case PW_CODE_DISCONNECT_NAK:
2902         case PW_CODE_COA_ACK:
2903         case PW_CODE_COA_NAK:
2904                 rcode = calc_replydigest(packet, original, secret);
2905                 if (rcode > 1) {
2906                         fr_strerror_printf("Received %s packet "
2907                                            "from home server %s port %d with invalid Response Authenticator!  "
2908                                            "(Shared secret is incorrect.)",
2909                                            fr_packet_codes[packet->code],
2910                                            inet_ntop(packet->src_ipaddr.af,
2911                                                      &packet->src_ipaddr.ipaddr,
2912                                                      buffer, sizeof(buffer)),
2913                                            packet->src_port);
2914                         return -1;
2915                 }
2916                 break;
2917
2918         default:
2919                 fr_strerror_printf("Received Unknown packet code %d "
2920                                    "from client %s port %d: Cannot validate Request/Response Authenticator",
2921                                    packet->code,
2922                                    inet_ntop(packet->src_ipaddr.af,
2923                                              &packet->src_ipaddr.ipaddr,
2924                                              buffer, sizeof(buffer)),
2925                                    packet->src_port);
2926                 return -1;
2927         }
2928
2929         return 0;
2930 }
2931
2932
2933 /** Convert a "concatenated" attribute to one long VP
2934  *
2935  */
2936 static ssize_t data2vp_concat(TALLOC_CTX *ctx,
2937                               DICT_ATTR const *da, uint8_t const *start,
2938                               size_t const packetlen, VALUE_PAIR **pvp)
2939 {
2940         size_t total;
2941         uint8_t attr;
2942         uint8_t const *ptr = start;
2943         uint8_t const *end = start + packetlen;
2944         uint8_t *p;
2945         VALUE_PAIR *vp;
2946
2947         total = 0;
2948         attr = ptr[0];
2949
2950         /*
2951          *      The packet has already been sanity checked, so we
2952          *      don't care about walking off of the end of it.
2953          */
2954         while (ptr < end) {
2955                 total += ptr[1] - 2;
2956
2957                 ptr += ptr[1];
2958
2959                 /*
2960                  *      Attributes MUST be consecutive.
2961                  */
2962                 if (ptr[0] != attr) break;
2963         }
2964
2965         vp = fr_pair_afrom_da(ctx, da);
2966         if (!vp) return -1;
2967
2968         vp->vp_length = total;
2969         vp->vp_octets = p = talloc_array(vp, uint8_t, vp->vp_length);
2970         if (!p) {
2971                 fr_pair_list_free(&vp);
2972                 return -1;
2973         }
2974
2975         total = 0;
2976         ptr = start;
2977         while (total < vp->vp_length) {
2978                 memcpy(p, ptr + 2, ptr[1] - 2);
2979                 p += ptr[1] - 2;
2980                 total += ptr[1] - 2;
2981                 ptr += ptr[1];
2982         }
2983
2984         *pvp = vp;
2985         return ptr - start;
2986 }
2987
2988
2989 /** Convert TLVs to one or more VPs
2990  *
2991  */
2992 ssize_t rad_data2vp_tlvs(TALLOC_CTX *ctx,
2993                             RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2994                             char const *secret, DICT_ATTR const *da,
2995                             uint8_t const *start, size_t length,
2996                             VALUE_PAIR **pvp)
2997 {
2998         uint8_t const *data = start;
2999         DICT_ATTR const *child;
3000         VALUE_PAIR *head, **tail;
3001
3002         if (length < 3) return -1; /* type, length, value */
3003
3004         VP_HEXDUMP("tlvs", data, length);
3005
3006         if (rad_tlv_ok(data, length, 1, 1) < 0) return -1;
3007
3008         head = NULL;
3009         tail = &head;
3010
3011         while (data < (start + length)) {
3012                 ssize_t tlv_len;
3013
3014                 child = dict_attrbyparent(da, data[0], da->vendor);
3015                 if (!child) {
3016                         unsigned int my_attr, my_vendor;
3017
3018                         VP_TRACE("Failed to find child %u of TLV %s\n",
3019                                  data[0], da->name);
3020
3021                         /*
3022                          *      Get child attr/vendor so that
3023                          *      we can call unknown attr.
3024                          */
3025                         my_attr = data[0];
3026                         my_vendor = da->vendor;
3027
3028                         if (!dict_attr_child(da, &my_attr, &my_vendor)) {
3029                                 fr_pair_list_free(&head);
3030                                 return -1;
3031                         }
3032
3033                         child = dict_unknown_afrom_fields(ctx, my_attr, my_vendor);
3034                         if (!child) {
3035                                 fr_pair_list_free(&head);
3036                                 return -1;
3037                         }
3038                 }
3039
3040                 tlv_len = data2vp(ctx, packet, original, secret, child,
3041                                   data + 2, data[1] - 2, data[1] - 2, tail);
3042                 if (tlv_len < 0) {
3043                         fr_pair_list_free(&head);
3044                         return -1;
3045                 }
3046                 if (*tail) tail = &((*tail)->next);
3047                 data += data[1];
3048         }
3049
3050         *pvp = head;
3051         return length;
3052 }
3053
3054 /** Convert a top-level VSA to a VP.
3055  *
3056  * "length" can be LONGER than just this sub-vsa.
3057  */
3058 static ssize_t data2vp_vsa(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3059                            RADIUS_PACKET const *original,
3060                            char const *secret, DICT_VENDOR *dv,
3061                            uint8_t const *data, size_t length,
3062                            VALUE_PAIR **pvp)
3063 {
3064         unsigned int attribute;
3065         ssize_t attrlen, my_len;
3066         DICT_ATTR const *da;
3067
3068         VP_TRACE("data2vp_vsa: length %u\n", (unsigned int) length);
3069
3070 #ifndef NDEBUG
3071         if (length <= (dv->type + dv->length)) {
3072                 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
3073                 return -1;
3074         }
3075 #endif
3076
3077         switch (dv->type) {
3078         case 4:
3079                 /* data[0] must be zero */
3080                 attribute = data[1] << 16;
3081                 attribute |= data[2] << 8;
3082                 attribute |= data[3];
3083                 break;
3084
3085         case 2:
3086                 attribute = data[0] << 8;
3087                 attribute |= data[1];
3088                 break;
3089
3090         case 1:
3091                 attribute = data[0];
3092                 break;
3093
3094         default:
3095                 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3096                 return -1;
3097         }
3098
3099         switch (dv->length) {
3100         case 2:
3101                 /* data[dv->type] must be zero, from rad_tlv_ok() */
3102                 attrlen = data[dv->type + 1];
3103                 break;
3104
3105         case 1:
3106                 attrlen = data[dv->type];
3107                 break;
3108
3109         case 0:
3110                 attrlen = length;
3111                 break;
3112
3113         default:
3114                 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3115                 return -1;
3116         }
3117
3118         /*
3119          *      See if the VSA is known.
3120          */
3121         da = dict_attrbyvalue(attribute, dv->vendorpec);
3122         if (!da) da = dict_unknown_afrom_fields(ctx, attribute, dv->vendorpec);
3123         if (!da) return -1;
3124
3125         my_len = data2vp(ctx, packet, original, secret, da,
3126                          data + dv->type + dv->length,
3127                          attrlen - (dv->type + dv->length),
3128                          attrlen - (dv->type + dv->length),
3129                          pvp);
3130         if (my_len < 0) return my_len;
3131
3132         return attrlen;
3133 }
3134
3135
3136 /** Convert a fragmented extended attr to a VP
3137  *
3138  * Format is:
3139  *
3140  * attr
3141  * length
3142  * extended-attr
3143  * flag
3144  * data...
3145  *
3146  * But for the first fragment, we get passed a pointer to the "extended-attr"
3147  */
3148 static ssize_t data2vp_extended(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3149                                 RADIUS_PACKET const *original,
3150                                 char const *secret, DICT_ATTR const *da,
3151                                 uint8_t const *data,
3152                                 size_t attrlen, size_t packetlen,
3153                                 VALUE_PAIR **pvp)
3154 {
3155         ssize_t rcode;
3156         size_t fraglen;
3157         uint8_t *head, *tail;
3158         uint8_t const *frag, *end;
3159         uint8_t const *attr;
3160         int fragments;
3161         bool last_frag;
3162
3163         if (attrlen < 3) return -1;
3164
3165         /*
3166          *      Calculate the length of all of the fragments.  For
3167          *      now, they MUST be contiguous in the packet, and they
3168          *      MUST be all of the same TYPE and EXTENDED-TYPE
3169          */
3170         attr = data - 2;
3171         fraglen = attrlen - 2;
3172         frag = data + attrlen;
3173         end = data + packetlen;
3174         fragments = 1;
3175         last_frag = false;
3176
3177         while (frag < end) {
3178                 if (last_frag ||
3179                     (frag[0] != attr[0]) ||
3180                     (frag[1] < 4) ||                   /* too short for long-extended */
3181                     (frag[2] != attr[2]) ||
3182                     ((frag + frag[1]) > end)) {         /* overflow */
3183                         end = frag;
3184                         break;
3185                 }
3186
3187                 last_frag = ((frag[3] & 0x80) == 0);
3188
3189                 fraglen += frag[1] - 4;
3190                 frag += frag[1];
3191                 fragments++;
3192         }
3193
3194         head = tail = malloc(fraglen);
3195         if (!head) return -1;
3196
3197         VP_TRACE("Fragments %d, total length %d\n", fragments, (int) fraglen);
3198
3199         /*
3200          *      And again, but faster and looser.
3201          *
3202          *      We copy the first fragment, followed by the rest of
3203          *      the fragments.
3204          */
3205         frag = attr;
3206
3207         while (fragments >  0) {
3208                 memcpy(tail, frag + 4, frag[1] - 4);
3209                 tail += frag[1] - 4;
3210                 frag += frag[1];
3211                 fragments--;
3212         }
3213
3214         VP_HEXDUMP("long-extended fragments", head, fraglen);
3215
3216         rcode = data2vp(ctx, packet, original, secret, da,
3217                         head, fraglen, fraglen, pvp);
3218         free(head);
3219         if (rcode < 0) return rcode;
3220
3221         return end - data;
3222 }
3223
3224 /** Convert a Vendor-Specific WIMAX to vps
3225  *
3226  * @note Called ONLY for Vendor-Specific
3227  */
3228 static ssize_t data2vp_wimax(TALLOC_CTX *ctx,
3229                              RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3230                              char const *secret, uint32_t vendor,
3231                              uint8_t const *data,
3232                              size_t attrlen, size_t packetlen,
3233                              VALUE_PAIR **pvp)
3234 {
3235         ssize_t rcode;
3236         size_t fraglen;
3237         bool last_frag;
3238         uint8_t *head, *tail;
3239         uint8_t const *frag, *end;
3240         DICT_ATTR const *child;
3241
3242         if (attrlen < 8) return -1;
3243
3244         if (((size_t) (data[5] + 4)) != attrlen) return -1;
3245
3246         child = dict_attrbyvalue(data[4], vendor);
3247         if (!child) return -1;
3248
3249         if ((data[6] & 0x80) == 0) {
3250                 rcode = data2vp(ctx, packet, original, secret, child,
3251                                 data + 7, data[5] - 3, data[5] - 3,
3252                                 pvp);
3253                 if (rcode < 0) return -1;
3254                 return 7 + rcode;
3255         }
3256
3257         /*
3258          *      Calculate the length of all of the fragments.  For
3259          *      now, they MUST be contiguous in the packet, and they
3260          *      MUST be all of the same VSA, WiMAX, and WiMAX-attr.
3261          *
3262          *      The first fragment doesn't have a RADIUS attribute
3263          *      header, so it needs to be treated a little special.
3264          */
3265         fraglen = data[5] - 3;
3266         frag = data + attrlen;
3267         end = data + packetlen;
3268         last_frag = false;
3269
3270         while (frag < end) {
3271                 if (last_frag ||
3272                     (frag[0] != PW_VENDOR_SPECIFIC) ||
3273                     (frag[1] < 9) ||                   /* too short for wimax */
3274                     ((frag + frag[1]) > end) ||         /* overflow */
3275                     (memcmp(frag + 2, data, 4) != 0) || /* not wimax */
3276                     (frag[6] != data[4]) || /* not the same wimax attr */
3277                     ((frag[7] + 6) != frag[1])) { /* doesn't fill the attr */
3278                         end = frag;
3279                         break;
3280                 }
3281
3282                 last_frag = ((frag[8] & 0x80) == 0);
3283
3284                 fraglen += frag[7] - 3;
3285                 frag += frag[1];
3286         }
3287
3288         head = tail = malloc(fraglen);
3289         if (!head) return -1;
3290
3291         /*
3292          *      And again, but faster and looser.
3293          *
3294          *      We copy the first fragment, followed by the rest of
3295          *      the fragments.
3296          */
3297         frag = data;
3298
3299         memcpy(tail, frag + 4 + 3, frag[4 + 1] - 3);
3300         tail += frag[4 + 1] - 3;
3301         frag += attrlen;        /* should be frag[1] - 7 */
3302
3303         /*
3304          *      frag now points to RADIUS attributes
3305          */
3306         do {
3307                 memcpy(tail, frag + 2 + 4 + 3, frag[2 + 4 + 1] - 3);
3308                 tail += frag[2 + 4 + 1] - 3;
3309                 frag += frag[1];
3310         } while (frag < end);
3311
3312         VP_HEXDUMP("wimax fragments", head, fraglen);
3313
3314         rcode = data2vp(ctx, packet, original, secret, child,
3315                         head, fraglen, fraglen, pvp);
3316         free(head);
3317         if (rcode < 0) return rcode;
3318
3319         return end - data;
3320 }
3321
3322
3323 /** Convert a top-level VSA to one or more VPs
3324  *
3325  */
3326 static ssize_t data2vp_vsas(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3327                             RADIUS_PACKET const *original,
3328                             char const *secret, uint8_t const *data,
3329                             size_t attrlen, size_t packetlen,
3330                             VALUE_PAIR **pvp)
3331 {
3332         size_t total;
3333         ssize_t rcode;
3334         uint32_t vendor;
3335         DICT_VENDOR *dv;
3336         VALUE_PAIR *head, **tail;
3337         DICT_VENDOR my_dv;
3338
3339         if (attrlen > packetlen) return -1;
3340         if (attrlen < 5) return -1; /* vid, value */
3341         if (data[0] != 0) return -1; /* we require 24-bit VIDs */
3342
3343         VP_TRACE("data2vp_vsas\n");
3344
3345         memcpy(&vendor, data, 4);
3346         vendor = ntohl(vendor);
3347         dv = dict_vendorbyvalue(vendor);
3348         if (!dv) {
3349                 /*
3350                  *      RFC format is 1 octet type, 1 octet length
3351                  */
3352                 if (rad_tlv_ok(data + 4, attrlen - 4, 1, 1) < 0) {
3353                         VP_TRACE("data2vp_vsas: unknown tlvs not OK: %s\n", fr_strerror());
3354                         return -1;
3355                 }
3356
3357                 /*
3358                  *      It's a known unknown.
3359                  */
3360                 memset(&my_dv, 0, sizeof(my_dv));
3361                 dv = &my_dv;
3362
3363                 /*
3364                  *      Fill in the fields.  Note that the name is empty!
3365                  */
3366                 dv->vendorpec = vendor;
3367                 dv->type = 1;
3368                 dv->length = 1;
3369
3370                 goto create_attrs;
3371         }
3372
3373         /*
3374          *      WiMAX craziness
3375          */
3376         if ((vendor == VENDORPEC_WIMAX) && dv->flags) {
3377                 rcode = data2vp_wimax(ctx, packet, original, secret, vendor,
3378                                       data, attrlen, packetlen, pvp);
3379                 return rcode;
3380         }
3381
3382         /*
3383          *      VSAs should normally be in TLV format.
3384          */
3385         if (rad_tlv_ok(data + 4, attrlen - 4,
3386                        dv->type, dv->length) < 0) {
3387                 VP_TRACE("data2vp_vsas: tlvs not OK: %s\n", fr_strerror());
3388                 return -1;
3389         }
3390
3391         /*
3392          *      There may be more than one VSA in the
3393          *      Vendor-Specific.  If so, loop over them all.
3394          */
3395 create_attrs:
3396         data += 4;
3397         attrlen -= 4;
3398         packetlen -= 4;
3399         total = 4;
3400         head = NULL;
3401         tail = &head;
3402
3403         while (attrlen > 0) {
3404                 ssize_t vsa_len;
3405
3406                 vsa_len = data2vp_vsa(ctx, packet, original, secret, dv,
3407                                       data, attrlen, tail);
3408                 if (vsa_len < 0) {
3409                         fr_pair_list_free(&head);
3410                         fr_strerror_printf("Internal sanity check %d", __LINE__);
3411                         return -1;
3412                 }
3413
3414                 /*
3415                  *      Vendors can send zero-length VSAs.
3416                  */
3417                 if (*tail) tail = &((*tail)->next);
3418
3419                 data += vsa_len;
3420                 attrlen -= vsa_len;
3421                 packetlen -= vsa_len;
3422                 total += vsa_len;
3423         }
3424
3425         *pvp = head;
3426         return total;
3427 }
3428
3429 /** Create any kind of VP from the attribute contents
3430  *
3431  * "length" is AT LEAST the length of this attribute, as we
3432  * expect the caller to have verified the data with
3433  * rad_packet_ok().  "length" may be up to the length of the
3434  * packet.
3435  *
3436  * @return -1 on error, or "length".
3437  */
3438 ssize_t data2vp(TALLOC_CTX *ctx,
3439                 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3440                 char const *secret,
3441                 DICT_ATTR const *da, uint8_t const *start,
3442                 size_t const attrlen, size_t const packetlen,
3443                 VALUE_PAIR **pvp)
3444 {
3445         int8_t tag = TAG_NONE;
3446         size_t datalen;
3447         ssize_t rcode;
3448         uint32_t vendor;
3449         DICT_ATTR const *child;
3450         VALUE_PAIR *vp;
3451         uint8_t const *data = start;
3452         char *p;
3453         uint8_t buffer[256];
3454
3455         /*
3456          *      FIXME: Attrlen can be larger than 253 for extended attrs!
3457          */
3458         if (!da || (attrlen > packetlen) ||
3459             ((attrlen > 253) && (attrlen != packetlen)) ||
3460             (attrlen > 128*1024)) {
3461                 fr_strerror_printf("data2vp: invalid arguments");
3462                 return -1;
3463         }
3464
3465         VP_HEXDUMP("data2vp", start, attrlen);
3466
3467         VP_TRACE("parent %s len %zu ... %zu\n", da->name, attrlen, packetlen);
3468
3469         datalen = attrlen;
3470
3471         /*
3472          *      Hacks for CUI.  The WiMAX spec says that it can be
3473          *      zero length, even though this is forbidden by the
3474          *      RADIUS specs.  So... we make a special case for it.
3475          */
3476         if (attrlen == 0) {
3477                 if (!((da->vendor == 0) &&
3478                       (da->attr == PW_CHARGEABLE_USER_IDENTITY))) {
3479                         *pvp = NULL;
3480                         return 0;
3481                 }
3482
3483 #ifndef NDEBUG
3484                 /*
3485                  *      Hacks for Coverity.  Editing the dictionary
3486                  *      will break assumptions about CUI.  We know
3487                  *      this, but Coverity doesn't.
3488                  */
3489                 if (da->type != PW_TYPE_OCTETS) return -1;
3490 #endif
3491
3492                 data = NULL;
3493                 datalen = 0;
3494                 goto alloc_cui; /* skip everything */
3495         }
3496
3497         /*
3498          *      Hacks for tags.  If the attribute is capable of
3499          *      encoding a tag, and there's room for the tag, and
3500          *      there is a tag, or it's encrypted with Tunnel-Password,
3501          *      then decode the tag.
3502          */
3503         if (da->flags.has_tag && (datalen > 1) &&
3504             ((data[0] < 0x20) ||
3505              (da->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
3506                 /*
3507                  *      Only "short" attributes can be encrypted.
3508                  */
3509                 if (datalen >= sizeof(buffer)) return -1;
3510
3511                 if (da->type == PW_TYPE_STRING) {
3512                         memcpy(buffer, data + 1, datalen - 1);
3513                         tag = data[0];
3514                         datalen -= 1;
3515
3516                 } else if (da->type == PW_TYPE_INTEGER) {
3517                         memcpy(buffer, data, attrlen);
3518                         tag = buffer[0];
3519                         buffer[0] = 0;
3520
3521                 } else {
3522                         return -1; /* only string and integer can have tags */
3523                 }
3524
3525                 data = buffer;
3526         }
3527
3528         /*
3529          *      Decrypt the attribute.
3530          */
3531         if (secret && packet && (da->flags.encrypt != FLAG_ENCRYPT_NONE)) {
3532                 VP_TRACE("data2vp: decrypting type %u\n", da->flags.encrypt);
3533                 /*
3534                  *      Encrypted attributes can only exist for the
3535                  *      old-style format.  Extended attributes CANNOT
3536                  *      be encrypted.
3537                  */
3538                 if (attrlen > 253) {
3539                         return -1;
3540                 }
3541
3542                 if (data == start) {
3543                         memcpy(buffer, data, attrlen);
3544                 }
3545                 data = buffer;
3546
3547                 switch (da->flags.encrypt) { /* can't be tagged */
3548                 /*
3549                  *  User-Password
3550                  */
3551                 case FLAG_ENCRYPT_USER_PASSWORD:
3552                         if (original) {
3553                                 rad_pwdecode((char *) buffer,
3554                                              attrlen, secret,
3555                                              original->vector);
3556                         } else {
3557                                 rad_pwdecode((char *) buffer,
3558                                              attrlen, secret,
3559                                              packet->vector);
3560                         }
3561                         buffer[253] = '\0';
3562
3563                         /*
3564                          *      MS-CHAP-MPPE-Keys are 24 octets, and
3565                          *      encrypted.  Since it's binary, we can't
3566                          *      look for trailing zeros.
3567                          */
3568                         if (da->flags.length) {
3569                                 if (datalen > da->flags.length) {
3570                                         datalen = da->flags.length;
3571                                 } /* else leave datalen alone */
3572                         } else {
3573                                 /*
3574                                  *      Take off trailing zeros from the END.
3575                                  *      This allows passwords to have zeros in
3576                                  *      the middle of a field.
3577                                  *
3578                                  *      However, if the password has a zero at
3579                                  *      the end, it will get mashed by this
3580                                  *      code.  There's really no way around
3581                                  *      that.
3582                                  */
3583                                 while ((datalen > 0) && (buffer[datalen - 1] == '\0')) datalen--;
3584                         }
3585                         break;
3586
3587                 /*
3588                  *      Tunnel-Password's may go ONLY in response
3589                  *      packets.  They can have a tag, so datalen is
3590                  *      not the same as attrlen.
3591                  */
3592                 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
3593                         if (rad_tunnel_pwdecode(buffer, &datalen, secret,
3594                                                 original ? original->vector : nullvector) < 0) {
3595                                 goto raw;
3596                         }
3597                         break;
3598
3599                 /*
3600                  *  Ascend-Send-Secret
3601                  *  Ascend-Receive-Secret
3602                  */
3603                 case FLAG_ENCRYPT_ASCEND_SECRET:
3604                         if (!original) {
3605                                 goto raw;
3606                         } else {
3607                                 uint8_t my_digest[AUTH_VECTOR_LEN];
3608                                 make_secret(my_digest,
3609                                             original->vector,
3610                                             secret, data);
3611                                 memcpy(buffer, my_digest,
3612                                        AUTH_VECTOR_LEN );
3613                                 buffer[AUTH_VECTOR_LEN] = '\0';
3614                                 datalen = strlen((char *) buffer);
3615                         }
3616                         break;
3617
3618                 default:
3619                         break;
3620                 } /* switch over encryption flags */
3621         }
3622
3623         /*
3624          *      Double-check the length after decrypting the
3625          *      attribute.
3626          */
3627         VP_TRACE("data2vp: type %u\n", da->type);
3628         switch (da->type) {
3629         case PW_TYPE_STRING:
3630         case PW_TYPE_OCTETS:
3631                 break;
3632
3633         case PW_TYPE_ABINARY:
3634                 if (datalen > sizeof(vp->vp_filter)) goto raw;
3635                 break;
3636
3637         case PW_TYPE_INTEGER:
3638         case PW_TYPE_IPV4_ADDR:
3639         case PW_TYPE_DATE:
3640         case PW_TYPE_SIGNED:
3641                 if (datalen != 4) goto raw;
3642                 break;
3643
3644         case PW_TYPE_INTEGER64:
3645         case PW_TYPE_IFID:
3646                 if (datalen != 8) goto raw;
3647                 break;
3648
3649         case PW_TYPE_IPV6_ADDR:
3650                 if (datalen != 16) goto raw;
3651                 break;
3652
3653         case PW_TYPE_IPV6_PREFIX:
3654                 if ((datalen < 2) || (datalen > 18)) goto raw;
3655                 if (data[1] > 128) goto raw;
3656                 break;
3657
3658         case PW_TYPE_BYTE:
3659                 if (datalen != 1) goto raw;
3660                 break;
3661
3662         case PW_TYPE_SHORT:
3663                 if (datalen != 2) goto raw;
3664                 break;
3665
3666         case PW_TYPE_ETHERNET:
3667                 if (datalen != 6) goto raw;
3668                 break;
3669
3670         case PW_TYPE_COMBO_IP_ADDR:
3671                 if (datalen == 4) {
3672                         child = dict_attrbytype(da->attr, da->vendor,
3673                                                 PW_TYPE_IPV4_ADDR);
3674                 } else if (datalen == 16) {
3675                         child = dict_attrbytype(da->attr, da->vendor,
3676                                              PW_TYPE_IPV6_ADDR);
3677                 } else {
3678                         goto raw;
3679                 }
3680                 if (!child) goto raw;
3681                 da = child;     /* re-write it */
3682                 break;
3683
3684         case PW_TYPE_IPV4_PREFIX:
3685                 if (datalen != 6) goto raw;
3686                 if ((data[1] & 0x3f) > 32) goto raw;
3687                 break;
3688
3689                 /*
3690                  *      The rest of the data types can cause
3691                  *      recursion!  Ask yourself, "is recursion OK?"
3692                  */
3693
3694         case PW_TYPE_EXTENDED:
3695                 if (datalen < 2) goto raw; /* etype, value */
3696
3697                 child = dict_attrbyparent(da, data[0], 0);
3698                 if (!child) goto raw;
3699
3700                 /*
3701                  *      Recurse to decode the contents, which could be
3702                  *      a TLV, IPaddr, etc.  Note that we decode only
3703                  *      the current attribute, and we ignore any extra
3704                  *      data after it.
3705                  */
3706                 rcode = data2vp(ctx, packet, original, secret, child,
3707                                 data + 1, attrlen - 1, attrlen - 1, pvp);
3708                 if (rcode < 0) goto raw;
3709                 return 1 + rcode;
3710
3711         case PW_TYPE_LONG_EXTENDED:
3712                 if (datalen < 3) goto raw; /* etype, flags, value */
3713
3714                 child = dict_attrbyparent(da, data[0], 0);
3715                 if (!child) {
3716                         if ((data[0] != PW_VENDOR_SPECIFIC) ||
3717                             (datalen < (3 + 4 + 1))) {
3718                                 /* da->attr < 255, da->vendor == 0 */
3719                                 child = dict_unknown_afrom_fields(ctx, data[0], da->attr * FR_MAX_VENDOR);
3720                         } else {
3721                                 /*
3722                                  *      Try to find the VSA.
3723                                  */
3724                                 memcpy(&vendor, data + 3, 4);
3725                                 vendor = ntohl(vendor);
3726
3727                                 if (vendor == 0) goto raw;
3728
3729                                 child = dict_unknown_afrom_fields(ctx, data[7], vendor | (da->attr * FR_MAX_VENDOR));
3730                         }
3731
3732                         if (!child) {
3733                                 fr_strerror_printf("Internal sanity check %d", __LINE__);
3734                                 return -1;
3735                         }
3736                 }
3737
3738                 /*
3739                  *      If there no more fragments, then the contents
3740                  *      have to be a well-known data type.
3741                  *
3742                  */
3743                 if ((data[1] & 0x80) == 0) {
3744                         rcode = data2vp(ctx, packet, original, secret, child,
3745                                         data + 2, attrlen - 2, attrlen - 2,
3746                                         pvp);
3747                         if (rcode < 0) goto raw;
3748                         return 2 + rcode;
3749                 }
3750
3751                 /*
3752                  *      This requires a whole lot more work.
3753                  */
3754                 return data2vp_extended(ctx, packet, original, secret, child,
3755                                         start, attrlen, packetlen, pvp);
3756
3757         case PW_TYPE_EVS:
3758                 if (datalen < 6) goto raw; /* vid, vtype, value */
3759
3760                 if (data[0] != 0) goto raw; /* we require 24-bit VIDs */
3761
3762                 memcpy(&vendor, data, 4);
3763                 vendor = ntohl(vendor);
3764                 vendor |= da->vendor;
3765
3766                 child = dict_attrbyvalue(data[4], vendor);
3767                 if (!child) {
3768                         /*
3769                          *      Create a "raw" attribute from the
3770                          *      contents of the EVS VSA.
3771                          */
3772                         da = dict_unknown_afrom_fields(ctx, data[4], vendor);
3773                         data += 5;
3774                         datalen -= 5;
3775                         break;
3776                 }
3777
3778                 rcode = data2vp(ctx, packet, original, secret, child,
3779                                 data + 5, attrlen - 5, attrlen - 5, pvp);
3780                 if (rcode < 0) goto raw;
3781                 return 5 + rcode;
3782
3783         case PW_TYPE_TLV:
3784                 /*
3785                  *      We presume that the TLVs all fit into one
3786                  *      attribute, OR they've already been grouped
3787                  *      into a contiguous memory buffer.
3788                  */
3789                 rcode = rad_data2vp_tlvs(ctx, packet, original, secret, da,
3790                                          data, attrlen, pvp);
3791                 if (rcode < 0) goto raw;
3792                 return rcode;
3793
3794         case PW_TYPE_VSA:
3795                 /*
3796                  *      VSAs can be WiMAX, in which case they don't
3797                  *      fit into one attribute.
3798                  */
3799                 rcode = data2vp_vsas(ctx, packet, original, secret,
3800                                      data, attrlen, packetlen, pvp);
3801                 if (rcode < 0) goto raw;
3802                 return rcode;
3803
3804         default:
3805         raw:
3806                 /*
3807                  *      Re-write the attribute to be "raw".  It is
3808                  *      therefore of type "octets", and will be
3809                  *      handled below.
3810                  */
3811                 da = dict_unknown_afrom_fields(ctx, da->attr, da->vendor);
3812                 if (!da) {
3813                         fr_strerror_printf("Internal sanity check %d", __LINE__);
3814                         return -1;
3815                 }
3816                 tag = TAG_NONE;
3817 #ifndef NDEBUG
3818                 /*
3819                  *      Fix for Coverity.
3820                  */
3821                 if (da->type != PW_TYPE_OCTETS) {
3822                         dict_attr_free(&da);
3823                         return -1;
3824                 }
3825 #endif
3826                 break;
3827         }
3828
3829         /*
3830          *      And now that we've verified the basic type
3831          *      information, decode the actual data.
3832          */
3833  alloc_cui:
3834         vp = fr_pair_afrom_da(ctx, da);
3835         if (!vp) return -1;
3836
3837         vp->vp_length = datalen;
3838         vp->tag = tag;
3839
3840         switch (da->type) {
3841         case PW_TYPE_STRING:
3842                 p = talloc_array(vp, char, vp->vp_length + 1);
3843                 memcpy(p, data, vp->vp_length);
3844                 p[vp->vp_length] = '\0';
3845                 vp->vp_strvalue = p;
3846                 break;
3847
3848         case PW_TYPE_OCTETS:
3849                 fr_pair_value_memcpy(vp, data, vp->vp_length);
3850                 break;
3851
3852         case PW_TYPE_ABINARY:
3853                 if (vp->vp_length > sizeof(vp->vp_filter)) {
3854                         vp->vp_length = sizeof(vp->vp_filter);
3855                 }
3856                 memcpy(vp->vp_filter, data, vp->vp_length);
3857                 break;
3858
3859         case PW_TYPE_BYTE:
3860                 vp->vp_byte = data[0];
3861                 break;
3862
3863         case PW_TYPE_SHORT:
3864                 vp->vp_short = (data[0] << 8) | data[1];
3865                 break;
3866
3867         case PW_TYPE_INTEGER:
3868                 memcpy(&vp->vp_integer, data, 4);
3869                 vp->vp_integer = ntohl(vp->vp_integer);
3870                 break;
3871
3872         case PW_TYPE_INTEGER64:
3873                 memcpy(&vp->vp_integer64, data, 8);
3874                 vp->vp_integer64 = ntohll(vp->vp_integer64);
3875                 break;
3876
3877         case PW_TYPE_DATE:
3878                 memcpy(&vp->vp_date, data, 4);
3879                 vp->vp_date = ntohl(vp->vp_date);
3880                 break;
3881
3882         case PW_TYPE_ETHERNET:
3883                 memcpy(vp->vp_ether, data, 6);
3884                 break;
3885
3886         case PW_TYPE_IPV4_ADDR:
3887                 memcpy(&vp->vp_ipaddr, data, 4);
3888                 break;
3889
3890         case PW_TYPE_IFID:
3891                 memcpy(vp->vp_ifid, data, 8);
3892                 break;
3893
3894         case PW_TYPE_IPV6_ADDR:
3895                 memcpy(&vp->vp_ipv6addr, data, 16);
3896                 break;
3897
3898         case PW_TYPE_IPV6_PREFIX:
3899                 /*
3900                  *      FIXME: double-check that
3901                  *      (vp->vp_octets[1] >> 3) matches vp->vp_length + 2
3902                  */
3903                 memcpy(vp->vp_ipv6prefix, data, vp->vp_length);
3904                 if (vp->vp_length < 18) {
3905                         memset(((uint8_t *)vp->vp_ipv6prefix) + vp->vp_length, 0,
3906                                18 - vp->vp_length);
3907                 }
3908                 break;
3909
3910         case PW_TYPE_IPV4_PREFIX:
3911                 /* FIXME: do the same double-check as for IPv6Prefix */
3912                 memcpy(vp->vp_ipv4prefix, data, vp->vp_length);
3913
3914                 /*
3915                  *      /32 means "keep all bits".  Otherwise, mask
3916                  *      them out.
3917                  */
3918                 if ((data[1] & 0x3f) > 32) {
3919                         uint32_t addr, mask;
3920
3921                         memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
3922                         mask = 1;
3923                         mask <<= (32 - (data[1] & 0x3f));
3924                         mask--;
3925                         mask = ~mask;
3926                         mask = htonl(mask);
3927                         addr &= mask;
3928                         memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
3929                 }
3930                 break;
3931
3932         case PW_TYPE_SIGNED:    /* overloaded with vp_integer */
3933                 memcpy(&vp->vp_integer, buffer, 4);
3934                 vp->vp_integer = ntohl(vp->vp_integer);
3935                 break;
3936
3937         default:
3938                 fr_pair_list_free(&vp);
3939                 fr_strerror_printf("Internal sanity check %d", __LINE__);
3940                 return -1;
3941         }
3942         vp->type = VT_DATA;
3943         *pvp = vp;
3944
3945         return attrlen;
3946 }
3947
3948
3949 /** Create a "normal" VALUE_PAIR from the given data
3950  *
3951  */
3952 ssize_t rad_attr2vp(TALLOC_CTX *ctx,
3953                     RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3954                     char const *secret,
3955                     uint8_t const *data, size_t length,
3956                     VALUE_PAIR **pvp)
3957 {
3958         ssize_t rcode;
3959
3960         DICT_ATTR const *da;
3961
3962         if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3963                 fr_strerror_printf("rad_attr2vp: Insufficient data");
3964                 return -1;
3965         }
3966
3967         da = dict_attrbyvalue(data[0], 0);
3968         if (!da) {
3969                 VP_TRACE("attr2vp: unknown attribute %u\n", data[0]);
3970                 da = dict_unknown_afrom_fields(ctx, data[0], 0);
3971         }
3972         if (!da) return -1;
3973
3974         /*
3975          *      Pass the entire thing to the decoding function
3976          */
3977         if (da->flags.concat) {
3978                 VP_TRACE("attr2vp: concat attribute\n");
3979                 return data2vp_concat(ctx, da, data, length, pvp);
3980         }
3981
3982         /*
3983          *      Note that we pass the entire length, not just the
3984          *      length of this attribute.  The Extended or WiMAX
3985          *      attributes may have the "continuation" bit set, and
3986          *      will thus be more than one attribute in length.
3987          */
3988         rcode = data2vp(ctx, packet, original, secret, da,
3989                         data + 2, data[1] - 2, length - 2, pvp);
3990         if (rcode < 0) return rcode;
3991
3992         return 2 + rcode;
3993 }
3994
3995 fr_thread_local_setup(uint8_t *, rad_vp2data_buff)
3996
3997 /** Converts vp_data to network byte order
3998  *
3999  * Provide a pointer to a buffer which contains the value of the VALUE_PAIR
4000  * in an architecture independent format.
4001  *
4002  * The pointer is only guaranteed to be valid between calls to rad_vp2data, and so long
4003  * as the source VALUE_PAIR is not freed.
4004  *
4005  * @param out where to write the pointer to the value.
4006  * @param vp to get the value from.
4007  * @return -1 on error, or the length of the value
4008  */
4009 ssize_t rad_vp2data(uint8_t const **out, VALUE_PAIR const *vp)
4010 {
4011         uint8_t         *buffer;
4012         uint32_t        lvalue;
4013         uint64_t        lvalue64;
4014
4015         *out = NULL;
4016
4017         buffer = fr_thread_local_init(rad_vp2data_buff, free);
4018         if (!buffer) {
4019                 int ret;
4020
4021                 buffer = malloc(sizeof(uint8_t) * sizeof(value_data_t));
4022                 if (!buffer) {
4023                         fr_strerror_printf("Failed allocating memory for rad_vp2data buffer");
4024                         return -1;
4025                 }
4026
4027                 ret = fr_thread_local_set(rad_vp2data_buff, buffer);
4028                 if (ret != 0) {
4029                         fr_strerror_printf("Failed setting up TLS for rad_vp2data buffer: %s", strerror(errno));
4030                         free(buffer);
4031                         return -1;
4032                 }
4033         }
4034
4035         VERIFY_VP(vp);
4036
4037         switch (vp->da->type) {
4038         case PW_TYPE_STRING:
4039         case PW_TYPE_OCTETS:
4040                 memcpy(out, &vp->data.ptr, sizeof(*out));
4041                 break;
4042
4043         /*
4044          *      All of these values are at the same location.
4045          */
4046         case PW_TYPE_IFID:
4047         case PW_TYPE_IPV4_ADDR:
4048         case PW_TYPE_IPV6_ADDR:
4049         case PW_TYPE_IPV6_PREFIX:
4050         case PW_TYPE_IPV4_PREFIX:
4051         case PW_TYPE_ABINARY:
4052         case PW_TYPE_ETHERNET:
4053         case PW_TYPE_COMBO_IP_ADDR:
4054         case PW_TYPE_COMBO_IP_PREFIX:
4055         {
4056                 void const *p = &vp->data;
4057                 memcpy(out, &p, sizeof(*out));
4058                 break;
4059         }
4060
4061         case PW_TYPE_BOOLEAN:
4062                 buffer[0] = vp->vp_byte & 0x01;
4063                 *out = buffer;
4064                 break;
4065
4066         case PW_TYPE_BYTE:
4067                 buffer[0] = vp->vp_byte & 0xff;
4068                 *out = buffer;
4069                 break;
4070
4071         case PW_TYPE_SHORT:
4072                 buffer[0] = (vp->vp_short >> 8) & 0xff;
4073                 buffer[1] = vp->vp_short & 0xff;
4074                 *out = buffer;
4075                 break;
4076
4077         case PW_TYPE_INTEGER:
4078                 lvalue = htonl(vp->vp_integer);
4079                 memcpy(buffer, &lvalue, sizeof(lvalue));
4080                 *out = buffer;
4081                 break;
4082
4083         case PW_TYPE_INTEGER64:
4084                 lvalue64 = htonll(vp->vp_integer64);
4085                 memcpy(buffer, &lvalue64, sizeof(lvalue64));
4086                 *out = buffer;
4087                 break;
4088
4089         case PW_TYPE_DATE:
4090                 lvalue = htonl(vp->vp_date);
4091                 memcpy(buffer, &lvalue, sizeof(lvalue));
4092                 *out = buffer;
4093                 break;
4094
4095         case PW_TYPE_SIGNED:
4096         {
4097                 int32_t slvalue = htonl(vp->vp_signed);
4098                 memcpy(buffer, &slvalue, sizeof(slvalue));
4099                 *out = buffer;
4100                 break;
4101         }
4102
4103         case PW_TYPE_INVALID:
4104         case PW_TYPE_EXTENDED:
4105         case PW_TYPE_LONG_EXTENDED:
4106         case PW_TYPE_EVS:
4107         case PW_TYPE_VSA:
4108         case PW_TYPE_TLV:
4109         case PW_TYPE_TIMEVAL:
4110         case PW_TYPE_MAX:
4111                 fr_strerror_printf("Cannot get data for VALUE_PAIR type %i", vp->da->type);
4112                 return -1;
4113
4114         /* Don't add default */
4115         }
4116
4117         return vp->vp_length;
4118 }
4119
4120 /** Calculate/check digest, and decode radius attributes
4121  *
4122  * @return -1 on decoding error, 0 on success
4123  */
4124 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
4125                char const *secret)
4126 {
4127         int                     packet_length;
4128         uint32_t                num_attributes;
4129         uint8_t                 *ptr;
4130         radius_packet_t         *hdr;
4131         VALUE_PAIR *head, **tail, *vp;
4132
4133         /*
4134          *      Extract attribute-value pairs
4135          */
4136         hdr = (radius_packet_t *)packet->data;
4137         ptr = hdr->data;
4138         packet_length = packet->data_len - RADIUS_HDR_LEN;
4139
4140         head = NULL;
4141         tail = &head;
4142         num_attributes = 0;
4143
4144         /*
4145          *      Loop over the attributes, decoding them into VPs.
4146          */
4147         while (packet_length > 0) {
4148                 ssize_t my_len;
4149
4150                 /*
4151                  *      This may return many VPs
4152                  */
4153                 my_len = rad_attr2vp(packet, packet, original, secret,
4154                                      ptr, packet_length, &vp);
4155                 if (my_len < 0) {
4156                         fr_pair_list_free(&head);
4157                         return -1;
4158                 }
4159
4160                 *tail = vp;
4161                 while (vp) {
4162                         num_attributes++;
4163                         tail = &(vp->next);
4164                         vp = vp->next;
4165                 }
4166
4167                 /*
4168                  *      VSA's may not have been counted properly in
4169                  *      rad_packet_ok() above, as it is hard to count
4170                  *      then without using the dictionary.  We
4171                  *      therefore enforce the limits here, too.
4172                  */
4173                 if ((fr_max_attributes > 0) &&
4174                     (num_attributes > fr_max_attributes)) {
4175                         char host_ipaddr[128];
4176
4177                         fr_pair_list_free(&head);
4178                         fr_strerror_printf("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
4179                                    inet_ntop(packet->src_ipaddr.af,
4180                                              &packet->src_ipaddr.ipaddr,
4181                                              host_ipaddr, sizeof(host_ipaddr)),
4182                                    num_attributes, fr_max_attributes);
4183                         return -1;
4184                 }
4185
4186                 ptr += my_len;
4187                 packet_length -= my_len;
4188         }
4189
4190         /*
4191          *      Merge information from the outside world into our
4192          *      random pool.
4193          */
4194         fr_rand_seed(packet->data, RADIUS_HDR_LEN);
4195
4196         /*
4197          *      There may be VP's already in the packet.  Don't
4198          *      destroy them.  Instead, add the decoded attributes to
4199          *      the tail of the list.
4200          */
4201         for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
4202                 /* nothing */
4203         }
4204         *tail = head;
4205
4206         return 0;
4207 }
4208
4209
4210 /** Encode password
4211  *
4212  * We assume that the passwd buffer passed is big enough.
4213  * RFC2138 says the password is max 128 chars, so the size
4214  * of the passwd buffer must be at least 129 characters.
4215  * Preferably it's just MAX_STRING_LEN.
4216  *
4217  * int *pwlen is updated to the new length of the encrypted
4218  * password - a multiple of 16 bytes.
4219  */
4220 int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
4221                  uint8_t const *vector)
4222 {
4223         FR_MD5_CTX context, old;
4224         uint8_t digest[AUTH_VECTOR_LEN];
4225         int     i, n, secretlen;
4226         int     len;
4227
4228         /*
4229          *      RFC maximum is 128 bytes.
4230          *
4231          *      If length is zero, pad it out with zeros.
4232          *
4233          *      If the length isn't aligned to 16 bytes,
4234          *      zero out the extra data.
4235          */
4236         len = *pwlen;
4237
4238         if (len > 128) len = 128;
4239
4240         if (len == 0) {
4241                 memset(passwd, 0, AUTH_PASS_LEN);
4242                 len = AUTH_PASS_LEN;
4243         } else if ((len % AUTH_PASS_LEN) != 0) {
4244                 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
4245                 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
4246         }
4247         *pwlen = len;
4248
4249         /*
4250          *      Use the secret to setup the decryption digest
4251          */
4252         secretlen = strlen(secret);
4253
4254         fr_md5_init(&context);
4255         fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4256         old = context;          /* save intermediate work */
4257
4258         /*
4259          *      Encrypt it in place.  Don't bother checking
4260          *      len, as we've ensured above that it's OK.
4261          */
4262         for (n = 0; n < len; n += AUTH_PASS_LEN) {
4263                 if (n == 0) {
4264                         fr_md5_update(&context, vector, AUTH_PASS_LEN);
4265                         fr_md5_final(digest, &context);
4266                 } else {
4267                         context = old;
4268                         fr_md5_update(&context,
4269                                      (uint8_t *) passwd + n - AUTH_PASS_LEN,
4270                                      AUTH_PASS_LEN);
4271                         fr_md5_final(digest, &context);
4272                 }
4273
4274                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4275                         passwd[i + n] ^= digest[i];
4276                 }
4277         }
4278
4279         return 0;
4280 }
4281
4282 /** Decode password
4283  *
4284  */
4285 int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
4286                  uint8_t const *vector)
4287 {
4288         FR_MD5_CTX context, old;
4289         uint8_t digest[AUTH_VECTOR_LEN];
4290         int     i;
4291         size_t  n, secretlen;
4292
4293         /*
4294          *      The RFC's say that the maximum is 128.
4295          *      The buffer we're putting it into above is 254, so
4296          *      we don't need to do any length checking.
4297          */
4298         if (pwlen > 128) pwlen = 128;
4299
4300         /*
4301          *      Catch idiots.
4302          */
4303         if (pwlen == 0) goto done;
4304
4305         /*
4306          *      Use the secret to setup the decryption digest
4307          */
4308         secretlen = strlen(secret);
4309
4310         fr_md5_init(&context);
4311         fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4312         old = context;          /* save intermediate work */
4313
4314         /*
4315          *      The inverse of the code above.
4316          */
4317         for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
4318                 if (n == 0) {
4319                         fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4320                         fr_md5_final(digest, &context);
4321
4322                         context = old;
4323                         if (pwlen > AUTH_PASS_LEN) {
4324                                 fr_md5_update(&context, (uint8_t *) passwd,
4325                                              AUTH_PASS_LEN);
4326                         }
4327                 } else {
4328                         fr_md5_final(digest, &context);
4329
4330                         context = old;
4331                         if (pwlen > (n + AUTH_PASS_LEN)) {
4332                                 fr_md5_update(&context, (uint8_t *) passwd + n,
4333                                              AUTH_PASS_LEN);
4334                         }
4335                 }
4336
4337                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4338                         passwd[i + n] ^= digest[i];
4339                 }
4340         }
4341
4342  done:
4343         passwd[pwlen] = '\0';
4344         return strlen(passwd);
4345 }
4346
4347
4348 /** Encode Tunnel-Password attributes when sending them out on the wire
4349  *
4350  * int *pwlen is updated to the new length of the encrypted
4351  * password - a multiple of 16 bytes.
4352  *
4353  * This is per RFC-2868 which adds a two char SALT to the initial intermediate
4354  * value MD5 hash.
4355  */
4356 ssize_t rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret, uint8_t const *vector)
4357 {
4358         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
4359         unsigned char   digest[AUTH_VECTOR_LEN];
4360         char*   salt;
4361         int     i, n, secretlen;
4362         unsigned len, n2;
4363
4364         len = *pwlen;
4365
4366         if (len > 127) len = 127;
4367
4368         /*
4369          *      Shift the password 3 positions right to place a salt and original
4370          *      length, tag will be added automatically on packet send.
4371          */
4372         for (n = len ; n >= 0 ; n--) passwd[n + 3] = passwd[n];
4373         salt = passwd;
4374         passwd += 2;
4375
4376         /*
4377          *      save original password length as first password character;
4378          */
4379         *passwd = len;
4380         len += 1;
4381
4382
4383         /*
4384          *      Generate salt.  The RFC's say:
4385          *
4386          *      The high bit of salt[0] must be set, each salt in a
4387          *      packet should be unique, and they should be random
4388          *
4389          *      So, we set the high bit, add in a counter, and then
4390          *      add in some CSPRNG data.  should be OK..
4391          */
4392         salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
4393                    (fr_rand() & 0x07));
4394         salt[1] = fr_rand();
4395
4396         /*
4397          *      Padd password to multiple of AUTH_PASS_LEN bytes.
4398          */
4399         n = len % AUTH_PASS_LEN;
4400         if (n) {
4401                 n = AUTH_PASS_LEN - n;
4402                 for (; n > 0; n--, len++)
4403                         passwd[len] = 0;
4404         }
4405         /* set new password length */
4406         *pwlen = len + 2;
4407
4408         /*
4409          *      Use the secret to setup the decryption digest
4410          */
4411         secretlen = strlen(secret);
4412         memcpy(buffer, secret, secretlen);
4413
4414         for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
4415                 if (!n2) {
4416                         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
4417                         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
4418                         fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
4419                 } else {
4420                         memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4421                         fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4422                 }
4423
4424                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4425                         passwd[i + n2] ^= digest[i];
4426                 }
4427         }
4428         passwd[n2] = 0;
4429         return 0;
4430 }
4431
4432 /** Decode Tunnel-Password encrypted attributes
4433  *
4434  * Defined in RFC-2868, this uses a two char SALT along with the
4435  * initial intermediate value, to differentiate it from the
4436  * above.
4437  */
4438 ssize_t rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret, uint8_t const *vector)
4439 {
4440         FR_MD5_CTX  context, old;
4441         uint8_t         digest[AUTH_VECTOR_LEN];
4442         int             secretlen;
4443         size_t          i, n, encrypted_len, reallen;
4444
4445         encrypted_len = *pwlen;
4446
4447         /*
4448          *      We need at least a salt.
4449          */
4450         if (encrypted_len < 2) {
4451                 fr_strerror_printf("tunnel password is too short");
4452                 return -1;
4453         }
4454
4455         /*
4456          *      There's a salt, but no password.  Or, there's a salt
4457          *      and a 'data_len' octet.  It's wrong, but at least we
4458          *      can figure out what it means: the password is empty.
4459          *
4460          *      Note that this means we ignore the 'data_len' field,
4461          *      if the attribute length tells us that there's no
4462          *      more data.  So the 'data_len' field may be wrong,
4463          *      but that's ok...
4464          */
4465         if (encrypted_len <= 3) {
4466                 passwd[0] = 0;
4467                 *pwlen = 0;
4468                 return 0;
4469         }
4470
4471         encrypted_len -= 2;             /* discount the salt */
4472
4473         /*
4474          *      Use the secret to setup the decryption digest
4475          */
4476         secretlen = strlen(secret);
4477
4478         fr_md5_init(&context);
4479         fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4480         old = context;          /* save intermediate work */
4481
4482         /*
4483          *      Set up the initial key:
4484          *
4485          *       b(1) = MD5(secret + vector + salt)
4486          */
4487         fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4488         fr_md5_update(&context, passwd, 2);
4489
4490         reallen = 0;
4491         for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
4492                 size_t base;
4493                 size_t block_len = AUTH_PASS_LEN;
4494
4495                 /*
4496                  *      Ensure we don't overflow the input on MD5
4497                  */
4498                 if ((n + 2 + AUTH_PASS_LEN) > *pwlen) {
4499                         block_len = *pwlen - n - 2;
4500                 }
4501
4502                 if (n == 0) {
4503                         base = 1;
4504
4505                         fr_md5_final(digest, &context);
4506
4507                         context = old;
4508
4509                         /*
4510                          *      A quick check: decrypt the first octet
4511                          *      of the password, which is the
4512                          *      'data_len' field.  Ensure it's sane.
4513                          */
4514                         reallen = passwd[2] ^ digest[0];
4515                         if (reallen > encrypted_len) {
4516                                 fr_strerror_printf("tunnel password is too long for the attribute");
4517                                 return -1;
4518                         }
4519
4520                         fr_md5_update(&context, passwd + 2, block_len);
4521
4522                 } else {
4523                         base = 0;
4524
4525                         fr_md5_final(digest, &context);
4526
4527                         context = old;
4528                         fr_md5_update(&context, passwd + n + 2, block_len);
4529                 }
4530
4531                 for (i = base; i < block_len; i++) {
4532                         passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4533                 }
4534         }
4535
4536         *pwlen = reallen;
4537         passwd[reallen] = 0;
4538
4539         return reallen;
4540 }
4541
4542 /** Encode a CHAP password
4543  *
4544  * @bug FIXME: might not work with Ascend because
4545  * we use vp->vp_length, and Ascend gear likes
4546  * to send an extra '\0' in the string!
4547  */
4548 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4549                     VALUE_PAIR *password)
4550 {
4551         int             i;
4552         uint8_t         *ptr;
4553         uint8_t         string[MAX_STRING_LEN * 2 + 1];
4554         VALUE_PAIR      *challenge;
4555
4556         /*
4557          *      Sanity check the input parameters
4558          */
4559         if ((packet == NULL) || (password == NULL)) {
4560                 return -1;
4561         }
4562
4563         /*
4564          *      Note that the password VP can be EITHER
4565          *      a User-Password attribute (from a check-item list),
4566          *      or a CHAP-Password attribute (the client asking
4567          *      the library to encode it).
4568          */
4569
4570         i = 0;
4571         ptr = string;
4572         *ptr++ = id;
4573
4574         i++;
4575         memcpy(ptr, password->vp_strvalue, password->vp_length);
4576         ptr += password->vp_length;
4577         i += password->vp_length;
4578
4579         /*
4580          *      Use Chap-Challenge pair if present,
4581          *      Request Authenticator otherwise.
4582          */
4583         challenge = fr_pair_find_by_num(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
4584         if (challenge) {
4585                 memcpy(ptr, challenge->vp_strvalue, challenge->vp_length);
4586                 i += challenge->vp_length;
4587         } else {
4588                 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4589                 i += AUTH_VECTOR_LEN;
4590         }
4591
4592         *output = id;
4593         fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4594
4595         return 0;
4596 }
4597
4598
4599 /** Seed the random number generator
4600  *
4601  * May be called any number of times.
4602  */
4603 void fr_rand_seed(void const *data, size_t size)
4604 {
4605         uint32_t hash;
4606
4607         /*
4608          *      Ensure that the pool is initialized.
4609          */
4610         if (!fr_rand_initialized) {
4611                 int fd;
4612
4613                 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4614
4615                 fd = open("/dev/urandom", O_RDONLY);
4616                 if (fd >= 0) {
4617                         size_t total;
4618                         ssize_t this;
4619
4620                         total = 0;
4621                         while (total < sizeof(fr_rand_pool.randrsl)) {
4622                                 this = read(fd, fr_rand_pool.randrsl,
4623                                             sizeof(fr_rand_pool.randrsl) - total);
4624                                 if ((this < 0) && (errno != EINTR)) break;
4625                                 if (this > 0) total += this;
4626                         }
4627                         close(fd);
4628                 } else {
4629                         fr_rand_pool.randrsl[0] = fd;
4630                         fr_rand_pool.randrsl[1] = time(NULL);
4631                         fr_rand_pool.randrsl[2] = errno;
4632                 }
4633
4634                 fr_randinit(&fr_rand_pool, 1);
4635                 fr_rand_pool.randcnt = 0;
4636                 fr_rand_initialized = 1;
4637         }
4638
4639         if (!data) return;
4640
4641         /*
4642          *      Hash the user data
4643          */
4644         hash = fr_rand();
4645         if (!hash) hash = fr_rand();
4646         hash = fr_hash_update(data, size, hash);
4647
4648         fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4649 }
4650
4651
4652 /** Return a 32-bit random number
4653  *
4654  */
4655 uint32_t fr_rand(void)
4656 {
4657         uint32_t num;
4658
4659         /*
4660          *      Ensure that the pool is initialized.
4661          */
4662         if (!fr_rand_initialized) {
4663                 fr_rand_seed(NULL, 0);
4664         }
4665
4666         num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4667         if (fr_rand_pool.randcnt >= 256) {
4668                 fr_rand_pool.randcnt = 0;
4669                 fr_isaac(&fr_rand_pool);
4670         }
4671
4672         return num;
4673 }
4674
4675
4676 /** Allocate a new RADIUS_PACKET
4677  *
4678  * @param ctx the context in which the packet is allocated. May be NULL if
4679  *      the packet is not associated with a REQUEST.
4680  * @param new_vector if true a new request authenticator will be generated.
4681  * @return a new RADIUS_PACKET or NULL on error.
4682  */
4683 RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, bool new_vector)
4684 {
4685         RADIUS_PACKET   *rp;
4686
4687         rp = talloc_zero(ctx, RADIUS_PACKET);
4688         if (!rp) {
4689                 fr_strerror_printf("out of memory");
4690                 return NULL;
4691         }
4692         rp->id = -1;
4693         rp->offset = -1;
4694
4695         if (new_vector) {
4696                 int i;
4697                 uint32_t hash, base;
4698
4699                 /*
4700                  *      Don't expose the actual contents of the random
4701                  *      pool.
4702                  */
4703                 base = fr_rand();
4704                 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4705                         hash = fr_rand() ^ base;
4706                         memcpy(rp->vector + i, &hash, sizeof(hash));
4707                 }
4708         }
4709         fr_rand();              /* stir the pool again */
4710
4711         return rp;
4712 }
4713
4714 /** Allocate a new RADIUS_PACKET response
4715  *
4716  * @param ctx the context in which the packet is allocated. May be NULL if
4717  *      the packet is not associated with a REQUEST.
4718  * @param packet The request packet.
4719  * @return a new RADIUS_PACKET or NULL on error.
4720  */
4721 RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
4722 {
4723         RADIUS_PACKET *reply;
4724
4725         if (!packet) return NULL;
4726
4727         reply = rad_alloc(ctx, false);
4728         if (!reply) return NULL;
4729
4730         /*
4731          *      Initialize the fields from the request.
4732          */
4733         reply->sockfd = packet->sockfd;
4734         reply->dst_ipaddr = packet->src_ipaddr;
4735         reply->src_ipaddr = packet->dst_ipaddr;
4736         reply->dst_port = packet->src_port;
4737         reply->src_port = packet->dst_port;
4738         reply->id = packet->id;
4739         reply->code = 0; /* UNKNOWN code */
4740         memcpy(reply->vector, packet->vector,
4741                sizeof(reply->vector));
4742         reply->vps = NULL;
4743         reply->data = NULL;
4744         reply->data_len = 0;
4745
4746 #ifdef WITH_TCP
4747         reply->proto = packet->proto;
4748 #endif
4749         return reply;
4750 }
4751
4752
4753 /** Free a RADIUS_PACKET
4754  *
4755  */
4756 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4757 {
4758         RADIUS_PACKET *radius_packet;
4759
4760         if (!radius_packet_ptr || !*radius_packet_ptr) return;
4761         radius_packet = *radius_packet_ptr;
4762
4763         VERIFY_PACKET(radius_packet);
4764
4765         fr_pair_list_free(&radius_packet->vps);
4766
4767         talloc_free(radius_packet);
4768         *radius_packet_ptr = NULL;
4769 }
4770
4771 /** Duplicate a RADIUS_PACKET
4772  *
4773  * @param ctx the context in which the packet is allocated. May be NULL if
4774  *      the packet is not associated with a REQUEST.
4775  * @param in The packet to copy
4776  * @return a new RADIUS_PACKET or NULL on error.
4777  */
4778 RADIUS_PACKET *rad_copy_packet(TALLOC_CTX *ctx, RADIUS_PACKET const *in)
4779 {
4780         RADIUS_PACKET *out;
4781
4782         out = rad_alloc(ctx, false);
4783         if (!out) return NULL;
4784
4785         /*
4786          *      Bootstrap by copying everything.
4787          */
4788         memcpy(out, in, sizeof(*out));
4789
4790         /*
4791          *      Then reset necessary fields
4792          */
4793         out->sockfd = -1;
4794
4795         out->data = NULL;
4796         out->data_len = 0;
4797
4798         out->vps = fr_pair_list_copy(out, in->vps);
4799         out->offset = 0;
4800
4801         return out;
4802 }