/** Test Overflow of CRL Period */
 @Test
 public void testCRLPeriodOverflow() throws Exception {
   log.trace(">test05CRLPeriodOverflow()");
   // Fetch CAInfo and save CRLPeriod
   CAInfo cainfo = testx509ca.getCAInfo();
   long tempCRLPeriod = cainfo.getCRLPeriod();
   X509Certificate cert = createCertWithValidity(1);
   try {
     // Revoke the user
     certificateStoreSession.setRevokeStatus(
         roleMgmgToken, cert, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE, null);
     // Change CRLPeriod
     cainfo.setCRLPeriod(Long.MAX_VALUE);
     caSession.editCA(roleMgmgToken, cainfo);
     // Create new CRL's
     assertTrue(publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId()));
     // Verify that status is not archived
     CertificateInfo certinfo =
         certificateStoreSession.getCertificateInfo(CertTools.getFingerprintAsString(cert));
     assertFalse(
         "Non Expired Revoked Certificate was archived",
         certinfo.getStatus() == CertificateConstants.CERT_ARCHIVED);
   } finally {
     internalCertificateStoreSession.removeCertificate(CertTools.getSerialNumber(cert));
     // Restore CRL Period
     cainfo.setCRLPeriod(tempCRLPeriod);
     caSession.editCA(roleMgmgToken, cainfo);
   }
 }
  /** Tests the extension Freshest CRL DP. */
  @Test
  public void testCRLFreshestCRL() throws Exception {
    final String cdpURL = "http://www.ejbca.org/foo/bar.crl";
    final String freshestCdpURL = "http://www.ejbca.org/foo/delta.crl";
    X509CAInfo cainfo = (X509CAInfo) testx509ca.getCAInfo();
    X509CRL x509crl;
    byte[] cFreshestDpDER;

    cainfo.setUseCrlDistributionPointOnCrl(true);
    cainfo.setDefaultCRLDistPoint(cdpURL);
    cainfo.setCADefinedFreshestCRL(freshestCdpURL);
    caSession.editCA(roleMgmgToken, cainfo);
    publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId());
    x509crl =
        CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(cainfo.getSubjectDN(), false));
    cFreshestDpDER = x509crl.getExtensionValue(Extension.freshestCRL.getId());
    assertNotNull("CRL has no Freshest Distribution Point", cFreshestDpDER);

    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(cFreshestDpDER));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    CRLDistPoint cdp = CRLDistPoint.getInstance((ASN1Sequence) aIn.readObject());
    DistributionPoint[] distpoints = cdp.getDistributionPoints();

    assertEquals("More CRL Freshest distributions points than expected", 1, distpoints.length);
    assertEquals(
        "Freshest CRL distribution point is different",
        freshestCdpURL,
        ((DERIA5String)
                ((GeneralNames) distpoints[0].getDistributionPoint().getName())
                    .getNames()[0].getName())
            .getString());
  }
 @After
 public void tearDown() throws Exception {
   // Remove any testca before exiting tests
   byte[] crl;
   while ((crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false)) != null) {
     X509CRL x509crl = CertTools.getCRLfromByteArray(crl);
     internalCertificateStoreSession.removeCRL(
         alwaysAllowToken, CertTools.getFingerprintAsString(x509crl));
   }
   while ((crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), true)) != null) {
     X509CRL x509crl = CertTools.getCRLfromByteArray(crl);
     internalCertificateStoreSession.removeCRL(
         alwaysAllowToken, CertTools.getFingerprintAsString(x509crl));
   }
   caSession.removeCA(alwaysAllowToken, testx509ca.getCAId());
 }
