HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/resolve/resolved-dns-dnssec.c

84,182 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 0e234111d3499f3d3425030135d88ba1f15c70fb

Lines 1001–2000 of 2,284

 
                        case DNSSEC_INVALID:
                                /* If the signature is invalid, let's try another
                                   key and/or signature. After all they
                                   key_tags and stuff are not unique, and
                                   might be shared by multiple keys. */
                                found_invalid = true;
                                continue;
 
                        case DNSSEC_UNSUPPORTED_ALGORITHM:
                                /* If the key algorithm is
                                   unsupported, try another
                                   RRSIG/DNSKEY pair, but remember we
                                   encountered this, so that we can
                                   return a proper error when we
                                   encounter nothing better. */
                                found_unsupported_algorithm = true;
                                continue;
 
                        case DNSSEC_SIGNATURE_EXPIRED:
                                /* If the signature is expired, try
                                   another one, but remember it, so
                                   that we can return this */
                                found_expired_rrsig = true;
                                continue;
 
                        default:
                                assert_not_reached();
                        }
                }
        }
 
        if (found_expired_rrsig)
                *result = DNSSEC_SIGNATURE_EXPIRED;
        else if (found_unsupported_algorithm)
                *result = DNSSEC_UNSUPPORTED_ALGORITHM;
        else if (found_invalid)
                *result = DNSSEC_INVALID;
        else if (found_rrsig)
                *result = DNSSEC_MISSING_KEY;
        else
                *result = DNSSEC_NO_SIGNATURE;
 
        if (ret_rrsig)
                *ret_rrsig = NULL;
 
        return (int) nvalidations;
}
 
int dnssec_has_rrsig(DnsAnswer *a, const DnsResourceKey *key) {
        DnsResourceRecord *rr;
        int r;
 
        /* Checks whether there's at least one RRSIG in 'a' that protects RRs of the specified key */
 
        DNS_ANSWER_FOREACH(rr, a) {
                r = dnssec_key_match_rrsig(key, rr);
                if (r < 0)
                        return r;
                if (r > 0)
                        return 1;
        }
 
        return 0;
}
 
static const EVP_MD* digest_to_hash_md(uint8_t algorithm) {
 
        /* Translates a DNSSEC digest algorithm into an openssl digest identifier */
 
        switch (algorithm) {
 
        case DNSSEC_DIGEST_SHA1:
                return sym_EVP_sha1();
 
        case DNSSEC_DIGEST_SHA256:
                return sym_EVP_sha256();
 
        case DNSSEC_DIGEST_SHA384:
                return sym_EVP_sha384();
 
        default:
                return NULL;
        }
}
 
int dnssec_verify_dnskey_by_ds(DnsResourceRecord *dnskey, DnsResourceRecord *ds, bool mask_revoke) {
        uint8_t wire_format[DNS_WIRE_FORMAT_HOSTNAME_MAX];
        size_t encoded_length;
        int r;
 
        assert(dnskey);
        assert(ds);
 
        r = dlopen_libcrypto(LOG_WARNING);
        if (r < 0)
                return r;
 
        /* Implements DNSKEY verification by a DS, according to RFC 4035, section 5.2 */
 
        if (dnskey->key->type != DNS_TYPE_DNSKEY)
                return -EINVAL;
        if (ds->key->type != DNS_TYPE_DS)
                return -EINVAL;
        if ((dnskey->dnskey.flags & DNSKEY_FLAG_ZONE_KEY) == 0)
                return -EKEYREJECTED;
        if (!mask_revoke && (dnskey->dnskey.flags & DNSKEY_FLAG_REVOKE))
                return -EKEYREJECTED;
        if (dnskey->dnskey.protocol != 3)
                return -EKEYREJECTED;
 
        if (dnskey->dnskey.algorithm != ds->ds.algorithm)
                return 0;
        if (dnssec_keytag(dnskey, mask_revoke) != ds->ds.key_tag)
                return 0;
 
        r = dns_name_to_wire_format(dns_resource_key_name(dnskey->key), wire_format, sizeof wire_format, true);
        if (r < 0)
                return r;
        encoded_length = r;
 
        const EVP_MD *md_algorithm = digest_to_hash_md(ds->ds.digest_type);
        if (!md_algorithm)
                return -EOPNOTSUPP;
 
        _cleanup_(EVP_MD_CTX_freep) EVP_MD_CTX *ctx = NULL;
        uint8_t result[EVP_MAX_MD_SIZE];
 
        unsigned hash_size = sym_EVP_MD_get_size(md_algorithm);
        assert(hash_size > 0);
 
        if (ds->ds.digest_size != hash_size)
                return 0;
 
        ctx = sym_EVP_MD_CTX_new();
        if (!ctx)
                return -ENOMEM;
 
        /* If the digest is supported by systemd-resolved but disabled by host policy, also return -EOPNOTSUPP
         */
        if (sym_EVP_DigestInit_ex(ctx, md_algorithm, NULL) <= 0)
                return -EOPNOTSUPP;
 
        if (sym_EVP_DigestUpdate(ctx, wire_format, encoded_length) <= 0)
                return dnssec_verify_errno(log_openssl_errors(LOG_DEBUG, "Failed to update digest"));
 
        if (mask_revoke)
                md_add_uint16(ctx, dnskey->dnskey.flags & ~DNSKEY_FLAG_REVOKE);
        else
                md_add_uint16(ctx, dnskey->dnskey.flags);
 
        r = md_add_uint8(ctx, dnskey->dnskey.protocol);
        if (r <= 0)
                return r;
        r = md_add_uint8(ctx, dnskey->dnskey.algorithm);
        if (r <= 0)
                return r;
        if (sym_EVP_DigestUpdate(ctx, dnskey->dnskey.key, dnskey->dnskey.key_size) <= 0)
                return dnssec_verify_errno(log_openssl_errors(LOG_DEBUG, "Failed to update digest"));
 
        if (sym_EVP_DigestFinal_ex(ctx, result, NULL) <= 0)
                return dnssec_verify_errno(log_openssl_errors(LOG_DEBUG, "Failed to finalize digest"));
 
        return memcmp(result, ds->ds.digest, ds->ds.digest_size) == 0;
}
 
