Search in sources :

Example 41 with CertificateSerial

use of org.candlepin.model.CertificateSerial in project candlepin by candlepin.

the class DefaultEntitlementCertServiceAdapter method doEntitlementCertGeneration.

/**
 * @param entitlements a map of entitlements indexed by pool ids to generate
 *        the certs of
 * @param productMap a map of respective products indexed by pool id
 * @throws IOException
 * @throws GeneralSecurityException
 * @return entitlementCerts the respective entitlement certs indexed by pool
 *         id
 */
private Map<String, EntitlementCertificate> doEntitlementCertGeneration(Consumer consumer, Map<String, Product> productMap, Map<String, PoolQuantity> poolQuantities, Map<String, Entitlement> entitlements, boolean save) throws GeneralSecurityException, IOException {
    Owner owner = ownerCurator.findOwnerById(consumer.getOwnerId());
    log.debug("Generating entitlement cert for entitlements");
    KeyPair keyPair = keyPairCurator.getConsumerKeyPair(consumer);
    byte[] pemEncodedKeyPair = pki.getPemEncoded(keyPair.getPrivate());
    Map<String, CertificateSerial> serialMap = new HashMap<>();
    for (Entry<String, PoolQuantity> entry : poolQuantities.entrySet()) {
        // No need to persist the cert serial here as the IDs are generated on object creation.
        serialMap.put(entry.getKey(), new CertificateSerial(entry.getValue().getPool().getEndDate()));
    }
    Map<String, EntitlementCertificate> entitlementCerts = new HashMap<>();
    for (Entry<String, PoolQuantity> entry : poolQuantities.entrySet()) {
        Pool pool = entry.getValue().getPool();
        Entitlement ent = entitlements.get(entry.getKey());
        CertificateSerial serial = serialMap.get(entry.getKey());
        Product product = productMap.get(entry.getKey());
        log.info("Generating entitlement cert for pool: {} quantity: {} entitlement id: {}", pool, ent.getQuantity(), ent.getId());
        Set<Product> products = new HashSet<>(productCurator.getPoolProvidedProductsCached(pool));
        // If creating a certificate for a distributor, we need
        // to add any derived products as well so that their content
        // is available in the upstream certificate.
        products.addAll(getDerivedProductsForDistributor(pool, consumer));
        products.add(product);
        Map<String, EnvironmentContent> promotedContent = getPromotedContent(consumer);
        String contentPrefix = getContentPrefix(consumer, owner, true);
        log.info("Creating X509 cert for product: {}", product);
        log.debug("Provided products: {}", products);
        List<org.candlepin.model.dto.Product> productModels = v3extensionUtil.createProducts(product, products, contentPrefix, promotedContent, consumer, pool);
        X509Certificate x509Cert = createX509Certificate(consumer, owner, pool, ent, product, products, productModels, BigInteger.valueOf(serial.getId()), keyPair, true);
        log.debug("Getting PEM encoded cert.");
        String pem = new String(this.pki.getPemEncoded(x509Cert));
        if (shouldGenerateV3(consumer)) {
            log.debug("Generating v3 entitlement data");
            byte[] payloadBytes = v3extensionUtil.createEntitlementDataPayload(productModels, consumer, pool, ent.getQuantity());
            String payload = "-----BEGIN ENTITLEMENT DATA-----\n";
            payload += Util.toBase64(payloadBytes);
            payload += "-----END ENTITLEMENT DATA-----\n";
            byte[] bytes = pki.getSHA256WithRSAHash(new ByteArrayInputStream(payloadBytes));
            String signature = "-----BEGIN RSA SIGNATURE-----\n";
            signature += Util.toBase64(bytes);
            signature += "-----END RSA SIGNATURE-----\n";
            pem += payload + signature;
        }
        // Build a skeleton cert as part of the entitlement processing.
        EntitlementCertificate cert = new EntitlementCertificate();
        cert.setKeyAsBytes(pemEncodedKeyPair);
        cert.setCert(pem);
        if (save) {
            cert.setEntitlement(ent);
        }
        if (log.isDebugEnabled()) {
            log.debug("Generated cert serial number: {}", serial.getId());
            log.debug("Key: {}", cert.getKey());
            log.debug("Cert: {}", cert.getCert());
        }
        entitlementCerts.put(entry.getKey(), cert);
    }
    // Serials need to be saved before the certs.
    log.debug("Persisting new certificate serials");
    serialCurator.saveOrUpdateAll(serialMap);
    // certs with their serials and add them to the entitlements.
    for (Entry<String, PoolQuantity> entry : poolQuantities.entrySet()) {
        CertificateSerial nextSerial = serialMap.get(entry.getKey());
        if (nextSerial == null) {
            // This should never happen, but checking to be safe.
            throw new RuntimeException("Certificate serial not found for entitlement during cert generation.");
        }
        EntitlementCertificate nextCert = entitlementCerts.get(entry.getKey());
        if (nextCert == null) {
            // This should never happen, but checking to be safe.
            throw new RuntimeException("Entitlement certificate not found for entitlement during cert generation");
        }
        nextCert.setSerial(nextSerial);
        if (save) {
            Entitlement ent = entitlements.get(entry.getKey());
            ent.getCertificates().add(nextCert);
        }
    }
    if (save) {
        log.info("Persisting certs.");
        entCertCurator.saveOrUpdateAll(entitlementCerts.values(), false, false);
    }
    return entitlementCerts;
}
Also used : PoolQuantity(org.candlepin.model.PoolQuantity) Owner(org.candlepin.model.Owner) KeyPair(java.security.KeyPair) EntitlementCertificate(org.candlepin.model.EntitlementCertificate) HashMap(java.util.HashMap) CertificateSerial(org.candlepin.model.CertificateSerial) Product(org.candlepin.model.Product) EnvironmentContent(org.candlepin.model.EnvironmentContent) X509Certificate(java.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) Pool(org.candlepin.model.Pool) Entitlement(org.candlepin.model.Entitlement) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 42 with CertificateSerial

