]> WPIA git - gigi.git/commitdiff
UPD: extract certificate requests out of form (preparing for API)
authorFelix Dörre <felix@dogcraft.de>
Thu, 12 Feb 2015 01:05:58 +0000 (02:05 +0100)
committerFelix Dörre <felix@dogcraft.de>
Thu, 12 Feb 2015 02:21:50 +0000 (03:21 +0100)
src/org/cacert/gigi/pages/account/certs/CertificateIssueForm.java
src/org/cacert/gigi/pages/account/certs/CertificateRequest.java [new file with mode: 0644]
tests/org/cacert/gigi/pages/account/TestCertificateAdd.java
tests/org/cacert/gigi/pages/account/TestCertificateRequest.java [new file with mode: 0644]

index 428e39a6439f54480486cdbbc78dc8b5b4811e53..6f099195ee1b780c1771ca02a4a283325350daee 100644 (file)
@@ -3,29 +3,17 @@ package org.cacert.gigi.pages.account.certs;
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.security.GeneralSecurityException;
-import java.security.PublicKey;
-import java.security.interfaces.DSAPublicKey;
-import java.security.interfaces.ECPublicKey;
-import java.security.interfaces.RSAPublicKey;
-import java.util.Base64;
 import java.util.HashMap;
 import java.util.Iterator;
-import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
 
 import javax.servlet.http.HttpServletRequest;
 
 import org.cacert.gigi.GigiApiException;
-import org.cacert.gigi.crypto.SPKAC;
 import org.cacert.gigi.dbObjects.Certificate;
-import org.cacert.gigi.dbObjects.Certificate.CSRType;
-import org.cacert.gigi.dbObjects.Certificate.SANType;
 import org.cacert.gigi.dbObjects.Certificate.SubjectAlternateName;
 import org.cacert.gigi.dbObjects.CertificateProfile;
-import org.cacert.gigi.dbObjects.Digest;
 import org.cacert.gigi.dbObjects.Organisation;
 import org.cacert.gigi.dbObjects.User;
 import org.cacert.gigi.localisation.Language;
@@ -34,93 +22,25 @@ import org.cacert.gigi.output.HashAlgorithms;
 import org.cacert.gigi.output.template.Form;
 import org.cacert.gigi.output.template.IterableDataset;
 import org.cacert.gigi.output.template.Template;
-import org.cacert.gigi.pages.LoginPage;
 import org.cacert.gigi.pages.Page;
-import org.cacert.gigi.util.PEM;
 import org.cacert.gigi.util.RandomToken;
 
-import sun.security.pkcs.PKCS9Attribute;
-import sun.security.pkcs10.PKCS10;
-import sun.security.pkcs10.PKCS10Attribute;
-import sun.security.pkcs10.PKCS10Attributes;
-import sun.security.util.DerInputStream;
-import sun.security.util.DerValue;
-import sun.security.util.ObjectIdentifier;
-import sun.security.x509.AVA;
-import sun.security.x509.AlgorithmId;
-import sun.security.x509.CertificateExtensions;
-import sun.security.x509.DNSName;
-import sun.security.x509.ExtendedKeyUsageExtension;
-import sun.security.x509.Extension;
-import sun.security.x509.GeneralName;
-import sun.security.x509.GeneralNameInterface;
-import sun.security.x509.GeneralNames;
-import sun.security.x509.PKIXExtensions;
-import sun.security.x509.RDN;
-import sun.security.x509.RFC822Name;
-import sun.security.x509.SubjectAlternativeNameExtension;
-import sun.security.x509.X500Name;
-
 /**
  * This class represents a form that is used for issuing certificates. This
  * class uses "sun.security" and therefore needs "-XDignore.symbol.file"
  */
 public class CertificateIssueForm extends Form {
 
-    public static final String DEFAULT_CN = "CAcert WoT User";
-
     private final static Template t = new Template(CertificateIssueForm.class.getResource("CertificateIssueForm.templ"));
 
     private final static Template tIni = new Template(CertificateAdd.class.getResource("RequestCertificate.templ"));
 
-    public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
-            1, 3, 6, 1, 5, 5, 7, 3, 1
-    });
-
-    public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
-            1, 3, 6, 1, 5, 5, 7, 3, 2
-    });
-
-    public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
-            1, 3, 6, 1, 5, 5, 7, 3, 3
-    });
-
-    public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
-            1, 3, 6, 1, 5, 5, 7, 3, 4
-    });
-
-    public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
-            1, 3, 6, 1, 5, 5, 7, 3, 8
-    });
-
-    public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
-            1, 3, 6, 1, 5, 5, 7, 3, 9
-    });
-
     private User u;
 
-    private CSRType csrType;
-
-    private String csr;
-
     private String spkacChallenge;
 
