f51a71
diff --git a/lib/dns/resolver.c b/lib/dns/resolver.c
f51a71
index 252a02f..bfffb8a 100644
f51a71
--- a/lib/dns/resolver.c
f51a71
+++ b/lib/dns/resolver.c
f51a71
@@ -5957,6 +5957,7 @@ is_answertarget_allowed(fetchctx_t *fctx, dns_name_t *qname, dns_name_t *rname,
f51a71
 	unsigned int nlabels;
f51a71
 	dns_fixedname_t fixed;
f51a71
 	dns_name_t prefix;
f51a71
+	int order;
f51a71
 
f51a71
 	REQUIRE(rdataset != NULL);
f51a71
 	REQUIRE(rdataset->type == dns_rdatatype_cname ||
f51a71
@@ -5979,18 +5980,26 @@ is_answertarget_allowed(fetchctx_t *fctx, dns_name_t *qname, dns_name_t *rname,
f51a71
 		tname = &cname.cname;
f51a71
 		break;
f51a71
 	case dns_rdatatype_dname:
f51a71
+		if (dns_name_fullcompare(qname, rname, &order, &nlabels) !=
f51a71
+		    dns_namereln_subdomain)
f51a71
+		{
f51a71
+			return (ISC_TRUE);
f51a71
+		}
f51a71
 		result = dns_rdata_tostruct(&rdata, &dname, NULL);
f51a71
 		RUNTIME_CHECK(result == ISC_R_SUCCESS);
f51a71
 		dns_name_init(&prefix, NULL);
f51a71
 		dns_fixedname_init(&fixed);
f51a71
 		tname = dns_fixedname_name(&fixed);
f51a71
-		nlabels = dns_name_countlabels(qname) -
f51a71
-			  dns_name_countlabels(rname);
f51a71
+		nlabels = dns_name_countlabels(rname);
f51a71
 		dns_name_split(qname, nlabels, &prefix, NULL);
f51a71
 		result = dns_name_concatenate(&prefix, &dname.dname, tname,
f51a71
 					      NULL);
f51a71
-		if (result == DNS_R_NAMETOOLONG)
f51a71
+		if (result == DNS_R_NAMETOOLONG) {
f51a71
+			if (chainingp != NULL) {
f51a71
+				*chainingp = ISC_TRUE;
f51a71
+			}
f51a71
 			return (ISC_TRUE);
f51a71
+		}
f51a71
 		RUNTIME_CHECK(result == ISC_R_SUCCESS);
f51a71
 		break;
f51a71
 	default:
f51a71
@@ -6719,7 +6728,9 @@ answer_response(fetchctx_t *fctx) {
f51a71
 		}
f51a71
 		if ((ardataset->type == dns_rdatatype_cname ||
f51a71
 		     ardataset->type == dns_rdatatype_dname) &&
f51a71
-		     !is_answertarget_allowed(fctx, qname, aname, ardataset,
f51a71
+		    type != ardataset->type &&
f51a71
+		    type != dns_rdatatype_any &&
f51a71
+		    !is_answertarget_allowed(fctx, qname, aname, ardataset,
f51a71
 					      NULL))
f51a71
 		{
f51a71
 			return (DNS_R_SERVFAIL);