int dnssec_verify_dnskey_by_ds_search(DnsResourceRecord *dnskey, DnsAnswer *validated_ds) {
        DnsResourceRecord *ds;
        DnsAnswerFlags flags;
        bool found_unsupported_algorithm = false;
        int r;
 
        assert(dnskey);
 
        if (dnskey->key->type != DNS_TYPE_DNSKEY)
                return 0;
 
        DNS_ANSWER_FOREACH_FLAGS(ds, flags, validated_ds) {
 
                if ((flags & DNS_ANSWER_AUTHENTICATED) == 0)
                        continue;
 
                if (ds->key->type != DNS_TYPE_DS)
                        continue;
                if (ds->key->class != dnskey->key->class)
                        continue;
 
                r = dns_name_equal(dns_resource_key_name(dnskey->key), dns_resource_key_name(ds->key));
                if (r < 0)
                        return r;
                if (r == 0)
                        continue;
 
                r = dnssec_verify_dnskey_by_ds(dnskey, ds, false);
                if (r == -EKEYREJECTED)
                        continue; /* The DNSKEY is revoked or otherwise invalid. */
                if (r == -EOPNOTSUPP) {
                        found_unsupported_algorithm = true;
                        continue;
                }
                if (r < 0)
                        return r;
                if (r > 0)
                        return 1;
        }
 
        if (found_unsupported_algorithm)
                return -EOPNOTSUPP;
 
        return 0;
}
 
static const EVP_MD* nsec3_hash_to_hash_md(uint8_t algorithm) {
 
        /* Translates a DNSSEC NSEC3 hash algorithm into an openssl digest identifier */
 
        switch (algorithm) {
 
        case NSEC3_ALGORITHM_SHA1:
                return sym_EVP_sha1();
 
        default:
                return NULL;
        }
}
 
