public boolean match(Certificate cert) {
    if (!(cert instanceof X509Certificate)) {
      return false;
    }

    X509Certificate x509Cert = (X509Certificate) cert;

    if (form instanceof V2Form) {
      V2Form issuer = (V2Form) form;
      if (issuer.getBaseCertificateID() != null) {
        return issuer
                .getBaseCertificateID()
                .getSerial()
                .getValue()
                .equals(x509Cert.getSerialNumber())
            && matchesDN(
                x509Cert.getIssuerX500Principal(), issuer.getBaseCertificateID().getIssuer());
      }

      GeneralNames name = issuer.getIssuerName();
      if (matchesDN(x509Cert.getSubjectX500Principal(), name)) {
        return true;
      }
    } else {
      GeneralNames name = (GeneralNames) form;
      if (matchesDN(x509Cert.getSubjectX500Principal(), name)) {
        return true;
      }
    }

    return false;
  }
  /*
   * Check for a valid certificate pair
   */
  private void checkPair() throws CertificateException {

    /* if either of pair is missing, return w/o error */
    if (forward == null || reverse == null) {
      return;
    }
    /*
     * If both elements of the pair are present, check that they
     * are a valid pair.
     */
    X500Principal fwSubject = forward.getSubjectX500Principal();
    X500Principal fwIssuer = forward.getIssuerX500Principal();
    X500Principal rvSubject = reverse.getSubjectX500Principal();
    X500Principal rvIssuer = reverse.getIssuerX500Principal();
    if (!fwIssuer.equals(rvSubject) || !rvIssuer.equals(fwSubject)) {
      throw new CertificateException(
          "subject and issuer names in " + "forward and reverse certificates do not match");
    }

    /* check signatures unless key parameters are missing */
    try {
      PublicKey pk = reverse.getPublicKey();
      if (!(pk instanceof DSAPublicKey) || ((DSAPublicKey) pk).getParams() != null) {
        forward.verify(pk);
      }
      pk = forward.getPublicKey();
      if (!(pk instanceof DSAPublicKey) || ((DSAPublicKey) pk).getParams() != null) {
        reverse.verify(pk);
      }
    } catch (GeneralSecurityException e) {
      throw new CertificateException("invalid signature: " + e.getMessage());
    }
  }
  @Override
  protected HttpURLConnection openConnection(String path, String query) throws IOException {
    query = addDelegationTokenParam(query);
    final URL url = new URL("https", nnAddr.getHostName(), nnAddr.getPort(), path + '?' + query);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    // bypass hostname verification
    try {
      conn.setHostnameVerifier(new DummyHostnameVerifier());
      conn.setRequestMethod("GET");
      conn.connect();
    } catch (IOException ioe) {
      throwIOExceptionFromConnection(conn, ioe);
    }

    // check cert expiration date
    final int warnDays = ExpWarnDays;
    if (warnDays > 0) { // make sure only check once
      ExpWarnDays = 0;
      long expTimeThreshold = warnDays * MM_SECONDS_PER_DAY + System.currentTimeMillis();
      X509Certificate[] clientCerts = (X509Certificate[]) conn.getLocalCertificates();
      if (clientCerts != null) {
        for (X509Certificate cert : clientCerts) {
          long expTime = cert.getNotAfter().getTime();
          if (expTime < expTimeThreshold) {
            StringBuilder sb = new StringBuilder();
            sb.append("\n Client certificate " + cert.getSubjectX500Principal().getName());
            int dayOffSet = (int) ((expTime - System.currentTimeMillis()) / MM_SECONDS_PER_DAY);
            sb.append(" have " + dayOffSet + " days to expire");
            LOG.warn(sb.toString());
          }
        }
      }
    }
    return (HttpURLConnection) conn;
  }
