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