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