Disallow "TLV" types to have any data
[freeradius.git] / src / lib / radius.c
1 /*
2  *   This library is free software; you can redistribute it and/or
3  *   modify it under the terms of the GNU Lesser General Public
4  *   License as published by the Free Software Foundation; either
5  *   version 2.1 of the License, or (at your option) any later version.
6  *
7  *   This library is distributed in the hope that it will be useful,
8  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10  *   Lesser General Public License for more details.
11  *
12  *   You should have received a copy of the GNU Lesser General Public
13  *   License along with this library; if not, write to the Free Software
14  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15  */
16
17 /**
18  * $Id$
19  *
20  * @file radius.c
21  * @brief Functions to send/receive radius packets.
22  *
23  * @copyright 2000-2003,2006  The FreeRADIUS server project
24  */
25
26 RCSID("$Id$")
27
28 #include        <freeradius-devel/libradius.h>
29
30 #include        <freeradius-devel/md5.h>
31
32 #include        <fcntl.h>
33 #include        <ctype.h>
34
35 #ifdef WITH_UDPFROMTO
36 #include        <freeradius-devel/udpfromto.h>
37 #endif
38
39 /*
40  *      Some messages get printed out only in debugging mode.
41  */
42 #define FR_DEBUG_STRERROR_PRINTF if (fr_debug_lvl) fr_strerror_printf
43
44 #if 0
45 #define VP_TRACE printf
46
47 static void VP_HEXDUMP(char const *msg, uint8_t const *data, size_t len)
48 {
49         size_t i;
50
51         printf("--- %s ---\n", msg);
52         for (i = 0; i < len; i++) {
53                 if ((i & 0x0f) == 0) printf("%04x: ", (unsigned int) i);
54                 printf("%02x ", data[i]);
55                 if ((i & 0x0f) == 0x0f) printf("\n");
56         }
57         if ((len == 0x0f) || ((len & 0x0f) != 0x0f)) printf("\n");
58         fflush(stdout);
59 }
60
61 #else
62 #define VP_TRACE(_x, ...)
63 #define VP_HEXDUMP(_x, _y, _z)
64 #endif
65
66
67 /*
68  *  The RFC says 4096 octets max, and most packets are less than 256.
69  */
70 #define MAX_PACKET_LEN 4096
71
72 /*
73  *      The maximum number of attributes which we allow in an incoming
74  *      request.  If there are more attributes than this, the request
75  *      is rejected.
76  *
77  *      This helps to minimize the potential for a DoS, when an
78  *      attacker spoofs Access-Request packets, which don't have a
79  *      Message-Authenticator attribute.  This means that the packet
80  *      is unsigned, and the attacker can use resources on the server,
81  *      even if the end request is rejected.
82  */
83 uint32_t fr_max_attributes = 0;
84 FILE *fr_log_fp = NULL;
85
86 typedef struct radius_packet_t {
87   uint8_t       code;
88   uint8_t       id;
89   uint8_t       length[2];
90   uint8_t       vector[AUTH_VECTOR_LEN];
91   uint8_t       data[1];
92 } radius_packet_t;
93
94 static fr_randctx fr_rand_pool; /* across multiple calls */
95 static int fr_rand_initialized = 0;
96 static unsigned int salt_offset = 0;
97 static uint8_t nullvector[AUTH_VECTOR_LEN] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* for CoA decode */
98
99 char const *fr_packet_codes[FR_MAX_PACKET_CODE] = {
100   "",                                   //!< 0
101   "Access-Request",
102   "Access-Accept",
103   "Access-Reject",
104   "Accounting-Request",
105   "Accounting-Response",
106   "Accounting-Status",
107   "Password-Request",
108   "Password-Accept",
109   "Password-Reject",
110   "Accounting-Message",                 //!< 10
111   "Access-Challenge",
112   "Status-Server",
113   "Status-Client",
114   "14",
115   "15",
116   "16",
117   "17",
118   "18",
119   "19",
120   "20",                                 //!< 20
121   "Resource-Free-Request",
122   "Resource-Free-Response",
123   "Resource-Query-Request",
124   "Resource-Query-Response",
125   "Alternate-Resource-Reclaim-Request",
126   "NAS-Reboot-Request",
127   "NAS-Reboot-Response",
128   "28",
129   "Next-Passcode",
130   "New-Pin",                            //!< 30
131   "Terminate-Session",
132   "Password-Expired",
133   "Event-Request",
134   "Event-Response",
135   "35",
136   "36",
137   "37",
138   "38",
139   "39",
140   "Disconnect-Request",                 //!< 40
141   "Disconnect-ACK",
142   "Disconnect-NAK",
143   "CoA-Request",
144   "CoA-ACK",
145   "CoA-NAK",
146   "46",
147   "47",
148   "48",
149   "49",
150   "IP-Address-Allocate",
151   "IP-Address-Release",                 //!< 50
152 };
153
154
155 void fr_printf_log(char const *fmt, ...)
156 {
157         va_list ap;
158
159         va_start(ap, fmt);
160         if ((fr_debug_lvl == 0) || !fr_log_fp) {
161                 va_end(ap);
162                 return;
163         }
164
165         vfprintf(fr_log_fp, fmt, ap);
166         va_end(ap);
167
168         return;
169 }
170
171 static char const tabs[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
172
173 static void print_hex_data(uint8_t const *ptr, int attrlen, int depth)
174 {
175         int i;
176
177         for (i = 0; i < attrlen; i++) {
178                 if ((i > 0) && ((i & 0x0f) == 0x00))
179                         fprintf(fr_log_fp, "%.*s", depth, tabs);
180                 fprintf(fr_log_fp, "%02x ", ptr[i]);
181                 if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
182         }
183         if ((i & 0x0f) != 0) fprintf(fr_log_fp, "\n");
184 }
185
186
187 void rad_print_hex(RADIUS_PACKET *packet)
188 {
189         int i;
190
191         if (!packet->data || !fr_log_fp) return;
192
193         fprintf(fr_log_fp, "  Code:\t\t%u\n", packet->data[0]);
194         fprintf(fr_log_fp, "  Id:\t\t%u\n", packet->data[1]);
195         fprintf(fr_log_fp, "  Length:\t%u\n", ((packet->data[2] << 8) |
196                                    (packet->data[3])));
197         fprintf(fr_log_fp, "  Vector:\t");
198         for (i = 4; i < 20; i++) {
199                 fprintf(fr_log_fp, "%02x", packet->data[i]);
200         }
201         fprintf(fr_log_fp, "\n");
202
203         if (packet->data_len > 20) {
204                 int total;
205                 uint8_t const *ptr;
206                 fprintf(fr_log_fp, "  Data:");
207
208                 total = packet->data_len - 20;
209                 ptr = packet->data + 20;
210
211                 while (total > 0) {
212                         int attrlen;
213                         unsigned int vendor = 0;
214
215                         fprintf(fr_log_fp, "\t\t");
216                         if (total < 2) { /* too short */
217                                 fprintf(fr_log_fp, "%02x\n", *ptr);
218                                 break;
219                         }
220
221                         if (ptr[1] > total) { /* too long */
222                                 for (i = 0; i < total; i++) {
223                                         fprintf(fr_log_fp, "%02x ", ptr[i]);
224                                 }
225                                 break;
226                         }
227
228                         fprintf(fr_log_fp, "%02x  %02x  ", ptr[0], ptr[1]);
229                         attrlen = ptr[1] - 2;
230
231                         if ((ptr[0] == PW_VENDOR_SPECIFIC) &&
232                             (attrlen > 4)) {
233                                 vendor = (ptr[3] << 16) | (ptr[4] << 8) | ptr[5];
234                                 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u)  ",
235                                        ptr[2], ptr[3], ptr[4], ptr[5], vendor);
236                                 attrlen -= 4;
237                                 ptr += 6;
238                                 total -= 6;
239
240                         } else {
241                                 ptr += 2;
242                                 total -= 2;
243                         }
244
245                         print_hex_data(ptr, attrlen, 3);
246
247                         ptr += attrlen;
248                         total -= attrlen;
249                 }
250         }
251         fflush(stdout);
252 }
253
254 /** Wrapper for sendto which handles sendfromto, IPv6, and all possible combinations
255  *
256  */
257 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
258 #ifdef WITH_UDPFROMTO
259                       fr_ipaddr_t *src_ipaddr, uint16_t src_port,
260 #else
261                       UNUSED fr_ipaddr_t *src_ipaddr, UNUSED uint16_t src_port,
262 #endif
263                       fr_ipaddr_t *dst_ipaddr, uint16_t dst_port)
264 {
265         int rcode;
266         struct sockaddr_storage dst;
267         socklen_t               sizeof_dst;
268
269 #ifdef WITH_UDPFROMTO
270         struct sockaddr_storage src;
271         socklen_t               sizeof_src;
272
273         fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
274 #endif
275
276         if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
277                 return -1;
278         }
279
280 #ifdef WITH_UDPFROMTO
281         /*
282          *      And if they don't specify a source IP address, don't
283          *      use udpfromto.
284          */
285         if (((dst_ipaddr->af == AF_INET) || (dst_ipaddr->af == AF_INET6)) &&
286             (src_ipaddr->af != AF_UNSPEC) &&
287             !fr_inaddr_any(src_ipaddr)) {
288                 rcode = sendfromto(sockfd, data, data_len, flags,
289                                    (struct sockaddr *)&src, sizeof_src,
290                                    (struct sockaddr *)&dst, sizeof_dst);
291                 goto done;
292         }
293 #endif
294
295         /*
296          *      No udpfromto, fail gracefully.
297          */
298         rcode = sendto(sockfd, data, data_len, flags,
299                        (struct sockaddr *) &dst, sizeof_dst);
300 #ifdef WITH_UDPFROMTO
301 done:
302 #endif
303         if (rcode < 0) {
304                 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
305         }
306
307         return rcode;
308 }
309
310
311 void rad_recv_discard(int sockfd)
312 {
313         uint8_t                 header[4];
314         struct sockaddr_storage src;
315         socklen_t               sizeof_src = sizeof(src);
316
317         (void) recvfrom(sockfd, header, sizeof(header), 0,
318                         (struct sockaddr *)&src, &sizeof_src);
319 }
320
321 /** Basic validation of RADIUS packet header
322  *
323  * @note fr_strerror errors are only available if fr_debug_lvl > 0. This is to reduce CPU time
324  *      consumed when discarding malformed packet.
325  *
326  * @param[in] sockfd we're reading from.
327  * @param[out] src_ipaddr of the packet.
328  * @param[out] src_port of the packet.
329  * @param[out] code Pointer to where to write the packet code.
330  * @return
331  *      - -1 on failure.
332  *      - 1 on decode error.
333  *      - >= RADIUS_HDR_LEN on success. This is the packet length as specified in the header.
334  */
335 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, uint16_t *src_port, int *code)
336 {
337         ssize_t                 data_len, packet_len;
338         uint8_t                 header[4];
339         struct sockaddr_storage src;
340         socklen_t               sizeof_src = sizeof(src);
341
342         data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
343                             (struct sockaddr *)&src, &sizeof_src);
344         if (data_len < 0) {
345                 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
346                 return -1;
347         }
348
349         /*
350          *      Too little data is available, discard the packet.
351          */
352         if (data_len < 4) {
353                 FR_DEBUG_STRERROR_PRINTF("Expected at least 4 bytes of header data, got %zu bytes", data_len);
354                 rad_recv_discard(sockfd);
355
356                 return 1;
357
358         } else {                /* we got 4 bytes of data. */
359                 /*
360                  *      See how long the packet says it is.
361                  */
362                 packet_len = (header[2] * 256) + header[3];
363
364                 /*
365                  *      The length in the packet says it's less than
366                  *      a RADIUS header length: discard it.
367                  */
368                 if (packet_len < RADIUS_HDR_LEN) {
369                         FR_DEBUG_STRERROR_PRINTF("Expected at least " STRINGIFY(RADIUS_HDR_LEN)  " bytes of packet "
370                                                  "data, got %zu bytes", packet_len);
371                         rad_recv_discard(sockfd);
372
373                         return 1;
374
375                         /*
376                          *      Enforce RFC requirements, for sanity.
377                          *      Anything after 4k will be discarded.
378                          */
379                 } else if (packet_len > MAX_PACKET_LEN) {
380                         FR_DEBUG_STRERROR_PRINTF("Length field value too large, expected maximum of "
381                                                  STRINGIFY(MAX_PACKET_LEN) " bytes, got %zu bytes", packet_len);
382                         rad_recv_discard(sockfd);
383
384                         return 1;
385                 }
386         }
387
388         /*
389          *      Convert AF.  If unknown, discard packet.
390          */
391         if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
392                 FR_DEBUG_STRERROR_PRINTF("Unkown address family");
393                 rad_recv_discard(sockfd);
394
395                 return 1;
396         }
397
398         *code = header[0];
399
400         /*
401          *      The packet says it's this long, but the actual UDP
402          *      size could still be smaller.
403          */
404         return packet_len;
405 }
406
407
408 /** Wrapper for recvfrom, which handles recvfromto, IPv6, and all possible combinations
409  *
410  */
411 static ssize_t rad_recvfrom(int sockfd, RADIUS_PACKET *packet, int flags,
412                             fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
413                             fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
414 {
415         struct sockaddr_storage src;
416         struct sockaddr_storage dst;
417         socklen_t               sizeof_src = sizeof(src);
418         socklen_t               sizeof_dst = sizeof(dst);
419         ssize_t                 data_len;
420         uint8_t                 header[4];
421         size_t                  len;
422         uint16_t                port;
423
424         memset(&src, 0, sizeof_src);
425         memset(&dst, 0, sizeof_dst);
426
427         /*
428          *      Read the length of the packet, from the packet.
429          *      This lets us allocate the buffer to use for
430          *      reading the rest of the packet.
431          */
432         data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
433                             (struct sockaddr *)&src, &sizeof_src);
434         if (data_len < 0) {
435                 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
436                 return -1;
437         }
438
439         /*
440          *      Too little data is available, discard the packet.
441          */
442         if (data_len < 4) {
443                 rad_recv_discard(sockfd);
444
445                 return 0;
446
447         } else {                /* we got 4 bytes of data. */
448                 /*
449                  *      See how long the packet says it is.
450                  */
451                 len = (header[2] * 256) + header[3];
452
453                 /*
454                  *      The length in the packet says it's less than
455                  *      a RADIUS header length: discard it.
456                  */
457                 if (len < RADIUS_HDR_LEN) {
458                         recvfrom(sockfd, header, sizeof(header), flags,
459                                  (struct sockaddr *)&src, &sizeof_src);
460                         return 0;
461
462                         /*
463                          *      Enforce RFC requirements, for sanity.
464                          *      Anything after 4k will be discarded.
465                          */
466                 } else if (len > MAX_PACKET_LEN) {
467                         recvfrom(sockfd, header, sizeof(header), flags,
468                                  (struct sockaddr *)&src, &sizeof_src);
469                         return len;
470                 }
471         }
472
473         packet->data = talloc_array(packet, uint8_t, len);
474         if (!packet->data) return -1;
475
476         /*
477          *      Receive the packet.  The OS will discard any data in the
478          *      packet after "len" bytes.
479          */
480 #ifdef WITH_UDPFROMTO
481         data_len = recvfromto(sockfd, packet->data, len, flags,
482                               (struct sockaddr *)&src, &sizeof_src,
483                               (struct sockaddr *)&dst, &sizeof_dst);
484 #else
485         data_len = recvfrom(sockfd, packet->data, len, flags,
486                             (struct sockaddr *)&src, &sizeof_src);
487
488         /*
489          *      Get the destination address, too.
490          */
491         if (getsockname(sockfd, (struct sockaddr *)&dst,
492                         &sizeof_dst) < 0) return -1;
493 #endif
494         if (data_len < 0) {
495                 return data_len;
496         }
497
498         if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
499                 return -1;      /* Unknown address family, Die Die Die! */
500         }
501         *src_port = port;
502
503         fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
504         *dst_port = port;
505
506         /*
507          *      Different address families should never happen.
508          */
509         if (src.ss_family != dst.ss_family) {
510                 return -1;
511         }
512
513         return data_len;
514 }
515
516
517 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
518 /** Build an encrypted secret value to return in a reply packet
519  *
520  * The secret is hidden by xoring with a MD5 digest created from
521  * the shared secret and the authentication vector.
522  * We put them into MD5 in the reverse order from that used when
523  * encrypting passwords to RADIUS.
524  */
525 static void make_secret(uint8_t *digest, uint8_t const *vector,
526                         char const *secret, uint8_t const *value)
527 {
528         FR_MD5_CTX context;
529         int          i;
530
531         fr_md5_init(&context);
532         fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
533         fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
534         fr_md5_final(digest, &context);
535
536         for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
537                 digest[i] ^= value[i];
538         }
539 }
540
541 #define MAX_PASS_LEN (128)
542 static void make_passwd(uint8_t *output, ssize_t *outlen,
543                         uint8_t const *input, size_t inlen,
544                         char const *secret, uint8_t const *vector)
545 {
546         FR_MD5_CTX context, old;
547         uint8_t digest[AUTH_VECTOR_LEN];
548         uint8_t passwd[MAX_PASS_LEN];
549         size_t  i, n;
550         size_t  len;
551
552         /*
553          *      If the length is zero, round it up.
554          */
555         len = inlen;
556
557         if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
558
559         memcpy(passwd, input, len);
560         if (len < sizeof(passwd)) memset(passwd + len, 0, sizeof(passwd) - len);
561
562         if (len == 0) {
563                 len = AUTH_PASS_LEN;
564         }
565
566         else if ((len & 0x0f) != 0) {
567                 len += 0x0f;
568                 len &= ~0x0f;
569         }
570         *outlen = len;
571
572         fr_md5_init(&context);
573         fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
574         old = context;
575
576         /*
577          *      Do first pass.
578          */
579         fr_md5_update(&context, vector, AUTH_PASS_LEN);
580
581         for (n = 0; n < len; n += AUTH_PASS_LEN) {
582                 if (n > 0) {
583                         context = old;
584                         fr_md5_update(&context,
585                                        passwd + n - AUTH_PASS_LEN,
586                                        AUTH_PASS_LEN);
587                 }
588
589                 fr_md5_final(digest, &context);
590                 for (i = 0; i < AUTH_PASS_LEN; i++) {
591                         passwd[i + n] ^= digest[i];
592                 }
593         }
594
595         memcpy(output, passwd, len);
596 }
597
598 static void make_tunnel_passwd(uint8_t *output, ssize_t *outlen,
599                                uint8_t const *input, size_t inlen, size_t room,
600                                char const *secret, uint8_t const *vector)
601 {
602         FR_MD5_CTX context, old;
603         uint8_t digest[AUTH_VECTOR_LEN];
604         uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
605         int     i, n;
606         int     len;
607
608         /*
609          *      Be paranoid.
610          */
611         if (room > 253) room = 253;
612
613         /*
614          *      Account for 2 bytes of the salt, and round the room
615          *      available down to the nearest multiple of 16.  Then,
616          *      subtract one from that to account for the length byte,
617          *      and the resulting number is the upper bound on the data
618          *      to copy.
619          *
620          *      We could short-cut this calculation just be forcing
621          *      inlen to be no more than 239.  It would work for all
622          *      VSA's, as we don't pack multiple VSA's into one
623          *      attribute.
624          *
625          *      However, this calculation is more general, if a little
626          *      complex.  And it will work in the future for all possible
627          *      kinds of weird attribute packing.
628          */
629         room -= 2;
630         room -= (room & 0x0f);
631         room--;
632
633         if (inlen > room) inlen = room;
634
635         /*
636          *      Length of the encrypted data is password length plus
637          *      one byte for the length of the password.
638          */
639         len = inlen + 1;
640         if ((len & 0x0f) != 0) {
641                 len += 0x0f;
642                 len &= ~0x0f;
643         }
644         *outlen = len + 2;      /* account for the salt */
645
646         /*
647          *      Copy the password over.
648          */
649         memcpy(passwd + 3, input, inlen);
650         memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
651
652         /*
653          *      Generate salt.  The RFC's say:
654          *
655          *      The high bit of salt[0] must be set, each salt in a
656          *      packet should be unique, and they should be random
657          *
658          *      So, we set the high bit, add in a counter, and then
659          *      add in some CSPRNG data.  should be OK..
660          */
661         passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
662                      (fr_rand() & 0x07));
663         passwd[1] = fr_rand();
664         passwd[2] = inlen;      /* length of the password string */
665
666         fr_md5_init(&context);
667         fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
668         old = context;
669
670         fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
671         fr_md5_update(&context, &passwd[0], 2);
672
673         for (n = 0; n < len; n += AUTH_PASS_LEN) {
674                 if (n > 0) {
675                         context = old;
676                         fr_md5_update(&context,
677                                        passwd + 2 + n - AUTH_PASS_LEN,
678                                        AUTH_PASS_LEN);
679                 }
680
681                 fr_md5_final(digest, &context);
682
683                 for (i = 0; i < AUTH_PASS_LEN; i++) {
684                         passwd[i + 2 + n] ^= digest[i];
685                 }
686         }
687         memcpy(output, passwd, len + 2);
688 }
689
690 static int do_next_tlv(VALUE_PAIR const *vp, VALUE_PAIR const *next, int nest)
691 {
692         unsigned int tlv1, tlv2;
693
694         if (nest > fr_attr_max_tlv) return 0;
695
696         if (!vp) return 0;
697
698         /*
699          *      Keep encoding TLVs which have the same scope.
700          *      e.g. two attributes of:
701          *              ATTR.TLV1.TLV2.TLV3 = data1
702          *              ATTR.TLV1.TLV2.TLV4 = data2
703          *      both get put into a container of "ATTR.TLV1.TLV2"
704          */
705
706         /*
707          *      Nothing to follow, we're done.
708          */
709         if (!next) return 0;
710
711         /*
712          *      Not from the same vendor, skip it.
713          */
714         if (vp->da->vendor != next->da->vendor) return 0;
715
716         /*
717          *      In a different TLV space, skip it.
718          */
719         tlv1 = vp->da->attr;
720         tlv2 = next->da->attr;
721
722         tlv1 &= ((1 << fr_attr_shift[nest]) - 1);
723         tlv2 &= ((1 << fr_attr_shift[nest]) - 1);
724
725         if (tlv1 != tlv2) return 0;
726
727         return 1;
728 }
729
730
731 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
732                            RADIUS_PACKET const *original,
733                            char const *secret, int nest,
734                            VALUE_PAIR const **pvp,
735                            uint8_t *start, size_t room);
736
737 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
738                            RADIUS_PACKET const *original,
739                            char const *secret, VALUE_PAIR const **pvp,
740                            unsigned int attribute, uint8_t *ptr, size_t room);
741
742 /** Encode the *data* portion of the TLV
743  *
744  * This is really a sub-function of vp2data_any().  It encodes the *data* portion
745  * of the TLV, and assumes that the encapsulating attribute has already been encoded.
746  */
747 static ssize_t vp2data_tlvs(RADIUS_PACKET const *packet,
748                             RADIUS_PACKET const *original,
749                             char const *secret, int nest,
750                             VALUE_PAIR const **pvp,
751                             uint8_t *start, size_t room)
752 {
753         ssize_t len;
754         size_t my_room;
755         uint8_t *ptr = start;
756         VALUE_PAIR const *vp = *pvp;
757         VALUE_PAIR const *svp = vp;
758
759         if (!svp) return 0;
760
761 #ifndef NDEBUG
762         if (nest > fr_attr_max_tlv) {
763                 fr_strerror_printf("vp2data_tlvs: attribute nesting overflow");
764                 return -1;
765         }
766 #endif
767
768         while (vp) {
769                 VERIFY_VP(vp);
770
771                 if (room <= 2) return ptr - start;
772
773                 ptr[0] = (vp->da->attr >> fr_attr_shift[nest]) & fr_attr_mask[nest];
774                 ptr[1] = 2;
775
776                 my_room = room;
777                 if (room > 255) my_room = 255;
778
779                 len = vp2data_any(packet, original, secret, nest,
780                                   &vp, ptr + 2, my_room - 2);
781                 if (len < 0) return len;
782                 if (len == 0) return ptr - start;
783                 /* len can NEVER be more than 253 */
784
785                 ptr[1] += len;
786
787 #ifndef NDEBUG
788                 if ((fr_debug_lvl > 3) && fr_log_fp) {
789                         fprintf(fr_log_fp, "\t\t%02x %02x  ", ptr[0], ptr[1]);
790                         print_hex_data(ptr + 2, len, 3);
791                 }
792 #endif
793
794                 room -= ptr[1];
795                 ptr += ptr[1];
796                 *pvp = vp;
797
798                 if (!do_next_tlv(svp, vp, nest)) break;
799         }
800
801 #ifndef NDEBUG
802         if ((fr_debug_lvl > 3) && fr_log_fp) {
803                 DICT_ATTR const *da;
804
805                 da = dict_attrbyvalue(svp->da->attr & ((1 << fr_attr_shift[nest ]) - 1), svp->da->vendor);
806                 if (da) fprintf(fr_log_fp, "\t%s = ...\n", da->name);
807         }
808 #endif
809
810         return ptr - start;
811 }
812
813 /** Encodes the data portion of an attribute
814  *
815  * @return -1 on error, or the length of the data portion.
816  */
817 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
818                            RADIUS_PACKET const *original,
819                            char const *secret, int nest,
820                            VALUE_PAIR const **pvp,
821                            uint8_t *start, size_t room)
822 {
823         uint32_t lvalue;
824         ssize_t len;
825         uint8_t const *data;
826         uint8_t *ptr = start;
827         uint8_t array[4];
828         uint64_t lvalue64;
829         VALUE_PAIR const *vp = *pvp;
830
831         VERIFY_VP(vp);
832
833         /*
834          *      See if we need to encode a TLV.  The low portion of
835          *      the attribute has already been placed into the packer.
836          *      If there are still attribute bytes left, then go
837          *      encode them as TLVs.
838          *
839          *      If we cared about the stack, we could unroll the loop.
840          */
841         if (vp->da->flags.is_tlv && (nest < fr_attr_max_tlv) &&
842             ((vp->da->attr >> fr_attr_shift[nest + 1]) != 0)) {
843                 return vp2data_tlvs(packet, original, secret, nest + 1, pvp,
844                                     start, room);
845         }
846
847         /*
848          *      Set up the default sources for the data.
849          */
850         len = vp->vp_length;
851
852         switch (vp->da->type) {
853         case PW_TYPE_STRING:
854         case PW_TYPE_OCTETS:
855                 data = vp->data.ptr;
856                 if (!data) {
857                         fr_strerror_printf("ERROR: Cannot encode NULL data");
858                         return -1;
859                 }
860                 break;
861
862         case PW_TYPE_IFID:
863         case PW_TYPE_IPV4_ADDR:
864         case PW_TYPE_IPV6_ADDR:
865         case PW_TYPE_IPV6_PREFIX:
866         case PW_TYPE_IPV4_PREFIX:
867         case PW_TYPE_ABINARY:
868         case PW_TYPE_ETHERNET:  /* just in case */
869                 data = (uint8_t const *) &vp->data;
870                 break;
871
872         case PW_TYPE_BYTE:
873                 len = 1;        /* just in case */
874                 array[0] = vp->vp_byte;
875                 data = array;
876                 break;
877
878         case PW_TYPE_SHORT:
879                 len = 2;        /* just in case */
880                 array[0] = (vp->vp_short >> 8) & 0xff;
881                 array[1] = vp->vp_short & 0xff;
882                 data = array;
883                 break;
884
885         case PW_TYPE_INTEGER:
886                 len = 4;        /* just in case */
887                 lvalue = htonl(vp->vp_integer);
888                 memcpy(array, &lvalue, sizeof(lvalue));
889                 data = array;
890                 break;
891
892         case PW_TYPE_INTEGER64:
893                 len = 8;        /* just in case */
894                 lvalue64 = htonll(vp->vp_integer64);
895                 data = (uint8_t *) &lvalue64;
896                 break;
897
898                 /*
899                  *  There are no tagged date attributes.
900                  */
901         case PW_TYPE_DATE:
902                 lvalue = htonl(vp->vp_date);
903                 data = (uint8_t const *) &lvalue;
904                 len = 4;        /* just in case */
905                 break;
906
907         case PW_TYPE_SIGNED:
908         {
909                 int32_t slvalue;
910
911                 len = 4;        /* just in case */
912                 slvalue = htonl(vp->vp_signed);
913                 memcpy(array, &slvalue, sizeof(slvalue));
914                 data = array;
915                 break;
916         }
917
918         default:                /* unknown type: ignore it */
919                 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->da->type);
920                 return -1;
921         }
922
923         /*
924          *      No data: skip it.
925          */
926         if (len == 0) {
927                 *pvp = vp->next;
928                 return 0;
929         }
930
931         /*
932          *      Bound the data to the calling size
933          */
934         if (len > (ssize_t) room) len = room;
935
936         /*
937          *      Encrypt the various password styles
938          *
939          *      Attributes with encrypted values MUST be less than
940          *      128 bytes long.
941          */
942         switch (vp->da->flags.encrypt) {
943         case FLAG_ENCRYPT_USER_PASSWORD:
944                 make_passwd(ptr, &len, data, len,
945                             secret, packet->vector);
946                 break;
947
948         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
949                 lvalue = 0;
950                 if (vp->da->flags.has_tag) lvalue = 1;
951
952                 /*
953                  *      Check if there's enough room.  If there isn't,
954                  *      we discard the attribute.
955                  *
956                  *      This is ONLY a problem if we have multiple VSA's
957                  *      in one Vendor-Specific, though.
958                  */
959                 if (room < (18 + lvalue)) return 0;
960
961                 switch (packet->code) {
962                 case PW_CODE_ACCESS_ACCEPT:
963                 case PW_CODE_ACCESS_REJECT:
964                 case PW_CODE_ACCESS_CHALLENGE:
965                 default:
966                         if (!original) {
967                                 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->da->name);
968                                 return -1;
969                         }
970
971                         if (lvalue) ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
972                         make_tunnel_passwd(ptr + lvalue, &len, data, len,
973                                            room - lvalue,
974                                            secret, original->vector);
975                         break;
976                 case PW_CODE_ACCOUNTING_REQUEST:
977                 case PW_CODE_DISCONNECT_REQUEST:
978                 case PW_CODE_COA_REQUEST:
979                         ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
980                         make_tunnel_passwd(ptr + 1, &len, data, len - 1, room,
981                                            secret, packet->vector);
982                         break;
983                 }
984                 break;
985
986                 /*
987                  *      The code above ensures that this attribute
988                  *      always fits.
989                  */
990         case FLAG_ENCRYPT_ASCEND_SECRET:
991                 if (len != 16) return 0;
992                 make_secret(ptr, packet->vector, secret, data);
993                 len = AUTH_VECTOR_LEN;
994                 break;
995
996
997         default:
998                 if (vp->da->flags.has_tag && TAG_VALID(vp->tag)) {
999                         if (vp->da->type == PW_TYPE_STRING) {
1000                                 if (len > ((ssize_t) (room - 1))) len = room - 1;
1001                                 ptr[0] = vp->tag;
1002                                 ptr++;
1003                         } else if (vp->da->type == PW_TYPE_INTEGER) {
1004                                 array[0] = vp->tag;
1005                         } /* else it can't be any other type */
1006                 }
1007                 memcpy(ptr, data, len);
1008                 break;
1009         } /* switch over encryption flags */
1010
1011         *pvp = vp->next;
1012         return len + (ptr - start);
1013 }
1014
1015 static ssize_t attr_shift(uint8_t const *start, uint8_t const *end,
1016                           uint8_t *ptr, int hdr_len, ssize_t len,
1017                           int flag_offset, int vsa_offset)
1018 {
1019         int check_len = len - ptr[1];
1020         int total = len + hdr_len;
1021
1022         /*
1023          *      Pass 1: Check if the addition of the headers
1024          *      overflows the available room.  If so, return
1025          *      what we were capable of encoding.
1026          */
1027
1028         while (check_len > (255 - hdr_len)) {
1029                 total += hdr_len;
1030                 check_len -= (255 - hdr_len);
1031         }
1032
1033         /*
1034          *      Note that this results in a number of attributes maybe
1035          *      being marked as "encoded", but which aren't in the
1036          *      packet.  Oh well.  The solution is to fix the
1037          *      "vp2data_any" function to take into account the header
1038          *      lengths.
1039          */
1040         if ((ptr + ptr[1] + total) > end) {
1041                 return (ptr + ptr[1]) - start;
1042         }
1043
1044         /*
1045          *      Pass 2: Now that we know there's enough room,
1046          *      re-arrange the data to form a set of valid
1047          *      RADIUS attributes.
1048          */
1049         while (1) {
1050                 int sublen = 255 - ptr[1];
1051
1052                 if (len <= sublen) {
1053                         break;
1054                 }
1055
1056                 len -= sublen;
1057                 memmove(ptr + 255 + hdr_len, ptr + 255, sublen);
1058                 memmove(ptr + 255, ptr, hdr_len);
1059                 ptr[1] += sublen;
1060                 if (vsa_offset) ptr[vsa_offset] += sublen;
1061                 ptr[flag_offset] |= 0x80;
1062
1063                 ptr += 255;
1064                 ptr[1] = hdr_len;
1065                 if (vsa_offset) ptr[vsa_offset] = 3;
1066         }
1067
1068         ptr[1] += len;
1069         if (vsa_offset) ptr[vsa_offset] += len;
1070
1071         return (ptr + ptr[1]) - start;
1072 }
1073
1074
1075 /** Encode an "extended" attribute
1076  */
1077 int rad_vp2extended(RADIUS_PACKET const *packet,
1078                     RADIUS_PACKET const *original,
1079                     char const *secret, VALUE_PAIR const **pvp,
1080                     uint8_t *ptr, size_t room)
1081 {
1082         int len;
1083         int hdr_len;
1084         uint8_t *start = ptr;
1085         VALUE_PAIR const *vp = *pvp;
1086
1087         VERIFY_VP(vp);
1088
1089         if (!vp->da->flags.extended) {
1090                 fr_strerror_printf("rad_vp2extended called for non-extended attribute");
1091                 return -1;
1092         }
1093
1094         /*
1095          *      The attribute number is encoded into the upper 8 bits
1096          *      of the vendor ID.
1097          */
1098         ptr[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1099
1100         if (!vp->da->flags.long_extended) {
1101                 if (room < 3) return 0;
1102
1103                 ptr[1] = 3;
1104                 ptr[2] = vp->da->attr & fr_attr_mask[0];
1105
1106         } else {
1107                 if (room < 4) return 0;
1108
1109                 ptr[1] = 4;
1110                 ptr[2] = vp->da->attr & fr_attr_mask[0];
1111                 ptr[3] = 0;
1112         }
1113
1114         /*
1115          *      Only "flagged" attributes can be longer than one
1116          *      attribute.
1117          */
1118         if (!vp->da->flags.long_extended && (room > 255)) {
1119                 room = 255;
1120         }
1121
1122         /*
1123          *      Handle EVS VSAs.
1124          */
1125         if (vp->da->flags.evs) {
1126                 uint8_t *evs = ptr + ptr[1];
1127
1128                 if (room < (size_t) (ptr[1] + 5)) return 0;
1129
1130                 ptr[2] = 26;
1131
1132                 evs[0] = 0;     /* always zero */
1133                 evs[1] = (vp->da->vendor >> 16) & 0xff;
1134                 evs[2] = (vp->da->vendor >> 8) & 0xff;
1135                 evs[3] = vp->da->vendor & 0xff;
1136                 evs[4] = vp->da->attr & fr_attr_mask[0];
1137
1138                 ptr[1] += 5;
1139         }
1140         hdr_len = ptr[1];
1141
1142         len = vp2data_any(packet, original, secret, 0,
1143                           pvp, ptr + ptr[1], room - hdr_len);
1144         if (len <= 0) return len;
1145
1146         /*
1147          *      There may be more than 252 octets of data encoded in
1148          *      the attribute.  If so, move the data up in the packet,
1149          *      and copy the existing header over.  Set the "M" flag ONLY
1150          *      after copying the rest of the data.
1151          */
1152         if (vp->da->flags.long_extended && (len > (255 - ptr[1]))) {
1153                 return attr_shift(start, start + room, ptr, 4, len, 3, 0);
1154         }
1155
1156         ptr[1] += len;
1157
1158 #ifndef NDEBUG
1159         if ((fr_debug_lvl > 3) && fr_log_fp) {
1160                 int jump = 3;
1161
1162                 fprintf(fr_log_fp, "\t\t%02x %02x  ", ptr[0], ptr[1]);
1163                 if (!vp->da->flags.long_extended) {
1164                         fprintf(fr_log_fp, "%02x  ", ptr[2]);
1165
1166                 } else {
1167                         fprintf(fr_log_fp, "%02x %02x  ", ptr[2], ptr[3]);
1168                         jump = 4;
1169                 }
1170
1171                 if (vp->da->flags.evs) {
1172                         fprintf(fr_log_fp, "%02x%02x%02x%02x (%u)  %02x  ",
1173                                 ptr[jump], ptr[jump + 1],
1174                                 ptr[jump + 2], ptr[jump + 3],
1175                                 ((ptr[jump + 1] << 16) |
1176                                  (ptr[jump + 2] << 8) |
1177                                  ptr[jump + 3]),
1178                                 ptr[jump + 4]);
1179                         jump += 5;
1180                 }
1181
1182                 print_hex_data(ptr + jump, len, 3);
1183         }
1184 #endif
1185
1186         return (ptr + ptr[1]) - start;
1187 }
1188
1189
1190 /** Encode a WiMAX attribute
1191  *
1192  */
1193 int rad_vp2wimax(RADIUS_PACKET const *packet,
1194                  RADIUS_PACKET const *original,
1195                  char const *secret, VALUE_PAIR const **pvp,
1196                  uint8_t *ptr, size_t room)
1197 {
1198         int len;
1199         uint32_t lvalue;
1200         int hdr_len;
1201         uint8_t *start = ptr;
1202         VALUE_PAIR const *vp = *pvp;
1203
1204         VERIFY_VP(vp);
1205
1206         /*
1207          *      Double-check for WiMAX format.
1208          */
1209         if (!vp->da->flags.wimax) {
1210                 fr_strerror_printf("rad_vp2wimax called for non-WIMAX VSA");
1211                 return -1;
1212         }
1213
1214         /*
1215          *      Not enough room for:
1216          *              attr, len, vendor-id, vsa, vsalen, continuation
1217          */
1218         if (room < 9) return 0;
1219
1220         /*
1221          *      Build the Vendor-Specific header
1222          */
1223         ptr = start;
1224         ptr[0] = PW_VENDOR_SPECIFIC;
1225         ptr[1] = 9;
1226         lvalue = htonl(vp->da->vendor);
1227         memcpy(ptr + 2, &lvalue, 4);
1228         ptr[6] = (vp->da->attr & fr_attr_mask[1]);
1229         ptr[7] = 3;
1230         ptr[8] = 0;             /* continuation byte */
1231
1232         hdr_len = 9;
1233
1234         len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1],
1235                           room - hdr_len);
1236         if (len <= 0) return len;
1237
1238         /*
1239          *      There may be more than 252 octets of data encoded in
1240          *      the attribute.  If so, move the data up in the packet,
1241          *      and copy the existing header over.  Set the "C" flag
1242          *      ONLY after copying the rest of the data.
1243          */
1244         if (len > (255 - ptr[1])) {
1245                 return attr_shift(start, start + room, ptr, hdr_len, len, 8, 7);
1246         }
1247
1248         ptr[1] += len;
1249         ptr[7] += len;
1250
1251 #ifndef NDEBUG
1252         if ((fr_debug_lvl > 3) && fr_log_fp) {
1253                 fprintf(fr_log_fp, "\t\t%02x %02x  %02x%02x%02x%02x (%u)  %02x %02x %02x   ",
1254                        ptr[0], ptr[1],
1255                        ptr[2], ptr[3], ptr[4], ptr[5],
1256                        (ptr[3] << 16) | (ptr[4] << 8) | ptr[5],
1257                        ptr[6], ptr[7], ptr[8]);
1258                 print_hex_data(ptr + 9, len, 3);
1259         }
1260 #endif
1261
1262         return (ptr + ptr[1]) - start;
1263 }
1264
1265 /** Encode an RFC format attribute, with the "concat" flag set
1266  *
1267  * If there isn't enough room in the packet, the data is
1268  * truncated to fit.
1269  */
1270 static ssize_t vp2attr_concat(UNUSED RADIUS_PACKET const *packet,
1271                               UNUSED RADIUS_PACKET const *original,
1272                               UNUSED char const *secret, VALUE_PAIR const **pvp,
1273                               unsigned int attribute, uint8_t *start, size_t room)
1274 {
1275         uint8_t *ptr = start;
1276         uint8_t const *p;
1277         size_t len, left;
1278         VALUE_PAIR const *vp = *pvp;
1279
1280         VERIFY_VP(vp);
1281
1282         p = vp->vp_octets;
1283         len = vp->vp_length;
1284
1285         while (len > 0) {
1286                 if (room <= 2) break;
1287
1288                 ptr[0] = attribute;
1289                 ptr[1] = 2;
1290
1291                 left = len;
1292
1293                 /* no more than 253 octets */
1294                 if (left > 253) left = 253;
1295
1296                 /* no more than "room" octets */
1297                 if (room < (left + 2)) left = room - 2;
1298
1299                 memcpy(ptr + 2, p, left);
1300
1301 #ifndef NDEBUG
1302                 if ((fr_debug_lvl > 3) && fr_log_fp) {
1303                         fprintf(fr_log_fp, "\t\t%02x %02x  ", ptr[0], ptr[1]);
1304                         print_hex_data(ptr + 2, len, 3);
1305                 }
1306 #endif
1307                 ptr[1] += left;
1308                 ptr += ptr[1];
1309                 p += left;
1310                 room -= left;
1311                 len -= left;
1312         }
1313
1314         *pvp = vp->next;
1315         return ptr - start;
1316 }
1317
1318 /** Encode an RFC format TLV.
1319  *
1320  * This could be a standard attribute, or a TLV data type.
1321  * If it's a standard attribute, then vp->da->attr == attribute.
1322  * Otherwise, attribute may be something else.
1323  */
1324 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
1325                            RADIUS_PACKET const *original,
1326                            char const *secret, VALUE_PAIR const **pvp,
1327                            unsigned int attribute, uint8_t *ptr, size_t room)
1328 {
1329         ssize_t len;
1330
1331         if (room <= 2) return 0;
1332
1333         ptr[0] = attribute & 0xff;
1334         ptr[1] = 2;
1335
1336         if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1337
1338         len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1], room);
1339         if (len <= 0) return len;
1340
1341         ptr[1] += len;
1342
1343 #ifndef NDEBUG
1344         if ((fr_debug_lvl > 3) && fr_log_fp) {
1345                 fprintf(fr_log_fp, "\t\t%02x %02x  ", ptr[0], ptr[1]);
1346                 print_hex_data(ptr + 2, len, 3);
1347         }
1348 #endif
1349
1350         return ptr[1];
1351 }
1352
1353
1354 /** Encode a VSA which is a TLV
1355  *
1356  * If it's in the RFC format, call vp2attr_rfc.  Otherwise, encode it here.
1357  */
1358 static ssize_t vp2attr_vsa(RADIUS_PACKET const *packet,
1359                            RADIUS_PACKET const *original,
1360                            char const *secret, VALUE_PAIR const **pvp,
1361                            unsigned int attribute, unsigned int vendor,
1362                            uint8_t *ptr, size_t room)
1363 {
1364         ssize_t len;
1365         DICT_VENDOR *dv;
1366         VALUE_PAIR const *vp = *pvp;
1367
1368         VERIFY_VP(vp);
1369         /*
1370          *      Unknown vendor: RFC format.
1371          *      Known vendor and RFC format: go do that.
1372          */
1373         dv = dict_vendorbyvalue(vendor);
1374         if (!dv ||
1375             (!vp->da->flags.is_tlv && (dv->type == 1) && (dv->length == 1))) {
1376                 return vp2attr_rfc(packet, original, secret, pvp,
1377                                    attribute, ptr, room);
1378         }
1379
1380         switch (dv->type) {
1381         default:
1382                 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1383                                    " type %u", (unsigned) dv->type);
1384                 return -1;
1385
1386         case 4:
1387                 ptr[0] = 0;     /* attr must be 24-bit */
1388                 ptr[1] = (attribute >> 16) & 0xff;
1389                 ptr[2] = (attribute >> 8) & 0xff;
1390                 ptr[3] = attribute & 0xff;
1391                 break;
1392
1393         case 2:
1394                 ptr[0] = (attribute >> 8) & 0xff;
1395                 ptr[1] = attribute & 0xff;
1396                 break;
1397
1398         case 1:
1399                 ptr[0] = attribute & 0xff;
1400                 break;
1401         }
1402
1403         switch (dv->length) {
1404         default:
1405                 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1406                                    " length %u", (unsigned) dv->length);
1407                 return -1;
1408
1409         case 0:
1410                 break;
1411
1412         case 2:
1413                 ptr[dv->type] = 0;
1414                 ptr[dv->type + 1] = dv->type + 2;
1415                 break;
1416
1417         case 1:
1418                 ptr[dv->type] = dv->type + 1;
1419                 break;
1420
1421         }
1422
1423         if (room > ((unsigned) 255 - (dv->type + dv->length))) {
1424                 room = 255 - (dv->type + dv->length);
1425         }
1426
1427         len = vp2data_any(packet, original, secret, 0, pvp,
1428                           ptr + dv->type + dv->length, room);
1429         if (len <= 0) return len;
1430
1431         if (dv->length) ptr[dv->type + dv->length - 1] += len;
1432
1433 #ifndef NDEBUG
1434         if ((fr_debug_lvl > 3) && fr_log_fp) {
1435                 switch (dv->type) {
1436                 default:
1437                         break;
1438
1439                 case 4:
1440                         if ((fr_debug_lvl > 3) && fr_log_fp)
1441                                 fprintf(fr_log_fp, "\t\t%02x%02x%02x%02x ",
1442                                         ptr[0], ptr[1], ptr[2], ptr[3]);
1443                         break;
1444
1445                 case 2:
1446                         if ((fr_debug_lvl > 3) && fr_log_fp)
1447                                 fprintf(fr_log_fp, "\t\t%02x%02x ",
1448                                         ptr[0], ptr[1]);
1449                 break;
1450
1451                 case 1:
1452                         if ((fr_debug_lvl > 3) && fr_log_fp)
1453                                 fprintf(fr_log_fp, "\t\t%02x ", ptr[0]);
1454                         break;
1455                 }
1456
1457                 switch (dv->length) {
1458                 default:
1459                         break;
1460
1461                 case 0:
1462                         fprintf(fr_log_fp, "  ");
1463                         break;
1464
1465                 case 1:
1466                         fprintf(fr_log_fp, "%02x  ",
1467                                 ptr[dv->type]);
1468                         break;
1469
1470                 case 2:
1471                         fprintf(fr_log_fp, "%02x%02x  ",
1472                                 ptr[dv->type], ptr[dv->type] + 1);
1473                         break;
1474                 }
1475
1476                 print_hex_data(ptr + dv->type + dv->length, len, 3);
1477         }
1478 #endif
1479
1480         return dv->type + dv->length + len;
1481 }
1482
1483
1484 /** Encode a Vendor-Specific attribute
1485  *
1486  */
1487 int rad_vp2vsa(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1488                 char const *secret, VALUE_PAIR const **pvp, uint8_t *ptr,
1489                 size_t room)
1490 {
1491         ssize_t len;
1492         uint32_t lvalue;
1493         VALUE_PAIR const *vp = *pvp;
1494
1495         VERIFY_VP(vp);
1496
1497         if (vp->da->vendor == 0) {
1498                 fr_strerror_printf("rad_vp2vsa called with rfc attribute");
1499                 return -1;
1500         }
1501
1502         /*
1503          *      Double-check for WiMAX format.
1504          */
1505         if (vp->da->flags.wimax) {
1506                 return rad_vp2wimax(packet, original, secret, pvp, ptr, room);
1507         }
1508
1509         if (vp->da->vendor > FR_MAX_VENDOR) {
1510                 fr_strerror_printf("rad_vp2vsa: Invalid arguments");
1511                 return -1;
1512         }
1513
1514         /*
1515          *      Not enough room for:
1516          *              attr, len, vendor-id
1517          */
1518         if (room < 6) return 0;
1519
1520         /*
1521          *      Build the Vendor-Specific header
1522          */
1523         ptr[0] = PW_VENDOR_SPECIFIC;
1524         ptr[1] = 6;
1525         lvalue = htonl(vp->da->vendor);
1526         memcpy(ptr + 2, &lvalue, 4);
1527
1528         if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1529
1530         len = vp2attr_vsa(packet, original, secret, pvp,
1531                           vp->da->attr, vp->da->vendor,
1532                           ptr + ptr[1], room);
1533         if (len < 0) return len;
1534
1535 #ifndef NDEBUG
1536         if ((fr_debug_lvl > 3) && fr_log_fp) {
1537                 fprintf(fr_log_fp, "\t\t%02x %02x  %02x%02x%02x%02x (%u)  ",
1538                        ptr[0], ptr[1],
1539                        ptr[2], ptr[3], ptr[4], ptr[5],
1540                        (ptr[3] << 16) | (ptr[4] << 8) | ptr[5]);
1541                 print_hex_data(ptr + 6, len, 3);
1542         }
1543 #endif
1544
1545         ptr[1] += len;
1546
1547         return ptr[1];
1548 }
1549
1550
1551 /** Encode an RFC standard attribute 1..255
1552  *
1553  */
1554 int rad_vp2rfc(RADIUS_PACKET const *packet,
1555                RADIUS_PACKET const *original,
1556                char const *secret, VALUE_PAIR const **pvp,
1557                uint8_t *ptr, size_t room)
1558 {
1559         VALUE_PAIR const *vp = *pvp;
1560
1561         VERIFY_VP(vp);
1562
1563         if (vp->da->vendor != 0) {
1564                 fr_strerror_printf("rad_vp2rfc called with VSA");
1565                 return -1;
1566         }
1567
1568         if ((vp->da->attr == 0) || (vp->da->attr > 255)) {
1569                 fr_strerror_printf("rad_vp2rfc called with non-standard attribute %u", vp->da->attr);
1570                 return -1;
1571         }
1572
1573         /*
1574          *      Only CUI is allowed to have zero length.
1575          *      Thank you, WiMAX!
1576          */
1577         if ((vp->vp_length == 0) &&
1578             (vp->da->attr == PW_CHARGEABLE_USER_IDENTITY)) {
1579                 ptr[0] = PW_CHARGEABLE_USER_IDENTITY;
1580                 ptr[1] = 2;
1581
1582                 *pvp = vp->next;
1583                 return 2;
1584         }
1585
1586         /*
1587          *      Message-Authenticator is hard-coded.
1588          */
1589         if (!vp->da->vendor && (vp->da->attr == PW_MESSAGE_AUTHENTICATOR)) {
1590                 if (room < 18) return -1;
1591
1592                 ptr[0] = PW_MESSAGE_AUTHENTICATOR;
1593                 ptr[1] = 18;
1594                 memset(ptr + 2, 0, 16);
1595 #ifndef NDEBUG
1596                 if ((fr_debug_lvl > 3) && fr_log_fp) {
1597                         fprintf(fr_log_fp, "\t\t50 12 ...\n");
1598                 }
1599 #endif
1600
1601                 *pvp = (*pvp)->next;
1602                 return 18;
1603         }
1604
1605         /*
1606          *      EAP-Message is special.
1607          */
1608         if (vp->da->flags.concat && (vp->vp_length > 253)) {
1609                 return vp2attr_concat(packet, original, secret, pvp, vp->da->attr,
1610                                       ptr, room);
1611         }
1612
1613         return vp2attr_rfc(packet, original, secret, pvp, vp->da->attr,
1614                            ptr, room);
1615 }
1616
1617 static ssize_t rad_vp2rfctlv(RADIUS_PACKET const *packet,
1618                              RADIUS_PACKET const *original,
1619                              char const *secret, VALUE_PAIR const **pvp,
1620                              uint8_t *start, size_t room)
1621 {
1622         ssize_t len;
1623         VALUE_PAIR const *vp = *pvp;
1624
1625         VERIFY_VP(vp);
1626
1627         if (!vp->da->flags.is_tlv) {
1628                 fr_strerror_printf("rad_vp2rfctlv: attr is not a TLV");
1629                 return -1;
1630         }
1631
1632         if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) != 0) {
1633                 fr_strerror_printf("rad_vp2rfctlv: attr is not an RFC TLV");
1634                 return -1;
1635         }
1636
1637         if (room < 5) return 0;
1638
1639         /*
1640          *      Encode the first level of TLVs
1641          */
1642         start[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1643         start[1] = 4;
1644         start[2] = vp->da->attr & fr_attr_mask[0];
1645         start[3] = 2;
1646
1647         len = vp2data_any(packet, original, secret, 0, pvp,
1648                           start + 4, room - 4);
1649         if (len <= 0) return len;
1650
1651         if (len > 253) {
1652                 return -1;
1653         }
1654
1655         start[1] += len;
1656         start[3] += len;
1657
1658         return start[1];
1659 }
1660
1661 /** Parse a data structure into a RADIUS attribute
1662  *
1663  */
1664 int rad_vp2attr(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1665                 char const *secret, VALUE_PAIR const **pvp, uint8_t *start,
1666                 size_t room)
1667 {
1668         VALUE_PAIR const *vp;
1669
1670         if (!pvp || !*pvp || !start || (room <= 2)) return -1;
1671
1672         vp = *pvp;
1673
1674         VERIFY_VP(vp);
1675
1676         /*
1677          *      RFC format attributes take the fast path.
1678          */
1679         if (!vp->da->vendor) {
1680                 if (vp->da->attr > 255) return 0;
1681
1682                 return rad_vp2rfc(packet, original, secret, pvp,
1683                                   start, room);
1684         }
1685
1686         if (vp->da->flags.extended) {
1687                 return rad_vp2extended(packet, original, secret, pvp,
1688                                        start, room);
1689         }
1690
1691         /*
1692          *      The upper 8 bits of the vendor number are the standard
1693          *      space attribute which is a TLV.
1694          */
1695         if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) == 0) {
1696                 return rad_vp2rfctlv(packet, original, secret, pvp,
1697                                      start, room);
1698         }
1699
1700         if (vp->da->flags.wimax) {
1701                 return rad_vp2wimax(packet, original, secret, pvp,
1702                                     start, room);
1703         }
1704
1705         return rad_vp2vsa(packet, original, secret, pvp, start, room);
1706 }
1707
1708
1709 /** Encode a packet
1710  *
1711  */
1712 int rad_encode(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1713                char const *secret)
1714 {
1715         radius_packet_t         *hdr;
1716         uint8_t                 *ptr;
1717         uint16_t                total_length;
1718         int                     len;
1719         VALUE_PAIR const        *reply;
1720
1721         /*
1722          *      A 4K packet, aligned on 64-bits.
1723          */
1724         uint64_t        data[MAX_PACKET_LEN / sizeof(uint64_t)];
1725
1726         /*
1727          *      Double-check some things based on packet code.
1728          */
1729         switch (packet->code) {
1730         case PW_CODE_ACCESS_ACCEPT:
1731         case PW_CODE_ACCESS_REJECT:
1732         case PW_CODE_ACCESS_CHALLENGE:
1733                 if (!original) {
1734                         fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1735                         return -1;
1736                 }
1737                 break;
1738
1739                 /*
1740                  *      These packet vectors start off as all zero.
1741                  */
1742         case PW_CODE_ACCOUNTING_REQUEST:
1743         case PW_CODE_DISCONNECT_REQUEST:
1744         case PW_CODE_COA_REQUEST:
1745                 memset(packet->vector, 0, sizeof(packet->vector));
1746                 break;
1747
1748         default:
1749                 break;
1750         }
1751
1752         /*
1753          *      Use memory on the stack, until we know how
1754          *      large the packet will be.
1755          */
1756         hdr = (radius_packet_t *) data;
1757
1758         /*
1759          *      Build standard header
1760          */
1761         hdr->code = packet->code;
1762         hdr->id = packet->id;
1763
1764         memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1765
1766         total_length = RADIUS_HDR_LEN;
1767
1768         /*
1769          *      Load up the configuration values for the user
1770          */
1771         ptr = hdr->data;
1772         packet->offset = 0;
1773
1774         /*
1775          *      FIXME: Loop twice over the reply list.  The first time,
1776          *      calculate the total length of data.  The second time,
1777          *      allocate the memory, and fill in the VP's.
1778          *
1779          *      Hmm... this may be slower than just doing a small
1780          *      memcpy.
1781          */
1782
1783         /*
1784          *      Loop over the reply attributes for the packet.
1785          */
1786         reply = packet->vps;
1787         while (reply) {
1788                 size_t last_len;
1789                 char const *last_name = NULL;
1790
1791                 VERIFY_VP(reply);
1792
1793                 /*
1794                  *      Ignore non-wire attributes, but allow extended
1795                  *      attributes.
1796                  */
1797                 if ((reply->da->vendor == 0) &&
1798                     ((reply->da->attr & 0xFFFF) >= 256) &&
1799                     !reply->da->flags.extended && !reply->da->flags.long_extended) {
1800 #ifndef NDEBUG
1801                         /*
1802                          *      Permit the admin to send BADLY formatted
1803                          *      attributes with a debug build.
1804                          */
1805                         if (reply->da->attr == PW_RAW_ATTRIBUTE) {
1806                                 memcpy(ptr, reply->vp_octets, reply->vp_length);
1807                                 len = reply->vp_length;
1808                                 reply = reply->next;
1809                                 goto next;
1810                         }
1811 #endif
1812                         reply = reply->next;
1813                         continue;
1814                 }
1815
1816                 /*
1817                  *      Set the Message-Authenticator to the correct
1818                  *      length and initial value.
1819                  */
1820                 if (!reply->da->vendor && (reply->da->attr == PW_MESSAGE_AUTHENTICATOR)) {
1821                         /*
1822                          *      Cache the offset to the
1823                          *      Message-Authenticator
1824                          */
1825                         packet->offset = total_length;
1826                         last_len = 16;
1827                 } else {
1828                         last_len = reply->vp_length;
1829                 }
1830                 last_name = reply->da->name;
1831
1832                 len = rad_vp2attr(packet, original, secret, &reply, ptr,
1833                                   ((uint8_t *) data) + sizeof(data) - ptr);
1834                 if (len < 0) return -1;
1835
1836                 /*
1837                  *      Failed to encode the attribute, likely because
1838                  *      the packet is full.
1839                  */
1840                 if (len == 0) {
1841                         if (last_len != 0) {
1842                                 fr_strerror_printf("WARNING: Failed encoding attribute %s\n", last_name);
1843                                 break;
1844                         } else {
1845                                 fr_strerror_printf("WARNING: Skipping zero-length attribute %s\n", last_name);
1846                         }
1847                 }
1848
1849 #ifndef NDEBUG
1850         next:                   /* Used only for Raw-Attribute */
1851 #endif
1852                 ptr += len;
1853                 total_length += len;
1854         } /* done looping over all attributes */
1855
1856         /*
1857          *      Fill in the rest of the fields, and copy the data over
1858          *      from the local stack to the newly allocated memory.
1859          *
1860          *      Yes, all this 'memcpy' is slow, but it means
1861          *      that we only allocate the minimum amount of
1862          *      memory for a request.
1863          */
1864         packet->data_len = total_length;
1865         packet->data = talloc_array(packet, uint8_t, packet->data_len);
1866         if (!packet->data) {
1867                 fr_strerror_printf("Out of memory");
1868                 return -1;
1869         }
1870
1871         memcpy(packet->data, hdr, packet->data_len);
1872         hdr = (radius_packet_t *) packet->data;
1873
1874         total_length = htons(total_length);
1875         memcpy(hdr->length, &total_length, sizeof(total_length));
1876
1877         return 0;
1878 }
1879
1880
1881 /** Sign a previously encoded packet
1882  *
1883  */
1884 int rad_sign(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1885              char const *secret)
1886 {
1887         radius_packet_t *hdr = (radius_packet_t *)packet->data;
1888
1889         /*
1890          *      It wasn't assigned an Id, this is bad!
1891          */
1892         if (packet->id < 0) {
1893                 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id");
1894                 return -1;
1895         }
1896
1897         if (!packet->data || (packet->data_len < RADIUS_HDR_LEN) ||
1898             (packet->offset < 0)) {
1899                 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1900                 return -1;
1901         }
1902
1903         /*
1904          *      If there's a Message-Authenticator, update it
1905          *      now, BEFORE updating the authentication vector.
1906          */
1907         if (packet->offset > 0) {
1908                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1909
1910                 switch (packet->code) {
1911                 case PW_CODE_ACCOUNTING_RESPONSE:
1912                         if (original && original->code == PW_CODE_STATUS_SERVER) {
1913                                 goto do_ack;
1914                         }
1915
1916                 case PW_CODE_ACCOUNTING_REQUEST:
1917                 case PW_CODE_DISCONNECT_REQUEST:
1918                 case PW_CODE_DISCONNECT_ACK:
1919                 case PW_CODE_DISCONNECT_NAK:
1920                 case PW_CODE_COA_REQUEST:
1921                 case PW_CODE_COA_ACK:
1922                         memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1923                         break;
1924
1925                 do_ack:
1926                 case PW_CODE_ACCESS_ACCEPT:
1927                 case PW_CODE_ACCESS_REJECT:
1928                 case PW_CODE_ACCESS_CHALLENGE:
1929                         if (!original) {
1930                                 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1931                                 return -1;
1932                         }
1933                         memcpy(hdr->vector, original->vector,
1934                                AUTH_VECTOR_LEN);
1935                         break;
1936
1937                 default:        /* others have vector already set to zero */
1938                         break;
1939
1940                 }
1941
1942                 /*
1943                  *      Set the authentication vector to zero,
1944                  *      calculate the HMAC, and put it
1945                  *      into the Message-Authenticator
1946                  *      attribute.
1947                  */
1948                 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
1949                             (uint8_t const *) secret, strlen(secret));
1950                 memcpy(packet->data + packet->offset + 2,
1951                        calc_auth_vector, AUTH_VECTOR_LEN);
1952
1953                 /*
1954                  *      Copy the original request vector back
1955                  *      to the raw packet.
1956                  */
1957                 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1958         }
1959
1960         /*
1961          *      Switch over the packet code, deciding how to
1962          *      sign the packet.
1963          */
1964         switch (packet->code) {
1965                 /*
1966                  *      Request packets are not signed, bur
1967                  *      have a random authentication vector.
1968                  */
1969         case PW_CODE_ACCESS_REQUEST:
1970         case PW_CODE_STATUS_SERVER:
1971                 break;
1972
1973                 /*
1974                  *      Reply packets are signed with the
1975                  *      authentication vector of the request.
1976                  */
1977         default:
1978                 {
1979                         uint8_t digest[16];
1980
1981                         FR_MD5_CTX      context;
1982                         fr_md5_init(&context);
1983                         fr_md5_update(&context, packet->data, packet->data_len);
1984                         fr_md5_update(&context, (uint8_t const *) secret,
1985                                      strlen(secret));
1986                         fr_md5_final(digest, &context);
1987
1988                         memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1989                         memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1990                         break;
1991                 }
1992         }/* switch over packet codes */
1993
1994         return 0;
1995 }
1996
1997 /** Reply to the request
1998  *
1999  * Also attach reply attribute value pairs and any user message provided.
2000  */
2001 int rad_send(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2002              char const *secret)
2003 {
2004         /*
2005          *      Maybe it's a fake packet.  Don't send it.
2006          */
2007         if (!packet || (packet->sockfd < 0)) {
2008                 return 0;
2009         }
2010
2011         /*
2012          *  First time through, allocate room for the packet
2013          */
2014         if (!packet->data) {
2015                 /*
2016                  *      Encode the packet.
2017                  */
2018                 if (rad_encode(packet, original, secret) < 0) {
2019                         return -1;
2020                 }
2021
2022                 /*
2023                  *      Re-sign it, including updating the
2024                  *      Message-Authenticator.
2025                  */
2026                 if (rad_sign(packet, original, secret) < 0) {
2027                         return -1;
2028                 }
2029
2030                 /*
2031                  *      If packet->data points to data, then we print out
2032                  *      the VP list again only for debugging.
2033                  */
2034         }
2035
2036 #ifndef NDEBUG
2037         if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2038 #endif
2039
2040 #ifdef WITH_TCP
2041         /*
2042          *      If the socket is TCP, call write().  Calling sendto()
2043          *      is allowed on some platforms, but it's not nice.  Even
2044          *      worse, if UDPFROMTO is defined, we *can't* use it on
2045          *      TCP sockets.  So... just call write().
2046          */
2047         if (packet->proto == IPPROTO_TCP) {
2048                 ssize_t rcode;
2049
2050                 rcode = write(packet->sockfd, packet->data, packet->data_len);
2051                 if (rcode >= 0) return rcode;
2052
2053                 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
2054                 return -1;
2055         }
2056 #endif
2057
2058         /*
2059          *      And send it on it's way.
2060          */
2061         return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
2062                           &packet->src_ipaddr, packet->src_port,
2063                           &packet->dst_ipaddr, packet->dst_port);
2064 }
2065
2066 /** Do a comparison of two authentication digests by comparing the FULL digest
2067  *
2068  * Otherwise, the server can be subject to timing attacks that allow attackers
2069  * find a valid message authenticator.
2070  *
2071  * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
2072  */
2073 int rad_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
2074 {
2075         int result = 0;
2076         size_t i;
2077
2078         for (i = 0; i < length; i++) {
2079                 result |= a[i] ^ b[i];
2080         }
2081
2082         return result;          /* 0 is OK, !0 is !OK, just like memcmp */
2083 }
2084
2085
2086 /** Validates the requesting client NAS
2087  *
2088  * Calculates the request Authenticator based on the clients private key.
2089  */
2090 static int calc_acctdigest(RADIUS_PACKET *packet, char const *secret)
2091 {
2092         uint8_t         digest[AUTH_VECTOR_LEN];
2093         FR_MD5_CTX              context;
2094
2095         /*
2096          *      Zero out the auth_vector in the received packet.
2097          *      Then append the shared secret to the received packet,
2098          *      and calculate the MD5 sum. This must be the same
2099          *      as the original MD5 sum (packet->vector).
2100          */
2101         memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2102
2103         /*
2104          *  MD5(packet + secret);
2105          */
2106         fr_md5_init(&context);
2107         fr_md5_update(&context, packet->data, packet->data_len);
2108         fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2109         fr_md5_final(digest, &context);
2110
2111         /*
2112          *      Return 0 if OK, 2 if not OK.
2113          */
2114         if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
2115         return 0;
2116 }
2117
2118
2119 /** Validates the requesting client NAS
2120  *
2121  * Calculates the response Authenticator based on the clients
2122  * private key.
2123  */
2124 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2125                             char const *secret)
2126 {
2127         uint8_t         calc_digest[AUTH_VECTOR_LEN];
2128         FR_MD5_CTX              context;
2129
2130         /*
2131          *      Very bad!
2132          */
2133         if (original == NULL) {
2134                 return 3;
2135         }
2136
2137         /*
2138          *  Copy the original vector in place.
2139          */
2140         memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2141
2142         /*
2143          *  MD5(packet + secret);
2144          */
2145         fr_md5_init(&context);
2146         fr_md5_update(&context, packet->data, packet->data_len);
2147         fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2148         fr_md5_final(calc_digest, &context);
2149
2150         /*
2151          *  Copy the packet's vector back to the packet.
2152          */
2153         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2154
2155         /*
2156          *      Return 0 if OK, 2 if not OK.
2157          */
2158         if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
2159         return 0;
2160 }
2161
2162 /** Check if a set of RADIUS formatted TLVs are OK
2163  *
2164  */
2165 int rad_tlv_ok(uint8_t const *data, size_t length,
2166                size_t dv_type, size_t dv_length)
2167 {
2168         uint8_t const *end = data + length;
2169
2170         VP_TRACE("checking TLV %u/%u\n", (unsigned int) dv_type, (unsigned int) dv_length);
2171
2172         VP_HEXDUMP("tlv_ok", data, length);
2173
2174         if ((dv_length > 2) || (dv_type == 0) || (dv_type > 4)) {
2175                 fr_strerror_printf("rad_tlv_ok: Invalid arguments");
2176                 return -1;
2177         }
2178
2179         while (data < end) {
2180                 size_t attrlen;
2181
2182                 if ((data + dv_type + dv_length) > end) {
2183                         fr_strerror_printf("Attribute header overflow");
2184                         return -1;
2185                 }
2186
2187                 switch (dv_type) {
2188                 case 4:
2189                         if ((data[0] == 0) && (data[1] == 0) &&
2190                             (data[2] == 0) && (data[3] == 0)) {
2191                         zero:
2192                                 fr_strerror_printf("Invalid attribute 0");
2193                                 return -1;
2194                         }
2195
2196                         if (data[0] != 0) {
2197                                 fr_strerror_printf("Invalid attribute > 2^24");
2198                                 return -1;
2199                         }
2200                         break;
2201
2202                 case 2:
2203                         if ((data[0] == 0) && (data[1] == 0)) goto zero;
2204                         break;
2205
2206                 case 1:
2207                         /*
2208                          *      Zero is allowed, because the Colubris
2209                          *      people are dumb and use it.
2210                          */
2211                         break;
2212
2213                 default:
2214                         fr_strerror_printf("Internal sanity check failed");
2215                         return -1;
2216                 }
2217
2218                 switch (dv_length) {
2219                 case 0:
2220                         return 0;
2221
2222                 case 2:
2223                         if (data[dv_type] != 0) {
2224                                 fr_strerror_printf("Attribute is longer than 256 octets");
2225                                 return -1;
2226                         }
2227                         /* FALL-THROUGH */
2228                 case 1:
2229                         attrlen = data[dv_type + dv_length - 1];
2230                         break;
2231
2232
2233                 default:
2234                         fr_strerror_printf("Internal sanity check failed");
2235                         return -1;
2236                 }
2237
2238                 if (attrlen < (dv_type + dv_length)) {
2239                         fr_strerror_printf("Attribute header has invalid length");
2240                         return -1;
2241                 }
2242
2243                 if (attrlen > length) {
2244                         fr_strerror_printf("Attribute overflows container");
2245                         return -1;
2246                 }
2247
2248                 data += attrlen;
2249                 length -= attrlen;
2250         }
2251
2252         return 0;
2253 }
2254
2255
2256 /** See if the data pointed to by PTR is a valid RADIUS packet.
2257  *
2258  * Packet is not 'const * const' because we may update data_len, if there's more data
2259  * in the UDP packet than in the RADIUS packet.
2260  *
2261  * @param packet to check
2262  * @param flags to control decoding
2263  * @param reason if not NULL, will have the failure reason written to where it points.
2264  * @return bool, true on success, false on failure.
2265  */
2266 bool rad_packet_ok(RADIUS_PACKET *packet, int flags, decode_fail_t *reason)
2267 {
2268         uint8_t                 *attr;
2269         size_t                  totallen;
2270         int                     count;
2271         radius_packet_t         *hdr;
2272         char                    host_ipaddr[128];
2273         bool                    require_ma = false;
2274         bool                    seen_ma = false;
2275         uint32_t                num_attributes;
2276         decode_fail_t           failure = DECODE_FAIL_NONE;
2277
2278         /*
2279          *      Check for packets smaller than the packet header.
2280          *
2281          *      RFC 2865, Section 3., subsection 'length' says:
2282          *
2283          *      "The minimum length is 20 ..."
2284          */
2285         if (packet->data_len < RADIUS_HDR_LEN) {
2286                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (received %zu < minimum %d)",
2287                            inet_ntop(packet->src_ipaddr.af,
2288                                      &packet->src_ipaddr.ipaddr,
2289                                      host_ipaddr, sizeof(host_ipaddr)),
2290                                      packet->data_len, RADIUS_HDR_LEN);
2291                 failure = DECODE_FAIL_MIN_LENGTH_PACKET;
2292                 goto finish;
2293         }
2294
2295
2296         /*
2297          *      Check for packets with mismatched size.
2298          *      i.e. We've received 128 bytes, and the packet header
2299          *      says it's 256 bytes long.
2300          */
2301         totallen = (packet->data[2] << 8) | packet->data[3];
2302         hdr = (radius_packet_t *)packet->data;
2303
2304         /*
2305          *      Code of 0 is not understood.
2306          *      Code of 16 or greate is not understood.
2307          */
2308         if ((hdr->code == 0) ||
2309             (hdr->code >= FR_MAX_PACKET_CODE)) {
2310                 FR_DEBUG_STRERROR_PRINTF("Bad RADIUS packet from host %s: unknown packet code %d",
2311                            inet_ntop(packet->src_ipaddr.af,
2312                                      &packet->src_ipaddr.ipaddr,
2313                                      host_ipaddr, sizeof(host_ipaddr)),
2314                            hdr->code);
2315                 failure = DECODE_FAIL_UNKNOWN_PACKET_CODE;
2316                 goto finish;
2317         }
2318
2319         /*
2320          *      Message-Authenticator is required in Status-Server
2321          *      packets, otherwise they can be trivially forged.
2322          */
2323         if (hdr->code == PW_CODE_STATUS_SERVER) require_ma = true;
2324
2325         /*
2326          *      It's also required if the caller asks for it.
2327          */
2328         if (flags) require_ma = true;
2329
2330         /*
2331          *      Repeat the length checks.  This time, instead of
2332          *      looking at the data we received, look at the value
2333          *      of the 'length' field inside of the packet.
2334          *
2335          *      Check for packets smaller than the packet header.
2336          *
2337          *      RFC 2865, Section 3., subsection 'length' says:
2338          *
2339          *      "The minimum length is 20 ..."
2340          */
2341         if (totallen < RADIUS_HDR_LEN) {
2342                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (length %zu < minimum %d)",
2343                            inet_ntop(packet->src_ipaddr.af,
2344                                      &packet->src_ipaddr.ipaddr,
2345                                      host_ipaddr, sizeof(host_ipaddr)),
2346                                      totallen, RADIUS_HDR_LEN);
2347                 failure = DECODE_FAIL_MIN_LENGTH_FIELD;
2348                 goto finish;
2349         }
2350
2351         /*
2352          *      And again, for the value of the 'length' field.
2353          *
2354          *      RFC 2865, Section 3., subsection 'length' says:
2355          *
2356          *      " ... and maximum length is 4096."
2357          *
2358          *      HOWEVER.  This requirement is for the network layer.
2359          *      If the code gets here, we assume that a well-formed
2360          *      packet is an OK packet.
2361          *
2362          *      We allow both the UDP data length, and the RADIUS
2363          *      "length" field to contain up to 64K of data.
2364          */
2365
2366         /*
2367          *      RFC 2865, Section 3., subsection 'length' says:
2368          *
2369          *      "If the packet is shorter than the Length field
2370          *      indicates, it MUST be silently discarded."
2371          *
2372          *      i.e. No response to the NAS.
2373          */
2374         if (packet->data_len < totallen) {
2375                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: received %zu octets, packet length says %zu",
2376                            inet_ntop(packet->src_ipaddr.af,
2377                                      &packet->src_ipaddr.ipaddr,
2378                                      host_ipaddr, sizeof(host_ipaddr)),
2379                                      packet->data_len, totallen);
2380                 failure = DECODE_FAIL_MIN_LENGTH_MISMATCH;
2381                 goto finish;
2382         }
2383
2384         /*
2385          *      RFC 2865, Section 3., subsection 'length' says:
2386          *
2387          *      "Octets outside the range of the Length field MUST be
2388          *      treated as padding and ignored on reception."
2389          */
2390         if (packet->data_len > totallen) {
2391                 /*
2392                  *      We're shortening the packet below, but just
2393                  *      to be paranoid, zero out the extra data.
2394                  */
2395                 memset(packet->data + totallen, 0, packet->data_len - totallen);
2396                 packet->data_len = totallen;
2397         }
2398
2399         /*
2400          *      Walk through the packet's attributes, ensuring that
2401          *      they add up EXACTLY to the size of the packet.
2402          *
2403          *      If they don't, then the attributes either under-fill
2404          *      or over-fill the packet.  Any parsing of the packet
2405          *      is impossible, and will result in unknown side effects.
2406          *
2407          *      This would ONLY happen with buggy RADIUS implementations,
2408          *      or with an intentional attack.  Either way, we do NOT want
2409          *      to be vulnerable to this problem.
2410          */
2411         attr = hdr->data;
2412         count = totallen - RADIUS_HDR_LEN;
2413         num_attributes = 0;
2414
2415         while (count > 0) {
2416                 /*
2417                  *      We need at least 2 bytes to check the
2418                  *      attribute header.
2419                  */
2420                 if (count < 2) {
2421                         FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute header overflows the packet",
2422                                    inet_ntop(packet->src_ipaddr.af,
2423                                              &packet->src_ipaddr.ipaddr,
2424                                              host_ipaddr, sizeof(host_ipaddr)));
2425                         failure = DECODE_FAIL_HEADER_OVERFLOW;
2426                         goto finish;
2427                 }
2428
2429                 /*
2430                  *      Attribute number zero is NOT defined.
2431                  */
2432                 if (attr[0] == 0) {
2433                         FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Invalid attribute 0",
2434                                    inet_ntop(packet->src_ipaddr.af,
2435                                              &packet->src_ipaddr.ipaddr,
2436                                              host_ipaddr, sizeof(host_ipaddr)));
2437                         failure = DECODE_FAIL_INVALID_ATTRIBUTE;
2438                         goto finish;
2439                 }
2440
2441                 /*
2442                  *      Attributes are at LEAST as long as the ID & length
2443                  *      fields.  Anything shorter is an invalid attribute.
2444                  */
2445                 if (attr[1] < 2) {
2446                         FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u too short",
2447                                    inet_ntop(packet->src_ipaddr.af,
2448                                              &packet->src_ipaddr.ipaddr,
2449                                              host_ipaddr, sizeof(host_ipaddr)),
2450                                    attr[0]);
2451                         failure = DECODE_FAIL_ATTRIBUTE_TOO_SHORT;
2452                         goto finish;
2453                 }
2454
2455                 /*
2456                  *      If there are fewer bytes in the packet than in the
2457                  *      attribute, it's a bad packet.
2458                  */
2459                 if (count < attr[1]) {
2460                         FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
2461                                    inet_ntop(packet->src_ipaddr.af,
2462                                              &packet->src_ipaddr.ipaddr,
2463                                              host_ipaddr, sizeof(host_ipaddr)),
2464                                            attr[0]);
2465                         failure = DECODE_FAIL_ATTRIBUTE_OVERFLOW;
2466                         goto finish;
2467                 }
2468
2469                 /*
2470                  *      Sanity check the attributes for length.
2471                  */
2472                 switch (attr[0]) {
2473                 default:        /* don't do anything by default */
2474                         break;
2475
2476                         /*
2477                          *      If there's an EAP-Message, we require
2478                          *      a Message-Authenticator.
2479                          */
2480                 case PW_EAP_MESSAGE:
2481                         require_ma = true;
2482                         break;
2483
2484                 case PW_MESSAGE_AUTHENTICATOR:
2485                         if (attr[1] != 2 + AUTH_VECTOR_LEN) {
2486                                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
2487                                            inet_ntop(packet->src_ipaddr.af,
2488                                                      &packet->src_ipaddr.ipaddr,
2489                                                      host_ipaddr, sizeof(host_ipaddr)),
2490                                            attr[1] - 2);
2491                                 failure = DECODE_FAIL_MA_INVALID_LENGTH;
2492                                 goto finish;
2493                         }
2494                         seen_ma = true;
2495                         break;
2496                 }
2497
2498                 /*
2499                  *      FIXME: Look up the base 255 attributes in the
2500                  *      dictionary, and switch over their type.  For
2501                  *      integer/date/ip, the attribute length SHOULD
2502                  *      be 6.
2503                  */
2504                 count -= attr[1];       /* grab the attribute length */
2505                 attr += attr[1];
2506                 num_attributes++;       /* seen one more attribute */
2507         }
2508
2509         /*
2510          *      If the attributes add up to a packet, it's allowed.
2511          *
2512          *      If not, we complain, and throw the packet away.
2513          */
2514         if (count != 0) {
2515                 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
2516                            inet_ntop(packet->src_ipaddr.af,
2517                                      &packet->src_ipaddr.ipaddr,
2518                                      host_ipaddr, sizeof(host_ipaddr)));
2519                 failure = DECODE_FAIL_ATTRIBUTE_UNDERFLOW;
2520                 goto finish;
2521         }
2522
2523         /*
2524          *      If we're configured to look for a maximum number of
2525          *      attributes, and we've seen more than that maximum,
2526          *      then throw the packet away, as a possible DoS.
2527          */
2528         if ((fr_max_attributes > 0) &&
2529             (num_attributes > fr_max_attributes)) {
2530                 FR_DEBUG_STRERROR_PRINTF("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2531                            inet_ntop(packet->src_ipaddr.af,
2532                                      &packet->src_ipaddr.ipaddr,
2533                                      host_ipaddr, sizeof(host_ipaddr)),
2534                            num_attributes, fr_max_attributes);
2535                 failure = DECODE_FAIL_TOO_MANY_ATTRIBUTES;
2536                 goto finish;
2537         }
2538
2539         /*
2540          *      http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
2541          *
2542          *      A packet with an EAP-Message attribute MUST also have
2543          *      a Message-Authenticator attribute.
2544          *
2545          *      A Message-Authenticator all by itself is OK, though.
2546          *
2547          *      Similarly, Status-Server packets MUST contain
2548          *      Message-Authenticator attributes.
2549          */
2550         if (require_ma && !seen_ma) {
2551                 FR_DEBUG_STRERROR_PRINTF("Insecure packet from host %s:  Packet does not contain required Message-Authenticator attribute",
2552                            inet_ntop(packet->src_ipaddr.af,
2553                                      &packet->src_ipaddr.ipaddr,
2554                                      host_ipaddr, sizeof(host_ipaddr)));
2555                 failure = DECODE_FAIL_MA_MISSING;
2556                 goto finish;
2557         }
2558
2559         /*
2560          *      Fill RADIUS header fields
2561          */
2562         packet->code = hdr->code;
2563         packet->id = hdr->id;
2564         memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
2565
2566
2567         finish:
2568
2569         if (reason) {
2570                 *reason = failure;
2571         }
2572         return (failure == DECODE_FAIL_NONE);
2573 }
2574
2575
2576 /** Receive UDP client requests, and fill in the basics of a RADIUS_PACKET structure
2577  *
2578  */
2579 RADIUS_PACKET *rad_recv(TALLOC_CTX *ctx, int fd, int flags)
2580 {
2581         int sock_flags = 0;
2582         ssize_t data_len;
2583         RADIUS_PACKET           *packet;
2584
2585         /*
2586          *      Allocate the new request data structure
2587          */
2588         packet = rad_alloc(ctx, false);
2589         if (!packet) {
2590                 fr_strerror_printf("out of memory");
2591                 return NULL;
2592         }
2593
2594         if (flags & 0x02) {
2595                 sock_flags = MSG_PEEK;
2596                 flags &= ~0x02;
2597         }
2598
2599         data_len = rad_recvfrom(fd, packet, sock_flags,
2600                                 &packet->src_ipaddr, &packet->src_port,
2601                                 &packet->dst_ipaddr, &packet->dst_port);
2602
2603         /*
2604          *      Check for socket errors.
2605          */
2606         if (data_len < 0) {
2607                 FR_DEBUG_STRERROR_PRINTF("Error receiving packet: %s", fr_syserror(errno));
2608                 /* packet->data is NULL */
2609                 rad_free(&packet);
2610                 return NULL;
2611         }
2612         packet->data_len = data_len; /* unsigned vs signed */
2613
2614         /*
2615          *      If the packet is too big, then rad_recvfrom did NOT
2616          *      allocate memory.  Instead, it just discarded the
2617          *      packet.
2618          */
2619         if (packet->data_len > MAX_PACKET_LEN) {
2620                 FR_DEBUG_STRERROR_PRINTF("Discarding packet: Larger than RFC limitation of 4096 bytes");
2621                 /* packet->data is NULL */
2622                 rad_free(&packet);
2623                 return NULL;
2624         }
2625
2626         /*
2627          *      Read no data.  Continue.
2628          *      This check is AFTER the MAX_PACKET_LEN check above, because
2629          *      if the packet is larger than MAX_PACKET_LEN, we also have
2630          *      packet->data == NULL
2631          */
2632         if ((packet->data_len == 0) || !packet->data) {
2633                 FR_DEBUG_STRERROR_PRINTF("Empty packet: Socket is not ready");
2634                 rad_free(&packet);
2635                 return NULL;
2636         }
2637
2638         /*
2639          *      See if it's a well-formed RADIUS packet.
2640          */
2641         if (!rad_packet_ok(packet, flags, NULL)) {
2642                 rad_free(&packet);
2643                 return NULL;
2644         }
2645
2646         /*
2647          *      Remember which socket we read the packet from.
2648          */
2649         packet->sockfd = fd;
2650
2651         /*
2652          *      FIXME: Do even more filtering by only permitting
2653          *      certain IP's.  The problem is that we don't know
2654          *      how to do this properly for all possible clients...
2655          */
2656
2657         /*
2658          *      Explicitely set the VP list to empty.
2659          */
2660         packet->vps = NULL;
2661
2662 #ifndef NDEBUG
2663         if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2664 #endif
2665
2666         return packet;
2667 }
2668
2669
2670 /** Verify the Request/Response Authenticator (and Message-Authenticator if present) of a packet
2671  *
2672  */
2673 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original, char const *secret)
2674 {
2675         uint8_t         *ptr;
2676         int             length;
2677         int             attrlen;
2678         int             rcode;
2679         char            buffer[32];
2680
2681         if (!packet || !packet->data) return -1;
2682
2683         /*
2684          *      Before we allocate memory for the attributes, do more
2685          *      sanity checking.
2686          */
2687         ptr = packet->data + RADIUS_HDR_LEN;
2688         length = packet->data_len - RADIUS_HDR_LEN;
2689         while (length > 0) {
2690                 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2691                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2692
2693                 attrlen = ptr[1];
2694
2695                 switch (ptr[0]) {
2696                 default:        /* don't do anything. */
2697                         break;
2698
2699                         /*
2700                          *      Note that more than one Message-Authenticator
2701                          *      attribute is invalid.
2702                          */
2703                 case PW_MESSAGE_AUTHENTICATOR:
2704                         memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2705                         memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2706
2707                         switch (packet->code) {
2708                         default:
2709                                 break;
2710
2711                         case PW_CODE_ACCOUNTING_RESPONSE:
2712                                 if (original &&
2713                                     (original->code == PW_CODE_STATUS_SERVER)) {
2714                                         goto do_ack;
2715                                 }
2716
2717                         case PW_CODE_ACCOUNTING_REQUEST:
2718                         case PW_CODE_DISCONNECT_REQUEST:
2719                         case PW_CODE_COA_REQUEST:
2720                                 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2721                                 break;
2722
2723                         do_ack:
2724                         case PW_CODE_ACCESS_ACCEPT:
2725                         case PW_CODE_ACCESS_REJECT:
2726                         case PW_CODE_ACCESS_CHALLENGE:
2727                         case PW_CODE_DISCONNECT_ACK:
2728                         case PW_CODE_DISCONNECT_NAK:
2729                         case PW_CODE_COA_ACK:
2730                         case PW_CODE_COA_NAK:
2731                                 if (!original) {
2732                                         fr_strerror_printf("Cannot validate Message-Authenticator in response "
2733                                                            "packet without a request packet");
2734                                         return -1;
2735                                 }
2736                                 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2737                                 break;
2738                         }
2739
2740                         fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
2741                                     (uint8_t const *) secret, strlen(secret));
2742                         if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2743                                    sizeof(calc_auth_vector)) != 0) {
2744                                 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator!  "
2745                                                    "(Shared secret is incorrect.)",
2746                                                    inet_ntop(packet->src_ipaddr.af,
2747                                                              &packet->src_ipaddr.ipaddr,
2748                                                              buffer, sizeof(buffer)));
2749                                 /* Silently drop packet, according to RFC 3579 */
2750                                 return -1;
2751                         } /* else the message authenticator was good */
2752
2753                         /*
2754                          *      Reinitialize Authenticators.
2755                          */
2756                         memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2757                         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2758                         break;
2759                 } /* switch over the attributes */
2760
2761                 ptr += attrlen;
2762                 length -= attrlen;
2763         } /* loop over the packet, sanity checking the attributes */
2764
2765         /*
2766          *      It looks like a RADIUS packet, but we don't know what it is
2767          *      so can't validate the authenticators.
2768          */
2769         if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2770                 fr_strerror_printf("Received Unknown packet code %d "
2771                                    "from client %s port %d: Cannot validate Request/Response Authenticator.",
2772                                    packet->code,
2773                                    inet_ntop(packet->src_ipaddr.af,
2774                                              &packet->src_ipaddr.ipaddr,
2775                                              buffer, sizeof(buffer)),
2776                                    packet->src_port);
2777                 return -1;
2778         }
2779
2780         /*
2781          *      Calculate and/or verify Request or Response Authenticator.
2782          */
2783         switch (packet->code) {
2784         case PW_CODE_ACCESS_REQUEST:
2785         case PW_CODE_STATUS_SERVER:
2786                 /*
2787                  *      The authentication vector is random
2788                  *      nonsense, invented by the client.
2789                  */
2790                 break;
2791
2792         case PW_CODE_COA_REQUEST:
2793         case PW_CODE_DISCONNECT_REQUEST:
2794         case PW_CODE_ACCOUNTING_REQUEST:
2795                 if (calc_acctdigest(packet, secret) > 1) {
2796                         fr_strerror_printf("Received %s packet "
2797                                            "from client %s with invalid Request Authenticator!  "
2798                                            "(Shared secret is incorrect.)",
2799                                            fr_packet_codes[packet->code],
2800                                            inet_ntop(packet->src_ipaddr.af,
2801                                                      &packet->src_ipaddr.ipaddr,
2802                                                      buffer, sizeof(buffer)));
2803                         return -1;
2804                 }
2805                 break;
2806
2807                 /* Verify the reply digest */
2808         case PW_CODE_ACCESS_ACCEPT:
2809         case PW_CODE_ACCESS_REJECT:
2810         case PW_CODE_ACCESS_CHALLENGE:
2811         case PW_CODE_ACCOUNTING_RESPONSE:
2812         case PW_CODE_DISCONNECT_ACK:
2813         case PW_CODE_DISCONNECT_NAK:
2814         case PW_CODE_COA_ACK:
2815         case PW_CODE_COA_NAK:
2816                 rcode = calc_replydigest(packet, original, secret);
2817                 if (rcode > 1) {
2818                         fr_strerror_printf("Received %s packet "
2819                                            "from home server %s port %d with invalid Response Authenticator!  "
2820                                            "(Shared secret is incorrect.)",
2821                                            fr_packet_codes[packet->code],
2822                                            inet_ntop(packet->src_ipaddr.af,
2823                                                      &packet->src_ipaddr.ipaddr,
2824                                                      buffer, sizeof(buffer)),
2825                                            packet->src_port);
2826                         return -1;
2827                 }
2828                 break;
2829
2830         default:
2831                 fr_strerror_printf("Received Unknown packet code %d "
2832                                    "from client %s port %d: Cannot validate Request/Response Authenticator",
2833                                    packet->code,
2834                                    inet_ntop(packet->src_ipaddr.af,
2835                                              &packet->src_ipaddr.ipaddr,
2836                                              buffer, sizeof(buffer)),
2837                                    packet->src_port);
2838                 return -1;
2839         }
2840
2841         return 0;
2842 }
2843
2844
2845 /** Convert a "concatenated" attribute to one long VP
2846  *
2847  */
2848 static ssize_t data2vp_concat(TALLOC_CTX *ctx,
2849                               DICT_ATTR const *da, uint8_t const *start,
2850                               size_t const packetlen, VALUE_PAIR **pvp)
2851 {
2852         size_t total;
2853         uint8_t attr;
2854         uint8_t const *ptr = start;
2855         uint8_t const *end = start + packetlen;
2856         uint8_t *p;
2857         VALUE_PAIR *vp;
2858
2859         total = 0;
2860         attr = ptr[0];
2861
2862         /*
2863          *      The packet has already been sanity checked, so we
2864          *      don't care about walking off of the end of it.
2865          */
2866         while (ptr < end) {
2867                 total += ptr[1] - 2;
2868
2869                 ptr += ptr[1];
2870
2871                 /*
2872                  *      Attributes MUST be consecutive.
2873                  */
2874                 if (ptr[0] != attr) break;
2875         }
2876
2877         vp = pairalloc(ctx, da);
2878         if (!vp) return -1;
2879
2880         vp->vp_length = total;
2881         vp->vp_octets = p = talloc_array(vp, uint8_t, vp->vp_length);
2882         if (!p) {
2883                 pairfree(&vp);
2884                 return -1;
2885         }
2886
2887         total = 0;
2888         ptr = start;
2889         while (total < vp->vp_length) {
2890                 memcpy(p, ptr + 2, ptr[1] - 2);
2891                 p += ptr[1] - 2;
2892                 total += ptr[1] - 2;
2893                 ptr += ptr[1];
2894         }
2895
2896         *pvp = vp;
2897         return ptr - start;
2898 }
2899
2900
2901 /** Convert TLVs to one or more VPs
2902  *
2903  */
2904 ssize_t rad_data2vp_tlvs(TALLOC_CTX *ctx,
2905                             RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2906                             char const *secret, DICT_ATTR const *da,
2907                             uint8_t const *start, size_t length,
2908                             VALUE_PAIR **pvp)
2909 {
2910         uint8_t const *data = start;
2911         DICT_ATTR const *child;
2912         VALUE_PAIR *head, **tail;
2913
2914         if (length < 3) return -1; /* type, length, value */
2915
2916         VP_HEXDUMP("tlvs", data, length);
2917
2918         if (rad_tlv_ok(data, length, 1, 1) < 0) return -1;
2919
2920         head = NULL;
2921         tail = &head;
2922
2923         while (data < (start + length)) {
2924                 ssize_t tlv_len;
2925
2926                 child = dict_attrbyparent(da, data[0], da->vendor);
2927                 if (!child) {
2928                         unsigned int my_attr, my_vendor;
2929
2930                         VP_TRACE("Failed to find child %u of TLV %s\n",
2931                                  data[0], da->name);
2932
2933                         /*
2934                          *      Get child attr/vendor so that
2935                          *      we can call unknown attr.
2936                          */
2937                         my_attr = data[0];
2938                         my_vendor = da->vendor;
2939
2940                         if (!dict_attr_child(da, &my_attr, &my_vendor)) {
2941                                 pairfree(&head);
2942                                 return -1;
2943                         }
2944
2945                         child = dict_unknown_afrom_fields(ctx, my_attr, my_vendor);
2946                         if (!child) {
2947                                 pairfree(&head);
2948                                 return -1;
2949                         }
2950                 }
2951
2952                 tlv_len = data2vp(ctx, packet, original, secret, child,
2953                                   data + 2, data[1] - 2, data[1] - 2, tail);
2954                 if (tlv_len < 0) {
2955                         pairfree(&head);
2956                         return -1;
2957                 }
2958                 if (*tail) tail = &((*tail)->next);
2959                 data += data[1];
2960         }
2961
2962         *pvp = head;
2963         return length;
2964 }
2965
2966 /** Convert a top-level VSA to a VP.
2967  *
2968  * "length" can be LONGER than just this sub-vsa.
2969  */
2970 static ssize_t data2vp_vsa(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
2971                            RADIUS_PACKET const *original,
2972                            char const *secret, DICT_VENDOR *dv,
2973                            uint8_t const *data, size_t length,
2974                            VALUE_PAIR **pvp)
2975 {
2976         unsigned int attribute;
2977         ssize_t attrlen, my_len;
2978         DICT_ATTR const *da;
2979
2980         VP_TRACE("data2vp_vsa: length %u\n", (unsigned int) length);
2981
2982 #ifndef NDEBUG
2983         if (length <= (dv->type + dv->length)) {
2984                 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
2985                 return -1;
2986         }
2987 #endif
2988
2989         switch (dv->type) {
2990         case 4:
2991                 /* data[0] must be zero */
2992                 attribute = data[1] << 16;
2993                 attribute |= data[2] << 8;
2994                 attribute |= data[3];
2995                 break;
2996
2997         case 2:
2998                 attribute = data[0] << 8;
2999                 attribute |= data[1];
3000                 break;
3001
3002         case 1:
3003                 attribute = data[0];
3004                 break;
3005
3006         default:
3007                 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3008                 return -1;
3009         }
3010
3011         switch (dv->length) {
3012         case 2:
3013                 /* data[dv->type] must be zero, from rad_tlv_ok() */
3014                 attrlen = data[dv->type + 1];
3015                 break;
3016
3017         case 1:
3018                 attrlen = data[dv->type];
3019                 break;
3020
3021         case 0:
3022                 attrlen = length;
3023                 break;
3024
3025         default:
3026                 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3027                 return -1;
3028         }
3029
3030         /*
3031          *      See if the VSA is known.
3032          */
3033         da = dict_attrbyvalue(attribute, dv->vendorpec);
3034         if (!da) da = dict_unknown_afrom_fields(ctx, attribute, dv->vendorpec);
3035         if (!da) return -1;
3036
3037         my_len = data2vp(ctx, packet, original, secret, da,
3038                          data + dv->type + dv->length,
3039                          attrlen - (dv->type + dv->length),
3040                          attrlen - (dv->type + dv->length),
3041                          pvp);
3042         if (my_len < 0) return my_len;
3043
3044         return attrlen;
3045 }
3046
3047
3048 /** Convert a fragmented extended attr to a VP
3049  *
3050  * Format is:
3051  *
3052  * attr
3053  * length
3054  * extended-attr
3055  * flag
3056  * data...
3057  *
3058  * But for the first fragment, we get passed a pointer to the "extended-attr"
3059  */
3060 static ssize_t data2vp_extended(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3061                                 RADIUS_PACKET const *original,
3062                                 char const *secret, DICT_ATTR const *da,
3063                                 uint8_t const *data,
3064                                 size_t attrlen, size_t packetlen,
3065                                 VALUE_PAIR **pvp)
3066 {
3067         ssize_t rcode;
3068         size_t fraglen;
3069         uint8_t *head, *tail;
3070         uint8_t const *frag, *end;
3071         uint8_t const *attr;
3072         int fragments;
3073         bool last_frag;
3074
3075         if (attrlen < 3) return -1;
3076
3077         /*
3078          *      Calculate the length of all of the fragments.  For
3079          *      now, they MUST be contiguous in the packet, and they
3080          *      MUST be all of the same TYPE and EXTENDED-TYPE
3081          */
3082         attr = data - 2;
3083         fraglen = attrlen - 2;
3084         frag = data + attrlen;
3085         end = data + packetlen;
3086         fragments = 1;
3087         last_frag = false;
3088
3089         while (frag < end) {
3090                 if (last_frag ||
3091                     (frag[0] != attr[0]) ||
3092                     (frag[1] < 4) ||                   /* too short for long-extended */
3093                     (frag[2] != attr[2]) ||
3094                     ((frag + frag[1]) > end)) {         /* overflow */
3095                         end = frag;
3096                         break;
3097                 }
3098
3099                 last_frag = ((frag[3] & 0x80) == 0);
3100
3101                 fraglen += frag[1] - 4;
3102                 frag += frag[1];
3103                 fragments++;
3104         }
3105
3106         head = tail = malloc(fraglen);
3107         if (!head) return -1;
3108
3109         VP_TRACE("Fragments %d, total length %d\n", fragments, (int) fraglen);
3110
3111         /*
3112          *      And again, but faster and looser.
3113          *
3114          *      We copy the first fragment, followed by the rest of
3115          *      the fragments.
3116          */
3117         frag = attr;
3118
3119         while (fragments >  0) {
3120                 memcpy(tail, frag + 4, frag[1] - 4);
3121                 tail += frag[1] - 4;
3122                 frag += frag[1];
3123                 fragments--;
3124         }
3125
3126         VP_HEXDUMP("long-extended fragments", head, fraglen);
3127
3128         rcode = data2vp(ctx, packet, original, secret, da,
3129                         head, fraglen, fraglen, pvp);
3130         free(head);
3131         if (rcode < 0) return rcode;
3132
3133         return end - data;
3134 }
3135
3136 /** Convert a Vendor-Specific WIMAX to vps
3137  *
3138  * @note Called ONLY for Vendor-Specific
3139  */
3140 static ssize_t data2vp_wimax(TALLOC_CTX *ctx,
3141                              RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3142                              char const *secret, uint32_t vendor,
3143                              uint8_t const *data,
3144                              size_t attrlen, size_t packetlen,
3145                              VALUE_PAIR **pvp)
3146 {
3147         ssize_t rcode;
3148         size_t fraglen;
3149         bool last_frag;
3150         uint8_t *head, *tail;
3151         uint8_t const *frag, *end;
3152         DICT_ATTR const *child;
3153
3154         if (attrlen < 8) return -1;
3155
3156         if (((size_t) (data[5] + 4)) != attrlen) return -1;
3157
3158         child = dict_attrbyvalue(data[4], vendor);
3159         if (!child) return -1;
3160
3161         if ((data[6] & 0x80) == 0) {
3162                 rcode = data2vp(ctx, packet, original, secret, child,
3163                                 data + 7, data[5] - 3, data[5] - 3,
3164                                 pvp);
3165                 if (rcode < 0) return -1;
3166                 return 7 + rcode;
3167         }
3168
3169         /*
3170          *      Calculate the length of all of the fragments.  For
3171          *      now, they MUST be contiguous in the packet, and they
3172          *      MUST be all of the same VSA, WiMAX, and WiMAX-attr.
3173          *
3174          *      The first fragment doesn't have a RADIUS attribute
3175          *      header, so it needs to be treated a little special.
3176          */
3177         fraglen = data[5] - 3;
3178         frag = data + attrlen;
3179         end = data + packetlen;
3180         last_frag = false;
3181
3182         while (frag < end) {
3183                 if (last_frag ||
3184                     (frag[0] != PW_VENDOR_SPECIFIC) ||
3185                     (frag[1] < 9) ||                   /* too short for wimax */
3186                     ((frag + frag[1]) > end) ||         /* overflow */
3187                     (memcmp(frag + 2, data, 4) != 0) || /* not wimax */
3188                     (frag[6] != data[4]) || /* not the same wimax attr */
3189                     ((frag[7] + 6) != frag[1])) { /* doesn't fill the attr */
3190                         end = frag;
3191                         break;
3192                 }
3193
3194                 last_frag = ((frag[8] & 0x80) == 0);
3195
3196                 fraglen += frag[7] - 3;
3197                 frag += frag[1];
3198         }
3199
3200         head = tail = malloc(fraglen);
3201         if (!head) return -1;
3202
3203         /*
3204          *      And again, but faster and looser.
3205          *
3206          *      We copy the first fragment, followed by the rest of
3207          *      the fragments.
3208          */
3209         frag = data;
3210
3211         memcpy(tail, frag + 4 + 3, frag[4 + 1] - 3);
3212         tail += frag[4 + 1] - 3;
3213         frag += attrlen;        /* should be frag[1] - 7 */
3214
3215         /*
3216          *      frag now points to RADIUS attributes
3217          */
3218         do {
3219                 memcpy(tail, frag + 2 + 4 + 3, frag[2 + 4 + 1] - 3);
3220                 tail += frag[2 + 4 + 1] - 3;
3221                 frag += frag[1];
3222         } while (frag < end);
3223
3224         VP_HEXDUMP("wimax fragments", head, fraglen);
3225
3226         rcode = data2vp(ctx, packet, original, secret, child,
3227                         head, fraglen, fraglen, pvp);
3228         free(head);
3229         if (rcode < 0) return rcode;
3230
3231         return end - data;
3232 }
3233
3234
3235 /** Convert a top-level VSA to one or more VPs
3236  *
3237  */
3238 static ssize_t data2vp_vsas(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3239                             RADIUS_PACKET const *original,
3240                             char const *secret, uint8_t const *data,
3241                             size_t attrlen, size_t packetlen,
3242                             VALUE_PAIR **pvp)
3243 {
3244         size_t total;
3245         ssize_t rcode;
3246         uint32_t vendor;
3247         DICT_VENDOR *dv;
3248         VALUE_PAIR *head, **tail;
3249         DICT_VENDOR my_dv;
3250
3251         if (attrlen > packetlen) return -1;
3252         if (attrlen < 5) return -1; /* vid, value */
3253         if (data[0] != 0) return -1; /* we require 24-bit VIDs */
3254
3255         VP_TRACE("data2vp_vsas\n");
3256
3257         memcpy(&vendor, data, 4);
3258         vendor = ntohl(vendor);
3259         dv = dict_vendorbyvalue(vendor);
3260         if (!dv) {
3261                 /*
3262                  *      RFC format is 1 octet type, 1 octet length
3263                  */
3264                 if (rad_tlv_ok(data + 4, attrlen - 4, 1, 1) < 0) {
3265                         VP_TRACE("data2vp_vsas: unknown tlvs not OK: %s\n", fr_strerror());
3266                         return -1;
3267                 }
3268
3269                 /*
3270                  *      It's a known unknown.
3271                  */
3272                 memset(&my_dv, 0, sizeof(my_dv));
3273                 dv = &my_dv;
3274
3275                 /*
3276                  *      Fill in the fields.  Note that the name is empty!
3277                  */
3278                 dv->vendorpec = vendor;
3279                 dv->type = 1;
3280                 dv->length = 1;
3281
3282                 goto create_attrs;
3283         }
3284
3285         /*
3286          *      WiMAX craziness
3287          */
3288         if ((vendor == VENDORPEC_WIMAX) && dv->flags) {
3289                 rcode = data2vp_wimax(ctx, packet, original, secret, vendor,
3290                                       data, attrlen, packetlen, pvp);
3291                 return rcode;
3292         }
3293
3294         /*
3295          *      VSAs should normally be in TLV format.
3296          */
3297         if (rad_tlv_ok(data + 4, attrlen - 4,
3298                        dv->type, dv->length) < 0) {
3299                 VP_TRACE("data2vp_vsas: tlvs not OK: %s\n", fr_strerror());
3300                 return -1;
3301         }
3302
3303         /*
3304          *      There may be more than one VSA in the
3305          *      Vendor-Specific.  If so, loop over them all.
3306          */
3307 create_attrs:
3308         data += 4;
3309         attrlen -= 4;
3310         packetlen -= 4;
3311         total = 4;
3312         head = NULL;
3313         tail = &head;
3314
3315         while (attrlen > 0) {
3316                 ssize_t vsa_len;
3317
3318                 vsa_len = data2vp_vsa(ctx, packet, original, secret, dv,
3319                                       data, attrlen, tail);
3320                 if (vsa_len < 0) {
3321                         pairfree(&head);
3322                         fr_strerror_printf("Internal sanity check %d", __LINE__);
3323                         return -1;
3324                 }
3325
3326                 /*
3327                  *      Vendors can send zero-length VSAs.
3328                  */
3329                 if (*tail) tail = &((*tail)->next);
3330
3331                 data += vsa_len;
3332                 attrlen -= vsa_len;
3333                 packetlen -= vsa_len;
3334                 total += vsa_len;
3335         }
3336
3337         *pvp = head;
3338         return total;
3339 }
3340
3341 /** Create any kind of VP from the attribute contents
3342  *
3343  * "length" is AT LEAST the length of this attribute, as we
3344  * expect the caller to have verified the data with
3345  * rad_packet_ok().  "length" may be up to the length of the
3346  * packet.
3347  *
3348  * @return -1 on error, or "length".
3349  */
3350 ssize_t data2vp(TALLOC_CTX *ctx,
3351                 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3352                 char const *secret,
3353                 DICT_ATTR const *da, uint8_t const *start,
3354                 size_t const attrlen, size_t const packetlen,
3355                 VALUE_PAIR **pvp)
3356 {
3357         int8_t tag = TAG_NONE;
3358         size_t datalen;
3359         ssize_t rcode;
3360         uint32_t vendor;
3361         DICT_ATTR const *child;
3362         VALUE_PAIR *vp;
3363         uint8_t const *data = start;
3364         char *p;
3365         uint8_t buffer[256];
3366
3367         /*
3368          *      FIXME: Attrlen can be larger than 253 for extended attrs!
3369          */
3370         if (!da || (attrlen > packetlen) ||
3371             ((attrlen > 253) && (attrlen != packetlen)) ||
3372             (attrlen > 128*1024)) {
3373                 fr_strerror_printf("data2vp: invalid arguments");
3374                 return -1;
3375         }
3376
3377         VP_HEXDUMP("data2vp", start, attrlen);
3378
3379         VP_TRACE("parent %s len %zu ... %zu\n", da->name, attrlen, packetlen);
3380
3381         datalen = attrlen;
3382
3383         /*
3384          *      Hacks for CUI.  The WiMAX spec says that it can be
3385          *      zero length, even though this is forbidden by the
3386          *      RADIUS specs.  So... we make a special case for it.
3387          */
3388         if (attrlen == 0) {
3389                 if (!((da->vendor == 0) &&
3390                       (da->attr == PW_CHARGEABLE_USER_IDENTITY))) {
3391                         *pvp = NULL;
3392                         return 0;
3393                 }
3394
3395 #ifndef NDEBUG
3396                 /*
3397                  *      Hacks for Coverity.  Editing the dictionary
3398                  *      will break assumptions about CUI.  We know
3399                  *      this, but Coverity doesn't.
3400                  */
3401                 if (da->type != PW_TYPE_OCTETS) return -1;
3402 #endif
3403
3404                 data = NULL;
3405                 datalen = 0;
3406                 goto alloc_cui; /* skip everything */
3407         }
3408
3409         /*
3410          *      Hacks for tags.  If the attribute is capable of
3411          *      encoding a tag, and there's room for the tag, and
3412          *      there is a tag, or it's encrypted with Tunnel-Password,
3413          *      then decode the tag.
3414          */
3415         if (da->flags.has_tag && (datalen > 1) &&
3416             ((data[0] < 0x20) ||
3417              (da->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
3418                 /*
3419                  *      Only "short" attributes can be encrypted.
3420                  */
3421                 if (datalen >= sizeof(buffer)) return -1;
3422
3423                 if (da->type == PW_TYPE_STRING) {
3424                         memcpy(buffer, data + 1, datalen - 1);
3425                         tag = data[0];
3426                         datalen -= 1;
3427
3428                 } else if (da->type == PW_TYPE_INTEGER) {
3429                         memcpy(buffer, data, attrlen);
3430                         tag = buffer[0];
3431                         buffer[0] = 0;
3432
3433                 } else {
3434                         return -1; /* only string and integer can have tags */
3435                 }
3436
3437                 data = buffer;
3438         }
3439
3440         /*
3441          *      Decrypt the attribute.
3442          */
3443         if (secret && packet && (da->flags.encrypt != FLAG_ENCRYPT_NONE)) {
3444                 VP_TRACE("data2vp: decrypting type %u\n", da->flags.encrypt);
3445                 /*
3446                  *      Encrypted attributes can only exist for the
3447                  *      old-style format.  Extended attributes CANNOT
3448                  *      be encrypted.
3449                  */
3450                 if (attrlen > 253) {
3451                         return -1;
3452                 }
3453
3454                 if (data == start) {
3455                         memcpy(buffer, data, attrlen);
3456                 }
3457                 data = buffer;
3458
3459                 switch (da->flags.encrypt) { /* can't be tagged */
3460                 /*
3461                  *  User-Password
3462                  */
3463                 case FLAG_ENCRYPT_USER_PASSWORD:
3464                         if (original) {
3465                                 rad_pwdecode((char *) buffer,
3466                                              attrlen, secret,
3467                                              original->vector);
3468                         } else {
3469                                 rad_pwdecode((char *) buffer,
3470                                              attrlen, secret,
3471                                              packet->vector);
3472                         }
3473                         buffer[253] = '\0';
3474
3475                         /*
3476                          *      Take off trailing zeros from the END.
3477                          *      This allows passwords to have zeros in
3478                          *      the middle of a field.
3479                          *
3480                          *      However, if the password has a zero at
3481                          *      the end, it will get mashed by this
3482                          *      code.  There's really no way around
3483                          *      that.
3484                          */
3485                         while ((datalen > 0) && (buffer[datalen - 1] == '\0')) datalen--;
3486                         break;
3487
3488                 /*
3489                  *      Tunnel-Password's may go ONLY in response
3490                  *      packets.  They can have a tag, so datalen is
3491                  *      not the same as attrlen.
3492                  */
3493                 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
3494                         if (rad_tunnel_pwdecode(buffer, &datalen, secret,
3495                                                 original ? original->vector : nullvector) < 0) {
3496                                 goto raw;
3497                         }
3498                         break;
3499
3500                 /*
3501                  *  Ascend-Send-Secret
3502                  *  Ascend-Receive-Secret
3503                  */
3504                 case FLAG_ENCRYPT_ASCEND_SECRET:
3505                         if (!original) {
3506                                 goto raw;
3507                         } else {
3508                                 uint8_t my_digest[AUTH_VECTOR_LEN];
3509                                 make_secret(my_digest,
3510                                             original->vector,
3511                                             secret, data);
3512                                 memcpy(buffer, my_digest,
3513                                        AUTH_VECTOR_LEN );
3514                                 buffer[AUTH_VECTOR_LEN] = '\0';
3515                                 datalen = strlen((char *) buffer);
3516                         }
3517                         break;
3518
3519                 default:
3520                         break;
3521                 } /* switch over encryption flags */
3522         }
3523
3524         /*
3525          *      Double-check the length after decrypting the
3526          *      attribute.
3527          */
3528         VP_TRACE("data2vp: type %u\n", da->type);
3529         switch (da->type) {
3530         case PW_TYPE_STRING:
3531         case PW_TYPE_OCTETS:
3532                 break;
3533
3534         case PW_TYPE_ABINARY:
3535                 if (datalen > sizeof(vp->vp_filter)) goto raw;
3536                 break;
3537
3538         case PW_TYPE_INTEGER:
3539         case PW_TYPE_IPV4_ADDR:
3540         case PW_TYPE_DATE:
3541         case PW_TYPE_SIGNED:
3542                 if (datalen != 4) goto raw;
3543                 break;
3544
3545         case PW_TYPE_INTEGER64:
3546         case PW_TYPE_IFID:
3547                 if (datalen != 8) goto raw;
3548                 break;
3549
3550         case PW_TYPE_IPV6_ADDR:
3551                 if (datalen != 16) goto raw;
3552                 break;
3553
3554         case PW_TYPE_IPV6_PREFIX:
3555                 if ((datalen < 2) || (datalen > 18)) goto raw;
3556                 if (data[1] > 128) goto raw;
3557                 break;
3558
3559         case PW_TYPE_BYTE:
3560                 if (datalen != 1) goto raw;
3561                 break;
3562
3563         case PW_TYPE_SHORT:
3564                 if (datalen != 2) goto raw;
3565                 break;
3566
3567         case PW_TYPE_ETHERNET:
3568                 if (datalen != 6) goto raw;
3569                 break;
3570
3571         case PW_TYPE_COMBO_IP_ADDR:
3572                 if (datalen == 4) {
3573                         child = dict_attrbytype(da->attr, da->vendor,
3574                                                 PW_TYPE_IPV4_ADDR);
3575                 } else if (datalen == 16) {
3576                         child = dict_attrbytype(da->attr, da->vendor,
3577                                              PW_TYPE_IPV6_ADDR);
3578                 } else {
3579                         goto raw;
3580                 }
3581                 if (!child) goto raw;
3582                 da = child;     /* re-write it */
3583                 break;
3584
3585         case PW_TYPE_IPV4_PREFIX:
3586                 if (datalen != 6) goto raw;
3587                 if ((data[1] & 0x3f) > 32) goto raw;
3588                 break;
3589
3590                 /*
3591                  *      The rest of the data types can cause
3592                  *      recursion!  Ask yourself, "is recursion OK?"
3593                  */
3594
3595         case PW_TYPE_EXTENDED:
3596                 if (datalen < 2) goto raw; /* etype, value */
3597
3598                 child = dict_attrbyparent(da, data[0], 0);
3599                 if (!child) goto raw;
3600
3601                 /*
3602                  *      Recurse to decode the contents, which could be
3603                  *      a TLV, IPaddr, etc.  Note that we decode only
3604                  *      the current attribute, and we ignore any extra
3605                  *      data after it.
3606                  */
3607                 rcode = data2vp(ctx, packet, original, secret, child,
3608                                 data + 1, attrlen - 1, attrlen - 1, pvp);
3609                 if (rcode < 0) goto raw;
3610                 return 1 + rcode;
3611
3612         case PW_TYPE_LONG_EXTENDED:
3613                 if (datalen < 3) goto raw; /* etype, flags, value */
3614
3615                 child = dict_attrbyparent(da, data[0], 0);
3616                 if (!child) {
3617                         if ((data[0] != PW_VENDOR_SPECIFIC) ||
3618                             (datalen < (3 + 4 + 1))) {
3619                                 /* da->attr < 255, da->vendor == 0 */
3620                                 child = dict_unknown_afrom_fields(ctx, data[0], da->attr * FR_MAX_VENDOR);
3621                         } else {
3622                                 /*
3623                                  *      Try to find the VSA.
3624                                  */
3625                                 memcpy(&vendor, data + 3, 4);
3626                                 vendor = ntohl(vendor);
3627
3628                                 if (vendor == 0) goto raw;
3629
3630                                 child = dict_unknown_afrom_fields(ctx, data[7], vendor | (da->attr * FR_MAX_VENDOR));
3631                         }
3632
3633                         if (!child) {
3634                                 fr_strerror_printf("Internal sanity check %d", __LINE__);
3635                                 return -1;
3636                         }
3637                 }
3638
3639                 /*
3640                  *      If there no more fragments, then the contents
3641                  *      have to be a well-known data type.
3642                  *
3643                  */
3644                 if ((data[1] & 0x80) == 0) {
3645                         rcode = data2vp(ctx, packet, original, secret, child,
3646                                         data + 2, attrlen - 2, attrlen - 2,
3647                                         pvp);
3648                         if (rcode < 0) goto raw;
3649                         return 2 + rcode;
3650                 }
3651
3652                 /*
3653                  *      This requires a whole lot more work.
3654                  */
3655                 return data2vp_extended(ctx, packet, original, secret, child,
3656                                         start, attrlen, packetlen, pvp);
3657
3658         case PW_TYPE_EVS:
3659                 if (datalen < 6) goto raw; /* vid, vtype, value */
3660
3661                 if (data[0] != 0) goto raw; /* we require 24-bit VIDs */
3662
3663                 memcpy(&vendor, data, 4);
3664                 vendor = ntohl(vendor);
3665                 vendor |= da->vendor;
3666
3667                 child = dict_attrbyvalue(data[4], vendor);
3668                 if (!child) {
3669                         /*
3670                          *      Create a "raw" attribute from the
3671                          *      contents of the EVS VSA.
3672                          */
3673                         da = dict_unknown_afrom_fields(ctx, data[4], vendor);
3674                         data += 5;
3675                         datalen -= 5;
3676                         break;
3677                 }
3678
3679                 rcode = data2vp(ctx, packet, original, secret, child,
3680                                 data + 5, attrlen - 5, attrlen - 5, pvp);
3681                 if (rcode < 0) goto raw;
3682                 return 5 + rcode;
3683
3684         case PW_TYPE_TLV:
3685                 /*
3686                  *      We presume that the TLVs all fit into one
3687                  *      attribute, OR they've already been grouped
3688                  *      into a contiguous memory buffer.
3689                  */
3690                 rcode = rad_data2vp_tlvs(ctx, packet, original, secret, da,
3691                                          data, attrlen, pvp);
3692                 if (rcode < 0) goto raw;
3693                 return rcode;
3694
3695         case PW_TYPE_VSA:
3696                 /*
3697                  *      VSAs can be WiMAX, in which case they don't
3698                  *      fit into one attribute.
3699                  */
3700                 rcode = data2vp_vsas(ctx, packet, original, secret,
3701                                      data, attrlen, packetlen, pvp);
3702                 if (rcode < 0) goto raw;
3703                 return rcode;
3704
3705         default:
3706         raw:
3707                 /*
3708                  *      Re-write the attribute to be "raw".  It is
3709                  *      therefore of type "octets", and will be
3710                  *      handled below.
3711                  */
3712                 da = dict_unknown_afrom_fields(ctx, da->attr, da->vendor);
3713                 if (!da) {
3714                         fr_strerror_printf("Internal sanity check %d", __LINE__);
3715                         return -1;
3716                 }
3717                 tag = TAG_NONE;
3718 #ifndef NDEBUG
3719                 /*
3720                  *      Fix for Coverity.
3721                  */
3722                 if (da->type != PW_TYPE_OCTETS) {
3723                         dict_attr_free(&da);
3724                         return -1;
3725                 }
3726 #endif
3727                 break;
3728         }
3729
3730         /*
3731          *      And now that we've verified the basic type
3732          *      information, decode the actual data.
3733          */
3734  alloc_cui:
3735         vp = pairalloc(ctx, da);
3736         if (!vp) return -1;
3737
3738         vp->vp_length = datalen;
3739         vp->tag = tag;
3740
3741         switch (da->type) {
3742         case PW_TYPE_STRING:
3743                 p = talloc_array(vp, char, vp->vp_length + 1);
3744                 memcpy(p, data, vp->vp_length);
3745                 p[vp->vp_length] = '\0';
3746                 vp->vp_strvalue = p;
3747                 break;
3748
3749         case PW_TYPE_OCTETS:
3750                 pairmemcpy(vp, data, vp->vp_length);
3751                 break;
3752
3753         case PW_TYPE_ABINARY:
3754                 if (vp->vp_length > sizeof(vp->vp_filter)) {
3755                         vp->vp_length = sizeof(vp->vp_filter);
3756                 }
3757                 memcpy(vp->vp_filter, data, vp->vp_length);
3758                 break;
3759
3760         case PW_TYPE_BYTE:
3761                 vp->vp_byte = data[0];
3762                 break;
3763
3764         case PW_TYPE_SHORT:
3765                 vp->vp_short = (data[0] << 8) | data[1];
3766                 break;
3767
3768         case PW_TYPE_INTEGER:
3769                 memcpy(&vp->vp_integer, data, 4);
3770                 vp->vp_integer = ntohl(vp->vp_integer);
3771                 break;
3772
3773         case PW_TYPE_INTEGER64:
3774                 memcpy(&vp->vp_integer64, data, 8);
3775                 vp->vp_integer64 = ntohll(vp->vp_integer64);
3776                 break;
3777
3778         case PW_TYPE_DATE:
3779                 memcpy(&vp->vp_date, data, 4);
3780                 vp->vp_date = ntohl(vp->vp_date);
3781                 break;
3782
3783         case PW_TYPE_ETHERNET:
3784                 memcpy(vp->vp_ether, data, 6);
3785                 break;
3786
3787         case PW_TYPE_IPV4_ADDR:
3788                 memcpy(&vp->vp_ipaddr, data, 4);
3789                 break;
3790
3791         case PW_TYPE_IFID:
3792                 memcpy(vp->vp_ifid, data, 8);
3793                 break;
3794
3795         case PW_TYPE_IPV6_ADDR:
3796                 memcpy(&vp->vp_ipv6addr, data, 16);
3797                 break;
3798
3799         case PW_TYPE_IPV6_PREFIX:
3800                 /*
3801                  *      FIXME: double-check that
3802                  *      (vp->vp_octets[1] >> 3) matches vp->vp_length + 2
3803                  */
3804                 memcpy(vp->vp_ipv6prefix, data, vp->vp_length);
3805                 if (vp->vp_length < 18) {
3806                         memset(((uint8_t *)vp->vp_ipv6prefix) + vp->vp_length, 0,
3807                                18 - vp->vp_length);
3808                 }
3809                 break;
3810
3811         case PW_TYPE_IPV4_PREFIX:
3812                 /* FIXME: do the same double-check as for IPv6Prefix */
3813                 memcpy(vp->vp_ipv4prefix, data, vp->vp_length);
3814
3815                 /*
3816                  *      /32 means "keep all bits".  Otherwise, mask
3817                  *      them out.
3818                  */
3819                 if ((data[1] & 0x3f) > 32) {
3820                         uint32_t addr, mask;
3821
3822                         memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
3823                         mask = 1;
3824                         mask <<= (32 - (data[1] & 0x3f));
3825                         mask--;
3826                         mask = ~mask;
3827                         mask = htonl(mask);
3828                         addr &= mask;
3829                         memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
3830                 }
3831                 break;
3832
3833         case PW_TYPE_SIGNED:    /* overloaded with vp_integer */
3834                 memcpy(&vp->vp_integer, buffer, 4);
3835                 vp->vp_integer = ntohl(vp->vp_integer);
3836                 break;
3837
3838         default:
3839                 pairfree(&vp);
3840                 fr_strerror_printf("Internal sanity check %d", __LINE__);
3841                 return -1;
3842         }
3843         vp->type = VT_DATA;
3844         *pvp = vp;
3845
3846         return attrlen;
3847 }
3848
3849
3850 /** Create a "normal" VALUE_PAIR from the given data
3851  *
3852  */
3853 ssize_t rad_attr2vp(TALLOC_CTX *ctx,
3854                     RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3855                     char const *secret,
3856                     uint8_t const *data, size_t length,
3857                     VALUE_PAIR **pvp)
3858 {
3859         ssize_t rcode;
3860
3861         DICT_ATTR const *da;
3862
3863         if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3864                 fr_strerror_printf("rad_attr2vp: Insufficient data");
3865                 return -1;
3866         }
3867
3868         da = dict_attrbyvalue(data[0], 0);
3869         if (!da) {
3870                 VP_TRACE("attr2vp: unknown attribute %u\n", data[0]);
3871                 da = dict_unknown_afrom_fields(ctx, data[0], 0);
3872         }
3873         if (!da) return -1;
3874
3875         /*
3876          *      Pass the entire thing to the decoding function
3877          */
3878         if (da->flags.concat) {
3879                 VP_TRACE("attr2vp: concat attribute\n");
3880                 return data2vp_concat(ctx, da, data, length, pvp);
3881         }
3882
3883         /*
3884          *      Note that we pass the entire length, not just the
3885          *      length of this attribute.  The Extended or WiMAX
3886          *      attributes may have the "continuation" bit set, and
3887          *      will thus be more than one attribute in length.
3888          */
3889         rcode = data2vp(ctx, packet, original, secret, da,
3890                         data + 2, data[1] - 2, length - 2, pvp);
3891         if (rcode < 0) return rcode;
3892
3893         return 2 + rcode;
3894 }
3895
3896 fr_thread_local_setup(uint8_t *, rad_vp2data_buff)
3897
3898 /** Converts vp_data to network byte order
3899  *
3900  * Provide a pointer to a buffer which contains the value of the VALUE_PAIR
3901  * in an architecture independent format.
3902  *
3903  * The pointer is only guaranteed to be valid between calls to rad_vp2data, and so long
3904  * as the source VALUE_PAIR is not freed.
3905  *
3906  * @param out where to write the pointer to the value.
3907  * @param vp to get the value from.
3908  * @return -1 on error, or the length of the value
3909  */
3910 ssize_t rad_vp2data(uint8_t const **out, VALUE_PAIR const *vp)
3911 {
3912         uint8_t         *buffer;
3913         uint32_t        lvalue;
3914         uint64_t        lvalue64;
3915
3916         *out = NULL;
3917
3918         buffer = fr_thread_local_init(rad_vp2data_buff, free);
3919         if (!buffer) {
3920                 int ret;
3921
3922                 buffer = malloc(sizeof(uint8_t) * sizeof(value_data_t));
3923                 if (!buffer) {
3924                         fr_strerror_printf("Failed allocating memory for rad_vp2data buffer");
3925                         return -1;
3926                 }
3927
3928                 ret = fr_thread_local_set(rad_vp2data_buff, buffer);
3929                 if (ret != 0) {
3930                         fr_strerror_printf("Failed setting up TLS for rad_vp2data buffer: %s", strerror(errno));
3931                         free(buffer);
3932                         return -1;
3933                 }
3934         }
3935
3936         VERIFY_VP(vp);
3937
3938         switch (vp->da->type) {
3939         case PW_TYPE_STRING:
3940         case PW_TYPE_OCTETS:
3941                 memcpy(out, &vp->data.ptr, sizeof(*out));
3942                 break;
3943
3944         /*
3945          *      All of these values are at the same location.
3946          */
3947         case PW_TYPE_IFID:
3948         case PW_TYPE_IPV4_ADDR:
3949         case PW_TYPE_IPV6_ADDR:
3950         case PW_TYPE_IPV6_PREFIX:
3951         case PW_TYPE_IPV4_PREFIX:
3952         case PW_TYPE_ABINARY:
3953         case PW_TYPE_ETHERNET:
3954         case PW_TYPE_COMBO_IP_ADDR:
3955         case PW_TYPE_COMBO_IP_PREFIX:
3956         {
3957                 void const *p = &vp->data;
3958                 memcpy(out, &p, sizeof(*out));
3959                 break;
3960         }
3961
3962         case PW_TYPE_BOOLEAN:
3963                 buffer[0] = vp->vp_byte & 0x01;
3964                 *out = buffer;
3965                 break;
3966
3967         case PW_TYPE_BYTE:
3968                 buffer[0] = vp->vp_byte & 0xff;
3969                 *out = buffer;
3970                 break;
3971
3972         case PW_TYPE_SHORT:
3973                 buffer[0] = (vp->vp_short >> 8) & 0xff;
3974                 buffer[1] = vp->vp_short & 0xff;
3975                 *out = buffer;
3976                 break;
3977
3978         case PW_TYPE_INTEGER:
3979                 lvalue = htonl(vp->vp_integer);
3980                 memcpy(buffer, &lvalue, sizeof(lvalue));
3981                 *out = buffer;
3982                 break;
3983
3984         case PW_TYPE_INTEGER64:
3985                 lvalue64 = htonll(vp->vp_integer64);
3986                 memcpy(buffer, &lvalue64, sizeof(lvalue64));
3987                 *out = buffer;
3988                 break;
3989
3990         case PW_TYPE_DATE:
3991                 lvalue = htonl(vp->vp_date);
3992                 memcpy(buffer, &lvalue, sizeof(lvalue));
3993                 *out = buffer;
3994                 break;
3995
3996         case PW_TYPE_SIGNED:
3997         {
3998                 int32_t slvalue = htonl(vp->vp_signed);
3999                 memcpy(buffer, &slvalue, sizeof(slvalue));
4000                 *out = buffer;
4001                 break;
4002         }
4003
4004         case PW_TYPE_INVALID:
4005         case PW_TYPE_EXTENDED:
4006         case PW_TYPE_LONG_EXTENDED:
4007         case PW_TYPE_EVS:
4008         case PW_TYPE_VSA:
4009         case PW_TYPE_TLV:
4010         case PW_TYPE_TIMEVAL:
4011         case PW_TYPE_MAX:
4012                 fr_strerror_printf("Cannot get data for VALUE_PAIR type %i", vp->da->type);
4013                 return -1;
4014
4015         /* Don't add default */
4016         }
4017
4018         return vp->vp_length;
4019 }
4020
4021 /** Calculate/check digest, and decode radius attributes
4022  *
4023  * @return -1 on decoding error, 0 on success
4024  */
4025 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
4026                char const *secret)
4027 {
4028         int                     packet_length;
4029         uint32_t                num_attributes;
4030         uint8_t                 *ptr;
4031         radius_packet_t         *hdr;
4032         VALUE_PAIR *head, **tail, *vp;
4033
4034         /*
4035          *      Extract attribute-value pairs
4036          */
4037         hdr = (radius_packet_t *)packet->data;
4038         ptr = hdr->data;
4039         packet_length = packet->data_len - RADIUS_HDR_LEN;
4040
4041         head = NULL;
4042         tail = &head;
4043         num_attributes = 0;
4044
4045         /*
4046          *      Loop over the attributes, decoding them into VPs.
4047          */
4048         while (packet_length > 0) {
4049                 ssize_t my_len;
4050
4051                 /*
4052                  *      This may return many VPs
4053                  */
4054                 my_len = rad_attr2vp(packet, packet, original, secret,
4055                                      ptr, packet_length, &vp);
4056                 if (my_len < 0) {
4057                         pairfree(&head);
4058                         return -1;
4059                 }
4060
4061                 *tail = vp;
4062                 while (vp) {
4063                         num_attributes++;
4064                         tail = &(vp->next);
4065                         vp = vp->next;
4066                 }
4067
4068                 /*
4069                  *      VSA's may not have been counted properly in
4070                  *      rad_packet_ok() above, as it is hard to count
4071                  *      then without using the dictionary.  We
4072                  *      therefore enforce the limits here, too.
4073                  */
4074                 if ((fr_max_attributes > 0) &&
4075                     (num_attributes > fr_max_attributes)) {
4076                         char host_ipaddr[128];
4077
4078                         pairfree(&head);
4079                         fr_strerror_printf("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
4080                                    inet_ntop(packet->src_ipaddr.af,
4081                                              &packet->src_ipaddr.ipaddr,
4082                                              host_ipaddr, sizeof(host_ipaddr)),
4083                                    num_attributes, fr_max_attributes);
4084                         return -1;
4085                 }
4086
4087                 ptr += my_len;
4088                 packet_length -= my_len;
4089         }
4090
4091         /*
4092          *      Merge information from the outside world into our
4093          *      random pool.
4094          */
4095         fr_rand_seed(packet->data, RADIUS_HDR_LEN);
4096
4097         /*
4098          *      There may be VP's already in the packet.  Don't
4099          *      destroy them.  Instead, add the decoded attributes to
4100          *      the tail of the list.
4101          */
4102         for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
4103                 /* nothing */
4104         }
4105         *tail = head;
4106
4107         return 0;
4108 }
4109
4110
4111 /** Encode password
4112  *
4113  * We assume that the passwd buffer passed is big enough.
4114  * RFC2138 says the password is max 128 chars, so the size
4115  * of the passwd buffer must be at least 129 characters.
4116  * Preferably it's just MAX_STRING_LEN.
4117  *
4118  * int *pwlen is updated to the new length of the encrypted
4119  * password - a multiple of 16 bytes.
4120  */
4121 int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
4122                  uint8_t const *vector)
4123 {
4124         FR_MD5_CTX context, old;
4125         uint8_t digest[AUTH_VECTOR_LEN];
4126         int     i, n, secretlen;
4127         int     len;
4128
4129         /*
4130          *      RFC maximum is 128 bytes.
4131          *
4132          *      If length is zero, pad it out with zeros.
4133          *
4134          *      If the length isn't aligned to 16 bytes,
4135          *      zero out the extra data.
4136          */
4137         len = *pwlen;
4138
4139         if (len > 128) len = 128;
4140
4141         if (len == 0) {
4142                 memset(passwd, 0, AUTH_PASS_LEN);
4143                 len = AUTH_PASS_LEN;
4144         } else if ((len % AUTH_PASS_LEN) != 0) {
4145                 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
4146                 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
4147         }
4148         *pwlen = len;
4149
4150         /*
4151          *      Use the secret to setup the decryption digest
4152          */
4153         secretlen = strlen(secret);
4154
4155         fr_md5_init(&context);
4156         fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4157         old = context;          /* save intermediate work */
4158
4159         /*
4160          *      Encrypt it in place.  Don't bother checking
4161          *      len, as we've ensured above that it's OK.
4162          */
4163         for (n = 0; n < len; n += AUTH_PASS_LEN) {
4164                 if (n == 0) {
4165                         fr_md5_update(&context, vector, AUTH_PASS_LEN);
4166                         fr_md5_final(digest, &context);
4167                 } else {
4168                         context = old;
4169                         fr_md5_update(&context,
4170                                      (uint8_t *) passwd + n - AUTH_PASS_LEN,
4171                                      AUTH_PASS_LEN);
4172                         fr_md5_final(digest, &context);
4173                 }
4174
4175                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4176                         passwd[i + n] ^= digest[i];
4177                 }
4178         }
4179
4180         return 0;
4181 }
4182
4183 /** Decode password
4184  *
4185  */
4186 int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
4187                  uint8_t const *vector)
4188 {
4189         FR_MD5_CTX context, old;
4190         uint8_t digest[AUTH_VECTOR_LEN];
4191         int     i;
4192         size_t  n, secretlen;
4193
4194         /*
4195          *      The RFC's say that the maximum is 128.
4196          *      The buffer we're putting it into above is 254, so
4197          *      we don't need to do any length checking.
4198          */
4199         if (pwlen > 128) pwlen = 128;
4200
4201         /*
4202          *      Catch idiots.
4203          */
4204         if (pwlen == 0) goto done;
4205
4206         /*
4207          *      Use the secret to setup the decryption digest
4208          */
4209         secretlen = strlen(secret);
4210
4211         fr_md5_init(&context);
4212         fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4213         old = context;          /* save intermediate work */
4214
4215         /*
4216          *      The inverse of the code above.
4217          */
4218         for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
4219                 if (n == 0) {
4220                         fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4221                         fr_md5_final(digest, &context);
4222
4223                         context = old;
4224                         if (pwlen > AUTH_PASS_LEN) {
4225                                 fr_md5_update(&context, (uint8_t *) passwd,
4226                                              AUTH_PASS_LEN);
4227                         }
4228                 } else {
4229                         fr_md5_final(digest, &context);
4230
4231                         context = old;
4232                         if (pwlen > (n + AUTH_PASS_LEN)) {
4233                                 fr_md5_update(&context, (uint8_t *) passwd + n,
4234                                              AUTH_PASS_LEN);
4235                         }
4236                 }
4237
4238                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4239                         passwd[i + n] ^= digest[i];
4240                 }
4241         }
4242
4243  done:
4244         passwd[pwlen] = '\0';
4245         return strlen(passwd);
4246 }
4247
4248
4249 /** Encode Tunnel-Password attributes when sending them out on the wire
4250  *
4251  * int *pwlen is updated to the new length of the encrypted
4252  * password - a multiple of 16 bytes.
4253  *
4254  * This is per RFC-2868 which adds a two char SALT to the initial intermediate
4255  * value MD5 hash.
4256  */
4257 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret,
4258                         uint8_t const *vector)
4259 {
4260         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
4261         unsigned char   digest[AUTH_VECTOR_LEN];
4262         char*   salt;
4263         int     i, n, secretlen;
4264         unsigned len, n2;
4265
4266         len = *pwlen;
4267
4268         if (len > 127) len = 127;
4269
4270         /*
4271          * Shift the password 3 positions right to place a salt and original
4272          * length, tag will be added automatically on packet send
4273          */
4274         for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
4275         salt = passwd;
4276         passwd += 2;
4277         /*
4278          * save original password length as first password character;
4279          */
4280         *passwd = len;
4281         len += 1;
4282
4283
4284         /*
4285          *      Generate salt.  The RFC's say:
4286          *
4287          *      The high bit of salt[0] must be set, each salt in a
4288          *      packet should be unique, and they should be random
4289          *
4290          *      So, we set the high bit, add in a counter, and then
4291          *      add in some CSPRNG data.  should be OK..
4292          */
4293         salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
4294                    (fr_rand() & 0x07));
4295         salt[1] = fr_rand();
4296
4297         /*
4298          *      Padd password to multiple of AUTH_PASS_LEN bytes.
4299          */
4300         n = len % AUTH_PASS_LEN;
4301         if (n) {
4302                 n = AUTH_PASS_LEN - n;
4303                 for (; n > 0; n--, len++)
4304                         passwd[len] = 0;
4305         }
4306         /* set new password length */
4307         *pwlen = len + 2;
4308
4309         /*
4310          *      Use the secret to setup the decryption digest
4311          */
4312         secretlen = strlen(secret);
4313         memcpy(buffer, secret, secretlen);
4314
4315         for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
4316                 if (!n2) {
4317                         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
4318                         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
4319                         fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
4320                 } else {
4321                         memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4322                         fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4323                 }
4324
4325                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4326                         passwd[i + n2] ^= digest[i];
4327                 }
4328         }
4329         passwd[n2] = 0;
4330         return 0;
4331 }
4332
4333 /** Decode Tunnel-Password encrypted attributes
4334  *
4335  * Defined in RFC-2868, this uses a two char SALT along with the
4336  * initial intermediate value, to differentiate it from the
4337  * above.
4338  */
4339 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret,
4340                         uint8_t const *vector)
4341 {
4342         FR_MD5_CTX  context, old;
4343         uint8_t         digest[AUTH_VECTOR_LEN];
4344         int             secretlen;
4345         unsigned        i, n, len, reallen;
4346
4347         len = *pwlen;
4348
4349         /*
4350          *      We need at least a salt.
4351          */
4352         if (len < 2) {
4353                 fr_strerror_printf("tunnel password is too short");
4354                 return -1;
4355         }
4356
4357         /*
4358          *      There's a salt, but no password.  Or, there's a salt
4359          *      and a 'data_len' octet.  It's wrong, but at least we
4360          *      can figure out what it means: the password is empty.
4361          *
4362          *      Note that this means we ignore the 'data_len' field,
4363          *      if the attribute length tells us that there's no
4364          *      more data.  So the 'data_len' field may be wrong,
4365          *      but that's ok...
4366          */
4367         if (len <= 3) {
4368                 passwd[0] = 0;
4369                 *pwlen = 0;
4370                 return 0;
4371         }
4372
4373         len -= 2;               /* discount the salt */
4374
4375         /*
4376          *      Use the secret to setup the decryption digest
4377          */
4378         secretlen = strlen(secret);
4379
4380         fr_md5_init(&context);
4381         fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4382         old = context;          /* save intermediate work */
4383
4384         /*
4385          *      Set up the initial key:
4386          *
4387          *       b(1) = MD5(secret + vector + salt)
4388          */
4389         fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4390         fr_md5_update(&context, passwd, 2);
4391
4392         reallen = 0;
4393         for (n = 0; n < len; n += AUTH_PASS_LEN) {
4394                 int base = 0;
4395
4396                 if (n == 0) {
4397                         fr_md5_final(digest, &context);
4398
4399                         context = old;
4400
4401                         /*
4402                          *      A quick check: decrypt the first octet
4403                          *      of the password, which is the
4404                          *      'data_len' field.  Ensure it's sane.
4405                          */
4406                         reallen = passwd[2] ^ digest[0];
4407                         if (reallen >= len) {
4408                                 fr_strerror_printf("tunnel password is too long for the attribute");
4409                                 return -1;
4410                         }
4411
4412                         fr_md5_update(&context, passwd + 2, AUTH_PASS_LEN);
4413
4414                         base = 1;
4415                 } else {
4416                         fr_md5_final(digest, &context);
4417
4418                         context = old;
4419                         fr_md5_update(&context, passwd + n + 2, AUTH_PASS_LEN);
4420                 }
4421
4422                 for (i = base; i < AUTH_PASS_LEN; i++) {
4423                         passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4424                 }
4425         }
4426
4427         /*
4428          *      See make_tunnel_password, above.
4429          */
4430         if (reallen > 239) reallen = 239;
4431
4432         *pwlen = reallen;
4433         passwd[reallen] = 0;
4434
4435         return reallen;
4436 }
4437
4438 /** Encode a CHAP password
4439  *
4440  * @bug FIXME: might not work with Ascend because
4441  * we use vp->vp_length, and Ascend gear likes
4442  * to send an extra '\0' in the string!
4443  */
4444 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4445                     VALUE_PAIR *password)
4446 {
4447         int             i;
4448         uint8_t         *ptr;
4449         uint8_t         string[MAX_STRING_LEN * 2 + 1];
4450         VALUE_PAIR      *challenge;
4451
4452         /*
4453          *      Sanity check the input parameters
4454          */
4455         if ((packet == NULL) || (password == NULL)) {
4456                 return -1;
4457         }
4458
4459         /*
4460          *      Note that the password VP can be EITHER
4461          *      a User-Password attribute (from a check-item list),
4462          *      or a CHAP-Password attribute (the client asking
4463          *      the library to encode it).
4464          */
4465
4466         i = 0;
4467         ptr = string;
4468         *ptr++ = id;
4469
4470         i++;
4471         memcpy(ptr, password->vp_strvalue, password->vp_length);
4472         ptr += password->vp_length;
4473         i += password->vp_length;
4474
4475         /*
4476          *      Use Chap-Challenge pair if present,
4477          *      Request Authenticator otherwise.
4478          */
4479         challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
4480         if (challenge) {
4481                 memcpy(ptr, challenge->vp_strvalue, challenge->vp_length);
4482                 i += challenge->vp_length;
4483         } else {
4484                 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4485                 i += AUTH_VECTOR_LEN;
4486         }
4487
4488         *output = id;
4489         fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4490
4491         return 0;
4492 }
4493
4494
4495 /** Seed the random number generator
4496  *
4497  * May be called any number of times.
4498  */
4499 void fr_rand_seed(void const *data, size_t size)
4500 {
4501         uint32_t hash;
4502
4503         /*
4504          *      Ensure that the pool is initialized.
4505          */
4506         if (!fr_rand_initialized) {
4507                 int fd;
4508
4509                 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4510
4511                 fd = open("/dev/urandom", O_RDONLY);
4512                 if (fd >= 0) {
4513                         size_t total;
4514                         ssize_t this;
4515
4516                         total = 0;
4517                         while (total < sizeof(fr_rand_pool.randrsl)) {
4518                                 this = read(fd, fr_rand_pool.randrsl,
4519                                             sizeof(fr_rand_pool.randrsl) - total);
4520                                 if ((this < 0) && (errno != EINTR)) break;
4521                                 if (this > 0) total += this;
4522                         }
4523                         close(fd);
4524                 } else {
4525                         fr_rand_pool.randrsl[0] = fd;
4526                         fr_rand_pool.randrsl[1] = time(NULL);
4527                         fr_rand_pool.randrsl[2] = errno;
4528                 }
4529
4530                 fr_randinit(&fr_rand_pool, 1);
4531                 fr_rand_pool.randcnt = 0;
4532                 fr_rand_initialized = 1;
4533         }
4534
4535         if (!data) return;
4536
4537         /*
4538          *      Hash the user data
4539          */
4540         hash = fr_rand();
4541         if (!hash) hash = fr_rand();
4542         hash = fr_hash_update(data, size, hash);
4543
4544         fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4545 }
4546
4547
4548 /** Return a 32-bit random number
4549  *
4550  */
4551 uint32_t fr_rand(void)
4552 {
4553         uint32_t num;
4554
4555         /*
4556          *      Ensure that the pool is initialized.
4557          */
4558         if (!fr_rand_initialized) {
4559                 fr_rand_seed(NULL, 0);
4560         }
4561
4562         num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4563         if (fr_rand_pool.randcnt >= 256) {
4564                 fr_rand_pool.randcnt = 0;
4565                 fr_isaac(&fr_rand_pool);
4566         }
4567
4568         return num;
4569 }
4570
4571
4572 /** Allocate a new RADIUS_PACKET
4573  *
4574  * @param ctx the context in which the packet is allocated. May be NULL if
4575  *      the packet is not associated with a REQUEST.
4576  * @param new_vector if true a new request authenticator will be generated.
4577  * @return a new RADIUS_PACKET or NULL on error.
4578  */
4579 RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, bool new_vector)
4580 {
4581         RADIUS_PACKET   *rp;
4582
4583         rp = talloc_zero(ctx, RADIUS_PACKET);
4584         if (!rp) {
4585                 fr_strerror_printf("out of memory");
4586                 return NULL;
4587         }
4588         rp->id = -1;
4589         rp->offset = -1;
4590
4591         if (new_vector) {
4592                 int i;
4593                 uint32_t hash, base;
4594
4595                 /*
4596                  *      Don't expose the actual contents of the random
4597                  *      pool.
4598                  */
4599                 base = fr_rand();
4600                 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4601                         hash = fr_rand() ^ base;
4602                         memcpy(rp->vector + i, &hash, sizeof(hash));
4603                 }
4604         }
4605         fr_rand();              /* stir the pool again */
4606
4607         return rp;
4608 }
4609
4610 /** Allocate a new RADIUS_PACKET response
4611  *
4612  * @param ctx the context in which the packet is allocated. May be NULL if
4613  *      the packet is not associated with a REQUEST.
4614  * @param packet The request packet.
4615  * @return a new RADIUS_PACKET or NULL on error.
4616  */
4617 RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
4618 {
4619         RADIUS_PACKET *reply;
4620
4621         if (!packet) return NULL;
4622
4623         reply = rad_alloc(ctx, false);
4624         if (!reply) return NULL;
4625
4626         /*
4627          *      Initialize the fields from the request.
4628          */
4629         reply->sockfd = packet->sockfd;
4630         reply->dst_ipaddr = packet->src_ipaddr;
4631         reply->src_ipaddr = packet->dst_ipaddr;
4632         reply->dst_port = packet->src_port;
4633         reply->src_port = packet->dst_port;
4634         reply->id = packet->id;
4635         reply->code = 0; /* UNKNOWN code */
4636         memcpy(reply->vector, packet->vector,
4637                sizeof(reply->vector));
4638         reply->vps = NULL;
4639         reply->data = NULL;
4640         reply->data_len = 0;
4641
4642 #ifdef WITH_TCP
4643         reply->proto = packet->proto;
4644 #endif
4645         return reply;
4646 }
4647
4648
4649 /** Free a RADIUS_PACKET
4650  *
4651  */
4652 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4653 {
4654         RADIUS_PACKET *radius_packet;
4655
4656         if (!radius_packet_ptr || !*radius_packet_ptr) return;
4657         radius_packet = *radius_packet_ptr;
4658
4659         VERIFY_PACKET(radius_packet);
4660
4661         pairfree(&radius_packet->vps);
4662
4663         talloc_free(radius_packet);
4664         *radius_packet_ptr = NULL;
4665 }
4666
4667 /** Duplicate a RADIUS_PACKET
4668  *
4669  * @param ctx the context in which the packet is allocated. May be NULL if
4670  *      the packet is not associated with a REQUEST.
4671  * @param in The packet to copy
4672  * @return a new RADIUS_PACKET or NULL on error.
4673  */
4674 RADIUS_PACKET *rad_copy_packet(TALLOC_CTX *ctx, RADIUS_PACKET const *in)
4675 {
4676         RADIUS_PACKET *out;
4677
4678         out = rad_alloc(ctx, false);
4679         if (!out) return NULL;
4680
4681         /*
4682          *      Bootstrap by copying everything.
4683          */
4684         memcpy(out, in, sizeof(*out));
4685
4686         /*
4687          *      Then reset necessary fields
4688          */
4689         out->sockfd = -1;
4690
4691         out->data = NULL;
4692         out->data_len = 0;
4693
4694         out->vps = paircopy(out, in->vps);
4695         out->offset = 0;
4696
4697         return out;
4698 }