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