summaryrefslogtreecommitdiffstats
path: root/base/common/src/com/netscape/cms/servlet/cert/model/CertDAO.java
blob: e71055580377899e611a46b5dcae393f0b225f38 (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
// --- 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) 2011 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert.model;

import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.security.Principal;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.ws.rs.Path;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;

import netscape.security.pkcs.ContentInfo;
import netscape.security.pkcs.PKCS7;
import netscape.security.pkcs.SignerInfo;
import netscape.security.x509.AlgorithmId;
import netscape.security.x509.X509CertImpl;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.ca.ICertificateAuthority;
import com.netscape.certsrv.dbs.certdb.CertId;
import com.netscape.certsrv.dbs.certdb.ICertRecord;
import com.netscape.certsrv.dbs.certdb.ICertificateRepository;
import com.netscape.cms.servlet.cert.CertResource;
import com.netscape.cms.servlet.request.model.CertRetrievalRequestData;
import com.netscape.cmsutil.util.Utils;

/**
 * @author alee
 *
 */
public class CertDAO {

    private ICertificateRepository repo;
    private ICertificateAuthority ca;

    public CertDAO() {
        ca = (ICertificateAuthority) CMS.getSubsystem("ca");
        repo = ca.getCertificateRepository();
    }

    /**
     * Returns list of certs meeting specified search filter.
     * Currently, vlv searches are not used for certs.
     *
     * @param filter
     * @param maxResults
     * @param maxTime
     * @param uriInfo
     * @return
     * @throws EBaseException
     */
    public CertDataInfos listCerts(String filter, int maxResults, int maxTime, UriInfo uriInfo)
            throws EBaseException {
        List<CertDataInfo> list = new ArrayList<CertDataInfo>();
        Enumeration<ICertRecord> e = null;

        e = repo.searchCertificates(filter, maxResults, maxTime);
        if (e == null) {
            throw new EBaseException("search results are null");
        }

        while (e.hasMoreElements()) {
            ICertRecord rec = e.nextElement();
            if (rec != null) {
                list.add(createCertDataInfo(rec, uriInfo));
            }
        }

        CertDataInfos ret = new CertDataInfos();
        ret.setCertInfos(list);

        return ret;
    }

    public CertificateData getCert(CertRetrievalRequestData data) throws EBaseException, CertificateEncodingException {

        CertificateData certData = null;
        CertId certId = data.getCertId();

        //find the cert in question

        ICertRecord rec = null;
        BigInteger seq = certId.toBigInteger();

        rec = repo.readCertificateRecord(seq);
        X509CertImpl x509cert = null;

        if (rec != null) {
            x509cert = rec.getCertificate();
        }

        if (x509cert != null) {
            certData = new CertificateData();

            byte[] ba = null;
            String encoded64 = null;

            ba = x509cert.getEncoded();

            encoded64 = Utils.base64encode(ba);

            String prettyPrint = x509cert.toString();

            certData.setB64(encoded64);
            certData.setPrettyPrint(prettyPrint);

            String subjectNameStr = null;
            Principal subjectName = x509cert.getSubjectDN();

            if (subjectName != null) {
                subjectNameStr = subjectName.toString();
            }

            certData.setSubjectName(subjectNameStr);

            //Try to get the chain

            String p7Str = getCertChainData(x509cert);

            certData.setPkcs7CertChain(p7Str);

            certData.setSerialNo(certId);

            Date notBefore = x509cert.getNotBefore();
            Date notAfter = x509cert.getNotAfter();

            String notBeforeStr = null;
            String notAfterStr = null;

            if (notBefore != null) {
                notBeforeStr = notBefore.toString();
            }

            if (notAfter != null) {
                notAfterStr = notAfter.toString();
            }

            certData.setNotBefore(notBeforeStr);
            certData.setNotAfter(notAfterStr);

            String issuerNameStr = null;

            Principal issuerName = x509cert.getIssuerDN();

            if (issuerName != null) {
                issuerNameStr = issuerName.toString();
            }

            certData.setIssuerName(issuerNameStr);

        }

        return certData;
    }

    private CertDataInfo createCertDataInfo(ICertRecord rec, UriInfo uriInfo) throws EBaseException {
        CertDataInfo ret = new CertDataInfo();

        Path certPath = CertResource.class.getAnnotation(Path.class);
        BigInteger serial = rec.getSerialNumber();

        UriBuilder certBuilder = uriInfo.getBaseUriBuilder();
        certBuilder.path(certPath.value() + "/" + serial);
        ret.setCertURL(certBuilder.build().toString());

        return ret;
    }

    private String getCertChainData(X509CertImpl x509cert) {

        X509Certificate mCACerts[];

        if (x509cert == null) {
            return null;
        }

        try {
            mCACerts = ca.getCACertChain().getChain();
        } catch (Exception e) {
            mCACerts = null;
        }

        X509CertImpl[] certsInChain = new X509CertImpl[1];
        ;

        int mCACertsLength = 0;
        boolean certAlreadyInChain = false;
        int certsInChainLength = 0;
        if (mCACerts != null) {
            mCACertsLength = mCACerts.length;
            for (int i = 0; i < mCACertsLength; i++) {
                if (x509cert.equals(mCACerts[i])) {
                    certAlreadyInChain = true;
                    break;
                }
            }

            if (certAlreadyInChain == true) {
                certsInChainLength = mCACertsLength;
            } else {
                certsInChainLength = mCACertsLength + 1;
            }

            certsInChain = new X509CertImpl[certsInChainLength];

        }

        certsInChain[0] = x509cert;

        if (mCACerts != null) {
            int curCount = 1;
            for (int i = 0; i < mCACertsLength; i++) {
                if (!x509cert.equals(mCACerts[i])) {
                    certsInChain[curCount] = (X509CertImpl) mCACerts[i];
                    curCount++;
                }

            }
        }

        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, false);
            byte[] p7Bytes = bos.toByteArray();

            p7Str = Utils.base64encode(p7Bytes);
        } catch (Exception e) {
            p7Str = null;
        }

        return p7Str;
    }
}