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