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