use of org.candlepin.model.CertificateSerial in project candlepin by candlepin.

the class DefaultContentAccessCertServiceAdapter method getCertificate.

@Transactional
public ContentAccessCertificate getCertificate(Consumer consumer) throws GeneralSecurityException, IOException {
    Owner owner = ownerCurator.findOwnerById(consumer.getOwnerId());
    // appropriate cert generation
    if (!ORG_ENV_ACCESS_MODE.equals(owner.getContentAccessMode()) || !this.consumerIsCertV3Capable(consumer)) {
        return null;
    }
    ContentAccessCertificate existing = consumer.getContentAccessCert();
    ContentAccessCertificate result = new ContentAccessCertificate();
    String pem = "";
    if (existing != null && existing.getSerial().getExpiration().getTime() < (new Date()).getTime()) {
        consumer.setContentAccessCert(null);
        contentAccessCertificateCurator.delete(existing);
        existing = null;
    }
    if (existing == null) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.HOUR, -1);
        Date startDate = cal.getTime();
        cal.add(Calendar.YEAR, 1);
        Date endDate = cal.getTime();
        CertificateSerial serial = new CertificateSerial(endDate);
        // We need the sequence generated id before we create the Certificate,
        // otherwise we could have used cascading create
        serialCurator.create(serial);
        KeyPair keyPair = keyPairCurator.getConsumerKeyPair(consumer);
        byte[] pemEncodedKeyPair = pki.getPemEncoded(keyPair.getPrivate());
        X509Certificate x509Cert = createX509Certificate(consumer, owner, BigInteger.valueOf(serial.getId()), keyPair, startDate, endDate);
        existing = new ContentAccessCertificate();
        existing.setSerial(serial);
        existing.setKeyAsBytes(pemEncodedKeyPair);
        existing.setConsumer(consumer);
        log.info("Setting PEM encoded cert.");
        pem = new String(this.pki.getPemEncoded(x509Cert));
        existing.setCert(pem);
        consumer.setContentAccessCert(existing);
        contentAccessCertificateCurator.create(existing);
        consumerCurator.merge(consumer);
    } else {
        pem = existing.getCert();
    }
    Environment env = this.environmentCurator.getConsumerEnvironment(consumer);
    // we need to see if this is newer than the previous result
    OwnerEnvContentAccess oeca = ownerEnvContentAccessCurator.getContentAccess(owner.getId(), env == null ? null : env.getId());
    if (oeca == null) {
        String contentJson = createPayloadAndSignature(owner, env);
        oeca = new OwnerEnvContentAccess(owner, env, contentJson);
        ownerEnvContentAccessCurator.saveOrUpdate(oeca);
    }
    pem += oeca.getContentJson();
    result.setCert(pem);
    result.setCreated(existing.getCreated());
    result.setUpdated(existing.getUpdated());
    result.setId(existing.getId());
    result.setConsumer(existing.getConsumer());
    result.setKey(existing.getKey());
    result.setSerial(existing.getSerial());
    return result;
}
Also used : Owner(org.candlepin.model.Owner) KeyPair(java.security.KeyPair) Calendar(java.util.Calendar) CertificateSerial(org.candlepin.model.CertificateSerial) Environment(org.candlepin.model.Environment) ContentAccessCertificate(org.candlepin.model.ContentAccessCertificate) OwnerEnvContentAccess(org.candlepin.model.OwnerEnvContentAccess) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) Transactional(com.google.inject.persist.Transactional)