Exemple #4
0
  public static String getCertOwner(X509Certificate cert) {
    X500Principal prin = cert.getSubjectX500Principal();

    // get the domain name
    Map<String, String> oidMap = new HashMap<String, String>();
    oidMap.put("1.2.840.113549.1.9.1", "EMAILADDRESS"); // OID for email address
    String prinName = prin.getName(X500Principal.RFC1779, oidMap);

    // see if there is an email address first in the DN
    String searchString = "EMAILADDRESS=";
    int index = prinName.indexOf(searchString);
    if (index == -1) {
      searchString = "CN=";
      // no Email.. check the CN
      index = prinName.indexOf(searchString);
      if (index == -1) return ""; // no CN... nothing else that can be done from here
    }

    // look for a "," to find the end of this attribute
    int endIndex = prinName.indexOf(",", index);
    String address;
    if (endIndex > -1) address = prinName.substring(index + searchString.length(), endIndex);
    else address = prinName.substring(index + searchString.length());

    return address;
  }
 /**
  * Handles server certificate validation. Flags for validity and certificate chain verification
  * decides this functions behavior.
  *
  * <p>Implements X509TrustManager.
  */
 public void checkServerTrusted(X509Certificate[] chain, String authType)
     throws CertificateException {
   try {
     Set<TrustAnchor> trust = new HashSet<TrustAnchor>();
     // All CAs must in an *installed* CA path be valid as trust
     // anchors
     Enumeration<String> aliases = trust_store.aliases();
     while (aliases.hasMoreElements()) {
       String alias = aliases.nextElement();
       if (trust_store.isCertificateEntry(alias)) {
         trust.add(new TrustAnchor((X509Certificate) trust_store.getCertificate(alias), null));
       }
     }
     CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
     PKIXParameters param = new PKIXParameters(trust);
     param.setDate(new Date());
     param.setRevocationEnabled(enable_revocation_test);
     List<X509Certificate> certchain = new ArrayList<X509Certificate>();
     for (X509Certificate cert : chain) {
       if (!cert.getSubjectX500Principal().equals(cert.getIssuerX500Principal())) {
         certchain.add(cert);
       }
     }
     CertPath cp = CertificateFactory.getInstance("X.509").generateCertPath(certchain);
     cpv.validate(cp, param);
   } catch (GeneralSecurityException e) {
     if (!allow_invalidcert) {
       throw new CertificateException(e);
     }
   }
 }
 /** Build a sample V3 certificate to use as an end entity certificate */
 public static X509Certificate buildEndEntityCert(
     PublicKey entityKey, PrivateKey caKey, X509Certificate caCert) throws Exception {
   X509v3CertificateBuilder certBldr =
       new JcaX509v3CertificateBuilder(
           caCert.getSubjectX500Principal(),
           BigInteger.valueOf(1),
           new Date(System.currentTimeMillis()),
           new Date(System.currentTimeMillis() + VALIDITY_PERIOD),
           new X500Principal("CN=Test End Entity Certificate"),
           entityKey);
   JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
   certBldr
       .addExtension(
           Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert))
       .addExtension(
           Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(entityKey))
       .addExtension(Extension.basicConstraints, true, new BasicConstraints(false))
       .addExtension(
           Extension.keyUsage,
           true,
           new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
   ContentSigner signer =
       new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(caKey);
   return new JcaX509CertificateConverter()
       .setProvider("BC")
       .getCertificate(certBldr.build(signer));
 }
 /** Build a sample V3 certificate to use as an intermediate CA certificate */
 public static X509Certificate buildIntermediateCert(
     PublicKey intKey, PrivateKey caKey, X509Certificate caCert) throws Exception {
   X509v3CertificateBuilder certBldr =
       new JcaX509v3CertificateBuilder(
           caCert.getSubjectX500Principal(),
           BigInteger.valueOf(1),
           new Date(),
           sdf.parse("2016-07-06 06:06:06"),
           new X500Principal("CN=Test CA Certificate"),
           intKey);
   JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
   certBldr
       .addExtension(
           Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert))
       .addExtension(
           Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(intKey))
       .addExtension(Extension.basicConstraints, true, new BasicConstraints(0))
       .addExtension(
           Extension.keyUsage,
           true,
           new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
   ContentSigner signer =
       new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(caKey);
   return new JcaX509CertificateConverter()
       .setProvider("BC")
       .getCertificate(certBldr.build(signer));
 }
 /** javax.net.ssl.SSLSession#getPeerPrincipal() */
 public void test_getPeerPrincipal() throws Exception {
   Principal p1 = clientSession.getPeerPrincipal();
   KeyStore store = server.getStore();
   X509Certificate cert = (X509Certificate) store.getCertificate("mykey");
   Principal p2 = cert.getSubjectX500Principal();
   assertEquals(p1, p2);
 }