int dnssec_nsec3_hash(DnsResourceRecord *nsec3, const char *name, void *ret) {
        uint8_t wire_format[DNS_WIRE_FORMAT_HOSTNAME_MAX];
        int r;
 
        assert(nsec3);
        assert(name);
        assert(ret);
 
        r = dlopen_libcrypto(LOG_WARNING);
        if (r < 0)
                return r;
 
        if (nsec3->key->type != DNS_TYPE_NSEC3)
                return -EINVAL;
 
        if (nsec3->nsec3.iterations > NSEC3_ITERATIONS_MAX)
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                       "Ignoring NSEC3 RR %s with excessive number of iterations.",
                                       dns_resource_record_to_string(nsec3));
 
        const EVP_MD *algorithm = nsec3_hash_to_hash_md(nsec3->nsec3.algorithm);
        if (!algorithm)
                return -EOPNOTSUPP;
 
        size_t hash_size = sym_EVP_MD_get_size(algorithm);
        assert(hash_size > 0);
 
        if (nsec3->nsec3.next_hashed_name_size != hash_size)
                return -EINVAL;
 
        _cleanup_(EVP_MD_CTX_freep) EVP_MD_CTX *ctx = sym_EVP_MD_CTX_new();
        if (!ctx)
                return -ENOMEM;
 
        if (sym_EVP_DigestInit_ex(ctx, algorithm, NULL) <= 0)
                return -EOPNOTSUPP;
 
        r = dns_name_to_wire_format(name, wire_format, sizeof(wire_format), true);
        if (r < 0)
                return r;
 
        if (sym_EVP_DigestUpdate(ctx, wire_format, r) <= 0)
                return dnssec_verify_errno(log_openssl_errors(LOG_DEBUG, "Failed to update digest"));
        if (sym_EVP_DigestUpdate(ctx, nsec3->nsec3.salt, nsec3->nsec3.salt_size) <= 0)
                return dnssec_verify_errno(log_openssl_errors(LOG_DEBUG, "Failed to update digest"));
 
        uint8_t result[EVP_MAX_MD_SIZE];
        if (sym_EVP_DigestFinal_ex(ctx, result, NULL) <= 0)
                return dnssec_verify_errno(log_openssl_errors(LOG_DEBUG, "Failed to finalize digest"));
 
        for (unsigned k = 0; k < nsec3->nsec3.iterations; k++) {
                if (sym_EVP_DigestInit_ex(ctx, algorithm, NULL) <= 0)
                        return -EOPNOTSUPP;
                if (sym_EVP_DigestUpdate(ctx, result, hash_size) <= 0)
                        return dnssec_verify_errno(log_openssl_errors(LOG_DEBUG, "Failed to update digest"));
                if (sym_EVP_DigestUpdate(ctx, nsec3->nsec3.salt, nsec3->nsec3.salt_size) <= 0)
                        return dnssec_verify_errno(log_openssl_errors(LOG_DEBUG, "Failed to update digest"));
 
                if (sym_EVP_DigestFinal_ex(ctx, result, NULL) <= 0)
                        return dnssec_verify_errno(log_openssl_errors(LOG_DEBUG, "Failed to finalize digest"));
        }
 
        memcpy(ret, result, hash_size);
        return (int) hash_size;
}
 
static int nsec3_is_good(DnsResourceRecord *rr, DnsResourceRecord *nsec3) {
        const char *a, *b;
        int r;
 
        assert(rr);
 
        if (rr->key->type != DNS_TYPE_NSEC3)
                return 0;
 
        /* RFC 5155, Section 8.2 says we MUST ignore NSEC3 RRs with flags != 0 or 1 */
        if (!IN_SET(rr->nsec3.flags, 0, 1))
                return 0;
 
        /* Ignore NSEC3 RRs whose algorithm we don't know */
        if (!nsec3_hash_to_hash_md(rr->nsec3.algorithm))
                return 0;
 
        /* Ignore NSEC3 RRs with an excessive number of required iterations */
        if (rr->nsec3.iterations > NSEC3_ITERATIONS_MAX)
                return 0;
 
        /* Ignore NSEC3 RRs generated from wildcards. If these NSEC3 RRs weren't correctly signed we can't make this
         * check (since rr->n_skip_labels_source is -1), but that's OK, as we won't trust them anyway in that case. */
        if (!IN_SET(rr->n_skip_labels_source, 0, UINT8_MAX))
                return 0;
        /* Ignore NSEC3 RRs that are located anywhere else than one label below the zone */
        if (!IN_SET(rr->n_skip_labels_signer, 1, UINT8_MAX))
                return 0;
 
        if (!nsec3)
                return 1;
 
        /* If a second NSEC3 RR is specified, also check if they are from the same zone. */
 
        if (nsec3 == rr) /* Shortcut */
                return 1;
 
        if (rr->key->class != nsec3->key->class)
                return 0;
        if (rr->nsec3.algorithm != nsec3->nsec3.algorithm)
                return 0;
        if (rr->nsec3.iterations != nsec3->nsec3.iterations)
                return 0;
        if (rr->nsec3.salt_size != nsec3->nsec3.salt_size)
                return 0;
        if (memcmp_safe(rr->nsec3.salt, nsec3->nsec3.salt, rr->nsec3.salt_size) != 0)
                return 0;
 
        a = dns_resource_key_name(rr->key);
        r = dns_name_parent(&a); /* strip off hash */
        if (r <= 0)
                return r;
 
        b = dns_resource_key_name(nsec3->key);
        r = dns_name_parent(&b); /* strip off hash */
        if (r <= 0)
                return r;
 
        /* Make sure both have the same parent */
        return dns_name_equal(a, b);
}
 
