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