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