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