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