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