Exemple #9
0
  @Override
  public void authenticate(
      Set<Object> publicCredentials,
      Set<Object> privateCredentials,
      Set<Principal> identifiedPrincipals)
      throws AuthenticationException {
    String message = "no X.509 certificate chain";

    boolean found = false;
    for (Object credential : publicCredentials) {
      if (isX509CertPath(credential)) {
        X509Certificate eec = CertPaths.getEndEntityCertificate((CertPath) credential);

        if (eec == null) {
          message = "X.509 chain contains no End-Entity Certificate";
        } else {
          identifiedPrincipals.add(new GlobusPrincipal(eec.getSubjectX500Principal()));

          if (isPolicyPrincipalsEnabled) {
            listPolicies(eec)
                .stream()
                .map(PolicyInformation::getInstance)
                .map(PolicyInformation::getPolicyIdentifier)
                .map(DERObjectIdentifier::getId)
                .map(X509Plugin::asPrincipal)
                .filter(Objects::nonNull)
                .forEach(identifiedPrincipals::add);
          }

          found = true;
        }
      }
    }
    checkAuthentication(found, message);
  }
Exemple #10
0
  /**
   * Take an array of X509 certificates and arrange them as a list of chains. Certificates of
   * unknown types and broken chains are add returned in failed list.
   */
  public static ArrayList<List<X509Certificate>> getCertificateChains(
      Certificate[] c, ArrayList<Certificate> failed) {
    if (c == null) {
      return null;
    }
    final ArrayList<List<X509Certificate>> res = new ArrayList<List<X509Certificate>>(3);
    ArrayList<X509Certificate> chain = new ArrayList<X509Certificate>(3);
    int i = 0;
    while (i < c.length) {
      if (c[i] instanceof X509Certificate) {
        final X509Certificate cert = (X509Certificate) c[i++];
        // TBD, can we use == and do we need to check uniqID?
        chain.add(cert);
        if (cert.getIssuerX500Principal().equals(cert.getSubjectX500Principal())) {
          res.add(chain);
          chain = new ArrayList<X509Certificate>(3);
        }
      } else {
        // Unsupported type
        if (!chain.isEmpty()) {
          failed.addAll(chain);
          chain.clear();
        }
        failed.add(c[i++]);
      }
    }
    // Add remaining certs as failed
    failed.addAll(chain);

    return res;
  }
Exemple #11
0
  private void mockCert(String dn) {
    X509Certificate idCert = mock(X509Certificate.class);
    X500Principal principal = new X500Principal(dn);

    when(idCert.getSubjectX500Principal()).thenReturn(principal);
    when(this.httpRequest.getAttribute("javax.servlet.request.X509Certificate"))
        .thenReturn(new X509Certificate[] {idCert});
  }
