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