如何验证证书是否为带有Java的EV证书?

时间:2009-11-07 21:23:47

标签: java ssl certificate

请考虑以下示例代码,该代码使用TrustManager来记录传出连接是否使用了有效证书(但在所有情况下都接受连接):

import java.security.*;
import java.security.cert.*;
import javax.net.ssl.*;

public class CertChecker implements X509TrustManager {

    private final X509TrustManager defaultTM;

    public CertChecker() throws GeneralSecurityException {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init((KeyStore)null);
        defaultTM = (X509TrustManager) tmf.getTrustManagers()[0];
    }

    public void checkServerTrusted(X509Certificate[] certs, String authType) {
        if (defaultTM != null) {
            try {
                defaultTM.checkServerTrusted(certs, authType);
                System.out.println("Certificate valid");
            } catch (CertificateException ex) {
                System.out.println("Certificate invalid: " + ex.getMessage());
            }
        }
    }

    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
    public X509Certificate[] getAcceptedIssuers() { return null;}

    public static void main(String[] args) throws Exception {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] {new CertChecker()}, new SecureRandom());
        SSLSocketFactory ssf = (SSLSocketFactory) sc.getSocketFactory();
        ((SSLSocket)ssf.createSocket(args[0], 443)).startHandshake();
    }
}

我需要在checkClientTrusted方法中检查该证书是扩展验证证书(现代浏览器中的绿色地址栏)还是普通证书(黄色地址栏)?

修改

我正在努力让CertPathValidator正常工作,但不知怎的,我只能获得有关证书的例外不是CA证书...有什么想法吗?

edit2 :使用PKIXParameters代替PKIXBuilderParameters

private boolean isEVCertificate(X509Certificate[] certs, String authType) {
    try {
        CertPath cp = new X509CertPath(Arrays.asList(certs));
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(new File(System.getProperty("java.home"), "lib/security/cacerts")), null);
        PKIXParameters cpp = new PKIXParameters(ks);
        cpp.setRevocationEnabled(false);
        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");          
        PKIXCertPathValidatorResult res = (PKIXCertPathValidatorResult) cpv.validate(cp, cpp);
        System.out.println(res.getTrustAnchor().getCAName());
        System.out.println(res.getPolicyTree().getValidPolicy());
        System.out.println(cp);
        return false;
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }
}

我正在测试现实世界的EV证书。该代码现在与www.paypal.com一起使用(从某种意义上说它不会引发异常),但不适用于banking.dkb.de。 : - (

但即使使用Paypal.com,信任锚getCAName也会返回null,那么我怎么知道它被验证了哪个CA以便我可以查找正确的EV策略?

3 个答案:

答案 0 :(得分:3)

首先,您需要一张发行人名称表及其相应的EV政策标识符。

当CA颁发证书时,他们可以记下颁发证书的策略。发行人分配的此政策的标识符,这就是您需要发行人及其EV政策列表的原因。

然后,您需要从服务器证书中获取策略。 Refer to RFC 5280, § 4.1.2.4了解有关一般政策及其运作方式的更多信息。

您需要验证证书链以获取PKIXCertPathValidatorResult.部分结果是policy tree.您可以浏览策略树以确定它是否包含目标证书的EV策略发行者。


以下是检查证书路径结果的详细示例。

private static final Map<X500Principal, String> policies = new HashMap<X500Principal, String>();

static {
  /* 
   * It would make sense to populate this map from Properties loaded through 
   * Class.getResourceAsStream().
   */
  policies.put(
    new X500Principal("OU=Class 3 Public Primary Certification Authority,O=VeriSign\\, Inc.,C=US"), 
    "2.16.840.1.113733.1.7.23.6"
  );
  // ...
}

static boolean isEV(PKIXCertPathValidatorResult result)
{
  /* Determine the policy to look for. */
  X500Principal root = result.getTrustAnchor().getTrustedCert().getSubjectX500Principal();
  String policy = policies.get(root);
  if (policy == null)
    /* The EV policy for this issuer is unknown (or there is none). */
    return false;
  /* Traverse the tree, looking at its "leaves" to see if the end-entity 
   * certificate was issued under the corresponding EV policy. */
  PolicyNode tree = result.getPolicyTree();
  Deque<PolicyNode> stack = new ArrayDeque<PolicyNode>();
  stack.push(tree);
  while (!stack.isEmpty()) {
    PolicyNode current = stack.pop();
    Iterator<? extends PolicyNode> children = current.getChildren();
    int leaf = stack.size();
    while (children.hasNext())
      stack.push(children.next());
    if (stack.size() == leaf) {
      /* If the stack didn't grow, there were no "children". I.e., the 
       * current node is a "leaf" node of the policy tree. */
      if (current.getValidPolicy().equals(policy))
        return true;
    }
  }
  /* The certificate wasn't issued under the authority's EV policy. */
  return false;
}

答案 1 :(得分:2)

编辑:发布了附加代码。

如果你使用Sun的X509实现,你可以做这样的事情,

  CertificatePoliciesExtension ext = ((X509CertImpl)cert).getCertificatePoliciesExtension();
  List<PolicyInformation> policies = (List<PolicyInformation>)ext.get(CertificatePoliciesExtension.POLICIES);
  boolean evCert = false;
  for (PolicyInformation info : policies) {
      CertificatePolicyId id = info.getPolicyIdentifier();
      if (isEVPolicy(id)) {
         evCert = true;
         break;                 
      }             
  }

  ......

  public static ObjectIdentifier[] EV_POLICIES;

  static {
      try {
          EV_POLICIES = new ObjectIdentifier[] {
                new ObjectIdentifier("2.16.840.1.113733.1.7.23.6"), // Verisign
                new ObjectIdentifier("1.3.6.1.4.1.14370.1.6"), // Geo-Trust of Verisign
                new ObjectIdentifier("2.16.840.1.113733.1.7.48.1") // Thawte
          };
      } catch (IOException e) {
        throw new IllegalStateException("Invalid OIDs");
      }
  }

  private boolean isEVPolicy(CertificatePolicyId id) {
    for (ObjectIdentifier oid : EV_POLICIES) {
        if (oid.equals((Object)id.getIdentifier())) 
            return true;
    }
    return false;
 }

我们只允许来自3个CA的EV证书。您可以在该阵列中添加更多EV OID。您可以从

获取完整的OID列表

http://hg.mozilla.org/mozilla-central/file/05ab1cbc361f/security/manager/ssl/src/nsIdentityChecking.cpp

答案 2 :(得分:2)

我终于让它工作了......下面是一个显示所有逻辑和检查的运行最小例子。是的,它适用于banking.dkb.de: - )

