コード例 #1
0
  public void testSelfSignedCert() throws Exception {
    KeyPair keyPair = createKeyPair(1024, "secret");

    // Certificate
    String email = "*****@*****.**";
    String domain = "tigase.org";
    String ou = "XMPP Service";
    String o = "Tigase.org";
    String l = "Cambourne";
    String st = "Cambridgeshire";
    String c = "UK";

    // System.out.println("Creating self-signed certificate for issuer: " + domain);

    X509Certificate cert = createSelfSignedCertificate(email, domain, ou, o, l, st, c, keyPair);

    cert.checkValidity();
    assertTrue("Checked certificate validty for today - valid", true);

    try {
      cert.checkValidity(new Date(System.currentTimeMillis() - (1000 * 3600 * 24)));
      fail("Checked certificate validty for yesterday - valid");
    } catch (CertificateNotYetValidException e) {
      assertTrue("Checked certificate validty for yesterday - not valid", true);
    }

    cert.verify(keyPair.getPublic());
    assertTrue("Verified certificate with public key - done", true);
  }
コード例 #2
0
ファイル: LDAPLoginModule.java プロジェクト: YaqubGhazi/olat
 private static boolean isCertificateValid(final X509Certificate x509Cert, final int daysFromNow) {
   try {
     x509Cert.checkValidity();
     if (daysFromNow > 0) {
       final Date nowPlusDays =
           new Date(
               System.currentTimeMillis()
                   + (new Long(daysFromNow).longValue() * 24l * 60l * 60l * 1000l));
       x509Cert.checkValidity(nowPlusDays);
     }
   } catch (final Exception e) {
     return false;
   }
   return true;
 }
コード例 #3
0
  public static X509Certificate makeV1Certificate(
      KeyPair subKP, String _subDN, KeyPair issKP, String _issDN)
      throws GeneralSecurityException, IOException, OperatorCreationException {

    PublicKey subPub = subKP.getPublic();
    PrivateKey issPriv = issKP.getPrivate();
    PublicKey issPub = issKP.getPublic();

    X509v1CertificateBuilder v1CertGen =
        new JcaX509v1CertificateBuilder(
            new X500Name(_issDN),
            allocateSerialNumber(),
            new Date(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
            new X500Name(_subDN),
            subPub);

    JcaContentSignerBuilder contentSignerBuilder = makeContentSignerBuilder(issPub);

    X509Certificate _cert =
        new JcaX509CertificateConverter()
            .setProvider("SC")
            .getCertificate(v1CertGen.build(contentSignerBuilder.build(issPriv)));

    _cert.checkValidity(new Date());
    _cert.verify(issPub);

    return _cert;
  }
コード例 #4
0
  private static X509Certificate makeCertificate(
      KeyPair subKP, String _subDN, KeyPair issKP, String _issDN)
      throws GeneralSecurityException, IOException {

    PublicKey subPub = subKP.getPublic();
    PrivateKey issPriv = issKP.getPrivate();
    PublicKey issPub = issKP.getPublic();

    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    v3CertGen.reset();
    v3CertGen.setSerialNumber(BigInteger.valueOf(1));
    v3CertGen.setIssuerDN(new X509Name(_issDN));
    v3CertGen.setNotBefore(new Date(System.currentTimeMillis()));
    v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)));
    v3CertGen.setSubjectDN(new X509Name(_subDN));
    v3CertGen.setPublicKey(subPub);

    v3CertGen.setSignatureAlgorithm("SHA1WithRSA");

    X509Certificate _cert = v3CertGen.generate(issPriv, "SunRsaSign");

    _cert.checkValidity(new Date());
    _cert.verify(issPub);

    return _cert;
  }
コード例 #5
0
  public static X509Certificate makeCertificate(
      KeyPair subKP, String _subDN, KeyPair issKP, String _issDN, boolean _ca)
      throws GeneralSecurityException, IOException, OperatorCreationException {

    PublicKey subPub = subKP.getPublic();
    PrivateKey issPriv = issKP.getPrivate();
    PublicKey issPub = issKP.getPublic();

    X509v3CertificateBuilder v3CertGen =
        new JcaX509v3CertificateBuilder(
            new X500Name(_issDN),
            allocateSerialNumber(),
            new Date(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
            new X500Name(_subDN),
            subPub);

    JcaContentSignerBuilder contentSignerBuilder = makeContentSignerBuilder(issPub);

    v3CertGen.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyId(subPub));

    v3CertGen.addExtension(Extension.authorityKeyIdentifier, false, createAuthorityKeyId(issPub));

    v3CertGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(_ca));

    X509Certificate _cert =
        new JcaX509CertificateConverter()
            .setProvider("SC")
            .getCertificate(v3CertGen.build(contentSignerBuilder.build(issPriv)));

    _cert.checkValidity(new Date());
    _cert.verify(issPub);

    return _cert;
  }
