commit 4273d3cfb8327724eec51a1c7f34daef2a8c30d7 Author: David Blacka Date: Sun Apr 19 13:56:34 2009 -0400 work in progress -- doesn't all compile yet, but it is starting to take shape diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6e094aa --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +build +.classpath +.project diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..6e20357 --- /dev/null +++ b/build.xml @@ -0,0 +1,334 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/dnsjava-2.0.6-vrsn-2.jar b/lib/dnsjava-2.0.6-vrsn-2.jar new file mode 100644 index 0000000..85a506e Binary files /dev/null and b/lib/dnsjava-2.0.6-vrsn-2.jar differ diff --git a/src/se/rfc/unbound/CaptiveValidator.java b/src/se/rfc/unbound/CaptiveValidator.java new file mode 100644 index 0000000..96e84d4 --- /dev/null +++ b/src/se/rfc/unbound/CaptiveValidator.java @@ -0,0 +1,716 @@ +/* + * Copyright (c) 2009 VeriSign, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +package se.rfc.unbound; + +import java.io.IOException; +import java.util.*; + +import org.xbill.DNS.*; + +/** + * This resolver module implements a "captive" DNSSEC validator. The captive + * validator does not have direct access to the Internet and DNS system -- + * instead it attempts to validate DNS messages using only configured context. + * This is useful for determining if responses coming from a given authoritative + * server will validate independent of the normal chain of trust. + */ + +public class CaptiveValidator { + + // A data structure holding all all of our trusted keys. + private TrustAnchorStore mTrustedKeys; + + // The local validation utilities. + private ValUtils mValUtils; + + // The local verification utility. + private DnsSecVerifier mVerifier; + + public CaptiveValidator() { + mVerifier = new DnsSecVerifier(); + mValUtils = new ValUtils(mVerifier); + mTrustedKeys = new TrustAnchorStore(); + } + + // ---------------- Module Initialization ------------------- + + /** + * Initialize the module. + */ + public void init(Properties config) throws Exception { + mVerifier.init(config); + + String s = config.getProperty("dns.trust_anchor_file"); + if (s != null) { + try { + loadTrustAnchors(s); + } catch (IOException e) { + System.err.println("Error loading trust anchors: " + e); + } + } + } + + /** + * Load the trust anchor file into the trust anchor store. The trust anchors + * are currently stored in a zone file format list of DNSKEY or DS records. + * + * @param filename + * The trust anchor file. + * @throws IOException + */ + private void loadTrustAnchors(String filename) throws IOException { + System.err.println("reading trust anchor file file: " + filename); + + // First read in the whole trust anchor file. + Master master = new Master(filename, Name.root, 0); + ArrayList records = new ArrayList(); + Record r = null; + + while ((r = master.nextRecord()) != null) { + records.add(r); + } + + // Record.compareTo() should sort them into DNSSEC canonical order. + // Don't care about canonical order per se, but do want them to be + // formable into RRsets. + Collections.sort(records); + + SRRset cur_rrset = new SRRset(); + for (Iterator i = records.iterator(); i.hasNext();) { + r = (Record) i.next(); + // Skip RR types that cannot be used as trust anchors. + if (r.getType() != Type.DNSKEY && r.getType() != Type.DS) continue; + + // If our cur_rrset is empty, we can just add it. + if (cur_rrset.size() == 0) { + cur_rrset.addRR(r); + continue; + } + // If this record matches our current RRset, we can just add it. + if (cur_rrset.getName().equals(r.getName()) + && cur_rrset.getType() == r.getType() + && cur_rrset.getDClass() == r.getDClass()) { + cur_rrset.addRR(r); + continue; + } + + // Otherwise, we add the rrset to our set of trust anchors. + mTrustedKeys.store(cur_rrset); + cur_rrset = new SRRset(); + cur_rrset.addRR(r); + } + + // add the last rrset (if it was not empty) + if (cur_rrset.size() > 0) { + mTrustedKeys.store(cur_rrset); + } + } + + // ----------------- Validation Support ---------------------- + + private SRRset findKeys(SMessage message) { + Name qname = message.getQName(); + int qclass = message.getQClass(); + + return mTrustedKeys.find(qname, qclass); + } + /** + * Check to see if a given response needs to go through the validation + * process. Typical reasons for this routine to return false are: CD bit was + * on in the original request, the response was already validated, or the + * response is a kind of message that is unvalidatable (i.e., SERVFAIL, + * REFUSED, etc.) + * + * @param message + * The message to check. + * @param origRequest + * The original request received from the client. + * + * @return true if the response could use validation (although this does not + * mean we can actually validate this response). + */ + private boolean needsValidation(SMessage message) { + + // FIXME: add check to see if message qname is at or below any of our + // configured trust anchors. + + int rcode = message.getRcode(); + + if (rcode != Rcode.NOERROR && rcode != Rcode.NXDOMAIN) { + // log.debug("cannot validate non-answer."); + // log.trace("non-answer: " + response); + return false; + } + + return true; + } + + /** + * Given a "positive" response -- a response that contains an answer to the + * question, and no CNAME chain, validate this response. This generally + * consists of verifying the answer RRset and the authority RRsets. + * + * Note that by the time this method is called, the process of finding the + * trusted DNSKEY rrset that signs this response must already have been + * completed. + * + * @param response + * The response to validate. + * @param request + * The request that generated this response. + * @param key_rrset + * The trusted DNSKEY rrset that matches the signer of the + * answer. + */ + private void validatePositiveResponse(SMessage message, SRRset key_rrset) { + Name qname = message.getQName(); + int qtype = message.getQType(); + + SMessage m = message; + + // validate the ANSWER section - this will be the answer itself + SRRset[] rrsets = m.getSectionRRsets(Section.ANSWER); + + Name wc = null; + boolean wcNSEC_ok = false; + boolean dname = false; + List nsec3s = null; + + for (int i = 0; i < rrsets.length; i++) { + // Skip the CNAME following a (validated) DNAME. + // Because of the normalization routines in NameserverClient, there + // will always be an unsigned CNAME following a DNAME (unless + // qtype=DNAME). + if (dname && rrsets[i].getType() == Type.CNAME) { + dname = false; + continue; + } + + // Verify the answer rrset. + int status = mValUtils.verifySRRset(rrsets[i], key_rrset); + // If the (answer) rrset failed to validate, then this message is + // BAD. + if (status != SecurityStatus.SECURE) { +// log.debug("Positive response has failed ANSWER rrset: " +// + rrsets[i]); + m.setStatus(SecurityStatus.BOGUS); + return; + } + // Check to see if the rrset is the result of a wildcard expansion. + // If so, an additional check will need to be made in the authority + // section. + wc = ValUtils.rrsetWildcard(rrsets[i]); + + // Notice a DNAME that should be followed by an unsigned CNAME. + if (qtype != Type.DNAME && rrsets[i].getType() == Type.DNAME) { + dname = true; + } + } + + // validate the AUTHORITY section as well - this will generally be the + // NS rrset (which could be missing, no problem) + rrsets = m.getSectionRRsets(Section.AUTHORITY); + for (int i = 0; i < rrsets.length; i++) { + int status = mValUtils.verifySRRset(rrsets[i], key_rrset); + // If anything in the authority section fails to be secure, we have + // a + // bad message. + if (status != SecurityStatus.SECURE) { +// log.debug("Positive response has failed AUTHORITY rrset: " +// + rrsets[i]); + m.setStatus(SecurityStatus.BOGUS); + return; + } + + // If this is a positive wildcard response, and we have a (just + // verified) NSEC record, try to use it to 1) prove that qname + // doesn't exist and 2) that the correct wildcard was used. + if (wc != null && rrsets[i].getType() == Type.NSEC) { + NSECRecord nsec = (NSECRecord) rrsets[i].first(); + + if (ValUtils.nsecProvesNameError(nsec, qname, + key_rrset.getName())) { + Name nsec_wc = ValUtils.nsecWildcard(qname, nsec); + if (!wc.equals(nsec_wc)) { +// log.debug("Postive wildcard response wasn't generated " +// + "by the correct wildcard"); + m.setStatus(SecurityStatus.BOGUS); + return; + } + wcNSEC_ok = true; + } + } + + // Otherwise, if this is a positive wildcard response and we have + // NSEC3 records, collect them. + if (wc != null && rrsets[i].getType() == Type.NSEC3) { + if (nsec3s == null) nsec3s = new ArrayList(); + nsec3s.add(rrsets[i].first()); + } + } + + // If this was a positive wildcard response that we haven't already + // proven, and we have NSEC3 records, try to prove it using the NSEC3 + // records. + if (wc != null && !wcNSEC_ok && nsec3s != null) { + if (NSEC3ValUtils.proveWildcard(nsec3s, qname, key_rrset.getName(), + wc)) { + wcNSEC_ok = true; + } + } + + // If after all this, we still haven't proven the positive wildcard + // response, fail. + if (wc != null && !wcNSEC_ok) { +// log.debug("positive response was wildcard expansion and " +// + "did not prove original data did not exist"); + m.setStatus(SecurityStatus.BOGUS); + return; + } + +// log.trace("Successfully validated postive response"); + m.setStatus(SecurityStatus.SECURE); + } + + /** + * Given an "ANY" response -- a response that contains an answer to a + * qtype==ANY question, with answers. This consists of simply verifying all + * present answer/auth RRsets, with no checking that all types are present. + * + * NOTE: it may be possible to get parent-side delegation point records + * here, which won't all be signed. Right now, this routine relies on the + * upstream iterative resolver to not return these responses -- instead + * treating them as referrals. + * + * NOTE: RFC 4035 is silent on this issue, so this may change upon + * clarification. + * + * Note that by the time this method is called, the process of finding the + * trusted DNSKEY rrset that signs this response must already have been + * completed. + * + * @param message + * The response to validate. + * @param key_rrset + * The trusted DNSKEY rrset that matches the signer of the + * answer. + */ + private void validateAnyResponse(SMessage message, SRRset key_rrset) { + int qtype = message.getQType(); + + if (qtype != Type.ANY) + throw new IllegalArgumentException( + "ANY validation called on non-ANY response."); + + SMessage m = message; + + // validate the ANSWER section. + SRRset[] rrsets = m.getSectionRRsets(Section.ANSWER); + for (int i = 0; i < rrsets.length; i++) { + int status = mValUtils.verifySRRset(rrsets[i], key_rrset); + // If the (answer) rrset failed to validate, then this message is + // BAD. + if (status != SecurityStatus.SECURE) { +// log.debug("Postive response has failed ANSWER rrset: " +// + rrsets[i]); + m.setStatus(SecurityStatus.BOGUS); + return; + } + } + + // validate the AUTHORITY section as well - this will be the NS rrset + // (which could be missing, no problem) + rrsets = m.getSectionRRsets(Section.AUTHORITY); + for (int i = 0; i < rrsets.length; i++) { + int status = mValUtils.verifySRRset(rrsets[i], key_rrset); + // If anything in the authority section fails to be secure, we have + // a + // bad message. + if (status != SecurityStatus.SECURE) { +// log.debug("Postive response has failed AUTHORITY rrset: " +// + rrsets[i]); + m.setStatus(SecurityStatus.BOGUS); + return; + } + } + +// log.trace("Successfully validated postive ANY response"); + m.setStatus(SecurityStatus.SECURE); + } + + /** + * Validate a NOERROR/NODATA signed response -- a response that has a + * NOERROR Rcode but no ANSWER section RRsets. This consists of verifying + * the authority section rrsets and making certain that the authority + * section NSEC/NSEC3s proves that the qname does exist and the qtype + * doesn't. + * + * Note that by the time this method is called, the process of finding the + * trusted DNSKEY rrset that signs this response must already have been + * completed. + * + * @param response + * The response to validate. + * @param request + * The request that generated this response. + * @param key_rrset + * The trusted DNSKEY rrset that signs this response. + */ + private void validateNodataResponse(SMessage message, SRRset key_rrset) { + Name qname = message.getQName(); + int qtype = message.getQType(); + + SMessage m = message; + + // Since we are here, there must be nothing in the ANSWER section to + // validate. (Note: CNAME/DNAME responses will not directly get here -- + // instead they are broken down into individual CNAME/DNAME/final answer + // responses.) + + // validate the AUTHORITY section + SRRset[] rrsets = m.getSectionRRsets(Section.AUTHORITY); + + boolean hasValidNSEC = false; // If true, then the NODATA has been + // proven. + Name ce = null; // for wildcard nodata responses. This is the proven + // closest encloser. + NSECRecord wc = null; // for wildcard nodata responses. This is the + // wildcard NSEC. + List nsec3s = null; // A collection of NSEC3 RRs found in the authority + // section. + Name nsec3Signer = null; // The RRSIG signer field for the NSEC3 RRs. + + for (int i = 0; i < rrsets.length; i++) { + int status = mValUtils.verifySRRset(rrsets[i], key_rrset); + if (status != SecurityStatus.SECURE) { +// log.debug("NODATA response has failed AUTHORITY rrset: " +// + rrsets[i]); + m.setStatus(SecurityStatus.BOGUS); + return; + } + + // If we encounter an NSEC record, try to use it to prove NODATA. + // This needs to handle the ENT NODATA case. + if (rrsets[i].getType() == Type.NSEC) { + NSECRecord nsec = (NSECRecord) rrsets[i].first(); + if (ValUtils.nsecProvesNodata(nsec, qname, qtype)) { + hasValidNSEC = true; + if (nsec.getName().isWild()) wc = nsec; + } else if (ValUtils.nsecProvesNameError( + nsec, + qname, + rrsets[i].getSignerName())) { + ce = ValUtils.closestEncloser(qname, nsec); + } + } + + // Collect any NSEC3 records present. + if (rrsets[i].getType() == Type.NSEC3) { + if (nsec3s == null) nsec3s = new ArrayList(); + nsec3s.add(rrsets[i].first()); + nsec3Signer = rrsets[i].getSignerName(); + } + } + + // check to see if we have a wildcard NODATA proof. + + // The wildcard NODATA is 1 NSEC proving that qname does not exists (and + // also proving what the closest encloser is), and 1 NSEC showing the + // matching wildcard, which must be *.closest_encloser. + if (ce != null || wc != null) { + try { + Name wc_name = new Name("*", ce); + if (!wc_name.equals(wc.getName())) { + hasValidNSEC = false; + } + } catch (TextParseException e) { +// log.error(e); + } + } + + NSEC3ValUtils.stripUnknownAlgNSEC3s(nsec3s); + + if (!hasValidNSEC && nsec3s != null && nsec3s.size() > 0) { + // try to prove NODATA with our NSEC3 record(s) + hasValidNSEC = NSEC3ValUtils.proveNodata(nsec3s, qname, qtype, + nsec3Signer); + } + + if (!hasValidNSEC) { +// log.debug("NODATA response failed to prove NODATA " +// + "status with NSEC/NSEC3"); +// log.trace("Failed NODATA:\n" + m); + m.setStatus(SecurityStatus.BOGUS); + return; + } +// log.trace("sucessfully validated NODATA response."); + m.setStatus(SecurityStatus.SECURE); + } + + /** + * Validate a NAMEERROR signed response -- a response that has a NXDOMAIN + * Rcode. This consists of verifying the authority section rrsets and making + * certain that the authority section NSEC proves that the qname doesn't + * exist and the covering wildcard also doesn't exist.. + * + * Note that by the time this method is called, the process of finding the + * trusted DNSKEY rrset that signs this response must already have been + * completed. + * + * @param response + * The response to validate. + * @param request + * The request that generated this response. + * @param key_rrset + * The trusted DNSKEY rrset that signs this response. + */ + private void validateNameErrorResponse(SMessage message, SRRset key_rrset) { + Name qname = message.getQName(); + + SMessage m = message; + + // FIXME: should we check to see if there is anything in the answer + // section? if so, what should the result be? + + // Validate the authority section -- all RRsets in the authority section + // must be signed and valid. + // In addition, the NSEC record(s) must prove the NXDOMAIN condition. + + boolean hasValidNSEC = false; + boolean hasValidWCNSEC = false; + SRRset[] rrsets = m.getSectionRRsets(Section.AUTHORITY); + List nsec3s = null; + Name nsec3Signer = null; + + for (int i = 0; i < rrsets.length; i++) { + int status = mValUtils.verifySRRset(rrsets[i], key_rrset); + if (status != SecurityStatus.SECURE) { +// log.debug("NameError response has failed AUTHORITY rrset: " +// + rrsets[i]); + m.setStatus(SecurityStatus.BOGUS); + return; + } + if (rrsets[i].getType() == Type.NSEC) { + NSECRecord nsec = (NSECRecord) rrsets[i].first(); + + if (ValUtils.nsecProvesNameError(nsec, qname, + rrsets[i].getSignerName())) { + hasValidNSEC = true; + } + if (ValUtils.nsecProvesNoWC(nsec, qname, + rrsets[i].getSignerName())) { + hasValidWCNSEC = true; + } + } + if (rrsets[i].getType() == Type.NSEC3) { + if (nsec3s == null) nsec3s = new ArrayList(); + nsec3s.add(rrsets[i].first()); + nsec3Signer = rrsets[i].getSignerName(); + } + } + + NSEC3ValUtils.stripUnknownAlgNSEC3s(nsec3s); + + if (nsec3s != null && nsec3s.size() > 0) { +// log.debug("Validating nxdomain: using NSEC3 records"); + // Attempt to prove name error with nsec3 records. + + if (NSEC3ValUtils.allNSEC3sIgnoreable(nsec3s, key_rrset, mVerifier)) { +// log.debug("all NSEC3s were validated but ignored."); + m.setStatus(SecurityStatus.INSECURE); + return; + } + + hasValidNSEC = NSEC3ValUtils.proveNameError(nsec3s, qname, + nsec3Signer); + + // Note that we assume that the NSEC3ValUtils proofs encompass the + // wildcard part of the proof. + hasValidWCNSEC = hasValidNSEC; + } + + // If the message fails to prove either condition, it is bogus. + if (!hasValidNSEC) { +// log.debug("NameError response has failed to prove: " +// + "qname does not exist"); + m.setStatus(SecurityStatus.BOGUS); + return; + } + + if (!hasValidWCNSEC) { +// log.debug("NameError response has failed to prove: " +// + "covering wildcard does not exist"); + m.setStatus(SecurityStatus.BOGUS); + return; + } + + // Otherwise, we consider the message secure. +// log.trace("successfully validated NAME ERROR response."); + m.setStatus(SecurityStatus.SECURE); + } + +// /** +// * This state is used for validating CNAME-type responses -- i.e., responses +// * that have CNAME chains. +// * +// * It primarily is responsible for breaking down the response into a series +// * of separately validated queries & responses. +// * +// * @param event +// * @param state +// * @return +// */ +// private boolean processCNAME(DNSEvent event, ValEventState state) { +// Request req = event.getRequest(); +// +// Name qname = req.getQName(); +// int qtype = req.getQType(); +// int qclass = req.getQClass(); +// +// SMessage m = event.getResponse().getSMessage(); +// +// if (state.cnameSname == null) state.cnameSname = qname; +// +// // We break the chain down by re-querying for the specific CNAME or +// // DNAME +// // (or final answer). +// SRRset[] rrsets = m.getSectionRRsets(Section.ANSWER); +// +// while (state.cnameIndex < rrsets.length) { +// SRRset rrset = rrsets[state.cnameIndex++]; +// Name rname = rrset.getName(); +// int rtype = rrset.getType(); +// +// // Skip DNAMEs -- prefer to query for the generated CNAME, +// if (rtype == Type.DNAME && qtype != Type.DNAME) continue; +// +// // Set the SNAME if we are dealing with a CNAME +// if (rtype == Type.CNAME) { +// CNAMERecord cname = (CNAMERecord) rrset.first(); +// state.cnameSname = cname.getTarget(); +// } +// +// // Note if the current rrset is the answer. In that case, we want to +// // set +// // the final state differently. +// // For non-answers, the response ultimately comes back here. +// int final_state = ValEventState.CNAME_RESP_STATE; +// if (isAnswerRRset(rrset.getName(), rtype, state.cnameSname, qtype, +// Section.ANSWER)) { +// // If this is an answer, however, break out of this loop. +// final_state = ValEventState.CNAME_ANS_RESP_STATE; +// } +// +// // Generate the sub-query. +// Request localRequest = generateLocalRequest(rname, rtype, qclass); +// DNSEvent localEvent = generateLocalEvent(event, localRequest, +// ValEventState.INIT_STATE, +// final_state); +// +// // ...and send it along. +// processLocalRequest(localEvent); +// return false; +// } +// +// // Something odd has happened if we get here. +// log.warn("processCNAME: encountered unknown issue handling a CNAME chain."); +// return false; +// } +// +// private boolean processCNAMEResponse(DNSEvent event, ValEventState state) { +// DNSEvent forEvent = event.forEvent(); +// ValEventState forState = getModuleState(forEvent); +// +// SMessage resp = event.getResponse().getSMessage(); +// if (resp.getStatus() != SecurityStatus.SECURE) { +// forEvent.getResponse().getSMessage().setStatus(resp.getStatus()); +// forState.state = forState.finalState; +// handleResponse(forEvent, forState); +// return false; +// } +// +// forState.state = ValEventState.CNAME_STATE; +// handleResponse(forEvent, forState); +// return false; +// } +// +// private boolean processCNAMEAnswer(DNSEvent event, ValEventState state) { +// DNSEvent forEvent = event.forEvent(); +// ValEventState forState = getModuleState(forEvent); +// +// SMessage resp = event.getResponse().getSMessage(); +// SMessage forResp = forEvent.getResponse().getSMessage(); +// +// forResp.setStatus(resp.getStatus()); +// +// forState.state = forState.finalState; +// handleResponse(forEvent, forState); +// return false; +// } + + + public byte validateMessage(SMessage message) { + + SRRset key_rrset = findKeys(message); + if (key_rrset == null) { + return SecurityStatus.BOGUS; + } + + int subtype = ValUtils.classifyResponse(message); + + switch (subtype) { + case ValUtils.POSITIVE: + // log.trace("Validating a positive response"); + validatePositiveResponse(message, key_rrset); + break; + case ValUtils.NODATA: + // log.trace("Validating a nodata response"); + validateNodataResponse(message, key_rrset); + break; + case ValUtils.NAMEERROR: + // log.trace("Validating a nxdomain response"); + validateNameErrorResponse(message, key_rrset); + break; + case ValUtils.CNAME: + // log.trace("Validating a cname response"); + // forward on to the special CNAME state for this. +// state.state = ValEventState.CNAME_STATE; + break; + case ValUtils.ANY: + // log.trace("Validating a postive ANY response"); + validateAnyResponse(message, key_rrset); + break; + default: + // log.error("unhandled response subtype: " + subtype); + } + + return message.getSecurityStatus().getStatus(); + + } +} diff --git a/src/se/rfc/unbound/DnsSecVerifier.java b/src/se/rfc/unbound/DnsSecVerifier.java new file mode 100644 index 0000000..239316e --- /dev/null +++ b/src/se/rfc/unbound/DnsSecVerifier.java @@ -0,0 +1,499 @@ +/* + * $Id$ + * + * Copyright (c) 2005 VeriSign, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +package se.rfc.unbound.validator; + +import java.util.*; +import java.io.*; +import java.security.*; + +import org.apache.log4j.Logger; +import org.xbill.DNS.*; +import org.xbill.DNS.security.*; + +import se.rfc.unbound.SecurityStatus; +import se.rfc.unbound.Util; + +/** + * A class for performing basic DNSSEC verification. The DNSJAVA package + * contains a similar class. This is a reimplementation that allows us to have + * finer control over the validation process. + * + * @author davidb + * @version $Revision$ + */ +public class DnsSecVerifier +{ + public static final int UNKNOWN = 0; + public static final int RSA = 1; + public static final int DSA = 2; + + /** + * This is a mapping of DNSSEC algorithm numbers/private identifiers to JCA + * algorithm identifiers. + */ + private HashMap mAlgorithmMap; + + private Logger log = Logger.getLogger(this.getClass()); + + private static class AlgEntry + { + public String jcaName; + public boolean isDSA; + public int dnssecAlg; + + public AlgEntry(String name, int dnssecAlg, boolean isDSA) + { + jcaName = name; + this.dnssecAlg = dnssecAlg; + this.isDSA = isDSA; + } + } + + public DnsSecVerifier() + { + mAlgorithmMap = new HashMap(); + + // set the default algorithm map. + mAlgorithmMap.put(new Integer(DNSSEC.RSAMD5), new AlgEntry("MD5withRSA", + DNSSEC.RSAMD5, false)); + mAlgorithmMap.put(new Integer(DNSSEC.DSA), new AlgEntry("SHA1withDSA", DNSSEC.DSA, + true)); + mAlgorithmMap.put(new Integer(DNSSEC.RSASHA1), new AlgEntry( + "SHA1withRSA", DNSSEC.RSASHA1, false)); + } + + private boolean isDSA(int algorithm) + { + // shortcut the standard algorithms + if (algorithm == DNSSEC.DSA) return true; + if (algorithm == DNSSEC.RSASHA1) return false; + if (algorithm == DNSSEC.RSAMD5) return false; + + AlgEntry entry = (AlgEntry) mAlgorithmMap.get(new Integer(algorithm)); + if (entry != null) return entry.isDSA; + return false; + } + + public void init(Properties config) + { + if (config == null) return; + + // Algorithm configuration + + // For now, we just accept new identifiers for existing algoirthms. + // FIXME: handle private identifiers. + List aliases = Util.parseConfigPrefix(config, "dns.algorithm."); + + for (Iterator i = aliases.iterator(); i.hasNext();) + { + Util.ConfigEntry entry = (Util.ConfigEntry) i.next(); + + Integer alg_alias = new Integer(Util.parseInt(entry.key, -1)); + Integer alg_orig = new Integer(Util.parseInt(entry.value, -1)); + + if (!mAlgorithmMap.containsKey(alg_orig)) + { + log.warn("Unable to alias " + alg_alias + " to unknown algorithm " + + alg_orig); + continue; + } + + if (mAlgorithmMap.containsKey(alg_alias)) + { + log.warn("Algorithm alias " + alg_alias + + " is already defined and cannot be redefined"); + continue; + } + + mAlgorithmMap.put(alg_alias, mAlgorithmMap.get(alg_orig)); + } + + // for debugging purposes, log the entire algorithm map table. + for (Iterator i = mAlgorithmMap.keySet().iterator(); i.hasNext(); ) + { + Integer alg = (Integer) i.next(); + AlgEntry entry = (AlgEntry) mAlgorithmMap.get(alg); + if (entry == null) + log.warn("DNSSEC alg " + alg + " has a null entry!"); + else + log.debug("DNSSEC alg " + alg + " maps to " + entry.jcaName + + " (" + entry.dnssecAlg + ")"); + } + } + + /** + * Find the matching DNSKEY(s) to an RRSIG within a DNSKEY rrset. Normally + * this will only return one DNSKEY. It can return more than one, since + * KeyID/Footprints are not guaranteed to be unique. + * + * @param dnskey_rrset The DNSKEY rrset to search. + * @param signature The RRSIG to match against. + * @return A List contains a one or more DNSKEYRecord objects, or null if a + * matching DNSKEY could not be found. + */ + private List findKey(RRset dnskey_rrset, RRSIGRecord signature) + { + if (!signature.getSigner().equals(dnskey_rrset.getName())) + { + log.trace("findKey: could not find appropriate key because " + + "incorrect keyset was supplied. Wanted: " + signature.getSigner() + + ", got: " + dnskey_rrset.getName()); + return null; + } + + int keyid = signature.getFootprint(); + int alg = signature.getAlgorithm(); + + List res = new ArrayList(dnskey_rrset.size()); + + for (Iterator i = dnskey_rrset.rrs(); i.hasNext();) + { + DNSKEYRecord r = (DNSKEYRecord) i.next(); + if (r.getAlgorithm() == alg && r.getFootprint() == keyid) + { + res.add(r); + } + } + + if (res.size() == 0) + { + log.trace("findKey: could not find a key matching " + + "the algorithm and footprint in supplied keyset. "); + return null; + } + return res; + } + + /** + * Check to see if a signature looks valid (i.e., matches the rrset in + * question, in the validity period, etc.) + * + * @param rrset The rrset that the signature belongs to. + * @param sigrec The signature record to check. + * @return A value of DNSSEC.Secure if it looks OK, DNSSEC.Faile if it looks + * bad. + */ + private byte checkSignature(RRset rrset, RRSIGRecord sigrec) + { + if (rrset == null || sigrec == null) return DNSSEC.Failed; + if (!rrset.getName().equals(sigrec.getName())) + { + log.debug("Signature name does not match RRset name"); + return SecurityStatus.BOGUS; + } + if (rrset.getType() != sigrec.getTypeCovered()) + { + log.debug("Signature type does not match RRset type"); + return SecurityStatus.BOGUS; + } + + Date now = new Date(); + Date start = sigrec.getTimeSigned(); + Date expire = sigrec.getExpire(); + if (now.before(start)) + { + log.debug("Signature is not yet valid"); + return SecurityStatus.BOGUS; + } + + if (now.after(expire)) + { + log.debug("Signature has expired (now = " + now + ", sig expires = " + + expire); + return SecurityStatus.BOGUS; + } + + return SecurityStatus.SECURE; + } + + public PublicKey parseDNSKEY(DNSKEYRecord key) + { + AlgEntry ae = (AlgEntry) mAlgorithmMap + .get(new Integer(key.getAlgorithm())); + if (key.getAlgorithm() != ae.dnssecAlg) + { + // Recast the DNSKEYRecord in question as one using the offical + // algorithm, to work around the lack of alias support in the underlying + // KEYConverter class from DNSjava + + key = new DNSKEYRecord(key.getName(), key.getDClass(), key.getTTL(), + key.getFlags(), key.getProtocol(), ae.dnssecAlg, key.getKey()); + } + + return KEYConverter.parseRecord(key); + } + + + /** + * Actually cryptographically verify a signature over the rrset. The RRSIG + * record must match the rrset being verified (see checkSignature). + * + * @param rrset The rrset to verify. + * @param sigrec The signature to verify with. + * @param key The (public) key associated with the RRSIG record. + * @return A security status code: SECURE if it worked, BOGUS if not, + * UNCHECKED if we just couldn't actually do the function. + */ + public byte verifySignature(RRset rrset, RRSIGRecord sigrec, + DNSKEYRecord key) + { + try + { + PublicKey pk = parseDNSKEY(key); + + if (pk == null) + { + log.warn("Could not convert DNSKEY record to a JCA public key: " + + key); + return SecurityStatus.UNCHECKED; + } + + byte[] data = SignUtils.generateSigData(rrset, sigrec); + + Signature signer = getSignature(sigrec.getAlgorithm()); + if (signer == null) + { + return SecurityStatus.BOGUS; + } + + signer.initVerify(pk); + signer.update(data); + + byte[] sig = sigrec.getSignature(); + if (isDSA(sigrec.getAlgorithm())) + { + sig = SignUtils.convertDSASignature(sig); + } + if (!signer.verify(sig)) + { + log.info("Signature failed to verify cryptographically"); + log.debug("Failed signature: " + sigrec); + return SecurityStatus.BOGUS; + } + log.trace("Signature verified: " + sigrec); + return SecurityStatus.SECURE; + } + catch (IOException e) + { + log.error("I/O error", e); + } + catch (GeneralSecurityException e) + { + log.error("Security error", e); + } + + // FIXME: Since I'm not sure what would cause an exception here (failure + // to have the required crypto?) + // We default to UNCHECKED instead of BOGUS. This could be wrong. + return SecurityStatus.UNCHECKED; + + } + + /** + * Verify an RRset against a particular signature. + * + * @return DNSSEC.Secure if the signature verfied, DNSSEC.Failed if it did + * not verify (for any reason), and DNSSEC.Insecure if verification + * could not be completed (usually because the public key was not + * available). + */ + public byte verifySignature(RRset rrset, RRSIGRecord sigrec, RRset key_rrset) + { + byte result = checkSignature(rrset, sigrec); + if (result != SecurityStatus.SECURE) return result; + + List keys = findKey(key_rrset, sigrec); + + if (keys == null) + { + log.trace("could not find appropriate key"); + return SecurityStatus.BOGUS; + } + + byte status = SecurityStatus.UNCHECKED; + + for (Iterator i = keys.iterator(); i.hasNext();) + { + DNSKEYRecord key = (DNSKEYRecord) i.next(); + status = verifySignature(rrset, sigrec, key); + + if (status == SecurityStatus.SECURE) break; + } + + return status; + } + + /** + * Verifies an RRset. This routine does not modify the RRset. This RRset is + * presumed to be verifiable, and the correct DNSKEY rrset is presumed to + * have been found. + * + * @return SecurityStatus.SECURE if the rrest verified positively, + * SecurityStatus.BOGUS otherwise. + */ + public byte verify(RRset rrset, RRset key_rrset) + { + Iterator i = rrset.sigs(); + + if (!i.hasNext()) + { + log.info("RRset failed to verify due to lack of signatures"); + return SecurityStatus.BOGUS; + } + + while (i.hasNext()) + { + RRSIGRecord sigrec = (RRSIGRecord) i.next(); + + byte res = verifySignature(rrset, sigrec, key_rrset); + + if (res == SecurityStatus.SECURE) return res; + } + + log.info("RRset failed to verify: all signatures were BOGUS"); + return SecurityStatus.BOGUS; + } + + /** + * Verify an RRset against a single DNSKEY. Use this when you must be + * certain that an RRset signed and verifies with a particular DNSKEY (as + * opposed to a particular DNSKEY rrset). + * + * @param rrset The rrset to verify. + * @param dnskey The DNSKEY to verify with. + * @return SecurityStatus.SECURE if the rrset verified, BOGUS otherwise. + */ + public byte verify(RRset rrset, DNSKEYRecord dnskey) + { + // Iterate over RRSIGS + + Iterator i = rrset.sigs(); + if (!i.hasNext()) + { + log.info("RRset failed to verify due to lack of signatures"); + return SecurityStatus.BOGUS; + } + + while (i.hasNext()) + { + RRSIGRecord sigrec = (RRSIGRecord) i.next(); + + // Skip RRSIGs that do not match our given key's footprint. + if (sigrec.getFootprint() != dnskey.getFootprint()) continue; + + byte res = verifySignature(rrset, sigrec, dnskey); + + if (res == SecurityStatus.SECURE) return res; + } + + log.info("RRset failed to verify: all signatures were BOGUS"); + return SecurityStatus.BOGUS; + } + + public boolean supportsAlgorithm(int algorithm) + { + return mAlgorithmMap.containsKey(new Integer(algorithm)); + } + + public boolean supportsAlgorithm(Name private_id) + { + return mAlgorithmMap.containsKey(private_id); + } + + public int baseAlgorithm(int algorithm) + { + switch (algorithm) + { + case DNSSEC.RSAMD5: + case DNSSEC.RSASHA1: + return RSA; + case DNSSEC.DSA: + return DSA; + } + AlgEntry entry = (AlgEntry) mAlgorithmMap.get(new Integer(algorithm)); + if (entry == null) return UNKNOWN; + if (entry.isDSA) return DSA; + return RSA; + } + + /** @return the appropriate Signature object for this keypair. */ + private Signature getSignature(int algorithm) + { + Signature s = null; + + + try + { + AlgEntry entry = (AlgEntry) mAlgorithmMap.get(new Integer(algorithm)); + if (entry == null) + { + log.info("DNSSEC algorithm " + algorithm + " not recognized."); + return null; + } + // TODO: should we cache the instance? + s = Signature.getInstance(entry.jcaName); + } + catch (NoSuchAlgorithmException e) + { + log.error("error getting Signature object", e); + } + + return s; + } + + // TODO: enable private algorithm support in dnsjava. + // Right now, this cannot be used because the DNSKEYRecord object doesn't + // give us + // the private key name. + // private Signature getSignature(Name private_alg) + // { + // Signature s = null; + // + // try + // { + // String alg_id = (String) mAlgorithmMap.get(private_alg); + // if (alg_id == null) + // { + // log.debug("DNSSEC private algorithm '" + private_alg + // + "' not recognized."); + // return null; + // } + // + // s = Signature.getInstance(alg_id); + // } + // catch (NoSuchAlgorithmException e) + // { + // log.error("error getting Signature object", e); + // } + // + // return s; + // } +} diff --git a/src/se/rfc/unbound/NSEC3ValUtils.java b/src/se/rfc/unbound/NSEC3ValUtils.java new file mode 100644 index 0000000..73bd0f8 --- /dev/null +++ b/src/se/rfc/unbound/NSEC3ValUtils.java @@ -0,0 +1,868 @@ +/* + * $Id$ + * + * Copyright (c) 2006 VeriSign. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. 2. Redistributions in + * binary form must reproduce the above copyright notice, this list of + * conditions and the following disclaimer in the documentation and/or other + * materials provided with the distribution. 3. The name of the author may not + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN + * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +package se.rfc.unbound; + +import java.security.NoSuchAlgorithmException; +import java.util.*; + +import org.apache.log4j.Logger; +import org.xbill.DNS.*; +import org.xbill.DNS.utils.base32; + +import se.rfc.unbound.validator.DnsSecVerifier; +import se.rfc.unbound.validator.SignUtils; +import se.rfc.unbound.validator.SignUtils.ByteArrayComparator; + +public class NSEC3ValUtils +{ + + // FIXME: should probably refactor to handle different NSEC3 parameters more + // efficiently. + // Given a list of NSEC3 RRs, they should be grouped according to + // parameters. The idea is to hash and compare for each group independently, + // instead of having to skip NSEC3 RRs with the wrong parameters. + + // The logger to use in static methods. + private static Logger st_log = Logger.getLogger(NSEC3ValUtils.class); + + private static Name asterisk_label = Name.fromConstantString("*"); + + /** + * This is a class to encapsulate a unique set of NSEC3 parameters: + * algorithm, iterations, and salt. + */ + private static class NSEC3Parameters + { + public byte alg; + public byte[] salt; + public int iterations; + + public NSEC3Parameters(NSEC3Record r) + { + alg = r.getHashAlgorithm(); + salt = r.getSalt(); + iterations = r.getIterations(); + } + + public boolean match(NSEC3Record r, ByteArrayComparator bac) + { + if (r.getHashAlgorithm() != alg) return false; + if (r.getIterations() != iterations) return false; + + if (salt == null && r.getSalt() != null) return false; + + if (bac == null) bac = new ByteArrayComparator(); + return bac.compare(r.getSalt(), salt) == 0; + } + } + + /** + * This is just a simple class to enapsulate the response to a closest + * encloser proof. + */ + private static class CEResponse + { + public Name closestEncloser; + public NSEC3Record ce_nsec3; + public NSEC3Record nc_nsec3; + + public CEResponse(Name ce, NSEC3Record nsec3) + { + this.closestEncloser = ce; + this.ce_nsec3 = nsec3; + } + } + + public static boolean supportsHashAlgorithm(int alg) + { + if (alg == NSEC3Record.SHA1_DIGEST_ID) return true; + return false; + } + + public static void stripUnknownAlgNSEC3s(List nsec3s) + { + if (nsec3s == null) return; + for (ListIterator i = nsec3s.listIterator(); i.hasNext(); ) + { + NSEC3Record nsec3 = (NSEC3Record) i.next(); + if (!supportsHashAlgorithm(nsec3.getHashAlgorithm())) + { + i.remove(); + } + } + } + + /** + * Given a list of NSEC3Records that are part of a message, determine the + * NSEC3 parameters (hash algorithm, iterations, and salt) present. If there + * is more than one distinct grouping, return null; + * + * @param nsec3s A list of NSEC3Record object. + * @return A set containing a number of objects (NSEC3Parameter objects) + * that correspond to each distinct set of parameters, or null if + * the nsec3s list was empty. + */ + public static NSEC3Parameters nsec3Parameters(List nsec3s) + { + if (nsec3s == null || nsec3s.size() == 0) return null; + + NSEC3Parameters params = new NSEC3Parameters((NSEC3Record) nsec3s.get(0)); + ByteArrayComparator bac = new ByteArrayComparator(); + + for (Iterator i = nsec3s.iterator(); i.hasNext();) + { + if (! params.match((NSEC3Record) i.next(), bac)) + { + return null; + } + } + return params; + } + + /** + * In a list of NSEC3Record object pulled from a given message, find the + * NSEC3 that directly matches a given name, without hashing. + * + * @param n The name in question. + * @param nsec3s A list of NSEC3Records from a given message. + * @return The matching NSEC3Record, or null if there wasn't one. + */ + // private static NSEC3Record findDirectMatchingNSEC3(Name n, List nsec3s) + // { + // if (n == null || nsec3s == null) return null; + // + // for (Iterator i = nsec3s.iterator(); i.hasNext();) + // { + // NSEC3Record nsec3 = (NSEC3Record) i.next(); + // if (n.equals(nsec3.getName())) return nsec3; + // } + // + // return null; + // } + /** + * Given a hash and an a zone name, construct an NSEC3 ownername. + * + * @param hash The hash of an original name. + * @param zonename The zone to use in constructing the NSEC3 name. + * @return The NSEC3 name. + */ + private static Name hashName(byte[] hash, Name zonename) + { + try + { + return new Name(base32.toString(hash).toLowerCase(), zonename); + } + catch (TextParseException e) + { + // Note, this should never happen. + return null; + } + } + + /** + * Given a set of NSEC3 parameters, hash a name. + * + * @param name The name to hash. + * @param params The parameters to hash with. + * @return The hash. + */ + private static byte[] hash(Name name, NSEC3Parameters params) + { + try + { + return NSEC3Record.hash(name, + params.alg, + params.iterations, + params.salt); + } + catch (NoSuchAlgorithmException e) + { + st_log.debug("Did not recognize hash algorithm: " + params.alg); + return null; + } + } + + /** + * Given the name of a closest encloser, return the name *.closest_encloser. + * + * @param closestEncloser The name to start with. + * @return The wildcard name. + */ + private static Name ceWildcard(Name closestEncloser) + { + try + { + Name wc = Name.concatenate(asterisk_label, closestEncloser); + return wc; + } + catch (NameTooLongException e) + { + return null; + } + } + + /** + * Given a qname and its proven closest encloser, calculate the "next + * closest" name. Basically, this is the name that is one label longer than + * the closest encloser that is still a subdomain of qname. + * + * @param qname The qname. + * @param closestEncloser The closest encloser name. + * @return The next closer name. + */ + private static Name nextClosest(Name qname, Name closestEncloser) + { + int strip = qname.labels() - closestEncloser.labels() - 1; + return (strip > 0) ? new Name(qname, strip) : qname; + } + + /** + * Find the NSEC3Record that matches a hash of a name. + * + * @param hash The pre-calculated hash of a name. + * @param zonename The name of the zone that the NSEC3s are from. + * @param nsec3s A list of NSEC3Records from a given message. + * @param params The parameters used for calculating the hash. + * @param bac An already allocated ByteArrayComparator, for reuse. This may + * be null. + * + * @return The matching NSEC3Record, if one is present. + */ + private static NSEC3Record findMatchingNSEC3(byte[] hash, Name zonename, + List nsec3s, NSEC3Parameters params, ByteArrayComparator bac) + { + Name n = hashName(hash, zonename); + + for (Iterator i = nsec3s.iterator(); i.hasNext();) + { + NSEC3Record nsec3 = (NSEC3Record) i.next(); + // Skip nsec3 records that are using different parameters. + if (!params.match(nsec3, bac)) continue; + if (n.equals(nsec3.getName())) return nsec3; + } + return null; + } + + /** + * Given a hash and a candidate NSEC3Record, determine if that NSEC3Record + * covers the hash. Covers specifically means that the hash is in between + * the owner and next hashes and does not equal either. + * + * @param nsec3 The candidate NSEC3Record. + * @param hash The precalculated hash. + * @param bac An already allocated comparator. This may be null. + * @return True if the NSEC3Record covers the hash. + */ + private static boolean nsec3Covers(NSEC3Record nsec3, byte[] hash, + ByteArrayComparator bac) + { + byte[] owner = nsec3.getOwner(); + byte[] next = nsec3.getNext(); + + // This is the "normal case: owner < next and owner < hash < next + if (bac.compare(owner, hash) < 0 && bac.compare(hash, next) < 0) + return true; + + // this is the end of zone case: next < owner && hash > owner || hash < + // next + if (bac.compare(next, owner) <= 0 + && (bac.compare(hash, next) < 0 || bac.compare(owner, hash) < 0)) + return true; + + // Otherwise, the NSEC3 does not cover the hash. + return false; + } + + /** + * Given a pre-hashed name, find a covering NSEC3 from among a list of + * NSEC3s. + * + * @param hash The hash to consider. + * @param zonename The name of the zone. + * @param nsec3s The list of NSEC3s present in a message. + * @param params The NSEC3 parameters used to generate the hash -- NSEC3s + * that do not use those parameters will be skipped. + * + * @return A covering NSEC3 if one is present, null otherwise. + */ + private static NSEC3Record findCoveringNSEC3(byte[] hash, Name zonename, + List nsec3s, NSEC3Parameters params, ByteArrayComparator bac) + { + ByteArrayComparator comparator = new ByteArrayComparator(); + + for (Iterator i = nsec3s.iterator(); i.hasNext();) + { + NSEC3Record nsec3 = (NSEC3Record) i.next(); + if (!params.match(nsec3, bac)) continue; + + if (nsec3Covers(nsec3, hash, comparator)) return nsec3; + } + + return null; + } + + + /** + * Given a name and a list of NSEC3s, find the candidate closest encloser. + * This will be the first ancestor of 'name' (including itself) to have a + * matching NSEC3 RR. + * + * @param name The name the start with. + * @param zonename The name of the zone that the NSEC3s came from. + * @param nsec3s The list of NSEC3s. + * @param nsec3params The NSEC3 parameters. + * @param bac A pre-allocated comparator. May be null. + * + * @return A CEResponse containing the closest encloser name and the NSEC3 + * RR that matched it, or null if there wasn't one. + */ + private static CEResponse findClosestEncloser(Name name, Name zonename, + List nsec3s, NSEC3Parameters params, ByteArrayComparator bac) + { + Name n = name; + + NSEC3Record nsec3; + + // This scans from longest name to shortest, so the first match we find is + // the only viable candidate. + // FIXME: modify so that the NSEC3 matching the zone apex need not be + // present. + while (n.labels() >= zonename.labels()) + { + nsec3 = findMatchingNSEC3(hash(n, params), zonename, nsec3s, params, bac); + if (nsec3 != null) return new CEResponse(n, nsec3); + n = new Name(n, 1); + } + + return null; + } + + /** + * Given a List of nsec3 RRs, find and prove the closest encloser to qname. + * + * @param qname The qname in question. + * @param zonename The name of the zone that the NSEC3 RRs come from. + * @param nsec3s The list of NSEC3s found the this response (already + * verified). + * @param params The NSEC3 parameters found in the response. + * @param bac A pre-allocated comparator. May be null. + * @param proveDoesNotExist If true, then if the closest encloser turns out + * to be qname, then null is returned. + * @return null if the proof isn't completed. Otherwise, return a CEResponse + * object which contains the closest encloser name and the NSEC3 + * that matches it. + */ + private static CEResponse proveClosestEncloser(Name qname, Name zonename, + List nsec3s, NSEC3Parameters params, ByteArrayComparator bac, + boolean proveDoesNotExist) + { + CEResponse candidate = findClosestEncloser(qname, + zonename, + nsec3s, + params, + bac); + + if (candidate == null) + { + st_log.debug("proveClosestEncloser: could not find a " + + "candidate for the closest encloser."); + return null; + } + + if (candidate.closestEncloser.equals(qname)) + { + if (proveDoesNotExist) + { + st_log.debug("proveClosestEncloser: proved that qname existed!"); + return null; + } + // otherwise, we need to nothing else to prove that qname is its own + // closest encloser. + return candidate; + } + + // If the closest encloser is actually a delegation, then the response + // should have been a referral. If it is a DNAME, then it should have been + // a DNAME response. + if (candidate.ce_nsec3.hasType(Type.NS) + && !candidate.ce_nsec3.hasType(Type.SOA)) + { + st_log.debug("proveClosestEncloser: closest encloser " + + "was a delegation!"); + return null; + } + if (candidate.ce_nsec3.hasType(Type.DNAME)) + { + st_log.debug("proveClosestEncloser: closest encloser was a DNAME!"); + return null; + } + + // Otherwise, we need to show that the next closer name is covered. + Name nextClosest = nextClosest(qname, candidate.closestEncloser); + + byte[] nc_hash = hash(nextClosest, params); + candidate.nc_nsec3 = findCoveringNSEC3(nc_hash, + zonename, + nsec3s, + params, + bac); + if (candidate.nc_nsec3 == null) + { + st_log.debug("Could not find proof that the " + + "closest encloser was the closest encloser"); + return null; + } + + return candidate; + } + + private static int maxIterations(int baseAlg, int keysize) + { + switch (baseAlg) + { + case DnsSecVerifier.RSA: + if (keysize == 0) return 2500; // the max at 4096 + if (keysize > 2048) return 2500; + if (keysize > 1024) return 500; + if (keysize > 0) return 150; + break; + case DnsSecVerifier.DSA: + if (keysize == 0) return 5000; // the max at 2048; + if (keysize > 1024) return 5000; + if (keysize > 0) return 1500; + break; + } + return -1; + } + + private static boolean validIterations(NSEC3Parameters nsec3params, + RRset dnskey_rrset, DnsSecVerifier verifier) + { + // for now, we return the maximum iterations based simply on the key + // algorithms that may have been used to sign the NSEC3 RRsets. + + int max_iterations = 0; + for (Iterator i = dnskey_rrset.rrs(); i.hasNext();) + { + DNSKEYRecord dnskey = (DNSKEYRecord) i.next(); + int baseAlg = verifier.baseAlgorithm(dnskey.getAlgorithm()); + int iters = maxIterations(baseAlg, 0); + max_iterations = max_iterations < iters ? iters : max_iterations; + } + + if (nsec3params.iterations > max_iterations) return false; + + return true; + } + + /** + * Determine if all of the NSEC3s in a response are legally ignoreable + * (i.e., their presence should lead to an INSECURE result). Currently, this + * is solely based on iterations. + * + * @param nsec3s The list of NSEC3s. If there is more than one set of NSEC3 + * parameters present, this test will not be performed. + * @param dnskey_rrset The set of validating DNSKEYs. + * @param verifier The verifier used to verify the NSEC3 RRsets. This is + * solely used to map algorithm aliases. + * @return true if all of the NSEC3s can be legally ignored, false if not. + */ + public static boolean allNSEC3sIgnoreable(List nsec3s, RRset dnskey_rrset, DnsSecVerifier verifier) + { + NSEC3Parameters params = nsec3Parameters(nsec3s); + if (params == null) return false; + + return !validIterations(params, dnskey_rrset, verifier); + } + + /** + * Determine if the set of NSEC3 records provided with a response prove NAME + * ERROR. This means that the NSEC3s prove a) the closest encloser exists, + * b) the direct child of the closest encloser towards qname doesn't exist, + * and c) *.closest encloser does not exist. + * + * @param nsec3s The list of NSEC3s. + * @param qname The query name to check against. + * @param zonename This is the name of the zone that the NSEC3s belong to. + * This may be discovered in any number of ways. A good one is to + * use the signerName from the NSEC3 record's RRSIG. + * @return SecurityStatus.SECURE of the Name Error is proven by the NSEC3 + * RRs, BOGUS if not, INSECURE if all of the NSEC3s could be validly + * ignored. + */ + public static boolean proveNameError(List nsec3s, Name qname, Name zonename) + { + if (nsec3s == null || nsec3s.size() == 0) return false; + + NSEC3Parameters nsec3params = nsec3Parameters(nsec3s); + if (nsec3params == null) + { + st_log.debug("Could not find a single set of " + + "NSEC3 parameters (multiple parameters present)."); + return false; + } + + ByteArrayComparator bac = new ByteArrayComparator(); + + // First locate and prove the closest encloser to qname. We will use the + // variant that fails if the closest encloser turns out to be qname. + CEResponse ce = proveClosestEncloser(qname, + zonename, + nsec3s, + nsec3params, + bac, + true); + + if (ce == null) + { + st_log.debug("proveNameError: failed to prove a closest encloser."); + return false; + } + + // At this point, we know that qname does not exist. Now we need to prove + // that the wildcard does not exist. + Name wc = ceWildcard(ce.closestEncloser); + byte[] wc_hash = hash(wc, nsec3params); + NSEC3Record nsec3 = findCoveringNSEC3(wc_hash, + zonename, + nsec3s, + nsec3params, + bac); + if (nsec3 == null) + { + st_log.debug("proveNameError: could not prove that the " + + "applicable wildcard did not exist."); + return false; + } + + return true; + } + + /** + * Determine if the set of NSEC3 records provided with a response prove NAME + * ERROR when qtype = NSEC3. This is a special case, and (currently anyway) + * it suffices to simply prove that the NSEC3 RRset itself does not exist, + * without proving that no wildcard could have generated it, etc.. + * + * @param nsec3s The list of NSEC3s. + * @param qname The query name to check against. + * @param zonename This is the name of the zone that the NSEC3s belong to. + * This may be discovered in any number of ways. A good one is to + * use the signerName from the NSEC3 record's RRSIG. + * @return true of the Name Error is proven by the NSEC3 RRs, false if not. + */ + // public static boolean proveNSEC3NameError(List nsec3s, Name qname, + // Name zonename) + // { + // if (nsec3s == null || nsec3s.size() == 0) return false; + // + // for (Iterator i = nsec3s.iterator(); i.hasNext(); ) + // { + // NSEC3Record nsec3 = (NSEC3Record) i.next(); + // + // // Convert owner and next into Names. + // Name owner = nsec3.getName(); + // Name next = null; + // try + // { + // next = new Name(base32.toString(nsec3.getNext()), zonename); + // } + // catch (TextParseException e) + // { + // continue; + // } + // + // // Now see if qname is covered by the NSEC3. + // + // // normal case, owner < qname < next. + // if (owner.compareTo(next) < 0 && owner.compareTo(qname) < 0 && + // next.compareTo(qname) > 0) + // { + // st_log.debug("proveNSEC3NameError: found a covering NSEC3: " + nsec3); + // return true; + // } + // // end-of-zone case: next < owner and qname > owner || qname < next. + // if (owner.compareTo(next) > 0 && (owner.compareTo(qname) < 0 || + // next.compareTo(qname) > 0)) + // { + // st_log.debug("proveNSEC3NameError: found a covering NSEC3: " + nsec3); + // return true; + // } + // } + // + // st_log.debug("proveNSEC3NameError: did not find a covering NSEC3"); + // return false; + // } + /** + * Determine if the NSEC3s provided in a response prove the NOERROR/NODATA + * status. There are a number of different variants to this: + * + * 1) Normal NODATA -- qname is matched to an NSEC3 record, type is not + * present. + * + * 2) ENT NODATA -- because there must be NSEC3 record for + * empty-non-terminals, this is the same as #1. + * + * 3) NSEC3 ownername NODATA -- qname matched an existing, lone NSEC3 + * ownername, but qtype was not NSEC3. NOTE: as of nsec-05, this case no + * longer exists. + * + * 4) Wildcard NODATA -- A wildcard matched the name, but not the type. + * + * 5) Opt-In DS NODATA -- the qname is covered by an opt-in span and qtype == + * DS. (or maybe some future record with the same parent-side-only property) + * + * @param nsec3s The NSEC3Records to consider. + * @param qname The qname in question. + * @param qtype The qtype in question. + * @param zonename The name of the zone that the NSEC3s came from. + * @return true if the NSEC3s prove the proposition. + */ + public static boolean proveNodata(List nsec3s, Name qname, int qtype, + Name zonename) + { + if (nsec3s == null || nsec3s.size() == 0) return false; + + NSEC3Parameters nsec3params = nsec3Parameters(nsec3s); + if (nsec3params == null) + { + st_log.debug("could not find a single set of " + + "NSEC3 parameters (multiple parameters present)"); + return false; + } + ByteArrayComparator bac = new ByteArrayComparator(); + + NSEC3Record nsec3 = findMatchingNSEC3(hash(qname, nsec3params), + zonename, + nsec3s, + nsec3params, + bac); + // Cases 1 & 2. + if (nsec3 != null) + { + if (nsec3.hasType(qtype)) + { + st_log.debug("proveNodata: Matching NSEC3 proved that type existed!"); + return false; + } + if (nsec3.hasType(Type.CNAME)) + { + st_log.debug("proveNodata: Matching NSEC3 proved " + + "that a CNAME existed!"); + return false; + } + return true; + } + + // For cases 3 - 5, we need the proven closest encloser, and it can't + // match qname. Although, at this point, we know that it won't since we + // just checked that. + CEResponse ce = proveClosestEncloser(qname, + zonename, + nsec3s, + nsec3params, + bac, + true); + + // At this point, not finding a match or a proven closest encloser is a + // problem. + if (ce == null) + { + st_log.debug("proveNodata: did not match qname, " + + "nor found a proven closest encloser."); + return false; + } + + // Case 3: REMOVED + + // Case 4: + Name wc = ceWildcard(ce.closestEncloser); + nsec3 = findMatchingNSEC3(hash(wc, nsec3params), + zonename, + nsec3s, + nsec3params, + bac); + + if (nsec3 != null) + { + if (nsec3.hasType(qtype)) + { + st_log.debug("proveNodata: matching wildcard had qtype!"); + return false; + } + return true; + } + + // Case 5. + if (qtype != Type.DS) + { + st_log.debug("proveNodata: could not find matching NSEC3, " + + "nor matching wildcard, and qtype is not DS -- no more options."); + return false; + } + + // We need to make sure that the covering NSEC3 is opt-in. + if (!ce.nc_nsec3.getOptInFlag()) + { + st_log.debug("proveNodata: covering NSEC3 was not " + + "opt-in in an opt-in DS NOERROR/NODATA case."); + return false; + } + + return true; + } + + /** + * Prove that a positive wildcard match was appropriate (no direct match + * RRset). + * + * @param nsec3s The NSEC3 records to work with. + * @param qname The qname that was matched to the wildard + * @param zonename The name of the zone that the NSEC3s come from. + * @param wildcard The purported wildcard that matched. + * @return true if the NSEC3 records prove this case. + */ + public static boolean proveWildcard(List nsec3s, Name qname, Name zonename, + Name wildcard) + { + if (nsec3s == null || nsec3s.size() == 0) return false; + if (qname == null || wildcard == null) return false; + + NSEC3Parameters nsec3params = nsec3Parameters(nsec3s); + if (nsec3params == null) + { + st_log.debug("couldn't find a single set of NSEC3 parameters (multiple parameters present)."); + return false; + } + + ByteArrayComparator bac = new ByteArrayComparator(); + + // We know what the (purported) closest encloser is by just looking at the + // supposed generating wildcard. + CEResponse candidate = new CEResponse(new Name(wildcard, 1), null); + + // Now we still need to prove that the original data did not exist. + // Otherwise, we need to show that the next closer name is covered. + Name nextClosest = nextClosest(qname, candidate.closestEncloser); + candidate.nc_nsec3 = findCoveringNSEC3(hash(nextClosest, nsec3params), + zonename, + nsec3s, + nsec3params, + bac); + + if (candidate.nc_nsec3 == null) + { + st_log.debug("proveWildcard: did not find a covering NSEC3 " + + "that covered the next closer name to " + qname + " from " + + candidate.closestEncloser + " (derived from wildcard " + wildcard + + ")"); + return false; + } + + return true; + } + + /** + * Prove that a DS response either had no DS, or wasn't a delegation point. + * + * Fundamentally there are two cases here: normal NODATA and Opt-In NODATA. + * + * @param nsec3s The NSEC3 RRs to examine. + * @param qname The name of the DS in question. + * @param zonename The name of the zone that the NSEC3 RRs come from. + * + * @return SecurityStatus.SECURE if it was proven that there is no DS in a + * secure (i.e., not opt-in) way, SecurityStatus.INSECURE if there + * was no DS in an insecure (i.e., opt-in) way, + * SecurityStatus.INDETERMINATE if it was clear that this wasn't a + * delegation point, and SecurityStatus.BOGUS if the proofs don't + * work out. + */ + public static int proveNoDS(List nsec3s, Name qname, Name zonename) + { + if (nsec3s == null || nsec3s.size() == 0) return SecurityStatus.BOGUS; + + NSEC3Parameters nsec3params = nsec3Parameters(nsec3s); + if (nsec3params == null) + { + st_log.debug("couldn't find a single set of " + + "NSEC3 parameters (multiple parameters present)."); + return SecurityStatus.BOGUS; + } + ByteArrayComparator bac = new ByteArrayComparator(); + + // Look for a matching NSEC3 to qname -- this is the normal NODATA case. + NSEC3Record nsec3 = findMatchingNSEC3(hash(qname, nsec3params), + zonename, + nsec3s, + nsec3params, + bac); + + if (nsec3 != null) + { + // If the matching NSEC3 has the SOA bit set, it is from the wrong zone + // (the child instead of the parent). If it has the DS bit set, then we + // were lied to. + if (nsec3.hasType(Type.SOA) || nsec3.hasType(Type.DS)) + { + return SecurityStatus.BOGUS; + } + // If the NSEC3 RR doesn't have the NS bit set, then this wasn't a + // delegation point. + if (!nsec3.hasType(Type.NS)) return SecurityStatus.INDETERMINATE; + + // Otherwise, this proves no DS. + return SecurityStatus.SECURE; + } + + // Otherwise, we are probably in the opt-in case. + CEResponse ce = proveClosestEncloser(qname, + zonename, + nsec3s, + nsec3params, + bac, + true); + if (ce == null) + { + return SecurityStatus.BOGUS; + } + + // If we had the closest encloser proof, then we need to check that the + // covering NSEC3 was opt-in -- the proveClosestEncloser step already + // checked to see if the closest encloser was a delegation or DNAME. + if (ce.nc_nsec3.getOptInFlag()) + { + return SecurityStatus.SECURE; + } + + return SecurityStatus.BOGUS; + } + +} diff --git a/src/se/rfc/unbound/SMessage.java b/src/se/rfc/unbound/SMessage.java new file mode 100644 index 0000000..df29613 --- /dev/null +++ b/src/se/rfc/unbound/SMessage.java @@ -0,0 +1,398 @@ +/* + * $Id$ + * + * Copyright (c) 2005 VeriSign. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. 2. Redistributions in + * binary form must reproduce the above copyright notice, this list of + * conditions and the following disclaimer in the documentation and/or other + * materials provided with the distribution. 3. The name of the author may not + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN + * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +package se.rfc.unbound; + +import java.util.*; + +import org.xbill.DNS.*; + +/** + * This class represents a DNS message with resolver/validator state. + */ +public class SMessage +{ + private Header mHeader; + + private Record mQuestion; + private OPTRecord mOPTRecord; + private List[] mSection; + private SecurityStatus mSecurityStatus; + + private static SRRset[] empty_srrset_array = new SRRset[0]; + + public SMessage(Header h) + { + mSection = new List[3]; + mHeader = h; + mSecurityStatus = new SecurityStatus(); + } + + public SMessage(int id) + { + this(new Header(id)); + } + + public SMessage() + { + this(new Header(0)); + } + + public SMessage(Message m) + { + this(m.getHeader()); + mQuestion = m.getQuestion(); + mOPTRecord = m.getOPT(); + + for (int i = Section.ANSWER; i <= Section.ADDITIONAL; i++) + { + RRset[] rrsets = m.getSectionRRsets(i); + + for (int j = 0; j < rrsets.length; j++) + { + addRRset(rrsets[j], i); + } + } + } + + public Header getHeader() + { + return mHeader; + } + + public void setHeader(Header h) + { + mHeader = h; + } + + public void setQuestion(Record r) + { + mQuestion = r; + } + + public Record getQuestion() + { + return mQuestion; + } + + public Name getQName() { + return getQuestion().getName(); + } + + public int getQType() { + return getQuestion().getType(); + } + + public int getQClass() { + return getQuestion().getDClass(); + } + + public void setOPT(OPTRecord r) + { + mOPTRecord = r; + } + + public OPTRecord getOPT() + { + return mOPTRecord; + } + + public List getSectionList(int section) + { + if (section <= Section.QUESTION || section > Section.ADDITIONAL) + throw new IllegalArgumentException("Invalid section."); + + if (mSection[section - 1] == null) + { + mSection[section - 1] = new LinkedList(); + } + + return mSection[section - 1]; + } + + public void addRRset(SRRset srrset, int section) + { + if (section <= Section.QUESTION || section > Section.ADDITIONAL) + throw new IllegalArgumentException("Invalid section"); + + if (srrset.getType() == Type.OPT) + { + mOPTRecord = (OPTRecord) srrset.first(); + return; + } + + List sectionList = getSectionList(section); + sectionList.add(srrset); + } + + public void addRRset(RRset rrset, int section) + { + if (rrset instanceof SRRset) + { + addRRset((SRRset) rrset, section); + return; + } + + SRRset srrset = new SRRset(rrset); + addRRset(srrset, section); + } + + public void prependRRsets(List rrsets, int section) + { + if (section <= Section.QUESTION || section > Section.ADDITIONAL) + throw new IllegalArgumentException("Invalid section"); + + List sectionList = getSectionList(section); + sectionList.addAll(0, rrsets); + } + + public SRRset[] getSectionRRsets(int section) + { + List slist = getSectionList(section); + + return (SRRset[]) slist.toArray(empty_srrset_array); + } + + public SRRset[] getSectionRRsets(int section, int qtype) + { + List slist = getSectionList(section); + + if (slist.size() == 0) return new SRRset[0]; + + ArrayList result = new ArrayList(slist.size()); + for (Iterator i = slist.iterator(); i.hasNext();) + { + SRRset rrset = (SRRset) i.next(); + if (rrset.getType() == qtype) result.add(rrset); + } + + return (SRRset[]) result.toArray(empty_srrset_array); + } + + public void deleteRRset(SRRset rrset, int section) + { + List slist = getSectionList(section); + + if (slist.size() == 0) return; + + slist.remove(rrset); + } + + public void clear(int section) + { + if (section < Section.QUESTION || section > Section.ADDITIONAL) + throw new IllegalArgumentException("Invalid section."); + + if (section == Section.QUESTION) + { + mQuestion = null; + return; + } + if (section == Section.ADDITIONAL) + { + mOPTRecord = null; + } + + mSection[section - 1] = null; + } + + public void clear() + { + for (int s = Section.QUESTION; s <= Section.ADDITIONAL; s++) + { + clear(s); + } + } + + public int getRcode() + { + // FIXME: might want to do what Message does and handle extended rcodes. + return mHeader.getRcode(); + } + + public int getStatus() + { + return mSecurityStatus.getStatus(); + } + + public void setStatus(byte status) + { + mSecurityStatus.setStatus(status); + } + + public SecurityStatus getSecurityStatus() + { + return mSecurityStatus; + } + public void setSecurityStatus(SecurityStatus s) + { + if (s == null) return; + mSecurityStatus = s; + } + + public Message getMessage() + { + // Generate our new message. + Message m = new Message(mHeader.getID()); + + // Convert the header + // We do this for two reasons: 1) setCount() is package scope, so we can't + // do that, and 2) setting the header on a message after creating the + // message frequently gets stuff out of sync, leading to malformed wire + // format messages. + Header h = m.getHeader(); + h.setOpcode(mHeader.getOpcode()); + h.setRcode(mHeader.getRcode()); + for (int i = 0; i < 16; i++) + { + if (Flags.isFlag(i)) h.setFlag(i, mHeader.getFlag(i)); + } + + // Add all the records. -- this will set the counts correctly in the + // message header. + + if (mQuestion != null) + { + m.addRecord(mQuestion, Section.QUESTION); + } + + for (int sec = Section.ANSWER; sec <= Section.ADDITIONAL; sec++) + { + List slist = getSectionList(sec); + for (Iterator i = slist.iterator(); i.hasNext();) + { + SRRset rrset = (SRRset) i.next(); + for (Iterator j = rrset.rrs(); j.hasNext();) + { + m.addRecord((Record) j.next(), sec); + } + for (Iterator j = rrset.sigs(); j.hasNext();) + { + m.addRecord((Record) j.next(), sec); + } + } + } + + if (mOPTRecord != null) + { + m.addRecord(mOPTRecord, Section.ADDITIONAL); + } + + return m; + } + + public int getCount(int section) + { + if (section == Section.QUESTION) + { + return mQuestion == null ? 0 : 1; + } + List sectionList = getSectionList(section); + if (sectionList == null) return 0; + if (sectionList.size() == 0) return 0; + + int count = 0; + for (Iterator i = sectionList.iterator(); i.hasNext(); ) + { + SRRset sr = (SRRset) i.next(); + count += sr.totalSize(); + } + return count; + } + + public String toString() + { + return getMessage().toString(); + } + + /** + * Find a specific (S)RRset in a given section. + * + * @param name the name of the RRset. + * @param type the type of the RRset. + * @param dclass the class of the RRset. + * @param section the section to look in (ANSWER -> ADDITIONAL) + * + * @return The SRRset if found, null otherwise. + */ + public SRRset findRRset(Name name, int type, int dclass, int section) + { + if (section <= Section.QUESTION || section > Section.ADDITIONAL) + throw new IllegalArgumentException("Invalid section."); + + SRRset[] rrsets = getSectionRRsets(section); + + for (int i = 0; i < rrsets.length; i++) + { + if (rrsets[i].getName().equals(name) && rrsets[i].getType() == type + && rrsets[i].getDClass() == dclass) + { + return rrsets[i]; + } + } + + return null; + } + + /** + * Find an "answer" RRset. This will look for RRsets in the ANSWER section + * that match the , taking into consideration CNAMEs. + * + * @param qname The starting search name. + * @param qtype The search type. + * @param qclass The search class. + * + * @return a SRRset matching the query. This SRRset may have a different + * name from qname, due to following a CNAME chain. + */ + public SRRset findAnswerRRset(Name qname, int qtype, int qclass) + { + SRRset[] srrsets = getSectionRRsets(Section.ANSWER); + + for (int i = 0; i < srrsets.length; i++) + { + if (srrsets[i].getName().equals(qname) + && srrsets[i].getType() == Type.CNAME) + { + CNAMERecord cname = (CNAMERecord) srrsets[i].first(); + qname = cname.getTarget(); + continue; + } + + if (srrsets[i].getName().equals(qname) && srrsets[i].getType() == qtype + && srrsets[i].getDClass() == qclass) + { + return srrsets[i]; + } + } + + return null; + } + +} \ No newline at end of file diff --git a/src/se/rfc/unbound/SRRset.java b/src/se/rfc/unbound/SRRset.java new file mode 100644 index 0000000..8c6cb7e --- /dev/null +++ b/src/se/rfc/unbound/SRRset.java @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2005 VeriSign. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. 2. Redistributions in + * binary form must reproduce the above copyright notice, this list of + * conditions and the following disclaimer in the documentation and/or other + * materials provided with the distribution. 3. The name of the author may not + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN + * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +package se.rfc.unbound; + +import java.util.*; + +import org.xbill.DNS.*; + +/** + * A version of the RRset class overrides the standard security status. + */ +public class SRRset extends RRset +{ + private SecurityStatus mSecurityStatus; + + /** Create a new, blank SRRset. */ + public SRRset() + { + super(); + mSecurityStatus = new SecurityStatus(); + } + + /** + * Create a new SRRset from an existing RRset. This SRRset will contain that + * same internal Record objects as the original RRset. + */ + @SuppressWarnings("unchecked") // org.xbill.DNS.RRset isn't typesafe-aware. +public SRRset(RRset r) + { + this(); + + for (Iterator i = r.rrs(); i.hasNext();) + { + addRR((Record) i.next()); + } + + for (Iterator i = r.sigs(); i.hasNext();) + { + addRR((Record) i.next()); + } + } + + /** + * Clone this SRRset, giving the copy a new TTL. The copy is independent + * from the original except for the security status. + * + * @param withNewTTL The new TTL to apply to the RRset. This applies to + * contained RRsig records as well. + * @return The cloned SRRset. + */ + public SRRset cloneSRRset(long withNewTTL) + { + SRRset nr = new SRRset(); + + for (Iterator i = rrs(); i.hasNext();) + { + nr.addRR(((Record) i.next()).withTTL(withNewTTL)); + } + for (Iterator i = sigs(); i.hasNext();) + { + nr.addRR(((Record) i.next()).withTTL(withNewTTL)); + } + + nr.mSecurityStatus = mSecurityStatus; + + return nr; + } + + public SRRset cloneSRRsetNoSigs() + { + SRRset nr = new SRRset(); + for (Iterator i = rrs(); i.hasNext();) + { + // NOTE: should this clone the records as well? + nr.addRR((Record) i.next()); + } + // Do not copy the SecurityStatus reference + + return nr; + } + /** + * Return the current security status (generally: UNCHECKED, BOGUS, or + * SECURE). + */ + public int getSecurity() + { + return getSecurityStatus(); + } + + /** + * Return the current security status (generally: UNCHECKED, BOGUS, or + * SECURE). + */ + public int getSecurityStatus() + { + return mSecurityStatus.getStatus(); + } + + /** + * Set the current security status for this SRRset. This status will be + * shared amongst all copies of this SRRset (created with cloneSRRset()) + */ + public void setSecurityStatus(int status) + { + mSecurityStatus.setStatus(status); + } + + /** + * @return The total number of records (data + sigs) in the SRRset. + */ + public int getNumRecords() + { + return totalSize(); + } + + /** + * @return true if this RRset has RRSIG records that cover data records. + * (i.e., RRSIG SRRsets return false) + */ + public boolean isSigned() + { + if (getType() == Type.RRSIG) return false; + return firstSig() != null; + } + + /** + * @return The "signer" name for this SRRset, if signed, or null if not. + */ + public Name getSignerName() + { + RRSIGRecord sig = (RRSIGRecord) firstSig(); + if (sig == null) return null; + return sig.getSigner(); + } + + public void setTTL(long ttl) + { + if (ttl < 0) + { + throw new IllegalArgumentException("ttl can't be less than zero, stupid! was " + ttl); + } + super.setTTL(ttl); + } +} diff --git a/src/se/rfc/unbound/SecurityStatus.java b/src/se/rfc/unbound/SecurityStatus.java new file mode 100644 index 0000000..d6e7757 --- /dev/null +++ b/src/se/rfc/unbound/SecurityStatus.java @@ -0,0 +1,112 @@ +/* + * $Id$ + * + * Copyright (c) 2005 VeriSign. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. 2. Redistributions in + * binary form must reproduce the above copyright notice, this list of + * conditions and the following disclaimer in the documentation and/or other + * materials provided with the distribution. 3. The name of the author may not + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN + * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +package se.rfc.unbound; + +/** + * Codes for DNSSEC security statuses. + * + * @author davidb + */ +public class SecurityStatus +{ + + /** + * UNCHECKED means that object has yet to be validated. + */ + public static final byte UNCHECKED = 0; + /** + * BOGUS means that the object (RRset or message) failed to validate + * (according to local policy), but should have validated. + */ + public static final byte BOGUS = 1; + /** + * BAD is a synonym for BOGUS. + */ + public static final byte BAD = BOGUS; + /** + * INDTERMINATE means that the object is insecure, but not authoritatively + * so. Generally this means that the RRset is not below a configured trust + * anchor. + */ + public static final byte INDETERMINATE = 2; + /** + * INSECURE means that the object is authoritatively known to be insecure. + * Generally this means that this RRset is below a trust anchor, but also + * below a verified, insecure delegation. + */ + public static final byte INSECURE = 3; + /** + * SECURE means that the object (RRset or message) validated according to + * local policy. + */ + public static final byte SECURE = 4; + + private byte status; + + public static String string(int status) + { + switch (status) + { + case BOGUS : + return "Bogus"; + case SECURE : + return "Secure"; + case INSECURE : + return "Insecure"; + case INDETERMINATE : + return "Indeterminate"; + case UNCHECKED : + return "Unchecked"; + default : + return "UNKNOWN"; + } + } + + public SecurityStatus() + { + status = UNCHECKED; + } + + public SecurityStatus(byte status) + { + setStatus(status); + } + + public byte getStatus() + { + return status; + } + + public void setStatus(byte status) + { + this.status = status; + } + +} diff --git a/src/se/rfc/unbound/TrustAnchorStore.java b/src/se/rfc/unbound/TrustAnchorStore.java new file mode 100644 index 0000000..ba8e26d --- /dev/null +++ b/src/se/rfc/unbound/TrustAnchorStore.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2009 VeriSign, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +package se.rfc.unbound; + +import java.util.HashMap; +import java.util.Map; + +import org.xbill.DNS.Name; + +import se.rfc.unbound.SRRset; +import se.rfc.unbound.SecurityStatus; + +/** + * + */ +public class TrustAnchorStore +{ + private Map mMap; + + public TrustAnchorStore() + { + mMap = null; + } + + private String key(Name n, int dclass) + { + return "T" + dclass + "/" + Util.nameToString(n); + } + + + public void store(SRRset rrset) + { + if (mMap == null) + { + mMap = new HashMap(); + } + String k = key(rrset.getName(), rrset.getDClass()); + rrset.setSecurityStatus(SecurityStatus.SECURE); + + mMap.put(k, rrset); + } + + private SRRset lookup(String key) + { + if (mMap == null) return null; + return (SRRset) mMap.get(key); + } + + public SRRset find(Name n, int dclass) + { + if (mMap == null) return null; + + while (n.labels() > 0) + { + String k = key(n, dclass); + SRRset r = lookup(k); + if (r != null) return r; + n = new Name(n, 1); + } + + return null; + } + +} diff --git a/src/se/rfc/unbound/Util.java b/src/se/rfc/unbound/Util.java new file mode 100644 index 0000000..3e0cae3 --- /dev/null +++ b/src/se/rfc/unbound/Util.java @@ -0,0 +1,149 @@ +/* + * $Id$ + * + * Copyright (c) 2005 VeriSign. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. 2. Redistributions in + * binary form must reproduce the above copyright notice, this list of + * conditions and the following disclaimer in the documentation and/or other + * materials provided with the distribution. 3. The name of the author may not + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN + * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +package se.rfc.unbound; + +import java.util.*; + +import org.xbill.DNS.Flags; +import org.xbill.DNS.Header; +import org.xbill.DNS.Name; + +/** + * Some basic utility functions. + * + * @author davidb + * @version $Revision$ + */ +public class Util +{ + + /** + * Convert a DNS name into a string suitable for use as a cache key. + * + * @param name The name to convert. + * @return A string representing the name. This isn't ever meant to be + * converted back into a DNS name. + */ + public static String nameToString(Name name) + { + if (name.equals(Name.root)) return "."; + + String n = name.toString().toLowerCase(); + if (n.endsWith(".")) n = n.substring(0, n.length() - 1); + + return n; + } + +// public static SMessage errorMessage(Request request, int rcode) +// { +// SMessage m = new SMessage(request.getID()); +// Header h = m.getHeader(); +// h.setRcode(rcode); +// h.setFlag(Flags.QR); +// m.setQuestion(request.getQuestion()); +// m.setOPT(request.getOPT()); +// +// return m; +// } +// +// public static SMessage errorMessage(SMessage message, int rcode) +// { +// Header h = message.getHeader(); +// SMessage m = new SMessage(h.getID()); +// h = m.getHeader(); +// h.setRcode(rcode); +// h.setFlag(Flags.QR); +// m.setQuestion(message.getQuestion()); +// m.setOPT(message.getOPT()); +// +// return m; +// } + + public static int parseInt(String s, int def) + { + if (s == null) return def; + try + { + return Integer.parseInt(s); + } + catch (NumberFormatException e) + { + return def; + } + } + + public static long parseLong(String s, long def) + { + if (s == null) return def; + try + { + return Long.parseLong(s); + } + catch (NumberFormatException e) + { + return def; + } + } + + public static class ConfigEntry + { + public String key; + public String value; + + public ConfigEntry(String key, String value) + { + this.key = key; this.value = value; + } + } + + public static List parseConfigPrefix(Properties config, String prefix) + { + if (! prefix.endsWith(".")) + { + prefix = prefix + "."; + } + + List res = new ArrayList(); + + for (Iterator i = config.entrySet().iterator(); i.hasNext(); ) + { + Map.Entry entry = (Map.Entry) i.next(); + String key = (String) entry.getKey(); + if (key.startsWith(prefix)) + { + key = key.substring(prefix.length()); + + res.add(new ConfigEntry(key, (String) entry.getValue())); + } + } + + return res; + } +} diff --git a/src/se/rfc/unbound/ValUtils.java b/src/se/rfc/unbound/ValUtils.java new file mode 100644 index 0000000..14570d5 --- /dev/null +++ b/src/se/rfc/unbound/ValUtils.java @@ -0,0 +1,719 @@ +/* + * $Id$ + * + * Copyright (c) 2005 VeriSign, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +package se.rfc.unbound.validator; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Iterator; + +import org.apache.log4j.Logger; +import org.xbill.DNS.*; + +import se.rfc.unbound.*; + +/** + * This is a collection of routines encompassing the logic of validating + * different message types. + * + * @author davidb + * @version $Revision$ + */ +public class ValUtils +{ + + // These are response subtypes. They are necessary for determining the + // validation strategy. They have no bearing on the iterative resolution + // algorithm, so they are confined here. + + /** Not subtyped yet. */ + public static final int UNTYPED = 0; + + /** Not a recognized subtype. */ + public static final int UNKNOWN = 1; + + /** A postive, direct, response. */ + public static final int POSITIVE = 2; + + /** A postive response, with a CNAME/DNAME chain. */ + public static final int CNAME = 3; + + /** A NOERROR/NODATA response. */ + public static final int NODATA = 4; + + /** A NXDOMAIN response. */ + public static final int NAMEERROR = 5; + + /** A response to a qtype=ANY query. */ + public static final int ANY = 6; + + private Logger log = Logger.getLogger(this.getClass()); + private static Logger st_log = Logger.getLogger(ValUtils.class); + + /** A local copy of the verifier object. */ + private DnsSecVerifier mVerifier; + + public ValUtils(DnsSecVerifier verifier) + { + mVerifier = verifier; + } + + /** + * Given a response, classify ANSWER responses into a subtype. + * + * @param m The response to classify. + * + * @return A subtype ranging from UNKNOWN to NAMEERROR. + */ + public static int classifyResponse(SMessage m) + { + // Normal Name Error's are easy to detect -- but don't mistake a CNAME + // chain ending in NXDOMAIN. + if (m.getRcode() == Rcode.NXDOMAIN + && m.getCount(Section.ANSWER) == 0) + { + return NAMEERROR; + } + + // Next is NODATA + // st_log.debug("classifyResponse: ancount = " + + // m.getCount(Section.ANSWER)); + if (m.getCount(Section.ANSWER) == 0) + { + return NODATA; + } + + // We distinguish between CNAME response and other positive/negative + // responses because CNAME answers require extra processing. + int qtype = m.getQuestion().getType(); + + // We distinguish between ANY and CNAME or POSITIVE because ANY responses + // are validated differently. + if (qtype == Type.ANY) + { + return ANY; + } + + SRRset[] rrsets = m.getSectionRRsets(Section.ANSWER); + + // Note that DNAMEs will be ignored here, unless qtype=DNAME. Unless + // qtype=CNAME, this will yield a CNAME response. + for (int i = 0; i < rrsets.length; i++) + { + if (rrsets[i].getType() == qtype) return POSITIVE; + if (rrsets[i].getType() == Type.CNAME) return CNAME; + } + + st_log.warn("Failed to classify response message:\n" + m); + return UNKNOWN; + } + + /** + * Given a response, determine the name of the "signer". This is primarily + * to determine if the response is, in fact, signed at all, and, if so, what + * is the name of the most pertinent keyset. + * + * @param m The response to analyze. + * @param request The request that generated the response. + * @return a signer name, if the response is signed (even partially), or + * null if the response isn't signed. + */ + public Name findSigner(SMessage m, Request request) + { + int subtype = classifyResponse(m); + Name qname = request.getQName(); + + SRRset[] rrsets; + + switch (subtype) + { + case POSITIVE : + case CNAME : + case ANY : + // Check to see if the ANSWER section RRset + rrsets = m.getSectionRRsets(Section.ANSWER); + for (int i = 0; i < rrsets.length; i++) + { + if (rrsets[i].getName().equals(qname)) + { + return rrsets[i].getSignerName(); + } + } + return null; + + case NAMEERROR : + case NODATA : + // Check to see if the AUTH section NSEC record(s) have rrsigs + rrsets = m.getSectionRRsets(Section.AUTHORITY); + for (int i = 0; i < rrsets.length; i++) + { + if (rrsets[i].getType() == Type.NSEC + || rrsets[i].getType() == Type.NSEC3) + { + return rrsets[i].getSignerName(); + } + } + return null; + default : + log.debug("findSigner: could not find signer name " + + "for unknown type response."); + return null; + } + } + + public boolean dssetIsUsable(SRRset ds_rrset) + { + for (Iterator i = ds_rrset.rrs(); i.hasNext();) + { + DSRecord ds = (DSRecord) i.next(); + if (supportsDigestID(ds.getDigestID()) + && mVerifier.supportsAlgorithm(ds.getAlgorithm())) + { + return true; + } + } + + return false; + } + + /** + * Given a DS rrset and a DNSKEY rrset, match the DS to a DNSKEY and verify + * the DNSKEY rrset with that key. + * + * @param dnskey_rrset The DNSKEY rrset to match against. The security + * status of this rrset will be updated on a successful + * verification. + * @param ds_rrset The DS rrset to match with. This rrset must already be + * trusted. + * + * @return a KeyEntry. This will either contain the now trusted + * dnskey_rrset, a "null" key entry indicating that this DS + * rrset/DNSKEY pair indicate an secure end to the island of trust + * (i.e., unknown algorithms), or a "bad" KeyEntry if the dnskey + * rrset fails to verify. Note that the "null" response should + * generally only occur in a private algorithm scenario: normally + * this sort of thing is checked before fetching the matching DNSKEY + * rrset. + */ + public KeyEntry verifyNewDNSKEYs(SRRset dnskey_rrset, SRRset ds_rrset) + { + if (!dnskey_rrset.getName().equals(ds_rrset.getName())) + { + log.debug("DNSKEY RRset did not match DS RRset by name!"); + return KeyEntry + .newBadKeyEntry(ds_rrset.getName(), ds_rrset.getDClass()); + } + + // as long as this is false, we can consider this DS rrset to be + // equivalent to no DS rrset. + boolean hasUsefulDS = false; + + for (Iterator i = ds_rrset.rrs(); i.hasNext();) + { + DSRecord ds = (DSRecord) i.next(); + + // Check to see if we can understand this DS. + if (!supportsDigestID(ds.getDigestID()) + || !mVerifier.supportsAlgorithm(ds.getAlgorithm())) + { + continue; + } + + // Once we see a single DS with a known digestID and algorithm, we + // cannot return INSECURE (with a "null" KeyEntry). + hasUsefulDS = true; + + DNSKEY : for (Iterator j = dnskey_rrset.rrs(); j.hasNext();) + { + DNSKEYRecord dnskey = (DNSKEYRecord) j.next(); + + // Skip DNSKEYs that don't match the basic criteria. + if (ds.getFootprint() != dnskey.getFootprint() + || ds.getAlgorithm() != dnskey.getAlgorithm()) + { + continue; + } + + // Convert the candidate DNSKEY into a hash using the same DS hash + // algorithm. + byte[] key_hash = calculateDSHash(dnskey, ds.getDigestID()); + byte[] ds_hash = ds.getDigest(); + + // see if there is a length mismatch (unlikely) + if (key_hash.length != ds_hash.length) + { + continue DNSKEY; + } + + for (int k = 0; k < key_hash.length; k++) + { + if (key_hash[k] != ds_hash[k]) continue DNSKEY; + } + + // Otherwise, we have a match! Make sure that the DNSKEY verifies + // *with this key*. + byte res = mVerifier.verify(dnskey_rrset, dnskey); + if (res == SecurityStatus.SECURE) + { + log.trace("DS matched DNSKEY."); + dnskey_rrset.setSecurityStatus(SecurityStatus.SECURE); + return KeyEntry.newKeyEntry(dnskey_rrset); + } + // If it didn't validate with the DNSKEY, try the next one! + } + } + + // None of the DS's worked out. + + // If no DSs were understandable, then this is OK. + if (!hasUsefulDS) + { + log.debug("No usuable DS records were found -- treating as insecure."); + return KeyEntry.newNullKeyEntry(ds_rrset.getName(), ds_rrset + .getDClass(), ds_rrset.getTTL()); + } + // If any were understandable, then it is bad. + log.debug("Failed to match any usable DS to a DNSKEY."); + return KeyEntry.newBadKeyEntry(ds_rrset.getName(), ds_rrset.getDClass()); + } + + /** + * Given a DNSKEY record, generate the DS record from it. + * + * @param keyrec the DNSKEY record in question. + * @param ds_alg The DS digest algorithm in use. + * @return the corresponding {@link org.xbill.DNS.DSRecord} + */ + public static byte[] calculateDSHash(DNSKEYRecord keyrec, int ds_alg) + { + DNSOutput os = new DNSOutput(); + + os.writeByteArray(keyrec.getName().toWireCanonical()); + os.writeByteArray(keyrec.rdataToWireCanonical()); + + try + { + MessageDigest md = null; + switch (ds_alg) + { + case DSRecord.SHA1_DIGEST_ID : + md = MessageDigest.getInstance("SHA"); + return md.digest(os.toByteArray()); + case DSRecord.SHA256_DIGEST_ID: + SHA256 sha = new SHA256(); + sha.setData(os.toByteArray()); + return sha.getDigest(); + default : + st_log.warn("Unknown DS algorithm: " + ds_alg); + return null; + } + + } + catch (NoSuchAlgorithmException e) + { + st_log.error("Error using DS algorithm: " + ds_alg, e); + return null; + } + } + + public static boolean supportsDigestID(int digest_id) + { + if (digest_id == DSRecord.SHA1_DIGEST_ID) return true; + if (digest_id == DSRecord.SHA256_DIGEST_ID) return true; + return false; + } + + /** + * Check to see if a type is a special DNSSEC type. + * + * @param type The type. + * + * @return true if the type is one of the special DNSSEC types. + */ + public static boolean isDNSSECType(int type) + { + switch (type) + { + case Type.DNSKEY : + case Type.NSEC : + case Type.DS : + case Type.RRSIG : + case Type.NSEC3 : + return true; + default : + return false; + } + } + + /** + * Set the security status of a particular RRset. This will only upgrade the + * security status. + * + * @param rrset The SRRset to update. + * @param security The security status. + */ + public static void setRRsetSecurity(SRRset rrset, int security) + { + if (rrset == null) return; + + int cur_sec = rrset.getSecurityStatus(); + if (cur_sec == SecurityStatus.UNCHECKED || security > cur_sec) + { + rrset.setSecurityStatus(security); + } + } + + /** + * Set the security status of a message and all of its RRsets. This will + * only upgrade the status of the message (i.e., set to more secure, not + * less) and all of the RRsets. + * + * @param m + * @param security KeyEntry ke; + * + * SMessage m = response.getSMessage(); SRRset ans_rrset = + * m.findAnswerRRset(qname, qtype, qclass); + * + * ke = verifySRRset(ans_rrset, key_rrset); if + * (ans_rrset.getSecurityStatus() != SecurityStatus.SECURE) { return; } + * key_rrset = ke.getRRset(); + */ + public static void setMessageSecurity(SMessage m, int security) + { + if (m == null) return; + + int cur_sec = m.getStatus(); + if (cur_sec == SecurityStatus.UNCHECKED || security > cur_sec) + { + m.setStatus(security); + } + + for (int section = Section.ANSWER; section <= Section.ADDITIONAL; section++) + { + SRRset[] rrsets = m.getSectionRRsets(section); + for (int i = 0; i < rrsets.length; i++) + { + setRRsetSecurity(rrsets[i], security); + } + } + } + + /** + * Given an SRRset that is signed by a DNSKEY found in the key_rrset, verify + * it. This will return the status (either BOGUS or SECURE) and set that + * status in rrset. + * + * @param rrset The SRRset to verify. + * @param key_rrset The set of keys to verify against. + * @return The status (BOGUS or SECURE). + */ + public byte verifySRRset(SRRset rrset, SRRset key_rrset) + { + String rrset_name = rrset.getName() + "/" + Type.string(rrset.getType()) + + "/" + DClass.string(rrset.getDClass()); + + if (rrset.getSecurityStatus() == SecurityStatus.SECURE) + { + log.trace("verifySRRset: rrset <" + rrset_name + + "> previously found to be SECURE"); + return SecurityStatus.SECURE; + } + + byte status = mVerifier.verify(rrset, key_rrset); + if (status != SecurityStatus.SECURE) + { + log.debug("verifySRRset: rrset <" + rrset_name + "> found to be BAD"); + status = SecurityStatus.BOGUS; + } + else + { + log.trace("verifySRRset: rrset <" + rrset_name + "> found to be SECURE"); + } + + rrset.setSecurityStatus(status); + return status; + } + + /** + * Determine if a given type map has a given typ. + * + * @param types The type map from the NSEC record. + * @param type The type to look for. + * @return true if the type is present in the type map, false otherwise. + */ + public static boolean typeMapHasType(int[] types, int type) + { + for (int i = 0; i < types.length; i++) + { + if (types[i] == type) return true; + } + return false; + } + + /** + * Determine by looking at a signed RRset whether or not the rrset name was + * the result of a wildcard expansion. + * + * @param rrset The rrset to examine. + * @return true if the rrset is a wildcard expansion. This will return false + * for all unsigned rrsets. + */ + public static boolean rrsetIsWildcardExpansion(RRset rrset) + { + if (rrset == null) return false; + RRSIGRecord rrsig = (RRSIGRecord) rrset.firstSig(); + + if (rrset.getName().labels() - 1 > rrsig.getLabels()) + { + return true; + } + + return false; + } + + /** + * Determine by looking at a signed RRset whether or not the RRset name was + * the result of a wildcard expansion. If so, return the name of the + * generating wildcard. + * + * @param rrset The rrset to chedck. + * @return the wildcard name, if the rrset was synthesized from a wildcard. + * null if not. + */ + public static Name rrsetWildcard(RRset rrset) + { + if (rrset == null) return null; + RRSIGRecord rrsig = (RRSIGRecord) rrset.firstSig(); + + // if the RRSIG label count is shorter than the number of actual labels, + // then this rrset was synthesized from a wildcard. + // Note that the RRSIG label count doesn't count the root label. + int label_diff = (rrset.getName().labels() - 1) - rrsig.getLabels(); + if (label_diff > 0) + { + return rrset.getName().wild(label_diff); + } + return null; + } + + public static Name closestEncloser(Name domain, NSECRecord nsec) + { + Name n1 = domain.longestCommonName(nsec.getName()); + Name n2 = domain.longestCommonName(nsec.getNext()); + + return (n1.labels() > n2.labels()) ? n1 : n2; + } + + public static Name nsecWildcard(Name domain, NSECRecord nsec) + { + try + { + return new Name("*", closestEncloser(domain, nsec)); + } + catch (TextParseException e) + { + // this should never happen. + return null; + } + } + + /** + * Determine if the given NSEC proves a NameError (NXDOMAIN) for a given + * qname. + * + * @param nsec The NSEC to check. + * @param qname The qname to check against. + * @param signerName The signer name of the NSEC record, which is used as + * the zone name, for a more precise (but perhaps more brittle) + * check for the last NSEC in a zone. + * @return true if the NSEC proves the condition. + */ + public static boolean nsecProvesNameError(NSECRecord nsec, Name qname, + Name signerName) + { + Name owner = nsec.getName(); + Name next = nsec.getNext(); + + // If NSEC owner == qname, then this NSEC proves that qname exists. + if (qname.equals(owner)) + { + return false; + } + + // If NSEC is a parent of qname, we need to check the type map + // If the parent name has a DNAME or is a delegation point, then this NSEC + // is being misused. + if (qname.subdomain(owner) + && (typeMapHasType(nsec.getTypes(), Type.DNAME) || (typeMapHasType(nsec + .getTypes(), + Type.NS) && !typeMapHasType(nsec.getTypes(), Type.SOA)))) + { + return false; + } + + if (qname.compareTo(owner) > 0 && (qname.compareTo(next) < 0) + || signerName.equals(next)) + { + return true; + } + return false; + } + + /** + * Determine if a NSEC record proves the non-existence of a wildcard that + * could have produced qname. + * + * @param nsec The nsec to check. + * @param qname The qname to check against. + * @param signerName The signer name for the NSEC rrset, used as the zone + * name. + * @return true if the NSEC proves the condition. + */ + public static boolean nsecProvesNoWC(NSECRecord nsec, Name qname, + Name signerName) + { + Name owner = nsec.getName(); + Name next = nsec.getNext(); + + int qname_labels = qname.labels(); + int signer_labels = signerName.labels(); + + for (int i = qname_labels - signer_labels; i > 0; i--) + { + Name wc_name = qname.wild(i); + if (wc_name.compareTo(owner) > 0 + && (wc_name.compareTo(next) < 0 || signerName.equals(next))) + { + return true; + } + } + + return false; + } + + /** + * Determine if a NSEC proves the NOERROR/NODATA conditions. This will also + * handle the empty non-terminal (ENT) case and partially handle the + * wildcard case. If the ownername of 'nsec' is a wildcard, the validator + * must still be provided proof that qname did not directly exist and that + * the wildcard is, in fact, *.closest_encloser. + * + * @param nsec The NSEC to check + * @param qname The query name to check against. + * @param qtype The query type to check against. + * @return true if the NSEC proves the condition. + */ + public static boolean nsecProvesNodata(NSECRecord nsec, Name qname, + int qtype) + { + if (!nsec.getName().equals(qname)) + { + // wildcard checking. + + // If this is a wildcard NSEC, make sure that a) it was possible to have + // generated qname from the wildcard and b) the type map does not + // contain qtype. Note that this does NOT prove that this wildcard was + // the applicable wildcard. + if (nsec.getName().isWild()) + { + // the is the purported closest encloser. + Name ce = new Name(nsec.getName(), 1); + + // The qname must be a strict subdomain of the closest encloser, and + // the qtype must be absent from the type map. + if (!qname.strictSubdomain(ce) || typeMapHasType(nsec.getTypes(), qtype)) + { + return false; + } + return true; + } + + // empty-non-terminal checking. + + // If the nsec is proving that qname is an ENT, the nsec owner will be + // less than qname, and the next name will be a child domain of the + // qname. + if (nsec.getNext().strictSubdomain(qname) + && qname.compareTo(nsec.getName()) > 0) + { + return true; + } + // Otherwise, this NSEC does not prove ENT, so it does not prove NODATA. + return false; + } + + // If the qtype exists, then we should have gotten it. + if (typeMapHasType(nsec.getTypes(), qtype)) + { + return false; + } + + // if the name is a CNAME node, then we should have gotten the CNAME + if (typeMapHasType(nsec.getTypes(), Type.CNAME)) + { + return false; + } + + // If an NS set exists at this name, and NOT a SOA (so this is a zone cut, + // not a zone apex), then we should have gotten a referral (or we just got + // the wrong NSEC). + if (typeMapHasType(nsec.getTypes(), Type.NS) + && !typeMapHasType(nsec.getTypes(), Type.SOA)) + { + return false; + } + + return true; + } + + public static int nsecProvesNoDS(NSECRecord nsec, Name qname) + { + // Could check to make sure the qname is a subdomain of nsec + int[] types = nsec.getTypes(); + if (typeMapHasType(types, Type.SOA) || typeMapHasType(types, Type.DS)) + { + // SOA present means that this is the NSEC from the child, not the + // parent (so it is the wrong one) + // DS present means that there should have been a positive response to + // the DS query, so there is something wrong. + return SecurityStatus.BOGUS; + } + + if (!typeMapHasType(types, Type.NS)) + { + // If there is no NS at this point at all, then this doesn't prove + // anything one way or the other. + return SecurityStatus.INSECURE; + } + // Otherwise, this proves no DS. + return SecurityStatus.SECURE; + } + +}