static int nsec3_hashed_domain_format(const uint8_t *hashed, size_t hashed_size, const char *zone, char **ret) {
        _cleanup_free_ char *l = NULL;
        char *j;
 
        assert(hashed);
        assert(hashed_size > 0);
        assert(zone);
        assert(ret);
 
        l = base32hexmem(hashed, hashed_size, false);
        if (!l)
                return -ENOMEM;
 
        j = strjoin(l, ".", zone);
        if (!j)
                return -ENOMEM;
 
        *ret = j;
        return (int) hashed_size;
}
 
static int nsec3_hashed_domain_make(DnsResourceRecord *nsec3, const char *domain, const char *zone, char **ret) {
        uint8_t hashed[DNSSEC_HASH_SIZE_MAX];
        int hashed_size;
 
        assert(nsec3);
        assert(domain);
        assert(zone);
        assert(ret);
 
        hashed_size = dnssec_nsec3_hash(nsec3, domain, hashed);
        if (hashed_size < 0)
                return hashed_size;
 
        return nsec3_hashed_domain_format(hashed, (size_t) hashed_size, zone, ret);
}
 
/* See RFC 5155, Section 8
 * First try to find a NSEC3 record that matches our query precisely, if that fails, find the closest
 * enclosure. Secondly, find a proof that there is no closer enclosure and either a proof that there
 * is no wildcard domain as a direct descendant of the closest enclosure, or find an NSEC3 record that
 * matches the wildcard domain.
 *
 * Based on this we can prove either the existence of the record in @key, or NXDOMAIN or NODATA, or
 * that there is no proof either way. The latter is the case if a proof of non-existence of a given
 * name uses an NSEC3 record with the opt-out bit set. Lastly, if we are given insufficient NSEC3 records
 * to conclude anything we indicate this by returning NO_RR. */
