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