Exemple #12
0
  /**
   * retrieve the subject's CN field from given certificate
   *
   * @param cert given certificate
   * @return subject's CN field
   * @throws CertificateException
   */
  public static String getSubjectFromCert(java.security.cert.X509Certificate cert)
      throws CertificateException {
    String dn = cert.getSubjectX500Principal().getName();
    Matcher m = _pattern.matcher(dn);
    if (!m.find()) throw new CertificateException("Unable to get CN from certificate");

    return m.group(1);
  }
 @Override
 public void validate(List<X509Certificate> certificateChain, RevocationData revocationData)
     throws Exception {
   for (X509Certificate certificate : certificateChain) {
     LOG.debug("certificate: " + certificate.getSubjectX500Principal());
     LOG.debug("validity: " + certificate.getNotBefore() + " - " + certificate.getNotAfter());
   }
   this.trustValidator.isTrusted(certificateChain);
 }
 private String a(X509Certificate paramX509Certificate) {
   String[] arrayOfString = paramX509Certificate.getSubjectX500Principal().toString().split(",");
   int i = arrayOfString.length;
   for (int j = 0; ; j++) {
     if (j >= i) return null;
     String str = arrayOfString[j];
     int k = str.indexOf("CN=");
     if (k >= 0) return str.substring(k + 3);
   }
 }
 public static String[] getCNs(X509Certificate x509certificate) {
   x509certificate = x509certificate.getSubjectX500Principal().toString();
   try {
     x509certificate = extractCNs(x509certificate);
   }
   // Misplaced declaration of an exception variable
   catch (X509Certificate x509certificate) {
     return null;
   }
   return x509certificate;
 }
  private X509Certificate generateCertificate(
      PublicKey subjectPublicKey,
      String subjectDn,
      DateTime notBefore,
      DateTime notAfter,
      X509Certificate issuerCertificate,
      PrivateKey issuerPrivateKey)
      throws Exception {

    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.reset();
    certificateGenerator.setPublicKey(subjectPublicKey);
    certificateGenerator.setSignatureAlgorithm("SHA1WithRSAEncryption");
    certificateGenerator.setNotBefore(notBefore.toDate());
    certificateGenerator.setNotAfter(notAfter.toDate());

    X509Principal issuerDN;
    if (null != issuerCertificate) {
      issuerDN = new X509Principal(issuerCertificate.getSubjectX500Principal().toString());
    } else {
      issuerDN = new X509Principal(subjectDn);
    }
    certificateGenerator.setIssuerDN(issuerDN);
    certificateGenerator.setSubjectDN(new X509Principal(subjectDn));
    certificateGenerator.setSerialNumber(new BigInteger(128, new SecureRandom()));

    certificateGenerator.addExtension(
        X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(subjectPublicKey));

    PublicKey issuerPublicKey;
    if (null != issuerCertificate) {
      issuerPublicKey = issuerCertificate.getPublicKey();
    } else {
      issuerPublicKey = subjectPublicKey;
    }
    certificateGenerator.addExtension(
        X509Extensions.AuthorityKeyIdentifier, false, createAuthorityKeyId(issuerPublicKey));

    X509Certificate certificate;
    certificate = certificateGenerator.generate(issuerPrivateKey);

    /*
     * Next certificate factory trick is needed to make sure that the
     * certificate delivered to the caller is provided by the default
     * security provider instead of BouncyCastle. If we don't do this trick
     * we might run into trouble when trying to use the CertPath validator.
     */
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    certificate =
        (X509Certificate)
            certificateFactory.generateCertificate(
                new ByteArrayInputStream(certificate.getEncoded()));
    return certificate;
  }
  public void testGetSigningPolicyWithDNPrincipal() throws Exception {

    String sigPolPattern = caCertsLocation + "/*.signing_policy";
    ResourceSigningPolicyStore sigPolStore =
        new ResourceSigningPolicyStore(new ResourceSigningPolicyStoreParameters(sigPolPattern));

    String certPath1 = caCertsLocation + "/e5cc84c2.0";

    X509Certificate crt1 = readCertificate(certPath1);
    Assert.assertNotNull("Unable to read certificate in " + certPath1, crt1);

    SigningPolicy signingPolicy = sigPolStore.getSigningPolicy(crt1.getSubjectX500Principal());

    Assert.assertNotNull(signingPolicy);

    // According to https://github.com/jglobus/JGlobus/issues/102 the second attempt is failing.
    // Therefore we query twice.
    signingPolicy = sigPolStore.getSigningPolicy(crt1.getSubjectX500Principal());

    Assert.assertNotNull(signingPolicy);
  }
