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