static int dnssec_test_nsec3(DnsAnswer *answer, DnsResourceKey *key, DnssecNsecResult *result, bool *authenticated, uint32_t *ttl) {
        _cleanup_free_ char *next_closer_domain = NULL, *wildcard_domain = NULL;
        const char *zone, *p, *pp = NULL, *wildcard;
        DnsResourceRecord *rr, *enclosure_rr, *zone_rr, *wildcard_rr = NULL;
        DnsAnswerFlags flags;
        int hashed_size, r;
        bool a, no_closer = false, no_wildcard = false, optout = false;
 
        assert(key);
        assert(result);
 
        /* First step, find the zone name and the NSEC3 parameters of the zone.
         * it is sufficient to look for the longest common suffix we find with
         * any NSEC3 RR in the response. Any NSEC3 record will do as all NSEC3
         * records from a given zone in a response must use the same
         * parameters. */
        zone = dns_resource_key_name(key);
        for (;;) {
                DNS_ANSWER_FOREACH_FLAGS(zone_rr, flags, answer) {
                        r = nsec3_is_good(zone_rr, NULL);
                        if (r < 0)
                                return r;
                        if (r == 0)
                                continue;
 
                        r = dns_name_equal_skip(dns_resource_key_name(zone_rr->key), 1, zone);
                        if (r < 0)
                                return r;
                        if (r > 0)
                                goto found_zone;
                }
 
                /* Strip one label from the front */
                r = dns_name_parent(&zone);
                if (r < 0)
                        return r;
                if (r == 0)
                        break;
        }
 
        *result = DNSSEC_NSEC_NO_RR;
        return 0;
 
found_zone:
        /* Second step, find the closest encloser NSEC3 RR in 'answer' that matches 'key' */
        p = dns_resource_key_name(key);
        for (;;) {
                _cleanup_free_ char *hashed_domain = NULL;
 
                hashed_size = nsec3_hashed_domain_make(zone_rr, p, zone, &hashed_domain);
                if (hashed_size == -EOPNOTSUPP) {
                        *result = DNSSEC_NSEC_UNSUPPORTED_ALGORITHM;
                        return 0;
                }
                if (hashed_size < 0)
                        return hashed_size;
 
                DNS_ANSWER_FOREACH_FLAGS(enclosure_rr, flags, answer) {
 
                        r = nsec3_is_good(enclosure_rr, zone_rr);
                        if (r < 0)
                                return r;
                        if (r == 0)
                                continue;
 
                        if (enclosure_rr->nsec3.next_hashed_name_size != (size_t) hashed_size)
                                continue;
 
                        r = dns_name_equal(dns_resource_key_name(enclosure_rr->key), hashed_domain);
                        if (r < 0)
                                return r;
                        if (r > 0) {
                                a = flags & DNS_ANSWER_AUTHENTICATED;
                                goto found_closest_encloser;
                        }
                }
 
                /* We didn't find the closest encloser with this name,
                 * but let's remember this domain name, it might be
                 * the next closer name */
 
                pp = p;
 
                /* Strip one label from the front */
                r = dns_name_parent(&p);
                if (r < 0)
                        return r;
                if (r == 0)
                        break;
        }
 
        *result = DNSSEC_NSEC_NO_RR;
        return 0;
 
found_closest_encloser:
        /* We found a closest encloser in 'p'; next closer is 'pp' */
 
        if (!pp) {
                /* We have an exact match! If we area looking for a DS RR, then we must insist that we got the NSEC3 RR
                 * from the parent. Otherwise the one from the child. Do so, by checking whether SOA and NS are
                 * appropriately set. */
 
                if (key->type == DNS_TYPE_DS) {
                        if (bitmap_isset(enclosure_rr->nsec3.types, DNS_TYPE_SOA))
                                return -EBADMSG;
                } else {
                        if (bitmap_isset(enclosure_rr->nsec3.types, DNS_TYPE_NS) &&
                            !bitmap_isset(enclosure_rr->nsec3.types, DNS_TYPE_SOA))
                                return -EBADMSG;
                }
 
                /* No next closer NSEC3 RR. That means there's a direct NSEC3 RR for our key. */
                if (bitmap_isset(enclosure_rr->nsec3.types, key->type))
                        *result = DNSSEC_NSEC_FOUND;
                else if (bitmap_isset(enclosure_rr->nsec3.types, DNS_TYPE_CNAME))
                        *result = DNSSEC_NSEC_CNAME;
                else
                        *result = DNSSEC_NSEC_NODATA;
 
                if (authenticated)
                        *authenticated = a;
                if (ttl)
                        *ttl = enclosure_rr->ttl;
 
                return 0;
        }
 
        /* Ensure this is not a DNAME domain, see RFC5155, section 8.3. */
        if (bitmap_isset(enclosure_rr->nsec3.types, DNS_TYPE_DNAME))
                return -EBADMSG;
 
        /* Ensure that this data is from the delegated domain
         * (i.e. originates from the "lower" DNS server), and isn't
         * just glue records (i.e. doesn't originate from the "upper"
         * DNS server). */
        if (bitmap_isset(enclosure_rr->nsec3.types, DNS_TYPE_NS) &&
            !bitmap_isset(enclosure_rr->nsec3.types, DNS_TYPE_SOA))
                return -EBADMSG;
 
        /* Prove that there is no next closer and whether or not there is a wildcard domain. */
 
        wildcard = strjoina("*.", p);
        r = nsec3_hashed_domain_make(enclosure_rr, wildcard, zone, &wildcard_domain);
        if (r < 0)
                return r;
        if (r != hashed_size)
                return -EBADMSG;
 
        r = nsec3_hashed_domain_make(enclosure_rr, pp, zone, &next_closer_domain);
        if (r < 0)
                return r;
        if (r != hashed_size)
                return -EBADMSG;
 
        DNS_ANSWER_FOREACH_FLAGS(rr, flags, answer) {
                _cleanup_free_ char *next_hashed_domain = NULL;
 
                r = nsec3_is_good(rr, zone_rr);
                if (r < 0)
                        return r;
                if (r == 0)
                        continue;
 
                r = nsec3_hashed_domain_format(rr->nsec3.next_hashed_name, rr->nsec3.next_hashed_name_size, zone, &next_hashed_domain);
                if (r < 0)
                        return r;
 
                r = dns_name_between(dns_resource_key_name(rr->key), next_closer_domain, next_hashed_domain);
                if (r < 0)
                        return r;
                if (r > 0) {
                        if (rr->nsec3.flags & 1)
                                optout = true;
 
                        a = a && (flags & DNS_ANSWER_AUTHENTICATED);
 
                        no_closer = true;
                }
 
                r = dns_name_equal(dns_resource_key_name(rr->key), wildcard_domain);
                if (r < 0)
                        return r;
                if (r > 0) {
                        a = a && (flags & DNS_ANSWER_AUTHENTICATED);
 
                        wildcard_rr = rr;
                }
 
                r = dns_name_between(dns_resource_key_name(rr->key), wildcard_domain, next_hashed_domain);
                if (r < 0)
                        return r;
                if (r > 0) {
                        if (rr->nsec3.flags & 1)
                                /* This only makes sense if we have a wildcard delegation, which is
                                 * very unlikely, see RFC 4592, Section 4.2, but we cannot rely on
                                 * this not happening, so hence cannot simply conclude NXDOMAIN as
                                 * we would wish */
                                optout = true;
 
                        a = a && (flags & DNS_ANSWER_AUTHENTICATED);
 
                        no_wildcard = true;
                }
        }
 
        if (wildcard_rr && no_wildcard)
                return -EBADMSG;
 
        if (!no_closer) {
                *result = DNSSEC_NSEC_NO_RR;
                return 0;
        }
 
        if (wildcard_rr) {
                /* A wildcard exists that matches our query. */
                if (optout)
                        /* This is not specified in any RFC to the best of my knowledge, but
                         * if the next closer enclosure is covered by an opt-out NSEC3 RR
                         * it means that we cannot prove that the source of synthesis is
                         * correct, as there may be a closer match. */
                        *result = DNSSEC_NSEC_OPTOUT;
                else if (bitmap_isset(wildcard_rr->nsec3.types, key->type))
                        *result = DNSSEC_NSEC_FOUND;
                else if (bitmap_isset(wildcard_rr->nsec3.types, DNS_TYPE_CNAME))
                        *result = DNSSEC_NSEC_CNAME;
                else
                        *result = DNSSEC_NSEC_NODATA;
        } else {
                if (optout)
                        /* The RFC only specifies that we have to care for optout for NODATA for
                         * DS records. However, children of an insecure opt-out delegation should
                         * also be considered opt-out, rather than verified NXDOMAIN.
                         * Note that we do not require a proof of wildcard non-existence if the
                         * next closer domain is covered by an opt-out, as that would not provide
                         * any additional information. */
                        *result = DNSSEC_NSEC_OPTOUT;
                else if (no_wildcard)
                        *result = DNSSEC_NSEC_NXDOMAIN;
                else {
                        *result = DNSSEC_NSEC_NO_RR;
 
                        return 0;
                }
        }
 
        if (authenticated)
                *authenticated = a;
 
        if (ttl)
                *ttl = enclosure_rr->ttl;
 
        return 0;
}
 
