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