Exemple #18
0
  public static String getCertificateFriendlyName(X509Certificate cert) {
    X500Principal principal = cert.getSubjectX500Principal();
    byte[] encodedSubject = principal.getEncoded();
    String friendlyName = null;

    /* Hack so we do not have to ship a whole Spongy/bouncycastle */
    Exception exp = null;
    try {
      Class X509NameClass = Class.forName("com.android.org.bouncycastle.asn1.x509.X509Name");
      Method getInstance = X509NameClass.getMethod("getInstance", Object.class);

      Hashtable defaultSymbols =
          (Hashtable) X509NameClass.getField("DefaultSymbols").get(X509NameClass);

      if (!defaultSymbols.containsKey("1.2.840.113549.1.9.1"))
        defaultSymbols.put("1.2.840.113549.1.9.1", "eMail");

      Object subjectName = getInstance.invoke(X509NameClass, encodedSubject);

      Method toString = X509NameClass.getMethod("toString", boolean.class, Hashtable.class);

      friendlyName = (String) toString.invoke(subjectName, true, defaultSymbols);

    } catch (ClassNotFoundException e) {
      exp = e;
    } catch (NoSuchMethodException e) {
      exp = e;
    } catch (InvocationTargetException e) {
      exp = e;
    } catch (IllegalAccessException e) {
      exp = e;
    } catch (NoSuchFieldException e) {
      exp = e;
    }
    if (exp != null) VpnStatus.logException("Getting X509 Name from certificate", exp);

    /* Fallback if the reflection method did not work */
    if (friendlyName == null) friendlyName = principal.getName();

    // Really evil hack to decode email address
    // See: http://code.google.com/p/android/issues/detail?id=21531

    String[] parts = friendlyName.split(",");
    for (int i = 0; i < parts.length; i++) {
      String part = parts[i];
      if (part.startsWith("1.2.840.113549.1.9.1=#16")) {
        parts[i] = "email=" + ia5decode(part.replace("1.2.840.113549.1.9.1=#16", ""));
      }
    }
    friendlyName = TextUtils.join(",", parts);
    return friendlyName;
  }
  private static boolean isValidLink(X509Certificate parent, X509Certificate child) {
    if (!parent.getSubjectX500Principal().equals(child.getIssuerX500Principal())) {
      return false;
    }

    try {
      child.verify(parent.getPublicKey());
    } catch (GeneralSecurityException gse) {
      return false;
    }

    return true;
  }
    public int compare(Object o1, Object o2) {

      X509Certificate cert1 = (X509Certificate) o1;
      X509Certificate cert2 = (X509Certificate) o2;

      /*
       * if either cert certifies the target, always
       * put at head of list.
       */
      if (cert1.getSubjectX500Principal().equals(targetSubjectDN)) {
        return -1;
      }
      if (cert2.getSubjectX500Principal().equals(targetSubjectDN)) {
        return 1;
      }

      int targetDist1;
      int targetDist2;
      try {
        X500Name targetSubjectName = X500Name.asX500Name(targetSubjectDN);
        targetDist1 = Builder.targetDistance(null, cert1, targetSubjectName);
        targetDist2 = Builder.targetDistance(null, cert2, targetSubjectName);
      } catch (IOException e) {
        if (debug != null) {
          debug.println("IOException in call to Builder.targetDistance");
          e.printStackTrace();
        }
        throw new ClassCastException("Invalid target subject distinguished name");
      }

      if (targetDist1 == targetDist2) return 0;

      if (targetDist1 == -1) return 1;

      if (targetDist1 < targetDist2) return -1;

      return 1;
    }
 /**
  * Return the subject of a certificate as X500Name, by reparsing if necessary. X500Name should
  * only be used if access to name components is required, in other cases X500Principal is to be
  * prefered.
  *
  * <p>This method is currently used from within JSSE, do not remove.
  */
 public static X500Name getSubjectX500Name(X509Certificate cert)
     throws CertificateParsingException {
   try {
     Principal subjectDN = cert.getSubjectDN();
     if (subjectDN instanceof X500Name) {
       return (X500Name) subjectDN;
     } else {
       X500Principal subjectX500 = cert.getSubjectX500Principal();
       return new X500Name(subjectX500.getEncoded());
     }
   } catch (IOException e) {
     throw (CertificateParsingException) new CertificateParsingException().initCause(e);
   }
 }
 public static String prettyPrint(X509Certificate x509) {
   if (x509 == null) throw new IllegalArgumentException("x509 cannot be null");
   return String.format(
       FORMAT,
       x509.getVersion(),
       x509.getSerialNumber(),
       x509.getSigAlgName(),
       x509.getIssuerX500Principal().getName(),
       x509.getNotBefore(),
       x509.getNotAfter(),
       x509.getSubjectX500Principal().getName(),
       x509.getPublicKey().getAlgorithm(),
       x509.getBasicConstraints(),
       x509.getSigAlgName());
 }
  /**
   * Construct a "simplified name" based on the subject DN from the certificate. The purpose is to
   * have something shorter to display in the list. The name used is one of the following DN parts,
   * if available, otherwise the complete DN: 'CN', 'OU' or else 'O'.
   *
   * @param cert to read subject DN from
   * @return the simplified name
   */
  private static String getSimplifiedName(X509Certificate cert) {
    final HashMap<String, String> parts = new HashMap<String, String>();
    try {
      for (Rdn name : new LdapName(cert.getSubjectX500Principal().getName()).getRdns()) {
        if (name.getType() != null && name.getValue() != null) {
          parts.put(name.getType(), name.getValue().toString());
        }
      }
    } catch (InvalidNameException ignored) // NOPMD
    {
    }

    String result = parts.get("CN");
    if (result == null) {
      result = parts.get("OU");
    }
    if (result == null) {
      result = parts.get("O");
    }
    if (result == null) {
      result = cert.getSubjectX500Principal().getName();
    }
    return result;
  }
 protected static void processAttrCert4(
     X509Certificate acIssuerCert, ExtendedPKIXParameters pkixParams)
     throws CertPathValidatorException {
   Set set = pkixParams.getTrustedACIssuers();
   boolean trusted = false;
   for (Iterator it = set.iterator(); it.hasNext(); ) {
     TrustAnchor anchor = (TrustAnchor) it.next();
     if (acIssuerCert.getSubjectX500Principal().getName("RFC2253").equals(anchor.getCAName())
         || acIssuerCert.equals(anchor.getTrustedCert())) {
       trusted = true;
     }
   }
   if (!trusted) {
     throw new CertPathValidatorException("Attribute certificate issuer is not directly trusted.");
   }
 }
  public void setCertificateChain(X509Certificate[] certificatesChain) {
    this.certificateChain = certificatesChain;
    DefaultListModel dlm = new DefaultListModel();
    if (certificatesChain != null) {
      for (X509Certificate cert : certificatesChain) {
        dlm.addElement(cert.getSubjectX500Principal().toString());
      }
    }

    cd.setCertificate(certificatesChain[certificateChain.length - 1]);

    certificateChainDNs.setModel(dlm);
    updateCertificateDetail();

    syncSizeToCertificateDetail();
  }
