From 2c1aec1e979a209eb2f2b035314a8c973b4ac269 Mon Sep 17 00:00:00 2001
From: Simon Kelley <simon@thekelleys.org.uk>
Date: Thu, 7 Sep 2017 20:45:00 +0100
Subject: [PATCH 7/9]     Don't return arcount=1 if EDNS0 RR won't fit in the
 packet.

    Omitting the EDNS0 RR but setting arcount gives a malformed packet.
    Also, don't accept UDP packet size less than 512 in recieved EDNS0.
---
 src/edns0.c   | 5 ++++-
 src/forward.c | 2 ++
 2 files changed, 6 insertions(+), 1 deletion(-)

diff --git a/src/edns0.c b/src/edns0.c
index 5bdc133..a8d0167 100644
--- a/src/edns0.c
+++ b/src/edns0.c
@@ -221,7 +221,10 @@ size_t add_pseudoheader(struct dns_header *header, size_t plen, unsigned char *l
 	  free(buff);
 	  p += rdlen;
 	}
-      header->arcount = htons(ntohs(header->arcount) + 1);
+      
+      /* Only bump arcount if RR is going to fit */ 
+      if (((ssize_t)optlen) <= (limit - (p + 4)))
+	header->arcount = htons(ntohs(header->arcount) + 1);
     }
   
   if (((ssize_t)optlen) > (limit - (p + 4)))
diff --git a/src/forward.c b/src/forward.c
index 9b464d3..0f8f462 100644
--- a/src/forward.c
+++ b/src/forward.c
@@ -1408,6 +1408,8 @@ void receive_query(struct listener *listen, time_t now)
 	 defaults to 512 */
       if (udp_size > daemon->edns_pktsz)
 	udp_size = daemon->edns_pktsz;
+      else if (udp_size < PACKETSZ)
+	udp_size = PACKETSZ; /* Sanity check - can't reduce below default. RFC 6891 6.2.3 */
     }
 
 #ifdef HAVE_AUTH
-- 
2.9.5