-    public String CN = DEFAULT_CN;
-
-    private Set<SubjectAlternateName> SANs = new LinkedHashSet<>();
-
-    private Digest selectedDigest = Digest.getDefault();
-
-    CertificateValiditySelector issueDate = new CertificateValiditySelector();
-
     private boolean login;
 
-    private CertificateProfile profile = CertificateProfile.getById(1);
-
-    private String ou = "";
-
-    private Organisation org = null;
-
     public CertificateIssueForm(HttpServletRequest hsr) {
         super(hsr);
         u = Page.getUser(hsr);
@@ -133,6 +53,10 @@ public class CertificateIssueForm extends Form {
         return result;
     }
 
+    private CertificateRequest cr;
+
+    CertificateValiditySelector issueDate = new CertificateValiditySelector();
+
     @Override
     public boolean submit(PrintWriter out, HttpServletRequest req) {
         String csr = req.getParameter("CSR");
@@ -140,193 +64,38 @@ public class CertificateIssueForm extends Form {
         try {
             try {
                 if (csr != null) {
-                    byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
-                    PKCS10 parsed = new PKCS10(data);
-                    PKCS10Attributes atts = parsed.getAttributes();
-
-                    for (PKCS10Attribute b : atts.getAttributes()) {
-
-                        if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
-                            // unknown attrib
-                            continue;
-                        }
-
-                        for (RDN r : parsed.getSubjectName().rdns()) {
-                            for (AVA a : r.avas()) {
-                                if (a.getObjectIdentifier().equals((Object) PKCS9Attribute.EMAIL_ADDRESS_OID)) {
-                                    SANs.add(new SubjectAlternateName(SANType.EMAIL, a.getValueString()));
-                                } else if (a.getObjectIdentifier().equals((Object) X500Name.commonName_oid)) {
-                                    String value = a.getValueString();
-                                    if (value.contains(".") && !value.contains(" ")) {
-                                        SANs.add(new SubjectAlternateName(SANType.DNS, value));
-                                    } else {
-                                        CN = value;
-                                    }
-                                } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
-                                    // parse invalid SANs
-                                }
-                            }
-                        }
-
-                        for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
-                            if (c instanceof SubjectAlternativeNameExtension) {
-
-                                SubjectAlternativeNameExtension san = (SubjectAlternativeNameExtension) c;
-                                GeneralNames obj = san.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
-                                for (int i = 0; i < obj.size(); i++) {
-                                    GeneralName generalName = obj.get(i);
-                                    GeneralNameInterface peeled = generalName.getName();
-                                    if (peeled instanceof DNSName) {
-                                        SANs.add(new SubjectAlternateName(SANType.DNS, ((DNSName) peeled).getName()));
-                                    } else if (peeled instanceof RFC822Name) {
-                                        SANs.add(new SubjectAlternateName(SANType.EMAIL, ((RFC822Name) peeled).getName()));
-                                    }
-                                }
-                            } else if (c instanceof ExtendedKeyUsageExtension) {
-                                ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
-                                for (String s : ekue.getExtendedKeyUsage()) {
-                                    if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
-                                        // server
-                                        profile = CertificateProfile.getByName("server");
-                                    } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
-                                        // client
-                                        profile = CertificateProfile.getByName("client");
-                                    } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
-                                        // code sign
-                                    } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
-                                        // emailProtection
-                                        profile = CertificateProfile.getByName("mail");
-                                    } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
-                                        // timestamp
-                                    } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
-                                        // OCSP
-                                    }
-                                }
-                            } else {
-                                // Unknown requested extension
-                            }
-                        }
-
-                    }
-                    out.println(parsed.getSubjectName().getCommonName());
-                    out.println(parsed.getSubjectName().getCountry());
-
-                    out.println("CSR DN: " + parsed.getSubjectName() + "<br/>");
-                    PublicKey pk = parsed.getSubjectPublicKeyInfo();
-                    checkKeyStrength(pk, out);
-                    String sign = getSignatureAlgorithm(data);
-                    guessDigest(sign);
-
-                    out.println("<br/>digest: " + sign + "<br/>");
-
-                    this.csr = csr;
-                    this.csrType = CSRType.CSR;
+                    cr = new CertificateRequest(u, csr);
+                    cr.checkKeyStrength(out);
                 } else if (spkac != null) {
-                    String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
-                    byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
-                    SPKAC parsed = new SPKAC(data);
-                    if ( !parsed.getChallenge().equals(spkacChallenge)) {
-                        throw new GigiApiException("Challenge mismatch");
-                    }
-                    checkKeyStrength(parsed.getPubkey(), out);
-                    String sign = getSignatureAlgorithm(data);
-                    guessDigest(sign);
-                    out.println("<br/>digest: " + sign + "<br/>");
-
-                    // spkacChallenge
-                    this.csr = "SPKAC=" + cleanedSPKAC;
-                    this.csrType = CSRType.SPKAC;
-
-                } else {
+                    cr = new CertificateRequest(u, spkac, spkacChallenge);
+                    cr.checkKeyStrength(out);
+                } else if (cr != null) {
                     login = "1".equals(req.getParameter("login"));
                     issueDate.update(req);
-                    CN = req.getParameter("CN");
-                    String hashAlg = req.getParameter("hash_alg");
-                    if (hashAlg != null) {
-                        selectedDigest = Digest.valueOf(hashAlg);
-                    }
-                    profile = CertificateProfile.getByName(req.getParameter("profile"));
-                    String newOrgStr = req.getParameter("org");
-                    if (newOrgStr != null) {
-                        Organisation neworg = Organisation.getById(Integer.parseInt(newOrgStr));
-                        if (neworg == null || u.getOrganisations().contains(neworg)) {
-                            org = neworg;
-                        } else {
-                            outputError(out, req, "Selected Organisation is not part of your account.");
-                        }
-                    }
-                    ou = req.getParameter("OU");
-                    if ( !u.canIssue(profile)) {
-                        profile = CertificateProfile.getById(1);
-                        outputError(out, req, "Certificate Profile is invalid.");
-                        return false;
-                    }
-
-                    String pDNS = null;
-                    String pMail = null;
-                    Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
-                    boolean server = profile.getKeyName().equals("server");
-                    for (SubjectAlternateName san : parseSANBox(req.getParameter("SANs"))) {
-                        if (san.getType() == SANType.DNS) {
-                            if (u.isValidDomain(san.getName()) && server) {
-                                if (pDNS == null) {
-                                    pDNS = san.getName();
-                                }
-                                filteredSANs.add(san);
-                                continue;
-                            }
-                        } else if (san.getType() == SANType.EMAIL) {
-                            if (u.isValidEmail(san.getName()) && !server) {
-                                if (pMail == null) {
-                                    pMail = san.getName();
-                                }
-                                filteredSANs.add(san);
-                                continue;
-                            }
-                        }
-                        outputError(out, req, "The requested Subject alternate name \"%s\" has been removed.",//
-                                san.getType().toString().toLowerCase() + ":" + san.getName());
-                    }
-                    SANs = filteredSANs;
-                    if ( !u.isValidName(CN) && !server && !CN.equals(DEFAULT_CN)) {
-                        CN = DEFAULT_CN;
-                        outputError(out, req, "The name entered, does not match the details in your account. You cannot issue certificates with this name. Enter a name that matches the one that has been assured in your account.");
-                    }
+                    GigiApiException error = new GigiApiException();
 
-                    HashMap<String, String> subject = new HashMap<>();
-                    if (server && pDNS != null) {
-                        subject.put("CN", pDNS);
-                        if (pMail != null) {
-                            outputError(out, req, "No email is included in this certificate.");
-                        }
-                        if (CN.equals("")) {
-                            CN = "";
-                            outputError(out, req, "No real name is included in this certificate. The real name, you entered will be ignored.");
-                        }
-                    } else {
-                        subject.put("CN", CN);
-                        if (pMail != null) {
-                            subject.put("EMAIL", pMail);
-                        }
-                    }
-                    if (org != null) {
-                        subject.put("O", org.getName());
-                        subject.put("C", org.getState());
-                        subject.put("ST", org.getProvince());
-                        subject.put("L", org.getCity());
-                        subject.put("OU", ou);
+                    try {
+                        cr.update(req.getParameter("CN"), req.getParameter("hash_alg"), req.getParameter("profile"), //
+                                req.getParameter("org"), req.getParameter("OU"), req.getParameter("SANs"), out, req);
+                    } catch (GigiApiException e) {
+                        error.mergeInto(e);
                     }
                     if (req.getParameter("CCA") == null) {
-                        outputError(out, req, "You need to accept the CCA.");
+                        error.mergeInto(new GigiApiException("You need to accept the CCA."));
                     }
-                    if (isFailed(out)) {
+                    try {
+                        result = cr.draft();
+                    } catch (GigiApiException e) {
+                        error.mergeInto(e);
+                    }
+                    if ( !error.isEmpty()) {
+                        error.format(out, Page.getLanguage(req));
                         return false;
                     }
-
-                    result = new Certificate(LoginPage.getUser(req), subject, selectedDigest.toString(), //
-                            this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
                     result.issue(issueDate.getFrom(), issueDate.getTo()).waitFor(60000);
                     return true;
+                } else {
+                    throw new GigiApiException("Error no action.");
                 }
             } catch (IOException e) {
                 e.printStackTrace();
@@ -345,70 +114,9 @@ public class CertificateIssueForm extends Form {
         return false;
     }
 
-    private void guessDigest(String sign) {
-        if (sign.toLowerCase().startsWith("sha512")) {
-            selectedDigest = Digest.SHA512;
-        } else if (sign.toLowerCase().startsWith("sha384")) {
-            selectedDigest = Digest.SHA384;
-        }
-    }
-
-    private TreeSet<SubjectAlternateName> parseSANBox(String SANs) {
-        String[] SANparts = SANs.split("[\r\n]+|, *");
-        TreeSet<SubjectAlternateName> parsedNames = new TreeSet<>();
-        for (String SANline : SANparts) {
-            String[] parts = SANline.split(":", 2);
-            if (parts.length == 1) {
-                if (parts[0].trim().equals("")) {
-                    continue;
-                }
-                if (parts[0].contains("@")) {
-                    parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
-                } else {
-                    parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
-                }
-                continue;
-            }
-            try {
-                SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase());
-                if (t == null) {
-                    continue;
-                }
-                parsedNames.add(new SubjectAlternateName(t, parts[1]));
-            } catch (IllegalArgumentException e) {
-                // invalid enum type
-                continue;
-            }
-        }
-        return parsedNames;
-    }
-
-    private void checkKeyStrength(PublicKey pk, PrintWriter out) {
-        out.println("Type: " + pk.getAlgorithm() + "<br/>");
-        if (pk instanceof RSAPublicKey) {
-            out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
-            out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
-        } else if (pk instanceof DSAPublicKey) {
-            DSAPublicKey dpk = (DSAPublicKey) pk;
-            out.println("Length: " + dpk.getY().bitLength() + "<br/>");
-            out.println(dpk.getParams());
-        } else if (pk instanceof ECPublicKey) {
-            ECPublicKey epk = (ECPublicKey) pk;
-            out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
-            out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
-            out.println(epk.getParams().getCurve());
-        }
-    }
-
-    private static String getSignatureAlgorithm(byte[] data) throws IOException {
-        DerInputStream in = new DerInputStream(data);
-        DerValue[] seq = in.getSequence(3);
-        return AlgorithmId.parse(seq[1]).getName();
-    }
-
     @Override
     public void output(PrintWriter out, Language l, Map<String, Object> vars) {
-        if (csr == null) {
+        if (cr == null) {
             HashMap<String, Object> vars2 = new HashMap<String, Object>(vars);
             vars2.put("csrf", getCSRFToken());
             vars2.put("csrf_name", getCsrfFieldName());
@@ -426,18 +134,18 @@ public class CertificateIssueForm extends Form {
         vars2.put("CCA", "<a href='/policy/CAcertCommunityAgreement.html'>CCA</a>");
 
         StringBuffer content = new StringBuffer();
-        for (SubjectAlternateName SAN : SANs) {
+        for (SubjectAlternateName SAN : cr.getSANs()) {
             content.append(SAN.getType().toString().toLowerCase());
             content.append(':');
             content.append(SAN.getName());
             content.append('\n');
         }
 
-        vars2.put("CN", CN);
-        vars2.put("department", ou);
+        vars2.put("CN", cr.getCN());
+        vars2.put("department", cr.getOu());
         vars2.put("validity", issueDate);
         vars2.put("emails", content.toString());
-        vars2.put("hashs", new HashAlgorithms(selectedDigest));
+        vars2.put("hashs", new HashAlgorithms(cr.getSelectedDigest()));
         vars2.put("profiles", new IterableDataset() {
 
             int i = 1;
@@ -452,7 +160,7 @@ public class CertificateIssueForm extends Form {
                     }
                 } while ( !u.canIssue(cp));
 
-                if (cp.getId() == profile.getId()) {
+                if (cp.getId() == cr.getProfile().getId()) {
                     vars.put("selected", " selected");
                 } else {
                     vars.put("selected", "");
@@ -475,7 +183,7 @@ public class CertificateIssueForm extends Form {
                 Organisation orga = iter.next();
                 vars.put("key", orga.getId());
                 vars.put("name", orga.getName());
-                if (orga == org) {
+                if (orga == cr.getOrg()) {
                     vars.put("selected", " selected");
                 } else {
                     vars.put("selected", "");
diff --git a/src/org/cacert/gigi/pages/account/certs/CertificateRequest.java b/src/org/cacert/gigi/pages/account/certs/CertificateRequest.java
new file mode 100644 (file)
index 0000000..fe46244
--- /dev/null
@@ -0,0 +1,391 @@
+package org.cacert.gigi.pages.account.certs;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.security.GeneralSecurityException;
+import java.security.PublicKey;
+import java.security.interfaces.DSAPublicKey;
+import java.security.interfaces.ECPublicKey;
+import java.security.interfaces.RSAPublicKey;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.Set;
+import java.util.TreeSet;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.cacert.gigi.GigiApiException;
+import org.cacert.gigi.crypto.SPKAC;
+import org.cacert.gigi.dbObjects.Certificate;
+import org.cacert.gigi.dbObjects.Certificate.CSRType;
+import org.cacert.gigi.dbObjects.Certificate.SANType;
+import org.cacert.gigi.dbObjects.Certificate.SubjectAlternateName;
+import org.cacert.gigi.dbObjects.CertificateProfile;
+import org.cacert.gigi.dbObjects.Digest;
+import org.cacert.gigi.dbObjects.Organisation;
+import org.cacert.gigi.dbObjects.User;
+import org.cacert.gigi.output.template.Scope;
+import org.cacert.gigi.output.template.SprintfCommand;
+import org.cacert.gigi.util.PEM;
+
+import sun.security.pkcs.PKCS9Attribute;
+import sun.security.pkcs10.PKCS10;
+import sun.security.pkcs10.PKCS10Attribute;
+import sun.security.pkcs10.PKCS10Attributes;
+import sun.security.util.DerInputStream;
+import sun.security.util.DerValue;
+import sun.security.util.ObjectIdentifier;
+import sun.security.x509.AVA;
+import sun.security.x509.AlgorithmId;
+import sun.security.x509.CertificateExtensions;
+import sun.security.x509.DNSName;
+import sun.security.x509.ExtendedKeyUsageExtension;
+import sun.security.x509.Extension;
+import sun.security.x509.GeneralName;
+import sun.security.x509.GeneralNameInterface;
+import sun.security.x509.GeneralNames;
+import sun.security.x509.PKIXExtensions;
+import sun.security.x509.RDN;
+import sun.security.x509.RFC822Name;
+import sun.security.x509.SubjectAlternativeNameExtension;
+import sun.security.x509.X500Name;
+
+public class CertificateRequest {
+
+    public static final String DEFAULT_CN = "CAcert WoT User";
+
+    public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
+            1, 3, 6, 1, 5, 5, 7, 3, 1
+    });
+
+    public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
+            1, 3, 6, 1, 5, 5, 7, 3, 2
+    });
+
+    public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
+            1, 3, 6, 1, 5, 5, 7, 3, 3
+    });
+
+    public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
+            1, 3, 6, 1, 5, 5, 7, 3, 4
+    });
+
+    public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
+            1, 3, 6, 1, 5, 5, 7, 3, 8
+    });
+
+    public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
+            1, 3, 6, 1, 5, 5, 7, 3, 9
+    });
+
+    private CSRType csrType;
+
+    private final PublicKey pk;
+
+    private String csr;
+
+    public String CN = DEFAULT_CN;
+
+    private Set<SubjectAlternateName> SANs;
+
+    private Digest selectedDigest = Digest.getDefault();
+
+    private CertificateProfile profile = CertificateProfile.getById(1);
+
+    private String ou = "";
+
+    private Organisation org = null;
+
+    private User u;
+
+    private String pDNS, pMail;
+
+    public CertificateRequest(User issuer, String csr) throws IOException, GeneralSecurityException, GigiApiException {
+        u = issuer;
+        byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
+        PKCS10 parsed = new PKCS10(data);
+        PKCS10Attributes atts = parsed.getAttributes();
+
+        TreeSet<SubjectAlternateName> SANs = new TreeSet<>();
+        for (RDN r : parsed.getSubjectName().rdns()) {
+            for (AVA a : r.avas()) {
+                if (a.getObjectIdentifier().equals((Object) PKCS9Attribute.EMAIL_ADDRESS_OID)) {
+                    SANs.add(new SubjectAlternateName(SANType.EMAIL, a.getValueString()));
+                } else if (a.getObjectIdentifier().equals((Object) X500Name.commonName_oid)) {
+                    String value = a.getValueString();
+                    if (value.contains(".") && !value.contains(" ")) {
+                        SANs.add(new SubjectAlternateName(SANType.DNS, value));
+                    } else {
+                        CN = value;
+                    }
+                } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
+                    // TODO? parse invalid SANs
+                }
+            }
+        }
+
+        for (PKCS10Attribute b : atts.getAttributes()) {
+
+            if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
+                // unknown attrib
+                continue;
+            }
+
+            for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
+                if (c instanceof SubjectAlternativeNameExtension) {
+
+                    SubjectAlternativeNameExtension san = (SubjectAlternativeNameExtension) c;
+                    GeneralNames obj = san.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
+                    for (int i = 0; i < obj.size(); i++) {
+                        GeneralName generalName = obj.get(i);
+                        GeneralNameInterface peeled = generalName.getName();
+                        if (peeled instanceof DNSName) {
+                            SANs.add(new SubjectAlternateName(SANType.DNS, ((DNSName) peeled).getName()));
+                        } else if (peeled instanceof RFC822Name) {
+                            SANs.add(new SubjectAlternateName(SANType.EMAIL, ((RFC822Name) peeled).getName()));
+                        }
+                    }
+                } else if (c instanceof ExtendedKeyUsageExtension) {
+                    ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
+                    for (String s : ekue.getExtendedKeyUsage()) {
+                        if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
+                            // server
+                            profile = CertificateProfile.getByName("server");
+                        } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
+                            // client
+                            profile = CertificateProfile.getByName("client");
+                        } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
+                            // code sign
+                        } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
+                            // emailProtection
+                            profile = CertificateProfile.getByName("mail");
+                        } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
+                            // timestamp
+                        } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
+                            // OCSP
+                        }
+                    }
+                } else {
+                    // Unknown requested extension
+                }
+            }
+
+        }
+        GigiApiException error = new GigiApiException();
+        this.SANs = verifySANs(error, false, SANs);
+        if ( !error.isEmpty()) {
+            throw error;
+        }
+        pk = parsed.getSubjectPublicKeyInfo();
+        String sign = getSignatureAlgorithm(data);
+        guessDigest(sign);
+
+        this.csr = csr;
+        this.csrType = CSRType.CSR;
+    }
+
+    public CertificateRequest(User issuer, String spkac, String spkacChallenge) throws IOException, GigiApiException, GeneralSecurityException {
+        u = issuer;
+        String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
+        byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
+        SPKAC parsed = new SPKAC(data);
+        if ( !parsed.getChallenge().equals(spkacChallenge)) {
+            throw new GigiApiException("Challenge mismatch");
+        }
+        pk = parsed.getPubkey();
+        String sign = getSignatureAlgorithm(data);
+        guessDigest(sign);
+
+        this.csr = "SPKAC=" + cleanedSPKAC;
+        this.csrType = CSRType.SPKAC;
+
+    }
+
+    private static String getSignatureAlgorithm(byte[] data) throws IOException {
+        DerInputStream in = new DerInputStream(data);
+        DerValue[] seq = in.getSequence(3);
+        return AlgorithmId.parse(seq[1]).getName();
+    }
+
+    private void guessDigest(String sign) {
+        if (sign.toLowerCase().startsWith("sha512")) {
+            selectedDigest = Digest.SHA512;
+        } else if (sign.toLowerCase().startsWith("sha384")) {
+            selectedDigest = Digest.SHA384;
+        }
+    }
+
+    public void checkKeyStrength(PrintWriter out) {
+        out.println("Type: " + pk.getAlgorithm() + "<br/>");
+        if (pk instanceof RSAPublicKey) {
+            out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
+            out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
+        } else if (pk instanceof DSAPublicKey) {
+            DSAPublicKey dpk = (DSAPublicKey) pk;
+            out.println("Length: " + dpk.getY().bitLength() + "<br/>");
+            out.println(dpk.getParams());
+        } else if (pk instanceof ECPublicKey) {
+            ECPublicKey epk = (ECPublicKey) pk;
+            out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
+            out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
+            out.println(epk.getParams().getCurve());
+        }
+    }
+
+    private TreeSet<SubjectAlternateName> parseSANBox(String SANs) {
+        String[] SANparts = SANs.split("[\r\n]+|, *");
+        TreeSet<SubjectAlternateName> parsedNames = new TreeSet<>();
+        for (String SANline : SANparts) {
+            String[] parts = SANline.split(":", 2);
+            if (parts.length == 1) {
+                if (parts[0].trim().equals("")) {
+                    continue;
+                }
+                if (parts[0].contains("@")) {
+                    parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
+                } else {
+                    parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
+                }
+                continue;
+            }
+            try {
+                SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase());
+                if (t == null) {
+                    continue;
+                }
+                parsedNames.add(new SubjectAlternateName(t, parts[1]));
+            } catch (IllegalArgumentException e) {
+                // invalid enum type
+                continue;
+            }
+        }
+        return parsedNames;
+    }
+
+    public Set<SubjectAlternateName> getSANs() {
+        return SANs;
+    }
+
+    public String getCN() {
+        return CN;
+    }
+
+    public Organisation getOrg() {
+        return org;
+    }
+
+    public String getOu() {
+        return ou;
+    }
+
+    public Digest getSelectedDigest() {
+        return selectedDigest;
+    }
+
+    public CertificateProfile getProfile() {
+        return profile;
+    }
+
+    public boolean update(String CNin, String hashAlg, String profileStr, String newOrgStr, String ou, String SANsStr, PrintWriter out, HttpServletRequest req) throws GigiApiException {
+        GigiApiException error = new GigiApiException();
+        this.CN = CNin;
+        if (hashAlg != null) {
+            selectedDigest = Digest.valueOf(hashAlg);
+        }
+        this.profile = CertificateProfile.getByName(profileStr);
+        if (newOrgStr != null) {
+            Organisation neworg = Organisation.getById(Integer.parseInt(newOrgStr));
+            if (neworg == null || u.getOrganisations().contains(neworg)) {
+                org = neworg;
+            } else {
+                error.mergeInto(new GigiApiException("Selected Organisation is not part of your account."));
+            }
+        }
+        this.ou = ou;
+
+        boolean server = profile.getKeyName().equals("server");
+        SANs = verifySANs(error, server, parseSANBox(SANsStr));
+
+        if ( !error.isEmpty()) {
+            throw error;
+        }
+        return true;
+    }
+
+    private Set<SubjectAlternateName> verifySANs(GigiApiException error, boolean server, TreeSet<SubjectAlternateName> parseSANBox) {
+        Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
+        for (SubjectAlternateName san : parseSANBox) {
+            if (san.getType() == SANType.DNS) {
+                if (u.isValidDomain(san.getName()) && server) {
+                    if (pDNS == null) {
+                        pDNS = san.getName();
+                    }
+                    filteredSANs.add(san);
+                    continue;
+                }
+            } else if (san.getType() == SANType.EMAIL) {
+                if (u.isValidEmail(san.getName()) && !server) {
+                    if (pMail == null) {
+                        pMail = san.getName();
+                    }
+                    filteredSANs.add(san);
+                    continue;
+                }
+            }
+            HashMap<String, Object> vars = new HashMap<>();
+            vars.put("SAN", san.getType().toString().toLowerCase() + ":" + san.getName());
+            error.mergeInto(new GigiApiException(new Scope(new SprintfCommand(//
+                    "The requested Subject alternate name \"%s\" has been removed.", Arrays.asList("$SAN")), vars)));
+        }
+        return filteredSANs;
+    }
+
+    public Certificate draft() throws GigiApiException {
+
+        GigiApiException error = new GigiApiException();
+        if ( !u.canIssue(this.profile)) {
+            this.profile = CertificateProfile.getById(1);
+            error.mergeInto(new GigiApiException("Certificate Profile is invalid."));
+            throw error;
+        }
+
+        boolean server = profile.getKeyName().equals("server");
+        if ( !u.isValidName(CN) && !server && !CN.equals(DEFAULT_CN)) {
+            this.CN = DEFAULT_CN;
+            error.mergeInto(new GigiApiException("The name entered, does not match the details in your account. You cannot issue certificates with this name. Enter a name that matches the one that has been assured in your account."));
+        }
+
+        HashMap<String, String> subject = new HashMap<>();
+        if (server && pDNS != null) {
+            subject.put("CN", pDNS);
+            if (pMail != null) {
+                error.mergeInto(new GigiApiException("No email is included in this certificate."));
+            }
+            if (CN.equals("")) {
+                CN = "";
+                error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
+            }
+        } else {
+            u.isValidName(CN);
+            subject.put("CN", CN);
+            if (pMail != null) {
+                subject.put("EMAIL", pMail);
+            }
+        }
+        if (org != null) {
+            subject.put("O", org.getName());
+            subject.put("C", org.getState());
+            subject.put("ST", org.getProvince());
+            subject.put("L", org.getCity());
+            subject.put("OU", ou);
+        }
+
+        if ( !error.isEmpty()) {
+            throw error;
+        }
+        return new Certificate(u, subject, selectedDigest.toString(), //
+                this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
+    }
+}
index ba36830be206646de8b20f15b6492cc0c65d7f81..6009095a9de0be8b9b8f59fd145c01808ab8358f 100644 (file)
@@ -32,7 +32,7 @@ import java.util.regex.Pattern;
 import org.cacert.gigi.crypto.SPKAC;
 import org.cacert.gigi.dbObjects.Digest;
 import org.cacert.gigi.pages.account.certs.CertificateAdd;
