From d4b95298902c8cea1411fc696ed80028b6091aa7 Mon Sep 17 00:00:00 2001
From: Rafael Cavazin <rafaelcavazin@gmail.com>
Date: Thu, 06 Dec 2012 11:25:01 -0500
Subject: [PATCH] Update from upstream/master

---
 src/com/gitblit/utils/X509Utils.java |  225 +++++++++++++++++++++++++++++++++++++++-----------------
 1 files changed, 157 insertions(+), 68 deletions(-)

diff --git a/src/com/gitblit/utils/X509Utils.java b/src/com/gitblit/utils/X509Utils.java
index e27d7bc..237c8da 100644
--- a/src/com/gitblit/utils/X509Utils.java
+++ b/src/com/gitblit/utils/X509Utils.java
@@ -15,12 +15,12 @@
  */
 package com.gitblit.utils;
 
-import java.io.BufferedWriter;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.FileWriter;
 import java.io.IOException;
+import java.io.InputStream;
 import java.lang.reflect.Field;
 import java.math.BigInteger;
 import java.security.InvalidKeyException;
@@ -36,6 +36,7 @@
 import java.security.cert.CertPathBuilderException;
 import java.security.cert.CertStore;
 import java.security.cert.Certificate;
+import java.security.cert.CertificateFactory;
 import java.security.cert.CollectionCertStoreParameters;
 import java.security.cert.PKIXBuilderParameters;
 import java.security.cert.PKIXCertPathBuilderResult;
@@ -45,11 +46,13 @@
 import java.security.cert.X509Certificate;
 import java.text.MessageFormat;
 import java.text.SimpleDateFormat;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Calendar;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.TimeZone;
@@ -82,8 +85,6 @@
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import sun.security.x509.X509CRLImpl;
-
 import com.gitblit.Constants;
 
 /**
@@ -108,9 +109,15 @@
 
 	public static final String CA_CN = "Gitblit Certificate Authority";
 	
-	public static final String CA_FN = CA_CN;
+	public static final String CA_ALIAS = CA_CN;
 
 	private static final String BC = org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME;
+	
+	private static final int KEY_LENGTH = 2048;
+	
+	private static final String KEY_ALGORITHM = "RSA";
+	
+	private static final String SIGNING_ALGORITHM = "SHA512withRSA";
 	
 	public static final boolean unlimitedStrength;
 	
@@ -151,6 +158,10 @@
 		 }
 	}
 	
+	public interface X509Log {
+		void log(String message);
+	}
+	
 	public static class X509Metadata {
 
 		// map for distinguished name OIDs
@@ -179,6 +190,9 @@
 		
 		// displayname of user for README in bundle
 		public String userDisplayname;
+
+		// serialnumber of generated or read certificate
+		public String serialNumber;
 
 		public X509Metadata(String cn, String pwd) {
 			if (StringUtils.isEmpty(cn)) {
@@ -211,6 +225,21 @@
 			clone.userDisplayname = userDisplayname;
 			return clone;
 		}
+		
+		public String getOID(String oid, String defaultValue) {
+			if (oids.containsKey(oid)) {
+				return oids.get(oid);
+			}
+			return defaultValue;
+		}
+		
+		public void setOID(String oid, String value) {
+			if (StringUtils.isEmpty(value)) {
+				oids.remove(oid);
+			} else {
+				oids.put(oid, value);
+			}
+		}
 	}
 	
 	/**
@@ -218,9 +247,9 @@
 	 * 
 	 * @param metadata
 	 * @param folder
-	 * @param logger
+	 * @param x509log
 	 */
