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