From e1fa6cbab82fe424a94269e3ae9e106c10bf59be Mon Sep 17 00:00:00 2001
From: Evan Hunt <each@isc.org>
Date: Fri, 26 Aug 2022 15:38:34 -0700
Subject: [PATCH] dnstap query_message field was erroneously set with responses

The dnstap query_message field was in some cases being filled in
with response messages, along with the response_message field.
The query_message field should only be used when logging requests,
and the response_message field only when logging responses.

Conflict: NA
Reference: https://gitlab.isc.org/isc-projects/bind9/-/commit/e1fa6cbab82fe424a94269e3ae9e106c10bf59be
---
 lib/dns/dnstap.c | 18 ++++++++++++------
 1 file changed, 12 insertions(+), 6 deletions(-)

diff --git a/lib/dns/dnstap.c b/lib/dns/dnstap.c
index 30ca97e636..97f070937d 100644
--- a/lib/dns/dnstap.c
+++ b/lib/dns/dnstap.c
@@ -808,10 +808,11 @@ dns_dt_send(dns_view_t *view, dns_dtmsgtype_t msgtype, isc_sockaddr_t *qaddr,
 		dm.m.response_time_nsec = isc_time_nanoseconds(t);
 		dm.m.has_response_time_nsec = 1;
 
-		cpbuf(buf, &dm.m.response_message, &dm.m.has_response_message);
-
-		/* Types RR and FR get both query and response times */
-		if (msgtype == DNS_DTTYPE_CR || msgtype == DNS_DTTYPE_AR) {
+		/*
+		 * Types RR and FR can fall through and get the query
+		 * time set as well. Any other response type, break.
+		 */
+		if (msgtype != DNS_DTTYPE_RR && msgtype != DNS_DTTYPE_FR) {
 			break;
 		}
 
@@ -831,8 +832,6 @@ dns_dt_send(dns_view_t *view, dns_dtmsgtype_t msgtype, isc_sockaddr_t *qaddr,
 		dm.m.has_query_time_sec = 1;
 		dm.m.query_time_nsec = isc_time_nanoseconds(t);
 		dm.m.has_query_time_nsec = 1;
-
-		cpbuf(buf, &dm.m.query_message, &dm.m.has_query_message);
 		break;
 	default:
 		isc_log_write(dns_lctx, DNS_LOGCATEGORY_DNSTAP,
@@ -841,6 +840,13 @@ dns_dt_send(dns_view_t *view, dns_dtmsgtype_t msgtype, isc_sockaddr_t *qaddr,
 		return;
 	}
 
+	/* Query and response messages */
+	if ((msgtype & DNS_DTTYPE_QUERY) != 0) {
+		cpbuf(buf, &dm.m.query_message, &dm.m.has_query_message);
+	} else if ((msgtype & DNS_DTTYPE_RESPONSE) != 0) {
+		cpbuf(buf, &dm.m.response_message, &dm.m.has_response_message);
+	}
+
 	/* Zone/bailiwick */
 	switch (msgtype) {
 	case DNS_DTTYPE_AR:
-- 
2.23.0