コード例 #6
0
 /*
  * mini test
  */
 public static void main(String[] args) throws Exception {
   final CAFactory caFactory = new CAFactory();
   final X509Certificate caCert =
       caFactory.create("321lfn432oifno", 24, caFactory.createNewKeyPair());
   caCert.checkValidity();
   System.out.println(caCert.getSubjectDN().toString());
 }
コード例 #7
0
  /* Cert creation engine */
  private static synchronized X509Certificate createX509V3Certificate(
      PublicKey pubKey,
      PrivateKey privKey,
      int ttlMonths,
      String issuerDN,
      String subjectDN,
      long serial,
      String signAlgoritm)
      throws GeneralSecurityException {
    X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
    certGenerator.reset();

    certGenerator.setSerialNumber(java.math.BigInteger.valueOf(serial));
    certGenerator.setIssuerDN(new org.bouncycastle.asn1.x509.X509Name(issuerDN));
    certGenerator.setNotBefore(new java.util.Date(System.currentTimeMillis()));
    certGenerator.setNotAfter(
        new java.util.Date(System.currentTimeMillis() + ttlMonths * (1000L * 60 * 60 * 24 * 30)));
    certGenerator.setSubjectDN(new org.bouncycastle.asn1.x509.X509Name(subjectDN));
    certGenerator.setPublicKey(pubKey);
    certGenerator.setSignatureAlgorithm(signAlgoritm);

    X509Certificate cert =
        certGenerator.generateX509Certificate(privKey, "BC", new java.security.SecureRandom());
    cert.checkValidity(new java.util.Date());
    cert.verify(pubKey);

    return cert;
  }
コード例 #8
0
ファイル: SSLUtil.java プロジェクト: opencadc/core
  /**
   * @param certBuf
   * @return certificate chain
   * @throws CertificateException
   * @throws IOException
   */
  public static X509Certificate[] readCertificateChain(byte[] certBuf)
      throws CertificateException, IOException {
    BufferedInputStream istream = new BufferedInputStream(new ByteArrayInputStream(certBuf));
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ArrayList<Certificate> certs = new ArrayList<Certificate>();
    while (istream.available() > 0) {
      Certificate cert = cf.generateCertificate(istream);
      // log.debug("found: " + cert);
      certs.add(cert);
    }
    istream.close();

    X509Certificate[] chain = new X509Certificate[certs.size()];
    Iterator<Certificate> i = certs.iterator();
    int c = 0;
    while (i.hasNext()) {
      X509Certificate x509 = (X509Certificate) i.next();
      chain[c++] = x509;
      try {
        x509.checkValidity();
        log.debug("X509 certificate is valid");
      } catch (CertificateExpiredException exp) {
        log.debug("X509 certificate is expired");
        // nothing to be done here
      } catch (CertificateException ex) {
        throw new RuntimeException("certificate byte array is not valid", ex);
      }
    }
    return chain;
  }
コード例 #9
0
ファイル: X509Utils.java プロジェクト: QiangNy/TestV
  public static String getCertificateValidityString(X509Certificate cert, Resources res) {
    try {
      cert.checkValidity();
    } catch (CertificateExpiredException ce) {
      return "EXPIRED: ";
    } catch (CertificateNotYetValidException cny) {
      return "NOT YET VALID: ";
    }

    Date certNotAfter = cert.getNotAfter();
    Date now = new Date();
    long timeLeft = certNotAfter.getTime() - now.getTime(); // Time left in ms

    // More than 72h left, display days
    // More than 3 months display months
    if (timeLeft > 90l * 24 * 3600 * 1000) {
      long months = getMonthsDifference(now, certNotAfter);
      return res.getString(R.string.months_left, months);
    } else if (timeLeft > 72 * 3600 * 1000) {
      long days = timeLeft / (24 * 3600 * 1000);
      return res.getString(R.string.days_left, days);
    } else {
      long hours = timeLeft / (3600 * 1000);

      return res.getString(R.string.hours_left, hours);
    }
  }