예제 #4
0
  /**
   * Generate a certificate signing request (PKCS#10).
   *
   * @param info A PKCS10CertReqInfo
   * @param privateKey Private key for signing the request
   * @param signatureProvider Name of provider to sign with
   * @param publicKey Public key to include in the request
   * @param explicitEccParameters True if the EC domain parameters should be included (ie. not a
   *     named curve)
   * @return the certificate request data
   */
  public static ICertReqData genCertificateRequest(
      ISignerCertReqInfo info,
      final PrivateKey privateKey,
      final String signatureProvider,
      PublicKey publicKey,
      final boolean explicitEccParameters)
      throws IllegalArgumentException {
    LOG.debug(">genCertificateRequest");
    final Base64SignerCertReqData retval;
    if (info instanceof PKCS10CertReqInfo) {
      PKCS10CertReqInfo reqInfo = (PKCS10CertReqInfo) info;
      PKCS10CertificationRequest pkcs10;

      if (LOG.isDebugEnabled()) {
        LOG.debug("signatureAlgorithm: " + reqInfo.getSignatureAlgorithm());
        LOG.debug("subjectDN: " + reqInfo.getSubjectDN());
        LOG.debug("explicitEccParameters: " + explicitEccParameters);
      }

      try {
        // Handle ECDSA key with explicit parameters
        if (explicitEccParameters && publicKey.getAlgorithm().contains("EC")) {
          publicKey = ECKeyUtil.publicToExplicitParameters(publicKey, "BC");
        }

        if (LOG.isDebugEnabled()) {
          LOG.debug("Public key SHA1: " + createKeyHash(publicKey));
          LOG.debug("Public key SHA256: " + KeyUsageCounterHash.create(publicKey));
        }

        // Generate request
        final JcaPKCS10CertificationRequestBuilder builder =
            new JcaPKCS10CertificationRequestBuilder(
                new X500Name(CertTools.stringToBCDNString(reqInfo.getSubjectDN())), publicKey);
        final ContentSigner contentSigner =
            new JcaContentSignerBuilder(reqInfo.getSignatureAlgorithm())
                .setProvider(signatureProvider)
                .build(privateKey);
        pkcs10 = builder.build(contentSigner);
        retval = new Base64SignerCertReqData(Base64.encode(pkcs10.getEncoded()));
      } catch (IOException e) {
        throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
      } catch (OperatorCreationException e) {
        throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
      } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
      } catch (NoSuchProviderException e) {
        throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
      }
      LOG.debug("<genCertificateRequest");
      return retval;
    } else {
      throw new IllegalArgumentException(
          "Unsupported certificate request info type: " + info.getClass().getName());
    }
  }
  /** creates new crl */
  @Test
  public void testCreateNewCRL() throws Exception {
    publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId());
    X509CRL x509crl = null;

    // Get number of last CRL
    int number = crlStoreSession.getLastCRLNumber(testx509ca.getSubjectDN(), false);
    log.debug("Last CRLNumber = " + number);
    byte[] crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false);
    assertNotNull("Could not get CRL", crl);
    x509crl = CertTools.getCRLfromByteArray(crl);

    BigInteger num = CrlExtensions.getCrlNumber(x509crl);
    // Create a new CRL again to see that the number increases
    publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId());
    int number1 = crlStoreSession.getLastCRLNumber(testx509ca.getSubjectDN(), false);
    assertEquals(number + 1, number1);
    byte[] crl1 = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false);
    X509CRL x509crl1 = CertTools.getCRLfromByteArray(crl1);
    BigInteger num1 = CrlExtensions.getCrlNumber(x509crl1);
    assertEquals(num.intValue() + 1, num1.intValue());

    /*
     * check revoked certificates
     */

    // Get number of last CRL
    Collection<RevokedCertInfo> revfp =
        certificateStoreSession.listRevokedCertInfo(testx509ca.getSubjectDN(), -1);
    log.debug("Number of revoked certificates=" + revfp.size());
    crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false);
    assertNotNull("Could not get CRL", crl);

    x509crl = CertTools.getCRLfromByteArray(crl);
    Set<? extends X509CRLEntry> revset = x509crl.getRevokedCertificates();
    // Revset will be null if there are no revoked certificates
    if (revset != null) {
      int revsize = revset.size();
      assertEquals(revfp.size(), revsize);
    } else {
      assertEquals(0, revfp.size());
    }
  }
 private void createCertificate(int certificateProfileId) throws Exception {
   KeyPair keys = KeyTools.genKeys("1024", "RSA");
   cert =
       (X509Certificate)
           signSession.createCertificate(
               admin,
               USERNAME,
               PASSWORD,
               new PublicKeyWrapper(keys.getPublic()),
               -1,
               null,
               null,
               certificateProfileId,
               SecConst.CAID_USEUSERDEFINED);
   certificatesToRemove.add(cert);
   fingerprint = CertTools.getFingerprintAsString(cert);
   X509Certificate ce =
       (X509Certificate) certificateStoreSession.findCertificateByFingerprint(fingerprint);
   if (ce == null) {
     throw new Exception("Cannot find certificate with fp=" + fingerprint);
   }
   info = certificateStoreSession.getCertificateInfo(fingerprint);
   if (!fingerprint.equals(info.getFingerprint())) {
     throw new Exception("fingerprint does not match.");
   }
   if (!cert.getSerialNumber().equals(info.getSerialNumber())) {
     throw new Exception("serialnumber does not match.");
   }
   if (!CertTools.getIssuerDN(cert).equals(info.getIssuerDN())) {
     throw new Exception("issuerdn does not match.");
   }
   if (!CertTools.getSubjectDN(cert).equals(info.getSubjectDN())) {
     throw new Exception("subjectdn does not match.");
   }
   // The cert was just stored above with status INACTIVE
   if (!(CertificateConstants.CERT_ACTIVE == info.getStatus())) {
     throw new Exception("status does not match.");
   }
 }