-import org.cacert.gigi.pages.account.certs.CertificateIssueForm;
+import org.cacert.gigi.pages.account.certs.CertificateRequest;
 import org.cacert.gigi.testUtils.ClientTest;
 import org.cacert.gigi.testUtils.IOUtils;
 import org.cacert.gigi.util.PEM;
@@ -66,7 +66,7 @@ public class TestCertificateAdd extends ClientTest {
     @Test
     public void testSimpleServer() throws IOException, GeneralSecurityException {
         PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
-            CertificateIssueForm.OID_KEY_USAGE_SSL_SERVER
+            CertificateRequest.OID_KEY_USAGE_SSL_SERVER
         }, new DNSName(uniq + ".tld"));
 
         String pem = generatePEMCSR(kp, "CN=a." + uniq + ".tld", atts);
@@ -80,7 +80,7 @@ public class TestCertificateAdd extends ClientTest {
     @Test
     public void testSimpleMail() throws IOException, GeneralSecurityException {
         PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
-            CertificateIssueForm.OID_KEY_USAGE_EMAIL_PROTECTION
+            CertificateRequest.OID_KEY_USAGE_EMAIL_PROTECTION
         }, new DNSName("a." + uniq + ".tld"), new DNSName("b." + uniq + ".tld"), new RFC822Name(email));
 
         String pem = generatePEMCSR(kp, "CN=a b", atts, "SHA384WithRSA");
