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