ce0a2effe11cb5de74606f3787ffed19f705ac59
[freeradius.git] / src / lib / radius.c
1 /*
2  * radius.c     Functions to send/receive radius packets.
3  *
4  * Version:     $Id$
5  *
6  *   This library is free software; you can redistribute it and/or
7  *   modify it under the terms of the GNU Lesser General Public
8  *   License as published by the Free Software Foundation; either
9  *   version 2.1 of the License, or (at your option) any later version.
10  *
11  *   This library is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  *   Lesser General Public License for more details.
15  *
16  *   You should have received a copy of the GNU Lesser General Public
17  *   License along with this library; if not, write to the Free Software
18  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
19  *
20  * Copyright 2000-2003  The FreeRADIUS server project
21  */
22
23 static const char rcsid[] = "$Id$";
24
25 #include        "autoconf.h"
26 #include        "md5.h"
27
28 #include        <stdlib.h>
29
30 #ifdef HAVE_UNISTD_H
31 #include        <unistd.h>
32 #endif
33
34 #include        <fcntl.h>
35 #include        <string.h>
36 #include        <ctype.h>
37
38 #include        "libradius.h"
39 #ifdef WITH_UDPFROMTO
40 #include        "udpfromto.h"
41 #endif
42
43 #ifdef HAVE_NETINET_IN_H
44 #include        <netinet/in.h>
45 #endif
46
47 #include        <sys/socket.h>
48
49 #ifdef HAVE_ARPA_INET_H
50 #include        <arpa/inet.h>
51 #endif
52
53 #ifdef HAVE_MALLOC_H
54 #include        <malloc.h>
55 #endif
56
57 #ifdef WIN32
58 #include        <process.h>
59 #endif
60
61 /*
62  *  The RFC says 4096 octets max, and most packets are less than 256.
63  */
64 #define MAX_PACKET_LEN 4096
65
66 /*
67  *      The maximum number of attributes which we allow in an incoming
68  *      request.  If there are more attributes than this, the request
69  *      is rejected.
70  *
71  *      This helps to minimize the potential for a DoS, when an
72  *      attacker spoofs Access-Request packets, which don't have a
73  *      Message-Authenticator attribute.  This means that the packet
74  *      is unsigned, and the attacker can use resources on the server,
75  *      even if the end request is rejected.
76  */
77 int librad_max_attributes = 0;
78
79 typedef struct radius_packet_t {
80   uint8_t       code;
81   uint8_t       id;
82   uint8_t       length[2];
83   uint8_t       vector[AUTH_VECTOR_LEN];
84   uint8_t       data[1];
85 } radius_packet_t;
86
87 static lrad_randctx lrad_rand_pool;     /* across multiple calls */
88 static int lrad_pool_initialized = 0;
89
90 static const char *packet_codes[] = {
91   "",
92   "Access-Request",
93   "Access-Accept",
94   "Access-Reject",
95   "Accounting-Request",
96   "Accounting-Response",
97   "Accounting-Status",
98   "Password-Request",
99   "Password-Accept",
100   "Password-Reject",
101   "Accounting-Message",
102   "Access-Challenge",
103   "Status-Server",
104   "Status-Client",
105   "14",
106   "15",
107   "16",
108   "17",
109   "18",
110   "19",
111   "20",
112   "Resource-Free-Request",
113   "Resource-Free-Response",
114   "Resource-Query-Request",
115   "Resource-Query-Response",
116   "Alternate-Resource-Reclaim-Request",
117   "NAS-Reboot-Request",
118   "NAS-Reboot-Response",
119   "28",
120   "Next-Passcode",
121   "New-Pin",
122   "Terminate-Session",
123   "Password-Expired",
124   "Event-Request",
125   "Event-Response",
126   "35",
127   "36",
128   "37",
129   "38",
130   "39",
131   "Disconnect-Request",
132   "Disconnect-ACK",
133   "Disconnect-NAK",
134   "CoF-Request",
135   "CoF-ACK",
136   "CoF-NAK",
137   "46",
138   "47",
139   "48",
140   "49",
141   "IP-Address-Allocate",
142   "IP-Address-Release"
143 };
144
145 /*
146  *  Internal prototypes
147  */
148 static void make_secret(unsigned char *digest, uint8_t *vector,
149                         const char *secret, char *value);
150
151 /*
152  *      Reply to the request.  Also attach
153  *      reply attribute value pairs and any user message provided.
154  */
155 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
156              const char *secret)
157 {
158         VALUE_PAIR              *reply;
159         struct  sockaddr_in     saremote;
160         struct  sockaddr_in     *sa;
161         const char              *what;
162         uint8_t                 ip_buffer[16];
163
164         /*
165          *      Maybe it's a fake packet.  Don't send it.
166          */
167         if (!packet || (packet->sockfd < 0)) {
168                 return 0;
169         }
170
171         if ((packet->code > 0) && (packet->code < 52)) {
172                 what = packet_codes[packet->code];
173         } else {
174                 what = "Reply";
175         }
176
177         /*
178          *  First time through, allocate room for the packet
179          */
180         if (!packet->data) {
181                   radius_packet_t       *hdr;
182                   uint32_t              lvalue;
183                   uint8_t               *ptr, *length_ptr, *vsa_length_ptr;
184                   uint8_t               digest[16];
185                   int                   secretlen;
186                   int                   vendorcode, vendorpec;
187                   u_short               total_length;
188                   int                   len, allowed;
189                   int                   msg_auth_offset = 0;
190
191                   /*
192                    *    For simplicity in the following logic, we allow
193                    *    the attributes to "overflow" the 4k maximum
194                    *    RADIUS packet size, by one attribute.
195                    */
196                   uint8_t               data[MAX_PACKET_LEN + 256];
197
198                   /*
199                    *    Use memory on the stack, until we know how
200                    *    large the packet will be.
201                    */
202                   hdr = (radius_packet_t *) data;
203
204                   /*
205                    *    Build standard header
206                    */
207                   hdr->code = packet->code;
208                   hdr->id = packet->id;
209
210                   /*
211                    *    Double-check some things based on packet code.
212                    */
213                   switch (packet->code) {
214                   case PW_AUTHENTICATION_ACK:
215                   case PW_AUTHENTICATION_REJECT:
216                   case PW_ACCESS_CHALLENGE:
217                           if (!original) {
218                                   librad_log("ERROR: Cannot sign response packet without a request packet.");
219                                   return -1;
220                           }
221                           break;
222
223                           /*
224                            *    These packet vectors start off as all zero.
225                            */
226                   case PW_ACCOUNTING_REQUEST:
227                   case PW_DISCONNECT_REQUEST:
228                           memset(packet->vector, 0, sizeof(packet->vector));
229                           break;
230
231                   default:
232                           break;
233
234                   }
235                   memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
236
237                   DEBUG("Sending %s of id %d to %s:%d\n",
238                         what, packet->id,
239                         ip_ntoa((char *)ip_buffer, packet->dst_ipaddr),
240                         packet->dst_port);
241
242                   total_length = AUTH_HDR_LEN;
243
244                   /*
245                    *    Load up the configuration values for the user
246                    */
247                   ptr = hdr->data;
248                   vendorcode = 0;
249                   vendorpec = 0;
250                   vsa_length_ptr = NULL;
251
252                   /*
253                    *    Loop over the reply attributes for the packet.
254                    */
255                   for (reply = packet->vps; reply; reply = reply->next) {
256                           /*
257                            *    Ignore non-wire attributes
258                            */
259                           if ((VENDOR(reply->attribute) == 0) &&
260                               ((reply->attribute & 0xFFFF) > 0xff)) {
261                                   continue;
262                           }
263
264                           /*
265                            *    Check that the packet is no more than
266                            *    4k in size, AFTER over-flowing the 4k
267                            *    boundary.  Note that the 'data'
268                            *    buffer, above, is one attribute longer
269                            *    than necessary, in order to permit
270                            *    this overflow.
271                            */
272                           if (total_length > MAX_PACKET_LEN) {
273                                   librad_log("ERROR: Too many attributes for packet, result is larger than RFC maximum of 4k");
274                                   return -1;
275                           }
276
277                           /*
278                            *    Set the Message-Authenticator to the
279                            *    correct length and initial value.
280                            */
281                           if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
282                                   reply->length = AUTH_VECTOR_LEN;
283                                   memset(reply->strvalue, 0, AUTH_VECTOR_LEN);
284                                   msg_auth_offset = total_length;
285                           }
286
287                           /*
288                            *    Print out ONLY the attributes which
289                            *    we're sending over the wire, and print
290                            *    them out BEFORE they're encrypted.
291                            */
292                           debug_pair(reply);
293
294                           /*
295                            *    We have a different vendor.  Re-set
296                            *    the vendor codes.
297                            */
298                           if (vendorcode != VENDOR(reply->attribute)) {
299                                   vendorcode = 0;
300                                   vendorpec = 0;
301                                   vsa_length_ptr = NULL;
302                           }
303
304                           /*
305                            *    If the Vendor-Specific attribute is getting
306                            *    full, then create a new VSA attribute
307                            *
308                            *    FIXME: Multiple VSA's per Vendor-Specific
309                            *    SHOULD be configurable.  When that's done,
310                            *    the (1), below, can be changed to point to
311                            *    a configuration variable which is set TRUE
312                            *    if the NAS cannot understand multiple VSA's
313                            *    per Vendor-Specific
314                            */
315                           if ((1) || /* ALWAYS create a new Vendor-Specific */
316                               (vsa_length_ptr &&
317                                (reply->length + *vsa_length_ptr) >= MAX_STRING_LEN)) {
318                                   vendorcode = 0;
319                                   vendorpec = 0;
320                                   vsa_length_ptr = NULL;
321                           }
322
323                           /*
324                            *    Maybe we have the start of a set of
325                            *    (possibly many) VSA attributes from
326                            *    one vendor.  Set a global VSA wrapper
327                            */
328                           if ((vendorcode == 0) &&
329                               ((vendorcode = VENDOR(reply->attribute)) != 0)) {
330                                   vendorpec  = dict_vendorpec(vendorcode);
331
332                                   /*
333                                    *    This is a potentially bad error...
334                                    *    we can't find the vendor ID!
335                                    */
336                                   if (vendorpec == 0) {
337                                           /* FIXME: log an error */
338                                           continue;
339                                   }
340
341                                   /*
342                                    *    Build a VSA header.
343                                    */
344                                   *ptr++ = PW_VENDOR_SPECIFIC;
345                                   vsa_length_ptr = ptr;
346                                   *ptr++ = 6;
347                                   lvalue = htonl(vendorpec);
348                                   memcpy(ptr, &lvalue, 4);
349                                   ptr += 4;
350                                   total_length += 6;
351                           }
352
353                           if (vendorpec == VENDORPEC_USR) {
354                                   lvalue = htonl(reply->attribute & 0xFFFF);
355                                   memcpy(ptr, &lvalue, 4);
356
357                                   length_ptr = vsa_length_ptr;
358
359                                   total_length += 4;
360                                   *length_ptr  += 4;
361                                   ptr          += 4;
362
363                                   /*
364                                    *    Each USR-style attribute gets
365                                    *    it's own VSA wrapper, so we
366                                    *    re-set the vendor specific
367                                    *    information.
368                                    */
369                                   vendorcode = 0;
370                                   vendorpec = 0;
371                                   vsa_length_ptr = NULL;
372
373                           } else {
374                                   /*
375                                    *    All other attributes are as
376                                    *    per the RFC spec.
377                                    */
378                                   *ptr++ = (reply->attribute & 0xFF);
379                                   length_ptr = ptr;
380                                   if (vsa_length_ptr) *vsa_length_ptr += 2;
381                                   *ptr++ = 2;
382                                   total_length += 2;
383                           }
384
385                           switch(reply->type) {
386
387                                   /*
388                                    *    Ascend binary attributes are
389                                    *    stored internally in binary form.
390                                    */
391                           case PW_TYPE_IFID:
392                           case PW_TYPE_IPV6ADDR:
393                           case PW_TYPE_IPV6PREFIX:
394                           case PW_TYPE_ABINARY:
395                           case PW_TYPE_STRING:
396                           case PW_TYPE_OCTETS:
397                                   /*
398                                    *  Encrypt the various password styles
399                                    */
400                                   switch (reply->flags.encrypt) {
401                                   default:
402                                           break;
403
404                                   case FLAG_ENCRYPT_USER_PASSWORD:
405                                     rad_pwencode((char *)reply->strvalue,
406                                                  &(reply->length),
407                                                  (const char *)secret,
408                                                  (const char *)packet->vector);
409                                     break;
410
411                                   case FLAG_ENCRYPT_TUNNEL_PASSWORD:
412                                           if (!original) {
413                                                   librad_log("ERROR: No request packet, cannot encrypt Tunnel-Password attribute in the reply.");
414                                                   return -1;
415                                           }
416                                           rad_tunnel_pwencode(reply->strvalue,
417                                                               &(reply->length),
418                                                               secret,
419                                                               original->vector);
420                                           break;
421
422
423                                   case FLAG_ENCRYPT_ASCEND_SECRET:
424                                           make_secret(digest, packet->vector,
425                                                       secret, reply->strvalue);
426                                           memcpy(reply->strvalue, digest, AUTH_VECTOR_LEN );
427                                           reply->length = AUTH_VECTOR_LEN;
428                                           break;
429                                   } /* switch over encryption flags */
430
431                                   len = reply->length;
432
433                                   /*
434                                    *    Set the TAG at the beginning
435                                    *    of the string if tagged.  If
436                                    *    tag value is not valid for
437                                    *    tagged attribute, make it 0x00
438                                    *    per RFC 2868.  -cparker
439                                    */
440                                   if (reply->flags.has_tag) {
441                                           if (TAG_VALID(reply->flags.tag)) {
442                                                   len++;
443                                                   *ptr++ = reply->flags.tag;
444
445                                           } else if (reply->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD) {
446                                                   /*
447                                                    *  Tunnel passwords
448                                                    *  REQUIRE a tag,
449                                                    *  even if we don't
450                                                    *  have a valid
451                                                    *  tag.
452                                                    */
453                                                   len++;
454                                                   *ptr++ = 0x00;
455                                           } /* else don't write a tag */
456                                   } /* else the attribute doesn't have a tag */
457
458                                   /*
459                                    *    Ensure we don't go too far.
460                                    *    The 'length' of the attribute
461                                    *    may be 0..255, minus whatever
462                                    *    octets are used in the attribute
463                                    *    header.
464                                    */
465                                   allowed = 255;
466                                   if (vsa_length_ptr) {
467                                           allowed -= *vsa_length_ptr;
468                                   } else {
469                                           allowed -= *length_ptr;
470                                   }
471
472                                   if (len > allowed) {
473                                           len = allowed;
474                                   }
475
476                                   *length_ptr += len;
477                                   if (vsa_length_ptr) *vsa_length_ptr += len;
478                                   /*
479                                    *  If we have tagged attributes we can't assume that
480                                    *  len == reply->length.  Use reply->length for copying
481                                    *  the string data into the packet.  Use len for the
482                                    *  true length of the string+tags.
483                                    */
484                                   memcpy(ptr, reply->strvalue, reply->length);
485                                   ptr += reply->length;
486                                   total_length += len;
487                                   break;
488
489                           case PW_TYPE_INTEGER:
490                           case PW_TYPE_IPADDR:
491                                   *length_ptr += 4;
492                                   if (vsa_length_ptr) *vsa_length_ptr += 4;
493
494                                   if (reply->type == PW_TYPE_INTEGER ) {
495                                           /*  If tagged, the tag becomes the MSB of the value */
496                                           if(reply->flags.has_tag) {
497                                                  /*  Tag must be ( 0x01 -> 0x1F ) OR 0x00  */
498                                                  if(!TAG_VALID(reply->flags.tag)) {
499                                                        reply->flags.tag = 0x00;
500                                                  }
501                                                  lvalue = htonl((reply->lvalue & 0xffffff) |
502                                                                 ((reply->flags.tag & 0xff) << 24));
503                                           } else {
504                                                  lvalue = htonl(reply->lvalue);
505                                           }
506                                   } else {
507                                           /*
508                                            *  IP address is already in
509                                            *  network byte order.
510                                            */
511                                           lvalue = reply->lvalue;
512                                   }
513                                   memcpy(ptr, &lvalue, 4);
514                                   ptr += 4;
515                                   total_length += 4;
516                                   break;
517
518                                   /*
519                                    *  There are no tagged date attributes.
520                                    */
521                           case PW_TYPE_DATE:
522                                   *length_ptr += 4;
523                                   if (vsa_length_ptr) *vsa_length_ptr += 4;
524
525                                   lvalue = htonl(reply->lvalue);
526                                   memcpy(ptr, &lvalue, 4);
527                                   ptr += 4;
528                                   total_length += 4;
529                                   break;
530                           default:
531                                   break;
532                           }
533                   } /* done looping over all attributes */
534
535                   /*
536                    *    Fill in the rest of the fields, and copy
537                    *    the data over from the local stack to
538                    *    the newly allocated memory.
539                    *
540                    *    Yes, all this 'memcpy' is slow, but it means
541                    *    that we only allocate the minimum amount of
542                    *    memory for a request.
543                    */
544                   packet->data_len = total_length;
545                   packet->data = (uint8_t *) malloc(packet->data_len);
546                   if (!packet->data) {
547                           librad_log("Out of memory");
548                           return -1;
549                   }
550                   memcpy(packet->data, data, packet->data_len);
551                   hdr = (radius_packet_t *) packet->data;
552
553                   total_length = htons(total_length);
554                   memcpy(hdr->length, &total_length, sizeof(u_short));
555
556                   /*
557                    *    If this is not an authentication request, we
558                    *    need to calculate the md5 hash over the entire packet
559                    *    and put it in the vector.
560                    */
561                   secretlen = strlen(secret);
562
563                   /*
564                    *    If there's a Message-Authenticator, update it
565                    *    now, BEFORE updating the authentication vector.
566                    */
567                   if (msg_auth_offset) {
568                           uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
569
570                           switch (packet->code) {
571                           default:
572                                   break;
573
574                           case PW_AUTHENTICATION_ACK:
575                           case PW_AUTHENTICATION_REJECT:
576                           case PW_ACCESS_CHALLENGE:
577                                   /* this was checked above */
578                                   memcpy(hdr->vector, original->vector,
579                                          AUTH_VECTOR_LEN);
580                                   break;
581                           }
582
583                           /*
584                            *    Set the authentication vector to zero,
585                            *    calculate the signature, and put it
586                            *    into the Message-Authenticator
587                            *    attribute.
588                            */
589                           memset(packet->data + msg_auth_offset + 2,
590                                  0, AUTH_VECTOR_LEN);
591                           lrad_hmac_md5(packet->data, packet->data_len,
592                                         secret, secretlen, calc_auth_vector);
593                           memcpy(packet->data + msg_auth_offset + 2,
594                                  calc_auth_vector, AUTH_VECTOR_LEN);
595
596                           /*
597                            *    Copy the original request vector back
598                            *    to the raw packet.
599                            */
600                           memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
601                   }
602
603                   /*
604                    *    Switch over the packet code, deciding how to
605                    *    sign the packet.
606                    */
607                   switch (packet->code) {
608                           /*
609                            *    Request packets are not signed, bur
610                            *    have a random authentication vector.
611                            */
612                   case PW_AUTHENTICATION_REQUEST:
613                   case PW_STATUS_SERVER:
614                           break;
615
616                           /*
617                            *    Reply packets are signed with the
618                            *    authentication vector of the request.
619                            */
620                   default:
621                         {
622                                 MD5_CTX context;
623                                 MD5Init(&context);
624                                 MD5Update(&context, packet->data, packet->data_len);
625                                 MD5Update(&context, secret, strlen(secret));
626                                 MD5Final(digest, &context);
627
628                                 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
629                                 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
630                                 break;
631                         }
632                   } /* switch over packet codes */
633
634
635                   /*
636                    *    If packet->data points to data, then we print out
637                    *    the VP list again only for debugging.
638                    */
639         } else if (librad_debug) {
640                 DEBUG("Re-sending %s of id %d to %s:%d\n", what, packet->id,
641                       ip_ntoa((char *)ip_buffer, packet->dst_ipaddr),
642                       packet->dst_port);
643
644                 for (reply = packet->vps; reply; reply = reply->next) {
645                         /* FIXME: ignore attributes > 0xff */
646                         debug_pair(reply);
647                 }
648         }
649
650         /*
651          *      And send it on it's way.
652          */
653         sa = (struct sockaddr_in *) &saremote;
654         memset ((char *) sa, '\0', sizeof (saremote));
655         sa->sin_family = AF_INET;
656         sa->sin_addr.s_addr = packet->dst_ipaddr;
657         sa->sin_port = htons(packet->dst_port);
658 #ifndef WITH_UDPFROMTO
659         return sendto(packet->sockfd, packet->data, (int)packet->data_len, 0,
660                       (struct sockaddr *)&saremote, sizeof(struct sockaddr_in));
661 #else
662         {
663                 struct sockaddr_in salocal;
664                 memset ((char *) &salocal, '\0', sizeof (salocal));
665                 salocal.sin_family = AF_INET;
666                 salocal.sin_addr.s_addr = packet->src_ipaddr;
667                 
668                 return sendfromto(packet->sockfd, packet->data, (int)packet->data_len, 0,
669                                   (struct sockaddr *)&salocal,  sizeof(struct sockaddr_in),
670                                   (struct sockaddr *)&saremote, sizeof(struct sockaddr_in));
671         }
672 #endif
673 }
674
675
676 /*
677  *      Validates the requesting client NAS.  Calculates the
678  *      signature based on the clients private key.
679  */
680 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
681 {
682         u_char          digest[AUTH_VECTOR_LEN];
683         MD5_CTX         context;
684
685         /*
686          *      Older clients have the authentication vector set to
687          *      all zeros. Return `1' in that case.
688          */
689         memset(digest, 0, sizeof(digest));
690         if (memcmp(packet->vector, digest, AUTH_VECTOR_LEN) == 0) {
691                 packet->verified = 1;
692                 return 1;
693         }
694
695         /*
696          *      Zero out the auth_vector in the received packet.
697          *      Then append the shared secret to the received packet,
698          *      and calculate the MD5 sum. This must be the same
699          *      as the original MD5 sum (packet->vector).
700          */
701         memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
702
703         /*
704          *  MD5(packet + secret);
705          */
706         MD5Init(&context);
707         MD5Update(&context, packet->data, packet->data_len);
708         MD5Update(&context, secret, strlen(secret));
709         MD5Final(digest, &context);
710
711         /*
712          *      Return 0 if OK, 2 if not OK.
713          */
714         packet->verified =
715         memcmp(digest, packet->vector, AUTH_VECTOR_LEN) ? 2 : 0;
716
717         return packet->verified;
718 }
719
720 /*
721  *      Validates the requesting client NAS.  Calculates the
722  *      signature based on the clients private key.
723  */
724 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
725                             const char *secret)
726 {
727         uint8_t         calc_digest[AUTH_VECTOR_LEN];
728         MD5_CTX         context;
729
730         /*
731          *      Very bad!
732          */
733         if (original == NULL) {
734                 return 3;
735         }
736
737         /*
738          *  Copy the original vector in place.
739          */
740         memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
741
742         /*
743          *  MD5(packet + secret);
744          */
745         MD5Init(&context);
746         MD5Update(&context, packet->data, packet->data_len);
747         MD5Update(&context, secret, strlen(secret));
748         MD5Final(calc_digest, &context);
749
750         /*
751          *  Copy the packet's vector back to the packet.
752          */
753         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
754
755         /*
756          *      Return 0 if OK, 2 if not OK.
757          */
758         packet->verified =
759                 memcmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) ? 2 : 0;
760         return packet->verified;
761 }
762
763 /*
764  *      Receive UDP client requests, and fill in
765  *      the basics of a RADIUS_PACKET structure.
766  */
767 RADIUS_PACKET *rad_recv(int fd)
768 {
769         RADIUS_PACKET           *packet;
770         struct sockaddr_in      saremote;
771         int                     totallen;
772         socklen_t               salen;
773         uint8_t                 *attr;
774         int                     count;
775         radius_packet_t         *hdr;
776         char                    host_ipaddr[16];
777         int                     seen_eap;
778         uint8_t                 data[MAX_PACKET_LEN];
779         int                     num_attributes;
780
781         /*
782          *      Allocate the new request data structure
783          */
784         if ((packet = malloc(sizeof(RADIUS_PACKET))) == NULL) {
785                 librad_log("out of memory");
786                 return NULL;
787         }
788         memset(packet, 0, sizeof(RADIUS_PACKET));
789
790         /*
791          *      Receive the packet.
792          */
793         salen = sizeof(saremote);
794         memset(&saremote, 0, sizeof(saremote));
795 #ifndef WITH_UDPFROMTO
796         packet->data_len = recvfrom(fd, data, sizeof(data),
797                                     0, (struct sockaddr *)&saremote, &salen);
798         packet->dst_ipaddr = htonl(INADDR_ANY); /* i.e. unknown */
799 #else
800         {
801                 socklen_t               salen_local;
802                 struct sockaddr_in      salocal;
803                 salen_local = sizeof(salocal);
804                 memset(&salocal, 0, sizeof(salocal));
805                 packet->data_len = recvfromto(fd, data, sizeof(data), 0,
806                                               (struct sockaddr *)&saremote, &salen,
807                                               (struct sockaddr *)&salocal, &salen_local);
808                 packet->dst_ipaddr = salocal.sin_addr.s_addr;
809         }
810 #endif
811
812         /*
813          *      Check for socket errors.
814          */
815         if (packet->data_len < 0) {
816                 librad_log("Error receiving packet: %s", strerror(errno));
817                 free(packet);
818                 return NULL;
819         }
820
821         /*
822          *      Fill IP header fields.  We need these for the error
823          *      messages which may come later.
824          */
825         packet->sockfd = fd;
826         packet->src_ipaddr = saremote.sin_addr.s_addr;
827         packet->src_port = ntohs(saremote.sin_port);
828
829         /*
830          *      FIXME: Do even more filtering by only permitting
831          *      certain IP's.  The problem is that we don't know
832          *      how to do this properly for all possible clients...
833          */
834
835         /*
836          *      Explicitely set the VP list to empty.
837          */
838         packet->vps = NULL;
839
840         /*
841          *      Check for packets smaller than the packet header.
842          *
843          *      RFC 2865, Section 3., subsection 'length' says:
844          *
845          *      "The minimum length is 20 ..."
846          */
847         if (packet->data_len < AUTH_HDR_LEN) {
848                 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
849                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
850                            packet->data_len, AUTH_HDR_LEN);
851                 free(packet);
852                 return NULL;
853         }
854
855         /*
856          *      RFC 2865, Section 3., subsection 'length' says:
857          *
858          *      " ... and maximum length is 4096."
859          */
860         if (packet->data_len > MAX_PACKET_LEN) {
861                 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
862                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
863                            packet->data_len, MAX_PACKET_LEN);
864                 free(packet);
865                 return NULL;
866         }
867
868         /*
869          *      Check for packets with mismatched size.
870          *      i.e. We've received 128 bytes, and the packet header
871          *      says it's 256 bytes long.
872          */
873         totallen = (data[2] << 8) | data[3];
874         hdr = (radius_packet_t *)data;
875
876         /*
877          *      Code of 0 is not understood.
878          *      Code of 16 or greate is not understood.
879          */
880         if ((hdr->code == 0) ||
881             (hdr->code >= 52)) {
882                 librad_log("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
883                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
884                            hdr->code);
885                 free(packet);
886                 return NULL;
887         }
888
889         /*
890          *      Repeat the length checks.  This time, instead of
891          *      looking at the data we received, look at the value
892          *      of the 'length' field inside of the packet.
893          *
894          *      Check for packets smaller than the packet header.
895          *
896          *      RFC 2865, Section 3., subsection 'length' says:
897          *
898          *      "The minimum length is 20 ..."
899          */
900         if (totallen < AUTH_HDR_LEN) {
901                 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
902                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
903                            totallen, AUTH_HDR_LEN);
904                 free(packet);
905                 return NULL;
906         }
907
908         /*
909          *      And again, for the value of the 'length' field.
910          *
911          *      RFC 2865, Section 3., subsection 'length' says:
912          *
913          *      " ... and maximum length is 4096."
914          */
915         if (totallen > MAX_PACKET_LEN) {
916                 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
917                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
918                            totallen, MAX_PACKET_LEN);
919                 free(packet);
920                 return NULL;
921         }
922
923         /*
924          *      RFC 2865, Section 3., subsection 'length' says:
925          *
926          *      "If the packet is shorter than the Length field
927          *      indicates, it MUST be silently discarded."
928          *
929          *      i.e. No response to the NAS.
930          */
931         if (packet->data_len < totallen) {
932                 librad_log("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
933                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
934                            packet->data_len, totallen);
935                 free(packet);
936                 return NULL;
937         }
938
939         /*
940          *      RFC 2865, Section 3., subsection 'length' says:
941          *
942          *      "Octets outside the range of the Length field MUST be
943          *      treated as padding and ignored on reception."
944          */
945         if (packet->data_len > totallen) {
946                 /*
947                  *      We're shortening the packet below, but just
948                  *      to be paranoid, zero out the extra data.
949                  */
950                 memset(data + totallen, 0, packet->data_len - totallen);
951                 packet->data_len = totallen;
952         }
953
954         /*
955          *      Walk through the packet's attributes, ensuring that
956          *      they add up EXACTLY to the size of the packet.
957          *
958          *      If they don't, then the attributes either under-fill
959          *      or over-fill the packet.  Any parsing of the packet
960          *      is impossible, and will result in unknown side effects.
961          *
962          *      This would ONLY happen with buggy RADIUS implementations,
963          *      or with an intentional attack.  Either way, we do NOT want
964          *      to be vulnerable to this problem.
965          */
966         attr = hdr->data;
967         count = totallen - AUTH_HDR_LEN;
968         seen_eap = 0;
969         num_attributes = 0;
970
971         while (count > 0) {
972                 /*
973                  *      Attribute number zero is NOT defined.
974                  */
975                 if (attr[0] == 0) {
976                         librad_log("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
977                                    ip_ntoa(host_ipaddr, packet->src_ipaddr));
978                         free(packet);
979                         return NULL;
980                 }
981
982                 /*
983                  *      Attributes are at LEAST as long as the ID & length
984                  *      fields.  Anything shorter is an invalid attribute.
985                  */
986                 if (attr[1] < 2) {
987                         librad_log("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
988                                    ip_ntoa(host_ipaddr, packet->src_ipaddr),
989                                    attr[0]);
990                         free(packet);
991                         return NULL;
992                 }
993
994                 /*
995                  *      Sanity check the attributes for length.
996                  */
997                 switch (attr[0]) {
998                 default:        /* don't do anything by default */
999                         break;
1000
1001                 case PW_EAP_MESSAGE:
1002                         seen_eap |= PW_EAP_MESSAGE;
1003                         break;
1004
1005                 case PW_MESSAGE_AUTHENTICATOR:
1006                         if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1007                                 librad_log("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1008                                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
1009                                            attr[1] - 2);
1010                                 free(packet);
1011                                 return NULL;
1012                         }
1013                         seen_eap |= PW_MESSAGE_AUTHENTICATOR;
1014                         break;
1015
1016                 case PW_VENDOR_SPECIFIC:
1017                         if (attr[1] <= 6) {
1018                                 librad_log("WARNING: Malformed RADIUS packet from host %s: Vendor-Specific has invalid length %d",
1019                                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
1020                                            attr[1] - 2);
1021                                 free(packet);
1022                                 return NULL;
1023                         }
1024
1025                         /*
1026                          *      Don't allow VSA's with vendor zero.
1027                          */
1028                         if ((attr[2] == 0) && (attr[3] == 0) &&
1029                             (attr[4] == 0) && (attr[5] == 0)) {
1030                                 librad_log("WARNING: Malformed RADIUS packet from host %s: Vendor-Specific has vendor ID of zero",
1031                                            ip_ntoa(host_ipaddr, packet->src_ipaddr));
1032                                 free(packet);
1033                                 return NULL;
1034                         }
1035
1036                         /*
1037                          *      Don't look at the contents of VSA's,
1038                          *      too many vendors have non-standard
1039                          *      formats.
1040                          */
1041                         break;
1042                 }
1043
1044                 /*
1045                  *      FIXME: Look up the base 255 attributes in the
1046                  *      dictionary, and switch over their type.  For
1047                  *      integer/date/ip, the attribute length SHOULD
1048                  *      be 6.
1049                  */
1050                 count -= attr[1];       /* grab the attribute length */
1051                 attr += attr[1];
1052                 num_attributes++;       /* seen one more attribute */
1053         }
1054
1055         /*
1056          *      If the attributes add up to a packet, it's allowed.
1057          *
1058          *      If not, we complain, and throw the packet away.
1059          */
1060         if (count != 0) {
1061                 librad_log("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1062                            ip_ntoa(host_ipaddr, packet->src_ipaddr));
1063                 free(packet);
1064                 return NULL;
1065         }
1066
1067         /*
1068          *      If we're configured to look for a maximum number of
1069          *      attributes, and we've seen more than that maximum,
1070          *      then throw the packet away, as a possible DoS.
1071          */
1072         if ((librad_max_attributes > 0) &&
1073             (num_attributes > librad_max_attributes)) {
1074                 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1075                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
1076                            num_attributes, librad_max_attributes);
1077                 free(packet);
1078                 return NULL;
1079         }
1080
1081         /*
1082          *      http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1083          *
1084          *      A packet with an EAP-Message attribute MUST also have
1085          *      a Message-Authenticator attribute.
1086          *
1087          *      A Message-Authenticator all by itself is OK, though.
1088          */
1089         if (seen_eap &&
1090             (seen_eap != PW_MESSAGE_AUTHENTICATOR) &&
1091             (seen_eap != (PW_EAP_MESSAGE | PW_MESSAGE_AUTHENTICATOR))) {
1092                 librad_log("WARNING: Insecure packet from host %s:  Received EAP-Message with no Message-Authenticator.",
1093                            ip_ntoa(host_ipaddr, packet->src_ipaddr));
1094                 free(packet);
1095                 return NULL;
1096         }
1097
1098         if (librad_debug) {
1099                 if ((hdr->code > 0) && (hdr->code < 52)) {
1100                         printf("rad_recv: %s packet from host %s:%d",
1101                                packet_codes[hdr->code],
1102                                ip_ntoa(host_ipaddr, packet->src_ipaddr), packet->src_port);
1103                 } else {
1104                         printf("rad_recv: Packet from host %s:%d code=%d",
1105                                ip_ntoa(host_ipaddr, packet->src_ipaddr), packet->src_port,
1106                                hdr->code);
1107                 }
1108                 printf(", id=%d, length=%d\n", hdr->id, totallen);
1109         }
1110
1111         /*
1112          *      Fill RADIUS header fields
1113          */
1114         packet->code = hdr->code;
1115         packet->id = hdr->id;
1116         memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1117
1118         /*
1119          *  Now that we've sanity checked the packet, we can allocate
1120          *  memory for it, and copy the data from the local area to
1121          *  the packet buffer.
1122          */
1123         if ((packet->data = malloc(packet->data_len)) == NULL) {
1124           free(packet);
1125           librad_log("out of memory");
1126           return NULL;
1127         }
1128         memcpy(packet->data, data, packet->data_len);
1129
1130         return packet;
1131 }
1132
1133 /*
1134  *      Calculate/check digest, and decode radius attributes.
1135  */
1136 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1137                const char *secret)
1138 {
1139         uint32_t                lvalue;
1140         uint32_t                vendorcode;
1141         VALUE_PAIR              **tail;
1142         VALUE_PAIR              *pair;
1143         uint8_t                 *ptr;
1144         int                     length;
1145         int                     attribute;
1146         int                     attrlen;
1147         int                     vendorlen;
1148         radius_packet_t         *hdr;
1149
1150         hdr = (radius_packet_t *)packet->data;
1151
1152         /*
1153          *      Before we allocate memory for the attributes, do more
1154          *      sanity checking.
1155          */
1156         ptr = hdr->data;
1157         length = packet->data_len - AUTH_HDR_LEN;
1158         while (length > 0) {
1159                 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1160                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1161
1162                 attrlen = ptr[1];
1163
1164                 switch (ptr[0]) {
1165                 default:        /* don't do anything. */
1166                         break;
1167
1168                         /*
1169                          *      Note that more than one Message-Authenticator
1170                          *      attribute is invalid.
1171                          */
1172                 case PW_MESSAGE_AUTHENTICATOR:
1173                         memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1174                         memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1175
1176                         switch (packet->code) {
1177                         default:
1178                           break;
1179
1180                         case PW_AUTHENTICATION_ACK:
1181                         case PW_AUTHENTICATION_REJECT:
1182                         case PW_ACCESS_CHALLENGE:
1183                           if (!original) {
1184                                   librad_log("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1185                                   return -1;
1186                           }
1187                           memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1188                           break;
1189                         }
1190
1191                         lrad_hmac_md5(packet->data, packet->data_len,
1192                                       secret, strlen(secret), calc_auth_vector);
1193                         if (memcmp(calc_auth_vector, msg_auth_vector,
1194                                     sizeof(calc_auth_vector)) != 0) {
1195                                 char buffer[32];
1196                                 librad_log("Received packet from %s with invalid Message-Authenticator!  (Shared secret is incorrect.)",
1197                                            ip_ntoa(buffer, packet->src_ipaddr));
1198                                 return -1;
1199                         } /* else the message authenticator was good */
1200
1201                         /*
1202                          *      Reinitialize Authenticators.
1203                          */
1204                         memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
1205                         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1206                         break;
1207                 } /* switch over the attributes */
1208
1209                 ptr += attrlen;
1210                 length -= attrlen;
1211         } /* loop over the packet, sanity checking the attributes */
1212
1213         /*
1214          *      Calculate and/or verify digest.
1215          */
1216         switch(packet->code) {
1217                 int rcode;
1218
1219                 case PW_AUTHENTICATION_REQUEST:
1220                 case PW_STATUS_SERVER:
1221                 case PW_DISCONNECT_REQUEST:
1222                         /*
1223                          *      The authentication vector is random
1224                          *      nonsense, invented by the client.
1225                          */
1226                         break;
1227
1228                 case PW_ACCOUNTING_REQUEST:
1229                         if (calc_acctdigest(packet, secret) > 1) {
1230                                 char buffer[32];
1231                                 librad_log("Received Accounting-Request packet "
1232                                     "from %s with invalid signature!  (Shared secret is incorrect.)",
1233                                     ip_ntoa(buffer, packet->src_ipaddr));
1234                                 return -1;
1235                         }
1236                         break;
1237
1238                         /* Verify the reply digest */
1239                 case PW_AUTHENTICATION_ACK:
1240                 case PW_AUTHENTICATION_REJECT:
1241                 case PW_ACCOUNTING_RESPONSE:
1242                         rcode = calc_replydigest(packet, original, secret);
1243                         if (rcode > 1) {
1244                                 char buffer[32];
1245                                 librad_log("Received %s packet "
1246                                            "from %s:%d with invalid signature (err=%d)!  (Shared secret is incorrect.)",
1247                                            packet_codes[packet->code],
1248                                            ip_ntoa(buffer, packet->src_ipaddr),
1249                                            packet->src_port,
1250                                            rcode);
1251                                 return -1;
1252                         }
1253                   break;
1254         }
1255
1256         /*
1257          *      Extract attribute-value pairs
1258          */
1259         ptr = hdr->data;
1260         length = packet->data_len - AUTH_HDR_LEN;
1261
1262         /*
1263          *      There may be VP's already in the packet.  Don't
1264          *      destroy them.
1265          */
1266         for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
1267                 /* nothing */
1268         }
1269
1270         vendorcode = 0;
1271         vendorlen  = 0;
1272
1273         while (length > 0) {
1274                 if (vendorlen > 0) {
1275                         attribute = *ptr++ | (vendorcode << 16);
1276                         attrlen   = *ptr++;
1277                 } else {
1278                         attribute = *ptr++;
1279                         attrlen   = *ptr++;
1280                 }
1281
1282                 attrlen -= 2;
1283                 length  -= 2;
1284
1285                 /*
1286                  *      This could be a Vendor-Specific attribute.
1287                  */
1288                 if ((vendorlen <= 0) &&
1289                     (attribute == PW_VENDOR_SPECIFIC)) {
1290                         int     sublen;
1291                         uint8_t *subptr;
1292
1293                         /*
1294                          *      attrlen was checked to be >= 6, in rad_recv
1295                          */
1296                         memcpy(&lvalue, ptr, 4);
1297                         vendorcode = ntohl(lvalue);
1298
1299                         /*
1300                          *      This is an implementation issue.
1301                          *      We currently pack vendor into the upper
1302                          *      16 bits of a 32-bit attribute number,
1303                          *      so we can't handle vendor numbers larger
1304                          *      than 16 bits.
1305                          */
1306                         if (vendorcode > 65535) goto create_pair;
1307
1308                         /*
1309                          *      vendorcode was checked to be non-zero
1310                          *      above, in rad_recv.
1311                          */
1312
1313                         /*
1314                          *      First, check to see if the
1315                          *      sub-attributes fill the VSA, as
1316                          *      defined by the RFC.  If not, then it
1317                          *      may be a USR-style VSA, or it may be a
1318                          *      vendor who packs all of the
1319                          *      information into one nonsense
1320                          *      attribute
1321                          */
1322                         subptr = ptr + 4;
1323                         sublen = attrlen - 4;
1324
1325                         while (sublen > 0) {
1326                                 if (subptr[1] < 2) { /* too short */
1327                                         break;
1328                                 }
1329
1330                                 if (subptr[1] > sublen) { /* too long */
1331                                         break;
1332                                 }
1333
1334                                 sublen -= subptr[1]; /* just right */
1335                                 subptr += subptr[1];
1336                         }
1337
1338                         /*
1339                          *      If the attribute is RFC compatible,
1340                          *      then allow it as an RFC style VSA.
1341                          */
1342                         if (sublen == 0) {
1343                                 ptr += 4;
1344                                 vendorlen = attrlen - 4;
1345                                 attribute = *ptr++ | (vendorcode << 16);
1346                                 attrlen   = *ptr++;
1347                                 attrlen -= 2;
1348                                 length -= 6;
1349
1350                                 /*
1351                                  *      USR-style attributes are 4 octets,
1352                                  *      with the upper 2 octets being zero.
1353                                  *
1354                                  *      The upper octets may not be zero,
1355                                  *      but that then means we won't be
1356                                  *      able to pack the vendor & attribute
1357                                  *      into a 32-bit number, so we can't
1358                                  *      handle it.
1359                                  *
1360                                  *
1361                                  *      FIXME: Update the dictionaries so
1362                                  *      that we key off of per-attribute
1363                                  *      flags "4-octet", instead of hard
1364                                  *      coding USR here.  This will also
1365                                  *      let us send packets with other
1366                                  *      vendors having 4-octet attributes.
1367                                  */
1368                         } else if ((vendorcode == VENDORPEC_USR) &&
1369                                    ((ptr[4] == 0) && (ptr[5] == 0)) &&
1370                                    (attrlen >= 8)) {
1371                                 DICT_ATTR *da;
1372
1373                                 da = dict_attrbyvalue((vendorcode << 16) |
1374                                                       (ptr[6] << 8) |
1375                                                       ptr[7]);
1376
1377                                 /*
1378                                  *      See if it's in the dictionary.
1379                                  *      If so, it's a valid USR style
1380                                  *      attribute.  If not, it's not...
1381                                  *
1382                                  *      Don't touch 'attribute' until
1383                                  *      we know what to do!
1384                                  */
1385                                 if (da != NULL) {
1386                                         attribute = ((vendorcode << 16) |
1387                                                      (ptr[6] << 8) |
1388                                                      ptr[7]);
1389                                         ptr += 8;
1390                                         attrlen -= 8;
1391                                         length -= 8;
1392                                 } /* else it's not in the dictionary */
1393                         } /* else it was a stupid vendor format */
1394                 } /* else it wasn't a VSA */
1395
1396                 /*
1397                  *      Create the attribute, setting the default type
1398                  *      to 'octects'.  If the type in the dictionary
1399                  *      is different, then the dictionary type will
1400                  *      over-ride this one.
1401                  */
1402         create_pair:
1403                 if ((pair = paircreate(attribute, PW_TYPE_OCTETS)) == NULL) {
1404                         pairfree(&packet->vps);
1405                         librad_log("out of memory");
1406                         return -1;
1407                 }
1408
1409                 pair->length = attrlen;
1410                 pair->operator = T_OP_EQ;
1411                 pair->next = NULL;
1412
1413                 switch (pair->type) {
1414
1415                         /*
1416                          *      The attribute may be zero length,
1417                          *      or it may have a tag, and then no data...
1418                          */
1419                 case PW_TYPE_STRING:
1420                         if (pair->flags.has_tag) {
1421                                 int offset = 0;
1422
1423                                 /*
1424                                  *      If there's sufficient room for
1425                                  *      a tag, and the tag looks valid,
1426                                  *      then use it.
1427                                  */
1428                                 if ((pair->length > 0) &&
1429                                     TAG_VALID_ZERO(*ptr)) {
1430                                         pair->flags.tag = *ptr;
1431                                         pair->length--;
1432                                         offset = 1;
1433
1434                                         /*
1435                                          *      If the leading tag
1436                                          *      isn't valid, then it's
1437                                          *      ignored for the tunnel
1438                                          *      password attribute.
1439                                          */
1440                                 } else if (pair->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD) {
1441                                         /*
1442                                          * from RFC2868 - 3.5.  Tunnel-Password
1443                                          * If the value of the Tag field is greater than
1444                                          * 0x00 and less than or equal to 0x1F, it SHOULD
1445                                          * be interpreted as indicating which tunnel
1446                                          * (of several alternatives) this attribute pertains;
1447                                          * otherwise, the Tag field SHOULD be ignored.
1448                                          */
1449                                         pair->flags.tag = 0x00;
1450                                         if (pair->length > 0) pair->length--;
1451                                         offset = 1;
1452                                 } else {
1453                                        pair->flags.tag = 0x00;
1454                                 }
1455
1456                                 /*
1457                                  *      pair->length MAY be zero here.
1458                                  */
1459                                 memcpy(pair->strvalue, ptr + offset,
1460                                        pair->length);
1461                         } else {
1462                           /*
1463                            *    Ascend binary attributes never have a
1464                            *    tag, and neither do the 'octets' type.
1465                            */
1466                         case PW_TYPE_ABINARY:
1467                         case PW_TYPE_OCTETS:
1468                                 /* attrlen always < MAX_STRING_LEN */
1469                                 memcpy(pair->strvalue, ptr, attrlen);
1470                                 pair->flags.tag = 0;
1471                         }
1472
1473                         /*
1474                          *      Decrypt passwords here.
1475                          */
1476                         switch (pair->flags.encrypt) {
1477                         default:
1478                                 break;
1479
1480                                 /*
1481                                  *  User-Password
1482                                  */
1483                         case FLAG_ENCRYPT_USER_PASSWORD:
1484                                 if (original) {
1485                                         rad_pwdecode((char *)pair->strvalue,
1486                                                      pair->length, secret,
1487                                                      (char *)original->vector);
1488                                 } else {
1489                                         rad_pwdecode((char *)pair->strvalue,
1490                                                      pair->length, secret,
1491                                                      (char *)packet->vector);
1492                                 }
1493                                 if (pair->attribute == PW_USER_PASSWORD) {
1494                                         pair->length = strlen(pair->strvalue);
1495                                 }
1496                                 break;
1497
1498                                 /*
1499                                  *      Tunnel-Password's may go ONLY
1500                                  *      in response packets.
1501                                  */
1502                         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
1503                                 if (!original) {
1504                                         librad_log("ERROR: Tunnel-Password attribute in request: Cannot decrypt it.");
1505                                         free(pair);
1506                                         return -1;
1507                                 }
1508                                 if (rad_tunnel_pwdecode(pair->strvalue,
1509                                                         &pair->length,
1510                                                         secret,
1511                                                         (char *)original->vector) < 0) {
1512                                         free(pair);
1513                                         return -1;
1514                                 }
1515                                 break;
1516
1517                                 /*
1518                                  *  Ascend-Send-Secret
1519                                  *  Ascend-Receive-Secret
1520                                  */
1521                         case FLAG_ENCRYPT_ASCEND_SECRET:
1522                                 if (!original) {
1523                                         librad_log("ERROR: Ascend-Send-Secret attribute in request: Cannot decrypt it.");
1524                                         free(pair);
1525                                         return -1;
1526                                 } else {
1527                                         uint8_t my_digest[AUTH_VECTOR_LEN];
1528                                         make_secret(my_digest,
1529                                                     original->vector,
1530                                                     secret, ptr);
1531                                         memcpy(pair->strvalue, my_digest,
1532                                                AUTH_VECTOR_LEN );
1533                                         pair->strvalue[AUTH_VECTOR_LEN] = '\0';
1534                                         pair->length = strlen(pair->strvalue);
1535                                 }
1536                                 break;
1537                         } /* switch over encryption flags */
1538                         break;  /* from octets/string/abinary */
1539
1540                 case PW_TYPE_INTEGER:
1541                 case PW_TYPE_DATE:
1542                 case PW_TYPE_IPADDR:
1543                         /*
1544                          *      Check for RFC compliance.  If the
1545                          *      attribute isn't compliant, turn it
1546                          *      into a string of raw octets.
1547                          *
1548                          *      Also set the lvalue to something
1549                          *      which should never match anything.
1550                          */
1551                         if (attrlen != 4) {
1552                                 pair->type = PW_TYPE_OCTETS;
1553                                 memcpy(pair->strvalue, ptr, attrlen);
1554                                 pair->lvalue = 0xbad1bad1;
1555                                 break;
1556                         }
1557
1558                         memcpy(&lvalue, ptr, 4);
1559
1560                         if (pair->type != PW_TYPE_IPADDR) {
1561                                 pair->lvalue = ntohl(lvalue);
1562                         } else {
1563                                  /*
1564                                   *  It's an IP address, keep it in network
1565                                   *  byte order, and put the ASCII IP
1566                                   *  address or host name into the string
1567                                   *  value.
1568                                   */
1569                                 pair->lvalue = lvalue;
1570                                 ip_ntoa(pair->strvalue, pair->lvalue);
1571                         }
1572
1573                         /*
1574                          *      Tagged attributes of type integer have
1575                          *      special treatment.
1576                          */
1577                         if (pair->flags.has_tag &&
1578                             pair->type == PW_TYPE_INTEGER) {
1579                                 pair->flags.tag = (pair->lvalue >> 24) & 0xff;
1580                                 pair->lvalue &= 0x00ffffff;
1581                         }
1582
1583                         /*
1584                          *      Try to get the name for integer
1585                          *      attributes.
1586                          */
1587                         if (pair->type == PW_TYPE_INTEGER) {
1588                                 DICT_VALUE *dval;
1589                                 dval = dict_valbyattr(pair->attribute,
1590                                                       pair->lvalue);
1591                                 if (dval) {
1592                                         strNcpy(pair->strvalue,
1593                                                 dval->name,
1594                                                 sizeof(pair->strvalue));
1595                                 }
1596                         }
1597                         break;
1598
1599                         /*
1600                          *      IPv6 interface ID is 8 octets long.
1601                          */
1602                 case PW_TYPE_IFID:
1603                         if (attrlen != 8)
1604                                 pair->type = PW_TYPE_OCTETS;
1605                         memcpy(pair->strvalue, ptr, attrlen);
1606                         break;
1607
1608                         /*
1609                          *      IPv6 addresses are 16 octets long
1610                          */
1611                 case PW_TYPE_IPV6ADDR:
1612                         if (attrlen != 16)
1613                                 pair->type = PW_TYPE_OCTETS;
1614                         memcpy(pair->strvalue, ptr, attrlen);
1615                         break;
1616
1617                         /*
1618                          *      IPv6 prefixes are 2 to 18 octets long.
1619                          *
1620                          *      RFC 3162: The first octet is unused.
1621                          *      The second is the length of the prefix
1622                          *      the rest are the prefix data.
1623                          *
1624                          *      The prefix length can have value 0 to 128.
1625                          */
1626                 case PW_TYPE_IPV6PREFIX:
1627                         if (attrlen < 2 || attrlen > 18)
1628                                 pair->type = PW_TYPE_OCTETS;
1629                         if (attrlen >= 2) {
1630                                 if (ptr[1] > 128) {
1631                                         pair->type = PW_TYPE_OCTETS;
1632                                 }
1633                                 /*
1634                                  *      FIXME: double-check that
1635                                  *      (ptr[1] >> 3) matches attrlen + 2
1636                                  */
1637                         }
1638                         memcpy(pair->strvalue, ptr, attrlen);
1639                         break;
1640
1641                 default:
1642                         DEBUG("    %s (Unknown Type %d)\n",
1643                               pair->name, pair->type);
1644                         free(pair);
1645                         pair = NULL;
1646                         break;
1647                 }
1648
1649                 if (pair) {
1650                         debug_pair(pair);
1651                         *tail = pair;
1652                         tail = &pair->next;
1653                 }
1654
1655                 ptr += attrlen;
1656                 length -= attrlen;
1657                 if (vendorlen > 0) vendorlen -= (attrlen + 2);
1658         }
1659
1660         /*
1661          *      Merge information from the outside world into our
1662          *      random pool
1663          */
1664         for (length = 0; length < AUTH_VECTOR_LEN; length++) {
1665                 lrad_rand_pool.randmem[length] += packet->vector[length];
1666         }
1667         lrad_rand_pool.randmem[lrad_rand_pool.randmem[0] & 0xff] += packet->id;
1668         lrad_rand_pool.randmem[lrad_rand_pool.randmem[1] & 0xff] += packet->data_len;
1669
1670         return 0;
1671 }
1672
1673
1674 /*
1675  *      Encode password.
1676  *
1677  *      We assume that the passwd buffer passed is big enough.
1678  *      RFC2138 says the password is max 128 chars, so the size
1679  *      of the passwd buffer must be at least 129 characters.
1680  *      Preferably it's just MAX_STRING_LEN.
1681  *
1682  *      int *pwlen is updated to the new length of the encrypted
1683  *      password - a multiple of 16 bytes.
1684  */
1685 #define AUTH_PASS_LEN (16)
1686 int rad_pwencode(char *passwd, int *pwlen, const char *secret,
1687                  const char *vector)
1688 {
1689         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 1];
1690         char    digest[AUTH_VECTOR_LEN];
1691         int     i, n, secretlen;
1692         int     len;
1693
1694         /*
1695          *      Pad password to multiple of AUTH_PASS_LEN bytes.
1696          */
1697         len = *pwlen;
1698         if (len > 128) len = 128;
1699         *pwlen = len;
1700         if (len % AUTH_PASS_LEN != 0) {
1701                 n = AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
1702                 for (i = len; n > 0; n--, i++)
1703                         passwd[i] = 0;
1704                 len = *pwlen = i;
1705
1706         } else if (len == 0) {
1707                 memset(passwd, 0, AUTH_PASS_LEN);
1708                 *pwlen = len = AUTH_PASS_LEN;
1709         }
1710
1711         /*
1712          *      Use the secret to setup the decryption digest
1713          */
1714         secretlen = strlen(secret);
1715         memcpy(buffer, secret, secretlen);
1716         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
1717         librad_md5_calc((u_char *)digest, buffer, secretlen + AUTH_VECTOR_LEN);
1718
1719         /*
1720          *      Now we can encode the password *in place*
1721          */
1722         for (i = 0; i < AUTH_PASS_LEN; i++)
1723                 passwd[i] ^= digest[i];
1724
1725         if (len <= AUTH_PASS_LEN) return 0;
1726
1727         /*
1728          *      Length > AUTH_PASS_LEN, so we need to use the extended
1729          *      algorithm.
1730          */
1731         for (n = 0; n < 128 && n <= (len - AUTH_PASS_LEN); n += AUTH_PASS_LEN) {
1732                 memcpy(buffer + secretlen, passwd + n, AUTH_PASS_LEN);
1733                 librad_md5_calc((u_char *)digest, buffer, secretlen + AUTH_PASS_LEN);
1734                 for (i = 0; i < AUTH_PASS_LEN; i++)
1735                         passwd[i + n + AUTH_PASS_LEN] ^= digest[i];
1736         }
1737
1738         return 0;
1739 }
1740
1741 /*
1742  *      Decode password.
1743  */
1744 int rad_pwdecode(char *passwd, int pwlen, const char *secret,
1745                  const char *vector)
1746 {
1747         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 1];
1748         char    digest[AUTH_VECTOR_LEN];
1749         char    r[AUTH_VECTOR_LEN];
1750         char    *s;
1751         int     i, n, secretlen;
1752         int     rlen;
1753
1754         /*
1755          *      Use the secret to setup the decryption digest
1756          */
1757         secretlen = strlen(secret);
1758         memcpy(buffer, secret, secretlen);
1759         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
1760         librad_md5_calc((u_char *)digest, buffer, secretlen + AUTH_VECTOR_LEN);
1761
1762         /*
1763          *      Now we can decode the password *in place*
1764          */
1765         memcpy(r, passwd, AUTH_PASS_LEN);
1766         for (i = 0; i < AUTH_PASS_LEN && i < pwlen; i++)
1767                 passwd[i] ^= digest[i];
1768
1769         if (pwlen <= AUTH_PASS_LEN) {
1770                 passwd[pwlen+1] = 0;
1771                 return pwlen;
1772         }
1773
1774         /*
1775          *      Length > AUTH_PASS_LEN, so we need to use the extended
1776          *      algorithm.
1777          */
1778         rlen = ((pwlen - 1) / AUTH_PASS_LEN) * AUTH_PASS_LEN;
1779
1780         for (n = rlen; n > 0; n -= AUTH_PASS_LEN ) {
1781                 s = (n == AUTH_PASS_LEN) ? r : (passwd + n - AUTH_PASS_LEN);
1782                 memcpy(buffer + secretlen, s, AUTH_PASS_LEN);
1783                 librad_md5_calc((u_char *)digest, buffer, secretlen + AUTH_PASS_LEN);
1784                 for (i = 0; i < AUTH_PASS_LEN && (i + n) < pwlen; i++)
1785                         passwd[i + n] ^= digest[i];
1786         }
1787         passwd[pwlen] = 0;
1788
1789         return pwlen;
1790 }
1791
1792 static unsigned int salt_offset = 0;
1793
1794 /*
1795  *      Encode Tunnel-Password attributes when sending them out on the wire.
1796  *
1797  *      int *pwlen is updated to the new length of the encrypted
1798  *      password - a multiple of 16 bytes.
1799  *
1800  *      This is per RFC-2868 which adds a two char SALT to the initial intermediate
1801  *      value MD5 hash.
1802  */
1803 int rad_tunnel_pwencode(char *passwd, int *pwlen, const char *secret,
1804                         const char *vector)
1805 {
1806         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
1807         unsigned char   digest[AUTH_VECTOR_LEN];
1808         char*   salt;
1809         int     i, n, secretlen;
1810         unsigned len, n2;
1811
1812         len = *pwlen;
1813
1814         if (len > 127) len = 127;
1815         /*
1816          * Shift the password 3 positions right to place a salt and original
1817          * length, tag will be added automatically on packet send
1818          */
1819         for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
1820         salt = passwd;
1821         passwd += 2;
1822         /*
1823          * save original password length as first password character;
1824          */
1825         *passwd = len;
1826         len += 1;
1827
1828
1829         /*
1830          *      Generate salt.  The RFC's say:
1831          *
1832          *      The high bit of salt[0] must be set, each salt in a
1833          *      packet should be unique, and they should be random
1834          *
1835          *      So, we set the high bit, add in a counter, and then
1836          *      add in some CSPRNG data.  should be OK..
1837          */
1838         salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
1839                    (lrad_rand() & 0x07));
1840         salt[1] = lrad_rand();
1841
1842         /*
1843          *      Padd password to multiple of AUTH_PASS_LEN bytes.
1844          */
1845         n = len % AUTH_PASS_LEN;
1846         if (n) {
1847                 n = AUTH_PASS_LEN - n;
1848                 for (; n > 0; n--, len++)
1849                         passwd[len] = 0;
1850         }
1851         /* set new password length */
1852         *pwlen = len + 2;
1853
1854         /*
1855          *      Use the secret to setup the decryption digest
1856          */
1857         secretlen = strlen(secret);
1858         memcpy(buffer, secret, secretlen);
1859
1860         for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
1861                 if (!n2) {
1862                         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
1863                         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
1864                         librad_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
1865                 } else {
1866                         memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
1867                         librad_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
1868                 }
1869
1870                 for (i = 0; i < AUTH_PASS_LEN; i++) {
1871                         passwd[i + n2] ^= digest[i];
1872                 }
1873         }
1874         passwd[n2] = 0;
1875         return 0;
1876 }
1877
1878 /*
1879  *      Decode Tunnel-Password encrypted attributes.
1880  *
1881  *      Defined in RFC-2868, this uses a two char SALT along with the
1882  *      initial intermediate value, to differentiate it from the
1883  *      above.
1884  */
1885 int rad_tunnel_pwdecode(uint8_t *passwd, int *pwlen, const char *secret,
1886                         const char *vector)
1887 {
1888         uint8_t         buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
1889         uint8_t         digest[AUTH_VECTOR_LEN];
1890         uint8_t         decrypted[MAX_STRING_LEN + 1];
1891         int             secretlen;
1892         unsigned        i, n, len;
1893
1894         len = *pwlen;
1895
1896         /*
1897          *      We need at least a salt.
1898          */
1899         if (len < 2) {
1900                 librad_log("tunnel password is too short");
1901                 return -1;
1902         }
1903
1904         /*
1905          *      There's a salt, but no password.  Or, there's a salt
1906          *      and a 'data_len' octet.  It's wrong, but at least we
1907          *      can figure out what it means: the password is empty.
1908          *
1909          *      Note that this means we ignore the 'data_len' field,
1910          *      if the attribute length tells us that there's no
1911          *      more data.  So the 'data_len' field may be wrong,
1912          *      but that's ok...
1913          */
1914         if (len <= 3) {
1915                 passwd[0] = 0;
1916                 *pwlen = 0;
1917                 return 0;
1918         }
1919
1920         len -= 2;               /* discount the salt */
1921
1922         /*
1923          *      Use the secret to setup the decryption digest
1924          */
1925         secretlen = strlen(secret);
1926
1927         /*
1928          *      Set up the initial key:
1929          *
1930          *       b(1) = MD5(secret + vector + salt)
1931          */
1932         memcpy(buffer, secret, secretlen);
1933         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
1934         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, passwd, 2);
1935         librad_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
1936
1937         /*
1938          *      A quick check: decrypt the first octet of the password,
1939          *      which is the 'data_len' field.  Ensure it's sane.
1940          *
1941          *      'n' doesn't include the 'data_len' octet
1942          *      'len' does.
1943          */
1944         n = passwd[2] ^ digest[0];
1945         if (n >= len) {
1946                 librad_log("tunnel password is too long for the attribute");
1947                 return -1;
1948         }
1949
1950         /*
1951          *      Loop over the data, decrypting it, and generating
1952          *      the key for the next round of decryption.
1953          */
1954         for (n = 0; n < len; n += AUTH_PASS_LEN) {
1955                 for (i = 0; i < AUTH_PASS_LEN; i++) {
1956                         decrypted[n + i] = passwd[n + i + 2] ^ digest[i];
1957
1958                         /*
1959                          *      Encrypted password may not be aligned
1960                          *      on 16 octets, so we catch that here...
1961                          */
1962                         if ((n + i) == len) break;
1963                 }
1964
1965                 /*
1966                  *      Update the digest, based on
1967                  *
1968                  *      b(n) = MD5(secret + cleartext(n-1)
1969                  *
1970                  *      but only if there's more data...
1971                  */
1972                 memcpy(buffer + secretlen, passwd + n + 2, AUTH_PASS_LEN);
1973                 librad_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
1974         }
1975
1976         /*
1977          *      We've already validated the length of the decrypted
1978          *      password.  Copy it back to the caller.
1979          */
1980         memcpy(passwd, decrypted + 1, decrypted[0]);
1981         passwd[decrypted[0]] = 0;
1982         *pwlen = decrypted[0];
1983
1984         return decrypted[0];
1985 }
1986
1987 /*
1988  *      Encode a CHAP password
1989  *
1990  *      FIXME: might not work with Ascend because
1991  *      we use vp->length, and Ascend gear likes
1992  *      to send an extra '\0' in the string!
1993  */
1994 int rad_chap_encode(RADIUS_PACKET *packet, char *output, int id,
1995                     VALUE_PAIR *password)
1996 {
1997         int             i;
1998         char            *ptr;
1999         char            string[MAX_STRING_LEN * 2 + 1];
2000         VALUE_PAIR      *challenge;
2001
2002         /*
2003          *      Sanity check the input parameters
2004          */
2005         if ((packet == NULL) || (password == NULL)) {
2006                 return -1;
2007         }
2008
2009         /*
2010          *      Note that the password VP can be EITHER
2011          *      a User-Password attribute (from a check-item list),
2012          *      or a CHAP-Password attribute (the client asking
2013          *      the library to encode it).
2014          */
2015
2016         i = 0;
2017         ptr = string;
2018         *ptr++ = id;
2019
2020         i++;
2021         memcpy(ptr, password->strvalue, password->length);
2022         ptr += password->length;
2023         i += password->length;
2024
2025         /*
2026          *      Use Chap-Challenge pair if present,
2027          *      Request-Authenticator otherwise.
2028          */
2029         challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
2030         if (challenge) {
2031                 memcpy(ptr, challenge->strvalue, challenge->length);
2032                 i += challenge->length;
2033         } else {
2034                 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
2035                 i += AUTH_VECTOR_LEN;
2036         }
2037
2038         *output = id;
2039         librad_md5_calc((u_char *)output + 1, (u_char *)string, i);
2040
2041         return 0;
2042 }
2043
2044 /*
2045  *      Create a random vector of AUTH_VECTOR_LEN bytes.
2046  */
2047 static void random_vector(uint8_t *vector)
2048 {
2049         int i;
2050
2051         if (!lrad_pool_initialized) {
2052                 memset(&lrad_rand_pool, 0, sizeof(lrad_rand_pool));
2053
2054                 /*
2055                  *      Initialize the state to something, using
2056                  *      numbers which aren't random, but which also
2057                  *      aren't static.
2058                  */
2059                 lrad_rand_pool.randrsl[0] = (uint32_t) &lrad_pool_initialized;
2060                 lrad_rand_pool.randrsl[1] = (uint32_t) &i;
2061                 lrad_rand_pool.randrsl[2] = (uint32_t) vector;
2062
2063                 lrad_randinit(&lrad_rand_pool, 1);
2064                 lrad_pool_initialized = 1;
2065         }
2066
2067         lrad_isaac(&lrad_rand_pool);
2068
2069         /*
2070          *      Copy the random data over.
2071          */
2072         for (i = 0; i < AUTH_VECTOR_LEN; i++) {
2073                 *(vector++) = lrad_rand_pool.randrsl[i] & 0xff;
2074         }
2075 }
2076
2077 /*
2078  *      Return a 32-bit random number.
2079  */
2080 uint32_t lrad_rand(void)
2081 {
2082         uint32_t answer;
2083         static int rand_index = 0;
2084
2085         /*
2086          *      Ensure that the pool is initialized.
2087          */
2088         if (!lrad_pool_initialized) {
2089                 uint8_t vector[AUTH_VECTOR_LEN];
2090
2091                 random_vector(vector);
2092         }
2093
2094         /*
2095          *      Grab an entry from the pool.
2096          */
2097         answer = lrad_rand_pool.randrsl[rand_index];
2098
2099         /*
2100          *      Go to the next entry (wrapping around to zero).
2101          */
2102         rand_index++;
2103         rand_index &= 0xff;
2104
2105         /*
2106          *      Every 256 numbers, churn the pool again.
2107          */
2108         if (rand_index == 0) {
2109                 lrad_isaac(&lrad_rand_pool);
2110         }
2111
2112         return answer;
2113 }
2114
2115 /*
2116  *      Allocate a new RADIUS_PACKET
2117  */
2118 RADIUS_PACKET *rad_alloc(int newvector)
2119 {
2120         RADIUS_PACKET   *rp;
2121
2122         if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
2123                 librad_log("out of memory");
2124                 return NULL;
2125         }
2126         memset(rp, 0, sizeof(RADIUS_PACKET));
2127         if (newvector)
2128                 random_vector(rp->vector);
2129         lrad_rand();
2130
2131         return rp;
2132 }
2133
2134 /*
2135  *      Free a RADIUS_PACKET
2136  */
2137 void rad_free(RADIUS_PACKET **radius_packet_ptr)
2138 {
2139         RADIUS_PACKET *radius_packet;
2140
2141         if (!radius_packet_ptr) return;
2142         radius_packet = *radius_packet_ptr;
2143
2144         if (radius_packet->data) free(radius_packet->data);
2145         if (radius_packet->vps) pairfree(&radius_packet->vps);
2146
2147         free(radius_packet);
2148
2149         *radius_packet_ptr = NULL;
2150 }
2151
2152 /*************************************************************************
2153  *
2154  *      Function: make_secret
2155  *
2156  *      Purpose: Build an encrypted secret value to return in a reply
2157  *               packet.  The secret is hidden by xoring with a MD5 digest
2158  *               created from the shared secret and the authentication
2159  *               vector.  We put them into MD5 in the reverse order from
2160  *               that used when encrypting passwords to RADIUS.
2161  *
2162  *************************************************************************/
2163 static void make_secret(unsigned char *digest, uint8_t *vector,
2164                         const char *secret, char *value)
2165 {
2166         u_char  buffer[256 + AUTH_VECTOR_LEN];
2167         int             secretLen = strlen(secret);
2168         int             i;
2169
2170         memcpy(buffer, vector, AUTH_VECTOR_LEN );
2171         memcpy(buffer + AUTH_VECTOR_LEN, secret, secretLen );
2172
2173         librad_md5_calc(digest, buffer, AUTH_VECTOR_LEN + secretLen );
2174         memset(buffer, 0, sizeof(buffer));
2175
2176         for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
2177                 digest[i] ^= value[i];
2178         }
2179 }