Example 43 with CertificateSerial

use of org.candlepin.model.CertificateSerial in project candlepin by candlepin.

the class ConsumerResourceCreationTest method init.

@Before
public void init() throws Exception {
    this.i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK);
    this.modelTranslator = new StandardTranslator(this.consumerTypeCurator, this.environmentCurator, this.ownerCurator);
    testMigration = new GuestMigration(consumerCurator);
    migrationProvider = Providers.of(testMigration);
    this.config = initConfig();
    this.resource = new ConsumerResource(this.consumerCurator, this.consumerTypeCurator, null, this.subscriptionService, this.ownerService, null, this.idCertService, null, this.i18n, this.sink, null, null, null, this.userService, null, null, this.ownerCurator, this.activationKeyCurator, null, this.complianceRules, this.deletedConsumerCurator, null, null, this.config, null, null, null, this.consumerBindUtil, null, null, new FactValidator(this.config, this.i18n), null, consumerEnricher, migrationProvider, modelTranslator);
    this.system = this.initConsumerType();
    this.mockConsumerType(this.system);
    this.systemDto = this.modelTranslator.translate(this.system, ConsumerTypeDTO.class);
    owner = new Owner("test_owner");
    owner.setId(TestUtil.randomString());
    user = new User(USER, "");
    PermissionBlueprint p = new PermissionBlueprint(PermissionType.OWNER, owner, Access.ALL);
    role = new Role();
    role.addPermission(p);
    role.addUser(user);
    when(consumerCurator.create(any(Consumer.class))).thenAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return invocation.getArguments()[0];
        }
    });
    when(consumerCurator.create(any(Consumer.class), any(Boolean.class))).thenAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return invocation.getArguments()[0];
        }
    });
    when(userService.findByLogin(USER)).thenReturn(user);
    IdentityCertificate cert = new IdentityCertificate();
    cert.setKey("testKey");
    cert.setCert("testCert");
    cert.setId("testId");
    cert.setSerial(new CertificateSerial(new Date()));
    when(idCertService.generateIdentityCert(any(Consumer.class))).thenReturn(cert);
    when(ownerCurator.lookupByKey(owner.getKey())).thenReturn(owner);
    when(complianceRules.getStatus(any(Consumer.class), any(Date.class), any(Boolean.class), any(Boolean.class))).thenReturn(new ComplianceStatus(new Date()));
}
Also used : FactValidator(org.candlepin.util.FactValidator) Owner(org.candlepin.model.Owner) User(org.candlepin.model.User) ComplianceStatus(org.candlepin.policy.js.compliance.ComplianceStatus) CertificateSerial(org.candlepin.model.CertificateSerial) StandardTranslator(org.candlepin.dto.StandardTranslator) ConsumerTypeDTO(org.candlepin.dto.api.v1.ConsumerTypeDTO) Date(java.util.Date) Role(org.candlepin.model.Role) GuestMigration(org.candlepin.resource.util.GuestMigration) Answer(org.mockito.stubbing.Answer) Consumer(org.candlepin.model.Consumer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) PermissionBlueprint(org.candlepin.model.PermissionBlueprint) Matchers.anyBoolean(org.mockito.Matchers.anyBoolean) IdentityCertificate(org.candlepin.model.IdentityCertificate) Before(org.junit.Before)