static int dnssec_nsec_wildcard_equal(DnsResourceRecord *rr, const char *name) {
        char label[DNS_LABEL_MAX+1];
        const char *n;
        int r;
 
        assert(rr);
        assert(rr->key->type == DNS_TYPE_NSEC);
 
        /* Checks whether the specified RR has a name beginning in "*.", and if the rest is a suffix of our name */
 
        if (rr->n_skip_labels_source != 1)
                return 0;
 
        n = dns_resource_key_name(rr->key);
        r = dns_label_unescape(&n, label, sizeof label, 0);
        if (r <= 0)
                return r;
        if (r != 1 || label[0] != '*')
                return 0;
 
        return dns_name_endswith(name, n);
}
 
static int dnssec_nsec_in_path(DnsResourceRecord *rr, const char *name) {
        const char *nn, *common_suffix;
        int r;
 
        assert(rr);
        assert(rr->key->type == DNS_TYPE_NSEC);
 
        /* Checks whether the specified nsec RR indicates that name is an empty non-terminal (ENT)
         *
         * A couple of examples:
         *
         *      NSEC             bar →   waldo.foo.bar: indicates that foo.bar exists and is an ENT
         *      NSEC   waldo.foo.bar → yyy.zzz.xoo.bar: indicates that xoo.bar and zzz.xoo.bar exist and are ENTs
         *      NSEC yyy.zzz.xoo.bar →             bar: indicates pretty much nothing about ENTs
         */
 
        /* First, determine parent of next domain. */
        nn = rr->nsec.next_domain_name;
        r = dns_name_parent(&nn);
        if (r <= 0)
                return r;
 
        /* If the name we just determined is not equal or child of the name we are interested in, then we can't say
         * anything at all. */
        r = dns_name_endswith(nn, name);
        if (r <= 0)
                return r;
 
        /* If the name we are interested in is not a prefix of the common suffix of the NSEC RR's owner and next domain names, then we can't say anything either. */
        r = dns_name_common_suffix(dns_resource_key_name(rr->key), rr->nsec.next_domain_name, &common_suffix);
        if (r < 0)
                return r;
 
        return dns_name_endswith(name, common_suffix);
}
 
static int dnssec_nsec_from_parent_zone(DnsResourceRecord *rr, const char *name) {
        int r;
 
        assert(rr);
        assert(rr->key->type == DNS_TYPE_NSEC);
 
        /* Checks whether this NSEC originates to the parent zone or the child zone. */
 
        r = dns_name_parent(&name);
        if (r <= 0)
                return r;
 
        r = dns_name_equal(name, dns_resource_key_name(rr->key));
        if (r <= 0)
                return r;
 
        /* DNAME, and NS without SOA is an indication for a delegation. */
        if (bitmap_isset(rr->nsec.types, DNS_TYPE_DNAME))
                return 1;
 
        if (bitmap_isset(rr->nsec.types, DNS_TYPE_NS) && !bitmap_isset(rr->nsec.types, DNS_TYPE_SOA))
                return 1;
 
        return 0;
}
 
