2 * Copyright (c) 2009 VeriSign, Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 package com.versign.tat.dnssec;
31 import java.security.MessageDigest;
32 import java.security.NoSuchAlgorithmException;
33 import java.util.Iterator;
35 import org.xbill.DNS.*;
38 * This is a collection of routines encompassing the logic of validating
39 * different message types.
42 public class ValUtils {
44 // These are response subtypes. They are necessary for determining the
45 // validation strategy. They have no bearing on the iterative resolution
46 // algorithm, so they are confined here.
48 public enum ResponseType {
49 UNTYPED, // not sub typed yet
50 UNKNOWN, // not a recognized sub type
51 POSITIVE, // a positive response (no CNAME/DNAME chain)
52 CNAME, // a positive response with a CNAME/DNAME chain.
53 NODATA, // a NOERROR/NODATA response
54 NAMEERROR, // a NXDOMAIN response
55 ANY, // a response to a qtype=ANY query
57 // a referral response
59 // a throwaway response (i.e., an error)
62 /** A local copy of the verifier object. */
63 private DnsSecVerifier mVerifier;
65 public ValUtils(DnsSecVerifier verifier) {
70 * Given a response, classify ANSWER responses into a subtype.
73 * The response to classify.
75 * @return A subtype ranging from UNKNOWN to NAMEERROR.
77 public static ResponseType classifyResponse(SMessage m, Name zone) {
80 // Normal Name Error's are easy to detect -- but don't mistake a CNAME
81 // chain ending in NXDOMAIN.
82 if (m.getRcode() == Rcode.NXDOMAIN && m.getCount(Section.ANSWER) == 0) {
83 return ResponseType.NAMEERROR;
86 // If rcode isn't NXDOMAIN or NOERROR, it is a throwaway response.
87 if (m.getRcode() != Rcode.NOERROR) {
88 return ResponseType.THROWAWAY;
91 // Next is REFERRAL. These are distinguished by having:
92 // 1) nothing in the ANSWER section
93 // 2) an NS RRset in the AUTHORITY section that is a strict subdomain of
94 // 'zone' (the presumed queried zone).
95 if (zone != null && m.getCount(Section.ANSWER) == 0
96 && m.getCount(Section.AUTHORITY) > 0) {
97 rrsets = m.getSectionRRsets(Section.AUTHORITY);
98 for (int i = 0; i < rrsets.length; ++i) {
99 if (rrsets[i].getType() == Type.NS
100 && strictSubdomain(rrsets[i].getName(), zone)) {
101 return ResponseType.REFERRAL;
107 if (m.getCount(Section.ANSWER) == 0) {
108 return ResponseType.NODATA;
111 // We distinguish between CNAME response and other positive/negative
112 // responses because CNAME answers require extra processing.
113 int qtype = m.getQuestion().getType();
115 // We distinguish between ANY and CNAME or POSITIVE because ANY
116 // responses are validated differently.
117 if (qtype == Type.ANY) {
118 return ResponseType.ANY;
121 rrsets = m.getSectionRRsets(Section.ANSWER);
123 // Note that DNAMEs will be ignored here, unless qtype=DNAME. Unless
124 // qtype=CNAME, this will yield a CNAME response.
125 for (int i = 0; i < rrsets.length; i++) {
126 if (rrsets[i].getType() == qtype) return ResponseType.POSITIVE;
127 if (rrsets[i].getType() == Type.CNAME) return ResponseType.CNAME;
130 // st_log.warn("Failed to classify response message:\n" + m);
131 return ResponseType.UNKNOWN;
135 * Given a response, determine the name of the "signer". This is primarily
136 * to determine if the response is, in fact, signed at all, and, if so, what
137 * is the name of the most pertinent keyset.
140 * The response to analyze.
141 * @return a signer name, if the response is signed (even partially), or
142 * null if the response isn't signed.
144 public Name findSigner(SMessage m) {
145 // FIXME: this used to classify the message, then look in the pertinent
146 // section. Now we just find the first RRSIG in the ANSWER and AUTHORIY
149 for (int section = Section.ANSWER; section < Section.ADDITIONAL; ++section) {
150 SRRset[] rrsets = m.getSectionRRsets(section);
151 for (int i = 0; i < rrsets.length; ++i) {
152 Name signerName = rrsets[i].getSignerName();
153 if (signerName != null) return signerName;
161 * Given a DNSKEY record, generate the DS record from it.
164 * the DNSKEY record in question.
166 * The DS digest algorithm in use.
167 * @return the corresponding {@link org.xbill.DNS.DSRecord}
169 public static byte[] calculateDSHash(DNSKEYRecord keyrec, int ds_alg) {
170 DNSOutput os = new DNSOutput();
172 os.writeByteArray(keyrec.getName().toWireCanonical());
173 os.writeByteArray(keyrec.rdataToWireCanonical());
176 MessageDigest md = null;
178 case DSRecord.SHA1_DIGEST_ID:
179 md = MessageDigest.getInstance("SHA");
180 return md.digest(os.toByteArray());
181 case DSRecord.SHA256_DIGEST_ID:
182 md = MessageDigest.getInstance("SHA256");
183 return md.digest(os.toByteArray());
185 // st_log.warn("Unknown DS algorithm: " + ds_alg);
189 } catch (NoSuchAlgorithmException e) {
190 // st_log.error("Error using DS algorithm: " + ds_alg, e);
195 public static boolean supportsDigestID(int digest_id) {
196 if (digest_id == DSRecord.SHA1_DIGEST_ID) return true;
197 if (digest_id == DSRecord.SHA256_DIGEST_ID) return true;
202 * Check to see if a type is a special DNSSEC type.
207 * @return true if the type is one of the special DNSSEC types.
209 public static boolean isDNSSECType(int type) {
223 * Set the security status of a particular RRset. This will only upgrade the
227 * The SRRset to update.
229 * The security status.
231 public static void setRRsetSecurity(SRRset rrset, byte security) {
232 if (rrset == null) return;
234 int cur_sec = rrset.getSecurityStatus();
235 if (cur_sec == SecurityStatus.UNCHECKED || security > cur_sec) {
236 rrset.setSecurityStatus(security);
241 * Set the security status of a message and all of its RRsets. This will
242 * only upgrade the status of the message (i.e., set to more secure, not
243 * less) and all of the RRsets.
249 * SMessage m = response.getSMessage(); SRRset ans_rrset =
250 * m.findAnswerRRset(qname, qtype, qclass);
252 * ke = verifySRRset(ans_rrset, key_rrset); if
253 * (ans_rrset.getSecurityStatus() != SecurityStatus.SECURE) {
254 * return; } key_rrset = ke.getRRset();
256 public static void setMessageSecurity(SMessage m, byte security) {
257 if (m == null) return;
259 int cur_sec = m.getStatus();
260 if (cur_sec == SecurityStatus.UNCHECKED || security > cur_sec) {
261 m.setStatus(security);
264 for (int section = Section.ANSWER; section <= Section.ADDITIONAL; section++) {
265 SRRset[] rrsets = m.getSectionRRsets(section);
266 for (int i = 0; i < rrsets.length; i++) {
267 setRRsetSecurity(rrsets[i], security);
273 * Given an SRRset that is signed by a DNSKEY found in the key_rrset, verify
274 * it. This will return the status (either BOGUS or SECURE) and set that
278 * The SRRset to verify.
280 * The set of keys to verify against.
281 * @return The status (BOGUS or SECURE).
283 public byte verifySRRset(SRRset rrset, SRRset key_rrset) {
284 // String rrset_name = rrset.getName() + "/"
285 // + Type.string(rrset.getType()) + "/"
286 // + DClass.string(rrset.getDClass());
288 if (rrset.getSecurityStatus() == SecurityStatus.SECURE) {
289 // log.trace("verifySRRset: rrset <" + rrset_name
290 // + "> previously found to be SECURE");
291 return SecurityStatus.SECURE;
294 byte status = mVerifier.verify(rrset, key_rrset);
295 if (status != SecurityStatus.SECURE) {
296 // log.debug("verifySRRset: rrset <" + rrset_name +
297 // "> found to be BAD");
298 status = SecurityStatus.BOGUS;
302 // log.trace("verifySRRset: rrset <" + rrset_name +
303 // "> found to be SECURE");
306 rrset.setSecurityStatus(status);
311 * Determine if a given type map has a given type.
314 * The type map from the NSEC record.
316 * The type to look for.
317 * @return true if the type is present in the type map, false otherwise.
319 public static boolean typeMapHasType(int[] types, int type) {
320 for (int i = 0; i < types.length; i++) {
321 if (types[i] == type) return true;
326 @SuppressWarnings("unchecked")
327 public static RRSIGRecord rrsetFirstSig(RRset rrset) {
328 for (Iterator i = rrset.sigs(); i.hasNext();) {
329 return (RRSIGRecord) i.next();
335 * Finds the longest common name between two domain names.
341 public static Name longestCommonName(Name domain1, Name domain2) {
342 if (domain1 == null || domain2 == null) return null;
343 // for now, do this in a a fairly brute force way
344 // FIXME: convert this to direct operations on the byte[]
346 int d1_labels = domain1.labels();
347 int d2_labels = domain2.labels();
349 int l = (d1_labels < d2_labels) ? d1_labels : d2_labels;
350 for (int i = l; i > 0; i--) {
351 Name n1 = new Name(domain1, d1_labels - i);
352 Name n2 = new Name(domain2, d2_labels - i);
361 public static boolean strictSubdomain(Name child, Name parent) {
362 int clabels = child.labels();
363 int plabels = parent.labels();
364 if (plabels >= clabels) return false;
366 Name n = new Name(child, clabels - plabels);
367 return parent.equals(n);
371 * Determine by looking at a signed RRset whether or not the rrset name was
372 * the result of a wildcard expansion.
375 * The rrset to examine.
376 * @return true if the rrset is a wildcard expansion. This will return false
377 * for all unsigned rrsets.
379 public static boolean rrsetIsWildcardExpansion(RRset rrset) {
380 if (rrset == null) return false;
381 RRSIGRecord rrsig = rrsetFirstSig(rrset);
383 if (rrset.getName().labels() - 1 > rrsig.getLabels()) {
391 * Determine by looking at a signed RRset whether or not the RRset name was
392 * the result of a wildcard expansion. If so, return the name of the
393 * generating wildcard.
396 * The rrset to check.
397 * @return the wildcard name, if the rrset was synthesized from a wildcard.
400 public static Name rrsetWildcard(RRset rrset) {
401 if (rrset == null) return null;
402 RRSIGRecord rrsig = rrsetFirstSig(rrset);
404 // if the RRSIG label count is shorter than the number of actual labels,
405 // then this rrset was synthesized from a wildcard.
406 // Note that the RRSIG label count doesn't count the root label.
407 int label_diff = (rrset.getName().labels() - 1) - rrsig.getLabels();
408 if (label_diff > 0) {
409 return rrset.getName().wild(label_diff);
414 public static Name closestEncloser(Name domain, NSECRecord nsec) {
415 Name n1 = longestCommonName(domain, nsec.getName());
416 Name n2 = longestCommonName(domain, nsec.getNext());
418 return (n1.labels() > n2.labels()) ? n1 : n2;
421 public static Name nsecWildcard(Name domain, NSECRecord nsec) {
423 return new Name("*", closestEncloser(domain, nsec));
424 } catch (TextParseException e) {
425 // this should never happen.
431 * Determine if the given NSEC proves a NameError (NXDOMAIN) for a given
437 * The qname to check against.
439 * The signer name of the NSEC record, which is used as the zone
440 * name, for a more precise (but perhaps more brittle) check for
441 * the last NSEC in a zone.
442 * @return true if the NSEC proves the condition.
444 public static boolean nsecProvesNameError(NSECRecord nsec, Name qname,
446 Name owner = nsec.getName();
447 Name next = nsec.getNext();
449 // If NSEC owner == qname, then this NSEC proves that qname exists.
450 if (qname.equals(owner)) {
454 // If NSEC is a parent of qname, we need to check the type map
455 // If the parent name has a DNAME or is a delegation point, then this
456 // NSEC is being misused.
457 boolean hasBadType = typeMapHasType(nsec.getTypes(), Type.DNAME)
458 || (typeMapHasType(nsec.getTypes(), Type.NS) && !typeMapHasType(nsec.getTypes(),
460 if (qname.subdomain(owner) && hasBadType) {
464 if (qname.compareTo(owner) > 0 && (qname.compareTo(next) < 0)
465 || signerName.equals(next)) {
472 * Determine if a NSEC record proves the non-existence of a wildcard that
473 * could have produced qname.
478 * The qname to check against.
480 * The signer name for the NSEC rrset, used as the zone name.
481 * @return true if the NSEC proves the condition.
483 public static boolean nsecProvesNoWC(NSECRecord nsec, Name qname,
485 Name owner = nsec.getName();
486 Name next = nsec.getNext();
488 int qname_labels = qname.labels();
489 int signer_labels = signerName.labels();
491 for (int i = qname_labels - signer_labels; i > 0; i--) {
492 Name wc_name = qname.wild(i);
493 if (wc_name.compareTo(owner) > 0
494 && (wc_name.compareTo(next) < 0 || signerName.equals(next))) {
503 * Determine if a NSEC proves the NOERROR/NODATA conditions. This will also
504 * handle the empty non-terminal (ENT) case and partially handle the
505 * wildcard case. If the ownername of 'nsec' is a wildcard, the validator
506 * must still be provided proof that qname did not directly exist and that
507 * the wildcard is, in fact, *.closest_encloser.
512 * The query name to check against.
514 * The query type to check against.
515 * @return true if the NSEC proves the condition.
517 public static boolean nsecProvesNodata(NSECRecord nsec, Name qname,
519 if (!nsec.getName().equals(qname)) {
520 // wildcard checking.
522 // If this is a wildcard NSEC, make sure that a) it was possible to
524 // generated qname from the wildcard and b) the type map does not
525 // contain qtype. Note that this does NOT prove that this wildcard
527 // the applicable wildcard.
528 if (nsec.getName().isWild()) {
529 // the is the purported closest encloser.
530 Name ce = new Name(nsec.getName(), 1);
532 // The qname must be a strict subdomain of the closest encloser,
534 // the qtype must be absent from the type map.
535 if (!strictSubdomain(qname, ce)
536 || typeMapHasType(nsec.getTypes(), qtype)) {
542 // empty-non-terminal checking.
544 // If the nsec is proving that qname is an ENT, the nsec owner will
546 // less than qname, and the next name will be a child domain of the
548 if (strictSubdomain(nsec.getNext(), qname)
549 && qname.compareTo(nsec.getName()) > 0) {
552 // Otherwise, this NSEC does not prove ENT, so it does not prove
557 // If the qtype exists, then we should have gotten it.
558 if (typeMapHasType(nsec.getTypes(), qtype)) {
562 // if the name is a CNAME node, then we should have gotten the CNAME
563 if (typeMapHasType(nsec.getTypes(), Type.CNAME)) {
567 // If an NS set exists at this name, and NOT a SOA (so this is a zone
569 // not a zone apex), then we should have gotten a referral (or we just
572 if (typeMapHasType(nsec.getTypes(), Type.NS)
573 && !typeMapHasType(nsec.getTypes(), Type.SOA)) {
580 public static byte nsecProvesNoDS(NSECRecord nsec, Name qname) {
581 // Could check to make sure the qname is a subdomain of nsec
582 int[] types = nsec.getTypes();
583 if (typeMapHasType(types, Type.SOA) || typeMapHasType(types, Type.DS)) {
584 // SOA present means that this is the NSEC from the child, not the
585 // parent (so it is the wrong one)
586 // DS present means that there should have been a positive response
588 // the DS query, so there is something wrong.
589 return SecurityStatus.BOGUS;
592 if (!typeMapHasType(types, Type.NS)) {
593 // If there is no NS at this point at all, then this doesn't prove
594 // anything one way or the other.
595 return SecurityStatus.INSECURE;
597 // Otherwise, this proves no DS.
598 return SecurityStatus.SECURE;