Issue #2. Handle CNAME responses
[captive-validator.git] / src / com / verisign / tat / dnssec / SignUtils.java
1 /***************************** -*- Java -*- ********************************\
2  *                                                                         *
3  *   Copyright (c) 2009 VeriSign, Inc. All rights reserved.                *
4  *                                                                         *
5  * This software is provided solely in connection with the terms of the    *
6  * license agreement.  Any other use without the prior express written     *
7  * permission of VeriSign is completely prohibited.  The software and      *
8  * documentation are "Commercial Items", as that term is defined in 48     *
9  * C.F.R.  section 2.101, consisting of "Commercial Computer Software" and *
10  * "Commercial Computer Software Documentation" as such terms are defined  *
11  * in 48 C.F.R. section 252.227-7014(a)(5) and 48 C.F.R. section           *
12  * 252.227-7014(a)(1), and used in 48 C.F.R. section 12.212 and 48 C.F.R.  *
13  * section 227.7202, as applicable.  Pursuant to the above and other       *
14  * relevant sections of the Code of Federal Regulations, as applicable,    *
15  * VeriSign's publications, commercial computer software, and commercial   *
16  * computer software documentation are distributed and licensed to United  *
17  * States Government end users with only those rights as granted to all    *
18  * other end users, according to the terms and conditions contained in the *
19  * license agreement(s) that accompany the products and software           *
20  * documentation.                                                          *
21  *                                                                         *
22 \***************************************************************************/
23
24 package com.verisign.tat.dnssec;
25
26 import org.apache.log4j.Logger;
27
28 import org.xbill.DNS.DNSKEYRecord;
29 import org.xbill.DNS.DNSOutput;
30 import org.xbill.DNS.Name;
31 import org.xbill.DNS.RRSIGRecord;
32 import org.xbill.DNS.RRset;
33 import org.xbill.DNS.Record;
34 import org.xbill.DNS.utils.base64;
35
36 import java.io.ByteArrayOutputStream;
37 import java.io.IOException;
38 import java.io.Serializable;
39
40 import java.security.SignatureException;
41 import java.security.interfaces.DSAParams;
42
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.Collections;
46 import java.util.Comparator;
47 import java.util.Date;
48 import java.util.Iterator;
49
50 /**
51  * This class contains a bunch of utility methods that are generally useful in
52  * signing and verifying rrsets.
53  */
54 public class SignUtils {
55     // private static final int DSA_SIGNATURE_LENGTH = 20;
56     private static final int ASN1_INT      = 0x02;
57     private static final int ASN1_SEQ      = 0x30;
58     public static  final int RR_NORMAL     = 0;
59     public static  final int RR_DELEGATION = 1;
60     public static  final int RR_GLUE       = 2;
61     public static  final int RR_INVALID    = 3;
62
63     private static Logger log = Logger.getLogger(SignUtils.class);
64
65     /**
66      * Generate from some basic information a prototype SIG RR containing
67      * everything but the actual signature itself.
68      *
69      * @param rrset
70      *            the RRset being signed.
71      * @param signer
72      *            the name of the signing key
73      * @param alg
74      *            the algorithm of the signing key
75      * @param keyid
76      *            the keyid (or footprint) of the signing key
77      * @param start
78      *            the SIG inception time.
79      * @param expire
80      *            the SIG expiration time.
81      * @param sig_ttl
82      *            the TTL of the resulting SIG record.
83      * @return a prototype signature based on the RRset and key information.
84      */
85     public static RRSIGRecord generatePreRRSIG(RRset rrset,
86                                                Name  signer,
87                                                int   alg,
88                                                int   keyid,
89                                                Date  start,
90                                                Date  expire,
91                                                long  sig_ttl) {
92         return new RRSIGRecord(rrset.getName(), rrset.getDClass(), sig_ttl,
93                                rrset.getType(), alg, rrset.getTTL(), expire, start, keyid,
94                                signer, null);
95     }
96
97     /**
98      * Generate from some basic information a prototype SIG RR
99      * containing everything but the actual signature itself.
100      *
101      * @param rrset
102      *            the RRset being signed.
103      * @param key
104      *            the public KEY RR counterpart to the key being used
105      *            to sign the RRset
106      * @param start
107      *            the SIG inception time.
108      * @param expire
109      *            the SIG expiration time.
110      * @param sig_ttl
111      *            the TTL of the resulting SIG record.
112      * @return a prototype signature based on the RRset and key information.
113      */
114     public static RRSIGRecord generatePreRRSIG(RRset        rrset,
115                                                DNSKEYRecord key,
116                                                Date         start,
117                                                Date         expire,
118                                                long         sig_ttl) {
119         return generatePreRRSIG(rrset, key.getName(), key.getAlgorithm(),
120                                 key.getFootprint(), start, expire, sig_ttl);
121     }
122
123     /**
124      * Generate from some basic information a prototype SIG RR
125      * containing everything but the actual signature itself.
126      *
127      * @param rec
128      *            the DNS record being signed (forming an entire RRset).
129      * @param key
130      *            the public KEY RR counterpart to the key signing the record.
131      * @param start
132      *            the SIG inception time.
133      * @param expire
134      *            the SIG expiration time.
135      * @param sig_ttl
136      *            the TTL of the result SIG record.
137      * @return a prototype signature based on the Record and key information.
138      */
139     public static RRSIGRecord generatePreRRSIG(Record       rec,
140                                                DNSKEYRecord key,
141                                                Date         start,
142                                                Date         expire,
143                                                long         sig_ttl) {
144         return new RRSIGRecord(rec.getName(), rec.getDClass(), sig_ttl,
145                                rec.getType(), key.getAlgorithm(), rec.getTTL(),
146                                expire, start, key.getFootprint(), key.getName(), null);
147     }
148
149     /**
150      * Generate the binary image of the prototype SIG RR.
151      *
152      * @param presig
153      *            the SIG RR prototype.
154      * @return the RDATA portion of the prototype SIG record. This forms the
155      *         first part of the data to be signed.
156      */
157     private static byte[] generatePreSigRdata(RRSIGRecord presig) {
158         // Generate the binary image;
159         DNSOutput image = new DNSOutput();
160
161         // precalculate some things
162         int  start_time  = (int) (presig.getTimeSigned().getTime() / 1000);
163         int  expire_time = (int) (presig.getExpire().getTime() / 1000);
164         Name signer      = presig.getSigner();
165
166         // first write out the partial SIG record (this is the SIG RDATA
167         // minus the actual signature.
168         image.writeU16(presig.getTypeCovered());
169         image.writeU8(presig.getAlgorithm());
170         image.writeU8(presig.getLabels());
171         image.writeU32((int) presig.getOrigTTL());
172         image.writeU32(expire_time);
173         image.writeU32(start_time);
174         image.writeU16(presig.getFootprint());
175         image.writeByteArray(signer.toWireCanonical());
176
177         return image.toByteArray();
178     }
179
180     /**
181      * Calculate the canonical wire line format of the RRset.
182      *
183      * @param rrset
184      *            the RRset to convert.
185      * @param ttl
186      *            the TTL to use when canonicalizing -- this is generally the
187      *            TTL of the signature if there is a pre-existing signature. If
188      *            not it is just the ttl of the rrset itself.
189      * @param labels
190      *            the labels field of the signature, or 0.
191      * @return the canonical wire line format of the rrset. This is the second
192      *         part of data to be signed.
193      */
194     @SuppressWarnings("rawtypes")
195     public static byte[] generateCanonicalRRsetData(RRset rrset, long ttl, int labels) {
196         DNSOutput image = new DNSOutput();
197
198         if (ttl == 0) {
199             ttl = rrset.getTTL();
200         }
201
202         Name n = rrset.getName();
203
204         if (labels == 0) {
205             labels = n.labels();
206         } else {
207             // correct for Name()'s conception of label count.
208             labels++;
209         }
210
211         boolean wildcardName = false;
212
213         if (n.labels() != labels) {
214             n = n.wild(n.labels() - labels);
215             wildcardName = true;
216             log.trace("Detected wildcard expansion: " + rrset.getName() +
217                       " changed to " + n);
218         }
219
220         // now convert the wire format records in the RRset into a
221         // list of byte arrays.
222         ArrayList<byte[]> canonical_rrs = new ArrayList<byte[]>();
223
224         for (Iterator i = rrset.rrs(); i.hasNext();) {
225             Record r = (Record) i.next();
226
227             if ((r.getTTL() != ttl) || wildcardName) {
228                 // If necessary, we need to create a new record with a new ttl
229                 // or ownername.
230                 // In the TTL case, this avoids changing the ttl in the
231                 // response.
232                 r = Record.newRecord(n, r.getType(), r.getDClass(), ttl,
233                                      r.rdataToWireCanonical());
234             }
235
236             byte[] wire_fmt = r.toWireCanonical();
237             canonical_rrs.add(wire_fmt);
238         }
239
240         // put the records into the correct ordering.
241         // Calculate the offset where the RDATA begins (we have to skip
242         // past the length byte)
243         int                 offset = rrset.getName().toWireCanonical().length + 10;
244         ByteArrayComparator bac    = new ByteArrayComparator(offset, false);
245
246         Collections.sort(canonical_rrs, bac);
247
248         for (Iterator<byte[]> i = canonical_rrs.iterator(); i.hasNext();) {
249             byte[] wire_fmt_rec = i.next();
250             image.writeByteArray(wire_fmt_rec);
251         }
252
253         return image.toByteArray();
254     }
255
256     /**
257      * Given an RRset and the prototype signature, generate the
258      * canonical data that is to be signed.
259      *
260      * @param rrset
261      *            the RRset to be signed.
262      * @param presig
263      *            a prototype SIG RR created using the same RRset.
264      * @return a block of data ready to be signed.
265      */
266     public static byte[] generateSigData(RRset rrset, RRSIGRecord presig)
267             throws IOException {
268         byte[] rrset_data = generateCanonicalRRsetData(rrset, presig.getOrigTTL(), presig.getLabels());
269
270         return generateSigData(rrset_data, presig);
271     }
272
273     /**
274      * Given an RRset and the prototype signature, generate the
275      * canonical data that is to be signed.
276      *
277      * @param rrset_data
278      *            the RRset converted into canonical wire line format (as per
279      *            the canonicalization rules in RFC 2535).
280      * @param presig
281      *            the prototype signature based on the same RRset represented in
282      *            <code>rrset_data</code>.
283      * @return a block of data ready to be signed.
284      */
285     public static byte[] generateSigData(byte[] rrset_data, RRSIGRecord presig)
286         throws IOException {
287         byte[] sig_rdata = generatePreSigRdata(presig);
288
289         ByteArrayOutputStream image = new ByteArrayOutputStream(sig_rdata.length + rrset_data.length);
290
291         image.write(sig_rdata);
292         image.write(rrset_data);
293
294         return image.toByteArray();
295     }
296
297     /**
298      * Given the actual signature and the prototype signature, combine
299      * them and return the fully formed RRSIGRecord.
300      *
301      * @param signature
302      *            the cryptographic signature, in DNSSEC format.
303      * @param presig
304      *            the prototype RRSIG RR to add the signature to.
305      * @return the fully formed RRSIG RR.
306      */
307     public static RRSIGRecord generateRRSIG(byte[] signature, RRSIGRecord presig) {
308         return new RRSIGRecord(presig.getName(), presig.getDClass(),
309                                presig.getTTL(), presig.getTypeCovered(), presig.getAlgorithm(),
310                                presig.getOrigTTL(), presig.getExpire(), presig.getTimeSigned(),
311                                presig.getFootprint(), presig.getSigner(), signature);
312     }
313
314     /**
315      * Converts from a RFC 2536 formatted DSA signature to a JCE
316      * (ASN.1) formatted signature.
317      *
318      * <p>
319      * ASN.1 format = ASN1_SEQ . seq_length . ASN1_INT . Rlength . R . ANS1_INT
320      * . Slength . S
321      * </p>
322      *
323      * The integers R and S may have a leading null byte to force the
324      * integer positive.
325      *
326      * @param signature
327      *            the RFC 2536 formatted DSA signature.
328      * @return The ASN.1 formatted DSA signature.
329      * @throws SignatureException
330      *             if there was something wrong with the RFC 2536 formatted
331      *             signature.
332      */
333     public static byte[] convertDSASignature(byte[] signature)
334         throws SignatureException {
335         if (signature.length != 41) {
336             throw new SignatureException("RFC 2536 signature not expected length.");
337         }
338
339         byte r_pad = 0;
340         byte s_pad = 0;
341
342         // handle initial null byte padding.
343         if (signature[1] < 0) {
344             r_pad++;
345         }
346
347         if (signature[21] < 0) {
348             s_pad++;
349         }
350
351         // ASN.1 length = R length + S length + (2 + 2 + 2), where each 2
352         // is for a ASN.1 type-length byte pair of which there are three
353         // (SEQ, INT, INT).
354         byte sig_length = (byte) (40 + r_pad + s_pad + 6);
355
356         byte[] sig = new byte[sig_length];
357         byte pos = 0;
358
359         sig[pos++] = ASN1_SEQ;
360         sig[pos++] = (byte) (sig_length - 2); // all but the SEQ type+length.
361         sig[pos++] = ASN1_INT;
362         sig[pos++] = (byte) (20 + r_pad);
363
364         // copy the value of R, leaving a null byte if necessary
365         if (r_pad == 1) {
366             sig[pos++] = 0;
367         }
368
369         System.arraycopy(signature, 1, sig, pos, 20);
370         pos += 20;
371
372         sig[pos++] = ASN1_INT;
373         sig[pos++] = (byte) (20 + s_pad);
374
375         // copy the value of S, leaving a null byte if necessary
376         if (s_pad == 1) {
377             sig[pos++] = 0;
378         }
379
380         System.arraycopy(signature, 21, sig, pos, 20);
381
382         return sig;
383     }
384
385     /**
386      * Converts from a JCE (ASN.1) formatted DSA signature to a RFC
387      * 2536 compliant signature.
388      *
389      * <p>
390      * rfc2536 format = T . R . S
391      * </p>
392      *
393      * where T is a number between 0 and 8, which is based on the DSA key
394      * length, and R & S are formatted to be exactly 20 bytes each (no leading
395      * null bytes).
396      *
397      * @param params
398      *            the DSA parameters associated with the DSA key used to
399      *            generate the signature.
400      * @param signature
401      *            the ASN.1 formatted DSA signature.
402      * @return a RFC 2536 formatted DSA signature.
403      * @throws SignatureException
404      *             if something is wrong with the ASN.1 format.
405      */
406     public static byte[] convertDSASignature(DSAParams params, byte[] signature)
407         throws SignatureException {
408         if ((signature[0] != ASN1_SEQ) || (signature[2] != ASN1_INT)) {
409             throw new SignatureException("Invalid ASN.1 signature format: expected SEQ, INT");
410         }
411
412         byte r_pad = (byte) (signature[3] - 20);
413
414         if (signature[24 + r_pad] != ASN1_INT) {
415             throw new SignatureException("Invalid ASN.1 signature format: expected SEQ, INT, INT");
416         }
417
418         log.trace("(start) ASN.1 DSA Sig:\n" + base64.toString(signature));
419
420         byte s_pad = (byte) (signature[25 + r_pad] - 20);
421
422         byte[] sig = new byte[41]; // all rfc2536 signatures are 41 bytes.
423
424         // Calculate T:
425         sig[0] = (byte) ((params.getP().bitLength() - 512) / 64);
426
427         // copy R value
428         if (r_pad >= 0) {
429             System.arraycopy(signature, 4 + r_pad, sig, 1, 20);
430         } else {
431             // R is shorter than 20 bytes, so right justify the number
432             // (r_pad is negative here, remember?).
433             Arrays.fill(sig, 1, 1 - r_pad, (byte) 0);
434             System.arraycopy(signature, 4, sig, 1 - r_pad, 20 + r_pad);
435         }
436
437         // copy S value
438         if (s_pad >= 0) {
439             System.arraycopy(signature, 26 + r_pad + s_pad, sig, 21, 20);
440         } else {
441             // S is shorter than 20 bytes, so right justify the number
442             // (s_pad is negative here).
443             Arrays.fill(sig, 21, 21 - s_pad, (byte) 0);
444             System.arraycopy(signature, 26 + r_pad, sig, 21 - s_pad, 20 + s_pad);
445         }
446
447         if ((r_pad < 0) || (s_pad < 0)) {
448             log.trace("(finish ***) RFC 2536 DSA Sig:\n" + base64.toString(sig));
449         } else {
450             log.trace("(finish) RFC 2536 DSA Sig:\n" + base64.toString(sig));
451         }
452
453         return sig;
454     }
455
456     /**
457      * This class implements a basic comparator for byte arrays. It is
458      * primarily useful for comparing RDATA portions of DNS records in
459      * doing DNSSEC canonical ordering.
460      */
461     public static class ByteArrayComparator implements Comparator<byte[]>, Serializable {
462         private static final long serialVersionUID = 1L;
463         private int               mOffset          = 0;
464         private boolean           mDebug           = false;
465
466         public ByteArrayComparator() { }
467
468         public ByteArrayComparator(int offset, boolean debug) {
469             mOffset = offset;
470             mDebug  = debug;
471         }
472
473         public int compare(byte[] b1, byte[] b2) throws ClassCastException {
474             for (int i = mOffset; (i < b1.length) && (i < b2.length); i++) {
475                 if (b1[i] != b2[i]) {
476                     if (mDebug) {
477                         System.out.println("offset " + i + " differs (this is " + (i - mOffset) +
478                                            " bytes in from our offset.)");
479                     }
480
481                     return (b1[i] & 0xFF) - (b2[i] & 0xFF);
482                 }
483             }
484
485             return b1.length - b2.length;
486         }
487     }
488 }