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