From f4b96e1ce7ba95893c8dff929f6e0ef1e5b22809 Mon Sep 17 00:00:00 2001
From: Daniel <dhaavi@users.noreply.github.com>
Date: Tue, 12 Nov 2024 15:13:44 +0100
Subject: [PATCH] Make saving IP and CNAMEs more defensive

---
 service/firewall/dns.go          | 6 +++---
 service/nameserver/nameserver.go | 2 +-
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/service/firewall/dns.go b/service/firewall/dns.go
index 8a6e1973..9b1a55e5 100644
--- a/service/firewall/dns.go
+++ b/service/firewall/dns.go
@@ -302,11 +302,11 @@ func UpdateIPsAndCNAMEs(q *resolver.Query, rrCache *resolver.RRCache, conn *netw
 			Expires:           rrCache.Expires,
 		}
 
-		// Resolve all CNAMEs in the correct order and add the to the record.
+		// Resolve all CNAMEs in the correct order and add the to the record - up to max 50 layers.
 		domain := q.FQDN
-		for {
+		for range 50 {
 			nextDomain, isCNAME := cnames[domain]
-			if !isCNAME {
+			if !isCNAME || nextDomain == domain {
 				break
 			}
 
diff --git a/service/nameserver/nameserver.go b/service/nameserver/nameserver.go
index c699cd99..1d346220 100644
--- a/service/nameserver/nameserver.go
+++ b/service/nameserver/nameserver.go
@@ -224,8 +224,8 @@ func handleRequest(ctx context.Context, w dns.ResponseWriter, request *dns.Msg)
 			}
 
 			// Save the request as open, as we don't know if there will be a connection or not.
-			network.SaveOpenDNSRequest(q, rrCache, conn)
 			firewall.UpdateIPsAndCNAMEs(q, rrCache, conn)
+			network.SaveOpenDNSRequest(q, rrCache, conn)
 
 		case network.VerdictUndeterminable:
 			fallthrough