import from HEAD:
[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  The FreeRADIUS server project
21  */
22
23 static const char rcsid[] = "$Id$";
24
25 #include        "autoconf.h"
26 #include        "md5.h"
27
28 #include        <stdlib.h>
29
30 #ifdef HAVE_UNISTD_H
31 #include        <unistd.h>
32 #endif
33
34 #include        <fcntl.h>
35 #include        <string.h>
36 #include        <ctype.h>
37
38 #include        "libradius.h"
39 #ifdef WITH_UDPFROMTO
40 #include        "udpfromto.h"
41 #endif
42
43 #ifdef HAVE_NETINET_IN_H
44 #include        <netinet/in.h>
45 #endif
46
47 #include        <sys/socket.h>
48
49 #ifdef HAVE_ARPA_INET_H
50 #include        <arpa/inet.h>
51 #endif
52
53 #ifdef HAVE_MALLOC_H
54 #include        <malloc.h>
55 #endif
56
57 #ifdef WIN32
58 #include        <process.h>
59 #endif
60
61 /*
62  *  The RFC says 4096 octets max, and most packets are less than 256.
63  */
64 #define MAX_PACKET_LEN 4096
65
66 /*
67  *      The maximum number of attributes which we allow in an incoming
68  *      request.  If there are more attributes than this, the request
69  *      is rejected.
70  *
71  *      This helps to minimize the potential for a DoS, when an
72  *      attacker spoofs Access-Request packets, which don't have a
73  *      Message-Authenticator attribute.  This means that the packet
74  *      is unsigned, and the attacker can use resources on the server,
75  *      even if the end request is rejected.
76  */
77 int librad_max_attributes = 0;
78
79 typedef struct radius_packet_t {
80   uint8_t       code;
81   uint8_t       id;
82   uint8_t       length[2];
83   uint8_t       vector[AUTH_VECTOR_LEN];
84   uint8_t       data[1];
85 } radius_packet_t;
86
87 static lrad_randctx lrad_rand_pool;     /* across multiple calls */
88 static volatile int lrad_rand_index = -1;
89 static unsigned int salt_offset = 0;
90
91 static const char *packet_codes[] = {
92   "",
93   "Access-Request",
94   "Access-Accept",
95   "Access-Reject",
96   "Accounting-Request",
97   "Accounting-Response",
98   "Accounting-Status",
99   "Password-Request",
100   "Password-Accept",
101   "Password-Reject",
102   "Accounting-Message",
103   "Access-Challenge",
104   "Status-Server",
105   "Status-Client",
106   "14",
107   "15",
108   "16",
109   "17",
110   "18",
111   "19",
112   "20",
113   "Resource-Free-Request",
114   "Resource-Free-Response",
115   "Resource-Query-Request",
116   "Resource-Query-Response",
117   "Alternate-Resource-Reclaim-Request",
118   "NAS-Reboot-Request",
119   "NAS-Reboot-Response",
120   "28",
121   "Next-Passcode",
122   "New-Pin",
123   "Terminate-Session",
124   "Password-Expired",
125   "Event-Request",
126   "Event-Response",
127   "35",
128   "36",
129   "37",
130   "38",
131   "39",
132   "Disconnect-Request",
133   "Disconnect-ACK",
134   "Disconnect-NAK",
135   "CoA-Request",
136   "CoA-ACK",
137   "CoA-NAK",
138   "46",
139   "47",
140   "48",
141   "49",
142   "IP-Address-Allocate",
143   "IP-Address-Release"
144 };
145
146
147 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
148 /*************************************************************************
149  *
150  *      Function: make_secret
151  *
152  *      Purpose: Build an encrypted secret value to return in a reply
153  *               packet.  The secret is hidden by xoring with a MD5 digest
154  *               created from the shared secret and the authentication
155  *               vector.  We put them into MD5 in the reverse order from
156  *               that used when encrypting passwords to RADIUS.
157  *
158  *************************************************************************/
159 static void make_secret(uint8_t *digest, const uint8_t *vector,
160                         const char *secret, const uint8_t *value)
161 {
162         MD5_CTX context;
163         int             i;
164
165         MD5Init(&context);
166         MD5Update(&context, vector, AUTH_VECTOR_LEN);
167         MD5Update(&context, secret, strlen(secret));
168         MD5Final(digest, &context);
169
170         for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
171                 digest[i] ^= value[i];
172         }
173 }
174
175 #define MAX_PASS_LEN (128)
176 static void make_passwd(uint8_t *output, int *outlen,
177                         const uint8_t *input, int inlen,
178                         const char *secret, const uint8_t *vector)
179 {
180         MD5_CTX context, old;
181         uint8_t digest[AUTH_VECTOR_LEN];
182         uint8_t passwd[MAX_PASS_LEN];
183         int     i, n;
184         int     len;
185
186         /*
187          *      If the length is zero, round it up.
188          */
189         len = inlen;
190         if (len == 0) {
191                 len = AUTH_PASS_LEN;
192         }
193         else if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
194
195         else if ((len & 0x0f) != 0) {
196                 len += 0x0f;
197                 len &= ~0x0f;
198         }
199         *outlen = len;
200
201         memcpy(passwd, input, len);
202         memset(passwd + len, 0, sizeof(passwd) - len);
203
204         MD5Init(&context);
205         MD5Update(&context, secret, strlen(secret));
206         old = context;
207
208         /*
209          *      Do first pass.
210          */
211         MD5Update(&context, vector, AUTH_PASS_LEN);
212
213         for (n = 0; n < len; n += AUTH_PASS_LEN) {
214                 if (n > 0) {
215                         context = old;
216                         MD5Update(&context,
217                                        passwd + n - AUTH_PASS_LEN,
218                                        AUTH_PASS_LEN);
219                 }
220
221                 MD5Final(digest, &context);
222                 for (i = 0; i < AUTH_PASS_LEN; i++) {
223                         passwd[i + n] ^= digest[i];
224                 }
225         }
226
227         memcpy(output, passwd, len);
228 }
229
230 static void make_tunnel_passwd(uint8_t *output, int *outlen,
231                                const uint8_t *input, int inlen, int room,
232                                const char *secret, const uint8_t *vector)
233 {
234         MD5_CTX context, old;
235         uint8_t digest[AUTH_VECTOR_LEN];
236         uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
237         int     i, n;
238         int     len;
239
240         /*
241          *      Account for 2 bytes of the salt, and round the room
242          *      available down to the nearest multiple of 16.  Then,
243          *      subtract one from that to account for the length byte,
244          *      and the resulting number is the upper bound on the data
245          *      to copy.
246          *
247          *      We could short-cut this calculation just be forcing
248          *      inlen to be no more than 239.  It would work for all
249          *      VSA's, as we don't pack multiple VSA's into one
250          *      attribute.
251          *
252          *      However, this calculation is more general, if a little
253          *      complex.  And it will work in the future for all possible
254          *      kinds of weird attribute packing.
255          */
256         room -= 2;
257         room -= (room & 0x0f);
258         room--;
259
260         if (inlen > room) inlen = room;
261
262         /*
263          *      Length of the encrypted data is password length plus
264          *      one byte for the length of the password.
265          */
266         len = inlen + 1;
267         if ((len & 0x0f) != 0) {
268                 len += 0x0f;
269                 len &= ~0x0f;
270         }
271         *outlen = len + 2;      /* account for the salt */
272
273         /*
274          *      Copy the password over.
275          */
276         memcpy(passwd + 3, input, inlen);
277         memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
278
279         /*
280          *      Generate salt.  The RFC's say:
281          *
282          *      The high bit of salt[0] must be set, each salt in a
283          *      packet should be unique, and they should be random
284          *
285          *      So, we set the high bit, add in a counter, and then
286          *      add in some CSPRNG data.  should be OK..
287          */
288         passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
289                      (lrad_rand() & 0x07));
290         passwd[1] = lrad_rand();
291         passwd[2] = inlen;      /* length of the password string */
292
293         MD5Init(&context);
294         MD5Update(&context, secret, strlen(secret));
295         old = context;
296
297         MD5Update(&context, vector, AUTH_VECTOR_LEN);
298         MD5Update(&context, &passwd[0], 2);
299
300         for (n = 0; n < len; n += AUTH_PASS_LEN) {
301                 if (n > 0) {
302                         context = old;
303                         MD5Update(&context,
304                                        passwd + 2 + n - AUTH_PASS_LEN,
305                                        AUTH_PASS_LEN);
306                 }
307
308                 MD5Final(digest, &context);
309                 for (i = 0; i < AUTH_PASS_LEN; i++) {
310                         passwd[i + 2 + n] ^= digest[i];
311                 }
312         }
313         memcpy(output, passwd, len + 2);
314 }
315
316
317 /*
318  *      Parse a data structure into a RADIUS attribute.
319  */
320 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
321                 const char *secret, const VALUE_PAIR *vp, uint8_t *ptr)
322 {
323         int             vendorcode;
324         int             offset, len, total_length;
325         uint32_t        lvalue;
326         uint8_t         *length_ptr, *vsa_length_ptr;
327         const uint8_t   *data = NULL;
328         uint8_t         array[4];
329
330         vendorcode = total_length = 0;
331         length_ptr = vsa_length_ptr = NULL;
332         
333         /*
334          *      For interoperability, always put vendor attributes
335          *      into their own VSA.
336          */
337         if ((vendorcode = VENDOR(vp->attribute)) != 0) {
338                 /*
339                  *      Build a VSA header.
340                  */
341                 *ptr++ = PW_VENDOR_SPECIFIC;
342                 vsa_length_ptr = ptr;
343                 *ptr++ = 6;
344                 lvalue = htonl(vendorcode);
345                 memcpy(ptr, &lvalue, 4);
346                 ptr += 4;
347                 total_length += 6;
348                 
349                 if (vendorcode == VENDORPEC_USR) {
350                         lvalue = htonl(vp->attribute & 0xFFFF);
351                         memcpy(ptr, &lvalue, 4);
352                         
353                         length_ptr = vsa_length_ptr;
354                         
355                         total_length += 4;
356                         *length_ptr  += 4;
357                         ptr          += 4;
358                         
359                         /*
360                          *      We don't have two different lengths.
361                          */
362                         vsa_length_ptr = NULL;
363                         
364                 } else if (vendorcode == VENDORPEC_LUCENT) {
365                         /*
366                          *      16-bit attribute, 8-bit length
367                          */
368                         *ptr++ = ((vp->attribute >> 8) & 0xFF);
369                         *ptr++ = (vp->attribute & 0xFF);
370                         length_ptr = ptr;
371                         *vsa_length_ptr += 3;
372                         *ptr++ = 3;
373                         total_length += 3;
374
375                 } else if (vendorcode == VENDORPEC_STARENT) {
376                         /*
377                          *      16-bit attribute, 16-bit length
378                          *      with the upper 8 bits of the length
379                          *      always zero!
380                          */
381                         *ptr++ = ((vp->attribute >> 8) & 0xFF);
382                         *ptr++ = (vp->attribute & 0xFF);
383                         *ptr++ = 0;
384                         length_ptr = ptr;
385                         *vsa_length_ptr += 4;
386                         *ptr++ = 4;
387                         total_length += 4;
388                 } else {
389                         /*
390                          *      All other VSA's are encoded the same
391                          *      as RFC attributes.
392                          */
393                         *vsa_length_ptr += 2;
394                         goto rfc;
395                 }
396         } else {
397         rfc:
398                 /*
399                  *      All other attributes are encoded as
400                  *      per the RFC.
401                  */
402                 *ptr++ = (vp->attribute & 0xFF);
403                 length_ptr = ptr;
404                 *ptr++ = 2;
405                 total_length += 2;
406         }
407
408         offset = 0;
409         if (vp->flags.has_tag) {
410                 if (TAG_VALID(vp->flags.tag)) {
411                         ptr[0] = vp->flags.tag & 0xff;
412                         offset = 1;
413             
414                 } else if (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD) {
415                         /*
416                          *      Tunnel passwords REQUIRE a tag, even
417                          *      if don't have a valid tag.
418                          */
419                         ptr[0] = 0;
420                         offset = 1;
421                 } /* else don't write a tag */
422         } /* else the attribute doesn't have a tag */
423         
424         /*
425          *      Set up the default sources for the data.
426          */
427         data = vp->strvalue;
428         len = vp->length;
429
430         /*
431          *      Encrypted passwords can't be very long.
432          *      This check also ensures that the hashed version
433          *      of the password + attribute header fits into one
434          *      attribute.
435          *
436          *      FIXME: Print a warning message if it's too long?
437          */
438         if (vp->flags.encrypt && (len > MAX_PASS_LEN)) {
439                 len = MAX_PASS_LEN;
440         }
441
442         switch(vp->type) {
443         case PW_TYPE_STRING:
444         case PW_TYPE_OCTETS:
445         case PW_TYPE_IFID:
446         case PW_TYPE_IPV6ADDR:
447         case PW_TYPE_IPV6PREFIX:
448         case PW_TYPE_ABINARY:
449                 /* nothing more to do */
450                 break;
451                         
452         case PW_TYPE_INTEGER:
453                 len = 4;        /* just in case */
454                 lvalue = htonl(vp->lvalue);
455                 memcpy(array, &lvalue, sizeof(lvalue));
456
457                 /*
458                  *      Perhaps discard the first octet.
459                  */
460                 data = &array[offset];
461                 len -= offset;
462                 break;
463                         
464         case PW_TYPE_IPADDR:
465                 data = (const uint8_t *) &vp->lvalue;
466                 len = 4;        /* just in case */
467                 break;
468
469                 /*
470                  *  There are no tagged date attributes.
471                  */
472         case PW_TYPE_DATE:
473                 lvalue = htonl(vp->lvalue);
474                 data = (const uint8_t *) &lvalue;
475                 len = 4;        /* just in case */
476                 break;
477
478         default:                /* unknown type: ignore it */
479                 librad_log("ERROR: Unknown attribute type %d", vp->type);
480                 return -1;
481         }
482
483         /*
484          *      Bound the data to 255 bytes.
485          */
486         if (len + offset + total_length > 255) {
487                 len = 255 - offset - total_length;
488         }       
489
490         /*
491          *      Encrypt the various password styles
492          *
493          *      Attributes with encrypted values MUST be less than
494          *      128 bytes long.
495          */
496         switch (vp->flags.encrypt) {
497         case FLAG_ENCRYPT_USER_PASSWORD:
498                 make_passwd(ptr + offset, &len,
499                             data, len,
500                             secret, packet->vector);
501                 break;
502                 
503         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
504                 if (!original) {
505                         librad_log("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
506                         return -1;
507                 }
508
509                 /*
510                  *      Check if 255 - offset - total_length is less
511                  *      than 18.  If so, we can't fit the data into
512                  *      the available space, and we discard the
513                  *      attribute.
514                  *
515                  *      This is ONLY a problem if we have multiple VSA's
516                  *      in one Vendor-Specific, though.
517                  */
518                 if ((255 - offset - total_length) < 18) return 0;
519
520                 /*
521                  *      Can't make the password, suppress it.
522                  */
523                 make_tunnel_passwd(ptr + offset, &len,
524                                    data, len, 255 - offset - total_length,
525                                    secret, original->vector);
526                 break;
527
528                 /*
529                  *      The code above ensures that this attribute
530                  *      always fits.
531                  */
532         case FLAG_ENCRYPT_ASCEND_SECRET:
533                 make_secret(ptr + offset, packet->vector,
534                             secret, data);
535                 len = AUTH_VECTOR_LEN;
536                 break;
537
538                 
539         default:
540                 /*
541                  *      Just copy the data over
542                  */
543                 memcpy(ptr + offset, data, len);
544                 break;
545         } /* switch over encryption flags */
546
547         /*
548          *      Account for the tag (if any).
549          */
550         len += offset;
551
552         /*
553          *      RFC 2865 section 5 says that zero-length attributes
554          *      MUST NOT be sent.
555          */
556         if (len == 0) return 0;
557
558         /*
559          *      Update the various lengths.
560          */
561         *length_ptr += len;
562         if (vsa_length_ptr) *vsa_length_ptr += len;
563         ptr += len;
564         total_length += len;
565
566         return total_length;    /* of attribute */
567 }
568
569
570 /*
571  *      Encode a packet.
572  */
573 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
574                const char *secret)
575 {
576         radius_packet_t *hdr;
577         uint8_t         *ptr;
578         uint16_t        total_length;
579         int             len;
580         VALUE_PAIR      *reply;
581         
582         /*
583          *      For simplicity in the following logic, we allow
584          *      the attributes to "overflow" the 4k maximum
585          *      RADIUS packet size, by one attribute.
586          *
587          *      It's uint32_t, for alignment purposes.
588          */
589         uint32_t        data[(MAX_PACKET_LEN + 256) / 4];
590
591         /*
592          *      Double-check some things based on packet code.
593          */
594         switch (packet->code) {
595         case PW_AUTHENTICATION_ACK:
596         case PW_AUTHENTICATION_REJECT:
597         case PW_ACCESS_CHALLENGE:
598                 if (!original) {
599                         librad_log("ERROR: Cannot sign response packet without a request packet.");
600                         return -1;
601                 }
602                 break;
603                 
604                 /*
605                  *      These packet vectors start off as all zero.
606                  */
607         case PW_ACCOUNTING_REQUEST:
608         case PW_DISCONNECT_REQUEST:
609         case PW_COA_REQUEST:
610                 memset(packet->vector, 0, sizeof(packet->vector));
611                 break;
612                 
613         default:
614                 break;
615         }
616                 
617         /*
618          *      Use memory on the stack, until we know how
619          *      large the packet will be.
620          */
621         hdr = (radius_packet_t *) data;
622         
623         /*
624          *      Build standard header
625          */
626         hdr->code = packet->code;
627         hdr->id = packet->id;
628         
629         memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
630
631         total_length = AUTH_HDR_LEN;
632         packet->verified = 0;
633         
634         /*
635          *      Load up the configuration values for the user
636          */
637         ptr = hdr->data;
638
639         /*
640          *      FIXME: Loop twice over the reply list.  The first time,
641          *      calculate the total length of data.  The second time,
642          *      allocate the memory, and fill in the VP's.
643          *
644          *      Hmm... this may be slower than just doing a small
645          *      memcpy.
646          */
647         
648         /*
649          *      Loop over the reply attributes for the packet.
650          */
651         for (reply = packet->vps; reply; reply = reply->next) {
652                 /*
653                  *      Ignore non-wire attributes
654                  */
655                 if ((VENDOR(reply->attribute) == 0) &&
656                     ((reply->attribute & 0xFFFF) > 0xff)) {
657                         continue;
658                 }
659                 
660                 /*
661                  *      Set the Message-Authenticator to the correct
662                  *      length and initial value.
663                  */
664                 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
665                         reply->length = AUTH_VECTOR_LEN;
666                         memset(reply->strvalue, 0, AUTH_VECTOR_LEN);
667                         packet->verified = total_length; /* HACK! */
668                 }
669                 
670                 /*
671                  *      Print out ONLY the attributes which
672                  *      we're sending over the wire, and print
673                  *      them out BEFORE they're encrypted.
674                  */
675                 debug_pair(reply);
676
677                 len = rad_vp2attr(packet, original, secret, reply, ptr);
678                 if (len < 0) return -1;
679
680                 /*
681                  *      Check that the packet is no more than 4k in
682                  *      size, AFTER writing the attribute past the 4k
683                  *      boundary, but BEFORE deciding to increase the
684                  *      size of the packet. Note that the 'data'
685                  *      buffer, above, is one attribute longer than
686                  *      necessary, in order to permit this overflow.
687                  */
688                 if ((total_length + len) > MAX_PACKET_LEN) {
689                         break;
690                 }
691
692                 ptr += len;
693                 total_length += len;
694         } /* done looping over all attributes */
695         
696         /*
697          *      Fill in the rest of the fields, and copy the data over
698          *      from the local stack to the newly allocated memory.
699          *
700          *      Yes, all this 'memcpy' is slow, but it means
701          *      that we only allocate the minimum amount of
702          *      memory for a request.
703          */
704         packet->data_len = total_length;
705         packet->data = (uint8_t *) malloc(packet->data_len);
706         if (!packet->data) {
707                 librad_log("Out of memory");
708                 return -1;
709         }
710
711         memcpy(packet->data, data, packet->data_len);
712         hdr = (radius_packet_t *) packet->data;
713         
714         total_length = htons(total_length);
715         memcpy(hdr->length, &total_length, sizeof(total_length));
716
717         return 0;
718 }
719
720
721 /*
722  *      Sign a previously encoded packet.
723  */
724 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
725              const char *secret)
726 {
727         radius_packet_t *hdr = (radius_packet_t *)packet->data;
728
729         /*
730          *      It wasn't assigned an Id, this is bad!
731          */
732         if (packet->id < 0) {
733                 librad_log("ERROR: RADIUS packets must be assigned an Id.");
734                 return -1;
735         }
736
737         if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
738             (packet->verified < 0)) {
739                 librad_log("ERROR: You must call rad_encode() before rad_sign()");
740                 return -1;
741         }
742
743         /*
744          *      If there's a Message-Authenticator, update it
745          *      now, BEFORE updating the authentication vector.
746          *
747          *      This is a hack...
748          */
749         if (packet->verified > 0) {
750                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
751                 
752                 switch (packet->code) {
753                 case PW_ACCOUNTING_REQUEST:
754                 case PW_ACCOUNTING_RESPONSE:
755                 case PW_DISCONNECT_REQUEST:
756                 case PW_DISCONNECT_ACK:
757                 case PW_DISCONNECT_NAK:
758                 case PW_COA_REQUEST:
759                 case PW_COA_ACK:
760                 case PW_COA_NAK:
761                         memset(hdr->vector, 0, AUTH_VECTOR_LEN);
762                         break;
763
764                 case PW_AUTHENTICATION_ACK:
765                 case PW_AUTHENTICATION_REJECT:
766                 case PW_ACCESS_CHALLENGE:
767                         if (!original) {
768                                 librad_log("ERROR: Cannot sign response packet without a request packet.");
769                                 return -1;
770                         }
771                         memcpy(hdr->vector, original->vector,
772                                AUTH_VECTOR_LEN);
773                         break;
774
775                 default:        /* others have vector already set to zero */
776                         break;
777                         
778                 }
779                 
780                 /*
781                  *      Set the authentication vector to zero,
782                  *      calculate the signature, and put it
783                  *      into the Message-Authenticator
784                  *      attribute.
785                  */
786                 lrad_hmac_md5(packet->data, packet->data_len,
787                               secret, strlen(secret),
788                               calc_auth_vector);
789                 memcpy(packet->data + packet->verified + 2,
790                        calc_auth_vector, AUTH_VECTOR_LEN);
791                 
792                 /*
793                  *      Copy the original request vector back
794                  *      to the raw packet.
795                  */
796                 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
797         }
798         
799         /*
800          *      Switch over the packet code, deciding how to
801          *      sign the packet.
802          */
803         switch (packet->code) {
804                 /*
805                  *      Request packets are not signed, bur
806                  *      have a random authentication vector.
807                  */
808         case PW_AUTHENTICATION_REQUEST:
809         case PW_STATUS_SERVER:
810                 break;
811                 
812                 /*
813                  *      Reply packets are signed with the
814                  *      authentication vector of the request.
815                  */
816         default:
817                 {
818                         uint8_t digest[16];
819                         
820                         MD5_CTX context;
821                         MD5Init(&context);
822                         MD5Update(&context, packet->data, packet->data_len);
823                         MD5Update(&context, secret, strlen(secret));
824                         MD5Final(digest, &context);
825                         
826                         memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
827                         memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
828                         break;
829                 }
830         }/* switch over packet codes */
831
832         return 0;
833 }
834
835 /*
836  *      Reply to the request.  Also attach
837  *      reply attribute value pairs and any user message provided.
838  */
839 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
840              const char *secret)
841 {
842         VALUE_PAIR              *reply;
843         const char              *what;
844         char                    ip_buffer[128];
845         struct  sockaddr_in     saremote;
846         struct  sockaddr_in     *sa;
847
848         /*
849          *      Maybe it's a fake packet.  Don't send it.
850          */
851         if (!packet || (packet->sockfd < 0)) {
852                 return 0;
853         }
854
855         if ((packet->code > 0) && (packet->code < 52)) {
856                 what = packet_codes[packet->code];
857         } else {
858                 what = "Reply";
859         }
860
861         /*
862          *  First time through, allocate room for the packet
863          */
864         if (!packet->data) {
865                 DEBUG("Sending %s of id %d to %s port %d\n",
866                       what, packet->id,
867                       ip_ntoa(ip_buffer, packet->dst_ipaddr),
868                       packet->dst_port);
869                 
870                 /*
871                  *      Encode the packet.
872                  */
873                 if (rad_encode(packet, original, secret) < 0) {
874                         return -1;
875                 }
876                 
877                 /*
878                  *      Re-sign it, including updating the
879                  *      Message-Authenticator.
880                  */
881                 if (rad_sign(packet, original, secret) < 0) {
882                         return -1;
883                 }
884
885                 /*
886                  *      If packet->data points to data, then we print out
887                  *      the VP list again only for debugging.
888                  */
889         } else if (librad_debug) {
890                 DEBUG("Re-sending %s of id %d to %s port %d\n", what, packet->id,
891                       ip_ntoa(ip_buffer, packet->dst_ipaddr),
892                       packet->dst_port);
893
894                 for (reply = packet->vps; reply; reply = reply->next) {
895                         /* FIXME: ignore attributes > 0xff */
896                         debug_pair(reply);
897                 }
898         }
899
900         /*
901          *      And send it on it's way.
902          */
903         sa = (struct sockaddr_in *) &saremote;
904         memset ((char *) sa, '\0', sizeof (saremote));
905         sa->sin_family = AF_INET;
906         sa->sin_addr.s_addr = packet->dst_ipaddr;
907         sa->sin_port = htons(packet->dst_port);
908 #ifndef WITH_UDPFROMTO
909         return sendto(packet->sockfd, packet->data, (int)packet->data_len, 0,
910                       (struct sockaddr *)&saremote, sizeof(struct sockaddr_in));
911 #else
912         {
913                 struct sockaddr_in salocal;
914                 memset ((char *) &salocal, '\0', sizeof (salocal));
915                 salocal.sin_family = AF_INET;
916                 salocal.sin_addr.s_addr = packet->src_ipaddr;
917                 
918                 return sendfromto(packet->sockfd, packet->data, (int)packet->data_len, 0,
919                                   (struct sockaddr *)&salocal,  sizeof(struct sockaddr_in),
920                                   (struct sockaddr *)&saremote, sizeof(struct sockaddr_in));
921         }
922 #endif
923 }
924
925
926 /*
927  *      Validates the requesting client NAS.  Calculates the
928  *      signature based on the clients private key.
929  */
930 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
931 {
932         u_char          digest[AUTH_VECTOR_LEN];
933         MD5_CTX         context;
934
935         /*
936          *      Older clients have the authentication vector set to
937          *      all zeros. Return `1' in that case.
938          */
939         memset(digest, 0, sizeof(digest));
940         if (memcmp(packet->vector, digest, AUTH_VECTOR_LEN) == 0) {
941                 packet->verified = 1;
942                 return 1;
943         }
944
945         /*
946          *      Zero out the auth_vector in the received packet.
947          *      Then append the shared secret to the received packet,
948          *      and calculate the MD5 sum. This must be the same
949          *      as the original MD5 sum (packet->vector).
950          */
951         memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
952
953         /*
954          *  MD5(packet + secret);
955          */
956         MD5Init(&context);
957         MD5Update(&context, packet->data, packet->data_len);
958         MD5Update(&context, secret, strlen(secret));
959         MD5Final(digest, &context);
960
961         /*
962          *      Return 0 if OK, 2 if not OK.
963          */
964         packet->verified =
965         memcmp(digest, packet->vector, AUTH_VECTOR_LEN) ? 2 : 0;
966
967         return packet->verified;
968 }
969
970 /*
971  *      Validates the requesting client NAS.  Calculates the
972  *      signature based on the clients private key.
973  */
974 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
975                             const char *secret)
976 {
977         uint8_t         calc_digest[AUTH_VECTOR_LEN];
978         MD5_CTX         context;
979
980         /*
981          *      Very bad!
982          */
983         if (original == NULL) {
984                 return 3;
985         }
986
987         /*
988          *  Copy the original vector in place.
989          */
990         memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
991
992         /*
993          *  MD5(packet + secret);
994          */
995         MD5Init(&context);
996         MD5Update(&context, packet->data, packet->data_len);
997         MD5Update(&context, secret, strlen(secret));
998         MD5Final(calc_digest, &context);
999
1000         /*
1001          *  Copy the packet's vector back to the packet.
1002          */
1003         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1004
1005         /*
1006          *      Return 0 if OK, 2 if not OK.
1007          */
1008         packet->verified =
1009                 memcmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) ? 2 : 0;
1010         return packet->verified;
1011 }
1012
1013 /*
1014  *      Receive UDP client requests, and fill in
1015  *      the basics of a RADIUS_PACKET structure.
1016  */
1017 RADIUS_PACKET *rad_recv(int fd)
1018 {
1019         RADIUS_PACKET           *packet;
1020         struct sockaddr_in      saremote;
1021         int                     totallen;
1022         socklen_t               salen;
1023         uint8_t                 *attr;
1024         int                     count;
1025         radius_packet_t         *hdr;
1026         char                    host_ipaddr[16];
1027         int                     require_ma = 0;
1028         int                     seen_ma = 0;
1029         uint8_t                 data[MAX_PACKET_LEN];
1030         int                     num_attributes;
1031
1032         /*
1033          *      Allocate the new request data structure
1034          */
1035         if ((packet = malloc(sizeof(RADIUS_PACKET))) == NULL) {
1036                 librad_log("out of memory");
1037                 return NULL;
1038         }
1039         memset(packet, 0, sizeof(RADIUS_PACKET));
1040
1041         /*
1042          *      Receive the packet.
1043          */
1044         salen = sizeof(saremote);
1045         memset(&saremote, 0, sizeof(saremote));
1046 #ifndef WITH_UDPFROMTO
1047         packet->data_len = recvfrom(fd, data, sizeof(data),
1048                                     0, (struct sockaddr *)&saremote, &salen);
1049         packet->dst_ipaddr = htonl(INADDR_ANY); /* i.e. unknown */
1050 #else
1051         {
1052                 socklen_t               salen_local;
1053                 struct sockaddr_in      salocal;
1054                 salen_local = sizeof(salocal);
1055                 memset(&salocal, 0, sizeof(salocal));
1056                 packet->data_len = recvfromto(fd, data, sizeof(data), 0,
1057                                               (struct sockaddr *)&saremote, &salen,
1058                                               (struct sockaddr *)&salocal, &salen_local);
1059                 packet->dst_ipaddr = salocal.sin_addr.s_addr;
1060         }
1061 #endif
1062
1063         /*
1064          *      Check for socket errors.
1065          */
1066         if (packet->data_len < 0) {
1067                 librad_log("Error receiving packet: %s", strerror(errno));
1068                 free(packet);
1069                 return NULL;
1070         }
1071
1072         /*
1073          *      Fill IP header fields.  We need these for the error
1074          *      messages which may come later.
1075          */
1076         packet->sockfd = fd;
1077         packet->src_ipaddr = saremote.sin_addr.s_addr;
1078         packet->src_port = ntohs(saremote.sin_port);
1079
1080         /*
1081          *      FIXME: Do even more filtering by only permitting
1082          *      certain IP's.  The problem is that we don't know
1083          *      how to do this properly for all possible clients...
1084          */
1085
1086         /*
1087          *      Explicitely set the VP list to empty.
1088          */
1089         packet->vps = NULL;
1090
1091         /*
1092          *      Check for packets smaller than the packet header.
1093          *
1094          *      RFC 2865, Section 3., subsection 'length' says:
1095          *
1096          *      "The minimum length is 20 ..."
1097          */
1098         if (packet->data_len < AUTH_HDR_LEN) {
1099                 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1100                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
1101                            packet->data_len, AUTH_HDR_LEN);
1102                 free(packet);
1103                 return NULL;
1104         }
1105
1106         /*
1107          *      RFC 2865, Section 3., subsection 'length' says:
1108          *
1109          *      " ... and maximum length is 4096."
1110          */
1111         if (packet->data_len > MAX_PACKET_LEN) {
1112                 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1113                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
1114                            packet->data_len, MAX_PACKET_LEN);
1115                 free(packet);
1116                 return NULL;
1117         }
1118
1119         /*
1120          *      Check for packets with mismatched size.
1121          *      i.e. We've received 128 bytes, and the packet header
1122          *      says it's 256 bytes long.
1123          */
1124         totallen = (data[2] << 8) | data[3];
1125         hdr = (radius_packet_t *)data;
1126
1127         /*
1128          *      Code of 0 is not understood.
1129          *      Code of 16 or greate is not understood.
1130          */
1131         if ((hdr->code == 0) ||
1132             (hdr->code >= 52)) {
1133                 librad_log("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
1134                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
1135                            hdr->code);
1136                 free(packet);
1137                 return NULL;
1138         }
1139
1140         /*
1141          *      Message-Authenticator is required in Status-Server
1142          *      packets, otherwise they can be trivially forged.
1143          */
1144         if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1145
1146         /*
1147          *      Repeat the length checks.  This time, instead of
1148          *      looking at the data we received, look at the value
1149          *      of the 'length' field inside of the packet.
1150          *
1151          *      Check for packets smaller than the packet header.
1152          *
1153          *      RFC 2865, Section 3., subsection 'length' says:
1154          *
1155          *      "The minimum length is 20 ..."
1156          */
1157         if (totallen < AUTH_HDR_LEN) {
1158                 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1159                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
1160                            totallen, AUTH_HDR_LEN);
1161                 free(packet);
1162                 return NULL;
1163         }
1164
1165         /*
1166          *      And again, for the value of the 'length' field.
1167          *
1168          *      RFC 2865, Section 3., subsection 'length' says:
1169          *
1170          *      " ... and maximum length is 4096."
1171          */
1172         if (totallen > MAX_PACKET_LEN) {
1173                 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1174                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
1175                            totallen, MAX_PACKET_LEN);
1176                 free(packet);
1177                 return NULL;
1178         }
1179
1180         /*
1181          *      RFC 2865, Section 3., subsection 'length' says:
1182          *
1183          *      "If the packet is shorter than the Length field
1184          *      indicates, it MUST be silently discarded."
1185          *
1186          *      i.e. No response to the NAS.
1187          */
1188         if (packet->data_len < totallen) {
1189                 librad_log("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1190                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
1191                            packet->data_len, totallen);
1192                 free(packet);
1193                 return NULL;
1194         }
1195
1196         /*
1197          *      RFC 2865, Section 3., subsection 'length' says:
1198          *
1199          *      "Octets outside the range of the Length field MUST be
1200          *      treated as padding and ignored on reception."
1201          */
1202         if (packet->data_len > totallen) {
1203                 /*
1204                  *      We're shortening the packet below, but just
1205                  *      to be paranoid, zero out the extra data.
1206                  */
1207                 memset(data + totallen, 0, packet->data_len - totallen);
1208                 packet->data_len = totallen;
1209         }
1210
1211         /*
1212          *      Walk through the packet's attributes, ensuring that
1213          *      they add up EXACTLY to the size of the packet.
1214          *
1215          *      If they don't, then the attributes either under-fill
1216          *      or over-fill the packet.  Any parsing of the packet
1217          *      is impossible, and will result in unknown side effects.
1218          *
1219          *      This would ONLY happen with buggy RADIUS implementations,
1220          *      or with an intentional attack.  Either way, we do NOT want
1221          *      to be vulnerable to this problem.
1222          */
1223         attr = hdr->data;
1224         count = totallen - AUTH_HDR_LEN;
1225         num_attributes = 0;
1226
1227         while (count > 0) {
1228                 /*
1229                  *      Attribute number zero is NOT defined.
1230                  */
1231                 if (attr[0] == 0) {
1232                         librad_log("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1233                                    ip_ntoa(host_ipaddr, packet->src_ipaddr));
1234                         free(packet);
1235                         return NULL;
1236                 }
1237
1238                 /*
1239                  *      Attributes are at LEAST as long as the ID & length
1240                  *      fields.  Anything shorter is an invalid attribute.
1241                  */
1242                 if (attr[1] < 2) {
1243                         librad_log("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1244                                    ip_ntoa(host_ipaddr, packet->src_ipaddr),
1245                                    attr[0]);
1246                         free(packet);
1247                         return NULL;
1248                 }
1249
1250                 /*
1251                  *      Sanity check the attributes for length.
1252                  */
1253                 switch (attr[0]) {
1254                 default:        /* don't do anything by default */
1255                         break;
1256
1257
1258                         /*
1259                          *      If there's an EAP-Message, we require
1260                          *      a Message-Authenticator.
1261                          */
1262                 case PW_EAP_MESSAGE:
1263                         require_ma = 1;
1264                         break;
1265
1266                 case PW_MESSAGE_AUTHENTICATOR:
1267                         if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1268                                 librad_log("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1269                                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
1270                                            attr[1] - 2);
1271                                 free(packet);
1272                                 return NULL;
1273                         }
1274                         seen_ma = 1;
1275                         break;
1276                 }
1277
1278                 /*
1279                  *      FIXME: Look up the base 255 attributes in the
1280                  *      dictionary, and switch over their type.  For
1281                  *      integer/date/ip, the attribute length SHOULD
1282                  *      be 6.
1283                  */
1284                 count -= attr[1];       /* grab the attribute length */
1285                 attr += attr[1];
1286                 num_attributes++;       /* seen one more attribute */
1287         }
1288
1289         /*
1290          *      If the attributes add up to a packet, it's allowed.
1291          *
1292          *      If not, we complain, and throw the packet away.
1293          */
1294         if (count != 0) {
1295                 librad_log("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1296                            ip_ntoa(host_ipaddr, packet->src_ipaddr));
1297                 free(packet);
1298                 return NULL;
1299         }
1300
1301         /*
1302          *      If we're configured to look for a maximum number of
1303          *      attributes, and we've seen more than that maximum,
1304          *      then throw the packet away, as a possible DoS.
1305          */
1306         if ((librad_max_attributes > 0) &&
1307             (num_attributes > librad_max_attributes)) {
1308                 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1309                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
1310                            num_attributes, librad_max_attributes);
1311                 free(packet);
1312                 return NULL;
1313         }
1314
1315         /*
1316          *      http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1317          *
1318          *      A packet with an EAP-Message attribute MUST also have
1319          *      a Message-Authenticator attribute.
1320          *
1321          *      A Message-Authenticator all by itself is OK, though.
1322          *
1323          *      Similarly, Status-Server packets MUST contain
1324          *      Message-Authenticator attributes.
1325          */
1326         if (require_ma && ! seen_ma) {
1327                 librad_log("WARNING: Insecure packet from host %s:  Packet does not contain required Message-Authenticator attribute",
1328                            ip_ntoa(host_ipaddr, packet->src_ipaddr));
1329                 free(packet);
1330                 return NULL;
1331         }
1332
1333         if (librad_debug) {
1334                 if ((hdr->code > 0) && (hdr->code < 52)) {
1335                         printf("rad_recv: %s packet from host %s:%d",
1336                                packet_codes[hdr->code],
1337                                ip_ntoa(host_ipaddr, packet->src_ipaddr), packet->src_port);
1338                 } else {
1339                         printf("rad_recv: Packet from host %s:%d code=%d",
1340                                ip_ntoa(host_ipaddr, packet->src_ipaddr), packet->src_port,
1341                                hdr->code);
1342                 }
1343                 printf(", id=%d, length=%d\n", hdr->id, totallen);
1344         }
1345
1346         /*
1347          *      Fill RADIUS header fields
1348          */
1349         packet->code = hdr->code;
1350         packet->id = hdr->id;
1351         memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1352
1353         /*
1354          *  Now that we've sanity checked the packet, we can allocate
1355          *  memory for it, and copy the data from the local area to
1356          *  the packet buffer.
1357          */
1358         if ((packet->data = malloc(packet->data_len)) == NULL) {
1359           free(packet);
1360           librad_log("out of memory");
1361           return NULL;
1362         }
1363         memcpy(packet->data, data, packet->data_len);
1364
1365         return packet;
1366 }
1367
1368
1369 /*
1370  *      Verify the signature of a packet.
1371  */
1372 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1373                const char *secret)
1374 {
1375         uint8_t                 *ptr;
1376         int                     length;
1377         int                     attrlen;
1378
1379         if (!packet || !packet->data) return -1;
1380
1381         /*
1382          *      Before we allocate memory for the attributes, do more
1383          *      sanity checking.
1384          */
1385         ptr = packet->data + AUTH_HDR_LEN;
1386         length = packet->data_len - AUTH_HDR_LEN;
1387         while (length > 0) {
1388                 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1389                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1390
1391                 attrlen = ptr[1];
1392
1393                 switch (ptr[0]) {
1394                 default:        /* don't do anything. */
1395                         break;
1396
1397                         /*
1398                          *      Note that more than one Message-Authenticator
1399                          *      attribute is invalid.
1400                          */
1401                 case PW_MESSAGE_AUTHENTICATOR:
1402                         memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1403                         memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1404
1405                         switch (packet->code) {
1406                         default:
1407                                 break;
1408
1409                         case PW_ACCOUNTING_REQUEST:
1410                         case PW_ACCOUNTING_RESPONSE:
1411                         case PW_DISCONNECT_REQUEST:
1412                         case PW_DISCONNECT_ACK:
1413                         case PW_DISCONNECT_NAK:
1414                         case PW_COA_REQUEST:
1415                         case PW_COA_ACK:
1416                         case PW_COA_NAK:
1417                                 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1418                                 break;
1419
1420                         case PW_AUTHENTICATION_ACK:
1421                         case PW_AUTHENTICATION_REJECT:
1422                         case PW_ACCESS_CHALLENGE:
1423                                 if (!original) {
1424                                         librad_log("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1425                                         return -1;
1426                                 }
1427                                 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1428                                 break;
1429                         }
1430
1431                         lrad_hmac_md5(packet->data, packet->data_len,
1432                                       secret, strlen(secret), calc_auth_vector);
1433                         if (memcmp(calc_auth_vector, msg_auth_vector,
1434                                    sizeof(calc_auth_vector)) != 0) {
1435                                 char buffer[32];
1436                                 librad_log("Received packet from %s with invalid Message-Authenticator!  (Shared secret is incorrect.)",
1437                                            ip_ntoa(buffer, packet->src_ipaddr));
1438                                 /* Silently drop packet, according to RFC 3579 */
1439                                 return -2;
1440                         } /* else the message authenticator was good */
1441
1442                         /*
1443                          *      Reinitialize Authenticators.
1444                          */
1445                         memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
1446                         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1447                         break;
1448                 } /* switch over the attributes */
1449
1450                 ptr += attrlen;
1451                 length -= attrlen;
1452         } /* loop over the packet, sanity checking the attributes */
1453
1454         /*
1455          *      Calculate and/or verify digest.
1456          */
1457         switch(packet->code) {
1458                 int rcode;
1459
1460                 case PW_AUTHENTICATION_REQUEST:
1461                 case PW_STATUS_SERVER:
1462                 case PW_DISCONNECT_REQUEST:
1463                         /*
1464                          *      The authentication vector is random
1465                          *      nonsense, invented by the client.
1466                          */
1467                         break;
1468
1469                 case PW_ACCOUNTING_REQUEST:
1470                         if (calc_acctdigest(packet, secret) > 1) {
1471                                 char buffer[32];
1472                                 librad_log("Received Accounting-Request packet "
1473                                            "from %s with invalid signature!  (Shared secret is incorrect.)",
1474                                            ip_ntoa(buffer, packet->src_ipaddr));
1475                                 return -1;
1476                         }
1477                         break;
1478
1479                         /* Verify the reply digest */
1480                 case PW_AUTHENTICATION_ACK:
1481                 case PW_AUTHENTICATION_REJECT:
1482                 case PW_ACCESS_CHALLENGE:
1483                 case PW_ACCOUNTING_RESPONSE:
1484                         rcode = calc_replydigest(packet, original, secret);
1485                         if (rcode > 1) {
1486                                 char buffer[32];
1487                                 librad_log("Received %s packet "
1488                                            "from client %s port %d with invalid signature (err=%d)!  (Shared secret is incorrect.)",
1489                                            packet_codes[packet->code],
1490                                            ip_ntoa(buffer, packet->src_ipaddr),
1491                                            packet->src_port,
1492                                            rcode);
1493                                 return -1;
1494                         }
1495                   break;
1496         }
1497
1498         return 0;
1499 }
1500
1501
1502 /*
1503  *      Parse a RADIUS attribute into a data structure.
1504  */
1505 static VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1506                         const char *secret, int attribute, int length,
1507                         const uint8_t *data)
1508 {
1509         int offset = 0;
1510         VALUE_PAIR *vp;
1511
1512         if ((vp = paircreate(attribute, PW_TYPE_OCTETS)) == NULL) {
1513                 return NULL;
1514         }
1515         
1516         /*
1517          *      If length is greater than 253, something is SERIOUSLY
1518          *      wrong.
1519          */
1520         if (length > 253) length = 253; /* paranoia (pair-anoia?) */
1521
1522         vp->length = length;
1523         vp->operator = T_OP_EQ;
1524         vp->next = NULL;
1525
1526         /*
1527          *      Handle tags.
1528          */
1529         if (vp->flags.has_tag) {
1530                 if (TAG_VALID(data[0]) ||
1531                     (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
1532                         /*
1533                          *      Tunnel passwords REQUIRE a tag, even
1534                          *      if don't have a valid tag.
1535                          */
1536                         vp->flags.tag = data[0];
1537
1538                         if ((vp->type == PW_TYPE_STRING) ||
1539                             (vp->type == PW_TYPE_OCTETS)) offset = 1;
1540                 }
1541         }
1542
1543         /*
1544          *      Copy the data to be decrypted
1545          */
1546         memcpy(&vp->strvalue[0], data + offset, length - offset);
1547         vp->length -= offset;
1548
1549         /*
1550          *      Decrypt the attribute.
1551          */
1552         switch (vp->flags.encrypt) {
1553                 /*
1554                  *  User-Password
1555                  */
1556         case FLAG_ENCRYPT_USER_PASSWORD:
1557                 if (original) {
1558                         rad_pwdecode((char *)vp->strvalue,
1559                                      vp->length, secret,
1560                                      original->vector);
1561                 } else {
1562                         rad_pwdecode((char *)vp->strvalue,
1563                                      vp->length, secret,
1564                                      packet->vector);
1565                 }
1566                 if (vp->attribute == PW_USER_PASSWORD) {
1567                         vp->length = strlen(vp->strvalue);
1568                 }
1569                 break;
1570                 
1571                 /*
1572                  *      Tunnel-Password's may go ONLY
1573                  *      in response packets.
1574                  */
1575         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
1576                 if (!original) goto raw;
1577                 
1578                 if (rad_tunnel_pwdecode(vp->strvalue, &vp->length,
1579                                         secret, original->vector) < 0) {
1580                         goto raw;
1581                 }
1582                 break;
1583                 
1584                 /*
1585                  *  Ascend-Send-Secret
1586                  *  Ascend-Receive-Secret
1587                  */
1588         case FLAG_ENCRYPT_ASCEND_SECRET:
1589                 if (!original) {
1590                         goto raw;
1591                 } else {
1592                         uint8_t my_digest[AUTH_VECTOR_LEN];
1593                         make_secret(my_digest,
1594                                     original->vector,
1595                                     secret, data);
1596                         memcpy(vp->strvalue, my_digest,
1597                                AUTH_VECTOR_LEN );
1598                         vp->strvalue[AUTH_VECTOR_LEN] = '\0';
1599                         vp->length = strlen(vp->strvalue);
1600                 }
1601                 break;
1602
1603         default:
1604                 break;
1605         } /* switch over encryption flags */
1606
1607
1608         switch (vp->type) {
1609         case PW_TYPE_STRING:
1610         case PW_TYPE_OCTETS:
1611         case PW_TYPE_ABINARY:
1612                 /* nothing more to do */
1613                 break;
1614
1615         case PW_TYPE_INTEGER:
1616                 if (vp->length != 4) goto raw;
1617
1618                 memcpy(&vp->lvalue, vp->strvalue, 4);
1619                 vp->lvalue = ntohl(vp->lvalue);
1620
1621                 if (vp->flags.has_tag) vp->lvalue &= 0x00ffffff;
1622
1623                 /*
1624                  *      Try to get named VALUEs
1625                  */
1626                 {
1627                         DICT_VALUE *dval;
1628                         dval = dict_valbyattr(vp->attribute,
1629                                               vp->lvalue);
1630                         if (dval) {
1631                                 strNcpy(vp->strvalue,
1632                                         dval->name,
1633                                         sizeof(vp->strvalue));
1634                         }
1635                 }
1636                 break;
1637
1638         case PW_TYPE_DATE:
1639                 if (vp->length != 4) goto raw;
1640
1641                 memcpy(&vp->lvalue, vp->strvalue, 4);
1642                 vp->lvalue = ntohl(vp->lvalue);
1643                 break;
1644
1645                 /*
1646                  *      IPv4 address. Keep it in network byte order in
1647                  *      vp->lvalue and put ASCII IP address in standard
1648                  *      dot notation into vp->strvalue.
1649                  */
1650         case PW_TYPE_IPADDR:
1651                 if (vp->length != 4) goto raw;
1652
1653                 memcpy(&vp->lvalue, vp->strvalue, 4);
1654                 ip_ntoa(vp->strvalue, vp->lvalue);
1655                 break;
1656
1657                 /*
1658                  *      IPv6 interface ID is 8 octets long.
1659                  */
1660         case PW_TYPE_IFID:
1661                 if (vp->length != 8) goto raw;
1662                 /* vp->vp_ifid == vp->strvalue */
1663                 break;
1664                 
1665                 /*
1666                  *      IPv6 addresses are 16 octets long
1667                  */
1668         case PW_TYPE_IPV6ADDR:
1669                 if (vp->length != 16) goto raw;
1670                 /* vp->vp_ipv6addr == vp->strvalue */
1671                 break;
1672                 
1673                 /*
1674                  *      IPv6 prefixes are 2 to 18 octets long.
1675                  *
1676                  *      RFC 3162: The first octet is unused.
1677                  *      The second is the length of the prefix
1678                  *      the rest are the prefix data.
1679                  *
1680                  *      The prefix length can have value 0 to 128.
1681                  */
1682         case PW_TYPE_IPV6PREFIX:
1683                 if (vp->length < 2 || vp->length > 18) goto raw;
1684                 if (vp->strvalue[1] > 128) goto raw;
1685
1686                 /*
1687                  *      FIXME: double-check that
1688                  *      (vp->strvalue[1] >> 3) matches vp->length + 2
1689                  */
1690                 if (vp->length < 18) {
1691                         memset(vp->strvalue + vp->length, 0,
1692                                18 - vp->length);
1693                 }
1694                 break;
1695
1696         default:
1697         raw:
1698                 vp->type = PW_TYPE_OCTETS;
1699                 vp->length = length;
1700                 memcpy(vp->strvalue, data, length);
1701                 
1702
1703                 /*
1704                  *      Ensure there's no encryption or tag stuff,
1705                  *      we just pass the attribute as-is.
1706                  */
1707                 memset(&vp->flags, 0, sizeof(vp->flags));
1708         }
1709
1710         return vp;
1711 }
1712
1713
1714 /*
1715  *      Calculate/check digest, and decode radius attributes.
1716  */
1717 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1718                const char *secret)
1719 {
1720         uint32_t                lvalue;
1721         uint32_t                vendorcode;
1722         VALUE_PAIR              **tail;
1723         VALUE_PAIR              *pair;
1724         uint8_t                 *ptr;
1725         int                     packet_length;
1726         int                     attribute;
1727         int                     attrlen;
1728         int                     vendorlen;
1729         radius_packet_t         *hdr;
1730         int                     vsa_tlen, vsa_llen;
1731         DICT_VENDOR             *dv = NULL;
1732
1733         /*
1734          *      Extract attribute-value pairs
1735          */
1736         hdr = (radius_packet_t *)packet->data;
1737         ptr = hdr->data;
1738         packet_length = packet->data_len - AUTH_HDR_LEN;
1739
1740         /*
1741          *      There may be VP's already in the packet.  Don't
1742          *      destroy them.
1743          */
1744         for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
1745                 /* nothing */
1746         }
1747
1748         vendorcode = 0;
1749         vendorlen  = 0;
1750         vsa_tlen = vsa_llen = 1;
1751
1752         /*
1753          *      We have to read at least two bytes.
1754          *
1755          *      rad_recv() above ensures that this is OK.
1756          */
1757         while (packet_length > 0) {
1758                 attribute = -1;
1759                 attrlen = -1;
1760
1761                 /*
1762                  *      Normal attribute, handle it like normal.
1763                  */
1764                 if (vendorcode == 0) {
1765                         /*
1766                          *      No room to read attr/length,
1767                          *      or bad attribute, or attribute is
1768                          *      too short, or attribute is too long,
1769                          *      stop processing the packet.
1770                          */
1771                         if ((packet_length < 2) ||
1772                             (ptr[0] == 0) ||  (ptr[1] < 2) ||
1773                             (ptr[1] > packet_length)) break;
1774
1775                         attribute = *ptr++;
1776                         attrlen   = *ptr++;
1777
1778                         attrlen -= 2;
1779                         packet_length  -= 2;
1780
1781                         if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
1782                         
1783                         /*
1784                          *      No vendor code, or ONLY vendor code.
1785                          */
1786                         if (attrlen <= 4) goto create_pair;
1787
1788                         vendorlen = 0;
1789                 }
1790                 
1791                 /*
1792                  *      Handle Vendor-Specific
1793                  */
1794                 if (vendorlen == 0) {
1795                         uint8_t *subptr;
1796                         int sublen;
1797                         int myvendor;
1798                         
1799                         /*
1800                          *      attrlen was checked above.
1801                          */
1802                         memcpy(&lvalue, ptr, 4);
1803                         myvendor = ntohl(lvalue);
1804
1805                         /*
1806                          *      Zero isn't allowed.
1807                          */
1808                         if (myvendor == 0) goto create_pair;
1809                         
1810                         /*
1811                          *      This is an implementation issue.
1812                          *      We currently pack vendor into the upper
1813                          *      16 bits of a 32-bit attribute number,
1814                          *      so we can't handle vendor numbers larger
1815                          *      than 16 bits.
1816                          */
1817                         if (myvendor > 65535) goto create_pair;
1818                         
1819                         vsa_tlen = vsa_llen = 1;
1820                         dv = dict_vendorbyvalue(myvendor);
1821                         if (dv) {
1822                                 vsa_tlen = dv->type;
1823                                 vsa_llen = dv->length;
1824                         }
1825                         
1826                         /*
1827                          *      Sweep through the list of VSA's,
1828                          *      seeing if they exactly fill the
1829                          *      outer Vendor-Specific attribute.
1830                          *
1831                          *      If not, create a raw Vendor-Specific.
1832                          */
1833                         subptr = ptr + 4;
1834                         sublen = attrlen - 4;
1835
1836                         /*
1837                          *      See if we can parse it.
1838                          */
1839                         do {
1840                                 int myattr = 0;
1841
1842                                 /*
1843                                  *      Don't have a type, it's bad.
1844                                  */
1845                                 if (sublen < vsa_tlen) goto create_pair;
1846                                 
1847                                 /*
1848                                  *      Ensure that the attribute number
1849                                  *      is OK.
1850                                  */
1851                                 switch (vsa_tlen) {
1852                                 case 1:
1853                                         myattr = subptr[0];
1854                                         break;
1855                                         
1856                                 case 2:
1857                                         myattr = (subptr[0] << 8) | subptr[1];
1858                                         break;
1859                                         
1860                                 case 4:
1861                                         if ((subptr[0] != 0) ||
1862                                             (subptr[1] != 0)) goto create_pair;
1863                                         
1864                                         myattr = (subptr[2] << 8) | subptr[3];
1865                                         break;
1866                                         
1867                                         /*
1868                                          *      Our dictionary is broken.
1869                                          */
1870                                 default:
1871                                         goto create_pair;
1872                                 }
1873                                 
1874                                 /*
1875                                  *      Not enough room for one more
1876                                  *      attribute.  Die!
1877                                  */
1878                                 if (sublen < vsa_tlen + vsa_llen) goto create_pair;
1879                                 switch (vsa_llen) {
1880                                 case 0:
1881                                         attribute = (myvendor << 16) | myattr;
1882                                         ptr += 4 + vsa_tlen;
1883                                         attrlen -= (4 + vsa_tlen);
1884                                         packet_length -= 4 + vsa_tlen;
1885                                         goto create_pair;
1886
1887                                 case 1:
1888                                         if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen))
1889                                                 goto create_pair;
1890
1891                                         if (subptr[vsa_tlen] > sublen)
1892                                                 goto create_pair;
1893                                         sublen -= subptr[vsa_tlen];
1894                                         subptr += subptr[vsa_tlen];
1895                                         break;
1896
1897                                 case 2:
1898                                         if (subptr[vsa_tlen] != 0) goto create_pair;
1899                                         if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
1900                                                 goto create_pair;
1901                                         if (subptr[vsa_tlen + 1] > sublen)
1902                                                 goto create_pair;
1903                                         sublen -= subptr[vsa_tlen + 1];
1904                                         subptr += subptr[vsa_tlen + 1];
1905                                         break;
1906
1907                                         /*
1908                                          *      Our dictionaries are
1909                                          *      broken.
1910                                          */
1911                                 default:
1912                                         goto create_pair;
1913                                 }
1914                         } while (sublen > 0);
1915
1916                         vendorcode = myvendor;
1917                         vendorlen = attrlen - 4;
1918                         packet_length -= 4;
1919
1920                         ptr += 4;
1921                 }
1922
1923                 /*
1924                  *      attrlen is the length of this attribute.
1925                  *      total_len is the length of the encompassing
1926                  *      attribute.
1927                  */
1928                 switch (vsa_tlen) {
1929                 case 1:
1930                         attribute = ptr[0];
1931                         break;
1932                         
1933                 case 2:
1934                         attribute = (ptr[0] << 8) | ptr[1];
1935                         break;
1936
1937                 default:        /* can't hit this. */
1938                         return -1;
1939                 }
1940                 attribute |= (vendorcode << 16);
1941                 ptr += vsa_tlen;
1942
1943                 switch (vsa_llen) {
1944                 case 1:
1945                         attrlen = ptr[0] - (vsa_tlen + vsa_llen);
1946                         break;
1947                         
1948                 case 2:
1949                         attrlen = ptr[1] - (vsa_tlen + vsa_llen);
1950                         break;
1951
1952                 default:        /* can't hit this. */
1953                         return -1;
1954                 }
1955                 ptr += vsa_llen;
1956                 vendorlen -= vsa_tlen + vsa_llen + attrlen;
1957                 if (vendorlen == 0) vendorcode = 0;
1958                 packet_length -= (vsa_tlen + vsa_llen);
1959
1960                 /*
1961                  *      Create the attribute, setting the default type
1962                  *      to 'octects'.  If the type in the dictionary
1963                  *      is different, then the dictionary type will
1964                  *      over-ride this one.
1965                  */
1966         create_pair:
1967                 pair = rad_attr2vp(packet, original, secret,
1968                                  attribute, attrlen, ptr);
1969                 if (!pair) {
1970                         pairfree(&packet->vps);
1971                         librad_log("out of memory");
1972                         return -1;
1973                 }
1974
1975                 debug_pair(pair);
1976                 *tail = pair;
1977                 tail = &pair->next;
1978
1979                 ptr += attrlen;
1980                 packet_length -= attrlen;
1981         }
1982
1983         /*
1984          *      Merge information from the outside world into our
1985          *      random pool.
1986          */
1987         lrad_rand_seed(packet->data, AUTH_HDR_LEN);
1988           
1989         return 0;
1990 }
1991
1992
1993 /*
1994  *      Encode password.
1995  *
1996  *      We assume that the passwd buffer passed is big enough.
1997  *      RFC2138 says the password is max 128 chars, so the size
1998  *      of the passwd buffer must be at least 129 characters.
1999  *      Preferably it's just MAX_STRING_LEN.
2000  *
2001  *      int *pwlen is updated to the new length of the encrypted
2002  *      password - a multiple of 16 bytes.
2003  */
2004 int rad_pwencode(char *passwd, int *pwlen, const char *secret,
2005                  const char *vector)
2006 {
2007         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 1];
2008         char    digest[AUTH_VECTOR_LEN];
2009         int     i, n, secretlen;
2010         int     len;
2011
2012         /*
2013          *      Pad password to multiple of AUTH_PASS_LEN bytes.
2014          */
2015         len = *pwlen;
2016         if (len > 128) len = 128;
2017         *pwlen = len;
2018         if (len % AUTH_PASS_LEN != 0) {
2019                 n = AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
2020                 for (i = len; n > 0; n--, i++)
2021                         passwd[i] = 0;
2022                 len = *pwlen = i;
2023
2024         } else if (len == 0) {
2025                 memset(passwd, 0, AUTH_PASS_LEN);
2026                 *pwlen = len = AUTH_PASS_LEN;
2027         }
2028
2029         /*
2030          *      Use the secret to setup the decryption digest
2031          */
2032         secretlen = strlen(secret);
2033         memcpy(buffer, secret, secretlen);
2034         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2035         librad_md5_calc((u_char *)digest, buffer, secretlen + AUTH_VECTOR_LEN);
2036
2037         /*
2038          *      Now we can encode the password *in place*
2039          */
2040         for (i = 0; i < AUTH_PASS_LEN; i++)
2041                 passwd[i] ^= digest[i];
2042
2043         if (len <= AUTH_PASS_LEN) return 0;
2044
2045         /*
2046          *      Length > AUTH_PASS_LEN, so we need to use the extended
2047          *      algorithm.
2048          */
2049         for (n = 0; n < 128 && n <= (len - AUTH_PASS_LEN); n += AUTH_PASS_LEN) {
2050                 memcpy(buffer + secretlen, passwd + n, AUTH_PASS_LEN);
2051                 librad_md5_calc((u_char *)digest, buffer, secretlen + AUTH_PASS_LEN);
2052                 for (i = 0; i < AUTH_PASS_LEN; i++)
2053                         passwd[i + n + AUTH_PASS_LEN] ^= digest[i];
2054         }
2055
2056         return 0;
2057 }
2058
2059 /*
2060  *      Decode password.
2061  */
2062 int rad_pwdecode(char *passwd, int pwlen, const char *secret,
2063                  const char *vector)
2064 {
2065         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 1];
2066         char    digest[AUTH_VECTOR_LEN];
2067         char    r[AUTH_VECTOR_LEN];
2068         char    *s;
2069         int     i, n, secretlen;
2070         int     rlen;
2071
2072         /*
2073          *      Use the secret to setup the decryption digest
2074          */
2075         secretlen = strlen(secret);
2076         memcpy(buffer, secret, secretlen);
2077         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2078         librad_md5_calc((u_char *)digest, buffer, secretlen + AUTH_VECTOR_LEN);
2079
2080         /*
2081          *      Now we can decode the password *in place*
2082          */
2083         memcpy(r, passwd, AUTH_PASS_LEN);
2084         for (i = 0; i < AUTH_PASS_LEN && i < pwlen; i++)
2085                 passwd[i] ^= digest[i];
2086
2087         if (pwlen <= AUTH_PASS_LEN) {
2088                 passwd[pwlen+1] = 0;
2089                 return pwlen;
2090         }
2091
2092         /*
2093          *      Length > AUTH_PASS_LEN, so we need to use the extended
2094          *      algorithm.
2095          */
2096         rlen = ((pwlen - 1) / AUTH_PASS_LEN) * AUTH_PASS_LEN;
2097
2098         for (n = rlen; n > 0; n -= AUTH_PASS_LEN ) {
2099                 s = (n == AUTH_PASS_LEN) ? r : (passwd + n - AUTH_PASS_LEN);
2100                 memcpy(buffer + secretlen, s, AUTH_PASS_LEN);
2101                 librad_md5_calc((u_char *)digest, buffer, secretlen + AUTH_PASS_LEN);
2102                 for (i = 0; i < AUTH_PASS_LEN && (i + n) < pwlen; i++)
2103                         passwd[i + n] ^= digest[i];
2104         }
2105         passwd[pwlen] = 0;
2106
2107         return pwlen;
2108 }
2109
2110
2111 /*
2112  *      Encode Tunnel-Password attributes when sending them out on the wire.
2113  *
2114  *      int *pwlen is updated to the new length of the encrypted
2115  *      password - a multiple of 16 bytes.
2116  *
2117  *      This is per RFC-2868 which adds a two char SALT to the initial intermediate
2118  *      value MD5 hash.
2119  */
2120 int rad_tunnel_pwencode(char *passwd, int *pwlen, const char *secret,
2121                         const char *vector)
2122 {
2123         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
2124         unsigned char   digest[AUTH_VECTOR_LEN];
2125         char*   salt;
2126         int     i, n, secretlen;
2127         unsigned len, n2;
2128
2129         len = *pwlen;
2130
2131         if (len > 127) len = 127;
2132         /*
2133          * Shift the password 3 positions right to place a salt and original
2134          * length, tag will be added automatically on packet send
2135          */
2136         for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
2137         salt = passwd;
2138         passwd += 2;
2139         /*
2140          * save original password length as first password character;
2141          */
2142         *passwd = len;
2143         len += 1;
2144
2145
2146         /*
2147          *      Generate salt.  The RFC's say:
2148          *
2149          *      The high bit of salt[0] must be set, each salt in a
2150          *      packet should be unique, and they should be random
2151          *
2152          *      So, we set the high bit, add in a counter, and then
2153          *      add in some CSPRNG data.  should be OK..
2154          */
2155         salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
2156                    (lrad_rand() & 0x07));
2157         salt[1] = lrad_rand();
2158
2159         /*
2160          *      Padd password to multiple of AUTH_PASS_LEN bytes.
2161          */
2162         n = len % AUTH_PASS_LEN;
2163         if (n) {
2164                 n = AUTH_PASS_LEN - n;
2165                 for (; n > 0; n--, len++)
2166                         passwd[len] = 0;
2167         }
2168         /* set new password length */
2169         *pwlen = len + 2;
2170
2171         /*
2172          *      Use the secret to setup the decryption digest
2173          */
2174         secretlen = strlen(secret);
2175         memcpy(buffer, secret, secretlen);
2176
2177         for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
2178                 if (!n2) {
2179                         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2180                         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
2181                         librad_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
2182                 } else {
2183                         memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
2184                         librad_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
2185                 }
2186
2187                 for (i = 0; i < AUTH_PASS_LEN; i++) {
2188                         passwd[i + n2] ^= digest[i];
2189                 }
2190         }
2191         passwd[n2] = 0;
2192         return 0;
2193 }
2194
2195 /*
2196  *      Decode Tunnel-Password encrypted attributes.
2197  *
2198  *      Defined in RFC-2868, this uses a two char SALT along with the
2199  *      initial intermediate value, to differentiate it from the
2200  *      above.
2201  */
2202 int rad_tunnel_pwdecode(uint8_t *passwd, int *pwlen, const char *secret,
2203                         const char *vector)
2204 {
2205         uint8_t         buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
2206         uint8_t         digest[AUTH_VECTOR_LEN];
2207         uint8_t         decrypted[MAX_STRING_LEN + 1];
2208         int             secretlen;
2209         unsigned        i, n, len;
2210
2211         len = *pwlen;
2212
2213         /*
2214          *      We need at least a salt.
2215          */
2216         if (len < 2) {
2217                 librad_log("tunnel password is too short");
2218                 return -1;
2219         }
2220
2221         /*
2222          *      There's a salt, but no password.  Or, there's a salt
2223          *      and a 'data_len' octet.  It's wrong, but at least we
2224          *      can figure out what it means: the password is empty.
2225          *
2226          *      Note that this means we ignore the 'data_len' field,
2227          *      if the attribute length tells us that there's no
2228          *      more data.  So the 'data_len' field may be wrong,
2229          *      but that's ok...
2230          */
2231         if (len <= 3) {
2232                 passwd[0] = 0;
2233                 *pwlen = 0;
2234                 return 0;
2235         }
2236
2237         len -= 2;               /* discount the salt */
2238
2239         /*
2240          *      Use the secret to setup the decryption digest
2241          */
2242         secretlen = strlen(secret);
2243
2244         /*
2245          *      Set up the initial key:
2246          *
2247          *       b(1) = MD5(secret + vector + salt)
2248          */
2249         memcpy(buffer, secret, secretlen);
2250         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2251         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, passwd, 2);
2252         librad_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
2253
2254         /*
2255          *      A quick check: decrypt the first octet of the password,
2256          *      which is the 'data_len' field.  Ensure it's sane.
2257          *
2258          *      'n' doesn't include the 'data_len' octet
2259          *      'len' does.
2260          */
2261         n = passwd[2] ^ digest[0];
2262         if (n >= len) {
2263                 librad_log("tunnel password is too long for the attribute");
2264                 return -1;
2265         }
2266
2267         /*
2268          *      Loop over the data, decrypting it, and generating
2269          *      the key for the next round of decryption.
2270          */
2271         for (n = 0; n < len; n += AUTH_PASS_LEN) {
2272                 for (i = 0; i < AUTH_PASS_LEN; i++) {
2273                         decrypted[n + i] = passwd[n + i + 2] ^ digest[i];
2274
2275                         /*
2276                          *      Encrypted password may not be aligned
2277                          *      on 16 octets, so we catch that here...
2278                          */
2279                         if ((n + i) == len) break;
2280                 }
2281
2282                 /*
2283                  *      Update the digest, based on
2284                  *
2285                  *      b(n) = MD5(secret + cleartext(n-1)
2286                  *
2287                  *      but only if there's more data...
2288                  */
2289                 memcpy(buffer + secretlen, passwd + n + 2, AUTH_PASS_LEN);
2290                 librad_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
2291         }
2292
2293         /*
2294          *      We've already validated the length of the decrypted
2295          *      password.  Copy it back to the caller.
2296          */
2297         memcpy(passwd, decrypted + 1, decrypted[0]);
2298         passwd[decrypted[0]] = 0;
2299         *pwlen = decrypted[0];
2300
2301         return decrypted[0];
2302 }
2303
2304 /*
2305  *      Encode a CHAP password
2306  *
2307  *      FIXME: might not work with Ascend because
2308  *      we use vp->length, and Ascend gear likes
2309  *      to send an extra '\0' in the string!
2310  */
2311 int rad_chap_encode(RADIUS_PACKET *packet, char *output, int id,
2312                     VALUE_PAIR *password)
2313 {
2314         int             i;
2315         char            *ptr;
2316         char            string[MAX_STRING_LEN * 2 + 1];
2317         VALUE_PAIR      *challenge;
2318
2319         /*
2320          *      Sanity check the input parameters
2321          */
2322         if ((packet == NULL) || (password == NULL)) {
2323                 return -1;
2324         }
2325
2326         /*
2327          *      Note that the password VP can be EITHER
2328          *      a User-Password attribute (from a check-item list),
2329          *      or a CHAP-Password attribute (the client asking
2330          *      the library to encode it).
2331          */
2332
2333         i = 0;
2334         ptr = string;
2335         *ptr++ = id;
2336
2337         i++;
2338         memcpy(ptr, password->strvalue, password->length);
2339         ptr += password->length;
2340         i += password->length;
2341
2342         /*
2343          *      Use Chap-Challenge pair if present,
2344          *      Request-Authenticator otherwise.
2345          */
2346         challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
2347         if (challenge) {
2348                 memcpy(ptr, challenge->strvalue, challenge->length);
2349                 i += challenge->length;
2350         } else {
2351                 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
2352                 i += AUTH_VECTOR_LEN;
2353         }
2354
2355         *output = id;
2356         librad_md5_calc((u_char *)output + 1, (u_char *)string, i);
2357
2358         return 0;
2359 }
2360
2361
2362 /*
2363  *      Seed the random number generator.
2364  *
2365  *      May be called any number of times.
2366  */
2367 void lrad_rand_seed(const void *data, size_t size)
2368 {
2369         uint32_t hash;
2370
2371         /*
2372          *      Ensure that the pool is initialized.
2373          */
2374         if (lrad_rand_index < 0) {
2375                 int fd;
2376                 
2377                 memset(&lrad_rand_pool, 0, sizeof(lrad_rand_pool));
2378
2379                 fd = open("/dev/urandom", O_RDONLY);
2380                 if (fd >= 0) {
2381                         size_t total;
2382                         ssize_t this;
2383
2384                         total = this = 0;
2385                         while (total < sizeof(lrad_rand_pool.randrsl)) {
2386                                 this = read(fd, lrad_rand_pool.randrsl,
2387                                             sizeof(lrad_rand_pool.randrsl) - total);
2388                                 if ((this < 0) && (errno != EINTR)) break;
2389                                 if (this > 0) total += this;
2390                         }
2391                         close(fd);
2392                 } else {
2393                         lrad_rand_pool.randrsl[0] = fd;
2394                         lrad_rand_pool.randrsl[1] = time(NULL);
2395                         lrad_rand_pool.randrsl[2] = errno;
2396                 }
2397
2398                 lrad_randinit(&lrad_rand_pool, 1);
2399                 lrad_rand_index = 0;
2400         }
2401
2402         if (!data) return;
2403
2404         /*
2405          *      Hash the user data
2406          */
2407         hash = lrad_hash(data, size);
2408         
2409         lrad_rand_pool.randrsl[lrad_rand_index & 0xff] ^= hash;
2410         lrad_rand_index++;
2411         lrad_rand_index &= 0xff;
2412
2413         /*
2414          *      Churn the pool every so often after seeding it.
2415          */
2416         if (((int) (hash & 0xff)) == lrad_rand_index) {
2417                 lrad_isaac(&lrad_rand_pool);
2418         }
2419 }
2420
2421
2422 /*
2423  *      Return a 32-bit random number.
2424  */
2425 uint32_t lrad_rand(void)
2426 {
2427         uint32_t num;
2428
2429         /*
2430          *      Ensure that the pool is initialized.
2431          */
2432         if (lrad_rand_index < 0) {
2433                 lrad_rand_seed(NULL, 0);
2434         }
2435
2436         /*
2437          *      We don't return data directly from the pool.
2438          *      Rather, we return a summary of the data.
2439          */
2440         num = lrad_rand_pool.randrsl[lrad_rand_index & 0xff];
2441         lrad_rand_index++;
2442         lrad_rand_index &= 0xff;
2443
2444         /*
2445          *      Every so often, churn the pool.
2446          */
2447         if (((int) (num & 0xff)) == lrad_rand_index) {
2448                 lrad_isaac(&lrad_rand_pool);
2449         }
2450
2451         return num;
2452 }
2453
2454 /*
2455  *      Allocate a new RADIUS_PACKET
2456  */
2457 RADIUS_PACKET *rad_alloc(int newvector)
2458 {
2459         RADIUS_PACKET   *rp;
2460
2461         if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
2462                 librad_log("out of memory");
2463                 return NULL;
2464         }
2465         memset(rp, 0, sizeof(RADIUS_PACKET));
2466         if (newvector) {
2467                 int i;
2468                 uint32_t hash, base;
2469
2470                 /*
2471                  *      Don't expose the actual contents of the random
2472                  *      pool.
2473                  */
2474                 base = lrad_rand();
2475                 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
2476                         hash = lrad_rand() ^ base;
2477                         memcpy(rp->vector + i, &hash, sizeof(hash));
2478                 }
2479         }
2480         lrad_rand();
2481
2482         return rp;
2483 }
2484
2485 /*
2486  *      Free a RADIUS_PACKET
2487  */
2488 void rad_free(RADIUS_PACKET **radius_packet_ptr)
2489 {
2490         RADIUS_PACKET *radius_packet;
2491
2492         if (!radius_packet_ptr) return;
2493         radius_packet = *radius_packet_ptr;
2494
2495         if (radius_packet->data) free(radius_packet->data);
2496         if (radius_packet->vps) pairfree(&radius_packet->vps);
2497
2498         free(radius_packet);
2499
2500         *radius_packet_ptr = NULL;
2501 }