static int dnssec_nsec_covers(DnsResourceRecord *rr, const char *name) {
        const char *signer;
        int r;
 
        assert(rr);
        assert(rr->key->type == DNS_TYPE_NSEC);
 
        /* Checks whether the name is covered by this NSEC RR. This means, that the name is somewhere below the NSEC's
         * signer name, and between the NSEC's two names. */
 
        r = dns_resource_record_signer(rr, &signer);
        if (r < 0)
                return r;
 
        r = dns_name_endswith(name, signer); /* this NSEC isn't suitable the name is not in the signer's domain */
        if (r <= 0)
                return r;
 
        return dns_name_between(dns_resource_key_name(rr->key), name, rr->nsec.next_domain_name);
}
 
static int dnssec_nsec_generate_wildcard(DnsResourceRecord *rr, const char *name, char **wc) {
        const char *common_suffix1, *common_suffix2, *signer;
        int r, labels1, labels2;
 
        assert(rr);
        assert(rr->key->type == DNS_TYPE_NSEC);
 
        /* Generates "Wildcard at the Closest Encloser" for the given name and NSEC RR. */
 
        r = dns_resource_record_signer(rr, &signer);
        if (r < 0)
                return r;
 
        r = dns_name_endswith(name, signer); /* this NSEC isn't suitable the name is not in the signer's domain */
        if (r <= 0)
                return r;
 
        r = dns_name_common_suffix(name, dns_resource_key_name(rr->key), &common_suffix1);
        if (r < 0)
                return r;
 
        r = dns_name_common_suffix(name, rr->nsec.next_domain_name, &common_suffix2);
        if (r < 0)
                return r;
 
        labels1 = dns_name_count_labels(common_suffix1);
        if (labels1 < 0)
            return labels1;
 
        labels2 = dns_name_count_labels(common_suffix2);
        if (labels2 < 0)
            return labels2;
 
        if (labels1 > labels2)
                r = dns_name_concat("*", common_suffix1, 0, wc);
        else
                r = dns_name_concat("*", common_suffix2, 0, wc);
 
        if (r < 0)
                return r;
 
        return 0;
}
 
