summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/servlet/cert/ImportCertsTemplateFiller.java
blob: 98da803723c56fb4866d54b3dade757d9e2f91d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;


import com.netscape.cms.servlet.common.*;
import com.netscape.cms.servlet.base.*;
 
import java.util.Locale;
import java.math.BigInteger;
import java.io.ByteArrayOutputStream;
import java.io.StringWriter;
import java.io.StringReader;
import java.io.BufferedReader;


import javax.servlet.http.HttpServletRequest;

import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.NoSuchAlgorithmException;
import netscape.security.x509.X509CertImpl;
import netscape.security.x509.CertificateChain;
import netscape.security.x509.AlgorithmId;
import netscape.security.pkcs.PKCS7;
import netscape.security.pkcs.ContentInfo;
import netscape.security.pkcs.SignerInfo;

import com.netscape.certsrv.apps.*;
import com.netscape.certsrv.base.*;
import com.netscape.certsrv.authority.*;
import com.netscape.certsrv.dbs.keydb.*;
import com.netscape.certsrv.request.IRequest;

import org.mozilla.jss.asn1.*;
import org.mozilla.jss.pkix.cmmf.*;


/**
 * Set up HTTP response to import certificate into browsers
 * 
 * The result must have been populate with the set of certificates
 * to return.
 * <pre>
 * inputs: certtype.
 * outputs: 
 *		- cert type from http input (if any)
 *      - CA chain 
 *		- authority name (RM, CM, DRM)
 *      - scheme:host:port of server.
 *	 array of one or more 
 *      - cert serial number
 *      - cert pretty print
 *		- cert in base 64 encoding.
 *		- cmmf blob to import 
 * </pre>
 * @version $Revision$, $Date$
 */
public class ImportCertsTemplateFiller implements ICMSTemplateFiller {
    public static final String CRMF_REQID = "crmfReqId";
    public static final String ISSUED_CERT_SERIAL = "serialNo";
    public static final String CERT_TYPE = "certType";
    public static final String BASE64_CERT = "base64Cert";
    public static final String CERT_PRETTYPRINT = "certPrettyPrint";
    public static final String CERT_FINGERPRINT = "certFingerprint"; // cisco
    public static final String CERT_NICKNAME = "certNickname";
    public static final String CMMF_RESP = "cmmfResponse";
    public static final String PKCS7_RESP = "pkcs7ChainBase64";  // for MSIE

    public ImportCertsTemplateFiller() {
    }

    /**
     * @param cmsReq CMS Request
     * @param authority this authority
     * @param locale locale of template.
     * @param e unexpected exception e. ignored.
     */
    public CMSTemplateParams getTemplateParams(
        CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e) 
        throws Exception {
        Certificate[] certs = (Certificate[]) cmsReq.getResult();

        if (certs instanceof X509CertImpl[])
            return 	getX509TemplateParams(cmsReq, authority, locale, e);
        else
            return null;
    }
	
