Example #1
0
  private X509Certificate createAll(int index) throws GeneralSecurityException, IOException {
    logger.info("Generating CA key pair");
    KeyPair ca = CertUtil.generateKeyPair(CA_CERT_ALGORITHM, CA_CERT_BITS);
    OpenSSLKey caKey = new BouncyCastleOpenSSLKey(ca.getPrivate());
    logger.info("Self-signing CA certificate");
    X509Certificate caCert = genCert(ca.getPrivate(), ca.getPublic(), CA_CERT_DN, CA_CERT_DN, null);

    logger.info("Generating user key pair");
    KeyPair user = CertUtil.generateKeyPair(CA_CERT_ALGORITHM, CA_CERT_BITS);
    OpenSSLKey userKey = new BouncyCastleOpenSSLKey(user.getPrivate());
    logger.info("Signing user certificate");
    X509Certificate userCert =
        genCert(
            ca.getPrivate(),
            user.getPublic(),
            USER_CERT_DN,
            CA_CERT_DN,
            createExtensions(ca.getPublic(), user.getPublic()));
    logger.info("Generating proxy certificate");
    GlobusCredential proxy = makeProxy(user, userCert);

    try {
      logger.info("Writing keys, certificates, and proxy");
      writeKey(caKey, makeFile(CA_KEY_NAME_PREFIX, index));
      writeCert(caCert, makeFile(CA_CRT_NAME_PREFIX, index));
      writeKey(userKey, makeFile(USER_KEY_NAME_PREFIX, index));
      writeCert(userCert, makeFile(USER_CRT_NAME_PREFIX, index));
      writeProxy(proxy, makeFile(PROXY_NAME_PREFIX, index));
      copySigningPolicy(index);
    } catch (GeneralSecurityException e) {
      deleteAll(index);
      throw e;
    }
    return cert;
  }
  /**
   * Tests authentication for failure.
   *
   * @throws Exception if the test fails.
   */
  @Test
  @Ignore
  public void testAuthenticateForFailure() throws Exception {

    // no certificate
    try {
      OpenSSLKey key =
          new BouncyCastleOpenSSLKey(
              getClass().getResourceAsStream(AuthenticationTestConstants.USERKEY_RCE_ENGINEER_PEM));
      authService.authenticate(null, key, AuthenticationTestConstants.PASSWORD_RCE_ENEMY);
      fail();

    } catch (IllegalArgumentException e) {
      assertTrue(true);
    }

    // no private key
    try {
      X509Certificate certificate =
          CertUtil.loadCertificate(
              getClass()
                  .getResourceAsStream(AuthenticationTestConstants.USERCERT_RCE_ENGINEER_PEM));

      authService.authenticate(certificate, null, AuthenticationTestConstants.PASSWORD_RCE_ENEMY);

      fail();
    } catch (IllegalArgumentException e) {
      assertTrue(true);
    }
  }
  /**
   * Tests getting a CertificateUser for success.
   *
   * @throws Exception if the test fails.
   */
  @Test
  public void testGetCertificateUserForSuccess() throws Exception {

    X509Certificate certificate =
        CertUtil.loadCertificate(
            getClass().getResourceAsStream(AuthenticationTestConstants.USERCERT_RCE_ENGINEER_PEM));
    User certificateUser = authService.createUser(certificate, validityInDays);

    assertTrue(certificateUser.isValid());
  }
  protected void getClientPublicKey(byte[] clpubkey) throws Exception {
    DERObject obj = BouncyCastleUtil.toDERObject(clpubkey);
    byte[] pubkey = BouncyCastleUtil.toByteArray(obj);
    ByteArrayInputStream in = new ByteArrayInputStream(pubkey);
    X509Certificate cert = CertUtil.loadCertificate(in);

    SCUtil.pathValidation(cert, trustedCerts);
    logger.finest("path validated !!!");

    clPubkey = cert.getPublicKey();
  }
Example #5
0
 private void writeCert(X509Certificate cert, File f) throws GeneralSecurityException {
   try {
     OutputStream fw = openStream(f);
     if (!SHARED_PROXIES) {
       f.deleteOnExit();
     }
     CertUtil.writeCertificate(fw, cert);
   } catch (Exception e) {
     throw new GeneralSecurityException("Failed to save X509 certificate", e);
   }
 }