Example 44 with CertificateSerial

use of org.candlepin.model.CertificateSerial in project candlepin by candlepin.

the class ConsumerResourceIntegrationTest method testContentAccessExpireRegen.

@Test
public void testContentAccessExpireRegen() {
    owner.setContentAccessModeList(ContentAccessCertServiceAdapter.ORG_ENV_ACCESS_MODE);
    owner.setContentAccessMode(ContentAccessCertServiceAdapter.ORG_ENV_ACCESS_MODE);
    ownerCurator.merge(owner);
    consumer = TestUtil.createConsumer(standardSystemType, owner);
    consumer.setFact("system.certificate_version", "3.3");
    consumerCurator.create(consumer);
    List<CertificateDTO> serials = consumerResource.getEntitlementCertificates(consumer.getUuid(), null);
    assertEquals(1, serials.size());
    CertificateDTO original = serials.get(0);
    CertificateSerialDTO serialDTO = original.getSerial();
    CertificateSerial serial = new CertificateSerial(serialDTO.getId(), serialDTO.getExpiration());
    serial.setSerial(serialDTO.getSerial().longValue());
    serial.setCollected(serialDTO.isCollected());
    serial.setRevoked(serialDTO.isRevoked());
    Calendar cal = Calendar.getInstance();
    cal.setTime(serial.getExpiration());
    cal.add(Calendar.YEAR, -2);
    serial.setExpiration(cal.getTime());
    serialCurator.merge(serial);
    serials = consumerResource.getEntitlementCertificates(consumer.getUuid(), null);
    assertEquals(1, serials.size());
    CertificateDTO updated = serials.get(0);
    assert (updated instanceof CertificateDTO);
    assertFalse(original.getSerial().getId() == updated.getSerial().getId());
}
Also used : CertificateDTO(org.candlepin.dto.api.v1.CertificateDTO) CertificateSerialDTO(org.candlepin.dto.api.v1.CertificateSerialDTO) Calendar(java.util.Calendar) CertificateSerial(org.candlepin.model.CertificateSerial) Test(org.junit.Test)

Example 45 with CertificateSerial

use of org.candlepin.model.CertificateSerial in project candlepin by candlepin.

the class CrlResourceTest method testUnrevokeWithArguments.

@Test
@SuppressWarnings("unchecked")
public void testUnrevokeWithArguments() throws Exception {
    String[] input = new String[] { "123", "456", "789" };
    CandlepinQuery cqmock = mock(CandlepinQuery.class);
    List<CertificateSerial> serials = new LinkedList<>();
    serials.add(new CertificateSerial(123L));
    serials.add(new CertificateSerial(456L));
    serials.add(new CertificateSerial(789L));
    when(cqmock.iterator()).thenReturn(serials.iterator());
    when(this.certSerialCurator.listBySerialIds(eq(input))).thenReturn(cqmock);
    this.resource.unrevoke(input);
    verify(crlFileUtil).updateCRLFile(any(File.class), anyCollection(), anyCollection());
}
Also used : CertificateSerial(org.candlepin.model.CertificateSerial) CandlepinQuery(org.candlepin.model.CandlepinQuery) File(java.io.File) LinkedList(java.util.LinkedList) Test(org.junit.Test)

Aggregations

CertificateSerial (org.candlepin.model.CertificateSerial)46 Date (java.util.Date)23 Test (org.junit.Test)21 Consumer (org.candlepin.model.Consumer)16 IdentityCertificate (org.candlepin.model.IdentityCertificate)16 Entitlement (org.candlepin.model.Entitlement)11 EntitlementCertificate (org.candlepin.model.EntitlementCertificate)11 HashSet (java.util.HashSet)9 CandlepinQuery (org.candlepin.model.CandlepinQuery)9 Owner (org.candlepin.model.Owner)9 File (java.io.File)8 FileInputStream (java.io.FileInputStream)7 InputStream (java.io.InputStream)7 KeyPair (java.security.KeyPair)7 X509Certificate (java.security.cert.X509Certificate)7 ZipInputStream (java.util.zip.ZipInputStream)7 Principal (org.candlepin.auth.Principal)7 ConsumerType (org.candlepin.model.ConsumerType)7 HashMap (java.util.HashMap)6 KeyPair (org.candlepin.model.KeyPair)6