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