Example #6
0
  private GlobusCredential makeProxy(KeyPair kp, X509Certificate issuerCert)
      throws GeneralSecurityException {
    BouncyCastleCertProcessingFactory factory = BouncyCastleCertProcessingFactory.getDefault();
    KeyPair newKeyPair = CertUtil.generateKeyPair(CA_CERT_ALGORITHM, CA_CERT_BITS);

    return factory.createCredential(
        new X509Certificate[] {issuerCert},
        kp.getPrivate(),
        CA_CERT_BITS,
        (int) (CA_CERT_LIFETIME / 1000),
        GSIConstants.DELEGATION_FULL,
        (X509ExtensionSet) null);
  }
  /**
   * Tests authentication for success.
   *
   * <p>Tests fail due to expired test certificates. As the code is currently not used and probably
   * won't be used in the future, the tests are ignored to reduce the maintenance effort. The
   * related methods in are deprecated.
   *
   * @throws Exception in error
   */
  @Test
  @Ignore
  public void testAuthenticateForSuccess() throws Exception {

    X509Certificate certificate =
        CertUtil.loadCertificate(
            getClass().getResourceAsStream(AuthenticationTestConstants.USERCERT_RCE_ENGINEER_PEM));
    OpenSSLKey key =
        new BouncyCastleOpenSSLKey(
            getClass().getResourceAsStream(AuthenticationTestConstants.USERKEY_RCE_ENGINEER_PEM));

    X509AuthenticationResult result =
        authService.authenticate(
            certificate, key, AuthenticationTestConstants.PASSWORD_RCE_ENGINEER);
    assertEquals(X509AuthenticationResult.AUTHENTICATED, result);
  }
  /**
   * Creates an X509 version3 certificate
   *
   * @param algorithm (e.g RSA, DSA, etc...)
   * @param bits Cet strength e.g 1024
   * @param issuer Issuer string e.g "O=Grid,OU=OGSA,CN=ACME"
   * @param subject Subject string e.g "O=Grid,OU=OGSA,CN=John Doe"
   * @param months time to live
   * @param outPrivKey OutputStream to the private key in PKCS#8 format (Note: this key will not be
   *     encrypted)
   * @return X509 V3 Certificate
   * @throws GeneralSecurityException
   */
  public static X509Certificate createX509Cert(
      String algorithm,
      int bits,
      String issuer,
      String subject,
      int months,
      OutputStream outPrivKey,
      String sigAlg,
      String pwd)
      throws GeneralSecurityException, IOException {
    // String sigAlg = "SHA1WithRSAEncryption";

    // Priv key is in PKCS#8 format
    KeyPair kp = CertUtil.generateKeyPair(algorithm, bits);

    // must convert from PKCS#8 to PKCS#1 to encrypt with BouncyCastleOpenSSLKey
    // Priv key must be DER encoded key data in PKCS#1 format to be encrypted.
    OpenSSLKey PKCS_8key = new BouncyCastleOpenSSLKey(kp.getPrivate());

    long serial = 0;

    logger.debug(
        "createX509Cert Alg: "
            + algorithm
            + " bits:"
            + bits
            + " Issuer: "
            + issuer
            + " Subject: "
            + subject);
    logger.debug(
        "createX509Cert Sig alg:"
            + sigAlg
            + " Priv key format:"
            + PKCS_8key.getPrivateKey().getFormat());

    // if ( pwd != null && ! PKCS_8key.isEncrypted())
    //	PKCS_8key.encrypt(pwd);

    // write private key
    PKCS_8key.writeTo(outPrivKey);

    // return X509 Cert
    return createX509V3Certificate(
        kp.getPublic(), kp.getPrivate(), months, issuer, subject, serial, sigAlg);
  }
  /**
   * Tests authentication for failure.
   *
   * <p>Tests fail due to expired test certificates. As the code is currently not used and probably
   * won't be used in the future, the tests are ignored to reduce the maintenance effort. The
   * related methods in are deprecated.
   *
   * @throws Exception on error
   */
  @Test
  @Ignore
  public void testAuthenticateForSanity() throws Exception {

    // incorrect password

    X509Certificate certificate =
        CertUtil.loadCertificate(
            getClass().getResourceAsStream(AuthenticationTestConstants.USERCERT_RCE_ENGINEER_PEM));
    OpenSSLKey key =
        new BouncyCastleOpenSSLKey(
            getClass().getResourceAsStream(AuthenticationTestConstants.USERKEY_RCE_ENGINEER_PEM));

    X509AuthenticationResult result =
        authService.authenticate(certificate, key, AuthenticationTestConstants.PASSWORD_RCE_ENEMY);
    assertEquals(X509AuthenticationResult.PASSWORD_INCORRECT, result);

    // private and public key do not belong together

    certificate =
        CertUtil.loadCertificate(
            getClass().getResourceAsStream(AuthenticationTestConstants.USERCERT_RCE_ENGINEER_PEM));
    key =
        new BouncyCastleOpenSSLKey(
            getClass().getResourceAsStream(AuthenticationTestConstants.KEY_RCE_ENEMY_PEM));

    result =
        authService.authenticate(certificate, key, AuthenticationTestConstants.PASSWORD_RCE_ENEMY);
    assertEquals(X509AuthenticationResult.PRIVATE_KEY_NOT_BELONGS_TO_PUBLIC_KEY, result);

    // not signed by trusted CA

    certificate =
        CertUtil.loadCertificate(
            getClass().getResourceAsStream(AuthenticationTestConstants.CERT_UNKNOWN_USER_PEM));
    key =
        new BouncyCastleOpenSSLKey(
            getClass().getResourceAsStream(AuthenticationTestConstants.KEY_UNKNOWN_USER_PEM));

    result =
        authService.authenticate(
            certificate, key, AuthenticationTestConstants.PASSWORD_UNKNOWN_USER);
    assertEquals(X509AuthenticationResult.NOT_SIGNED_BY_TRUSTED_CA, result);

    // revoked

    certificate =
        CertUtil.loadCertificate(
            getClass().getResourceAsStream(AuthenticationTestConstants.CERT_RCE_ENEMY_PEM));
    key =
        new BouncyCastleOpenSSLKey(
            getClass().getResourceAsStream(AuthenticationTestConstants.KEY_RCE_ENEMY_PEM));

    result =
        authService.authenticate(certificate, key, AuthenticationTestConstants.PASSWORD_RCE_ENEMY);
    assertEquals(X509AuthenticationResult.CERTIFICATE_REVOKED, result);

    // no password, but encrypted key

    certificate =
        CertUtil.loadCertificate(
            getClass().getResourceAsStream(AuthenticationTestConstants.USERCERT_RCE_ENGINEER_PEM));
    key =
        new BouncyCastleOpenSSLKey(
            getClass().getResourceAsStream(AuthenticationTestConstants.USERKEY_RCE_ENGINEER_PEM));

    result = authService.authenticate(certificate, key, null);
    assertEquals(X509AuthenticationResult.PASSWORD_REQUIRED, result);
  }
