work in progress -- doesn't all compile yet, but it is starting to take shape

This commit is contained in:
David Blacka 2009-04-19 13:56:34 -04:00
commit 4273d3cfb8
12 changed files with 4057 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
build
.classpath
.project

334
build.xml Normal file
View File

@ -0,0 +1,334 @@
<?xml version="1.0"?>
<project default="compile" basedir=".">
<!-- defaults -->
<property name="build.deprecation" value="off" />
<property name="build.debug" value="off" />
<!-- import local build options -->
<property file="build.properties" />
<!-- import current version string -->
<property file="VERSION" />
<!-- the base location to put build targets -->
<property name="build.dir" value="build" />
<!-- where to put compiled class files -->
<property name="build.dest" value="${build.dir}/classes" />
<!-- where to put generated jar files -->
<property name="build.lib.dest" value="${build.dir}/lib" />
<!-- where to put generated javadocs -->
<property name="javadoc.dest" value="${build.dir}/doc" />
<!-- where to find the java source -->
<property name="build.src" value="src" />
<!-- where to find external jar files -->
<property name="lib.dir" value="lib" />
<!-- where the unit tests reside -->
<property name="test.dir" value="test" />
<property name="test.reports" value="${test.dir}/reports" />
<!-- PREPARE targets -->
<target name="prepare-env">
<!-- see if the 'test' directory exists -->
<available file="${test.dir}" type="dir" property="test.present" />
<!-- set the standard classpath -->
<path id="project.classpath">
<pathelement location="${build.dest}" />
<fileset dir="${lib.dir}" includes="*.jar,*.zip" />
</path>
<property name="project.classpath" refid="project.classpath" />
</target>
<target name="prepare-src" depends="prepare-env">
<mkdir dir="${build.dest}" />
<mkdir dir="${build.lib.dest}" />
</target>
<target name="prepare-test" depends="prepare-src" if="test.present">
<mkdir dir="${test.dir}/${build.dest}" />
<mkdir dir="${test.reports}" />
<path id="test.classpath">
<pathelement location="${test.dir}/${build.dest}" />
<pathelement path="${project.classpath}" />
<fileset dir="${test.dir}/${lib.dir}" includes="*jar,*.zip" />
</path>
<property name="test.classpath" refid="test.classpath" />
</target>
<!-- BUILD targets -->
<target name="dnsjava">
<javac srcdir="dnsjava"
destdir="${build.dest}"
deprecation="${build.deprecation}"
debug="${build.debug}"
target="1.4"
source="1.4"
includes="org/xbill/DNS/" />
<jar destfile="${build.lib.dest}/dnsjava-unbound.jar"
basedir="${build.dest}"
includes="org/xbill/DNS/" />
</target>
<target name="unbound-proto" depends="prepare-src, dnsjava" >
<javac srcdir="${build.src}"
destdir="${build.dest}"
deprecation="${build.deprecation}"
debug="${build.debug}"
target="1.4"
source="1.4"
classpathref="project.classpath"
includes="se/rfc/unbound/" />
</target>
<target name="unbound-proto-jar" depends="unbound-proto">
<jar jarfile="${build.lib.dest}/unbound-prototype.jar"
basedir="${build.dest}"
includes="se/rfc/unbound/" />
</target>
<!-- DOC targets -->
<target name="javadoc-unbound-proto" depends="prepare-src">
<mkdir dir="${javadoc.dest}" />
<javadoc packagenames="se.rfc.unbound.*"
sourcepath="${build.src}"
overview=""
classpath="${project.classpath}"
destdir="${javadoc.dest}"
verbose="false"
version="true"
author="true"
use="true"
windowtitle="Unbound Prototype API Documentation">
</javadoc>
</target>
<!-- TEST targets -->
<target name="build-tests" depends="prepare-test, unbound-proto"
if="test.present">
<javac srcdir="${test.dir}/${build.src}"
destdir="${test.dir}/${build.dest}"
deprecation="${build.deprecation}"
debug="${build.debug}"
target="1.4"
source="1.4"
classpathref="test.classpath"
includes="se/rfc/unbound/" />
</target>
<target name="run-tests" depends="build-tests" if="test.present">
<junit printsummary="yes"
fork="yes"
dir="${test.dir}"
timeout="12000">
<classpath>
<pathelement path="${test.classpath}" />
</classpath>
<formatter type="plain" />
<batchtest todir="${test.reports}">
<fileset dir="${test.dir}/${build.dest}">
<include name="se/rfc/unbound/**/*Test.class" />
</fileset>
</batchtest>
</junit>
</target>
<!-- DIST targets -->
<property name="unbound-proto-distname"
value="unbound-prototype-${version}" />
<target name="unbound-proto-dist"
depends="compile">
<tar tarfile="${unbound-proto-distname}.tar.gz"
compression="gzip">
<tarfileset mode="755"
dir="."
prefix="${unbound-proto-distname}">
<include name="bin/*.sh" />
<exclude name="bin/_*.sh" />
</tarfileset>
<tarfileset dir="."
prefix="${unbound-proto-distname}">
<include name="lib/*.jar" />
<include name="etc/*.properties" />
<include name="etc/named.ca" />
<include name="etc/trust_anchors" />
<include name="etc/*_trust_anchors" />
<include name="VERSION" />
<include name="README" />
<include name="licenses/**" />
<exclude name="bin/**" />
</tarfileset>
<tarfileset dir="${build.lib.dest}"
prefix="${unbound-proto-distname}/lib">
<include name="*.jar" />
</tarfileset>
</tar>
</target>
<target name="unbound-proto-src-dist">
<tar tarfile="${unbound-proto-distname}-src.tar.gz"
compression="gzip">
<tarfileset mode="755"
dir="."
prefix="${unbound-proto-distname}">
<include name="bin/*.sh" />
</tarfileset>
<tarfileset dir="."
prefix="${unbound-proto-distname}">
<include name="src/**/*.java" />
<include name="dnsjava/**" />
<include name="lib/*.jar" />
<include name="etc/*.properties" />
<include name="etc/named.ca" />
<include name="etc/trust_anchors" />
<include name="licenses/**" />
<include name="VERSION" />
<include name="README" />
<include name="build.xml" />
<exclude name="bin/**" />
</tarfileset>
</tar>
</target>
<target name="sign-dist"
depends="unbound-proto-dist, unbound-proto-src-dist">
<exec executable="gpg">
<arg value="-a" />
<arg value="-s" />
<arg value="--detach-sig" />
<arg path="${unbound-proto-distname}.tar.gz" />
</exec>
<exec executable="gpg">
<arg value="-a" />
<arg value="-s" />
<arg value="--detach-sig" />
<arg path="${unbound-proto-distname}-src.tar.gz" />
</exec>
</target>
<target name="flatten-jar-libs">
<mkdir dir="${build.dir}/jar" />
<unjar dest="${build.dir}/jar/">
<fileset dir="lib" includes="*.jar" />
</unjar>
</target>
<target name="unbound-resolver-jar" depends="compile, flatten-jar-libs">
<!-- this attempts to make a single runnable jar file for the
validating iterative resolver version of this project -->
<jar destfile="unbound-resolver.jar">
<fileset dir="${build.dest}"
includes="se/rfc/unbound/,org/xbill/DNS/" />
<fileset dir="${build.dir}/jar"
includes="**" />
<manifest>
<attribute name="Main-Class" value="se.rfc.unbound.server.Server" />
</manifest>
</jar>
</target>
<target name="unbound-digtest-jar" depends="compile, flatten-jar-libs">
<jar destfile="unbound-digtest.jar">
<fileset dir="${build.dest}"
includes="se/rfc/unbound/,org/xbill/DNS/" />
<fileset dir="${build.dir}/jar"
includes="**" />
<manifest>
<attribute name="Main-Class" value="se.rfc.unbound.cl.DigTest" />
</manifest>
</jar>
</target>
<!-- CLEAN targets -->
<target name="clean-unbound-proto" depends="prepare-env">
<delete dir="${build.dest}" />
<delete dir="${build.dir}/jar" />
<delete file="${build.lib.dest}/*.jar" />
</target>
<target name="clean-unbound-tests" depends="prepare-env"
if="test.present">
<delete dir="${test.dir}/${build.dest}" />
<delete dir="${test.reports}" />
</target>
<target name="clean-dist" depends="prepare-env">
<delete>
<fileset dir="." includes="*.tar.gz" />
</delete>
</target>
<!-- MASTER targets -->
<target name="compile"
depends="usage, unbound-proto-jar">
</target>
<target name="docs"
depends="javadoc-unbound-proto">
</target>
<target name="test"
depends="run-tests"
if="test.present">
</target>
<target name="dist"
depends="usage, unbound-proto-dist, unbound-proto-src-dist">
</target>
<target name="clean"
depends="usage, clean-unbound-proto, clean-unbound-tests, clean-dist">
</target>
<!-- USAGE target -->
<target name="usage" depends="prepare-env">
<echo message=" " />
<echo message="Unbound Prototype v. ${version} Build System" />
<echo message="--------------------------------------" />
<echo message="Available Targets:" />
<echo message=" compile (default) - compiles the source code" />
<echo message=" test - run the unit tests" />
<echo message=" dist - create the distribution files" />
<echo message=" clean - delete class files" />
<echo message=" usage - this help message" />
<echo message=" " />
</target>
</project>

Binary file not shown.

View File

@ -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();
}
}

View File

@ -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;
}