@@ -94,7 +94,7 @@ public class TestCertificateAdd extends ClientTest {
     @Test
     public void testSimpleClient() throws IOException, GeneralSecurityException {
         PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
-            CertificateIssueForm.OID_KEY_USAGE_SSL_CLIENT
+            CertificateRequest.OID_KEY_USAGE_SSL_CLIENT
         }, new RFC822Name(email));
 
         String pem = generatePEMCSR(kp, "CN=a b,email=" + email, atts, "SHA512WithRSA");
@@ -114,7 +114,7 @@ public class TestCertificateAdd extends ClientTest {
     @Test
     public void testIssue() throws IOException, GeneralSecurityException {
         PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
-            CertificateIssueForm.OID_KEY_USAGE_SSL_CLIENT
+            CertificateRequest.OID_KEY_USAGE_SSL_CLIENT
         }, new RFC822Name(email));
 
         String pem = generatePEMCSR(kp, "CN=a b,email=" + email, atts, "SHA512WithRSA");
@@ -201,7 +201,7 @@ public class TestCertificateAdd extends ClientTest {
 
     private X509Certificate createCertWithValidity(String validity) throws IOException, GeneralSecurityException, UnsupportedEncodingException, MalformedURLException, CertificateException {
         PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
-            CertificateIssueForm.OID_KEY_USAGE_SSL_CLIENT
+            CertificateRequest.OID_KEY_USAGE_SSL_CLIENT
         }, new RFC822Name(email));
 
         String pem = generatePEMCSR(kp, "CN=a b", atts, "SHA512WithRSA");