コード例 #10
0
ファイル: SSLUtil.java プロジェクト: opencadc/core
 /**
  * Checks whether the subject's certificate credentials are valid at a given date. If date is
  * missing, current time is used as reference.
  *
  * @param subject Subject to check
  * @param date Date the certificate is verified against. If null, the credentials are verified
  *     against current time.
  * @throws CertificateException Subject has no associated certificate credentials or there is a
  *     problem with the existing certificate.
  * @throws CertificateExpiredException Certificate is expired.
  * @throws CertificateNotYetValidException Certificate not valid yet.
  */
 public static void validateSubject(Subject subject, Date date)
     throws CertificateException, CertificateExpiredException, CertificateNotYetValidException {
   if (subject != null) {
     Set<X509CertificateChain> certs = subject.getPublicCredentials(X509CertificateChain.class);
     if (certs.size() == 0) {
       // subject without certs
       throw new CertificateException("No certificates associated with subject");
     }
     X509CertificateChain chain = certs.iterator().next();
     for (X509Certificate c : chain.getChain()) {
       if (date != null) {
         c.checkValidity(date);
       } else {
         c.checkValidity();
       }
     }
   }
 }
コード例 #11
0
  /**
   * verify that the given certificate successfully handles and confirms the signature associated
   * with this signer and, if a signingTime attribute is available, that the certificate was valid
   * at the time the signature was generated.
   *
   * @deprecated use verify(ContentVerifierProvider)
   */
  public boolean verify(X509Certificate cert, Provider sigProvider)
      throws NoSuchAlgorithmException, CertificateExpiredException, CertificateNotYetValidException,
          CMSException {
    Time signingTime = getSigningTime();
    if (signingTime != null) {
      cert.checkValidity(signingTime.getDate());
    }

    return doVerify(cert.getPublicKey(), sigProvider);
  }
コード例 #12
0
 /**
  * Checks the certificates in a certificate chain: are they valid on a specific date, and do they
  * chain up correctly?
  *
  * @param chain
  * @throws GeneralSecurityException
  */
 public void verifyChain(Certificate[] chain) throws GeneralSecurityException {
   // Loop over the certificates in the chain
   for (int i = 0; i < chain.length; i++) {
     X509Certificate cert = (X509Certificate) chain[i];
     // check if the certificate was/is valid
     cert.checkValidity(signDate);
     // check if the previous certificate was issued by this certificate
     if (i > 0) chain[i - 1].verify(chain[i].getPublicKey());
   }
   LOGGER.info("All certificates are valid on " + signDate.toString());
 }
コード例 #13
0
 @Test
 public void testCert() throws Exception {
   CertificateFactory certFactory = new BcCertificateFactory();
   KeyPair keyPair = KeyPairFactory.newRsa2048();
   X509Certificate cert = certFactory.newCertificate(keyPair, "study");
   String pem = PemUtils.toPem(cert);
   assertNotNull(pem);
   cert = PemUtils.loadCertificateFromPem(pem);
   cert.checkValidity();
   cert.verify(keyPair.getPublic(), BcCmsConstants.PROVIDER);
 }
コード例 #14
0
  /*
   * Returns a String to show if the certificate is valid
   */
  private String checkValidity(X509Certificate cert) {

    try {
      cert.checkValidity();
    } catch (CertificateExpiredException e) {
      return ("\r\n" + Messages.JarVerificationResult_ExpiredCertificate); // $NON-NLS-1$
    } catch (CertificateNotYetValidException e) {
      return ("\r\n" + Messages.JarVerificationResult_CertificateNotYetValid); // $NON-NLS-1$
    }
    return ("\r\n" + Messages.JarVerificationResult_CertificateValid); // $NON-NLS-1$
  }
