9ebab5fe703ef3a37722b2846b628185c923150e
[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         u_short                 len;
774         uint8_t                 *attr;
775         int                     count;
776         radius_packet_t         *hdr;
777         char                    host_ipaddr[16];
778         int                     seen_eap;
779         uint8_t                 data[MAX_PACKET_LEN];
780         int                     num_attributes;
781         
782         /*
783          *      Allocate the new request data structure
784          */
785         if ((packet = malloc(sizeof(RADIUS_PACKET))) == NULL) {
786                 librad_log("out of memory");
787                 return NULL;
788         }
789         memset(packet, 0, sizeof(RADIUS_PACKET));
790
791         /*
792          *      Receive the packet.
793          */
794         salen = sizeof(saremote);
795         memset(&saremote, 0, sizeof(saremote));
796 #ifndef WITH_UDPFROMTO
797         packet->data_len = recvfrom(fd, data, sizeof(data),
798                 0, (struct sockaddr *)&saremote, &salen);
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         hdr = (radius_packet_t *)data;
874         memcpy(&len, hdr->length, sizeof(u_short));
875         totallen = ntohs(len);
876
877         /*
878          *      Code of 0 is not understood.
879          *      Code of 16 or greate is not understood.
880          */
881         if ((hdr->code == 0) ||
882             (hdr->code >= 52)) {
883                 librad_log("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
884                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
885                            hdr->code);
886                 free(packet);
887                 return NULL;
888         }
889
890         /*
891          *      Repeat the length checks.  This time, instead of
892          *      looking at the data we received, look at the value
893          *      of the 'length' field inside of the packet.
894          *
895          *      Check for packets smaller than the packet header.
896          *
897          *      RFC 2865, Section 3., subsection 'length' says:
898          *
899          *      "The minimum length is 20 ..."
900          */
901         if (totallen < AUTH_HDR_LEN) {
902                 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
903                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
904                            totallen, AUTH_HDR_LEN);
905                 free(packet);
906                 return NULL;
907         }
908
909         /*
910          *      And again, for the value of the 'length' field.
911          *
912          *      RFC 2865, Section 3., subsection 'length' says:
913          *
914          *      " ... and maximum length is 4096."
915          */
916         if (totallen > MAX_PACKET_LEN) {
917                 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
918                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
919                            totallen, MAX_PACKET_LEN);
920                 free(packet);
921                 return NULL;
922         }
923
924         /*
925          *      RFC 2865, Section 3., subsection 'length' says:
926          *
927          *      "If the packet is shorter than the Length field
928          *      indicates, it MUST be silently discarded."
929          *
930          *      i.e. No response to the NAS.
931          */
932         if (packet->data_len < totallen) {
933                 librad_log("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
934                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
935                            packet->data_len, totallen);
936                 free(packet);
937                 return NULL;
938         }
939
940         /*
941          *      RFC 2865, Section 3., subsection 'length' says:
942          *
943          *      "Octets outside the range of the Length field MUST be
944          *      treated as padding and ignored on reception."
945          */
946         if (packet->data_len > totallen) {
947                 /*
948                  *      We're shortening the packet below, but just
949                  *      to be paranoid, zero out the extra data.
950                  */
951                 memset(data + totallen, 0, packet->data_len - totallen);
952                 packet->data_len = totallen;
953         }
954
955         /*
956          *      Walk through the packet's attributes, ensuring that
957          *      they add up EXACTLY to the size of the packet.
958          *
959          *      If they don't, then the attributes either under-fill
960          *      or over-fill the packet.  Any parsing of the packet
961          *      is impossible, and will result in unknown side effects.
962          *
963          *      This would ONLY happen with buggy RADIUS implementations,
964          *      or with an intentional attack.  Either way, we do NOT want
965          *      to be vulnerable to this problem.
966          */
967         attr = hdr->data;
968         count = totallen - AUTH_HDR_LEN;
969         seen_eap = 0;
970         num_attributes = 0;
971
972         while (count > 0) {
973                 /*
974                  *      Attribute number zero is NOT defined.
975                  */
976                 if (attr[0] == 0) {
977                         librad_log("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
978                                    ip_ntoa(host_ipaddr, packet->src_ipaddr));
979                         free(packet);
980                         return NULL;
981                 }
982                 
983                 /*
984                  *      Attributes are at LEAST as long as the ID & length
985                  *      fields.  Anything shorter is an invalid attribute.
986                  */
987                 if (attr[1] < 2) {
988                         librad_log("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
989                                    ip_ntoa(host_ipaddr, packet->src_ipaddr),
990                                    attr[0]);
991                         free(packet);
992                         return NULL;
993                 }
994
995                 /*
996                  *      Sanity check the attributes for length.
997                  */
998                 switch (attr[0]) {
999                 default:        /* don't do anything by default */
1000                         break;
1001
1002                 case PW_EAP_MESSAGE:
1003                         seen_eap |= PW_EAP_MESSAGE;
1004                         break;
1005
1006                 case PW_MESSAGE_AUTHENTICATOR:
1007                         if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1008                                 librad_log("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1009                                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
1010                                            attr[1] - 2);
1011                                 free(packet);
1012                                 return NULL;
1013                         }
1014                         seen_eap |= PW_MESSAGE_AUTHENTICATOR;
1015                         break;
1016                         
1017                 case PW_VENDOR_SPECIFIC:
1018                         if (attr[1] <= 6) {
1019                                 librad_log("WARNING: Malformed RADIUS packet from host %s: Vendor-Specific has invalid length %d",
1020                                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
1021                                            attr[1] - 2);
1022                                 free(packet);
1023                                 return NULL;
1024                         }
1025
1026                         /*
1027                          *      Don't allow VSA's with vendor zero.
1028                          */
1029                         if ((attr[2] == 0) && (attr[3] == 0) &&
1030                             (attr[4] == 0) && (attr[5] == 0)) {
1031                                 librad_log("WARNING: Malformed RADIUS packet from host %s: Vendor-Specific has vendor ID of zero",
1032                                            ip_ntoa(host_ipaddr, packet->src_ipaddr));
1033                                 free(packet);
1034                                 return NULL;
1035                         }
1036
1037                         /*
1038                          *      Don't look at the contents of VSA's,
1039                          *      too many vendors have non-standard
1040                          *      formats.
1041                          */
1042                         break;
1043                 }
1044
1045                 /*
1046                  *      FIXME: Look up the base 255 attributes in the
1047                  *      dictionary, and switch over their type.  For
1048                  *      integer/date/ip, the attribute length SHOULD
1049                  *      be 6.
1050                  */
1051                 count -= attr[1];       /* grab the attribute length */
1052                 attr += attr[1];
1053                 num_attributes++;       /* seen one more attribute */
1054         }
1055
1056         /*
1057          *      If the attributes add up to a packet, it's allowed.
1058          *
1059          *      If not, we complain, and throw the packet away.
1060          */
1061         if (count != 0) {
1062                 librad_log("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1063                            ip_ntoa(host_ipaddr, packet->src_ipaddr));
1064                 free(packet);
1065                 return NULL;
1066         }
1067
1068         /*
1069          *      If we're configured to look for a maximum number of
1070          *      attributes, and we've seen more than that maximum,
1071          *      then throw the packet away, as a possible DoS.
1072          */
1073         if ((librad_max_attributes > 0) &&
1074             (num_attributes > librad_max_attributes)) {
1075                 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1076                            ip_ntoa(host_ipaddr, packet->src_ipaddr),
1077                            num_attributes, librad_max_attributes);
1078                 free(packet);
1079                 return NULL;
1080         }
1081
1082         /*
1083          *      http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1084          *
1085          *      A packet with an EAP-Message attribute MUST also have
1086          *      a Message-Authenticator attribute.
1087          *
1088          *      A Message-Authenticator all by itself is OK, though.
1089          */
1090         if (seen_eap &&
1091             (seen_eap != PW_MESSAGE_AUTHENTICATOR) &&
1092             (seen_eap != (PW_EAP_MESSAGE | PW_MESSAGE_AUTHENTICATOR))) {
1093                 librad_log("WARNING: Insecure packet from host %s:  Received EAP-Message with no Message-Authenticator.",
1094                            ip_ntoa(host_ipaddr, packet->src_ipaddr));
1095                 free(packet);
1096                 return NULL;
1097         }
1098
1099         if (librad_debug) {
1100                 if ((hdr->code > 0) && (hdr->code < 52)) {
1101                         printf("rad_recv: %s packet from host %s:%d",
1102                                packet_codes[hdr->code],
1103                                ip_ntoa(host_ipaddr, packet->src_ipaddr), packet->src_port);
1104                 } else {
1105                         printf("rad_recv: Packet from host %s:%d code=%d",      
1106                                ip_ntoa(host_ipaddr, packet->src_ipaddr), packet->src_port,
1107                                hdr->code);
1108                 }
1109                 printf(", id=%d, length=%d\n", hdr->id, totallen);
1110         }
1111
1112         /*
1113          *      Fill RADIUS header fields
1114          */
1115         packet->code = hdr->code;
1116         packet->id = hdr->id;
1117         memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1118
1119         /*
1120          *  Now that we've sanity checked the packet, we can allocate
1121          *  memory for it, and copy the data from the local area to
1122          *  the packet buffer.
1123          */
1124         if ((packet->data = malloc(packet->data_len)) == NULL) {
1125           free(packet);
1126           librad_log("out of memory");
1127           return NULL;
1128         }
1129         memcpy(packet->data, data, packet->data_len);
1130
1131         return packet;
1132 }
1133
1134 /*
1135  *      Calculate/check digest, and decode radius attributes.
1136  */
1137 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1138                const char *secret)
1139 {
1140         uint32_t                lvalue;
1141         uint32_t                vendorcode;
1142         VALUE_PAIR              **tail;
1143         VALUE_PAIR              *pair;
1144         uint8_t                 *ptr;
1145         int                     length;
1146         int                     attribute;
1147         int                     attrlen;
1148         int                     vendorlen;
1149         radius_packet_t         *hdr;
1150
1151         hdr = (radius_packet_t *)packet->data;
1152
1153         /*
1154          *      Before we allocate memory for the attributes, do more
1155          *      sanity checking.
1156          */
1157         ptr = hdr->data;
1158         length = packet->data_len - AUTH_HDR_LEN;
1159         while (length > 0) {
1160                 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1161                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1162
1163                 attrlen = ptr[1];
1164
1165                 switch (ptr[0]) {
1166                 default:        /* don't do anything. */
1167                         break;
1168
1169                         /*
1170                          *      Note that more than one Message-Authenticator
1171                          *      attribute is invalid.
1172                          */
1173                 case PW_MESSAGE_AUTHENTICATOR:
1174                         memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1175                         memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1176
1177                         switch (packet->code) {
1178                         default:
1179                           break;
1180
1181                         case PW_AUTHENTICATION_ACK:
1182                         case PW_AUTHENTICATION_REJECT:
1183                         case PW_ACCESS_CHALLENGE:
1184                           if (!original) {
1185                                   librad_log("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1186                                   return -1;
1187                           }
1188                           memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1189                           break;
1190                         }
1191
1192                         lrad_hmac_md5(packet->data, packet->data_len,
1193                                       secret, strlen(secret), calc_auth_vector);
1194                         if (memcmp(calc_auth_vector, msg_auth_vector,
1195                                     sizeof(calc_auth_vector)) != 0) {
1196                                 char buffer[32];
1197                                 librad_log("Received packet from %s with invalid Message-Authenticator!  (Shared secret is incorrect.)",
1198                                            ip_ntoa(buffer, packet->src_ipaddr));
1199                                 return -1;
1200                         } /* else the message authenticator was good */
1201
1202                         /*
1203                          *      Reinitialize Authenticators.
1204                          */
1205                         memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
1206                         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1207                         break;
1208                 } /* switch over the attributes */
1209
1210                 ptr += attrlen;
1211                 length -= attrlen;
1212         } /* loop over the packet, sanity checking the attributes */
1213
1214         /*
1215          *      Calculate and/or verify digest.
1216          */
1217         switch(packet->code) {
1218                 int rcode;
1219
1220                 case PW_AUTHENTICATION_REQUEST:
1221                 case PW_STATUS_SERVER:
1222                 case PW_DISCONNECT_REQUEST:
1223                         /*
1224                          *      The authentication vector is random
1225                          *      nonsense, invented by the client.
1226                          */
1227                         break;
1228
1229                 case PW_ACCOUNTING_REQUEST:
1230                         if (calc_acctdigest(packet, secret) > 1) {
1231                                 char buffer[32];
1232                                 librad_log("Received Accounting-Request packet "
1233                                     "from %s with invalid signature!  (Shared secret is incorrect.)",
1234                                     ip_ntoa(buffer, packet->src_ipaddr));
1235                                 return -1;
1236                         }
1237                         break;
1238
1239                         /* Verify the reply digest */
1240                 case PW_AUTHENTICATION_ACK:
1241                 case PW_AUTHENTICATION_REJECT:
1242                 case PW_ACCOUNTING_RESPONSE:
1243                         rcode = calc_replydigest(packet, original, secret);
1244                         if (rcode > 1) {
1245                                 char buffer[32];
1246                                 librad_log("Received %s packet "
1247                                            "from %s:%d with invalid signature (err=%d)!  (Shared secret is incorrect.)",
1248                                            packet_codes[packet->code],
1249                                            ip_ntoa(buffer, packet->src_ipaddr),
1250                                            packet->src_port,
1251                                            rcode);
1252                                 return -1;
1253                         }
1254                   break;
1255         }
1256
1257         /*
1258          *      Extract attribute-value pairs
1259          */
1260         ptr = hdr->data;
1261         length = packet->data_len - AUTH_HDR_LEN;
1262         packet->vps = NULL;
1263         tail = &packet->vps;
1264
1265         vendorcode = 0;
1266         vendorlen  = 0;
1267
1268         while (length > 0) {
1269                 if (vendorlen > 0) {
1270                         attribute = *ptr++ | (vendorcode << 16);
1271                         attrlen   = *ptr++;
1272                 } else {
1273                         attribute = *ptr++;
1274                         attrlen   = *ptr++;
1275                 }
1276
1277                 attrlen -= 2;
1278                 length  -= 2;
1279
1280                 /*
1281                  *      This could be a Vendor-Specific attribute.
1282                  */
1283                 if ((vendorlen <= 0) &&
1284                     (attribute == PW_VENDOR_SPECIFIC)) {
1285                         int     sublen;
1286                         uint8_t *subptr;
1287
1288                         /*
1289                          *      attrlen was checked to be >= 6, in rad_recv
1290                          */
1291
1292                         memcpy(&lvalue, ptr, 4);
1293                         vendorcode = ntohl(lvalue);
1294
1295                         /*
1296                          *      This is an implementation issue.
1297                          *      We currently pack vendor into the upper
1298                          *      16 bits of a 32-bit attribute number,
1299                          *      so we can't handle vendor numbers larger
1300                          *      than 16 bits.
1301                          */
1302                         if (vendorcode > 65535) goto create_pair;
1303
1304                         /*
1305                          *      vendorcode was checked to be non-zero
1306                          *      above, in rad_recv.
1307                          */
1308
1309                         /*
1310                          *      First, check to see if the
1311                          *      sub-attributes fill the VSA, as
1312                          *      defined by the RFC.  If not, then it
1313                          *      may be a USR-style VSA, or it may be a
1314                          *      vendor who packs all of the
1315                          *      information into one nonsense
1316                          *      attribute
1317                          */
1318                         subptr = ptr + 4;
1319                         sublen = attrlen - 4;
1320
1321                         while (sublen > 0) {
1322                                 if (subptr[1] < 2) { /* too short */
1323                                         break;
1324                                 }
1325
1326                                 if (subptr[1] > sublen) { /* too long */
1327                                         break;
1328                                 }
1329
1330                                 sublen -= subptr[1]; /* just right */
1331                                 subptr += subptr[1];
1332                         }
1333
1334                         /*
1335                          *      If the attribute is RFC compatible,
1336                          *      then allow it as an RFC style VSA.
1337                          */
1338                         if (sublen == 0) {
1339                                 ptr += 4;
1340                                 vendorlen = attrlen - 4;
1341                                 attribute = *ptr++ | (vendorcode << 16);
1342                                 attrlen   = *ptr++;
1343                                 attrlen -= 2;
1344                                 length -= 6;
1345
1346                                 /*
1347                                  *      USR-style attributes are 4 octets,
1348                                  *      with the upper 2 octets being zero.
1349                                  *
1350                                  *      The upper octets may not be zero,
1351                                  *      but that then means we won't be
1352                                  *      able to pack the vendor & attribute
1353                                  *      into a 32-bit number, so we can't
1354                                  *      handle it.
1355                                  *
1356                                  *
1357                                  *      FIXME: Update the dictionaries so
1358                                  *      that we key off of per-attribute
1359                                  *      flags "4-octet", instead of hard
1360                                  *      coding USR here.  This will also
1361                                  *      let us send packets with other
1362                                  *      vendors having 4-octet attributes.
1363                                  */
1364                         } else if ((vendorcode == VENDORPEC_USR) &&
1365                                    ((ptr[4] == 0) && (ptr[5] == 0))) {
1366                                 DICT_ATTR *da;
1367                                 
1368                                 da = dict_attrbyvalue((vendorcode << 16) |
1369                                                       (ptr[6] << 8) |
1370                                                       ptr[7]);
1371
1372                                 /*
1373                                  *      See if it's in the dictionary.
1374                                  *      If so, it's a valid USR style
1375                                  *      attribute.  If not, it's not...
1376                                  *
1377                                  *      Don't touch 'attribute' until
1378                                  *      we know what to do!
1379                                  */
1380                                 if (da != NULL) {
1381                                         attribute = ((vendorcode << 16) |
1382                                                      (ptr[6] << 8) |
1383                                                      ptr[7]);
1384                                         ptr += 8;
1385                                         attrlen -= 8;
1386                                         length -= 8;
1387                                 } /* else it's not in the dictionary */
1388                         } /* else it was a stupid vendor format */
1389                 } /* else it wasn't a VSA */
1390
1391                 /*
1392                  *      Create the attribute, setting the default type
1393                  *      to 'octects'.  If the type in the dictionary
1394                  *      is different, then the dictionary type will
1395                  *      over-ride this one.
1396                  */
1397         create_pair:
1398                 if ((pair = paircreate(attribute, PW_TYPE_OCTETS)) == NULL) {
1399                         pairfree(&packet->vps);
1400                         librad_log("out of memory");
1401                         return -1;
1402                 }
1403                 
1404                 pair->length = attrlen;
1405                 pair->operator = T_OP_EQ;
1406                 pair->next = NULL;
1407                 
1408                 switch (pair->type) {
1409                         
1410                         /*
1411                          *      The attribute may be zero length,
1412                          *      or it may have a tag, and then no data...
1413                          */
1414                 case PW_TYPE_STRING:
1415                         if (pair->flags.has_tag) {
1416                                 int offset = 0;
1417
1418                                 /*
1419                                  *      If there's sufficient room for
1420                                  *      a tag, and the tag looks valid,
1421                                  *      then use it.
1422                                  */
1423                                 if ((pair->length > 0) &&
1424                                     TAG_VALID(*ptr)) {
1425                                         pair->flags.tag = *ptr;
1426                                         pair->length--;
1427                                         offset = 1;
1428
1429                                         /*
1430                                          *      If the leading tag
1431                                          *      isn't valid, then it's
1432                                          *      ignored for the tunnel
1433                                          *      password attribute.
1434                                          */
1435                                 } else if (pair->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD) {
1436                                         /*
1437                                          * from RFC2868 - 3.5.  Tunnel-Password
1438                                          * If the value of the Tag field is greater than
1439                                          * 0x00 and less than or equal to 0x1F, it SHOULD
1440                                          * be interpreted as indicating which tunnel
1441                                          * (of several alternatives) this attribute pertains;
1442                                          * otherwise, the Tag field SHOULD be ignored.
1443                                          */
1444                                         pair->flags.tag = 0x00;
1445                                         if (pair->length > 0) pair->length--;
1446                                         offset = 1;
1447                                 } else {
1448                                        pair->flags.tag = 0x00;
1449                                 }
1450
1451                                 /*
1452                                  *      pair->length MAY be zero here.
1453                                  */
1454                                 memcpy(pair->strvalue, ptr + offset,
1455                                        pair->length);
1456                         } else {
1457                           /*
1458                            *    Ascend binary attributes never have a
1459                            *    tag, and neither do the 'octets' type.
1460                            */
1461                         case PW_TYPE_ABINARY:
1462                         case PW_TYPE_OCTETS:
1463                                 /* attrlen always < MAX_STRING_LEN */
1464                                 memcpy(pair->strvalue, ptr, attrlen);
1465                                 pair->flags.tag = 0;
1466                         }
1467
1468                         /*
1469                          *      Decrypt passwords here.
1470                          */
1471                         switch (pair->flags.encrypt) {
1472                         default:
1473                                 break;
1474
1475                                 /*
1476                                  *  User-Password
1477                                  */
1478                         case FLAG_ENCRYPT_USER_PASSWORD:
1479                                 if (original) {
1480                                         rad_pwdecode((char *)pair->strvalue,
1481                                                      pair->length, secret,
1482                                                      (char *)original->vector);
1483                                 } else {
1484                                         rad_pwdecode((char *)pair->strvalue,
1485                                                      pair->length, secret,
1486                                                      (char *)packet->vector);
1487                                 }
1488                                 if (pair->attribute == PW_USER_PASSWORD) {
1489                                         pair->length = strlen(pair->strvalue);
1490                                 }
1491                                 break;
1492
1493                                 /*
1494                                  *      Tunnel-Password's may go ONLY
1495                                  *      in response packets.
1496                                  */
1497                         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
1498                                 if (!original) {
1499                                         librad_log("ERROR: Tunnel-Password attribute in request: Cannot decrypt it.");
1500                                         return -1;
1501                                 }
1502                                 if (rad_tunnel_pwdecode(pair->strvalue,
1503                                                         &pair->length, 
1504                                                         secret,
1505                                                         (char *)original->vector) < 0) {
1506                                         return -1;
1507                                 }
1508                                 break;
1509
1510                                 /*
1511                                  *  Ascend-Send-Secret
1512                                  *  Ascend-Receive-Secret
1513                                  */
1514                         case FLAG_ENCRYPT_ASCEND_SECRET:
1515                                 {
1516                                         uint8_t my_digest[AUTH_VECTOR_LEN];
1517                                         make_secret(my_digest,
1518                                                     original->vector,
1519                                                     secret, ptr);
1520                                         memcpy(pair->strvalue, my_digest,
1521                                                AUTH_VECTOR_LEN );
1522                                         pair->strvalue[AUTH_VECTOR_LEN] = '\0';
1523                                         pair->length = strlen(pair->strvalue);
1524                                 }
1525                                 break;
1526                         } /* switch over encryption flags */
1527                         break;  /* from octets/string/abinary */
1528                         
1529                 case PW_TYPE_INTEGER:
1530                 case PW_TYPE_DATE:
1531                 case PW_TYPE_IPADDR:
1532                         /*
1533                          *      Check for RFC compliance.  If the
1534                          *      attribute isn't compliant, turn it
1535                          *      into a string of raw octets.
1536                          *
1537                          *      Also set the lvalue to something
1538                          *      which should never match anything.
1539                          */
1540                         if (attrlen != 4) {
1541                                 pair->type = PW_TYPE_OCTETS;
1542                                 memcpy(pair->strvalue, ptr, attrlen);
1543                                 pair->lvalue = 0xbad1bad1;
1544                                 break;
1545                         }
1546
1547                         memcpy(&lvalue, ptr, 4);
1548
1549                         if (pair->type != PW_TYPE_IPADDR) {
1550                                 pair->lvalue = ntohl(lvalue);
1551                         } else {
1552                                  /*
1553                                   *  It's an IP address, keep it in network
1554                                   *  byte order, and put the ASCII IP
1555                                   *  address or host name into the string
1556                                   *  value.
1557                                   */
1558                                 pair->lvalue = lvalue;
1559                                 ip_ntoa(pair->strvalue, pair->lvalue);
1560                         }
1561
1562                         /*
1563                          *      Tagged attributes of type integer have
1564                          *      special treatment.
1565                          */
1566                         if (pair->flags.has_tag &&
1567                             pair->type == PW_TYPE_INTEGER) {
1568                                 pair->flags.tag = (pair->lvalue >> 24) & 0xff;
1569                                 pair->lvalue &= 0x00ffffff;
1570                         }
1571
1572                         /*
1573                          *      Try to get the name for integer
1574                          *      attributes.
1575                          */
1576                         if (pair->type == PW_TYPE_INTEGER) {
1577                                 DICT_VALUE *dval;
1578                                 dval = dict_valbyattr(pair->attribute,
1579                                                       pair->lvalue);
1580                                 if (dval) {
1581                                         strNcpy(pair->strvalue,
1582                                                 dval->name,
1583                                                 sizeof(pair->strvalue));
1584                                 }
1585                         }
1586                         break;
1587                         
1588                         /*
1589                          *      IPv6 interface ID is 8 octets long.
1590                          */
1591                 case PW_TYPE_IFID:
1592                         if (attrlen != 8)
1593                                 pair->type = PW_TYPE_OCTETS;
1594                         memcpy(pair->strvalue, ptr, attrlen);
1595                         break;
1596
1597                         /*
1598                          *      IPv6 addresses are 16 octets long
1599                          */
1600                 case PW_TYPE_IPV6ADDR:
1601                         if (attrlen != 16)
1602                                 pair->type = PW_TYPE_OCTETS;
1603                         memcpy(pair->strvalue, ptr, attrlen);
1604                         break;
1605
1606                         /*
1607                          *      IPv6 prefixes are 2 to 18 octets long.
1608                          *
1609                          *      RFC 3162: The first octet is unused.
1610                          *      The second is the length of the prefix
1611                          *      the rest are the prefix data.
1612                          *
1613                          *      The prefix length can have value 0 to 128.
1614                          */
1615                 case PW_TYPE_IPV6PREFIX:
1616                         if (attrlen < 2 || attrlen > 18)
1617                                 pair->type = PW_TYPE_OCTETS;
1618                         if (attrlen >= 2) {
1619                                 if (ptr[1] > 128) {
1620                                         pair->type = PW_TYPE_OCTETS;
1621                                 }
1622                                 /*
1623                                  *      FIXME: double-check that
1624                                  *      (ptr[1] >> 3) matches attrlen + 2
1625                                  */
1626                         }
1627                         memcpy(pair->strvalue, ptr, attrlen);
1628                         break;
1629
1630                 default:
1631                         DEBUG("    %s (Unknown Type %d)\n",
1632                               pair->name, pair->type);
1633                         free(pair);
1634                         pair = NULL;
1635                         break;
1636                 }
1637                 
1638                 if (pair) {
1639                         debug_pair(pair);
1640                         *tail = pair;
1641                         tail = &pair->next;
1642                 }
1643
1644                 ptr += attrlen;
1645                 length -= attrlen;
1646                 if (vendorlen > 0) vendorlen -= (attrlen + 2);
1647         }
1648
1649         /*
1650          *      Merge information from the outside world into our
1651          *      random pool
1652          */
1653         for (length = 0; length < AUTH_VECTOR_LEN; length++) {
1654                 lrad_rand_pool.randmem[length] += packet->vector[length];
1655         }
1656         lrad_rand_pool.randmem[lrad_rand_pool.randmem[0] & 0xff] += packet->id;
1657         lrad_rand_pool.randmem[lrad_rand_pool.randmem[1] & 0xff] += packet->data_len;
1658
1659         return 0;
1660 }
1661
1662
1663 /*
1664  *      Encode password.
1665  *
1666  *      We assume that the passwd buffer passed is big enough.
1667  *      RFC2138 says the password is max 128 chars, so the size
1668  *      of the passwd buffer must be at least 129 characters.
1669  *      Preferably it's just MAX_STRING_LEN.
1670  *
1671  *      int *pwlen is updated to the new length of the encrypted
1672  *      password - a multiple of 16 bytes.
1673  */
1674 #define AUTH_PASS_LEN (16)
1675 int rad_pwencode(char *passwd, int *pwlen, const char *secret,
1676                  const char *vector)
1677 {
1678         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 1];
1679         char    digest[AUTH_VECTOR_LEN];
1680         int     i, n, secretlen;
1681         int     len;
1682
1683         /*
1684          *      Pad password to multiple of AUTH_PASS_LEN bytes.
1685          */
1686         len = *pwlen;
1687         if (len > 128) len = 128;
1688         *pwlen = len;
1689         if (len % AUTH_PASS_LEN != 0) {
1690                 n = AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
1691                 for (i = len; n > 0; n--, i++)
1692                         passwd[i] = 0;
1693                 len = *pwlen = i;
1694         }
1695
1696         /*
1697          *      Use the secret to setup the decryption digest
1698          */
1699         secretlen = strlen(secret);
1700         memcpy(buffer, secret, secretlen);
1701         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
1702         librad_md5_calc((u_char *)digest, buffer, secretlen + AUTH_VECTOR_LEN);
1703
1704         /*
1705          *      Now we can encode the password *in place*
1706          */
1707         for (i = 0; i < AUTH_PASS_LEN; i++)
1708                 passwd[i] ^= digest[i];
1709
1710         if (len <= AUTH_PASS_LEN) return 0;
1711
1712         /*
1713          *      Length > AUTH_PASS_LEN, so we need to use the extended
1714          *      algorithm.
1715          */
1716         for (n = 0; n < 128 && n <= (len - AUTH_PASS_LEN); n += AUTH_PASS_LEN) { 
1717                 memcpy(buffer + secretlen, passwd + n, AUTH_PASS_LEN);
1718                 librad_md5_calc((u_char *)digest, buffer, secretlen + AUTH_PASS_LEN);
1719                 for (i = 0; i < AUTH_PASS_LEN; i++)
1720                         passwd[i + n + AUTH_PASS_LEN] ^= digest[i];
1721         }
1722
1723         return 0;
1724 }
1725
1726 /*
1727  *      Decode password.
1728  */
1729 int rad_pwdecode(char *passwd, int pwlen, const char *secret,
1730                  const char *vector)
1731 {
1732         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 1];
1733         char    digest[AUTH_VECTOR_LEN];
1734         char    r[AUTH_VECTOR_LEN];
1735         char    *s;
1736         int     i, n, secretlen;
1737         int     rlen;
1738
1739         /*
1740          *      Use the secret to setup the decryption digest
1741          */
1742         secretlen = strlen(secret);
1743         memcpy(buffer, secret, secretlen);
1744         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
1745         librad_md5_calc((u_char *)digest, buffer, secretlen + AUTH_VECTOR_LEN);
1746
1747         /*
1748          *      Now we can decode the password *in place*
1749          */
1750         memcpy(r, passwd, AUTH_PASS_LEN);
1751         for (i = 0; i < AUTH_PASS_LEN && i < pwlen; i++)
1752                 passwd[i] ^= digest[i];
1753
1754         if (pwlen <= AUTH_PASS_LEN) {
1755                 passwd[pwlen+1] = 0;
1756                 return pwlen;
1757         }
1758
1759         /*
1760          *      Length > AUTH_PASS_LEN, so we need to use the extended
1761          *      algorithm.
1762          */
1763         rlen = ((pwlen - 1) / AUTH_PASS_LEN) * AUTH_PASS_LEN;
1764
1765         for (n = rlen; n > 0; n -= AUTH_PASS_LEN ) { 
1766                 s = (n == AUTH_PASS_LEN) ? r : (passwd + n - AUTH_PASS_LEN);
1767                 memcpy(buffer + secretlen, s, AUTH_PASS_LEN);
1768                 librad_md5_calc((u_char *)digest, buffer, secretlen + AUTH_PASS_LEN);
1769                 for (i = 0; i < AUTH_PASS_LEN && (i + n) < pwlen; i++)
1770                         passwd[i + n] ^= digest[i];
1771         }
1772         passwd[pwlen] = 0;
1773
1774         return pwlen;
1775 }
1776
1777 static unsigned int salt_offset = 0;
1778
1779 /*
1780  *      Encode Tunnel-Password attributes when sending them out on the wire.
1781  *
1782  *      int *pwlen is updated to the new length of the encrypted
1783  *      password - a multiple of 16 bytes.
1784  *
1785  *      This is per RFC-2868 which adds a two char SALT to the initial intermediate
1786  *      value MD5 hash.
1787  */
1788 int rad_tunnel_pwencode(char *passwd, int *pwlen, const char *secret,
1789                         const char *vector)
1790 {
1791         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
1792         unsigned char   digest[AUTH_VECTOR_LEN];
1793         char*   salt;
1794         int     i, n, secretlen;
1795         unsigned len, n2;
1796         
1797         len = *pwlen;
1798
1799         if (len > 127) len = 127;
1800         /*
1801          * Shift the password 3 positions right to place a salt and original
1802          * length, tag will be added automatically on packet send
1803          */
1804         for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
1805         salt = passwd;
1806         passwd += 2;
1807         /*
1808          * save original password length as first password character;
1809          */
1810         *passwd = len;
1811         len += 1;
1812
1813
1814         /*
1815          *      Generate salt.  The RFC's say:
1816          *
1817          *      The high bit of salt[0] must be set, each salt in a
1818          *      packet should be unique, and they should be random
1819          *
1820          *      So, we set the high bit, add in a counter, and then
1821          *      add in some CSPRNG data.  should be OK..
1822          */
1823         salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
1824                    (lrad_rand() & 0x07));
1825         salt[1] = lrad_rand();
1826         
1827         /*
1828          *      Padd password to multiple of AUTH_PASS_LEN bytes.
1829          */
1830         n = len % AUTH_PASS_LEN;
1831         if (n) {
1832                 n = AUTH_PASS_LEN - n;
1833                 for (; n > 0; n--, len++)
1834                         passwd[len] = 0;
1835         }
1836         /* set new password length */
1837         *pwlen = len + 2;
1838         
1839         /*
1840          *      Use the secret to setup the decryption digest
1841          */
1842         secretlen = strlen(secret);
1843         memcpy(buffer, secret, secretlen);
1844         
1845         for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
1846                 if (!n2) {
1847                         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
1848                         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
1849                         librad_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
1850                 } else {
1851                         memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN); 
1852                         librad_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
1853                 }
1854                 
1855                 for (i = 0; i < AUTH_PASS_LEN; i++) {
1856                         passwd[i + n2] ^= digest[i];
1857                 }
1858         }
1859         passwd[n2] = 0;
1860         return 0;
1861 }
1862
1863 /*
1864  *      Decode Tunnel-Password encrypted attributes.
1865  *
1866  *      Defined in RFC-2868, this uses a two char SALT along with the
1867  *      initial intermediate value, to differentiate it from the
1868  *      above.
1869  */
1870 int rad_tunnel_pwdecode(uint8_t *passwd, int *pwlen, const char *secret,
1871                         const char *vector)
1872 {
1873         uint8_t         buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
1874         uint8_t         digest[AUTH_VECTOR_LEN];
1875         uint8_t         decrypted[MAX_STRING_LEN + 1];
1876         int             secretlen;
1877         unsigned        i, n, len;
1878         
1879         len = *pwlen;
1880
1881         /*
1882          *      We need at least a salt.
1883          */
1884         if (len < 2) {
1885                 librad_log("tunnel password is too short");
1886                 return -1;
1887         }
1888
1889         /*
1890          *      There's a salt, but no password.  Or, there's a salt 
1891          *      and a 'data_len' octet.  It's wrong, but at least we
1892          *      can figure out what it means: the password is empty.
1893          *
1894          *      Note that this means we ignore the 'data_len' field,
1895          *      if the attribute length tells us that there's no
1896          *      more data.  So the 'data_len' field may be wrong,
1897          *      but that's ok...
1898          */
1899         if (len <= 3) {
1900                 passwd[0] = 0;
1901                 *pwlen = 0;
1902                 return 0;
1903         }
1904
1905         len -= 2;               /* discount the salt */
1906
1907         /*
1908          *      Use the secret to setup the decryption digest
1909          */
1910         secretlen = strlen(secret);
1911
1912         /*
1913          *      Set up the initial key:
1914          *
1915          *       b(1) = MD5(secret + vector + salt)
1916          */
1917         memcpy(buffer, secret, secretlen);
1918         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
1919         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, passwd, 2);
1920         librad_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
1921
1922         /*
1923          *      A quick check: decrypt the first octet of the password,
1924          *      which is the 'data_len' field.  Ensure it's sane.
1925          *
1926          *      'n' doesn't include the 'data_len' octet
1927          *      'len' does.
1928          */
1929         n = passwd[2] ^ digest[0];
1930         if (n >= len) {
1931                 librad_log("tunnel password is too long for the attribute");
1932                 return -1;
1933         }
1934
1935         /*
1936          *      Loop over the data, decrypting it, and generating
1937          *      the key for the next round of decryption.
1938          */
1939         for (n = 0; n < len; n += AUTH_PASS_LEN) {
1940                 for (i = 0; i < AUTH_PASS_LEN; i++) {
1941                         decrypted[n + i] = passwd[n + i + 2] ^ digest[i];
1942
1943                         /*
1944                          *      Encrypted password may not be aligned
1945                          *      on 16 octets, so we catch that here...
1946                          */
1947                         if ((n + i) == len) break;
1948                 }
1949
1950                 /*
1951                  *      Update the digest, based on
1952                  *
1953                  *      b(n) = MD5(secret + cleartext(n-1)
1954                  *
1955                  *      but only if there's more data...
1956                  */
1957                 memcpy(buffer + secretlen, passwd + n + 2, AUTH_PASS_LEN);
1958                 librad_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
1959         }
1960
1961         /*
1962          *      We've already validated the length of the decrypted
1963          *      password.  Copy it back to the caller.
1964          */
1965         memcpy(passwd, decrypted + 1, decrypted[0]);
1966         passwd[decrypted[0]] = 0;
1967         *pwlen = decrypted[0];
1968
1969         return decrypted[0];
1970 }
1971
1972 /*
1973  *      Encode a CHAP password
1974  *
1975  *      FIXME: might not work with Ascend because
1976  *      we use vp->length, and Ascend gear likes
1977  *      to send an extra '\0' in the string!
1978  */
1979 int rad_chap_encode(RADIUS_PACKET *packet, char *output, int id,
1980                     VALUE_PAIR *password)
1981 {
1982         int             i;
1983         char            *ptr;
1984         char            string[MAX_STRING_LEN * 2 + 1];
1985         VALUE_PAIR      *challenge;
1986
1987         /*
1988          *      Sanity check the input parameters
1989          */
1990         if ((packet == NULL) || (password == NULL)) {
1991                 return -1;
1992         }
1993
1994         /*
1995          *      Note that the password VP can be EITHER
1996          *      a User-Password attribute (from a check-item list),
1997          *      or a CHAP-Password attribute (the client asking
1998          *      the library to encode it).
1999          */
2000
2001         i = 0;
2002         ptr = string;
2003         *ptr++ = id;
2004
2005         i++;
2006         memcpy(ptr, password->strvalue, password->length);
2007         ptr += password->length;
2008         i += password->length;
2009
2010         /*
2011          *      Use Chap-Challenge pair if present,
2012          *      Request-Authenticator otherwise.
2013          */
2014         challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
2015         if (challenge) {
2016                 memcpy(ptr, challenge->strvalue, challenge->length);
2017                 i += challenge->length;
2018         } else {
2019                 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
2020                 i += AUTH_VECTOR_LEN; 
2021         }
2022
2023         *output = id;
2024         librad_md5_calc((u_char *)output + 1, (u_char *)string, i);
2025
2026         return 0;
2027 }
2028
2029 /*
2030  *      Create a random vector of AUTH_VECTOR_LEN bytes.
2031  */
2032 static void random_vector(uint8_t *vector)
2033 {
2034         int i;
2035
2036         if (!lrad_pool_initialized) {
2037                 memset(&lrad_rand_pool, 0, sizeof(lrad_rand_pool));
2038
2039                 /*
2040                  *      Initialize the state to something, using
2041                  *      numbers which aren't random, but which also
2042                  *      aren't static.
2043                  */
2044                 lrad_rand_pool.randrsl[0] = (uint32_t) &lrad_pool_initialized;
2045                 lrad_rand_pool.randrsl[1] = (uint32_t) &i;
2046                 lrad_rand_pool.randrsl[2] = (uint32_t) vector;
2047
2048                 lrad_randinit(&lrad_rand_pool, 1);
2049         }
2050
2051         lrad_isaac(&lrad_rand_pool);
2052
2053         /*
2054          *      Copy the random data over.
2055          */
2056         for (i = 0; i < AUTH_VECTOR_LEN; i++) {
2057                 *(vector++) = lrad_rand_pool.randrsl[i] & 0xff;
2058         }
2059 }
2060
2061 /*
2062  *      Return a 32-bit random number.
2063  */
2064 uint32_t lrad_rand(void)
2065 {
2066         uint32_t answer;
2067         static int rand_index = 0;
2068
2069         /*
2070          *      Ensure that the pool is initialized.
2071          */
2072         if (!lrad_pool_initialized) {
2073                 uint8_t vector[AUTH_VECTOR_LEN];
2074
2075                 random_vector(vector);
2076         }
2077
2078         /*
2079          *      Grab an entry from the pool.
2080          */
2081         answer = lrad_rand_pool.randrsl[rand_index];
2082
2083         /*
2084          *      Go to the next entry (wrapping around to zero).
2085          */
2086         rand_index++;
2087         rand_index &= 0xff;
2088
2089         /*
2090          *      Every 256 numbers, churn the pool again.
2091          */
2092         if (rand_index == 0) {
2093                 lrad_isaac(&lrad_rand_pool);
2094         }
2095
2096         return answer;
2097 }
2098
2099 /*
2100  *      Allocate a new RADIUS_PACKET
2101  */
2102 RADIUS_PACKET *rad_alloc(int newvector)
2103 {
2104         RADIUS_PACKET   *rp;
2105
2106         if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
2107                 librad_log("out of memory");
2108                 return NULL;
2109         }
2110         memset(rp, 0, sizeof(RADIUS_PACKET));
2111         if (newvector)
2112                 random_vector(rp->vector);
2113
2114         return rp;
2115 }
2116
2117 /*
2118  *      Free a RADIUS_PACKET
2119  */
2120 void rad_free(RADIUS_PACKET **radius_packet_ptr)
2121 {
2122         RADIUS_PACKET *radius_packet;
2123
2124         if (!radius_packet_ptr) return;
2125         radius_packet = *radius_packet_ptr;
2126
2127         if (radius_packet->data) free(radius_packet->data);
2128         if (radius_packet->vps) pairfree(&radius_packet->vps);
2129
2130         free(radius_packet);
2131
2132         *radius_packet_ptr = NULL;
2133 }
2134
2135 /*************************************************************************
2136  *
2137  *      Function: make_secret
2138  *
2139  *      Purpose: Build an encrypted secret value to return in a reply
2140  *               packet.  The secret is hidden by xoring with a MD5 digest
2141  *               created from the shared secret and the authentication
2142  *               vector.  We put them into MD5 in the reverse order from
2143  *               that used when encrypting passwords to RADIUS.
2144  *
2145  *************************************************************************/
2146 static void make_secret(unsigned char *digest, uint8_t *vector,
2147                         const char *secret, char *value)
2148 {
2149         u_char  buffer[256 + AUTH_VECTOR_LEN];
2150         int             secretLen = strlen(secret);
2151         int             i;
2152
2153         memcpy(buffer, vector, AUTH_VECTOR_LEN );
2154         memcpy(buffer + AUTH_VECTOR_LEN, secret, secretLen );
2155
2156         librad_md5_calc(digest, buffer, AUTH_VECTOR_LEN + secretLen );
2157         memset(buffer, 0, sizeof(buffer));
2158
2159         for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
2160                 digest[i] ^= value[i];
2161         }
2162 }