@@ -251,7 +251,7 @@ public class TestCertificateAdd extends ClientTest {
                 fail("Should not succeed with wrong challange.");
             }
             assertArrayEquals(new String[] {
-                    "client", CertificateIssueForm.DEFAULT_CN, "", Digest.SHA512.toString()
+                    "client", CertificateRequest.DEFAULT_CN, "", Digest.SHA512.toString()
             }, res);
         } catch (Error e) {
             assertTrue(e.getMessage().startsWith("<div>Challenge mismatch"));
diff --git a/tests/org/cacert/gigi/pages/account/TestCertificateRequest.java b/tests/org/cacert/gigi/pages/account/TestCertificateRequest.java
new file mode 100644 (file)
index 0000000..ecea232
--- /dev/null
@@ -0,0 +1,48 @@
+package org.cacert.gigi.pages.account;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.junit.Assert.*;
+
+import java.security.GeneralSecurityException;
+import java.security.KeyPair;
+
+import org.cacert.gigi.GigiApiException;
+import org.cacert.gigi.pages.account.certs.CertificateRequest;
+import org.cacert.gigi.testUtils.ClientTest;
+import org.junit.Test;
+
+public class TestCertificateRequest extends ClientTest {
+
+    KeyPair kp = generateKeypair();
+
+    public TestCertificateRequest() throws GeneralSecurityException {}
+
+    @Test
+    public void testIssuingOtherName() throws Exception {
+        try {
+            new CertificateRequest(u, generatePEMCSR(kp, "CN=hansi")).draft();
+        } catch (GigiApiException e) {
+            assertThat(e.getMessage(), containsString("does not match the details"));
+        }
+    }
+
+    @Test
+    public void testIssuingDefault() throws Exception {
+        new CertificateRequest(u, generatePEMCSR(kp, "CN=" + CertificateRequest.DEFAULT_CN)).draft();
+    }
+
+    @Test
+    public void testIssuingRealName() throws Exception {
+        new CertificateRequest(u, generatePEMCSR(kp, "CN=a b")).draft();
+    }
+
+    @Test
+    public void testIssuingModifiedName() throws Exception {
+        try {
+            new CertificateRequest(u, generatePEMCSR(kp, "CN=a ab")).draft();
+        } catch (GigiApiException e) {
+            assertThat(e.getMessage(), containsString("does not match the details"));
+        }
+
+    }
+}