コード例 #15
0
  /**
   * Retrieves displayable information about the certificate with the specified index in the chain.
   *
   * @param index The index of the certificate to request information on
   * @return A list of lists of {@link CertificateInformationEntry}s.
   */
  public List<List<CertificateInformationEntry>> getCertificateInfo(final int index) {
    final List<List<CertificateInformationEntry>> res =
        new ArrayList<List<CertificateInformationEntry>>();
    final X509Certificate cert = chain[index];
    List<CertificateInformationEntry> group;

    boolean tooOld = false, tooNew = false;

    try {
      cert.checkValidity();
    } catch (CertificateExpiredException ex) {
      tooOld = true;
    } catch (CertificateNotYetValidException ex) {
      tooNew = true;
    }

    group = new ArrayList<CertificateInformationEntry>();
    group.add(
        new CertificateInformationEntry(
            "Valid from", cert.getNotBefore().toString(), tooNew, false));
    group.add(
        new CertificateInformationEntry("Valid to", cert.getNotAfter().toString(), tooOld, false));
    res.add(group);

    final boolean wrongName = index == 0 && !manager.isValidHost(cert);
    final String names = getAlternateNames(cert);
    final Map<String, String> fields = CertificateManager.getDNFieldsFromCert(cert);

    group = new ArrayList<CertificateInformationEntry>();
    addCertField(fields, group, "Common name", "CN", wrongName);

    group.add(
        new CertificateInformationEntry(
            "Alternate names", names == null ? NOTPRESENT : names, wrongName, names == null));

    addCertField(fields, group, "Organisation", "O", false);
    addCertField(fields, group, "Unit", "OU", false);
    addCertField(fields, group, "Locality", "L", false);
    addCertField(fields, group, "State", "ST", false);
    addCertField(fields, group, "Country", "C", false);
    res.add(group);

    group = new ArrayList<CertificateInformationEntry>();
    group.add(
        new CertificateInformationEntry(
            "Serial number", cert.getSerialNumber().toString(), false, false));
    group.add(new CertificateInformationEntry("Algorithm", cert.getSigAlgName(), false, false));
    group.add(
        new CertificateInformationEntry(
            "SSL version", String.valueOf(cert.getVersion()), false, false));
    res.add(group);

    return res;
  }
コード例 #16
0
ファイル: CertValidity.java プロジェクト: pankajkh/javafirma
  /**
   * Return true if the certificate is active<br>
   * <br>
   * Restituisce true se il certificato è ancora attivo
   *
   * @return true: if the certificate is active
   */
  public boolean getInUse() {
    try {
      cert.checkValidity();
      isInUse = true;
      isExpired = false;
    } catch (CertificateNotYetValidException ex) {
      isInUse = false;
    } catch (CertificateExpiredException ex) {
      isExpired = true;
    }

    return isInUse;
  }
コード例 #17
0
 /** Helper method, which extracts a valid X509 certificate for an end point. */
 private X509Certificate getX509CertificateFromEndpointType(EndpointType endpointType) {
   try {
     String body = endpointType.getCertificate();
     String endpointCertificate =
         "-----BEGIN CERTIFICATE-----\n" + body + "\n-----END CERTIFICATE-----";
     CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
     X509Certificate cert =
         (X509Certificate)
             certificateFactory.generateCertificate(
                 new ByteArrayInputStream(endpointCertificate.getBytes()));
     cert.checkValidity();
     return cert;
   } catch (CertificateException e) {
     throw new RuntimeException("Failed to get valid certificate from Endpoint data", e);
   }
 }
コード例 #18
0
ファイル: HTTPSession.java プロジェクト: msdsoftware/thredds
 @Override
 public boolean isTrusted(final X509Certificate[] chain, String authType)
     throws CertificateException {
   try {
     if (super.isTrusted(chain, authType)) return true;
     // check expiration dates
     for (X509Certificate x5 : chain) {
       try {
         x5.checkValidity();
       } catch (CertificateExpiredException | CertificateNotYetValidException ce) {
         return true;
       }
     }
   } catch (CertificateException e) {
     return true; // temporary
   }
   return false;
 }
コード例 #19
0
  @Test
  public void testTrustStore()
      throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
    File caPem = getTempFile("ca/cert.pem");
    KeyStore keystore = createKeyStore();

    KeyStoreUtil.updateWithCaPem(keystore, caPem);

    Enumeration<String> aliases = keystore.aliases();
    String alias = aliases.nextElement();
    assertFalse(aliases.hasMoreElements());
    assertTrue(alias.contains("ca.test.jolokia.org"));
    X509Certificate cert = (X509Certificate) keystore.getCertificate(alias);
    cert.checkValidity();
    assertTrue(cert.getSubjectDN().getName().contains(CA_CERT_SUBJECT_DN_CN));
    RSAPublicKey key = (RSAPublicKey) cert.getPublicKey();
    assertEquals(key.getAlgorithm(), "RSA");
  }
コード例 #20
0
  private void validateCert(Certificate cert, boolean chainPresent) {

    if (!(cert instanceof X509Certificate))
      throw new IllegalArgumentException("Invalid certificate format. Expected X509 certificate");

    try {
      ((X509Certificate) cert).checkValidity();
    } catch (Exception e) {
      throw new IllegalArgumentException("Certificate expired or not valid", e);
    }

    if (!chainPresent) {
      PublicKey pubKey = cert.getPublicKey();
      try {
        cert.verify(pubKey);
      } catch (Exception e) {
        throw new IllegalArgumentException("No chain given and certificate not self signed", e);
      }
    }
  }