Exemple #26
0
  /**
   * Liefert den Aussteller, insofern ermittelbar.
   *
   * @return der Aussteller. Wenn es sich um ein selbstsigniertes Zertifikat handelt, liefert die
   *     Funktion NULL.
   * @throws Exception
   */
  public Entry getIssuer() throws Exception {
    if (this.issuer != null || this.issuerChecked) return this.issuer;

    this.issuerChecked = true;

    X509Certificate x = this.getCertificate();
    X500Principal issuer = x.getIssuerX500Principal();

    // brauchmer gar nicht erst anfangen zu suchen
    if (issuer == null) return null;

    // selbstsigniert
    if (issuer.equals(x.getSubjectX500Principal())) return null;

    byte[] issuerSig = x.getExtensionValue(Extension.authorityKeyIdentifier.getId());

    List<Entry> all = this.store.getEntries();
    // wenn die Signatur des Ausstellers bekannt ist, suchen wir anhand
    // der. Das ist die zuverlaessigste Methode.
    if (issuerSig != null && issuerSig.length > 0) {
      for (Entry e : all) {
        if (CHECK_CA && !e.isCA()) continue;

        // OK, wir haben die Signatur des Ausstellers. Mal schauen,
        // ob wir sie im Keystore finden.
        byte[] test = e.getCertificate().getPublicKey().getEncoded();
        if (Arrays.equals(issuerSig, test)) {
          this.issuer = e;
          return e; // gefunden
        }
      }
    }

    // Wir haben die Signatur nicht, stimmt vielleicht einen passenden DN?
    for (Entry e : all) {
      if (CHECK_CA && !e.isCA()) continue;

      X500Principal subject = e.getCertificate().getSubjectX500Principal();
      if (subject.equals(issuer)) {
        this.issuer = e;
        return e;
      }
    }

    // nichts gefunden
    return null;
  }
Exemple #27
0
 private static boolean a(X509Certificate x509certificate, X509Certificate x509certificate1)
 {
     if (!x509certificate.getSubjectX500Principal().equals(x509certificate1.getIssuerX500Principal()))
     {
         return false;
     }
     try
     {
         x509certificate1.verify(x509certificate.getPublicKey());
     }
     // Misplaced declaration of an exception variable
     catch (X509Certificate x509certificate)
     {
         return false;
     }
     return true;
 }