Example #10
0
  private void ensureCACertsExist() throws IOException, GeneralSecurityException {
    // delete expired CAs, make a new one if the existing ones don't have
    // at least MIN_CA_LIFETIME_LEFT
    Object fl = lockDir(CA_DIR);

    try {
      File[] certs = discoverProxies();
      if (certs == null) {
        throw new IOException("Failed to list files in CA directory (" + CA_DIR + ")");
      }
      long now = System.currentTimeMillis();
      long maxExpirationTime = 0;

      for (File c : certs) {
        if (logger.isInfoEnabled()) {
          logger.info("Checking certificate " + c);
        }
        try {
          X509Certificate cert = CertUtil.loadCertificate(c.getAbsolutePath());
          long certExpirationTime = cert.getNotAfter().getTime();
          if (certExpirationTime < now) {
            // delete cert and key
            if (logger.isInfoEnabled()) {
              logger.info("Certificate expired. Deleting.");
            }
            deleteAll(getIndex(c));
          }
          if (certExpirationTime > maxExpirationTime) {
            maxExpirationTime = certExpirationTime;
            int index = getIndex(c);
            this.info =
                new Info(makeFile(PROXY_NAME_PREFIX, index), makeFile(CA_CRT_NAME_PREFIX, index));
            this.cert = cert;
          }
        } catch (Exception e) {
          logger.info("Failed to check " + c + ". Ignoring.", e);
        }
      }

      if (now + MIN_CA_CERT_LIFETIME_LEFT > maxExpirationTime || !SHARED_PROXIES) {
        int index;
        boolean create;
        if (this.localBundleIndex == -1) {
          index = discoverNextIndex();
          this.localBundleIndex = index;
          create = true;
        } else {
          index = this.localBundleIndex;
          create = false;
        }
        this.info =
            new Info(makeFile(PROXY_NAME_PREFIX, index), makeFile(CA_CRT_NAME_PREFIX, index));
        if (create) {
          if (logger.isInfoEnabled()) {
            if (!SHARED_PROXIES) {
              logger.info(
                  "Shared proxies are disabled. Creating new certificate: " + info.proxyPath);
            } else {
              logger.info(
                  "No certificates with enough lifetime. Creating new certificate: "
                      + info.proxyPath);
            }
          }
          this.cert = createAll(index);
        } else {
          if (logger.isInfoEnabled()) {
            logger.info("Using local JVM certificate " + this.info.proxyPath);
          }
          this.cert = CertUtil.loadCertificate(this.info.caCertPath);
        }
      } else {
        if (logger.isInfoEnabled()) {
          logger.info(
              "Using certificate "
                  + info.proxyPath
                  + " with expiration date "
                  + this.cert.getNotAfter());
        }
      }
    } finally {
      unlock(fl);
    }
  }