コード例 #21
0
ファイル: KeyStoreUtil.java プロジェクト: Juiceman/i2p.i2p
 /**
  * Load an X509 Cert from a file and add it to the trusted set of certificates in the key store
  *
  * @return success
  * @since 0.8.2, moved from SSLEepGet in 0.9.9
  */
 public static boolean addCert(File file, String alias, KeyStore ks) {
   InputStream fis = null;
   try {
     fis = new FileInputStream(file);
     CertificateFactory cf = CertificateFactory.getInstance("X.509");
     X509Certificate cert = (X509Certificate) cf.generateCertificate(fis);
     info(
         "Read X509 Certificate from "
             + file.getAbsolutePath()
             + " Issuer: "
             + cert.getIssuerX500Principal()
             + "; Valid From: "
             + cert.getNotBefore()
             + " To: "
             + cert.getNotAfter());
     try {
       cert.checkValidity();
     } catch (CertificateExpiredException cee) {
       error("Rejecting expired X509 Certificate: " + file.getAbsolutePath(), cee);
       return false;
     } catch (CertificateNotYetValidException cnyve) {
       error("Rejecting X509 Certificate not yet valid: " + file.getAbsolutePath(), cnyve);
       return false;
     }
     ks.setCertificateEntry(alias, cert);
     info("Now trusting X509 Certificate, Issuer: " + cert.getIssuerX500Principal());
   } catch (GeneralSecurityException gse) {
     error("Error reading X509 Certificate: " + file.getAbsolutePath(), gse);
     return false;
   } catch (IOException ioe) {
     error("Error reading X509 Certificate: " + file.getAbsolutePath(), ioe);
     return false;
   } finally {
     try {
       if (fis != null) fis.close();
     } catch (IOException foo) {
     }
   }
   return true;
 }
コード例 #22
0
ファイル: JettySSLService.java プロジェクト: raapadma/knox
  private void logAndValidateCertificate() throws ServiceLifecycleException {
    // let's log the hostname (CN) and cert expiry from the gateway's public cert to aid in SSL
    // debugging
    Certificate cert;
    try {
      cert = as.getCertificateForGateway("gateway-identity");
    } catch (AliasServiceException e) {
      throw new ServiceLifecycleException(
          "Cannot Retreive Gateway SSL Certificate. Server will not start.", e);
    }
    if (cert != null) {
      if (cert instanceof X509Certificate) {
        X500Principal x500Principal = ((X509Certificate) cert).getSubjectX500Principal();
        X500PrincipalParser parser = new X500PrincipalParser(x500Principal);
        log.certificateHostNameForGateway(parser.getCN());
        Date notBefore = ((X509Certificate) cert).getNotBefore();
        Date notAfter = ((X509Certificate) cert).getNotAfter();
        log.certificateValidityPeriod(notBefore, notAfter);

        // let's not even start if the current date is not within the validity period for the SSL
        // cert
        try {
          ((X509Certificate) cert).checkValidity();
        } catch (CertificateExpiredException e) {
          throw new ServiceLifecycleException(
              "Gateway SSL Certificate is Expired. Server will not start.", e);
        } catch (CertificateNotYetValidException e) {
          throw new ServiceLifecycleException(
              "Gateway SSL Certificate is not yet valid. Server will not start.", e);
        }
      } else {
        throw new ServiceLifecycleException(
            "Public certificate for the gateway cannot be found with the alias gateway-identity. Plase check the identity certificate alias.");
      }
    } else {
      throw new ServiceLifecycleException(
          "Public certificate for the gateway is not of the expected type of X509Certificate. Something is wrong with the gateway keystore.");
    }
  }
コード例 #23
0
  @Test
  public void testKeyStore()
      throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException,
          InvalidKeySpecException, UnrecoverableKeyException {
    File serverPem = getTempFile("server/cert.pem");
    File keyPem = getTempFile("server/key.pem");
    KeyStore keystore = createKeyStore();

    KeyStoreUtil.updateWithServerPems(keystore, serverPem, keyPem, "RSA", new char[0]);

    Enumeration<String> aliases = keystore.aliases();
    String alias = aliases.nextElement();
    assertFalse(aliases.hasMoreElements());

    assertTrue(alias.contains("server"));

    X509Certificate cert = (X509Certificate) keystore.getCertificate(alias);
    cert.checkValidity();
    assertEquals(cert.getSubjectDN().getName(), SERVER_CERT_SUBJECT_DN);
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) keystore.getKey(alias, new char[0]);
    assertEquals("RSA", key.getAlgorithm());
    RSAPublicKey pubKey = (RSAPublicKey) cert.getPublicKey();
    assertEquals("RSA", pubKey.getAlgorithm());
  }
