]> WPIA git - gigi.git/blob - src/org/cacert/gigi/pages/account/certs/Certificates.java
Show certificate as PEM
[gigi.git] / src / org / cacert / gigi / pages / account / certs / Certificates.java
1 package org.cacert.gigi.pages.account.certs;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.math.BigInteger;
6 import java.net.URLEncoder;
7 import java.security.GeneralSecurityException;
8 import java.security.cert.CRLException;
9 import java.security.cert.CertificateEncodingException;
10 import java.security.cert.CertificateException;
11 import java.security.cert.X509CRL;
12 import java.security.cert.X509Certificate;
13 import java.util.HashMap;
14 import java.util.HashSet;
15 import java.util.LinkedList;
16 import java.util.Map;
17 import java.util.Set;
18
19 import javax.servlet.ServletOutputStream;
20 import javax.servlet.http.HttpServletRequest;
21 import javax.servlet.http.HttpServletResponse;
22
23 import org.cacert.gigi.dbObjects.CACertificate;
24 import org.cacert.gigi.dbObjects.Certificate;
25 import org.cacert.gigi.localisation.Language;
26 import org.cacert.gigi.output.template.Form;
27 import org.cacert.gigi.output.template.IterableDataset;
28 import org.cacert.gigi.output.template.Template;
29 import org.cacert.gigi.pages.HandlesMixedRequest;
30 import org.cacert.gigi.pages.LoginPage;
31 import org.cacert.gigi.pages.Page;
32 import org.cacert.gigi.util.PEM;
33
34 import sun.security.pkcs.ContentInfo;
35 import sun.security.pkcs.PKCS7;
36 import sun.security.pkcs.SignerInfo;
37 import sun.security.util.DerOutputStream;
38 import sun.security.util.DerValue;
39 import sun.security.x509.AlgorithmId;
40 import sun.security.x509.X509CRLImpl;
41 import sun.security.x509.X509CertImpl;
42
43 public class Certificates extends Page implements HandlesMixedRequest {
44
45     private Template certDisplay = new Template(Certificates.class.getResource("CertificateDisplay.templ"));
46
47     public static final String PATH = "/account/certs";
48
49     static class TrustchainIterable implements IterableDataset {
50
51         CACertificate cert;
52
53         public TrustchainIterable(CACertificate cert) {
54             this.cert = cert;
55         }
56
57         @Override
58         public boolean next(Language l, Map<String, Object> vars) {
59             if (cert == null) {
60                 return false;
61             }
62             vars.put("name", cert.getKeyname());
63             vars.put("link", cert.getLink());
64             if (cert.isSelfsigned()) {
65                 cert = null;
66                 return true;
67             }
68             cert = cert.getParent();
69             return true;
70         }
71
72     }
73
74     public Certificates() {
75         super("Certificates");
76     }
77
78     @Override
79     public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
80
81         String pi = req.getPathInfo().substring(PATH.length());
82         if (pi.length() == 0) {
83             return false;
84         }
85         pi = pi.substring(1);
86         boolean crt = false;
87         boolean cer = false;
88         resp.setContentType("application/pkix-cert");
89         if (req.getParameter("install") != null) {
90             resp.setContentType("application/x-x509-user-cert");
91         }
92         if (pi.endsWith(".crt")) {
93             crt = true;
94             pi = pi.substring(0, pi.length() - 4);
95         } else if (pi.endsWith(".cer")) {
96             cer = true;
97             pi = pi.substring(0, pi.length() - 4);
98         } else if (pi.endsWith(".cer")) {
99             cer = true;
100             pi = pi.substring(0, pi.length() - 4);
101         }
102         String serial = pi;
103         try {
104             Certificate c = Certificate.getBySerial(serial);
105             if (c == null || LoginPage.getAuthorizationContext(req).getTarget().getId() != c.getOwner().getId()) {
106                 resp.sendError(404);
107                 return true;
108             }
109             X509Certificate cert = c.cert();
110             if ( !crt && !cer) {
111                 return false;
112             }
113             ServletOutputStream out = resp.getOutputStream();
114             if (crt) {
115                 out.println(PEM.encode("CERTIFICATE", cert.getEncoded()));
116                 if (req.getParameter("chain") != null) {
117                     CACertificate ca = c.getParent();
118                     while ( !ca.isSelfsigned()) {
119                         out.println(PEM.encode("CERTIFICATE", ca.getCertificate().getEncoded()));
120                         ca = ca.getParent();
121                     }
122                     if (req.getParameter("noAnchor") == null) {
123                         out.println(PEM.encode("CERTIFICATE", ca.getCertificate().getEncoded()));
124                     }
125                 }
126             } else if (cer) {
127                 if (req.getParameter("chain") != null) {
128                     PKCS7 p7 = toP7Chain(c);
129                     p7.encodeSignedData(out);
130                     /*
131                      * ContentInfo ci = toCIChain(c); try (DerOutputStream dos =
132                      * new DerOutputStream()) { ci.encode(dos);
133                      * out.write(dos.toByteArray()); }
134                      */
135                 } else {
136                     out.write(cert.getEncoded());
137                 }
138             }
139         } catch (IllegalArgumentException e) {
140             resp.sendError(404);
141             return true;
142         } catch (GeneralSecurityException e) {
143             resp.sendError(404);
144             return true;
145         }
146
147         return true;
148     }
149
150     private static PKCS7 toP7Chain(Certificate c) throws IOException, GeneralSecurityException {
151         LinkedList<X509Certificate> ll = getChain(c);
152         PKCS7 p7 = new PKCS7(new AlgorithmId[0], new ContentInfo(ContentInfo.DATA_OID, null), ll.toArray(new X509Certificate[ll.size()]), new SignerInfo[0]) {
153
154             @Override
155             public void encodeSignedData(DerOutputStream out) throws IOException {
156                 DerOutputStream signedData = new DerOutputStream();
157                 BigInteger version = getVersion();
158                 AlgorithmId[] digestAlgorithmIds = getDigestAlgorithmIds();
159                 ContentInfo contentInfo = getContentInfo();
160                 X509Certificate[] certificates = getCertificates();
161                 X509CRL[] crls = getCRLs();
162                 SignerInfo[] signerInfos = getSignerInfos();
163
164                 // version
165                 signedData.putInteger(version);
166
167                 // digestAlgorithmIds
168                 signedData.putOrderedSetOf(DerValue.tag_Set, digestAlgorithmIds);
169
170                 // contentInfo
171                 contentInfo.encode(signedData);
172
173                 // certificates (optional)
174                 if (certificates != null && certificates.length != 0) {
175                     DerOutputStream sub = new DerOutputStream();
176                     // cast to X509CertImpl[] since X509CertImpl implements
177                     // DerEncoder
178                     X509CertImpl implCerts[] = new X509CertImpl[certificates.length];
179                     for (int i = 0; i < certificates.length; i++) {
180                         try {
181                             sub.write(certificates[i].getEncoded());
182                         } catch (CertificateEncodingException e) {
183                             sub.close();
184                             throw new IOException(e);
185                         }
186                         if (certificates[i] instanceof X509CertImpl) {
187                             implCerts[i] = (X509CertImpl) certificates[i];
188                         } else {
189                             try {
190                                 byte[] encoded = certificates[i].getEncoded();
191                                 implCerts[i] = new X509CertImpl(encoded);
192                             } catch (CertificateException ce) {
193                                 sub.close();
194                                 throw new IOException(ce);
195                             }
196                         }
197                     }
198
199                     // Add the certificate set (tagged with [0] IMPLICIT)
200                     // to the signed data
201                     signedData.write((byte) 0xA0, sub);
202                     sub.close();
203                 }
204
205                 // CRLs (optional)
206                 if (crls != null && crls.length != 0) {
207                     // cast to X509CRLImpl[] since X509CRLImpl implements
208                     // DerEncoder
209                     Set<X509CRLImpl> implCRLs = new HashSet<X509CRLImpl>(crls.length);
210                     for (X509CRL crl : crls) {
211                         if (crl instanceof X509CRLImpl) {
212                             implCRLs.add((X509CRLImpl) crl);
213                         } else {
214                             try {
215                                 byte[] encoded = crl.getEncoded();
216                                 implCRLs.add(new X509CRLImpl(encoded));
217                             } catch (CRLException ce) {
218                                 throw new IOException(ce);
219                             }
220                         }
221                     }
222
223                     // Add the CRL set (tagged with [1] IMPLICIT)
224                     // to the signed data
225                     signedData.putOrderedSetOf((byte) 0xA1, implCRLs.toArray(new X509CRLImpl[implCRLs.size()]));
226                 }
227
228                 // signerInfos
229                 signedData.putOrderedSetOf(DerValue.tag_Set, signerInfos);
230
231                 // making it a signed data block
232                 DerValue signedDataSeq = new DerValue(DerValue.tag_Sequence, signedData.toByteArray());
233
234                 // making it a content info sequence
235                 ContentInfo block = new ContentInfo(ContentInfo.SIGNED_DATA_OID, signedDataSeq);
236
237                 // writing out the contentInfo sequence
238                 block.encode(out);
239             }
240
241         };
242         return p7;
243     }
244
245     private static LinkedList<X509Certificate> getChain(Certificate c) throws IOException, GeneralSecurityException {
246         LinkedList<X509Certificate> ll = new LinkedList<>();
247         ll.add(c.cert());
248         CACertificate ca = c.getParent();
249         while ( !ca.isSelfsigned()) {
250             ll.add(ca.getCertificate());
251             ca = ca.getParent();
252         }
253         ll.add(ca.getCertificate());
254         return ll;
255     }
256
257     @Override
258     public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
259         if (req.getQueryString() != null && !req.getQueryString().equals("") && !req.getQueryString().equals("withRevoked")) {
260             return;// Block actions by get parameters.
261         }
262         if ( !req.getPathInfo().equals(PATH)) {
263             resp.sendError(500);
264             return;
265         }
266         Form.getForm(req, CertificateModificationForm.class).submit(resp.getWriter(), req);
267         doGet(req, resp);
268     }
269
270     @Override
271     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
272         PrintWriter out = resp.getWriter();
273         String pi = req.getPathInfo().substring(PATH.length());
274         if (pi.length() != 0) {
275             pi = pi.substring(1);
276
277             String serial = pi;
278             Certificate c = Certificate.getBySerial(serial);
279             if (c == null || LoginPage.getAuthorizationContext(req).getTarget().getId() != c.getOwner().getId()) {
280                 resp.sendError(404);
281                 return;
282             }
283             HashMap<String, Object> vars = new HashMap<>();
284             vars.put("serial", URLEncoder.encode(serial, "UTF-8"));
285             vars.put("trustchain", new TrustchainIterable(c.getParent()));
286             try {
287                 vars.put("cert", PEM.encode("CERTIFICATE", c.cert().getEncoded()));
288             } catch (GeneralSecurityException e) {
289                 e.printStackTrace();
290             }
291             certDisplay.output(out, getLanguage(req), vars);
292
293             return;
294         }
295
296         HashMap<String, Object> vars = new HashMap<String, Object>();
297         new CertificateModificationForm(req, req.getParameter("withRevoked") != null).output(out, getLanguage(req), vars);
298     }
299
300 }