-	public static void prepareX509Infrastructure(X509Metadata metadata, File folder) {
+	public static void prepareX509Infrastructure(X509Metadata metadata, File folder, X509Log x509log) {
 		// make the specified folder, if necessary
 		folder.mkdirs();
 		
@@ -228,7 +257,7 @@
 		File caKeyStore = new File(folder, CA_KEY_STORE);			
 		if (!caKeyStore.exists()) {
 			logger.info(MessageFormat.format("Generating {0} ({1})", CA_CN, caKeyStore.getAbsolutePath()));
-			X509Certificate caCert = newCertificateAuthority(metadata, caKeyStore);
+			X509Certificate caCert = newCertificateAuthority(metadata, caKeyStore, x509log);
 			saveCertificate(caCert, new File(caKeyStore.getParentFile(), "ca.cer"));
 		}
 
@@ -236,7 +265,8 @@
 		File caRevocationList = new File(folder, CA_REVOCATION_LIST);			
 		if (!caRevocationList.exists()) {
 			logger.info(MessageFormat.format("Generating {0} CRL ({1})", CA_CN, caRevocationList.getAbsolutePath()));
-			newCertificateRevocationList(caRevocationList, caKeyStore, metadata.password);			
+			newCertificateRevocationList(caRevocationList, caKeyStore, metadata.password);
+			x509log.log("new certificate revocation list created");
 		}
 
 		// rename the old keystore to the new name
@@ -250,17 +280,17 @@
 		File serverKeyStore = new File(folder, SERVER_KEY_STORE);
 		if (!serverKeyStore.exists()) {
 			logger.info(MessageFormat.format("Generating SSL certificate for {0} signed by {1} ({2})", metadata.commonName, CA_CN, serverKeyStore.getAbsolutePath()));
-			PrivateKey caPrivateKey = getPrivateKey(CA_FN, caKeyStore, metadata.password);
-			X509Certificate caCert = getCertificate(CA_FN, caKeyStore, metadata.password);
-			newSSLCertificate(metadata, caPrivateKey, caCert, serverKeyStore);
+			PrivateKey caPrivateKey = getPrivateKey(CA_ALIAS, caKeyStore, metadata.password);
+			X509Certificate caCert = getCertificate(CA_ALIAS, caKeyStore, metadata.password);
+			newSSLCertificate(metadata, caPrivateKey, caCert, serverKeyStore, x509log);			
 		}
 
 		// server certificate trust store holds trusted public certificates
 		File serverTrustStore = new File(folder, X509Utils.SERVER_TRUST_STORE);
 		if (!serverTrustStore.exists()) {
-			logger.info(MessageFormat.format("Importing {0} into trust store ({1})", CA_FN, serverTrustStore.getAbsolutePath()));
-			X509Certificate caCert = getCertificate(CA_FN, caKeyStore, metadata.password);
-			addTrustedCertificate(CA_FN, caCert, serverTrustStore, metadata.password);
+			logger.info(MessageFormat.format("Importing {0} into trust store ({1})", CA_ALIAS, serverTrustStore.getAbsolutePath()));
+			X509Certificate caCert = getCertificate(CA_ALIAS, caKeyStore, metadata.password);
+			addTrustedCertificate(CA_ALIAS, caCert, serverTrustStore, metadata.password);
 		}
 	}
 	
@@ -453,8 +483,8 @@
 	 * @throws Exception
 	 */
 	private static KeyPair newKeyPair() throws Exception {
-		KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", BC);
-		kpGen.initialize(2048, new SecureRandom());
+		KeyPairGenerator kpGen = KeyPairGenerator.getInstance(KEY_ALGORITHM, BC);
+		kpGen.initialize(KEY_LENGTH, new SecureRandom());
 		return kpGen.generateKeyPair();
 	}
 	
@@ -506,8 +536,9 @@
 	 * @param caPrivateKey
 	 * @param caCert
 	 * @param targetStoreFile
+	 * @param x509log
 	 */
-	public static X509Certificate newSSLCertificate(X509Metadata sslMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetStoreFile) {
+	public static X509Certificate newSSLCertificate(X509Metadata sslMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetStoreFile, X509Log x509log) {
 		try {
 			KeyPair pair = newKeyPair();
 
@@ -527,7 +558,17 @@
 			certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
 			certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));
 
-			ContentSigner caSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
+			// support alternateSubjectNames for SSL certificates
+			List<GeneralName> altNames = new ArrayList<GeneralName>();
+			if (HttpUtils.isIpAddress(sslMetadata.commonName)) {
+				altNames.add(new GeneralName(GeneralName.iPAddress, sslMetadata.commonName));				
+			}
+			if (altNames.size() > 0) {
+				GeneralNames subjectAltName = new GeneralNames(altNames.toArray(new GeneralName [altNames.size()]));
+				certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
+			}
+
+			ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM)
 					.setProvider(BC).build(caPrivateKey);
 			X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC)
 					.getCertificate(certBuilder.build(caSigner));
@@ -541,8 +582,11 @@
 					new Certificate[] { cert, caCert });
 			saveKeyStore(targetStoreFile, serverStore, sslMetadata.password);
 			