コード例 #24
0
  /**
   * Retrieves the certificate chain that's under question.
   *
   * @return A list of {@link CertificateChainEntry}s corresponding to the certificate chain being
   *     questioned.
   */
  public List<CertificateChainEntry> getCertificateChain() {
    final List<CertificateChainEntry> res = new ArrayList<CertificateChainEntry>();

    boolean first = true;

    for (X509Certificate cert : chain) {
      boolean invalid = first && !manager.isValidHost(cert);
      first = false;

      try {
        cert.checkValidity();
      } catch (CertificateException ex) {
        invalid |= true;
      }

      res.add(
          new CertificateChainEntry(
              CertificateManager.getDNFieldsFromCert(cert).get("CN"),
              manager.isTrusted(cert).isTrusted(),
              invalid));
    }

    return res;
  }
コード例 #25
0
ファイル: X509Download.java プロジェクト: sosilent/euca
  private static byte[] getX509Zip(User u) throws Exception {
    X509Certificate cloudCert = null;
    final X509Certificate x509;
    String userAccessKey = null;
    String userSecretKey = null;
    KeyPair keyPair = null;
    try {
      for (AccessKey k : u.getKeys()) {
        if (k.isActive()) {
          userAccessKey = k.getAccessKey();
          userSecretKey = k.getSecretKey();
        }
      }
      if (userAccessKey == null) {
        AccessKey k = u.createKey();
        userAccessKey = k.getAccessKey();
        userSecretKey = k.getSecretKey();
      }
      keyPair = Certs.generateKeyPair();
      x509 = Certs.generateCertificate(keyPair, u.getName());
      x509.checkValidity();
      u.addCertificate(x509);
      cloudCert = SystemCredentials.lookup(Eucalyptus.class).getCertificate();
    } catch (Exception e) {
      LOG.fatal(e, e);
      throw e;
    }
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(byteOut);
    ZipArchiveEntry entry = null;
    String fingerPrint = Certs.getFingerPrint(keyPair.getPublic());
    if (fingerPrint != null) {
      String baseName =
          X509Download.NAME_SHORT
              + "-"
              + u.getName()
              + "-"
              + fingerPrint.replaceAll(":", "").toLowerCase().substring(0, 8);

      zipOut.setComment("To setup the environment run: source /path/to/eucarc");
      StringBuilder sb = new StringBuilder();
      // TODO:GRZE:FIXME velocity
      String userNumber = u.getAccount().getAccountNumber();
      sb.append("EUCA_KEY_DIR=$(dirname $(readlink -f ${BASH_SOURCE}))");
      if (Topology.isEnabled(Eucalyptus.class)) { // GRZE:NOTE: this is temporary
        sb.append(
            "\nexport EC2_URL=" + ServiceUris.remotePublicify(Topology.lookup(Eucalyptus.class)));
      } else {
        sb.append("\necho WARN:  Eucalyptus URL is not configured. >&2");
        ServiceBuilder<? extends ServiceConfiguration> builder =
            ServiceBuilders.lookup(Eucalyptus.class);
        ServiceConfiguration localConfig =
            builder.newInstance(
                Internets.localHostAddress(),
                Internets.localHostAddress(),
                Internets.localHostAddress(),
                Eucalyptus.INSTANCE.getPort());
        sb.append("\nexport EC2_URL=" + ServiceUris.remotePublicify(localConfig));
      }
      if (Topology.isEnabled(Walrus.class)) {
        ServiceConfiguration walrusConfig = Topology.lookup(Walrus.class);
        try {
          String uri = ServiceUris.remotePublicify(walrusConfig).toASCIIString();
          LOG.debug("Found walrus uri/configuration: uri=" + uri + " config=" + walrusConfig);
          sb.append("\nexport S3_URL=" + uri);
        } catch (Exception e) {
          LOG.error("Failed to set Walrus URL: " + walrusConfig, e);
        }
      } else {
        sb.append("\necho WARN:  Walrus URL is not configured. >&2");
      }
      // Disable notifications for now
      // sb.append( "\nexport AWS_SNS_URL=" + ServiceUris.remote( Notifications.class ) );
      if (Topology.isEnabled(Euare.class)) { // GRZE:NOTE: this is temporary
        sb.append("\nexport EUARE_URL=" + ServiceUris.remotePublicify(Euare.class));
      } else {
        sb.append("\necho WARN:  EUARE URL is not configured. >&2");
      }
      sb.append("\nexport EC2_PRIVATE_KEY=${EUCA_KEY_DIR}/" + baseName + "-pk.pem");
      sb.append("\nexport EC2_CERT=${EUCA_KEY_DIR}/" + baseName + "-cert.pem");
      sb.append("\nexport EC2_JVM_ARGS=-Djavax.net.ssl.trustStore=${EUCA_KEY_DIR}/jssecacerts");
      sb.append("\nexport EUCALYPTUS_CERT=${EUCA_KEY_DIR}/cloud-cert.pem");
      sb.append("\nexport EC2_ACCOUNT_NUMBER='" + u.getAccount().getAccountNumber() + "'");
      sb.append("\nexport EC2_ACCESS_KEY='" + userAccessKey + "'");
      sb.append("\nexport EC2_SECRET_KEY='" + userSecretKey + "'");
      sb.append("\nexport AWS_CREDENTIAL_FILE=${EUCA_KEY_DIR}/iamrc");
      sb.append("\nexport EC2_USER_ID='" + userNumber + "'");
      sb.append(
          "\nalias ec2-bundle-image=\"ec2-bundle-image --cert ${EC2_CERT} --privatekey ${EC2_PRIVATE_KEY} --user ${EC2_ACCOUNT_NUMBER} --ec2cert ${EUCALYPTUS_CERT}\"");
      sb.append(
          "\nalias ec2-upload-bundle=\"ec2-upload-bundle -a ${EC2_ACCESS_KEY} -s ${EC2_SECRET_KEY} --url ${S3_URL}\"");
      sb.append("\n");
      zipOut.putArchiveEntry(entry = new ZipArchiveEntry("eucarc"));
      entry.setUnixMode(0600);
      zipOut.write(sb.toString().getBytes("UTF-8"));
      zipOut.closeArchiveEntry();

      sb = new StringBuilder();
      sb.append("AWSAccessKeyId=").append(userAccessKey).append('\n');
      sb.append("AWSSecretKey=").append(userSecretKey);
      zipOut.putArchiveEntry(entry = new ZipArchiveEntry("iamrc"));
      entry.setUnixMode(0600);
      zipOut.write(sb.toString().getBytes("UTF-8"));
      zipOut.closeArchiveEntry();

      /** write the private key to the zip stream * */
      zipOut.putArchiveEntry(entry = new ZipArchiveEntry("cloud-cert.pem"));
      entry.setUnixMode(0600);
      zipOut.write(PEMFiles.getBytes(cloudCert));
      zipOut.closeArchiveEntry();

      zipOut.putArchiveEntry(entry = new ZipArchiveEntry("jssecacerts"));
      entry.setUnixMode(0600);
      KeyStore tempKs = KeyStore.getInstance("jks");
      tempKs.load(null);
      tempKs.setCertificateEntry("eucalyptus", cloudCert);
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      tempKs.store(bos, "changeit".toCharArray());
      zipOut.write(bos.toByteArray());
      zipOut.closeArchiveEntry();

      /** write the private key to the zip stream * */
      zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-pk.pem"));
      entry.setUnixMode(0600);
      zipOut.write(PEMFiles.getBytes(keyPair.getPrivate()));
      zipOut.closeArchiveEntry();

      /** write the X509 certificate to the zip stream * */
      zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-cert.pem"));
      entry.setUnixMode(0600);
      zipOut.write(PEMFiles.getBytes(x509));
      zipOut.closeArchiveEntry();
    }
    /** close the zip output stream and return the bytes * */
    zipOut.close();
    return byteOut.toByteArray();
  }