Example #11
0
  /** Generates a encrypted private key and certificate request. */
  public static void genCertificateRequest(
      String dname,
      String emailAddressOfCA,
      String password,
      String privKeyLoc,
      String certLoc,
      String certReqLoc)
      throws Exception {

    String sigAlgName = "MD5WithRSA";
    String keyAlgName = "RSA";

    CertUtil.init();

    // Generate a new key pair.
    KeyPairGenerator keygen = KeyPairGenerator.getInstance(keyAlgName);
    KeyPair keyPair = keygen.genKeyPair();
    PrivateKey privKey = keyPair.getPrivate();
    PublicKey pubKey = keyPair.getPublic();

    // Generate the certificate request.
    X509Name name = new X509Name(dname);
    DERConstructedSet derSet = new DERConstructedSet();
    PKCS10CertificationRequest request =
        new PKCS10CertificationRequest(sigAlgName, name, pubKey, derSet, privKey);

    // Save the certificate request to a .pem file.
    byte[] data = request.getEncoded();
    PrintStream ps = new PrintStream(new FileOutputStream(certReqLoc));

    // build / delimited name.
    String certSubject = "";
    StringTokenizer tokens = new StringTokenizer(dname, ",");
    while (tokens.hasMoreTokens()) {
      certSubject = certSubject + "/" + tokens.nextToken();
    }

    /*        ps.print( "\n\n"
    + "Please mail the following certificate request to " + emailAddressOfCA + "\n"
    + "\n"
    + "==================================================================\n"
    + "\n"
    + "Certificate Subject:\n"
    + "\n"
    + certSubject
    + "\n"
    + "\n"
    + "The above string is known as your user certificate subject, and it \n"
    + "uniquely identifies this user.\n"
    + "\n"
    + "To install this user certificate, please save this e-mail message\n"
    + "into the following file.\n"
    + "\n"
    + "\n"
    + certLoc
    + "\n"
    + "\n"
    + "\n"
    + "      You need not edit this message in any way. Simply \n"
    + "      save this e-mail message to the file.\n"
    + "\n"
    + "\n"
    + "If you have any questions about the certificate contact\n"
    + "the Certificate Authority at " + emailAddressOfCA + "\n"
    + "\n");*/
    ps.print(toPEM(data));
    ps.close();

    // Save private key to a .pem file.
    OpenSSLKey key = new BouncyCastleOpenSSLKey(privKey);
    if (password.length() != 0) {
      key.encrypt(password);
    }
    key.writeTo(new File(privKeyLoc).getAbsolutePath());
    // set read only permissions
    Util.setFilePermissions(privKeyLoc, 600);

    // Create an empty cert file.
    /*        File f = new File(certLoc);
    f.createNewFile();*/
  }