-	        log(targetStoreFile.getParentFile(), MessageFormat.format("New web certificate {0,number,0} [{1}]", cert.getSerialNumber(), webDN.toString()));
-			
+	        x509log.log(MessageFormat.format("New SSL certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getSubjectDN().getName()));
+	        
+	        // update serial number in metadata object
+	        sslMetadata.serialNumber = cert.getSerialNumber().toString();
+
 			return cert;
 		} catch (Throwable t) {
 			throw new RuntimeException("Failed to generate SSL certificate!", t);
@@ -556,13 +600,14 @@
 	 * @param metadata
 	 * @param storeFile
 	 * @param keystorePassword
+	 * @param x509log
 	 * @return
 	 */
-	public static X509Certificate newCertificateAuthority(X509Metadata metadata, File storeFile) {
+	public static X509Certificate newCertificateAuthority(X509Metadata metadata, File storeFile, X509Log x509log) {
 		try {
 			KeyPair caPair = newKeyPair();
 			
-			ContentSigner caSigner = new JcaContentSignerBuilder("SHA1WithRSA").setProvider(BC).build(caPair.getPrivate());
+			ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPair.getPrivate());
 			
 			// clone metadata
 			X509Metadata caMetadata = metadata.clone(CA_CN, metadata.password);
@@ -597,11 +642,15 @@
 			
 			// Save private key and certificate to new keystore
 			KeyStore store = openKeyStore(storeFile, caMetadata.password);
-			store.setKeyEntry(CA_FN, caPair.getPrivate(), caMetadata.password.toCharArray(),
+			store.setKeyEntry(CA_ALIAS, caPair.getPrivate(), caMetadata.password.toCharArray(),
 					new Certificate[] { cert });
 			saveKeyStore(storeFile, store, caMetadata.password);
 			
-	        log(storeFile.getParentFile(), MessageFormat.format("New CA certificate {0,number,0} [{1}]", cert.getSerialNumber(), issuerDN.toString()));
+			x509log.log(MessageFormat.format("New CA certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getIssuerDN().getName()));
+
+	        // update serial number in metadata object
+	        caMetadata.serialNumber = cert.getSerialNumber().toString();
+
 			return cert;
 		} catch (Throwable t) {
 			throw new RuntimeException("Failed to generate Gitblit CA certificate!", t);
@@ -621,14 +670,14 @@
 		try {
 			// read the Gitblit CA key and certificate
 			KeyStore store = openKeyStore(caKeystoreFile, caKeystorePassword);
-			PrivateKey caPrivateKey = (PrivateKey) store.getKey(CA_FN, caKeystorePassword.toCharArray());
-			X509Certificate caCert = (X509Certificate) store.getCertificate(CA_FN);
+			PrivateKey caPrivateKey = (PrivateKey) store.getKey(CA_ALIAS, caKeystorePassword.toCharArray());
+			X509Certificate caCert = (X509Certificate) store.getCertificate(CA_ALIAS);
 
 			X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
 			X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuerDN, new Date());
 			
 			// build and sign CRL with CA private key
-			ContentSigner signer = new JcaContentSignerBuilder("SHA1WithRSA").setProvider(BC).build(caPrivateKey);
+			ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);
 			X509CRLHolder crl = crlBuilder.build(signer);
 
 			File tmpFile = new File(caRevocationList.getParentFile(), Long.toHexString(System.currentTimeMillis()) + ".tmp");
@@ -642,8 +691,6 @@
 					caRevocationList.delete();
 				}
 				tmpFile.renameTo(caRevocationList);
-
-				log(caRevocationList.getParentFile(), "new certificate revocation list created");
 			} finally {
 				if (fos != null) {
 					fos.close();
@@ -685,19 +732,22 @@
 	 * @param clientMetadata a container for dynamic parameters needed for generation
 	 * @param caKeystoreFile
 	 * @param caKeystorePassword
+	 * @param x509log
 	 * @return a zip file containing the P12, PEM, and personalized README
 	 */
-	public static File newClientBundle(X509Metadata clientMetadata, File caKeystoreFile, String caKeystorePassword) {
+	public static File newClientBundle(X509Metadata clientMetadata, File caKeystoreFile, 
+			String caKeystorePassword, X509Log x509log) {
 		try {
 			// read the Gitblit CA key and certificate
 			KeyStore store = openKeyStore(caKeystoreFile, caKeystorePassword);
-			PrivateKey caPrivateKey = (PrivateKey) store.getKey(CA_FN, caKeystorePassword.toCharArray());
-			X509Certificate caCert = (X509Certificate) store.getCertificate(CA_FN);
+			PrivateKey caPrivateKey = (PrivateKey) store.getKey(CA_ALIAS, caKeystorePassword.toCharArray());
+			X509Certificate caCert = (X509Certificate) store.getCertificate(CA_ALIAS);
 			
 			// generate the P12 and PEM files
 			File targetFolder = new File(caKeystoreFile.getParentFile(), clientMetadata.commonName);
-			newClientCertificate(clientMetadata, caPrivateKey, caCert, targetFolder);
-			
+			X509Certificate cert = newClientCertificate(clientMetadata, caPrivateKey, caCert, targetFolder);
+	        x509log.log(MessageFormat.format("New client certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getSubjectDN().getName()));
+
 	        // process template message
 	        String readme = processTemplate(new File(caKeystoreFile.getParentFile(), "instructions.tmpl"), clientMetadata);
 	        
@@ -721,6 +771,17 @@
 	        		zos.write(FileUtils.readContent(pemFile));
 	        		zos.closeEntry();
 	        	}
+	        	
+	        	// include user's public certificate
+	        	zos.putNextEntry(new ZipEntry(clientMetadata.commonName + ".cer"));
+        		zos.write(cert.getEncoded());
+        		zos.closeEntry();
+        		
+	        	// include CA public certificate
+	        	zos.putNextEntry(new ZipEntry("ca.cer"));
+        		zos.write(caCert.getEncoded());
+        		zos.closeEntry();
+        		
 	        	if (readme != null) {
 	        		zos.putNextEntry(new ZipEntry("README.TXT"));
 	        		zos.write(readme.getBytes("UTF-8"));
@@ -777,7 +838,7 @@
 				certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
 			}
 
-			ContentSigner signer = new JcaContentSignerBuilder("SHA1WithRSA").setProvider(BC).build(caPrivateKey);
+			ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);
 
 			X509Certificate userCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certBuilder.build(signer));
 			PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)pair.getPrivate();
@@ -830,7 +891,8 @@
 	        // save certificate after successfully creating the key stores
 	        saveCertificate(userCert, certFile);
 	        
-	        log(targetFolder.getParentFile(), MessageFormat.format("New client certificate {0,number,0} [{1}]", userCert.getSerialNumber(), userDN.toString()));
+	        // update serial number in metadata object
+	        clientMetadata.serialNumber = userCert.getSerialNumber().toString();
 	        
 	        return userCert;
 		} catch (Throwable t) {
@@ -915,32 +977,21 @@
 			String message = FileUtils.readContent(template, "\n");
 			if (!StringUtils.isEmpty(message)) {
 				content = message;
-				content = content.replace("$serverHostname", metadata.serverHostname);
-				content = content.replace("$username", metadata.commonName);
-				content = content.replace("$userDisplayname", metadata.userDisplayname);
-				content = content.replace("$storePasswordHint", metadata.passwordHint);
-			}
-		}
-		return content;
-	}
-	
-	private static void log(File folder, String message) {
-		BufferedWriter writer = null;
-		try {
-			writer = new BufferedWriter(new FileWriter(new File(folder, "log.txt"), true));
-			writer.write(MessageFormat.format("{0,date,yyyy-MM-dd HH:mm}: {1}", new Date(), message));
-			writer.newLine();
-			writer.flush();
-		} catch (Exception e) {
-			logger.error("Failed to append log entry!", e);
-		} finally {
-			if (writer != null) {
-				try {
-					writer.close();
-				} catch (IOException e) {
+				if (!StringUtils.isEmpty(metadata.serverHostname)) {
+					content = content.replace("$serverHostname", metadata.serverHostname);
+				}
+				if (!StringUtils.isEmpty(metadata.commonName)) {
+					content = content.replace("$username", metadata.commonName);
+				}
+				if (!StringUtils.isEmpty(metadata.userDisplayname)) {
+					content = content.replace("$userDisplayname", metadata.userDisplayname);
+				}
+				if (!StringUtils.isEmpty(metadata.passwordHint)) {
+					content = content.replace("$storePasswordHint", metadata.passwordHint);
 				}
 			}
 		}
+		return content;
 	}
 	
 	/**
@@ -951,15 +1002,17 @@
 	 * @param caRevocationList
 	 * @param caKeystoreFile
 	 * @param caKeystorePassword
+	 * @param x509log
 	 * @return true if the certificate has been revoked
 	 */
 	public static boolean revoke(X509Certificate cert, RevocationReason reason,
-			File caRevocationList, File caKeystoreFile, String caKeystorePassword) {
+			File caRevocationList, File caKeystoreFile, String caKeystorePassword,
+			X509Log x509log) {
 		try {
 			// read the Gitblit CA key and certificate
 			KeyStore store = openKeyStore(caKeystoreFile, caKeystorePassword);
-			PrivateKey caPrivateKey = (PrivateKey) store.getKey(CA_FN, caKeystorePassword.toCharArray());
-			return revoke(cert, reason, caRevocationList, caPrivateKey);
+			PrivateKey caPrivateKey = (PrivateKey) store.getKey(CA_ALIAS, caKeystorePassword.toCharArray());
+			return revoke(cert, reason, caRevocationList, caPrivateKey, x509log);
 		} catch (Exception e) {
 			logger.error(MessageFormat.format("Failed to revoke certificate {0,number,0} [{1}] in {2}",
 					cert.getSerialNumber(), cert.getSubjectDN().getName(), caRevocationList));
@@ -974,12 +1027,12 @@
 	 * @param reason
 	 * @param caRevocationList
 	 * @param caPrivateKey
+	 * @param x509log
 	 * @return true if the certificate has been revoked
 	 */
 	public static boolean revoke(X509Certificate cert, RevocationReason reason,
-			 File caRevocationList, PrivateKey caPrivateKey) {
+			 File caRevocationList, PrivateKey caPrivateKey, X509Log x509log) {
 		try {
-			X500Name subjectDN = new X500Name(PrincipalUtil.getSubjectX509Principal(cert).getName());
 			X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(cert).getName());
 			X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuerDN, new Date());
 			if (caRevocationList.exists()) {
@@ -1005,8 +1058,6 @@
 				}
 				tmpFile.renameTo(caRevocationList);
 				
-				log(caRevocationList.getParentFile(), MessageFormat.format("Revoked certificate {0,number,0} reason: {1} [{2}]",
-						cert.getSerialNumber(), reason.toString(), subjectDN.toString()));
 			} finally {
 				if (fos != null) {
 					fos.close();
@@ -1015,6 +1066,9 @@
 					tmpFile.delete();
 				}
 			}
+			
+			x509log.log(MessageFormat.format("Revoked certificate {0,number,0} reason: {1} [{2}]",
+					cert.getSerialNumber(), reason.toString(), cert.getSubjectDN().getName()));
 			return true;
 		} catch (Exception e) {
 			logger.error(MessageFormat.format("Failed to revoke certificate {0,number,0} [{1}] in {2}",
@@ -1034,14 +1088,49 @@
 		if (!caRevocationList.exists()) {
 			return false;
 		}
+		InputStream inStream = null;
 		try {
-			byte [] data = FileUtils.readContent(caRevocationList);
-			X509CRL crl = new X509CRLImpl(data);
+			inStream = new FileInputStream(caRevocationList);
+			CertificateFactory cf = CertificateFactory.getInstance("X.509");
+			X509CRL crl = (X509CRL)cf.generateCRL(inStream);
 			return crl.isRevoked(cert);
 		} catch (Exception e) {
 			logger.error(MessageFormat.format("Failed to check revocation status for certificate {0,number,0} [{1}] in {2}",
 					cert.getSerialNumber(), cert.getSubjectDN().getName(), caRevocationList));
+		} finally {
+			if (inStream != null) {
+				try {
+					inStream.close();
+				} catch (Exception e) {
+				}
+			}
 		}
 		return false;
 	}
+	
+	public static X509Metadata getMetadata(X509Certificate cert) {
+		// manually split DN into OID components
+		// this is instead of parsing with LdapName which:
+		// (1) I don't trust the order of values
+		// (2) it filters out values like EMAILADDRESS
+		String dn = cert.getSubjectDN().getName();
+		Map<String, String> oids = new HashMap<String, String>();
+		for (String kvp : dn.split(",")) {
+			String [] val = kvp.trim().split("=");
+			String oid = val[0].toUpperCase().trim();
+			String data = val[1].trim();
+			oids.put(oid, data);
+		}
+		
+		X509Metadata metadata = new X509Metadata(oids.get("CN"), "whocares");
+		metadata.oids.putAll(oids);
+		metadata.serialNumber = cert.getSerialNumber().toString();
+		metadata.notAfter = cert.getNotAfter();
+		metadata.notBefore = cert.getNotBefore();
+		metadata.emailAddress = metadata.getOID("E", null);
+		if (metadata.emailAddress == null) {
+			metadata.emailAddress = metadata.getOID("EMAILADDRESS", null);
+		}
+		return metadata;
+	}
 }

--
Gitblit v1.9.1