コード例 #26
0
  /** {@inheritDoc} */
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    HttpServletRequest rqst = (HttpServletRequest) request;
    HttpServletResponse rsp = (HttpServletResponse) response;

    if (LOG.isDebugEnabled()) {
      StringBuilder b =
          new StringBuilder("Request from ")
              .append(rqst.getRemoteHost())
              .append("/")
              .append(rqst.getRemoteAddr())
              .append(":")
              .append(rqst.getRemotePort());

      @SuppressWarnings("unchecked")
      Enumeration<String> e = rqst.getAttributeNames();
      for (; e.hasMoreElements(); ) {
        String attribute = e.nextElement();
        b.append("\n  " + attribute + " => " + rqst.getAttribute(attribute));
      }

      X509Certificate[] userCerts =
          (X509Certificate[]) rqst.getAttribute("javax.servlet.request.X509Certificate");
      if (userCerts != null)
        for (X509Certificate cert : userCerts)
          b.append(
              "\n Client certificate Subject Name is " + cert.getSubjectX500Principal().getName());

      b.append("\n The Scheme is " + rqst.getScheme());
      b.append("\n The Auth Type is " + rqst.getAuthType());
      b.append("\n The Path Info is " + rqst.getPathInfo());
      b.append("\n The Translated Path Info is " + rqst.getPathTranslated());
      b.append("\n The Context Path is " + rqst.getContextPath());
      b.append("\n The Query String is " + rqst.getQueryString());
      b.append("\n The Remote User is " + rqst.getRemoteUser());
      b.append("\n The User Principal is " + rqst.getUserPrincipal());
      b.append("\n The Request URI is " + rqst.getRequestURI());
      b.append("\n The Request URL is " + rqst.getRequestURL());
      b.append("\n The Servlet Path is " + rqst.getServletPath());

      LOG.debug(b.toString());
    }

    if (rqst.getScheme().equalsIgnoreCase("https")) {
      boolean isAuthorized = false;
      X509Certificate[] certs =
          (X509Certificate[]) rqst.getAttribute("javax.servlet.request.X509Certificate");
      if (certs == null || certs.length == 0) {
        rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No client SSL certificate received");
        return;
      }
      for (X509Certificate cert : certs) {
        try {
          cert.checkValidity();
        } catch (CertificateExpiredException e) {
          LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " expired");
          rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate expired");
          return;
        } catch (CertificateNotYetValidException e) {
          LOG.info(
              "Received cert for "
                  + cert.getSubjectX500Principal().getName()
                  + " is not yet valid");
          rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate is not yet valid");
          return;
        }
      }

      String[] tokens = certs[0].getSubjectX500Principal().getName().split("\\s*,\\s*");
      String userID = null;
      for (String s : tokens) {
        if (s.startsWith("CN=")) {
          userID = s;
          break;
        }
      }
      if (userID == null || userID.length() < 4) {
        LOG.info("Can't retrieve user ID from SSL certificate");
        rsp.sendError(
            HttpServletResponse.SC_FORBIDDEN, "Can't retrieve user ID from SSL certificate");
        return;
      }
      userID = userID.substring(3);

      String servletPath = rqst.getServletPath();
      if (HFTP_PATTERN.matcher(servletPath).matches()) {
        // request is an HSFTP request
        if (FILEPATH_PATTERN.matcher(servletPath).matches()) {
          // file path as part of the URL
          isAuthorized =
              checkPath(userID, certs[0], rqst.getPathInfo() != null ? rqst.getPathInfo() : "/");
        } else {
          // file path is stored in "filename" parameter
          isAuthorized = checkPath(userID, certs[0], rqst.getParameter("filename"));
        }
      } else if (RELOAD_PATTERN.matcher(servletPath).matches() && checkUser("Admin", certs[0])) {
        Configuration conf = new Configuration(false);
        conf.addResource("hdfsproxy-default.xml");
        Map<String, Set<Path>> permsMap = getPermMap(conf);
        Map<String, Set<BigInteger>> certsMap = getCertsMap(conf);
        if (permsMap == null || certsMap == null) {
          LOG.warn("Permission files reloading failed");
          rsp.sendError(
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Permission files reloading failed");
          return;
        }
        ProxyFilter.permsMap = permsMap;
        ProxyFilter.certsMap = certsMap;
        LOG.info("User permissions and user certs files reloaded");
        rsp.setStatus(HttpServletResponse.SC_OK);
        return;
      } else if (CLEAR_PATTERN.matcher(servletPath).matches() && checkUser("Admin", certs[0])) {
        ProxyUgiManager.clearCache();
        LOG.info("Ugi cache cleared");
        rsp.setStatus(HttpServletResponse.SC_OK);
        return;
      }

      if (!isAuthorized) {
        rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized access");
        return;
      }
      // request is authorized, set ugi for servlets
      UnixUserGroupInformation ugi = ProxyUgiManager.getUgiForUser(userID);
      if (ugi == null) {
        LOG.info("Can't retrieve ugi for user " + userID);
        rsp.sendError(
            HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Can't retrieve ugi for user " + userID);
        return;
      }
      rqst.setAttribute("authorized.ugi", ugi);
    } else { // http request, set ugi for servlets, only for testing purposes
      String ugi = rqst.getParameter("ugi");
      rqst.setAttribute("authorized.ugi", new UnixUserGroupInformation(ugi.split(",")));
    }

    chain.doFilter(request, response);
  }