Added API to allocate a reply packet from a request packet.
[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 fr_max_attributes = 0;
57 FILE *fr_log_fp = NULL;
58
59 typedef struct radius_packet_t {
60   uint8_t       code;
61   uint8_t       id;
62   uint8_t       length[2];
63   uint8_t       vector[AUTH_VECTOR_LEN];
64   uint8_t       data[1];
65 } radius_packet_t;
66
67 static fr_randctx fr_rand_pool; /* across multiple calls */
68 static int fr_rand_initialized = 0;
69 static unsigned int salt_offset = 0;
70
71 const char *fr_packet_codes[FR_MAX_PACKET_CODE] = {
72   "",
73   "Access-Request",
74   "Access-Accept",
75   "Access-Reject",
76   "Accounting-Request",
77   "Accounting-Response",
78   "Accounting-Status",
79   "Password-Request",
80   "Password-Accept",
81   "Password-Reject",
82   "Accounting-Message",
83   "Access-Challenge",
84   "Status-Server",
85   "Status-Client",
86   "14",
87   "15",
88   "16",
89   "17",
90   "18",
91   "19",
92   "20",
93   "Resource-Free-Request",
94   "Resource-Free-Response",
95   "Resource-Query-Request",
96   "Resource-Query-Response",
97   "Alternate-Resource-Reclaim-Request",
98   "NAS-Reboot-Request",
99   "NAS-Reboot-Response",
100   "28",
101   "Next-Passcode",
102   "New-Pin",
103   "Terminate-Session",
104   "Password-Expired",
105   "Event-Request",
106   "Event-Response",
107   "35",
108   "36",
109   "37",
110   "38",
111   "39",
112   "Disconnect-Request",
113   "Disconnect-ACK",
114   "Disconnect-NAK",
115   "CoA-Request",
116   "CoA-ACK",
117   "CoA-NAK",
118   "46",
119   "47",
120   "48",
121   "49",
122   "IP-Address-Allocate",
123   "IP-Address-Release"
124 };
125
126
127 void fr_printf_log(const char *fmt, ...)
128 {
129         va_list ap;
130
131         va_start(ap, fmt);
132         if ((fr_debug_flag == 0) || !fr_log_fp) {
133                 va_end(ap);
134                 return;
135         }
136
137         vfprintf(fr_log_fp, fmt, ap);
138         va_end(ap);
139
140         return;
141 }
142
143 /*
144  *      Wrapper for sendto which handles sendfromto, IPv6, and all
145  *      possible combinations.
146  */
147 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
148                       fr_ipaddr_t *src_ipaddr, int src_port,
149                       fr_ipaddr_t *dst_ipaddr, int dst_port)
150 {
151         struct sockaddr_storage dst;
152         socklen_t               sizeof_dst;
153
154 #ifdef WITH_UDPFROMTO
155         struct sockaddr_storage src;
156         socklen_t               sizeof_src;
157
158         fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
159 #else
160         src_port = src_port;    /* -Wunused */
161 #endif
162
163         if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
164                 return -1;
165         }
166
167 #ifdef WITH_UDPFROMTO
168         /*
169          *      Only IPv4 is supported for udpfromto.
170          *
171          *      And if they don't specify a source IP address, don't
172          *      use udpfromto.
173          */
174         if ((dst_ipaddr->af == AF_INET) ||
175             (src_ipaddr->af != AF_UNSPEC)) {
176                 return sendfromto(sockfd, data, data_len, flags,
177                                   (struct sockaddr *)&src, sizeof_src,
178                                   (struct sockaddr *)&dst, sizeof_dst);
179         }
180 #else
181         src_ipaddr = src_ipaddr; /* -Wunused */
182 #endif
183
184         /*
185          *      No udpfromto, OR an IPv6 socket, fail gracefully.
186          */
187         return sendto(sockfd, data, data_len, flags,
188                       (struct sockaddr *) &dst, sizeof_dst);
189 }
190
191
192 void rad_recv_discard(int sockfd)
193 {
194         uint8_t                 header[4];
195         struct sockaddr_storage src;
196         socklen_t               sizeof_src = sizeof(src);
197
198         recvfrom(sockfd, header, sizeof(header), 0,
199                  (struct sockaddr *)&src, &sizeof_src);
200 }
201
202
203 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, int *src_port,
204                         int *code)
205 {
206         ssize_t                 data_len, packet_len;
207         uint8_t                 header[4];
208         struct sockaddr_storage src;
209         socklen_t               sizeof_src = sizeof(src);
210
211         data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
212                             (struct sockaddr *)&src, &sizeof_src);
213         if (data_len < 0) {
214                 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
215                 return -1;
216         }
217
218         /*
219          *      Too little data is available, discard the packet.
220          */
221         if (data_len < 4) {
222                 recvfrom(sockfd, header, sizeof(header), 0,
223                          (struct sockaddr *)&src, &sizeof_src);
224                 return 1;
225
226         } else {                /* we got 4 bytes of data. */
227                 /*
228                  *      See how long the packet says it is.
229                  */
230                 packet_len = (header[2] * 256) + header[3];
231
232                 /*
233                  *      The length in the packet says it's less than
234                  *      a RADIUS header length: discard it.
235                  */
236                 if (packet_len < AUTH_HDR_LEN) {
237                         recvfrom(sockfd, header, sizeof(header), 0,
238                                  (struct sockaddr *)&src, &sizeof_src);
239                         return 1;
240
241                         /*
242                          *      Enforce RFC requirements, for sanity.
243                          *      Anything after 4k will be discarded.
244                          */
245                 } else if (packet_len > MAX_PACKET_LEN) {
246                         recvfrom(sockfd, header, sizeof(header), 0,
247                                  (struct sockaddr *)&src, &sizeof_src);
248                         return 1;
249                 }
250         }
251
252         /*
253          *      Convert AF.  If unknown, discard packet.
254          */
255         if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
256                 recvfrom(sockfd, header, sizeof(header), 0,
257                          (struct sockaddr *)&src, &sizeof_src);
258                 return 1;
259         }
260
261         *code = header[0];
262
263         /*
264          *      The packet says it's this long, but the actual UDP
265          *      size could still be smaller.
266          */
267         return packet_len;
268 }
269
270
271 /*
272  *      wrapper for recvfrom, which handles recvfromto, IPv6, and all
273  *      possible combinations.
274  */
275 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
276                             fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
277                             fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
278 {
279         struct sockaddr_storage src;
280         struct sockaddr_storage dst;
281         socklen_t               sizeof_src = sizeof(src);
282         socklen_t               sizeof_dst = sizeof(dst);
283         ssize_t                 data_len;
284         uint8_t                 header[4];
285         void                    *buf;
286         size_t                  len;
287         int                     port;
288
289         memset(&src, 0, sizeof_src);
290         memset(&dst, 0, sizeof_dst);
291
292         /*
293          *      Get address family, etc. first, so we know if we
294          *      need to do udpfromto.
295          *
296          *      FIXME: udpfromto also does this, but it's not
297          *      a critical problem.
298          */
299         if (getsockname(sockfd, (struct sockaddr *)&dst,
300                         &sizeof_dst) < 0) return -1;
301
302         /*
303          *      Read the length of the packet, from the packet.
304          *      This lets us allocate the buffer to use for
305          *      reading the rest of the packet.
306          */
307         data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
308                             (struct sockaddr *)&src, &sizeof_src);
309         if (data_len < 0) {
310                 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
311                 return -1;
312         }
313
314         /*
315          *      Too little data is available, discard the packet.
316          */
317         if (data_len < 4) {
318                 recvfrom(sockfd, header, sizeof(header), flags,
319                          (struct sockaddr *)&src, &sizeof_src);
320                 return 0;
321
322         } else {                /* we got 4 bytes of data. */
323                 /*
324                  *      See how long the packet says it is.
325                  */
326                 len = (header[2] * 256) + header[3];
327
328                 /*
329                  *      The length in the packet says it's less than
330                  *      a RADIUS header length: discard it.
331                  */
332                 if (len < AUTH_HDR_LEN) {
333                         recvfrom(sockfd, header, sizeof(header), flags,
334                                  (struct sockaddr *)&src, &sizeof_src);
335                         return 0;
336
337                         /*
338                          *      Enforce RFC requirements, for sanity.
339                          *      Anything after 4k will be discarded.
340                          */
341                 } else if (len > MAX_PACKET_LEN) {
342                         recvfrom(sockfd, header, sizeof(header), flags,
343                                  (struct sockaddr *)&src, &sizeof_src);
344                         return len;
345                 }
346         }
347
348         buf = malloc(len);
349         if (!buf) return -1;
350
351         /*
352          *      Receive the packet.  The OS will discard any data in the
353          *      packet after "len" bytes.
354          */
355 #ifdef WITH_UDPFROMTO
356         if (dst.ss_family == AF_INET) {
357                 data_len = recvfromto(sockfd, buf, len, flags,
358                                       (struct sockaddr *)&src, &sizeof_src,
359                                       (struct sockaddr *)&dst, &sizeof_dst);
360         } else
361 #endif
362                 /*
363                  *      No udpfromto, OR an IPv6 socket.  Fail gracefully.
364                  */
365                 data_len = recvfrom(sockfd, buf, len, flags,
366                                     (struct sockaddr *)&src, &sizeof_src);
367         if (data_len < 0) {
368                 free(buf);
369                 return data_len;
370         }
371
372         if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
373                 free(buf);
374                 return -1;      /* Unknown address family, Die Die Die! */
375         }
376         *src_port = port;
377
378         fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
379         *dst_port = port;
380
381         /*
382          *      Different address families should never happen.
383          */
384         if (src.ss_family != dst.ss_family) {
385                 free(buf);
386                 return -1;
387         }
388
389         /*
390          *      Tell the caller about the data
391          */
392         *pbuf = buf;
393
394         return data_len;
395 }
396
397
398 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
399 /*************************************************************************
400  *
401  *      Function: make_secret
402  *
403  *      Purpose: Build an encrypted secret value to return in a reply
404  *               packet.  The secret is hidden by xoring with a MD5 digest
405  *               created from the shared secret and the authentication
406  *               vector.  We put them into MD5 in the reverse order from
407  *               that used when encrypting passwords to RADIUS.
408  *
409  *************************************************************************/
410 static void make_secret(uint8_t *digest, const uint8_t *vector,
411                         const char *secret, const uint8_t *value)
412 {
413         FR_MD5_CTX context;
414         int             i;
415
416         fr_MD5Init(&context);
417         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
418         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
419         fr_MD5Final(digest, &context);
420
421         for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
422                 digest[i] ^= value[i];
423         }
424 }
425
426 #define MAX_PASS_LEN (128)
427 static void make_passwd(uint8_t *output, int *outlen,
428                         const uint8_t *input, int inlen,
429                         const char *secret, const uint8_t *vector)
430 {
431         FR_MD5_CTX context, old;
432         uint8_t digest[AUTH_VECTOR_LEN];
433         uint8_t passwd[MAX_PASS_LEN];
434         int     i, n;
435         int     len;
436
437         /*
438          *      If the length is zero, round it up.
439          */
440         len = inlen;
441         if (len == 0) {
442                 len = AUTH_PASS_LEN;
443         }
444         else if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
445
446         else if ((len & 0x0f) != 0) {
447                 len += 0x0f;
448                 len &= ~0x0f;
449         }
450         *outlen = len;
451
452         memcpy(passwd, input, len);
453         memset(passwd + len, 0, sizeof(passwd) - len);
454
455         fr_MD5Init(&context);
456         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
457         old = context;
458
459         /*
460          *      Do first pass.
461          */
462         fr_MD5Update(&context, vector, AUTH_PASS_LEN);
463
464         for (n = 0; n < len; n += AUTH_PASS_LEN) {
465                 if (n > 0) {
466                         context = old;
467                         fr_MD5Update(&context,
468                                        passwd + n - AUTH_PASS_LEN,
469                                        AUTH_PASS_LEN);
470                 }
471
472                 fr_MD5Final(digest, &context);
473                 for (i = 0; i < AUTH_PASS_LEN; i++) {
474                         passwd[i + n] ^= digest[i];
475                 }
476         }
477
478         memcpy(output, passwd, len);
479 }
480
481 static void make_tunnel_passwd(uint8_t *output, int *outlen,
482                                const uint8_t *input, int inlen, int room,
483                                const char *secret, const uint8_t *vector)
484 {
485         FR_MD5_CTX context, old;
486         uint8_t digest[AUTH_VECTOR_LEN];
487         uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
488         int     i, n;
489         int     len;
490
491         /*
492          *      Be paranoid.
493          */
494         if (room > 253) room = 253;
495
496         /*
497          *      Account for 2 bytes of the salt, and round the room
498          *      available down to the nearest multiple of 16.  Then,
499          *      subtract one from that to account for the length byte,
500          *      and the resulting number is the upper bound on the data
501          *      to copy.
502          *
503          *      We could short-cut this calculation just be forcing
504          *      inlen to be no more than 239.  It would work for all
505          *      VSA's, as we don't pack multiple VSA's into one
506          *      attribute.
507          *
508          *      However, this calculation is more general, if a little
509          *      complex.  And it will work in the future for all possible
510          *      kinds of weird attribute packing.
511          */
512         room -= 2;
513         room -= (room & 0x0f);
514         room--;
515
516         if (inlen > room) inlen = room;
517
518         /*
519          *      Length of the encrypted data is password length plus
520          *      one byte for the length of the password.
521          */
522         len = inlen + 1;
523         if ((len & 0x0f) != 0) {
524                 len += 0x0f;
525                 len &= ~0x0f;
526         }
527         *outlen = len + 2;      /* account for the salt */
528
529         /*
530          *      Copy the password over.
531          */
532         memcpy(passwd + 3, input, inlen);
533         memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
534
535         /*
536          *      Generate salt.  The RFC's say:
537          *
538          *      The high bit of salt[0] must be set, each salt in a
539          *      packet should be unique, and they should be random
540          *
541          *      So, we set the high bit, add in a counter, and then
542          *      add in some CSPRNG data.  should be OK..
543          */
544         passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
545                      (fr_rand() & 0x07));
546         passwd[1] = fr_rand();
547         passwd[2] = inlen;      /* length of the password string */
548
549         fr_MD5Init(&context);
550         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
551         old = context;
552
553         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
554         fr_MD5Update(&context, &passwd[0], 2);
555
556         for (n = 0; n < len; n += AUTH_PASS_LEN) {
557                 if (n > 0) {
558                         context = old;
559                         fr_MD5Update(&context,
560                                        passwd + 2 + n - AUTH_PASS_LEN,
561                                        AUTH_PASS_LEN);
562                 }
563
564                 fr_MD5Final(digest, &context);
565                 for (i = 0; i < AUTH_PASS_LEN; i++) {
566                         passwd[i + 2 + n] ^= digest[i];
567                 }
568         }
569         memcpy(output, passwd, len + 2);
570 }
571
572 static int vp2data(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
573                    const char *secret, const VALUE_PAIR *vp, uint8_t *ptr,
574                    int offset, int room)
575 {
576         uint32_t lvalue;
577         size_t len;
578         const uint8_t *data;
579         uint8_t array[4];
580
581         /*
582          *      Set up the default sources for the data.
583          */
584         data = vp->vp_octets;
585         len = vp->length;
586
587         switch(vp->type) {
588         case PW_TYPE_STRING:
589         case PW_TYPE_OCTETS:
590         case PW_TYPE_IFID:
591         case PW_TYPE_IPV6ADDR:
592         case PW_TYPE_IPV6PREFIX:
593         case PW_TYPE_ABINARY:
594                 /* nothing more to do */
595                 break;
596
597         case PW_TYPE_BYTE:
598                 len = 1;        /* just in case */
599                 array[0] = vp->vp_integer & 0xff;
600                 data = array;
601                 offset = 0;
602                 break;
603
604         case PW_TYPE_SHORT:
605                 len = 2;        /* just in case */
606                 array[0] = (vp->vp_integer >> 8) & 0xff;
607                 array[1] = vp->vp_integer & 0xff;
608                 data = array;
609                 offset = 0;
610                 break;
611
612         case PW_TYPE_INTEGER:
613                 len = 4;        /* just in case */
614                 lvalue = htonl(vp->vp_integer);
615                 memcpy(array, &lvalue, sizeof(lvalue));
616
617                 /*
618                  *      Perhaps discard the first octet.
619                  */
620                 data = &array[offset];
621                 len -= offset;
622                 break;
623
624         case PW_TYPE_IPADDR:
625                 data = (const uint8_t *) &vp->vp_ipaddr;
626                 len = 4;        /* just in case */
627                 break;
628
629                 /*
630                  *  There are no tagged date attributes.
631                  */
632         case PW_TYPE_DATE:
633                 lvalue = htonl(vp->vp_date);
634                 data = (const uint8_t *) &lvalue;
635                 len = 4;        /* just in case */
636                 break;
637
638         case PW_TYPE_SIGNED:
639         {
640                 int32_t slvalue;
641
642                 len = 4;        /* just in case */
643                 slvalue = htonl(vp->vp_signed);
644                 memcpy(array, &slvalue, sizeof(slvalue));
645                 break;
646         }
647
648         case PW_TYPE_TLV:
649                 data = vp->vp_tlv;
650                 if (!data) {
651                         fr_strerror_printf("ERROR: Cannot encode NULL TLV");
652                         return -1;
653                 }
654                 break;
655
656         default:                /* unknown type: ignore it */
657                 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->type);
658                 return -1;
659         }
660
661         /*
662          *      Bound the data to 255 bytes.
663          */
664         if (len + offset > room) {
665                 len = room - offset;
666         }
667
668         /*
669          *      Encrypt the various password styles
670          *
671          *      Attributes with encrypted values MUST be less than
672          *      128 bytes long.
673          */
674         switch (vp->flags.encrypt) {
675         case FLAG_ENCRYPT_USER_PASSWORD:
676                 make_passwd(ptr + offset, &len,
677                             data, len,
678                             secret, packet->vector);
679                 break;
680
681         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
682                 /*
683                  *      Check if 255 - offset - total_length is less
684                  *      than 18.  If so, we can't fit the data into
685                  *      the available space, and we discard the
686                  *      attribute.
687                  *
688                  *      This is ONLY a problem if we have multiple VSA's
689                  *      in one Vendor-Specific, though.
690                  */
691                 if ((room - offset) < 18) return 0;
692
693                 switch (packet->code) {
694                 case PW_AUTHENTICATION_ACK:
695                 case PW_AUTHENTICATION_REJECT:
696                 case PW_ACCESS_CHALLENGE:
697                 default:
698                         if (!original) {
699                                 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
700                                 return -1;
701                         }
702                         make_tunnel_passwd(ptr + offset, &len,
703                                            data, len, room - offset,
704                                            secret, original->vector);
705                         break;
706                 case PW_ACCOUNTING_REQUEST:
707                 case PW_DISCONNECT_REQUEST:
708                 case PW_COA_REQUEST:
709                         make_tunnel_passwd(ptr + offset, &len,
710                                            data, len, room - offset,
711                                            secret, packet->vector);
712                         break;
713                 }
714                 break;
715
716                 /*
717                  *      The code above ensures that this attribute
718                  *      always fits.
719                  */
720         case FLAG_ENCRYPT_ASCEND_SECRET:
721                 make_secret(ptr + offset, packet->vector,
722                             secret, data);
723                 len = AUTH_VECTOR_LEN;
724                 break;
725
726
727         default:
728                 /*
729                  *      Just copy the data over
730                  */
731                 memcpy(ptr + offset, data, len);
732                 break;
733         } /* switch over encryption flags */
734
735         return len;
736 }
737
738
739 static VALUE_PAIR *rad_vp2tlv(VALUE_PAIR *vps)
740 {
741         int maxattr = 0;
742         int length, attribute;
743         uint8_t *ptr;
744         VALUE_PAIR *vp, *tlv;
745
746         attribute = vps->attribute & 0xffff00ff;
747         maxattr = vps->attribute & 0x0ff;
748
749         tlv = paircreate(attribute, PW_TYPE_TLV);
750         if (!tlv) return NULL;
751
752         tlv->length = 0;
753         for (vp = vps; vp != NULL; vp = vp->next) {
754                 /*
755                  *      Group the attributes ONLY until we see a
756                  *      non-TLV attribute.
757                  */
758                 if (!vp->flags.is_tlv ||
759                     vp->flags.encoded ||
760                     (vp->flags.encrypt != FLAG_ENCRYPT_NONE) ||
761                     ((vp->attribute & 0xffff00ff) != attribute) ||
762                     ((vp->attribute & 0x0000ff00) <= maxattr)) {
763                         break;
764                 }
765
766                 maxattr = vp->attribute & 0xff00;
767                 tlv->length += vp->length + 2;
768         }
769
770         if (!tlv->length) {
771                 pairfree(&tlv);
772                 return NULL;
773         }
774
775         tlv->vp_tlv = malloc(tlv->length);
776         if (!tlv->vp_tlv) {
777                 pairfree(&tlv);
778                 return NULL;
779         }
780
781         ptr = tlv->vp_tlv;
782         maxattr = vps->attribute & 0x0ff;
783         for (vp = vps; vp != NULL; vp = vp->next) {
784                 if (!vp->flags.is_tlv ||
785                     vp->flags.encoded ||
786                     (vp->flags.encrypt != FLAG_ENCRYPT_NONE) ||
787                     ((vp->attribute & 0xffff00ff) != attribute) ||
788                     ((vp->attribute & 0x0000ff00) <= maxattr)) {
789                         break;
790                 }
791
792                 maxattr = vp->attribute & 0xff00;
793                 length = vp2data(NULL, NULL, NULL, vp, ptr + 2, 0,
794                                  tlv->vp_tlv + tlv->length - ptr);
795                 if (length < 0) {
796                         vp->length = ptr - vp->vp_tlv;
797                         return tlv; /* should be a more serious error... */
798                 }
799
800                 /*
801                  *      Pack the attribute.
802                  */
803                 ptr[0] = (vp->attribute & 0xff00) >> 8;
804                 ptr[1] = (length & 0xff) + 2;
805
806                 ptr += vp->length + 2;
807                 vp->flags.encoded = 1;
808         }
809
810         return tlv;
811 }
812
813 /*
814  *      Pack data without any encryption.
815  *      start == start of RADIUS attribute
816  *      ptr   == continuation byte (i.e. one after length)
817  */
818 static int rad_vp2continuation(const VALUE_PAIR *vp, uint8_t *start,
819                                uint8_t *ptr)
820 {
821         size_t left, piece;
822         size_t hsize = (ptr - start);
823         uint8_t *this = start;
824         const uint8_t *data;
825         uint8_t header[16];
826         
827         /*
828          *      If it's too long and marked as encrypted, ignore it.
829          */
830         if (vp->flags.encrypt != FLAG_ENCRYPT_NONE) {
831                 return 0;
832         }
833         
834         memcpy(header, start, hsize);
835
836         left = vp->length;
837         
838         switch (vp->type) {
839         case PW_TYPE_TLV:
840                 data = vp->vp_tlv;
841                 break;
842
843         case PW_TYPE_OCTETS:
844         case PW_TYPE_STRING:
845                 data = vp->vp_octets;
846                 break;
847
848                 /*
849                  *      This is invalid.
850                  */
851         default:
852                 return 0;
853         }
854         
855         while (left > 0) {
856                 memcpy(this, header, hsize);
857                 ptr = this + hsize;
858                 
859                 /*
860                  *      254 to account for
861                  *      continuation flag.
862                  */
863                 if (left > (254 - hsize)) {
864                         piece = 254 - hsize;
865                         *(ptr++) = 0x80;
866                 } else {
867                         piece = left;
868                         *(ptr++) = 0x00;
869                 }
870                 
871                 memcpy(ptr, data, piece);
872                 this[1] = hsize + piece + 1;
873
874                 /*
875                  *      
876                  */
877                 this[hsize - 1] = hsize - 6 + 1 + piece;
878                 data += piece;
879                 ptr += piece;
880                 left -= piece;
881                 this = ptr;
882         }
883         
884         return (ptr - start);
885 }
886
887
888 /*
889  *      Parse a data structure into a RADIUS attribute.
890  */
891 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
892                 const char *secret, const VALUE_PAIR *vp, uint8_t *start)
893 {
894         int             vendorcode;
895         int             offset, len, total_length;
896         uint32_t        lvalue;
897         uint8_t         *ptr, *length_ptr, *vsa_length_ptr, *tlv_length_ptr;
898
899         ptr = start;
900         vendorcode = total_length = 0;
901         length_ptr = vsa_length_ptr = tlv_length_ptr = NULL;
902
903         /*
904          *      For interoperability, always put vendor attributes
905          *      into their own VSA.
906          */
907         if ((vendorcode = VENDOR(vp->attribute)) == 0) {
908                 *(ptr++) = vp->attribute & 0xFF;
909                 length_ptr = ptr;
910                 *(ptr++) = 2;
911                 total_length += 2;
912
913         } else {
914                 int vsa_tlen = 1;
915                 int vsa_llen = 1;
916                 int vsa_offset = 0;
917                 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
918
919                 /*
920                  *      This must be an RFC-format attribute.  If it
921                  *      wasn't, then the "decode" function would have
922                  *      made a Vendor-Specific attribute (i.e. type
923                  *      26), and we would have "vendorcode == 0" here.
924                  */
925                 if (dv) {
926                         vsa_tlen = dv->type;
927                         vsa_llen = dv->length;
928                         if (dv->flags) vsa_offset = 1;
929                 }
930
931                 /*
932                  *      Build a VSA header.
933                  */
934                 *ptr++ = PW_VENDOR_SPECIFIC;
935                 vsa_length_ptr = ptr;
936                 *ptr++ = 6;
937                 lvalue = htonl(vendorcode);
938                 memcpy(ptr, &lvalue, 4);
939                 ptr += 4;
940                 total_length += 6;
941
942                 switch (vsa_tlen) {
943                 case 1:
944                         ptr[0] = (vp->attribute & 0xFF);
945                         break;
946
947                 case 2:
948                         ptr[0] = ((vp->attribute >> 8) & 0xFF);
949                         ptr[1] = (vp->attribute & 0xFF);
950                         break;
951
952                 case 4:
953                         ptr[0] = 0;
954                         ptr[1] = 0;
955                         ptr[2] = ((vp->attribute >> 8) & 0xFF);
956                         ptr[3] = (vp->attribute & 0xFF);
957                         break;
958
959                 default:
960                         return 0; /* silently discard it */
961                 }
962                 ptr += vsa_tlen;
963
964                 switch (vsa_llen) {
965                 case 0:
966                         length_ptr = vsa_length_ptr;
967                         vsa_length_ptr = NULL;
968                         break;
969                 case 1:
970                         ptr[0] = 0;
971                         length_ptr = ptr;
972                         break;
973                 case 2:
974                         ptr[0] = 0;
975                         ptr[1] = 0;
976                         length_ptr = ptr + 1;
977                         break;
978
979                 default:
980                         return 0; /* silently discard it */
981                 }
982                 ptr += vsa_llen;
983
984                 /*
985                  *      Allow for some continuation.
986                  */
987                 if (vsa_offset) {
988                         /*
989                          *      Allow TLV's to be encoded, if someone
990                          *      manages to somehow encode the sub-tlv's.
991                          *
992                          *      FIXME: Keep track of room in the packet!
993                          */
994                         if (vp->length > (254 - (ptr - start))) {
995                                 return rad_vp2continuation(vp, start, ptr);
996                         }
997
998                         ptr[0] = 0x00;
999                         ptr++;
1000
1001                         /*
1002                          *      sub-TLV's can only be in one format.
1003                          */
1004                         if (vp->flags.is_tlv) {
1005                                 *(ptr++) = (vp->attribute & 0xff00) >> 8;
1006                                 tlv_length_ptr = ptr;
1007                                 *(ptr++) = 2;
1008                                 vsa_offset += 2;
1009                         }
1010                 }
1011
1012                 total_length += vsa_tlen + vsa_llen + vsa_offset;
1013                 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen + vsa_offset;
1014                 *length_ptr += vsa_tlen + vsa_llen + vsa_offset;
1015         }
1016
1017         offset = 0;
1018         if (vp->flags.has_tag) {
1019                 if (TAG_VALID(vp->flags.tag)) {
1020                         ptr[0] = vp->flags.tag & 0xff;
1021                         offset = 1;
1022
1023                 } else if (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD) {
1024                         /*
1025                          *      Tunnel passwords REQUIRE a tag, even
1026                          *      if don't have a valid tag.
1027                          */
1028                         ptr[0] = 0;
1029                         offset = 1;
1030                 } /* else don't write a tag */
1031         } /* else the attribute doesn't have a tag */
1032
1033         len = vp2data(packet, original, secret, vp, ptr, offset,
1034                       255 - total_length);
1035         if (len < 0) return -1;
1036
1037         /*
1038          *      Account for the tag (if any).
1039          */
1040         len += offset;
1041
1042         /*
1043          *      RFC 2865 section 5 says that zero-length attributes
1044          *      MUST NOT be sent.
1045          *
1046          *      ... and the WiMAX forum ignores this... because of
1047          *      one vendor.  Don't they have anything better to do
1048          *      with their time?
1049          */
1050         if ((len == 0) &&
1051             (vp->attribute != PW_CHARGEABLE_USER_IDENTITY)) return 0;
1052
1053         /*
1054          *      Update the various lengths.
1055          */
1056         *length_ptr += len;
1057         if (vsa_length_ptr) *vsa_length_ptr += len;
1058         if (tlv_length_ptr) *tlv_length_ptr += len;
1059         ptr += len;
1060         total_length += len;
1061
1062         return total_length;    /* of attribute */
1063 }
1064
1065
1066 /*
1067  *      Encode a packet.
1068  */
1069 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1070                const char *secret)
1071 {
1072         radius_packet_t *hdr;
1073         uint8_t         *ptr;
1074         uint16_t        total_length;
1075         int             len;
1076         VALUE_PAIR      *reply;
1077         const char      *what;
1078         char            ip_buffer[128];
1079
1080         /*
1081          *      For simplicity in the following logic, we allow
1082          *      the attributes to "overflow" the 4k maximum
1083          *      RADIUS packet size, by one attribute.
1084          *
1085          *      It's uint32_t, for alignment purposes.
1086          */
1087         uint32_t        data[(MAX_PACKET_LEN + 256) / 4];
1088
1089         if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1090                 what = fr_packet_codes[packet->code];
1091         } else {
1092                 what = "Reply";
1093         }
1094
1095         DEBUG("Sending %s of id %d to %s port %d\n",
1096               what, packet->id,
1097               inet_ntop(packet->dst_ipaddr.af,
1098                         &packet->dst_ipaddr.ipaddr,
1099                         ip_buffer, sizeof(ip_buffer)),
1100               packet->dst_port);
1101
1102         /*
1103          *      Double-check some things based on packet code.
1104          */
1105         switch (packet->code) {
1106         case PW_AUTHENTICATION_ACK:
1107         case PW_AUTHENTICATION_REJECT:
1108         case PW_ACCESS_CHALLENGE:
1109                 if (!original) {
1110                         fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1111                         return -1;
1112                 }
1113                 break;
1114
1115                 /*
1116                  *      These packet vectors start off as all zero.
1117                  */
1118         case PW_ACCOUNTING_REQUEST:
1119         case PW_DISCONNECT_REQUEST:
1120         case PW_COA_REQUEST:
1121                 memset(packet->vector, 0, sizeof(packet->vector));
1122                 break;
1123
1124         default:
1125                 break;
1126         }
1127
1128         /*
1129          *      Use memory on the stack, until we know how
1130          *      large the packet will be.
1131          */
1132         hdr = (radius_packet_t *) data;
1133
1134         /*
1135          *      Build standard header
1136          */
1137         hdr->code = packet->code;
1138         hdr->id = packet->id;
1139
1140         memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1141
1142         total_length = AUTH_HDR_LEN;
1143
1144         /*
1145          *      Load up the configuration values for the user
1146          */
1147         ptr = hdr->data;
1148         packet->offset = 0;
1149
1150         /*
1151          *      FIXME: Loop twice over the reply list.  The first time,
1152          *      calculate the total length of data.  The second time,
1153          *      allocate the memory, and fill in the VP's.
1154          *
1155          *      Hmm... this may be slower than just doing a small
1156          *      memcpy.
1157          */
1158
1159         /*
1160          *      Loop over the reply attributes for the packet.
1161          */
1162         for (reply = packet->vps; reply; reply = reply->next) {
1163                 /*
1164                  *      Ignore non-wire attributes
1165                  */
1166                 if ((VENDOR(reply->attribute) == 0) &&
1167                     ((reply->attribute & 0xFFFF) > 0xff)) {
1168 #ifndef NDEBUG
1169                         /*
1170                          *      Permit the admin to send BADLY formatted
1171                          *      attributes with a debug build.
1172                          */
1173                         if (reply->attribute == PW_RAW_ATTRIBUTE) {
1174                                 memcpy(ptr, reply->vp_octets, reply->length);
1175                                 len = reply->length;
1176                                 goto next;
1177                         }
1178 #endif
1179                         continue;
1180                 }
1181
1182                 /*
1183                  *      Set the Message-Authenticator to the correct
1184                  *      length and initial value.
1185                  */
1186                 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1187                         reply->length = AUTH_VECTOR_LEN;
1188                         memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1189
1190                         /*
1191                          *      Cache the offset to the
1192                          *      Message-Authenticator
1193                          */
1194                         packet->offset = total_length;
1195                 }
1196
1197                 /*
1198                  *      Print out ONLY the attributes which
1199                  *      we're sending over the wire, and print
1200                  *      them out BEFORE they're encrypted.
1201                  */
1202                 debug_pair(reply);
1203
1204                 /*
1205                  *      Print them in order, even if they were encoded
1206                  *      already.
1207                  */
1208                 len = 0;
1209                 if (reply->flags.encoded) goto next;
1210
1211                 if (reply->flags.is_tlv) {
1212                         VALUE_PAIR *tlv = rad_vp2tlv(reply);
1213                         if (tlv) {
1214                                 tlv->next = reply->next;
1215                                 reply->next = tlv;
1216                         }
1217
1218                         /*
1219                          *      The encoded flag MUST be set in reply!
1220                          */
1221                         reply = reply->next;
1222                 }
1223
1224                 len = rad_vp2attr(packet, original, secret, reply, ptr);
1225
1226                 if (len < 0) return -1;
1227
1228                 /*
1229                  *      Check that the packet is no more than 4k in
1230                  *      size, AFTER writing the attribute past the 4k
1231                  *      boundary, but BEFORE deciding to increase the
1232                  *      size of the packet. Note that the 'data'
1233                  *      buffer, above, is one attribute longer than
1234                  *      necessary, in order to permit this overflow.
1235                  */
1236                 if ((total_length + len) > MAX_PACKET_LEN) {
1237                         break;
1238                 }
1239
1240         next:
1241                 ptr += len;
1242                 total_length += len;
1243         } /* done looping over all attributes */
1244
1245         /*
1246          *      Fill in the rest of the fields, and copy the data over
1247          *      from the local stack to the newly allocated memory.
1248          *
1249          *      Yes, all this 'memcpy' is slow, but it means
1250          *      that we only allocate the minimum amount of
1251          *      memory for a request.
1252          */
1253         packet->data_len = total_length;
1254         packet->data = (uint8_t *) malloc(packet->data_len);
1255         if (!packet->data) {
1256                 fr_strerror_printf("Out of memory");
1257                 return -1;
1258         }
1259
1260         memcpy(packet->data, hdr, packet->data_len);
1261         hdr = (radius_packet_t *) packet->data;
1262
1263         total_length = htons(total_length);
1264         memcpy(hdr->length, &total_length, sizeof(total_length));
1265
1266         return 0;
1267 }
1268
1269
1270 /*
1271  *      Sign a previously encoded packet.
1272  */
1273 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1274              const char *secret)
1275 {
1276         radius_packet_t *hdr = (radius_packet_t *)packet->data;
1277
1278         /*
1279          *      It wasn't assigned an Id, this is bad!
1280          */
1281         if (packet->id < 0) {
1282                 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id.");
1283                 return -1;
1284         }
1285
1286         if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1287             (packet->offset < 0)) {
1288                 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1289                 return -1;
1290         }
1291
1292         /*
1293          *      If there's a Message-Authenticator, update it
1294          *      now, BEFORE updating the authentication vector.
1295          */
1296         if (packet->offset > 0) {
1297                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1298
1299                 switch (packet->code) {
1300                 case PW_ACCOUNTING_REQUEST:
1301                 case PW_ACCOUNTING_RESPONSE:
1302                 case PW_DISCONNECT_REQUEST:
1303                 case PW_DISCONNECT_ACK:
1304                 case PW_DISCONNECT_NAK:
1305                 case PW_COA_REQUEST:
1306                 case PW_COA_ACK:
1307                 case PW_COA_NAK:
1308                         memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1309                         break;
1310
1311                 case PW_AUTHENTICATION_ACK:
1312                 case PW_AUTHENTICATION_REJECT:
1313                 case PW_ACCESS_CHALLENGE:
1314                         if (!original) {
1315                                 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1316                                 return -1;
1317                         }
1318                         memcpy(hdr->vector, original->vector,
1319                                AUTH_VECTOR_LEN);
1320                         break;
1321
1322                 default:        /* others have vector already set to zero */
1323                         break;
1324
1325                 }
1326
1327                 /*
1328                  *      Set the authentication vector to zero,
1329                  *      calculate the signature, and put it
1330                  *      into the Message-Authenticator
1331                  *      attribute.
1332                  */
1333                 fr_hmac_md5(packet->data, packet->data_len,
1334                             (const uint8_t *) secret, strlen(secret),
1335                             calc_auth_vector);
1336                 memcpy(packet->data + packet->offset + 2,
1337                        calc_auth_vector, AUTH_VECTOR_LEN);
1338
1339                 /*
1340                  *      Copy the original request vector back
1341                  *      to the raw packet.
1342                  */
1343                 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1344         }
1345
1346         /*
1347          *      Switch over the packet code, deciding how to
1348          *      sign the packet.
1349          */
1350         switch (packet->code) {
1351                 /*
1352                  *      Request packets are not signed, bur
1353                  *      have a random authentication vector.
1354                  */
1355         case PW_AUTHENTICATION_REQUEST:
1356         case PW_STATUS_SERVER:
1357                 break;
1358
1359                 /*
1360                  *      Reply packets are signed with the
1361                  *      authentication vector of the request.
1362                  */
1363         default:
1364                 {
1365                         uint8_t digest[16];
1366
1367                         FR_MD5_CTX      context;
1368                         fr_MD5Init(&context);
1369                         fr_MD5Update(&context, packet->data, packet->data_len);
1370                         fr_MD5Update(&context, (const uint8_t *) secret,
1371                                      strlen(secret));
1372                         fr_MD5Final(digest, &context);
1373
1374                         memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1375                         memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1376                         break;
1377                 }
1378         }/* switch over packet codes */
1379
1380         return 0;
1381 }
1382
1383 /*
1384  *      Reply to the request.  Also attach
1385  *      reply attribute value pairs and any user message provided.
1386  */
1387 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1388              const char *secret)
1389 {
1390         VALUE_PAIR              *reply;
1391         const char              *what;
1392         char                    ip_buffer[128];
1393
1394         /*
1395          *      Maybe it's a fake packet.  Don't send it.
1396          */
1397         if (!packet || (packet->sockfd < 0)) {
1398                 return 0;
1399         }
1400
1401         if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1402                 what = fr_packet_codes[packet->code];
1403         } else {
1404                 what = "Reply";
1405         }
1406
1407         /*
1408          *  First time through, allocate room for the packet
1409          */
1410         if (!packet->data) {
1411                 /*
1412                  *      Encode the packet.
1413                  */
1414                 if (rad_encode(packet, original, secret) < 0) {
1415                         return -1;
1416                 }
1417
1418                 /*
1419                  *      Re-sign it, including updating the
1420                  *      Message-Authenticator.
1421                  */
1422                 if (rad_sign(packet, original, secret) < 0) {
1423                         return -1;
1424                 }
1425
1426                 /*
1427                  *      If packet->data points to data, then we print out
1428                  *      the VP list again only for debugging.
1429                  */
1430         } else if (fr_debug_flag) {
1431                 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1432                       inet_ntop(packet->dst_ipaddr.af,
1433                                 &packet->dst_ipaddr.ipaddr,
1434                                 ip_buffer, sizeof(ip_buffer)),
1435                       packet->dst_port);
1436
1437                 for (reply = packet->vps; reply; reply = reply->next) {
1438                         if ((VENDOR(reply->attribute) == 0) &&
1439                             ((reply->attribute & 0xFFFF) > 0xff)) continue;
1440                         debug_pair(reply);
1441                 }
1442         }
1443
1444         /*
1445          *      And send it on it's way.
1446          */
1447         return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1448                           &packet->src_ipaddr, packet->src_port,
1449                           &packet->dst_ipaddr, packet->dst_port);
1450 }
1451
1452
1453 /*
1454  *      Validates the requesting client NAS.  Calculates the
1455  *      signature based on the clients private key.
1456  */
1457 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1458 {
1459         uint8_t         digest[AUTH_VECTOR_LEN];
1460         FR_MD5_CTX              context;
1461
1462         /*
1463          *      Zero out the auth_vector in the received packet.
1464          *      Then append the shared secret to the received packet,
1465          *      and calculate the MD5 sum. This must be the same
1466          *      as the original MD5 sum (packet->vector).
1467          */
1468         memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1469
1470         /*
1471          *  MD5(packet + secret);
1472          */
1473         fr_MD5Init(&context);
1474         fr_MD5Update(&context, packet->data, packet->data_len);
1475         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1476         fr_MD5Final(digest, &context);
1477
1478         /*
1479          *      Return 0 if OK, 2 if not OK.
1480          */
1481         if (memcmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1482         return 0;
1483 }
1484
1485
1486 /*
1487  *      Validates the requesting client NAS.  Calculates the
1488  *      signature based on the clients private key.
1489  */
1490 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1491                             const char *secret)
1492 {
1493         uint8_t         calc_digest[AUTH_VECTOR_LEN];
1494         FR_MD5_CTX              context;
1495
1496         /*
1497          *      Very bad!
1498          */
1499         if (original == NULL) {
1500                 return 3;
1501         }
1502
1503         /*
1504          *  Copy the original vector in place.
1505          */
1506         memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1507
1508         /*
1509          *  MD5(packet + secret);
1510          */
1511         fr_MD5Init(&context);
1512         fr_MD5Update(&context, packet->data, packet->data_len);
1513         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1514         fr_MD5Final(calc_digest, &context);
1515
1516         /*
1517          *  Copy the packet's vector back to the packet.
1518          */
1519         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1520
1521         /*
1522          *      Return 0 if OK, 2 if not OK.
1523          */
1524         if (memcmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1525         return 0;
1526 }
1527
1528
1529 /*
1530  *      See if the data pointed to by PTR is a valid RADIUS packet.
1531  *
1532  *      packet is not 'const * const' because we may update data_len,
1533  *      if there's more data in the UDP packet than in the RADIUS packet.
1534  */
1535 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
1536 {
1537         uint8_t                 *attr;
1538         int                     totallen;
1539         int                     count;
1540         radius_packet_t         *hdr;
1541         char                    host_ipaddr[128];
1542         int                     require_ma = 0;
1543         int                     seen_ma = 0;
1544         int                     num_attributes;
1545
1546         /*
1547          *      Check for packets smaller than the packet header.
1548          *
1549          *      RFC 2865, Section 3., subsection 'length' says:
1550          *
1551          *      "The minimum length is 20 ..."
1552          */
1553         if (packet->data_len < AUTH_HDR_LEN) {
1554                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1555                            inet_ntop(packet->src_ipaddr.af,
1556                                      &packet->src_ipaddr.ipaddr,
1557                                      host_ipaddr, sizeof(host_ipaddr)),
1558                            packet->data_len, AUTH_HDR_LEN);
1559                 return 0;
1560         }
1561
1562         /*
1563          *      RFC 2865, Section 3., subsection 'length' says:
1564          *
1565          *      " ... and maximum length is 4096."
1566          */
1567         if (packet->data_len > MAX_PACKET_LEN) {
1568                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1569                            inet_ntop(packet->src_ipaddr.af,
1570                                      &packet->src_ipaddr.ipaddr,
1571                                      host_ipaddr, sizeof(host_ipaddr)),
1572                            packet->data_len, MAX_PACKET_LEN);
1573                 return 0;
1574         }
1575
1576         /*
1577          *      Check for packets with mismatched size.
1578          *      i.e. We've received 128 bytes, and the packet header
1579          *      says it's 256 bytes long.
1580          */
1581         totallen = (packet->data[2] << 8) | packet->data[3];
1582         hdr = (radius_packet_t *)packet->data;
1583
1584         /*
1585          *      Code of 0 is not understood.
1586          *      Code of 16 or greate is not understood.
1587          */
1588         if ((hdr->code == 0) ||
1589             (hdr->code >= FR_MAX_PACKET_CODE)) {
1590                 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code%d ",
1591                            inet_ntop(packet->src_ipaddr.af,
1592                                      &packet->src_ipaddr.ipaddr,
1593                                      host_ipaddr, sizeof(host_ipaddr)),
1594                            hdr->code);
1595                 return 0;
1596         }
1597
1598         /*
1599          *      Message-Authenticator is required in Status-Server
1600          *      packets, otherwise they can be trivially forged.
1601          */
1602         if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1603
1604         /*
1605          *      It's also required if the caller asks for it.
1606          */
1607         if (flags) require_ma = 1;
1608
1609         /*
1610          *      Repeat the length checks.  This time, instead of
1611          *      looking at the data we received, look at the value
1612          *      of the 'length' field inside of the packet.
1613          *
1614          *      Check for packets smaller than the packet header.
1615          *
1616          *      RFC 2865, Section 3., subsection 'length' says:
1617          *
1618          *      "The minimum length is 20 ..."
1619          */
1620         if (totallen < AUTH_HDR_LEN) {
1621                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1622                            inet_ntop(packet->src_ipaddr.af,
1623                                      &packet->src_ipaddr.ipaddr,
1624                                      host_ipaddr, sizeof(host_ipaddr)),
1625                            totallen, AUTH_HDR_LEN);
1626                 return 0;
1627         }
1628
1629         /*
1630          *      And again, for the value of the 'length' field.
1631          *
1632          *      RFC 2865, Section 3., subsection 'length' says:
1633          *
1634          *      " ... and maximum length is 4096."
1635          */
1636         if (totallen > MAX_PACKET_LEN) {
1637                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1638                            inet_ntop(packet->src_ipaddr.af,
1639                                      &packet->src_ipaddr.ipaddr,
1640                                      host_ipaddr, sizeof(host_ipaddr)),
1641                            totallen, MAX_PACKET_LEN);
1642                 return 0;
1643         }
1644
1645         /*
1646          *      RFC 2865, Section 3., subsection 'length' says:
1647          *
1648          *      "If the packet is shorter than the Length field
1649          *      indicates, it MUST be silently discarded."
1650          *
1651          *      i.e. No response to the NAS.
1652          */
1653         if (packet->data_len < totallen) {
1654                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1655                            inet_ntop(packet->src_ipaddr.af,
1656                                      &packet->src_ipaddr.ipaddr,
1657                                      host_ipaddr, sizeof(host_ipaddr)),
1658                            packet->data_len, totallen);
1659                 return 0;
1660         }
1661
1662         /*
1663          *      RFC 2865, Section 3., subsection 'length' says:
1664          *
1665          *      "Octets outside the range of the Length field MUST be
1666          *      treated as padding and ignored on reception."
1667          */
1668         if (packet->data_len > totallen) {
1669                 /*
1670                  *      We're shortening the packet below, but just
1671                  *      to be paranoid, zero out the extra data.
1672                  */
1673                 memset(packet->data + totallen, 0, packet->data_len - totallen);
1674                 packet->data_len = totallen;
1675         }
1676
1677         /*
1678          *      Walk through the packet's attributes, ensuring that
1679          *      they add up EXACTLY to the size of the packet.
1680          *
1681          *      If they don't, then the attributes either under-fill
1682          *      or over-fill the packet.  Any parsing of the packet
1683          *      is impossible, and will result in unknown side effects.
1684          *
1685          *      This would ONLY happen with buggy RADIUS implementations,
1686          *      or with an intentional attack.  Either way, we do NOT want
1687          *      to be vulnerable to this problem.
1688          */
1689         attr = hdr->data;
1690         count = totallen - AUTH_HDR_LEN;
1691         num_attributes = 0;
1692
1693         while (count > 0) {
1694                 /*
1695                  *      Attribute number zero is NOT defined.
1696                  */
1697                 if (attr[0] == 0) {
1698                         fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1699                                    inet_ntop(packet->src_ipaddr.af,
1700                                              &packet->src_ipaddr.ipaddr,
1701                                              host_ipaddr, sizeof(host_ipaddr)));
1702                         return 0;
1703                 }
1704
1705                 /*
1706                  *      Attributes are at LEAST as long as the ID & length
1707                  *      fields.  Anything shorter is an invalid attribute.
1708                  */
1709                 if (attr[1] < 2) {
1710                         fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1711                                    inet_ntop(packet->src_ipaddr.af,
1712                                              &packet->src_ipaddr.ipaddr,
1713                                              host_ipaddr, sizeof(host_ipaddr)),
1714                                    attr[0]);
1715                         return 0;
1716                 }
1717
1718                 /*
1719                  *      Sanity check the attributes for length.
1720                  */
1721                 switch (attr[0]) {
1722                 default:        /* don't do anything by default */
1723                         break;
1724
1725                         /*
1726                          *      If there's an EAP-Message, we require
1727                          *      a Message-Authenticator.
1728                          */
1729                 case PW_EAP_MESSAGE:
1730                         require_ma = 1;
1731                         break;
1732
1733                 case PW_MESSAGE_AUTHENTICATOR:
1734                         if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1735                                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1736                                            inet_ntop(packet->src_ipaddr.af,
1737                                                      &packet->src_ipaddr.ipaddr,
1738                                                      host_ipaddr, sizeof(host_ipaddr)),
1739                                            attr[1] - 2);
1740                                 return 0;
1741                         }
1742                         seen_ma = 1;
1743                         break;
1744                 }
1745
1746                 /*
1747                  *      FIXME: Look up the base 255 attributes in the
1748                  *      dictionary, and switch over their type.  For
1749                  *      integer/date/ip, the attribute length SHOULD
1750                  *      be 6.
1751                  */
1752                 count -= attr[1];       /* grab the attribute length */
1753                 attr += attr[1];
1754                 num_attributes++;       /* seen one more attribute */
1755         }
1756
1757         /*
1758          *      If the attributes add up to a packet, it's allowed.
1759          *
1760          *      If not, we complain, and throw the packet away.
1761          */
1762         if (count != 0) {
1763                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1764                            inet_ntop(packet->src_ipaddr.af,
1765                                      &packet->src_ipaddr.ipaddr,
1766                                      host_ipaddr, sizeof(host_ipaddr)));
1767                 return 0;
1768         }
1769
1770         /*
1771          *      If we're configured to look for a maximum number of
1772          *      attributes, and we've seen more than that maximum,
1773          *      then throw the packet away, as a possible DoS.
1774          */
1775         if ((fr_max_attributes > 0) &&
1776             (num_attributes > fr_max_attributes)) {
1777                 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1778                            inet_ntop(packet->src_ipaddr.af,
1779                                      &packet->src_ipaddr.ipaddr,
1780                                      host_ipaddr, sizeof(host_ipaddr)),
1781                            num_attributes, fr_max_attributes);
1782                 return 0;
1783         }
1784
1785         /*
1786          *      http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1787          *
1788          *      A packet with an EAP-Message attribute MUST also have
1789          *      a Message-Authenticator attribute.
1790          *
1791          *      A Message-Authenticator all by itself is OK, though.
1792          *
1793          *      Similarly, Status-Server packets MUST contain
1794          *      Message-Authenticator attributes.
1795          */
1796         if (require_ma && ! seen_ma) {
1797                 fr_strerror_printf("WARNING: Insecure packet from host %s:  Packet does not contain required Message-Authenticator attribute",
1798                            inet_ntop(packet->src_ipaddr.af,
1799                                      &packet->src_ipaddr.ipaddr,
1800                                      host_ipaddr, sizeof(host_ipaddr)));
1801                 return 0;
1802         }
1803
1804         /*
1805          *      Fill RADIUS header fields
1806          */
1807         packet->code = hdr->code;
1808         packet->id = hdr->id;
1809         memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1810
1811         return 1;
1812 }
1813
1814
1815 /*
1816  *      Receive UDP client requests, and fill in
1817  *      the basics of a RADIUS_PACKET structure.
1818  */
1819 RADIUS_PACKET *rad_recv(int fd, int flags)
1820 {
1821         RADIUS_PACKET           *packet;
1822
1823         /*
1824          *      Allocate the new request data structure
1825          */
1826         if ((packet = malloc(sizeof(*packet))) == NULL) {
1827                 fr_strerror_printf("out of memory");
1828                 return NULL;
1829         }
1830         memset(packet, 0, sizeof(*packet));
1831
1832         packet->data_len = rad_recvfrom(fd, &packet->data, 0,
1833                                         &packet->src_ipaddr, &packet->src_port,
1834                                         &packet->dst_ipaddr, &packet->dst_port);
1835
1836         /*
1837          *      Check for socket errors.
1838          */
1839         if (packet->data_len < 0) {
1840                 fr_strerror_printf("Error receiving packet: %s", strerror(errno));
1841                 /* packet->data is NULL */
1842                 free(packet);
1843                 return NULL;
1844         }
1845
1846         /*
1847          *      If the packet is too big, then rad_recvfrom did NOT
1848          *      allocate memory.  Instead, it just discarded the
1849          *      packet.
1850          */
1851         if (packet->data_len > MAX_PACKET_LEN) {
1852                 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1853                 /* packet->data is NULL */
1854                 free(packet);
1855                 return NULL;
1856         }
1857
1858         /*
1859          *      Read no data.  Continue.
1860          *      This check is AFTER the MAX_PACKET_LEN check above, because
1861          *      if the packet is larger than MAX_PACKET_LEN, we also have
1862          *      packet->data == NULL
1863          */
1864         if ((packet->data_len == 0) || !packet->data) {
1865                 fr_strerror_printf("Empty packet: Socket is not ready.");
1866                 free(packet);
1867                 return NULL;
1868         }
1869
1870         /*
1871          *      See if it's a well-formed RADIUS packet.
1872          */
1873         if (!rad_packet_ok(packet, flags)) {
1874                 rad_free(&packet);
1875                 return NULL;
1876         }
1877
1878         /*
1879          *      Remember which socket we read the packet from.
1880          */
1881         packet->sockfd = fd;
1882
1883         /*
1884          *      FIXME: Do even more filtering by only permitting
1885          *      certain IP's.  The problem is that we don't know
1886          *      how to do this properly for all possible clients...
1887          */
1888
1889         /*
1890          *      Explicitely set the VP list to empty.
1891          */
1892         packet->vps = NULL;
1893
1894         if (fr_debug_flag) {
1895                 char host_ipaddr[128];
1896
1897                 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1898                         DEBUG("rad_recv: %s packet from host %s port %d",
1899                               fr_packet_codes[packet->code],
1900                               inet_ntop(packet->src_ipaddr.af,
1901                                         &packet->src_ipaddr.ipaddr,
1902                                         host_ipaddr, sizeof(host_ipaddr)),
1903                               packet->src_port);
1904                 } else {
1905                         DEBUG("rad_recv: Packet from host %s port %d code=%d",
1906                               inet_ntop(packet->src_ipaddr.af,
1907                                         &packet->src_ipaddr.ipaddr,
1908                                         host_ipaddr, sizeof(host_ipaddr)),
1909                               packet->src_port,
1910                               packet->code);
1911                 }
1912                 DEBUG(", id=%d, length=%d\n", packet->id, packet->data_len);
1913         }
1914
1915         return packet;
1916 }
1917
1918
1919 /*
1920  *      Verify the signature of a packet.
1921  */
1922 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1923                const char *secret)
1924 {
1925         uint8_t                 *ptr;
1926         int                     length;
1927         int                     attrlen;
1928
1929         if (!packet || !packet->data) return -1;
1930
1931         /*
1932          *      Before we allocate memory for the attributes, do more
1933          *      sanity checking.
1934          */
1935         ptr = packet->data + AUTH_HDR_LEN;
1936         length = packet->data_len - AUTH_HDR_LEN;
1937         while (length > 0) {
1938                 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1939                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1940
1941                 attrlen = ptr[1];
1942
1943                 switch (ptr[0]) {
1944                 default:        /* don't do anything. */
1945                         break;
1946
1947                         /*
1948                          *      Note that more than one Message-Authenticator
1949                          *      attribute is invalid.
1950                          */
1951                 case PW_MESSAGE_AUTHENTICATOR:
1952                         memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1953                         memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1954
1955                         switch (packet->code) {
1956                         default:
1957                                 break;
1958
1959                         case PW_ACCOUNTING_REQUEST:
1960                         case PW_ACCOUNTING_RESPONSE:
1961                         case PW_DISCONNECT_REQUEST:
1962                         case PW_DISCONNECT_ACK:
1963                         case PW_DISCONNECT_NAK:
1964                         case PW_COA_REQUEST:
1965                         case PW_COA_ACK:
1966                         case PW_COA_NAK:
1967                                 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1968                                 break;
1969
1970                         case PW_AUTHENTICATION_ACK:
1971                         case PW_AUTHENTICATION_REJECT:
1972                         case PW_ACCESS_CHALLENGE:
1973                                 if (!original) {
1974                                         fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1975                                         return -1;
1976                                 }
1977                                 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1978                                 break;
1979                         }
1980
1981                         fr_hmac_md5(packet->data, packet->data_len,
1982                                     (const uint8_t *) secret, strlen(secret),
1983                                     calc_auth_vector);
1984                         if (memcmp(calc_auth_vector, msg_auth_vector,
1985                                    sizeof(calc_auth_vector)) != 0) {
1986                                 char buffer[32];
1987                                 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator!  (Shared secret is incorrect.)",
1988                                            inet_ntop(packet->src_ipaddr.af,
1989                                                      &packet->src_ipaddr.ipaddr,
1990                                                      buffer, sizeof(buffer)));
1991                                 /* Silently drop packet, according to RFC 3579 */
1992                                 return -1;
1993                         } /* else the message authenticator was good */
1994
1995                         /*
1996                          *      Reinitialize Authenticators.
1997                          */
1998                         memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
1999                         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2000                         break;
2001                 } /* switch over the attributes */
2002
2003                 ptr += attrlen;
2004                 length -= attrlen;
2005         } /* loop over the packet, sanity checking the attributes */
2006
2007         /*
2008          *      It looks like a RADIUS packet, but we can't validate
2009          *      the signature.
2010          */
2011         if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2012                 char buffer[32];
2013                 fr_strerror_printf("Received Unknown packet code %d "
2014                            "from client %s port %d: Cannot validate signature.",
2015                            packet->code,
2016                            inet_ntop(packet->src_ipaddr.af,
2017                                      &packet->src_ipaddr.ipaddr,
2018                                      buffer, sizeof(buffer)),
2019                            packet->src_port);
2020                 return -1;
2021         }
2022
2023         /*
2024          *      Calculate and/or verify digest.
2025          */
2026         switch(packet->code) {
2027                 int rcode;
2028                 char buffer[32];
2029
2030                 case PW_AUTHENTICATION_REQUEST:
2031                 case PW_STATUS_SERVER:
2032                         /*
2033                          *      The authentication vector is random
2034                          *      nonsense, invented by the client.
2035                          */
2036                         break;
2037
2038                 case PW_COA_REQUEST:
2039                 case PW_DISCONNECT_REQUEST:
2040                 case PW_ACCOUNTING_REQUEST:
2041                         if (calc_acctdigest(packet, secret) > 1) {
2042                                 fr_strerror_printf("Received %s packet "
2043                                            "from %s with invalid signature!  (Shared secret is incorrect.)",
2044                                            fr_packet_codes[packet->code],
2045                                            inet_ntop(packet->src_ipaddr.af,
2046                                                      &packet->src_ipaddr.ipaddr,
2047                                                      buffer, sizeof(buffer)));
2048                                 return -1;
2049                         }
2050                         break;
2051
2052                         /* Verify the reply digest */
2053                 case PW_AUTHENTICATION_ACK:
2054                 case PW_AUTHENTICATION_REJECT:
2055                 case PW_ACCESS_CHALLENGE:
2056                 case PW_ACCOUNTING_RESPONSE:
2057                 case PW_DISCONNECT_ACK:
2058                 case PW_DISCONNECT_NAK:
2059                 case PW_COA_ACK:
2060                 case PW_COA_NAK:
2061                         rcode = calc_replydigest(packet, original, secret);
2062                         if (rcode > 1) {
2063                                 fr_strerror_printf("Received %s packet "
2064                                            "from client %s port %d with invalid signature (err=%d)!  (Shared secret is incorrect.)",
2065                                            fr_packet_codes[packet->code],
2066                                            inet_ntop(packet->src_ipaddr.af,
2067                                                      &packet->src_ipaddr.ipaddr,
2068                                                      buffer, sizeof(buffer)),
2069                                            packet->src_port,
2070                                            rcode);
2071                                 return -1;
2072                         }
2073                         break;
2074
2075                 default:
2076                         fr_strerror_printf("Received Unknown packet code %d "
2077                                    "from client %s port %d: Cannot validate signature",
2078                                    packet->code,
2079                                    inet_ntop(packet->src_ipaddr.af,
2080                                              &packet->src_ipaddr.ipaddr,
2081                                                      buffer, sizeof(buffer)),
2082                                    packet->src_port);
2083                         return -1;
2084         }
2085
2086         return 0;
2087 }
2088
2089
2090 static VALUE_PAIR *data2vp(const RADIUS_PACKET *packet,
2091                            const RADIUS_PACKET *original,
2092                            const char *secret, int attribute, int length,
2093                            const uint8_t *data, VALUE_PAIR *vp)
2094 {
2095         int offset = 0;
2096
2097         /*
2098          *      If length is greater than 253, something is SERIOUSLY
2099          *      wrong.
2100          */
2101         if (length > 253) length = 253; /* paranoia (pair-anoia?) */
2102
2103         vp->length = length;
2104         vp->operator = T_OP_EQ;
2105         vp->next = NULL;
2106
2107         /*
2108          *      Handle tags.
2109          */
2110         if (vp->flags.has_tag) {
2111                 if (TAG_VALID(data[0]) ||
2112                     (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
2113                         /*
2114                          *      Tunnel passwords REQUIRE a tag, even
2115                          *      if don't have a valid tag.
2116                          */
2117                         vp->flags.tag = data[0];
2118
2119                         if ((vp->type == PW_TYPE_STRING) ||
2120                             (vp->type == PW_TYPE_OCTETS)) offset = 1;
2121                 }
2122         }
2123
2124         /*
2125          *      Copy the data to be decrypted
2126          */
2127         memcpy(&vp->vp_octets[0], data + offset, length - offset);
2128         vp->length -= offset;
2129
2130         /*
2131          *      Decrypt the attribute.
2132          */
2133         switch (vp->flags.encrypt) {
2134                 /*
2135                  *  User-Password
2136                  */
2137         case FLAG_ENCRYPT_USER_PASSWORD:
2138                 if (original) {
2139                         rad_pwdecode((char *)vp->vp_strvalue,
2140                                      vp->length, secret,
2141                                      original->vector);
2142                 } else {
2143                         rad_pwdecode((char *)vp->vp_strvalue,
2144                                      vp->length, secret,
2145                                      packet->vector);
2146                 }
2147                 if (vp->attribute == PW_USER_PASSWORD) {
2148                         vp->length = strlen(vp->vp_strvalue);
2149                 }
2150                 break;
2151
2152                 /*
2153                  *      Tunnel-Password's may go ONLY
2154                  *      in response packets.
2155                  */
2156         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
2157                 if (!original) goto raw;
2158
2159                 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
2160                                         secret, original->vector) < 0) {
2161                         goto raw;
2162                 }
2163                 break;
2164
2165                 /*
2166                  *  Ascend-Send-Secret
2167                  *  Ascend-Receive-Secret
2168                  */
2169         case FLAG_ENCRYPT_ASCEND_SECRET:
2170                 if (!original) {
2171                         goto raw;
2172                 } else {
2173                         uint8_t my_digest[AUTH_VECTOR_LEN];
2174                         make_secret(my_digest,
2175                                     original->vector,
2176                                     secret, data);
2177                         memcpy(vp->vp_strvalue, my_digest,
2178                                AUTH_VECTOR_LEN );
2179                         vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2180                         vp->length = strlen(vp->vp_strvalue);
2181                 }
2182                 break;
2183
2184         default:
2185                 break;
2186         } /* switch over encryption flags */
2187
2188
2189         switch (vp->type) {
2190         case PW_TYPE_STRING:
2191         case PW_TYPE_OCTETS:
2192         case PW_TYPE_ABINARY:
2193                 /* nothing more to do */
2194                 break;
2195
2196         case PW_TYPE_BYTE:
2197                 if (vp->length != 1) goto raw;
2198
2199                 vp->vp_integer = vp->vp_octets[0];
2200                 break;
2201
2202
2203         case PW_TYPE_SHORT:
2204                 if (vp->length != 2) goto raw;
2205
2206                 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2207                 break;
2208
2209         case PW_TYPE_INTEGER:
2210                 if (vp->length != 4) goto raw;
2211
2212                 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2213                 vp->vp_integer = ntohl(vp->vp_integer);
2214
2215                 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2216
2217                 /*
2218                  *      Try to get named VALUEs
2219                  */
2220                 {
2221                         DICT_VALUE *dval;
2222                         dval = dict_valbyattr(vp->attribute,
2223                                               vp->vp_integer);
2224                         if (dval) {
2225                                 strlcpy(vp->vp_strvalue,
2226                                         dval->name,
2227                                         sizeof(vp->vp_strvalue));
2228                         }
2229                 }
2230                 break;
2231
2232         case PW_TYPE_DATE:
2233                 if (vp->length != 4) goto raw;
2234
2235                 memcpy(&vp->vp_date, vp->vp_octets, 4);
2236                 vp->vp_date = ntohl(vp->vp_date);
2237                 break;
2238
2239
2240         case PW_TYPE_IPADDR:
2241                 if (vp->length != 4) goto raw;
2242
2243                 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2244                 break;
2245
2246                 /*
2247                  *      IPv6 interface ID is 8 octets long.
2248                  */
2249         case PW_TYPE_IFID:
2250                 if (vp->length != 8) goto raw;
2251                 /* vp->vp_ifid == vp->vp_octets */
2252                 break;
2253
2254                 /*
2255                  *      IPv6 addresses are 16 octets long
2256                  */
2257         case PW_TYPE_IPV6ADDR:
2258                 if (vp->length != 16) goto raw;
2259                 /* vp->vp_ipv6addr == vp->vp_octets */
2260                 break;
2261
2262                 /*
2263                  *      IPv6 prefixes are 2 to 18 octets long.
2264                  *
2265                  *      RFC 3162: The first octet is unused.
2266                  *      The second is the length of the prefix
2267                  *      the rest are the prefix data.
2268                  *
2269                  *      The prefix length can have value 0 to 128.
2270                  */
2271         case PW_TYPE_IPV6PREFIX:
2272                 if (vp->length < 2 || vp->length > 18) goto raw;
2273                 if (vp->vp_octets[1] > 128) goto raw;
2274
2275                 /*
2276                  *      FIXME: double-check that
2277                  *      (vp->vp_octets[1] >> 3) matches vp->length + 2
2278                  */
2279                 if (vp->length < 18) {
2280                         memset(vp->vp_octets + vp->length, 0,
2281                                18 - vp->length);
2282                 }
2283                 break;
2284
2285         case PW_TYPE_SIGNED:
2286                 if (vp->length != 4) goto raw;
2287
2288                 /*
2289                  *      Overload vp_integer for ntohl, which takes
2290                  *      uint32_t, not int32_t
2291                  */
2292                 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2293                 vp->vp_integer = ntohl(vp->vp_integer);
2294                 memcpy(&vp->vp_signed, &vp->vp_integer, 4);
2295                 break;
2296
2297         case PW_TYPE_TLV:
2298                 vp->length = length;
2299                 vp->vp_tlv = malloc(length);
2300                 if (!vp->vp_tlv) {
2301                         pairfree(&vp);
2302                         fr_strerror_printf("No memory");
2303                         return NULL;
2304                 }
2305                 memcpy(vp->vp_tlv, data, length);
2306                 break;
2307
2308         case PW_TYPE_COMBO_IP:
2309                 if (vp->length == 4) {
2310                         vp->type = PW_TYPE_IPADDR;
2311                         memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2312                         break;
2313
2314                 } else if (vp->length == 16) {
2315                         vp->type = PW_TYPE_IPV6ADDR;
2316                         /* vp->vp_ipv6addr == vp->vp_octets */
2317                         break;
2318
2319                 }
2320                 /* FALL-THROUGH */
2321
2322         default:
2323         raw:
2324                 vp->type = PW_TYPE_OCTETS;
2325                 vp->length = length;
2326                 memcpy(vp->vp_octets, data, length);
2327
2328
2329                 /*
2330                  *      Ensure there's no encryption or tag stuff,
2331                  *      we just pass the attribute as-is.
2332                  */
2333                 memset(&vp->flags, 0, sizeof(vp->flags));
2334         }
2335
2336         return vp;
2337 }
2338
2339 static void rad_sortvp(VALUE_PAIR **head)
2340 {
2341         int swapped;
2342         VALUE_PAIR *vp, **tail;
2343
2344         /*
2345          *      Walk over the VP's, sorting them in order.  Did I
2346          *      mention that I hate WiMAX continuations?
2347          *
2348          *      And bubble sort!  WTF is up with that?
2349          */
2350         do {
2351                 swapped = 0;
2352                 tail = head;
2353                 while (*tail) {
2354                         vp = *tail;
2355                         if (!vp->next) break;
2356
2357                         if (vp->attribute > vp->next->attribute) {
2358                                 *tail = vp->next;
2359                                 vp->next = (*tail)->next;
2360                                 (*tail)->next = vp;
2361                                 swapped = 1;
2362                         }
2363                         tail = &(vp->next);
2364                 }
2365         } while (swapped);
2366 }
2367
2368
2369 /*
2370  *      Walk the packet, looking for continuations of this attribute.
2371  *
2372  *      This is (worst-case) O(N^2) in the number of RADIUS
2373  *      attributes.  That happens only when perverse clients create
2374  *      continued attributes, AND separate the fragmented portions
2375  *      with a lot of other attributes.
2376  *
2377  *      Sane clients should put the fragments next to each other, in
2378  *      which case this is O(N), in the number of fragments.
2379  */
2380 static uint8_t *rad_coalesce(int attribute, size_t length, uint8_t *data,
2381                              size_t packet_length, size_t *ptlv_length)
2382                              
2383 {
2384         uint32_t lvalue;
2385         size_t tlv_length = length;
2386         uint8_t *ptr, *tlv, *tlv_data;
2387
2388         for (ptr = data + length;
2389              ptr != (data + packet_length);
2390              ptr += ptr[1]) {
2391                 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2392                     (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2393                     (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2394                         continue;
2395                 }
2396
2397                 memcpy(&lvalue, ptr + 2, 4); /* Vendor Id */
2398                 lvalue = ntohl(lvalue);
2399                 lvalue <<= 16;
2400                 lvalue |= ptr[2 + 4]; /* add in VSA number */
2401                 if (lvalue != attribute) continue;
2402
2403                 /*
2404                  *      If the vendor-length is too small, it's badly
2405                  *      formed, so we stop.
2406                  */
2407                 if ((ptr[2 + 4 + 1]) < 3) break;
2408
2409                 tlv_length += ptr[2 + 4 + 1] - 3;
2410                 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2411         }
2412
2413         tlv = tlv_data = malloc(tlv_length);
2414         if (!tlv_data) return NULL;
2415
2416         memcpy(tlv, data, length);
2417         tlv += length;
2418
2419         /*
2420          *      Now we walk the list again, copying the data over to
2421          *      our newly created memory.
2422          */
2423         for (ptr = data + length;
2424              ptr != (data + packet_length);
2425              ptr += ptr[1]) {
2426                 int this_length;
2427
2428                 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2429                     (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2430                     (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2431                         continue;
2432                 }
2433
2434                 memcpy(&lvalue, ptr + 2, 4);
2435                 lvalue = ntohl(lvalue);
2436                 lvalue <<= 16;
2437                 lvalue |= ptr[2 + 4];
2438                 if (lvalue != attribute) continue;
2439
2440                 /*
2441                  *      If the vendor-length is too small, it's badly
2442                  *      formed, so we stop.
2443                  */
2444                 if ((ptr[2 + 4 + 1]) < 3) break;
2445
2446                 this_length = ptr[2 + 4 + 1] - 3;
2447                 memcpy(tlv, ptr + 2 + 4 + 3, this_length);
2448                 tlv += this_length;
2449
2450                 ptr[2 + 4] = 0; /* What a hack! */
2451                 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2452         }
2453
2454         *ptlv_length = tlv_length;
2455         return tlv_data;
2456 }
2457
2458 /*
2459  *      Start at the *data* portion of a continued attribute.  search
2460  *      through the rest of the attributes to find a matching one, and
2461  *      add it's contents to our contents.
2462  */
2463 static VALUE_PAIR *rad_continuation2vp(const RADIUS_PACKET *packet,
2464                                        const RADIUS_PACKET *original,
2465                                        const char *secret, int attribute,
2466                                        int length, /* CANNOT be zero */
2467                                        uint8_t *data, size_t packet_length,
2468                                        int flag, DICT_ATTR *da)
2469 {
2470         size_t tlv_length, left;
2471         uint8_t *ptr;
2472         uint8_t *tlv_data;
2473         VALUE_PAIR *vp, *head, **tail;
2474
2475         /*
2476          *      Ensure we have data that hasn't been split across
2477          *      multiple attributes.
2478          */
2479         if (flag) {
2480                 tlv_data = rad_coalesce(attribute, length,
2481                                         data, packet_length, &tlv_length);
2482                 if (!tlv_data) return NULL;
2483         } else {
2484                 tlv_data = data;
2485                 tlv_length = length;
2486         }
2487
2488         /*
2489          *      Non-TLV types cannot be continued across multiple
2490          *      attributes.  This is true even of keys that are
2491          *      encrypted with the tunnel-password method.  The spec
2492          *      says that they can be continued... but also that the
2493          *      keys are 160 bits, which means that they CANNOT be
2494          *      continued.  <sigh>
2495          *
2496          *      Note that we don't check "flag" here.  The calling
2497          *      code ensures that 
2498          */
2499         if (da->type != PW_TYPE_TLV) {
2500         not_well_formed:
2501                 if (tlv_data == data) { /* true if we had 'goto' */
2502                         tlv_data = malloc(tlv_length);
2503                         if (!tlv_data) return NULL;
2504                         memcpy(tlv_data, data, tlv_length);
2505                 }
2506                 
2507                 vp = paircreate(attribute, PW_TYPE_OCTETS);
2508                 if (!vp) return NULL;
2509                         
2510                 vp->type = PW_TYPE_TLV;
2511                 vp->flags.encrypt = FLAG_ENCRYPT_NONE;
2512                 vp->flags.has_tag = 0;
2513                 vp->flags.is_tlv = 0;
2514                 vp->vp_tlv = tlv_data;
2515                 vp->length = tlv_length;
2516                 return vp;
2517         } /* else it WAS a TLV, go decode the sub-tlv's */
2518
2519         /*
2520          *      Now (sigh) we walk over the TLV, seeing if it is
2521          *      well-formed.
2522          */
2523         left = tlv_length;
2524         for (ptr = tlv_data;
2525              ptr != (tlv_data + tlv_length);
2526              ptr += ptr[1]) {
2527                 if ((left < 2) ||
2528                     (ptr[1] < 2) ||
2529                     (ptr[1] > left)) {
2530                         goto not_well_formed;
2531                 }
2532                 left -= ptr[1];
2533         }
2534
2535         /*
2536          *      Now we walk over the TLV *again*, creating sub-tlv's.
2537          */
2538         head = NULL;
2539         tail = &head;
2540
2541         for (ptr = tlv_data;
2542              ptr != (tlv_data + tlv_length);
2543              ptr += ptr[1]) {
2544                 vp = paircreate(attribute | (ptr[0] << 8), PW_TYPE_OCTETS);
2545                 if (!vp) {
2546                         pairfree(&head);
2547                         goto not_well_formed;
2548                 }
2549
2550                 if (!data2vp(packet, original, secret,
2551                              ptr[0], ptr[1] - 2, ptr + 2, vp)) {
2552                         pairfree(&head);
2553                         goto not_well_formed;
2554                 }
2555
2556                 *tail = vp;
2557                 tail = &(vp->next);
2558         }
2559
2560         /*
2561          *      TLV's MAY be continued, but sometimes they're not.
2562          */
2563         if (tlv_data != data) free(tlv_data);
2564
2565         if (head->next) rad_sortvp(&head);
2566
2567         return head;
2568 }
2569
2570
2571 /*
2572  *      Parse a RADIUS attribute into a data structure.
2573  */
2574 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
2575                         const char *secret, int attribute, int length,
2576                         const uint8_t *data)
2577 {
2578         VALUE_PAIR *vp;
2579
2580         vp = paircreate(attribute, PW_TYPE_OCTETS);
2581         if (!vp) return NULL;
2582
2583         return data2vp(packet, original, secret, attribute, length, data, vp);
2584 }
2585
2586
2587 /*
2588  *      Calculate/check digest, and decode radius attributes.
2589  *      Returns:
2590  *      -1 on decoding error
2591  *      0 on success
2592  */
2593 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2594                const char *secret)
2595 {
2596         uint32_t                lvalue;
2597         uint32_t                vendorcode;
2598         VALUE_PAIR              **tail;
2599         VALUE_PAIR              *pair;
2600         uint8_t                 *ptr, *vsa_ptr;
2601         int                     packet_length;
2602         int                     attribute;
2603         int                     attrlen;
2604         int                     vendorlen;
2605         radius_packet_t         *hdr;
2606         int                     vsa_tlen, vsa_llen, vsa_offset;
2607         DICT_VENDOR             *dv = NULL;
2608         int                     num_attributes = 0;
2609
2610         /*
2611          *      Extract attribute-value pairs
2612          */
2613         hdr = (radius_packet_t *)packet->data;
2614         ptr = hdr->data;
2615         packet_length = packet->data_len - AUTH_HDR_LEN;
2616
2617         /*
2618          *      There may be VP's already in the packet.  Don't
2619          *      destroy them.
2620          */
2621         for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2622                 /* nothing */
2623         }
2624
2625         vendorcode = 0;
2626         vendorlen  = 0;
2627         vsa_tlen = vsa_llen = 1;
2628         vsa_offset = 0;
2629
2630         /*
2631          *      We have to read at least two bytes.
2632          *
2633          *      rad_recv() above ensures that this is OK.
2634          */
2635         while (packet_length > 0) {
2636                 attribute = -1;
2637                 attrlen = -1;
2638
2639                 /*
2640                  *      Normal attribute, handle it like normal.
2641                  */
2642                 if (vendorcode == 0) {
2643                         /*
2644                          *      No room to read attr/length,
2645                          *      or bad attribute, or attribute is
2646                          *      too short, or attribute is too long,
2647                          *      stop processing the packet.
2648                          */
2649                         if ((packet_length < 2) ||
2650                             (ptr[0] == 0) ||  (ptr[1] < 2) ||
2651                             (ptr[1] > packet_length)) break;
2652
2653                         attribute = *ptr++;
2654                         attrlen   = *ptr++;
2655
2656                         attrlen -= 2;
2657                         packet_length  -= 2;
2658
2659                         if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2660
2661                         /*
2662                          *      No vendor code, or ONLY vendor code.
2663                          */
2664                         if (attrlen <= 4) goto create_pair;
2665
2666                         vendorlen = 0;
2667                 }
2668
2669                 /*
2670                  *      Handle Vendor-Specific
2671                  */
2672                 if (vendorlen == 0) {
2673                         uint8_t *subptr;
2674                         int sublen;
2675                         int myvendor;
2676
2677                         /*
2678                          *      attrlen was checked above.
2679                          */
2680                         memcpy(&lvalue, ptr, 4);
2681                         myvendor = ntohl(lvalue);
2682
2683                         /*
2684                          *      Zero isn't allowed.
2685                          */
2686                         if (myvendor == 0) goto create_pair;
2687
2688                         /*
2689                          *      This is an implementation issue.
2690                          *      We currently pack vendor into the upper
2691                          *      16 bits of a 32-bit attribute number,
2692                          *      so we can't handle vendor numbers larger
2693                          *      than 16 bits.
2694                          */
2695                         if (myvendor > 65535) goto create_pair;
2696
2697                         vsa_tlen = vsa_llen = 1;
2698                         vsa_offset = 0;
2699                         dv = dict_vendorbyvalue(myvendor);
2700                         if (dv) {
2701                                 vsa_tlen = dv->type;
2702                                 vsa_llen = dv->length;
2703                                 if (dv->flags) vsa_offset = 1;
2704                         }
2705
2706                         /*
2707                          *      Sweep through the list of VSA's,
2708                          *      seeing if they exactly fill the
2709                          *      outer Vendor-Specific attribute.
2710                          *
2711                          *      If not, create a raw Vendor-Specific.
2712                          */
2713                         subptr = ptr + 4;
2714                         sublen = attrlen - 4;
2715
2716                         /*
2717                          *      See if we can parse it.
2718                          */
2719                         do {
2720                                 int myattr = 0;
2721
2722                                 /*
2723                                  *      Not enough room for one more
2724                                  *      attribute.  Die!
2725                                  */
2726                                 if (sublen < (vsa_tlen + vsa_llen + vsa_offset)) goto create_pair;
2727
2728                                 /*
2729                                  *      Ensure that the attribute number
2730                                  *      is OK.
2731                                  */
2732                                 switch (vsa_tlen) {
2733                                 case 1:
2734                                         myattr = subptr[0];
2735                                         break;
2736
2737                                 case 2:
2738                                         myattr = (subptr[0] << 8) | subptr[1];
2739                                         break;
2740
2741                                 case 4:
2742                                         if ((subptr[0] != 0) ||
2743                                             (subptr[1] != 0)) goto create_pair;
2744
2745                                         myattr = (subptr[2] << 8) | subptr[3];
2746                                         break;
2747
2748                                         /*
2749                                          *      Our dictionary is broken.
2750                                          */
2751                                 default:
2752                                         goto create_pair;
2753                                 }
2754
2755                                 switch (vsa_llen) {
2756                                 case 0:
2757                                         attribute = (myvendor << 16) | myattr;
2758                                         ptr += 4 + vsa_tlen;
2759                                         attrlen -= (4 + vsa_tlen);
2760                                         packet_length -= 4 + vsa_tlen;
2761                                         goto create_pair;
2762
2763                                 case 1:
2764                                         if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen + vsa_offset))
2765                                                 goto create_pair;
2766
2767                                         if (subptr[vsa_tlen] > sublen)
2768                                                 goto create_pair;
2769
2770                                         /*
2771                                          *      WiMAX: 0bCrrrrrrr
2772                                          *      Reserved bits MUST be
2773                                          *      zero.
2774                                          */
2775                                         if (vsa_offset &&
2776                                             ((subptr[vsa_tlen + vsa_llen] & 0x7f) != 0))
2777                                                 goto create_pair;
2778
2779                                         sublen -= subptr[vsa_tlen];
2780                                         subptr += subptr[vsa_tlen];
2781                                         break;
2782
2783                                 case 2:
2784                                         if (subptr[vsa_tlen] != 0) goto create_pair;
2785                                         if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2786                                                 goto create_pair;
2787                                         if (subptr[vsa_tlen + 1] > sublen)
2788                                                 goto create_pair;
2789                                         sublen -= subptr[vsa_tlen + 1];
2790                                         subptr += subptr[vsa_tlen + 1];
2791                                         break;
2792
2793                                         /*
2794                                          *      Our dictionaries are
2795                                          *      broken.
2796                                          */
2797                                 default:
2798                                         goto create_pair;
2799                                 }
2800                         } while (sublen > 0);
2801
2802                         vendorcode = myvendor;
2803                         vendorlen = attrlen - 4;
2804                         packet_length -= 4;
2805
2806                         ptr += 4;
2807                 }
2808
2809                 /*
2810                  *      attrlen is the length of this attribute.
2811                  *      total_len is the length of the encompassing
2812                  *      attribute.
2813                  */
2814                 switch (vsa_tlen) {
2815                 case 1:
2816                         attribute = ptr[0];
2817                         break;
2818
2819                 case 2:
2820                         attribute = (ptr[0] << 8) | ptr[1];
2821                         break;
2822
2823                 default:        /* can't hit this. */
2824                         return -1;
2825                 }
2826                 attribute |= (vendorcode << 16);
2827                 vsa_ptr = ptr;
2828                 ptr += vsa_tlen;
2829
2830                 switch (vsa_llen) {
2831                 case 1:
2832                         attrlen = ptr[0] - (vsa_tlen + vsa_llen + vsa_offset);
2833                         break;
2834
2835                 case 2:
2836                         attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2837                         break;
2838
2839                 default:        /* can't hit this. */
2840                         return -1;
2841                 }
2842
2843                 ptr += vsa_llen + vsa_offset;
2844                 vendorlen -= vsa_tlen + vsa_llen + vsa_offset + attrlen;
2845                 if (vendorlen == 0) vendorcode = 0;
2846                 packet_length -= (vsa_tlen + vsa_llen + vsa_offset);
2847
2848                 /*
2849                  *      Ignore VSAs that have no data.
2850                  */
2851                 if (attrlen == 0) goto next;
2852
2853                 /*
2854                  *      WiMAX attributes of type 0 are ignored.  They
2855                  *      are a secret flag to us that the attribute has
2856                  *      already been dealt with.
2857                  */
2858                 if (attribute == 0x60b50000) goto next;
2859
2860                 if (vsa_offset) {
2861                         DICT_ATTR *da;
2862
2863                         da = dict_attrbyvalue(attribute);
2864
2865                         /*
2866                          *      If it's NOT continued, AND we know
2867                          *      about it, AND it's not a TLV, we can
2868                          *      create a normal pair.
2869                          */
2870                         if (((vsa_ptr[2] & 0x80) == 0) &&
2871                             da && (da->type != PW_TYPE_TLV)) goto create_pair;
2872
2873                         /*
2874                          *      Else it IS continued, or it's a TLV.
2875                          *      Go do a lot of work to find the stuff.
2876                          */
2877                         pair = rad_continuation2vp(packet, original, secret,
2878                                                    attribute, attrlen, ptr,
2879                                                    packet_length,
2880                                                    ((vsa_ptr[2] & 0x80) != 0),
2881                                                    da);
2882                         goto created_pair;
2883                 }
2884
2885                 /*
2886                  *      Create the attribute, setting the default type
2887                  *      to 'octets'.  If the type in the dictionary
2888                  *      is different, then the dictionary type will
2889                  *      over-ride this one.
2890                  *
2891                  *      If the attribute has no data, then discard it.
2892                  *
2893                  *      Unless it's CUI.  Damn you, CUI!
2894                  */
2895         create_pair:
2896                 if (!attrlen &&
2897                     (attribute != PW_CHARGEABLE_USER_IDENTITY)) goto next;
2898
2899                 pair = rad_attr2vp(packet, original, secret,
2900                                    attribute, attrlen, ptr);
2901                 if (!pair) {
2902                         pairfree(&packet->vps);
2903                         fr_strerror_printf("out of memory");
2904                         return -1;
2905                 }
2906
2907         created_pair:
2908                 *tail = pair;
2909                 while (pair) {
2910                         num_attributes++;
2911                         debug_pair(pair);
2912                         tail = &pair->next;
2913                         pair = pair->next;
2914                 }
2915
2916                 /*
2917                  *      VSA's may not have been counted properly in
2918                  *      rad_packet_ok() above, as it is hard to count
2919                  *      then without using the dictionary.  We
2920                  *      therefore enforce the limits here, too.
2921                  */
2922                 if ((fr_max_attributes > 0) &&
2923                     (num_attributes > fr_max_attributes)) {
2924                         char host_ipaddr[128];
2925
2926                         pairfree(&packet->vps);
2927                         fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2928                                    inet_ntop(packet->src_ipaddr.af,
2929                                              &packet->src_ipaddr.ipaddr,
2930                                              host_ipaddr, sizeof(host_ipaddr)),
2931                                    num_attributes, fr_max_attributes);
2932                         return -1;
2933                 }
2934
2935         next:
2936                 ptr += attrlen;
2937                 packet_length -= attrlen;
2938         }
2939
2940         /*
2941          *      Merge information from the outside world into our
2942          *      random pool.
2943          */
2944         fr_rand_seed(packet->data, AUTH_HDR_LEN);
2945
2946         return 0;
2947 }
2948
2949
2950 /*
2951  *      Encode password.
2952  *
2953  *      We assume that the passwd buffer passed is big enough.
2954  *      RFC2138 says the password is max 128 chars, so the size
2955  *      of the passwd buffer must be at least 129 characters.
2956  *      Preferably it's just MAX_STRING_LEN.
2957  *
2958  *      int *pwlen is updated to the new length of the encrypted
2959  *      password - a multiple of 16 bytes.
2960  */
2961 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
2962                  const uint8_t *vector)
2963 {
2964         FR_MD5_CTX context, old;
2965         uint8_t digest[AUTH_VECTOR_LEN];
2966         int     i, n, secretlen;
2967         int     len;
2968
2969         /*
2970          *      RFC maximum is 128 bytes.
2971          *
2972          *      If length is zero, pad it out with zeros.
2973          *
2974          *      If the length isn't aligned to 16 bytes,
2975          *      zero out the extra data.
2976          */
2977         len = *pwlen;
2978
2979         if (len > 128) len = 128;
2980
2981         if (len == 0) {
2982                 memset(passwd, 0, AUTH_PASS_LEN);
2983                 len = AUTH_PASS_LEN;
2984         } else if ((len % AUTH_PASS_LEN) != 0) {
2985                 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
2986                 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
2987         }
2988         *pwlen = len;
2989
2990         /*
2991          *      Use the secret to setup the decryption digest
2992          */
2993         secretlen = strlen(secret);
2994
2995         fr_MD5Init(&context);
2996         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2997         old = context;          /* save intermediate work */
2998
2999         /*
3000          *      Encrypt it in place.  Don't bother checking
3001          *      len, as we've ensured above that it's OK.
3002          */
3003         for (n = 0; n < len; n += AUTH_PASS_LEN) {
3004                 if (n == 0) {
3005                         fr_MD5Update(&context, vector, AUTH_PASS_LEN);
3006                         fr_MD5Final(digest, &context);
3007                 } else {
3008                         context = old;
3009                         fr_MD5Update(&context,
3010                                      (uint8_t *) passwd + n - AUTH_PASS_LEN,
3011                                      AUTH_PASS_LEN);
3012                         fr_MD5Final(digest, &context);
3013                 }
3014
3015                 for (i = 0; i < AUTH_PASS_LEN; i++) {
3016                         passwd[i + n] ^= digest[i];
3017                 }
3018         }
3019
3020         return 0;
3021 }
3022
3023 /*
3024  *      Decode password.
3025  */
3026 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
3027                  const uint8_t *vector)
3028 {
3029         FR_MD5_CTX context, old;
3030         uint8_t digest[AUTH_VECTOR_LEN];
3031         int     i;
3032         size_t  n, secretlen;
3033
3034         /*
3035          *      The RFC's say that the maximum is 128.
3036          *      The buffer we're putting it into above is 254, so
3037          *      we don't need to do any length checking.
3038          */
3039         if (pwlen > 128) pwlen = 128;
3040
3041         /*
3042          *      Catch idiots.
3043          */
3044         if (pwlen == 0) goto done;
3045
3046         /*
3047          *      Use the secret to setup the decryption digest
3048          */
3049         secretlen = strlen(secret);
3050
3051         fr_MD5Init(&context);
3052         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3053         old = context;          /* save intermediate work */
3054
3055         /*
3056          *      The inverse of the code above.
3057          */
3058         for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
3059                 if (n == 0) {
3060                         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3061                         fr_MD5Final(digest, &context);
3062
3063                         context = old;
3064                         if (pwlen > AUTH_PASS_LEN) {
3065                                 fr_MD5Update(&context, (uint8_t *) passwd,
3066                                              AUTH_PASS_LEN);
3067                         }
3068                 } else {
3069                         fr_MD5Final(digest, &context);
3070
3071                         context = old;
3072                         if (pwlen > (n + AUTH_PASS_LEN)) {
3073                                 fr_MD5Update(&context, (uint8_t *) passwd + n,
3074                                              AUTH_PASS_LEN);
3075                         }
3076                 }
3077
3078                 for (i = 0; i < AUTH_PASS_LEN; i++) {
3079                         passwd[i + n] ^= digest[i];
3080                 }
3081         }
3082
3083  done:
3084         passwd[pwlen] = '\0';
3085         return strlen(passwd);
3086 }
3087
3088
3089 /*
3090  *      Encode Tunnel-Password attributes when sending them out on the wire.
3091  *
3092  *      int *pwlen is updated to the new length of the encrypted
3093  *      password - a multiple of 16 bytes.
3094  *
3095  *      This is per RFC-2868 which adds a two char SALT to the initial intermediate
3096  *      value MD5 hash.
3097  */
3098 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
3099                         const uint8_t *vector)
3100 {
3101         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
3102         unsigned char   digest[AUTH_VECTOR_LEN];
3103         char*   salt;
3104         int     i, n, secretlen;
3105         unsigned len, n2;
3106
3107         len = *pwlen;
3108
3109         if (len > 127) len = 127;
3110
3111         /*
3112          * Shift the password 3 positions right to place a salt and original
3113          * length, tag will be added automatically on packet send
3114          */
3115         for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
3116         salt = passwd;
3117         passwd += 2;
3118         /*
3119          * save original password length as first password character;
3120          */
3121         *passwd = len;
3122         len += 1;
3123
3124
3125         /*
3126          *      Generate salt.  The RFC's say:
3127          *
3128          *      The high bit of salt[0] must be set, each salt in a
3129          *      packet should be unique, and they should be random
3130          *
3131          *      So, we set the high bit, add in a counter, and then
3132          *      add in some CSPRNG data.  should be OK..
3133          */
3134         salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
3135                    (fr_rand() & 0x07));
3136         salt[1] = fr_rand();
3137
3138         /*
3139          *      Padd password to multiple of AUTH_PASS_LEN bytes.
3140          */
3141         n = len % AUTH_PASS_LEN;
3142         if (n) {
3143                 n = AUTH_PASS_LEN - n;
3144                 for (; n > 0; n--, len++)
3145                         passwd[len] = 0;
3146         }
3147         /* set new password length */
3148         *pwlen = len + 2;
3149
3150         /*
3151          *      Use the secret to setup the decryption digest
3152          */
3153         secretlen = strlen(secret);
3154         memcpy(buffer, secret, secretlen);
3155
3156         for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
3157                 if (!n2) {
3158                         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
3159                         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
3160                         fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
3161                 } else {
3162                         memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
3163                         fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
3164                 }
3165
3166                 for (i = 0; i < AUTH_PASS_LEN; i++) {
3167                         passwd[i + n2] ^= digest[i];
3168                 }
3169         }
3170         passwd[n2] = 0;
3171         return 0;
3172 }
3173
3174 /*
3175  *      Decode Tunnel-Password encrypted attributes.
3176  *
3177  *      Defined in RFC-2868, this uses a two char SALT along with the
3178  *      initial intermediate value, to differentiate it from the
3179  *      above.
3180  */
3181 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
3182                         const uint8_t *vector)
3183 {
3184         FR_MD5_CTX  context, old;
3185         uint8_t         digest[AUTH_VECTOR_LEN];
3186         int             secretlen;
3187         unsigned        i, n, len, reallen;
3188
3189         len = *pwlen;
3190
3191         /*
3192          *      We need at least a salt.
3193          */
3194         if (len < 2) {
3195                 fr_strerror_printf("tunnel password is too short");
3196                 return -1;
3197         }
3198
3199         /*
3200          *      There's a salt, but no password.  Or, there's a salt
3201          *      and a 'data_len' octet.  It's wrong, but at least we
3202          *      can figure out what it means: the password is empty.
3203          *
3204          *      Note that this means we ignore the 'data_len' field,
3205          *      if the attribute length tells us that there's no
3206          *      more data.  So the 'data_len' field may be wrong,
3207          *      but that's ok...
3208          */
3209         if (len <= 3) {
3210                 passwd[0] = 0;
3211                 *pwlen = 0;
3212                 return 0;
3213         }
3214
3215         len -= 2;               /* discount the salt */
3216
3217         /*
3218          *      Use the secret to setup the decryption digest
3219          */
3220         secretlen = strlen(secret);
3221
3222         fr_MD5Init(&context);
3223         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3224         old = context;          /* save intermediate work */
3225
3226         /*
3227          *      Set up the initial key:
3228          *
3229          *       b(1) = MD5(secret + vector + salt)
3230          */
3231         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3232         fr_MD5Update(&context, passwd, 2);
3233
3234         reallen = 0;
3235         for (n = 0; n < len; n += AUTH_PASS_LEN) {
3236                 int base = 0;
3237
3238                 if (n == 0) {
3239                         fr_MD5Final(digest, &context);
3240
3241                         context = old;
3242
3243                         /*
3244                          *      A quick check: decrypt the first octet
3245                          *      of the password, which is the
3246                          *      'data_len' field.  Ensure it's sane.
3247                          */
3248                         reallen = passwd[2] ^ digest[0];
3249                         if (reallen >= len) {
3250                                 fr_strerror_printf("tunnel password is too long for the attribute");
3251                                 return -1;
3252                         }
3253
3254                         fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
3255
3256                         base = 1;
3257                 } else {
3258                         fr_MD5Final(digest, &context);
3259
3260                         context = old;
3261                         fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
3262                 }
3263
3264                 for (i = base; i < AUTH_PASS_LEN; i++) {
3265                         passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
3266                 }
3267         }
3268
3269         /*
3270          *      See make_tunnel_password, above.
3271          */
3272         if (reallen > 239) reallen = 239;
3273
3274         *pwlen = reallen;
3275         passwd[reallen] = 0;
3276
3277         return reallen;
3278 }
3279
3280 /*
3281  *      Encode a CHAP password
3282  *
3283  *      FIXME: might not work with Ascend because
3284  *      we use vp->length, and Ascend gear likes
3285  *      to send an extra '\0' in the string!
3286  */
3287 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
3288                     VALUE_PAIR *password)
3289 {
3290         int             i;
3291         uint8_t         *ptr;
3292         uint8_t         string[MAX_STRING_LEN * 2 + 1];
3293         VALUE_PAIR      *challenge;
3294
3295         /*
3296          *      Sanity check the input parameters
3297          */
3298         if ((packet == NULL) || (password == NULL)) {
3299                 return -1;
3300         }
3301
3302         /*
3303          *      Note that the password VP can be EITHER
3304          *      a User-Password attribute (from a check-item list),
3305          *      or a CHAP-Password attribute (the client asking
3306          *      the library to encode it).
3307          */
3308
3309         i = 0;
3310         ptr = string;
3311         *ptr++ = id;
3312
3313         i++;
3314         memcpy(ptr, password->vp_strvalue, password->length);
3315         ptr += password->length;
3316         i += password->length;
3317
3318         /*
3319          *      Use Chap-Challenge pair if present,
3320          *      Request-Authenticator otherwise.
3321          */
3322         challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
3323         if (challenge) {
3324                 memcpy(ptr, challenge->vp_strvalue, challenge->length);
3325                 i += challenge->length;
3326         } else {
3327                 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
3328                 i += AUTH_VECTOR_LEN;
3329         }
3330
3331         *output = id;
3332         fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
3333
3334         return 0;
3335 }
3336
3337
3338 /*
3339  *      Seed the random number generator.
3340  *
3341  *      May be called any number of times.
3342  */
3343 void fr_rand_seed(const void *data, size_t size)
3344 {
3345         uint32_t hash;
3346
3347         /*
3348          *      Ensure that the pool is initialized.
3349          */
3350         if (!fr_rand_initialized) {
3351                 int fd;
3352
3353                 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
3354
3355                 fd = open("/dev/urandom", O_RDONLY);
3356                 if (fd >= 0) {
3357                         size_t total;
3358                         ssize_t this;
3359
3360                         total = this = 0;
3361                         while (total < sizeof(fr_rand_pool.randrsl)) {
3362                                 this = read(fd, fr_rand_pool.randrsl,
3363                                             sizeof(fr_rand_pool.randrsl) - total);
3364                                 if ((this < 0) && (errno != EINTR)) break;
3365                                 if (this > 0) total += this;
3366                         }
3367                         close(fd);
3368                 } else {
3369                         fr_rand_pool.randrsl[0] = fd;
3370                         fr_rand_pool.randrsl[1] = time(NULL);
3371                         fr_rand_pool.randrsl[2] = errno;
3372                 }
3373
3374                 fr_randinit(&fr_rand_pool, 1);
3375                 fr_rand_pool.randcnt = 0;
3376                 fr_rand_initialized = 1;
3377         }
3378
3379         if (!data) return;
3380
3381         /*
3382          *      Hash the user data
3383          */
3384         hash = fr_rand();
3385         if (!hash) hash = fr_rand();
3386         hash = fr_hash_update(data, size, hash);
3387
3388         fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
3389 }
3390
3391
3392 /*
3393  *      Return a 32-bit random number.
3394  */
3395 uint32_t fr_rand(void)
3396 {
3397         uint32_t num;
3398
3399         /*
3400          *      Ensure that the pool is initialized.
3401          */
3402         if (!fr_rand_initialized) {
3403                 fr_rand_seed(NULL, 0);
3404         }
3405
3406         num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
3407         if (fr_rand_pool.randcnt >= 256) {
3408                 fr_rand_pool.randcnt = 0;
3409                 fr_isaac(&fr_rand_pool);
3410         }
3411
3412         return num;
3413 }
3414
3415
3416 /*
3417  *      Allocate a new RADIUS_PACKET
3418  */
3419 RADIUS_PACKET *rad_alloc(int newvector)
3420 {
3421         RADIUS_PACKET   *rp;
3422
3423         if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
3424                 fr_strerror_printf("out of memory");
3425                 return NULL;
3426         }
3427         memset(rp, 0, sizeof(*rp));
3428         rp->id = -1;
3429         rp->offset = -1;
3430
3431         if (newvector) {
3432                 int i;
3433                 uint32_t hash, base;
3434
3435                 /*
3436                  *      Don't expose the actual contents of the random
3437                  *      pool.
3438                  */
3439                 base = fr_rand();
3440                 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
3441                         hash = fr_rand() ^ base;
3442                         memcpy(rp->vector + i, &hash, sizeof(hash));
3443                 }
3444         }
3445         fr_rand();              /* stir the pool again */
3446
3447         return rp;
3448 }
3449
3450 RADIUS_PACKET *rad_alloc_reply(RADIUS_PACKET *packet)
3451 {
3452         RADIUS_PACKET *reply;
3453
3454         if (!packet) return NULL;
3455
3456         reply = rad_alloc(0);
3457         if (!reply) return NULL;
3458
3459         /*
3460          *      Initialize the fields from the request.
3461          */
3462         reply->sockfd = packet->sockfd;
3463         reply->dst_ipaddr = packet->src_ipaddr;
3464         reply->src_ipaddr = packet->dst_ipaddr;
3465         reply->dst_port = packet->src_port;
3466         reply->src_port = packet->dst_port;
3467         reply->id = packet->id;
3468         reply->code = 0; /* UNKNOWN code */
3469         memcpy(reply->vector, packet->vector,
3470                sizeof(reply->vector));
3471         reply->vps = NULL;
3472         reply->data = NULL;
3473         reply->data_len = 0;
3474
3475         return reply;
3476 }
3477
3478
3479 /*
3480  *      Free a RADIUS_PACKET
3481  */
3482 void rad_free(RADIUS_PACKET **radius_packet_ptr)
3483 {
3484         RADIUS_PACKET *radius_packet;
3485
3486         if (!radius_packet_ptr || !*radius_packet_ptr) return;
3487         radius_packet = *radius_packet_ptr;
3488
3489         free(radius_packet->data);
3490
3491         pairfree(&radius_packet->vps);
3492
3493         free(radius_packet);
3494
3495         *radius_packet_ptr = NULL;
3496 }