Exemple #28
0
  /**
   * Liefert alle Schluessel, die von diesem signiert wurden.
   *
   * @return Liste aller Schluessel, die von diesem signiert wurden. Die Funktion liefert nie NULL
   *     sondern hoechstens eine leere Liste.
   * @throws Exception
   */
  public List<Entry> getClients() throws Exception {
    if (this.clients != null) return this.clients;

    this.clients = new ArrayList<Entry>();

    if (CHECK_CA && !this.isCA()) return this.clients;

    X509Certificate x = this.getCertificate();

    byte[] sig = x.getPublicKey().getEncoded();
    X500Principal self = x.getSubjectX500Principal();

    // 2. Wir sind ein CA-Zertifikat, jetzt holen wir alle
    // Zertifikate, bei denen wir als CA eingetragen sind.
    List<Entry> all = this.store.getEntries();
    for (Entry e : all) {
      X509Certificate c = e.getCertificate();

      // sind wir selbst
      if (c.equals(x)) continue;

      // Checken, ob die Aussteller-Signatur angegeben ist
      byte[] issuerSig = x.getExtensionValue(Extension.authorityKeyIdentifier.getId());
      if (issuerSig != null && issuerSig.length > 0) {
        // Issuer-Signatur angegeben. Mal checken, ob es unsere ist
        if (Arrays.equals(issuerSig, sig)) {
          // jepp, passt
          this.clients.add(e);
          continue;
        }
      }

      // Checken, ob der DN uebereinstimmt.
      X500Principal p = c.getIssuerX500Principal();

      // passt, nehmen wir auch
      if (p != null && p.equals(self)) {
        this.clients.add(e);
        continue;
      }
    }

    Collections.sort(this.clients);
    return this.clients;
  }
 ServerHelloSSLv2(InputStream in) throws IOException {
   // Record length
   byte[] buf = new byte[2];
   CipherSuiteUtil.readFully(in, buf);
   int len = CipherSuiteUtil.dec16be(buf, 0);
   if ((len & 0x8000) == 0) {
     throw new IOException("not a SSLv2 record");
   }
   len &= 0x7FFF;
   if (len < 11) {
     throw new IOException("not a SSLv2 server hello");
   }
   buf = new byte[11];
   CipherSuiteUtil.readFully(in, buf);
   if (buf[0] != 0x04) {
     throw new IOException("not a SSLv2 server hello");
   }
   int certLen = CipherSuiteUtil.dec16be(buf, 5);
   int csLen = CipherSuiteUtil.dec16be(buf, 7);
   int connIdLen = CipherSuiteUtil.dec16be(buf, 9);
   if (len != 11 + certLen + csLen + connIdLen) {
     throw new IOException("not a SSLv2 server hello");
   }
   if (csLen == 0 || csLen % 3 != 0) {
     throw new IOException("not a SSLv2 server hello");
   }
   byte[] cert = new byte[certLen];
   CipherSuiteUtil.readFully(in, cert);
   byte[] cs = new byte[csLen];
   CipherSuiteUtil.readFully(in, cs);
   byte[] connId = new byte[connIdLen];
   CipherSuiteUtil.readFully(in, connId);
   cipherSuites = new int[csLen / 3];
   for (int i = 0, j = 0; i < csLen; i += 3, j++) {
     cipherSuites[j] = CipherSuiteUtil.dec24be(cs, i);
   }
   try {
     CertificateFactory cf = CertificateFactory.getInstance("X.509");
     X509Certificate xc = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(cert));
     serverCertName = xc.getSubjectX500Principal().toString();
     serverCertHash = CipherSuiteUtil.doSHA1(cert);
   } catch (CertificateException e) {
     // ignored
   }
 }
Exemple #30
0
    // The lint is wrong here
    @SuppressLint("StringFormatMatches")
    private String getMobileInfoString(Context c) {
      c.getPackageManager();
      String apksign = "error getting package signature";

      String version = "error getting version";
      try {
        Signature raw =
            c.getPackageManager()
                .getPackageInfo(c.getPackageName(), PackageManager.GET_SIGNATURES)
                .signatures[0];
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert =
            (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(raw.toByteArray()));
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] der = cert.getEncoded();
        md.update(der);
        byte[] digest = md.digest();

        if (Arrays.equals(digest, officalkey))
          apksign = c.getString(com.openvpn.Durai.R.string.official_build);
        else if (Arrays.equals(digest, officaldebugkey))
          apksign = c.getString(com.openvpn.Durai.R.string.debug_build);
        else if (Arrays.equals(digest, amazonkey)) apksign = "amazon version";
        else if (Arrays.equals(digest, fdroidkey)) apksign = "F-Droid built and signed version";
        else
          apksign =
              c.getString(
                  com.openvpn.Durai.R.string.built_by, cert.getSubjectX500Principal().getName());

        PackageInfo packageinfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
        version = packageinfo.versionName;

      } catch (NameNotFoundException e) {
      } catch (CertificateException e) {
      } catch (NoSuchAlgorithmException e) {
      }

      Object[] argsext = Arrays.copyOf(mArgs, mArgs.length + 2);
      argsext[argsext.length - 1] = apksign;
      argsext[argsext.length - 2] = version;

      return c.getString(com.openvpn.Durai.R.string.mobile_info_extended, argsext);
    }