예제 #7
0
 @Test
 public void testBase64Small() throws Exception {
   // Testcert is on long line of base 64 encoded stuff
   byte[] certBytes = Base64.decode(testcert_oneline.getBytes());
   assertNotNull(certBytes);
   // This should be a cert
   Certificate cert = CertTools.getCertfromByteArray(certBytes);
   assertNotNull(cert);
   // Base64 encode it again
   byte[] encBytes = Base64.encode(cert.getEncoded(), false);
   assertEquals(new String(encBytes), testcert_oneline);
   // Testcert_crlf has \n after each line
   certBytes = Base64.decode(testcert_crlf.getBytes());
   assertNotNull(certBytes);
   // This should be a cert
   cert = CertTools.getCertfromByteArray(certBytes);
   assertNotNull(cert);
   // Base64 encode it again
   encBytes = Base64.encode(cert.getEncoded(), true);
   assertEquals(new String(encBytes), testcert_crlf);
   // This is the same method as above
   encBytes = Base64.encode(cert.getEncoded());
   assertEquals(new String(encBytes), testcert_crlf);
 }
 @Before
 public void setUp() throws Exception {
   admin =
       (TestX509CertificateAuthenticationToken)
           simpleAuthenticationProvider.authenticate(new AuthenticationSubject(null, null));
   RoleData role = roleManagementSessionRemote.create(internalAdmin, ROLENAME);
   Collection<AccessUserAspectData> subjects = new LinkedList<AccessUserAspectData>();
   subjects.add(
       new AccessUserAspectData(
           ROLENAME,
           CertTools.getIssuerDN(admin.getCertificate()).hashCode(),
           X500PrincipalAccessMatchValue.WITH_COMMONNAME,
           AccessMatchType.TYPE_EQUALCASEINS,
           CertTools.getPartFromDN(SimpleAuthenticationProviderSessionRemote.DEFAULT_DN, "CN")));
   role = roleManagementSessionRemote.addSubjectsToRole(internalAdmin, role, subjects);
   Collection<AccessRuleData> accessRules = new LinkedList<AccessRuleData>();
   accessRules.add(
       new AccessRuleData(
           ROLENAME, AccessRulesConstants.ROLE_ADMINISTRATOR, AccessRuleState.RULE_ACCEPT, false));
   accessRules.add(
       new AccessRuleData(
           ROLENAME,
           AccessRulesConstants.REGULAR_EDITUSERDATASOURCES,
           AccessRuleState.RULE_ACCEPT,
           false));
   accessRules.add(
       new AccessRuleData(
           ROLENAME,
           AccessRulesConstants.USERDATASOURCEPREFIX
               + Integer.valueOf(
                   userDataSourceSession.getUserDataSourceId(admin, "TESTNEWDUMMYCUSTOM"))
               + AccessRulesConstants.UDS_FETCH_RIGHTS,
           AccessRuleState.RULE_ACCEPT,
           false));
   role = roleManagementSessionRemote.addAccessRulesToRole(internalAdmin, role, accessRules);
 }
 @Test
 public void testCrlGenerateForAll() throws Exception {
   X509CAInfo cainfo = (X509CAInfo) testx509ca.getCAInfo();
   cainfo.setCRLIssueInterval(1); // Issue very often..
   cainfo.setDeltaCRLPeriod(1); // Issue very often..
   caSession.editCA(roleMgmgToken, cainfo);
   // make sure we have a CRL and delta CRL generated
   publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId());
   publishingCrlSessionRemote.forceDeltaCRL(roleMgmgToken, testx509ca.getCAId());
   try {
     // Now wait and test again
     Thread.sleep(1000);
     final X509CRL x509crl =
         CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(cainfo.getSubjectDN(), false));
     assertTrue(publishingCrlSessionRemote.createCRLs(roleMgmgToken) > 0);
     final X509CRL x509crlAfter =
         CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(cainfo.getSubjectDN(), false));
     assertTrue(
         "Did not generate a newer CRL.",
         x509crlAfter.getThisUpdate().after(x509crl.getThisUpdate()));
     final X509CRL x509deltaCrl =
         CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(cainfo.getSubjectDN(), true));
     assertTrue(publishingCrlSessionRemote.createDeltaCRLs(roleMgmgToken) > 0);
     final X509CRL x509deltaCrlAfter =
         CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(cainfo.getSubjectDN(), true));
     assertTrue(
         "Did not generate a newer Delta CRL.",
         x509deltaCrlAfter.getThisUpdate().after(x509deltaCrl.getThisUpdate()));
     // Try a similar thing when we specify which CA IDs to generate CRLs for
     // Compare CRL numbers instead of Dates, since these CRLs might have been generated the same
     // second as the last ones
     final Collection<Integer> caids = new ArrayList<Integer>();
     caids.add(Integer.valueOf(testx509ca.getCAId()));
     publishingCrlProxySession.createCRLs(roleMgmgToken, caids, 2);
     final X509CRL x509crlAfter2 =
         CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(cainfo.getSubjectDN(), false));
     assertTrue(
         "Did not generate a newer CRL.",
         CrlExtensions.getCrlNumber(x509crlAfter2).intValue()
             > CrlExtensions.getCrlNumber(x509crlAfter).intValue());
     publishingCrlProxySession.createDeltaCRLs(roleMgmgToken, caids, 2);
     final X509CRL x509deltaCrlAfter2 =
         CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(cainfo.getSubjectDN(), true));
     assertTrue(
         "Did not generate a newer Delta CRL.",
         CrlExtensions.getCrlNumber(x509deltaCrlAfter2).intValue()
             > CrlExtensions.getCrlNumber(x509deltaCrlAfter).intValue());
   } finally {
     byte[] crl;
     while ((crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false)) != null) {
       X509CRL x509crl = CertTools.getCRLfromByteArray(crl);
       internalCertificateStoreSession.removeCRL(
           roleMgmgToken, CertTools.getFingerprintAsString(x509crl));
     }
     while ((crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), true)) != null) {
       X509CRL x509crl = CertTools.getCRLfromByteArray(crl);
       internalCertificateStoreSession.removeCRL(
           roleMgmgToken, CertTools.getFingerprintAsString(x509crl));
     }
   }
 }
  /** Test revocation and reactivation of certificates */
  @Test
  public void testRevokeAndUnrevoke() throws Exception {

    X509Certificate cert = createCert();
    try {
      // Create a new CRL again...
      assertTrue(publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId()));
      // Check that our newly signed certificate is not present in a new CRL
      byte[] crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false);
      assertNotNull("Could not get CRL", crl);
      X509CRL x509crl = CertTools.getCRLfromByteArray(crl);
      Set<? extends X509CRLEntry> revset = x509crl.getRevokedCertificates();
      if (revset != null) {
        Iterator<? extends X509CRLEntry> iter = revset.iterator();
        while (iter.hasNext()) {
          X509CRLEntry ce = iter.next();
          assertTrue(ce.getSerialNumber().compareTo(cert.getSerialNumber()) != 0);
        }
      } // If no revoked certificates exist at all, this test passed...

      certificateStoreSession.setRevokeStatus(
          roleMgmgToken, cert, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, null);
      // Create a new CRL again...
      assertTrue(publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId()));
      // Check that our newly signed certificate IS present in a new CRL
      crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false);
      assertNotNull("Could not get CRL", crl);
      x509crl = CertTools.getCRLfromByteArray(crl);
      revset = x509crl.getRevokedCertificates();
      assertNotNull(revset);
      Iterator<? extends X509CRLEntry> iter = revset.iterator();
      boolean found = false;
      while (iter.hasNext()) {
        X509CRLEntry ce = iter.next();
        if (ce.getSerialNumber().compareTo(cert.getSerialNumber()) == 0) {
          found = true;
          // TODO: verify the reason code
        }
      }
      assertTrue(
          "Certificate with serial " + cert.getSerialNumber().toString(16) + " not revoked", found);

      // Unrevoke the certificate that we just revoked
      certificateStoreSession.setRevokeStatus(
          roleMgmgToken, cert, RevokedCertInfo.NOT_REVOKED, null);
      // Create a new CRL again...
      assertTrue(publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId()));
      // Check that our newly signed certificate IS NOT present in the new
      // CRL.
      crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false);
      assertNotNull("Could not get CRL", crl);
      x509crl = CertTools.getCRLfromByteArray(crl);
      revset = x509crl.getRevokedCertificates();
      if (revset != null) {
        iter = revset.iterator();
        found = false;
        while (iter.hasNext()) {
          X509CRLEntry ce = iter.next();
          if (ce.getSerialNumber().compareTo(cert.getSerialNumber()) == 0) {
            found = true;
          }
        }
        assertFalse(found);
      } // If no revoked certificates exist at all, this test passed...

      certificateStoreSession.setRevokeStatus(
          roleMgmgToken, cert, RevokedCertInfo.REVOCATION_REASON_CACOMPROMISE, null);
      assertTrue(
          "Failed to revoke certificate!",
          certificateStoreSession.isRevoked(
              CertTools.getIssuerDN(cert), CertTools.getSerialNumber(cert)));
      // Create a new CRL again...
      assertTrue(publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId()));
      // Check that our newly signed certificate IS present in a new CRL
      crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false);
      assertNotNull("Could not get CRL", crl);
      x509crl = CertTools.getCRLfromByteArray(crl);
      revset = x509crl.getRevokedCertificates();
      iter = revset.iterator();
      found = false;
      while (iter.hasNext()) {
        X509CRLEntry ce = (X509CRLEntry) iter.next();
        if (ce.getSerialNumber().compareTo(cert.getSerialNumber()) == 0) {
          found = true;
          // TODO: verify the reason code
        }
      }
      assertTrue(found);

      certificateStoreSession.setRevokeStatus(
          roleMgmgToken, cert, RevokedCertInfo.NOT_REVOKED, null);
      assertTrue(
          "Was able to re-activate permanently revoked certificate!",
          certificateStoreSession.isRevoked(
              CertTools.getIssuerDN(cert), CertTools.getSerialNumber(cert)));
      // Create a new CRL again...
      assertTrue(publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId()));
      // Check that our newly signed certificate is present in the new CRL,
      // because the revocation reason
      // was not CERTIFICATE_HOLD, we can only un-revoke certificates that are
      // on hold.
      crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false);
      assertNotNull("Could not get CRL", crl);
      x509crl = CertTools.getCRLfromByteArray(crl);
      revset = x509crl.getRevokedCertificates();
      iter = revset.iterator();
      found = false;
      while (iter.hasNext()) {
        X509CRLEntry ce = (X509CRLEntry) iter.next();
        if (ce.getSerialNumber().compareTo(cert.getSerialNumber()) == 0) {
          found = true;
        }
      }
      assertTrue(found);
    } finally {
      internalCertificateStoreSession.removeCertificate(cert);
    }
  }
  @Override
  public CommandResult execute(ParameterContainer parameters) {

    final String issuerDNStr = parameters.get(DN_KEY);
    final String issuerDN = CertTools.stringToBCDNString(issuerDNStr);
    final String certserno = parameters.get(SERIAL_NUMBER_KEY);
    final BigInteger serno;
    try {
      serno = new BigInteger(certserno, 16);
    } catch (NumberFormatException e) {
      log.error("ERROR: Invalid hexadecimal certificate serial number string: " + certserno);
      return CommandResult.FUNCTIONAL_FAILURE;
    }
    int reason;
    try {
      reason = Integer.parseInt(parameters.get(REASON_KEY));
    } catch (NumberFormatException e) {
      log.error("ERROR: " + parameters.get(REASON_KEY) + " was not a number.");
      return CommandResult.FUNCTIONAL_FAILURE;
    }
    if ((reason == 7) || (reason < 0) || (reason > 10)) {
      getLogger().error("ERROR: Reason must be an integer between 0 and 10 except 7.");
      return CommandResult.FUNCTIONAL_FAILURE;
    } else {
      Certificate cert =
          EjbRemoteHelper.INSTANCE
              .getRemoteSession(CertificateStoreSessionRemote.class)
              .findCertificateByIssuerAndSerno(issuerDN, serno);
      if (cert != null) {
        getLogger().info("Found certificate:");
        getLogger().info("Subject DN=" + CertTools.getSubjectDN(cert));
        // We need the user this cert is connected with
        // Revoke or unrevoke, will throw appropriate exceptions if parameters are wrong, such as
        // trying to unrevoke a certificate
        // that was permanently revoked
        try {
          try {
            EjbRemoteHelper.INSTANCE
                .getRemoteSession(EndEntityManagementSessionRemote.class)
                .revokeCert(getAuthenticationToken(), serno, issuerDN, reason);
          } catch (ApprovalException e) {
            log.error(e.getMessage(), e);
            return CommandResult.FUNCTIONAL_FAILURE;
          } catch (AuthorizationDeniedException e) {
            log.error("ERROR: CLI user not authorized to revoke certificate.");
            return CommandResult.FUNCTIONAL_FAILURE;
          } catch (FinderException e) {
            log.error("ERROR: " + e.getMessage());
            return CommandResult.FUNCTIONAL_FAILURE;
          } catch (WaitingForApprovalException e) {
            log.error("ERROR: " + e.getMessage());
            return CommandResult.FUNCTIONAL_FAILURE;
          }
          getLogger()
              .info(
                  (reason == 8 ? "Unrevoked" : "Revoked")
                      + " certificate with issuerDN '"
                      + issuerDN
                      + "' and serialNumber "
                      + certserno
                      + ". Revocation reason="
                      + reason);
        } catch (AlreadyRevokedException e) {
          if (reason == 8) {
            getLogger()
                .info(
                    "Certificate with issuerDN '"
                        + issuerDN
                        + "' and serialNumber "
                        + certserno
                        + " is not revoked, nothing was done.");
          } else {
            getLogger()
                .info(
                    "Certificate with issuerDN '"
                        + issuerDN
                        + "' and serialNumber "
                        + certserno
                        + " is already revoked, nothing was done.");
          }
          getLogger().info(e.getMessage());
        }
      } else {
        getLogger()
            .info(
                "No certificate found with issuerDN '"
                    + issuerDN
                    + "' and serialNumber "
                    + certserno);
      }
    }
    return CommandResult.SUCCESS;
  }
  @Override
  public CommandResult execute(ParameterContainer parameters) {
    String username = parameters.get(ENTITY_NAME);
    String password = parameters.get(ENTITY_PASSWORD);
    String csr = parameters.get(CSR);
    String certf = parameters.get(DESTINATION_FILE);

    byte[] bytes;
    try {
      bytes = FileTools.readFiletoBuffer(csr);
    } catch (FileNotFoundException e) {
      log.error("File " + csr + " not found.");
      return CommandResult.FUNCTIONAL_FAILURE;
    }
    RequestMessage req = RequestMessageUtils.parseRequestMessage(bytes);
    if (req instanceof PKCS10RequestMessage) {
      PKCS10RequestMessage p10req = (PKCS10RequestMessage) req;
      p10req.setUsername(username);
      p10req.setPassword(password);
    } else {
      log.error("Input file '" + csr + "' is not a PKCS#10 request.");
      return CommandResult.FUNCTIONAL_FAILURE;
    }
    final SignSessionRemote signSession =
        EjbRemoteHelper.INSTANCE.getRemoteSession(SignSessionRemote.class);
    // Call signsession to create a certificate
    ResponseMessage resp;
    try {
      resp =
          signSession.createCertificate(
              getAuthenticationToken(), req, X509ResponseMessage.class, null);
    } catch (EjbcaException e) {
      log.error("Could not create certificate: " + e.getMessage());
      return CommandResult.FUNCTIONAL_FAILURE;
    } catch (CesecoreException e) {
      log.error("Could not create certificate: " + e.getMessage());
      return CommandResult.FUNCTIONAL_FAILURE;
    } catch (AuthorizationDeniedException ee) {
      log.error(
          "CLI user with username "
              + parameters.get(USERNAME_KEY)
              + " was not authorized to create a certificate.");
      return CommandResult.AUTHORIZATION_FAILURE;
    } catch (CertificateExtensionException e) {
      log.error("CSR specified extensions which were invalid: " + e.getMessage());
      return CommandResult.FUNCTIONAL_FAILURE;
    }
    byte[] pembytes;
    try {
      pembytes =
          CertTools.getPemFromCertificateChain(
              Arrays.asList(((X509ResponseMessage) resp).getCertificate()));
    } catch (CertificateException e) {
      throw new IllegalStateException(
          "Newly created certificate could not be parsed. This should not happen.", e);
    }
    // Write the resulting cert to file
    try {
      FileOutputStream fos = new FileOutputStream(certf);
      fos.write(pembytes);
      fos.close();
    } catch (IOException e) {
      log.error("Could not write to certificate file " + certf + ". " + e.getMessage());
      return CommandResult.FUNCTIONAL_FAILURE;
    }
    log.info("PEM certificate written to file '" + certf + "'");
    return CommandResult.SUCCESS;
  }
  /** Add a new user and an expire service. Test running on all CAs. */
  @Test
  public void testExpireCertificateWithAllCAs() throws Exception {
    try {
      createCertificate();
      long seconds = (cert.getNotAfter().getTime() - new Date().getTime()) / 1000l;
      // Create a new UserPasswordExpireService
      ServiceConfiguration config = new ServiceConfiguration();
      config.setActive(true);
      config.setDescription("This is a description");
      // No mailsending for this Junit test service
      config.setActionClassPath(NoAction.class.getName());
      config.setActionProperties(null);
      config.setIntervalClassPath(PeriodicalInterval.class.getName());
      Properties intervalprop = new Properties();
      // Run the service every 3:rd second
      intervalprop.setProperty(PeriodicalInterval.PROP_VALUE, "3");
      intervalprop.setProperty(PeriodicalInterval.PROP_UNIT, PeriodicalInterval.UNIT_SECONDS);
      config.setIntervalProperties(intervalprop);
      config.setWorkerClassPath(CertificateExpirationNotifierWorker.class.getName());
      Properties workerprop = new Properties();
      workerprop.setProperty(EmailSendingWorkerConstants.PROP_SENDTOADMINS, "FALSE");
      workerprop.setProperty(EmailSendingWorkerConstants.PROP_SENDTOENDUSERS, "FALSE");
      // Here is the line that matters for this test
      workerprop.setProperty(BaseWorker.PROP_CAIDSTOCHECK, String.valueOf(SecConst.ALLCAS));

      workerprop.setProperty(BaseWorker.PROP_TIMEBEFOREEXPIRING, String.valueOf(seconds - 5));
      workerprop.setProperty(BaseWorker.PROP_TIMEUNIT, BaseWorker.UNIT_SECONDS);
      config.setWorkerProperties(workerprop);
      if (serviceSession.getService(CERTIFICATE_EXPIRATION_SERVICE) == null) {
        serviceSession.addService(admin, 4711, CERTIFICATE_EXPIRATION_SERVICE, config);
      }
      serviceSession.activateServiceTimer(admin, CERTIFICATE_EXPIRATION_SERVICE);
      // The service will run... the cert should still be active after 2
      // seconds..
      Thread.sleep(2000);
      info = certificateStoreSession.getCertificateInfo(fingerprint);
      assertEquals("status does not match.", CertificateConstants.CERT_ACTIVE, info.getStatus());
      // The service will run...We need some tolerance since timers cannot
      // be guaranteed to executed at the exact interval.
      Thread.sleep(10000);
      int tries = 0;
      while (info.getStatus() != CertificateConstants.CERT_NOTIFIEDABOUTEXPIRATION && tries < 8) {
        Thread.sleep(1000);
        info = certificateStoreSession.getCertificateInfo(fingerprint);
        tries++;
      }
      info = certificateStoreSession.getCertificateInfo(fingerprint);
      assertEquals(
          "Status does not match.",
          CertificateConstants.CERT_NOTIFIEDABOUTEXPIRATION,
          info.getStatus());
    } finally {
      // Restore superadmin CA if it got screwed up.
      List<Certificate> certs = certificateStoreSession.findCertificatesByUsername("superadmin");
      for (Certificate certificate : certs) {
        String superAdminFingerprint = CertTools.getFingerprintAsString(certificate);
        internalCertificateStoreSession.setStatus(
            admin, superAdminFingerprint, CertificateConstants.CERT_ACTIVE);
      }
    }
  }
  @Test
  public void testIsAuthorizedToUserDataSource() throws Exception {
    final String rolename = "testIsAuthorizedToUserDataSource";
    Set<Principal> principals = new HashSet<Principal>();
    principals.add(new X500Principal("CN=" + rolename));
    TestX509CertificateAuthenticationToken adminNoAuth =
        (TestX509CertificateAuthenticationToken)
            simpleAuthenticationProvider.authenticate(new AuthenticationSubject(principals, null));

    final int caid = CertTools.getIssuerDN(admin.getCertificate()).hashCode();
    final String cN = CertTools.getPartFromDN(CertTools.getIssuerDN(admin.getCertificate()), "CN");
    RoleData role = roleManagementSessionRemote.create(internalAdmin, rolename);
    final String alias = "spacemonkeys";
    try {
      Collection<AccessUserAspectData> subjects = new ArrayList<AccessUserAspectData>();
      subjects.add(
          new AccessUserAspectData(
              rolename,
              caid,
              X500PrincipalAccessMatchValue.WITH_COMMONNAME,
              AccessMatchType.TYPE_EQUALCASE,
              cN));
      role = roleManagementSessionRemote.addSubjectsToRole(internalAdmin, role, subjects);
      Collection<AccessRuleData> accessRules = new ArrayList<AccessRuleData>();
      // Not authorized to user data sources
      accessRules.add(
          new AccessRuleData(
              rolename,
              AccessRulesConstants.REGULAR_EDITENDENTITYPROFILES,
              AccessRuleState.RULE_ACCEPT,
              true));
      role = roleManagementSessionRemote.addAccessRulesToRole(internalAdmin, role, accessRules);

      CustomUserDataSourceContainer userdatasource = new CustomUserDataSourceContainer();
      userdatasource.setClassPath(
          "org.ejbca.core.model.ra.userdatasource.DummyCustomUserDataSource");
      userdatasource.setDescription("Used in Junit Test, Remove this one");

      // Test authorization to edit with an unauthorized admin
      try {
        userDataSourceSession.addUserDataSource(adminNoAuth, alias, userdatasource);
        fail("admin should not have been authorized to edit user data source");
      } catch (AuthorizationDeniedException e) {
        assertEquals("Error, not authorized to user data source spacemonkeys.", e.getMessage());
      }
      try {
        userDataSourceSession.changeUserDataSource(adminNoAuth, alias, userdatasource);
        fail("admin should not have been authorized to edit user data source");
      } catch (AuthorizationDeniedException e) {
        assertEquals("Error, not authorized to user data source spacemonkeys.", e.getMessage());
      }
      // Add so we can try to clone, remove and rename
      userDataSourceSession.addUserDataSource(internalAdmin, alias, userdatasource);
      try {
        userDataSourceSession.cloneUserDataSource(adminNoAuth, alias, "newmonkeys");
        fail("admin should not have been authorized to edit user data source");
      } catch (AuthorizationDeniedException e) {
        assertEquals("Error, not authorized to user data source newmonkeys.", e.getMessage());
      }
      try {
        userDataSourceSession.removeUserDataSource(adminNoAuth, alias);
        fail("admin should not have been authorized to edit user data source");
      } catch (AuthorizationDeniedException e) {
        assertEquals("Error, not authorized to user data source spacemonkeys.", e.getMessage());
      }
      try {
        userDataSourceSession.renameUserDataSource(adminNoAuth, alias, "renamedmonkey");
        fail("admin should not have been authorized to edit user data source");
      } catch (AuthorizationDeniedException e) {
        assertEquals("Error, not authorized to user data source spacemonkeys.", e.getMessage());
      }

    } finally {
      userDataSourceSession.removeUserDataSource(internalAdmin, alias);
      roleManagementSessionRemote.remove(internalAdmin, rolename);
    }
  }