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