int dnssec_nsec_test(DnsAnswer *answer, DnsResourceKey *key, DnssecNsecResult *result, bool *authenticated, uint32_t *ttl) {
        bool have_nsec3 = false, covering_rr_authenticated = false, wildcard_rr_authenticated = false;
        DnsResourceRecord *rr, *covering_rr = NULL, *wildcard_rr = NULL;
        DnsAnswerFlags flags;
        const char *name;
        int r;
 
        assert(key);
        assert(result);
 
        /* Look for any NSEC/NSEC3 RRs that say something about the specified key. */
 
        name = dns_resource_key_name(key);
 
        DNS_ANSWER_FOREACH_FLAGS(rr, flags, answer) {
 
                if (rr->key->class != key->class)
                        continue;
 
                have_nsec3 = have_nsec3 || (rr->key->type == DNS_TYPE_NSEC3);
 
                if (rr->key->type != DNS_TYPE_NSEC)
                        continue;
 
                /* The following checks only make sense for NSEC RRs that are not expanded from a wildcard */
                r = dns_resource_record_is_synthetic(rr);
                if (r == -ENODATA) /* No signing RR known. */
                        continue;
                if (r < 0)
                        return r;
                if (r > 0)
                        continue;
 
                /* Check if this is a direct match. If so, we have encountered a NODATA case */
                r = dns_name_equal(dns_resource_key_name(rr->key), name);
                if (r < 0)
                        return r;
                if (r == 0) {
                        /* If it's not a direct match, maybe it's a wild card match? */
                        r = dnssec_nsec_wildcard_equal(rr, name);
                        if (r < 0)
                                return r;
                }
                if (r > 0) {
                        if (key->type == DNS_TYPE_DS) {
                                /* If we look for a DS RR and the server sent us the NSEC RR of the child zone
                                 * we have a problem. For DS RRs we want the NSEC RR from the parent */
                                if (bitmap_isset(rr->nsec.types, DNS_TYPE_SOA))
                                        continue;
                        } else {
                                /* For all RR types, ensure that if NS is set SOA is set too, so that we know
                                 * we got the child's NSEC. */
                                if (bitmap_isset(rr->nsec.types, DNS_TYPE_NS) &&
                                    !bitmap_isset(rr->nsec.types, DNS_TYPE_SOA))
                                        continue;
                        }
 
                        if (bitmap_isset(rr->nsec.types, key->type))
                                *result = DNSSEC_NSEC_FOUND;
                        else if (bitmap_isset(rr->nsec.types, DNS_TYPE_CNAME))
                                *result = DNSSEC_NSEC_CNAME;
                        else
                                *result = DNSSEC_NSEC_NODATA;
 
                        if (authenticated)
                                *authenticated = flags & DNS_ANSWER_AUTHENTICATED;
                        if (ttl)
                                *ttl = rr->ttl;
 
                        return 0;
                }
 
                /* Check if the name we are looking for is an empty non-terminal within the owner or next name
                 * of the NSEC RR. */
                r = dnssec_nsec_in_path(rr, name);
                if (r < 0)
                        return r;
                if (r > 0) {
                        *result = DNSSEC_NSEC_NODATA;
 
                        if (authenticated)
                                *authenticated = flags & DNS_ANSWER_AUTHENTICATED;
                        if (ttl)
                                *ttl = rr->ttl;
 
                        return 0;
                }
 
                /* The following two "covering" checks, are not useful if the NSEC is from the parent */
                r = dnssec_nsec_from_parent_zone(rr, name);
                if (r < 0)
                        return r;
                if (r > 0)
                        continue;
 
                /* Check if this NSEC RR proves the absence of an explicit RR under this name */
                r = dnssec_nsec_covers(rr, name);
                if (r < 0)
                        return r;
                if (r > 0 && (!covering_rr || !covering_rr_authenticated)) {
                        covering_rr = rr;
                        covering_rr_authenticated = flags & DNS_ANSWER_AUTHENTICATED;
                }
        }
 
        if (covering_rr) {
                _cleanup_free_ char *wc = NULL;
                r = dnssec_nsec_generate_wildcard(covering_rr, name, &wc);
                if (r < 0)
                        return r;
 
                DNS_ANSWER_FOREACH_FLAGS(rr, flags, answer) {
 
                        if (rr->key->class != key->class)
                                continue;
 
                        if (rr->key->type != DNS_TYPE_NSEC)
                                continue;
 
                        /* Check if this NSEC RR proves the nonexistence of the wildcard */
                        r = dnssec_nsec_covers(rr, wc);
                        if (r < 0)
                                return r;
                        if (r > 0 && (!wildcard_rr || !wildcard_rr_authenticated)) {
                                wildcard_rr = rr;
                                wildcard_rr_authenticated = flags & DNS_ANSWER_AUTHENTICATED;
                        }
                }
        }
 
        if (covering_rr && wildcard_rr) {
                /* If we could prove that neither the name itself, nor the wildcard at the closest encloser exists, we
                 * proved the NXDOMAIN case. */
                *result = DNSSEC_NSEC_NXDOMAIN;
 
                if (authenticated)
                        *authenticated = covering_rr_authenticated && wildcard_rr_authenticated;
                if (ttl)
                        *ttl = MIN(covering_rr->ttl, wildcard_rr->ttl);
 
                return 0;
        }
 
        /* OK, this was not sufficient. Let's see if NSEC3 can help. */
        if (have_nsec3)
                return dnssec_test_nsec3(answer, key, result, authenticated, ttl);
 
        /* No appropriate NSEC RR found, report this. */
        *result = DNSSEC_NSEC_NO_RR;
        return 0;
}
 
static int dnssec_nsec_test_enclosed(DnsAnswer *answer, uint16_t type, const char *name, const char *zone, bool *authenticated) {
        DnsResourceRecord *rr;
        DnsAnswerFlags flags;
        int r;
 
        assert(name);
        assert(zone);
 
        /* Checks whether there's an NSEC/NSEC3 that proves that the specified 'name' is non-existing in the specified
         * 'zone'. The 'zone' must be a suffix of the 'name'. */
 
        DNS_ANSWER_FOREACH_FLAGS(rr, flags, answer) {
                bool found = false;
 
                if (rr->key->type != type && type != DNS_TYPE_ANY)
                        continue;
 
                switch (rr->key->type) {
 
                case DNS_TYPE_NSEC:
 
                        /* We only care for NSEC RRs from the indicated zone */
                        r = dns_resource_record_is_signer(rr, zone);
                        if (r < 0)
                                return r;
                        if (r == 0)
                                continue;
 
                        r = dns_name_between(dns_resource_key_name(rr->key), name, rr->nsec.next_domain_name);
                        if (r < 0)
                                return r;
 
                        found = r > 0;
                        break;
 
                case DNS_TYPE_NSEC3: {
                        _cleanup_free_ char *hashed_domain = NULL, *next_hashed_domain = NULL;
 
                        /* We only care for NSEC3 RRs from the indicated zone */
                        r = dns_resource_record_is_signer(rr, zone);
                        if (r < 0)
                                return r;
                        if (r == 0)