    public CMSTemplateParams getX509TemplateParams(
        CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e) 
        throws Exception {
        IArgBlock header = CMS.createArgBlock();
        IArgBlock fixed = CMS.createArgBlock();
        CMSTemplateParams params = new CMSTemplateParams(header, fixed);

        // set host name and port. 
        HttpServletRequest httpReq = cmsReq.getHttpReq();
        String host = httpReq.getServerName();
        int port = httpReq.getServerPort();
        String scheme = httpReq.getScheme();
        String format = httpReq.getParameter("format");
        if(format!=null && format.equals("cmc"))
            fixed.set("importCMC", "false");
        String agentPort = ""+port;
        fixed.set("agentHost", host);
        fixed.set("agentPort", agentPort);
        fixed.set(ICMSTemplateFiller.HOST, host);
        fixed.set(ICMSTemplateFiller.PORT, Integer.valueOf(port));
        fixed.set(ICMSTemplateFiller.SCHEME, scheme);
        IRequest r = cmsReq.getIRequest();

        if (r != null) {
            fixed.set(ICMSTemplateFiller.REQUEST_ID, r.getRequestId().toString());
        }

        // set key record (if KRA enabled)
        if (r != null) {
            BigInteger keyRecSerialNo = r.getExtDataInBigInteger("keyRecord");

            if (keyRecSerialNo != null) {
                fixed.set(ICMSTemplateFiller.KEYREC_ID, keyRecSerialNo.toString());
            }
        }

        // set cert type.
        IArgBlock httpParams = cmsReq.getHttpParams();
        String certType = 
            httpParams.getValueAsString(CERT_TYPE, null);

        if (certType != null) 
            fixed.set(CERT_TYPE, certType);

            // this authority
        fixed.set(ICMSTemplateFiller.AUTHORITY, 
            (String) authority.getOfficialName());

        // CA chain.
        CertificateChain cachain = 
            ((ICertAuthority) authority).getCACertChain();
        X509Certificate[] cacerts = cachain.getChain();

        String replyTo = httpParams.getValueAsString("replyTo", null);

        if (replyTo != null) fixed.set("replyTo", replyTo);

            // set user + CA cert chain and pkcs7 for MSIE. 
        X509CertImpl[] userChain = new X509CertImpl[cacerts.length + 1];
        int m = 1, n = 0;

        for (; n < cacerts.length; m++, n++) 
            userChain[m] = (X509CertImpl) cacerts[n];

            // certs. 
        X509CertImpl[] certs = (X509CertImpl[]) cmsReq.getResult();

        // expose CRMF request id
        String crmfReqId = cmsReq.getExtData(IRequest.CRMF_REQID);

        if (crmfReqId == null) {
            crmfReqId = (String) cmsReq.getResult(
                        IRequest.CRMF_REQID);
        }
        if (crmfReqId != null) {
            fixed.set(CRMF_REQID, crmfReqId);
        }

        // set CA certs in cmmf, initialize CertRepContent 
        // note cartman can't trust ca certs yet but it'll import them.
        // also set cert nickname for cartman.
        CertRepContent certRepContent = null;

        if (CMSServlet.doCMMFResponse(httpParams)) {
            byte[][] caPubs = new byte[cacerts.length][];

            for (int j = 0; j < cacerts.length; j++) 
                caPubs[j] = ((X509CertImpl) cacerts[j]).getEncoded();
            certRepContent = new CertRepContent(caPubs);

            String certnickname = 
                cmsReq.getHttpParams().getValueAsString(CERT_NICKNAME, null);

            // if nickname is not requested set to subject name by default.
            if (certnickname == null) 
                fixed.set(CERT_NICKNAME, certs[0].getSubjectDN().toString());
            else
                fixed.set(CERT_NICKNAME, certnickname);
        }

        // make pkcs7 for MSIE 
        if (CMSServlet.clientIsMSIE(cmsReq.getHttpReq()) && 
            (certType == null || certType.equals("client"))) {
            userChain[0] = certs[0];
            PKCS7 p7 = new PKCS7(new AlgorithmId[0],
                    new ContentInfo(new byte[0]),
                    userChain,
                    new SignerInfo[0]);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            p7.encodeSignedData(bos);
            byte[] p7Bytes = bos.toByteArray();
            //		String p7Str = encoder.encodeBuffer(p7Bytes);
            String p7Str = CMS.BtoA(p7Bytes);

            header.set(PKCS7_RESP, p7Str);
        }

        // set base 64, pretty print and cmmf response for each issued cert.
        for (int i = 0; i < certs.length; i++) {
            IArgBlock repeat = CMS.createArgBlock();
            X509CertImpl cert = certs[i];

            // set serial number.
            BigInteger serialNo = 
                ((X509Certificate) cert).getSerialNumber();

            repeat.addBigIntegerValue(ISSUED_CERT_SERIAL, serialNo, 16);

            // set base64 encoded blob.
            byte[] certEncoded = cert.getEncoded();
            //			String b64 = encoder.encodeBuffer(certEncoded);
            String b64 = CMS.BtoA(certEncoded);
            String b64cert = "-----BEGIN CERTIFICATE-----\n" +
                b64 + "\n-----END CERTIFICATE-----";

            repeat.set(BASE64_CERT, b64cert);
			
            // set cert pretty print.
			
            String prettyPrintRequested =
                cmsReq.getHttpParams().getValueAsString(CERT_PRETTYPRINT, null);

            if (prettyPrintRequested == null) {
                prettyPrintRequested = "true";
            }
            String ppStr = "";

            if (!prettyPrintRequested.equals("false")) {
                ICertPrettyPrint pp = CMS.getCertPrettyPrint(cert);

                ppStr = pp.toString(locale);
            }
            repeat.set(CERT_PRETTYPRINT, ppStr);

            // Now formulate a PKCS#7 blob
            X509CertImpl[] certsInChain = new X509CertImpl[1];; 
            if (cacerts != null) {
                for (int j = 0; j < cacerts.length; j++) {
                    if (cert.equals(cacerts[j])) {
                        certsInChain = new
                                X509CertImpl[cacerts.length];
                        break;
                    }
                    certsInChain = new X509CertImpl[cacerts.length + 1];
                }
            }
			
            // Set the EE cert
            certsInChain[0] = cert;
			
            // Set the Ca certificate chain
            if (cacerts != null) {
                for (int j = 0; j < cacerts.length; j++) {
                    if (!cert.equals(cacerts[j]))
                        certsInChain[j + 1] = (X509CertImpl) cacerts[j];
                }
            }
            // Wrap the chain into a degenerate P7 object
            String p7Str;

            try {
                PKCS7 p7 = new PKCS7(new AlgorithmId[0], 
                        new ContentInfo(new byte[0]),
                        certsInChain,
                        new SignerInfo[0]);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                p7.encodeSignedData(bos);
                byte[] p7Bytes = bos.toByteArray();

                //p7Str = encoder.encodeBuffer(p7Bytes);
                p7Str = CMS.BtoA(p7Bytes);
                repeat.addStringValue("pkcs7ChainBase64", p7Str);
            } catch (Exception ex) {
                //p7Str = "PKCS#7 B64 Encoding error - " + ex.toString() 
                //+ "; Please contact your administrator";
                throw new ECMSGWException(
                  CMS.getUserMessage("CMS_GW_FORMING_PKCS7_ERROR"));
            }

            // set cert fingerprint (for Cisco routers)
            String fingerprint = null;

            try {
                fingerprint = CMS.getFingerPrints(cert);
            } catch (CertificateEncodingException ex) {
                // should never happen
                throw new EBaseException(
                        CMS.getUserMessage(locale, "CMS_BASE_INTERNAL_ERROR", ex.toString()));
            } catch (NoSuchAlgorithmException ex) {
                // should never happen
                throw new EBaseException(
                        CMS.getUserMessage(locale, "CMS_BASE_INTERNAL_ERROR", ex.toString()));
            }
            if (fingerprint != null && fingerprint.length() > 0) 
                repeat.set(CERT_FINGERPRINT, fingerprint);

                // cmmf response for this cert.
            if (CMSServlet.doCMMFResponse(httpParams) && crmfReqId != null &&
                (certType == null || certType.equals("client"))) {
                PKIStatusInfo status = new PKIStatusInfo(PKIStatusInfo.granted);
                CertifiedKeyPair certifiedKP = 
                    new CertifiedKeyPair(new CertOrEncCert(certEncoded));
                CertResponse resp = 
                    new CertResponse(new INTEGER(crmfReqId), status, 
                        certifiedKP);

                certRepContent.addCertResponse(resp);
            }

            params.addRepeatRecord(repeat);
        }

        // if cartman set whole cmmf response (CertRepContent) string.
        if (CMSServlet.doCMMFResponse(httpParams)) {
            ByteArrayOutputStream certRepOut = new ByteArrayOutputStream();

            certRepContent.encode(certRepOut);
            byte[] certRepBytes = certRepOut.toByteArray();
            String certRepB64 = com.netscape.osutil.OSUtil.BtoA(certRepBytes);
            // add CR to each return as required by cartman
            BufferedReader certRepB64lines = 
                new BufferedReader(new StringReader(certRepB64));
            StringWriter certRepStringOut = new StringWriter();
            String oneLine = null;
            boolean first = true;

            while ((oneLine = certRepB64lines.readLine()) != null) {
                if (first) {
                    //certRepStringOut.write("\""+oneLine+"\"");
                    certRepStringOut.write(oneLine);
                    first = false;
                } else {
                    //certRepStringOut.write("+\"\\n"+oneLine+"\"");
                    certRepStringOut.write("\n" + oneLine);
                }
            }
            String certRepString = certRepStringOut.toString();

            fixed.set(CMMF_RESP, certRepString);
        }

        return params;
    }
}