感谢所有帮助过我的人。任何有关明显安全漏洞或其他任何内容的评论(除了代码样式或缺少错误处理;我努力将我的代码压缩到绝对最小的可运行代码)都是受欢迎的,所以随时评论:)

import java.io.*;
import java.security.*;
import java.security.cert.*;
import java.util.*;

import javax.net.ssl.*;
import javax.security.auth.x500.X500Principal;

public class CertChecker implements X509TrustManager {

    private final X509TrustManager defaultTM;

    public CertChecker() throws GeneralSecurityException {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init((KeyStore)null);
        defaultTM = (X509TrustManager) tmf.getTrustManagers()[0];
    }

    public void checkServerTrusted(X509Certificate[] certs, String authType) {
        if (defaultTM != null) {
            try {
                defaultTM.checkServerTrusted(certs, authType);
                if (isEVCertificate(certs))
                    System.out.println("EV Certificate: "+ certs[0].getSubjectX500Principal().getName() + " issued by " + certs[0].getIssuerX500Principal().getName());                    
                System.out.println("Certificate valid");
            } catch (CertificateException ex) {
                System.out.println("Certificate invalid: " + ex.getMessage());
            }
        }
    }

    private boolean isEVCertificate(X509Certificate[] certs) {
        try {
            // load keystore with trusted CA certificates
            KeyStore cacerts = KeyStore.getInstance("JKS");
            cacerts.load(new FileInputStream(new File(System.getProperty("java.home"), "lib/security/cacerts")), null);

            // build a cert selector that selects the first certificate of the certificate chain
            // TODO we should verify this against the hostname...
            X509CertSelector targetConstraints = new X509CertSelector();
            targetConstraints.setSubject(certs[0].getSubjectX500Principal());

            // build a cert path from our selected cert to a CA cert
            PKIXBuilderParameters params = new PKIXBuilderParameters(cacerts, targetConstraints);        
            params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(Arrays.asList(certs))));
            params.setRevocationEnabled(false);
            CertPath cp = CertPathBuilder.getInstance("PKIX").build(params).getCertPath();

            // validate the cert path
            PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) CertPathValidator.getInstance("PKIX").validate(cp, params);
            return isEV(result);
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
    public X509Certificate[] getAcceptedIssuers() { return null;}

    public static void main(String[] args) throws Exception {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] {new CertChecker()}, new SecureRandom());
        SSLSocketFactory ssf = (SSLSocketFactory) sc.getSocketFactory();
        ((SSLSocket)ssf.createSocket(args[0], 443)).startHandshake();
    }

    private static final Map<X500Principal, String> policies = new HashMap<X500Principal, String>();

    static {
        // It would make sense to populate this map from Properties loaded through 
        // Class.getResourceAsStream().
        policies.put(
                new X500Principal("OU=Class 3 Public Primary Certification Authority,O=VeriSign\\, Inc.,C=US"), 
                "2.16.840.1.113733.1.7.23.6"
        );
        // TODO add more certificates here
    }

    // based on http://stackoverflow.com/questions/1694466/1694720#1694720
    static boolean isEV(PKIXCertPathValidatorResult result)
    {
        // Determine the policy to look for.
        X500Principal root = result.getTrustAnchor().getTrustedCert().getSubjectX500Principal();
        System.out.println("[Debug] Found root DN: "+root.getName());
        String policy = policies.get(root);
        if (policy != null)
            System.out.println("[Debug] EV Policy should be: "+policy);

        // Traverse the tree, looking at its "leaves" to see if the end-entity 
        // certificate was issued under the corresponding EV policy.
        PolicyNode tree = result.getPolicyTree();
        if (tree == null)
            return false;
        Deque<PolicyNode> stack = new ArrayDeque<PolicyNode>();
        stack.push(tree);
        while (!stack.isEmpty()) {
            PolicyNode current = stack.pop();
            Iterator<? extends PolicyNode> children = current.getChildren();
            int leaf = stack.size();
            while (children.hasNext())
                stack.push(children.next());
            if (stack.size() == leaf) {
                System.out.println("[Debug] Found policy: " + current.getValidPolicy());
                // If the stack didn't grow, there were no "children". I.e., the 
                // current node is a "leaf" node of the policy tree.
                if (current.getValidPolicy().equals(policy))
                    return true;
            }
        }
        // The certificate wasn't issued under the authority's EV policy.
        return false;
    }
}