Diff for /embedaddon/dnsmasq/src/forward.c between versions 1.1.1.1 and 1.1.1.2

version 1.1.1.1, 2013/07/29 19:37:40 version 1.1.1.2, 2014/06/15 16:31:38
Line 1 Line 1
/* dnsmasq is Copyright (c) 2000-2013 Simon Kelley/* dnsmasq is Copyright (c) 2000-2014 Simon Kelley
   
    This program is free software; you can redistribute it and/or modify     This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by     it under the terms of the GNU General Public License as published by
Line 16 Line 16
   
 #include "dnsmasq.h"  #include "dnsmasq.h"
   
static struct frec *lookup_frec(unsigned short id, unsigned int crc);static struct frec *lookup_frec(unsigned short id, void *hash);
 static struct frec *lookup_frec_by_sender(unsigned short id,  static struct frec *lookup_frec_by_sender(unsigned short id,
                                           union mysockaddr *addr,                                            union mysockaddr *addr,
                                          unsigned int crc);                                          void *hash);
static unsigned short get_id(unsigned int crc);static unsigned short get_id(void);
 static void free_frec(struct frec *f);  static void free_frec(struct frec *f);
 static struct randfd *allocate_rfd(int family);  static struct randfd *allocate_rfd(int family);
   
   #ifdef HAVE_DNSSEC
   static int tcp_key_recurse(time_t now, int status, struct dns_header *header, size_t n, 
                              int class, char *name, char *keyname, struct server *server, int *keycount);
   static int do_check_sign(time_t now, struct dns_header *header, size_t plen, char *name, char *keyname, int class);
   static int send_check_sign(time_t now, struct dns_header *header, size_t plen, char *name, char *keyname);
   #endif
   
   
 /* Send a UDP packet with its source address set as "source"   /* Send a UDP packet with its source address set as "source" 
    unless nowild is true, when we just send it with the kernel default */     unless nowild is true, when we just send it with the kernel default */
 int send_from(int fd, int nowild, char *packet, size_t len,   int send_from(int fd, int nowild, char *packet, size_t len, 
Line 234  static unsigned int search_servers(time_t now, struct  Line 242  static unsigned int search_servers(time_t now, struct 
   
 static int forward_query(int udpfd, union mysockaddr *udpaddr,  static int forward_query(int udpfd, union mysockaddr *udpaddr,
                          struct all_addr *dst_addr, unsigned int dst_iface,                           struct all_addr *dst_addr, unsigned int dst_iface,
                         struct dns_header *header, size_t plen, time_t now, struct frec *forward)                         struct dns_header *header, size_t plen, time_t now, 
                          struct frec *forward, int ad_reqd, int do_bit)
 {  {
   char *domain = NULL;    char *domain = NULL;
   int type = 0, norebind = 0;    int type = 0, norebind = 0;
   struct all_addr *addrp = NULL;    struct all_addr *addrp = NULL;
   unsigned int crc = questions_crc(header, plen, daemon->namebuff);  
   unsigned int flags = 0;    unsigned int flags = 0;
   unsigned int gotname = extract_request(header, plen, daemon->namebuff, NULL);  
   struct server *start = NULL;    struct server *start = NULL;
  #ifdef HAVE_DNSSEC
  /* RFC 4035: sect 4.6 para 2 */  void *hash = hash_questions(header, plen, daemon->namebuff);
  header->hb4 &= ~HB4_AD;#else
    unsigned int crc = questions_crc(header, plen, daemon->namebuff);
   void *hash = &crc;
 #endif
  unsigned int gotname = extract_request(header, plen, daemon->namebuff, NULL);
 
  (void)do_bit;
 
   /* may be no servers available. */    /* may be no servers available. */
   if (!daemon->servers)    if (!daemon->servers)
     forward = NULL;      forward = NULL;
  else if (forward || (forward = lookup_frec_by_sender(ntohs(header->id), udpaddr, crc)))  else if (forward || (hash && (forward = lookup_frec_by_sender(ntohs(header->id), udpaddr, hash))))
     {      {
   #ifdef HAVE_DNSSEC
         /* If we've already got an answer to this query, but we're awaiting keys for validation,
            there's no point retrying the query, retry the key query instead...... */
         if (forward->blocking_query)
           {
             int fd;
   
             while (forward->blocking_query)
               forward = forward->blocking_query;
             
             blockdata_retrieve(forward->stash, forward->stash_len, (void *)header);
             plen = forward->stash_len;
             
             if (forward->sentto->addr.sa.sa_family == AF_INET) 
               log_query(F_DNSSEC | F_IPV4, "retry", (struct all_addr *)&forward->sentto->addr.in.sin_addr, "dnssec");
   #ifdef HAVE_IPV6
             else
               log_query(F_DNSSEC | F_IPV6, "retry", (struct all_addr *)&forward->sentto->addr.in6.sin6_addr, "dnssec");
   #endif
     
             if (forward->sentto->sfd)
               fd = forward->sentto->sfd->fd;
             else
               {
   #ifdef HAVE_IPV6
                 if (forward->sentto->addr.sa.sa_family == AF_INET6)
                   fd = forward->rfd6->fd;
                 else
   #endif
                   fd = forward->rfd4->fd;
               }
             
             while (sendto(fd, (char *)header, plen, 0,
                           &forward->sentto->addr.sa,
                           sa_len(&forward->sentto->addr)) == -1 && retry_send());
             
             return 1;
           }
   #endif
   
       /* retry on existing query, send to all available servers  */        /* retry on existing query, send to all available servers  */
       domain = forward->sentto->domain;        domain = forward->sentto->domain;
       forward->sentto->failed_queries++;        forward->sentto->failed_queries++;
Line 270  static int forward_query(int udpfd, union mysockaddr * Line 323  static int forward_query(int udpfd, union mysockaddr *
       if (gotname)        if (gotname)
         flags = search_servers(now, &addrp, gotname, daemon->namebuff, &type, &domain, &norebind);          flags = search_servers(now, &addrp, gotname, daemon->namebuff, &type, &domain, &norebind);
               
      if (!flags && !(forward = get_new_frec(now, NULL)))      if (!flags && !(forward = get_new_frec(now, NULL, 0)))
         /* table full - server failure. */          /* table full - server failure. */
         flags = F_NEG;          flags = F_NEG;
               
Line 280  static int forward_query(int udpfd, union mysockaddr * Line 333  static int forward_query(int udpfd, union mysockaddr *
           forward->dest = *dst_addr;            forward->dest = *dst_addr;
           forward->iface = dst_iface;            forward->iface = dst_iface;
           forward->orig_id = ntohs(header->id);            forward->orig_id = ntohs(header->id);
          forward->new_id = get_id(crc);          forward->new_id = get_id();
           forward->fd = udpfd;            forward->fd = udpfd;
          forward->crc = crc;          memcpy(forward->hash, hash, HASH_SIZE);
           forward->forwardall = 0;            forward->forwardall = 0;
             forward->flags = 0;
           if (norebind)            if (norebind)
             forward->flags |= FREC_NOREBIND;              forward->flags |= FREC_NOREBIND;
           if (header->hb4 & HB4_CD)            if (header->hb4 & HB4_CD)
             forward->flags |= FREC_CHECKING_DISABLED;              forward->flags |= FREC_CHECKING_DISABLED;
          if (ad_reqd)
             forward->flags |= FREC_AD_QUESTION;
 #ifdef HAVE_DNSSEC
           forward->work_counter = DNSSEC_WORK;
           if (do_bit)
             forward->flags |= FREC_DO_QUESTION;
 #endif
           
           header->id = htons(forward->new_id);            header->id = htons(forward->new_id);
                       
           /* In strict_order mode, always try servers in the order             /* In strict_order mode, always try servers in the order 
Line 328  static int forward_query(int udpfd, union mysockaddr * Line 389  static int forward_query(int udpfd, union mysockaddr *
       struct server *firstsentto = start;        struct server *firstsentto = start;
       int forwarded = 0;        int forwarded = 0;
               
      if (udpaddr && option_bool(OPT_ADD_MAC))      if (option_bool(OPT_ADD_MAC))
        plen = add_mac(header, plen, ((char *) header) + PACKETSZ, udpaddr);        plen = add_mac(header, plen, ((char *) header) + daemon->packet_buff_sz, &forward->source);
               
         if (option_bool(OPT_CLIENT_SUBNET))
           {
             size_t new = add_source_addr(header, plen, ((char *) header) + daemon->packet_buff_sz, &forward->source); 
             if (new != plen)
               {
                 plen = new;
                 forward->flags |= FREC_HAS_SUBNET;
               }
           }
   
   #ifdef HAVE_DNSSEC
         if (option_bool(OPT_DNSSEC_VALID))
           {
             size_t new_plen = add_do_bit(header, plen, ((char *) header) + daemon->packet_buff_sz);
            
             /* For debugging, set Checking Disabled, otherwise, have the upstream check too,
                this allows it to select auth servers when one is returning bad data. */
             if (option_bool(OPT_DNSSEC_DEBUG))
               header->hb4 |= HB4_CD;
   
             if (new_plen != plen)
               forward->flags |= FREC_ADDED_PHEADER;
   
             plen = new_plen;
           }
   #endif
   
       while (1)        while (1)
         {           { 
           /* only send to servers dealing with our domain.            /* only send to servers dealing with our domain.
Line 372  static int forward_query(int udpfd, union mysockaddr * Line 460  static int forward_query(int udpfd, union mysockaddr *
                   if (option_bool(OPT_CONNTRACK))                    if (option_bool(OPT_CONNTRACK))
                     {                      {
                       unsigned int mark;                        unsigned int mark;
                      if (get_incoming_mark(udpaddr, dst_addr, 0, &mark))                      if (get_incoming_mark(&forward->source, &forward->dest, 0, &mark))
                         setsockopt(fd, SOL_SOCKET, SO_MARK, &mark, sizeof(unsigned int));                          setsockopt(fd, SOL_SOCKET, SO_MARK, &mark, sizeof(unsigned int));
                     }                      }
 #endif  #endif
Line 435  static int forward_query(int udpfd, union mysockaddr * Line 523  static int forward_query(int udpfd, union mysockaddr *
   return 0;    return 0;
 }  }
   
static size_t process_reply(struct dns_header *header, time_t now, static size_t process_reply(struct dns_header *header, time_t now, struct server *server, size_t n, int check_rebind, 
                            struct server *server, size_t n, int check_rebind, int checking_disabled)                            int no_cache, int cache_secure, int ad_reqd, int do_bit, int added_pheader, int check_subnet, union mysockaddr *query_source)
 {  {
   unsigned char *pheader, *sizep;    unsigned char *pheader, *sizep;
   char **sets = 0;    char **sets = 0;
   int munged = 0, is_sign;    int munged = 0, is_sign;
   size_t plen;     size_t plen; 
   
     (void)ad_reqd;
     (void) do_bit;
   
 #ifdef HAVE_IPSET  #ifdef HAVE_IPSET
  /* Similar algorithm to search_servers. */  if (daemon->ipsets && extract_request(header, n, daemon->namebuff, NULL))
  struct ipsets *ipset_pos; 
  unsigned int namelen = strlen(daemon->namebuff); 
  unsigned int matchlen = 0; 
  for (ipset_pos = daemon->ipsets; ipset_pos; ipset_pos = ipset_pos->next)  
     {      {
      unsigned int domainlen = strlen(ipset_pos->domain);      /* Similar algorithm to search_servers. */
      char *matchstart = daemon->namebuff + namelen - domainlen;      struct ipsets *ipset_pos;
      if (namelen >= domainlen && hostname_isequal(matchstart, ipset_pos->domain) &&      unsigned int namelen = strlen(daemon->namebuff);
          (domainlen == 0 || namelen == domainlen || *(matchstart - 1) == '.' ) &&      unsigned int matchlen = 0;
          domainlen >= matchlen) {      for (ipset_pos = daemon->ipsets; ipset_pos; ipset_pos = ipset_pos->next) 
        matchlen = domainlen;        {
        sets = ipset_pos->sets;          unsigned int domainlen = strlen(ipset_pos->domain);
      }          char *matchstart = daemon->namebuff + namelen - domainlen;
           if (namelen >= domainlen && hostname_isequal(matchstart, ipset_pos->domain) &&
               (domainlen == 0 || namelen == domainlen || *(matchstart - 1) == '.' ) &&
               domainlen >= matchlen) 
             {
               matchlen = domainlen;
               sets = ipset_pos->sets;
             }
         }
     }      }
 #endif  #endif
       
Line 465  static size_t process_reply(struct dns_header *header, Line 560  static size_t process_reply(struct dns_header *header,
      than we allow, trim it so that we don't get overlarge       than we allow, trim it so that we don't get overlarge
      requests for the client. We can't do this for signed packets. */       requests for the client. We can't do this for signed packets. */
   
  if ((pheader = find_pseudoheader(header, n, &plen, &sizep, &is_sign)) && !is_sign)  if ((pheader = find_pseudoheader(header, n, &plen, &sizep, &is_sign)))
     {      {
       unsigned short udpsz;        unsigned short udpsz;
       unsigned char *psave = sizep;        unsigned char *psave = sizep;
               
       GETSHORT(udpsz, sizep);        GETSHORT(udpsz, sizep);
      if (udpsz > daemon->edns_pktsz)
       if (!is_sign && udpsz > daemon->edns_pktsz)
         PUTSHORT(daemon->edns_pktsz, psave);          PUTSHORT(daemon->edns_pktsz, psave);
         
         if (check_subnet && !check_source(header, plen, pheader, query_source))
           {
             my_syslog(LOG_WARNING, _("discarding DNS reply: subnet option mismatch"));
             return 0;
           }
         
         if (added_pheader)
           {
             pheader = 0; 
             header->arcount = htons(0);
           }
     }      }
  
   /* RFC 4035 sect 4.6 para 3 */    /* RFC 4035 sect 4.6 para 3 */
  if (!is_sign && !option_bool(OPT_DNSSEC))  if (!is_sign && !option_bool(OPT_DNSSEC_PROXY))
      header->hb4 &= ~HB4_AD;       header->hb4 &= ~HB4_AD;
  
   if (OPCODE(header) != QUERY || (RCODE(header) != NOERROR && RCODE(header) != NXDOMAIN))    if (OPCODE(header) != QUERY || (RCODE(header) != NOERROR && RCODE(header) != NXDOMAIN))
    return n;    return resize_packet(header, n, pheader, plen);
       
   /* Complain loudly if the upstream server is non-recursive. */    /* Complain loudly if the upstream server is non-recursive. */
   if (!(header->hb4 & HB4_RA) && RCODE(header) == NOERROR && ntohs(header->ancount) == 0 &&    if (!(header->hb4 & HB4_RA) && RCODE(header) == NOERROR && ntohs(header->ancount) == 0 &&
Line 491  static size_t process_reply(struct dns_header *header, Line 599  static size_t process_reply(struct dns_header *header,
       if (!option_bool(OPT_LOG))        if (!option_bool(OPT_LOG))
         server->flags |= SERV_WARNED_RECURSIVE;          server->flags |= SERV_WARNED_RECURSIVE;
     }        }  
    
   if (daemon->bogus_addr && RCODE(header) != NXDOMAIN &&    if (daemon->bogus_addr && RCODE(header) != NXDOMAIN &&
       check_for_bogus_wildcard(header, n, daemon->namebuff, daemon->bogus_addr, now))        check_for_bogus_wildcard(header, n, daemon->namebuff, daemon->bogus_addr, now))
     {      {
       munged = 1;        munged = 1;
       SET_RCODE(header, NXDOMAIN);        SET_RCODE(header, NXDOMAIN);
       header->hb3 &= ~HB3_AA;        header->hb3 &= ~HB3_AA;
         cache_secure = 0;
     }      }
   else     else 
     {      {
         int doctored = 0;
         
       if (RCODE(header) == NXDOMAIN &&         if (RCODE(header) == NXDOMAIN && 
           extract_request(header, n, daemon->namebuff, NULL) &&            extract_request(header, n, daemon->namebuff, NULL) &&
           check_for_local_domain(daemon->namebuff, now))            check_for_local_domain(daemon->namebuff, now))
Line 511  static size_t process_reply(struct dns_header *header, Line 622  static size_t process_reply(struct dns_header *header,
           munged = 1;            munged = 1;
           header->hb3 |= HB3_AA;            header->hb3 |= HB3_AA;
           SET_RCODE(header, NOERROR);            SET_RCODE(header, NOERROR);
             cache_secure = 0;
         }          }
               
      if (extract_addresses(header, n, daemon->namebuff, now, sets, is_sign, check_rebind, checking_disabled))      if (extract_addresses(header, n, daemon->namebuff, now, sets, is_sign, check_rebind, no_cache, cache_secure, &doctored))
         {          {
           my_syslog(LOG_WARNING, _("possible DNS-rebind attack detected: %s"), daemon->namebuff);            my_syslog(LOG_WARNING, _("possible DNS-rebind attack detected: %s"), daemon->namebuff);
           munged = 1;            munged = 1;
             cache_secure = 0;
         }          }
   
         if (doctored)
           cache_secure = 0;
     }      }
       
   #ifdef HAVE_DNSSEC
     if (no_cache && !(header->hb4 & HB4_CD)) 
       {
         if (!option_bool(OPT_DNSSEC_DEBUG))
           {
             /* Bogus reply, turn into SERVFAIL */
             SET_RCODE(header, SERVFAIL);
             munged = 1;
           }
       }
   
     if (option_bool(OPT_DNSSEC_VALID))
       header->hb4 &= ~HB4_AD;
     
     if (!(header->hb4 & HB4_CD) && ad_reqd && cache_secure)
       header->hb4 |= HB4_AD;
   
     /* If the requestor didn't set the DO bit, don't return DNSSEC info. */
     if (!do_bit)
       n = filter_rrsigs(header, n);
   #endif
   
   /* do this after extract_addresses. Ensure NODATA reply and remove    /* do this after extract_addresses. Ensure NODATA reply and remove
      nameserver info. */       nameserver info. */
       
Line 545  void reply_query(int fd, int family, time_t now) Line 683  void reply_query(int fd, int family, time_t now)
   union mysockaddr serveraddr;    union mysockaddr serveraddr;
   struct frec *forward;    struct frec *forward;
   socklen_t addrlen = sizeof(serveraddr);    socklen_t addrlen = sizeof(serveraddr);
  ssize_t n = recvfrom(fd, daemon->packet, daemon->edns_pktsz, 0, &serveraddr.sa, &addrlen);  ssize_t n = recvfrom(fd, daemon->packet, daemon->packet_buff_sz, 0, &serveraddr.sa, &addrlen);
   size_t nn;    size_t nn;
   struct server *server;    struct server *server;
    void *hash;
 #ifndef HAVE_DNSSEC
   unsigned int crc;
 #endif
 
   /* packet buffer overwritten */    /* packet buffer overwritten */
   daemon->srv_save = NULL;    daemon->srv_save = NULL;
       
Line 559  void reply_query(int fd, int family, time_t now) Line 701  void reply_query(int fd, int family, time_t now)
     serveraddr.in6.sin6_flowinfo = 0;      serveraddr.in6.sin6_flowinfo = 0;
 #endif  #endif
       
     header = (struct dns_header *)daemon->packet;
     
     if (n < (int)sizeof(struct dns_header) || !(header->hb3 & HB3_QR))
       return;
     
   /* spoof check: answer must come from known server, */    /* spoof check: answer must come from known server, */
   for (server = daemon->servers; server; server = server->next)    for (server = daemon->servers; server; server = server->next)
     if (!(server->flags & (SERV_LITERAL_ADDRESS | SERV_NO_ADDR)) &&      if (!(server->flags & (SERV_LITERAL_ADDRESS | SERV_NO_ADDR)) &&
         sockaddr_isequal(&server->addr, &serveraddr))          sockaddr_isequal(&server->addr, &serveraddr))
       break;        break;
      
   header = (struct dns_header *)daemon->packet;  
       
  if (!server ||  if (!server)
      n < (int)sizeof(struct dns_header) || !(header->hb3 & HB3_QR) || 
      !(forward = lookup_frec(ntohs(header->id), questions_crc(header, n, daemon->namebuff)))) 
     return;      return;
      
   server = forward->sentto;  
       
   #ifdef HAVE_DNSSEC
     hash = hash_questions(header, n, daemon->namebuff);
   #else
     hash = &crc;
     crc = questions_crc(header, n, daemon->namebuff);
   #endif
     
     if (!(forward = lookup_frec(ntohs(header->id), hash)))
       return;
     
   if ((RCODE(header) == SERVFAIL || RCODE(header) == REFUSED) &&    if ((RCODE(header) == SERVFAIL || RCODE(header) == REFUSED) &&
       !option_bool(OPT_ORDER) &&        !option_bool(OPT_ORDER) &&
       forward->forwardall == 0)        forward->forwardall == 0)
Line 593  void reply_query(int fd, int family, time_t now) Line 744  void reply_query(int fd, int family, time_t now)
           if ((nn = resize_packet(header, (size_t)n, pheader, plen)))            if ((nn = resize_packet(header, (size_t)n, pheader, plen)))
             {              {
               header->hb3 &= ~(HB3_QR | HB3_TC);                header->hb3 &= ~(HB3_QR | HB3_TC);
              forward_query(-1, NULL, NULL, 0, header, nn, now, forward);              forward_query(-1, NULL, NULL, 0, header, nn, now, forward, 0, 0);
               return;                return;
             }              }
         }          }
     }         }   
      
     server = forward->sentto;
       
   if ((forward->sentto->flags & SERV_TYPE) == 0)    if ((forward->sentto->flags & SERV_TYPE) == 0)
     {      {
      if (RCODE(header) == SERVFAIL || RCODE(header) == REFUSED)      if (RCODE(header) == REFUSED)
         server = NULL;          server = NULL;
       else        else
         {          {
Line 619  void reply_query(int fd, int family, time_t now) Line 772  void reply_query(int fd, int family, time_t now)
       if (!option_bool(OPT_ALL_SERVERS))        if (!option_bool(OPT_ALL_SERVERS))
         daemon->last_server = server;          daemon->last_server = server;
     }      }
  
   /* If the answer is an error, keep the forward record in place in case    /* If the answer is an error, keep the forward record in place in case
      we get a good reply from another server. Kill it when we've       we get a good reply from another server. Kill it when we've
      had replies from all to avoid filling the forwarding table when       had replies from all to avoid filling the forwarding table when
      everything is broken */       everything is broken */
  if (forward->forwardall == 0 || --forward->forwardall == 1 ||   if (forward->forwardall == 0 || --forward->forwardall == 1 || RCODE(header) != SERVFAIL)
      (RCODE(header) != REFUSED && RCODE(header) != SERVFAIL)) 
     {      {
      int check_rebind = !(forward->flags & FREC_NOREBIND);      int check_rebind = 0, no_cache_dnssec = 0, cache_secure = 0;
   
      if (!option_bool(OPT_NO_REBIND))      if (option_bool(OPT_NO_REBIND))
        check_rebind = 0;        check_rebind = !(forward->flags & FREC_NOREBIND);
               
      if ((nn = process_reply(header, now, server, (size_t)n, check_rebind, forward->flags & FREC_CHECKING_DISABLED)))      /*   Don't cache replies where DNSSEC validation was turned off, either
            the upstream server told us so, or the original query specified it.  */
       if ((header->hb4 & HB4_CD) || (forward->flags & FREC_CHECKING_DISABLED))
         no_cache_dnssec = 1;
       
 #ifdef HAVE_DNSSEC
       if (server && option_bool(OPT_DNSSEC_VALID) && !(forward->flags & FREC_CHECKING_DISABLED))
         {          {
             int status;
   
             /* We've had a reply already, which we're validating. Ignore this duplicate */
             if (forward->blocking_query)
               return;
   
             if (header->hb3 & HB3_TC)
               {
                 /* Truncated answer can't be validated.
                    If this is an answer to a DNSSEC-generated query, we still
                    need to get the client to retry over TCP, so return
                    an answer with the TC bit set, even if the actual answer fits.
                 */
                 status = STAT_TRUNCATED;
               }
             else if (forward->flags & FREC_DNSKEY_QUERY)
               status = dnssec_validate_by_ds(now, header, n, daemon->namebuff, daemon->keyname, forward->class);
             else if (forward->flags & FREC_DS_QUERY)
               {
                 status = dnssec_validate_ds(now, header, n, daemon->namebuff, daemon->keyname, forward->class);
                 if (status == STAT_NO_DS)
                   status = STAT_INSECURE;
               }
             else if (forward->flags & FREC_CHECK_NOSIGN)
               status = do_check_sign(now, header, n, daemon->namebuff, daemon->keyname, forward->class);
             else
               {
                 status = dnssec_validate_reply(now, header, n, daemon->namebuff, daemon->keyname, &forward->class, NULL);
                 if (status == STAT_NO_SIG)
                   {
                     if (option_bool(OPT_DNSSEC_NO_SIGN))
                       status = send_check_sign(now, header, n, daemon->namebuff, daemon->keyname);
                     else
                       status = STAT_INSECURE;
                   }
               }
             /* Can't validate, as we're missing key data. Put this
                answer aside, whilst we get that. */     
             if (status == STAT_NEED_DS || status == STAT_NEED_DS_NEG || status == STAT_NEED_KEY)
               {
                 struct frec *new, *orig;
                 
                 /* Free any saved query */
                 if (forward->stash)
                   blockdata_free(forward->stash);
                 
                 /* Now save reply pending receipt of key data */
                 if (!(forward->stash = blockdata_alloc((char *)header, n)))
                   return;
                 forward->stash_len = n;
                 
               anotherkey:       
                 /* Find the original query that started it all.... */
                 for (orig = forward; orig->dependent; orig = orig->dependent);
   
                 if (--orig->work_counter == 0 || !(new = get_new_frec(now, NULL, 1)))
                   status = STAT_INSECURE;
                 else
                   {
                     int fd;
                     struct frec *next = new->next;
                     *new = *forward; /* copy everything, then overwrite */
                     new->next = next;
                     new->blocking_query = NULL;
                     new->sentto = server;
                     new->rfd4 = NULL;
   #ifdef HAVE_IPV6
                     new->rfd6 = NULL;
   #endif
                     new->flags &= ~(FREC_DNSKEY_QUERY | FREC_DS_QUERY | FREC_CHECK_NOSIGN);
                     
                     new->dependent = forward; /* to find query awaiting new one. */
                     forward->blocking_query = new; /* for garbage cleaning */
                     /* validate routines leave name of required record in daemon->keyname */
                     if (status == STAT_NEED_KEY)
                       {
                         new->flags |= FREC_DNSKEY_QUERY; 
                         nn = dnssec_generate_query(header, ((char *) header) + daemon->packet_buff_sz,
                                                    daemon->keyname, forward->class, T_DNSKEY, &server->addr);
                       }
                     else 
                       {
                         if (status == STAT_NEED_DS_NEG)
                           new->flags |= FREC_CHECK_NOSIGN;
                         else
                           new->flags |= FREC_DS_QUERY;
                         nn = dnssec_generate_query(header,((char *) header) + daemon->packet_buff_sz,
                                                    daemon->keyname, forward->class, T_DS, &server->addr);
                       }
                     if ((hash = hash_questions(header, nn, daemon->namebuff)))
                       memcpy(new->hash, hash, HASH_SIZE);
                     new->new_id = get_id();
                     header->id = htons(new->new_id);
                     /* Save query for retransmission */
                     new->stash = blockdata_alloc((char *)header, nn);
                     new->stash_len = nn;
                     
                     /* Don't resend this. */
                     daemon->srv_save = NULL;
                     
                     if (server->sfd)
                       fd = server->sfd->fd;
                     else
                       {
                         fd = -1;
   #ifdef HAVE_IPV6
                         if (server->addr.sa.sa_family == AF_INET6)
                           {
                             if (new->rfd6 || (new->rfd6 = allocate_rfd(AF_INET6)))
                               fd = new->rfd6->fd;
                           }
                         else
   #endif
                           {
                             if (new->rfd4 || (new->rfd4 = allocate_rfd(AF_INET)))
                               fd = new->rfd4->fd;
                           }
                       }
                     
                     if (fd != -1)
                       {
                         while (sendto(fd, (char *)header, nn, 0, &server->addr.sa, sa_len(&server->addr)) == -1 && retry_send()); 
                         server->queries++;
                       }
                     
                     return;
                   }
               }
             
             /* Ok, we reached far enough up the chain-of-trust that we can validate something.
                Now wind back down, pulling back answers which wouldn't previously validate
                and validate them with the new data. Note that if an answer needs multiple
                keys to validate, we may find another key is needed, in which case we set off
                down another branch of the tree. Once we get to the original answer 
                (FREC_DNSSEC_QUERY not set) and it validates, return it to the original requestor. */
             while (forward->dependent)
               {
                 struct frec *prev = forward->dependent;
                 free_frec(forward);
                 forward = prev;
                 forward->blocking_query = NULL; /* already gone */
                 blockdata_retrieve(forward->stash, forward->stash_len, (void *)header);
                 n = forward->stash_len;
                 
                 if (status == STAT_SECURE)
                   {
                     if (forward->flags & FREC_DNSKEY_QUERY)
                       status = dnssec_validate_by_ds(now, header, n, daemon->namebuff, daemon->keyname, forward->class);
                     else if (forward->flags & FREC_DS_QUERY)
                       {
                         status = dnssec_validate_ds(now, header, n, daemon->namebuff, daemon->keyname, forward->class);
                         if (status == STAT_NO_DS)
                           status = STAT_INSECURE;
                       }
                     else if (forward->flags & FREC_CHECK_NOSIGN)
                       status = do_check_sign(now, header, n, daemon->namebuff, daemon->keyname, forward->class);
                     else
                       {
                         status = dnssec_validate_reply(now, header, n, daemon->namebuff, daemon->keyname, &forward->class, NULL); 
                         if (status == STAT_NO_SIG)
                           {
                             if (option_bool(OPT_DNSSEC_NO_SIGN))
                               status = send_check_sign(now, header, n, daemon->namebuff, daemon->keyname);
                             else
                               status = STAT_INSECURE;
                           }
                       }
                  
                     if (status == STAT_NEED_DS || status == STAT_NEED_DS_NEG || status == STAT_NEED_KEY)
                       goto anotherkey;
                   }
               }
             
             if (status == STAT_TRUNCATED)
               header->hb3 |= HB3_TC;
             else
               {
                 char *result;
                 
                 if (forward->work_counter == 0)
                   result = "ABANDONED";
                 else
                   result = (status == STAT_SECURE ? "SECURE" : (status == STAT_INSECURE ? "INSECURE" : "BOGUS"));
                 
                 log_query(F_KEYTAG | F_SECSTAT, "result", NULL, result);
               }
             
             no_cache_dnssec = 0;
             
             if (status == STAT_SECURE)
               cache_secure = 1;
             else if (status == STAT_BOGUS)
               no_cache_dnssec = 1;
           }
   #endif     
         
         /* restore CD bit to the value in the query */
         if (forward->flags & FREC_CHECKING_DISABLED)
           header->hb4 |= HB4_CD;
         else
           header->hb4 &= ~HB4_CD;
         
         if ((nn = process_reply(header, now, server, (size_t)n, check_rebind, no_cache_dnssec, cache_secure,
                                 forward->flags & FREC_AD_QUESTION, forward->flags & FREC_DO_QUESTION, 
                                 forward->flags & FREC_ADDED_PHEADER, forward->flags & FREC_HAS_SUBNET, &forward->source)))
           {
           header->id = htons(forward->orig_id);            header->id = htons(forward->orig_id);
           header->hb4 |= HB4_RA; /* recursion if available */            header->hb4 |= HB4_RA; /* recursion if available */
           send_from(forward->fd, option_bool(OPT_NOWILD) || option_bool (OPT_CLEVERBIND), daemon->packet, nn,             send_from(forward->fd, option_bool(OPT_NOWILD) || option_bool (OPT_CLEVERBIND), daemon->packet, nn, 
Line 653  void receive_query(struct listener *listen, time_t now Line 1017  void receive_query(struct listener *listen, time_t now
   struct in_addr netmask, dst_addr_4;    struct in_addr netmask, dst_addr_4;
   size_t m;    size_t m;
   ssize_t n;    ssize_t n;
  int if_index = 0;  int if_index = 0, auth_dns = 0;
  int auth_dns = 0;#ifdef HAVE_AUTH
   int local_auth = 0;
 #endif
   struct iovec iov[1];    struct iovec iov[1];
   struct msghdr msg;    struct msghdr msg;
   struct cmsghdr *cmptr;    struct cmsghdr *cmptr;
Line 673  void receive_query(struct listener *listen, time_t now Line 1039  void receive_query(struct listener *listen, time_t now
                  CMSG_SPACE(sizeof(struct sockaddr_dl))];                   CMSG_SPACE(sizeof(struct sockaddr_dl))];
 #endif  #endif
   } control_u;    } control_u;
  #ifdef HAVE_IPV6
    /* Can always get recvd interface for IPv6 */
   int check_dst = !option_bool(OPT_NOWILD) || listen->family == AF_INET6;
 #else
   int check_dst = !option_bool(OPT_NOWILD);
 #endif
 
   /* packet buffer overwritten */    /* packet buffer overwritten */
   daemon->srv_save = NULL;    daemon->srv_save = NULL;
       
Line 711  void receive_query(struct listener *listen, time_t now Line 1083  void receive_query(struct listener *listen, time_t now
     return;      return;
       
   source_addr.sa.sa_family = listen->family;    source_addr.sa.sa_family = listen->family;
     
     if (listen->family == AF_INET)
       {
          /* Source-port == 0 is an error, we can't send back to that. 
             http://www.ietf.org/mail-archive/web/dnsop/current/msg11441.html */
         if (source_addr.in.sin_port == 0)
           return;
       }
 #ifdef HAVE_IPV6  #ifdef HAVE_IPV6
  if (listen->family == AF_INET6)  else
    source_addr.in6.sin6_flowinfo = 0;    {
       /* Source-port == 0 is an error, we can't send back to that. */
       if (source_addr.in6.sin6_port == 0)
         return;
       source_addr.in6.sin6_flowinfo = 0;
     }
 #endif  #endif
  
  if (!option_bool(OPT_NOWILD))  /* We can be configured to only accept queries from at-most-one-hop-away addresses. */
   if (option_bool(OPT_LOCAL_SERVICE))
     {      {
         struct addrlist *addr;
   #ifdef HAVE_IPV6
         if (listen->family == AF_INET6) 
           {
             for (addr = daemon->interface_addrs; addr; addr = addr->next)
               if ((addr->flags & ADDRLIST_IPV6) &&
                   is_same_net6(&addr->addr.addr.addr6, &source_addr.in6.sin6_addr, addr->prefixlen))
                 break;
           }
         else
   #endif
           {
             struct in_addr netmask;
             for (addr = daemon->interface_addrs; addr; addr = addr->next)
               {
                 netmask.s_addr = 0xffffffff << (32 - addr->prefixlen);
                 if (!(addr->flags & ADDRLIST_IPV6) &&
                     is_same_net(addr->addr.addr.addr4, source_addr.in.sin_addr, netmask))
                   break;
               }
           }
         if (!addr)
           {
             static int warned = 0;
             if (!warned)
               {
                 my_syslog(LOG_WARNING, _("Ignoring query from non-local network"));
                 warned = 1;
               }
             return;
           }
       }
                   
     if (check_dst)
       {
       struct ifreq ifr;        struct ifreq ifr;
   
       if (msg.msg_controllen < sizeof(struct cmsghdr))        if (msg.msg_controllen < sizeof(struct cmsghdr))
Line 788  void receive_query(struct listener *listen, time_t now Line 1209  void receive_query(struct listener *listen, time_t now
       if (!iface_check(listen->family, &dst_addr, ifr.ifr_name, &auth_dns))        if (!iface_check(listen->family, &dst_addr, ifr.ifr_name, &auth_dns))
         {          {
            if (!option_bool(OPT_CLEVERBIND))             if (!option_bool(OPT_CLEVERBIND))
             enumerate_interfaces();              enumerate_interfaces(0); 
           if (!loopback_exception(listen->fd, listen->family, &dst_addr, ifr.ifr_name))           if (!loopback_exception(listen->fd, listen->family, &dst_addr, ifr.ifr_name) &&
                !label_exception(if_index, listen->family, &dst_addr))
              return;               return;
         }          }
   
Line 807  void receive_query(struct listener *listen, time_t now Line 1229  void receive_query(struct listener *listen, time_t now
                       
           /* interface may be new */            /* interface may be new */
           if (!iface && !option_bool(OPT_CLEVERBIND))            if (!iface && !option_bool(OPT_CLEVERBIND))
            enumerate_interfaces();             enumerate_interfaces(0); 
                       
           for (iface = daemon->interfaces; iface; iface = iface->next)            for (iface = daemon->interfaces; iface; iface = iface->next)
             if (iface->addr.sa.sa_family == AF_INET &&              if (iface->addr.sa.sa_family == AF_INET &&
Line 824  void receive_query(struct listener *listen, time_t now Line 1246  void receive_query(struct listener *listen, time_t now
       
   if (extract_request(header, (size_t)n, daemon->namebuff, &type))    if (extract_request(header, (size_t)n, daemon->namebuff, &type))
     {      {
      char types[20];#ifdef HAVE_AUTH
      struct auth_zone *zone;
      querystr(auth_dns ? "auth" : "query", types, type);#endif
      char *types = querystr(auth_dns ? "auth" : "query", type);
       
       if (listen->family == AF_INET)         if (listen->family == AF_INET) 
         log_query(F_QUERY | F_IPV4 | F_FORWARD, daemon->namebuff,           log_query(F_QUERY | F_IPV4 | F_FORWARD, daemon->namebuff, 
                   (struct all_addr *)&source_addr.in.sin_addr, types);                    (struct all_addr *)&source_addr.in.sin_addr, types);
Line 836  void receive_query(struct listener *listen, time_t now Line 1259  void receive_query(struct listener *listen, time_t now
         log_query(F_QUERY | F_IPV6 | F_FORWARD, daemon->namebuff,           log_query(F_QUERY | F_IPV6 | F_FORWARD, daemon->namebuff, 
                   (struct all_addr *)&source_addr.in6.sin6_addr, types);                    (struct all_addr *)&source_addr.in6.sin6_addr, types);
 #endif  #endif
     }  
   
 #ifdef HAVE_AUTH  #ifdef HAVE_AUTH
         /* find queries for zones we're authoritative for, and answer them directly */
         if (!auth_dns)
           for (zone = daemon->auth_zones; zone; zone = zone->next)
             if (in_zone(zone, daemon->namebuff, NULL))
               {
                 auth_dns = 1;
                 local_auth = 1;
                 break;
               }
   #endif
       }
     
   #ifdef HAVE_AUTH
   if (auth_dns)    if (auth_dns)
     {      {
      m = answer_auth(header, ((char *) header) + PACKETSZ, (size_t)n, now, &source_addr);      m = answer_auth(header, ((char *) header) + daemon->packet_buff_sz, (size_t)n, now, &source_addr, local_auth);
       if (m >= 1)        if (m >= 1)
        send_from(listen->fd, option_bool(OPT_NOWILD) || option_bool(OPT_CLEVERBIND),        {
                  (char *)header, m, &source_addr, &dst_addr, if_index);          send_from(listen->fd, option_bool(OPT_NOWILD) || option_bool(OPT_CLEVERBIND),
                     (char *)header, m, &source_addr, &dst_addr, if_index);
           daemon->auth_answer++;
         }
     }      }
   else    else
 #endif  #endif
     {      {
      m = answer_request(header, ((char *) header) + PACKETSZ, (size_t)n,       int ad_reqd, do_bit;
                         dst_addr_4, netmask, now);      m = answer_request(header, ((char *) header) + daemon->packet_buff_sz, (size_t)n, 
                          dst_addr_4, netmask, now, &ad_reqd, &do_bit);
               
       if (m >= 1)        if (m >= 1)
         {          {
Line 859  void receive_query(struct listener *listen, time_t now Line 1298  void receive_query(struct listener *listen, time_t now
           daemon->local_answer++;            daemon->local_answer++;
         }          }
       else if (forward_query(listen->fd, &source_addr, &dst_addr, if_index,        else if (forward_query(listen->fd, &source_addr, &dst_addr, if_index,
                             header, (size_t)n, now, NULL))                             header, (size_t)n, now, NULL, ad_reqd, do_bit))
         daemon->queries_forwarded++;          daemon->queries_forwarded++;
       else        else
         daemon->local_answer++;          daemon->local_answer++;
     }      }
 }  }
   
   #ifdef HAVE_DNSSEC
   
   /* UDP: we've got an unsigned answer, return STAT_INSECURE if we can prove there's no DS
      and therefore the answer shouldn't be signed, or STAT_BOGUS if it should be, or 
      STAT_NEED_DS_NEG and keyname if we need to do the query. */
   static int send_check_sign(time_t now, struct dns_header *header, size_t plen, char *name, char *keyname)
   {
     struct crec *crecp;
     char *name_start = name;
     int status = dnssec_chase_cname(now, header, plen, name, keyname);
     
     if (status != STAT_INSECURE)
       return status;
   
     while (1)
       {
         crecp = cache_find_by_name(NULL, name_start, now, F_DS);
         
         if (crecp && (crecp->flags & F_DNSSECOK))
           return (crecp->flags & F_NEG) ? STAT_INSECURE : STAT_BOGUS;
          
         if (crecp && (crecp->flags & F_NEG) && (name_start = strchr(name_start, '.')))
           {
             name_start++; /* chop a label off and try again */
             continue;
           }
   
         /* Reached the root */
         if (!name_start)
           return STAT_BOGUS;
   
         strcpy(keyname, name_start);
         return STAT_NEED_DS_NEG;
       }
   }
   
   /* Got answer to DS query from send_check_sign, check for proven non-existence, or make the next DS query to try. */
   static int do_check_sign(time_t now, struct dns_header *header, size_t plen, char *name, char *keyname, int class)
     
   { 
     char *name_start;
     unsigned char *p;
     int status;
   
     /* In this case only, a SERVFAIL reply allows us to continue up the tree, looking for a 
        suitable NSEC reply to DS queries. */
     if (RCODE(header) != SERVFAIL)
       { 
         status = dnssec_validate_ds(now, header, plen, name, keyname, class);
         
         if (status != STAT_INSECURE)
           {
             if (status == STAT_NO_DS)
               status = STAT_INSECURE;
             return status;
           }
       }
     
     p = (unsigned char *)(header+1);
     
     if (extract_name(header, plen, &p, name, 1, 4) &&
         (name_start = strchr(name, '.')))
       {
         name_start++; /* chop a label off and try again */
         strcpy(keyname, name_start);
         return STAT_NEED_DS_NEG;
       }
     
     return STAT_BOGUS;
   }
   
   /* Move toward the root, until we find a signed non-existance of a DS, in which case
      an unsigned answer is OK, or we find a signed DS, in which case there should be 
      a signature, and the answer is BOGUS */
   static int  tcp_check_for_unsigned_zone(time_t now, struct dns_header *header, size_t plen, int class, char *name, 
                                           char *keyname, struct server *server, int *keycount)
   {
     size_t m;
     unsigned char *packet, *payload;
     u16 *length;
     unsigned char *p = (unsigned char *)(header+1);
     int status;
     char *name_start = name;
   
     /* Get first insecure entry in CNAME chain */
     status = tcp_key_recurse(now, STAT_CHASE_CNAME, header, plen, class, name, keyname, server, keycount);
     if (status == STAT_BOGUS)
       return STAT_BOGUS;
     
     if (!(packet = whine_malloc(65536 + MAXDNAME + RRFIXEDSZ + sizeof(u16))))
       return STAT_BOGUS;
     
     payload = &packet[2];
     header = (struct dns_header *)payload;
     length = (u16 *)packet;
     
     while (1)
       {
         unsigned char *newhash, hash[HASH_SIZE];
         unsigned char c1, c2;
         struct crec *crecp = cache_find_by_name(NULL, name_start, now, F_DS);
    
         if (--(*keycount) == 0)
           {
             free(packet);
             return STAT_BOGUS;    
           }
   
         if (crecp && (crecp->flags & F_DNSSECOK))
           {
             free(packet);
             return (crecp->flags & F_NEG) ? STAT_INSECURE : STAT_BOGUS;
           }
         
         /* If we have cached insecurely that a DS doesn't exist, 
            ise that is a hit for where to start looking for the secure one */
         if (crecp && (crecp->flags & F_NEG) && (name_start = strchr(name_start, '.')))
           {
             name_start++; /* chop a label off and try again */
             continue;
           }
   
         /* reached the root */
         if (!name_start)
           {
             free(packet);
             return STAT_BOGUS;
           }
   
         m = dnssec_generate_query(header, ((char *) header) + 65536, name_start, class, T_DS, &server->addr);
         
         /* We rely on the question section coming back unchanged, ensure it is with the hash. */
         if ((newhash = hash_questions(header, (unsigned int)m, name)))
           {
             memcpy(hash, newhash, HASH_SIZE);
         
             *length = htons(m);
             
             if (read_write(server->tcpfd, packet, m + sizeof(u16), 0) &&
                 read_write(server->tcpfd, &c1, 1, 1) &&
                 read_write(server->tcpfd, &c2, 1, 1) &&
                 read_write(server->tcpfd, payload, (c1 << 8) | c2, 1))
               {
                 m = (c1 << 8) | c2;
                 
                 newhash = hash_questions(header, (unsigned int)m, name);
                 if (newhash && memcmp(hash, newhash, HASH_SIZE) == 0)
                   {
                      /* In this case only, a SERVFAIL reply allows us to continue up the tree, looking for a 
                         suitable NSEC reply to DS queries. */
                     if (RCODE(header) == SERVFAIL)
                       status = STAT_INSECURE;
                     else
                       /* Note this trashes all three name workspaces */
                       status = tcp_key_recurse(now, STAT_NEED_DS_NEG, header, m, class, name, keyname, server, keycount);
                     
                     /* We've found a DS which proves the bit of the DNS where the
                        original query is, is unsigned, so the answer is OK, 
                        if unvalidated. */
                     if (status == STAT_NO_DS)
                       {
                         free(packet);
                         return STAT_INSECURE;
                       }
                 
                     /* No DS, not got to DNSSEC-land yet, go up. */
                     if (status == STAT_INSECURE)
                       {
                         p = (unsigned char *)(header+1);
                         
                         if (extract_name(header, plen, &p, name, 1, 4) &&
                             (name_start = strchr(name, '.')))
                           {
                             name_start++; /* chop a label off and try again */
                             continue;
                           }
                       }
                   }
               }
           }
         
         free(packet);
   
         return STAT_BOGUS;
       }
   }
   
   static int tcp_key_recurse(time_t now, int status, struct dns_header *header, size_t n, 
                              int class, char *name, char *keyname, struct server *server, int *keycount)
   {
     /* Recurse up the key heirarchy */
     int new_status;
   
     /* limit the amount of work we do, to avoid cycling forever on loops in the DNS */
     if (--(*keycount) == 0)
       return STAT_INSECURE;
     
     if (status == STAT_NEED_KEY)
       new_status = dnssec_validate_by_ds(now, header, n, name, keyname, class);
     else if (status == STAT_NEED_DS || status == STAT_NEED_DS_NEG)
       {
         new_status = dnssec_validate_ds(now, header, n, name, keyname, class);
         if (status == STAT_NEED_DS  && new_status == STAT_NO_DS)
           new_status = STAT_INSECURE;
       }
     else if (status == STAT_CHASE_CNAME)
       new_status = dnssec_chase_cname(now, header, n, name, keyname);
     else 
       {
         new_status = dnssec_validate_reply(now, header, n, name, keyname, &class, NULL);
         
         if (new_status == STAT_NO_SIG)
           {
             if (option_bool(OPT_DNSSEC_NO_SIGN))
               new_status = tcp_check_for_unsigned_zone(now, header, n, class, name, keyname, server, keycount);
             else
               new_status = STAT_INSECURE;
           }
       }
   
     /* Can't validate because we need a key/DS whose name now in keyname.
        Make query for same, and recurse to validate */
     if (new_status == STAT_NEED_DS || new_status == STAT_NEED_KEY)
       {
         size_t m; 
         unsigned char *packet = whine_malloc(65536 + MAXDNAME + RRFIXEDSZ + sizeof(u16));
         unsigned char *payload = &packet[2];
         struct dns_header *new_header = (struct dns_header *)payload;
         u16 *length = (u16 *)packet;
         unsigned char c1, c2;
          
         if (!packet)
           return STAT_INSECURE;
   
       another_tcp_key:
         m = dnssec_generate_query(new_header, ((char *) new_header) + 65536, keyname, class, 
                                   new_status == STAT_NEED_KEY ? T_DNSKEY : T_DS, &server->addr);
         
         *length = htons(m);
         
         if (!read_write(server->tcpfd, packet, m + sizeof(u16), 0) ||
             !read_write(server->tcpfd, &c1, 1, 1) ||
             !read_write(server->tcpfd, &c2, 1, 1) ||
             !read_write(server->tcpfd, payload, (c1 << 8) | c2, 1))
           new_status = STAT_INSECURE;
         else
           {
             m = (c1 << 8) | c2;
             
             new_status = tcp_key_recurse(now, new_status, new_header, m, class, name, keyname, server, keycount);
             
             if (new_status == STAT_SECURE)
               {
                 /* Reached a validated record, now try again at this level.
                    Note that we may get ANOTHER NEED_* if an answer needs more than one key.
                    If so, go round again. */
                 
                 if (status == STAT_NEED_KEY)
                   new_status = dnssec_validate_by_ds(now, header, n, name, keyname, class);
                 else if (status == STAT_NEED_DS || status == STAT_NEED_DS_NEG)
                   {
                     new_status = dnssec_validate_ds(now, header, n, name, keyname, class);
                     if (status == STAT_NEED_DS && new_status == STAT_NO_DS)
                       new_status = STAT_INSECURE; /* Validated no DS */
                   }
                 else if (status == STAT_CHASE_CNAME)
                   new_status = dnssec_chase_cname(now, header, n, name, keyname);
                 else 
                   {
                     new_status = dnssec_validate_reply(now, header, n, name, keyname, &class, NULL);
                     
                     if (new_status == STAT_NO_SIG)
                       {
                         if (option_bool(OPT_DNSSEC_NO_SIGN))
                           new_status = tcp_check_for_unsigned_zone(now, header, n, class, name, keyname, server, keycount);
                         else
                           new_status = STAT_INSECURE;
                       }
                   }
                 
                 if (new_status == STAT_NEED_DS || new_status == STAT_NEED_KEY)
                   goto another_tcp_key;
               }
           }
   
         free(packet);
       }
     return new_status;
   }
   #endif
   
   
 /* The daemon forks before calling this: it should deal with one connection,  /* The daemon forks before calling this: it should deal with one connection,
    blocking as neccessary, and then return. Note, need to be a bit careful     blocking as neccessary, and then return. Note, need to be a bit careful
    about resources for debug mode, when the fork is suppressed: that's     about resources for debug mode, when the fork is suppressed: that's
Line 875  unsigned char *tcp_request(int confd, time_t now, Line 1606  unsigned char *tcp_request(int confd, time_t now,
 {  {
   size_t size = 0;    size_t size = 0;
   int norebind = 0;    int norebind = 0;
  int checking_disabled;#ifdef HAVE_AUTH
   int local_auth = 0;
 #endif
   int checking_disabled, ad_question, do_bit, added_pheader = 0;
   int check_subnet, no_cache_dnssec = 0, cache_secure = 0;
   size_t m;    size_t m;
   unsigned short qtype;    unsigned short qtype;
   unsigned int gotname;    unsigned int gotname;
   unsigned char c1, c2;    unsigned char c1, c2;
  /* Max TCP packet + slop */  /* Max TCP packet + slop + size */
  unsigned char *packet = whine_malloc(65536 + MAXDNAME + RRFIXEDSZ);  unsigned char *packet = whine_malloc(65536 + MAXDNAME + RRFIXEDSZ + sizeof(u16));
  struct dns_header *header;  unsigned char *payload = &packet[2];
   /* largest field in header is 16-bits, so this is still sufficiently aligned */
   struct dns_header *header = (struct dns_header *)payload;
   u16 *length = (u16 *)packet;
   struct server *last_server;    struct server *last_server;
   struct in_addr dst_addr_4;    struct in_addr dst_addr_4;
   union mysockaddr peer_addr;    union mysockaddr peer_addr;
Line 890  unsigned char *tcp_request(int confd, time_t now, Line 1628  unsigned char *tcp_request(int confd, time_t now,
       
   if (getpeername(confd, (struct sockaddr *)&peer_addr, &peer_len) == -1)    if (getpeername(confd, (struct sockaddr *)&peer_addr, &peer_len) == -1)
     return packet;      return packet;
     
     /* We can be configured to only accept queries from at-most-one-hop-away addresses. */
     if (option_bool(OPT_LOCAL_SERVICE))
       {
         struct addrlist *addr;
   #ifdef HAVE_IPV6
         if (peer_addr.sa.sa_family == AF_INET6) 
           {
             for (addr = daemon->interface_addrs; addr; addr = addr->next)
               if ((addr->flags & ADDRLIST_IPV6) &&
                   is_same_net6(&addr->addr.addr.addr6, &peer_addr.in6.sin6_addr, addr->prefixlen))
                 break;
           }
         else
   #endif
           {
             struct in_addr netmask;
             for (addr = daemon->interface_addrs; addr; addr = addr->next)
               {
                 netmask.s_addr = 0xffffffff << (32 - addr->prefixlen);
                 if (!(addr->flags & ADDRLIST_IPV6) && 
                     is_same_net(addr->addr.addr.addr4, peer_addr.in.sin_addr, netmask))
                   break;
               }
           }
         if (!addr)
           {
             my_syslog(LOG_WARNING, _("Ignoring query from non-local network"));
             return packet;
           }
       }
   
   while (1)    while (1)
     {      {
       if (!packet ||        if (!packet ||
           !read_write(confd, &c1, 1, 1) || !read_write(confd, &c2, 1, 1) ||            !read_write(confd, &c1, 1, 1) || !read_write(confd, &c2, 1, 1) ||
           !(size = c1 << 8 | c2) ||            !(size = c1 << 8 | c2) ||
          !read_write(confd, packet, size, 1))          !read_write(confd, payload, size, 1))
         return packet;           return packet; 
       
       if (size < (int)sizeof(struct dns_header))        if (size < (int)sizeof(struct dns_header))
         continue;          continue;
               
      header = (struct dns_header *)packet;      check_subnet = 0;
   
       /* save state of "cd" flag in query */        /* save state of "cd" flag in query */
      checking_disabled = header->hb4 & HB4_CD;      if ((checking_disabled = header->hb4 & HB4_CD))
         no_cache_dnssec = 1;
                 
       /* RFC 4035: sect 4.6 para 2 */  
       header->hb4 &= ~HB4_AD;  
         
       if ((gotname = extract_request(header, (unsigned int)size, daemon->namebuff, &qtype)))        if ((gotname = extract_request(header, (unsigned int)size, daemon->namebuff, &qtype)))
         {          {
          char types[20];#ifdef HAVE_AUTH
           struct auth_zone *zone;
 #endif
           char *types = querystr(auth_dns ? "auth" : "query", qtype);
                       
           querystr(auth_dns ? "auth" : "query", types, qtype);  
             
           if (peer_addr.sa.sa_family == AF_INET)             if (peer_addr.sa.sa_family == AF_INET) 
             log_query(F_QUERY | F_IPV4 | F_FORWARD, daemon->namebuff,               log_query(F_QUERY | F_IPV4 | F_FORWARD, daemon->namebuff, 
                       (struct all_addr *)&peer_addr.in.sin_addr, types);                        (struct all_addr *)&peer_addr.in.sin_addr, types);
Line 924  unsigned char *tcp_request(int confd, time_t now, Line 1692  unsigned char *tcp_request(int confd, time_t now,
             log_query(F_QUERY | F_IPV6 | F_FORWARD, daemon->namebuff,               log_query(F_QUERY | F_IPV6 | F_FORWARD, daemon->namebuff, 
                       (struct all_addr *)&peer_addr.in6.sin6_addr, types);                        (struct all_addr *)&peer_addr.in6.sin6_addr, types);
 #endif  #endif
             
   #ifdef HAVE_AUTH
             /* find queries for zones we're authoritative for, and answer them directly */
             if (!auth_dns)
               for (zone = daemon->auth_zones; zone; zone = zone->next)
                 if (in_zone(zone, daemon->namebuff, NULL))
                   {
                     auth_dns = 1;
                     local_auth = 1;
                     break;
                   }
   #endif
         }          }
               
       if (local_addr->sa.sa_family == AF_INET)        if (local_addr->sa.sa_family == AF_INET)
Line 933  unsigned char *tcp_request(int confd, time_t now, Line 1713  unsigned char *tcp_request(int confd, time_t now,
               
 #ifdef HAVE_AUTH  #ifdef HAVE_AUTH
       if (auth_dns)        if (auth_dns)
        m = answer_auth(header, ((char *) header) + 65536, (size_t)size, now, &peer_addr);        m = answer_auth(header, ((char *) header) + 65536, (size_t)size, now, &peer_addr, local_auth);
       else        else
 #endif  #endif
         {          {
           /* m > 0 if answered from cache */            /* m > 0 if answered from cache */
           m = answer_request(header, ((char *) header) + 65536, (size_t)size,             m = answer_request(header, ((char *) header) + 65536, (size_t)size, 
                             dst_addr_4, netmask, now);                             dst_addr_4, netmask, now, &ad_question, &do_bit);
                       
           /* Do this by steam now we're not in the select() loop */            /* Do this by steam now we're not in the select() loop */
           check_log_writer(NULL);             check_log_writer(NULL); 
Line 953  unsigned char *tcp_request(int confd, time_t now, Line 1733  unsigned char *tcp_request(int confd, time_t now,
                               
               if (option_bool(OPT_ADD_MAC))                if (option_bool(OPT_ADD_MAC))
                 size = add_mac(header, size, ((char *) header) + 65536, &peer_addr);                  size = add_mac(header, size, ((char *) header) + 65536, &peer_addr);
                              
               if (option_bool(OPT_CLIENT_SUBNET))
                 {
                   size_t new = add_source_addr(header, size, ((char *) header) + 65536, &peer_addr);
                   if (size != new)
                     {
                       size = new;
                       check_subnet = 1;
                     }
                 }
 
               if (gotname)                if (gotname)
                 flags = search_servers(now, &addrp, gotname, daemon->namebuff, &type, &domain, &norebind);                  flags = search_servers(now, &addrp, gotname, daemon->namebuff, &type, &domain, &norebind);
                               
Line 965  unsigned char *tcp_request(int confd, time_t now, Line 1755  unsigned char *tcp_request(int confd, time_t now,
               if (!flags && last_server)                if (!flags && last_server)
                 {                  {
                   struct server *firstsendto = NULL;                    struct server *firstsendto = NULL;
   #ifdef HAVE_DNSSEC
                     unsigned char *newhash, hash[HASH_SIZE];
                     if ((newhash = hash_questions(header, (unsigned int)size, daemon->namebuff)))
                       memcpy(hash, newhash, HASH_SIZE);
                     else
                       memset(hash, 0, HASH_SIZE);
   #else
                   unsigned int crc = questions_crc(header, (unsigned int)size, daemon->namebuff);                    unsigned int crc = questions_crc(header, (unsigned int)size, daemon->namebuff);
                  #endif            
                   /* Loop round available servers until we succeed in connecting to one.                    /* Loop round available servers until we succeed in connecting to one.
                      Note that this code subtley ensures that consecutive queries on this connection                       Note that this code subtley ensures that consecutive queries on this connection
                      which can go to the same server, do so. */                       which can go to the same server, do so. */
Line 1001  unsigned char *tcp_request(int confd, time_t now, Line 1798  unsigned char *tcp_request(int confd, time_t now,
                               continue;                                continue;
                             }                              }
                                                       
   #ifdef HAVE_DNSSEC
                             if (option_bool(OPT_DNSSEC_VALID))
                               {
                                 size_t new_size = add_do_bit(header, size, ((char *) header) + 65536);
                                 
                                 /* For debugging, set Checking Disabled, otherwise, have the upstream check too,
                                    this allows it to select auth servers when one is returning bad data. */
                                 if (option_bool(OPT_DNSSEC_DEBUG))
                                   header->hb4 |= HB4_CD;
                                 
                                 if (size != new_size)
                                   added_pheader = 1;
                                 
                                 size = new_size;
                               }
   #endif
                             
 #ifdef HAVE_CONNTRACK  #ifdef HAVE_CONNTRACK
                           /* Copy connection mark of incoming query to outgoing connection. */                            /* Copy connection mark of incoming query to outgoing connection. */
                           if (option_bool(OPT_CONNTRACK))                            if (option_bool(OPT_CONNTRACK))
Line 1020  unsigned char *tcp_request(int confd, time_t now, Line 1834  unsigned char *tcp_request(int confd, time_t now,
 #endif    #endif  
                         }                          }
                                               
                      c1 = size >> 8;                      *length = htons(size);
                      c2 = size;
                       /* get query name again for logging - may have been overwritten */
                       if (!(gotname = extract_request(header, (unsigned int)size, daemon->namebuff, &qtype)))
                         strcpy(daemon->namebuff, "query");
                                               
                      if (!read_write(last_server->tcpfd, &c1, 1, 0) ||                      if (!read_write(last_server->tcpfd, packet, size + sizeof(u16), 0) ||
                          !read_write(last_server->tcpfd, &c2, 1, 0) || 
                          !read_write(last_server->tcpfd, packet, size, 0) || 
                           !read_write(last_server->tcpfd, &c1, 1, 1) ||                            !read_write(last_server->tcpfd, &c1, 1, 1) ||
                          !read_write(last_server->tcpfd, &c2, 1, 1))                          !read_write(last_server->tcpfd, &c2, 1, 1) ||
                           !read_write(last_server->tcpfd, payload, (c1 << 8) | c2, 1))
                         {                          {
                           close(last_server->tcpfd);                            close(last_server->tcpfd);
                           last_server->tcpfd = -1;                            last_server->tcpfd = -1;
Line 1035  unsigned char *tcp_request(int confd, time_t now, Line 1851  unsigned char *tcp_request(int confd, time_t now,
                         }                           } 
                                               
                       m = (c1 << 8) | c2;                        m = (c1 << 8) | c2;
                       if (!read_write(last_server->tcpfd, packet, m, 1))  
                         return packet;  
                                               
                       if (!gotname)  
                         strcpy(daemon->namebuff, "query");  
                       if (last_server->addr.sa.sa_family == AF_INET)                        if (last_server->addr.sa.sa_family == AF_INET)
                         log_query(F_SERVER | F_IPV4 | F_FORWARD, daemon->namebuff,                           log_query(F_SERVER | F_IPV4 | F_FORWARD, daemon->namebuff, 
                                   (struct all_addr *)&last_server->addr.in.sin_addr, NULL);                                     (struct all_addr *)&last_server->addr.in.sin_addr, NULL); 
Line 1048  unsigned char *tcp_request(int confd, time_t now, Line 1860  unsigned char *tcp_request(int confd, time_t now,
                         log_query(F_SERVER | F_IPV6 | F_FORWARD, daemon->namebuff,                           log_query(F_SERVER | F_IPV6 | F_FORWARD, daemon->namebuff, 
                                   (struct all_addr *)&last_server->addr.in6.sin6_addr, NULL);                                    (struct all_addr *)&last_server->addr.in6.sin6_addr, NULL);
 #endif   #endif 
   
   #ifdef HAVE_DNSSEC
                         if (option_bool(OPT_DNSSEC_VALID) && !checking_disabled)
                           {
                             int keycount = DNSSEC_WORK; /* Limit to number of DNSSEC questions, to catch loops and avoid filling cache. */
                             int status = tcp_key_recurse(now, STAT_TRUNCATED, header, m, 0, daemon->namebuff, daemon->keyname, last_server, &keycount);
                             char *result;
   
                             if (keycount == 0)
                               result = "ABANDONED";
                             else
                               result = (status == STAT_SECURE ? "SECURE" : (status == STAT_INSECURE ? "INSECURE" : "BOGUS"));
                             
                             log_query(F_KEYTAG | F_SECSTAT, "result", NULL, result);
                             
                             if (status == STAT_BOGUS)
                               no_cache_dnssec = 1;
                             
                             if (status == STAT_SECURE)
                               cache_secure = 1;
                           }
   #endif
   
                         /* restore CD bit to the value in the query */
                         if (checking_disabled)
                           header->hb4 |= HB4_CD;
                         else
                           header->hb4 &= ~HB4_CD;
                                               
                       /* There's no point in updating the cache, since this process will exit and                        /* There's no point in updating the cache, since this process will exit and
                          lose the information after a few queries. We make this call for the alias and                            lose the information after a few queries. We make this call for the alias and 
Line 1055  unsigned char *tcp_request(int confd, time_t now, Line 1895  unsigned char *tcp_request(int confd, time_t now,
                       /* If the crc of the question section doesn't match the crc we sent, then                        /* If the crc of the question section doesn't match the crc we sent, then
                          someone might be attempting to insert bogus values into the cache by                            someone might be attempting to insert bogus values into the cache by 
                          sending replies containing questions and bogus answers. */                           sending replies containing questions and bogus answers. */
                      if (crc == questions_crc(header, (unsigned int)m, daemon->namebuff))#ifdef HAVE_DNSSEC
                        m = process_reply(header, now, last_server, (unsigned int)m,                       newhash = hash_questions(header, (unsigned int)m, daemon->namebuff);
                                          option_bool(OPT_NO_REBIND) && !norebind, checking_disabled);                      if (!newhash || memcmp(hash, newhash, HASH_SIZE) != 0)
                         { 
                           m = 0;
                           break;
                         }
 #else                          
                       if (crc != questions_crc(header, (unsigned int)m, daemon->namebuff))
                         {
                           m = 0;
                           break;
                         }
 #endif
 
                       m = process_reply(header, now, last_server, (unsigned int)m, 
                                         option_bool(OPT_NO_REBIND) && !norebind, no_cache_dnssec,
                                         cache_secure, ad_question, do_bit, added_pheader, check_subnet, &peer_addr); 
                                               
                       break;                        break;
                     }                      }
Line 1071  unsigned char *tcp_request(int confd, time_t now, Line 1926  unsigned char *tcp_request(int confd, time_t now,
                       
       check_log_writer(NULL);        check_log_writer(NULL);
               
      c1 = m>>8;      *length = htons(m);
      c2 = m;           
      if (m == 0 ||      if (m == 0 || !read_write(confd, packet, m + sizeof(u16), 0))
          !read_write(confd, &c1, 1, 0) || 
          !read_write(confd, &c2, 1, 0) ||  
          !read_write(confd, packet, m, 0)) 
         return packet;          return packet;
     }      }
 }  }
Line 1095  static struct frec *allocate_frec(time_t now) Line 1947  static struct frec *allocate_frec(time_t now)
 #ifdef HAVE_IPV6  #ifdef HAVE_IPV6
       f->rfd6 = NULL;        f->rfd6 = NULL;
 #endif  #endif
   #ifdef HAVE_DNSSEC
         f->dependent = NULL;
         f->blocking_query = NULL;
         f->stash = NULL;
   #endif
       daemon->frec_list = f;        daemon->frec_list = f;
     }      }
   
Line 1136  static struct randfd *allocate_rfd(int family) Line 1993  static struct randfd *allocate_rfd(int family)
   
   return NULL; /* doom */    return NULL; /* doom */
 }  }
   
 static void free_frec(struct frec *f)  static void free_frec(struct frec *f)
 {  {
   if (f->rfd4 && --(f->rfd4->refcount) == 0)    if (f->rfd4 && --(f->rfd4->refcount) == 0)
Line 1152  static void free_frec(struct frec *f) Line 2008  static void free_frec(struct frec *f)
           
   f->rfd6 = NULL;    f->rfd6 = NULL;
 #endif  #endif
   
   #ifdef HAVE_DNSSEC
     if (f->stash)
       {
         blockdata_free(f->stash);
         f->stash = NULL;
       }
   
     /* Anything we're waiting on is pointless now, too */
     if (f->blocking_query)
       free_frec(f->blocking_query);
     f->blocking_query = NULL;
     f->dependent = NULL;
   #endif
 }  }
   
 /* if wait==NULL return a free or older than TIMEOUT record.  /* if wait==NULL return a free or older than TIMEOUT record.
    else return *wait zero if one available, or *wait is delay to     else return *wait zero if one available, or *wait is delay to
    when the oldest in-use record will expire. Impose an absolute     when the oldest in-use record will expire. Impose an absolute
   limit of 4*TIMEOUT before we wipe things (for random sockets) */   limit of 4*TIMEOUT before we wipe things (for random sockets).
struct frec *get_new_frec(time_t now, int *wait)   If force is set, always return a result, even if we have
    to allocate above the limit. */
 struct frec *get_new_frec(time_t now, int *wait, int force)
 {  {
   struct frec *f, *oldest, *target;    struct frec *f, *oldest, *target;
   int count;    int count;
Line 1207  struct frec *get_new_frec(time_t now, int *wait) Line 2079  struct frec *get_new_frec(time_t now, int *wait)
     }      }
       
   /* none available, calculate time 'till oldest record expires */    /* none available, calculate time 'till oldest record expires */
  if (count > daemon->ftabsize)  if (!force && count > daemon->ftabsize)
     {      {
         static time_t last_log = 0;
         
       if (oldest && wait)        if (oldest && wait)
         *wait = oldest->time + (time_t)TIMEOUT - now;          *wait = oldest->time + (time_t)TIMEOUT - now;
         
         if ((int)difftime(now, last_log) > 5)
           {
             last_log = now;
             my_syslog(LOG_WARNING, _("Maximum number of concurrent DNS queries reached (max: %d)"), daemon->ftabsize);
           }
   
       return NULL;        return NULL;
     }      }
       
Line 1222  struct frec *get_new_frec(time_t now, int *wait) Line 2103  struct frec *get_new_frec(time_t now, int *wait)
 }  }
     
 /* crc is all-ones if not known. */  /* crc is all-ones if not known. */
static struct frec *lookup_frec(unsigned short id, unsigned int crc)static struct frec *lookup_frec(unsigned short id, void *hash)
 {  {
   struct frec *f;    struct frec *f;
   
   for(f = daemon->frec_list; f; f = f->next)    for(f = daemon->frec_list; f; f = f->next)
     if (f->sentto && f->new_id == id &&       if (f->sentto && f->new_id == id && 
        (f->crc == crc || crc == 0xffffffff))        (!hash || memcmp(hash, f->hash, HASH_SIZE) == 0))
       return f;        return f;
               
   return NULL;    return NULL;
Line 1236  static struct frec *lookup_frec(unsigned short id, uns Line 2117  static struct frec *lookup_frec(unsigned short id, uns
   
 static struct frec *lookup_frec_by_sender(unsigned short id,  static struct frec *lookup_frec_by_sender(unsigned short id,
                                           union mysockaddr *addr,                                            union mysockaddr *addr,
                                          unsigned int crc)                                          void *hash)
 {  {
   struct frec *f;    struct frec *f;
       
   for(f = daemon->frec_list; f; f = f->next)    for(f = daemon->frec_list; f; f = f->next)
     if (f->sentto &&      if (f->sentto &&
         f->orig_id == id &&           f->orig_id == id && 
        f->crc == crc &&        memcmp(hash, f->hash, HASH_SIZE) == 0 &&
         sockaddr_isequal(&f->source, addr))          sockaddr_isequal(&f->source, addr))
       return f;        return f;
         
Line 1267  void server_gone(struct server *server) Line 2148  void server_gone(struct server *server)
 }  }
   
 /* return unique random ids. */  /* return unique random ids. */
static unsigned short get_id(unsigned int crc)static unsigned short get_id(void)
 {  {
   unsigned short ret = 0;    unsigned short ret = 0;
       
   do     do 
     ret = rand16();      ret = rand16();
  while (lookup_frec(ret, crc));  while (lookup_frec(ret, NULL));
       
   return ret;    return ret;
 }  }

Removed from v.1.1.1.1  
changed lines
  Added in v.1.1.1.2


FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>