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