diff --git a/HIRS_AttestationCA/build.gradle b/HIRS_AttestationCA/build.gradle index 6f1d76e1..28a586b2 100644 --- a/HIRS_AttestationCA/build.gradle +++ b/HIRS_AttestationCA/build.gradle @@ -54,6 +54,9 @@ dependencies { testImplementation 'org.mockito:mockito-core:4.2.0' testImplementation 'org.springframework:spring-test:6.0.8' + compileOnly "com.github.spotbugs:spotbugs-annotations:${spotBugAnnotationVersion}" + annotationProcessor "com.github.spotbugs:spotbugs-annotations:${spotBugAnnotationVersion}" + // spring management compileOnly libs.lombok implementation libs.lombok diff --git a/HIRS_AttestationCA/config/spotbugs/spotbugs-exclude.xml b/HIRS_AttestationCA/config/spotbugs/spotbugs-exclude.xml index 5c601ccc..acdcaa9b 100644 --- a/HIRS_AttestationCA/config/spotbugs/spotbugs-exclude.xml +++ b/HIRS_AttestationCA/config/spotbugs/spotbugs-exclude.xml @@ -2,18 +2,18 @@ - + - + - + - + diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/AttestationCertificateAuthority.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/AttestationCertificateAuthority.java index 6ca834f8..f45c7269 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/AttestationCertificateAuthority.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/AttestationCertificateAuthority.java @@ -45,44 +45,42 @@ public abstract class AttestationCertificateAuthority { * A handle to the service used to validate the supply chain. */ private final SupplyChainValidationService supplyChainValidationService; - + private final ComponentResultRepository componentResultRepository; + private final CertificateRepository certificateRepository; + private final IssuedCertificateRepository issuedCertificateRepository; + private final ReferenceManifestRepository referenceManifestRepository; + private final DeviceRepository deviceRepository; + // private final DBManager tpm2ProvisionerStateDBManager; + private final ReferenceDigestValueRepository referenceDigestValueRepository; + private final PolicyRepository policyRepository; + private final TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository; + private final ComponentInfoRepository componentInfoRepository; + private final CertificateRequestProcessor certificateRequestHandler; + private final IdentityClaimProcessor identityClaimHandler; /** * Container wired application configuration property identifying the number of days that * certificates issued by this ACA are valid for. */ private Integer validDays = 1; - private final ComponentResultRepository componentResultRepository; - private ComponentInfoRepository componentInfoRepository; - private final CertificateRepository certificateRepository; - private final IssuedCertificateRepository issuedCertificateRepository; - private final ReferenceManifestRepository referenceManifestRepository; - private final DeviceRepository deviceRepository; -// private final DBManager tpm2ProvisionerStateDBManager; - private final ReferenceDigestValueRepository referenceDigestValueRepository; - private final PolicyRepository policyRepository; - private final TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository; - - private CertificateRequestProcessor certificateRequestHandler; - private IdentityClaimProcessor identityClaimHandler; - /** * Constructor. - * @param supplyChainValidationService the supply chain service - * @param privateKey the ACA private key - * @param acaCertificate the ACA certificate - * @param structConverter the struct converter - * @param componentResultRepository the component result manager - * @param componentInfoRepository the component info manager - * @param certificateRepository the certificate manager - * @param referenceManifestRepository the Reference Manifest manager - * @param validDays the number of days issued certs are valid - * @param deviceRepository the device manager + * + * @param supplyChainValidationService the supply chain service + * @param privateKey the ACA private key + * @param acaCertificate the ACA certificate + * @param structConverter the struct converter + * @param componentResultRepository the component result manager + * @param componentInfoRepository the component info manager + * @param certificateRepository the certificate manager + * @param issuedCertificateRepository the issued certificate repository + * @param referenceManifestRepository the Reference Manifest manager + * @param validDays the number of days issued certs are valid + * @param deviceRepository the device manager * @param referenceDigestValueRepository the reference event manager - * @param policyRepository policy setting repository + * @param policyRepository policy setting repository * @param tpm2ProvisionerStateRepository tpm2 provisioner state repository */ - @SuppressWarnings("checkstyle:parameternumber") public AttestationCertificateAuthority( final SupplyChainValidationService supplyChainValidationService, final PrivateKey privateKey, final X509Certificate acaCertificate, @@ -121,14 +119,31 @@ public abstract class AttestationCertificateAuthority { deviceRepository, tpm2ProvisionerStateRepository, policyRepository); } + /** + * Processes the provided identity claim. + * + * @param identityClaim a byte array representation of the identity claim + * @return processed identity claim response + */ byte[] processIdentityClaimTpm2(final byte[] identityClaim) { return this.identityClaimHandler.processIdentityClaimTpm2(identityClaim); } + /** + * Processes the provided certificate request. + * + * @param certificateRequest a byte array representation of the certificate request + * @return processed certificate request response + */ byte[] processCertificateRequest(final byte[] certificateRequest) { return this.certificateRequestHandler.processCertificateRequest(certificateRequest); } + /** + * Retrieves the encoded public key. + * + * @return encoded public key + */ public byte[] getPublicKey() { return acaCertificate.getPublicKey().getEncoded(); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/CriteriaModifier.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/CriteriaModifier.java index 452138f4..8c42b383 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/CriteriaModifier.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/CriteriaModifier.java @@ -4,10 +4,13 @@ import jakarta.persistence.criteria.CriteriaQuery; /** * Allows a user of the DBManager to modify the criteria object before processing. + * + * @param the parameter type */ public interface CriteriaModifier { /** * Allows a client to modify the criteria object by reference. + * * @param criteria The hibernate criteria builder object */ void modify(CriteriaQuery criteria); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/DBManagerException.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/DBManagerException.java index e68d1b2e..aec4ddc9 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/DBManagerException.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/DBManagerException.java @@ -12,8 +12,7 @@ public class DBManagerException extends RuntimeException { * Creates a new DBManagerException that has the message * msg. * - * @param msg - * exception message + * @param msg exception message */ public DBManagerException(final String msg) { super(msg); @@ -23,8 +22,7 @@ public class DBManagerException extends RuntimeException { * Creates a new DBManagerException that wraps the given * Throwable. * - * @param t - * root cause + * @param t root cause */ public DBManagerException(final Throwable t) { super(t); @@ -34,13 +32,11 @@ public class DBManagerException extends RuntimeException { * Creates a new DBManagerException that has the message * msg and wraps the root cause. * - * @param msg - * exception message - * @param t - * root cause + * @param msg exception message + * @param t root cause */ public DBManagerException(final String msg, final Throwable t) { super(msg, t); } -} \ No newline at end of file +} diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/FilteredRecordsList.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/FilteredRecordsList.java index 07c5d5d7..0fedb994 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/FilteredRecordsList.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/FilteredRecordsList.java @@ -14,8 +14,10 @@ import java.util.ArrayList; * @param Class accepts generic for the list of data records. */ @Data -@EqualsAndHashCode(callSuper=false) +@EqualsAndHashCode(callSuper = false) public class FilteredRecordsList extends ArrayList { - private long recordsTotal, recordsFiltered; + private long recordsTotal; + + private long recordsFiltered; } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/OrderedListQuerier.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/OrderedListQuerier.java index f303e0e4..63e93515 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/OrderedListQuerier.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/OrderedListQuerier.java @@ -5,6 +5,7 @@ import java.util.Map; /** * Interface defining methods for getting ordered lists from a data source. Includes * properties for sorting, paging, and searching. + * * @param the record type, T. */ public interface OrderedListQuerier { @@ -14,16 +15,16 @@ public interface OrderedListQuerier { * direction (ASC, DESC) that is provided by the user. This method helps * support the server-side processing in the JQuery DataTables. * - * @param clazz class type of Ts to search for (may be null to - * use Class<T>) - * @param columnToOrder Column to be ordered - * @param ascending direction of sort - * @param firstResult starting point of first result in set - * @param maxResults total number we want returned for display in table - * @param search string of criteria to be matched to visible columns + * @param clazz class type of Ts to search for (may be null to + * use Class<T>) + * @param columnToOrder Column to be ordered + * @param ascending direction of sort + * @param firstResult starting point of first result in set + * @param maxResults total number we want returned for display in table + * @param search string of criteria to be matched to visible columns * @param searchableColumns Map of String and boolean values with column - * headers and whether they should be searched. Boolean is true if field provides a - * typical String that can be searched by Hibernate without transformation. + * headers and whether they should be searched. Boolean is true if field provides + * a typical String that can be searched by Hibernate without transformation. * @return FilteredRecordsList object with query data * @throws DBManagerException if unable to create the list */ @@ -41,21 +42,20 @@ public interface OrderedListQuerier { * support the server-side processing in the JQuery DataTables. For entities that support * soft-deletes, the returned list does not contain Ts that have been soft-deleted. * - * @param clazz class type of Ts to search for (may be null to - * use Class<T>) - * @param columnToOrder Column to be ordered - * @param ascending direction of sort - * @param firstResult starting point of first result in set - * @param maxResults total number we want returned for display in table - * @param search string of criteria to be matched to visible columns + * @param clazz class type of Ts to search for (may be null to + * use Class<T>) + * @param columnToOrder Column to be ordered + * @param ascending direction of sort + * @param firstResult starting point of first result in set + * @param maxResults total number we want returned for display in table + * @param search string of criteria to be matched to visible columns * @param searchableColumns Map of String and boolean values with column - * headers and whether they should be searched. Boolean is true if field provides a - * typical String that can be searched by Hibernate without transformation. - * @param criteriaModifier a way to modify the criteria used in the query + * headers and whether they should be searched. Boolean is true if field provides + * a typical String that can be searched by Hibernate without transformation. + * @param criteriaModifier a way to modify the criteria used in the query * @return FilteredRecordsList object with query data * @throws DBManagerException if unable to create the list */ - @SuppressWarnings("checkstyle:parameternumber") FilteredRecordsList getOrderedList( Class clazz, String columnToOrder, boolean ascending, int firstResult, diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/RestfulAttestationCertificateAuthority.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/RestfulAttestationCertificateAuthority.java index 5914cd40..db00267d 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/RestfulAttestationCertificateAuthority.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/RestfulAttestationCertificateAuthority.java @@ -33,13 +33,13 @@ import java.security.cert.X509Certificate; // detects if file exists, if not, ignore errors @PropertySource(value = "file:/etc/hirs/aca/application.properties", ignoreResourceNotFound = true), - @PropertySource(value = "file:C:/ProgramData/hirs/aca/application.win.properties", ignoreResourceNotFound = true) }) @RestController @RequestMapping("/HIRS_AttestationCA") -public class RestfulAttestationCertificateAuthority extends AttestationCertificateAuthority implements RestfulInterface { +public class RestfulAttestationCertificateAuthority extends AttestationCertificateAuthority + implements RestfulInterface { /** * Constructor. @@ -47,8 +47,11 @@ public class RestfulAttestationCertificateAuthority extends AttestationCertifica * @param supplyChainValidationService scp service * @param privateKey the ACA private key * @param acaCertificate the ACA certificate + * @param structConverter the struct converter * @param componentResultRepository the component result repository + * @param componentInfoRepository the component info repository * @param certificateRepository the certificate manager + * @param issuedCertificateRepository the issued certificate repository * @param referenceManifestRepository the referenceManifestManager * @param validDays the number of days issued certs are valid * @param deviceRepository the device manager @@ -56,11 +59,11 @@ public class RestfulAttestationCertificateAuthority extends AttestationCertifica * @param policyRepository the provisioning policy entity * @param tpm2ProvisionerStateRepository the provisioner state */ - @SuppressWarnings({"checkstyle:parameternumber"}) @Autowired public RestfulAttestationCertificateAuthority( final SupplyChainValidationService supplyChainValidationService, - final PrivateKey privateKey, final X509Certificate acaCertificate, + final PrivateKey privateKey, + final X509Certificate acaCertificate, final StructConverter structConverter, final ComponentResultRepository componentResultRepository, final ComponentInfoRepository componentInfoRepository, @@ -82,7 +85,7 @@ public class RestfulAttestationCertificateAuthority extends AttestationCertifica /** * Listener for identity requests from TPM 2.0 provisioning. - * + *

* Processes a given IdentityClaim and generates a response * containing an encrypted nonce to be returned by the client in * a future handshake request. @@ -105,7 +108,7 @@ public class RestfulAttestationCertificateAuthority extends AttestationCertifica * the client's desired attestation key, if the correct nonce is supplied. * * @param certificateRequest request containing nonce from earlier identity - * * claim handshake + * * claim handshake * @return The response to the client provisioner. */ @Override @@ -121,8 +124,8 @@ public class RestfulAttestationCertificateAuthority extends AttestationCertifica * (non-javadoc) *

* Wrap the {@link AttestationCertificateAuthority#getPublicKey()} with a Spring - * {@link org.springframework.web.bind.annotation.RequestMapping} such that Spring can serialize the certificate to be returned to an - * HTTP Request. + * {@link org.springframework.web.bind.annotation.RequestMapping} such that Spring can serialize + * the certificate to be returned to an HTTP Request. */ @Override @ResponseBody diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/RestfulInterface.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/RestfulInterface.java index e6c8eeaf..a4bb8a00 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/RestfulInterface.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/RestfulInterface.java @@ -5,8 +5,20 @@ package hirs.attestationca.persist; */ public interface RestfulInterface { + /** + * Processes the provided identity claim. + * + * @param identityClaim a byte array representation of the identity claim + * @return a byte array representation of the identity claim response + */ byte[] processIdentityClaimTpm2(byte[] identityClaim); + /** + * Processes the provided certificate request. + * + * @param certificateRequest a byte array representation of the certificate request + * @return a byte array representation of the certificate request response + */ byte[] processCertificateRequest(byte[] certificateRequest); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/AbstractEntity.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/AbstractEntity.java index 67755c06..8ab564a2 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/AbstractEntity.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/AbstractEntity.java @@ -32,7 +32,7 @@ public abstract class AbstractEntity implements Serializable { @Getter private UUID id; - @Column (name = "create_time") + @Column(name = "create_time") private Date createTime; /** @@ -47,9 +47,10 @@ public abstract class AbstractEntity implements Serializable { /** * Setter for the UUID that can not be null * and can not be overridden. + * * @param id - primary able key */ - public void setId(UUID id) { + public void setId(final UUID id) { if (id != null) { this.id = id; } @@ -74,6 +75,11 @@ public abstract class AbstractEntity implements Serializable { createTime.setTime(new Date().getTime()); } + /** + * Generates an integer hash code for this entity. + * + * @return hash code + */ @Override public int hashCode() { if (id != null) { @@ -82,6 +88,13 @@ public abstract class AbstractEntity implements Serializable { return super.hashCode(); } + /** + * Compares this entity to the provided object to verify + * that both objects are equal. + * + * @param object object to compare + * @return true if they are equal, false otherwise + */ @Override public boolean equals(final Object object) { if (this == object) { diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/Appraiser.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/Appraiser.java index 8c5fb78b..d64b2de7 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/Appraiser.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/Appraiser.java @@ -6,7 +6,11 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; -import lombok.*; +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.ToString; /** * The Appraiser class represents an appraiser that can appraise a Report. diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/ArchivableEntity.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/ArchivableEntity.java index c209df3e..295a159d 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/ArchivableEntity.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/ArchivableEntity.java @@ -55,9 +55,8 @@ public abstract class ArchivableEntity extends AbstractEntity { * Signals that this entity has been archived, by setting the archivedTime to the current date * and time. * - * @return - * true if time was null and date was set. - * false is archived time is already set, signifying the entity has been archived. + * @return true if time was null and date was set. + * false is archived time is already set, signifying the entity has been archived. */ public final boolean archive() { if (this.archivedTime == null) { @@ -73,8 +72,7 @@ public abstract class ArchivableEntity extends AbstractEntity { * purposes so the reason for action taken can be referenced. * * @param description - description of the action taken for resolution - * @return - * boolean result is dependent on the return value of the archive() method + * @return boolean result is dependent on the return value of the archive() method */ public final boolean archive(final String description) { if (archive()) { @@ -90,7 +88,7 @@ public abstract class ArchivableEntity extends AbstractEntity { * entity has not been resolved, then null is returned. * * @return archivedTime - * If entity was archived, timestamp of the occurrence, null otherwise. + * If entity was archived, timestamp of the occurrence, null otherwise. */ public final Date getArchivedTime() { if (archivedTime == null) { @@ -104,9 +102,8 @@ public abstract class ArchivableEntity extends AbstractEntity { * Sets the archivedTime to null. The archivedTime being null signifies that the entity has * not been archived. If the time is already null then this call was unnecessary. * - * @return - * true if the time is changed to null. - * false if time was already set to null. + * @return true if the time is changed to null. + * false if time was already set to null. */ public final boolean restore() { if (this.archivedTime != null) { diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/Policy.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/Policy.java index d4b1cb24..2e8648bb 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/Policy.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/Policy.java @@ -16,7 +16,7 @@ import jakarta.persistence.MappedSuperclass; @Inheritance(strategy = InheritanceType.JOINED) @Access(AccessType.FIELD) @MappedSuperclass -public abstract class Policy extends UserDefinedEntity { +public abstract class Policy extends UserDefinedEntity { /** * Default empty constructor is required for Hibernate. It is protected to @@ -29,8 +29,7 @@ public abstract class Policy extends UserDefinedEntity { /** * Creates a new Policy with the specified name. * - * @param name - * name + * @param name name */ public Policy(final String name) { super(name); @@ -40,10 +39,8 @@ public abstract class Policy extends UserDefinedEntity { * Creates a new Policy with the specified name and * description. * - * @param name - * name (required) - * @param description - * description (may be null) + * @param name name (required) + * @param description description (may be null) */ public Policy(final String name, final String description) { super(name, description); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/UserDefinedEntity.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/UserDefinedEntity.java index ca38680d..f061a8f0 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/UserDefinedEntity.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/UserDefinedEntity.java @@ -4,9 +4,9 @@ import jakarta.persistence.Column; import jakarta.persistence.MappedSuperclass; import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NonNull; import lombok.Setter; import lombok.ToString; -import lombok.NonNull; /** * An abstract archivable entity that can be given a user-defined name and description. @@ -18,11 +18,13 @@ import lombok.NonNull; public abstract class UserDefinedEntity extends ArchivableEntity { @Column(nullable = false, unique = true) - @NonNull private String name; + @NonNull + private String name; @ToString.Exclude @Column(nullable = false, unique = false) - @NonNull private String description = ""; + @NonNull + private String description = ""; /** * Default empty constructor is required for Hibernate. It is protected to @@ -47,8 +49,7 @@ public abstract class UserDefinedEntity extends ArchivableEntity { * an instance of UserDefinedEntity and its name is the same as this * UserDefinedEntity. Otherwise this returns false. * - * @param other - * other object to test for equals + * @param other other object to test for equals * @return true if other is Baseline and has same name */ @Override @@ -56,11 +57,10 @@ public abstract class UserDefinedEntity extends ArchivableEntity { if (this == other) { return true; } - if (!(other instanceof UserDefinedEntity)) { + if (!(other instanceof UserDefinedEntity entity)) { return false; } - final UserDefinedEntity entity = (UserDefinedEntity) other; return this.getName().equals(entity.getName()); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/CACredentialRepository.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/CACredentialRepository.java index 253d0a3d..1319399e 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/CACredentialRepository.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/CACredentialRepository.java @@ -12,12 +12,77 @@ import java.util.UUID; @Repository public interface CACredentialRepository extends JpaRepository { + /** + * Query that retrieves a list of certificate authority credentials using the provided archive flag. + * + * @param archiveFlag archive flag + * @return a list of certificate authority credentials + */ List findByArchiveFlag(boolean archiveFlag); + + /** + * Query that retrieves a page of certificate authority credentials using the provided archive + * flag and the provided pageable. + * + * @param archiveFlag archive flag + * @param pageable pageable + * @return a page of certificate authority credentials + */ Page findByArchiveFlag(boolean archiveFlag, Pageable pageable); + + /** + * Query that retrieves a list of certificate authority credentials using the provided subject. + * + * @param subject subject + * @return a list of certificate authority credentials + */ List findBySubject(String subject); + + /** + * Query that retrieves a sorted list of certificate authority credentials using the provided subject. + * + * @param subject subject + * @return a sorted list of certificate authority credentials + */ List findBySubjectSorted(String subject); + + /** + * Query that retrieves a list of certificate authority credentials using the provided subject + * and the provided archive flag. + * + * @param subject subject + * @param archiveFlag archive flag + * @return a list of certificate authority credentials + */ List findBySubjectAndArchiveFlag(String subject, boolean archiveFlag); - List findBySubjectSortedAndArchiveFlag(String subject, boolean archiveFlag); + + /** + * Query that retrieves a sorted list of certificate authority credentials using the provided subject + * and the provided archive flag. + * + * @param subject subject + * @param archiveFlag archive flag + * @return a sorted list of certificate authority credentials + */ + List findBySubjectSortedAndArchiveFlag(String subject, + boolean archiveFlag); + + /** + * Query that retrieves a certificate authority credential using the provided subject key identifier. + * + * @param subjectKeyIdentifier byte array representation of the subject key identifier + * @return a certificate authority credential + */ CertificateAuthorityCredential findBySubjectKeyIdentifier(byte[] subjectKeyIdentifier); - CertificateAuthorityCredential findBySubjectKeyIdStringAndArchiveFlag(String subjectKeyIdString, boolean archiveFlag); + + /** + * Query that retrieves a certificate authority credential using the provided subject key identifier + * and the provided archive flag. + * + * @param subjectKeyIdString string representation of the subject key id + * @param archiveFlag archive flag + * @return a certificate authority credential + */ + CertificateAuthorityCredential findBySubjectKeyIdStringAndArchiveFlag(String subjectKeyIdString, + boolean archiveFlag); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/CertificateRepository.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/CertificateRepository.java index cfdfd10a..ee4f5a7a 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/CertificateRepository.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/CertificateRepository.java @@ -16,26 +16,129 @@ import java.util.UUID; @Repository public interface CertificateRepository extends JpaRepository { + /** + * Query that retrieves a certificate using the provided uuid. + * + * @param uuid uuid + * @return a certificate + */ @Query(value = "SELECT * FROM Certificate where id = ?1", nativeQuery = true) Certificate getCertificate(UUID uuid); + + /** + * Query that retrieves a list of certificates using the provided subject and dtype. + * + * @param subject subject + * @param dType dtype + * @return a list of certificates + */ @Query(value = "SELECT * FROM Certificate where subject = ?1 AND DTYPE = ?2", nativeQuery = true) List findBySubject(String subject, String dType); + + /** + * Query that retrieves a sorted list of certificates using the provided subject and dtype. + * + * @param subjectSorted subject + * @param dType dtype + * @return a list of sorted certificates + */ @Query(value = "SELECT * FROM Certificate where subjectSorted = ?1 AND DTYPE = ?2", nativeQuery = true) List findBySubjectSorted(String subjectSorted, String dType); + + /** + * Query that retrieves a list of certificates using the provided dtype. + * + * @param dType dtype + * @return a list of certificates + */ @Query(value = "SELECT * FROM Certificate where DTYPE = ?1", nativeQuery = true) List findByType(String dType); + + /** + * Query that retrieves a list of certificates using the provided serial number and dtype. + * + * @param serialNumber serial number + * @param dType dtype + * @return a certificate + */ @Query(value = "SELECT * FROM Certificate where serialNumber = ?1 AND DTYPE = ?2", nativeQuery = true) Certificate findBySerialNumber(BigInteger serialNumber, String dType); - @Query(value = "SELECT * FROM Certificate where platformSerial = ?1 AND DTYPE = 'PlatformCredential'", nativeQuery = true) + + /** + * Query that retrieves a list of platform credentials using the provided board serial number + * and a dtype of "Platform Credential". + * + * @param boardSerialNumber board serial number + * @return a list of platform credentials + */ + @Query(value = "SELECT * FROM Certificate where platformSerial = ?1 AND DTYPE = 'PlatformCredential'", + nativeQuery = true) List byBoardSerialNumber(String boardSerialNumber); - @Query(value = "SELECT * FROM Certificate where holderSerialNumber = ?1 AND DTYPE = 'PlatformCredential'", nativeQuery = true) + + /** + * Query that retrieves a platform credential using the provided holder serial number + * and a dtype of "Platform Credential". + * + * @param holderSerialNumber holder serial number + * @return platform credential + */ + @Query(value = "SELECT * FROM Certificate where holderSerialNumber = ?1 AND DTYPE = 'PlatformCredential'", + nativeQuery = true) PlatformCredential getPcByHolderSerialNumber(BigInteger holderSerialNumber); - @Query(value = "SELECT * FROM Certificate where holderSerialNumber = ?1 AND DTYPE = 'PlatformCredential'", nativeQuery = true) + + /** + * Query that retrieves a list of platform credentials using the provided holder serial number + * and a dtype of "Platform Credential". + * + * @param holderSerialNumber holder serial numberz + * @return a list of platform credentials + */ + @Query(value = "SELECT * FROM Certificate where holderSerialNumber = ?1 AND DTYPE = 'PlatformCredential'", + nativeQuery = true) List getByHolderSerialNumber(BigInteger holderSerialNumber); + + /** + * Query that retrieves a certificate using the provided certificate hash and dtype. + * + * @param certificateHash integer certificate hash + * @param dType dtype + * @return a certificate + */ @Query(value = "SELECT * FROM Certificate where certificateHash = ?1 AND DTYPE = ?2", nativeQuery = true) Certificate findByCertificateHash(int certificateHash, String dType); + + /** + * Query that retrieves an endorssement credential using the provided public key modulus hex value. + * + * @param publicKeyModulusHexValue public key modulus hex value + * @return an endorsement credential + */ EndorsementCredential findByPublicKeyModulusHexValue(String publicKeyModulusHexValue); + + /** + * Query that retrieves an issued attestation certificate using the provided device id. + * + * @param deviceId uuid representation of the device id + * @return an issued attestation certificate + */ IssuedAttestationCertificate findByDeviceId(UUID deviceId); + + /** + * Query that retrieves a list of issued attestation certificates using the provided device id, + * isLDevID value and sort value. + * + * @param deviceId device id + * @param isLDevID is it a LDevId + * @param sort sort + * @return a list of issued attestation certificates + */ List findByDeviceIdAndIsLDevID(UUID deviceId, boolean isLDevID, Sort sort); + + /** + * Query that retrieves a certificates using the provided certificate hash. + * + * @param certificateHash integer certificate hash + * @return a certificate + */ Certificate findByCertificateHash(int certificateHash); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/ComponentAttributeRepository.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/ComponentAttributeRepository.java index bfa10117..87e4c9b4 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/ComponentAttributeRepository.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/ComponentAttributeRepository.java @@ -10,6 +10,7 @@ public interface ComponentAttributeRepository extends JpaRepository findByComponentIdAndProvisionSessionId(UUID componentId, UUID provisionSessionId); + List findByComponentIdAndProvisionSessionId(UUID componentId, + UUID provisionSessionId); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/ComponentInfoRepository.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/ComponentInfoRepository.java index 67fec4f0..919c0494 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/ComponentInfoRepository.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/ComponentInfoRepository.java @@ -9,6 +9,7 @@ import java.util.UUID; public interface ComponentInfoRepository extends JpaRepository { /** * Query that retrieves device components by device name. + * * @param deviceName string for the host name * @return a list of device components */ @@ -17,7 +18,8 @@ public interface ComponentInfoRepository extends JpaRepository findByBoardSerialNumberAndDelta(String boardSerialNumber, boolean delta); /** * Query based on certificate serial number and device serial number. + * * @param certificateSerialNumber certificate specific serial number - * @param boardSerialNumber variable holding the device serial number + * @param boardSerialNumber variable holding the device serial number * @return a list of component result. */ List findByCertificateSerialNumberAndBoardSerialNumber( diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/DeviceRepository.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/DeviceRepository.java index fb3c331b..e708812e 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/DeviceRepository.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/DeviceRepository.java @@ -8,5 +8,11 @@ import java.util.UUID; @Repository public interface DeviceRepository extends JpaRepository { + /** + * Query that retrieves a device using the provided device name. + * + * @param deviceName device name + * @return a device + */ Device findByName(String deviceName); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/EndorsementCredentialRepository.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/EndorsementCredentialRepository.java index 6ba43285..dbf09fdf 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/EndorsementCredentialRepository.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/EndorsementCredentialRepository.java @@ -13,9 +13,44 @@ import java.util.UUID; @Repository public interface EndorsementCredentialRepository extends JpaRepository { + /** + * Query that retrieves a list of endorsement credentials using the provided archive flag. + * + * @param archiveFlag archive flag + * @return a list of endorsement credentials + */ List findByArchiveFlag(boolean archiveFlag); + + /** + * Query that retrieves a page of endorsement credentials using provided archive flag and pageable value. + * + * @param archiveFlag archive flag + * @param pageable pageable value + * @return a page of endorsement credentials + */ Page findByArchiveFlag(boolean archiveFlag, Pageable pageable); + + /** + * Query that retrieves an endorsement credential using the provided holder serial number. + * + * @param holderSerialNumber big integer representation of the holder serial number + * @return an endorsement credential + */ EndorsementCredential findByHolderSerialNumber(BigInteger holderSerialNumber); + + /** + * Query that retrieves an endorsement credential using the provided serial number. + * + * @param serialNumber big integer representation of the serial number + * @return an endorsement credential + */ EndorsementCredential findBySerialNumber(BigInteger serialNumber); + + /** + * Query that retrieves a list of endorsement credentials using the provided device id. + * + * @param deviceId uuid representation of the device id + * @return an endorsement credential + */ List findByDeviceId(UUID deviceId); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/IDevIDCertificateRepository.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/IDevIDCertificateRepository.java index 5fd72a43..b8d062a0 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/IDevIDCertificateRepository.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/IDevIDCertificateRepository.java @@ -12,14 +12,74 @@ import java.util.UUID; @Repository public interface IDevIDCertificateRepository extends JpaRepository { + /** + * Query that retrieves a list of IDevId certificates using the provided archive flag. + * + * @param archiveFlag archive flag + * @return a list of IDevId certificates + */ List findByArchiveFlag(boolean archiveFlag); - Page findByArchiveFlag(boolean archiveFlag, Pageable pageable); - /*List findBySubject(String subject); - List findBySubjectSorted(String subject); - List findBySubjectAndArchiveFlag(String subject, boolean archiveFlag); - List findBySubjectSortedAndArchiveFlag(String subject, boolean archiveFlag); - IDevIDCertificate findBySubjectKeyIdentifier(byte[] subjectKeyIdentifier); - IDevIDCertificate findBySubjectKeyIdStringAndArchiveFlag(String subjectKeyIdString, boolean archiveFlag); + /** + * Query that retrieves a page of IDevId certificates using the provided archive flag and pageable value. + * + * @param archiveFlag archive flag + * @param pageable pageable value + * @return a page of IDevId certificates */ -} \ No newline at end of file + Page findByArchiveFlag(boolean archiveFlag, Pageable pageable); + + + // /** +// * Query that retrieves a list of IDevId certificates using the provided subject. +// * +// * @param subject string representation of the subject +// * @return a list of IDevId certificates +// */ +// List findBySubject(String subject); +// +// /** +// * Query that retrieves a sorted list of IDevId certificates using the provided subject. +// * +// * @param subject string representation of the subject +// * @return a sorted list of IDevId certificates +// */ +// List findBySubjectSorted(String subject); +// +// /** +// * Query that retrieves a list of IDevId certificates using the provided subject and archive flag. +// * +// * @param subject string representation of the subject +// * @param archiveFlag archive flag +// * @return a list of IDevId certificates +// */ +// List findBySubjectAndArchiveFlag(String subject, boolean archiveFlag); +// +// /** +// * Query that retrieves a sorted list of IDevId certificates using the provided subject +// * and archive flag. +// * +// * @param subject string representation of the subject +// * @param archiveFlag archive flag +// * @return a sorted list of IDevId certificates +// */ +// List findBySubjectSortedAndArchiveFlag(String subject, boolean archiveFlag); +// +// /** +// * Query that retrieves an IDevId certificate using the provided subject key identifier. +// * +// * @param subjectKeyIdentifier byte representation of the subject key identifier +// * @return an IDevId certificate +// */ +// IDevIDCertificate findBySubjectKeyIdentifier(byte[] subjectKeyIdentifier); +// +// /** +// * Query that retrieves an IDevId certificate using the provided subject key and archive flag. +// * +// * @param subjectKeyIdString string representation of the subject key id +// * @param archiveFlag archive flag +// * @return an IDevId certificate +// */ +// IDevIDCertificate findBySubjectKeyIdStringAndArchiveFlag(String subjectKeyIdString, +// boolean archiveFlag); +} diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/IssuedCertificateRepository.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/IssuedCertificateRepository.java index 9ceb14e6..0d50494f 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/IssuedCertificateRepository.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/IssuedCertificateRepository.java @@ -12,7 +12,29 @@ import java.util.UUID; @Repository public interface IssuedCertificateRepository extends JpaRepository { + /** + * Query that retrieves a list of issued attestation certificates using the provided archive flag. + * + * @param archiveFlag archive flag + * @return a list of issued attestation certificates + */ List findByArchiveFlag(boolean archiveFlag); + + /** + * Query that retrieves a page of issued attestation certificates using the provided archive flag + * and pageable value. + * + * @param archiveFlag archive flag + * @param pageable pageable value + * @return a page of issued attestation certificates + */ Page findByArchiveFlag(boolean archiveFlag, Pageable pageable); + + /** + * Query that retrieves a list of issued attestation certificates using the provided device id. + * + * @param deviceId uuid representation of the device id + * @return a list of issued attestation certificates + */ List findByDeviceId(UUID deviceId); -} \ No newline at end of file +} diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/PlatformCertificateRepository.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/PlatformCertificateRepository.java index 690d82ca..ad7a4190 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/PlatformCertificateRepository.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/PlatformCertificateRepository.java @@ -12,7 +12,29 @@ import java.util.UUID; @Repository public interface PlatformCertificateRepository extends JpaRepository { + /** + * Query that retrieves a list of platform credentials using the provided archive flag. + * + * @param archiveFlag archive flag + * @return a list of platform credentials + */ List findByArchiveFlag(boolean archiveFlag); + + /** + * Query that retrieves a page of platform credentials using the provided archive flag + * and pageable value. + * + * @param archiveFlag archive flag + * @param pageable pageable + * @return a page of platform credentials + */ Page findByArchiveFlag(boolean archiveFlag, Pageable pageable); + + /** + * Query that retrieves a list of platform credentials using the provided device id. + * + * @param deviceId uuid representation of the device id + * @return a list of platform credentials + */ List findByDeviceId(UUID deviceId); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/PolicyRepository.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/PolicyRepository.java index 78c48cde..ae30b966 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/PolicyRepository.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/PolicyRepository.java @@ -8,5 +8,12 @@ import java.util.UUID; @Repository public interface PolicyRepository extends JpaRepository { + + /** + * Query that retrieves policy settings using the provided name. + * + * @param name name + * @return policy settings + */ PolicySettings findByName(String name); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/ReferenceDigestValueRepository.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/ReferenceDigestValueRepository.java index 0d967757..008c2abe 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/ReferenceDigestValueRepository.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/ReferenceDigestValueRepository.java @@ -10,10 +10,52 @@ import java.util.UUID; @Repository public interface ReferenceDigestValueRepository extends JpaRepository { + /** + * Query that retrieves a list of reference digest values using the provided model. + * + * @param model string representation of the model + * @return a list of reference digest values + */ List findByModel(String model); + + /** + * Query that retrieves a list of reference digest values using the provided manufacturer. + * + * @param manufacturer string representation of the manufacturer + * @return a list of reference digest values + */ List findByManufacturer(String manufacturer); + + /** + * Query that retrieves a list of reference digest values using the provided associated rim id. + * + * @param associatedRimId uuid representation of the associated rim ID + * @return a list of reference digest values + */ List findValuesByBaseRimId(UUID associatedRimId); + + /** + * Query that retrieves a list of reference digest values using the provided support rim id. + * + * @param supportRimId uuid representation of the support rim ID + * @return a list of reference digest values + */ List findBySupportRimId(UUID supportRimId); + + /** + * Query that retrieves a list of reference digest values using the provided support rim hash. + * + * @param supportRimHash a string representation of the support rim hash + * @return a list of reference digest values + */ List findBySupportRimHash(String supportRimHash); + + /** + * Query that retrieves a list of reference digest values using the provided manufacturer and model. + * + * @param manufacturer string representation of the manufacturer + * @param model string representation of the model + * @return a list of reference digest values + */ List findByManufacturerAndModel(String manufacturer, String model); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/ReferenceManifestRepository.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/ReferenceManifestRepository.java index 53884809..5f145fb0 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/ReferenceManifestRepository.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/ReferenceManifestRepository.java @@ -15,36 +15,193 @@ import java.util.UUID; @Repository public interface ReferenceManifestRepository extends JpaRepository { - + /** + * Query that retrieves a reference manifest using the provided hex/dec hash. + * + * @param hexDecHash string representation of the hex dec hash + * @return a reference manifest + */ ReferenceManifest findByHexDecHash(String hexDecHash); + + /** + * Query that retrieves a reference manifest using the provided base 64 hash. + * + * @param base64Hash string representation of the base 64 hash + * @return a reference manifest + */ ReferenceManifest findByBase64Hash(String base64Hash); + + /** + * Query that retrieves a reference manifest using the provided hex/dec hash and rim type. + * + * @param hexDecHash string representation of the hex dec hash + * @param rimType string representation of the rim type + * @return a reference manifest + */ ReferenceManifest findByHexDecHashAndRimType(String hexDecHash, String rimType); + + /** + * Query that retrieves a reference manifest using the provided event log hash and rim type. + * + * @param hexDecHash string representation of the event log hash + * @param rimType string representation of the rim type + * @return a reference manifest + */ ReferenceManifest findByEventLogHashAndRimType(String hexDecHash, String rimType); - @Query(value = "SELECT * FROM ReferenceManifest WHERE platformManufacturer = ?1 AND platformModel = ?2 AND rimType = 'Base'", nativeQuery = true) + + /** + * Query that retrieves a list of base reference manifests using the provided manufacturer and model + * and where the rim type is equal to base. + * + * @param manufacturer string representation of platform manufacturer + * @param model string representation of platform model + * @return a list of base reference manifests + */ + @Query(value = "SELECT * FROM ReferenceManifest WHERE platformManufacturer = ?1 AND platformModel = ?2 " + + "AND rimType = 'Base'", nativeQuery = true) List getBaseByManufacturerModel(String manufacturer, String model); - @Query(value = "SELECT * FROM ReferenceManifest WHERE platformManufacturer = ?1 AND DTYPE = ?2", nativeQuery = true) + + /** + * Query that retrieves a list of base reference manifests using the provided manufacturer and model. + * + * @param manufacturer string representation of platform manufacturer + * @param dType dtype + * @return a list of base reference manifests + */ + @Query(value = "SELECT * FROM ReferenceManifest WHERE platformManufacturer = ?1 AND DTYPE = ?2", + nativeQuery = true) List getByManufacturer(String manufacturer, String dType); - @Query(value = "SELECT * FROM ReferenceManifest WHERE platformModel = ?1 AND DTYPE = ?2", nativeQuery = true) + + /** + * Query that retrieves a reference manifest using the provided model and dtype. + * + * @param model string representation of platform model + * @param dType dtype + * @return a reference manifest + */ + @Query(value = "SELECT * FROM ReferenceManifest WHERE platformModel = ?1 AND DTYPE = ?2", + nativeQuery = true) ReferenceManifest getByModel(String model, String dType); - @Query(value = "SELECT * FROM ReferenceManifest WHERE DTYPE = 'BaseReferenceManifest'", nativeQuery = true) + + /** + * Query that retrieves a list of base reference manifests where the dtype is a base reference manifest. + * + * @return a list of base reference manifests + */ + @Query(value = "SELECT * FROM ReferenceManifest WHERE DTYPE = 'BaseReferenceManifest'", + nativeQuery = true) List findAllBaseRims(); - @Query(value = "SELECT * FROM ReferenceManifest WHERE DTYPE = 'SupportReferenceManifest'", nativeQuery = true) + + /** + * Query that retrieves a list of support reference manifests where the dtype is a + * support reference manifest. + * + * @return a list of support reference manifests + */ + @Query(value = "SELECT * FROM ReferenceManifest WHERE DTYPE = 'SupportReferenceManifest'", + nativeQuery = true) List findAllSupportRims(); - @Query(value = "SELECT * FROM ReferenceManifest WHERE id = ?1 AND DTYPE = 'BaseReferenceManifest'", nativeQuery = true) + + /** + * Query that retrieves a base reference manifest using the provided uuid and where the dtype is a + * base reference manifest. + * + * @param uuid uuid + * @return a base reference manifest + */ + @Query(value = "SELECT * FROM ReferenceManifest WHERE id = ?1 AND DTYPE = 'BaseReferenceManifest'", + nativeQuery = true) BaseReferenceManifest getBaseRimEntityById(UUID uuid); - @Query(value = "SELECT * FROM ReferenceManifest WHERE id = ?1 AND DTYPE = 'SupportReferenceManifest'", nativeQuery = true) + + /** + * Query that retrieves a support reference manifest using the provided uuid and + * where the dtype is a support reference manifest. + * + * @param uuid uuid + * @return a support reference manifest + */ + @Query(value = "SELECT * FROM ReferenceManifest WHERE id = ?1 AND DTYPE = 'SupportReferenceManifest'", + nativeQuery = true) SupportReferenceManifest getSupportRimEntityById(UUID uuid); - @Query(value = "SELECT * FROM ReferenceManifest WHERE id = ?1 AND DTYPE = 'EventLogMeasurements'", nativeQuery = true) + + /** + * Query that retrieves event log measurements using the provided uuid and where the dtype is an + * event log measurement. + * + * @param uuid uuid + * @return event log measurements + */ + @Query(value = "SELECT * FROM ReferenceManifest WHERE id = ?1 AND DTYPE = 'EventLogMeasurements'", + nativeQuery = true) EventLogMeasurements getEventLogRimEntityById(UUID uuid); - @Query(value = "SELECT * FROM ReferenceManifest WHERE deviceName = ?1 AND DTYPE = 'SupportReferenceManifest'", nativeQuery = true) + + /** + * Query that retrieves a list of support reference manifests using the provided device name and where the + * dtype is a support reference manifest. + * + * @param deviceName string representation of the device name + * @return a list of support reference manifests + */ + @Query(value = "SELECT * FROM ReferenceManifest WHERE deviceName = ?1 " + + "AND DTYPE = 'SupportReferenceManifest'", nativeQuery = true) List byDeviceName(String deviceName); - @Query(value = "SELECT * FROM ReferenceManifest WHERE deviceName = ?1 AND DTYPE = 'EventLogMeasurements'", nativeQuery = true) + + /** + * Query that retrieves event log measurements using the provided device name and where the dtype is + * event log measurements. + * + * @param deviceName string representation of the device name + * @return event log measurements + */ + @Query(value = "SELECT * FROM ReferenceManifest WHERE deviceName = ?1 " + + "AND DTYPE = 'EventLogMeasurements'", nativeQuery = true) EventLogMeasurements byMeasurementDeviceName(String deviceName); - @Query(value = "SELECT * FROM ReferenceManifest WHERE platformManufacturer = ?1 AND platformModel = ?2 AND rimType = 'Support'", nativeQuery = true) + + /** + * Query that retrieves a list of support reference manifests using the provided manufacturer and platform + * model and where the rim type is support. + * + * @param manufacturer string representation of platform manufacturer + * @param model string representation of platform model + * @return a list of support reference manifests + */ + @Query(value = "SELECT * FROM ReferenceManifest WHERE platformManufacturer = ?1 AND platformModel = ?2 " + + "AND rimType = 'Support'", nativeQuery = true) List getSupportByManufacturerModel(String manufacturer, String model); - @Query(value = "SELECT * FROM ReferenceManifest WHERE platformModel = ?1 AND DTYPE = 'EventLogMeasurements'", nativeQuery = true) + + /** + * Query that retrieves event log measurements using the provided platform model and where the dtype is + * event log measurements. + * + * @param model string representation of platform model. + * @return event log measurements + */ + @Query(value = "SELECT * FROM ReferenceManifest WHERE platformModel = ?1 " + + "AND DTYPE = 'EventLogMeasurements'", nativeQuery = true) EventLogMeasurements getLogByModel(String model); + + /** + * Query that retrieves a list of reference manifests using the provided device name. + * + * @param deviceName string representation of device name + * @return a list of reference manifests + */ List findByDeviceName(String deviceName); + + /** + * Query that retrieves a list of reference manifests using the provided archive flag. + * + * @param archiveFlag archive flag + * @return a list of reference manifests + */ List findByArchiveFlag(boolean archiveFlag); + + /** + * Query that retrieves a page of reference manifests using the provided archive flag and pageable value. + * + * @param archiveFlag archive flag + * @param pageable pageable + * @return a page of reference manifests + */ Page findByArchiveFlag(boolean archiveFlag, Pageable pageable); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/SupplyChainValidationRepository.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/SupplyChainValidationRepository.java index 161273fa..6e6da523 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/SupplyChainValidationRepository.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/SupplyChainValidationRepository.java @@ -9,6 +9,19 @@ import java.util.UUID; @Repository public interface SupplyChainValidationRepository extends JpaRepository { + /** + * Query that retrieves a list of supply chain validation using the provided validate type. + * + * @param validateType string representation of the validate type + * @return a list of supply chain validation + */ List findByValidationType(String validateType); + + /** + * Query that retrieves a list of supply chain validation using the provided validation result. + * + * @param validationResult string representation of the validation result + * @return a list of supply chain validation + */ List findByValidationResult(String validationResult); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/SupplyChainValidationSummaryRepository.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/SupplyChainValidationSummaryRepository.java index 1e7f94f5..bf4964b3 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/SupplyChainValidationSummaryRepository.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/SupplyChainValidationSummaryRepository.java @@ -7,12 +7,34 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import java.util.UUID; import java.util.List; +import java.util.UUID; @Repository -public interface SupplyChainValidationSummaryRepository extends JpaRepository { +public interface SupplyChainValidationSummaryRepository + extends JpaRepository { + + /** + * Query that retrieves a supply chain validation summary using the provided device. + * + * @param device device + * @return a supply chain validation summary + */ SupplyChainValidationSummary findByDevice(Device device); + + /** + * Query that retrieves a list of supply chain validation summaries where the archive flag is false. + * + * @return a list of supply chain validation summary + */ List findByArchiveFlagFalse(); + + /** + * Query that retrieves a page of supply chain validation summaries using the provided pageable value + * and where the archive flag is false. + * + * @param pageable pageable + * @return a page of supply chain validation summary + */ Page findByArchiveFlagFalse(Pageable pageable); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/TPM2ProvisionerStateRepository.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/TPM2ProvisionerStateRepository.java index 3e17881d..ea6c7e91 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/TPM2ProvisionerStateRepository.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/TPM2ProvisionerStateRepository.java @@ -7,5 +7,11 @@ import org.springframework.stereotype.Repository; @Repository public interface TPM2ProvisionerStateRepository extends JpaRepository { + /** + * Query that retrieves the TPM2 Provisioner State using the provided first part of nonce. + * + * @param findByFirstPartOfNonce long representation of the first part of nonce + * @return TPM2 Provisioner State + */ TPM2ProvisionerState findByFirstPartOfNonce(Long findByFirstPartOfNonce); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/package-info.java new file mode 100644 index 00000000..a71f8943 --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/manager/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.entity.manager; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/tpm/TPM2ProvisionerState.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/tpm/TPM2ProvisionerState.java index 7ac3afc9..6a6a4f72 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/tpm/TPM2ProvisionerState.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/tpm/TPM2ProvisionerState.java @@ -35,12 +35,12 @@ public class TPM2ProvisionerState { private byte[] identityClaim; @Column(nullable = false) - private Date timestamp = new Date(); + private final Date timestamp = new Date(); /** * Constructor. * - * @param nonce the nonce + * @param nonce the nonce * @param identityClaim the identity claim */ public TPM2ProvisionerState(final byte[] nonce, final byte[] identityClaim) { @@ -69,33 +69,15 @@ public class TPM2ProvisionerState { } } - /** - * Get the nonce. - * - * @return the nonce - */ - public byte[] getNonce() { - return Arrays.clone(nonce); - } - - /** - * Get the identity claim. - * - * @return the identity claim - */ - public byte[] getIdentityClaim() { - return Arrays.clone(identityClaim); - } - /** * Convenience method for finding the {@link TPM2ProvisionerState} associated with the nonce. * * @param tpm2ProvisionerStateRepository the {@link TPM2ProvisionerStateRepository} * to use when looking for the - * {@link TPM2ProvisionerState} - * @param nonce the nonce to use as the key for the {@link TPM2ProvisionerState} + * {@link TPM2ProvisionerState} + * @param nonce the nonce to use as the key for the {@link TPM2ProvisionerState} * @return the {@link TPM2ProvisionerState} associated with the nonce; - * null if a match is not found + * null if a match is not found */ public static TPM2ProvisionerState getTPM2ProvisionerState( final TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository, @@ -114,4 +96,22 @@ public class TPM2ProvisionerState { } return null; } + + /** + * Get the nonce. + * + * @return the nonce + */ + public byte[] getNonce() { + return Arrays.clone(nonce); + } + + /** + * Get the identity claim. + * + * @return the identity claim + */ + public byte[] getIdentityClaim() { + return Arrays.clone(identityClaim); + } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/tpm/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/tpm/package-info.java new file mode 100644 index 00000000..247ff4f6 --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/tpm/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.entity.tpm; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/Certificate.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/Certificate.java index 257c834e..07df1852 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/Certificate.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/Certificate.java @@ -18,13 +18,11 @@ import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1GeneralizedTime; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERIA5String; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERTaggedObject; -import org.bouncycastle.asn1.DLSequence; import org.bouncycastle.asn1.DLTaggedObject; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.AccessDescription; @@ -79,24 +77,6 @@ import java.util.Objects; @Entity public abstract class Certificate extends ArchivableEntity { - /** - * Holds the different certificate types. - */ - public enum CertificateType { - /** - * Basic X509 Certificate. - */ - X509_CERTIFICATE, - /** - * Basic Attribute Certificate. - */ - ATTRIBUTE_CERTIFICATE, - /** - * Invalid Certificate. - */ - INVALID_CERTIFICATE - } - /** * Decimal digit representation of base 16. */ @@ -106,6 +86,7 @@ public abstract class Certificate extends ArchivableEntity { * Min length representing the attribute certificate. */ public static final int MIN_ATTR_CERT_LENGTH = 8; + /** * Holds the name of the entity 'ID' field. */ @@ -120,52 +101,78 @@ public abstract class Certificate extends ArchivableEntity { * Holds the name of the 'serialNumber' field. */ public static final String SERIAL_NUMBER_FIELD = "serialNumber"; - @Getter - @Column(nullable = false, precision = CertificateVariables.MAX_NUMERIC_PRECISION, scale = 0) - private final BigInteger serialNumber; /** * Holds the name of the 'issuer' field. */ public static final String ISSUER_FIELD = "issuer"; - @Getter - @Column(nullable = false) - private final String issuer; + /** * Holds the name of the 'issuerSorted' field. */ public static final String ISSUER_SORTED_FIELD = "issuerSorted"; - @Getter - @Column - private final String issuerSorted; /** * Holds the name of the 'subject' field. */ public static final String SUBJECT_FIELD = "subject"; - @Getter - @Column(nullable = true) - private final String subject; + /** * Holds the name of the 'subjectSorted' field. */ public static final String SUBJECT_SORTED_FIELD = "subjectSorted"; - @Getter - @Column - private final String subjectSorted; /** * Holds the name of the 'encodedPublicKey' field. */ public static final String ENCODED_PUBLIC_KEY_FIELD = "encodedPublicKey"; - @Column(length = CertificateVariables.MAX_CERT_LENGTH_BYTES, nullable = true) - private final byte[] encodedPublicKey; /** * Holds the name of the 'encodedPublicKey' field. */ public static final String PUBLIC_KEY_MODULUS_FIELD = "publicKeyModulusHexValue"; + /** + * Holds the name of the 'certificateHash' field. + */ + public static final String CERTIFICATE_HASH_FIELD = "certificateHash"; + + /** + * Holds the name of the 'holderSerialNumber' field. + */ + public static final String HOLDER_SERIAL_NUMBER_FIELD = "holderSerialNumber"; + + /** + * Holds the name of the 'authorityKeyIdentifier' field. + */ + public static final String AUTHORITY_KEY_ID_FIELD = "authorityKeyIdentifier"; + + @SuppressWarnings("PMD.AvoidUsingHardCodedIP") // this is not an IP address; PMD thinks it is + private static final String POLICY_CONSTRAINTS = "2.5.29.36"; + + @Getter + @Column(nullable = false, precision = CertificateVariables.MAX_NUMERIC_PRECISION, scale = 0) + private final BigInteger serialNumber; + + @Getter + @Column(nullable = false) + private final String issuer; + + @Getter + @Column + private final String issuerSorted; + + @Getter + @Column + private final String subject; + + @Getter + @Column + private final String subjectSorted; + + @Column(length = CertificateVariables.MAX_CERT_LENGTH_BYTES) + private final byte[] encodedPublicKey; + // We're currently seeing 2048-bit keys, which is 512 hex digits. // Using a max length of 1024 for future-proofing. @Getter @@ -181,16 +188,9 @@ public abstract class Certificate extends ArchivableEntity { @Column(nullable = false) private final Date endValidity; - @Column(length = CertificateVariables.MAX_CERT_LENGTH_BYTES*CertificateVariables.KEY_USAGE_BIT4, nullable = false) - @JsonIgnore - private byte[] certificateBytes; - - /** - * Holds the name of the 'certificateHash' field. - */ - public static final String CERTIFICATE_HASH_FIELD = "certificateHash"; @Column(nullable = false) - @JsonIgnore @Getter + @JsonIgnore + @Getter private final int certificateHash; /** @@ -202,42 +202,48 @@ public abstract class Certificate extends ArchivableEntity { @JsonIgnore private final int certAndTypeHash; - /** - * Holds the name of the 'holderSerialNumber' field. - */ - public static final String HOLDER_SERIAL_NUMBER_FIELD = "holderSerialNumber"; + @Getter + @Column(nullable = false, precision = CertificateVariables.MAX_NUMERIC_PRECISION) + private final BigInteger holderSerialNumber; @Getter - @Column(nullable = false, precision = CertificateVariables.MAX_NUMERIC_PRECISION, scale = 0) - private final BigInteger holderSerialNumber; - @Getter - private String holderIssuer; - @Getter - @Column(nullable = true, precision = CertificateVariables.MAX_NUMERIC_PRECISION, scale = 0) + @Column(precision = CertificateVariables.MAX_NUMERIC_PRECISION) private final BigInteger authoritySerialNumber; - @SuppressWarnings("PMD.AvoidUsingHardCodedIP") // this is not an IP address; PMD thinks it is - private static final String POLICY_CONSTRAINTS = "2.5.29.36"; + @Column(length = CertificateVariables.MAX_CERT_LENGTH_BYTES * CertificateVariables.KEY_USAGE_BIT4, + nullable = false) + @JsonIgnore + private byte[] certificateBytes; + @Getter + private String holderIssuer; // we don't need to persist this, but we don't want to unpack this cert multiple times @Transient private X509Certificate parsedX509Cert = null; @Getter - private String signatureAlgorithm, publicKeyAlgorithm; + private String signatureAlgorithm; + @Getter - private String keyUsage, extendedKeyUsage; + private String publicKeyAlgorithm; + + @Getter + private String keyUsage; + + @Getter + private String extendedKeyUsage; + private byte[] policyConstraints; - /** - * Holds the name of the 'authorityKeyIdentifier' field. - */ - public static final String AUTHORITY_KEY_ID_FIELD = "authorityKeyIdentifier"; + @Getter private String authorityKeyIdentifier; + @Getter private String authorityInfoAccess; + @Getter private String crlPoints; + @Getter private int publicKeySize; @@ -291,7 +297,7 @@ public abstract class Certificate extends ArchivableEntity { * @param certificateBytes the contents of a certificate file * @throws IOException if there is a problem extracting information from the certificate */ - @SuppressWarnings("methodlength") + public Certificate(final byte[] certificateBytes) throws IOException { Preconditions.checkArgument( certificateBytes != null, @@ -342,7 +348,7 @@ public abstract class Certificate extends ArchivableEntity { this.policyConstraints = x509Certificate .getExtensionValue(POLICY_CONSTRAINTS); authKeyIdentifier = AuthorityKeyIdentifier - .getInstance((DLSequence) getExtensionValue( + .getInstance(getExtensionValue( Extension.authorityKeyIdentifier.getId())); this.authorityInfoAccess = getAuthorityInfoAccess(x509Certificate @@ -460,385 +466,9 @@ public abstract class Certificate extends ArchivableEntity { this.certAndTypeHash = Objects.hash(certificateHash, getClass().getSimpleName()); } - /** - * Getter for the CRL Distribution that is reference by the Revocation Locator - * on the portal. - * - * @return A list of URLs that inform the location of the certificate revocation lists - * @throws java.io.IOException - */ - private String getCRLDistributionPoint() throws IOException { - List crlUrls = new ArrayList<>(); - ASN1Primitive primitive = getExtensionValue(Extension.cRLDistributionPoints.getId()); - StringBuilder sb = new StringBuilder(); - - if (primitive != null) { - CRLDistPoint crlDistPoint = CRLDistPoint.getInstance(primitive); - DistributionPoint[] distributionPoints = crlDistPoint.getDistributionPoints(); - - for (DistributionPoint distributionPoint : distributionPoints) { - DistributionPointName dpn = distributionPoint.getDistributionPoint(); - // Look for URIs in fullName - if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) { - GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()) - .getNames(); - for (GeneralName genName : genNames) { - if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) { - String url = DERIA5String.getInstance(genName.getName()) - .getString(); - crlUrls.add(url); - } - } - } - } - } - - for (String s : crlUrls) { - sb.append(String.format("%s%n", s)); - } - - return sb.toString(); - } - - /** - * Getter for the x509 Platform Certificate version. - * @return a big integer representing the certificate version. If there - * is an error, return the max value to visible show error. - */ - public int getX509CredentialVersion() { - try { - return getX509Certificate().getVersion() - 1; - } catch (IOException ex) { - log.warn("X509 Credential Version not found."); - log.error(ex); - return Integer.MAX_VALUE; - } - } - - /** - * Checks if another certificate is the issuer for this certificate. - * - * @param issuer the other certificate to check (must be an X509Certificate, - * not an X509AttributeCertificateHolder) - * @return whether or not the other certificate is the issuer for this certificate - * @throws IOException if there is an issue deserializing either certificate - */ - public String isIssuer(final Certificate issuer) throws IOException { - String isIssuer = "Certificate signature failed to verify"; - // only run if of the correct type, otherwise false - if (issuer.getCertificateType() == CertificateType.X509_CERTIFICATE) { - X509Certificate issuerX509 = issuer.getX509Certificate(); - // Validate if it's the issuer - switch (getCertificateType()) { - case X509_CERTIFICATE: - X509Certificate certX509 = getX509Certificate(); - try { - certX509.verify(issuerX509.getPublicKey()); - isIssuer = ""; - } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException - | NoSuchProviderException | SignatureException e) { - log.error(e); - } - break; - case ATTRIBUTE_CERTIFICATE: - AttributeCertificate attCert = getAttributeCertificate(); - try { - Signature sig = Signature.getInstance(this.getSignatureAlgorithm()); - sig.initVerify(issuerX509.getPublicKey()); - sig.update(attCert.getAcinfo().getEncoded()); - if (sig.verify(attCert.getSignatureValue().getBytes())) { - isIssuer = ""; - } - } catch (NoSuchAlgorithmException - | InvalidKeyException - | SignatureException sigEx) { - log.error(sigEx); - } - break; - default: - break; - } - } - - return isIssuer; - } - - /** - * Return whether or not this certificate is valid on a particular date. - * - * @param date the date of interest. - * @return true if the attribute certificate is valid, false otherwise. - */ - public boolean isValidOn(final Date date) { - return !date.before(getBeginValidity()) && !date.after(getEndValidity()); - } - - /** - * Retrieve the original X509 certificate. - * - * @return the original X509 certificate - * @throws IOException if there is a problem deserializing the certificate as an X509 cert - */ - @JsonIgnore - public X509Certificate getX509Certificate() throws IOException { - if (parsedX509Cert != null) { - return parsedX509Cert; - } - - try (ByteArrayInputStream certInputStream = new ByteArrayInputStream(certificateBytes)) { - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - parsedX509Cert = (X509Certificate) cf.generateCertificate(certInputStream); - return parsedX509Cert; - } catch (CertificateException cEx) { - throw new IOException("Cannot construct X509Certificate from the input stream", cEx); - } - } - - /** - * @return the type of certificate. - * @throws java.io.IOException if there is a problem extracting information from the certificate - */ - protected CertificateType getCertificateType() throws IOException { - //Parse the certificate into a sequence - ASN1Sequence testCred1 = (ASN1Sequence) ASN1Primitive.fromByteArray(this.certificateBytes); - ASN1Sequence testSeq = (ASN1Sequence) ((ASN1Object) testCred1.toArray()[0]); - - if (testSeq.toArray()[0] instanceof ASN1Integer) { - if (testSeq.toArray().length >= MIN_ATTR_CERT_LENGTH) { - // Attribute Certificate - return CertificateType.ATTRIBUTE_CERTIFICATE; - } else { - // V1 X509Certificate - return CertificateType.X509_CERTIFICATE; - } - } else if (testSeq.toArray()[0] instanceof DERTaggedObject || testSeq.toArray()[0] instanceof DLTaggedObject) { - // V2 or V3 X509Certificate - return CertificateType.X509_CERTIFICATE; - } - - return CertificateType.INVALID_CERTIFICATE; - } - - - private String parseKeyUsage(final boolean[] bools) { - StringBuilder sb = new StringBuilder(); - - if (bools != null) { - for (int i = 0; i < bools.length; i++) { - if (bools[i]) { - sb.append(CredentialHelper.getKeyUsageString(i)); - } - } - } - - return sb.toString(); - } - - /** - * Getter for the authorityKeyIdentifier. - * @return the ID's byte representation - */ - private String authKeyIdentifierToString(final AuthorityKeyIdentifier aki) { - String retValue = ""; - if (aki != null) { - byte[] keyArray = aki.getKeyIdentifier(); - if (keyArray != null) { - retValue = HexUtils.byteArrayToHexString(keyArray); - } - } - - return retValue; - } - - /** - * Gets the contents of requested OID. - * - * @param oid Object Identifier - * @return ASN1Primitive Content related to the requested OID - * @throws java.io.IOException - */ - private ASN1Primitive getExtensionValue(final String oid) throws IOException { - byte[] extensionValue = getX509Certificate().getExtensionValue(oid); - ASN1Primitive asn1Primitive = null; - ASN1InputStream asn1InputStream = null; - - if (extensionValue != null) { - try { - asn1InputStream = new ASN1InputStream(extensionValue); - DEROctetString oct = (DEROctetString) asn1InputStream.readObject(); - asn1InputStream.close(); - asn1InputStream = new ASN1InputStream(oct.getOctets()); - asn1Primitive = asn1InputStream.readObject(); - } catch (IOException ioEx) { - log.error(ioEx); - } finally { - if (asn1InputStream != null) { - asn1InputStream.close(); - } - } - } - - return asn1Primitive; - } - - /** - * Getter for the AuthorityInfoAccess extension value on list format. - * - * @return List Authority info access list - */ - private String getAuthorityInfoAccess(final byte[] authInfoAccess) { - StringBuilder sb = new StringBuilder(); - - try { - if (authInfoAccess != null && authInfoAccess.length > 0) { - sb.append(getAuthorityInfoAccess(AuthorityInformationAccess - .getInstance(JcaX509ExtensionUtils.parseExtensionValue(authInfoAccess)))); - } - } catch (IOException ioEx) { - log.error(ioEx); - } - - return sb.toString(); - } - - /** - * Getter for the AuthorityInfoAccess extension value on list format. - * - * @return List Authority info access list - */ - private String getAuthorityInfoAccess(final AuthorityInformationAccess authInfoAccess) { - StringBuilder sb = new StringBuilder(); - - if (authInfoAccess != null) { - for (AccessDescription desc : authInfoAccess.getAccessDescriptions()) { - if (desc.getAccessLocation().getTagNo() == GeneralName - .uniformResourceIdentifier) { - sb.append(String.format("%s%n", ((DERIA5String) desc - .getAccessLocation() - .getName()) - .getString())); - } - } - } - - return sb.toString(); - } - - - /** - * Retrieve the original X509 attribute certificate. - * - * @return the original X509 attribute certificate - * @throws IOException if there is a problem deserializing the certificate as an X509 - * attribute cert - */ - @JsonIgnore - public X509AttributeCertificateHolder getX509AttributeCertificateHolder() throws IOException { - return new X509AttributeCertificateHolder(certificateBytes); - } - - /** - * Retrieve the original Attribute Certificate. - * - * @return the original Attribute Certificate - * @throws IOException if there is a problem deserializing the certificate as an X509 - * attribute cert - */ - @JsonIgnore - public AttributeCertificate getAttributeCertificate() throws IOException { - return AttributeCertificate - .getInstance(ASN1Primitive.fromByteArray(certificateBytes)); - } - - /** - * @return this certificate's signature - */ - public byte[] getSignature() { - return signature.clone(); - } - - /** - * @return this certificate's validity start date - */ - public Date getBeginValidity() { - return new Date(beginValidity.getTime()); - } - - /** - * @return this certificate's validity end date - */ - public Date getEndValidity() { - return new Date(endValidity.getTime()); - } - - /** - * Getter for the policy statement. - * @return cloned bit representation of constraints - */ - public byte[] getPolicyConstraints() { - if (policyConstraints != null) { - return policyConstraints.clone(); - } - return null; - } - - /** - * @return this certificate's encoded public key - */ - public byte[] getEncodedPublicKey() { - if (encodedPublicKey == null) { - return null; - } else { - return encodedPublicKey.clone(); - } - } - /** * Gets the raw bytes for the certificate. * - * @return copy of the certificate bytes - */ - @JsonIgnore - public byte[] getRawBytes() { - if (this.certificateBytes != null) { - return this.certificateBytes.clone(); - } - return null; - } - - @Override - public String toString() { - return String.format("Certificate{%s, AuthID=%s, serialNumber=%s, " - + "issuer=%s, AuthSerialNumber=%s, publicKeySize=%d, " - + "signatureAlg=%s, Hash=%d}", super.toString(), - authorityKeyIdentifier, serialNumber.toString(), - issuer, authoritySerialNumber.toString(), publicKeySize, - signatureAlgorithm, certificateHash); - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - Certificate that = (Certificate) o; - - return Arrays.equals(certificateBytes, that.certificateBytes); - } - - @Override - public int hashCode() { - return Arrays.hashCode(certificateBytes); - } - - /** - * - * Gets the raw bytes for the certificate. * @param certificatePath path to the certificate file * @return bytes from the certificate file * @throws IOException if there is a problem reading the file @@ -853,8 +483,8 @@ public abstract class Certificate extends ArchivableEntity { } /** - * Retrieve a formatted subject DN string from a certificate. This allows for extended support of DNs found in - * various RFCs. + * Retrieve a formatted subject DN string from a certificate. This allows for extended support of DNs + * found in various RFCs. * * @param certificate the certificate holding subject DNs * @return IOException if there is an issue decoding the subject DNs @@ -873,8 +503,8 @@ public abstract class Certificate extends ArchivableEntity { } /** - * Retrieve a formatted issuer DN string from a certificate. This allows for extended support of DNs found in - * various RFCs. + * Retrieve a formatted issuer DN string from a certificate. This allows for extended support of DNs found + * in various RFCs. * * @param certificate the certificate holding issuer DNs * @return IOException if there is an issue decoding the issuer DNs @@ -926,8 +556,7 @@ public abstract class Certificate extends ArchivableEntity { */ public static BigInteger getPublicKeyModulus(final PublicKey publicKey) throws IOException { ASN1Primitive publicKeyASN1 = ASN1Primitive.fromByteArray(publicKey.getEncoded()); - if (publicKeyASN1 instanceof ASN1Sequence) { - ASN1Sequence publicKeyASN1Sequence = (ASN1Sequence) publicKeyASN1; + if (publicKeyASN1 instanceof ASN1Sequence publicKeyASN1Sequence) { ASN1BitString encodedModulusAndExponent = (ASN1BitString) publicKeyASN1Sequence.getObjectAt(1); byte[] modulusAndExponentBytes = encodedModulusAndExponent.getOctets(); @@ -939,8 +568,7 @@ public abstract class Certificate extends ArchivableEntity { private static BigInteger getPublicKeyModulus(final ASN1Primitive publicKey) throws IOException { - if (publicKey instanceof ASN1Sequence) { - ASN1Sequence pubKeySeq = (ASN1Sequence) publicKey; + if (publicKey instanceof ASN1Sequence pubKeySeq) { ASN1Encodable modulus = pubKeySeq.getObjectAt(0); if (modulus instanceof ASN1Integer) { return ((ASN1Integer) modulus).getValue(); @@ -976,7 +604,7 @@ public abstract class Certificate extends ArchivableEntity { } } - return (X500Name[]) l.toArray(new X500Name[l.size()]); + return l.toArray(new X500Name[l.size()]); } /** @@ -992,4 +620,420 @@ public abstract class Certificate extends ArchivableEntity { throw new IllegalStateException("unable to recover date: " + e.getMessage()); } } + + /** + * Getter for the CRL Distribution that is reference by the Revocation Locator + * on the portal. + * + * @return A list of URLs that inform the location of the certificate revocation lists + * @throws IOException if there is an issue while retrieving the CRL Distribution point + */ + private String getCRLDistributionPoint() throws IOException { + List crlUrls = new ArrayList<>(); + ASN1Primitive primitive = getExtensionValue(Extension.cRLDistributionPoints.getId()); + StringBuilder sb = new StringBuilder(); + + if (primitive != null) { + CRLDistPoint crlDistPoint = CRLDistPoint.getInstance(primitive); + DistributionPoint[] distributionPoints = crlDistPoint.getDistributionPoints(); + + for (DistributionPoint distributionPoint : distributionPoints) { + DistributionPointName dpn = distributionPoint.getDistributionPoint(); + // Look for URIs in fullName + if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) { + GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()) + .getNames(); + for (GeneralName genName : genNames) { + if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) { + String url = DERIA5String.getInstance(genName.getName()) + .getString(); + crlUrls.add(url); + } + } + } + } + } + + for (String s : crlUrls) { + sb.append(String.format("%s%n", s)); + } + + return sb.toString(); + } + + /** + * Getter for the x509 Platform Certificate version. + * + * @return a big integer representing the certificate version. If there + * is an error, return the max value to visible show error. + */ + public int getX509CredentialVersion() { + try { + return getX509Certificate().getVersion() - 1; + } catch (IOException ex) { + log.warn("X509 Credential Version not found."); + log.error(ex); + return Integer.MAX_VALUE; + } + } + + /** + * Checks if another certificate is the issuer for this certificate. + * + * @param issuer the other certificate to check (must be an X509Certificate, + * not an X509AttributeCertificateHolder) + * @return whether or not the other certificate is the issuer for this certificate + * @throws IOException if there is an issue deserializing either certificate + */ + public String isIssuer(final Certificate issuer) throws IOException { + String isIssuer = "Certificate signature failed to verify"; + // only run if of the correct type, otherwise false + if (issuer.getCertificateType() == CertificateType.X509_CERTIFICATE) { + X509Certificate issuerX509 = issuer.getX509Certificate(); + // Validate if it's the issuer + switch (getCertificateType()) { + case X509_CERTIFICATE: + X509Certificate certX509 = getX509Certificate(); + try { + certX509.verify(issuerX509.getPublicKey()); + isIssuer = ""; + } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException + | NoSuchProviderException | SignatureException e) { + log.error(e); + } + break; + case ATTRIBUTE_CERTIFICATE: + AttributeCertificate attCert = getAttributeCertificate(); + try { + Signature sig = Signature.getInstance(this.getSignatureAlgorithm()); + sig.initVerify(issuerX509.getPublicKey()); + sig.update(attCert.getAcinfo().getEncoded()); + if (sig.verify(attCert.getSignatureValue().getBytes())) { + isIssuer = ""; + } + } catch (NoSuchAlgorithmException + | InvalidKeyException + | SignatureException sigEx) { + log.error(sigEx); + } + break; + default: + break; + } + } + + return isIssuer; + } + + /** + * Return whether this certificate is valid on a particular date. + * + * @param date the date of interest. + * @return true if the attribute certificate is valid, false otherwise. + */ + public boolean isValidOn(final Date date) { + return !date.before(getBeginValidity()) && !date.after(getEndValidity()); + } + + /** + * Retrieve the original X509 certificate. + * + * @return the original X509 certificate + * @throws IOException if there is a problem deserializing the certificate as an X509 cert + */ + @JsonIgnore + public X509Certificate getX509Certificate() throws IOException { + if (parsedX509Cert != null) { + return parsedX509Cert; + } + + try (ByteArrayInputStream certInputStream = new ByteArrayInputStream(certificateBytes)) { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + parsedX509Cert = (X509Certificate) cf.generateCertificate(certInputStream); + return parsedX509Cert; + } catch (CertificateException cEx) { + throw new IOException("Cannot construct X509Certificate from the input stream", cEx); + } + } + + /** + * @return the type of certificate. + * @throws java.io.IOException if there is a problem extracting information from the certificate + */ + protected CertificateType getCertificateType() throws IOException { + //Parse the certificate into a sequence + ASN1Sequence testCred1 = (ASN1Sequence) ASN1Primitive.fromByteArray(this.certificateBytes); + ASN1Sequence testSeq = (ASN1Sequence) testCred1.toArray()[0]; + + if (testSeq.toArray()[0] instanceof ASN1Integer) { + if (testSeq.toArray().length >= MIN_ATTR_CERT_LENGTH) { + // Attribute Certificate + return CertificateType.ATTRIBUTE_CERTIFICATE; + } else { + // V1 X509Certificate + return CertificateType.X509_CERTIFICATE; + } + } else if (testSeq.toArray()[0] instanceof DERTaggedObject + || testSeq.toArray()[0] instanceof DLTaggedObject) { + // V2 or V3 X509Certificate + return CertificateType.X509_CERTIFICATE; + } + + return CertificateType.INVALID_CERTIFICATE; + } + + private String parseKeyUsage(final boolean[] bools) { + StringBuilder sb = new StringBuilder(); + + if (bools != null) { + for (int i = 0; i < bools.length; i++) { + if (bools[i]) { + sb.append(CredentialHelper.getKeyUsageString(i)); + } + } + } + + return sb.toString(); + } + + /** + * Getter for the authorityKeyIdentifier. + * + * @param aki authority key identifier + * @return the ID's byte representation + */ + private String authKeyIdentifierToString(final AuthorityKeyIdentifier aki) { + String retValue = ""; + if (aki != null) { + byte[] keyArray = aki.getKeyIdentifier(); + if (keyArray != null) { + retValue = HexUtils.byteArrayToHexString(keyArray); + } + } + + return retValue; + } + + /** + * Gets the contents of requested OID. + * + * @param oid Object Identifier + * @return ASN1Primitive Content related to the requested OID + * @throws IOException io exception + */ + private ASN1Primitive getExtensionValue(final String oid) throws IOException { + byte[] extensionValue = getX509Certificate().getExtensionValue(oid); + ASN1Primitive asn1Primitive = null; + ASN1InputStream asn1InputStream = null; + + if (extensionValue != null) { + try { + asn1InputStream = new ASN1InputStream(extensionValue); + DEROctetString oct = (DEROctetString) asn1InputStream.readObject(); + asn1InputStream.close(); + asn1InputStream = new ASN1InputStream(oct.getOctets()); + asn1Primitive = asn1InputStream.readObject(); + } catch (IOException ioEx) { + log.error(ioEx); + } finally { + if (asn1InputStream != null) { + asn1InputStream.close(); + } + } + } + + return asn1Primitive; + } + + /** + * Getter for the AuthorityInfoAccess extension value on list format. + * + * @param authInfoAccess byte representation of the authority info access + * @return List Authority info access list + */ + private String getAuthorityInfoAccess(final byte[] authInfoAccess) { + StringBuilder sb = new StringBuilder(); + + try { + if (authInfoAccess != null && authInfoAccess.length > 0) { + sb.append(getAuthorityInfoAccess(AuthorityInformationAccess + .getInstance(JcaX509ExtensionUtils.parseExtensionValue(authInfoAccess)))); + } + } catch (IOException ioEx) { + log.error(ioEx); + } + + return sb.toString(); + } + + /** + * Getter for the AuthorityInfoAccess extension value on list format. + * + * @param authInfoAccess authority information access + * @return List Authority info access list + */ + private String getAuthorityInfoAccess(final AuthorityInformationAccess authInfoAccess) { + StringBuilder sb = new StringBuilder(); + + if (authInfoAccess != null) { + for (AccessDescription desc : authInfoAccess.getAccessDescriptions()) { + if (desc.getAccessLocation().getTagNo() == GeneralName + .uniformResourceIdentifier) { + sb.append(String.format("%s%n", ((DERIA5String) desc + .getAccessLocation() + .getName()) + .getString())); + } + } + } + + return sb.toString(); + } + + /** + * Retrieve the original X509 attribute certificate. + * + * @return the original X509 attribute certificate + * @throws IOException if there is a problem deserializing the certificate as an X509 + * attribute cert + */ + @JsonIgnore + public X509AttributeCertificateHolder getX509AttributeCertificateHolder() throws IOException { + return new X509AttributeCertificateHolder(certificateBytes); + } + + /** + * Retrieve the original Attribute Certificate. + * + * @return the original Attribute Certificate + * @throws IOException if there is a problem deserializing the certificate as an X509 + * attribute cert + */ + @JsonIgnore + public AttributeCertificate getAttributeCertificate() throws IOException { + return AttributeCertificate + .getInstance(ASN1Primitive.fromByteArray(certificateBytes)); + } + + /** + * @return this certificate's signature + */ + public byte[] getSignature() { + return signature.clone(); + } + + /** + * @return this certificate's validity start date + */ + public Date getBeginValidity() { + return new Date(beginValidity.getTime()); + } + + /** + * @return this certificate's validity end date + */ + public Date getEndValidity() { + return new Date(endValidity.getTime()); + } + + /** + * Getter for the policy statement. + * + * @return cloned bit representation of constraints + */ + public byte[] getPolicyConstraints() { + if (policyConstraints != null) { + return policyConstraints.clone(); + } + return null; + } + + /** + * @return this certificate's encoded public key + */ + public byte[] getEncodedPublicKey() { + if (encodedPublicKey == null) { + return null; + } else { + return encodedPublicKey.clone(); + } + } + + /** + * Gets the raw bytes for the certificate. + * + * @return copy of the certificate bytes + */ + @JsonIgnore + public byte[] getRawBytes() { + if (this.certificateBytes != null) { + return this.certificateBytes.clone(); + } + return null; + } + + /** + * Creates a string representation of the Certificate object. + * + * @return a string representation of the Certificate object. + */ + @Override + public String toString() { + return String.format("Certificate{%s, AuthID=%s, serialNumber=%s, " + + "issuer=%s, AuthSerialNumber=%s, publicKeySize=%d, " + + "signatureAlg=%s, Hash=%d}", super.toString(), + authorityKeyIdentifier, serialNumber.toString(), + issuer, authoritySerialNumber.toString(), publicKeySize, + signatureAlgorithm, certificateHash); + } + + /** + * Compares this certificate to the provided object to verify that both this and the provided certificate + * objects are equal. + * + * @param o object to compare + * @return true if both the provided certificate and this certificate are equal, false otherwise + */ + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + Certificate that = (Certificate) o; + + return Arrays.equals(certificateBytes, that.certificateBytes); + } + + /** + * Creates an integer hash code for this Certificate object. + * + * @return integer hash code + */ + @Override + public int hashCode() { + return Arrays.hashCode(certificateBytes); + } + + /** + * Holds the different certificate types. + */ + public enum CertificateType { + /** + * Basic X509 Certificate. + */ + X509_CERTIFICATE, + /** + * Basic Attribute Certificate. + */ + ATTRIBUTE_CERTIFICATE, + /** + * Invalid Certificate. + */ + INVALID_CERTIFICATE + } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/Device.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/Device.java index ff6e7c0f..66a6ed8f 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/Device.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/Device.java @@ -14,19 +14,20 @@ import jakarta.persistence.OneToOne; import jakarta.persistence.Table; import lombok.AccessLevel; import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.sql.Timestamp; import java.time.LocalDateTime; -import java.util.Objects; @Entity @Table(name = "Device") @Setter @NoArgsConstructor(access = AccessLevel.PROTECTED) @AllArgsConstructor +@EqualsAndHashCode(callSuper = false) public class Device extends AbstractEntity { @Getter @@ -34,7 +35,7 @@ public class Device extends AbstractEntity { private String name; @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, - optional = true, orphanRemoval = true) + orphanRemoval = true) private DeviceInfoReport deviceInfo; @Getter @@ -65,6 +66,11 @@ public class Device extends AbstractEntity { @Column(name = "summary_id") private String summaryId; + /** + * Constructor creates a Device object using the provided device info report. + * + * @param deviceInfoReport device information report + */ public Device(final DeviceInfoReport deviceInfoReport) { super(); if (deviceInfoReport != null) { @@ -94,6 +100,7 @@ public class Device extends AbstractEntity { /** * Getter for the report time stamp. + * * @return a cloned version */ public Timestamp getLastReportTimestamp() { @@ -106,39 +113,22 @@ public class Device extends AbstractEntity { /** * Setter for the report time stamp. - * @param lastReportTimestamp + * + * @param lastReportTimestamp last reported time */ public void setLastReportTimestamp(final Timestamp lastReportTimestamp) { this.lastReportTimestamp = (Timestamp) lastReportTimestamp.clone(); } + /** + * Creates a string representation of the Device object. + * + * @return a string representation of the Device object. + */ + @Override public String toString() { return String.format("Device Name: %s%nStatus: %s%nSummary: %s%n", - name, (healthStatus == null ? "N/A" : healthStatus.getStatus()), + name, (healthStatus == null ? "N/A" : healthStatus.getHealthStatus()), (supplyChainValidationStatus == null ? "N/A" : supplyChainValidationStatus.toString())); } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Device)) { - return false; - } - - Device device = (Device) o; - return isStateOverridden == device.isStateOverridden - && Objects.equals(name, device.name) - && healthStatus == device.healthStatus - && supplyChainValidationStatus == device.supplyChainValidationStatus - && Objects.equals(lastReportTimestamp, device.lastReportTimestamp) - && Objects.equals(overrideReason, device.overrideReason) - && Objects.equals(summaryId, device.summaryId); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), name, healthStatus, - supplyChainValidationStatus, lastReportTimestamp, - isStateOverridden, overrideReason, summaryId); - } -} \ No newline at end of file +} diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/ExaminableRecord.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/ExaminableRecord.java index df4dfb48..0031eccd 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/ExaminableRecord.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/ExaminableRecord.java @@ -23,6 +23,29 @@ import lombok.extern.log4j.Log4j2; @XmlAccessorType(XmlAccessType.FIELD) public abstract class ExaminableRecord { + @Getter + @Column(nullable = false) + // Decided on ORDINAL instead of STRING due to concerns surrounding overall size and retrieval + // time of field from database. Consistent with other implementations of ExaminableRecord. + @Enumerated(EnumType.ORDINAL) + private ExamineState examineState = ExamineState.UNEXAMINED; + + /** + * Sets the examine state for this record. + * + * @param examineState the examine state + */ + public void setExamineState(final ExamineState examineState) { + if (examineState == ExamineState.UNEXAMINED) { + log.error("Can't set ExamineState on ExaminableRecord to Unexamined"); + throw new IllegalArgumentException( + "Can't set ExamineState on ExaminableRecord to Unexamined" + ); + } + + this.examineState = examineState; + } + /** * State capturing if a record was examined during appraisal or not. */ @@ -42,26 +65,4 @@ public abstract class ExaminableRecord { */ IGNORED } - - @Getter - @Column(nullable = false) - // Decided on ORDINAL instead of STRING due to concerns surrounding overall size and retrieval - // time of field from database. Consistent with other implementations of ExaminableRecord. - @Enumerated(EnumType.ORDINAL) - private ExamineState examineState = ExamineState.UNEXAMINED; - - /** - * Sets the examine state for this record. - * @param examineState the examine state - */ - public void setExamineState(final ExamineState examineState) { - if (examineState == ExamineState.UNEXAMINED) { - log.error("Can't set ExamineState on ExaminableRecord to Unexamined"); - throw new IllegalArgumentException( - "Can't set ExamineState on ExaminableRecord to Unexamined" - ); - } - - this.examineState = examineState; - } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/PolicySettings.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/PolicySettings.java index f6b2c1e1..f3dcf2f1 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/PolicySettings.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/PolicySettings.java @@ -105,8 +105,7 @@ public class PolicySettings extends UserDefinedEntity { /** * Constructor used to initialize PolicySettings object. * - * @param name - * A name used to uniquely identify and reference the Supply Chain policy. + * @param name A name used to uniquely identify and reference the Supply Chain policy. */ public PolicySettings(final String name) { super(name); @@ -115,10 +114,8 @@ public class PolicySettings extends UserDefinedEntity { /** * Constructor used to initialize PolicySettings object. * - * @param name - * A name used to uniquely identify and reference the supply chain policy. - * @param description - * Optional description of the policy that can be added by the user + * @param name A name used to uniquely identify and reference the supply chain policy. + * @param description Optional description of the policy that can be added by the user */ public PolicySettings(final String name, final String description) { super(name, description); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/ReferenceManifest.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/ReferenceManifest.java index db2d950f..572dd153 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/ReferenceManifest.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/ReferenceManifest.java @@ -10,6 +10,7 @@ import jakarta.persistence.Entity; import jakarta.persistence.Inheritance; import jakarta.persistence.InheritanceType; import jakarta.persistence.Table; +import lombok.AccessLevel; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @@ -28,14 +29,16 @@ import java.util.UUID; * This class represents the Reference Integrity Manifest object that will be * loaded into the DB and displayed in the ACA. */ -@Getter @ToString +@Getter +@Setter +@ToString @EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = false) @Log4j2 @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @Table(name = "ReferenceManifest") @Access(AccessType.FIELD) -public class ReferenceManifest extends ArchivableEntity { +public class ReferenceManifest extends ArchivableEntity { /** * Holds the name of the 'hexDecHash' field. @@ -72,54 +75,55 @@ public class ReferenceManifest extends ArchivableEntity { */ public static final String SCHEMA_PACKAGE = "hirs.utils.xjc"; + @Setter(AccessLevel.NONE) @EqualsAndHashCode.Include @Column(columnDefinition = "mediumblob", nullable = false) - private byte[] rimBytes; - @Setter + private final byte[] rimBytes; + @EqualsAndHashCode.Include @Column(nullable = false) private String rimType = "Base"; - @Setter + @Column private String tagId = null; - @Setter + @Column private boolean swidPatch = false; - @Setter + @Column private boolean swidSupplemental = false; - @Setter + @Column private String platformManufacturer = null; - @Setter + @Column private String platformManufacturerId = null; - @Setter + @Column private String swidTagVersion = null; - @Setter + @Column private String swidVersion = null; - @Setter + @Column private String platformModel = null; - @Setter + @Column(nullable = false) private String fileName = null; - @Setter + @JdbcTypeCode(java.sql.Types.VARCHAR) @Column private UUID associatedRim; - @Setter + @Column private String deviceName; - @Setter + @Column private String hexDecHash = ""; - @Setter + @Column private String eventLogHash = ""; - @Setter + @Column @JsonIgnore private String base64Hash = ""; @@ -141,6 +145,7 @@ public class ReferenceManifest extends ArchivableEntity { /** * Default constructor for ingesting the bytes of the file content. + * * @param rimBytes - file contents. */ public ReferenceManifest(final byte[] rimBytes) { @@ -183,10 +188,20 @@ public class ReferenceManifest extends ArchivableEntity { return null; } + /** + * Determines if this reference manifest's rim type is a base rim. + * + * @return true if the rim type is a base rim, false otherwise + */ public boolean isBase() { return rimType.equals(BASE_RIM); } + /** + * Determines if this reference manifest's rim type is a support rim. + * + * @return true if the rim type is a support rim, false otherwise + */ public boolean isSupport() { return rimType.equals(SUPPORT_RIM); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/SupplyChainValidation.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/SupplyChainValidation.java index c316f313..6485f46e 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/SupplyChainValidation.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/SupplyChainValidation.java @@ -2,7 +2,6 @@ package hirs.attestationca.persist.entity.userdefined; import com.google.common.base.Preconditions; import hirs.attestationca.persist.entity.ArchivableEntity; -import hirs.attestationca.persist.entity.userdefined.rim.BaseReferenceManifest; import hirs.attestationca.persist.enums.AppraisalStatus; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -10,6 +9,7 @@ import jakarta.persistence.FetchType; import jakarta.persistence.JoinColumn; import jakarta.persistence.JoinTable; import jakarta.persistence.ManyToMany; +import lombok.AccessLevel; import lombok.Getter; import java.util.ArrayList; @@ -19,51 +19,24 @@ import java.util.List; /** * Stores results of a single element of the supply chain validation process. */ +@Getter @Entity public class SupplyChainValidation extends ArchivableEntity { - /** - * Used to indicate which type of validation a result is related to. - */ - public enum ValidationType { - /** - * Validation of an endorsement credential. - */ - ENDORSEMENT_CREDENTIAL, - - /** - * Validation of a platform credential and also delta platform credentials from spec 1.1. - */ - PLATFORM_CREDENTIAL, - - /** - * Validation of a platform credential's attributes. - */ - PLATFORM_CREDENTIAL_ATTRIBUTES, - - /** - * Validation of the device firmware. - */ - FIRMWARE - } - - @Getter @Column private final ValidationType validationType; - @Getter @Column private final AppraisalStatus.Status validationResult; + @Getter(AccessLevel.NONE) @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "CertificatesUsedToValidate", - joinColumns = { @JoinColumn(name = "validation_id", nullable = false) }) + joinColumns = {@JoinColumn(name = "validation_id", nullable = false)}) private final List certificatesUsed; - @Getter @Column(length = RESULT_MESSAGE_LENGTH) private final String message; - @Getter @Column private String rimId; @@ -81,10 +54,10 @@ public class SupplyChainValidation extends ArchivableEntity { /** * Construct a new SupplyChainValidation instance. * - * @param validationType the type of validation this instance will represent; not null + * @param validationType the type of validation this instance will represent; not null * @param validationResult whether the validation was successful or not * @param certificatesUsed certificates used, if any, in the validation process; not null - * @param message a related information or error message; may be null + * @param message a related information or error message; may be null */ public SupplyChainValidation(final ValidationType validationType, final AppraisalStatus.Status validationResult, @@ -122,4 +95,29 @@ public class SupplyChainValidation extends ArchivableEntity { public List getCertificatesUsed() { return Collections.unmodifiableList(certificatesUsed); } + + /** + * Used to indicate which type of validation a result is related to. + */ + public enum ValidationType { + /** + * Validation of an endorsement credential. + */ + ENDORSEMENT_CREDENTIAL, + + /** + * Validation of a platform credential and also delta platform credentials from spec 1.1. + */ + PLATFORM_CREDENTIAL, + + /** + * Validation of a platform credential's attributes. + */ + PLATFORM_CREDENTIAL_ATTRIBUTES, + + /** + * Validation of the device firmware. + */ + FIRMWARE + } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/SupplyChainValidationSummary.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/SupplyChainValidationSummary.java index 8793fe37..a56503c4 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/SupplyChainValidationSummary.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/SupplyChainValidationSummary.java @@ -32,7 +32,6 @@ import java.util.Set; import java.util.UUID; - /** * A container class to group multiple related {@link SupplyChainValidation} instances * together. @@ -40,12 +39,10 @@ import java.util.UUID; @Entity public class SupplyChainValidationSummary extends ArchivableEntity { + private static final String DEVICE_ID_FIELD = "device.id"; @ManyToOne @JoinColumn(name = "device_id") private final Device device; - - private static final String DEVICE_ID_FIELD = "device.id"; - @Getter @Column @Enumerated(EnumType.STRING) @@ -72,120 +69,11 @@ public class SupplyChainValidationSummary extends ArchivableEntity { this.message = Strings.EMPTY; } - /** - * This class enables the retrieval of SupplyChainValidationSummaries by their attributes. - */ - public static class Selector { - private final CrudRepository - supplyChainValidationSummaryCrudManager; - - private final Map fieldValueSelections; - - /** - * Construct a new Selector that will use the given {@link CrudRepository} to - * retrieve SupplyChainValidationSummaries. - * - * @param supplyChainValidationSummaryCrudManager the summary manager to be used to retrieve - * supply chain validation summaries - */ - public Selector( - final CrudRepository - supplyChainValidationSummaryCrudManager) { - Preconditions.checkArgument( - supplyChainValidationSummaryCrudManager != null, - "supply chain validation summary manager cannot be null" - ); - - this.supplyChainValidationSummaryCrudManager = supplyChainValidationSummaryCrudManager; - this.fieldValueSelections = new HashMap<>(); - } - - /** - * Construct the criterion that can be used to query for supply chain validation summaries - * matching the configuration of this Selector. - * - * @return a Criterion that can be used to query for supply chain validation summaries - * matching the configuration of this instance - */ - public Predicate[] getCriterion(final CriteriaBuilder criteriaBuilder) { - Predicate[] predicates = new Predicate[fieldValueSelections.size()]; - CriteriaQuery query = criteriaBuilder.createQuery(SupplyChainValidationSummary.class); - Root root = query.from(SupplyChainValidationSummary.class); - - int i = 0; - for (Map.Entry fieldValueEntry : fieldValueSelections.entrySet()) { - predicates[i++] = criteriaBuilder.equal(root.get(fieldValueEntry.getKey()), fieldValueEntry.getValue()); - } - - return predicates; - } - - /** - * Set a field name and value to match. - * - * @param name the field name to query - * @param value the value to query - */ - protected void setFieldValue(final String name, final Object value) { - Object valueToAssign = value; - - Preconditions.checkArgument( - value != null, - "field value cannot be null." - ); - - if (value instanceof String) { - Preconditions.checkArgument( - StringUtils.isNotEmpty((String) value), - "field value cannot be empty." - ); - } - - if (value instanceof byte[]) { - byte[] valueBytes = (byte[]) value; - - Preconditions.checkArgument( - ArrayUtils.isNotEmpty(valueBytes), - "field value cannot be empty." - ); - - valueToAssign = Arrays.copyOf(valueBytes, valueBytes.length); - } - - fieldValueSelections.put(name, valueToAssign); - } - - - /** - * Specify a device id that supply chain validation summaries must have to be considered - * as matching. - * - * @param device the device id to query - * @return this instance (for chaining further calls) - */ - public Selector byDeviceId(final UUID device) { - setFieldValue(DEVICE_ID_FIELD, device); - return this; - } - } - - /** - * Get a Selector for use in retrieving SupplyChainValidationSummary. - * - * @param certMan the CrudManager to be used to retrieve persisted supply chain validation - * summaries - * @return a SupplyChainValidationSummary.Selector instance to use for retrieving certificates - */ - public static SupplyChainValidationSummary.Selector select( - final CrudRepository certMan) { - return new SupplyChainValidationSummary.Selector(certMan); - } - /** * Construct a new SupplyChainValidationSummary. * - * @param device device that underwent supply chain validation - * @param validations a Collection of Validations that should comprise this summary; not null + * @param device device that underwent supply chain validation + * @param validations a Collection of Validations that should comprise this summary; not null * @param provisionSessionId randomly generated UUID to associate with results */ public SupplyChainValidationSummary(final Device device, @@ -198,7 +86,7 @@ public class SupplyChainValidationSummary extends ArchivableEntity { /** * Construct a new SupplyChainValidationSummary. * - * @param device device that underwent supply chain validation + * @param device device that underwent supply chain validation * @param validations a Collection of Validations that should comprise this summary; not null */ public SupplyChainValidationSummary(final Device device, @@ -221,6 +109,18 @@ public class SupplyChainValidationSummary extends ArchivableEntity { this.message = status.getMessage(); } + /** + * Get a Selector for use in retrieving SupplyChainValidationSummary. + * + * @param certMan the CrudManager to be used to retrieve persisted supply chain validation + * summaries + * @return a SupplyChainValidationSummary.Selector instance to use for retrieving certificates + */ + public static SupplyChainValidationSummary.Selector select( + final CrudRepository certMan) { + return new SupplyChainValidationSummary.Selector(certMan); + } + /** * This retrieves the device associated with the supply chain validation summaries. * @@ -270,4 +170,103 @@ public class SupplyChainValidationSummary extends ArchivableEntity { return new AppraisalStatus(AppraisalStatus.Status.PASS, Strings.EMPTY); } + + /** + * This class enables the retrieval of SupplyChainValidationSummaries by their attributes. + */ + public static class Selector { + private final CrudRepository + supplyChainValidationSummaryCrudManager; + + private final Map fieldValueSelections; + + /** + * Construct a new Selector that will use the given {@link CrudRepository} to + * retrieve SupplyChainValidationSummaries. + * + * @param supplyChainValidationSummaryCrudManager the summary manager to be used to retrieve + * supply chain validation summaries + */ + public Selector( + final CrudRepository + supplyChainValidationSummaryCrudManager) { + Preconditions.checkArgument( + supplyChainValidationSummaryCrudManager != null, + "supply chain validation summary manager cannot be null" + ); + + this.supplyChainValidationSummaryCrudManager = supplyChainValidationSummaryCrudManager; + this.fieldValueSelections = new HashMap<>(); + } + + /** + * Construct the criterion that can be used to query for supply chain validation summaries + * matching the configuration of this Selector. + * + * @param criteriaBuilder criteria builder + * @return a Criterion that can be used to query for supply chain validation summaries + * matching the configuration of this instance + */ + public Predicate[] getCriterion(final CriteriaBuilder criteriaBuilder) { + Predicate[] predicates = new Predicate[fieldValueSelections.size()]; + CriteriaQuery query = + criteriaBuilder.createQuery(SupplyChainValidationSummary.class); + Root root = query.from(SupplyChainValidationSummary.class); + + int i = 0; + for (Map.Entry fieldValueEntry : fieldValueSelections.entrySet()) { + predicates[i++] = + criteriaBuilder.equal(root.get(fieldValueEntry.getKey()), fieldValueEntry.getValue()); + } + + return predicates; + } + + /** + * Set a field name and value to match. + * + * @param name the field name to query + * @param value the value to query + */ + protected void setFieldValue(final String name, final Object value) { + Object valueToAssign = value; + + Preconditions.checkArgument( + value != null, + "field value cannot be null." + ); + + if (value instanceof String) { + Preconditions.checkArgument( + StringUtils.isNotEmpty((String) value), + "field value cannot be empty." + ); + } + + if (value instanceof byte[] valueBytes) { + + Preconditions.checkArgument( + ArrayUtils.isNotEmpty(valueBytes), + "field value cannot be empty." + ); + + valueToAssign = Arrays.copyOf(valueBytes, valueBytes.length); + } + + fieldValueSelections.put(name, valueToAssign); + } + + + /** + * Specify a device id that supply chain validation summaries must have to be considered + * as matching. + * + * @param device the device id to query + * @return this instance (for chaining further calls) + */ + public Selector byDeviceId(final UUID device) { + setFieldValue(DEVICE_ID_FIELD, device); + return this; + } + } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/CertificateAuthorityCredential.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/CertificateAuthorityCredential.java index 72047d42..0f5e5421 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/CertificateAuthorityCredential.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/CertificateAuthorityCredential.java @@ -3,6 +3,7 @@ package hirs.attestationca.persist.entity.userdefined.certificate; import hirs.attestationca.persist.entity.userdefined.Certificate; import jakarta.persistence.Column; import jakarta.persistence.Entity; +import lombok.AccessLevel; import lombok.Getter; import org.apache.commons.codec.binary.Hex; @@ -14,36 +15,36 @@ import java.util.Arrays; * This class persists Certificate Authority credentials by extending the base Certificate * class with fields unique to CA credentials. */ +@Getter @Entity public class CertificateAuthorityCredential extends Certificate { - - @SuppressWarnings("PMD.AvoidUsingHardCodedIP") - private static final String SUBJECT_KEY_IDENTIFIER_EXTENSION = "2.5.29.14"; - /** * Holds the name of the 'subjectKeyIdentifier' field. */ public static final String SUBJECT_KEY_IDENTIFIER_FIELD = "subjectKeyIdentifier"; + @SuppressWarnings("PMD.AvoidUsingHardCodedIP") + private static final String SUBJECT_KEY_IDENTIFIER_EXTENSION = "2.5.29.14"; + private static final int CA_BYTE_SIZE = 20; + private static final int PREFIX_BYTE_SIZE = 4; + @Getter(AccessLevel.NONE) @Column private final byte[] subjectKeyIdentifier; - @Getter - @Column - private String subjectKeyIdString; - /** * this field is part of the TCG CA specification, but has not yet been found in * manufacturer-provided CAs, and is therefore not currently parsed. */ - @Getter @Column private final String credentialType = "TCPA Trusted Platform Module Endorsement"; + @Column + private String subjectKeyIdString; + /** * Construct a new CertificateAuthorityCredential given its binary contents. The given * certificate should represent either an X509 certificate or X509 attribute certificate. @@ -111,6 +112,13 @@ public class CertificateAuthorityCredential extends Certificate { return null; } + /** + * Helper method that uses the provided certificate bytes and truncates a portion + * of the certificate bytes array. + * + * @param certificateBytes byte array representation of the certificate bytes + * @return a truncated certificate byte array + */ private byte[] truncatePrefixBytes(final byte[] certificateBytes) { byte[] temp = new byte[CA_BYTE_SIZE]; System.arraycopy(certificateBytes, PREFIX_BYTE_SIZE, temp, 0, CA_BYTE_SIZE); @@ -118,8 +126,14 @@ public class CertificateAuthorityCredential extends Certificate { return temp; } - @Override - @SuppressWarnings("checkstyle:avoidinlineconditionals") + /** + * Compares this Certificate Authority Credential object to another Certificate + * Authority Credential object. + * + * @param o object to compare + * @return true if both this and the provided Certificate Authority Credential objects are equal, + * false otherwise + */ public boolean equals(final Object o) { if (this == o) { return true; @@ -140,12 +154,17 @@ public class CertificateAuthorityCredential extends Certificate { return Arrays.equals(subjectKeyIdentifier, that.subjectKeyIdentifier); } + /** + * Creates an integer hash code. + * + * @return an integer hash code + */ @Override - @SuppressWarnings({"checkstyle:magicnumber", "checkstyle:avoidinlineconditionals"}) public int hashCode() { + final int hashCodeConst = 31; int result = super.hashCode(); - result = 31 * result + (credentialType != null ? credentialType.hashCode() : 0); - result = 31 * result + Arrays.hashCode(subjectKeyIdentifier); + result = hashCodeConst * result + credentialType.hashCode(); + result = hashCodeConst * result + Arrays.hashCode(subjectKeyIdentifier); return result; } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/CertificateVariables.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/CertificateVariables.java index 621ef771..eff3b7a3 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/CertificateVariables.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/CertificateVariables.java @@ -1,47 +1,179 @@ package hirs.attestationca.persist.entity.userdefined.certificate; -public class CertificateVariables { +public final class CertificateVariables { + /** + * + */ public static final String PEM_HEADER = "-----BEGIN CERTIFICATE-----"; + /** + * + */ public static final String PEM_FOOTER = "-----END CERTIFICATE-----"; + /** + * + */ public static final String PEM_ATTRIBUTE_HEADER = "-----BEGIN ATTRIBUTE CERTIFICATE-----"; + /** + * + */ public static final String PEM_ATTRIBUTE_FOOTER = "-----END ATTRIBUTE CERTIFICATE-----"; + /** + * + */ public static final String MALFORMED_CERT_MESSAGE = "Malformed certificate detected."; + /** + * + */ public static final int MAX_CERT_LENGTH_BYTES = 2048; - public static final int MAX_NUMERIC_PRECISION = 49; // Can store up to 160 bit values + /** + * + */ + public static final int MAX_NUMERIC_PRECISION = 49; + /** + * Can store up to 160 bit values. + */ public static final int MAX_PUB_KEY_MODULUS_HEX_LENGTH = 1024; + /** + * + */ public static final int KEY_USAGE_BIT0 = 0; + /** + * + */ public static final int KEY_USAGE_BIT1 = 1; + /** + * + */ public static final int KEY_USAGE_BIT2 = 2; + /** + * + */ public static final int KEY_USAGE_BIT3 = 3; + /** + * + */ public static final int KEY_USAGE_BIT4 = 4; + /** + * + */ public static final int KEY_USAGE_BIT5 = 5; + /** + * + */ public static final int KEY_USAGE_BIT6 = 6; + /** + * + */ public static final int KEY_USAGE_BIT7 = 7; + /** + * + */ public static final int KEY_USAGE_BIT8 = 8; + /** + * + */ public static final String KEY_USAGE_DS = "DIGITAL SIGNATURE"; + /** + * + */ public static final String KEY_USAGE_NR = "NON-REPUDIATION"; + /** + * + */ public static final String KEY_USAGE_KE = "KEY ENCIPHERMENT"; + /** + * + */ public static final String KEY_USAGE_DE = "DATA ENCIPHERMENT"; + /** + * + */ public static final String KEY_USAGE_KA = "KEY AGREEMENT"; + /** + * + */ public static final String KEY_USAGE_KC = "KEY CERT SIGN"; + /** + * + */ public static final String KEY_USAGE_CS = "CRL SIGN"; + /** + * + */ public static final String KEY_USAGE_EO = "ENCIPHER ONLY"; + /** + * + */ public static final String KEY_USAGE_DO = "DECIPHER ONLY"; + /** + * + */ public static final String ECDSA_OID = "1.2.840.10045.4.3.2"; + /** + * + */ public static final String ECDSA_SHA224_OID = "1.2.840.10045.4.1"; + /** + * + */ public static final String RSA256_OID = "1.2.840.113549.1.1.11"; + /** + * + */ public static final String RSA384_OID = "1.2.840.113549.1.1.12"; + /** + * + */ public static final String RSA512_OID = "1.2.840.113549.1.1.13"; + /** + * + */ public static final String RSA224_OID = "1.2.840.113549.1.1.14"; + /** + * + */ public static final String RSA512_224_OID = "1.2.840.113549.1.1.15"; + /** + * + */ public static final String RSA512_256_OID = "1.2.840.113549.1.1.16"; + /** + * + */ public static final String RSA256_STRING = "SHA256WithRSA"; + /** + * + */ public static final String RSA384_STRING = "SHA384WithRSA"; + /** + * + */ public static final String RSA224_STRING = "SHA224WithRSA"; + /** + * + */ public static final String RSA512_STRING = "SHA512WithRSA"; + /** + * + */ public static final String RSA512_224_STRING = "SHA512-224WithRSA"; + /** + * + */ public static final String RSA512_256_STRING = "SHA512-256WithRSA"; + /** + * + */ public static final String ECDSA_STRING = "SHA256WithECDSA"; + /** + * + */ public static final String ECDSA_SHA224_STRING = "SHA224WithECDSA"; + + /** + * Private constructor was created to silence checkstyle error. + */ + private CertificateVariables() { + } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/ComponentResult.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/ComponentResult.java index 72b09a72..01eef415 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/ComponentResult.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/ComponentResult.java @@ -26,50 +26,80 @@ import java.util.Objects; @NoArgsConstructor(access = AccessLevel.PROTECTED) public class ComponentResult extends ArchivableEntity { - // String value for the Manufacturer title + /** + * String value for the Manufacturer title. + */ public static final String ATTRIBUTE_MANUFACTURER = "Manufacturer"; - // String value for the Model title + + /** + * String value for the Model title. + */ public static final String ATTRIBUTE_MODEL = "Model"; - // String value for the Serial title + + /** + * String value for the Serial title. + */ public static final String ATTRIBUTE_SERIAL = "Serial"; - // String value for the revision title + + /** + * String value for the revision title. + */ public static final String ATTRIBUTE_REVISION = "Revision"; - // embedded component info + + /** + * Embedded component info. + */ @Setter private String manufacturer; + @Setter private String model; + @Setter private String serialNumber; + @Setter private String revisionNumber; + private boolean fieldReplaceable = false; + // this is a string because component class doesn't inherit serializable. @Setter private String componentClassValue; + private String componentClassStr; + private String componentClassType; + private AttributeStatus attributeStatus; + private String componentAddress; + private boolean version2 = false; + @Setter private boolean delta = false; + @Setter private boolean failedValidation; + private String certificateType; private String issuerDN; - private String certificateSerialNumber; - private String boardSerialNumber; - private String uniformResourceIdentifier; + private String certificateSerialNumber; + + private String boardSerialNumber; + + private String uniformResourceIdentifier; /** * Default constructor. - * @param boardSerialNumber associated platform certificate serial number. + * + * @param boardSerialNumber associated platform certificate serial number. * @param certificateSerialNumber unique number associated with header info. - * @param certificateType parameter holds version 1.2 or 2.0. - * @param componentIdentifier object with information from the platform certificate components. + * @param certificateType parameter holds version 1.2 or 2.0. + * @param componentIdentifier object with information from the platform certificate components. */ public ComponentResult(final String boardSerialNumber, final String certificateSerialNumber, final String certificateType, @@ -94,10 +124,9 @@ public class ComponentResult extends ArchivableEntity { // V2 fields if (componentIdentifier.isVersion2() - && componentIdentifier instanceof ComponentIdentifierV2) { + && componentIdentifier instanceof ComponentIdentifierV2 ciV2) { // this is a downside of findbugs, the code is set up to indicate if a CI is V2 or not // but find bugs is throwing a flag because instanceof isn't being used. - ComponentIdentifierV2 ciV2 = (ComponentIdentifierV2) componentIdentifier; this.componentClassValue = ciV2.getComponentClass().getComponentIdentifier(); this.componentClassStr = ciV2.getComponentClass().toString(); this.componentClassType = ciV2.getComponentClass().getRegistryType(); @@ -117,6 +146,7 @@ public class ComponentResult extends ArchivableEntity { * This method is only used by the certificate-details.jsp page. This * method splits the compiled string of addresses into the component address * object for display on the jsp page. + * * @return a collection of component addresses. */ public List getComponentAddresses() { @@ -135,6 +165,7 @@ public class ComponentResult extends ArchivableEntity { /** * Returns a hash code that is associated with common fields for components. + * * @return int value of the elements */ public int hashCommonElements() { @@ -144,6 +175,7 @@ public class ComponentResult extends ArchivableEntity { /** * The string method for log entries. + * * @return a string for the component result */ public String toString() { diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/ConformanceCredential.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/ConformanceCredential.java index 25186117..963f869f 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/ConformanceCredential.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/ConformanceCredential.java @@ -12,12 +12,13 @@ import java.nio.file.Path; * This class persists Conformance credentials by extending the base Certificate * class with fields unique to Conformance credentials. */ -@NoArgsConstructor(access= AccessLevel.PROTECTED) +@NoArgsConstructor(access = AccessLevel.PROTECTED) @Entity public class ConformanceCredential extends Certificate { - /** - * This class enables the retrieval of ConformanceCredentials by their attributes. - */ + +// /** +// * This class enables the retrieval of ConformanceCredentials by their attributes. +// */ // public static class Selector extends CertificateSelector { // /** // * Construct a new CertificateSelector that will use the given {@link CertificateManager} to @@ -30,12 +31,12 @@ public class ConformanceCredential extends Certificate { // } // } - /** - * Get a Selector for use in retrieving ConformanceCredentials. - * - * @param certMan the CertificateManager to be used to retrieve persisted certificates - * @return a ConformanceCredential.Selector instance to use for retrieving certificates - */ +// /** +// * Get a Selector for use in retrieving ConformanceCredentials. +// * +// * @param certMan the CertificateManager to be used to retrieve persisted certificates +// * @return a ConformanceCredential.Selector instance to use for retrieving certificates +// */ // public static Selector select(final CertificateManager certMan) { // return new Selector(certMan); // } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/DeviceAssociatedCertificate.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/DeviceAssociatedCertificate.java index e0f54321..45c08175 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/DeviceAssociatedCertificate.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/DeviceAssociatedCertificate.java @@ -18,26 +18,25 @@ import java.util.UUID; * * @see Certificate */ -@NoArgsConstructor(access= AccessLevel.PACKAGE) +@Setter +@Getter +@NoArgsConstructor(access = AccessLevel.PACKAGE) @MappedSuperclass public abstract class DeviceAssociatedCertificate extends Certificate { - // a device can have multiple certs of this type. - @Getter - @Setter - @JdbcTypeCode(java.sql.Types.VARCHAR) - @Column - private UUID deviceId; - @Getter - @Setter - @Column - private String deviceName; - /** * Holds the name of the entity 'DEVICE_ID' field. */ protected static final String DEVICE_ID_FIELD = "device_id"; + // a device can have multiple certs of this type. + @JdbcTypeCode(java.sql.Types.VARCHAR) + @Column + private UUID deviceId; + + @Column + private String deviceName; + /** * Construct a new Certificate by parsing the file at the given path. The given certificate * should represent either an X509 certificate or X509 attribute certificate. diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/EndorsementCredential.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/EndorsementCredential.java index 8c12e05b..961e4423 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/EndorsementCredential.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/EndorsementCredential.java @@ -1,5 +1,6 @@ package hirs.attestationca.persist.entity.userdefined.certificate; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hirs.attestationca.persist.entity.userdefined.certificate.attributes.TPMSecurityAssertions; import hirs.attestationca.persist.entity.userdefined.certificate.attributes.TPMSpecification; import jakarta.persistence.Column; @@ -53,16 +54,18 @@ import java.util.Map; import java.util.Set; /** - * * This class persists an Endorsement Credential by extending the base Certificate * class with fields unique to Endorsement credentials, as defined in the Trusted * Computing Group Credential Profiles, specification v.1.2. - * + *

* trustedcomputinggroup.org/wp-content/uploads/Credential_Profiles_V1.2_Level2_Revision8.pdf */ @Log4j2 +@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", + justification = "property credentialType is guaranteed to always be non-null/initialized. Warning" + + "stems from auto-generated lombok equals and hashcode method doing redundant null checks.") @EqualsAndHashCode(callSuper = false) -@NoArgsConstructor(access= AccessLevel.PROTECTED) +@NoArgsConstructor(access = AccessLevel.PROTECTED) @Entity public class EndorsementCredential extends DeviceAssociatedCertificate { @@ -105,11 +108,27 @@ public class EndorsementCredential extends DeviceAssociatedCertificate { /** * this field is part of the TCG EC specification, but has not yet been found in - * manufacturer-provided ECs, and is therefore not currently parsed + * manufacturer-provided ECs, and is therefore not currently parsed. */ @Getter @Column - private String credentialType = "TCPA Trusted Platform Module Endorsement"; + private final String credentialType = "TCPA Trusted Platform Module Endorsement"; + + /** + * this field is part of the TCG EC specification, but has not yet been found in + * manufacturer-provided ECs, and is therefore not currently parsed. + */ + @Getter + @Column + private final String policyReference = null; // optional + + /** + * this field is part of the TCG EC specification, but has not yet been found in + * manufacturer-provided ECs, and is therefore not currently parsed. + */ + @Getter + @Column + private final String revocationLocator = null; // optional @Getter @Column @@ -131,22 +150,6 @@ public class EndorsementCredential extends DeviceAssociatedCertificate { @Embedded private TPMSecurityAssertions tpmSecurityAssertions = null; //optional - /* - * this field is part of the TCG EC specification, but has not yet been found in - * manufacturer-provided ECs, and is therefore not currently parsed - */ - @Getter - @Column(nullable = true) - private String policyReference = null; // optional - - /* - * this field is part of the TCG EC specification, but has not yet been found in - * manufacturer-provided ECs, and is therefore not currently parsed - */ - @Getter - @Column(nullable = true) - private String revocationLocator = null; // optional - @Transient private Set expectedOids; @@ -180,6 +183,7 @@ public class EndorsementCredential extends DeviceAssociatedCertificate { * Parses the bytes as an EK. If parsing fails initially, the optionally present header * is removed and tried again. The cert header, if present, contains some certificate length * information which isn't needed for parsing. + * * @param certificateBytes the bytes of the EC * @return the EC if a valid credential, null otherwise */ @@ -228,6 +232,7 @@ public class EndorsementCredential extends DeviceAssociatedCertificate { * ASN1Primitives in the certificate and searches for matching OID keys of specific values. If * matching OID keys are found, their values are encoded in the fields of the current * EndorsementCredential object. + * * @throws IOException the input certificate bytes were not readable into an X509 * certificate format */ @@ -264,13 +269,13 @@ public class EndorsementCredential extends DeviceAssociatedCertificate { value = entry.getValue(); if (oid.equals(TPM_MODEL)) { model = value.toString(); - log.debug("Found TPM Model: " + model); + log.debug("Found TPM Model: {}", model); } else if (oid.equals(TPM_VERSION)) { version = value.toString(); - log.debug("Found TPM Version: " + version); + log.debug("Found TPM Version: {}", version); } else if (oid.equals(TPM_MANUFACTURER)) { manufacturer = value.toString(); - log.debug("Found TPM Manufacturer: " + manufacturer); + log.debug("Found TPM Manufacturer: {}", manufacturer); } } } @@ -280,9 +285,10 @@ public class EndorsementCredential extends DeviceAssociatedCertificate { * however, the method is set to add the sequence to the OID mapping, it may search for * patterns that correspond to the TPM Security Assertions and TPM Specification and set * those fields appropriately. - * @param seq the sequence to parse + * + * @param seq the sequence to parse * @param addToMapping whether or not to store the sequence value as an OID key/value value - * @param key the associated OID key with this value necessary if addToMapping is true + * @param key the associated OID key with this value necessary if addToMapping is true * @throws IOException parsing individual subcomponents failed */ private void parseSequence(final ASN1Sequence seq, final boolean addToMapping, @@ -315,7 +321,7 @@ public class EndorsementCredential extends DeviceAssociatedCertificate { ASN1Integer revision = (ASN1Integer) seq.getObjectAt(ASN1_REV_INDEX); tpmSpecification = new TPMSpecification(family.getString(), level.getValue(), revision.getValue()); - log.debug("Found TPM Spec:" + tpmSpecification.toString()); + log.debug("Found TPM Spec:{}", tpmSpecification); } else if (addToMapping && key.equals(TPM_SECURITY_ASSERTIONS)) { // Parse TPM Security Assertions int seqPosition = 0; @@ -341,7 +347,7 @@ public class EndorsementCredential extends DeviceAssociatedCertificate { tpmSecurityAssertions = new TPMSecurityAssertions(ver.getValue(), fieldUpgradeable.isTrue()); - log.debug("Found TPM Assertions: " + tpmSecurityAssertions.toString()); + log.debug("Found TPM Assertions: {}", tpmSecurityAssertions); // Iterate through remaining fields to set optional attributes int tag; ASN1TaggedObject obj; @@ -392,13 +398,13 @@ public class EndorsementCredential extends DeviceAssociatedCertificate { * Parses the many different types of ASN1Primitives and searches for specific OID * key/value pairs. Works by traversing the entire ASN1Primitive tree with a single * pass and populates relevant fields in the EndorsementCredential object. - * @param component the ASN1Primitive to parse + * + * @param component the ASN1Primitive to parse * @param addToMapping whether or not the current component has been matched as the * value in an expected TPM OID key/value pair - * @param key if addToMapping is true, the key in the OID key/value pair + * @param key if addToMapping is true, the key in the OID key/value pair * @throws IOException parsing of subcomponents in the tree failed. */ - @SuppressWarnings("checkstyle:methodlength") private void parseSingle(final ASN1Primitive component, final boolean addToMapping, final String key) throws IOException { // null check the key if addToMapping is true @@ -421,13 +427,11 @@ public class EndorsementCredential extends DeviceAssociatedCertificate { parsedFields.put(key, ((ASN1ObjectIdentifier) component).getId()); } - } else if (component instanceof ASN1TaggedObject) { - ASN1TaggedObject taggedObj = (ASN1TaggedObject) component; + } else if (component instanceof ASN1TaggedObject taggedObj) { parseSingle(taggedObj.getBaseObject().toASN1Primitive(), addToMapping, key); - } else if (component instanceof ASN1OctetString) { + } else if (component instanceof ASN1OctetString octStr) { // this may contain parseable data or may just be a OID key-pair value - ASN1OctetString octStr = (ASN1OctetString) component; byte[] bytes = octStr.getOctets(); ByteArrayInputStream inStream = new ByteArrayInputStream(bytes); ASN1InputStream octIn = new ASN1InputStream(inStream); @@ -446,12 +450,11 @@ public class EndorsementCredential extends DeviceAssociatedCertificate { } } - } else if (component instanceof ASN1Set) { + } else if (component instanceof ASN1Set set) { // all ECs seen to this point use sets differently than sequences and their sets // don't contain top level OIDs, so we can parse everything term by term, if that // ceases to be the case, we need to switch to this parsing to be more like // parseSequences in the future - ASN1Set set = (ASN1Set) component; Enumeration setContents = set.getObjects(); ASN1Encodable subComp; while (setContents.hasMoreElements()) { @@ -563,7 +566,7 @@ public class EndorsementCredential extends DeviceAssociatedCertificate { } else { // there are some deprecated types that we don't parse - log.error("Unparsed type: " + component.getClass()); + log.error("Unparsed type: {}", component.getClass()); } } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/IDevIDCertificate.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/IDevIDCertificate.java index a282c6b8..2a30a6d4 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/IDevIDCertificate.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/IDevIDCertificate.java @@ -4,10 +4,15 @@ import hirs.attestationca.persist.entity.userdefined.Certificate; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Transient; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.extern.log4j.Log4j2; -import org.apache.commons.codec.binary.Hex; -import org.bouncycastle.asn1.*; +import org.bouncycastle.asn1.ASN1Encodable; +import org.bouncycastle.asn1.ASN1InputStream; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.ASN1OctetString; +import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.ASN1TaggedObject; import org.bouncycastle.asn1.x509.CertificatePolicies; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.PolicyInformation; @@ -15,23 +20,15 @@ import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils; import java.io.ByteArrayInputStream; import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.time.Instant; -import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; -import java.util.List; import java.util.Map; -import java.util.Objects; -import java.util.Set; @Entity +@Getter +@EqualsAndHashCode(callSuper = true) @Log4j2 public class IDevIDCertificate extends Certificate { @@ -49,28 +46,24 @@ public class IDevIDCertificate extends Certificate { private static final String POLICY_QUALIFIER_VERIFIED_TPM_FIXED = "2.23.133.11.1.2"; private static final String POLICY_QUALIFIER_VERIFIED_TPM_RESTRICTED = "2.23.133.11.1.3"; - @Getter @Transient private byte[] subjectAltName; /** * Corresponds to the hwType field found in a Hardware Module Name (if present). */ - @Getter @Column private String hwType; /** * Corresponds to the serial number found in a Hardware Module Name (if present). */ - @Getter @Column private byte[] hwSerialNum; /** * TPM policy qualifiers (TCG only). */ - @Getter @Column private String tpmPolicies; @@ -110,13 +103,14 @@ public class IDevIDCertificate extends Certificate { } /** - * Obtains TPM policy qualifiers from the Certificate Policies extension, if present. These policy qualifiers are - * specified in the TCG document "TPM 2.0 Keys for Device Identity and Attestation". + * Obtains TPM policy qualifiers from the Certificate Policies extension, if present. These policy + * qualifiers are specified in the TCG document "TPM 2.0 Keys for Device Identity and Attestation". * + * @param policyBytes byte array representation of the policy * @return A {@link java.util.Map} containing the policy qualifiers obtained. * @throws IOException if policy qualifiers cannot be parsed from extension value */ - public Map getTPMPolicyQualifiers(byte[] policyBytes) throws IOException { + public Map getTPMPolicyQualifiers(final byte[] policyBytes) throws IOException { CertificatePolicies certPolicies = CertificatePolicies.getInstance(JcaX509ExtensionUtils.parseExtensionValue(policyBytes)); Map policyQualifiers = new HashMap<>(); @@ -154,6 +148,7 @@ public class IDevIDCertificate extends Certificate { /** * Parses fields related to IDevID certificates. + * * @throws IOException if a problem is encountered during parsing */ private void parseIDevIDCertificate() throws IOException { @@ -170,13 +165,13 @@ public class IDevIDCertificate extends Certificate { ASN1OctetString obj = (ASN1OctetString) input.readObject(); boolean tcgOid = false; - // Parse the otherName structure. According to the specification "TPM 2.0 Keys for Device Identity and - // Attestation", otherName can contain up to two structures: HardwareModuleName and PermanentIdentifier. - // Currently, this parser only supports HardwareModuleName (if present). + // Parse the otherName structure. According to the specification "TPM 2.0 Keys for Device Identity + // and Attestation", otherName can contain up to two structures: HardwareModuleName and + // PermanentIdentifier. Currently, this parser only supports HardwareModuleName (if present). if (obj != null) { - // Parse Hardware Module Name structure, comprised of a hwType and hwSerialNum, and associated OID - // See also RFC 4108 + // Parse Hardware Module Name structure, comprised of a hwType and hwSerialNum, + // and associated OID. See also RFC 4108 ASN1Sequence seq1 = ASN1Sequence.getInstance(obj.getOctets()); // Iterate over GeneralNames sequence until HardwareModuleName is found @@ -207,23 +202,24 @@ public class IDevIDCertificate extends Certificate { } catch (IllegalArgumentException e) { // Some certs have been found to contain tagged objects for hwSerialNum. // Handle this as a special case. - log.warn("Could not parse octet string for hwSerialNum. Attempting to parse tag."); + log.warn( + "Could not parse octet string for hwSerialNum. " + + "Attempting to parse tag."); try { tagObj1 = ASN1TaggedObject.getInstance(seq1.getObjectAt(1)); obj2 = ASN1OctetString.getInstance(tagObj1, false); - } - catch (Exception i) { // Invalid object found + } catch (Exception i) { // Invalid object found log.warn("Invalid object found for hwSerialNum."); break; } } - // If an OID corresponding to TPM 2.0 for hwType is supported, according to the - // specification "TPM 2.0 Keys for Device Identity and Attestation", the contents of - // the hwSerialNum field will be parsed accordingly. + // If an OID corresponding to TPM 2.0 for hwType is supported, according + // to the specification "TPM 2.0 Keys for Device Identity and Attestation", + // the contents of the hwSerialNum field will be parsed accordingly. hwType = obj1.toString(); if (hasTCGOIDs()) { - tcgOid = true; + tcgOid = true; } // Convert octet string to byte array @@ -234,10 +230,11 @@ public class IDevIDCertificate extends Certificate { } } - // Check for certificate policy qualifiers, which should be present for IDevIDs if in compliance with the - // TCG specification. - // For interoperability reasons, this will only log a warning if a TCG OID is specified above. - byte[] policyBytes = getX509Certificate().getExtensionValue(Extension.certificatePolicies.getId()); + // Check for certificate policy qualifiers, which should be present for IDevIDs if in compliance + // with the TCG specification. For interoperability reasons, this will only log a warning + // if a TCG OID is specified above. + byte[] policyBytes = + getX509Certificate().getExtensionValue(Extension.certificatePolicies.getId()); Map policyQualifiers = null; if (policyBytes != null) { @@ -257,22 +254,23 @@ public class IDevIDCertificate extends Certificate { }); tpmPolicies = qualifierSB.toString(); - failCondition = !(policyQualifiers.get("verifiedTPMResidency") && - (policyQualifiers.get("verifiedTPMFixed") || - policyQualifiers.get("verifiedTPMRestricted"))); + failCondition = !(policyQualifiers.get("verifiedTPMResidency") + && (policyQualifiers.get("verifiedTPMFixed") + || policyQualifiers.get("verifiedTPMRestricted"))); } else { failCondition = true; } if (failCondition) { - log.warn("TPM policy qualifiers not found, or do not meet logical criteria. Certificate may not " + - "be in compliance with TCG specification."); + log.warn( + "TPM policy qualifiers not found, or do not meet logical criteria. " + + "Certificate may not be in compliance with TCG specification."); } } // Log a warning if notAfter field has an expiry date that is not indefinite if (!this.getEndValidity().toInstant().equals(Instant.ofEpochSecond(UNDEFINED_EXPIRY_DATE))) { - log.warn("IDevID does not contain an indefinite expiry date. This may indicate an invalid " + - "certificate."); + log.warn("IDevID does not contain an indefinite expiry date. This may indicate an invalid " + + "certificate."); } input.close(); @@ -280,54 +278,16 @@ public class IDevIDCertificate extends Certificate { } /** - * Function to check whether a given IDevID certificate has TCG OIDs, in order to check compliance with various - * fields. + * Function to check whether a given IDevID certificate has TCG OIDs, in order to check compliance with + * various fields. * * @return a boolean value */ public boolean hasTCGOIDs() { if (this.getHwType() != null) { return this.getHwType().equals(HWTYPE_TCG_TPM2_OID); - } - else { + } else { return false; } } - - @Override - @SuppressWarnings("checkstyle:avoidinlineconditionals") - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - - IDevIDCertificate that = (IDevIDCertificate) o; - - if (!Objects.equals(getTpmPolicies(), that.getTpmPolicies())) { - return false; - } - - if (!Objects.equals(getHwType(), that.getHwType())) { - return false; - } - - return Arrays.equals(getHwSerialNum(), that.getHwSerialNum()); - } - - @Override - @SuppressWarnings({"checkstyle:magicnumber", "checkstyle:avoidinlineconditionals"}) - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (getTpmPolicies() != null ? getTpmPolicies().hashCode() : 0); - result = 31 * result + (getHwType() != null ? getHwType().hashCode() : 0); - result = 31 * result + (getHwSerialNum() != null ? Arrays.hashCode(getHwSerialNum()) : 0); - - return result; - } -} \ No newline at end of file +} diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/IssuedAttestationCertificate.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/IssuedAttestationCertificate.java index 8c4c0e41..891bf6b1 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/IssuedAttestationCertificate.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/IssuedAttestationCertificate.java @@ -18,8 +18,8 @@ import java.util.List; /** * Represents an issued attestation certificate to a HIRS Client. */ -@NoArgsConstructor(access = AccessLevel.PROTECTED) @Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) @Entity public class IssuedAttestationCertificate extends DeviceAssociatedCertificate { @@ -28,6 +28,9 @@ public class IssuedAttestationCertificate extends DeviceAssociatedCertificate { */ public static final String AIC_TYPE_LABEL = "TCPA Trusted Platform Identity"; + @Column + private boolean isLDevID; + @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "ek_id") private EndorsementCredential endorsementCredential; @@ -36,19 +39,19 @@ public class IssuedAttestationCertificate extends DeviceAssociatedCertificate { @JoinColumn(name = "pc_id") private List platformCredentials; - @Column - public boolean isLDevID; - /** * Constructor. - * @param certificateBytes the issued certificate bytes + * + * @param certificateBytes the issued certificate bytes * @param endorsementCredential the endorsement credential - * @param platformCredentials the platform credentials + * @param platformCredentials the platform credentials + * @param isLDevID is LDevId * @throws IOException if there is a problem extracting information from the certificate */ public IssuedAttestationCertificate(final byte[] certificateBytes, final EndorsementCredential endorsementCredential, - final List platformCredentials, boolean isLDevID) + final List platformCredentials, + final boolean isLDevID) throws IOException { super(certificateBytes); this.endorsementCredential = endorsementCredential; @@ -58,9 +61,11 @@ public class IssuedAttestationCertificate extends DeviceAssociatedCertificate { /** * Constructor. - * @param certificatePath path to certificate + * + * @param certificatePath path to certificate * @param endorsementCredential the endorsement credential - * @param platformCredentials the platform credentials + * @param platformCredentials the platform credentials + * @param isLDevID is it an LDev ID * @throws IOException if there is a problem extracting information from the certificate */ public IssuedAttestationCertificate(final Path certificatePath, @@ -70,8 +75,4 @@ public class IssuedAttestationCertificate extends DeviceAssociatedCertificate { throws IOException { this(readBytes(certificatePath), endorsementCredential, platformCredentials, isLDevID); } - - public List getPlatformCredentials() { - return new ArrayList<>(platformCredentials); - } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/PlatformCredential.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/PlatformCredential.java index fb31822a..e11ab146 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/PlatformCredential.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/PlatformCredential.java @@ -46,7 +46,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.UUID; /** * This class persists Platform credentials by extending the base Certificate @@ -61,24 +60,29 @@ import java.util.UUID; @Entity public class PlatformCredential extends DeviceAssociatedCertificate { + /** + * TCPA Trusted Platform Endorsement. + */ + public static final String CERTIFICATE_TYPE_1_2 = "TCPA Trusted Platform Endorsement"; + /** + * TCG Trusted Platform Endorsement. + */ + public static final String CERTIFICATE_TYPE_2_0 = "TCG Trusted Platform Endorsement"; private static final int TCG_SPECIFICATION_LENGTH = 3; // These are Object Identifiers (OIDs) for sections in the credentials private static final String POLICY_QUALIFIER_CPSURI = "1.3.6.1.5.5.7.2.1"; private static final String POLICY_QUALIFIER_USER_NOTICE = "1.3.6.1.5.5.7.2.2"; - // OID for TCG Attributes private static final String PLATFORM_MANUFACTURER = "2.23.133.2.4"; private static final String PLATFORM_MODEL = "2.23.133.2.5"; private static final String PLATFORM_VERSION = "2.23.133.2.6"; private static final String PLATFORM_SERIAL = "2.23.133.2.23"; private static final String PLATFORM_BASEBOARD_CHASSIS_COMBINED = "2.23.133.5.1.6"; - // OID for TCG Platform Class Common Attributes private static final String PLATFORM_MANUFACTURER_2_0 = "2.23.133.5.1.1"; private static final String PLATFORM_MODEL_2_0 = "2.23.133.5.1.4"; private static final String PLATFORM_VERSION_2_0 = "2.23.133.5.1.5"; private static final String PLATFORM_SERIAL_2_0 = "2.23.133.5.1.6"; - // OID for Certificate Attributes private static final String TCG_PLATFORM_SPECIFICATION = "2.23.133.2.17"; private static final String TPM_SECURITY_ASSERTION = "2.23.133.2.18"; @@ -115,16 +119,11 @@ public class PlatformCredential extends DeviceAssociatedCertificate { // number of extra bytes potentially present in a cert header. private static final int PC_CERT_HEADER_BYTE_COUNT = 8; - - /** - * TCPA Trusted Platform Endorsement. - */ - public static final String CERTIFICATE_TYPE_1_2 = "TCPA Trusted Platform Endorsement"; - - /** - * TCG Trusted Platform Endorsement. - */ - public static final String CERTIFICATE_TYPE_2_0 = "TCG Trusted Platform Endorsement"; + private static final String MANUFACTURER_FIELD = "manufacturer"; + private static final String MODEL_FIELD = "model"; + private static final String VERSION_FIELD = "version"; + private static final String PLATFORM_SERIAL_FIELD = "platformSerial"; + private static final String CHASSIS_SERIAL_NUMBER_FIELD = "chassisSerialNumber"; @Column private String credentialType = null; @@ -132,23 +131,18 @@ public class PlatformCredential extends DeviceAssociatedCertificate { @Column private boolean platformBase = false; - private static final String MANUFACTURER_FIELD = "manufacturer"; @Column private String manufacturer = null; - private static final String MODEL_FIELD = "model"; @Column private String model = null; - private static final String VERSION_FIELD = "version"; @Column private String version = null; - private static final String PLATFORM_SERIAL_FIELD = "platformSerial"; @Column private String platformSerial = null; - private static final String CHASSIS_SERIAL_NUMBER_FIELD = "chassisSerialNumber"; @Column private String chassisSerialNumber; @@ -175,6 +169,7 @@ public class PlatformCredential extends DeviceAssociatedCertificate { @Column(length = MAX_MESSAGE_LENGTH) private String componentFailures = Strings.EMPTY; + @Column(length = MAX_MESSAGE_LENGTH) private String componentFailureMessage = Strings.EMPTY; @@ -182,6 +177,7 @@ public class PlatformCredential extends DeviceAssociatedCertificate { private EndorsementCredential endorsementCredential = null; private String platformChainType = Strings.EMPTY; + private boolean isDeltaChain = false; /** @@ -190,7 +186,7 @@ public class PlatformCredential extends DeviceAssociatedCertificate { * or X509 attribute certificate. * * @param certificateBytes the contents of a certificate file - * @param parseFields boolean True to parse fields + * @param parseFields boolean True to parse fields * @throws IOException if there is a problem extracting information from the certificate\ */ public PlatformCredential(final byte[] certificateBytes, @@ -223,40 +219,11 @@ public class PlatformCredential extends DeviceAssociatedCertificate { this(readBytes(certificatePath), true); } - /** - * Validate the signature on the attribute certificate in this holder. - * - * @param verifierProvider a ContentVerifierProvider that can generate a - * verifier for the signature. - * @return true if the signature is valid, false otherwise. - * @throws IOException if the signature cannot be processed or is inappropriate. - */ - public boolean isSignatureValid(final ContentVerifierProvider verifierProvider) - throws IOException { - AttributeCertificate attCert = getAttributeCertificate(); - AttributeCertificateInfo acinfo = getAttributeCertificate().getAcinfo(); - - // Check if the algorithm identifier is the same - if (!isAlgIdEqual(acinfo.getSignature(), attCert.getSignatureAlgorithm())) { - throw new IOException("signature invalid - algorithm identifier mismatch"); - } - - ContentVerifier verifier; - - try { - // Set ContentVerifier with the signature that will verify - verifier = verifierProvider.get((acinfo.getSignature())); - - } catch (Exception e) { - throw new IOException("unable to process signature: " + e.getMessage(), e); - } - - return verifier.verify(attCert.getSignatureValue().getOctets()); - } /** * Parses the bytes as an PC. If parsing fails initially, the optionally present header * is removed and tried again. The cert header, if present, contains some certificate length * information which isn't needed for parsing. + * * @param certificateBytes the bytes of the PC * @return the PC if a valid credential, null otherwise */ @@ -285,6 +252,103 @@ public class PlatformCredential extends DeviceAssociatedCertificate { return credential; } + /** + * Verify if the AlgorithmIdentifiers are equal. + * + * @param id1 AlgorithIdentifier one + * @param id2 AlgorithIdentifier two + * @return True if are the same, False if not + */ + public static boolean isAlgIdEqual(final AlgorithmIdentifier id1, + final AlgorithmIdentifier id2) { + if (!id1.getAlgorithm().equals(id2.getAlgorithm())) { + return false; + } + if (id1.getParameters() == null) { + return id2.getParameters() == null || id2.getParameters().equals(DERNull.INSTANCE); + } + if (id2.getParameters() == null) { + return id1.getParameters() == null || id1.getParameters().equals(DERNull.INSTANCE); + } + return id1.getParameters().equals(id2.getParameters()); + } + + /** + * Get the PolicyQualifier from the Certificate Policies Extension. + * + * @param certificate Attribute Certificate information + * @return Policy Qualifier from the Certificate Policies Extension + */ + public static Map getPolicyQualifier( + final AttributeCertificateInfo certificate) { + Preconditions.checkArgument(certificate.getExtensions() != null, + "Platform certificate should have extensions."); + + CertificatePolicies certPolicies + = CertificatePolicies.fromExtensions(certificate.getExtensions()); + Map policyQualifiers = new HashMap<>(); + String userNoticeQualifier = ""; + String cpsURI = ""; + + if (certPolicies != null) { + // Must contain at least one Policy + for (PolicyInformation policy : certPolicies.getPolicyInformation()) { + for (ASN1Encodable pQualifierInfo : policy.getPolicyQualifiers().toArray()) { + PolicyQualifierInfo info = PolicyQualifierInfo.getInstance(pQualifierInfo); + // Subtract the data based on the OID + switch (info.getPolicyQualifierId().getId()) { + case POLICY_QUALIFIER_CPSURI: + cpsURI = DERIA5String.getInstance(info.getQualifier()).getString(); + break; + case POLICY_QUALIFIER_USER_NOTICE: + UserNotice userNotice = UserNotice.getInstance(info.getQualifier()); + userNoticeQualifier = userNotice.getExplicitText().getString(); + break; + default: + break; + } + } + } + } + + // Add to map + policyQualifiers.put("userNotice", userNoticeQualifier); + policyQualifiers.put("cpsURI", cpsURI); + + return policyQualifiers; + } + + /** + * Validate the signature on the attribute certificate in this holder. + * + * @param verifierProvider a ContentVerifierProvider that can generate a + * verifier for the signature. + * @return true if the signature is valid, false otherwise. + * @throws IOException if the signature cannot be processed or is inappropriate. + */ + public boolean isSignatureValid(final ContentVerifierProvider verifierProvider) + throws IOException { + AttributeCertificate attCert = getAttributeCertificate(); + AttributeCertificateInfo acinfo = getAttributeCertificate().getAcinfo(); + + // Check if the algorithm identifier is the same + if (!isAlgIdEqual(acinfo.getSignature(), attCert.getSignatureAlgorithm())) { + throw new IOException("signature invalid - algorithm identifier mismatch"); + } + + ContentVerifier verifier; + + try { + // Set ContentVerifier with the signature that will verify + verifier = verifierProvider.get((acinfo.getSignature())); + + } catch (Exception e) { + throw new IOException("unable to process signature: " + e.getMessage(), e); + } + + return verifier.verify(attCert.getSignatureValue().getOctets()); + } + private void parseFields() throws IOException { AttributeCertificateInfo certificate = getAttributeCertificate().getAcinfo(); Map policyQualifier = getPolicyQualifier(certificate); @@ -340,6 +404,7 @@ public class PlatformCredential extends DeviceAssociatedCertificate { /** * Parse a 1.2 Platform Certificate (Attribute Certificate). + * * @param certificate Attribute Certificate */ private void parseAttributeCert(final AttributeCertificateInfo certificate) { @@ -347,14 +412,14 @@ public class PlatformCredential extends DeviceAssociatedCertificate { = certificate.getExtensions().getExtension(Extension.subjectAlternativeName); // It contains a Subject Alternative Name Extension if (subjectAlternativeNameExtension != null) { - GeneralNames gnames = GeneralNames.getInstance( + GeneralNames gnames = GeneralNames.getInstance( subjectAlternativeNameExtension.getParsedValue()); for (GeneralName gname : gnames.getNames()) { // Check if it's a directoryName [4] Name type if (gname.getTagNo() == GeneralName.directoryName) { X500Name name = X500Name.getInstance(gname.getName()); - for (RDN rdn: name.getRDNs()) { - for (AttributeTypeAndValue attTV: rdn.getTypesAndValues()) { + for (RDN rdn : name.getRDNs()) { + for (AttributeTypeAndValue attTV : rdn.getTypesAndValues()) { switch (attTV.getType().toString()) { case PLATFORM_MANUFACTURER: this.manufacturer = attTV.getValue().toString(); @@ -392,6 +457,7 @@ public class PlatformCredential extends DeviceAssociatedCertificate { /** * Parse a 2.0 Platform Certificate (Attribute Certificate). + * * @param certificate Attribute Certificate */ private void parseAttributeCert2(final AttributeCertificateInfo certificate) @@ -407,8 +473,8 @@ public class PlatformCredential extends DeviceAssociatedCertificate { // Check if it's a directoryName [4] Name type if (gname.getTagNo() == GeneralName.directoryName) { X500Name name = X500Name.getInstance(gname.getName()); - for (RDN rdn: name.getRDNs()) { - for (AttributeTypeAndValue attTV: rdn.getTypesAndValues()) { + for (RDN rdn : name.getRDNs()) { + for (AttributeTypeAndValue attTV : rdn.getTypesAndValues()) { switch (attTV.getType().toString()) { case PLATFORM_MANUFACTURER_2_0: this.manufacturer = attTV.getValue().toString(); @@ -440,6 +506,7 @@ public class PlatformCredential extends DeviceAssociatedCertificate { /** * Get the x509 Platform Certificate version. + * * @return a big integer representing the certificate version. */ @Override @@ -458,6 +525,7 @@ public class PlatformCredential extends DeviceAssociatedCertificate { /** * Get the cPSuri from the Certificate Policies. + * * @return cPSuri from the CertificatePolicies. * @throws IOException when reading the certificate. */ @@ -473,9 +541,10 @@ public class PlatformCredential extends DeviceAssociatedCertificate { /** * Get the Platform Configuration Attribute from the Platform Certificate. + * * @return a map with all the attributes * @throws IllegalArgumentException when there is a parsing error - * @throws IOException when reading the certificate. + * @throws IOException when reading the certificate. */ public Map getAllAttributes() throws IllegalArgumentException, IOException { @@ -523,10 +592,11 @@ public class PlatformCredential extends DeviceAssociatedCertificate { /** * Get the specified attribute from the Platform Certificate. + * * @param attributeName to retrieve from the map. * @return an Object with the attribute. * @throws IllegalArgumentException when there is a parsing error - * @throws IOException when reading the certificate. + * @throws IOException when reading the certificate. */ public Object getAttribute(final String attributeName) throws IllegalArgumentException, IOException { @@ -535,9 +605,10 @@ public class PlatformCredential extends DeviceAssociatedCertificate { /** * Get the Platform Configuration Attribute from the Platform Certificate. + * * @return a map with the Platform Configuration information. * @throws IllegalArgumentException when there is a parsing error - * @throws IOException when reading the certificate. + * @throws IOException when reading the certificate. */ public PlatformConfiguration getPlatformConfiguration() throws IllegalArgumentException, IOException { @@ -552,9 +623,10 @@ public class PlatformCredential extends DeviceAssociatedCertificate { /** * Get the Platform Configuration URI Attribute from the Platform Certificate. + * * @return an URIReference object to the Platform Configuration URI. * @throws IllegalArgumentException when there is a parsing error - * @throws IOException when reading the certificate. + * @throws IOException when reading the certificate. */ public URIReference getPlatformConfigurationURI() throws IllegalArgumentException, IOException { @@ -567,9 +639,10 @@ public class PlatformCredential extends DeviceAssociatedCertificate { /** * Get the TBB Security Assertion from the Platform Certificate. + * * @return a TBBSecurityAssertion object. * @throws IllegalArgumentException when there is a parsing error - * @throws IOException when reading the certificate. + * @throws IOException when reading the certificate. */ public TBBSecurityAssertion getTBBSecurityAssertion() throws IllegalArgumentException, IOException { @@ -612,6 +685,7 @@ public class PlatformCredential extends DeviceAssociatedCertificate { /** * Get the list of component identifiers if there are any. + * * @return the list of component identifiers if there are any */ public List getComponentIdentifiers() { @@ -626,76 +700,4 @@ public class PlatformCredential extends DeviceAssociatedCertificate { } return Collections.emptyList(); } - - /** - * Verify if the AlgorithmIdentifiers are equal. - * - * @param id1 AlgorithIdentifier one - * @param id2 AlgorithIdentifier two - * @return True if are the same, False if not - */ - public static boolean isAlgIdEqual(final AlgorithmIdentifier id1, - final AlgorithmIdentifier id2) { - if (!id1.getAlgorithm().equals(id2.getAlgorithm())) { - return false; - } - if (id1.getParameters() == null) { - if (id2.getParameters() != null && !id2.getParameters().equals(DERNull.INSTANCE)) { - return false; - } - return true; - } - if (id2.getParameters() == null) { - if (id1.getParameters() != null && !id1.getParameters().equals(DERNull.INSTANCE)) { - return false; - } - return true; - } - return id1.getParameters().equals(id2.getParameters()); - } - - /** - * Get the PolicyQualifier from the Certificate Policies Extension. - * - * @param certificate Attribute Certificate information - * @return Policy Qualifier from the Certificate Policies Extension - */ - public static Map getPolicyQualifier( - final AttributeCertificateInfo certificate) { - Preconditions.checkArgument(certificate.getExtensions() != null, - "Platform certificate should have extensions."); - - CertificatePolicies certPolicies - = CertificatePolicies.fromExtensions(certificate.getExtensions()); - Map policyQualifiers = new HashMap<>(); - String userNoticeQualifier = ""; - String cpsURI = ""; - - if (certPolicies != null) { - // Must contain at least one Policy - for (PolicyInformation policy : certPolicies.getPolicyInformation()) { - for (ASN1Encodable pQualifierInfo: policy.getPolicyQualifiers().toArray()) { - PolicyQualifierInfo info = PolicyQualifierInfo.getInstance(pQualifierInfo); - // Subtract the data based on the OID - switch (info.getPolicyQualifierId().getId()) { - case POLICY_QUALIFIER_CPSURI: - cpsURI = DERIA5String.getInstance(info.getQualifier()).getString(); - break; - case POLICY_QUALIFIER_USER_NOTICE: - UserNotice userNotice = UserNotice.getInstance(info.getQualifier()); - userNoticeQualifier = userNotice.getExplicitText().getString(); - break; - default: - break; - } - } - } - } - - // Add to map - policyQualifiers.put("userNotice", userNoticeQualifier); - policyQualifiers.put("cpsURI", cpsURI); - - return policyQualifiers; - } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/CommonCriteriaMeasures.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/CommonCriteriaMeasures.java index c7715226..a9c115a5 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/CommonCriteriaMeasures.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/CommonCriteriaMeasures.java @@ -25,7 +25,8 @@ import org.bouncycastle.asn1.ASN1TaggedObject; * targetUri [4] IMPLICIT URIReference OPTIONAL } * */ -@Getter @Setter +@Getter +@Setter public class CommonCriteriaMeasures { private static final int STRENGTH_OF_FUNCTION = 0; @@ -33,140 +34,6 @@ public class CommonCriteriaMeasures { private static final int PROFILE_URI = 2; private static final int TARGET_OID = 3; private static final int TARGET_URI = 4; - - /** - * A type to handle the evaluation status used in the Common Criteria Measurement. - * Ordering of enum types is intentional and their ordinal values correspond to enum - * values in the TCG spec. - * - *

-     * EvaluationStatus ::= ENUMERATED {
-     *      designedToMeet (0),
-     *      evaluationInProgress (1),
-     *      evaluationCompleted (2) }
-     * 
- */ - public enum EvaluationStatus { - /** - * Evaluation designed to meet. - */ - DESIGNEDTOMEET("designed To Meet"), - /** - * Evaluation in progress. - */ - EVALUATIONINPROGRESS("evaluation In Progress"), - /** - * Evaluation completed. - */ - EVALUATIONCOMPLETED("evaluation Completed"); - - @Getter - private final String value; - - /** - * Basic constructor. - * @param value string containing the value. - */ - EvaluationStatus(final String value) { - this.value = value; - } - } - - /** - * A type to handle the strength of function used in the Common Criteria Measurement. - * Ordering of enum types is intentional and their ordinal values correspond to enum - * values in the TCG spec. - * - *
-     * StrengthOfFunction ::= ENUMERATED {
-     *      basic (0),
-     *      medium (1),
-     *      high (2) }
-     * 
- */ - public enum StrengthOfFunction { - /** - * Basic function. - */ - BASIC("basic"), - /** - * Medium function. - */ - MEDIUM("medium"), - /** - * Hight function. - */ - HIGH("high"); - - @Getter - private final String value; - - /** - * Basic constructor. - * @param value string containing the value. - */ - StrengthOfFunction(final String value) { - this.value = value; - } - } - - /** - * A type to handle the evaluation assurance aevel used in the Common Criteria Measurement. - * Ordering of enum types is intentional and their ordinal values correspond to enum - * values in the TCG spec. - * - *
-     * EvaluationAssuranceLevel ::= ENUMERATED {
-     *      levell (1),
-     *      level2 (2),
-     *      level3 (3),
-     *      level4 (4),
-     *      level5 (5),
-     *      level6 (6),
-     *      level7 (7) }
-     * 
- */ - public enum EvaluationAssuranceLevel { - /** - * Evaluation Assurance Level 1. - */ - LEVEL1("level 1"), - /** - * Evaluation Assurance Level 2. - */ - LEVEL2("level 2"), - /** - * Evaluation Assurance Level 3. - */ - LEVEL3("level 3"), - /** - * Evaluation Assurance Level 4. - */ - LEVEL4("level 4"), - /** - * Evaluation Assurance Level 5. - */ - LEVEL5("level 5"), - /** - * Evaluation Assurance Level 6. - */ - LEVEL6("level 6"), - /** - * Evaluation Assurance Level 7. - */ - LEVEL7("level 7"); - - @Getter - private final String value; - /** - * Basic constructor. - * @param value string containing the value. - */ - EvaluationAssuranceLevel(final String value) { - this.value = value; - } - } - private ASN1IA5String version; private EvaluationAssuranceLevel assuranceLevel; private EvaluationStatus evaluationStatus; @@ -194,6 +61,7 @@ public class CommonCriteriaMeasures { /** * Constructor given the SEQUENCE that contains Common Criteria Measures. + * * @param sequence containing the the common criteria measures * @throws IllegalArgumentException if there was an error on the parsing */ @@ -258,7 +126,11 @@ public class CommonCriteriaMeasures { } } - + /** + * Creates a custom string representation of the Common Criteria Measures object. + * + * @return a string representation of Common Criteria Measures + */ @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -278,7 +150,7 @@ public class CommonCriteriaMeasures { } sb.append(", profileUri="); if (profileUri != null) { - sb.append(profileUri.toString()); + sb.append(profileUri); } sb.append(", targetOid="); if (targetOid != null) { @@ -286,10 +158,148 @@ public class CommonCriteriaMeasures { } sb.append(", targetUri="); if (targetUri != null) { - sb.append(targetUri.toString()); + sb.append(targetUri); } sb.append("}"); return sb.toString(); } + + /** + * A type to handle the evaluation status used in the Common Criteria Measurement. + * Ordering of enum types is intentional and their ordinal values correspond to enum + * values in the TCG spec. + * + *
+     * EvaluationStatus ::= ENUMERATED {
+     *      designedToMeet (0),
+     *      evaluationInProgress (1),
+     *      evaluationCompleted (2) }
+     * 
+ */ + public enum EvaluationStatus { + /** + * Evaluation designed to meet. + */ + DESIGNEDTOMEET("designed To Meet"), + /** + * Evaluation in progress. + */ + EVALUATIONINPROGRESS("evaluation In Progress"), + /** + * Evaluation completed. + */ + EVALUATIONCOMPLETED("evaluation Completed"); + + @Getter + private final String value; + + /** + * Basic constructor. + * + * @param value string containing the value. + */ + EvaluationStatus(final String value) { + this.value = value; + } + } + + /** + * A type to handle the strength of function used in the Common Criteria Measurement. + * Ordering of enum types is intentional and their ordinal values correspond to enum + * values in the TCG spec. + * + *
+     * StrengthOfFunction ::= ENUMERATED {
+     *      basic (0),
+     *      medium (1),
+     *      high (2) }
+     * 
+ */ + public enum StrengthOfFunction { + /** + * Basic function. + */ + BASIC("basic"), + /** + * Medium function. + */ + MEDIUM("medium"), + /** + * Hight function. + */ + HIGH("high"); + + @Getter + private final String value; + + /** + * Basic constructor. + * + * @param value string containing the value. + */ + StrengthOfFunction(final String value) { + this.value = value; + } + } + + + /** + * A type to handle the evaluation assurance aevel used in the Common Criteria Measurement. + * Ordering of enum types is intentional and their ordinal values correspond to enum + * values in the TCG spec. + * + *
+     * EvaluationAssuranceLevel ::= ENUMERATED {
+     *      levell (1),
+     *      level2 (2),
+     *      level3 (3),
+     *      level4 (4),
+     *      level5 (5),
+     *      level6 (6),
+     *      level7 (7) }
+     * 
+ */ + public enum EvaluationAssuranceLevel { + /** + * Evaluation Assurance Level 1. + */ + LEVEL1("level 1"), + /** + * Evaluation Assurance Level 2. + */ + LEVEL2("level 2"), + /** + * Evaluation Assurance Level 3. + */ + LEVEL3("level 3"), + /** + * Evaluation Assurance Level 4. + */ + LEVEL4("level 4"), + /** + * Evaluation Assurance Level 5. + */ + LEVEL5("level 5"), + /** + * Evaluation Assurance Level 6. + */ + LEVEL6("level 6"), + /** + * Evaluation Assurance Level 7. + */ + LEVEL7("level 7"); + + @Getter + private final String value; + + /** + * Basic constructor. + * + * @param value string containing the value. + */ + EvaluationAssuranceLevel(final String value) { + this.value = value; + } + } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentAddress.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentAddress.java index e979c4e2..2f9f82a9 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentAddress.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentAddress.java @@ -27,12 +27,17 @@ public class ComponentAddress { public static final int IDENTIFIER_NUMBER = 2; private static final String ETHERNET_MAC = "2.23.133.17.1"; + private static final String WLAN_MAC = "2.23.133.17.2"; + private static final String BLUETOOTH_MAC = "2.23.133.17.3"; private ASN1ObjectIdentifier addressType; + private ASN1UTF8String addressValue; + private String addressTypeString; + private String addressValueString; /** @@ -62,27 +67,24 @@ public class ComponentAddress { /** * Get the string value for the address type. + * * @return the string value for the address type */ public String getAddressTypeValue() { - String typeValue; - switch (this.addressType.getId()) { - case ETHERNET_MAC: - typeValue = "ethernet mac"; - break; - case WLAN_MAC: - typeValue = "wlan mac"; - break; - case BLUETOOTH_MAC: - typeValue = "bluetooth mac"; - break; - default: - typeValue = "unknown mac"; - break; - } - return typeValue; + return switch (this.addressType.getId()) { + case ETHERNET_MAC -> "ethernet mac"; + case WLAN_MAC -> "wlan mac"; + case BLUETOOTH_MAC -> "bluetooth mac"; + default -> "unknown mac"; + }; } + + /** + * Creates a string representation of the Component Address object. + * + * @return a string representation of the Component Address object. + */ @Override public String toString() { return "ComponentAddress{" diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentAttributeResult.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentAttributeResult.java index bf7c832d..476bad44 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentAttributeResult.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentAttributeResult.java @@ -6,7 +6,6 @@ import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import org.apache.commons.lang3.StringUtils; import java.util.UUID; @@ -14,29 +13,34 @@ import java.util.UUID; * This is tied to the ComponentResult class. If a component has a mismatched * value from what the device has listed, this class represents which attribute * of that component mismatched. - * + *

* If this is a delta issue, the component ID would be set to null if the * remove or modified don't exist. */ @Entity @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) -public class ComponentAttributeResult extends ArchivableEntity { +public class ComponentAttributeResult extends ArchivableEntity { private UUID componentId; + @Setter private UUID provisionSessionId; + // this is used to identify Revision for the ignore policy @Setter private String attribute; + private String expectedValue; + private String actualValue; /** * Default constructor that populates the expected and actual values. - * @param componentId id associated with component result + * + * @param componentId id associated with component result * @param expectedValue platform certificate value - * @param actualValue paccor value from the device + * @param actualValue paccor value from the device */ public ComponentAttributeResult(final UUID componentId, final String expectedValue, @@ -48,10 +52,11 @@ public class ComponentAttributeResult extends ArchivableEntity { /** * Default constructor that populates the expected and actual values. - * @param componentId id associated with component result + * + * @param componentId id associated with component result * @param provisionSessionId an id for the associated provision - * @param expectedValue platform certificate value - * @param actualValue paccor value from the device + * @param expectedValue platform certificate value + * @param actualValue paccor value from the device */ public ComponentAttributeResult(final UUID componentId, final UUID provisionSessionId, @@ -65,6 +70,8 @@ public class ComponentAttributeResult extends ArchivableEntity { /** * This method is used to check the mismatched status flag for * displaying red if there is a failure. + * + * @return true if there is status match, false otherwise */ public boolean checkMatchedStatus() { return this.actualValue.equals(this.expectedValue); @@ -72,6 +79,7 @@ public class ComponentAttributeResult extends ArchivableEntity { /** * For the state of the object, this shouldn't be negative. + * * @return the string value of the attribute name */ public String getAttribute() { diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentClass.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentClass.java index a12f73c5..ab4683d1 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentClass.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentClass.java @@ -23,39 +23,52 @@ import java.nio.file.Path; * componentClassRegistry ComponentClassRegistry, * componentClassValue OCTET STRING SIZE(4) ) } * - * + *

* A note for the future. */ -public class ComponentClass { +@Getter +public class +ComponentClass { private static final String TCG_COMPONENT_REGISTRY = "2.23.133.18.3.1"; + private static final String SMBIOS_COMPONENT_REGISTRY = "2.23.133.18.3.3"; + private static final Path WINDOWS_JSON_PATH = FileSystems.getDefault().getPath( - "C:/", "ProgramData", "hirs", "aca", "default-properties", "component-class.json"); - private static final Path JSON_PATH = WINDOWS_JSON_PATH.toFile().exists() ? WINDOWS_JSON_PATH : - FileSystems.getDefault().getPath( - "/etc", "hirs", "aca", "default-properties", "component-class.json"); + "C:/", "ProgramData", "hirs", "aca", "default-properties", "component-class.json"); + + private static final Path JSON_PATH = WINDOWS_JSON_PATH.toFile().exists() ? WINDOWS_JSON_PATH + : FileSystems.getDefault().getPath( + "/etc", "hirs", "aca", "default-properties", "component-class.json"); private static final String OTHER_STRING = "Other"; + private static final String UNKNOWN_STRING = "Unknown"; + private static final String NONE_STRING = "None"; // Used to indicate that the component string value provided is erroneous private static final String ERROR = "-1"; + private static final int MID_INDEX = 4; + /** * All TCG categories have Other and Unknown as the first 2 values. */ private static final String OTHER = "0000"; + private static final String UNKNOWN = "0001"; - @Getter - private String category, categoryStr; - @Getter - private String component, componentStr; - @Getter - private String registryType; - @Getter - private String componentIdentifier; + private final String registryType; + + private final String componentIdentifier; + + private String category; + + private String categoryStr; + + private String component; + + private String componentStr; /** * Default class constructor. @@ -68,7 +81,7 @@ public class ComponentClass { * Class Constructor that takes a String representation of the component * value. * - * @param registryOid the decimal notation for the type of registry + * @param registryOid the decimal notation for the type of registry * @param componentIdentifier component value */ public ComponentClass(final String registryOid, final String componentIdentifier) { @@ -79,7 +92,7 @@ public class ComponentClass { * Class Constructor that takes a String representation of the component * value. * - * @param componentClassPath file path for the json + * @param componentClassPath file path for the json * @param componentIdentifier component value */ public ComponentClass(final Path componentClassPath, final String componentIdentifier) { @@ -91,8 +104,8 @@ public class ComponentClass { * component value. Sets main class variables to default values and then * matches the value against defined values in the associated JSON file. * - * @param registryOid the decimal notation for the type of registry - * @param componentClassPath file path for the json + * @param registryOid the decimal notation for the type of registry + * @param componentClassPath file path for the json * @param componentIdentifier component value */ public ComponentClass(final String registryOid, @@ -106,11 +119,11 @@ public class ComponentClass { this.componentIdentifier = verifyComponentValue(componentIdentifier); } - switch (registryOid) { - case TCG_COMPONENT_REGISTRY -> registryType = "TCG"; - case SMBIOS_COMPONENT_REGISTRY -> registryType = "SMBIOS"; - default -> registryType = UNKNOWN_STRING; - } + this.registryType = switch (registryOid) { + case TCG_COMPONENT_REGISTRY -> "TCG"; + case SMBIOS_COMPONENT_REGISTRY -> "SMBIOS"; + default -> UNKNOWN_STRING; + }; switch (this.componentIdentifier) { case OTHER: @@ -135,91 +148,6 @@ public class ComponentClass { } } - /** - * This is the main way this class will be referenced and how it - * will be displayed on the portal. - * @return String combination of category and component. - */ - @Override - public String toString() { - String resultString; - if (componentStr.equals(UNKNOWN_STRING) || component.equals(OTHER_STRING)) { - resultString = String.format("%s%n%s", registryType, categoryStr); - } else { - resultString = String.format("%s%n%s - %s", registryType, categoryStr, componentStr); - } - return resultString; - } - - /** - * Getter for the Category mapped to the associated value in. - * - * @param categories a JSON object associated with mapped categories in file - * {}@link componentIdentifier}. - */ - private void findStringValues(final JsonObject categories) { - String categoryID; - String componentMask; - boolean found = false; - - if (categories != null) { - for (String name : categories.names()) { - categoryID = verifyComponentValue(categories.get(name) - .asObject().get("ID").asString()); - componentMask = componentIdentifier.substring(MID_INDEX); - // check for the correct flag - if (categoryMatch(componentIdentifier.substring(0, MID_INDEX), - categoryID.substring(0, MID_INDEX))) { - found = true; - JsonObject componentTypes = categories.get(name) - .asObject().get("Types").asObject(); - categoryStr = name; - - switch (componentMask) { - case OTHER -> componentStr = OTHER_STRING; - case UNKNOWN -> componentStr = UNKNOWN_STRING; - default -> getComponent(componentTypes); - } - } - } - } - - if (!found) { - this.categoryStr = NONE_STRING; - this.componentStr = UNKNOWN_STRING; - } - } - - /** - * Returns the value of the comparison between a category and the what's in the id. - * @param category the category to compare - * @param componentId the id value to compare - * @return true if they match - */ - public boolean categoryMatch(final String category, final String componentId) { - return category.equals(componentId); - } - - /** - * Getter for the component associated with the component JSON Object mapped - * in the JSON file. - * - * @param components JSON Object for the categories components - */ - private void getComponent(final JsonObject components) { - String typeID; - - if (components != null) { - for (Member member : components) { - typeID = verifyComponentValue(member.getName()); - - if (component.equalsIgnoreCase(typeID)) { - componentStr = member.getValue().asString(); - } - } - } - } - /** * This method converts the string representation of the component ID into * an integer. Or throws and error if the format is in error. @@ -248,4 +176,93 @@ public class ComponentClass { return componentValue; } + + /** + * This is the main way this class will be referenced and how it + * will be displayed on the portal. + * + * @return String combination of category and component. + */ + @Override + public String toString() { + String resultString; + if (componentStr.equals(UNKNOWN_STRING) || component.equals(OTHER_STRING)) { + resultString = String.format("%s%n%s", registryType, categoryStr); + } else { + resultString = String.format("%s%n%s - %s", registryType, categoryStr, componentStr); + } + return resultString; + } + + /** + * Getter for the Category mapped to the associated value in. + * + * @param categories a JSON object associated with mapped categories in file + * {}@link componentIdentifier}. + */ + private void findStringValues(final JsonObject categories) { + String categoryID; + String componentMask; + boolean found = false; + + if (categories != null) { + for (String name : categories.names()) { + categoryID = verifyComponentValue(categories.get(name) + .asObject().get("ID").asString()); + componentMask = componentIdentifier.substring(MID_INDEX); + // check for the correct flag + if (categoryMatch(componentIdentifier.substring(0, MID_INDEX), + categoryID.substring(0, MID_INDEX))) { + found = true; + JsonObject componentTypes = categories.get(name) + .asObject().get("Types").asObject(); + this.categoryStr = name; + + if (componentMask.equals(OTHER)) { + this.componentStr = OTHER_STRING; + } else if (componentMask.equals(UNKNOWN)) { + this.componentStr = UNKNOWN_STRING; + } else { + getComponent(componentTypes); + } + } + } + } + + if (!found) { + this.categoryStr = NONE_STRING; + this.componentStr = UNKNOWN_STRING; + } + } + + /** + * Returns the value of the comparison between a category and the what's in the id. + * + * @param category the category to compare + * @param componentId the id value to compare + * @return true if they match + */ + public boolean categoryMatch(final String category, final String componentId) { + return category.equals(componentId); + } + + /** + * Getter for the component associated with the component JSON Object mapped + * in the JSON file. + * + * @param components JSON Object for the categories components + */ + private void getComponent(final JsonObject components) { + String typeID; + + if (components != null) { + for (Member member : components) { + typeID = verifyComponentValue(member.getName()); + + if (component.equalsIgnoreCase(typeID)) { + componentStr = member.getValue().asString(); + } + } + } + } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentIdentifier.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentIdentifier.java index 7cf9a73b..7b56a283 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentIdentifier.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentIdentifier.java @@ -44,13 +44,11 @@ public class ComponentIdentifier { * Maximum number of configurations. */ public static final int CONFIGMAX = 32; - - private static final int MANDATORY_ELEMENTS = 2; - // optional sequence objects /** * Static variable indicated array position for the serial number. */ protected static final int COMPONENT_SERIAL = 0; + // optional sequence objects /** * Static variable indicated array position for the revision info. */ @@ -68,13 +66,22 @@ public class ComponentIdentifier { */ protected static final int COMPONENT_ADDRESS = 4; + private static final int MANDATORY_ELEMENTS = 2; + private DERUTF8String componentManufacturer; + private DERUTF8String componentModel; + private DERUTF8String componentSerial; + private DERUTF8String componentRevision; + private ASN1ObjectIdentifier componentManufacturerId; + private ASN1Boolean fieldReplaceable; + private List componentAddress; + private boolean validationResult = true; /** @@ -93,13 +100,13 @@ public class ComponentIdentifier { /** * Constructor given the components values. * - * @param componentManufacturer represents the component manufacturer - * @param componentModel represents the component model - * @param componentSerial represents the component serial number - * @param componentRevision represents the component revision + * @param componentManufacturer represents the component manufacturer + * @param componentModel represents the component model + * @param componentSerial represents the component serial number + * @param componentRevision represents the component revision * @param componentManufacturerId represents the component manufacturer ID - * @param fieldReplaceable represents if the component is replaceable - * @param componentAddress represents a list of addresses + * @param fieldReplaceable represents if the component is replaceable + * @param componentAddress represents a list of addresses */ public ComponentIdentifier(final DERUTF8String componentManufacturer, final DERUTF8String componentModel, @@ -119,6 +126,7 @@ public class ComponentIdentifier { /** * Constructor given the SEQUENCE that contains Component Identifier. + * * @param sequence containing the component identifier * @throws IllegalArgumentException if there was an error on the parsing */ @@ -194,21 +202,10 @@ public class ComponentIdentifier { } /** - * Getter for the component addresses. - * @return a collection of component addresses + * Creates a string representation of the Component Identifier object. + * + * @return a string representation of the Component Identifier object. */ - public List getComponentAddress() { - return componentAddress.stream().toList(); - } - - /** - * Setter for the list of component addresses. - * @param componentAddress collection of addresses - */ - public void setComponentAddress(List componentAddress) { - this.componentAddress = componentAddress.stream().toList(); - } - @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -230,7 +227,7 @@ public class ComponentIdentifier { } sb.append(", fieldReplaceable="); if (fieldReplaceable != null) { - sb.append(fieldReplaceable.toString()); + sb.append(fieldReplaceable); } sb.append(", componentAddress="); if (!componentAddress.isEmpty()) { diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/FIPSLevel.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/FIPSLevel.java index fa2db5aa..b04ce00d 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/FIPSLevel.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/FIPSLevel.java @@ -3,6 +3,7 @@ package hirs.attestationca.persist.entity.userdefined.certificate.attributes; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; +import lombok.ToString; import org.bouncycastle.asn1.ASN1Boolean; import org.bouncycastle.asn1.ASN1Enumerated; import org.bouncycastle.asn1.ASN1IA5String; @@ -17,64 +18,18 @@ import org.bouncycastle.asn1.ASN1Sequence; * plus BOOLEAN DEFAULT FALSE } * */ +@Getter +@Setter @AllArgsConstructor +@ToString public class FIPSLevel { private static final int MAX_SEQUENCE_SIZE = 3; - /** - * A type to handle the security Level used in the FIPS Level. - * Ordering of enum types is intentional and their ordinal values correspond to enum - * values in the TCG spec. - * - *

-     * SecurityLevel ::= ENUMERATED {
-     *      level1 (1),
-     *      level2 (2),
-     *      level3 (3),
-     *      level4 (4) }
-     * 
- */ - public enum SecurityLevel { - /** - * Security Level 1. - */ - LEVEL1("level 1"), - /** - * Security Level 2. - */ - LEVEL2("level 2"), - /** - * Security Level 3. - */ - LEVEL3("level 3"), - /** - * Security Level 4. - */ - LEVEL4("level 4"); - private final String value; - /** - * Basic constructor. - * @param value string containing the value. - */ - SecurityLevel(final String value) { - this.value = value; - } - - /** - * Get the string value from the StrengthOfFunction. - * @return the string containing the value. - */ - public String getValue() { - return this.value; - } - } - - @Getter @Setter private ASN1IA5String version; - @Getter @Setter + private SecurityLevel level; - @Getter @Setter + private ASN1Boolean plus; /** @@ -111,12 +66,39 @@ public class FIPSLevel { } } - @Override - public String toString() { - return "FIPSLevel{" - + "version=" + version.getString() - + ", level=" + level.getValue() - + ", plus=" + plus.toString() - + '}'; + /** + * A type to handle the security Level used in the FIPS Level. + * Ordering of enum types is intentional and their ordinal values correspond to enum + * values in the TCG spec. + * + *
+     * SecurityLevel ::= ENUMERATED {
+     *      level1 (1),
+     *      level2 (2),
+     *      level3 (3),
+     *      level4 (4) }
+     * 
+ */ + @Getter + @AllArgsConstructor + public enum SecurityLevel { + /** + * Security Level 1. + */ + LEVEL1("level 1"), + /** + * Security Level 2. + */ + LEVEL2("level 2"), + /** + * Security Level 3. + */ + LEVEL3("level 3"), + /** + * Security Level 4. + */ + LEVEL4("level 4"); + + private final String value; } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/PlatformConfiguration.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/PlatformConfiguration.java index 9f5e63d9..9680dc92 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/PlatformConfiguration.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/PlatformConfiguration.java @@ -15,10 +15,12 @@ import java.util.List; @AllArgsConstructor public abstract class PlatformConfiguration { private ArrayList componentIdentifier = new ArrayList<>(); - @Getter @Setter + @Getter + @Setter private URIReference componentIdentifierUri; private ArrayList platformProperties = new ArrayList<>(); - @Getter @Setter + @Getter + @Setter private URIReference platformPropertiesUri; /** @@ -34,10 +36,10 @@ public abstract class PlatformConfiguration { /** * Constructor given the Platform Configuration values. * - * @param componentIdentifier list containing all the components inside the - * Platform Configuration. - * @param platformProperties list containing all the properties inside the - * Platform Configuration. + * @param componentIdentifier list containing all the components inside the + * Platform Configuration. + * @param platformProperties list containing all the properties inside the + * Platform Configuration. * @param platformPropertiesUri object containing the URI Reference */ public PlatformConfiguration(final List componentIdentifier, @@ -55,8 +57,16 @@ public abstract class PlatformConfiguration { return Collections.unmodifiableList(componentIdentifier); } + /** + * @param componentIdentifier the componentIdentifier to set + */ + public void setComponentIdentifier(final List componentIdentifier) { + this.componentIdentifier = new ArrayList<>(componentIdentifier); + } + /** * Add function for the component identifier array. + * * @param componentIdentifier object to add * @return status of the add, if successful or not */ @@ -68,13 +78,6 @@ public abstract class PlatformConfiguration { return false; } - /** - * @param componentIdentifier the componentIdentifier to set - */ - public void setComponentIdentifier(final List componentIdentifier) { - this.componentIdentifier = new ArrayList<>(componentIdentifier); - } - /** * @return the platformProperties */ @@ -82,8 +85,16 @@ public abstract class PlatformConfiguration { return Collections.unmodifiableList(platformProperties); } + /** + * @param platformProperties the platformProperties to set + */ + public void setPlatformProperties(final List platformProperties) { + this.platformProperties = new ArrayList<>(platformProperties); + } + /** * Add function for the platform property array. + * * @param platformProperty property object to add * @return status of the add, if successful or not */ @@ -94,11 +105,4 @@ public abstract class PlatformConfiguration { return false; } - - /** - * @param platformProperties the platformProperties to set - */ - public void setPlatformProperties(final List platformProperties) { - this.platformProperties = new ArrayList<>(platformProperties); - } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/PlatformConfigurationV1.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/PlatformConfigurationV1.java index 57c6d793..c0dd0df6 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/PlatformConfigurationV1.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/PlatformConfigurationV1.java @@ -25,6 +25,7 @@ public class PlatformConfigurationV1 extends PlatformConfiguration { /** * Constructor given the SEQUENCE that contains Platform Configuration. + * * @param sequence containing the Platform Configuration. * @throws IllegalArgumentException if there was an error on the parsing */ @@ -76,6 +77,11 @@ public class PlatformConfigurationV1 extends PlatformConfiguration { } } + /** + * Creates a string representation of the Platform Configuration V1 object. + * + * @return a string representation of the Platform Configuration V1 object. + */ @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -96,7 +102,7 @@ public class PlatformConfigurationV1 extends PlatformConfiguration { } sb.append(", platformPropertiesUri="); if (getPlatformPropertiesUri() != null) { - sb.append(getPlatformPropertiesUri().toString()); + sb.append(getPlatformPropertiesUri()); } sb.append("}"); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/PlatformProperty.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/PlatformProperty.java index 6f7ac2b2..9f768c63 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/PlatformProperty.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/PlatformProperty.java @@ -3,12 +3,12 @@ package hirs.attestationca.persist.entity.userdefined.certificate.attributes; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; +import lombok.ToString; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1UTF8String; import org.bouncycastle.asn1.DERUTF8String; /** - * * Basic class that handles a single property for the platform configuration. *
  * Properties ::= SEQUENCE {
@@ -20,16 +20,17 @@ import org.bouncycastle.asn1.DERUTF8String;
 @Getter
 @Setter
 @AllArgsConstructor
+@ToString
 public class PlatformProperty {
 
-    private static final String NOT_SPECIFIED = "Not Specified";
-
     /**
      * Number of identifiers for version 1.
      */
     protected static final int IDENTIFIER_NUMBER = 2;
+    private static final String NOT_SPECIFIED = "Not Specified";
 
     private ASN1UTF8String propertyName;
+
     private ASN1UTF8String propertyValue;
 
     /**
@@ -57,12 +58,4 @@ public class PlatformProperty {
         this.propertyName = ASN1UTF8String.getInstance(sequence.getObjectAt(0));
         this.propertyValue = ASN1UTF8String.getInstance(sequence.getObjectAt(1));
     }
-
-    @Override
-    public String toString() {
-        return "PlatformProperty{"
-                + "propertyName=" + propertyName.getString()
-                + ", propertyValue=" + propertyValue.getString()
-                + "}";
-    }
 }
diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/TBBSecurityAssertion.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/TBBSecurityAssertion.java
index 2b6326da..616d1503 100644
--- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/TBBSecurityAssertion.java
+++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/TBBSecurityAssertion.java
@@ -2,6 +2,8 @@ package hirs.attestationca.persist.entity.userdefined.certificate.attributes;
 
 import lombok.AllArgsConstructor;
 import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
 import org.bouncycastle.asn1.ASN1Boolean;
 import org.bouncycastle.asn1.ASN1Enumerated;
 import org.bouncycastle.asn1.ASN1IA5String;
@@ -24,71 +26,26 @@ import java.math.BigInteger;
  *      iso9000Uri IA5STRING (SIZE (1..URIMAX)) OPTIONAL }
  * 
*/ +@Setter +@Getter @AllArgsConstructor +@ToString public class TBBSecurityAssertion { private static final int CCINFO = 0; private static final int FIPSLEVEL = 1; private static final int RTMTYPE = 2; - /** - * A type to handle the evaluation status used in the Common Criteria Measurement. - * Ordering of enum types is intentional and their ordinal values correspond to enum - * values in the TCG spec. - * - *
-     * MeasurementRootType ::= ENUMERATED {
-     *    static (0),
-     *    dynamic (1),
-     *    nonHost (2),
-     *    hybrid (3),
-     *    physical (4),
-     *    virtual (5) }
-     * 
- */ - public enum MeasurementRootType { - /** - * Static measurement root type. - */ - STATIC("static"), - /** - * Dynamic measurement root type. - */ - DYNAMIC("dynamic"), - /** - * Non-Host measurement root type. - */ - NONHOST("nonHost"), - /** - * Hybrid measurement root type. - */ - HYBRID("hybrid"), - /** - * Physical measurement root type. - */ - PHYSICAL("physical"), - /** - * Virtual measurement root type. - */ - VIRTUAL("virtual"); - - @Getter - private final String value; - - /** - * Basic constructor. - * @param value string containing the value. - */ - MeasurementRootType(final String value) { - this.value = value; - } - } - private ASN1Integer version; + private CommonCriteriaMeasures ccInfo; + private FIPSLevel fipsLevel; + private MeasurementRootType rtmType; + private ASN1Boolean iso9000Certified; + private ASN1IA5String iso9000Uri; /** @@ -105,6 +62,7 @@ public class TBBSecurityAssertion { /** * Constructor given the SEQUENCE that contains a TBBSecurityAssertion Object. + * * @param sequence containing the the TBB Security Assertion * @throws IllegalArgumentException if there was an error on the parsing */ @@ -169,114 +127,56 @@ public class TBBSecurityAssertion { } /** - * @return the version + * A type to handle the evaluation status used in the Common Criteria Measurement. + * Ordering of enum types is intentional and their ordinal values correspond to enum + * values in the TCG spec. + * + *
+     * MeasurementRootType ::= ENUMERATED {
+     *    static (0),
+     *    dynamic (1),
+     *    nonHost (2),
+     *    hybrid (3),
+     *    physical (4),
+     *    virtual (5) }
+     * 
*/ - public ASN1Integer getVersion() { - return version; - } + public enum MeasurementRootType { + /** + * Static measurement root type. + */ + STATIC("static"), + /** + * Dynamic measurement root type. + */ + DYNAMIC("dynamic"), + /** + * Non-Host measurement root type. + */ + NONHOST("nonHost"), + /** + * Hybrid measurement root type. + */ + HYBRID("hybrid"), + /** + * Physical measurement root type. + */ + PHYSICAL("physical"), + /** + * Virtual measurement root type. + */ + VIRTUAL("virtual"); - /** - * @param version the version to set - */ - public void setVersion(final ASN1Integer version) { - this.version = version; - } + @Getter + private final String value; - /** - * @return the ccInfo - */ - public CommonCriteriaMeasures getCcInfo() { - return ccInfo; - } - - /** - * @param ccInfo the ccInfo to set - */ - public void setCcInfo(final CommonCriteriaMeasures ccInfo) { - this.ccInfo = ccInfo; - } - - /** - * @return the fipsLevel - */ - public FIPSLevel getFipsLevel() { - return fipsLevel; - } - - /** - * @param fipsLevel the fipsLevel to set - */ - public void setFipsLevel(final FIPSLevel fipsLevel) { - this.fipsLevel = fipsLevel; - } - - /** - * @return the rtmType - */ - public MeasurementRootType getRtmType() { - return rtmType; - } - - /** - * @param rtmType the rtmType to set - */ - public void setRtmType(final MeasurementRootType rtmType) { - this.rtmType = rtmType; - } - - /** - * @return the iso9000Certified - */ - public ASN1Boolean getIso9000Certified() { - return iso9000Certified; - } - - /** - * @param iso9000Certified the iso9000Certified to set - */ - public void setIso9000Certified(final ASN1Boolean iso9000Certified) { - this.iso9000Certified = iso9000Certified; - } - - /** - * @return the iso9000Uri - */ - public ASN1IA5String getIso9000Uri() { - return iso9000Uri; - } - - /** - * @param iso9000Uri the iso9000Uri to set - */ - public void setIso9000Uri(final ASN1IA5String iso9000Uri) { - this.iso9000Uri = iso9000Uri; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("TBBSecurityAssertion{"); - sb.append("version=").append(version.toString()); - //Optional values not null - sb.append(", ccInfo="); - if (ccInfo != null) { - sb.append(ccInfo.toString()); + /** + * Basic constructor. + * + * @param value string containing the value. + */ + MeasurementRootType(final String value) { + this.value = value; } - sb.append(", fipsLevel="); - if (fipsLevel != null) { - sb.append(fipsLevel.toString()); - } - sb.append(", rtmType="); - if (rtmType != null) { - sb.append(rtmType.getValue()); - } - sb.append(", iso9000Certified=").append(iso9000Certified.toString()); - sb.append(", iso9000Uri="); - if (iso9000Uri != null) { - sb.append(iso9000Uri.getString()); - } - sb.append("}"); - - return sb.toString(); } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/TPMSecurityAssertions.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/TPMSecurityAssertions.java index 6fe9efdc..11553e8e 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/TPMSecurityAssertions.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/TPMSecurityAssertions.java @@ -7,6 +7,7 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import lombok.ToString; import java.io.Serializable; import java.math.BigInteger; @@ -14,19 +15,55 @@ import java.math.BigInteger; /** * A class to represent the TPM Security Assertions in an Endorsement Credential as * defined by the TCG spec for TPM 1.2. - * + *

* https://www.trustedcomputinggroup.org/wp-content/uploads/IWG-Credential_Profiles_V1_R0.pdf - * + *

* Future iterations of this code may want to reference * www.trustedcomputinggroup.org/wp-content/uploads/Credential_Profile_EK_V2.0_R14_published.pdf * for specifications for TPM 2.0 (pg. 19). */ +@Getter +@Setter @AllArgsConstructor @NoArgsConstructor(access = AccessLevel.PROTECTED) -@Getter @Setter +@ToString @Embeddable public class TPMSecurityAssertions implements Serializable { + @Column + private BigInteger tpmSecAssertsVersion; //default v1 + + @Column + private boolean fieldUpgradeable; //default false + + @Column + private EkGenerationType ekGenType; //optional + + @Column + private EkGenerationLocation ekGenerationLocation; //optionalv + + @Column + private EkGenerationLocation ekCertificateGenerationLocation; //optional + + /** + * Standard constructor that sets required fields. Use accessor methods + * to set optional fields. + * + * @param version the version of the security assertions + * @param fieldUpgradeable whether or not the security assertions are + * field upgradeable. + */ + public TPMSecurityAssertions(final BigInteger version, final boolean fieldUpgradeable) { + this.tpmSecAssertsVersion = version; + this.fieldUpgradeable = fieldUpgradeable; + } + + // Future work (may need to create other classes): + //private CommonCriteriaMeasures commCritMeasures; //optional + //private FIPSLevel fipsLevel; //optional + //private boolean iso9000Certified; //default false + //private IA5String iso9000Uri; //optional + /** * A type to handle the different endorsement key generation types used in the TPM * Assertions field of an endorsement credential. Ordering of enum types is intentional @@ -51,7 +88,7 @@ public class TPMSecurityAssertions implements Serializable { * Generated externally and then inserted under a controlled environment during * manufacturing. Can be revoked. Enum value of 3. */ - INJECTED_REVOCABLE; + INJECTED_REVOCABLE } /** @@ -73,50 +110,6 @@ public class TPMSecurityAssertions implements Serializable { /** * Generated by the endorsement key certificate signer. Enum value of 2. */ - EK_CERT_SIGNER; - } - - @Column - private BigInteger tpmSecAssertsVersion; //default v1 - - @Column - private boolean fieldUpgradeable; //default false - - @Column(nullable = true) - private EkGenerationType ekGenType; //optional - - @Column(nullable = true) - private EkGenerationLocation ekGenerationLocation; //optional - - @Column(nullable = true) - private EkGenerationLocation ekCertificateGenerationLocation; //optional - - // Future work (may need to create other classes): - //private CommonCriteriaMeasures commCritMeasures; //optional - //private FIPSLevel fipsLevel; //optional - //private boolean iso9000Certified; //default false - //private IA5String iso9000Uri; //optional - - /** - * Standard constructor that sets required fields. Use accessor methods - * to set optional fields. - * @param version the version of the security assertions - * @param fieldUpgradeable whether or not the security assertions are - * field upgradeable. - */ - public TPMSecurityAssertions(final BigInteger version, final boolean fieldUpgradeable) { - this.tpmSecAssertsVersion = version; - this.fieldUpgradeable = fieldUpgradeable; - } - - @Override - public String toString() { - return "TPMSecurityAssertions{" - + "version=" + tpmSecAssertsVersion - + ", fieldUpgradeable=" + fieldUpgradeable - + ", ekGenType=" + ekGenType - + ", ekGenLoc=" + ekGenerationLocation - + ", ekCertGenLoc=" + ekCertificateGenerationLocation - + '}'; + EK_CERT_SIGNER } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/TPMSpecification.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/TPMSpecification.java index 36b429d0..fef71ed8 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/TPMSpecification.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/TPMSpecification.java @@ -6,6 +6,7 @@ import lombok.AccessLevel; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; +import lombok.ToString; import java.io.Serializable; import java.math.BigInteger; @@ -13,16 +14,17 @@ import java.math.BigInteger; /** * A class to represent the TPM Specification in an Endorsement Credential as * defined by the TCG spec for TPM 1.2. - * + *

* https://www.trustedcomputinggroup.org/wp-content/uploads/IWG-Credential_Profiles_V1_R0.pdf - * + *

* Future iterations of this code may want to reference * www.trustedcomputinggroup.org/wp-content/uploads/Credential_Profile_EK_V2.0_R14_published.pdf * for specifications for TPM 2.0. */ -@EqualsAndHashCode -@NoArgsConstructor(access= AccessLevel.PROTECTED) @Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@ToString +@EqualsAndHashCode @Embeddable public class TPMSpecification implements Serializable { @@ -37,8 +39,9 @@ public class TPMSpecification implements Serializable { /** * Standard constructor. - * @param family the specification family. - * @param level the specification level. + * + * @param family the specification family. + * @param level the specification level. * @param revision the specification revision. */ public TPMSpecification(final String family, final BigInteger level, @@ -47,13 +50,4 @@ public class TPMSpecification implements Serializable { this.level = level; this.revision = revision; } - - @Override - public String toString() { - return "TPMSpecification{" - + "family='" + family + '\'' - + ", level=" + level - + ", revision=" + revision - + '}'; - } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/URIReference.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/URIReference.java index 622cc058..2df498ce 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/URIReference.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/URIReference.java @@ -10,27 +10,30 @@ import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; /** - * * Basic class that handle a URIReference object. *

  * URIReference ::= SEQUENCE {
  *      uniformResourceIdentifier IA5String (SIZE (1..URIMAX)),
  *      hashAlgorithm AlgorithmIdentifier OPTIONAL,
  *      hashValue BIT STRING OPTIONAL
- }
+ * }
  * 
*/ -@Getter @Setter +@Getter +@Setter @AllArgsConstructor public class URIReference { + private static final int PLATFORM_PROPERTIES_URI_MAX = 3; + + private static final int PLATFORM_PROPERTIES_URI_MIN = 1; + private ASN1IA5String uniformResourceIdentifier; + private AlgorithmIdentifier hashAlgorithm; + @JsonIgnore private ASN1BitString hashValue; - private static final int PLATFORM_PROPERTIES_URI_MAX = 3; - private static final int PLATFORM_PROPERTIES_URI_MIN = 1; - /** * Default constructor. */ @@ -71,6 +74,11 @@ public class URIReference { } } + /** + * Creates a string representation of the URI Reference object. + * + * @return a string representation of URI Reference + */ @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/CertificateIdentifier.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/CertificateIdentifier.java index 767bd045..2512d498 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/CertificateIdentifier.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/CertificateIdentifier.java @@ -51,6 +51,7 @@ public class CertificateIdentifier { /** * Primary constructor for the parsing of the sequence. + * * @param sequence containing the name and value of the Certificate Identifier */ public CertificateIdentifier(final ASN1Sequence sequence) { @@ -103,6 +104,7 @@ public class CertificateIdentifier { /** * String for the internal data stored. + * * @return String representation of the data. */ @Override @@ -114,11 +116,11 @@ public class CertificateIdentifier { sb.append(", hashSigValue").append(hashSigValue); sb.append(", issuerDN="); if (issuerDN != null) { - sb.append(issuerDN.toString()); + sb.append(issuerDN); } sb.append(", certificateSerialNumber="); if (certificateSerialNumber != null) { - sb.append(certificateSerialNumber.toString()); + sb.append(certificateSerialNumber); } sb.append("}"); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/ComponentIdentifierV2.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/ComponentIdentifierV2.java index 26090cbc..e7b4aa5b 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/ComponentIdentifierV2.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/ComponentIdentifierV2.java @@ -4,6 +4,7 @@ import hirs.attestationca.persist.entity.userdefined.certificate.attributes.Comp import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentClass; import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentIdentifier; import hirs.attestationca.persist.entity.userdefined.certificate.attributes.URIReference; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.bouncycastle.asn1.ASN1Boolean; @@ -16,7 +17,6 @@ import org.bouncycastle.asn1.ASN1UTF8String; import org.bouncycastle.asn1.DERUTF8String; import java.util.List; -import java.util.Objects; import java.util.stream.Collectors; /** @@ -40,17 +40,24 @@ import java.util.stream.Collectors; */ @Getter @Setter +@EqualsAndHashCode(callSuper = true) public class ComponentIdentifierV2 extends ComponentIdentifier { private static final int MANDATORY_ELEMENTS = 3; + // Additional optional identifiers for version 2 private static final int COMPONENT_PLATFORM_CERT = 5; + private static final int COMPONENT_PLATFORM_URI = 6; + private static final int ATTRIBUTE_STATUS = 7; private ComponentClass componentClass; + private CertificateIdentifier certificateIdentifier; + private URIReference componentPlatformUri; + private AttributeStatus attributeStatus; /** @@ -67,19 +74,18 @@ public class ComponentIdentifierV2 extends ComponentIdentifier { /** * Constructor given the components values. * - * @param componentClass represent the component type - * @param componentManufacturer represents the component manufacturer - * @param componentModel represents the component model - * @param componentSerial represents the component serial number - * @param componentRevision represents the component revision + * @param componentClass represent the component type + * @param componentManufacturer represents the component manufacturer + * @param componentModel represents the component model + * @param componentSerial represents the component serial number + * @param componentRevision represents the component revision * @param componentManufacturerId represents the component manufacturer ID - * @param fieldReplaceable represents if the component is replaceable - * @param componentAddress represents a list of addresses - * @param certificateIdentifier object representing certificate Id - * @param componentPlatformUri object containing the URI Reference - * @param attributeStatus object containing enumerated status + * @param fieldReplaceable represents if the component is replaceable + * @param componentAddress represents a list of addresses + * @param certificateIdentifier object representing certificate Id + * @param componentPlatformUri object containing the URI Reference + * @param attributeStatus object containing enumerated status */ - @SuppressWarnings("checkstyle:parameternumber") public ComponentIdentifierV2(final ComponentClass componentClass, final DERUTF8String componentManufacturer, final DERUTF8String componentModel, @@ -103,6 +109,7 @@ public class ComponentIdentifierV2 extends ComponentIdentifier { /** * Constructor given the SEQUENCE that contains Component Identifier. + * * @param sequence containing the component identifier * @throws IllegalArgumentException if there was an error on the parsing */ @@ -120,7 +127,8 @@ public class ComponentIdentifierV2 extends ComponentIdentifier { ASN1OctetString.getInstance(componentIdSeq.getObjectAt(tag)).toString()); // Mandatory values - this.setComponentManufacturer((DERUTF8String) ASN1UTF8String.getInstance(sequence.getObjectAt(tag++))); + this.setComponentManufacturer( + (DERUTF8String) ASN1UTF8String.getInstance(sequence.getObjectAt(tag++))); this.setComponentModel((DERUTF8String) ASN1UTF8String.getInstance(sequence.getObjectAt(tag++))); // Continue reading the sequence if it does contain more than 2 values @@ -200,24 +208,11 @@ public class ComponentIdentifierV2 extends ComponentIdentifier { return true; } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; - ComponentIdentifierV2 that = (ComponentIdentifierV2) o; - return Objects.equals(componentClass, that.componentClass) - && Objects.equals(certificateIdentifier, that.certificateIdentifier) - && Objects.equals(componentPlatformUri, that.componentPlatformUri) - && attributeStatus == that.attributeStatus; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), componentClass, - certificateIdentifier, componentPlatformUri, attributeStatus); - } - + /** + * Creates a string representation of the Component Identifier V2 object. + * + * @return a string representation of the Component Identifier V2 object. + */ @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -241,7 +236,7 @@ public class ComponentIdentifierV2 extends ComponentIdentifier { } sb.append(", fieldReplaceable="); if (getFieldReplaceable() != null) { - sb.append(getFieldReplaceable().toString()); + sb.append(getFieldReplaceable()); } sb.append(", componentAddress="); if (getComponentAddress().size() > 0) { @@ -252,11 +247,11 @@ public class ComponentIdentifierV2 extends ComponentIdentifier { } sb.append(", certificateIdentifier="); if (certificateIdentifier != null) { - sb.append(certificateIdentifier.toString()); + sb.append(certificateIdentifier); } sb.append(", componentPlatformUri="); if (componentPlatformUri != null) { - sb.append(componentPlatformUri.toString()); + sb.append(componentPlatformUri); } sb.append(", status="); if (attributeStatus != null) { diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/PlatformConfigurationV2.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/PlatformConfigurationV2.java index c92019f0..58dd341d 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/PlatformConfigurationV2.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/PlatformConfigurationV2.java @@ -29,6 +29,7 @@ public class PlatformConfigurationV2 extends PlatformConfiguration { /** * Constructor given the SEQUENCE that contains Platform Configuration. + * * @param sequence containing the the Platform Configuration. * @throws IllegalArgumentException if there was an error on the parsing */ @@ -86,6 +87,11 @@ public class PlatformConfigurationV2 extends PlatformConfiguration { } } + /** + * Creates a string representation of the Platform Configuration V2 object. + * + * @return a string representation of the Platform Configuration V2 object. + */ @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -99,7 +105,7 @@ public class PlatformConfigurationV2 extends PlatformConfiguration { } sb.append(", componentIdentifierUri="); if (getComponentIdentifierUri() != null) { - sb.append(getComponentIdentifierUri().toString()); + sb.append(getComponentIdentifierUri()); } sb.append(", platformProperties="); if (getPlatformProperties().size() > 0) { @@ -110,7 +116,7 @@ public class PlatformConfigurationV2 extends PlatformConfiguration { } sb.append(", platformPropertiesUri="); if (getPlatformPropertiesUri() != null) { - sb.append(getPlatformPropertiesUri().toString()); + sb.append(getPlatformPropertiesUri()); } sb.append("}"); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/PlatformPropertyV2.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/PlatformPropertyV2.java index 47a0d0cb..3a8146a4 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/PlatformPropertyV2.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/PlatformPropertyV2.java @@ -8,7 +8,6 @@ import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1UTF8String; /** - * * Basic class that handles a single property for the platform configuration. *
  * Properties ::= SEQUENCE {
@@ -18,10 +17,10 @@ import org.bouncycastle.asn1.ASN1UTF8String;
  *
  * 
*/ +@Setter +@Getter public class PlatformPropertyV2 extends PlatformProperty { - @Getter - @Setter private AttributeStatus attributeStatus; /** @@ -35,8 +34,8 @@ public class PlatformPropertyV2 extends PlatformProperty { /** * Constructor given the name and value for the platform property. * - * @param propertyName string containing the property name - * @param propertyValue string containing the property value + * @param propertyName string containing the property name + * @param propertyValue string containing the property value * @param attributeStatus enumerated object with the status of the property */ public PlatformPropertyV2(final ASN1UTF8String propertyName, final ASN1UTF8String propertyValue, @@ -84,6 +83,12 @@ public class PlatformPropertyV2 extends PlatformProperty { return getAttributeStatus() != AttributeStatus.REMOVED; } + + /** + * Creates a string representation of the PlatformPropertyV2 object. + * + * @return a string representation of the PlatformPropertyV2 object + */ @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -91,7 +96,7 @@ public class PlatformPropertyV2 extends PlatformProperty { sb.append("PropertyName=").append(getPropertyName().getString()); sb.append(", propertyValue=").append(getPropertyValue().getString()); if (attributeStatus != null) { - sb.append(", attributeStatus=").append(attributeStatus.toString()); + sb.append(", attributeStatus=").append(attributeStatus); } sb.append("}"); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/package-info.java index 59110856..12ec500e 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/package-info.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/package-info.java @@ -1 +1 @@ -package hirs.attestationca.persist.entity.userdefined.certificate.attributes.V2; \ No newline at end of file +package hirs.attestationca.persist.entity.userdefined.certificate.attributes.V2; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/package-info.java index 8a827d6d..e165d514 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/package-info.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/package-info.java @@ -1 +1 @@ -package hirs.attestationca.persist.entity.userdefined.certificate.attributes; \ No newline at end of file +package hirs.attestationca.persist.entity.userdefined.certificate.attributes; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/package-info.java index fc0e99e0..dea4ad9b 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/package-info.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/package-info.java @@ -1 +1 @@ -package hirs.attestationca.persist.entity.userdefined.certificate; \ No newline at end of file +package hirs.attestationca.persist.entity.userdefined.certificate; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/ComponentInfo.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/ComponentInfo.java index 1e9e9c7b..aa98f282 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/ComponentInfo.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/ComponentInfo.java @@ -9,6 +9,7 @@ import jakarta.persistence.DiscriminatorType; import jakarta.persistence.Entity; import jakarta.xml.bind.annotation.XmlElement; import lombok.AccessLevel; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.extern.log4j.Log4j2; @@ -24,6 +25,7 @@ import java.util.Objects; @Entity @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) +@EqualsAndHashCode(callSuper = false) @DiscriminatorColumn(name = "componentTypeEnum", discriminatorType = DiscriminatorType.STRING) public class ComponentInfo extends ArchivableEntity { @@ -34,6 +36,7 @@ public class ComponentInfo extends ArchivableEntity { @Column(nullable = false) private String deviceName; + @XmlElement @Column(nullable = false) private String componentManufacturer; @@ -56,10 +59,11 @@ public class ComponentInfo extends ArchivableEntity { /** * Base constructor for children. + * * @param componentManufacturer Component Manufacturer (must not be null) - * @param componentModel Component Model (must not be null) - * @param componentSerial Component Serial Number (can be null) - * @param componentRevision Component Revision or Version (can be null) + * @param componentModel Component Model (must not be null) + * @param componentSerial Component Serial Number (can be null) + * @param componentRevision Component Revision or Version (can be null) */ public ComponentInfo(final String componentManufacturer, final String componentModel, @@ -68,13 +72,15 @@ public class ComponentInfo extends ArchivableEntity { this(DeviceInfoEnums.NOT_SPECIFIED, componentManufacturer, componentModel, componentSerial, componentRevision); } + /** * Constructor. - * @param deviceName the host machine associated with this component. (must not be null) + * + * @param deviceName the host machine associated with this component. (must not be null) * @param componentManufacturer Component Manufacturer (must not be null) - * @param componentModel Component Model (must not be null) - * @param componentSerial Component Serial Number (can be null) - * @param componentRevision Component Revision or Version (can be null) + * @param componentModel Component Model (must not be null) + * @param componentSerial Component Serial Number (can be null) + * @param componentRevision Component Revision or Version (can be null) */ public ComponentInfo(final String deviceName, final String componentManufacturer, @@ -108,12 +114,13 @@ public class ComponentInfo extends ArchivableEntity { /** * Constructor. - * @param deviceName the host machine associated with this component. + * + * @param deviceName the host machine associated with this component. * @param componentManufacturer Component Manufacturer (must not be null) - * @param componentModel Component Model (must not be null) - * @param componentSerial Component Serial Number (can be null) - * @param componentRevision Component Revision or Version (can be null) - * @param componentClass Component Class (can be null) + * @param componentModel Component Model (must not be null) + * @param componentSerial Component Serial Number (can be null) + * @param componentRevision Component Revision or Version (can be null) + * @param componentClass Component Class (can be null) */ public ComponentInfo(final String deviceName, final String componentManufacturer, @@ -134,9 +141,9 @@ public class ComponentInfo extends ArchivableEntity { * manufacturer and model are considered valid. * * @param componentManufacturer a String containing a component's manufacturer - * @param componentModel a String representing a component's model - * @param componentSerial a String representing a component's serial number - * @param componentRevision a String representing a component's revision + * @param componentModel a String representing a component's model + * @param componentSerial a String representing a component's serial number + * @param componentRevision a String representing a component's revision * @return true if the component is valid, false if not */ public static boolean isComplete(final String componentManufacturer, @@ -147,43 +154,13 @@ public class ComponentInfo extends ArchivableEntity { || StringUtils.isEmpty(componentModel)); } - /** - * Equals for the component info that just uses this classes attributes. - * @param object the object to compare - * @return the boolean result - */ - @Override - public boolean equals(Object object) { - if (this == object) return true; - if (object == null || getClass() != object.getClass()) return false; - - ComponentInfo that = (ComponentInfo) object; - return Objects.equals(deviceName, that.deviceName) - && Objects.equals(componentManufacturer, - that.componentManufacturer) - && Objects.equals(componentModel, that.componentModel) - && Objects.equals(componentSerial, that.componentSerial) - && Objects.equals(componentRevision, that.componentRevision) - && Objects.equals(componentClass, that.componentClass); - } - /** * Returns a hash code that is associated with common fields for components. + * * @return int value of the elements */ public int hashCommonElements() { return Objects.hash(componentManufacturer, componentModel, componentSerial, componentRevision, componentClass); } - - /** - * Hash method for the attributes of this class. - * @return int value that represents this class - */ - @Override - public int hashCode() { - return Objects.hash(deviceName, componentManufacturer, - componentModel, componentSerial, componentRevision, - componentClass); - } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/FirmwareInfo.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/FirmwareInfo.java index 333379cb..8921c108 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/FirmwareInfo.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/FirmwareInfo.java @@ -33,8 +33,8 @@ public class FirmwareInfo implements Serializable { /** * Constructor used to create a populated firmware info object. * - * @param biosVendor String bios vendor name, i.e. Dell Inc. - * @param biosVersion String bios version info, i.e. A11 + * @param biosVendor String bios vendor name, i.e. Dell Inc. + * @param biosVersion String bios version info, i.e. A11 * @param biosReleaseDate String bios release date info, i.e. 03/12/2013 */ public FirmwareInfo(final String biosVendor, final String biosVersion, diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/HardwareInfo.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/HardwareInfo.java index 24d9539e..35a9bd7f 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/HardwareInfo.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/HardwareInfo.java @@ -48,11 +48,11 @@ public class HardwareInfo implements Serializable { /** * Constructor used to create a populated firmware info object. * - * @param manufacturer String manufacturer name - * @param productName String product name info - * @param version String bios release date info - * @param systemSerialNumber String device serial number - * @param chassisSerialNumber String device chassis serial number + * @param manufacturer String manufacturer name + * @param productName String product name info + * @param version String bios release date info + * @param systemSerialNumber String device serial number + * @param chassisSerialNumber String device chassis serial number * @param baseboardSerialNumber String device baseboard serial number */ public HardwareInfo( @@ -80,19 +80,19 @@ public class HardwareInfo implements Serializable { if (!StringUtils.isBlank(systemSerialNumber)) { this.systemSerialNumber = StringValidator.check(systemSerialNumber, - "systemSerialNumber") + "systemSerialNumber") .maxLength(DeviceInfoEnums.LONG_STRING_LENGTH).getValue(); } if (!StringUtils.isBlank(chassisSerialNumber)) { this.chassisSerialNumber = StringValidator.check(chassisSerialNumber, - "chassisSerialNumber") + "chassisSerialNumber") .maxLength(DeviceInfoEnums.LONG_STRING_LENGTH).getValue(); } if (!StringUtils.isBlank(baseboardSerialNumber)) { this.baseboardSerialNumber = StringValidator.check( - baseboardSerialNumber, "baseboardSerialNumber") + baseboardSerialNumber, "baseboardSerialNumber") .maxLength(DeviceInfoEnums.LONG_STRING_LENGTH).getValue(); } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/NetworkInfo.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/NetworkInfo.java index 2df866a7..73ec8d80 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/NetworkInfo.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/NetworkInfo.java @@ -10,47 +10,42 @@ import lombok.extern.log4j.Log4j2; import java.io.Serializable; import java.net.InetAddress; -import java.util.Arrays; -import java.util.Objects; /** * This class is used to represent the network info of a device. */ @Log4j2 @Embeddable +@EqualsAndHashCode public class NetworkInfo implements Serializable { private static final int NUM_MAC_ADDRESS_BYTES = 6; @XmlElement @Getter - @Column(length = DeviceInfoEnums.LONG_STRING_LENGTH, nullable = true) + @Column(length = DeviceInfoEnums.LONG_STRING_LENGTH) private String hostname; @XmlElement @Getter // @XmlJavaTypeAdapter(value = InetAddressXmlAdapter.class) - @Column(length = DeviceInfoEnums.SHORT_STRING_LENGTH, nullable = true) + @Column(length = DeviceInfoEnums.SHORT_STRING_LENGTH) // @JsonSubTypes.Type(type = "hirs.data.persist.type.InetAddressType") private InetAddress ipAddress; @XmlElement - @Column(length = NUM_MAC_ADDRESS_BYTES, nullable = true) - @SuppressWarnings("checkstyle:magicnumber") + @Column(length = NUM_MAC_ADDRESS_BYTES) private byte[] macAddress; /** * Constructor used to create a NetworkInfo object. * - * @param hostname - * String representing the hostname information for the device, - * can be null if hostname unknown - * @param ipAddress - * InetAddress object representing the IP address for the device, - * can be null if IP address unknown - * @param macAddress - * byte array representing the MAC address for the device, can be - * null if MAC address is unknown + * @param hostname String representing the hostname information for the device, + * can be null if hostname unknown + * @param ipAddress InetAddress object representing the IP address for the device, + * can be null if IP address unknown + * @param macAddress byte array representing the MAC address for the device, can be + * null if MAC address is unknown */ public NetworkInfo(final String hostname, final InetAddress ipAddress, final byte[] macAddress) { @@ -72,7 +67,7 @@ public class NetworkInfo implements Serializable { * Used to retrieve the MAC address of the device. * * @return a String representing the MAC address, may return null if no - * value is set + * value is set */ public final byte[] getMacAddress() { if (macAddress == null) { @@ -82,16 +77,6 @@ public class NetworkInfo implements Serializable { } } - private void setHostname(final String hostname) { - log.debug("setting hostname to: {}", hostname); - this.hostname = hostname; - } - - private void setIpAddress(final InetAddress ipAddress) { - log.debug("setting IP address to: {}", ipAddress); - this.ipAddress = ipAddress; - } - private void setMacAddress(final byte[] macAddress) { StringBuilder sb; if (macAddress == null) { @@ -114,22 +99,13 @@ public class NetworkInfo implements Serializable { this.macAddress = macAddress; } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof NetworkInfo)) { - return false; - } - NetworkInfo that = (NetworkInfo) o; - return Objects.equals(hostname, that.hostname) - && Objects.equals(ipAddress, that.ipAddress) - && Arrays.equals(macAddress, that.macAddress); + private void setHostname(final String hostname) { + log.debug("setting hostname to: {}", hostname); + this.hostname = hostname; } - @Override - public int hashCode() { - int result = Objects.hash(hostname, ipAddress); - result = 31 * result + Arrays.hashCode(macAddress); - return result; + private void setIpAddress(final InetAddress ipAddress) { + log.debug("setting IP address to: {}", ipAddress); + this.ipAddress = ipAddress; } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/OSInfo.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/OSInfo.java index add66ae3..285682df 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/OSInfo.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/OSInfo.java @@ -47,16 +47,11 @@ public class OSInfo implements Serializable { * Fedora), and distribution release (7.0.1406). Distribution only makes * sense for Linux, so distribution and distributionRelease may be null. * - * @param osName - * String OS name (Linux | Mac OS X | Windows 7) - * @param osVersion - * String OS version (i.e. 3.10.0-123.el7.x86_64) - * @param osArch - * String OS architecture (x86_64) - * @param distribution - * String distribution (CentOS | Fedora) - * @param distributionRelease - * String distribution release (7.0.1406) + * @param osName String OS name (Linux | Mac OS X | Windows 7) + * @param osVersion String OS version (i.e. 3.10.0-123.el7.x86_64) + * @param osArch String OS architecture (x86_64) + * @param distribution String distribution (CentOS | Fedora) + * @param distributionRelease String distribution release (7.0.1406) */ public OSInfo(final String osName, final String osVersion, final String osArch, final String distribution, diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/RIMInfo.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/RIMInfo.java index 70bb63a1..48c301cd 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/RIMInfo.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/RIMInfo.java @@ -38,10 +38,11 @@ public class RIMInfo implements Serializable { /** * Constructor for the initial values of the class. + * * @param rimManufacturer string of the rimManufacturer - * @param model string of the model - * @param fileHash string of the file hash - * @param pcrHash string of the pcr hash + * @param model string of the model + * @param fileHash string of the file hash + * @param pcrHash string of the pcr hash */ public RIMInfo(final String rimManufacturer, final String model, final String fileHash, final String pcrHash) { diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/TPMInfo.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/TPMInfo.java index 9dbf4757..099eecff 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/TPMInfo.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/TPMInfo.java @@ -68,27 +68,17 @@ public class TPMInfo implements Serializable { /** * Constructor used to create a TPMInfo object. * - * @param tpmMake - * String representing the make information for the TPM, - * NullPointerException thrown if null - * @param tpmVersionMajor - * short representing the major version number for the TPM - * @param tpmVersionMinor - * short representing the minor version number for the TPM - * @param tpmVersionRevMajor - * short representing the major revision number for the TPM - * @param tpmVersionRevMinor - * short representing the minor revision number for the TPM - * @param identityCertificate - * byte array with the value of the identity certificate - * @param pcrValues - * short representing the major revision number for the TPM - * @param tpmQuoteHash - * short representing the minor revision number for the TPM - * @param tpmQuoteSignature - * byte array with the value of the identity certificate + * @param tpmMake String representing the make information for the TPM, + * NullPointerException thrown if null + * @param tpmVersionMajor short representing the major version number for the TPM + * @param tpmVersionMinor short representing the minor version number for the TPM + * @param tpmVersionRevMajor short representing the major revision number for the TPM + * @param tpmVersionRevMinor short representing the minor revision number for the TPM + * @param identityCertificate byte array with the value of the identity certificate + * @param pcrValues short representing the major revision number for the TPM + * @param tpmQuoteHash short representing the minor revision number for the TPM + * @param tpmQuoteSignature byte array with the value of the identity certificate */ - @SuppressWarnings("parameternumber") public TPMInfo(final String tpmMake, final short tpmVersionMajor, final short tpmVersionMinor, final short tpmVersionRevMajor, final short tpmVersionRevMinor, @@ -109,25 +99,16 @@ public class TPMInfo implements Serializable { * Constructor used to create a TPMInfo object without an identity * certificate. * - * @param tpmMake - * String representing the make information for the TPM, - * NullPointerException thrown if null - * @param tpmVersionMajor - * short representing the major version number for the TPM - * @param tpmVersionMinor - * short representing the minor version number for the TPM - * @param tpmVersionRevMajor - * short representing the major revision number for the TPM - * @param tpmVersionRevMinor - * short representing the minor revision number for the TPM - * @param pcrValues - * short representing the major revision number for the TPM - * @param tpmQuoteHash - * short representing the minor revision number for the TPM - * @param tpmQuoteSignature - * byte array with the value of the identity certificate + * @param tpmMake String representing the make information for the TPM, + * NullPointerException thrown if null + * @param tpmVersionMajor short representing the major version number for the TPM + * @param tpmVersionMinor short representing the minor version number for the TPM + * @param tpmVersionRevMajor short representing the major revision number for the TPM + * @param tpmVersionRevMinor short representing the minor revision number for the TPM + * @param pcrValues short representing the major revision number for the TPM + * @param tpmQuoteHash short representing the minor revision number for the TPM + * @param tpmQuoteSignature byte array with the value of the identity certificate */ - @SuppressWarnings("parameternumber") public TPMInfo(final String tpmMake, final short tpmVersionMajor, final short tpmVersionMinor, final short tpmVersionRevMajor, final short tpmVersionRevMinor, final byte[] pcrValues, @@ -146,17 +127,12 @@ public class TPMInfo implements Serializable { * Constructor used to create a TPMInfo object without an identity * certificate. * - * @param tpmMake - * String representing the make information for the TPM, - * NullPointerException thrown if null - * @param tpmVersionMajor - * short representing the major version number for the TPM - * @param tpmVersionMinor - * short representing the minor version number for the TPM - * @param tpmVersionRevMajor - * short representing the major revision number for the TPM - * @param tpmVersionRevMinor - * short representing the minor revision number for the TPM + * @param tpmMake String representing the make information for the TPM, + * NullPointerException thrown if null + * @param tpmVersionMajor short representing the major version number for the TPM + * @param tpmVersionMinor short representing the minor version number for the TPM + * @param tpmVersionRevMajor short representing the major revision number for the TPM + * @param tpmVersionRevMinor short representing the minor revision number for the TPM */ public TPMInfo(final String tpmMake, final short tpmVersionMajor, final short tpmVersionMinor, final short tpmVersionRevMajor, @@ -170,19 +146,13 @@ public class TPMInfo implements Serializable { * Constructor used to create a TPMInfo object without an identity * certificate. * - * @param tpmMake - * String representing the make information for the TPM, - * NullPointerException thrown if null - * @param tpmVersionMajor - * short representing the major version number for the TPM - * @param tpmVersionMinor - * short representing the minor version number for the TPM - * @param tpmVersionRevMajor - * short representing the major revision number for the TPM - * @param tpmVersionRevMinor - * short representing the minor revision number for the TPM - * @param identityCertificate - * byte array with the value of the identity certificate + * @param tpmMake String representing the make information for the TPM, + * NullPointerException thrown if null + * @param tpmVersionMajor short representing the major version number for the TPM + * @param tpmVersionMinor short representing the minor version number for the TPM + * @param tpmVersionRevMajor short representing the major revision number for the TPM + * @param tpmVersionRevMinor short representing the minor revision number for the TPM + * @param identityCertificate byte array with the value of the identity certificate */ public TPMInfo(final String tpmMake, final short tpmVersionMajor, final short tpmVersionMinor, final short tpmVersionRevMajor, @@ -217,30 +187,67 @@ public class TPMInfo implements Serializable { return identityCertificate; } + private void setIdentityCertificate( + final X509Certificate identityCertificate) { + if (identityCertificate == null) { + log.error("identity certificate cannot be null"); + throw new NullPointerException("identityCertificate"); + } + log.debug("setting identity certificate"); + this.identityCertificate = identityCertificate; + } + /** * Getter for the tpmQuote passed up by the client. + * * @return a byte blob of quote */ public final byte[] getTpmQuoteHash() { return tpmQuoteHash.clone(); } + private void setTpmQuoteHash(final byte[] tpmQuoteHash) { + if (tpmQuoteHash == null) { + this.tpmQuoteHash = new byte[0]; + } else { + this.tpmQuoteHash = tpmQuoteHash.clone(); + } + } + /** * Getter for the quote signature. + * * @return a byte blob. */ public final byte[] getTpmQuoteSignature() { return tpmQuoteSignature.clone(); } + private void setTpmQuoteSignature(final byte[] tpmQuoteSignature) { + if (tpmQuoteSignature == null) { + this.tpmQuoteSignature = new byte[0]; + } else { + this.tpmQuoteSignature = tpmQuoteSignature.clone(); + } + } + /** * Getter for the pcr values. + * * @return a byte blob for the pcrValues. */ public final byte[] getPcrValues() { return pcrValues.clone(); } + private void setPcrValues(final byte[] pcrValues) { + if (pcrValues == null) { + this.pcrValues = new byte[0]; + } else { + this.pcrValues = pcrValues.clone(); + } + } + private void setTPMMake(final String tpmMake) { log.debug("setting TPM make info: {}", tpmMake); this.tpmMake = StringValidator.check(tpmMake, "tpmMake") @@ -292,38 +299,4 @@ public class TPMInfo implements Serializable { tpmVersionRevMinor); this.tpmVersionRevMinor = tpmVersionRevMinor; } - - private void setIdentityCertificate( - final X509Certificate identityCertificate) { - if (identityCertificate == null) { - log.error("identity certificate cannot be null"); - throw new NullPointerException("identityCertificate"); - } - log.debug("setting identity certificate"); - this.identityCertificate = identityCertificate; - } - - private void setPcrValues(final byte[] pcrValues) { - if (pcrValues == null) { - this.pcrValues = new byte[0]; - } else { - this.pcrValues = pcrValues.clone(); - } - } - - private void setTpmQuoteHash(final byte[] tpmQuoteHash) { - if (tpmQuoteHash == null) { - this.tpmQuoteHash = new byte[0]; - } else { - this.tpmQuoteHash = tpmQuoteHash.clone(); - } - } - - private void setTpmQuoteSignature(final byte[] tpmQuoteSignature) { - if (tpmQuoteSignature == null) { - this.tpmQuoteSignature = new byte[0]; - } else { - this.tpmQuoteSignature = tpmQuoteSignature.clone(); - } - } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/component/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/component/package-info.java new file mode 100644 index 00000000..a7f24171 --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/component/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.entity.userdefined.info.component; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/package-info.java new file mode 100644 index 00000000..3e4d9b76 --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/info/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.entity.userdefined.info; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/package-info.java index fd20b8af..0962e038 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/package-info.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/package-info.java @@ -1 +1 @@ -package hirs.attestationca.persist.entity.userdefined; \ No newline at end of file +package hirs.attestationca.persist.entity.userdefined; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/record/TPMMeasurementRecord.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/record/TPMMeasurementRecord.java index 7507b8c6..fd732039 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/record/TPMMeasurementRecord.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/record/TPMMeasurementRecord.java @@ -26,7 +26,7 @@ import org.apache.commons.codec.binary.Hex; @Log4j2 @Getter @ToString -@EqualsAndHashCode +@EqualsAndHashCode(callSuper = false) @Embeddable @XmlAccessorType(XmlAccessType.FIELD) public final class TPMMeasurementRecord extends ExaminableRecord { @@ -51,7 +51,6 @@ public final class TPMMeasurementRecord extends ExaminableRecord { */ public static final int SHA_256_BYTE_LENGTH = 64; - @Column(name = "pcr", nullable = false) @XmlAttribute(name = "PcrNumber", required = true) private final int pcrId; @@ -63,9 +62,8 @@ public final class TPMMeasurementRecord extends ExaminableRecord { * Constructor initializes values associated with TPMMeasurementRecord. * * @param pcrId is the TPM PCR index. pcrId must be between 0 and 23. - * @param hash - * represents the measurement digest found at the particular PCR - * index. + * @param hash represents the measurement digest found at the particular PCR + * index. * @throws IllegalArgumentException if pcrId is not valid */ public TPMMeasurementRecord(final int pcrId, final Digest hash) @@ -85,8 +83,8 @@ public final class TPMMeasurementRecord extends ExaminableRecord { * Constructor initializes values associated with TPMMeasurementRecord. * * @param pcrId is the TPM PCR index. pcrId must be between 0 and 23. - * @param hash represents the measurement digest found at the particular PCR - * index. + * @param hash represents the measurement digest found at the particular PCR + * index. * @throws DecoderException if there is a decode issue with string hex. */ public TPMMeasurementRecord(final int pcrId, final String hash) @@ -98,18 +96,26 @@ public final class TPMMeasurementRecord extends ExaminableRecord { * Constructor initializes values associated with TPMMeasurementRecord. * * @param pcrId is the TPM PCR index. pcrId must be between 0 and 23. - * @param hash represents the measurement digest found at the particular PCR - * index. + * @param hash represents the measurement digest found at the particular PCR + * index. */ public TPMMeasurementRecord(final int pcrId, final byte[] hash) { this(pcrId, new Digest(hash)); } + /** + * Default constructor necessary for Hibernate. + */ + private TPMMeasurementRecord() { + super(); + this.pcrId = -1; + this.hash = null; + } + /** * Helper method to determine if a PCR ID number is valid. * - * @param pcrId - * int to check + * @param pcrId int to check */ public static void checkForValidPcrId(final int pcrId) { if (pcrId < MIN_PCR_ID || pcrId > MAX_PCR_ID) { @@ -118,13 +124,4 @@ public final class TPMMeasurementRecord extends ExaminableRecord { throw new IllegalArgumentException(msg); } } - - /** - * Default constructor necessary for Hibernate. - */ - protected TPMMeasurementRecord() { - super(); - this.pcrId = -1; - this.hash = null; - } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/record/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/record/package-info.java new file mode 100644 index 00000000..a297fc9c --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/record/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.entity.userdefined.record; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/report/DeviceInfoReport.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/report/DeviceInfoReport.java index 04102611..d6d66edb 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/report/DeviceInfoReport.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/report/DeviceInfoReport.java @@ -1,5 +1,6 @@ package hirs.attestationca.persist.entity.userdefined.report; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hirs.attestationca.persist.entity.AbstractEntity; import hirs.attestationca.persist.entity.userdefined.info.FirmwareInfo; import hirs.attestationca.persist.entity.userdefined.info.HardwareInfo; @@ -13,6 +14,8 @@ import jakarta.persistence.Embedded; import jakarta.persistence.Entity; import jakarta.persistence.Transient; import jakarta.xml.bind.annotation.XmlElement; +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -20,16 +23,19 @@ import lombok.extern.log4j.Log4j2; import java.io.Serializable; import java.net.InetAddress; -import java.util.Objects; /** * A DeviceInfoReport is a Report used to transfer the * information about the device. This Report includes the network, * OS, and TPM information. */ -@Log4j2 +@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", + justification = "various class properties here are guaranteed to always be non-null/initialized." + + " Warning stems from auto-generated lombok equals and hashcode method doing redundant " + + "null checks.") @NoArgsConstructor -@Getter +@EqualsAndHashCode(callSuper = false) +@Log4j2 @Entity public class DeviceInfoReport extends AbstractEntity implements Serializable { @@ -49,14 +55,18 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable { @Embedded private HardwareInfo hardwareInfo; + @Setter(AccessLevel.PRIVATE) + @Getter @XmlElement @Embedded private TPMInfo tpmInfo; + @Getter @XmlElement @Column(nullable = false) private String clientApplicationVersion; + @Getter @Setter @XmlElement @Transient @@ -67,17 +77,12 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable { * information cannot be changed after the DeviceInfoReport is * created. * - * @param networkInfo - * NetworkInfo object, cannot be null - * @param osInfo - * OSInfo object, cannot be null - * @param firmwareInfo - * FirmwareInfo object, cannot be null - * @param hardwareInfo - * HardwareInfo object, cannot be null - * @param tpmInfo - * TPMInfo object, may be null if a TPM is not available on the - * device + * @param networkInfo NetworkInfo object, cannot be null + * @param osInfo OSInfo object, cannot be null + * @param firmwareInfo FirmwareInfo object, cannot be null + * @param hardwareInfo HardwareInfo object, cannot be null + * @param tpmInfo TPMInfo object, may be null if a TPM is not available on the + * device */ public DeviceInfoReport(final NetworkInfo networkInfo, final OSInfo osInfo, final FirmwareInfo firmwareInfo, final HardwareInfo hardwareInfo, @@ -90,20 +95,14 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable { * information cannot be changed after the DeviceInfoReport is * created. * - * @param networkInfo - * NetworkInfo object, cannot be null - * @param osInfo - * OSInfo object, cannot be null - * @param firmwareInfo - * FirmwareInfo object, cannot be null - * @param hardwareInfo - * HardwareInfo object, cannot be null - * @param tpmInfo - * TPMInfo object, may be null if a TPM is not available on the - * device - * @param clientApplicationVersion - * string representing the version of the client that submitted this report, - * cannot be null + * @param networkInfo NetworkInfo object, cannot be null + * @param osInfo OSInfo object, cannot be null + * @param firmwareInfo FirmwareInfo object, cannot be null + * @param hardwareInfo HardwareInfo object, cannot be null + * @param tpmInfo TPMInfo object, may be null if a TPM is not available on the + * device + * @param clientApplicationVersion string representing the version of the client that submitted this + * report, cannot be null */ public DeviceInfoReport(final NetworkInfo networkInfo, final OSInfo osInfo, final FirmwareInfo firmwareInfo, final HardwareInfo hardwareInfo, @@ -112,7 +111,7 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable { setOSInfo(osInfo); setFirmwareInfo(firmwareInfo); setHardwareInfo(hardwareInfo); - setTPMInfo(tpmInfo); + setTpmInfo(tpmInfo); this.clientApplicationVersion = clientApplicationVersion; } @@ -135,6 +134,14 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable { networkInfo.getIpAddress(), networkInfo.getMacAddress()); } + private void setNetworkInfo(final NetworkInfo networkInfo) { + if (networkInfo == null) { + log.error("NetworkInfo cannot be null"); + throw new NullPointerException("network info"); + } + this.networkInfo = networkInfo; + } + /** * Retrieves the OSInfo for this DeviceInfoReport. * @@ -154,6 +161,14 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable { return osInfo; } + private void setOSInfo(final OSInfo osInfo) { + if (osInfo == null) { + log.error("OSInfo cannot be null"); + throw new NullPointerException("os info"); + } + this.osInfo = osInfo; + } + /** * Retrieves the FirmwareInfo for this DeviceInfoReport. * @@ -172,6 +187,14 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable { return firmwareInfo; } + private void setFirmwareInfo(final FirmwareInfo firmwareInfo) { + if (firmwareInfo == null) { + log.error("FirmwareInfo cannot be null"); + throw new NullPointerException("firmware info"); + } + this.firmwareInfo = firmwareInfo; + } + /** * Retrieves the OSInfo for this DeviceInfoReport. * @@ -196,30 +219,6 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable { return hardwareInfo; } - private void setNetworkInfo(final NetworkInfo networkInfo) { - if (networkInfo == null) { - log.error("NetworkInfo cannot be null"); - throw new NullPointerException("network info"); - } - this.networkInfo = networkInfo; - } - - private void setOSInfo(final OSInfo osInfo) { - if (osInfo == null) { - log.error("OSInfo cannot be null"); - throw new NullPointerException("os info"); - } - this.osInfo = osInfo; - } - - private void setFirmwareInfo(final FirmwareInfo firmwareInfo) { - if (firmwareInfo == null) { - log.error("FirmwareInfo cannot be null"); - throw new NullPointerException("firmware info"); - } - this.firmwareInfo = firmwareInfo; - } - private void setHardwareInfo(final HardwareInfo hardwareInfo) { if (hardwareInfo == null) { log.error("HardwareInfo cannot be null"); @@ -227,31 +226,6 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable { } this.hardwareInfo = hardwareInfo; } - - private void setTPMInfo(final TPMInfo tpmInfo) { - this.tpmInfo = tpmInfo; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof DeviceInfoReport)) { - return false; - } - DeviceInfoReport that = (DeviceInfoReport) o; - return Objects.equals(networkInfo, that.networkInfo) - && Objects.equals(osInfo, that.osInfo) - && Objects.equals(firmwareInfo, that.firmwareInfo) - && Objects.equals(hardwareInfo, that.hardwareInfo) - && Objects.equals(tpmInfo, that.tpmInfo) - && Objects.equals(clientApplicationVersion, that.clientApplicationVersion) - && Objects.equals(paccorOutputString, that.paccorOutputString); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), networkInfo, osInfo, - firmwareInfo, hardwareInfo, tpmInfo, - clientApplicationVersion, paccorOutputString); - } } + + diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/report/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/report/package-info.java new file mode 100644 index 00000000..fca94e7e --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/report/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.entity.userdefined.report; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/result/CertificateValidationResult.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/result/CertificateValidationResult.java index 39d75739..a48573f3 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/result/CertificateValidationResult.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/result/CertificateValidationResult.java @@ -6,11 +6,27 @@ import lombok.Setter; /** * An CertificateValidationResult represents the result of a certificate validation * operation. - * */ @Getter @Setter public class CertificateValidationResult { + private CertificateValidationStatus validationStatus; + private String validationResultMessage; + + /** + * Sets the certificate validation status and result message. + * + * @param status enum representing the certificate validation status + * @param resultMessage String representing certificate validation message + */ + public final void setCertValidationStatusAndResultMessage( + final CertificateValidationStatus status, + final String resultMessage) { + this.validationStatus = status; + this.validationResultMessage = resultMessage; + } + + /** * Enum used to represent certificate validation status. */ @@ -31,21 +47,4 @@ public class CertificateValidationResult { */ ERROR } - - private CertificateValidationStatus validationStatus; - private String validationResultMessage; - - - /** - * Sets the certificate validation status and result message. - * - * @param status enum representing the certificate validation status - * @param resultMessage String representing certificate validation message - */ - public final void setCertValidationStatusAndResultMessage( - final CertificateValidationStatus status, - final String resultMessage) { - this.validationStatus = status; - this.validationResultMessage = resultMessage; - } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/result/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/result/package-info.java new file mode 100644 index 00000000..3ad7260f --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/result/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.entity.userdefined.result; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/BaseReferenceManifest.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/BaseReferenceManifest.java index b06af3df..dc340dfc 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/BaseReferenceManifest.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/BaseReferenceManifest.java @@ -10,6 +10,7 @@ import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.UnmarshalException; import jakarta.xml.bind.Unmarshaller; import lombok.AccessLevel; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -33,7 +34,6 @@ import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; -import java.util.Objects; /** * @@ -42,6 +42,7 @@ import java.util.Objects; @Getter @Setter @NoArgsConstructor(access = AccessLevel.PROTECTED) +@EqualsAndHashCode(callSuper = true) @Entity public class BaseReferenceManifest extends ReferenceManifest { /** @@ -53,43 +54,60 @@ public class BaseReferenceManifest extends ReferenceManifest { @Column private String swidName = null; + @Column private int swidCorpus = 0; + @Column private String colloquialVersion = null; + @Column private String product = null; + @Column private String revision = null; + @Column private String edition = null; + @Column private String rimLinkHash = null; + @Column private String bindingSpec = null; + @Column private String bindingSpecVersion = null; + @Column private String platformVersion = null; + @Column private String payloadType = null; + @Column private String pcURIGlobal = null; + @Column private String pcURILocal = null; private String entityName = null; + private String entityRegId = null; + private String entityRole = null; + private String entityThumbprint = null; + private String linkHref = null; + private String linkRel = null; /** * Support constructor for the RIM object. * * @param rimBytes - the file content of the uploaded file. - * @throws IOException - thrown if the file is invalid. + * @throws UnmarshalException - thrown if the file is invalid. */ public BaseReferenceManifest(final byte[] rimBytes) throws UnmarshalException { this("", rimBytes); @@ -101,7 +119,7 @@ public class BaseReferenceManifest extends ReferenceManifest { * * @param fileName - string representation of the uploaded file. * @param rimBytes byte array representation of the RIM - * @throws IOException if unable to unmarshal the string + * @throws UnmarshalException if unable to unmarshal the string */ public BaseReferenceManifest(final String fileName, final byte[] rimBytes) throws UnmarshalException { @@ -205,6 +223,9 @@ public class BaseReferenceManifest extends ReferenceManifest { * This method validates the .swidtag file at the given filepath against the * schema. A successful validation results in the output of the tag's name * and tagId attributes, otherwise a generic error message is printed. + * + * @param rimBytes byte array representation of the RIM + * @return an element */ private Element getDirectoryTag(final byte[] rimBytes) { if (rimBytes == null || rimBytes.length == 0) { @@ -220,13 +241,14 @@ public class BaseReferenceManifest extends ReferenceManifest { * and tagId attributes, otherwise a generic error message is printed. * * @param byteArrayInputStream the location of the file to be validated + * @return an element */ private Element getDirectoryTag(final ByteArrayInputStream byteArrayInputStream) { Document document = null; try { document = unmarshallSwidTag(byteArrayInputStream); } catch (UnmarshalException e) { - log.error("Error while parsing Directory tag: " + e.getMessage()); + log.error("Error while parsing Directory tag: {}", e.getMessage()); } if (document != null) { Element softwareIdentity = @@ -246,7 +268,9 @@ public class BaseReferenceManifest extends ReferenceManifest { } /** - * This method iterates over the list of File elements under the directory. * + * This method iterates over the list of File elements under the directory. + * + * @return a list of swid resources */ public List getFileResources() { return getFileResources(getRimBytes()); @@ -256,6 +280,7 @@ public class BaseReferenceManifest extends ReferenceManifest { * This method iterates over the list of File elements under the directory. * * @param rimBytes the bytes to find the files + * @return a list of swid resources */ public List getFileResources(final byte[] rimBytes) { Element directoryTag = getDirectoryTag(rimBytes); @@ -352,49 +377,11 @@ public class BaseReferenceManifest extends ReferenceManifest { return document; } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - BaseReferenceManifest that = (BaseReferenceManifest) o; - return swidCorpus == that.swidCorpus && Objects.equals(swidName, that.swidName) - && Objects.equals(colloquialVersion, that.colloquialVersion) - && Objects.equals(product, that.product) - && Objects.equals(revision, that.revision) - && Objects.equals(edition, that.edition) - && Objects.equals(rimLinkHash, that.rimLinkHash) - && Objects.equals(bindingSpec, that.bindingSpec) - && Objects.equals(bindingSpecVersion, that.bindingSpecVersion) - && Objects.equals(platformVersion, that.platformVersion) - && Objects.equals(payloadType, that.payloadType) - && Objects.equals(pcURIGlobal, that.pcURIGlobal) - && Objects.equals(pcURILocal, that.pcURILocal) - && Objects.equals(entityName, that.entityName) - && Objects.equals(entityRegId, that.entityRegId) - && Objects.equals(entityRole, that.entityRole) - && Objects.equals(entityThumbprint, that.entityThumbprint) - && Objects.equals(linkHref, that.linkHref) - && Objects.equals(linkRel, that.linkRel); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), swidName, - swidCorpus, colloquialVersion, product, - revision, edition, rimLinkHash, bindingSpec, - bindingSpecVersion, platformVersion, - payloadType, pcURIGlobal, pcURILocal, - entityName, entityRegId, entityRole, - entityThumbprint, linkHref, linkRel); - } - + /** + * Creates a string representation of the Base Reference Manifest object. + * + * @return a string representation of the Base Reference Manifest object. + */ @Override public String toString() { return String.format("ReferenceManifest{swidName=%s," diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/EventLogMeasurements.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/EventLogMeasurements.java index e361c5b7..fcfa394b 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/EventLogMeasurements.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/EventLogMeasurements.java @@ -1,7 +1,6 @@ package hirs.attestationca.persist.entity.userdefined.rim; import com.fasterxml.jackson.annotation.JsonIgnore; -import hirs.attestationca.persist.entity.userdefined.ReferenceManifest; import hirs.attestationca.persist.enums.AppraisalStatus; import hirs.utils.tpm.eventlog.TCGEventLog; import hirs.utils.tpm.eventlog.TpmPcrEvent; @@ -9,6 +8,7 @@ import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.extern.log4j.Log4j2; @@ -25,16 +25,18 @@ import java.util.Collection; * Similar to {@link SupportReferenceManifest} * however this is the live log from the client. */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) @Log4j2 @Entity public class EventLogMeasurements extends SupportReferenceManifest { @Column @JsonIgnore - @Getter @Setter private int pcrHash = 0; + @Enumerated(EnumType.STRING) - @Getter @Setter private AppraisalStatus.Status overallValidationResult = AppraisalStatus.Status.FAIL; /** @@ -74,6 +76,7 @@ public class EventLogMeasurements extends SupportReferenceManifest { /** * Getter method for the expected PCR values contained within the support * RIM. + * * @return a string array of the pcr values. */ public String[] getExpectedPCRList() { @@ -81,12 +84,8 @@ public class EventLogMeasurements extends SupportReferenceManifest { TCGEventLog logProcessor = new TCGEventLog(this.getRimBytes()); this.pcrHash = Arrays.hashCode(logProcessor.getExpectedPCRValues()); return logProcessor.getExpectedPCRValues(); - } catch (CertificateException cEx) { - log.error(cEx); - } catch (NoSuchAlgorithmException noSaEx) { - log.error(noSaEx); - } catch (IOException ioEx) { - log.error(ioEx); + } catch (CertificateException | NoSuchAlgorithmException | IOException exception) { + log.error(exception); } return new String[0]; @@ -102,32 +101,10 @@ public class EventLogMeasurements extends SupportReferenceManifest { try { logProcessor = new TCGEventLog(this.getRimBytes()); return logProcessor.getEventList(); - } catch (CertificateException cEx) { - log.error(cEx); - } catch (NoSuchAlgorithmException noSaEx) { - log.error(noSaEx); - } catch (IOException ioEx) { - log.error(ioEx); + } catch (CertificateException | NoSuchAlgorithmException | IOException exception) { + log.error(exception); } return new ArrayList<>(); } - - @Override - public boolean equals(final Object object) { - if (this == object) { - return true; - } - if (object == null || getClass() != object.getClass()) { - return false; - } - EventLogMeasurements that = (EventLogMeasurements) object; - - return this.getHexDecHash().equals(that.getHexDecHash()); - } - - @Override - public int hashCode() { - return super.hashCode(); - } -} \ No newline at end of file +} diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/ReferenceDigestValue.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/ReferenceDigestValue.java index 101fe606..0240c351 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/ReferenceDigestValue.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/ReferenceDigestValue.java @@ -6,9 +6,9 @@ import jakarta.persistence.AccessType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Table; +import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; - import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @@ -22,48 +22,50 @@ import java.util.UUID; * Digest Value, Event Type, index, RIM Tagid */ @Getter +@Setter @Builder @AllArgsConstructor @Entity -@EqualsAndHashCode(callSuper=false) +@EqualsAndHashCode(callSuper = false) @Table(name = "ReferenceDigestValue") @Access(AccessType.FIELD) public class ReferenceDigestValue extends AbstractEntity { - @Setter @JdbcTypeCode(java.sql.Types.VARCHAR) @Column private UUID baseRimId; - @Setter + @JdbcTypeCode(java.sql.Types.VARCHAR) @Column private UUID supportRimId; - @Setter + @Column(nullable = false) private String manufacturer; - @Setter + @Column(nullable = false) private String model; - @Setter + @Column(nullable = false) private int pcrIndex; - @Setter + @Column(nullable = false) private String digestValue; - @Setter + @Column(nullable = false) private String supportRimHash; - @Setter + @Column(nullable = false) private String eventType; - @Column(columnDefinition = "blob", nullable = true) + + @Setter(AccessLevel.NONE) + @Column(columnDefinition = "blob") private byte[] contentBlob; - @Setter + @Column(nullable = false) private boolean matchFail; - @Setter + @Column(nullable = false) private boolean patched; - @Setter + @Column(nullable = false) private boolean updated; @@ -88,18 +90,19 @@ public class ReferenceDigestValue extends AbstractEntity { /** * Default Constructor with parameters for all associated data. - * @param baseRimId the UUID of the associated record - * @param supportRimId the UUID of the associated record - * @param manufacturer associated creator for this information - * @param model the specific device type - * @param pcrIndex the event number - * @param digestValue the key digest value + * + * @param baseRimId the UUID of the associated record + * @param supportRimId the UUID of the associated record + * @param manufacturer associated creator for this information + * @param model the specific device type + * @param pcrIndex the event number + * @param digestValue the key digest value * @param supportRimHash the support file's hash value - * @param eventType the event type to store - * @param matchFail the status of the baseline check - * @param patched the status of the value being updated to patch - * @param updated the status of the value being updated with info - * @param contentBlob the data value of the content + * @param eventType the event type to store + * @param matchFail the status of the baseline check + * @param patched the status of the value being updated to patch + * @param updated the status of the value being updated with info + * @param contentBlob the data value of the content */ public ReferenceDigestValue(final UUID baseRimId, final UUID supportRimId, final String manufacturer, final String model, @@ -108,6 +111,8 @@ public class ReferenceDigestValue extends AbstractEntity { final String eventType, final boolean matchFail, final boolean patched, final boolean updated, final byte[] contentBlob) { + + this.baseRimId = baseRimId; this.supportRimId = supportRimId; this.manufacturer = manufacturer; @@ -122,17 +127,10 @@ public class ReferenceDigestValue extends AbstractEntity { this.contentBlob = Arrays.clone(contentBlob); } - /** - * the object that contains the raw bytes for this RDV. - * @return the raw bytes - */ - public byte[] getContentBlob() { - return Arrays.clone(contentBlob); - } - /** * Helper method to update the attributes of this object. - * @param support the associated RIM. + * + * @param support the associated RIM. * @param baseRimId the main id to update */ public void updateInfo(final SupportReferenceManifest support, final UUID baseRimId) { @@ -151,6 +149,7 @@ public class ReferenceDigestValue extends AbstractEntity { /** * Returns a string of the classes fields. + * * @return a string */ public String toString() { diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/SupportReferenceManifest.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/SupportReferenceManifest.java index 1e354615..2cde6cb1 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/SupportReferenceManifest.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/SupportReferenceManifest.java @@ -6,6 +6,7 @@ import hirs.utils.tpm.eventlog.TCGEventLog; import hirs.utils.tpm.eventlog.TpmPcrEvent; import jakarta.persistence.Column; import jakarta.persistence.Entity; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.extern.log4j.Log4j2; @@ -16,7 +17,6 @@ import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Objects; /** * Sub class that will just focus on PCR Values and Events. @@ -24,12 +24,14 @@ import java.util.Objects; @Log4j2 @Getter @Setter +@EqualsAndHashCode(callSuper = true) @Entity public class SupportReferenceManifest extends ReferenceManifest { @Column @JsonIgnore private int pcrHash = 0; + @Column private boolean updated = false; @@ -71,6 +73,7 @@ public class SupportReferenceManifest extends ReferenceManifest { /** * Getter method for the expected PCR values contained within the support * RIM. + * * @return a string array of the pcr values. */ public String[] getExpectedPCRList() { @@ -78,12 +81,8 @@ public class SupportReferenceManifest extends ReferenceManifest { TCGEventLog logProcessor = new TCGEventLog(this.getRimBytes()); this.pcrHash = Arrays.hashCode(logProcessor.getExpectedPCRValues()); return logProcessor.getExpectedPCRValues(); - } catch (CertificateException cEx) { - log.error(cEx); - } catch (NoSuchAlgorithmException noSaEx) { - log.error(noSaEx); - } catch (IOException ioEx) { - log.error(ioEx); + } catch (CertificateException | NoSuchAlgorithmException | IOException exception) { + log.error(exception); } return new String[0]; @@ -99,12 +98,8 @@ public class SupportReferenceManifest extends ReferenceManifest { try { logProcessor = new TCGEventLog(this.getRimBytes()); return logProcessor.getEventList(); - } catch (CertificateException cEx) { - log.error(cEx); - } catch (NoSuchAlgorithmException noSaEx) { - log.error(noSaEx); - } catch (IOException ioEx) { - log.error(ioEx); + } catch (CertificateException | NoSuchAlgorithmException | IOException exception) { + log.error(exception); } return new ArrayList<>(); @@ -113,23 +108,10 @@ public class SupportReferenceManifest extends ReferenceManifest { /** * This is a method to indicate whether or not this support * rim is a base log file. + * * @return flag for base. */ public boolean isBaseSupport() { return !this.isSwidSupplemental() && !this.isSwidPatch(); } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; - SupportReferenceManifest that = (SupportReferenceManifest) o; - return pcrHash == that.pcrHash && updated == that.updated; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), pcrHash, updated); - } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/package-info.java index 85a64fc8..aa634383 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/package-info.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/package-info.java @@ -1 +1 @@ -package hirs.attestationca.persist.entity.userdefined.rim; \ No newline at end of file +package hirs.attestationca.persist.entity.userdefined.rim; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/enums/AppraisalStatus.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/enums/AppraisalStatus.java index 0988656c..1067bf16 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/enums/AppraisalStatus.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/enums/AppraisalStatus.java @@ -9,6 +9,35 @@ import lombok.Setter; @Getter @Setter public class AppraisalStatus { + private Status appStatus; + private String message; + private String additionalInfo; + + /** + * Default constructor. Set appraisal status and description. + * + * @param appStatus status of appraisal + * @param message description of result + */ + public AppraisalStatus(final Status appStatus, final String message) { + this(appStatus, message, ""); + } + + /** + * Default constructor. Set appraisal status and description. + * + * @param appStatus status of appraisal + * @param message description of result + * @param additionalInfo any additional information needed to + * be passed on + */ + public AppraisalStatus(final Status appStatus, final String message, + final String additionalInfo) { + this.appStatus = appStatus; + this.message = message; + this.additionalInfo = additionalInfo; + } + /** * Enum used to represent appraisal status. */ @@ -33,31 +62,4 @@ public class AppraisalStatus { */ UNKNOWN } - - private Status appStatus; - private String message; - private String additionalInfo; - - /** - * Default constructor. Set appraisal status and description. - * @param appStatus status of appraisal - * @param message description of result - */ - public AppraisalStatus(final Status appStatus, final String message) { - this(appStatus, message, ""); - } - - /** - * Default constructor. Set appraisal status and description. - * @param appStatus status of appraisal - * @param message description of result - * @param additionalInfo any additional information needed to - * be passed on - */ - public AppraisalStatus(final Status appStatus, final String message, - final String additionalInfo) { - this.appStatus = appStatus; - this.message = message; - this.additionalInfo = additionalInfo; - } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/enums/HealthStatus.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/enums/HealthStatus.java index ffeffb99..4ff0c457 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/enums/HealthStatus.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/enums/HealthStatus.java @@ -1,11 +1,18 @@ package hirs.attestationca.persist.enums; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.ToString; + import java.util.Arrays; import java.util.stream.Collectors; /** * HealthStatus is used to represent the health of a device. */ +@Getter +@AllArgsConstructor +@ToString public enum HealthStatus { /** * The trusted state, no issues with the device. @@ -22,36 +29,18 @@ public enum HealthStatus { */ UNKNOWN("unknown"); - private String healthStatus; + private final String healthStatus; /** - * Creates a new HealthStatus object given a String. + * Determines if the provided health status is a valid health status. * - * @param healthStatus - * "trusted", "untrusted", or "unknown" + * @param healthStatus string representation of the healh status + * @return true if the health status is valid, otherwise false */ - HealthStatus(final String healthStatus) { - this.healthStatus = healthStatus; - } - - /** - * Returns the health status. - * - * @return the status - */ - public String getStatus() { - return this.healthStatus; - } - - @Override - public String toString() { - return getStatus(); - } - public static boolean isValidStatus(final String healthStatus) { return Arrays.stream(HealthStatus.values()) .map(HealthStatus::name) .collect(Collectors.toSet()) .contains(healthStatus); } -} \ No newline at end of file +} diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/enums/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/enums/package-info.java index cf1c1525..e1b0239f 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/enums/package-info.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/enums/package-info.java @@ -1 +1 @@ -package hirs.attestationca.persist.enums; \ No newline at end of file +package hirs.attestationca.persist.enums; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/exceptions/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/exceptions/package-info.java new file mode 100644 index 00000000..4bc1b624 --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/exceptions/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.exceptions; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/package-info.java new file mode 100644 index 00000000..625de584 --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/AbstractProcessor.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/AbstractProcessor.java index a98663dd..809e283d 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/AbstractProcessor.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/AbstractProcessor.java @@ -40,22 +40,23 @@ import java.util.Date; import java.util.LinkedList; import java.util.List; +@Getter @Log4j2 @NoArgsConstructor public class AbstractProcessor { - @Getter private int validDays; - @Getter + private PrivateKey privateKey; + @Setter - @Getter private PolicyRepository policyRepository; /** * Default constructor that sets main class fields. + * * @param privateKey private key used for communication authentication - * @param validDays property value to set for issued certificates + * @param validDays property value to set for issued certificates */ public AbstractProcessor(final PrivateKey privateKey, final int validDays) { @@ -66,17 +67,18 @@ public class AbstractProcessor { /** * Generates a credential using the specified public key. * - * @param publicKey cannot be null + * @param publicKey cannot be null * @param endorsementCredential the endorsement credential - * @param platformCredentials the set of platform credentials - * @param deviceName The host name used in the subject alternative name - * @param acaCertificate object used to create credential + * @param platformCredentials the set of platform credentials + * @param deviceName The host name used in the subject alternative name + * @param acaCertificate object used to create credential * @return identity credential */ protected X509Certificate generateCredential(final PublicKey publicKey, - final EndorsementCredential endorsementCredential, - final List platformCredentials, - final String deviceName, final X509Certificate acaCertificate) { + final EndorsementCredential endorsementCredential, + final List platformCredentials, + final String deviceName, + final X509Certificate acaCertificate) { try { // have the certificate expire in the configured number of days Calendar expiry = Calendar.getInstance(); @@ -132,8 +134,8 @@ public class AbstractProcessor { * IdentityClaim. Will also check if the Endorsement Credential was already uploaded. * Persists the Endorsement Credential if it does not already exist. * - * @param identityClaim a Protobuf generated Identity Claim object - * @param ekPub the endorsement public key from the Identity Claim object + * @param identityClaim a Protobuf generated Identity Claim object + * @param ekPub the endorsement public key from the Identity Claim object * @param certificateRepository db connector from certificates * @return the Endorsement Credential, if one exists, null otherwise */ @@ -162,7 +164,7 @@ public class AbstractProcessor { * IdentityClaim and Endorsement Credential. Persists the Platform Credentials if they * do not already exist. * - * @param identityClaim a Protobuf generated Identity Claim object + * @param identityClaim a Protobuf generated Identity Claim object * @param endorsementCredential an endorsement credential to check if platform credentials * exist * @param certificateRepository db connector from certificates @@ -193,7 +195,8 @@ public class AbstractProcessor { /** * Gets the Endorsement Credential from the DB given the EK public key. - * @param ekPublicKey the EK public key + * + * @param ekPublicKey the EK public key * @param certificateRepository db store manager for certificates * @return the Endorsement credential, if found, otherwise null */ @@ -229,22 +232,23 @@ public class AbstractProcessor { * Helper method to create an {@link IssuedAttestationCertificate} object, set its * corresponding device and persist it. * - * @param certificateRepository db store manager for certificates + * @param certificateRepository db store manager for certificates * @param derEncodedAttestationCertificate the byte array representing the Attestation * certificate - * @param endorsementCredential the endorsement credential used to generate the AC - * @param platformCredentials the platform credentials used to generate the AC - * @param device the device to which the attestation certificate is tied - * @param isLDevID whether the certificate is a ldevid + * @param endorsementCredential the endorsement credential used to generate the AC + * @param platformCredentials the platform credentials used to generate the AC + * @param device the device to which the attestation certificate is tied + * @param isLDevID whether the certificate is a ldevid * @return whether the certificate was saved successfully * @throws {@link CertificateProcessingException} if error occurs in persisting the Attestation - * Certificate + * Certificate */ public boolean saveAttestationCertificate(final CertificateRepository certificateRepository, - final byte[] derEncodedAttestationCertificate, - final EndorsementCredential endorsementCredential, - final List platformCredentials, - final Device device, boolean isLDevID) { + final byte[] derEncodedAttestationCertificate, + final EndorsementCredential endorsementCredential, + final List platformCredentials, + final Device device, + final boolean isLDevID) { List issuedAc; boolean generateCertificate = true; PolicyRepository scp = getPolicyRepository(); @@ -260,23 +264,22 @@ public class AbstractProcessor { policySettings = scp.findByName("Default"); Sort sortCriteria = Sort.by(Sort.Direction.DESC, "endValidity"); - issuedAc = certificateRepository.findByDeviceIdAndIsLDevID(device.getId(), isLDevID, sortCriteria); + issuedAc = certificateRepository.findByDeviceIdAndIsLDevID(device.getId(), isLDevID, + sortCriteria); generateCertificate = isLDevID ? policySettings.isIssueDevIdCertificate() : policySettings.isIssueAttestationCertificate(); - if (issuedAc != null && issuedAc.size() > 0 && (isLDevID ? policySettings.isDevIdExpirationFlag() + if (issuedAc != null && issuedAc.size() > 0 + && (isLDevID ? policySettings.isDevIdExpirationFlag() : policySettings.isGenerateOnExpiration())) { if (issuedAc.get(0).getEndValidity().after(currentDate)) { // so the issued AC is not expired // however are we within the threshold days = ProvisionUtils.daysBetween(currentDate, issuedAc.get(0).getEndValidity()); - if (days < Integer.parseInt(isLDevID ? policySettings.getDevIdReissueThreshold() - : policySettings.getReissueThreshold())) { - generateCertificate = true; - } else { - generateCertificate = false; - } + generateCertificate = + days < Integer.parseInt(isLDevID ? policySettings.getDevIdReissueThreshold() + : policySettings.getReissueThreshold()); } } } @@ -297,7 +300,7 @@ public class AbstractProcessor { } private List getPlatformCredentials(final CertificateRepository certificateRepository, - final EndorsementCredential ec) { + final EndorsementCredential ec) { List credentials = null; if (ec == null) { diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/CertificateRequestProcessor.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/CertificateRequestProcessor.java index e5c3ba0e..13eb83bb 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/CertificateRequestProcessor.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/CertificateRequestProcessor.java @@ -1,6 +1,5 @@ package hirs.attestationca.persist.provision; -import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import hirs.attestationca.configuration.provisionerTpm2.ProvisionerTpm2; import hirs.attestationca.persist.entity.manager.CertificateRepository; @@ -30,22 +29,23 @@ import java.util.List; @Log4j2 public class CertificateRequestProcessor extends AbstractProcessor { - private SupplyChainValidationService supplyChainValidationService; - private CertificateRepository certificateRepository; - private DeviceRepository deviceRepository; - private X509Certificate acaCertificate; - private TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository; + private final SupplyChainValidationService supplyChainValidationService; + private final CertificateRepository certificateRepository; + private final DeviceRepository deviceRepository; + private final X509Certificate acaCertificate; + private final TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository; /** * Constructor. - * @param supplyChainValidationService object that is used to run provisioning - * @param certificateRepository db connector for all certificates. - * @param deviceRepository database connector for Devices. - * @param privateKey private key used for communication authentication - * @param acaCertificate object used to create credential - * @param validDays int for the time in which a certificate is valid. + * + * @param supplyChainValidationService object that is used to run provisioning + * @param certificateRepository db connector for all certificates. + * @param deviceRepository database connector for Devices. + * @param privateKey private key used for communication authentication + * @param acaCertificate object used to create credential + * @param validDays int for the time in which a certificate is valid. * @param tpm2ProvisionerStateRepository db connector for provisioner state. - * @param policyRepository db connector for policies. + * @param policyRepository db connector for policies. */ public CertificateRequestProcessor(final SupplyChainValidationService supplyChainValidationService, final CertificateRepository certificateRepository, @@ -167,11 +167,12 @@ public class CertificateRequestProcessor extends AbstractProcessor { // We validated the nonce and made use of the identity claim so state can be deleted tpm2ProvisionerStateRepository.delete(tpm2ProvisionerState); - - boolean generateAtt = saveAttestationCertificate(certificateRepository, derEncodedAttestationCertificate, + boolean generateAtt = saveAttestationCertificate(certificateRepository, + derEncodedAttestationCertificate, endorsementCredential, platformCredentials, device, false); - boolean generateLDevID = saveAttestationCertificate(certificateRepository, derEncodedLdevidCertificate, - endorsementCredential, platformCredentials, device, true); + boolean generateLDevID = + saveAttestationCertificate(certificateRepository, derEncodedLdevidCertificate, + endorsementCredential, platformCredentials, device, true); ProvisionerTpm2.CertificateResponse.Builder builder = ProvisionerTpm2.CertificateResponse. newBuilder().setStatus(ProvisionerTpm2.ResponseStatus.PASS); @@ -184,8 +185,7 @@ public class CertificateRequestProcessor extends AbstractProcessor { ProvisionerTpm2.CertificateResponse response = builder.build(); return response.toByteArray(); - } - else { + } else { byte[] derEncodedAttestationCertificate = ProvisionUtils.getDerEncodedCertificate( attestationCertificate); String pemEncodedAttestationCertificate = ProvisionUtils.getPemEncodedCertificate( @@ -197,7 +197,8 @@ public class CertificateRequestProcessor extends AbstractProcessor { ProvisionerTpm2.CertificateResponse.Builder builder = ProvisionerTpm2.CertificateResponse. newBuilder().setStatus(ProvisionerTpm2.ResponseStatus.PASS); - boolean generateAtt = saveAttestationCertificate(certificateRepository, derEncodedAttestationCertificate, + boolean generateAtt = saveAttestationCertificate(certificateRepository, + derEncodedAttestationCertificate, endorsementCredential, platformCredentials, device, false); if (generateAtt) { builder = builder.setCertificate(pemEncodedAttestationCertificate); @@ -218,7 +219,7 @@ public class CertificateRequestProcessor extends AbstractProcessor { } } else { log.error("Could not process credential request. Invalid nonce provided: " - + request.getNonce().toString()); + + request.getNonce()); throw new CertificateProcessingException("Invalid nonce given in request by client."); } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/IdentityClaimProcessor.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/IdentityClaimProcessor.java index edb64617..cbe87597 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/IdentityClaimProcessor.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/IdentityClaimProcessor.java @@ -88,6 +88,16 @@ public class IdentityClaimProcessor extends AbstractProcessor { /** * Constructor. + * + * @param supplyChainValidationService supply chain validation service + * @param certificateRepository certificate repository + * @param componentResultRepository component result repository + * @param componentInfoRepository component info repository + * @param referenceManifestRepository reference manifest repository + * @param referenceDigestValueRepository reference digest value repository + * @param deviceRepository device repository + * @param tpm2ProvisionerStateRepository tpm2 provisioner state repository + * @param policyRepository policy repository */ public IdentityClaimProcessor( final SupplyChainValidationService supplyChainValidationService, @@ -155,8 +165,8 @@ public class IdentityClaimProcessor extends AbstractProcessor { String pcrQuoteMask = PCR_QUOTE_MASK; String strNonce = HexUtils.byteArrayToHexString(nonce); - log.info("Sending nonce: " + strNonce); - log.info("Persisting claim of length: " + identityClaim.length); + log.info("Sending nonce: {}", strNonce); + log.info("Persisting claim of length: {}", identityClaim.length); tpm2ProvisionerStateRepository.save(new TPM2ProvisionerState(nonce, identityClaim)); @@ -171,8 +181,7 @@ public class IdentityClaimProcessor extends AbstractProcessor { .build(); return response.toByteArray(); } else { - log.error("Supply chain validation did not succeed. Result is: " - + validationResult); + log.error("Supply chain validation did not succeed. Result is: {}", validationResult); // empty response ProvisionerTpm2.IdentityClaimResponse response = ProvisionerTpm2.IdentityClaimResponse.newBuilder() @@ -286,7 +295,6 @@ public class IdentityClaimProcessor extends AbstractProcessor { * @param claim the protobuf serialized identity claim containing the device info * @return a HIRS Utils DeviceInfoReport representation of device info */ - @SuppressWarnings("methodlength") private DeviceInfoReport parseDeviceInfo(final ProvisionerTpm2.IdentityClaim claim) throws NoSuchAlgorithmException { ProvisionerTpm2.DeviceInfo dv = claim.getDv(); @@ -394,8 +402,8 @@ public class IdentityClaimProcessor extends AbstractProcessor { */ List rims = referenceManifestRepository.findByArchiveFlag(false); for (ReferenceManifest rim : rims) { - if (rim.isBase() && rim.getTagId().equals(baseRim.getTagId()) && - rim.getCreateTime().after(baseRim.getCreateTime())) { + if (rim.isBase() && rim.getTagId().equals(baseRim.getTagId()) + && rim.getCreateTime().after(baseRim.getCreateTime())) { baseRim.setDeviceName(null); baseRim = (BaseReferenceManifest) rim; baseRim.setDeviceName(dv.getNw().getHostname()); @@ -414,12 +422,11 @@ public class IdentityClaimProcessor extends AbstractProcessor { } catch (UnmarshalException e) { log.error(e); } catch (Exception ex) { - log.error(String.format("Failed to load base rim: %s", ex.getMessage())); + log.error("Failed to load base rim: {}", ex.getMessage()); } } } else { - log.warn(String.format("%s did not send swid tag file...", - dv.getNw().getHostname())); + log.warn("{} did not send swid tag file...", dv.getNw().getHostname()); } if (dv.getLogfileCount() > 0) { @@ -467,9 +474,9 @@ public class IdentityClaimProcessor extends AbstractProcessor { */ List rims = referenceManifestRepository.findByArchiveFlag(false); for (ReferenceManifest rim : rims) { - if (rim.isSupport() && - rim.getTagId().equals(supportRim.getTagId()) && - rim.getCreateTime().after(supportRim.getCreateTime())) { + if (rim.isSupport() + && rim.getTagId().equals(supportRim.getTagId()) + && rim.getCreateTime().after(supportRim.getCreateTime())) { supportRim.setDeviceName(null); supportRim = (SupportReferenceManifest) rim; supportRim.setDeviceName(dv.getNw().getHostname()); @@ -487,12 +494,11 @@ public class IdentityClaimProcessor extends AbstractProcessor { } catch (IOException ioEx) { log.error(ioEx); } catch (Exception ex) { - log.error(String.format("Failed to load support rim: %s", ex.getMessage())); + log.error("Failed to load support rim: {}", ex.getMessage()); } } } else { - log.warn(String.format("%s did not send support RIM file...", - dv.getNw().getHostname())); + log.warn("{} did not send support RIM file...", dv.getNw().getHostname()); } //update Support RIMs and Base RIMs. @@ -583,8 +589,7 @@ public class IdentityClaimProcessor extends AbstractProcessor { log.error(ioEx); } } else { - log.warn(String.format("%s did not send bios measurement log...", - dv.getNw().getHostname())); + log.warn("{} did not send bios measurement log...", dv.getNw().getHostname()); } // Get TPM info, currently unimplemented @@ -689,8 +694,7 @@ public class IdentityClaimProcessor extends AbstractProcessor { dbRdv = digestValueMap.get(patchedValue); if (dbRdv == null) { - log.error(String.format("Patching value does not exist (%s)", - patchedValue)); + log.error("Patching value does not exist ({})", patchedValue); } else { // WIP - Until we get patch examples dbRdv.setPatched(true); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/CredentialManagementHelper.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/CredentialManagementHelper.java index 8bb2a7ba..ae22d14a 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/CredentialManagementHelper.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/CredentialManagementHelper.java @@ -22,9 +22,10 @@ public final class CredentialManagementHelper { /** * Parses and stores the EK in the cert manager. If the cert is already present and archived, * it is unarchived. + * * @param certificateRepository the certificate manager used for storage - * @param endorsementBytes the raw EK bytes used for parsing - * @param deviceName the host name + * @param endorsementBytes the raw EK bytes used for parsing + * @param deviceName the host name * @return the parsed, valid EK * @throws IllegalArgumentException if the provided bytes are not a valid EK. */ @@ -63,7 +64,7 @@ public final class CredentialManagementHelper { if (existingCredential == null) { log.info("No Endorsement Credential found with hash: " + certificateHash); endorsementCredential.setDeviceName(deviceName); - return (EndorsementCredential) certificateRepository.save(endorsementCredential); + return certificateRepository.save(endorsementCredential); } else if (existingCredential.isArchived()) { // if the EK is stored in the DB and it's archived, unarchive. log.info("Unarchiving credential"); @@ -77,9 +78,10 @@ public final class CredentialManagementHelper { /** * Parses and stores the PC in the cert manager. If the cert is already present and archived, * it is unarchived. + * * @param certificateRepository the certificate manager used for storage - * @param platformBytes the raw PC bytes used for parsing - * @param deviceName the host name of the associated machine + * @param platformBytes the raw PC bytes used for parsing + * @param deviceName the host name of the associated machine * @return the parsed, valid PC, or null if the provided bytes are not a valid EK. */ public static PlatformCredential storePlatformCredential( @@ -129,7 +131,7 @@ public final class CredentialManagementHelper { } } platformCredential.setDeviceName(deviceName); - return (PlatformCredential) certificateRepository.save(platformCredential); + return certificateRepository.save(platformCredential); } else if (existingCredential.isArchived()) { // if the PC is stored in the DB and it's archived, unarchive. log.info("Unarchiving credential"); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/IssuedCertificateAttributeHelper.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/IssuedCertificateAttributeHelper.java index f3772c9f..6154d5f9 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/IssuedCertificateAttributeHelper.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/IssuedCertificateAttributeHelper.java @@ -12,6 +12,7 @@ import org.bouncycastle.asn1.x500.AttributeTypeAndValue; import org.bouncycastle.asn1.x500.RDN; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.X500NameBuilder; +import org.bouncycastle.asn1.x509.AttributeCertificateInfo; import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier; import org.bouncycastle.asn1.x509.ExtendedKeyUsage; import org.bouncycastle.asn1.x509.Extension; @@ -21,7 +22,6 @@ import org.bouncycastle.asn1.x509.GeneralNames; import org.bouncycastle.asn1.x509.GeneralNamesBuilder; import org.bouncycastle.asn1.x509.KeyPurposeId; import org.bouncycastle.asn1.x509.TBSCertificate; -import org.bouncycastle.asn1.x509.AttributeCertificateInfo; import java.io.IOException; import java.security.cert.CertificateEncodingException; @@ -35,17 +35,16 @@ import java.util.Collection; @Log4j2 public final class IssuedCertificateAttributeHelper { + /** + * The extended key usage extension. + */ + public static final Extension EXTENDED_KEY_USAGE_EXTENSION; private static final String TPM_ID_LABEL_OID = "2.23.133.2.15"; - /** * Object Identifier TCPA at TPM ID Label. */ public static final ASN1ObjectIdentifier TCPA_AT_TPM_ID_LABEL = new ASN1ObjectIdentifier(TPM_ID_LABEL_OID); - /** - * The extended key usage extension. - */ - public static final Extension EXTENDED_KEY_USAGE_EXTENSION; private static final ASN1ObjectIdentifier TCG_KP_AIK_CERTIFICATE_ATTRIBUTE = new ASN1ObjectIdentifier("2.23.133.8.3"); @@ -69,6 +68,7 @@ public final class IssuedCertificateAttributeHelper { /** * This method builds the AKI extension that will be stored in the generated * Attestation Issued Certificate. + * * @param endorsementCredential EK object to pull AKI from. * @return the AKI extension. * @throws IOException on bad get instance for AKI. @@ -93,11 +93,12 @@ public final class IssuedCertificateAttributeHelper { /** * Builds the subject alternative name based on the supplied certificates. + * * @param endorsementCredential the endorsement credential - * @param platformCredentials the platform credentials - * @param hostName the host name + * @param platformCredentials the platform credentials + * @param hostName the host name * @return the subject alternative name extension - * @throws IOException an IO exception occurs building the extension + * @throws IOException an IO exception occurs building the extension * @throws IllegalArgumentException if the host name is null */ public static Extension buildSubjectAlternativeNameFromCerts( @@ -178,14 +179,11 @@ public final class IssuedCertificateAttributeHelper { populateRdnAttributesInNameBuilder(nameBuilder, rdns); } else { log.error("No RDNs in endorsement credential attributes"); - return; } } catch (CertificateEncodingException e) { log.error("Certificate encoding exception", e); - return; } catch (IOException e) { log.error("Error creating x509 cert from endorsement credential", e); - return; } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/ProvisionUtils.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/ProvisionUtils.java index 4181b09d..88c747fe 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/ProvisionUtils.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/ProvisionUtils.java @@ -3,7 +3,6 @@ package hirs.attestationca.persist.provision.helper; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import hirs.attestationca.configuration.provisionerTpm2.ProvisionerTpm2; -import hirs.attestationca.persist.entity.userdefined.info.TPMInfo; import hirs.attestationca.persist.exceptions.CertificateProcessingException; import hirs.attestationca.persist.exceptions.IdentityProcessingException; import hirs.attestationca.persist.exceptions.UnexpectedServerException; @@ -14,7 +13,6 @@ import hirs.structs.elements.tpm.IdentityRequest; import hirs.structs.elements.tpm.SymmetricKey; import hirs.structs.elements.tpm.SymmetricKeyParams; import hirs.utils.HexUtils; -import hirs.utils.enums.DeviceInfoEnums; import lombok.extern.log4j.Log4j2; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang3.ArrayUtils; @@ -56,32 +54,65 @@ public final class ProvisionUtils { /** * The default size for IV blocks. */ - public final static int DEFAULT_IV_SIZE = 16; + public static final int DEFAULT_IV_SIZE = 16; + + /** + * HMAC Size Length in bytes. + */ + public static final int HMAC_SIZE_LENGTH_BYTES = 2; + + /** + * HMAC key Length in bytes. + */ + public static final int HMAC_KEY_LENGTH_BYTES = 32; + + /** + * Seed Length in bytes. + */ + public static final int SEED_LENGTH = 32; + + /** + * Max secret length. + */ + public static final int MAX_SECRET_LENGTH = 32; + + /** + * AES Key Length un bytes. + */ + public static final int AES_KEY_LENGTH_BYTES = 16; + /** * Defines the well known exponent. * https://en.wikipedia.org/wiki/65537_(number)#Applications */ - private final static BigInteger EXPONENT = new BigInteger("010001", DEFAULT_IV_SIZE); - public static final int HMAC_SIZE_LENGTH_BYTES = 2; - public static final int HMAC_KEY_LENGTH_BYTES = 32; - public static final int SEED_LENGTH = 32; - public static final int MAX_SECRET_LENGTH = 32; - public static final int AES_KEY_LENGTH_BYTES = 16; + private static final BigInteger EXPONENT = new BigInteger("010001", DEFAULT_IV_SIZE); + private static final int TPM2_CREDENTIAL_BLOB_SIZE = 392; + private static final int RSA_MODULUS_LENGTH = 256; + // Constants used to parse out the ak name from the ak public data. Used in generateAkName private static final String AK_NAME_PREFIX = "000b"; + private static final String AK_NAME_HASH_PREFIX = "0001000b00050072000000100014000b0800000000000100"; - private static final SecureRandom random = new SecureRandom(); + + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); /** - * Helper method to parse a byte array into an {@link hirs.attestationca.configuration.provisionerTpm2.ProvisionerTpm2.IdentityClaim}. + * This private constructor was created to silence checkstyle error. + */ + private ProvisionUtils() { + } + + /** + * Helper method to parse a byte array into an + * {@link hirs.attestationca.configuration.provisionerTpm2.ProvisionerTpm2.IdentityClaim}. * * @param identityClaim byte array that should be converted to a Protobuf IdentityClaim * object - * @throws {@link IdentityProcessingException} if byte array could not be parsed * @return the Protobuf generated Identity Claim object + * @throws {@link InvalidProtocolBufferException} if byte array could not be parsed */ public static ProvisionerTpm2.IdentityClaim parseIdentityClaim(final byte[] identityClaim) { try { @@ -96,8 +127,8 @@ public final class ProvisionUtils { * Helper method to extract a DER encoded ASN.1 certificate from an X509 certificate. * * @param certificate the X509 certificate to be converted to DER encoding - * @throws {@link UnexpectedServerException} if error occurs during encoding retrieval * @return the byte array representing the DER encoded certificate + * @throws {@link UnexpectedServerException} if error occurs during encoding retrieval */ public static byte[] getDerEncodedCertificate(final X509Certificate certificate) { try { @@ -135,6 +166,7 @@ public final class ProvisionUtils { /** * Parse public key from public data segment generated by TPM 2.0. + * * @param publicArea the public area segment to parse * @return the RSA public key of the supplied public data */ @@ -154,8 +186,7 @@ public final class ProvisionUtils { /** * Constructs a public key where the modulus is in raw form. * - * @param modulus - * in byte array form + * @param modulus in byte array form * @return public key using specific modulus and the well known exponent */ public static PublicKey assemblePublicKey(final byte[] modulus) { @@ -165,8 +196,7 @@ public final class ProvisionUtils { /** * Constructs a public key where the modulus is Hex encoded. * - * @param modulus - * hex encoded modulus + * @param modulus hex encoded modulus * @return public key using specific modulus and the well known exponent */ public static PublicKey assemblePublicKey(final String modulus) { @@ -175,6 +205,9 @@ public final class ProvisionUtils { /** * Assembles a public key using a defined big int modulus and the well known exponent. + * + * @param modulus modulus + * @return public key using the provided integer modulus */ public static PublicKey assemblePublicKey(final BigInteger modulus) { // generate a key spec using mod and exp @@ -195,8 +228,8 @@ public final class ProvisionUtils { * {@link hirs.structs.elements.tpm.IdentityRequest} using the cipher transformation. * * @param asymmetricBlob to be decrypted - * @param scheme to decrypt with - * @param privateKey cipher private key + * @param scheme to decrypt with + * @param privateKey cipher private key * @return decrypted blob */ public static byte[] decryptAsymmetricBlob(final byte[] asymmetricBlob, @@ -206,25 +239,23 @@ public final class ProvisionUtils { // create a cipher from the specified transformation Cipher cipher = Cipher.getInstance(scheme.toString()); - switch (scheme) { - case OAEP: - OAEPParameterSpec spec = - new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, - new PSource.PSpecified("".getBytes(StandardCharsets.UTF_8))); + if (scheme == EncryptionScheme.OAEP) { + OAEPParameterSpec spec = + new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, + new PSource.PSpecified("".getBytes(StandardCharsets.UTF_8))); - cipher.init(Cipher.PRIVATE_KEY, privateKey, spec); - break; - default: - // initialize the cipher to decrypt using the ACA private key. - cipher.init(Cipher.DECRYPT_MODE, privateKey); + cipher.init(Cipher.PRIVATE_KEY, privateKey, spec); + } else { + // initialize the cipher to decrypt using the ACA private key. + cipher.init(Cipher.DECRYPT_MODE, privateKey); } cipher.update(asymmetricBlob); return cipher.doFinal(); } catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException - | BadPaddingException | IllegalBlockSizeException - | InvalidAlgorithmParameterException e) { + | BadPaddingException | IllegalBlockSizeException + | InvalidAlgorithmParameterException e) { throw new IdentityProcessingException( "Encountered error while decrypting asymmetric blob of an identity request: " + e.getMessage(), e); @@ -236,14 +267,14 @@ public final class ProvisionUtils { * {@link hirs.structs.elements.tpm.IdentityRequest} using the specified symmetric key * and cipher transformation. * - * @param symmetricBlob to be decrypted - * @param symmetricKey to use to decrypt - * @param iv to use with decryption cipher + * @param symmetricBlob to be decrypted + * @param symmetricKey to use to decrypt + * @param iv to use with decryption cipher * @param transformation of the cipher * @return decrypted symmetric blob */ public static byte[] decryptSymmetricBlob(final byte[] symmetricBlob, final byte[] symmetricKey, - final byte[] iv, final String transformation) { + final byte[] iv, final String transformation) { try { // create a cipher from the specified transformation Cipher cipher = Cipher.getInstance(transformation); @@ -257,8 +288,8 @@ public final class ProvisionUtils { // decrypt the symmetric blob return cipher.doFinal(symmetricBlob); } catch (IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException - | BadPaddingException | NoSuchPaddingException - | InvalidAlgorithmParameterException exception) { + | BadPaddingException | NoSuchPaddingException + | InvalidAlgorithmParameterException exception) { log.error("Encountered error while decrypting symmetric blob of an identity request: " + exception.getMessage(), exception); } @@ -266,6 +297,11 @@ public final class ProvisionUtils { return new byte[0]; } + /** + * Generates a symmetric key. + * + * @return a symmetric key + */ public static SymmetricKey generateSymmetricKey() { // create a session key for the CA contents byte[] responseSymmetricKey = @@ -287,16 +323,16 @@ public final class ProvisionUtils { * key to generate an HMAC to cover the encrypted secret and the ak name. The output is an * encrypted blob that acts as the first part of a challenge-response authentication mechanism * to validate an identity claim. - * + *

* Equivalent to calling tpm2_makecredential using tpm2_tools. * - * @param ek endorsement key in the identity claim - * @param ak attestation key in the identity claim + * @param ek endorsement key in the identity claim + * @param ak attestation key in the identity claim * @param secret a nonce * @return the encrypted blob forming the identity claim challenge */ public static ByteString tpm20MakeCredential(final RSAPublicKey ek, final RSAPublicKey ak, - final byte[] secret) { + final byte[] secret) { // check size of the secret if (secret.length > MAX_SECRET_LENGTH) { throw new IllegalArgumentException("Secret must be " + MAX_SECRET_LENGTH @@ -310,7 +346,8 @@ public final class ProvisionUtils { // encrypt seed with pubEk Cipher asymCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding"); OAEPParameterSpec oaepSpec = new OAEPParameterSpec("SHA-256", "MGF1", - MGF1ParameterSpec.SHA256, new PSource.PSpecified("IDENTITY\0".getBytes(StandardCharsets.UTF_8))); + MGF1ParameterSpec.SHA256, + new PSource.PSpecified("IDENTITY\0".getBytes(StandardCharsets.UTF_8))); asymCipher.init(Cipher.PUBLIC_KEY, ek, oaepSpec); asymCipher.update(seed); byte[] encSeed = asymCipher.doFinal(); @@ -365,8 +402,8 @@ public final class ProvisionUtils { return ByteString.copyFrom(bytesToReturn); } catch (BadPaddingException | IllegalBlockSizeException | NoSuchAlgorithmException - | InvalidKeyException | InvalidAlgorithmParameterException - | NoSuchPaddingException e) { + | InvalidKeyException | InvalidAlgorithmParameterException + | NoSuchPaddingException e) { throw new IdentityProcessingException( "Encountered error while making the identity claim challenge: " + e.getMessage(), e); @@ -377,13 +414,13 @@ public final class ProvisionUtils { * Generate asymmetric contents part of the identity response. * * @param identityKey identity requests symmetric contents, otherwise, the identity proof - * @param sessionKey identity response session key - * @param publicKey of the EK certificate contained within the identity proof + * @param sessionKey identity response session key + * @param publicKey of the EK certificate contained within the identity proof * @return encrypted asymmetric contents */ public static byte[] generateAsymmetricContents(final byte[] identityKey, - final byte[] sessionKey, - final PublicKey publicKey) { + final byte[] sessionKey, + final PublicKey publicKey) { try { // create a SHA1 digest of the identity key MessageDigest md = MessageDigest.getInstance("SHA-1"); @@ -408,8 +445,8 @@ public final class ProvisionUtils { return cipher.doFinal(asymmetricContents); } catch (NoSuchAlgorithmException | IllegalBlockSizeException | NoSuchPaddingException - | InvalidKeyException | BadPaddingException - | InvalidAlgorithmParameterException e) { + | InvalidKeyException | BadPaddingException + | InvalidAlgorithmParameterException e) { throw new CertificateProcessingException( "Encountered error while generating ACA session key: " + e.getMessage(), e); } @@ -447,12 +484,12 @@ public final class ProvisionUtils { /** * Generate the Identity Response using the identity credential and the session key. * - * @param credential the identity credential + * @param credential the identity credential * @param symmetricKey generated session key for this request/response chain * @return identity response for an identity request */ public static SymmetricAttestation generateAttestation(final X509Certificate credential, - final SymmetricKey symmetricKey) { + final SymmetricKey symmetricKey) { try { // initialize the symmetric cipher Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); @@ -489,18 +526,26 @@ public final class ProvisionUtils { return attestation; } catch (BadPaddingException | IllegalBlockSizeException | NoSuchAlgorithmException - | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException - | CertificateEncodingException exception) { + | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException + | CertificateEncodingException exception) { throw new CertificateProcessingException( "Encountered error while generating Identity Response: " + exception.getMessage(), exception); } } - @SuppressWarnings("magicnumber") + /** + * Assembles a credential blob. + * + * @param topSize byte array representation of the top size + * @param integrityHmac byte array representation of the integrity HMAC + * @param encryptedSecret byte array representation of the encrypted secret + * @param encryptedSeed byte array representation of the encrypted seed + * @return byte array representation of a credential blob + */ public static byte[] assembleCredential(final byte[] topSize, final byte[] integrityHmac, - final byte[] encryptedSecret, - final byte[] encryptedSeed) { + final byte[] encryptedSecret, + final byte[] encryptedSeed) { /* * Credential structure breakdown with endianness: * 0-1 topSize (2), LE @@ -514,21 +559,39 @@ public final class ProvisionUtils { credentialBlob[0] = topSize[1]; credentialBlob[1] = topSize[0]; credentialBlob[2] = 0x00; - credentialBlob[3] = 0x20; - System.arraycopy(integrityHmac, 0, credentialBlob, 4, 32); - for (int i = 0; i < 98; i++) { - credentialBlob[36 + i] = 0x00; + + final int credBlobPosition4 = 3; + final byte credBlobFourthPositionValue = 0x20; + credentialBlob[credBlobPosition4] = credBlobFourthPositionValue; + + final int credBlobPosition5 = 4; + final int credBlobSizeFromPosition5 = 32; + System.arraycopy(integrityHmac, 0, credentialBlob, credBlobPosition5, credBlobSizeFromPosition5); + + final int credBlobPosition99 = 98; + final int credBlobPosition37 = 36; + + for (int i = 0; i < credBlobPosition99; i++) { + credentialBlob[credBlobPosition37 + i] = 0x00; } - System.arraycopy(encryptedSecret, 0, credentialBlob, 36, encryptedSecret.length); - credentialBlob[134] = 0x00; - credentialBlob[135] = 0x01; - System.arraycopy(encryptedSeed, 0, credentialBlob, 136, 256); + System.arraycopy(encryptedSecret, 0, credentialBlob, credBlobPosition37, encryptedSecret.length); + + final int credBlobPosition135 = 134; + credentialBlob[credBlobPosition135] = 0x00; + + final int credBlobPosition136 = 135; + credentialBlob[credBlobPosition136] = 0x01; + + final int credBlobPosition137 = 136; + final int credBlobSizeFromPosition137 = 256; + System.arraycopy(encryptedSeed, 0, credentialBlob, credBlobPosition137, credBlobSizeFromPosition137); // return the result return credentialBlob; } /** * Determines the AK name from the AK Modulus. + * * @param akModulus modulus of an attestation key * @return the ak name byte array * @throws java.security.NoSuchAlgorithmException Underlying SHA256 method used a bad algorithm @@ -552,45 +615,49 @@ public final class ProvisionUtils { * multiple contexts are not supported in this implementation. This should work for all uses of * the KDF for TPM2_MakeCredential. * - * @param seed random value used to generate the key - * @param label first portion of message used to generate key - * @param context second portion of message used to generate key + * @param seed random value used to generate the key + * @param label first portion of message used to generate key + * @param context second portion of message used to generate key * @param sizeInBytes size of key to generate in bytes * @return the derived key - * @throws NoSuchAlgorithmException Wrong crypto algorithm selected + * @throws NoSuchAlgorithmException Wrong crypto algorithm selected * @throws java.security.InvalidKeyException Invalid key used */ - @SuppressWarnings("magicnumber") + public static byte[] cryptKDFa(final byte[] seed, final String label, final byte[] context, - final int sizeInBytes) + final int sizeInBytes) throws NoSuchAlgorithmException, InvalidKeyException { - ByteBuffer b = ByteBuffer.allocate(4); + final int capacity = 4; + ByteBuffer b = ByteBuffer.allocate(capacity); b.putInt(1); byte[] counter = b.array(); // get the label String labelWithEnding = label; - if (label.charAt(label.length() - 1) != "\0".charAt(0)) { + if (label.charAt(label.length() - 1) != '\u0000') { labelWithEnding = label + "\0"; } byte[] labelBytes = labelWithEnding.getBytes(StandardCharsets.UTF_8); - b = ByteBuffer.allocate(4); - b.putInt(sizeInBytes * 8); + final int byteOffset = 8; + b = ByteBuffer.allocate(capacity); + b.putInt(sizeInBytes * byteOffset); byte[] desiredSizeInBits = b.array(); - int sizeOfMessage = 8 + labelBytes.length; + int sizeOfMessage = byteOffset + labelBytes.length; if (context != null) { sizeOfMessage += context.length; } byte[] message = new byte[sizeOfMessage]; int marker = 0; - System.arraycopy(counter, 0, message, marker, 4); - marker += 4; + + final int markerLength = 4; + System.arraycopy(counter, 0, message, marker, markerLength); + marker += markerLength; System.arraycopy(labelBytes, 0, message, marker, labelBytes.length); marker += labelBytes.length; if (context != null) { System.arraycopy(context, 0, message, marker, context.length); marker += context.length; } - System.arraycopy(desiredSizeInBits, 0, message, marker, 4); + System.arraycopy(desiredSizeInBits, 0, message, marker, markerLength); Mac hmac; byte[] toReturn = new byte[sizeInBytes]; @@ -606,7 +673,9 @@ public final class ProvisionUtils { /** * This method takes the provided TPM Quote and splits it between the PCR * quote and the signature hash. + * * @param tpmQuote contains hash values for the quote and the signature + * @return parsed TPM Quote hash */ public static String parseTPMQuoteHash(final String tpmQuote) { if (tpmQuote != null) { @@ -624,7 +693,9 @@ public final class ProvisionUtils { /** * This method takes the provided TPM Quote and splits it between the PCR * quote and the signature hash. + * * @param tpmQuote contains hash values for the quote and the signature + * @return parsed TPM Quote signature */ public static String parseTPMQuoteSignature(final String tpmQuote) { if (tpmQuote != null) { @@ -638,6 +709,7 @@ public final class ProvisionUtils { /** * Computes the sha256 hash of the given blob. + * * @param blob byte array to take the hash of * @return sha256 hash of blob * @throws NoSuchAlgorithmException improper algorithm selected @@ -649,20 +721,29 @@ public final class ProvisionUtils { } /** - * Generates a array of random bytes. + * Generates an array of random bytes. * - * @param numberOfBytes - * to be generated + * @param numberOfBytes to be generated * @return byte array filled with the specified number of bytes. */ public static byte[] generateRandomBytes(final int numberOfBytes) { byte[] bytes = new byte[numberOfBytes]; - random.nextBytes(bytes); + SECURE_RANDOM.nextBytes(bytes); return bytes; } - @SuppressWarnings("magicnumber") + /** + * Calculates the difference in days between the two provided dates. + * + * @param date1 first provided date + * @param date2 second provided date + * @return difference in days between two dates + */ public static int daysBetween(final Date date1, final Date date2) { - return (int) ((date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24)); + final int hoursInADay = 24; + final int secondsInAnHour = 3600; + final int millisecondsInASecond = 1000; + return (int) ((date2.getTime() - date1.getTime()) + / (millisecondsInASecond * secondsInAnHour * hoursInADay)); } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/package-info.java new file mode 100644 index 00000000..52e582fe --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.provision.helper; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/package-info.java new file mode 100644 index 00000000..d995e10f --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.provision; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/SupplyChainValidationService.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/SupplyChainValidationService.java index ff5b1611..61120b1a 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/SupplyChainValidationService.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/SupplyChainValidationService.java @@ -11,7 +11,11 @@ import hirs.attestationca.persist.entity.manager.ReferenceDigestValueRepository; import hirs.attestationca.persist.entity.manager.ReferenceManifestRepository; import hirs.attestationca.persist.entity.manager.SupplyChainValidationRepository; import hirs.attestationca.persist.entity.manager.SupplyChainValidationSummaryRepository; -import hirs.attestationca.persist.entity.userdefined.*; +import hirs.attestationca.persist.entity.userdefined.Device; +import hirs.attestationca.persist.entity.userdefined.PolicySettings; +import hirs.attestationca.persist.entity.userdefined.ReferenceManifest; +import hirs.attestationca.persist.entity.userdefined.SupplyChainValidation; +import hirs.attestationca.persist.entity.userdefined.SupplyChainValidationSummary; import hirs.attestationca.persist.entity.userdefined.certificate.ComponentResult; import hirs.attestationca.persist.entity.userdefined.certificate.EndorsementCredential; import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredential; @@ -27,12 +31,10 @@ import lombok.extern.log4j.Log4j2; import org.apache.logging.log4j.Level; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import org.yaml.snakeyaml.events.Event; import java.security.KeyStore; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -46,31 +48,31 @@ import static hirs.attestationca.persist.enums.AppraisalStatus.Status.PASS; @Service public class SupplyChainValidationService { - private CACredentialRepository caCredentialRepository; - private PolicyRepository policyRepository; - private ReferenceManifestRepository referenceManifestRepository; - private ReferenceDigestValueRepository referenceDigestValueRepository; - private ComponentResultRepository componentResultRepository; - private ComponentAttributeRepository componentAttributeRepository; - private CertificateRepository certificateRepository; - private SupplyChainValidationRepository supplyChainValidationRepository; - private SupplyChainValidationSummaryRepository supplyChainValidationSummaryRepository; + private final CACredentialRepository caCredentialRepository; + private final PolicyRepository policyRepository; + private final ReferenceManifestRepository referenceManifestRepository; + private final ReferenceDigestValueRepository referenceDigestValueRepository; + private final ComponentResultRepository componentResultRepository; + private final ComponentAttributeRepository componentAttributeRepository; + private final CertificateRepository certificateRepository; + private final SupplyChainValidationRepository supplyChainValidationRepository; + private final SupplyChainValidationSummaryRepository supplyChainValidationSummaryRepository; private UUID provisionSessionId; /** * Constructor. * - * @param caCredentialRepository ca credential repository - * @param policyRepository the policy manager - * @param certificateRepository the cert manager - * @param componentResultRepository the comp result manager - * @param referenceManifestRepository the RIM manager - * @param supplyChainValidationRepository the scv manager + * @param caCredentialRepository ca credential repository + * @param policyRepository the policy manager + * @param certificateRepository the cert manager + * @param componentResultRepository the comp result manager + * @param componentAttributeRepository component attribute repository + * @param referenceManifestRepository the RIM manager + * @param supplyChainValidationRepository the scv manager * @param supplyChainValidationSummaryRepository the summary manager - * @param referenceDigestValueRepository the even manager + * @param referenceDigestValueRepository the even manager */ @Autowired - @SuppressWarnings("ParameterNumberCheck") public SupplyChainValidationService( final CACredentialRepository caCredentialRepository, final PolicyRepository policyRepository, @@ -97,13 +99,12 @@ public class SupplyChainValidationService { * an identity request and validates the supply chain in accordance to the * current supply chain policy. * - * @param ec The endorsement credential from the identity request. - * @param pcs The platform credentials from the identity request. - * @param device The device to be validated. + * @param ec The endorsement credential from the identity request. + * @param pcs The platform credentials from the identity request. + * @param device The device to be validated. * @param componentInfos list of components from the device * @return A summary of the validation results. */ - @SuppressWarnings("methodlength") public SupplyChainValidationSummary validateSupplyChain(final EndorsementCredential ec, final List pcs, final Device device, @@ -250,8 +251,8 @@ public class SupplyChainValidationService { updateComponentStatus(componentResultRepository .findByCertificateSerialNumberAndBoardSerialNumber( - baseCredential.getSerialNumber().toString(), - baseCredential.getPlatformSerial())); + baseCredential.getSerialNumber().toString(), + baseCredential.getPlatformSerial())); } if (!attrErrorMessage.isEmpty()) { //combine platform and platform attributes @@ -323,9 +324,10 @@ public class SupplyChainValidationService { deviceName)); } else { ReferenceManifest manifest = referenceManifestRepository - .findByHexDecHashAndRimType(sRim.getEventLogHash(), ReferenceManifest.MEASUREMENT_RIM); + .findByHexDecHashAndRimType(sRim.getEventLogHash(), + ReferenceManifest.MEASUREMENT_RIM); if (manifest instanceof EventLogMeasurements) { - eventLog = (EventLogMeasurements)manifest; + eventLog = (EventLogMeasurements) manifest; } } if (eventLog == null) { @@ -357,7 +359,8 @@ public class SupplyChainValidationService { BaseReferenceManifest bRim = null; if (sRim != null && sRim.getAssociatedRim() != null) { - Optional oRim = referenceManifestRepository.findById(sRim.getAssociatedRim()); + Optional oRim = + referenceManifestRepository.findById(sRim.getAssociatedRim()); if (oRim.isPresent()) { ReferenceManifest rim = oRim.get(); if (rim instanceof BaseReferenceManifest) { @@ -375,7 +378,8 @@ public class SupplyChainValidationService { Optional previousOpt //= this.supplyChainValidationSummaryRepository.findByDevice(deviceName); //= this.supplyChainValidationSummaryRepository.findByDevice(device); - = this.supplyChainValidationSummaryRepository.findById(UUID.fromString(device.getSummaryId())); + = this.supplyChainValidationSummaryRepository.findById( + UUID.fromString(device.getSummaryId())); if (previousOpt.isPresent()) { SupplyChainValidationSummary previous = previousOpt.get(); for (SupplyChainValidation scv : previous.getValidations()) { @@ -421,6 +425,7 @@ public class SupplyChainValidationService { * If the platform attributes policy is enabled, this method updates the matched * status for the component result. This is done so that the details page for the * platform certificate highlights the title card red. + * * @param componentResults list of associated component results */ private void updateComponentStatus(final List componentResults) { diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/ValidationService.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/ValidationService.java index 9ee79707..76efb8df 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/ValidationService.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/ValidationService.java @@ -18,7 +18,6 @@ import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredent import hirs.attestationca.persist.entity.userdefined.info.ComponentInfo; import hirs.attestationca.persist.entity.userdefined.report.DeviceInfoReport; import hirs.attestationca.persist.enums.AppraisalStatus; -import hirs.attestationca.persist.validation.CertificateAttributeScvValidator; import hirs.attestationca.persist.validation.CredentialValidator; import hirs.attestationca.persist.validation.FirmwareScvValidator; import hirs.utils.BouncyCastleUtils; @@ -41,70 +40,101 @@ import java.util.Set; import java.util.UUID; @Log4j2 -public class ValidationService { +public final class ValidationService { + /** + * This private constructor was created to silence checkstyle errors. + */ + private ValidationService() { + } + + /** + * Evaluates the provided endorsement credential status. + * + * @param endorsementCredential endorsement credential + * @param caCredentialRepository CA Credential repository + * @param acceptExpiredCerts whether to accept expired certificates + * @return a supply chain validation + */ public static SupplyChainValidation evaluateEndorsementCredentialStatus( - final EndorsementCredential ec, + final EndorsementCredential endorsementCredential, final CACredentialRepository caCredentialRepository, final boolean acceptExpiredCerts) { final SupplyChainValidation.ValidationType validationType = SupplyChainValidation.ValidationType.ENDORSEMENT_CREDENTIAL; log.info("Validating endorsement credential"); - if (ec == null) { + if (endorsementCredential == null) { log.error("No endorsement credential to validate"); return buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, "Endorsement credential is missing", null, Level.ERROR); } - KeyStore ecStore = getCaChain(ec, caCredentialRepository); + KeyStore ecStore = getCaChain(endorsementCredential, caCredentialRepository); AppraisalStatus result = CredentialValidator. - validateEndorsementCredential(ec, ecStore, acceptExpiredCerts); - switch (result.getAppStatus()) { - case PASS: - return buildValidationRecord(validationType, AppraisalStatus.Status.PASS, - result.getMessage(), ec, Level.INFO); - case FAIL: - return buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, - result.getMessage(), ec, Level.WARN); - case ERROR: - default: - return buildValidationRecord(validationType, AppraisalStatus.Status.ERROR, - result.getMessage(), ec, Level.ERROR); - } + validateEndorsementCredential(endorsementCredential, ecStore, acceptExpiredCerts); + return switch (result.getAppStatus()) { + case PASS -> buildValidationRecord(validationType, AppraisalStatus.Status.PASS, + result.getMessage(), endorsementCredential, Level.INFO); + case FAIL -> buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, + result.getMessage(), endorsementCredential, Level.WARN); + default -> buildValidationRecord(validationType, AppraisalStatus.Status.ERROR, + result.getMessage(), endorsementCredential, Level.ERROR); + }; } + /** + * Evaluates the provided platform credential status. + * + * @param platformCredential platform credential + * @param trustedCertificateAuthority trusted certificate authority + * @param acceptExpiredCerts whether to accept expired certificates + * @return a supply chain validation + */ public static SupplyChainValidation evaluatePlatformCredentialStatus( - final PlatformCredential pc, + final PlatformCredential platformCredential, final KeyStore trustedCertificateAuthority, final boolean acceptExpiredCerts) { final SupplyChainValidation.ValidationType validationType = SupplyChainValidation.ValidationType.PLATFORM_CREDENTIAL; - if (pc == null) { + if (platformCredential == null) { log.error("No platform credential to validate"); return buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, "Empty Platform credential", null, Level.ERROR); } + log.info("Validating Platform Credential"); - AppraisalStatus result = CredentialValidator.validatePlatformCredential(pc, + + AppraisalStatus result = CredentialValidator.validatePlatformCredential(platformCredential, trustedCertificateAuthority, acceptExpiredCerts); - switch (result.getAppStatus()) { - case PASS: - return buildValidationRecord(validationType, AppraisalStatus.Status.PASS, - result.getMessage(), pc, Level.INFO); - case FAIL: - return buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, - result.getMessage(), pc, Level.WARN); - case ERROR: - default: - return buildValidationRecord(validationType, AppraisalStatus.Status.ERROR, - result.getMessage(), pc, Level.ERROR); - } + + return switch (result.getAppStatus()) { + case PASS -> buildValidationRecord(validationType, AppraisalStatus.Status.PASS, + result.getMessage(), platformCredential, Level.INFO); + case FAIL -> buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, + result.getMessage(), platformCredential, Level.WARN); + default -> buildValidationRecord(validationType, AppraisalStatus.Status.ERROR, + result.getMessage(), platformCredential, Level.ERROR); + }; } + /** + * Evaluates PC Attributes status. + * + * @param platformCredential platform credential + * @param deviceInfoReport device information report + * @param endorsementCredential endorsement credential + * @param certificateRepository certificate repository + * @param componentResultRepository component result repository + * @param componentAttributeRepository component attribute repository + * @param componentInfos list of component information + * @param provisionSessionId uuid representation of the provision session id + * @param ignoreRevisionAttribute whether to ignore revision attribute + * @return a supply chain validation + */ public static SupplyChainValidation evaluatePCAttributesStatus( - final PlatformCredential pc, final DeviceInfoReport deviceInfoReport, - final EndorsementCredential ec, + final PlatformCredential platformCredential, final DeviceInfoReport deviceInfoReport, + final EndorsementCredential endorsementCredential, final CertificateRepository certificateRepository, final ComponentResultRepository componentResultRepository, final ComponentAttributeRepository componentAttributeRepository, @@ -113,36 +143,51 @@ public class ValidationService { final SupplyChainValidation.ValidationType validationType = SupplyChainValidation.ValidationType.PLATFORM_CREDENTIAL_ATTRIBUTES; - if (pc == null) { + if (platformCredential == null) { log.error("No platform credential to validate"); return buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, "Platform credential is missing", null, Level.ERROR); } log.info("Validating platform credential attributes"); + AppraisalStatus result = CredentialValidator. - validatePlatformCredentialAttributes(pc, deviceInfoReport, ec, + validatePlatformCredentialAttributes(platformCredential, deviceInfoReport, + endorsementCredential, componentResultRepository, componentAttributeRepository, componentInfos, provisionSessionId, ignoreRevisionAttribute); - switch (result.getAppStatus()) { - case PASS: - return buildValidationRecord(validationType, AppraisalStatus.Status.PASS, - result.getMessage(), pc, Level.INFO); - case FAIL: + + return switch (result.getAppStatus()) { + case PASS -> buildValidationRecord(validationType, AppraisalStatus.Status.PASS, + result.getMessage(), platformCredential, Level.INFO); + case FAIL -> { if (!result.getAdditionalInfo().isEmpty()) { - pc.setComponentFailures(result.getAdditionalInfo()); - pc.setComponentFailureMessage(result.getMessage()); - certificateRepository.save(pc); + platformCredential.setComponentFailures(result.getAdditionalInfo()); + platformCredential.setComponentFailureMessage(result.getMessage()); + certificateRepository.save(platformCredential); } - return buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, - result.getMessage(), pc, Level.WARN); - case ERROR: - default: - return buildValidationRecord(validationType, AppraisalStatus.Status.ERROR, - result.getMessage(), pc, Level.ERROR); - } + yield buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, + result.getMessage(), platformCredential, Level.WARN); + } + default -> buildValidationRecord(validationType, AppraisalStatus.Status.ERROR, + result.getMessage(), platformCredential, Level.ERROR); + }; } + /** + * Evaluates delta attributes status. + * + * @param deviceInfoReport device information report + * @param base base platform credential + * @param deltaMapping delta mapping + * @param certificateRepository certificate repository + * @param componentResultRepository component result repository + * @param componentAttributeRepository component attribute repository + * @param componentInfos list of component information + * @param provisionSessionId uuid representation of the provision session ID + * @param ignoreRevisionAttribute whether to ignore the revision attribute + * @return a supply chain validation + */ public static SupplyChainValidation evaluateDeltaAttributesStatus( final DeviceInfoReport deviceInfoReport, final PlatformCredential base, @@ -161,11 +206,11 @@ public class ValidationService { base, deltaMapping, componentInfos, componentResultRepository, componentAttributeRepository, provisionSessionId, ignoreRevisionAttribute); - switch (result.getAppStatus()) { - case PASS: - return buildValidationRecord(validationType, AppraisalStatus.Status.PASS, - result.getMessage(), base, Level.INFO); - case FAIL: + + return switch (result.getAppStatus()) { + case PASS -> buildValidationRecord(validationType, AppraisalStatus.Status.PASS, + result.getMessage(), base, Level.INFO); + case FAIL -> { if (!result.getAdditionalInfo().isEmpty()) { base.setComponentFailures(result.getAdditionalInfo()); base.setComponentFailureMessage(result.getMessage()); @@ -173,15 +218,26 @@ public class ValidationService { } // we are adding things to componentFailures // certificateRepository.save(delta); - return buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, + yield buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, result.getMessage(), base, Level.WARN); - case ERROR: - default: - return buildValidationRecord(validationType, AppraisalStatus.Status.ERROR, - result.getMessage(), base, Level.ERROR); - } + // we are adding things to componentFailures +// certificateRepository.save(delta); + } + default -> buildValidationRecord(validationType, AppraisalStatus.Status.ERROR, + result.getMessage(), base, Level.ERROR); + }; } + /** + * Evaluates the firmware status. + * + * @param device device + * @param policySettings policy settings + * @param rimRepo reference manifest repository + * @param rdvRepo reference digest value repository + * @param caRepo CA Credential repository + * @return a supply chain validation + */ public static SupplyChainValidation evaluateFirmwareStatus( final Device device, final PolicySettings policySettings, final ReferenceManifestRepository rimRepo, @@ -207,17 +263,12 @@ public class ValidationService { } } - switch (result.getAppStatus()) { - case PASS: - logLevel = Level.INFO; - break; - case FAIL: - logLevel = Level.WARN; - break; - case ERROR: - default: - logLevel = Level.ERROR; - } + logLevel = switch (result.getAppStatus()) { + case PASS -> Level.INFO; + case FAIL -> Level.WARN; + default -> Level.ERROR; + }; + return buildValidationRecord(validationType, result.getAppStatus(), result.getMessage(), referenceManifest, logLevel); } @@ -258,7 +309,7 @@ public class ValidationService { * include the trust chain if it exists in this class' CertificateManager. * Returns the certificate authority credentials in a KeyStore. * - * @param certificate the credential whose CA chain should be retrieved + * @param certificate the credential whose CA chain should be retrieved * @param caCredentialRepository db service to get CA Certs * @return A keystore containing all relevant CA credentials to the given * certificate's organization or null if the keystore can't be assembled @@ -297,6 +348,7 @@ public class ValidationService { * @param credential the credential whose CA chain should be retrieved * @param previouslyQueriedSubjects a list of organizations to refrain * from querying + * @param caCredentialRepository CA Credential repository * @return a Set containing all relevant CA credentials to the given * certificate's organization */ @@ -318,7 +370,8 @@ public class ValidationService { certAuthsWithMatchingIssuer = caCredentialRepository.findBySubject(credential.getIssuer()); } else { //Get certificates by subject organization - certAuthsWithMatchingIssuer = caCredentialRepository.findBySubjectSorted(credential.getIssuerSorted()); + certAuthsWithMatchingIssuer = + caCredentialRepository.findBySubjectSorted(credential.getIssuerSorted()); } } else { certAuthsWithMatchingIssuer.add(skiCA); @@ -337,6 +390,14 @@ public class ValidationService { return caCreds; } + /** + * Creates a key store using the provided set of certificate authority credentials. + * + * @param certs set of certificate authority credentials + * @return a keystore + * @throws KeyStoreException if there is an issue creating a key store + * @throws IOException if there is an issue creating a key store + */ public static KeyStore caCertSetToKeystore(final Set certs) throws KeyStoreException, IOException { KeyStore keyStore = KeyStore.getInstance("JKS"); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/package-info.java new file mode 100644 index 00000000..0210df6c --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.service; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/CertificateSelector.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/CertificateSelector.java index 5f28222c..10ad8859 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/CertificateSelector.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/CertificateSelector.java @@ -6,6 +6,7 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; +import lombok.Getter; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.bouncycastle.util.Arrays; @@ -24,7 +25,7 @@ import java.util.UUID; * This class is used to select one or many certificates in conjunction * with a {@link }. To make use of this object, * use (some CertificateImpl).select(CertificateManager). - * + *

* This class loosely follows the builder pattern. It is instantiated with * the type of certificate that should be retrieved. It is possible to * further specify which certificate(s) should be retrieved by using an @@ -32,10 +33,10 @@ import java.util.UUID; * restrict the result set. At any time, the results may be retrieved * by using one of the get* methods according to the form the * results should be in. - * + *

* If no matching certificates were found for the query, the returned * value may empty or null, depending on the return type. - * + *

* For example, to retrieve all platform certificates: * *

@@ -45,7 +46,7 @@ import java.util.UUID;
  *      .getCertificates();
  * }
  * 
- * + *

* To retrieve all CA certificates in a KeyStore: * *

@@ -55,7 +56,7 @@ import java.util.UUID;
  *      .getKeyStore();
  * }
  * 
- * + *

* To retrieve all CA certificates matching a certain issuer in X509 format: * *

@@ -71,6 +72,7 @@ import java.util.UUID;
  */
 public abstract class CertificateSelector {
 
+    @Getter
     private final Class certificateClass;
 
     private final Map fieldValueSelections;
@@ -91,7 +93,7 @@ public abstract class CertificateSelector {
      * Construct a new CertificateSelector that will use the given {@link  } to
      * retrieve certificates of the given type.
      *
-     * @param certificateClass the class of certificate to be retrieved
+     * @param certificateClass            the class of certificate to be retrieved
      * @param excludeArchivedCertificates true if excluding archived certificates
      */
     public CertificateSelector(
@@ -105,6 +107,7 @@ public abstract class CertificateSelector {
         this.fieldValueSelections = new HashMap<>();
         this.excludeArchivedCertificates = excludeArchivedCertificates;
     }
+
     /**
      * Specify the entity id that certificates must have to be considered
      * as matching.
@@ -249,6 +252,7 @@ public abstract class CertificateSelector {
 
     /**
      * Specify the authority key identifier to find certificate(s).
+     *
      * @param authorityKeyIdentifier the string of the AKI associated with the certificate.
      * @return this instance
      */
@@ -289,7 +293,7 @@ public abstract class CertificateSelector {
     /**
      * Set a field name and value to match.
      *
-     * @param name the field name to query
+     * @param name  the field name to query
      * @param value the value to query
      */
     protected void setFieldValue(final String name, final Object value) {
@@ -307,8 +311,7 @@ public abstract class CertificateSelector {
             );
         }
 
-        if (value instanceof byte[]) {
-            byte[] valueBytes = (byte[]) value;
+        if (value instanceof byte[] valueBytes) {
 
             Preconditions.checkArgument(
                     ArrayUtils.isNotEmpty(valueBytes),
@@ -329,7 +332,7 @@ public abstract class CertificateSelector {
      *
      * @return a KeyStore populated with the matching certificates, if any
      * @throws KeyStoreException if there is a problem instantiating a JKS-formatted KeyStore
-     * @throws IOException if there is a problem populating the keystore
+     * @throws IOException       if there is a problem populating the keystore
      */
     public KeyStore getKeyStore() throws KeyStoreException, IOException {
         KeyStore keyStore = KeyStore.getInstance("JKS");
@@ -349,8 +352,9 @@ public abstract class CertificateSelector {
      * Construct the criterion that can be used to query for certificates matching the configuration
      * of this {@link CertificateSelector}.
      *
+     * @param criteriaBuilder criteria builder
      * @return a Criterion that can be used to query for certificates matching the configuration of
-     *         this instance
+     * this instance
      */
     Predicate[] getCriterion(final CriteriaBuilder criteriaBuilder) {
         Predicate[] predicates = new Predicate[fieldValueSelections.size()];
@@ -359,7 +363,8 @@ public abstract class CertificateSelector {
 
         int i = 0;
         for (Map.Entry fieldValueEntry : fieldValueSelections.entrySet()) {
-            predicates[i++] = criteriaBuilder.equal(root.get(fieldValueEntry.getKey()), fieldValueEntry.getValue());
+            predicates[i++] =
+                    criteriaBuilder.equal(root.get(fieldValueEntry.getKey()), fieldValueEntry.getValue());
         }
 
         if (this.excludeArchivedCertificates) {
@@ -369,15 +374,9 @@ public abstract class CertificateSelector {
         return predicates;
     }
 
-    /**
-     * @return the certificate class that this instance will query
-     */
-    public Class getCertificateClass() {
-        return certificateClass;
-    }
-
     /**
      * Configures the selector to query for archived and unarchived certificates.
+     *
      * @return the selector
      */
     public CertificateSelector includeArchived() {
diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/ReferenceManifestSelector.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/ReferenceManifestSelector.java
index 62442115..876e302c 100644
--- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/ReferenceManifestSelector.java
+++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/ReferenceManifestSelector.java
@@ -12,9 +12,7 @@ import org.apache.commons.lang3.StringUtils;
 
 import java.util.Arrays;
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
-import java.util.Set;
 import java.util.UUID;
 
 /**
@@ -29,23 +27,28 @@ public abstract class ReferenceManifestSelector {
      * String representing the database field for the manufacturer.
      */
     public static final String PLATFORM_MANUFACTURER = "platformManufacturer";
+
     /**
      * String representing the database field for the manufacturer id.
      */
     public static final String PLATFORM_MANUFACTURER_ID = "platformManufacturerId";
+
     /**
      * String representing the database field for the model.
      */
     public static final String PLATFORM_MODEL = "platformModel";
+
     /**
      * String representing the database field for the filename.
      */
     public static final String RIM_FILENAME_FIELD = "fileName";
+
     private static final String RIM_TYPE_FIELD = "rimType";
 
     private final Class referenceTypeClass;
 
     private final Map fieldValueSelections;
+
     private boolean excludeArchivedRims;
 
     /**
@@ -60,7 +63,7 @@ public abstract class ReferenceManifestSelector {
     /**
      * Standard Constructor for the Selector.
      *
-     * @param referenceTypeClass the type of Reference Manifest to process.
+     * @param referenceTypeClass  the type of Reference Manifest to process.
      * @param excludeArchivedRims true if excluding archived RIMs
      */
     public ReferenceManifestSelector(final Class referenceTypeClass,
@@ -88,6 +91,7 @@ public abstract class ReferenceManifestSelector {
 
     /**
      * Specify the file name of the object to grab.
+     *
      * @param fileName the name of the file associated with the rim
      * @return instance of the manifest in relation to the filename.
      */
@@ -98,6 +102,7 @@ public abstract class ReferenceManifestSelector {
 
     /**
      * Specify the RIM Type to match.
+     *
      * @param rimType the type of rim
      * @return this instance
      */
@@ -109,7 +114,7 @@ public abstract class ReferenceManifestSelector {
     /**
      * Set a field name and value to match.
      *
-     * @param name the field name to query
+     * @param name  the field name to query
      * @param value the value to query
      */
     protected void setFieldValue(final String name, final Object value) {
@@ -127,8 +132,7 @@ public abstract class ReferenceManifestSelector {
             );
         }
 
-        if (value instanceof byte[]) {
-            byte[] valueBytes = (byte[]) value;
+        if (value instanceof byte[] valueBytes) {
 
             Preconditions.checkArgument(
                     ArrayUtils.isNotEmpty(valueBytes),
@@ -145,6 +149,7 @@ public abstract class ReferenceManifestSelector {
      * Construct the criterion that can be used to query for rims matching the
      * configuration of this {@link ReferenceManifestSelector}.
      *
+     * @param criteriaBuilder criteria builder
      * @return a Criterion that can be used to query for rims matching the
      * configuration of this instance
      */
@@ -155,7 +160,8 @@ public abstract class ReferenceManifestSelector {
 
         int i = 0;
         for (Map.Entry fieldValueEntry : fieldValueSelections.entrySet()) {
-            predicates[i++] = criteriaBuilder.equal(root.get(fieldValueEntry.getKey()), fieldValueEntry.getValue());
+            predicates[i++] =
+                    criteriaBuilder.equal(root.get(fieldValueEntry.getKey()), fieldValueEntry.getValue());
         }
 
         if (this.excludeArchivedRims) {
diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/package-info.java
new file mode 100644
index 00000000..263ee908
--- /dev/null
+++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/package-info.java
@@ -0,0 +1 @@
+package hirs.attestationca.persist.service.selector;
diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/PcrComposite.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/PcrComposite.java
index 5aef5da3..f678a282 100644
--- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/PcrComposite.java
+++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/PcrComposite.java
@@ -25,13 +25,13 @@ import java.util.List;
  * was removed. This change was not TCG-compliant, as the auto-generated code
  * would produce something like:
  * 

  - *

+ * 
  *     <PcrValue PcrNumber="0">06fl7EXo34MWxuLq9kcXI9la9NA=</ns3:PcrValue>
  * 
*

- * but using TPMMeasurementRecords result in something like: + * but using TPMMeasurementRecords result in something like: *

  - *

+ * 
  *     <PcrValue PcrNumber="2">
  *       <hash>
  *         <digest>AAECAwQFBgcICQoLDA0ODxAREhM=</digest>
@@ -39,14 +39,13 @@ import java.util.List;
  *     </hash>
  *   </PcrValue>
  * 
- * */ @Log4j2 @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PcrComposite", namespace = "http://www.trustedcomputinggroup.org/XML/SCHEMA/" + "Integrity_Report_v1_0#", propOrder = {"pcrSelection", - "valueSize", "pcrValueList" }) + "valueSize", "pcrValueList"}) @Embeddable public class PcrComposite { @@ -69,11 +68,9 @@ public class PcrComposite { /** * Constructor used to create a PcrComposite object. * - * @param pcrSelection - * {@link PcrSelection } object, identifies which TPM PCRs are - * quoted - * @param pcrValueList - * List of TPMMeasurementRecords representing the PCR values + * @param pcrSelection {@link PcrSelection } object, identifies which TPM PCRs are + * quoted + * @param pcrValueList List of TPMMeasurementRecords representing the PCR values */ public PcrComposite(final PcrSelection pcrSelection, final List pcrValueList) { @@ -90,13 +87,11 @@ public class PcrComposite { } - /** * Gets the value of the valueSize property, the length in bytes of the * array of PcrValue complex types. * * @return int value representing the valueSize - * */ @XmlElement(name = "ValueSize", required = true) public final int getValueSize() { diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/PcrInfoShort.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/PcrInfoShort.java index a81c87f0..3d0fc054 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/PcrInfoShort.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/PcrInfoShort.java @@ -39,7 +39,7 @@ import java.util.List; @XmlType(name = "PcrInfoShort", namespace = "http://www.trustedcomputinggroup.org/XML/SCHEMA/" + "Integrity_Report_v1_0#", propOrder = {"pcrSelection", - "localityAtRelease", "compositeHash", "pcrComposite" }) + "localityAtRelease", "compositeHash", "pcrComposite"}) @Embeddable public class PcrInfoShort { @@ -77,16 +77,12 @@ public class PcrInfoShort { /** * Constructor used to create a PcrInfoShort object. * - * @param pcrSelection - * PcrSelection defines which TPM PCRs are used in the TPM Quote. - * @param localityAtRelease - * short value includes locality information to provide the - * requestor a more complete view of the current platform - * configuration - * @param compositeHash - * A hash of PcrComposite - * @param pcrComposite - * A structure containing the actual values of the PCRs quoted. + * @param pcrSelection PcrSelection defines which TPM PCRs are used in the TPM Quote. + * @param localityAtRelease short value includes locality information to provide the + * requestor a more complete view of the current platform + * configuration + * @param compositeHash A hash of PcrComposite + * @param pcrComposite A structure containing the actual values of the PCRs quoted. */ public PcrInfoShort(final PcrSelection pcrSelection, final short localityAtRelease, final byte[] compositeHash, @@ -126,8 +122,7 @@ public class PcrInfoShort { * collected PCR values match the digest in the quote. * * @return byte array containing the digest - * @throws NoSuchAlgorithmException - * if MessageDigest doesn't recognize "SHA-1" or "SHA-256" + * @throws NoSuchAlgorithmException if MessageDigest doesn't recognize "SHA-1" or "SHA-256" */ public final byte[] getCalculatedDigest() throws NoSuchAlgorithmException { if (this.isTpm1()) { @@ -159,7 +154,7 @@ public class PcrInfoShort { byteBuffer.put(this.pcrSelection.getValue()); byteBuffer.putInt(pcrComposite.getValueSize()); - for (TPMMeasurementRecord record: pcrComposite.getPcrValueList()) { + for (TPMMeasurementRecord record : pcrComposite.getPcrValueList()) { byteBuffer.put(record.getHash().getDigest()); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/PcrSelection.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/PcrSelection.java index 1692697c..93c1b561 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/PcrSelection.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/PcrSelection.java @@ -6,7 +6,6 @@ import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlSchemaType; import jakarta.xml.bind.annotation.XmlType; -import lombok.extern.java.Log; import lombok.extern.log4j.Log4j2; import java.nio.ByteBuffer; @@ -27,12 +26,11 @@ import java.util.Arrays; @Embeddable public class PcrSelection { - private static final int MAX_SIZE_PCR_ARRAY = 3; /** * All PCRs are on. */ public static final int ALL_PCRS_ON = 0xffffff; - + private static final int MAX_SIZE_PCR_ARRAY = 3; @XmlAttribute(name = "PcrSelect", required = true) private final byte[] pcrSelect; @@ -50,9 +48,7 @@ public class PcrSelection { * Each byte represents 8 PCRs. Byte 0 indicates PCRs 0-7, byte 1 8-15 and * so on. For each byte, the individual bits represent a corresponding PCR. * - * @param pcrSelect - * byte array indicating which PCRS are selected - * + * @param pcrSelect byte array indicating which PCRS are selected */ public PcrSelection(final byte[] pcrSelect) { if (pcrSelect == null) { @@ -74,8 +70,7 @@ public class PcrSelection { * selection value. For example, to select the first 3 PCRs, one would use * the long value 7 (b0000 0000 0000 0111). * - * @param pcrSelectLong - * long value representing the bits to be selected + * @param pcrSelectLong long value representing the bits to be selected */ public PcrSelection(final long pcrSelectLong) { if (pcrSelectLong > ALL_PCRS_ON) { diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/package-info.java new file mode 100644 index 00000000..79899629 --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.tpm; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/type/InetAddressType.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/type/InetAddressType.java index 27fc35c4..a7ae064c 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/type/InetAddressType.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/type/InetAddressType.java @@ -72,19 +72,13 @@ public final class InetAddressType implements UserType { * Converts the IP address that is stored as a String and * converts it to an InetAddress. * - * @param rs - * result set - * @param index - * column names - * @param session - * session - * @param owner - * owner + * @param rs result set + * @param index column names + * @param session session + * @param owner owner * @return InetAddress of String - * @throws HibernateException - * if unable to convert the String to an InetAddress - * @throws SQLException - * if unable to retrieve the String from the result set + * @throws HibernateException if unable to convert the String to an InetAddress + * @throws SQLException if unable to retrieve the String from the result set */ @Override public Object nullSafeGet(final ResultSet rs, final int index, @@ -107,9 +101,9 @@ public final class InetAddressType implements UserType { * Converts the InetAddress value to a * String and stores it in the database. * - * @param st prepared statement - * @param value InetAddress - * @param index index + * @param st prepared statement + * @param value InetAddress + * @param index index * @param session session * @throws SQLException if unable to set the value in the result set */ @@ -165,7 +159,7 @@ public final class InetAddressType implements UserType { * immutable. * * @param cached cached - * @param owner owner + * @param owner owner * @return cached */ @Override @@ -178,8 +172,8 @@ public final class InetAddressType implements UserType { * immutable. * * @param original original - * @param target target - * @param owner owner + * @param target target + * @param owner owner * @return original */ @Override diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/type/X509CertificateType.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/type/X509CertificateType.java index 9836a682..9dfc6eee 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/type/X509CertificateType.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/type/X509CertificateType.java @@ -26,7 +26,7 @@ import java.util.Objects; * Hibernate. This class provides the mapping from X509Certificate * to Hibernate commands to JDBC. */ -@NoArgsConstructor(access= AccessLevel.PUBLIC) +@NoArgsConstructor(access = AccessLevel.PUBLIC) public final class X509CertificateType implements UserType { @Override @@ -73,19 +73,13 @@ public final class X509CertificateType implements UserType { * Converts the X509Certificate that is stored as a String and * converts it to an X509Certificate. * - * @param rs - * result set - * @param names - * column names - * @param session - * session - * @param owner - * owner + * @param rs result set + * @param names column names + * @param session session + * @param owner owner * @return X509Certificate of String - * @throws HibernateException - * if unable to convert the String to an X509Certificate - * @throws SQLException - * if unable to retrieve the String from the result set + * @throws HibernateException if unable to convert the String to an X509Certificate + * @throws SQLException if unable to retrieve the String from the result set */ @Override public Object nullSafeGet(final ResultSet rs, final int names, @@ -111,9 +105,9 @@ public final class X509CertificateType implements UserType { * Converts the X509Certificate value to a * String and stores it in the database. * - * @param st prepared statement - * @param value X509Certificate - * @param index index + * @param st prepared statement + * @param value X509Certificate + * @param index index * @param session session * @throws SQLException if unable to set the value in the result set */ @@ -131,7 +125,7 @@ public final class X509CertificateType implements UserType { } catch (Exception e) { final String msg = String.format("unable to convert certificate: %s", - value.toString()); + value); throw new HibernateException(msg, e); } } @@ -178,7 +172,7 @@ public final class X509CertificateType implements UserType { * immutable. * * @param cached cached - * @param owner owner + * @param owner owner * @return cached */ @Override @@ -191,8 +185,8 @@ public final class X509CertificateType implements UserType { * immutable. * * @param original original - * @param target target - * @param owner owner + * @param target target + * @param owner owner * @return original */ @Override diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/type/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/type/package-info.java new file mode 100644 index 00000000..8b7ae213 --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/type/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.type; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/AcaPciIds.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/AcaPciIds.java index 1234ebca..73e90f12 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/AcaPciIds.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/AcaPciIds.java @@ -3,7 +3,6 @@ package hirs.attestationca.persist.util; import hirs.attestationca.persist.entity.userdefined.certificate.ComponentResult; import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentIdentifier; import hirs.attestationca.persist.entity.userdefined.certificate.attributes.V2.ComponentIdentifierV2; - import lombok.extern.log4j.Log4j2; import org.bouncycastle.asn1.DERUTF8String; @@ -23,18 +22,27 @@ public final class AcaPciIds { * The Component Class TCG Registry OID. */ public static final String COMPCLASS_TCG_OID = "2.23.133.18.3.1"; + /** * The Component Class Value mask for NICs. */ public static final String COMPCLASS_TCG_CAT_NIC = "00090000"; + /** * The Component Class Value mask for GFX cards. */ public static final String COMPCLASS_TCG_CAT_GFX = "00050000"; + /** + * Private constructor created to silence checkstyle error. + */ + private AcaPciIds() { + } + /** * Iterate through all components and translate PCI hardware IDs as necessary. It will only * translate ComponentIdentifierV2+ objects as it relies on Component Class information. + * * @param components List of ComponentIdentifiers. * @return the translated list of ComponentIdentifiers. */ @@ -58,6 +66,7 @@ public final class AcaPciIds { /** * Iterate through all components and translate PCI hardware IDs as necessary. It will only * translate ComponentResults objects as it relies on Component Class information. + * * @param componentResults List of ComponentResults. * @return the translated list of ComponentResults. */ @@ -75,6 +84,7 @@ public final class AcaPciIds { /** * Translate Vendor and Device IDs, if found, in ComponentIdentifierV2 objects. * It will only translate ID values, any other value will pass through. + * * @param component ComponentIdentifierV2 object. * @return the translated ComponentIdentifierV2 object. */ @@ -113,6 +123,7 @@ public final class AcaPciIds { /** * Translate Vendor and Device IDs, if found, in ComponentResult objects. * It will only translate ID values, any other value will pass through. + * * @param componentResult ComponentResult object. * @return the translated ComponentResult object. */ diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/CredentialHelper.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/CredentialHelper.java index 8c4c38a2..be6a08e5 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/CredentialHelper.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/CredentialHelper.java @@ -1,8 +1,6 @@ package hirs.attestationca.persist.util; import hirs.attestationca.persist.entity.userdefined.certificate.CertificateVariables; -import lombok.AccessLevel; -import lombok.NoArgsConstructor; import lombok.extern.log4j.Log4j2; import org.bouncycastle.util.encoders.Base64; @@ -15,8 +13,15 @@ import java.util.ListIterator; @Log4j2 public final class CredentialHelper { + /** + * Private constructor was created to silence checkstyle error. + */ + private CredentialHelper() { + } + /** * Small method to check if the certificate is a PEM. + * * @param possiblePEM header information * @return true if it is. */ @@ -26,7 +31,8 @@ public final class CredentialHelper { } /** - * Small method to check if there are multi pem files + * Small method to check if there are multi pem files. + * * @param possiblePEM header information * @return true if it is. */ @@ -44,7 +50,8 @@ public final class CredentialHelper { } /** - * Method to remove header footer information from PEM + * Method to remove header footer information from PEM. + * * @param pemFile string representation of the file * @return a cleaned up raw byte object */ @@ -59,10 +66,11 @@ public final class CredentialHelper { /** * The method is used to remove unwanted spaces and other artifacts from the certificate. + * * @param certificateBytes raw byte form * @return a cleaned up byte form */ - @SuppressWarnings("magicnumber") + public static byte[] trimCertificate(final byte[] certificateBytes) { int certificateStart = 0; int certificateLength = 0; @@ -80,10 +88,13 @@ public final class CredentialHelper { // Look for first ASN.1 Sequence marked by the two bytes (0x30) and (0x82) // The check advances our position in the ByteBuffer by one byte int currentPosition = certificateByteBuffer.position(); - if (certificateByteBuffer.get() == (byte) 0x30 - && certificateByteBuffer.get(currentPosition + 1) == (byte) 0x82) { + final byte byte1 = (byte) 0x30; + final byte byte2 = (byte) 0x82; + if (certificateByteBuffer.get() == byte1 + && certificateByteBuffer.get(currentPosition + 1) == byte2) { // Check if we have anything more in the buffer than an ASN.1 Sequence header - if (certificateByteBuffer.remaining() <= 3) { + final int minByteBufferRemaining = 3; + if (certificateByteBuffer.remaining() <= minByteBufferRemaining) { throw new IllegalArgumentException(malformedCertStringBuilder .append(" Certificate is nothing more than ASN.1 Sequence.") .toString()); @@ -95,7 +106,8 @@ public final class CredentialHelper { certificateLength = Short.toUnsignedInt( certificateByteBuffer.getShort(currentPosition + 2)); // Add the 4 bytes that comprise the start of the ASN.1 Sequence and the length - certificateLength += 4; + final int startOfASN1Bytes = 4; + certificateLength += startOfASN1Bytes; break; } } @@ -112,6 +124,7 @@ public final class CredentialHelper { /** * Return the string associated with the boolean slot. + * * @param bit associated with the location in the array. * @return string value of the bit set. */ @@ -157,6 +170,7 @@ public final class CredentialHelper { * This method is to take the DNs from certificates and sort them in an order * that will be used to lookup issuer certificates. This will not be stored in * the certificate, just the DB for lookup. + * * @param distinguishedName the original DN string. * @return a modified string of sorted DNs */ diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/package-info.java new file mode 100644 index 00000000..736028a8 --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.util; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/CertificateAttributeScvValidator.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/CertificateAttributeScvValidator.java index a427835c..af9464ca 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/CertificateAttributeScvValidator.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/CertificateAttributeScvValidator.java @@ -49,10 +49,11 @@ public class CertificateAttributeScvValidator extends SupplyChainCredentialValid private static final String LC_UNKNOWN = "unknown"; /** + * Validates platform credential attributes v1 p2. * - * @param platformCredential - * @param deviceInfoReport - * @return + * @param platformCredential platform credential + * @param deviceInfoReport device information report + * @return an appraisal status */ public static AppraisalStatus validatePlatformCredentialAttributesV1p2( final PlatformCredential platformCredential, @@ -159,7 +160,7 @@ public class CertificateAttributeScvValidator extends SupplyChainCredentialValid * @param componentAttributeRepository db access to component attribute match status * @param componentInfos list of device components * @param provisionSessionId UUID associated with the SCV Summary - * @param ignoreRevisionAttribute policy flag to ignore the revision attribute + * @param ignoreRevisionAttribute policy flag to ignore the revision attribute * @return either PASS or FAIL */ public static AppraisalStatus validatePlatformCredentialAttributesV2p0( @@ -275,10 +276,10 @@ public class CertificateAttributeScvValidator extends SupplyChainCredentialValid numOfAttributes = attributeResults.size(); boolean saveAttributeResult; for (ComponentAttributeResult componentAttributeResult : attributeResults) { - saveAttributeResult = true; + saveAttributeResult = true; if (ignoreRevisionAttribute) { - saveAttributeResult = !componentAttributeResult.getAttribute() - .equalsIgnoreCase(ComponentResult.ATTRIBUTE_REVISION); + saveAttributeResult = !componentAttributeResult.getAttribute() + .equalsIgnoreCase(ComponentResult.ATTRIBUTE_REVISION); } if (saveAttributeResult) { componentAttributeResult.setProvisionSessionId(provisionSessionId); @@ -312,13 +313,18 @@ public class CertificateAttributeScvValidator extends SupplyChainCredentialValid * pick out the changes that lead to the delta cert and make sure the changes * are valid. * - * @param deviceInfoReport The paccor profile of device being validated against. - * @param deltaMapping map of delta certificates to their validated status - * @param origPcComponents The component identifier list associated with the - * base cert for this specific chain + * @param deviceInfoReport The paccor profile of device being validated against. + * @param deltaMapping map of delta certificates to their validated status + * @param origPcComponents The component identifier list associated with the + * base cert for this specific chain + * @param componentInfos list of component information + * @param componentResultRepository component result repository + * @param componentAttributeRepository component attribute repository + * @param provisionSessionId uuid representation of the provision session id + * @param ignoreRevisionAttribute whether to ignore the revision attribute * @return Appraisal Status of delta being validated. */ - @SuppressWarnings("methodlength") + static AppraisalStatus validateDeltaAttributesChainV2p0( final DeviceInfoReport deviceInfoReport, final Map deltaMapping, @@ -366,7 +372,7 @@ public class CertificateAttributeScvValidator extends SupplyChainCredentialValid if (!componentAttributeResults.isEmpty()) { resultMessage.append(String.format("There are %d errors with Delta " - + "Components associated with: %s%n", + + "Components associated with: %s%n", componentAttributeResults.size(), deltaCertificates.get(0).getPlatformSerial())); fieldValidation = false; @@ -856,7 +862,8 @@ public class CertificateAttributeScvValidator extends SupplyChainCredentialValid /** * This method uses a specific hash to match device components with certificate components. - * @param componentInfos list of device component infos + * + * @param componentInfos list of device component infos * @param compiledComponentList list of the remaining unmatched component results * @return remaining component results not matched */ @@ -892,7 +899,8 @@ public class CertificateAttributeScvValidator extends SupplyChainCredentialValid /** * This method is used to find matches based on the component class value. - * @param componentInfos list of device component infos + * + * @param componentInfos list of device component infos * @param remainingComponentResults list of the remaining unmatched component results * @return a generated list of component attributes results */ @@ -1019,12 +1027,13 @@ public class CertificateAttributeScvValidator extends SupplyChainCredentialValid } /** + * Compiles a list of delta component results. * - * @param deltaCertificates - * @param componentResultRepository - * @param componentAttributeRepository - * @param provisionSessionId - * @return + * @param deltaCertificates delta certificates + * @param componentResultRepository component result repository + * @param componentAttributeRepository component attribute repository + * @param provisionSessionId uuid representation of the provision session id + * @return a list of delta component results */ private static List compileDeltaComponentResults( final List deltaCertificates, @@ -1042,7 +1051,7 @@ public class CertificateAttributeScvValidator extends SupplyChainCredentialValid // pull all component results that are not delta List dbBaseComponents = componentResultRepository .findByBoardSerialNumberAndDelta(deltaCertificates.get(0).getPlatformSerial(), false); - dbBaseComponents.stream().forEach((componentResult) -> { + dbBaseComponents.forEach((componentResult) -> { // ignore values that are not unique if (nonSerialValues.contains(componentResult.getSerialNumber())) { componentNonUniqueSerialMap.put(componentResult.hashCommonElements(), componentResult); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/CredentialValidator.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/CredentialValidator.java index bb4beedc..722f9b48 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/CredentialValidator.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/CredentialValidator.java @@ -33,8 +33,8 @@ public class CredentialValidator extends SupplyChainCredentialValidator { /** * Checks if the endorsement credential is valid. * - * @param ec the endorsement credential to verify. - * @param trustStore trust store holding trusted certificates. + * @param ec the endorsement credential to verify. + * @param trustStore trust store holding trusted certificates. * @param acceptExpired whether or not to accept expired and not yet valid certificates * as valid. * @return the result of the validation. @@ -98,8 +98,8 @@ public class CredentialValidator extends SupplyChainCredentialValidator { /** * Checks if the platform credential is valid. * - * @param pc The platform credential to verify. - * @param trustStore trust store holding trusted certificates. + * @param pc The platform credential to verify. + * @param trustStore trust store holding trusted certificates. * @param acceptExpired whether or not to accept expired certificates as valid. * @return The result of the validation. */ @@ -163,16 +163,17 @@ public class CredentialValidator extends SupplyChainCredentialValidator { /** * Checks if the platform credential's attributes are valid. - * @param platformCredential The platform credential to verify. - * @param deviceInfoReport The device info report containing - * serial number of the platform to be validated. - * @param endorsementCredential The endorsement credential supplied from the same - * identity request as the platform credential. - * @param componentResultRepository db access to component result of mismatching - * @param componentAttributeRepository db access to component attribute match status - * @param componentInfos list of device components - * @param provisionSessionId UUID associated with this run of the provision - * @param ignoreRevisionAttribute policy flag to ignore the revision attribute + * + * @param platformCredential The platform credential to verify. + * @param deviceInfoReport The device info report containing + * serial number of the platform to be validated. + * @param endorsementCredential The endorsement credential supplied from the same + * identity request as the platform credential. + * @param componentResultRepository db access to component result of mismatching + * @param componentAttributeRepository db access to component attribute match status + * @param componentInfos list of device components + * @param provisionSessionId UUID associated with this run of the provision + * @param ignoreRevisionAttribute policy flag to ignore the revision attribute * @return The result of the validation. */ public static AppraisalStatus validatePlatformCredentialAttributes( @@ -223,16 +224,18 @@ public class CredentialValidator extends SupplyChainCredentialValidator { /** * Checks if the delta credential's attributes are valid. - * @param deviceInfoReport The device info report containing - * serial number of the platform to be validated. - * @param basePlatformCredential the base credential from the same identity request - * * as the delta credential. - * @param deltaMapping delta certificates associated with the - * * delta supply validation. - * @param componentInfos list of device components - * @param componentResultRepository repository for component results + * + * @param deviceInfoReport The device info report containing + * serial number of the platform to be validated. + * @param basePlatformCredential the base credential from the same identity request + * as the delta credential. + * @param deltaMapping delta certificates associated with the + * delta supply validation. + * @param componentInfos list of device components + * @param componentResultRepository repository for component results * @param componentAttributeRepository repository for the attribute status - * @param provisionSessionId the session id to share + * @param provisionSessionId the session id to share + * @param ignoreRevisionAttribute whether to ignore the revision attribute * @return the result of the validation. */ public static AppraisalStatus validateDeltaPlatformCredentialAttributes( @@ -242,7 +245,8 @@ public class CredentialValidator extends SupplyChainCredentialValidator { final List componentInfos, final ComponentResultRepository componentResultRepository, final ComponentAttributeRepository componentAttributeRepository, - final UUID provisionSessionId, final boolean ignoreRevisionAttribute) { + final UUID provisionSessionId, + final boolean ignoreRevisionAttribute) { final String baseErrorMessage = "Can't validate platform credential attributes without "; String message; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/FirmwareScvValidator.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/FirmwareScvValidator.java index 9edc08ce..e4af6686 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/FirmwareScvValidator.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/FirmwareScvValidator.java @@ -40,12 +40,12 @@ public class FirmwareScvValidator extends SupplyChainCredentialValidator { private static PcrValidator pcrValidator; /** - * @param device - * @param policySettings - * @param referenceManifestRepository - * @param referenceDigestValueRepository - * @param caCredentialRepository - * @return + * @param device device + * @param policySettings policy settings + * @param referenceManifestRepository reference manifest repository + * @param referenceDigestValueRepository reference digest value repository + * @param caCredentialRepository CA Credential repository + * @return an appraisal status */ @SuppressWarnings("methodlength") public static AppraisalStatus validateFirmware( @@ -66,12 +66,13 @@ public class FirmwareScvValidator extends SupplyChainCredentialValidator { //baseReferenceManifests = referenceManifestRepository.findAllBaseRims(); // This block was looking for a base RIM matching the device name - // The base rim might not have a device name associated with it- i.e. if it's uploaded to the ACA prior to provisioning - // In this case, try to look up the event log associated with the device, then get the base rim associated by event log hash + // The base rim might not have a device name associated with it- i.e. if it's uploaded to the ACA + // prior to provisioning In this case, try to look up the event log associated with the device, + // then get the base rim associated by event log hash List deviceRims = referenceManifestRepository.findByDeviceName(hostName); for (ReferenceManifest deviceRim : deviceRims) { - if (deviceRim instanceof BaseReferenceManifest && !deviceRim.isSwidSupplemental() && - !deviceRim.isSwidPatch()) { + if (deviceRim instanceof BaseReferenceManifest && !deviceRim.isSwidSupplemental() + && !deviceRim.isSwidPatch()) { baseReferenceManifest = (BaseReferenceManifest) deviceRim; } @@ -129,8 +130,8 @@ public class FirmwareScvValidator extends SupplyChainCredentialValidator { try { keyStore = ValidationService.caCertSetToKeystore(set); } catch (Exception e) { - log.error("Error building CA chain for " + signingCert.getSubjectKeyIdentifier() + ": " - + e.getMessage()); + log.error("Error building CA chain for {}: {}", signingCert.getSubjectKeyIdentifier(), + e.getMessage()); } ArrayList certs = new ArrayList<>(set.size()); @@ -138,9 +139,8 @@ public class FirmwareScvValidator extends SupplyChainCredentialValidator { try { certs.add(cac.getX509Certificate()); } catch (IOException e) { - log.error( - "Error building CA chain for " + signingCert.getSubjectKeyIdentifier() + ": " - + e.getMessage()); + log.error("Error building CA chain for {}: {}", signingCert.getSubjectKeyIdentifier(), + e.getMessage()); } } referenceManifestValidator.setTrustStore(certs); @@ -156,16 +156,16 @@ public class FirmwareScvValidator extends SupplyChainCredentialValidator { "Firmware validation failed: invalid certificate path."); } } catch (IOException ioEx) { - log.error("Error getting X509 cert from manager: " + ioEx.getMessage()); + log.error("Error getting X509 cert from manager: {}", ioEx.getMessage()); } catch (SupplyChainValidatorException scvEx) { - log.error("Error validating cert against keystore: " + scvEx.getMessage()); + log.error("Error validating cert against keystore: {}", scvEx.getMessage()); fwStatus = new AppraisalStatus(FAIL, "Firmware validation failed: invalid certificate path."); } break; } } catch (IOException ioEx) { - log.error("Error getting X509 cert from manager: " + ioEx.getMessage()); + log.error("Error getting X509 cert from manager: {}", ioEx.getMessage()); } } @@ -210,12 +210,8 @@ public class FirmwareScvValidator extends SupplyChainCredentialValidator { try { expectedEventLog = new TCGEventLog(supportReferenceManifest.getRimBytes()); baseline = expectedEventLog.getExpectedPCRValues(); - } catch (CertificateException cEx) { + } catch (CertificateException | IOException | NoSuchAlgorithmException cEx) { log.error(cEx); - } catch (NoSuchAlgorithmException noSaEx) { - log.error(noSaEx); - } catch (IOException ioEx) { - log.error(ioEx); } // part 1 of firmware validation check: PCR baseline match @@ -230,9 +226,8 @@ public class FirmwareScvValidator extends SupplyChainCredentialValidator { fwStatus = new AppraisalStatus(FAIL, "Firmware validation failed: Client did not " + "provide pcr values."); - log.warn(String.format( - "Firmware validation failed: Client (%s) did not " - + "provide pcr values.", device.getName())); + log.warn("Firmware validation failed: Client ({}) did not " + + "provide pcr values.", device.getName()); } else { // we have a full set of PCR values //int algorithmLength = baseline[0].length(); @@ -258,12 +253,8 @@ public class FirmwareScvValidator extends SupplyChainCredentialValidator { failedPcrValues.addAll(pcrValidator.validateTpmEvents( actualEventLog, expectedEventLogRecords, policySettings)); } - } catch (CertificateException cEx) { - log.error(cEx); - } catch (NoSuchAlgorithmException noSaEx) { - log.error(noSaEx); - } catch (IOException ioEx) { - log.error(ioEx); + } catch (CertificateException | NoSuchAlgorithmException | IOException exception) { + log.error(exception); } if (!failedPcrValues.isEmpty()) { @@ -277,7 +268,7 @@ public class FirmwareScvValidator extends SupplyChainCredentialValidator { } if (fwStatus.getAppStatus().equals(FAIL)) { fwStatus = new AppraisalStatus(FAIL, String.format("%s%n%s", - fwStatus.getMessage(), sb.toString())); + fwStatus.getMessage(), sb)); } else { fwStatus = new AppraisalStatus(FAIL, sb.toString(), ReferenceManifest.MEASUREMENT_RIM); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/PcrValidator.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/PcrValidator.java index b53296ba..f964007f 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/PcrValidator.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/PcrValidator.java @@ -63,13 +63,45 @@ public class PcrValidator { */ public PcrValidator(final String[] pcrValues) { baselinePcrs = new String[TPMMeasurementRecord.MAX_PCR_ID + 1]; - for (int i = 0; i <= TPMMeasurementRecord.MAX_PCR_ID; i++) { - baselinePcrs[i] = pcrValues[i]; + System.arraycopy(pcrValues, 0, baselinePcrs, 0, TPMMeasurementRecord.MAX_PCR_ID + 1); + } + + /** + * Builds a string array of stored pcrs. + * + * @param pcrContent string representation of the pcr content + * @param algorithmLength length of the algorithm + * @return string array representation of the stored pcrs. + */ + public static String[] buildStoredPcrs(final String pcrContent, final int algorithmLength) { + // we have a full set of PCR values + String[] pcrSet = pcrContent.split("\\n"); + String[] storedPcrs = new String[TPMMeasurementRecord.MAX_PCR_ID + 1]; + + // we need to scroll through the entire list until we find + // a matching hash length + int offset = 1; + + for (int i = 0; i < pcrSet.length; i++) { + if (pcrSet[i].contains("sha")) { + // entered a new set, check size + if (pcrSet[i + offset].split(":")[1].trim().length() + == algorithmLength) { + // found the matching set + for (int j = 0; j <= TPMMeasurementRecord.MAX_PCR_ID; j++) { + storedPcrs[j] = pcrSet[++i].split(":")[1].trim(); + } + break; + } + } } + + return storedPcrs; } /** * Getter for the array of baseline PCRs. + * * @return instance of the PCRs. */ public String[] getBaselinePcrs() { @@ -78,6 +110,7 @@ public class PcrValidator { /** * Setter for the array of baseline PCRs. + * * @param baselinePcrs instance of the PCRs. */ public void setBaselinePcrs(final String[] baselinePcrs) { @@ -88,7 +121,7 @@ public class PcrValidator { * Compares the baseline pcr list and the quote pcr list. If the * ignore flags are set, 10 and 17-19 will be skipped for comparison. * - * @param storedPcrs non-baseline pcr list + * @param storedPcrs non-baseline pcr list * @param policySettings db entity that holds all of policy * @return a StringBuilder that is empty if everything passes. */ @@ -116,7 +149,7 @@ public class PcrValidator { } if (!baselinePcrs[i].equals(storedPcrs[i])) { - log.error(String.format("%s =/= %s", baselinePcrs[i], storedPcrs[i])); + log.error("{} =/= {}", baselinePcrs[i], storedPcrs[i]); sb.append(String.format(failureMsg, i)); } } @@ -128,9 +161,10 @@ public class PcrValidator { /** * Checks that the expected FM events occurring. There are policy options that * will ignore certin PCRs, Event Types and Event Variables present. + * * @param tcgMeasurementLog Measurement log from the client - * @param eventValueMap The events stored as baseline to compare - * @param policySettings db entity that holds all of policy + * @param eventValueMap The events stored as baseline to compare + * @param policySettings db entity that holds all of policy * @return the events that didn't pass */ public List validateTpmEvents(final TCGEventLog tcgMeasurementLog, @@ -139,24 +173,24 @@ public class PcrValidator { List tpmPcrEvents = new LinkedList<>(); for (TpmPcrEvent tpe : tcgMeasurementLog.getEventList()) { if (policySettings.isIgnoreImaEnabled() && tpe.getPcrIndex() == IMA_PCR) { - log.info(String.format("IMA Ignored -> %s", tpe)); + log.info("IMA Ignored -> {}", tpe); } else if (policySettings.isIgnoretBootEnabled() && (tpe.getPcrIndex() >= TBOOT_PCR_START && tpe.getPcrIndex() <= TBOOT_PCR_END)) { - log.info(String.format("TBOOT Ignored -> %s", tpe)); + log.info("TBOOT Ignored -> {}", tpe); } else if (policySettings.isIgnoreOsEvtEnabled() && (tpe.getPcrIndex() >= PXE_PCR_START && tpe.getPcrIndex() <= PXE_PCR_END)) { - log.info(String.format("OS Evt Ignored -> %s", tpe)); + log.info("OS Evt Ignored -> {}", tpe); } else { if (policySettings.isIgnoreGptEnabled() && tpe.getEventTypeStr().contains(EVT_EFI_GPT)) { - log.info(String.format("GPT Ignored -> %s", tpe)); + log.info("GPT Ignored -> {}", tpe); } else if (policySettings.isIgnoreOsEvtEnabled() && ( tpe.getEventTypeStr().contains(EVT_EFI_BOOT) - || tpe.getEventTypeStr().contains(EVT_EFI_VAR))) { - log.info(String.format("OS Evt Ignored -> %s", tpe)); + || tpe.getEventTypeStr().contains(EVT_EFI_VAR))) { + log.info("OS Evt Ignored -> {}", tpe); } else if (policySettings.isIgnoreOsEvtEnabled() && ( tpe.getEventTypeStr().contains(EVT_EFI_CFG) - && tpe.getEventContentStr().contains("SecureBoot"))) { - log.info(String.format("OS Evt Config Ignored -> %s", tpe)); + && tpe.getEventContentStr().contains("SecureBoot"))) { + log.info("OS Evt Config Ignored -> {}", tpe); } else { if (!eventValueMap.containsKey(tpe.getEventDigestStr())) { tpmPcrEvents.add(tpe); @@ -171,8 +205,8 @@ public class PcrValidator { /** * Compares hashs to validate the quote from the client. * - * @param tpmQuote the provided quote - * @param storedPcrs values from the RIM file + * @param tpmQuote the provided quote + * @param storedPcrs values from the RIM file * @param policySettings db entity that holds all of policy * @return true if validated, false if not */ @@ -211,18 +245,19 @@ public class PcrValidator { try { - // The calculated string is being used in the contains method - // because the TPM Quote's hash isn't just for PCR values, - // it contains the calculated digest of the PCRs, along with - // other information. + // The calculated string is being used in the contains method + // because the TPM Quote's hash isn't just for PCR values, + // it contains the calculated digest of the PCRs, along with + // other information. String calculatedString = Hex.encodeHexString( pcrInfoShort.getCalculatedDigest()); - log.debug("Validating PCR information with the following:" + - System.lineSeparator() + "calculatedString = " + calculatedString + - System.lineSeparator() + "quoteString = " + quoteString); + log.debug( + "Validating PCR information with the following:{}calculatedString = {}{}" + + "quoteString = {}", System.lineSeparator(), calculatedString, + System.lineSeparator(), quoteString); validated = quoteString.contains(calculatedString); if (!validated) { - log.warn(calculatedString + " not found in " + quoteString); + log.warn("{} not found in {}", calculatedString, quoteString); } } catch (NoSuchAlgorithmException naEx) { log.error(naEx); @@ -230,30 +265,4 @@ public class PcrValidator { return validated; } - - public static String[] buildStoredPcrs(final String pcrContent, final int algorithmLength) { - // we have a full set of PCR values - String[] pcrSet = pcrContent.split("\\n"); - String[] storedPcrs = new String[TPMMeasurementRecord.MAX_PCR_ID + 1]; - - // we need to scroll through the entire list until we find - // a matching hash length - int offset = 1; - - for (int i = 0; i < pcrSet.length; i++) { - if (pcrSet[i].contains("sha")) { - // entered a new set, check size - if (pcrSet[i + offset].split(":")[1].trim().length() - == algorithmLength) { - // found the matching set - for (int j = 0; j <= TPMMeasurementRecord.MAX_PCR_ID; j++) { - storedPcrs[j] = pcrSet[++i].split(":")[1].trim(); - } - break; - } - } - } - - return storedPcrs; - } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/SupplyChainCredentialValidator.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/SupplyChainCredentialValidator.java index 86e3cdef..914ac968 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/SupplyChainCredentialValidator.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/SupplyChainCredentialValidator.java @@ -4,7 +4,6 @@ import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import hirs.attestationca.persist.entity.userdefined.info.ComponentInfo; -import lombok.NoArgsConstructor; import lombok.extern.log4j.Log4j2; import org.apache.commons.lang3.StringUtils; import org.bouncycastle.asn1.x500.X500Name; @@ -35,35 +34,31 @@ import java.util.List; import java.util.Set; @Log4j2 -@NoArgsConstructor -public class SupplyChainCredentialValidator { +public class SupplyChainCredentialValidator { /** - * used to identify and clear a nuc + * used to identify and clear a nuc. */ public static final int NUC_VARIABLE_BIT = 159; /** * AppraisalStatus message for a valid endorsement credential appraisal. */ public static final String ENDORSEMENT_VALID = "Endorsement credential validated"; - /** * AppraisalStatus message for a valid platform credential appraisal. */ public static final String PLATFORM_VALID = "Platform credential validated"; - /** * AppraisalStatus message for a valid platform credential attributes appraisal. */ public static final String PLATFORM_ATTRIBUTES_VALID = "Platform credential attributes validated"; - /** * AppraisalStatus message for a valid firmware appraisal. */ public static final String FIRMWARE_VALID = "Firmware validated"; - /** + /* * Ensure that BouncyCastle is configured as a javax.security.Security provider, as this * class expects it to be available. */ @@ -71,6 +66,12 @@ public class SupplyChainCredentialValidator { Security.addProvider(new BouncyCastleProvider()); } + /** + * Protected constructor was created to silence checkstyle. + */ + protected SupplyChainCredentialValidator() { + } + /** * Attempts to check if the certificate is validated by certificates in a cert chain. The cert * chain is expected to be stored in a non-ordered KeyStore (trust store). If the signing @@ -78,13 +79,10 @@ public class SupplyChainCredentialValidator { * continue to try to find the signing cert of the intermediate cert. It will continue searching * until it follows the chain up to a root (self-signed) cert. * - * @param cert - * certificate to validate - * @param trustStore - * trust store holding trusted root certificates and intermediate certificates + * @param cert certificate to validate + * @param trustStore trust store holding trusted root certificates and intermediate certificates * @return the certificate chain if validation is successful - * @throws SupplyChainValidatorException - * if the verification is not successful + * @throws SupplyChainValidatorException if the verification is not successful */ public static String verifyCertificate(final X509AttributeCertificateHolder cert, final KeyStore trustStore) throws SupplyChainValidatorException { @@ -122,13 +120,10 @@ public class SupplyChainCredentialValidator { * continue to try to find the signing cert of the intermediate cert. It will continue searching * until it follows the chain up to a root (self-signed) cert. * - * @param cert - * certificate to validate - * @param trustStore - * trust store holding trusted root certificates and intermediate certificates + * @param cert certificate to validate + * @param trustStore trust store holding trusted root certificates and intermediate certificates * @return the certificate chain if validation is successful - * @throws SupplyChainValidatorException - * if the verification is not successful + * @throws SupplyChainValidatorException if the verification is not successful */ public static boolean verifyCertificate(final X509Certificate cert, final KeyStore trustStore) throws SupplyChainValidatorException { @@ -164,12 +159,10 @@ public class SupplyChainCredentialValidator { * to find the signing cert of the intermediate cert. It will continue searching until it * follows the chain up to a root (self-signed) cert. * - * @param cert - * certificate to validate - * @param additionalCerts - * Set of certs to validate against + * @param cert certificate to validate + * @param additionalCerts Set of certs to validate against * @return String status of the cert chain validation - - * blank if successful, error message otherwise + * blank if successful, error message otherwise * @throws SupplyChainValidatorException tried to validate using null certificates */ public static String validateCertChain(final X509AttributeCertificateHolder cert, @@ -227,12 +220,10 @@ public class SupplyChainCredentialValidator { * to find the signing cert of the intermediate cert. It will continue searching until it * follows the chain up to a root (self-signed) cert. * - * @param cert - * certificate to validate - * @param additionalCerts - * Set of certs to validate against + * @param cert certificate to validate + * @param additionalCerts Set of certs to validate against * @return String status of the cert chain validation - - * blank if successful, error message otherwise + * blank if successful, error message otherwise * @throws SupplyChainValidatorException tried to validate using null certificates */ public static String validateCertChain(final X509Certificate cert, @@ -277,7 +268,8 @@ public class SupplyChainCredentialValidator { /** * Parses the output from PACCOR's allcomponents.sh script into ComponentInfo objects. - * @param hostName the host machine associated with the component + * + * @param hostName the host machine associated with the component * @param paccorOutput the output from PACCOR's allcomoponents.sh * @return a list of ComponentInfo objects built from paccorOutput * @throws java.io.IOException if something goes wrong parsing the JSON @@ -333,10 +325,8 @@ public class SupplyChainCredentialValidator { * Checks if the issuer info of an attribute cert matches the supposed signing cert's * distinguished name. * - * @param cert - * the attribute certificate with the signature to validate - * @param signingCert - * the certificate with the public key to validate + * @param cert the attribute certificate with the signature to validate + * @param signingCert the certificate with the public key to validate * @return boolean indicating if the names * @throws SupplyChainValidatorException tried to validate using null certificates */ @@ -359,10 +349,8 @@ public class SupplyChainCredentialValidator { * Checks if the issuer info of a public-key cert matches the supposed signing cert's * distinguished name. * - * @param cert - * the public-key certificate with the signature to validate - * @param signingCert - * the certificate with the public key to validate + * @param cert the public-key certificate with the signature to validate + * @param signingCert the certificate with the public key to validate * @return boolean indicating if the names * @throws SupplyChainValidatorException tried to validate using null certificates */ @@ -387,10 +375,8 @@ public class SupplyChainCredentialValidator { * Checks if the signature of an attribute cert is validated against the signing cert's public * key. * - * @param cert - * the public-key certificate with the signature to validate - * @param signingCert - * the certificate with the public key to validate + * @param cert the public-key certificate with the signature to validate + * @param signingCert the certificate with the public key to validate * @return boolean indicating if the validation passed * @throws SupplyChainValidatorException tried to validate using null certificates */ @@ -423,10 +409,8 @@ public class SupplyChainCredentialValidator { * Checks if the signature of a public-key cert is validated against the signing cert's public * key. * - * @param cert - * the attribute certificate with the signature to validate - * @param signingCert - * the certificate with the public key to validate + * @param cert the attribute certificate with the signature to validate + * @param signingCert the certificate with the public key to validate * @return boolean indicating if the validation passed * @throws SupplyChainValidatorException tried to validate using null certificates */ @@ -442,10 +426,8 @@ public class SupplyChainCredentialValidator { /** * Checks if an X509 Attribute Certificate is valid directly against a public key. * - * @param cert - * the attribute certificate with the signature to validate - * @param signingKey - * the key to use to check the attribute cert + * @param cert the attribute certificate with the signature to validate + * @param signingKey the key to use to check the attribute cert * @return boolean indicating if the validation passed * @throws SupplyChainValidatorException tried to validate using null certificates */ @@ -472,8 +454,7 @@ public class SupplyChainCredentialValidator { * Checks whether given X.509 public-key certificate is self-signed. If the cert can be * verified using its own public key, that means it was self-signed. * - * @param cert - * X.509 Certificate + * @param cert X.509 Certificate * @return boolean indicating if the cert was self-signed */ private static boolean isSelfSigned(final X509Certificate cert) diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/SupplyChainValidatorException.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/SupplyChainValidatorException.java index 82a300e8..456eb043 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/SupplyChainValidatorException.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/SupplyChainValidatorException.java @@ -11,10 +11,8 @@ public class SupplyChainValidatorException extends Exception { * Creates a new SupplyChainValidatorException that has the message * message and Throwable cause cause. * - * @param message - * exception message - * @param cause - * root cause + * @param message exception message + * @param cause root cause */ public SupplyChainValidatorException(final String message, final Throwable cause) { super(message, cause); @@ -24,8 +22,7 @@ public class SupplyChainValidatorException extends Exception { * Creates a new SupplyChainValidatorException that has the String * message message. * - * @param message - * exception message + * @param message exception message */ public SupplyChainValidatorException(final String message) { super(message); @@ -35,8 +32,7 @@ public class SupplyChainValidatorException extends Exception { * Creates a new SupplyChainValidatorException that has the Throwable * cause cause. * - * @param cause - * root cause + * @param cause root cause */ public SupplyChainValidatorException(final Throwable cause) { super(cause); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/package-info.java new file mode 100644 index 00000000..27ae86db --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.validation; diff --git a/HIRS_AttestationCA/src/main/resources/identity_transform.xslt b/HIRS_AttestationCA/src/main/resources/identity_transform.xslt index e5b58225..77396b49 100644 --- a/HIRS_AttestationCA/src/main/resources/identity_transform.xslt +++ b/HIRS_AttestationCA/src/main/resources/identity_transform.xslt @@ -1,6 +1,6 @@ - - + + diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/AttestationCertificateAuthorityTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/AttestationCertificateAuthorityTest.java index a638afa1..c0deaec3 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/AttestationCertificateAuthorityTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/AttestationCertificateAuthorityTest.java @@ -72,62 +72,10 @@ import static org.mockito.Mockito.when; @TestInstance(TestInstance.Lifecycle.PER_CLASS) // needed to use non-static BeforeAll public class AttestationCertificateAuthorityTest { - /** - * This internal class handles setup for testing the function - * generateCredential() from class AbstractProcessor. Because the - * function is Protected and in a different package than the test, - * it cannot be accessed directly. - */ - @Nested - public class AccessAbstractProcessor extends AbstractProcessor { - - /** - * Constructor. - * - * @param privateKey the private key of the ACA - * @param validDays int for the time in which a certificate is valid. - */ - public AccessAbstractProcessor(final PrivateKey privateKey, - final int validDays) { - super(privateKey, validDays); - } - - /** - * Public wrapper for the protected function generateCredential(), to access for testing. - * - * @param publicKey cannot be null - * @param endorsementCredential the endorsement credential - * @param platformCredentials the set of platform credentials - * @param deviceName The host name used in the subject alternative name - * @param acaCertificate the aca certificate - * @return the generated X509 certificate - */ - public X509Certificate accessGenerateCredential(final PublicKey publicKey, - final EndorsementCredential endorsementCredential, - final List platformCredentials, - final String deviceName, - final X509Certificate acaCertificate) { - - return generateCredential(publicKey, - endorsementCredential, - platformCredentials, - deviceName, - acaCertificate); - } - } - - // object in test - private AttestationCertificateAuthority aca; - private AccessAbstractProcessor abstractProcessor; - - // test key pair - private KeyPair keyPair; - // length of IV used in PKI private static final int ENCRYPTION_IV_LEN = 16; // length of secret key used in PKI private static final int SECRETKEY_LEN = 128; - private static final String EK_PUBLIC_PATH = "/tpm2/ek.pub"; private static final String AK_PUBLIC_PATH = "/tpm2/ak.pub"; private static final String AK_NAME_PATH = "/tpm2/ak.name"; @@ -167,7 +115,11 @@ public class AttestationCertificateAuthorityTest { private static final String AK_NAME_HEX = "00 0b 6e 8f 79 1c 7e 16 96 1b 11 71 65 9c e0 cd" + "ae 0d 4d aa c5 41 be 58 89 74 67 55 96 c2 5e 38" + "e2 94"; - + // object in test + private AttestationCertificateAuthority aca; + private AccessAbstractProcessor abstractProcessor; + // test key pair + private KeyPair keyPair; /** * Registers bouncy castle as a security provider. Normally the JEE container will handle this, @@ -178,8 +130,9 @@ public class AttestationCertificateAuthorityTest { public void setupTests() throws Exception { //BeforeSuite + final int keySize = 2048; KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); - keyPairGenerator.initialize(2048); + keyPairGenerator.initialize(keySize); keyPair = keyPairGenerator.generateKeyPair(); //BeforeTest @@ -199,7 +152,7 @@ public class AttestationCertificateAuthorityTest { @Test public void testProcessIdentityClaimTpm2NullRequest() { assertThrows(IllegalArgumentException.class, () -> - aca.processIdentityClaimTpm2(null)); + aca.processIdentityClaimTpm2(null)); } /** @@ -209,7 +162,7 @@ public class AttestationCertificateAuthorityTest { public void testGetPublicKey() { // encoded byte array to be returned by public key - byte[] encoded = new byte[]{0, 1, 0, 1, 0}; + byte[] encoded = new byte[] {0, 1, 0, 1, 0}; // create mocks for testing X509Certificate acaCertificate = mock(X509Certificate.class); @@ -260,7 +213,7 @@ public class AttestationCertificateAuthorityTest { /** * Tests {@link ProvisionUtils#decryptSymmetricBlob( - * byte[], byte[], byte[], String)}. + *byte[], byte[], byte[], String)}. * * @throws Exception during aca processing */ @@ -305,8 +258,11 @@ public class AttestationCertificateAuthorityTest { SymmetricKey symmetricKey = ProvisionUtils.generateSymmetricKey(); // assert the symmetric algorithm, scheme, and key size are all set appropriately - assertTrue(symmetricKey.getAlgorithmId() == 6); - assertTrue(symmetricKey.getEncryptionScheme() == 255); + final int expectedAlgorithmId = 6; + final int expectedEncryptionScheme = 255; + + assertTrue(symmetricKey.getAlgorithmId() == expectedAlgorithmId); + assertTrue(symmetricKey.getEncryptionScheme() == expectedEncryptionScheme); assertTrue(symmetricKey.getKeySize() == symmetricKey.getKey().length); } @@ -315,7 +271,7 @@ public class AttestationCertificateAuthorityTest { /** * Tests {@link ProvisionUtils#generateAsymmetricContents( - * byte[], byte[], PublicKey)}. + *byte[], byte[], PublicKey)}. * * @throws Exception during aca processing */ @@ -323,7 +279,7 @@ public class AttestationCertificateAuthorityTest { public void testGenerateAsymmetricContents() throws Exception { // "encoded" identity proof (returned by struct converter) - byte[] identityProofEncoded = new byte[]{0, 0, 1, 1}; + byte[] identityProofEncoded = new byte[] {0, 0, 1, 1}; // generate a random session key to be used for encryption and decryption byte[] sessionKey = new byte[ENCRYPTION_IV_LEN]; @@ -385,8 +341,9 @@ public class AttestationCertificateAuthorityTest { assertNotNull(attestation); // validate the attestation algorithm + final int expectedAlgorithmId = 6; assertNotNull(attestation.getAlgorithm()); - assertTrue(attestation.getAlgorithm().getAlgorithmId() == 6); + assertTrue(attestation.getAlgorithm().getAlgorithmId() == expectedAlgorithmId); assertTrue(attestation.getAlgorithm().getEncryptionScheme() == 0x1); assertTrue(attestation.getAlgorithm().getSignatureScheme() == 0); assertTrue(attestation.getAlgorithm().getParamsSize() == 0); @@ -478,10 +435,10 @@ public class AttestationCertificateAuthorityTest { assertEquals("", certificate.getSubjectX500Principal().getName()); assertEquals("exampleIdLabel", ((X500Name) GeneralNames.fromExtensions(((TBSCertificate.getInstance( - certificate.getTBSCertificate()).getExtensions())), Extension. - subjectAlternativeName).getNames()[0].getName()).getRDNs( + certificate.getTBSCertificate()).getExtensions())), Extension. + subjectAlternativeName).getNames()[0].getName()).getRDNs( IssuedCertificateAttributeHelper.TCPA_AT_TPM_ID_LABEL)[0].getFirst() - .getValue().toString()); + .getValue().toString()); assertArrayEquals(modulus, resultMod); @@ -513,7 +470,8 @@ public class AttestationCertificateAuthorityTest { // assert that the exponent and the modulus are the same. the exponents should be the well // known prime, 101 - assertTrue(publicKey.getPublicExponent().equals(new BigInteger("010001", 16))); + final int radix = 16; + assertTrue(publicKey.getPublicExponent().equals(new BigInteger("010001", radix))); assertTrue(publicKey.getModulus().equals(modulus)); } @@ -534,14 +492,16 @@ public class AttestationCertificateAuthorityTest { // assert that the exponent and the modulus are the same. the exponents should be the well // known prime, 101. - assertTrue(publicKey.getPublicExponent().equals(new BigInteger("010001", 16))); + final int radix = 16; + assertTrue(publicKey.getPublicExponent().equals(new BigInteger("010001", radix))); assertTrue(publicKey.getModulus().equals(modulus)); } /** * Tests parsing the EK from the TPM2 output file. + * * @throws URISyntaxException incorrect resource path - * @throws IOException unable to read from file + * @throws IOException unable to read from file */ @Test public void testParseEk() throws URISyntaxException, IOException { @@ -551,7 +511,8 @@ public class AttestationCertificateAuthorityTest { byte[] ekFile = Files.readAllBytes(ekPath); RSAPublicKey ek = ProvisionUtils.parsePublicKey(ekFile); - assertTrue(ek.getPublicExponent().equals(new BigInteger("010001", 16))); + final int radix = 16; + assertTrue(ek.getPublicExponent().equals(new BigInteger("010001", radix))); byte[] mod = ek.getModulus().toByteArray(); // big integer conversion is signed so it can add a 0 byte @@ -567,8 +528,9 @@ public class AttestationCertificateAuthorityTest { /** * Tests parsing the AK public key from the TPM2 output file. + * * @throws URISyntaxException incorrect resource path - * @throws IOException unable to read from file + * @throws IOException unable to read from file */ @Test public void testParseAk() throws URISyntaxException, IOException { @@ -578,7 +540,8 @@ public class AttestationCertificateAuthorityTest { byte[] akFile = Files.readAllBytes(akPath); RSAPublicKey ak = ProvisionUtils.parsePublicKey(akFile); - assertTrue(ak.getPublicExponent().equals(new BigInteger("010001", 16))); + final int radix = 16; + assertTrue(ak.getPublicExponent().equals(new BigInteger("010001", radix))); byte[] mod = ak.getModulus().toByteArray(); // big integer conversion is signed so it can add a 0 byte @@ -594,8 +557,9 @@ public class AttestationCertificateAuthorityTest { /** * Tests parsing the AK name from the TPM2 output file. - * @throws URISyntaxException incorrect resource path - * @throws IOException unable to read from file + * + * @throws URISyntaxException incorrect resource path + * @throws IOException unable to read from file * @throws NoSuchAlgorithmException inavlid algorithm */ @Test @@ -624,8 +588,9 @@ public class AttestationCertificateAuthorityTest { * and ekPubPath are correct. Your output file will be * HIRS_AttestationCA/src/test/resources/tpm2/test/make.blob and the nonce used will be * output as HIRS_AttestationCA/src/test/resources/tpm2/test/secret.blob + * * @throws URISyntaxException invalid file path - * @throws IOException unable to read file + * @throws IOException unable to read file */ @Disabled @Test @@ -642,12 +607,12 @@ public class AttestationCertificateAuthorityTest { RSAPublicKey akPub = ProvisionUtils.parsePublicKey(akPubFile); // prepare the nonce and wrap it with keys - byte[] nonce = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + final byte[] nonce = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31}; ByteString blob = ProvisionUtils.tpm20MakeCredential(ekPub, akPub, nonce); Path resources = Objects.requireNonNull(Paths.get(Objects.requireNonNull(this.getClass().getResource( - "/").toURI())) + "/").toURI())) .getParent().getParent().getParent().getParent()); Path makeBlob = resources.resolve("src/test/resources/tpm2/test/make.blob"); Files.write(makeBlob, blob.toByteArray()); @@ -680,12 +645,12 @@ public class AttestationCertificateAuthorityTest { * Test helper method that encrypts a blob using a shared key and IV using the specified * transformation. * - * @param blob to be encrypted + * @param blob blob to be encrypted * @param key shared key * @param iv to encrypt with * @param transformation of the encryption cipher * @return encrypted blob - * @throws Exception + * @throws Exception if there are any issues while encrypting the blob */ private byte[] encryptBlob(final byte[] blob, final byte[] key, final byte[] iv, final String transformation) throws Exception { @@ -708,9 +673,9 @@ public class AttestationCertificateAuthorityTest { /** * Test helper method to decrypt blobs. * - * @param blob to be decrypted + * @param blob blob to be decrypted * @return decrypted blob - * @throws Exception + * @throws Exception if there are any issues while decrypting the blob */ private byte[] decryptBlob(final byte[] blob) throws Exception { // initialize a cipher using the specified transformation @@ -730,12 +695,12 @@ public class AttestationCertificateAuthorityTest { * Test helper method that decrypts a blob using a shared key and IV using the specified. * transformation. * - * @param blob to be decrypted + * @param blob blob to be decrypted * @param key shared key * @param iv to decrypt with * @param transformation of the decryption cipher * @return decrypted blob - * @throws Exception + * @throws Exception if there are any issues while decrypting the blob */ private byte[] decryptBlob(final byte[] blob, final byte[] key, final byte[] iv, final String transformation) throws Exception { @@ -754,4 +719,48 @@ public class AttestationCertificateAuthorityTest { // return the cipher text return cipher.doFinal(blob); } + + /** + * This internal class handles setup for testing the function + * generateCredential() from class AbstractProcessor. Because the + * function is Protected and in a different package than the test, + * it cannot be accessed directly. + */ + @Nested + public class AccessAbstractProcessor extends AbstractProcessor { + + /** + * Constructor. + * + * @param privateKey the private key of the ACA + * @param validDays int for the time in which a certificate is valid. + */ + public AccessAbstractProcessor(final PrivateKey privateKey, + final int validDays) { + super(privateKey, validDays); + } + + /** + * Public wrapper for the protected function generateCredential(), to access for testing. + * + * @param publicKey cannot be null + * @param endorsementCredential the endorsement credential + * @param platformCredentials the set of platform credentials + * @param deviceName The host name used in the subject alternative name + * @param acaCertificate the aca certificate + * @return the generated X509 certificate + */ + public X509Certificate accessGenerateCredential(final PublicKey publicKey, + final EndorsementCredential endorsementCredential, + final List platformCredentials, + final String deviceName, + final X509Certificate acaCertificate) { + + return generateCredential(publicKey, + endorsementCredential, + platformCredentials, + deviceName, + acaCertificate); + } + } } diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/tpm/TPM2ProvisionerStateTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/tpm/TPM2ProvisionerStateTest.java index 72845e07..6ce900c9 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/tpm/TPM2ProvisionerStateTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/tpm/TPM2ProvisionerStateTest.java @@ -1,39 +1,40 @@ package hirs.attestationca.persist.entity.tpm; import hirs.attestationca.persist.entity.manager.TPM2ProvisionerStateRepository; - -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.util.Random; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + /** * Contains unit tests for {@link TPM2ProvisionerState}. */ public class TPM2ProvisionerStateTest { - private static final Random random = new Random(); + private static final Random RANDOM_GENERATOR = new Random(); /** * Tests that the values passed to the constructor are equal to the values * returned by the getters. - * - * @throws IOException this will never happen */ @Test - public final void testTPM2ProvisionerState() throws IOException { - byte[] nonce = new byte[32]; - byte[] identityClaim = new byte[360]; - random.nextBytes(nonce); - random.nextBytes(identityClaim); + public final void testTPM2ProvisionerState() { + final int nonceSize = 32; + final int identityClaimSize = 360; + byte[] nonce = new byte[nonceSize]; + byte[] identityClaim = new byte[identityClaimSize]; + + RANDOM_GENERATOR.nextBytes(nonce); + RANDOM_GENERATOR.nextBytes(identityClaim); TPM2ProvisionerState state = new TPM2ProvisionerState(nonce, identityClaim); @@ -45,12 +46,14 @@ public class TPM2ProvisionerStateTest { * Test that the constructor throws an {@link IllegalArgumentException} when a null is * passed in for the nonce. * - * @throws IOException this will never happen + * @throws IllegalArgumentException this will never happen */ @Test - public final void testNullNonce() throws IOException { - byte[] identityClaim = new byte[360]; - random.nextBytes(identityClaim); + public final void testNullNonce() throws IllegalArgumentException { + final int identityClaimSize = 360; + byte[] identityClaim = new byte[identityClaimSize]; + + RANDOM_GENERATOR.nextBytes(identityClaim); assertThrows(IllegalArgumentException.class, () -> new TPM2ProvisionerState(null, identityClaim)); } @@ -59,12 +62,15 @@ public class TPM2ProvisionerStateTest { * Test that the constructor throws an {@link IllegalArgumentException} when a null is * passed in for the identity claim. * - * @throws IOException this will never happen + * @throws IllegalArgumentException this will never happen */ @Test - public final void testNullIdentityClaim() throws IOException { - byte[] nonce = new byte[32]; - random.nextBytes(nonce); + public final void testNullIdentityClaim() throws IllegalArgumentException { + final int nonceSize = 32; + byte[] nonce = new byte[nonceSize]; + + RANDOM_GENERATOR.nextBytes(nonce); + assertThrows(IllegalArgumentException.class, () -> new TPM2ProvisionerState(nonce, null)); } @@ -73,14 +79,17 @@ public class TPM2ProvisionerStateTest { * Test that the constructor throws an {@link IllegalArgumentException} when a nonce is * passed in that is less than 8 bytes. * - * @throws IOException this will never happen + * @throws IllegalArgumentException this will never happen */ @Test - public final void testNonceToSmall() throws IOException { - byte[] nonce = new byte[7]; - byte[] identityClaim = new byte[360]; - random.nextBytes(nonce); - random.nextBytes(identityClaim); + public final void testNonceToSmall() throws IllegalArgumentException { + final int nonceSize = 7; + final int identityClaimSize = 360; + byte[] nonce = new byte[nonceSize]; + byte[] identityClaim = new byte[identityClaimSize]; + + RANDOM_GENERATOR.nextBytes(nonce); + RANDOM_GENERATOR.nextBytes(identityClaim); assertThrows(IllegalArgumentException.class, () -> new TPM2ProvisionerState(nonce, identityClaim)); } @@ -88,19 +97,23 @@ public class TPM2ProvisionerStateTest { /** * Test that {@link TPM2ProvisionerState#getTPM2ProvisionerState( - * TPM2ProvisionerStateRepository, byte[])} works. + *TPM2ProvisionerStateRepository, byte[])} works. * {@link TPM2ProvisionerState#getTPM2ProvisionerState( - * TPM2ProvisionerStateRepository, byte[])}, null is returned. + *TPM2ProvisionerStateRepository, byte[])}, null is returned. + * * @throws IOException this will never happen */ @Test public final void testGetTPM2ProvisionerStateNominal() throws IOException { TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository = mock(TPM2ProvisionerStateRepository.class); - byte[] nonce = new byte[32]; - byte[] identityClaim = new byte[360]; - random.nextBytes(nonce); - random.nextBytes(identityClaim); + final int nonceSize = 32; + final int identityClaimSize = 360; + byte[] nonce = new byte[nonceSize]; + byte[] identityClaim = new byte[identityClaimSize]; + + RANDOM_GENERATOR.nextBytes(nonce); + RANDOM_GENERATOR.nextBytes(identityClaim); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(nonce)); Long index = dis.readLong(); @@ -116,17 +129,22 @@ public class TPM2ProvisionerStateTest { /** * Test that if a null is passed as a nonce to * {@link TPM2ProvisionerState#getTPM2ProvisionerState( - * TPM2ProvisionerStateRepository, byte[])}, null is returned. + *TPM2ProvisionerStateRepository, byte[])}, null is returned. + * * @throws IOException this will never happen */ @Test public final void testGetTPM2ProvisionerStateNullNonce() throws IOException { TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository = mock(TPM2ProvisionerStateRepository.class); - byte[] nonce = new byte[32]; - byte[] identityClaim = new byte[360]; - random.nextBytes(nonce); - random.nextBytes(identityClaim); + final int nonceSize = 32; + final int identityClaimSize = 360; + byte[] nonce = new byte[nonceSize]; + byte[] identityClaim = new byte[identityClaimSize]; + + RANDOM_GENERATOR.nextBytes(nonce); + RANDOM_GENERATOR.nextBytes(identityClaim); + DataInputStream dis = new DataInputStream(new ByteArrayInputStream(nonce)); Long index = dis.readLong(); dis.close(); @@ -139,24 +157,35 @@ public class TPM2ProvisionerStateTest { /** * Test that if a nonce that is less than 8 bytes is passed to * {@link TPM2ProvisionerState#getTPM2ProvisionerState( - * TPM2ProvisionerStateRepository, byte[])}, null is returned. + *TPM2ProvisionerStateRepository, byte[])}, null is returned. + * * @throws IOException this will never happen */ @Test public final void testGetTPM2ProvisionerStateNonceTooSmall() throws IOException { TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository = mock(TPM2ProvisionerStateRepository.class); - byte[] nonce = new byte[32]; - byte[] identityClaim = new byte[360]; - random.nextBytes(nonce); - random.nextBytes(identityClaim); + final int nonceSize = 32; + final int identityClaimSize = 360; + byte[] nonce = new byte[nonceSize]; + byte[] identityClaim = new byte[identityClaimSize]; + + RANDOM_GENERATOR.nextBytes(nonce); + RANDOM_GENERATOR.nextBytes(identityClaim); + DataInputStream dis = new DataInputStream(new ByteArrayInputStream(nonce)); Long index = dis.readLong(); dis.close(); + TPM2ProvisionerState value = new TPM2ProvisionerState(nonce, identityClaim); + when(tpm2ProvisionerStateRepository.findByFirstPartOfNonce(index)).thenReturn(value); + + final int nonce2Size = 7; TPM2ProvisionerState tpm2ProvisionerState = - TPM2ProvisionerState.getTPM2ProvisionerState(tpm2ProvisionerStateRepository, new byte[7]); + TPM2ProvisionerState.getTPM2ProvisionerState(tpm2ProvisionerStateRepository, + new byte[nonce2Size]); + assertNull(tpm2ProvisionerState); } } diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/AbstractUserdefinedEntityTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/AbstractUserdefinedEntityTest.java index 56ff99c8..bd4786fc 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/AbstractUserdefinedEntityTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/AbstractUserdefinedEntityTest.java @@ -33,7 +33,6 @@ import java.util.Objects; /** * Class with definitions and functions common to multiple Userdefined Entity object tests. - * */ public class AbstractUserdefinedEntityTest { @@ -41,71 +40,65 @@ public class AbstractUserdefinedEntityTest { * Location of a test (fake) SGI intermediate CA certificate. */ public static final String FAKE_SGI_INT_CA_FILE = "/certificates/fakeSGIIntermediateCA.cer"; - /** * Location of a test (fake) Intel intermediate CA certificate. */ public static final String FAKE_INTEL_INT_CA_FILE = "/certificates/fakeIntelIntermediateCA.cer"; - /** * Location of a test (fake) root CA certificate. */ public static final String FAKE_ROOT_CA_FILE = "/certificates/fakeRootCA.cer"; - /** * Hex-encoded subject key identifier for the FAKE_ROOT_CA_FILE. */ public static final String FAKE_ROOT_CA_SUBJECT_KEY_IDENTIFIER_HEX = "58ec313a1699f94c1c8c4e2c6412402b258f0177"; - - /** - * Location of a test identity certificate. - */ - private static final String TEST_IDENTITY_CERT = "/tpm/sample_identity_cert.cer"; - /** * Location of a test platform attribute cert. */ public static final String TEST_PLATFORM_CERT_1 = "/validation/platform_credentials/Intel_pc1.cer"; - /** * Location of another, slightly different platform attribute cert. */ public static final String TEST_PLATFORM_CERT_2 = "/validation/platform_credentials/Intel_pc2.cer"; - /** * Location of another, slightly different platform attribute cert. */ public static final String TEST_PLATFORM_CERT_3 = "/validation/platform_credentials/Intel_pc3.cer"; - /** * Platform cert with comma separated baseboard and chassis serial number. */ public static final String TEST_PLATFORM_CERT_4 = "/validation/platform_credentials/Intel_pc4.pem"; - /** * Another platform cert with comma separated baseboard and chassis serial number. */ public static final String TEST_PLATFORM_CERT_5 = "/validation/platform_credentials/Intel_pc5.pem"; - /** * Location of another, slightly different platform attribute cert. */ public static final String TEST_PLATFORM_CERT_6 = "/validation/platform_credentials/TPM_INTC_Platform_Cert_RSA.txt"; - - private static final Logger LOGGER = LogManager.getLogger(DeviceInfoReportTest.class); - /** * Dummy message for supply chain validation test. */ public static final String VALIDATION_MESSAGE = "Some message."; + /** + * Location of a test identity certificate. + */ + private static final String TEST_IDENTITY_CERT = "/tpm/sample_identity_cert.cer"; + private static final Logger LOGGER = LogManager.getLogger(DeviceInfoReportTest.class); + + /** + * This protected constructor was created to silence one of checkstyle errors. + */ + protected AbstractUserdefinedEntityTest() { + } /** * Construct a test certificate from the given parameters. @@ -131,13 +124,14 @@ public class AbstractUserdefinedEntityTest { * @param endorsementCredential the endorsement credentials (can be null) * @param platformCredentials the platform credentials (can be null) * @return the newly-constructed Certificate - * @throws IOException if there is a problem constructing the test certificate + * @throws IOException if there is a problem constructing the test certificate + * @throws IllegalArgumentException if there is a problem retrieving the certificate class simple name */ public static Certificate getTestCertificate( final Class certificateClass, final String filename, final EndorsementCredential endorsementCredential, final List platformCredentials) - throws IOException { + throws IOException, IllegalArgumentException { Path certPath; try { @@ -149,23 +143,17 @@ public class AbstractUserdefinedEntityTest { throw new IOException("Could not resolve path URI", e); } - switch (certificateClass.getSimpleName()) { - case "CertificateAuthorityCredential": - return new CertificateAuthorityCredential(certPath); - case "ConformanceCredential": - return new ConformanceCredential(certPath); - case "EndorsementCredential": - return new EndorsementCredential(certPath); - case "PlatformCredential": - return new PlatformCredential(certPath); - case "IssuedAttestationCertificate": - return new IssuedAttestationCertificate(certPath, - endorsementCredential, platformCredentials, false); - default: - throw new IllegalArgumentException( - String.format("Unknown certificate class %s", certificateClass.getName()) - ); - } + return switch (certificateClass.getSimpleName()) { + case "CertificateAuthorityCredential" -> new CertificateAuthorityCredential(certPath); + case "ConformanceCredential" -> new ConformanceCredential(certPath); + case "EndorsementCredential" -> new EndorsementCredential(certPath); + case "PlatformCredential" -> new PlatformCredential(certPath); + case "IssuedAttestationCertificate" -> new IssuedAttestationCertificate(certPath, + endorsementCredential, platformCredentials, false); + default -> throw new IllegalArgumentException( + String.format("Unknown certificate class %s", certificateClass.getName()) + ); + }; } /** @@ -202,8 +190,9 @@ public class AbstractUserdefinedEntityTest { public static NetworkInfo createTestNetworkInfo() { try { final String hostname = "test.hostname"; + final byte[] byteAddress = new byte[] {127, 0, 0, 1}; final InetAddress ipAddress = - InetAddress.getByAddress(new byte[] {127, 0, 0, 1}); + InetAddress.getByAddress(byteAddress); final byte[] macAddress = new byte[] {11, 22, 33, 44, 55, 66}; return new NetworkInfo(hostname, ipAddress, macAddress); @@ -294,8 +283,8 @@ public class AbstractUserdefinedEntityTest { /** * Construct a SupplyChainValidation for use in tests according to the provided parameters. * - * @param type the type of validation - * @param result the appraisal result + * @param type the type of validation + * @param result the appraisal result * @param certificates the certificates related to this validation * @return the resulting SupplyChainValidation object */ diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/CertificateTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/CertificateTest.java index 00225c6b..49edfd87 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/CertificateTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/CertificateTest.java @@ -14,18 +14,18 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.security.NoSuchProviderException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.Objects; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * This class tests functionality of the {@link Certificate} class. @@ -79,15 +79,48 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { private static final String RDN_COMMA_SEPARATED = "CN=STM TPM EK Intermediate CA 02, O=STMicroelectronics NV, C=CH"; + private static final String RDN_MULTIVALUE = "CN=Nuvoton TPM Root CA 2010+O=Nuvoton Technology Corporation+C=TW"; private static final String RDN_COMMA_SEPARATED_ORGANIZATION = "STMicroelectronics NV"; + private static final String RDN_MULTIVALUE_ORGANIZATION = "Nuvoton Technology Corporation"; private static final String EK_CERT_WITH_PADDED_BYTES = "/certificates/ek_cert_with_padded_bytes.cer"; + /** + * Construct a CertificateAuthorityCredential from the given parameters. + * + * @param filename the location of the certificate to be used + * @return the newly-constructed Certificate + * @throws IOException if there is a problem constructing the test certificate + */ + public static Certificate getTestCertificate( + final String filename) throws IOException { + return getTestCertificate(CertificateAuthorityCredential.class, filename); + } + + private static X509Certificate readX509Certificate(final String resourceName) + throws IOException { + + CertificateFactory cf; + try { + cf = CertificateFactory.getInstance("X.509"); + } catch (CertificateException e) { + throw new IOException("Cannot get X509 CertificateFactory instance", e); + } + + try (FileInputStream certInputStream = new FileInputStream(Paths.get( + Objects.requireNonNull(CertificateTest.class.getResource( + resourceName)).toURI()).toFile() + )) { + return (X509Certificate) cf.generateCertificate(certInputStream); + } catch (CertificateException | URISyntaxException e) { + throw new IOException("Cannot read certificate", e); + } + } /** * Tests that a certificate can be constructed from a byte array. @@ -103,6 +136,7 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { FAKE_ROOT_CA_FILE)).toURI()) ) ); + assertEquals( "CN=Fake Root CA", certificate.getX509Certificate().getIssuerX500Principal().getName() @@ -112,12 +146,11 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { /** * Ensure that a Certificate cannot be created from a null byte array. * - * @throws IOException if the certificate could not be constructed properly - * @throws CertificateException if there is a problem de/serializing the certificate + * @throws IllegalArgumentException if there is a problem de/serializing the certificate */ @Test public void testConstructCertFromNullByteArray() - throws IOException, CertificateException { + throws IllegalArgumentException { assertThrows(IllegalArgumentException.class, () -> new CertificateAuthorityCredential((byte[]) null)); } @@ -125,14 +158,13 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { /** * Ensure that a Certificate cannot be created from an empty byte array. * - * @throws IOException if the certificate could not be constructed properly - * @throws CertificateException if there is a problem de/serializing the certificate + * @throws IllegalArgumentException if there is a problem de/serializing the certificate */ @Test public void testConstructCertFromEmptyByteArray() - throws IOException, CertificateException { + throws IllegalArgumentException { assertThrows(IllegalArgumentException.class, () -> - new CertificateAuthorityCredential(new byte[]{})); + new CertificateAuthorityCredential(new byte[] {})); } /** @@ -147,6 +179,7 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { Paths.get(Objects.requireNonNull(this.getClass().getResource( FAKE_ROOT_CA_FILE)).toURI()) ); + assertEquals( "CN=Fake Root CA", certificate.getX509Certificate().getIssuerX500Principal().getName() @@ -156,11 +189,10 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { /** * Tests that a certificate cannot be constructed from a null path. * - * @throws IOException if there is a problem reading the cert file at the given path - * @throws URISyntaxException if there is a problem constructing the URI + * @throws IllegalArgumentException if there is a problem constructing the URI */ @Test - public void testConstructCertFromNullPath() throws URISyntaxException, IOException { + public void testConstructCertFromNullPath() throws IllegalArgumentException { assertThrows(IllegalArgumentException.class, () -> new CertificateAuthorityCredential((Path) null)); } @@ -176,6 +208,7 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { assertEquals( Certificate.CertificateType.X509_CERTIFICATE, getTestCertificate(FAKE_ROOT_CA_FILE).getCertificateType()); + assertNotEquals( Certificate.CertificateType.ATTRIBUTE_CERTIFICATE, getTestCertificate(FAKE_ROOT_CA_FILE).getCertificateType()); @@ -190,7 +223,6 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { getTestCertificate( PlatformCredential.class, TEST_PLATFORM_CERT_3).getCertificateType()); - } /** @@ -224,7 +256,6 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { "GETY42100160", ((PlatformCredential) platformCredential).getPlatformSerial() ); - } /** @@ -257,6 +288,7 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { @Test public void testX509CertificateParsingExtended() throws IOException { Certificate rootCert = getTestCertificate(INTEL_INT_CA_FILE); + assertEquals( "https://trustedservices.intel.com/" + "content/TSC/certs/TSC_SS_RootCA_Certificate.cer\n", @@ -293,7 +325,7 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { attrCertHolder.getIssuer().getNames()[0].toString(), platformCert.getIssuer() ); - assertEquals(null, platformCert.getSubject()); + assertNull(platformCert.getSubject()); assertArrayEquals(null, platformCert.getEncodedPublicKey()); assertArrayEquals(attrCertHolder.getSignature(), platformCert.getSignature()); assertEquals(attrCertHolder.getNotBefore(), platformCert.getBeginValidity()); @@ -304,12 +336,11 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { * Tests that Certificate correctly parses out non-standard fields from an X509 attribute * certificate. * - * @throws IOException if there is a problem reading the cert file at the given path - * @throws URISyntaxException if there is a problem constructing the file's URI + * @throws IOException if there is a problem reading the cert file at the given path */ @Test public void testX509AttributeCertificateParsingExtended() - throws IOException, URISyntaxException { + throws IOException { Certificate platformCert = getTestCertificate( PlatformCredential.class, TEST_PLATFORM_CERT_6); @@ -330,7 +361,10 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { public void testCertificateTrim() throws IOException, URISyntaxException { byte[] rawFileBytes = Files.readAllBytes(Paths.get(Objects.requireNonNull(CertificateTest.class .getResource(EK_CERT_WITH_PADDED_BYTES)).toURI())); - byte[] expectedCertBytes = Arrays.copyOfRange(rawFileBytes, 0, 908); + + final int finalPosition = 908; + byte[] expectedCertBytes = Arrays.copyOfRange(rawFileBytes, 0, finalPosition); + Certificate ekCert = getTestCertificate(EndorsementCredential.class, EK_CERT_WITH_PADDED_BYTES); assertEquals(new BigInteger("16842032579184247954"), ekCert.getSerialNumber()); @@ -352,6 +386,7 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { URISyntaxException { byte[] rawFileBytes = Files.readAllBytes(Paths.get(Objects.requireNonNull(CertificateTest.class .getResource(EK_CERT_WITH_PADDED_BYTES)).toURI())); + assertThrows(IllegalArgumentException.class, () -> new EndorsementCredential(Arrays.copyOfRange(rawFileBytes, 0, 2)), ".* No certificate length field could be found\\."); @@ -369,8 +404,10 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { URISyntaxException { byte[] rawFileBytes = Files.readAllBytes(Paths.get(Objects.requireNonNull(CertificateTest.class .getResource(EK_CERT_WITH_PADDED_BYTES)).toURI())); + + final int finalPosition = 4; assertThrows(IllegalArgumentException.class, () -> - new EndorsementCredential(Arrays.copyOfRange(rawFileBytes, 0, 4)), + new EndorsementCredential(Arrays.copyOfRange(rawFileBytes, 0, finalPosition)), ".* Certificate is nothing more than ASN.1 Sequence\\\\."); } @@ -386,8 +423,10 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { URISyntaxException { byte[] rawFileBytes = Files.readAllBytes(Paths.get(Objects.requireNonNull(CertificateTest.class .getResource(EK_CERT_WITH_PADDED_BYTES)).toURI())); + + final int finalPosition = 42; assertThrows(IllegalArgumentException.class, () -> - new EndorsementCredential(Arrays.copyOfRange(rawFileBytes, 0, 42)), + new EndorsementCredential(Arrays.copyOfRange(rawFileBytes, 0, finalPosition)), ".* Value of certificate length field extends beyond" + " length of provided certificate\\."); } @@ -395,13 +434,11 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { /** * Tests that the equals method on {@link Certificate} works as expected. * - * @throws IOException if the certificate could not be constructed properly - * @throws CertificateException if there is a problem with the KeyStore or de/serializing the - * certificate - * @throws URISyntaxException if there is a problem constructing the path to the certificate + * @throws IOException if the certificate could not be constructed properly + * @throws URISyntaxException if there is a problem constructing the path to the certificate */ @Test - public void testEquals() throws CertificateException, IOException, URISyntaxException { + public void testEquals() throws IOException, URISyntaxException { assertEquals( getTestCertificate(FAKE_ROOT_CA_FILE), getTestCertificate(FAKE_ROOT_CA_FILE) @@ -439,15 +476,10 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { /** * Tests that the isIssuer method on {@link Certificate} works as expected. * - * @throws IOException if the certificate could not be constructed properly - * @throws CertificateException if there is a problem with the KeyStore or de/serializing the - * certificate - * @throws NoSuchProviderException if the Bouncy Castle security provider is unavailable - * @throws URISyntaxException if there is a problem constructing the path to the certificate + * @throws IOException if the certificate could not be constructed properly */ @Test - public void testIsIssuer() throws CertificateException, IOException, NoSuchProviderException, - URISyntaxException { + public void testIsIssuer() throws IOException { Certificate issuerCert = getTestCertificate(FAKE_ROOT_CA_FILE); Certificate cert = getTestCertificate(INT_CA_CERT02); @@ -458,13 +490,11 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { /** * Tests that the hashCode method on {@link Certificate} works as expected. * - * @throws IOException if the certificate could not be constructed properly - * @throws CertificateException if there is a problem with the KeyStore or de/serializing the - * certificate - * @throws URISyntaxException if there is a problem constructing the path to the certificate + * @throws IOException if the certificate could not be constructed properly + * @throws URISyntaxException if there is a problem constructing the path to the certificate */ @Test - public void testHashCode() throws CertificateException, IOException, URISyntaxException { + public void testHashCode() throws IOException, URISyntaxException { assertEquals( getTestCertificate(FAKE_ROOT_CA_FILE).hashCode(), getTestCertificate(FAKE_ROOT_CA_FILE).hashCode() @@ -492,36 +522,4 @@ public class CertificateTest extends AbstractUserdefinedEntityTest { ).hashCode() ); } - - /** - * Construct a CertificateAuthorityCredential from the given parameters. - * - * @param filename the location of the certificate to be used - * @return the newly-constructed Certificate - * @throws IOException if there is a problem constructing the test certificate - */ - public static Certificate getTestCertificate( - final String filename) throws IOException { - return getTestCertificate(CertificateAuthorityCredential.class, filename); - } - - private static X509Certificate readX509Certificate(final String resourceName) - throws IOException { - - CertificateFactory cf; - try { - cf = CertificateFactory.getInstance("X.509"); - } catch (CertificateException e) { - throw new IOException("Cannot get X509 CertificateFactory instance", e); - } - - try (FileInputStream certInputStream = new FileInputStream(Paths.get( - Objects.requireNonNull(CertificateTest.class.getResource( - resourceName)).toURI()).toFile() - )) { - return (X509Certificate) cf.generateCertificate(certInputStream); - } catch (CertificateException | URISyntaxException e) { - throw new IOException("Cannot read certificate", e); - } - } } diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/DeviceTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/DeviceTest.java index 7f7a54fc..0053338f 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/DeviceTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/DeviceTest.java @@ -11,7 +11,6 @@ import static org.junit.jupiter.api.Assertions.assertNull; /** * This is the test class for the Device class. - * */ public final class DeviceTest extends AbstractUserdefinedEntityTest { @@ -113,7 +112,7 @@ public final class DeviceTest extends AbstractUserdefinedEntityTest { */ @Test public void testSetHealthStatus() { - final Device device = new Device("test-device", null, HealthStatus.UNKNOWN, + final Device device = new Device("test-device", null, HealthStatus.UNKNOWN, AppraisalStatus.Status.UNKNOWN, null, false, null, null); device.setHealthStatus(HealthStatus.TRUSTED); diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/PolicySettingsTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/PolicySettingsTest.java index dfd56a55..33f2a595 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/PolicySettingsTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/PolicySettingsTest.java @@ -1,10 +1,11 @@ package hirs.attestationca.persist.entity.userdefined; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Unit test class for PolicySettings. */ diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/SupplyChainValidationSummaryTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/SupplyChainValidationSummaryTest.java index acb3fe48..4b2d07c0 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/SupplyChainValidationSummaryTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/SupplyChainValidationSummaryTest.java @@ -26,16 +26,28 @@ public class SupplyChainValidationSummaryTest extends AbstractUserdefinedEntityT /** * Test device. - * */ private Device device; /** * List of test certificates. - * */ private List certificates; + /** + * Utility method for getting a Device that can be used for + * testing. + * + * @param name name for the Device + * @return device + */ + public static Device getTestDevice(final String name) { + final DeviceInfoReport deviceInfo = getTestDeviceInfoReport(); + return new Device(name, deviceInfo, HealthStatus.UNKNOWN, + AppraisalStatus.Status.UNKNOWN, null, + false, null, null); + } + /** * Create a set of certificates and a device for use by these tests. * @@ -152,28 +164,12 @@ public class SupplyChainValidationSummaryTest extends AbstractUserdefinedEntityT assertNotNull(twoBadValidations.getCreateTime()); } - /** - * Utility method for getting a Device that can be used for - * testing. - * - * @param name name for the Device - * - * @return device - */ - public static Device getTestDevice(final String name) { - final DeviceInfoReport deviceInfo = getTestDeviceInfoReport(); - return new Device(name, deviceInfo, HealthStatus.UNKNOWN, - AppraisalStatus.Status.UNKNOWN, null, - false, null, null); - } - /** * Utility method for getting a SupplyChainValidationSummary that can be used for * testing. * * @param numberOfValidations number of validations for the SupplyChainValidationSummary - * @param numFail number of failed validations - * + * @param numFail number of failed validations * @return device */ private SupplyChainValidationSummary getTestSummary( @@ -199,10 +195,7 @@ public class SupplyChainValidationSummaryTest extends AbstractUserdefinedEntityT Collection validations = new HashSet<>(); for (int i = 0; i < numberOfValidations; i++) { - boolean successful = true; - if (i >= (numberOfValidations - numFail)) { - successful = false; - } + boolean successful = i < (numberOfValidations - numFail); AppraisalStatus.Status result = AppraisalStatus.Status.FAIL; if (successful) { diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/SupplyChainValidationTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/SupplyChainValidationTest.java index 4a3e1a53..f8353591 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/SupplyChainValidationTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/SupplyChainValidationTest.java @@ -14,6 +14,22 @@ import static org.junit.jupiter.api.Assertions.assertThrows; */ class SupplyChainValidationTest extends AbstractUserdefinedEntityTest { + /** + * Construct a SupplyChainValidation for use in tests. It will have a validation + * type of ENDORSEMENT_CREDENTIAL, will represent a successful validation, and will use + * multiple test certificates. + * + * @return the test SupplyChainValidation + * @throws IOException if there is a problem deserializing certificates + */ + public static SupplyChainValidation getTestSupplyChainValidation() throws IOException { + return getTestSupplyChainValidation( + SupplyChainValidation.ValidationType.ENDORSEMENT_CREDENTIAL, + AppraisalStatus.Status.PASS, + getAllTestCertificates() + ); + } + /** * Test that this class' getter methods work properly. * @@ -36,10 +52,10 @@ class SupplyChainValidationTest extends AbstractUserdefinedEntityTest { /** * Test that a SupplyChainValidation can't be instantiated with a null validation type. * - * @throws IOException if there is a problem deserializing certificates + * @throws IllegalArgumentException if there is a problem deserializing certificates */ @Test - public void testNullValidationType() throws IOException { + public void testNullValidationType() throws IllegalArgumentException { assertThrows(IllegalArgumentException.class, () -> new SupplyChainValidation( null, @@ -52,10 +68,10 @@ class SupplyChainValidationTest extends AbstractUserdefinedEntityTest { /** * Test that a SupplyChainValidation can't be instantiated with a null certificate list. * - * @throws IOException if there is a problem deserializing certificates + * @throws IllegalArgumentException if there is a problem deserializing certificates */ @Test - public void testNullCertificates() throws IOException { + public void testNullCertificates() throws IllegalArgumentException { assertThrows(IllegalArgumentException.class, () -> new SupplyChainValidation( SupplyChainValidation.ValidationType.ENDORSEMENT_CREDENTIAL, @@ -79,20 +95,4 @@ class SupplyChainValidationTest extends AbstractUserdefinedEntityTest { VALIDATION_MESSAGE ); } - - /** - * Construct a SupplyChainValidation for use in tests. It will have a validation - * type of ENDORSEMENT_CREDENTIAL, will represent a successful validation, and will use - * multiple test certificates. - * - * @return the test SupplyChainValidation - * @throws IOException if there si - */ - public static SupplyChainValidation getTestSupplyChainValidation() throws IOException { - return getTestSupplyChainValidation( - SupplyChainValidation.ValidationType.ENDORSEMENT_CREDENTIAL, - AppraisalStatus.Status.PASS, - getAllTestCertificates() - ); - } } diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/CertificateAuthorityCredentialTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/CertificateAuthorityCredentialTest.java index b0154d48..0481d449 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/CertificateAuthorityCredentialTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/CertificateAuthorityCredentialTest.java @@ -2,8 +2,6 @@ package hirs.attestationca.persist.entity.userdefined.certificate; import hirs.attestationca.persist.entity.userdefined.AbstractUserdefinedEntityTest; import org.apache.commons.codec.binary.Hex; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.Test; import java.io.IOException; @@ -12,6 +10,9 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.security.cert.CertificateException; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + /** * Tests that CertificateAuthorityCredential properly parses its fields. */ @@ -21,10 +22,10 @@ public class CertificateAuthorityCredentialTest extends AbstractUserdefinedEntit * Tests that a CertificateAuthorityCredential can be created from an X.509 certificate and * that the subject key identifier is correctly extracted. * - * @throws IOException if the certificate could not be constructed properly + * @throws IOException if the certificate could not be constructed properly * @throws CertificateException if there is a problem with the KeyStore or de/serializing the * certificate - * @throws URISyntaxException if there is a problem constructing the path to the certificate + * @throws URISyntaxException if there is a problem constructing the path to the certificate */ @Test public void testGetSubjectKeyIdentifier() diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/EndorsementCredentialTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/EndorsementCredentialTest.java index f176b4b4..41467ec6 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/EndorsementCredentialTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/EndorsementCredentialTest.java @@ -1,10 +1,7 @@ package hirs.attestationca.persist.entity.userdefined.certificate; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.assertNotNull; - +import hirs.attestationca.persist.entity.userdefined.certificate.attributes.TPMSecurityAssertions; +import hirs.attestationca.persist.entity.userdefined.certificate.attributes.TPMSpecification; import org.junit.jupiter.api.Test; import java.io.IOException; @@ -12,8 +9,11 @@ import java.math.BigInteger; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import hirs.attestationca.persist.entity.userdefined.certificate.attributes.TPMSecurityAssertions; -import hirs.attestationca.persist.entity.userdefined.certificate.attributes.TPMSpecification; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for the EndorsementCredential class. @@ -32,6 +32,7 @@ public class EndorsementCredentialTest { /** * Tests the successful parsing of an EC using a test cert from STM. + * * @throws IOException test failed due to invalid certificate parsing */ @Test @@ -65,6 +66,7 @@ public class EndorsementCredentialTest { /** * Tests the successful parsing of an EC using a test cert from NUC 1. + * * @throws IOException test failed due to invalid certificate parsing */ @Test @@ -99,6 +101,7 @@ public class EndorsementCredentialTest { /** * Tests the successful parsing of an EC using a test cert from NUC 1, * using the static builder method. + * * @throws IOException test failed due to invalid certificate parsing */ @Test @@ -134,6 +137,7 @@ public class EndorsementCredentialTest { /** * Tests the successful parsing of an EC using a test cert from NUC 2. + * * @throws IOException test failed due to invalid certificate parsing */ @Test @@ -167,6 +171,7 @@ public class EndorsementCredentialTest { /** * Tests that different EC certificates aren't the same, even if their attributes are the same. + * * @throws IOException test failed due to invalid certificate parsing */ @Test diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/PlatformCredentialTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/PlatformCredentialTest.java index aec780e4..355fa903 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/PlatformCredentialTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/PlatformCredentialTest.java @@ -12,7 +12,6 @@ import org.apache.commons.codec.binary.Hex; import org.bouncycastle.util.encoders.Base64; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.net.URISyntaxException; @@ -23,6 +22,8 @@ import java.util.Calendar; import java.util.List; import java.util.TimeZone; +import static org.junit.jupiter.api.Assertions.fail; + /** * Tests that a PlatformCredential parses its fields correctly. */ @@ -152,7 +153,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { try { new PlatformCredential(certPath); - //fail if it manage to parse the certificate + //fail if it manages to parse the certificate fail("Invalid certificate was parsed."); } catch (IOException ex) { if (ex == null || ex.getMessage().isEmpty()) { @@ -169,7 +170,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { * extension but is missing the subject alternative name extension. This certificate * also has a policy extension, but it is not currently parsed. * - * @throws IOException if an IO error occurs during processing + * @throws IOException if an IO error occurs during processing * @throws URISyntaxException if there is a problem constructing the cert's URI */ @Test @@ -178,12 +179,26 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { Path certPath = Paths.get(resource.toURI()); PlatformCredential credential = new PlatformCredential(certPath); + Calendar calendar = Calendar.getInstance(); calendar.setTimeZone(TimeZone.getTimeZone("UTC")); - calendar.set(2017, 2, 23, 22, 34, 33); + final int year1 = 2017; + final int month1 = 2; + final int day1 = 23; + final int hour1 = 22; + final int minute1 = 34; + final int second1 = 33; + calendar.set(year1, month1, day1, hour1, minute1, second1); calendar.set(Calendar.MILLISECOND, 0); Assertions.assertEquals(credential.getBeginValidity().getTime(), calendar.getTime().getTime()); - calendar.set(2030, 11, 31, 23, 59, 59); + + final int year2 = 2030; + final int month2 = 11; + final int day2 = 31; + final int hour2 = 23; + final int minute2 = 59; + final int second2 = 59; + calendar.set(year2, month2, day2, hour2, minute2, second2); Assertions.assertEquals(credential.getEndValidity().getTime(), calendar.getTime().getTime()); Assertions.assertNotNull(credential.getAttributeCertificate()); @@ -193,8 +208,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { Assertions.assertEquals(sigStr.toUpperCase(), EXPECTED_CERT_SIGNATURE_FOR_CERT_2); String issuer = Certificate.getAttributeCertificateIssuerNames( - credential.getAttributeCertificate().getAcinfo().getIssuer() - )[0].toString(); + credential.getAttributeCertificate().getAcinfo().getIssuer())[0].toString(); Assertions.assertEquals(credential.getManufacturer(), "Intel"); Assertions.assertEquals(credential.getModel(), "DE3815TYKH"); @@ -206,7 +220,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { Assertions.assertEquals(credential.getCredentialType(), "TCPA Trusted Platform Endorsement"); // the platform certificate in this test does not contain the following information - Assertions.assertEquals(credential.getPlatformSerial(), null); + Assertions.assertNull(credential.getPlatformSerial()); Assertions.assertEquals(credential.getMajorVersion(), 1); Assertions.assertEquals(credential.getMinorVersion(), 2); Assertions.assertEquals(credential.getRevisionLevel(), 1); @@ -218,7 +232,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { * extension but is missing the subject alternative name extension. This certificate * also has a policy extension, but it is not currently parsed. * - * @throws IOException if an IO error occurs during processing + * @throws IOException if an IO error occurs during processing * @throws URISyntaxException if there is a problem constructing the cert's URI */ @Test @@ -229,10 +243,23 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { PlatformCredential credential = new PlatformCredential(certPath); Calendar calendar = Calendar.getInstance(); calendar.setTimeZone(TimeZone.getTimeZone("UTC")); - calendar.set(2017, 2, 23, 22, 34, 33); + final int year1 = 2017; + final int month1 = 2; + final int day1 = 23; + final int hour1 = 22; + final int minute1 = 34; + final int second1 = 33; + calendar.set(year1, month1, day1, hour1, minute1, second1); calendar.set(Calendar.MILLISECOND, 0); Assertions.assertEquals(credential.getBeginValidity().getTime(), calendar.getTime().getTime()); - calendar.set(2030, 11, 31, 23, 59, 59); + + final int year2 = 2030; + final int month2 = 11; + final int day2 = 31; + final int hour2 = 23; + final int minute2 = 59; + final int second2 = 59; + calendar.set(year2, month2, day2, hour2, minute2, second2); Assertions.assertEquals(credential.getEndValidity().getTime(), calendar.getTime().getTime()); Assertions.assertNotNull(credential.getAttributeCertificate()); @@ -255,7 +282,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { Assertions.assertEquals(credential.getCredentialType(), "TCPA Trusted Platform Endorsement"); // the platform certificate in this test does not contain the following information - Assertions.assertEquals(credential.getPlatformSerial(), null); + Assertions.assertNull(credential.getPlatformSerial()); Assertions.assertEquals(credential.getMajorVersion(), 1); Assertions.assertEquals(credential.getMinorVersion(), 2); Assertions.assertEquals(credential.getRevisionLevel(), 1); @@ -266,7 +293,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { * Tests the parsing of a platform credential that has a combined baseboard and chassis * serial number in one attribute can be parsed. * - * @throws IOException if an IO error occurs during processing + * @throws IOException if an IO error occurs during processing * @throws URISyntaxException if there is a problem constructing the cert's URI */ @Test @@ -278,10 +305,23 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { Calendar calendar = Calendar.getInstance(); calendar.setTimeZone(TimeZone.getTimeZone("UTC")); - calendar.set(2017, 3, 21, 17, 5, 29); + final int year1 = 2017; + final int month1 = 3; + final int day1 = 21; + final int hour1 = 17; + final int minute1 = 5; + final int second1 = 29; + calendar.set(year1, month1, day1, hour1, minute1, second1); calendar.set(Calendar.MILLISECOND, 0); Assertions.assertEquals(credential.getBeginValidity().getTime(), calendar.getTime().getTime()); - calendar.set(2030, 11, 31, 23, 59, 59); + + final int year2 = 2030; + final int month2 = 11; + final int day2 = 31; + final int hour2 = 23; + final int minute2 = 59; + final int second2 = 59; + calendar.set(year2, month2, day2, hour2, minute2, second2); Assertions.assertEquals(credential.getEndValidity().getTime(), calendar.getTime().getTime()); Assertions.assertNotNull(credential.getAttributeCertificate()); @@ -311,7 +351,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { * Tests the parsing another platform credential that has a combined baseboard and chassis * serial number in one attribute can be parsed. * - * @throws IOException if an IO error occurs during processing + * @throws IOException if an IO error occurs during processing * @throws URISyntaxException if there is a problem constructing the cert's URI */ @Test @@ -323,10 +363,23 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { Calendar calendar = Calendar.getInstance(); calendar.setTimeZone(TimeZone.getTimeZone("UTC")); - calendar.set(2017, 3, 21, 17, 5, 30); + final int year1 = 2017; + final int month1 = 3; + final int day1 = 21; + final int hour1 = 17; + final int minute1 = 5; + final int second1 = 30; + calendar.set(year1, month1, day1, hour1, minute1, second1); calendar.set(Calendar.MILLISECOND, 0); Assertions.assertEquals(credential.getBeginValidity().getTime(), calendar.getTime().getTime()); - calendar.set(2030, 11, 31, 23, 59, 59); + + final int year2 = 2030; + final int month2 = 11; + final int day2 = 31; + final int hour2 = 23; + final int minute2 = 59; + final int second2 = 59; + calendar.set(year2, month2, day2, hour2, minute2, second2); Assertions.assertEquals(credential.getEndValidity().getTime(), calendar.getTime().getTime()); Assertions.assertNotNull(credential.getAttributeCertificate()); @@ -355,7 +408,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { /** * Tests isIssuer of a platform credential. * - * @throws IOException if an IO error occurs during processing + * @throws IOException if an IO error occurs during processing * @throws URISyntaxException if there is a problem constructing the cert's URI */ @Test @@ -376,7 +429,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { /** * Tests platform Configuration Values. * - * @throws IOException if an IO error occurs during processing + * @throws IOException if an IO error occurs during processing * @throws URISyntaxException if there is a problem constructing the cert's URI */ @Test @@ -394,41 +447,36 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { Assertions.fail("Component Identifier is empty."); } - Assertions.assertEquals(allComponents.size(), 7); + final int expectedComponentsSize = 7; + Assertions.assertEquals(expectedComponentsSize, allComponents.size()); ComponentIdentifier component; //Check component #2 - component = (ComponentIdentifier) allComponents.get(1); - Assertions.assertTrue(component.getComponentManufacturer() - .getString() - .equals("Intel Corporation")); - Assertions.assertTrue(component.getComponentModel() - .getString() - .equals("NUC7i5DNB")); - Assertions.assertTrue(component.getComponentSerial() - .getString() - .equals("BTDN732000QM")); + component = allComponents.get(1); + Assertions.assertEquals("Intel Corporation", component.getComponentManufacturer() + .getString()); + Assertions.assertEquals("NUC7i5DNB", component.getComponentModel() + .getString()); + Assertions.assertEquals("BTDN732000QM", component.getComponentSerial() + .getString()); //Check component #3 - component = (ComponentIdentifier) allComponents.get(2); - Assertions.assertTrue(component.getComponentManufacturer() - .getString() - .equals("Intel(R) Corporation")); - Assertions.assertTrue(component.getComponentModel().getString().equals("Core i5")); + component = allComponents.get(2); + Assertions.assertEquals("Intel(R) Corporation", component.getComponentManufacturer() + .getString()); + Assertions.assertEquals("Core i5", component.getComponentModel().getString()); Assertions.assertTrue(component.getFieldReplaceable().isTrue()); //Check component #5 - component = (ComponentIdentifier) allComponents.get(4); - Assertions.assertTrue(component.getComponentModel() - .getString() - .equals("Ethernet Connection I219-LM")); - Assertions.assertTrue(component.getComponentAddress().get(0) + final int component5Position = 4; + component = allComponents.get(component5Position); + Assertions.assertEquals("Ethernet Connection I219-LM", component.getComponentModel() + .getString()); + Assertions.assertEquals("8c:0f:6f:72:c6:c5", component.getComponentAddress().get(0) .getAddressValue() - .getString() - .equals("8c:0f:6f:72:c6:c5")); - Assertions.assertTrue(component.getComponentAddress().get(0) - .getAddressTypeValue() - .equals("ethernet mac")); + .getString()); + Assertions.assertEquals("ethernet mac", component.getComponentAddress().get(0) + .getAddressTypeValue()); //Check Platform Properties List platformProperties = platformConfig.getPlatformProperties(); @@ -441,22 +489,22 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { PlatformProperty property; //Check property #1 - property = (PlatformProperty) platformProperties.get(0); - Assertions.assertTrue(property.getPropertyName().getString().equals("vPro")); - Assertions.assertTrue(property.getPropertyValue().getString().equals("true")); + property = platformProperties.get(0); + Assertions.assertEquals("vPro", property.getPropertyName().getString()); + Assertions.assertEquals("true", property.getPropertyValue().getString()); //Check property #2 - property = (PlatformProperty) platformProperties.get(1); - Assertions.assertTrue(property.getPropertyName().getString().equals("AMT")); - Assertions.assertTrue(property.getPropertyValue().getString().equals("true")); + property = platformProperties.get(1); + Assertions.assertEquals("AMT", property.getPropertyName().getString()); + Assertions.assertEquals("true", property.getPropertyValue().getString()); //Check Platform Properties URI URIReference platformPropertyUri = platformConfig.getPlatformPropertiesUri(); Assertions.assertNotNull(platformPropertyUri); - Assertions.assertTrue(platformPropertyUri.getUniformResourceIdentifier() - .getString() - .equals("https://www.intel.com/platformproperties.xml")); + Assertions.assertEquals("https://www.intel.com/platformproperties.xml", + platformPropertyUri.getUniformResourceIdentifier() + .getString()); Assertions.assertNull(platformPropertyUri.getHashAlgorithm()); Assertions.assertNull(platformPropertyUri.getHashValue()); } @@ -464,7 +512,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { /** * Tests Platform Configuration Values. View platform Properties * - * @throws IOException if an IO error occurs during processing + * @throws IOException if an IO error occurs during processing * @throws URISyntaxException if there is a problem constructing the cert's URI */ @Test @@ -489,20 +537,20 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { PlatformProperty property; //Check property #1 - property = (PlatformProperty) platformProperties.get(0); - Assertions.assertTrue(property.getPropertyName().getString().equals("vPro")); - Assertions.assertTrue(property.getPropertyValue().getString().equals("true")); + property = platformProperties.get(0); + Assertions.assertEquals("vPro", property.getPropertyName().getString()); + Assertions.assertEquals("true", property.getPropertyValue().getString()); //Check property #2 - property = (PlatformProperty) platformProperties.get(1); - Assertions.assertTrue(property.getPropertyName().getString().equals("AMT")); - Assertions.assertTrue(property.getPropertyValue().getString().equals("true")); + property = platformProperties.get(1); + Assertions.assertEquals("AMT", property.getPropertyName().getString()); + Assertions.assertEquals("true", property.getPropertyValue().getString()); } /** * Tests Platform Configuration Values. View platform Properties * - * @throws IOException if an IO error occurs during processing + * @throws IOException if an IO error occurs during processing * @throws URISyntaxException if there is a problem constructing the cert's URI */ @Test @@ -520,29 +568,25 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { Assertions.fail("Component Identifier is empty."); } - Assertions.assertEquals(allComponents.size(), 3); + final int expectedComponentsSize = 3; + Assertions.assertEquals(expectedComponentsSize, allComponents.size()); ComponentIdentifier component; //Check component #2 - component = (ComponentIdentifier) allComponents.get(1); - Assertions.assertTrue(component.getComponentManufacturer() - .getString() - .equals("Intel(R) Corporation")); - Assertions.assertTrue(component.getComponentModel() - .getString() - .equals("Intel(R) Core(TM) i5-7300U CPU @ 2.60GHz")); + component = allComponents.get(1); + Assertions.assertEquals("Intel(R) Corporation", component.getComponentManufacturer() + .getString()); + Assertions.assertEquals("Intel(R) Core(TM) i5-7300U CPU @ 2.60GHz", component.getComponentModel() + .getString()); //Check component #3 - component = (ComponentIdentifier) allComponents.get(2); - Assertions.assertTrue(component.getComponentModel() - .getString() - .equals("BIOS")); - Assertions.assertTrue(component.getComponentSerial() - .getString() - .equals(ComponentIdentifier.NOT_SPECIFIED_COMPONENT)); - Assertions.assertTrue(component.getComponentRevision() - .getString() - .equals("DNKBLi5v.86A.0019.2017.0804.1146")); + component = allComponents.get(2); + Assertions.assertEquals("BIOS", component.getComponentModel() + .getString()); + Assertions.assertEquals(ComponentIdentifier.NOT_SPECIFIED_COMPONENT, component.getComponentSerial() + .getString()); + Assertions.assertEquals("DNKBLi5v.86A.0019.2017.0804.1146", component.getComponentRevision() + .getString()); //Check Platform Properties List platformProperties = platformConfig.getPlatformProperties(); @@ -556,26 +600,26 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { URIReference platformPropertyUri = platformConfig.getPlatformPropertiesUri(); Assertions.assertNotNull(platformPropertyUri); - Assertions.assertTrue(platformPropertyUri.getUniformResourceIdentifier() - .getString() - .equals("https://www.intel.com/platformproperties.xml")); + Assertions.assertEquals("https://www.intel.com/platformproperties.xml", + platformPropertyUri.getUniformResourceIdentifier() + .getString()); Assertions.assertNull(platformPropertyUri.getHashAlgorithm()); Assertions.assertNull(platformPropertyUri.getHashValue()); //Test TBBSecurityAssertion TBBSecurityAssertion tbbSec = platformCert.getTBBSecurityAssertion(); Assertions.assertNotNull(tbbSec); - Assertions.assertTrue(tbbSec.getCcInfo().getVersion().getString().equals("3.1")); - Assertions.assertTrue(tbbSec.getCcInfo().getProfileOid().getId().equals("1.2.3.4.5.6")); - Assertions.assertTrue(tbbSec.getFipsLevel().getVersion().getString().equals("140-2")); - Assertions.assertTrue(tbbSec.getIso9000Uri().getString() - .equals("https://www.intel.com/isocertification.pdf")); + Assertions.assertEquals("3.1", tbbSec.getCcInfo().getVersion().getString()); + Assertions.assertEquals("1.2.3.4.5.6", tbbSec.getCcInfo().getProfileOid().getId()); + Assertions.assertEquals("140-2", tbbSec.getFipsLevel().getVersion().getString()); + Assertions.assertEquals("https://www.intel.com/isocertification.pdf", + tbbSec.getIso9000Uri().getString()); } /** * Tests Platform Configuration Values. View platform Properties * - * @throws IOException if an IO error occurs during processing + * @throws IOException if an IO error occurs during processing * @throws URISyntaxException if there is a problem constructing the cert's URI */ @Test @@ -593,28 +637,26 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { Assertions.fail("Component Identifier is empty."); } - Assertions.assertEquals(allComponents.size(), 7); + final int expectedComponentsSize = 7; + Assertions.assertEquals(expectedComponentsSize, allComponents.size()); ComponentIdentifier component; //Check component #1 - component = (ComponentIdentifier) allComponents.get(0); - Assertions.assertTrue(component.getComponentModel() - .getString() - .equals("NUC7i5DNB")); - Assertions.assertTrue(component.getComponentRevision() - .getString() - .equals("J57626-401")); + component = allComponents.get(0); + Assertions.assertEquals("NUC7i5DNB", component.getComponentModel() + .getString()); + Assertions.assertEquals("J57626-401", component.getComponentRevision() + .getString()); //Check component #7 - component = (ComponentIdentifier) allComponents.get(6); + final int component7Position = 6; + component = allComponents.get(component7Position); Assertions.assertTrue(component.getComponentAddress().size() > 0); - Assertions.assertTrue(component.getComponentAddress().get(0) + Assertions.assertEquals("8c:0f:6f:72:c6:c5", component.getComponentAddress().get(0) .getAddressValue() - .getString() - .equals("8c:0f:6f:72:c6:c5")); - Assertions.assertTrue(component.getComponentAddress().get(0) - .getAddressTypeValue() - .equals("ethernet mac")); + .getString()); + Assertions.assertEquals("ethernet mac", component.getComponentAddress().get(0) + .getAddressTypeValue()); //Check Platform Properties List platformProperties = platformConfig.getPlatformProperties(); @@ -628,27 +670,27 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { URIReference platformPropertyUri = platformConfig.getPlatformPropertiesUri(); Assertions.assertNotNull(platformPropertyUri); - Assertions.assertTrue(platformPropertyUri.getUniformResourceIdentifier() - .getString() - .equals("https://www.intel.com/platformproperties.xml")); + Assertions.assertEquals("https://www.intel.com/platformproperties.xml", + platformPropertyUri.getUniformResourceIdentifier() + .getString()); Assertions.assertNull(platformPropertyUri.getHashAlgorithm()); Assertions.assertNull(platformPropertyUri.getHashValue()); //Test TBBSecurityAssertion TBBSecurityAssertion tbbSec = platformCert.getTBBSecurityAssertion(); Assertions.assertNotNull(tbbSec); - Assertions.assertTrue(tbbSec.getCcInfo().getVersion().getString().equals("3.1")); - Assertions.assertTrue(tbbSec.getCcInfo().getProfileOid().getId().equals("1.2.3.4.5.6")); - Assertions.assertTrue(tbbSec.getFipsLevel().getVersion().getString().equals("140-2")); - Assertions.assertTrue(tbbSec.getIso9000Uri().getString() - .equals("https://www.intel.com/isocertification.pdf")); + Assertions.assertEquals("3.1", tbbSec.getCcInfo().getVersion().getString()); + Assertions.assertEquals("1.2.3.4.5.6", tbbSec.getCcInfo().getProfileOid().getId()); + Assertions.assertEquals("140-2", tbbSec.getFipsLevel().getVersion().getString()); + Assertions.assertEquals("https://www.intel.com/isocertification.pdf", + tbbSec.getIso9000Uri().getString()); } /** * Tests Platform Configuration Values. View platform Properties * - * @throws IOException if an IO error occurs during processing + * @throws IOException if an IO error occurs during processing * @throws URISyntaxException if there is a problem constructing the cert's URI */ @Test @@ -663,37 +705,41 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { //Check component identifier List allComponents = platformConfig.getComponentIdentifier(); Assertions.assertFalse(allComponents.isEmpty()); - ComponentIdentifier component = allComponents.get(5); + + final int component6Position = 5; + ComponentIdentifier component = allComponents.get(component6Position); Assertions.assertTrue(component.isVersion2()); List platformProperties = platformConfig.getPlatformProperties(); if (platformProperties.isEmpty()) { Assertions.fail("Platform Properties is empty."); } - Assertions.assertEquals(platformProperties.size(), 3); + + final int platformPropSize = 3; + Assertions.assertEquals(platformPropSize, platformProperties.size()); PlatformProperty property; //Check property #1 - property = (PlatformProperty) platformProperties.get(0); - Assertions.assertTrue(property.getPropertyName().getString().equals("AMT")); - Assertions.assertTrue(property.getPropertyValue().getString().equals("true")); + property = platformProperties.get(0); + Assertions.assertEquals("AMT", property.getPropertyName().getString()); + Assertions.assertEquals("true", property.getPropertyValue().getString()); //Check property #2 - property = (PlatformProperty) platformProperties.get(1); - Assertions.assertTrue(property.getPropertyName().getString().equals("vPro Enabled")); - Assertions.assertTrue(property.getPropertyValue().getString().equals("true")); + property = platformProperties.get(1); + Assertions.assertEquals("vPro Enabled", property.getPropertyName().getString()); + Assertions.assertEquals("true", property.getPropertyValue().getString()); //Check property #3 - property = (PlatformProperty) platformProperties.get(2); - Assertions.assertTrue(property.getPropertyName().getString().equals("DropShip Enabled")); - Assertions.assertTrue(property.getPropertyValue().getString().equals("false")); + property = platformProperties.get(2); + Assertions.assertEquals("DropShip Enabled", property.getPropertyName().getString()); + Assertions.assertEquals("false", property.getPropertyValue().getString()); } /** * Tests Platform Configuration Values. View platform Properties * - * @throws IOException if an IO error occurs during processing + * @throws IOException if an IO error occurs during processing * @throws URISyntaxException if there is a problem constructing the cert's URI */ @Test @@ -705,7 +751,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { PlatformCredential platformCert = new PlatformCredential(certPath); PlatformConfiguration platformConfig = platformCert.getPlatformConfiguration(); - Assertions.assertTrue(platformConfig instanceof PlatformConfigurationV2); + Assertions.assertInstanceOf(PlatformConfigurationV2.class, platformConfig); Assertions.assertEquals(platformConfig.getPlatformPropertiesUri() .getUniformResourceIdentifier().toString(), "https://www.intel.com/platformproperties.xml"); @@ -721,7 +767,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { * Tests Platform Configuration Values. View platform Properties * * @throws URISyntaxException if there is a problem constructing the cert's URI - * @throws IOException if there is a problem reading the cert file + * @throws IOException if there is a problem reading the cert file */ @Test public final void testSmallNewPlatformCredential() throws URISyntaxException, IOException { @@ -734,7 +780,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { /** * Tests Platform Configuration Values. View platform Properties * - * @throws IOException if an IO error occurs during processing + * @throws IOException if an IO error occurs during processing * @throws URISyntaxException if there is a problem constructing the cert's URI */ @Test @@ -748,7 +794,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { /** * Tests Platform Configuration Values. View platform Properties * - * @throws IOException if an IO error occurs during processing + * @throws IOException if an IO error occurs during processing * @throws URISyntaxException if there is a problem constructing the cert's URI */ @Test @@ -762,7 +808,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest { /** * Tests Platform Configuration Values. View platform Properties * - * @throws IOException if an IO error occurs during processing + * @throws IOException if an IO error occurs during processing * @throws URISyntaxException if there is a problem constructing the cert's URI */ @Test diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentClassTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentClassTest.java index 3d62eccb..8dc54358 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentClassTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/ComponentClassTest.java @@ -1,12 +1,13 @@ package hirs.attestationca.persist.entity.userdefined.certificate.attributes; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; import java.net.URISyntaxException; import java.nio.file.Paths; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + /** * Tests for the ComponentClassTest class. */ @@ -16,6 +17,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -32,6 +34,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -47,6 +50,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -59,8 +63,10 @@ public class ComponentClassTest { assertEquals(resultComponent, "Unknown"); assertEquals(resultCategory, "None"); } + /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -76,6 +82,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -91,6 +98,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -106,6 +114,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -121,6 +130,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -136,6 +146,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -151,6 +162,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -166,6 +178,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -181,6 +194,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -196,6 +210,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -211,6 +226,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -226,6 +242,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -241,6 +258,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -256,6 +274,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test @@ -271,6 +290,7 @@ public class ComponentClassTest { /** * Test of getComponent method, of class ComponentClass. + * * @throws URISyntaxException if there is a problem constructing the URI */ @Test diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/TPMSecurityAssertionsTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/TPMSecurityAssertionsTest.java index ed4d806e..72b28673 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/TPMSecurityAssertionsTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/TPMSecurityAssertionsTest.java @@ -1,9 +1,10 @@ package hirs.attestationca.persist.entity.userdefined.certificate.attributes; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.fail; -import org.junit.jupiter.api.Test; /** * Tests for the TPMSecurityAssertions class. @@ -18,17 +19,21 @@ public class TPMSecurityAssertionsTest { public void testEkGenTypeEnum() { assertEquals(TPMSecurityAssertions.EkGenerationType.values()[0], TPMSecurityAssertions.EkGenerationType.INTERNAL); + assertEquals(TPMSecurityAssertions.EkGenerationType.values()[1], TPMSecurityAssertions.EkGenerationType.INJECTED); + assertEquals(TPMSecurityAssertions.EkGenerationType.values()[2], TPMSecurityAssertions.EkGenerationType.INTERNAL_REVOCABLE); - assertEquals(TPMSecurityAssertions.EkGenerationType.values()[3], + + final int thirdPosition = 3; + assertEquals(TPMSecurityAssertions.EkGenerationType.values()[thirdPosition], TPMSecurityAssertions.EkGenerationType.INJECTED_REVOCABLE); try { - assertNull(TPMSecurityAssertions.EkGenerationType.values()[4]); + final int positionOutOfBounds = 4; + assertNull(TPMSecurityAssertions.EkGenerationType.values()[positionOutOfBounds]); fail(); } catch (ArrayIndexOutOfBoundsException e) { - return; } } @@ -40,15 +45,17 @@ public class TPMSecurityAssertionsTest { public void testGenLocationEnum() { assertEquals(TPMSecurityAssertions.EkGenerationLocation.values()[0], TPMSecurityAssertions.EkGenerationLocation.TPM_MANUFACTURER); + assertEquals(TPMSecurityAssertions.EkGenerationLocation.values()[1], TPMSecurityAssertions.EkGenerationLocation.PLATFORM_MANUFACTURER); + assertEquals(TPMSecurityAssertions.EkGenerationLocation.values()[2], TPMSecurityAssertions.EkGenerationLocation.EK_CERT_SIGNER); try { - assertNull(TPMSecurityAssertions.EkGenerationLocation.values()[3]); + final int positionOutOfBounds = 3; + assertNull(TPMSecurityAssertions.EkGenerationLocation.values()[positionOutOfBounds]); fail(); } catch (ArrayIndexOutOfBoundsException e) { - return; } } } diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/info/PortalInfoTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/info/PortalInfoTest.java index 5acaba3d..ba3fa97a 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/info/PortalInfoTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/info/PortalInfoTest.java @@ -1,12 +1,13 @@ package hirs.attestationca.persist.entity.userdefined.info; import hirs.utils.enums.PortalScheme; +import org.junit.jupiter.api.Test; + import java.net.InetAddress; -import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.fail; -import org.junit.jupiter.api.Test; /** * Provides tests for PortalInfo. @@ -56,6 +57,7 @@ public class PortalInfoTest { /** * Test that the ip address can be set and retrieved via an InetAddress. + * * @throws Exception If there is a problem with InetAddress. */ @Test @@ -70,6 +72,7 @@ public class PortalInfoTest { /** * Test that the ip address can be set and retrieved via a String. + * * @throws Exception If there is a problem with InetAddress. */ @Test diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/info/TPMInfoTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/info/TPMInfoTest.java index 41382a19..62494a31 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/info/TPMInfoTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/info/TPMInfoTest.java @@ -1,15 +1,16 @@ package hirs.attestationca.persist.entity.userdefined.info; -import static hirs.utils.enums.DeviceInfoEnums.NOT_SPECIFIED; - import hirs.attestationca.persist.entity.userdefined.AbstractUserdefinedEntityTest; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.junit.jupiter.api.Test; + +import static hirs.utils.enums.DeviceInfoEnums.NOT_SPECIFIED; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.jupiter.api.Test; /** * TPMInfoTest is a unit test class for TPMInfo. @@ -17,14 +18,15 @@ import org.junit.jupiter.api.Test; public class TPMInfoTest extends AbstractUserdefinedEntityTest { private static final String TPM_MAKE = "test tpmMake"; - private static final String LONG_TPM_MAKE = StringUtils.rightPad("test tpmMake", 65); + private static final int RIGHT_PADDING_SIZE = 65; + private static final String LONG_TPM_MAKE = StringUtils.rightPad("test tpmMake", RIGHT_PADDING_SIZE); private static final short VERSION_MAJOR = 1; private static final short VERSION_MINOR = 2; private static final short VERSION_REV_MAJOR = 3; private static final short VERSION_REV_MINOR = 4; - private static final Logger LOGGER = LogManager - .getLogger(TPMInfoTest.class); + + private static final Logger LOGGER = LogManager.getLogger(TPMInfoTest.class); /** * Tests instantiation and getters of a TPMInfo object. @@ -53,71 +55,83 @@ public class TPMInfoTest extends AbstractUserdefinedEntityTest { assertEquals(tpmInfo.getTpmVersionMinor(), (short) 0); assertEquals(tpmInfo.getTpmVersionRevMajor(), (short) 0); assertEquals(tpmInfo.getTpmVersionRevMinor(), (short) 0); - assertEquals(tpmInfo.getIdentityCertificate(), null); + assertNull(tpmInfo.getIdentityCertificate()); } /** * Tests that the TPM make information cannot be null. + * + * @throws IllegalArgumentException if one of the provided parameters is an illegal/invalid value */ @Test - public final void tpmMakeNullTest() { + public final void tpmMakeNullTest() throws IllegalArgumentException { assertThrows(IllegalArgumentException.class, () -> new TPMInfo(null, VERSION_MAJOR, VERSION_MINOR, VERSION_REV_MAJOR, - VERSION_REV_MINOR, getTestIdentityCertificate())); + VERSION_REV_MINOR, getTestIdentityCertificate())); } /** * Tests that the TPM make information cannot be longer than 64 characters. + * + * @throws IllegalArgumentException if one of the provided parameters is an illegal/invalid value */ @Test - public final void tpmMakeLongTest() { + public final void tpmMakeLongTest() throws IllegalArgumentException { assertThrows(IllegalArgumentException.class, () -> new TPMInfo(LONG_TPM_MAKE, VERSION_MAJOR, VERSION_MINOR, VERSION_REV_MAJOR, - VERSION_REV_MINOR, getTestIdentityCertificate())); + VERSION_REV_MINOR, getTestIdentityCertificate())); } /** * Tests that the version major number info cannot be set to negative * values. + * + * @throws IllegalArgumentException if one of the provided parameters is an illegal/invalid value */ @Test - public final void testTPMInfoInvalidVersionMajor() { + public final void testTPMInfoInvalidVersionMajor() throws IllegalArgumentException { assertThrows(IllegalArgumentException.class, () -> new TPMInfo(TPM_MAKE, (short) -1, VERSION_MINOR, VERSION_REV_MAJOR, - VERSION_REV_MINOR, getTestIdentityCertificate())); + VERSION_REV_MINOR, getTestIdentityCertificate())); } /** * Tests that the version minor number info cannot be set to negative * values. + * + * @throws IllegalArgumentException if one of the provided parameters is an illegal/invalid value */ @Test - public final void testTPMInfoInvalidVersionMinor() { + public final void testTPMInfoInvalidVersionMinor() throws IllegalArgumentException { assertThrows(IllegalArgumentException.class, () -> new TPMInfo(TPM_MAKE, VERSION_MAJOR, (short) -1, VERSION_REV_MAJOR, - VERSION_REV_MINOR, getTestIdentityCertificate())); + VERSION_REV_MINOR, getTestIdentityCertificate())); } /** * Tests that the version revision major numbers cannot be set to negative * values. + * + * @throws IllegalArgumentException if one of the provided parameters is an illegal/invalid value */ @Test - public final void testTPMInfoInvalidVersionRevMajor() { + public final void testTPMInfoInvalidVersionRevMajor() throws IllegalArgumentException { assertThrows(IllegalArgumentException.class, () -> new TPMInfo(TPM_MAKE, VERSION_MAJOR, VERSION_MINOR, (short) -1, - VERSION_REV_MINOR, getTestIdentityCertificate())); + VERSION_REV_MINOR, getTestIdentityCertificate())); } /** * Tests that the version revision minor numbers cannot be set to negative * values. + * + * @throws IllegalArgumentException if one of the provided parameters is an illegal/invalid value */ @Test - public final void testTPMInfoInvalidVersionRevMinor() { + public final void testTPMInfoInvalidVersionRevMinor() throws IllegalArgumentException { assertThrows(IllegalArgumentException.class, () -> new TPMInfo(TPM_MAKE, VERSION_MAJOR, VERSION_MINOR, VERSION_REV_MAJOR, - (short) -1, getTestIdentityCertificate())); + (short) -1, getTestIdentityCertificate())); } /** diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/record/TPMMeasurementRecordTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/record/TPMMeasurementRecordTest.java index 56522cec..9fdccee1 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/record/TPMMeasurementRecordTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/record/TPMMeasurementRecordTest.java @@ -5,14 +5,13 @@ import hirs.utils.digest.Digest; import hirs.utils.digest.DigestAlgorithm; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; -import org.junit.jupiter.api.Test; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; /** diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/report/DeviceInfoReportTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/report/DeviceInfoReportTest.java index c00511eb..55297ac9 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/report/DeviceInfoReportTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/userdefined/report/DeviceInfoReportTest.java @@ -1,14 +1,14 @@ package hirs.attestationca.persist.entity.userdefined.report; import hirs.attestationca.persist.entity.userdefined.AbstractUserdefinedEntityTest; +import hirs.attestationca.persist.entity.userdefined.info.FirmwareInfo; +import hirs.attestationca.persist.entity.userdefined.info.HardwareInfo; +import hirs.attestationca.persist.entity.userdefined.info.NetworkInfo; import hirs.attestationca.persist.entity.userdefined.info.OSInfo; import hirs.attestationca.persist.entity.userdefined.info.TPMInfo; -import hirs.attestationca.persist.entity.userdefined.info.NetworkInfo; -import hirs.attestationca.persist.entity.userdefined.info.HardwareInfo; -import hirs.attestationca.persist.entity.userdefined.info.FirmwareInfo; - import hirs.utils.VersionHelper; import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -16,14 +16,13 @@ import static org.junit.jupiter.api.Assertions.assertThrows; * Unit test class for DeviceInfoReports. */ public class DeviceInfoReportTest extends AbstractUserdefinedEntityTest { + private static final String EXPECTED_CLIENT_VERSION = VersionHelper.getVersion(); private final NetworkInfo networkInfo = createTestNetworkInfo(); private final OSInfo osInfo = createTestOSInfo(); private final FirmwareInfo firmwareInfo = createTestFirmwareInfo(); private final HardwareInfo hardwareInfo = createTestHardwareInfo(); private final TPMInfo tpmInfo = createTPMInfo(); - private static final String EXPECTED_CLIENT_VERSION = VersionHelper.getVersion(); - /** * Tests instantiation of a DeviceInfoReport. */ diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/provision/helper/CredentialManagementHelperTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/provision/helper/CredentialManagementHelperTest.java index 1218137f..dfed1311 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/provision/helper/CredentialManagementHelperTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/provision/helper/CredentialManagementHelperTest.java @@ -3,6 +3,7 @@ package hirs.attestationca.persist.provision.helper; import hirs.attestationca.persist.entity.manager.CertificateRepository; import hirs.attestationca.persist.entity.userdefined.Certificate; import org.apache.commons.io.IOUtils; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -20,13 +21,19 @@ import static org.mockito.Mockito.verify; */ public class CredentialManagementHelperTest { + private static final String EK_HEADER_TRUNCATED + = "/certificates/nuc-1/ek_cert_7_byte_header_removed.cer"; + + private static final String EK_UNTOUCHED + = "/certificates/nuc-1/ek_cert_untouched.cer"; + @Mock private CertificateRepository certificateRepository; - private static final String EK_HEADER_TRUNCATED - = "/certificates/nuc-1/ek_cert_7_byte_header_removed.cer"; - private static final String EK_UNTOUCHED - = "/certificates/nuc-1/ek_cert_untouched.cer"; + /** + * Holds the AutoCloseable instance returned by openMocks. + */ + private AutoCloseable mocks; /** * Setup mocks. @@ -34,11 +41,24 @@ public class CredentialManagementHelperTest { @BeforeEach public void setUp() { //certificateRepository = mock(CertificateRepository.class); - MockitoAnnotations.initMocks(this); + mocks = MockitoAnnotations.openMocks(this); + } + + /** + * Tears down the mock instances. + * + * @throws Exception if there are any issues closing down mock instances + */ + @AfterEach + public void tearDown() throws Exception { + if (mocks != null) { + mocks.close(); + } } /** * Tests exception generated if providing a null cert repository. + * * @throws IOException if an IO error occurs */ @Test @@ -47,7 +67,7 @@ public class CredentialManagementHelperTest { String path = CredentialManagementHelperTest.class.getResource(EK_UNTOUCHED).getPath(); byte[] ekBytes = IOUtils.toByteArray(new FileInputStream(path)); assertThrows(IllegalArgumentException.class, () -> - CredentialManagementHelper.storeEndorsementCredential(null, ekBytes, "testName")); + CredentialManagementHelper.storeEndorsementCredential(null, ekBytes, "testName")); } /** @@ -56,7 +76,8 @@ public class CredentialManagementHelperTest { @Test public void processNullEndorsementCredential() { assertThrows(IllegalArgumentException.class, () -> - CredentialManagementHelper.storeEndorsementCredential(certificateRepository, null, "testName")); + CredentialManagementHelper.storeEndorsementCredential(certificateRepository, null, + "testName")); } /** @@ -65,8 +86,8 @@ public class CredentialManagementHelperTest { @Test public void processEmptyEndorsementCredential() { assertThrows(IllegalArgumentException.class, () -> - CredentialManagementHelper.storeEndorsementCredential( - certificateRepository, new byte[0], "testName")); + CredentialManagementHelper.storeEndorsementCredential( + certificateRepository, new byte[0], "testName")); } /** @@ -87,11 +108,13 @@ public class CredentialManagementHelperTest { public void processInvalidEndorsementCredentialCase2() { byte[] ekBytes = new byte[] {1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0}; assertThrows(IllegalArgumentException.class, () -> - CredentialManagementHelper.storeEndorsementCredential(certificateRepository, ekBytes, "testName")); + CredentialManagementHelper.storeEndorsementCredential(certificateRepository, ekBytes, + "testName")); } /** - * Tests processing a valid EK with the 7 byte header in tact. + * Tests processing a valid EK with the 7 byte header intact. + * * @throws IOException if an IO error occurs */ @Test @@ -105,6 +128,7 @@ public class CredentialManagementHelperTest { /** * Tests processing a valid EK with the 7 byte header already stripped. + * * @throws IOException if an IO error occurs */ @Test diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/provision/helper/IssuedCertificateAttributeHelperTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/provision/helper/IssuedCertificateAttributeHelperTest.java index 77185604..ff34d14d 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/provision/helper/IssuedCertificateAttributeHelperTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/provision/helper/IssuedCertificateAttributeHelperTest.java @@ -1,7 +1,7 @@ package hirs.attestationca.persist.provision.helper; -import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredential; import hirs.attestationca.persist.entity.userdefined.certificate.EndorsementCredential; +import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredential; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.ASN1TaggedObject; @@ -51,23 +51,25 @@ public class IssuedCertificateAttributeHelperTest { /** * Test that provide a null host name and is rejected. + * * @throws IOException an IO error occurs */ @Test public void rejectNullHostName() throws IOException { assertThrows(IllegalArgumentException.class, () -> - IssuedCertificateAttributeHelper.buildSubjectAlternativeNameFromCerts(null, null, "")); + IssuedCertificateAttributeHelper.buildSubjectAlternativeNameFromCerts(null, null, "")); } /** * Test that subject alt name can be built without an EC or PC. + * * @throws IOException an IO error occurs */ @Test public void buildAttributesNoEndorsementNoPlatform() throws IOException { Extension subjectAlternativeName = - IssuedCertificateAttributeHelper.buildSubjectAlternativeNameFromCerts( - null, new ArrayList(), TEST_HOSTNAME); + IssuedCertificateAttributeHelper.buildSubjectAlternativeNameFromCerts( + null, new ArrayList(), TEST_HOSTNAME); Map subjectAlternativeNameAttrMap = getSubjectAlternativeNameAttributes( subjectAlternativeName); @@ -83,7 +85,8 @@ public class IssuedCertificateAttributeHelperTest { /** * Test that subject alt name can be built with an EC but no PC. - * @throws IOException an IO error occurs + * + * @throws IOException an IO error occurs * @throws URISyntaxException unrecognized URI for EC Path */ @Test @@ -114,7 +117,8 @@ public class IssuedCertificateAttributeHelperTest { /** * Test that subject alt name can be built with an PC but no EC. - * @throws IOException an IO error occurs + * + * @throws IOException an IO error occurs * @throws URISyntaxException unrecognized URI for PC Path */ @Test @@ -147,7 +151,8 @@ public class IssuedCertificateAttributeHelperTest { /** * Test that subject alt name can be built with a PC and an EC. - * @throws IOException an IO error occurs + * + * @throws IOException an IO error occurs * @throws URISyntaxException unrecognized URI for EC or PC Path */ @Test diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/validation/SupplyChainCredentialValidatorTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/validation/SupplyChainCredentialValidatorTest.java index 4cb63d91..7384e4b5 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/validation/SupplyChainCredentialValidatorTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/validation/SupplyChainCredentialValidatorTest.java @@ -1,26 +1,20 @@ package hirs.attestationca.persist.validation; -import hirs.attestationca.persist.entity.ArchivableEntity; import hirs.attestationca.persist.entity.userdefined.Certificate; -import hirs.attestationca.persist.entity.userdefined.SupplyChainValidation; import hirs.attestationca.persist.entity.userdefined.certificate.CertificateAuthorityCredential; import hirs.attestationca.persist.entity.userdefined.certificate.EndorsementCredential; import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredential; -import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentClass; -import hirs.attestationca.persist.entity.userdefined.certificate.attributes.V2.AttributeStatus; +import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentIdentifier; import hirs.attestationca.persist.entity.userdefined.info.ComponentInfo; -import hirs.attestationca.persist.entity.userdefined.info.HardwareInfo; -import hirs.attestationca.persist.entity.userdefined.info.OSInfo; -import hirs.attestationca.persist.entity.userdefined.info.NetworkInfo; import hirs.attestationca.persist.entity.userdefined.info.FirmwareInfo; +import hirs.attestationca.persist.entity.userdefined.info.HardwareInfo; +import hirs.attestationca.persist.entity.userdefined.info.NetworkInfo; +import hirs.attestationca.persist.entity.userdefined.info.OSInfo; import hirs.attestationca.persist.entity.userdefined.info.TPMInfo; import hirs.attestationca.persist.entity.userdefined.info.component.NICComponentInfo; -import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentIdentifier; -import hirs.attestationca.persist.entity.userdefined.certificate.attributes.V2.ComponentIdentifierV2; import hirs.attestationca.persist.entity.userdefined.report.DeviceInfoReport; import hirs.attestationca.persist.enums.AppraisalStatus; import hirs.utils.enums.DeviceInfoEnums; - import org.apache.commons.io.IOUtils; import org.bouncycastle.asn1.ASN1Boolean; import org.bouncycastle.asn1.DERUTF8String; @@ -39,18 +33,10 @@ import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; - import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; @@ -81,17 +67,22 @@ import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; +import java.util.ArrayList; import java.util.Collections; +import java.util.Date; import java.util.HashSet; +import java.util.List; import java.util.Objects; import java.util.Set; -import java.util.List; -import java.util.ArrayList; -import java.util.Date; -import java.util.Map; -import java.util.HashMap; import java.util.UUID; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + /** * Tests the SupplyChainCredentialValidator and CredentialValidator class. * Migration note: Tests specifically for test Intel Nuc Platform Credentials @@ -100,24 +91,6 @@ import java.util.UUID; */ public class SupplyChainCredentialValidatorTest { - private static final String JSON_FILE = "/config/component-class.json"; - private static final String SAMPLE_PACCOR_OUTPUT_TXT = "/hirs/validation/sample_paccor_output.txt"; - private static final String SAMPLE_PACCOR_OUTPUT_NOT_SPECIFIED_TXT - = "/hirs/validation/sample_paccor_output_not_specified_values.txt"; - private static final String SAMPLE_TEST_PACCOR_CERT - = "/validation/platform_credentials_2/paccor_platform_cert.crt"; - - private static final String SAMPLE_PACCOR_OUTPUT_WITH_EXTRA_COMPONENT_TXT - = "/hirs/validation/sample_paccor_output_with_extra_component.txt"; - private static HardwareInfo hardwareInfo; - private final SupplyChainCredentialValidator supplyChainCredentialValidator = - new SupplyChainCredentialValidator(); - - private final CredentialValidator credentialValidator = - new CredentialValidator(); - - private static KeyStore keyStore; - private static KeyStore emptyKeyStore; /** * File name used to initialize a test KeyStore. */ @@ -127,10 +100,24 @@ public class SupplyChainCredentialValidatorTest { */ static final SecureRandom SECURE_RANDOM = new SecureRandom(); + private static final String JSON_FILE = "/config/component-class.json"; + + private static final String SAMPLE_PACCOR_OUTPUT_TXT = "/hirs/validation/sample_paccor_output.txt"; + + private static final String SAMPLE_PACCOR_OUTPUT_NOT_SPECIFIED_TXT + = "/hirs/validation/sample_paccor_output_not_specified_values.txt"; + + private static final String SAMPLE_TEST_PACCOR_CERT + = "/validation/platform_credentials_2/paccor_platform_cert.crt"; + + private static final String SAMPLE_PACCOR_OUTPUT_WITH_EXTRA_COMPONENT_TXT + = "/hirs/validation/sample_paccor_output_with_extra_component.txt"; + private static final String TEST_SIGNING_KEY = "/validation/platform_credentials/ca.pub"; private static final String TEST_PLATFORM_CRED = "/validation/platform_credentials/plat_cert1.pem"; + private static final String TEST_PLATFORM_CRED2 = "/validation/platform_credentials/pciids_plat_cert_2-0.pem"; @@ -138,21 +125,30 @@ public class SupplyChainCredentialValidatorTest { "/validation/platform_credentials/Intel_pc5.pem"; private static final String TEST_BOARD_SERIAL_NUMBER = "GETY421001GV"; + private static final String TEST_CHASSIS_SERIAL_NUMBER = "G6YK42300C87"; + private static final String TEST_EK_CERT = "/certificates/nuc-2/tpmcert.pem"; + private static final String TEST_EK_CERT_2 = "/certificates/nuc-1/tpmcert.pem"; + private static final String TEST_COMPONENT_MANUFACTURER = "Intel"; + private static final String TEST_COMPONENT_MODEL = "platform2018"; + private static final String TEST_COMPONENT_REVISION = "1.0"; + private static final String BAD_SERIAL = "BAD_SERIAL"; //-------Actual ST Micro Endorsement Credential Certificate Chain!-------------- private static final String EK_CERT = ""; + private static final String INT_CA_CERT02 = "/certificates/fakestmtpmekint02.pem"; //-------Generated Intel Credential Certificate Chain-------------- private static final String INTEL_PLATFORM_CERT = "/validation/platform_credentials/plat_cert3.pem"; + private static final String INTEL_PLATFORM_CERT_2 = "/validation/platform_credentials/Intel_pc2.pem"; @@ -161,32 +157,43 @@ public class SupplyChainCredentialValidatorTest { private static final String INTEL_INT_CA = "/validation/platform_credentials/intel_chain/root/intermediate1.crt"; + private static final String FAKE_ROOT_CA = "/validation/platform_credentials/intel_chain/root/rootca.crt"; + private static final String PLATFORM_MANUFACTURER = "Intel"; + private static final String PLATFORM_MODEL = "S2600KP"; + private static final String PLATFORM_VERSION = "H76962-350"; //-------Original Intel Credential Certificate Chain-------------- private static final String INTEL_PLATFORM_CERT_ORIG = "/certificates/fakeIntel_S2600KP_F00F00F00F00.pem"; + private static final String INTEL_ORIG_INT_CA_ORIG = "/certificates/fakeIntelIntermediateCA.pem"; + private static final String FAKE_ROOT_CA_ORIG = "/certificates/fakeCA.pem"; //-------Fake SGI Credential Certificate Chain-------------- private static final String SGI_PLATFORM_CERT = "/certificates/fakeSGI_J2_F00F00F0.pem"; + private static final String SGI_INT_CA = "/certificates/fakeSGIIntermediateCA.pem"; + private static final String SGI_CRED_SERIAL_NUMBER = "F00F00F0"; //-------Actual Intel NUC Platform -------------- + private static final String NUC_PLATFORM_CERT = "/certificates/Intel_nuc_pc.pem"; + private static final String NUC_PLATFORM_CERT_SERIAL_NUMBER = "GETY421001DY"; private static final String NUC_PLATFORM_CERT2 = "/certificates/Intel_nuc_pc2.pem"; + private static final String NUC_PLATFORM_CERT_SERIAL_NUMBER2 = "GETY4210001M"; private static final String INTEL_SIGNING_KEY = "/certificates/IntelSigningKey_20April2017.pem"; @@ -194,18 +201,23 @@ public class SupplyChainCredentialValidatorTest { private static final String NEW_NUC1 = "/validation/platform_credentials/Intel_pc3.cer"; + private static HardwareInfo hardwareInfo; + + private static KeyStore keyStore; + + private static KeyStore emptyKeyStore; + /** * Sets up a KeyStore for testing. * - * @throws KeyStoreException - * if no Provider supports a KeyStoreSpi implementation for the specified type. - * @throws NoSuchAlgorithmException - * if the algorithm used to check the integrity of the keystore cannot be found - * @throws CertificateException - * if any of the certificates in the keystore could not be loaded - * @throws IOException - * if there is an I/O or format problem with the keystore data, if a password is - * required but not given, or if the given password was incorrect + * @throws KeyStoreException if no Provider supports a KeyStoreSpi implementation for the + * specified type. + * @throws NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore + * cannot be found + * @throws CertificateException if any of the certificates in the keystore could not be loaded + * @throws IOException if there is an I/O or format problem with the keystore data, + * if a password is required but not given, + * or if the given password was incorrect */ @BeforeAll public static void setUp() throws KeyStoreException, NoSuchAlgorithmException, @@ -234,13 +246,179 @@ public class SupplyChainCredentialValidatorTest { } } + private static DeviceInfoReport setupDeviceInfoReport() { + hardwareInfo = new HardwareInfo( + "ACME", + "anvil", + "3.0", + "1234", + "567", + "890"); + + DeviceInfoReport deviceInfoReport = mock(DeviceInfoReport.class); + when(deviceInfoReport.getHardwareInfo()).thenReturn(hardwareInfo); + return deviceInfoReport; + } + + private static DeviceInfoReport setupDeviceInfoReportWithComponents() throws IOException { + return setupDeviceInfoReportWithComponents(SAMPLE_PACCOR_OUTPUT_TXT); + } + + private static DeviceInfoReport setupDeviceInfoReportWithNotSpecifiedComponents() + throws IOException { + return setupDeviceInfoReportWithComponents(SAMPLE_PACCOR_OUTPUT_NOT_SPECIFIED_TXT); + } + + private static DeviceInfoReport setupDeviceInfoReportWithComponents( + final String paccorOutputResource) throws IOException { + DeviceInfoReport deviceInfoReport = setupDeviceInfoReport(); + URL url = SupplyChainCredentialValidator.class.getResource(paccorOutputResource); + String paccorOutputString = IOUtils.toString(url, StandardCharsets.UTF_8); + when(deviceInfoReport.getPaccorOutputString()).thenReturn(paccorOutputString); + return deviceInfoReport; + } + + /** + * Creates a new RSA 1024-bit KeyPair using a Bouncy Castle Provider. + * + * @return new KeyPair + */ + private static KeyPair createKeyPair() { + final int keySize = 1024; + KeyPairGenerator gen; + KeyPair keyPair = null; + try { + gen = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); + gen.initialize(keySize, SECURE_RANDOM); + keyPair = gen.generateKeyPair(); + } catch (NoSuchAlgorithmException | NoSuchProviderException e) { + fail("Error occurred while generating key pair", e); + } + return keyPair; + } + + /** + * Create a new X.509 attribute certificate given the holder cert, the signing cert, and the + * signing key. + * + * @param targetCert X509Certificate that will be the holder of the attribute cert + * @param signingCert X509Certificate used to sign the new attribute cert + * @param caPrivateKey PrivateKey used to sign the new attribute cert + * @return new X509AttributeCertificate + */ + private static X509AttributeCertificateHolder createAttributeCert( + final X509Certificate targetCert, final X509Certificate signingCert, + final PrivateKey caPrivateKey) { + X509AttributeCertificateHolder cert = null; + try { + final int timeRange = 50000; + AttributeCertificateHolder holder = + new AttributeCertificateHolder(new X509CertificateHolder( + targetCert.getEncoded())); + AttributeCertificateIssuer issuer = + new AttributeCertificateIssuer(new X500Name(signingCert + .getSubjectX500Principal().getName())); + BigInteger serialNumber = BigInteger.ONE; + Date notBefore = new Date(System.currentTimeMillis() - timeRange); + Date notAfter = new Date(System.currentTimeMillis() + timeRange); + X509v2AttributeCertificateBuilder builder = + new X509v2AttributeCertificateBuilder(holder, issuer, serialNumber, notBefore, + notAfter); + + ContentSigner signer = + new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC") + .build(caPrivateKey); + + cert = builder.build(signer); + } catch (CertificateEncodingException | IOException | OperatorCreationException e) { + fail("Exception occurred while creating a cert", e); + } + + return cert; + + } + + /** + * Create a new X.509 public-key certificate signed by the given certificate. + * + * @param keyPair KeyPair to create the cert for + * @param signingKey PrivateKey of the signing cert + * @param signingCert signing cert + * @return new X509Certificate + */ + private static X509Certificate createCertSignedByAnotherCert(final KeyPair keyPair, + final PrivateKey signingKey, + final X509Certificate signingCert) { + final int timeRange = 10000; + X509Certificate cert = null; + try { + + X500Name issuerName = new X500Name(signingCert.getSubjectX500Principal().getName()); + X500Name subjectName = new X500Name("CN=Test V3 Certificate"); + BigInteger serialNumber = BigInteger.ONE; + Date notBefore = new Date(System.currentTimeMillis() - timeRange); + Date notAfter = new Date(System.currentTimeMillis() + timeRange); + X509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder(issuerName, serialNumber, notBefore, notAfter, + subjectName, keyPair.getPublic()); + ContentSigner signer = + new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build(signingKey); + return new JcaX509CertificateConverter().setProvider("BC").getCertificate( + builder.build(signer)); + } catch (Exception e) { + fail("Exception occurred while creating a cert", e); + } + return cert; + } + + /** + * Creates a self-signed X.509 public-key certificate. + * + * @param pair KeyPair to create the cert for + * @return self-signed X509Certificate + */ + private static X509Certificate createSelfSignedCertificate(final KeyPair pair) { + Security.addProvider(new BouncyCastleProvider()); + final int timeRange = 10000; + X509Certificate cert = null; + try { + + X500Name issuerName = new X500Name("CN=Test Self-Signed V3 Certificate"); + X500Name subjectName = new X500Name("CN=Test Self-Signed V3 Certificate"); + BigInteger serialNumber = BigInteger.ONE; + Date notBefore = new Date(System.currentTimeMillis() - timeRange); + Date notAfter = new Date(System.currentTimeMillis() + timeRange); + X509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder(issuerName, serialNumber, notBefore, notAfter, + subjectName, pair.getPublic()); + ContentSigner signer = + new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build( + pair.getPrivate()); + return new JcaX509CertificateConverter().setProvider("BC").getCertificate( + builder.build(signer)); + } catch (Exception e) { + fail("Exception occurred while creating a cert", e); + } + return cert; + } + + private static InetAddress getTestIpAddress() { + try { + final byte[] byteAddress = new byte[] {127, 0, 0, 1}; + return InetAddress.getByAddress(byteAddress); + } catch (UnknownHostException e) { + return null; + } + } + /** * Checks if the ST Micro Endorsement Credential can be validated against the * ST/GlobalSIgn Certificate Chain. - * @throws IOException if error occurs while reading files - * @throws URISyntaxException if error occurs while reading files + * + * @throws IOException if error occurs while reading files + * @throws URISyntaxException if error occurs while reading files * @throws CertificateException if error occurs while processing X509 Certs - * @throws KeyStoreException if error occurs while processing Keystore + * @throws KeyStoreException if error occurs while processing Keystore */ @Test public final void testValidateEndorsementCredential() @@ -267,7 +445,7 @@ public class SupplyChainCredentialValidatorTest { ekcert, keyStore, true); assertEquals(AppraisalStatus.Status.PASS, result.getAppStatus()); assertEquals(SupplyChainCredentialValidator.ENDORSEMENT_VALID, result.getMessage()); - } finally { + } finally { keyStore.deleteEntry("Intel Intermediate Cert"); keyStore.deleteEntry("CA cert"); } @@ -277,10 +455,10 @@ public class SupplyChainCredentialValidatorTest { * Validates a generated cert chain pretending to be from Intel. Credential was generated * with an intermediate CA. This tests the entire chain of validation back to the root CA. * - * @throws IOException if error occurs while reading files - * @throws KeyStoreException if there's an issue string certs to the keystore + * @throws IOException if error occurs while reading files + * @throws KeyStoreException if there's an issue string certs to the keystore * @throws CertificateException if error occurs while ingesting a certificate - * @throws URISyntaxException if a URI can't be processed + * @throws URISyntaxException if a URI can't be processed */ @Test public final void validateIntelPlatformCredentials() @@ -288,13 +466,13 @@ public class SupplyChainCredentialValidatorTest { Certificate intermediatecacert = new CertificateAuthorityCredential(Files.readAllBytes(Paths.get( - Objects.requireNonNull(getClass().getResource(INTEL_INT_CA)).toURI())) - ); + Objects.requireNonNull(getClass().getResource(INTEL_INT_CA)).toURI())) + ); Certificate rootcacert = new CertificateAuthorityCredential(Files.readAllBytes(Paths.get( - Objects.requireNonNull(getClass().getResource(FAKE_ROOT_CA)).toURI())) - ); + Objects.requireNonNull(getClass().getResource(FAKE_ROOT_CA)).toURI())) + ); try { keyStore.setCertificateEntry("CA cert", rootcacert.getX509Certificate()); @@ -354,9 +532,9 @@ public class SupplyChainCredentialValidatorTest { /** * Checks if the Platform Credential contains the serial number from * the device in the platform serial number field. - * @throws Exception If there are errors. * - * */ + * @throws Exception If there are errors. + */ // @Test public final void validatePlatformCredentialWithDeviceBaseboard() throws Exception { @@ -377,7 +555,7 @@ public class SupplyChainCredentialValidatorTest { AppraisalStatus result = CredentialValidator.validatePlatformCredentialAttributes(pc, deviceInfoReport, ec, null, null, - Collections.emptyList(), UUID.randomUUID(), false); + Collections.emptyList(), UUID.randomUUID(), false); assertEquals(AppraisalStatus.Status.PASS, result.getAppStatus()); assertEquals(SupplyChainCredentialValidator.PLATFORM_ATTRIBUTES_VALID, result.getMessage()); @@ -414,10 +592,10 @@ public class SupplyChainCredentialValidatorTest { result.getMessage()); } - /** * Checks if the NUC Platform Credential contains the serial number from * the device as a baseboard component in the serial number field. + * * @throws Exception If there are errors. */ // @Test @@ -462,7 +640,7 @@ public class SupplyChainCredentialValidatorTest { byte[] certBytes = Files.readAllBytes(Paths.get( Objects.requireNonNull(SupplyChainCredentialValidatorTest.class. - getResource(INTEL_PLATFORM_CERT_2)).toURI())); + getResource(INTEL_PLATFORM_CERT_2)).toURI())); PlatformCredential pc = new PlatformCredential(certBytes); @@ -530,7 +708,7 @@ public class SupplyChainCredentialValidatorTest { PlatformCredential pc = new PlatformCredential(certBytes); EndorsementCredential ec = new EndorsementCredential(Files.readAllBytes(Paths.get( - Objects.requireNonNull(getClass().getResource(TEST_EK_CERT)).toURI()))); + Objects.requireNonNull(getClass().getResource(TEST_EK_CERT)).toURI()))); AppraisalStatus result = CredentialValidator.validatePlatformCredentialAttributes(pc, @@ -544,6 +722,7 @@ public class SupplyChainCredentialValidatorTest { /** * Checks if the Platform Credential validator appropriately fails * when there are no serial numbers returned from the device. + * * @throws Exception If there are errors. */ // @Test @@ -578,6 +757,7 @@ public class SupplyChainCredentialValidatorTest { /** * Checks if the Platform Credential validator appropriately fails * when there are no serial numbers matching any of the platform info from the device. + * * @throws Exception If there are errors. */ // @Test @@ -611,10 +791,10 @@ public class SupplyChainCredentialValidatorTest { /** * Checks if a cert can be validated against the given public key. * - * @throws IOException if error occurs while reading files - * @throws InvalidKeySpecException if error occurs while generating the PublicKey - * @throws NoSuchAlgorithmException if error occurs while getting RSA KeyFactory - * @throws URISyntaxException if error occurs constructing test cert path + * @throws IOException if error occurs while reading files + * @throws InvalidKeySpecException if error occurs while generating the PublicKey + * @throws NoSuchAlgorithmException if error occurs while getting RSA KeyFactory + * @throws URISyntaxException if error occurs constructing test cert path * @throws SupplyChainValidatorException if error occurs due to using null certificates */ @Test @@ -643,8 +823,8 @@ public class SupplyChainCredentialValidatorTest { * Negative test to check if validation against a public key can fail. Generates a random * key pair and attempts to validate it against the Intel cert, which is expected to fail. * - * @throws IOException if error occurs while reading files - * @throws URISyntaxException if an error occurs while constructing test resource's URI + * @throws IOException if error occurs while reading files + * @throws URISyntaxException if an error occurs while constructing test resource's URI * @throws SupplyChainValidatorException if error occurs due to using null certificates */ @Test @@ -899,7 +1079,7 @@ public class SupplyChainCredentialValidatorTest { * validation passes. This should result in an error as keystores should never * be empty. * - * @throws IOException an error occurs when parsing the certificate + * @throws IOException an error occurs when parsing the certificate * @throws URISyntaxException an error occurs parsing the certificate file path */ @Test @@ -907,7 +1087,7 @@ public class SupplyChainCredentialValidatorTest { throws URISyntaxException, IOException { byte[] certBytes = Files.readAllBytes(Paths.get( Objects.requireNonNull(SupplyChainCredentialValidatorTest.class.getResource( - INTEL_PLATFORM_CERT)).toURI())); + INTEL_PLATFORM_CERT)).toURI())); PlatformCredential pc = new PlatformCredential(certBytes); @@ -939,7 +1119,7 @@ public class SupplyChainCredentialValidatorTest { * Verifies that a null check is performed on the keyStore * when validating platform credentials. * - * @throws IOException an error occurs when parsing the certificate + * @throws IOException an error occurs when parsing the certificate * @throws URISyntaxException an error occurs parsing the certificate file path */ @Test @@ -947,7 +1127,7 @@ public class SupplyChainCredentialValidatorTest { throws URISyntaxException, IOException { byte[] certBytes = Files.readAllBytes(Paths.get( Objects.requireNonNull(SupplyChainCredentialValidatorTest.class.getResource( - INTEL_PLATFORM_CERT)).toURI())); + INTEL_PLATFORM_CERT)).toURI())); PlatformCredential pc = new PlatformCredential(certBytes); @@ -964,7 +1144,7 @@ public class SupplyChainCredentialValidatorTest { * Verifies that a null check is performed on the device info report * when validating platform credentials. * - * @throws IOException an error occurs when parsing the certificate + * @throws IOException an error occurs when parsing the certificate * @throws URISyntaxException an error occurs parsing the certificate file path */ // @Test @@ -972,7 +1152,7 @@ public class SupplyChainCredentialValidatorTest { throws URISyntaxException, IOException { byte[] certBytes = Files.readAllBytes(Paths.get( Objects.requireNonNull(SupplyChainCredentialValidatorTest.class.getResource( - INTEL_PLATFORM_CERT_2)).toURI())); + INTEL_PLATFORM_CERT_2)).toURI())); PlatformCredential pc = new PlatformCredential(certBytes); @@ -992,9 +1172,10 @@ public class SupplyChainCredentialValidatorTest { /** * Tests that issuer/subject distinguished names can be properly verified as equal even * if their elements are in different orders. - * @throws URISyntaxException failed to read certificate - * @throws IOException failed to read certificate - * @throws KeyStoreException failed to read key store + * + * @throws URISyntaxException failed to read certificate + * @throws IOException failed to read certificate + * @throws KeyStoreException failed to read key store * @throws SupplyChainValidatorException missing credential */ @@ -1023,9 +1204,10 @@ public class SupplyChainCredentialValidatorTest { /** * Tests that issuer/subject distinguished names can be properly verified as being unequal * if their elements don't match. - * @throws URISyntaxException failed to read certificate - * @throws IOException failed to read certificate - * @throws KeyStoreException failed to read key store + * + * @throws URISyntaxException failed to read certificate + * @throws IOException failed to read certificate + * @throws KeyStoreException failed to read key store * @throws SupplyChainValidatorException missing credential */ @Test @@ -1038,7 +1220,7 @@ public class SupplyChainCredentialValidatorTest { byte[] certBytes = Files.readAllBytes(Paths.get( Objects.requireNonNull(SupplyChainCredentialValidator.class. - getResource(NEW_NUC1)).toURI())); + getResource(NEW_NUC1)).toURI())); PlatformCredential pc = new PlatformCredential(certBytes); @@ -1052,9 +1234,10 @@ public class SupplyChainCredentialValidatorTest { /** * Tests that issuer/subject distinguished names can be properly verified as equal. - * @throws URISyntaxException failed to read certificate - * @throws IOException failed to read certificate - * @throws KeyStoreException failed to read key store + * + * @throws URISyntaxException failed to read certificate + * @throws IOException failed to read certificate + * @throws KeyStoreException failed to read key store * @throws SupplyChainValidatorException missing credential */ @Test @@ -1082,9 +1265,10 @@ public class SupplyChainCredentialValidatorTest { /** * Tests that issuer/subject distinguished names can be properly verified as being unequal * if their elements don't match. - * @throws URISyntaxException failed to read certificate - * @throws IOException failed to read certificate - * @throws KeyStoreException failed to read key store + * + * @throws URISyntaxException failed to read certificate + * @throws IOException failed to read certificate + * @throws KeyStoreException failed to read key store * @throws SupplyChainValidatorException missing credential */ @Test @@ -1097,7 +1281,7 @@ public class SupplyChainCredentialValidatorTest { byte[] certBytes = Files.readAllBytes(Paths.get( Objects.requireNonNull(SupplyChainCredentialValidator.class. - getResource(TEST_EK_CERT)).toURI())); + getResource(TEST_EK_CERT)).toURI())); EndorsementCredential ec = new EndorsementCredential(certBytes); @@ -1109,38 +1293,6 @@ public class SupplyChainCredentialValidatorTest { x509Cert, caX509)); } - private static DeviceInfoReport setupDeviceInfoReport() { - hardwareInfo = new HardwareInfo( - "ACME", - "anvil", - "3.0", - "1234", - "567", - "890"); - - DeviceInfoReport deviceInfoReport = mock(DeviceInfoReport.class); - when(deviceInfoReport.getHardwareInfo()).thenReturn(hardwareInfo); - return deviceInfoReport; - } - - private static DeviceInfoReport setupDeviceInfoReportWithComponents() throws IOException { - return setupDeviceInfoReportWithComponents(SAMPLE_PACCOR_OUTPUT_TXT); - } - - private static DeviceInfoReport setupDeviceInfoReportWithNotSpecifiedComponents() - throws IOException { - return setupDeviceInfoReportWithComponents(SAMPLE_PACCOR_OUTPUT_NOT_SPECIFIED_TXT); - } - - private static DeviceInfoReport setupDeviceInfoReportWithComponents( - final String paccorOutputResource) throws IOException { - DeviceInfoReport deviceInfoReport = setupDeviceInfoReport(); - URL url = SupplyChainCredentialValidator.class.getResource(paccorOutputResource); - String paccorOutputString = IOUtils.toString(url, StandardCharsets.UTF_8); - when(deviceInfoReport.getPaccorOutputString()).thenReturn(paccorOutputString); - return deviceInfoReport; - } - /** * Tests that isMatch works correctly in comparing component info to component identifier. */ @@ -1199,7 +1351,7 @@ public class SupplyChainCredentialValidatorTest { List deviceInfoComponents = SupplyChainCredentialValidator.getComponentInfoFromPaccorOutput( - deviceInfoReport.getNetworkInfo().getHostname(), + deviceInfoReport.getNetworkInfo().getHostname(), deviceInfoReport.getPaccorOutputString()); List componentIdentifierList = new ArrayList<>(); for (ComponentInfo deviceInfoComponent : deviceInfoComponents) { @@ -1231,6 +1383,7 @@ public class SupplyChainCredentialValidatorTest { /** * Tests that TPM 2.0 Platform Credentials validate correctly against the device info report * when there are no components. + * * @throws IOException if unable to set up DeviceInfoReport from resource file */ // @Test @@ -1251,6 +1404,7 @@ public class SupplyChainCredentialValidatorTest { /** * Tests that TPM 2.0 Platform Credentials validate correctly against the device info report * when there are components present. + * * @throws IOException if unable to set up DeviceInfoReport from resource file */ // @Test @@ -1271,6 +1425,7 @@ public class SupplyChainCredentialValidatorTest { * Tests that TPM 2.0 Platform Credentials validate correctly against the device info report * when there are components present, and when the PlatformSerial field holds the system's * serial number instead of the baseboard serial number. + * * @throws IOException if unable to set up DeviceInfoReport from resource file */ // @Test @@ -1293,7 +1448,8 @@ public class SupplyChainCredentialValidatorTest { * Tests that TPM 2.0 Platform Credentials validate correctly against the device info report * when there are components present, and when the PlatformSerial field holds the system's * serial number instead of the baseboard serial number. - * @throws IOException if unable to set up DeviceInfoReport from resource file + * + * @throws IOException if unable to set up DeviceInfoReport from resource file * @throws URISyntaxException failed to read certificate */ // @Test @@ -1302,8 +1458,8 @@ public class SupplyChainCredentialValidatorTest { DeviceInfoReport deviceInfoReport = setupDeviceInfoReportWithNotSpecifiedComponents(); PlatformCredential platformCredential = new PlatformCredential( Files.readAllBytes(Paths.get( - Objects.requireNonNull(SupplyChainCredentialValidator.class.getResource( - SAMPLE_TEST_PACCOR_CERT)).toURI()))); + Objects.requireNonNull(SupplyChainCredentialValidator.class.getResource( + SAMPLE_TEST_PACCOR_CERT)).toURI()))); AppraisalStatus appraisalStatus = CertificateAttributeScvValidator .validatePlatformCredentialAttributesV2p0(platformCredential, deviceInfoReport, null, null, @@ -1313,6 +1469,7 @@ public class SupplyChainCredentialValidatorTest { /** * Tests that the SupplyChainCredentialValidator fails when required fields are null. + * * @throws IOException if unable to set up DeviceInfoReport from resource file */ // @Test @@ -1425,6 +1582,7 @@ public class SupplyChainCredentialValidatorTest { /** * Tests that the SupplyChainCredentialValidator fails when required fields contain only empty * strings. + * * @throws IOException if unable to set up DeviceInfoReport from resource file */ // @Test @@ -1484,7 +1642,7 @@ public class SupplyChainCredentialValidatorTest { result = CertificateAttributeScvValidator .validatePlatformCredentialAttributesV2p0(platformCredential, deviceInfoReport, null, null, - Collections.emptyList(), UUID.randomUUID(), false); + Collections.emptyList(), UUID.randomUUID(), false); assertEquals(AppraisalStatus.Status.PASS, result.getAppStatus()); assertEquals(SupplyChainCredentialValidator.PLATFORM_ATTRIBUTES_VALID, result.getMessage()); @@ -1514,9 +1672,9 @@ public class SupplyChainCredentialValidatorTest { Collections.emptyList(), UUID.randomUUID(), false); assertEquals(AppraisalStatus.Status.FAIL, result.getAppStatus()); assertEquals("Component manufacturer is empty\n" - + "There are unmatched components:\n" - + "Manufacturer=, Model=Core i7, Serial=Not Specified," - + " Revision=Intel(R) Core(TM) i7-4790 CPU @ 3.60GHz;\n", + + "There are unmatched components:\n" + + "Manufacturer=, Model=Core i7, Serial=Not Specified," + + " Revision=Intel(R) Core(TM) i7-4790 CPU @ 3.60GHz;\n", result.getMessage()); platformCredential = setupMatchingPlatformCredential(deviceInfoReport); @@ -1541,6 +1699,7 @@ public class SupplyChainCredentialValidatorTest { /** * Tests that {@link SupplyChainCredentialValidator} failes when a component exists in the * platform credential, but not in the device info report. + * * @throws IOException if unable to set up DeviceInfoReport from resource file */ // @Test @@ -1577,7 +1736,7 @@ public class SupplyChainCredentialValidatorTest { Collections.emptyList(), UUID.randomUUID(), false); assertEquals(AppraisalStatus.Status.FAIL, result.getAppStatus()); assertEquals("There are unmatched components:\n" - + "Manufacturer=ACME, Model=TNT, Serial=2, Revision=1.1;\n", + + "Manufacturer=ACME, Model=TNT, Serial=2, Revision=1.1;\n", result.getMessage()); } @@ -1585,6 +1744,7 @@ public class SupplyChainCredentialValidatorTest { * Tests that SupplyChainCredentialValidator passes when everything matches but there are * extra components in the device info report that are not represented in the platform * credential. + * * @throws IOException if unable to set up DeviceInfoReport from resource file */ // @Test @@ -1617,6 +1777,7 @@ public class SupplyChainCredentialValidatorTest { /** * Tests that SupplyChainCredentialValidator fails when a component is found in the platform * credential without a manufacturer or model. + * * @throws IOException if unable to set up DeviceInfoReport from resource file */ // @Test @@ -1644,9 +1805,9 @@ public class SupplyChainCredentialValidatorTest { Collections.emptyList(), UUID.randomUUID(), false); assertEquals(AppraisalStatus.Status.FAIL, result.getAppStatus()); assertEquals("Component manufacturer is empty\n" - + "There are unmatched components:\n" - + "Manufacturer=, Model=Core i7, Serial=Not Specified," - + " Revision=Intel(R) Core(TM) i7-4790 CPU @ 3.60GHz;\n", + + "There are unmatched components:\n" + + "Manufacturer=, Model=Core i7, Serial=Not Specified," + + " Revision=Intel(R) Core(TM) i7-4790 CPU @ 3.60GHz;\n", result.getMessage()); platformCredential = setupMatchingPlatformCredential(deviceInfoReport); @@ -1673,6 +1834,7 @@ public class SupplyChainCredentialValidatorTest { /** * Tests that SupplyChainCredentialValidator passes when a component on the system has a * matching component in the platform certificate, except the serial value is missing. + * * @throws IOException if unable to set up DeviceInfoReport from resource file */ // @Test @@ -1704,6 +1866,7 @@ public class SupplyChainCredentialValidatorTest { /** * Tests that SupplyChainCredentialValidator passes when a component on the system has a * matching component in the platform certificate, except the revision value is missing. + * * @throws IOException if unable to set up DeviceInfoReport from resource file */ // @Test @@ -1736,6 +1899,7 @@ public class SupplyChainCredentialValidatorTest { * Tests that SupplyChainCredentialValidator passes when a component on the system has a * matching component in the platform certificate, except the serial and revision values * are missing. + * * @throws IOException if unable to set up DeviceInfoReport from resource file */ // @Test @@ -1768,7 +1932,8 @@ public class SupplyChainCredentialValidatorTest { /** * Tests that SupplyChainCredentialValidator passes with a base and delta certificate where * the base serial number and delta holder serial number match. - * @throws java.io.IOException Reading file for the certificates + * + * @throws java.io.IOException Reading file for the certificates * @throws java.net.URISyntaxException when loading certificates bytes */ // @Test @@ -1904,7 +2069,8 @@ public class SupplyChainCredentialValidatorTest { /** * Tests that SupplyChainCredentialValidator fails when a component needs to * be replaced but hasn't been by a delta certificate. - * @throws java.io.IOException Reading file for the certificates + * + * @throws java.io.IOException Reading file for the certificates * @throws java.net.URISyntaxException when loading certificates bytes */ // @Test @@ -2014,136 +2180,6 @@ public class SupplyChainCredentialValidatorTest { // result.getMessage()); } - /** - * Creates a new RSA 1024-bit KeyPair using a Bouncy Castle Provider. - * - * @return new KeyPair - */ - private static KeyPair createKeyPair() { - final int keySize = 1024; - KeyPairGenerator gen; - KeyPair keyPair = null; - try { - gen = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); - gen.initialize(keySize, SECURE_RANDOM); - keyPair = gen.generateKeyPair(); - } catch (NoSuchAlgorithmException | NoSuchProviderException e) { - fail("Error occurred while generating key pair", e); - } - return keyPair; - } - - /** - * Create a new X.509 attribute certificate given the holder cert, the signing cert, and the - * signing key. - * - * @param targetCert - * X509Certificate that will be the holder of the attribute cert - * @param signingCert - * X509Certificate used to sign the new attribute cert - * @param caPrivateKey - * PrivateKey used to sign the new attribute cert - * @return new X509AttributeCertificate - */ - private static X509AttributeCertificateHolder createAttributeCert( - final X509Certificate targetCert, final X509Certificate signingCert, - final PrivateKey caPrivateKey) { - X509AttributeCertificateHolder cert = null; - try { - final int timeRange = 50000; - AttributeCertificateHolder holder = - new AttributeCertificateHolder(new X509CertificateHolder( - targetCert.getEncoded())); - AttributeCertificateIssuer issuer = - new AttributeCertificateIssuer(new X500Name(signingCert - .getSubjectX500Principal().getName())); - BigInteger serialNumber = BigInteger.ONE; - Date notBefore = new Date(System.currentTimeMillis() - timeRange); - Date notAfter = new Date(System.currentTimeMillis() + timeRange); - X509v2AttributeCertificateBuilder builder = - new X509v2AttributeCertificateBuilder(holder, issuer, serialNumber, notBefore, - notAfter); - - ContentSigner signer = - new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC") - .build(caPrivateKey); - - cert = builder.build(signer); - } catch (CertificateEncodingException | IOException | OperatorCreationException e) { - fail("Exception occurred while creating a cert", e); - } - - return cert; - - } - - /** - * Create a new X.509 public-key certificate signed by the given certificate. - * - * @param keyPair - * KeyPair to create the cert for - * @param signingKey - * PrivateKey of the signing cert - * @param signingCert - * signing cert - * @return new X509Certificate - */ - private static X509Certificate createCertSignedByAnotherCert(final KeyPair keyPair, - final PrivateKey signingKey, final X509Certificate signingCert) { - final int timeRange = 10000; - X509Certificate cert = null; - try { - - X500Name issuerName = new X500Name(signingCert.getSubjectX500Principal().getName()); - X500Name subjectName = new X500Name("CN=Test V3 Certificate"); - BigInteger serialNumber = BigInteger.ONE; - Date notBefore = new Date(System.currentTimeMillis() - timeRange); - Date notAfter = new Date(System.currentTimeMillis() + timeRange); - X509v3CertificateBuilder builder = - new JcaX509v3CertificateBuilder(issuerName, serialNumber, notBefore, notAfter, - subjectName, keyPair.getPublic()); - ContentSigner signer = - new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build(signingKey); - return new JcaX509CertificateConverter().setProvider("BC").getCertificate( - builder.build(signer)); - } catch (Exception e) { - fail("Exception occurred while creating a cert", e); - } - return cert; - } - - /** - * Creates a self-signed X.509 public-key certificate. - * - * @param pair - * KeyPair to create the cert for - * @return self-signed X509Certificate - */ - private static X509Certificate createSelfSignedCertificate(final KeyPair pair) { - Security.addProvider(new BouncyCastleProvider()); - final int timeRange = 10000; - X509Certificate cert = null; - try { - - X500Name issuerName = new X500Name("CN=Test Self-Signed V3 Certificate"); - X500Name subjectName = new X500Name("CN=Test Self-Signed V3 Certificate"); - BigInteger serialNumber = BigInteger.ONE; - Date notBefore = new Date(System.currentTimeMillis() - timeRange); - Date notAfter = new Date(System.currentTimeMillis() + timeRange); - X509v3CertificateBuilder builder = - new JcaX509v3CertificateBuilder(issuerName, serialNumber, notBefore, notAfter, - subjectName, pair.getPublic()); - ContentSigner signer = - new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build( - pair.getPrivate()); - return new JcaX509CertificateConverter().setProvider("BC").getCertificate( - builder.build(signer)); - } catch (Exception e) { - fail("Exception occurred while creating a cert", e); - } - return cert; - } - private DeviceInfoReport buildReport(final HardwareInfo givenHardwareInfo) { final InetAddress ipAddress = getTestIpAddress(); final byte[] macAddress = new byte[] {11, 22, 33, 44, 55, 66}; @@ -2156,11 +2192,4 @@ public class SupplyChainCredentialValidatorTest { return new DeviceInfoReport(networkInfo, osInfo, firmwareInfo, givenHardwareInfo, tpmInfo); } - private static InetAddress getTestIpAddress() { - try { - return InetAddress.getByAddress(new byte[] {127, 0, 0, 1}); - } catch (UnknownHostException e) { - return null; - } - } } diff --git a/HIRS_AttestationCAPortal/build.gradle b/HIRS_AttestationCAPortal/build.gradle index 83738123..310f0834 100644 --- a/HIRS_AttestationCAPortal/build.gradle +++ b/HIRS_AttestationCAPortal/build.gradle @@ -21,9 +21,9 @@ java { } bootRun { - if (project.hasProperty('debug')) { - jvmArgs project.debug - } + if (project.hasProperty('debug')) { + jvmArgs project.debug + } } configurations { @@ -80,10 +80,10 @@ configurations.checkstyle { } } checkstyleMain { - source ='src/main/java' + source = 'src/main/java' } checkstyleTest { - source ='src/test/java' + source = 'src/test/java' } tasks.withType(Checkstyle) { reports { @@ -110,36 +110,36 @@ ospackage { arch = NOARCH version = "$packVersion" release = '2' - - + + user 'root' fileMode = 0755 addParentDirs = true - createDirectoryEntry true + createDirectoryEntry true - into ('/etc/hirs') { - from '../VERSION' - } + into('/etc/hirs') { + from '../VERSION' + } // copy json tables - into ('/etc/hirs/aca/default-properties') { - from '../HIRS_AttestationCA/src/main/resources/component-class.json' - from '../HIRS_Utils/src/main/resources/vendor-table.json' + into('/etc/hirs/aca/default-properties') { + from '../HIRS_AttestationCA/src/main/resources/component-class.json' + from '../HIRS_Utils/src/main/resources/vendor-table.json' } // copy springboot property file - into ('/etc/hirs/aca/') { - from '../HIRS_AttestationCAPortal/src/main/resources/application.properties' - from 'build/VERSION' + into('/etc/hirs/aca/') { + from '../HIRS_AttestationCAPortal/src/main/resources/application.properties' + from 'build/VERSION' } // copy setup scripts to /opt/hirs/aca - into ('/opt/hirs/aca/scripts/') { - from '../package/linux/' + into('/opt/hirs/aca/scripts/') { + from '../package/linux/' } // copy the war file into /opt/hirs/aca - into ('/opt/hirs/aca/') { - from '../HIRS_AttestationCAPortal/build/libs/HIRS_AttestationCAPortal.war' - user 'root' - fileMode = 0755 + into('/opt/hirs/aca/') { + from '../HIRS_AttestationCAPortal/build/libs/HIRS_AttestationCAPortal.war' + user 'root' + fileMode = 0755 } // Install - check for existing setup @@ -152,12 +152,12 @@ ospackage { postUninstall 'if [ -d /opt/hirs ]; then rm -rf /opt/hirs; fi;' buildRpm { - dependsOn ':HIRS_AttestationCAPortal:buildVersion' - dependsOn ':HIRS_AttestationCAPortal:bootWar' + dependsOn ':HIRS_AttestationCAPortal:buildVersion' + dependsOn ':HIRS_AttestationCAPortal:bootWar' arch = X86_64 // Required apps will be aut installed by dnf if not present requires('java-17-openjdk', '17.0', GREATER | EQUAL) - requires('mariadb-server' , '10.3' , GREATER | EQUAL) + requires('mariadb-server', '10.3', GREATER | EQUAL) requires('procps-ng', '3.3.15', GREATER | EQUAL) requires('alternatives', '1.19', GREATER | EQUAL) requires('hwdata', '0.314', GREATER | EQUAL) @@ -175,12 +175,12 @@ ospackage { } buildDeb { - dependsOn ':HIRS_AttestationCAPortal:buildVersion' - dependsOn ':HIRS_AttestationCAPortal:bootWar' + dependsOn ':HIRS_AttestationCAPortal:buildVersion' + dependsOn ':HIRS_AttestationCAPortal:bootWar' packageName = 'hirs-attestationca' arch = 'amd64' requires('openjdk-17-jdk', '17.0', GREATER | EQUAL) - requires('mariadb-server' , '10.3' , GREATER | EQUAL) + requires('mariadb-server', '10.3', GREATER | EQUAL) requires('curl') requires('hwdata', '0.314', GREATER | EQUAL) // Install after required packages diff --git a/HIRS_AttestationCAPortal/config/spotbugs/spotbugs-exclude.xml b/HIRS_AttestationCAPortal/config/spotbugs/spotbugs-exclude.xml index a78c5f3d..9460d1e7 100644 --- a/HIRS_AttestationCAPortal/config/spotbugs/spotbugs-exclude.xml +++ b/HIRS_AttestationCAPortal/config/spotbugs/spotbugs-exclude.xml @@ -2,11 +2,11 @@ - + - + diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/HIRSApplication.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/HIRSApplication.java index 1207576f..29cc4b85 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/HIRSApplication.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/HIRSApplication.java @@ -1,23 +1,15 @@ package hirs.attestationca.portal; -import jakarta.servlet.ServletContext; -import jakarta.servlet.ServletException; -import jakarta.servlet.ServletRegistration; import lombok.extern.log4j.Log4j2; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.springframework.web.context.support.GenericWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -import java.util.Collections; +@SuppressWarnings("checkstyle:hideutilityclassconstructor") @SpringBootApplication //@EnableAutoConfiguration @Log4j2 -public class HIRSApplication {//extends SpringBootServletInitializer { +public class HIRSApplication { + //extends SpringBootServletInitializer { // private static final Logger LOGGER = LogManager.getLogger(HIRSApplication.class); // @Override // protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { @@ -32,9 +24,15 @@ public class HIRSApplication {//extends SpringBootServletInitializer { // appServlet.setLoadOnStartup(1); // } - public static void main(String[] args) { + /** + * This is the starting point of the HIRS application. + * + * @param args main method arguments + */ + public static void main(final String[] args) { // SpringApplication springApplication = new SpringApplication(HIRSApplication.class); -// springApplication.setDefaultProperties(Collections.singletonMap("server.servlet.context-path", "/portal")); +// springApplication.setDefaultProperties(Collections.singletonMap("server.servlet.context-path", +// "/portal")); // springApplication.run(args); SpringApplication.run(HIRSApplication.class, args); } diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/HIRSDbInitializer.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/HIRSDbInitializer.java index c42b7dfa..3594a4c5 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/HIRSDbInitializer.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/HIRSDbInitializer.java @@ -11,8 +11,14 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatche @Log4j2 @WebListener -public class HIRSDbInitializer extends AbstractAnnotationConfigDispatcherServletInitializer implements ServletContextListener { +public class HIRSDbInitializer extends AbstractAnnotationConfigDispatcherServletInitializer + implements ServletContextListener { + /** + * Initialize context. + * + * @param servletContextEvent servlet context event. + */ @Override public void contextInitialized(final ServletContextEvent servletContextEvent) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); @@ -21,29 +27,46 @@ public class HIRSDbInitializer extends AbstractAnnotationConfigDispatcherServlet // applicationContext.register(PersistenceConfiguration.class); try { - applicationContext.refresh(); + applicationContext.refresh(); } catch (NoSuchBeanDefinitionException nsbdEx) { if (log.isDebugEnabled()) { - log.debug("Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided"); + log.debug( + "Unable to locate MultipartResolver with name 'multipartResolver': no multipart" + + " request handling provided"); } } catch (Exception ex) { log.error(ex.getMessage()); } } + /** + * Retrieves root configuration classes. + * + * @return array of root configuration classes. + */ @Override - protected Class [] getRootConfigClasses() { + protected Class[] getRootConfigClasses() { return new Class[] { PersistenceJPAConfig.class, PageConfiguration.class, PersistenceConfiguration.class }; } + /** + * Retrieves servlet configuration classes. + * + * @return null + */ @Override - protected Class [] getServletConfigClasses() { + protected Class[] getServletConfigClasses() { return null; } + /** + * Retrieves servlet mappings. + * + * @return string array of servlet mappings. + */ @Override protected String[] getServletMappings() { return new String[] { diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/PersistenceJPAConfig.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/PersistenceJPAConfig.java index f969f751..36ce7d06 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/PersistenceJPAConfig.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/PersistenceJPAConfig.java @@ -56,10 +56,12 @@ import java.util.Properties; ignoreResourceNotFound = true), @PropertySource(value = "file:/etc/hirs/aca/application.properties", ignoreResourceNotFound = true), - @PropertySource(value = "file:C:/ProgramData/hirs/aca/application.win.properties", + @PropertySource(value = "file:C:/ProgramData/hirs/aca/application.win.properties", ignoreResourceNotFound = true) }) -@ComponentScan({"hirs.attestationca.portal", "hirs.attestationca.portal.page.controllers", "hirs.attestationca.persist", "hirs.attestationca.persist.entity", "hirs.attestationca.persist.service"}) +@ComponentScan({"hirs.attestationca.portal", "hirs.attestationca.portal.page.controllers", + "hirs.attestationca.persist", "hirs.attestationca.persist.entity", + "hirs.attestationca.persist.service"}) @EnableJpaRepositories(basePackages = "hirs.attestationca.persist.entity.manager") public class PersistenceJPAConfig implements WebMvcConfigurer { @@ -78,9 +80,15 @@ public class PersistenceJPAConfig implements WebMvcConfigurer { @Autowired private Environment environment; + /** + * Entity manager factory bean. + * + * @return a local container entity manager factory bean + */ @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - final LocalContainerEntityManagerFactoryBean entityManagerBean = new LocalContainerEntityManagerFactoryBean(); + final LocalContainerEntityManagerFactoryBean entityManagerBean = + new LocalContainerEntityManagerFactoryBean(); entityManagerBean.setDataSource(dataSource()); entityManagerBean.setPackagesToScan("hirs.attestationca.persist.entity"); @@ -91,6 +99,11 @@ public class PersistenceJPAConfig implements WebMvcConfigurer { return entityManagerBean; } + /** + * Data source bean. + * + * @return a data source + */ @Bean public DataSource dataSource() { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); @@ -210,6 +223,11 @@ public class PersistenceJPAConfig implements WebMvcConfigurer { } } + /** + * Platform Transaction Manager bean. + * + * @return platform transaction manager bean + */ @Bean public PlatformTransactionManager transactionManager() { final JpaTransactionManager transactionManager = new JpaTransactionManager(); @@ -217,6 +235,11 @@ public class PersistenceJPAConfig implements WebMvcConfigurer { return transactionManager; } + /** + * Persistence Exception Translation Post Processor bean. + * + * @return persistence exception translation post processor bean + */ @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { return new PersistenceExceptionTranslationPostProcessor(); @@ -248,12 +271,18 @@ public class PersistenceJPAConfig implements WebMvcConfigurer { // @Bean(name="default-settings") // public PolicySettings supplyChainSettings() { -// PolicySettings scSettings = new PolicySettings("Default", "Settings are configured for no validation flags set."); +// PolicySettings scSettings = new PolicySettings("Default", "Settings are configured for no +// validation flags set."); // // return scSettings; // } + /** + * Configures the default servlet handling. + * + * @param configurer default servlet handler configurer. + */ @Override public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { configurer.enable(); diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Column.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Column.java index 147fa274..2e8d465d 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Column.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Column.java @@ -3,11 +3,11 @@ package hirs.attestationca.portal.datatables; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; -import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import lombok.ToString; /** * Java representation of a jQuery DataTables Column. @@ -15,7 +15,8 @@ import lombok.Setter; @Getter @Setter @AllArgsConstructor -@NoArgsConstructor(access = AccessLevel.PUBLIC) +@NoArgsConstructor +@ToString public class Column { /** @@ -64,14 +65,4 @@ public class Column { this.search.setValue(searchValue); } - @Override - public String toString() { - return "Column{" - + "data='" + data + '\'' - + ", name='" + name + '\'' - + ", searchable=" + searchable - + ", orderable=" + orderable - + ", search=" + search - + '}'; - } } diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableInput.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableInput.java index ee6256c7..fcfab95c 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableInput.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableInput.java @@ -3,10 +3,10 @@ package hirs.attestationca.portal.datatables; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; -import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import lombok.ToString; import org.apache.commons.lang3.StringUtils; import org.springframework.util.CollectionUtils; @@ -18,18 +18,66 @@ import java.util.Map; /** * Represents a data table input in a jQuery DataTable. */ -@NoArgsConstructor(access = AccessLevel.PUBLIC) +@Getter +@NoArgsConstructor +@ToString public class DataTableInput { private static final int DEFAULT_LENGTH = 10; + /** + * Order parameter. + */ + @NotEmpty + private final List order = new ArrayList<>(); + /** + * Per-column search parameter. + */ + @NotEmpty + private final List columns = new ArrayList<>(); + /** + * Draw counter. This is used by DataTables to ensure that the Ajax returns from server-side + * processing requests are drawn in sequence by DataTables (Ajax requests are asynchronous and + * thus can return out of sequence). This is used as part of the draw return parameter (see + * below). + */ + @NotNull + @Min(0) + @Setter + private int draw = 1; + /** + * Paging first record indicator. This is the start point in the current data set + * (0 index based - i.e. 0 is the first record). + */ + @NotNull + @Min(0) + @Setter + private int start = 0; + /** + * Number of records that the table can display in the current draw. It is expected that the + * number of records returned will be equal to this number, + * unless the server has fewer records to return. Note that this can be -1 to indicate that + * all records should be returned (although that + * negates any benefits of server-side processing!) + */ + @NotNull + @Min(-1) + @Setter + private int length = DEFAULT_LENGTH; + /** + * Global search parameter. + */ + @Setter + @NotNull + private Search search = new Search(); /** * Constructor. - * @param draw the draw counter - * @param start the paging start indicator - * @param length the number of records in current draw - * @param search the search parameter - * @param order the orderings + * + * @param draw the draw counter + * @param start the paging start indicator + * @param length the number of records in current draw + * @param search the search parameter + * @param order the orderings * @param columns the columns of the input */ public DataTableInput(final Integer draw, final Integer start, final Integer length, @@ -43,65 +91,9 @@ public class DataTableInput { this.columns.addAll(columns); } - /** - * Draw counter. This is used by DataTables to ensure that the Ajax returns from server-side - * processing requests are drawn in sequence by DataTables (Ajax requests are asynchronous and - * thus can return out of sequence). This is used as part of the draw return parameter (see - * below). - */ - @NotNull - @Min(0) - @Getter - @Setter - private int draw = 1; - - /** - * Paging first record indicator. This is the start point in the current data set - * (0 index based - i.e. 0 is the first record). - */ - @NotNull - @Min(0) - @Getter - @Setter - private int start = 0; - - /** - * Number of records that the table can display in the current draw. It is expected that the - * number of records returned will be equal to this number, - * unless the server has fewer records to return. Note that this can be -1 to indicate that - * all records should be returned (although that - * negates any benefits of server-side processing!) - */ - @NotNull - @Min(-1) - @Getter - @Setter - private int length = DEFAULT_LENGTH; - - /** - * Global search parameter. - */ - @Getter - @Setter - @NotNull - private Search search = new Search(); - - /** - * Order parameter. - */ - @Getter - @NotEmpty - private List order = new ArrayList<>(); - - /** - * Per-column search parameter. - */ - @Getter - @NotEmpty - private List columns = new ArrayList<>(); - /** * Sets the orders. + * * @param order the orders */ public void setOrder(final List order) { @@ -111,6 +103,7 @@ public class DataTableInput { /** * Sets the table columns. + * * @param columns the columns */ public void setColumns(final List columns) { @@ -119,7 +112,6 @@ public class DataTableInput { } /** - * * @return a {@link Map} of {@link Column} indexed by name */ public Map getColumnsAsMap() { @@ -151,9 +143,9 @@ public class DataTableInput { /** * Add a new column. * - * @param columnName the name of the column - * @param searchable whether the column is searchable or not - * @param orderable whether the column is orderable or not + * @param columnName the name of the column + * @param searchable whether the column is searchable or not + * @param orderable whether the column is orderable or not * @param searchValue if any, the search value to apply */ public void addColumn(final String columnName, final boolean searchable, @@ -166,7 +158,7 @@ public class DataTableInput { * Add an order on the given column. * * @param columnName the name of the column - * @param ascending whether the sorting is ascending or descending + * @param ascending whether the sorting is ascending or descending */ public void addOrder(final String columnName, final boolean ascending) { if (columnName == null) { @@ -182,6 +174,7 @@ public class DataTableInput { /** * Gets the order column name, given the order ordinal value. + * * @return the order column name */ public String getOrderColumnName() { @@ -203,22 +196,4 @@ public class DataTableInput { } return orderColumnName; } - - - /** - * Generates a string for this object. - * @return the string - */ - @Override - public String toString() { - return "DataTableInput{" - + "draw=" + draw - + ", start=" + start - + ", length=" + length - + ", search=" + search - + ", order=" + order - + ", columns=" + columns - + '}'; - } } - diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableResponse.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableResponse.java index d366ea37..e5cc2ebb 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableResponse.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableResponse.java @@ -16,14 +16,20 @@ import java.util.List; * * @param the type of object that is being wrapped. */ +@Getter +@Setter @NoArgsConstructor(access = AccessLevel.PUBLIC) public final class DataTableResponse { - private List data = new LinkedList(); - @Getter @Setter + @Getter(AccessLevel.NONE) + @Setter(AccessLevel.NONE) + private final List data = new LinkedList(); + private int draw; - @Getter @Setter - private long recordsTotal, recordsFiltered; + + private long recordsTotal; + + private long recordsFiltered; /** * Builds a data table response using a FilteredRecordList. diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableView.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableView.java index 034fc819..d21b5231 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableView.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableView.java @@ -2,21 +2,22 @@ package hirs.attestationca.portal.datatables; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import java.util.Map; import jakarta.servlet.ServletOutputStream; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.MediaType; import org.springframework.web.servlet.view.AbstractUrlBasedView; +import java.util.Map; + /** * Serializes the DataTableResponse from the view as JSON and writes it to the HTTP response. - * */ public class DataTableView extends AbstractUrlBasedView { private static final Gson GSON = new GsonBuilder().create(); private static final String MODEL_FIELD; + static { final String name = DataTableResponse.class.getSimpleName(); MODEL_FIELD = name.substring(0, 1).toLowerCase() + name.substring(1); @@ -25,9 +26,9 @@ public class DataTableView extends AbstractUrlBasedView { /** * Serializes the DataTableResponse from the view as JSON and writes it to the HTTP response. * - * @param model combined output Map (never {@code null}), with dynamic values taking precedence - * over static attributes - * @param request current HTTP request + * @param model combined output Map (never {@code null}), with dynamic values taking precedence + * over static attributes + * @param request current HTTP request * @param response current HTTP response * @throws Exception if rendering failed */ diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Order.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Order.java index 80ecd80b..8aa4abcb 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Order.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Order.java @@ -3,25 +3,42 @@ package hirs.attestationca.portal.datatables; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Pattern; -import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import lombok.ToString; /** - * Represents a column ordering with regards to a jQuery DataTable. + * Represents a column ordering in regard to a jQuery DataTable. */ @Getter @Setter @AllArgsConstructor -@NoArgsConstructor(access = AccessLevel.PUBLIC) +@NoArgsConstructor +@ToString public class Order { + /** + * Column to which ordering should be applied. This is an index reference + * to the columns array of information that is also submitted to the server. + */ + @NotNull + @Min(0) + private int column; + /** + * Ordering direction for this column. It will be asc or desc to indicate ascending ordering or + * descending ordering, respectively. + */ + @NotNull + @Pattern(regexp = "(desc|asc)") + private String dir; + /** * Constructor. - * @param column the column index + * + * @param column the column index * @param isAscending true if ascending order */ public Order(final int column, final boolean isAscending) { @@ -33,40 +50,11 @@ public class Order { } } - /** - * Column to which ordering should be applied. This is an index reference - * to the columns array of information that is also submitted to the server. - */ - @NotNull - @Min(0) - private int column; - - /** - * Ordering direction for this column. It will be asc or desc to indicate ascending ordering or - * descending ordering, respectively. - */ - @NotNull - @Pattern(regexp = "(desc|asc)") - private String dir; - - /** - * * @return true if ascending order, false otherwise. */ public boolean isAscending() { - if (dir.equalsIgnoreCase("asc")) { - return true; - } - return false; - } - - @Override - public String toString() { - return "Order{" - + "column=" + column - + ", dir='" + dir + '\'' - + '}'; + return dir.equalsIgnoreCase("asc"); } } diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/OrderedListQueryDataTableAdapter.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/OrderedListQueryDataTableAdapter.java index 518fa12b..160fb169 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/OrderedListQueryDataTableAdapter.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/OrderedListQueryDataTableAdapter.java @@ -5,8 +5,6 @@ import hirs.attestationca.persist.FilteredRecordsList; import hirs.attestationca.persist.entity.userdefined.rim.ReferenceDigestValue; import jakarta.persistence.EntityManager; import jakarta.persistence.criteria.CriteriaQuery; -import lombok.AccessLevel; -import lombok.NoArgsConstructor; import lombok.extern.log4j.Log4j2; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.util.CollectionUtils; @@ -20,19 +18,26 @@ import java.util.UUID; /** * A class to adapt the Javascript DataTable java class abstractions to the DBManager's getting * of ordered lists. + * * @param The type of object to query */ -@NoArgsConstructor(access = AccessLevel.PRIVATE) @Log4j2 public final class OrderedListQueryDataTableAdapter { + /** + * Private constructor was created to silence checkstyle error. + */ + private OrderedListQueryDataTableAdapter() { + } + /** * Gets the ordered list of records using a default, no-op criteria modifier. - * @param clazz the type of objects to query for - * @param dbManager the db manager to execute the actual query - * @param dataTableInput the JS DataTable query abstraction + * + * @param clazz the type of objects to query for + * @param dbManager the db manager to execute the actual query + * @param dataTableInput the JS DataTable query abstraction * @param orderColumnName the name of the column (java object field name) to query on - * @param the parameter type + * @param the parameter type * @return the filtered record list */ public static FilteredRecordsList getOrderedList(final Class clazz, @@ -51,12 +56,13 @@ public final class OrderedListQueryDataTableAdapter { /** * Gets the ordered list of records. - * @param clazz the type of objects to query for - * @param dbManager the db manager to execute the actual query - * @param dataTableInput the JS DataTable query abstraction - * @param orderColumnName the name of the column (java object field name) to query on + * + * @param clazz the type of objects to query for + * @param dbManager the db manager to execute the actual query + * @param dataTableInput the JS DataTable query abstraction + * @param orderColumnName the name of the column (java object field name) to query on * @param criteriaModifier the criteria modifier - * @param the parameter type + * @param the parameter type * @return the filtered record list */ public static FilteredRecordsList getOrderedList(final Class clazz, @@ -82,7 +88,8 @@ public final class OrderedListQueryDataTableAdapter { filteredRecordsList.setRecordsTotal(dbManager.count()); filteredRecordsList.addAll((Collection) dbManager.findAll()); - filteredRecordsList.setRecordsFiltered(10); + final int recordsFilteredConstant = 10; + filteredRecordsList.setRecordsFiltered(recordsFilteredConstant); return filteredRecordsList; @@ -92,11 +99,22 @@ public final class OrderedListQueryDataTableAdapter { // searchableColumnMap, criteriaModifier); } - public static FilteredRecordsList getOrderedList(final JpaRepository dbManager, - final DataTableInput dataTableInput, - final String orderColumnName, - final CriteriaModifier criteriaModifier, - final EntityManager entityManager) { + /** + * Retrieves an ordered list of reference digest values. + * + * @param dbManager database manager. + * @param dataTableInput data table input. + * @param orderColumnName string representation of the order column name. + * @param criteriaModifier criteria modifier. + * @param entityManager entity manager. + * @return a filtered, ordered records list of the reference digest values + */ + public static FilteredRecordsList getOrderedList( + final JpaRepository dbManager, + final DataTableInput dataTableInput, + final String orderColumnName, + final CriteriaModifier criteriaModifier, + final EntityManager entityManager) { Map searchableColumnMap = new HashMap<>(); for (Column column : dataTableInput.getColumns()) { @@ -121,10 +139,10 @@ public final class OrderedListQueryDataTableAdapter { FilteredRecordsList filteredRecordsList = new FilteredRecordsList<>(); - filteredRecordsList.setRecordsTotal(dbManager.count()); filteredRecordsList.addAll(dbManager.findAll()); - filteredRecordsList.setRecordsFiltered(10); + final int recordsFilteredConstant = 10; + filteredRecordsList.setRecordsFiltered(recordsFilteredConstant); return filteredRecordsList; diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Search.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Search.java index c8d206d5..6f961d48 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Search.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Search.java @@ -1,11 +1,11 @@ package hirs.attestationca.portal.datatables; import jakarta.validation.constraints.NotNull; -import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import lombok.ToString; /** * Represents a jQuery DataTables search parameter. @@ -13,23 +13,15 @@ import lombok.Setter; @Getter @Setter @AllArgsConstructor -@NoArgsConstructor(access = AccessLevel.PUBLIC) +@NoArgsConstructor +@ToString public class Search { - /** - * Constructor for a non-regex search. - * @param value the search value - */ - public Search(final String value) { - this(value, false); - } - /** * Global search value. To be applied to all columns which have searchable as true. */ @NotNull private String value = ""; - /** * true if the global filter should be treated as a regular expression for advanced searching, * false otherwise. Note that normally server-side processing scripts will not perform regular @@ -39,12 +31,13 @@ public class Search { @NotNull private boolean regex; - @Override - public String toString() { - return "Search{" - + "value='" + value + '\'' - + ", regex=" + regex - + '}'; + /** + * Constructor for a non-regex search. + * + * @param value the search value + */ + public Search(final String value) { + this(value, false); } } diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/package-info.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/package-info.java new file mode 100644 index 00000000..d7bdd760 --- /dev/null +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.portal.datatables; diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/listener/AnnotationDrivenEndpointsListener.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/listener/AnnotationDrivenEndpointsListener.java index 0a990bd4..57abcc06 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/listener/AnnotationDrivenEndpointsListener.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/listener/AnnotationDrivenEndpointsListener.java @@ -15,8 +15,13 @@ import java.util.Map; @Configuration public class AnnotationDrivenEndpointsListener { + /** + * Annotation Driven Endpoints event listener. + * + * @param event context refreshed event. + */ @EventListener - public void handleContextRefresh(ContextRefreshedEvent event) { + public void handleContextRefresh(final ContextRefreshedEvent event) { ApplicationContext applicationContext = event.getApplicationContext(); RequestMappingHandlerMapping requestMappingHandlerMapping = applicationContext .getBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class); diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/listener/package-info.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/listener/package-info.java new file mode 100644 index 00000000..9f6fb6a5 --- /dev/null +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/listener/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.portal.listener; diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/Page.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/Page.java index eb39cf5e..49fbf333 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/Page.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/Page.java @@ -86,13 +86,13 @@ public enum Page { /** * Constructor for Page. * - * @param title title of the page - * @param subtitle subtitle of the page - * @param icon icon for the page - * @param hasMenu the page has its own menu - * @param inMenu the page appears in a menu + * @param title title of the page + * @param subtitle subtitle of the page + * @param icon icon for the page + * @param hasMenu the page has its own menu + * @param inMenu the page appears in a menu * @param menuLinkClass the category to which this page belongs - * @param prefixPath prefix path that appears in the URL for this page + * @param prefixPath prefix path that appears in the URL for this page */ Page(final String title, final String subtitle, @@ -115,10 +115,10 @@ public enum Page { /** * Constructor for Page. * - * @param title title of the page - * @param icon icon for the page + * @param title title of the page + * @param icon icon for the page * @param menuLinkClass the category to which this page belongs - * @param prefixPath prefix path that appears in the URL for this page + * @param prefixPath prefix path that appears in the URL for this page */ Page(final String title, final String icon, @@ -130,8 +130,8 @@ public enum Page { /** * Constructor for Page. * - * @param title title of the page - * @param icon icon for the page + * @param title title of the page + * @param icon icon for the page * @param menuLinkClass the category to which this page belongs */ Page(final String title, @@ -144,7 +144,7 @@ public enum Page { * Constructor for Page. * * @param title title of the page - * @param icon icon for the page + * @param icon icon for the page */ Page(final String title, final String icon) { diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/PageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/PageController.java index 13cf7455..e4a60827 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/PageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/PageController.java @@ -61,8 +61,8 @@ public abstract class PageController

{ * Returns the path for the view and the data model for the page. * * @param params The object to map url parameters into. - * @param model The data model for the request. Can contain data from - * redirect. + * @param model The data model for the request. Can contain data from + * redirect. * @return the path for the view and data model for the page. */ @RequestMapping @@ -110,8 +110,8 @@ public abstract class PageController

{ * Redirects back to this controller's page with the specified data. * * @param params The url parameters to pass to the page. - * @param model The model data to pass to the page. - * @param attr The request's RedirectAttributes to hold the model data. + * @param model The model data to pass to the page. + * @param attr The request's RedirectAttributes to hold the model data. * @return RedirectView back to the page with the specified parameters. * @throws URISyntaxException if malformed URI */ @@ -127,9 +127,9 @@ public abstract class PageController

{ * Redirects controller's page with the specified data. * * @param newPage new page to get the model and view - * @param params The url parameters to pass to the page. - * @param model The model data to pass to the page. - * @param attr The request's RedirectAttributes to hold the model data. + * @param params The url parameters to pass to the page. + * @param model The model data to pass to the page. + * @param attr The request's RedirectAttributes to hold the model data. * @return RedirectView back to the page with the specified parameters. * @throws URISyntaxException if malformed URI */ diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/PageParams.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/PageParams.java index c035fb26..0771facd 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/PageParams.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/PageParams.java @@ -14,4 +14,4 @@ public interface PageParams { */ LinkedHashMap asMap(); -} \ No newline at end of file +} diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/CertificateDetailsPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/CertificateDetailsPageController.java index eef67603..0853d7df 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/CertificateDetailsPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/CertificateDetailsPageController.java @@ -39,9 +39,10 @@ public class CertificateDetailsPageController extends PageController { - @Autowired(required = false) - private EntityManager entityManager; - - private CertificateAuthorityCredential certificateAuthorityCredential; + /** + * Model attribute name used by initPage for the aca cert info. + */ + static final String ACA_CERT_DATA = "acaCertData"; + private static final String TRUSTCHAIN = "trust-chain"; + private static final String PLATFORMCREDENTIAL = "platform-credentials"; + private static final String IDEVIDCERTIFICATE = "idevid-certificates"; + private static final String ENDORSEMENTCREDENTIAL = "endorsement-key-credentials"; + private static final String ISSUEDCERTIFICATES = "issued-certificates"; private final CertificateRepository certificateRepository; private final PlatformCertificateRepository platformCertificateRepository; private final ComponentResultRepository componentResultRepository; @@ -92,17 +97,9 @@ public class CertificatePageController extends PageController { private final IssuedCertificateRepository issuedCertificateRepository; private final CACredentialRepository caCredentialRepository; private final IDevIDCertificateRepository iDevIDCertificateRepository; - - private static final String TRUSTCHAIN = "trust-chain"; - private static final String PLATFORMCREDENTIAL = "platform-credentials"; - private static final String IDEVIDCERTIFICATE = "idevid-certificates"; - private static final String ENDORSEMENTCREDENTIAL = "endorsement-key-credentials"; - private static final String ISSUEDCERTIFICATES = "issued-certificates"; - - /** - * Model attribute name used by initPage for the aca cert info. - */ - static final String ACA_CERT_DATA = "acaCertData"; + @Autowired(required = false) + private EntityManager entityManager; + private CertificateAuthorityCredential certificateAuthorityCredential; /** * Constructor providing the Page's display and routing specification. @@ -113,7 +110,9 @@ public class CertificatePageController extends PageController { * @param endorsementCredentialRepository the endorsement credential manager * @param issuedCertificateRepository the issued certificate manager * @param caCredentialRepository the ca credential manager - * @param acaCertificate the ACA's X509 certificate */ + * @param iDevIDCertificateRepository the IDevID certificate repository + * @param acaCertificate the ACA's X509 certificate + */ @Autowired public CertificatePageController(final CertificateRepository certificateRepository, final PlatformCertificateRepository platformCertificateRepository, @@ -142,12 +141,53 @@ public class CertificatePageController extends PageController { } } + /** + * Get the page based on the certificate type. + * + * @param certificateType String containing the certificate type + * @return the page for the certificate type. + */ + private static Page getCertificatePage(final String certificateType) { + // get page information (default to TRUST_CHAIN) + return switch (certificateType) { + case PLATFORMCREDENTIAL -> Page.PLATFORM_CREDENTIALS; + case ENDORSEMENTCREDENTIAL -> Page.ENDORSEMENT_KEY_CREDENTIALS; + case ISSUEDCERTIFICATES -> Page.ISSUED_CERTIFICATES; + case IDEVIDCERTIFICATE -> Page.IDEVID_CERTIFICATES; + default -> Page.TRUST_CHAIN; + }; + } + + /** + * Gets the concrete certificate class type to query for. + * + * @param certificateType String containing the certificate type + * @return the certificate class type + */ + private static Class getCertificateClass(final String certificateType) { + switch (certificateType) { + case PLATFORMCREDENTIAL: + return PlatformCredential.class; + case ENDORSEMENTCREDENTIAL: + return EndorsementCredential.class; + case ISSUEDCERTIFICATES: + return IssuedAttestationCertificate.class; + case IDEVIDCERTIFICATE: + return IDevIDCertificate.class; + case TRUSTCHAIN: + return CertificateAuthorityCredential.class; + default: + throw new IllegalArgumentException( + String.format("Unknown certificate type: %s", certificateType)); + } + } + /** * Returns the path for the view and the data model for the page. * * @param params The object to map url parameters into. - * @param model The data model for the request. Can contain data from - * redirect. + * @param model The data model for the request. Can contain data from + * redirect. * @return the path for the view and data model for the page. */ @Override @@ -160,9 +200,9 @@ public class CertificatePageController extends PageController { * Returns the path for the view and the data model for the page. * * @param certificateType String containing the certificate type - * @param params The object to map url parameters into. - * @param model The data model for the request. Can contain data from - * redirect. + * @param params The object to map url parameters into. + * @param model The data model for the request. Can contain data from + * redirect. * @return the path for the view and data model for the page. */ @RequestMapping("/{certificateType}") @@ -189,7 +229,8 @@ public class CertificatePageController extends PageController { mav = getBaseModelAndView(Page.TRUST_CHAIN); // Map with the ACA certificate information data.putAll(CertificateStringMapBuilder.getCertificateAuthorityInformation( - certificateAuthorityCredential, this.certificateRepository, this.caCredentialRepository)); + certificateAuthorityCredential, this.certificateRepository, + this.caCredentialRepository)); mav.addObject(ACA_CERT_DATA, data); break; default: @@ -200,13 +241,12 @@ public class CertificatePageController extends PageController { return mav; } - /** * Queries for the list of Certificates and returns a data table response * with the records. * * @param certificateType String containing the certificate type - * @param input the DataTables search/query parameters + * @param input the DataTables search/query parameters * @return the data table */ @ResponseBody @@ -216,11 +256,11 @@ public class CertificatePageController extends PageController { public DataTableResponse getTableData( @PathVariable("certificateType") final String certificateType, final DataTableInput input) { - log.debug("Handling list request: " + input); + log.debug("Handling list request: {}", input); // attempt to get the column property based on the order index. String orderColumnName = input.getOrderColumnName(); - log.debug("Ordering on column: " + orderColumnName); + log.debug("Ordering on column: {}", orderColumnName); // check that the alert is not archived and that it is in the specified report CriteriaModifier criteriaModifier = new CriteriaModifier() { @@ -229,15 +269,16 @@ public class CertificatePageController extends PageController { Session session = entityManager.unwrap(Session.class); CriteriaBuilder cb = session.getCriteriaBuilder(); Root rimRoot = criteriaQuery.from(Reference.class); - criteriaQuery.select(rimRoot).distinct(true).where(cb.isNull(rimRoot.get(Certificate.ARCHIVE_FIELD))); + criteriaQuery.select(rimRoot).distinct(true) + .where(cb.isNull(rimRoot.get(Certificate.ARCHIVE_FIELD))); // add a device alias if this query includes the device table // for getting the device (e.g. device name). // use left join, since device may be null. Query will return all // Certs of this type, whether it has a Device or not (device field may be null) - if (hasDeviceTableToJoin(certificateType)) { -// criteria.createAlias("device", "device", JoinType.LEFT_OUTER_JOIN); - } + // if (hasDeviceTableToJoin(certificateType)) { + // criteria.createAlias("device", "device", JoinType.LEFT_OUTER_JOIN); + //} } }; @@ -249,7 +290,8 @@ public class CertificatePageController extends PageController { // serial number. (pc.HolderSerialNumber = ec.SerialNumber) if (certificateType.equals(PLATFORMCREDENTIAL)) { FilteredRecordsList records = new FilteredRecordsList<>(); - org.springframework.data.domain.Page pagedResult = this.platformCertificateRepository.findByArchiveFlag(false, paging); + org.springframework.data.domain.Page pagedResult = + this.platformCertificateRepository.findByArchiveFlag(false, paging); if (pagedResult.hasContent()) { records.addAll(pagedResult.getContent()); @@ -264,7 +306,7 @@ public class CertificatePageController extends PageController { if (!records.isEmpty()) { // loop all the platform certificates for (int i = 0; i < records.size(); i++) { - PlatformCredential pc = (PlatformCredential) records.get(i); + PlatformCredential pc = records.get(i); // find the EC using the PC's "holder serial number" associatedEC = this.endorsementCredentialRepository .findBySerialNumber(pc.getHolderSerialNumber()); @@ -282,7 +324,8 @@ public class CertificatePageController extends PageController { return new DataTableResponse<>(records, input); } else if (certificateType.equals(ENDORSEMENTCREDENTIAL)) { FilteredRecordsList records = new FilteredRecordsList<>(); - org.springframework.data.domain.Page pagedResult = this.endorsementCredentialRepository.findByArchiveFlag(false, paging); + org.springframework.data.domain.Page pagedResult = + this.endorsementCredentialRepository.findByArchiveFlag(false, paging); if (pagedResult.hasContent()) { records.addAll(pagedResult.getContent()); @@ -297,7 +340,8 @@ public class CertificatePageController extends PageController { return new DataTableResponse<>(records, input); } else if (certificateType.equals(TRUSTCHAIN)) { FilteredRecordsList records = new FilteredRecordsList<>(); - org.springframework.data.domain.Page pagedResult = this.caCredentialRepository.findByArchiveFlag(false, paging); + org.springframework.data.domain.Page pagedResult = + this.caCredentialRepository.findByArchiveFlag(false, paging); if (pagedResult.hasContent()) { records.addAll(pagedResult.getContent()); @@ -312,7 +356,8 @@ public class CertificatePageController extends PageController { return new DataTableResponse<>(records, input); } else if (certificateType.equals(ISSUEDCERTIFICATES)) { FilteredRecordsList records = new FilteredRecordsList<>(); - org.springframework.data.domain.Page pagedResult = this.issuedCertificateRepository.findByArchiveFlag(false, paging); + org.springframework.data.domain.Page pagedResult = + this.issuedCertificateRepository.findByArchiveFlag(false, paging); if (pagedResult.hasContent()) { records.addAll(pagedResult.getContent()); @@ -325,8 +370,7 @@ public class CertificatePageController extends PageController { log.debug("Returning list of size: " + records.size()); return new DataTableResponse<>(records, input); - } - else if (certificateType.equals(IDEVIDCERTIFICATE)) { + } else if (certificateType.equals(IDEVIDCERTIFICATE)) { FilteredRecordsList records = new FilteredRecordsList(); org.springframework.data.domain.Page pagedResult = this.iDevIDCertificateRepository.findByArchiveFlag(false, paging); @@ -351,8 +395,8 @@ public class CertificatePageController extends PageController { * Upload and processes a credential. * * @param certificateType String containing the certificate type - * @param files the files to process - * @param attr the redirection attributes + * @param files the files to process + * @param attr the redirection attributes * @return the redirection view * @throws URISyntaxException if malformed URI */ @@ -388,9 +432,9 @@ public class CertificatePageController extends PageController { * Archives (soft delete) the credential. * * @param certificateType String containing the certificate type - * @param id the UUID of the cert to delete - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param id the UUID of the cert to delete + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return redirect to this page * @throws URISyntaxException if malformed URI */ @@ -459,9 +503,9 @@ public class CertificatePageController extends PageController { * for download. * * @param certificateType String containing the certificate type - * @param id the UUID of the cert to download - * @param response the response object (needed to update the header with the - * file name) + * @param id the UUID of the cert to download + * @param response the response object (needed to update the header with the + * file name) * @throws java.io.IOException when writing to response output stream */ @RequestMapping(value = "/{certificateType}/download", method = RequestMethod.GET) @@ -482,11 +526,10 @@ public class CertificatePageController extends PageController { // send a 404 error when invalid certificate response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { - StringBuilder fileName = new StringBuilder("filename=\""); - fileName.append(getCertificateClass(certificateType).getSimpleName()); - fileName.append("_"); - fileName.append(certificate.getSerialNumber()); - fileName.append(".cer\""); + String fileName = "filename=\"" + getCertificateClass(certificateType).getSimpleName() + + "_" + + certificate.getSerialNumber() + + ".cer\""; // Set filename for download. response.setHeader("Content-Disposition", "attachment;" + fileName); @@ -508,8 +551,7 @@ public class CertificatePageController extends PageController { * stream for download. * * @param response the response object (needed to update the header with the - * file name) - * + * file name) * @throws java.io.IOException when writing to response output stream */ @ResponseBody @@ -530,7 +572,7 @@ public class CertificatePageController extends PageController { * for download in bulk. * * @param response the response object (needed to update the header with the - * file name) + * file name) * @throws java.io.IOException when writing to response output stream */ @RequestMapping(value = "/trust-chain/bulk", method = RequestMethod.GET) @@ -546,7 +588,8 @@ public class CertificatePageController extends PageController { try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) { // get all files - bulkDownload(zipOut, this.certificateRepository.findByType("CertificateAuthorityCredential"), singleFileName); + bulkDownload(zipOut, this.certificateRepository.findByType("CertificateAuthorityCredential"), + singleFileName); // write cert to output stream } catch (IllegalArgumentException ex) { String uuidError = "Failed to parse ID from: "; @@ -561,7 +604,7 @@ public class CertificatePageController extends PageController { * for download in bulk. * * @param response the response object (needed to update the header with the - * file name) + * file name) * @throws java.io.IOException when writing to response output stream */ @RequestMapping(value = "/platform-credentials/bulk", method = RequestMethod.GET) @@ -593,7 +636,7 @@ public class CertificatePageController extends PageController { * for download in bulk. * * @param response the response object (needed to update the header with the - * file name) + * file name) * @throws java.io.IOException when writing to response output stream */ @RequestMapping(value = "/issued-certificates/bulk", method = RequestMethod.GET) @@ -610,7 +653,8 @@ public class CertificatePageController extends PageController { try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) { // get all files - bulkDownload(zipOut, this.certificateRepository.findByType("IssuedAttestationCertificate"), singleFileName); + bulkDownload(zipOut, this.certificateRepository.findByType("IssuedAttestationCertificate"), + singleFileName); // write cert to output stream } catch (IllegalArgumentException ex) { String uuidError = "Failed to parse ID from: "; @@ -625,7 +669,7 @@ public class CertificatePageController extends PageController { * for download in bulk. * * @param response the response object (needed to update the header with the - * file name) + * file name) * @throws java.io.IOException when writing to response output stream */ @RequestMapping(value = "/endorsement-key-credentials/bulk", method = RequestMethod.GET) @@ -641,7 +685,8 @@ public class CertificatePageController extends PageController { try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) { // get all files - bulkDownload(zipOut, this.certificateRepository.findByType("EndorsementCredential"), singleFileName); + bulkDownload(zipOut, this.certificateRepository.findByType("EndorsementCredential"), + singleFileName); // write cert to output stream } catch (IllegalArgumentException ex) { String uuidError = "Failed to parse ID from: "; @@ -682,55 +727,11 @@ public class CertificatePageController extends PageController { * table, false otherwise. */ private boolean hasDeviceTableToJoin(final String certificateType) { - boolean hasDevice = true; + boolean hasDevice = !certificateType.equals(TRUSTCHAIN); // Trust_Chain Credential do not contain the device table to join. - if (certificateType.equals(TRUSTCHAIN)) { - hasDevice = false; - } return hasDevice; } - /** - * Get the page based on the certificate type. - * - * @param certificateType String containing the certificate type - * @return the page for the certificate type. - */ - private static Page getCertificatePage(final String certificateType) { - // get page information (default to TRUST_CHAIN) - return switch (certificateType) { - case PLATFORMCREDENTIAL -> Page.PLATFORM_CREDENTIALS; - case ENDORSEMENTCREDENTIAL -> Page.ENDORSEMENT_KEY_CREDENTIALS; - case ISSUEDCERTIFICATES -> Page.ISSUED_CERTIFICATES; - case IDEVIDCERTIFICATE -> Page.IDEVID_CERTIFICATES; - default -> Page.TRUST_CHAIN; - }; - } - - /** - * Gets the concrete certificate class type to query for. - * - * @param certificateType String containing the certificate type - * @return the certificate class type - */ - private static Class getCertificateClass(final String certificateType) { - switch (certificateType) { - case PLATFORMCREDENTIAL: - return PlatformCredential.class; - case ENDORSEMENTCREDENTIAL: - return EndorsementCredential.class; - case ISSUEDCERTIFICATES: - return IssuedAttestationCertificate.class; - case IDEVIDCERTIFICATE: - return IDevIDCertificate.class; - case TRUSTCHAIN: - return CertificateAuthorityCredential.class; - default: - throw new IllegalArgumentException( - String.format("Unknown certificate type: %s", certificateType)); - } - } - /** * Gets the certificate by the hash code of its bytes. Looks for both * archived and unarchived certificates. @@ -769,7 +770,7 @@ public class CertificatePageController extends PageController { * Gets the certificate by the platform serial number. * * @param certificateType String containing the certificate type - * @param serialNumber the platform serial number + * @param serialNumber the platform serial number * @return the certificate or null if none is found */ private List getCertificateByBoardSN( @@ -794,15 +795,15 @@ public class CertificatePageController extends PageController { * with error messages if parsing fails. * * @param certificateType String containing the certificate type - * @param file the file being uploaded from the portal - * @param messages contains any messages that will be display on the page + * @param file the file being uploaded from the portal + * @param messages contains any messages that will be display on the page * @return the parsed certificate or null if parsing failed. */ private Certificate parseCertificate( final String certificateType, final MultipartFile file, final PageMessages messages) { - log.info("Received File of Size: " + file.getSize()); + log.info("Received File of Size: {}", file.getSize()); byte[] fileBytes; String fileName = file.getOriginalFilename(); @@ -835,13 +836,15 @@ public class CertificatePageController extends PageController { storeCertificate( certificateType, file.getOriginalFilename(), - messages, new CertificateAuthorityCredential(((java.security.cert.Certificate) i.next()).getEncoded())); + messages, new CertificateAuthorityCredential( + ((java.security.cert.Certificate) i.next()).getEncoded())); } // stop the main thread from saving/storing return null; } catch (CertificateException e) { - throw new IOException("Cannot construct X509Certificate from the input stream", e); + throw new IOException("Cannot construct X509Certificate from the input stream", + e); } } return new CertificateAuthorityCredential(fileBytes); @@ -930,7 +933,7 @@ public class CertificatePageController extends PageController { return; } } - } /**else { + } /*else { // this is a delta, check if the holder exists. PlatformCredential holderPC = PlatformCredential .select(certificateManager) @@ -947,7 +950,7 @@ public class CertificatePageController extends PageController { LOGGER.error(failMessage); return; } - }**/ + }*/ } this.certificateRepository.save(certificate); diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/DevicePageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/DevicePageController.java index 4b475c35..56dd1982 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/DevicePageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/DevicePageController.java @@ -6,15 +6,12 @@ import hirs.attestationca.persist.entity.manager.DeviceRepository; import hirs.attestationca.persist.entity.manager.EndorsementCredentialRepository; import hirs.attestationca.persist.entity.manager.IssuedCertificateRepository; import hirs.attestationca.persist.entity.manager.PlatformCertificateRepository; -import hirs.attestationca.persist.entity.userdefined.Certificate; import hirs.attestationca.persist.entity.userdefined.Device; -import hirs.attestationca.persist.entity.userdefined.certificate.DeviceAssociatedCertificate; import hirs.attestationca.persist.entity.userdefined.certificate.EndorsementCredential; import hirs.attestationca.persist.entity.userdefined.certificate.IssuedAttestationCertificate; import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredential; import hirs.attestationca.portal.datatables.DataTableInput; import hirs.attestationca.portal.datatables.DataTableResponse; -import hirs.attestationca.portal.datatables.OrderedListQueryDataTableAdapter; import hirs.attestationca.portal.page.Page; import hirs.attestationca.portal.page.PageController; import hirs.attestationca.portal.page.params.NoPageParams; @@ -26,8 +23,8 @@ import org.springframework.data.domain.Sort; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; @@ -52,6 +49,15 @@ public class DevicePageController extends PageController { private final EndorsementCredentialRepository endorsementCredentialRepository; private final IssuedCertificateRepository issuedCertificateRepository; + /** + * Device Page Controller constructor. + * + * @param deviceRepository device repository. + * @param certificateRepository certificate repository. + * @param platformCertificateRepository platform certificate repository. + * @param endorsementCredentialRepository endorsement credential repository. + * @param issuedCertificateRepository issued certificate repository. + */ @Autowired public DevicePageController(final DeviceRepository deviceRepository, final CertificateRepository certificateRepository, @@ -66,21 +72,34 @@ public class DevicePageController extends PageController { this.issuedCertificateRepository = issuedCertificateRepository; } + /** + * Initializes page. + * + * @param params The object to map url parameters into. + * @param model The data model for the request. Can contain data from + * redirect. + * @return model and view + */ @Override @RequestMapping public ModelAndView initPage(final NoPageParams params, final Model model) { return getBaseModelAndView(); } + /** + * GET request that retrieves table data using the provided data table input. + * + * @param input data table input. + * @return a data table response + */ @ResponseBody - @RequestMapping(value = "/list", - produces = MediaType.APPLICATION_JSON_VALUE, - method = RequestMethod.GET) + @GetMapping(value = "/list", + produces = MediaType.APPLICATION_JSON_VALUE) public DataTableResponse> getTableData( final DataTableInput input) { log.debug("Handling request for device list"); String orderColumnName = input.getOrderColumnName(); - log.info("Ordering on column: " + orderColumnName); + log.info("Ordering on column: {}", orderColumnName); // get all the devices FilteredRecordsList deviceList = new FilteredRecordsList<>(); @@ -105,6 +124,7 @@ public class DevicePageController extends PageController { /** * Returns the list of devices combined with the certificates. + * * @param deviceList list containing the devices * @return a record list after the device and certificate was mapped together. */ @@ -209,11 +229,12 @@ public class DevicePageController extends PageController { /** * Returns the list of devices IDs. + * * @param deviceList list containing the devices * @return a list of the devices IDs */ private List getDevicesId(final FilteredRecordsList deviceList) { - List deviceIds = new ArrayList<>(); + List deviceIds = new ArrayList<>(); // loop all the devices for (int i = 0; i < deviceList.size(); i++) { @@ -223,4 +244,4 @@ public class DevicePageController extends PageController { return deviceIds; } -} \ No newline at end of file +} diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ErrorController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ErrorController.java index 90391ffd..b3aab1e7 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ErrorController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ErrorController.java @@ -9,8 +9,15 @@ import org.springframework.web.servlet.ModelAndView; @Controller("error") public class ErrorController { + /** + * Handles exceptions based on the provided request and exception. + * + * @param request http servlet request. + * @param ex exception. + * @return model and view + */ @ExceptionHandler(Exception.class) - public ModelAndView handleException(HttpServletRequest request, Exception ex) { + public ModelAndView handleException(final HttpServletRequest request, final Exception ex) { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("exception", ex.getLocalizedMessage()); diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/HelpPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/HelpPageController.java index 0f874f93..0bb6909e 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/HelpPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/HelpPageController.java @@ -23,11 +23,10 @@ import static hirs.attestationca.portal.page.Page.HELP; @RequestMapping("/HIRS_AttestationCAPortal/portal/help") public class HelpPageController extends PageController { + private static final String PATH = "/docs"; @Autowired private ApplicationContext applicationContext; - private static final String PATH = "/docs"; - /** * Constructor providing the Page's display and routing specification. */ @@ -39,7 +38,7 @@ public class HelpPageController extends PageController { * Returns the path for the view and the data model for the page. * * @param params The object to map url parameters into. - * @param model The data model for the request. Can contain data from redirect. + * @param model The data model for the request. Can contain data from redirect. * @return the path for the view and data model for the page. */ @Override diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/IndexPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/IndexPageController.java index 6a223db5..eb4f7911 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/IndexPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/IndexPageController.java @@ -29,7 +29,7 @@ public class IndexPageController extends PageController { * Returns the path for the view and the data model for the page. * * @param params The object to map url parameters into. - * @param model The data model for the request. Can contain data from redirect. + * @param model The data model for the request. Can contain data from redirect. * @return the path for the view and data model for the page. */ @Override diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/LombokLoggingController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/LombokLoggingController.java index f1e9bbe8..c4b0b93f 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/LombokLoggingController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/LombokLoggingController.java @@ -8,6 +8,11 @@ import org.springframework.web.bind.annotation.RestController; @Log4j2 public class LombokLoggingController { + /** + * REST endpoint that logs various issues regarding Lombok. + * + * @return a message that indicates there are logs regarding Lombok that should be looked at + */ @RequestMapping("/HIRS_AttestationCAPortal/portal/lombok") public String index() { log.trace("A TRACE Message"); diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/PolicyPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/PolicyPageController.java index eba8ad7f..ecd94bc8 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/PolicyPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/PolicyPageController.java @@ -31,27 +31,23 @@ import java.util.Map; @RequestMapping("/HIRS_AttestationCAPortal/portal/policy") public class PolicyPageController extends PageController { - /** - * Represents a web request indicating to enable a setting (based on radio - * buttons from a web form). - */ - private static final String ENABLED_CHECKED_PARAMETER_VALUE = "checked"; - - private static final String ENABLED_EXPIRES_PARAMETER_VALUE = "expires"; - - private final PolicyRepository policyRepository; - /** * Model attribute name used by initPage for the initial data passed to the * page. */ public static final String INITIAL_DATA = "initialData"; - /** * Flash attribute name used by initPage and post for the data forwarded * during the redirect from the POST operation back to the page. */ public static final String RESULT_DATA = "resultData"; + /** + * Represents a web request indicating to enable a setting (based on radio + * buttons from a web form). + */ + private static final String ENABLED_CHECKED_PARAMETER_VALUE = "checked"; + private static final String ENABLED_EXPIRES_PARAMETER_VALUE = "expires"; + private final PolicyRepository policyRepository; /** * Constructor. @@ -69,12 +65,31 @@ public class PolicyPageController extends PageController { } } + /** + * Takes in policy setting states and determines if policy configuration is + * valid or not. PC Attribute Validation must have PC Validation Enabled PC + * Validation must have EC Validation enabled + * + * @param isEcEnable EC Validation Policy State + * @param isPcEnable PC Validation Policy State + * @param isPcAttEnable PC Attribute Validation Policy State + * @return True if policy combination is valid + */ + private static boolean isPolicyValid(final boolean isEcEnable, final boolean isPcEnable, + final boolean isPcAttEnable) { + if (isPcAttEnable && !isPcEnable) { + return false; + } else { + return !isPcEnable || isEcEnable; + } + } + /** * Returns the path for the view and the data model for the page. * * @param params The object to map url parameters into. - * @param model The data model for the request. Can contain data from - * redirect. + * @param model The data model for the request. Can contain data from + * redirect. * @return the path for the view and data model for the page. */ @Override @@ -98,8 +113,8 @@ public class PolicyPageController extends PageController { * the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -149,8 +164,8 @@ public class PolicyPageController extends PageController { * redirects back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -199,14 +214,15 @@ public class PolicyPageController extends PageController { * redirects back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @RequestMapping(value = "update-revision-ignore", method = RequestMethod.POST) public RedirectView updateIgnoreRevisionAttribute(@ModelAttribute final PolicyPageModel ppModel, - final RedirectAttributes attr) throws URISyntaxException { + final RedirectAttributes attr) + throws URISyntaxException { // set the data received to be populated back into the form Map model = new HashMap<>(); PageMessages messages = new PageMessages(); @@ -250,7 +266,7 @@ public class PolicyPageController extends PageController { * back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original page. + * @param attr RedirectAttributes used to forward data back to the original page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -294,7 +310,7 @@ public class PolicyPageController extends PageController { * back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original page. + * @param attr RedirectAttributes used to forward data back to the original page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -339,7 +355,7 @@ public class PolicyPageController extends PageController { * back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original page. + * @param attr RedirectAttributes used to forward data back to the original page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -409,7 +425,7 @@ public class PolicyPageController extends PageController { * back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original page. + * @param attr RedirectAttributes used to forward data back to the original page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -479,7 +495,7 @@ public class PolicyPageController extends PageController { * back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original page. + * @param attr RedirectAttributes used to forward data back to the original page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -550,7 +566,7 @@ public class PolicyPageController extends PageController { * back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original page. + * @param attr RedirectAttributes used to forward data back to the original page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -619,8 +635,8 @@ public class PolicyPageController extends PageController { * redirects back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -671,8 +687,8 @@ public class PolicyPageController extends PageController { * redirects back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -728,8 +744,8 @@ public class PolicyPageController extends PageController { * redirects back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -779,8 +795,8 @@ public class PolicyPageController extends PageController { * redirects back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -830,8 +846,8 @@ public class PolicyPageController extends PageController { * redirects back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -881,8 +897,8 @@ public class PolicyPageController extends PageController { * redirects back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -946,25 +962,6 @@ public class PolicyPageController extends PageController { model.put(MESSAGES_ATTRIBUTE, messages); } - /** - * Takes in policy setting states and determines if policy configuration is - * valid or not. PC Attribute Validation must have PC Validation Enabled PC - * Validation must have EC Validation enabled - * - * @param isEcEnable EC Validation Policy State - * @param isPcEnable PC Validation Policy State - * @param isPcAttEnable PC Attribute Validation Policy State - * @return True if policy combination is valid - */ - private static boolean isPolicyValid(final boolean isEcEnable, final boolean isPcEnable, - final boolean isPcAttEnable) { - if (isPcAttEnable && !isPcEnable) { - return false; - } else { - return !isPcEnable || isEcEnable; - } - } - /** * Helper function to get a fresh load of the default policy from the DB. * @@ -985,7 +982,7 @@ public class PolicyPageController extends PageController { * model. * * @param ppModel the page model - * @param model the map of string messages to be displayed on the view + * @param model the map of string messages to be displayed on the view * @return The default Supply Chain Policy */ private PolicySettings getDefaultPolicyAndSetInModel( diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java index b89c78b7..ea440af0 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java @@ -19,8 +19,8 @@ import hirs.attestationca.portal.page.Page; import hirs.attestationca.portal.page.PageController; import hirs.attestationca.portal.page.PageMessages; import hirs.attestationca.portal.page.params.ReferenceManifestDetailsPageParams; -import hirs.utils.rim.ReferenceManifestValidator; import hirs.utils.SwidResource; +import hirs.utils.rim.ReferenceManifestValidator; import hirs.utils.tpm.eventlog.TCGEventLog; import hirs.utils.tpm.eventlog.TpmPcrEvent; import lombok.extern.log4j.Log4j2; @@ -33,7 +33,6 @@ import org.springframework.web.servlet.ModelAndView; import java.io.IOException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; -import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; @@ -53,28 +52,30 @@ import java.util.UUID; @Log4j2 @Controller @RequestMapping("/HIRS_AttestationCAPortal/portal/rim-details") -public class ReferenceManifestDetailsPageController extends PageController { +public class ReferenceManifestDetailsPageController + extends PageController { + private static final ReferenceManifestValidator RIM_VALIDATOR + = new ReferenceManifestValidator(); private final ReferenceManifestRepository referenceManifestRepository; private final ReferenceDigestValueRepository referenceDigestValueRepository; private final CertificateRepository certificateRepository; private final CACredentialRepository caCertificateRepository; - private static final ReferenceManifestValidator RIM_VALIDATOR - = new ReferenceManifestValidator(); /** * Constructor providing the Page's display and routing specification. * - * @param referenceManifestRepository the repository for RIM. - * @param referenceDigestValueRepository the reference event manager. - * @param certificateRepository the certificate manager. - * @param caCertificateRepository the CA certificate manager. + * @param referenceManifestRepository the repository for RIM. + * @param referenceDigestValueRepository the reference event manager. + * @param certificateRepository the certificate manager. + * @param caCertificateRepository the CA certificate manager. */ @Autowired - public ReferenceManifestDetailsPageController(final ReferenceManifestRepository referenceManifestRepository, - final ReferenceDigestValueRepository referenceDigestValueRepository, - final CertificateRepository certificateRepository, - final CACredentialRepository caCertificateRepository) { + public ReferenceManifestDetailsPageController( + final ReferenceManifestRepository referenceManifestRepository, + final ReferenceDigestValueRepository referenceDigestValueRepository, + final CertificateRepository certificateRepository, + final CACredentialRepository caCertificateRepository) { super(Page.RIM_DETAILS); this.referenceManifestRepository = referenceManifestRepository; this.referenceDigestValueRepository = referenceDigestValueRepository; @@ -82,83 +83,28 @@ public class ReferenceManifestDetailsPageController extends PageController data = new HashMap<>(); - - // Check if parameters were set - if (params.getId() == null) { - String typeError = "ID was not provided"; - messages.addError(typeError); - log.debug(typeError); - mav.addObject(MESSAGES_ATTRIBUTE, messages); - } else { - try { - UUID uuid = UUID.fromString(params.getId()); - data.putAll(getRimDetailInfo(uuid, referenceManifestRepository, - referenceDigestValueRepository, certificateRepository, - caCertificateRepository)); - } catch (IllegalArgumentException iaEx) { - String uuidError = "Failed to parse ID from: " + params.getId(); - messages.addError(uuidError); - log.error(uuidError, iaEx); - } catch (CertificateException cEx) { - log.error(cEx); - } catch (NoSuchAlgorithmException nsEx) { - log.error(nsEx); - } catch (IOException ioEx) { - log.error(ioEx); - } catch (Exception ex) { - log.error(ex); - } - - if (data.isEmpty()) { - String notFoundMessage = "Unable to find RIM with ID: " + params.getId(); - messages.addError(notFoundMessage); - log.warn(notFoundMessage); - mav.addObject(MESSAGES_ATTRIBUTE, messages); - } else { - mav.addObject(INITIAL_DATA, data); - } - } - - // return the model and view - return mav; - } - /** * This method takes the place of an entire class for a string builder. * Gathers all information and returns it for displays. * - * @param uuid database reference for the requested RIM. - * @param referenceManifestRepository the reference manifest manager. - * @param referenceDigestValueRepository the reference event manager. - * @param certificateRepository the certificate manager. - * @param caCertificateRepository the certificate manager. + * @param uuid database reference for the requested RIM. + * @param referenceManifestRepository the reference manifest manager. + * @param referenceDigestValueRepository the reference event manager. + * @param certificateRepository the certificate manager. + * @param caCertificateRepository the certificate manager. * @return mapping of the RIM information from the database. * @throws java.io.IOException error for reading file bytes. * @throws NoSuchAlgorithmException If an unknown Algorithm is encountered. * @throws CertificateException if a certificate doesn't parse. */ public static HashMap getRimDetailInfo(final UUID uuid, - final ReferenceManifestRepository referenceManifestRepository, - final ReferenceDigestValueRepository referenceDigestValueRepository, + final ReferenceManifestRepository + referenceManifestRepository, + final ReferenceDigestValueRepository + referenceDigestValueRepository, final CertificateRepository certificateRepository, - final CACredentialRepository caCertificateRepository) + final CACredentialRepository + caCertificateRepository) throws IOException, CertificateException, NoSuchAlgorithmException { HashMap data = new HashMap<>(); @@ -166,7 +112,8 @@ public class ReferenceManifestDetailsPageController extends PageController getBaseRimInfo( final BaseReferenceManifest baseRim, final ReferenceManifestRepository referenceManifestRepository, final CertificateRepository certificateRepository, final CACredentialRepository caCertificateRepository) - throws IOException, CertificateException, NoSuchAlgorithmException { + throws IOException { HashMap data = new HashMap<>(); // Software Identity @@ -313,8 +258,8 @@ public class ReferenceManifestDetailsPageController extends PageController to a List. + * * @param set of CACs to convert * @return list of X509Certificates */ - private static List convertCACsToX509Certificates(Set set) + private static List convertCACsToX509Certificates( + final Set set) throws IOException { ArrayList certs = new ArrayList<>(set.size()); for (CertificateAuthorityCredential cac : set) { @@ -364,7 +311,7 @@ public class ReferenceManifestDetailsPageController extends PageController data = new HashMap<>(); + + // Check if parameters were set + if (params.getId() == null) { + String typeError = "ID was not provided"; + messages.addError(typeError); + log.debug(typeError); + mav.addObject(MESSAGES_ATTRIBUTE, messages); + } else { + try { + UUID uuid = UUID.fromString(params.getId()); + data.putAll(getRimDetailInfo(uuid, referenceManifestRepository, + referenceDigestValueRepository, certificateRepository, + caCertificateRepository)); + } catch (IllegalArgumentException iaEx) { + String uuidError = "Failed to parse ID from: " + params.getId(); + messages.addError(uuidError); + log.error(uuidError, iaEx); + } catch (Exception ex) { + log.error(ex); + } + + if (data.isEmpty()) { + String notFoundMessage = "Unable to find RIM with ID: " + params.getId(); + messages.addError(notFoundMessage); + log.warn(notFoundMessage); + mav.addObject(MESSAGES_ATTRIBUTE, messages); + } else { + mav.addObject(INITIAL_DATA, data); + } + } + + // return the model and view + return mav; + } } diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java index 9722ab2d..7e885720 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java @@ -64,22 +64,22 @@ public class ReferenceManifestPageController extends PageController getTableData( @Valid final DataTableInput input) { - log.debug("Handling request for summary list: " + input); + log.debug("Handling request for summary list: {}", input); String orderColumnName = input.getOrderColumnName(); - log.info("Ordering on column: " + orderColumnName); - log.info("Querying with the following dataTableInput: " + input.toString()); + log.info("Ordering on column: {}", orderColumnName); + log.info("Querying with the following dataTableInput: {}", input); FilteredRecordsList records = new FilteredRecordsList<>(); int currentPage = input.getStart() / input.getLength(); Pageable paging = PageRequest.of(currentPage, input.getLength(), Sort.by(orderColumnName)); - org.springframework.data.domain.Page pagedResult = referenceManifestRepository.findByArchiveFlag(false, paging); + org.springframework.data.domain.Page pagedResult = + referenceManifestRepository.findByArchiveFlag(false, paging); int rimCount = 0; if (pagedResult.hasContent()) { @@ -137,7 +138,7 @@ public class ReferenceManifestPageController extends PageController(records, input); } @@ -145,10 +146,10 @@ public class ReferenceManifestPageController extends PageController baseRims = new ArrayList<>(); List supportRims = new ArrayList<>(); - log.info(String.format("Processing %s uploaded files", files.length)); + log.info("Processing {} uploaded files", files.length); // loop through the files for (MultipartFile file : files) { @@ -178,20 +179,22 @@ public class ReferenceManifestPageController extends PageController { - log.info(String.format("Storing swidtag %s", rim.getFileName())); + + baseRims.forEach((rim) -> { + log.info("Storing swidtag {}", rim.getFileName()); this.referenceManifestRepository.save(rim); }); - supportRims.stream().forEach((rim) -> { - log.info(String.format("Storing event log %s", rim.getFileName())); + + supportRims.forEach((rim) -> { + log.info("Storing event log {}", rim.getFileName()); this.referenceManifestRepository.save(rim); }); @@ -217,16 +220,16 @@ public class ReferenceManifestPageController extends PageController model = new HashMap<>(); PageMessages messages = new PageMessages(); @@ -262,16 +265,16 @@ public class ReferenceManifestPageController extends PageController { - @Autowired(required = false) - private EntityManager entityManager; - private final ReferenceDigestValueRepository referenceDigestValueRepository; private final ReferenceManifestRepository referenceManifestRepository; + @Autowired(required = false) + private EntityManager entityManager; /** * Constructor providing the Page's display and routing specification. * * @param referenceDigestValueRepository the referenceDigestValueRepository object - * @param referenceManifestRepository the reference manifest manager object + * @param referenceManifestRepository the reference manifest manager object */ @Autowired public RimDatabasePageController(final ReferenceDigestValueRepository referenceDigestValueRepository, @@ -102,7 +101,8 @@ public class RimDatabasePageController extends PageController { Session session = entityManager.unwrap(Session.class); CriteriaBuilder cb = session.getCriteriaBuilder(); Root rimRoot = criteriaQuery.from(Reference.class); - criteriaQuery.select(rimRoot).distinct(true).where(cb.isNull(rimRoot.get(Certificate.ARCHIVE_FIELD))); + criteriaQuery.select(rimRoot).distinct(true) + .where(cb.isNull(rimRoot.get(Certificate.ARCHIVE_FIELD))); } }; @@ -112,7 +112,8 @@ public class RimDatabasePageController extends PageController { int currentPage = input.getStart() / input.getLength(); Pageable paging = PageRequest.of(currentPage, input.getLength(), Sort.by(orderColumnName)); - org.springframework.data.domain.Page pagedResult = referenceDigestValueRepository.findAll(paging); + org.springframework.data.domain.Page pagedResult = + referenceDigestValueRepository.findAll(paging); if (pagedResult.hasContent()) { referenceDigestValues.addAll(pagedResult.getContent()); @@ -127,7 +128,8 @@ public class RimDatabasePageController extends PageController { for (ReferenceDigestValue rdv : referenceDigestValues) { // We are updating the base rim ID field if necessary and if (rdv.getBaseRimId() == null && referenceManifestRepository.existsById(rdv.getSupportRimId())) { - support = (SupportReferenceManifest) referenceManifestRepository.getReferenceById(rdv.getSupportRimId()); + support = (SupportReferenceManifest) referenceManifestRepository.getReferenceById( + rdv.getSupportRimId()); rdv.setBaseRimId(support.getAssociatedRim()); try { referenceDigestValueRepository.save(rdv); diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ValidationReportsPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ValidationReportsPageController.java index ce19f790..ba4fad8e 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ValidationReportsPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ValidationReportsPageController.java @@ -28,6 +28,7 @@ import org.springframework.data.domain.Sort; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @@ -55,6 +56,13 @@ import java.util.regex.Pattern; @RequestMapping("/HIRS_AttestationCAPortal/portal/validation-reports") public class ValidationReportsPageController extends PageController { + private static final String DEFAULT_COMPANY = "AllDevices"; + private static final String UNDEFINED = "undefined"; + private static final String TRUE = "true"; + private static final String SYSTEM_COLUMN_HEADERS = "Verified Manufacturer," + + "Model,SN,Verification Date,Device Status"; + private static final String COMPONENT_COLUMN_HEADERS = "Component name,Component manufacturer," + + "Component model,Component SN,Issuer,Component status"; private final SupplyChainValidationSummaryRepository supplyChainValidatorSummaryRepository; private final CertificateRepository certificateRepository; private final DeviceRepository deviceRepository; @@ -62,20 +70,13 @@ public class ValidationReportsPageController extends PageController getTableData( final DataTableInput input) { - log.debug("Handling request for summary list: " + input); + log.debug("Handling request for summary list: {}", input); // attempt to get the column property based on the order index. String orderColumnName = input.getOrderColumnName(); - log.debug("Ordering on column: " + orderColumnName); + log.debug("Ordering on column: {}", orderColumnName); FilteredRecordsList records = new FilteredRecordsList<>(); int currentPage = input.getStart() / input.getLength(); Pageable paging = PageRequest.of(currentPage, input.getLength(), Sort.by(orderColumnName)); - org.springframework.data.domain.Page pagedResult = supplyChainValidatorSummaryRepository.findByArchiveFlagFalse(paging); + org.springframework.data.domain.Page pagedResult = + supplyChainValidatorSummaryRepository.findByArchiveFlagFalse(paging); if (pagedResult.hasContent()) { records.addAll(pagedResult.getContent()); @@ -138,12 +141,12 @@ public class ValidationReportsPageController extends PageController createTimes = new ArrayList(); - String[] deviceNames = new String[]{}; + ArrayList createTimes = new ArrayList<>(); + String[] deviceNames = new String[] {}; String columnHeaders = ""; boolean systemOnly = false; boolean componentOnly = false; @@ -168,7 +171,7 @@ public class ValidationReportsPageController extends PageController> parsedComponents, final String company, @@ -350,14 +353,17 @@ public class ValidationReportsPageController extends PageController componentData : parsedComponents) { JsonObject component = new JsonObject(); component.addProperty("Component name", componentData.get(0)); component.addProperty("Component manufacturer", componentData.get(1)); component.addProperty("Component model", componentData.get(2)); - component.addProperty("Component SN", componentData.get(3)); - component.addProperty("Issuer", componentData.get(4)); - component.addProperty("Component status", componentData.get(5)); + component.addProperty("Component SN", componentData.get(componentDataPosition4)); + component.addProperty("Issuer", componentData.get(componentDataPosition5)); + component.addProperty("Component status", componentData.get(componentDataPosition6)); components.add(component); } systemData.add("Components", components); @@ -372,22 +378,24 @@ public class ValidationReportsPageController extends PageController> parseComponents(final PlatformCredential pc) { - ArrayList> parsedComponents = new ArrayList>(); + ArrayList> parsedComponents = new ArrayList<>(); ArrayList> chainComponents = new ArrayList<>(); StringBuilder componentFailureString = new StringBuilder(); if (pc.getComponentIdentifiers() != null - && pc.getComponentIdentifiers().size() > 0) { + && !pc.getComponentIdentifiers().isEmpty()) { componentFailureString.append(pc.getComponentFailures()); // get all the certificates associated with the platform serial - List chainCertificates = certificateRepository.byBoardSerialNumber(pc.getPlatformSerial()); + List chainCertificates = + certificateRepository.byBoardSerialNumber(pc.getPlatformSerial()); // combine all components in each certificate for (ComponentIdentifier ci : pc.getComponentIdentifiers()) { - ArrayList issuerAndComponent = new ArrayList(); + ArrayList issuerAndComponent = new ArrayList<>(); issuerAndComponent.add(pc.getHolderIssuer()); issuerAndComponent.add(ci); chainComponents.add(issuerAndComponent); @@ -397,16 +405,16 @@ public class ValidationReportsPageController extends PageController issuerAndComponent = new ArrayList(); + ArrayList issuerAndComponent = new ArrayList<>(); issuerAndComponent.add(cert.getHolderIssuer()); issuerAndComponent.add(ci); chainComponents.add(issuerAndComponent); } } } - log.info("Component failures: " + componentFailureString.toString()); + log.info("Component failures: {}", componentFailureString); for (ArrayList issuerAndComponent : chainComponents) { - ArrayList componentData = new ArrayList(); + ArrayList componentData = new ArrayList<>(); String issuer = (String) issuerAndComponent.get(0); issuer = issuer.replaceAll(",", " "); ComponentIdentifier ci = (ComponentIdentifier) issuerAndComponent.get(1); diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/package-info.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/package-info.java new file mode 100644 index 00000000..f6439890 --- /dev/null +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.portal.page.controllers; diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/package-info.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/package-info.java new file mode 100644 index 00000000..5b9018e2 --- /dev/null +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.portal.page; diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/CertificateDetailsPageParams.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/CertificateDetailsPageParams.java index c4c07382..7f5a94cc 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/CertificateDetailsPageParams.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/CertificateDetailsPageParams.java @@ -4,6 +4,7 @@ import hirs.attestationca.portal.page.PageParams; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; +import lombok.ToString; import java.util.LinkedHashMap; @@ -13,6 +14,7 @@ import java.util.LinkedHashMap; @Getter @Setter @AllArgsConstructor +@ToString public class CertificateDetailsPageParams implements PageParams { private String id; @@ -47,13 +49,4 @@ public class CertificateDetailsPageParams implements PageParams { map.put("type", type); return map; } - - @Override - public String toString() { - return "CertificateDetailsPageParams{" - + "id:' " + id + "'," - + "type: " + type - + "}"; - } - } diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/NoPageParams.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/NoPageParams.java index 55497f98..a270d0af 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/NoPageParams.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/NoPageParams.java @@ -1,6 +1,7 @@ package hirs.attestationca.portal.page.params; import hirs.attestationca.portal.page.PageParams; + import java.util.LinkedHashMap; /** diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/ReferenceManifestDetailsPageParams.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/ReferenceManifestDetailsPageParams.java index 23a3ddf6..0acb4eb6 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/ReferenceManifestDetailsPageParams.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/ReferenceManifestDetailsPageParams.java @@ -5,17 +5,20 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import lombok.ToString; import java.util.LinkedHashMap; /** * URL parameters object for the Reference Manifest Details page and controller. */ +@Setter +@Getter @NoArgsConstructor @AllArgsConstructor +@ToString public class ReferenceManifestDetailsPageParams implements PageParams { - @Getter @Setter private String id; /** @@ -29,11 +32,4 @@ public class ReferenceManifestDetailsPageParams implements PageParams { map.put("id", id); return map; } - - @Override - public String toString() { - return "ReferenceManifestDetailsPageParams{" - + "id:' " + id - + "}"; - } } diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/ReferenceManifestPageParams.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/ReferenceManifestPageParams.java index 789bd5fc..bd166cc5 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/ReferenceManifestPageParams.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/ReferenceManifestPageParams.java @@ -21,7 +21,7 @@ public class ReferenceManifestPageParams implements PageParams { private String type; /** - *Constructor to set all Reference Integrity Manifest URL parameters. + * Constructor to set all Reference Integrity Manifest URL parameters. * * @param id the String parameter to set */ diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/package-info.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/package-info.java index ab35d472..6721ad96 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/package-info.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/package-info.java @@ -1 +1 @@ -package hirs.attestationca.portal.page.params; \ No newline at end of file +package hirs.attestationca.portal.page.params; diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/utils/CertificateStringMapBuilder.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/utils/CertificateStringMapBuilder.java index d415f3f1..30d11444 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/utils/CertificateStringMapBuilder.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/utils/CertificateStringMapBuilder.java @@ -15,8 +15,6 @@ import hirs.attestationca.persist.entity.userdefined.certificate.attributes.Plat import hirs.attestationca.persist.util.AcaPciIds; import hirs.utils.BouncyCastleUtils; import hirs.utils.PciIds; -import lombok.AccessLevel; -import lombok.NoArgsConstructor; import lombok.extern.log4j.Log4j2; import org.bouncycastle.util.encoders.Hex; @@ -36,14 +34,19 @@ import java.util.UUID; * information on a web page, as X509 cert classes do not serialize to JSON */ @Log4j2 -@NoArgsConstructor(access = AccessLevel.PRIVATE) public final class CertificateStringMapBuilder { + /** + * This private constructor was created to silence checkstyle error. + */ + private CertificateStringMapBuilder() { + } /** * Returns the general information. * - * @param certificate certificate to get the general information. - * @param certificateRepository the certificate repository for retrieving certs. + * @param certificate certificate to get the general information. + * @param caCertificateRepository CA Certificate repository + * @param certificateRepository the certificate repository for retrieving certs. * @return a hash map with the general certificate information. */ public static HashMap getGeneralCertificateInfo( @@ -107,7 +110,8 @@ public final class CertificateStringMapBuilder { //Get issuer ID if not self signed if (data.get("isSelfSigned").equals("false")) { //Get the missing certificate chain for not self sign - Certificate missingCert = containsAllChain(certificate, certificateRepository, caCertificateRepository); + Certificate missingCert = + containsAllChain(certificate, certificateRepository, caCertificateRepository); String issuerResult; if (missingCert != null) { @@ -144,8 +148,9 @@ public final class CertificateStringMapBuilder { /** * Recursive function that check if all the certificate chain is present. * - * @param certificate certificate to get the issuer - * @param certificateRepository the certificate repository for retrieving certs. + * @param certificate certificate to get the issuer + * @param certificateRepository the certificate repository for retrieving certs. + * @param caCredentialRepository CA Certificate repository * @return a boolean indicating if it has the full chain or not. */ public static Certificate containsAllChain( @@ -159,20 +164,23 @@ public final class CertificateStringMapBuilder { //Check if there is a subject organization if (certificate.getAuthorityKeyIdentifier() != null && !certificate.getAuthorityKeyIdentifier().isEmpty()) { - skiCA = caCredentialRepository.findBySubjectKeyIdStringAndArchiveFlag(certificate.getAuthorityKeyIdentifier(), false); + skiCA = caCredentialRepository.findBySubjectKeyIdStringAndArchiveFlag( + certificate.getAuthorityKeyIdentifier(), false); } else { - log.error(String.format("Certificate (%s) for %s has no authority key identifier.", - certificate.getClass().toString(), certificate.getSubject())); + log.error("Certificate ({}) for {} has no authority key identifier.", certificate.getClass(), + certificate.getSubject()); } if (skiCA == null) { if (certificate.getIssuerSorted() == null || certificate.getIssuerSorted().isEmpty()) { //Get certificates by subject - issuerCertificates = caCredentialRepository.findBySubjectAndArchiveFlag(certificate.getIssuer(), false); + issuerCertificates = + caCredentialRepository.findBySubjectAndArchiveFlag(certificate.getIssuer(), false); } else { //Get certificates by subject organization - issuerCertificates = caCredentialRepository.findBySubjectSortedAndArchiveFlag(certificate.getIssuerSorted(), false); + issuerCertificates = caCredentialRepository.findBySubjectSortedAndArchiveFlag( + certificate.getIssuerSorted(), false); } } else { issuerCertificates.add(skiCA); @@ -202,13 +210,16 @@ public final class CertificateStringMapBuilder { /** * Returns the Certificate Authority information. * - * @param uuid ID for the certificate. - * @param caCertificateRepository the certificate manager for retrieving certs. + * @param uuid ID for the certificate. + * @param certificateRepository the certificate manager for retrieving certs. + * @param caCertificateRepository CA Certificate repository * @return a hash map with the endorsement certificate information. */ - public static HashMap getCertificateAuthorityInformation(final UUID uuid, - final CertificateRepository certificateRepository, - final CACredentialRepository caCertificateRepository) { + public static HashMap + getCertificateAuthorityInformation(final UUID uuid, + final CertificateRepository certificateRepository, + final CACredentialRepository caCertificateRepository) { + if (!caCertificateRepository.existsById(uuid)) { return new HashMap<>(); } @@ -217,14 +228,15 @@ public final class CertificateStringMapBuilder { String notFoundMessage = "Unable to find Certificate Authority " + "Credential with ID: " + uuid; - return getCertificateAuthorityInfoHelper(certificateRepository, caCertificateRepository, certificate, notFoundMessage); + return getCertificateAuthorityInfoHelper(certificateRepository, caCertificateRepository, certificate, + notFoundMessage); } /** * Returns the Trust Chain credential information. * - * @param certificate the certificate - * @param certificateRepository the certificate repository for retrieving certs. + * @param certificate the certificate + * @param certificateRepository the certificate repository for retrieving certs. * @param caCertificateRepository the certificate repository for retrieving certs. * @return a hash map with the endorsement certificate information. */ @@ -243,7 +255,8 @@ public final class CertificateStringMapBuilder { HashMap data = new HashMap<>(); if (certificate != null) { - data.putAll(getGeneralCertificateInfo(certificate, certificateRepository, caCertificateRepository)); + data.putAll( + getGeneralCertificateInfo(certificate, certificateRepository, caCertificateRepository)); data.put("subjectKeyIdentifier", Arrays.toString(certificate.getSubjectKeyIdentifier())); //x509 credential version @@ -259,18 +272,22 @@ public final class CertificateStringMapBuilder { /** * Returns the endorsement credential information. * - * @param uuid ID for the certificate. - * @param certificateRepository the certificate repository for retrieving certs. + * @param uuid ID for the certificate. + * @param certificateRepository the certificate repository for retrieving certs. + * @param caCertificateRepository CA Certificate repository * @return a hash map with the endorsement certificate information. */ - public static HashMap getEndorsementInformation(final UUID uuid, - final CertificateRepository certificateRepository, - final CACredentialRepository caCertificateRepository) { + public static HashMap getEndorsementInformation( + final UUID uuid, + final CertificateRepository certificateRepository, + final CACredentialRepository caCertificateRepository) { HashMap data = new HashMap<>(); - EndorsementCredential certificate = (EndorsementCredential) certificateRepository.getCertificate(uuid); + EndorsementCredential certificate = + (EndorsementCredential) certificateRepository.getCertificate(uuid); if (certificate != null) { - data.putAll(getGeneralCertificateInfo(certificate, certificateRepository, caCertificateRepository)); + data.putAll( + getGeneralCertificateInfo(certificate, certificateRepository, caCertificateRepository)); // Set extra fields data.put("manufacturer", certificate.getManufacturer()); data.put("model", certificate.getModel()); @@ -301,22 +318,28 @@ public final class CertificateStringMapBuilder { /** * Returns the Platform credential information. * - * @param uuid ID for the certificate. - * @param certificateRepository the certificate manager for retrieving certs. + * @param uuid ID for the certificate. + * @param certificateRepository the certificate manager for retrieving certs. + * @param componentResultRepository component result repository. + * @param caCertificateRepository CA credential repository. * @return a hash map with the endorsement certificate information. - * @throws IOException when parsing the certificate + * @throws IOException when parsing the certificate * @throws IllegalArgumentException invalid argument on parsing the certificate */ public static HashMap getPlatformInformation(final UUID uuid, - final CertificateRepository certificateRepository, - final ComponentResultRepository componentResultRepository, - final CACredentialRepository caCertificateRepository) + final CertificateRepository + certificateRepository, + final ComponentResultRepository + componentResultRepository, + final CACredentialRepository + caCertificateRepository) throws IllegalArgumentException, IOException { HashMap data = new HashMap<>(); PlatformCredential certificate = (PlatformCredential) certificateRepository.getCertificate(uuid); if (certificate != null) { - data.putAll(getGeneralCertificateInfo(certificate, certificateRepository, caCertificateRepository)); + data.putAll( + getGeneralCertificateInfo(certificate, certificateRepository, caCertificateRepository)); data.put("credentialType", certificate.getCredentialType()); data.put("platformType", certificate.getPlatformChainType()); data.put("manufacturer", certificate.getManufacturer()); @@ -344,7 +367,7 @@ public final class CertificateStringMapBuilder { data.put("holderId", ekCertificate.getId().toString()); } } else { - if (certificate.getPlatformChainType()!= null + if (certificate.getPlatformChainType() != null && certificate.getPlatformChainType().equals("Delta")) { PlatformCredential holderCertificate = (PlatformCredential) certificateRepository .findBySerialNumber(certificate.getHolderSerialNumber(), @@ -399,7 +422,8 @@ public final class CertificateStringMapBuilder { if (certificate.getPlatformSerial() != null) { // link certificate chain - List chainCertificates = certificateRepository.byBoardSerialNumber(certificate.getPlatformSerial()); + List chainCertificates = + certificateRepository.byBoardSerialNumber(certificate.getPlatformSerial()); data.put("numInChain", chainCertificates.size()); Collections.sort(chainCertificates, new Comparator() { @Override @@ -433,17 +457,17 @@ public final class CertificateStringMapBuilder { /** * Returns a HasHMap of a string. * Ex: input "TPMSpecification{family='abc',level=0, revision=0}" - * output map[TPMSpecificationFamily] = 'abc' - * map[TPMSpecificationLevel] = 0 - * map[TPMSpecificationRevision] = 0 + * output map[TPMSpecificationFamily] = 'abc' + * map[TPMSpecificationLevel] = 0 + * map[TPMSpecificationRevision] = 0 * * @param str HashMap string to be converted. * @return a hash map with key-value pairs from the string */ private static HashMap convertStringToHash(final String str) { HashMap map = new HashMap<>(); - String name = str.substring(0, str.indexOf('{')).trim(); - String data = str.trim().substring(str.trim().indexOf('{') + 1, + String name = str.substring(0, str.indexOf('(')).trim(); + String data = str.trim().substring(str.trim().indexOf('(') + 1, str.trim().length() - 1); // Separate key and value and parse the key for (String pair : data.split(",")) { @@ -460,18 +484,23 @@ public final class CertificateStringMapBuilder { /** * Returns the Issued Attestation Certificate information. * - * @param uuid ID for the certificate. - * @param certificateRepository the certificate manager for retrieving certs. + * @param uuid ID for the certificate. + * @param certificateRepository the certificate manager for retrieving certs. + * @param caCredentialRepository CA Credential repository. * @return a hash map with the endorsement certificate information. */ public static HashMap getIssuedInformation(final UUID uuid, - final CertificateRepository certificateRepository, - final CACredentialRepository caCredentialRepository) { + final CertificateRepository + certificateRepository, + final CACredentialRepository + caCredentialRepository) { HashMap data = new HashMap<>(); - IssuedAttestationCertificate certificate = (IssuedAttestationCertificate) certificateRepository.getCertificate(uuid); + IssuedAttestationCertificate certificate = + (IssuedAttestationCertificate) certificateRepository.getCertificate(uuid); if (certificate != null) { - data.putAll(getGeneralCertificateInfo(certificate, certificateRepository, caCredentialRepository)); + data.putAll( + getGeneralCertificateInfo(certificate, certificateRepository, caCredentialRepository)); // add endorsement credential ID if not null if (certificate.getEndorsementCredential() != null) { @@ -532,27 +561,30 @@ public final class CertificateStringMapBuilder { /** * Returns the IDevID Certificate information. * - * @param uuid ID for the certificate. - * @param certificateRepository the certificate manager for retrieving certs. + * @param uuid ID for the certificate. + * @param certificateRepository the certificate manager for retrieving certs. + * @param caCredentialRepository CA Credential repository. * @return a hash map with the endorsement certificate information. */ public static HashMap getIdevidInformation(final UUID uuid, - final CertificateRepository certificateRepository, - final CACredentialRepository caCredentialRepository) { + final CertificateRepository + certificateRepository, + final CACredentialRepository + caCredentialRepository) { HashMap data = new HashMap<>(); IDevIDCertificate certificate = (IDevIDCertificate) certificateRepository.getCertificate(uuid); if (certificate != null) { - data.putAll(getGeneralCertificateInfo(certificate, certificateRepository, caCredentialRepository)); + data.putAll( + getGeneralCertificateInfo(certificate, certificateRepository, caCredentialRepository)); if (certificate.getHwType() != null) { data.put("hwType", certificate.getHwType()); String hwTypeReadable; if (certificate.hasTCGOIDs()) { hwTypeReadable = "TPM-Bound IDevID"; - } - else { + } else { hwTypeReadable = "Manufacturer Specific"; } data.put("hwTypeReadable", hwTypeReadable); @@ -565,25 +597,26 @@ public final class CertificateStringMapBuilder { if (certificate.hasTCGOIDs()) { if (hwSerialStr.contains(":")) { String[] hwSerialArray = hwSerialStr.split(":"); - if (hwSerialArray.length >= 3) { + final int minArrayLength = 3; + if (hwSerialArray.length >= minArrayLength) { data.put("tcgTpmManufacturer", hwSerialArray[0]); data.put("ekAuthorityKeyIdentifier", hwSerialArray[1]); data.put("ekCertificateSerialNumber", hwSerialArray[2]); } - } - else { + } else { // Corresponds to digest of EK certificate data.put("ekCertificateDigest", Boolean.valueOf(true).toString()); String hwSerialToAdd = Hex.toHexString(certificate.getHwSerialNum()); data.put("hwSerialNumHex", Boolean.valueOf(true).toString()); data.put("hwSerialNum", hwSerialToAdd); } - } - else { + } else { String hwSerialToAdd = hwSerialStr; // Check if hwSerialNum is a printable ASCII string; default to hex otherwise - if (hwSerialStr.chars().allMatch(c -> c > 0x20 && c <= 0x7F)) { + final int minMatchedNum = 0x20; + final int maxMatchedNum = 0x7F; + if (hwSerialStr.chars().allMatch(c -> c > minMatchedNum && c <= maxMatchedNum)) { data.put("hwSerialNum", hwSerialStr); } else { hwSerialToAdd = Hex.toHexString(certificate.getHwSerialNum()); diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/utils/package-info.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/utils/package-info.java index cc0dc317..442ddcc8 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/utils/package-info.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/utils/package-info.java @@ -1 +1 @@ -package hirs.attestationca.portal.page.utils; \ No newline at end of file +package hirs.attestationca.portal.page.utils; diff --git a/HIRS_AttestationCAPortal/src/main/resources/application.properties b/HIRS_AttestationCAPortal/src/main/resources/application.properties index cab35cbb..6ea4a85e 100644 --- a/HIRS_AttestationCAPortal/src/main/resources/application.properties +++ b/HIRS_AttestationCAPortal/src/main/resources/application.properties @@ -5,26 +5,22 @@ logging.level.org.springframework.web=ERROR logging.level.org.hibernate=ERROR logging.file.path=/var/log/hirs logging.file.name=HIRS_AttestationCA_Portal.log - # Database Config spring.jpa.hibernate.ddl-auto=update -jakarta.persistence.sharedCache.mode = UNSPECIFIED +jakarta.persistence.sharedCache.mode=UNSPECIFIED spring.datasource.driver-class-name=org.mariadb.jdbc.Driver - # Tomcat Config server.tomcat.additional-tld-skip-patterns=jakarta.persistence-api*.jar, jakarta.xml.bind-api*.jar, txw2*.jar, *commons*.jar, *annotations*.jar, *checker*.jar, *lombok*.jar, *jsr*.jar, *guava*.jar, *access*.jar, *activation*.jar, *bcprov*.jar, *bcmail*.jar, *bcutil*.jar, *bcpkix*.jar, *json*.jar server.tomcat.basedir=/opt/embeddedtomcat server.servlet.register-default-servlet=true server.servlet.context-path=/ spring.mvc.servlet.path=/ - server.tomcat.accesslog.enabled=true server.tomcat.accesslog.directory=/var/log/hirs server.tomcat.accesslog.file-date-format=yyyy-MM-dd server.tomcat.accesslog.prefix=Tomcat_accesslog_ server.tomcat.accesslog.suffix=.log server.tomcat.accesslog.rotate=true - # Tomcat TLS support server.port=8443 server.ssl.enabled=true @@ -36,10 +32,8 @@ server.ssl.key-store=/etc/hirs/certificates/HIRS/KeyStore.jks server.ssl.key-alias=hirs_aca_tls_rsa_3k_sha384 server.ssl.enabled-protocols=TLSv1.2, TLSv1.3 server.ssl.ciphers=TLS_AES_256_GCM_SHA384, ECDHE-ECDSA-AES256-GCM-SHA384, ECDHE-RSA-AES256-GCM-SHA384, DHE-RSA-AES256-GCM-SHA384, AES256-GCM-SHA384 - # ACA specific default properties -aca.certificates.validity = 3652 - +aca.certificates.validity=3652 # Compression settings server.compression.enabled=true # Compression content types diff --git a/HIRS_AttestationCAPortal/src/main/resources/application.win.properties b/HIRS_AttestationCAPortal/src/main/resources/application.win.properties index 968ac61c..322228e1 100644 --- a/HIRS_AttestationCAPortal/src/main/resources/application.win.properties +++ b/HIRS_AttestationCAPortal/src/main/resources/application.win.properties @@ -1,4 +1,3 @@ - # Logging Config (tomcat may have further config) logging.level.org.springframework=ERROR logging.level.org.apache.catalina=ERROR @@ -8,25 +7,23 @@ logging.file.path=C:/ProgramData/hirs/log logging.file.name=hirs.spring.log # Database Config spring.jpa.hibernate.ddl-auto=update -jakarta.persistence.sharedCache.mode = UNSPECIFIED +jakarta.persistence.sharedCache.mode=UNSPECIFIED spring.datasource.driver-class-name=org.mariadb.jdbc.Driver #spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver #spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver -aca.certificates.validity = 3652 +aca.certificates.validity=3652 # Tomcat Config server.tomcat.additional-tld-skip-patterns=jakarta.persistence-api*.jar, jakarta.xml.bind-api*.jar, txw2*.jar, *commons*.jar, *annotations*.jar, *checker*.jar, *lombok*.jar, *jsr*.jar, *guava*.jar, *access*.jar, *activation*.jar, *bcprov*.jar, *bcmail*.jar, *bcutil*.jar, *bcpkix*.jar, *json*.jar server.tomcat.basedir=C:/ProgramData/hirs/embeddedtomcat server.servlet.register-default-servlet=true server.servlet.context-path=/ spring.mvc.servlet.path=/ - server.tomcat.accesslog.enabled=true server.tomcat.accesslog.directory=C:/ProgramData/hirs/log server.tomcat.accesslog.file-date-format=yyyy-MM-dd server.tomcat.accesslog.prefix=Tomcat_accesslog_ server.tomcat.accesslog.suffix=.log server.tomcat.accesslog.rotate=true - # Tomcat TLS support server.port=8443 server.ssl.enabled=true @@ -38,10 +35,8 @@ server.ssl.key-store=C:/ProgramData/hirs/certificates/HIRS/KeyStore.jks server.ssl.key-alias=hirs_aca_tls_rsa_3k_sha384 server.ssl.enabled-protocols=TLSv1.2, TLSv1.3 server.ssl.ciphers=TLS_AES_256_GCM_SHA384, ECDHE-ECDSA-AES256-GCM-SHA384, ECDHE-RSA-AES256-GCM-SHA384, DHE-RSA-AES256-GCM-SHA384, AES256-GCM-SHA384 - #--server.ssl.key-store-password=123456 #--server.ssl.trust-store-password=123456 - #jdbc.driverClassName = com.mysql.cj.jdbc.Driver #jdbc.url = jdbc:mysql://localhost:3306/hirs_db?autoReconnect=true&useSSL=false #jdbc.username = root @@ -49,6 +44,5 @@ server.ssl.ciphers=TLS_AES_256_GCM_SHA384, ECDHE-ECDSA-AES256-GCM-SHA384, ECDHE- #entitymanager.packagesToScan: hirs.attestationca.portal.page.controllers #spring.jpa.hibernate.ddl-auto=update #spring.jpa.show-sql=true - # DB dfault password. #spring.datasource.password=hirs_db diff --git a/HIRS_AttestationCAPortal/src/main/resources/banner.properties b/HIRS_AttestationCAPortal/src/main/resources/banner.properties index 14023f06..173d6e3c 100644 --- a/HIRS_AttestationCAPortal/src/main/resources/banner.properties +++ b/HIRS_AttestationCAPortal/src/main/resources/banner.properties @@ -4,14 +4,11 @@ # color: Indicate the color of the banner # string: String that will be display on the banner # dynamic: Dynamic string to display on the banner - banner.color= banner.string= banner.dynamic= - # Extra content that will be placed at the bottom of the page either on the left or right # side of the page - left.content.1= left.content.2= left.content.3= diff --git a/HIRS_AttestationCAPortal/src/main/resources/hibernate.properties b/HIRS_AttestationCAPortal/src/main/resources/hibernate.properties index e19198d2..4e55fcd2 100644 --- a/HIRS_AttestationCAPortal/src/main/resources/hibernate.properties +++ b/HIRS_AttestationCAPortal/src/main/resources/hibernate.properties @@ -2,9 +2,9 @@ hibernate.connection.url=jdbc:mariadb://localhost:3306/hirs_db?autoReconnect=tru #hibernate.connection.username=hirs_db #hibernate.connection.password=hirs_db hibernate.connection.driver_class=org.mariadb.jdbc.Driver -hibernate.dialect = org.hibernate.dialect.MariaDBDialect -hibernate.show_sql = false -hibernate.format_sql = true -hibernate.hbm2ddl.auto = update +hibernate.dialect=org.hibernate.dialect.MariaDBDialect +hibernate.show_sql=false +hibernate.format_sql=true +hibernate.hbm2ddl.auto=update #https://github.com/spring-projects/spring-data-jpa/issues/2717 -jakarta.persistence.sharedCache.mode = UNSPECIFIED \ No newline at end of file +jakarta.persistence.sharedCache.mode=UNSPECIFIED \ No newline at end of file diff --git a/HIRS_AttestationCAPortal/src/main/resources/log4j2-spring.win.xml b/HIRS_AttestationCAPortal/src/main/resources/log4j2-spring.win.xml index 16b13bf3..a2a7727a 100644 --- a/HIRS_AttestationCAPortal/src/main/resources/log4j2-spring.win.xml +++ b/HIRS_AttestationCAPortal/src/main/resources/log4j2-spring.win.xml @@ -5,28 +5,28 @@ + filePattern="C:/ProgramData/hirs/log/HIRS_AttestationCA_Portal.log-%d{yyyy-MM-dd}-%i.log"> %d{yyyy-MM-dd HH:mm:ss} [%C.%M] %-5p : %m%n - + - + size="10 MB"/> + - - + + - + - + diff --git a/HIRS_AttestationCAPortal/src/main/resources/log4j2-spring.xml b/HIRS_AttestationCAPortal/src/main/resources/log4j2-spring.xml index 8dec9345..2a64d950 100644 --- a/HIRS_AttestationCAPortal/src/main/resources/log4j2-spring.xml +++ b/HIRS_AttestationCAPortal/src/main/resources/log4j2-spring.xml @@ -5,28 +5,28 @@ + filePattern="/var/log/hirs/HIRS_AttestationCA_Portal-%d{yyyy-MM-dd}-%i.log"> %d{yyyy-MM-dd HH:mm:ss} [%C.%M] %-5p : %m%n - + - + size="10 MB"/> + - - - + + + - + - + diff --git a/HIRS_AttestationCAPortal/src/main/resources/portal.properties b/HIRS_AttestationCAPortal/src/main/resources/portal.properties index 3ec20bbe..5fe22171 100644 --- a/HIRS_AttestationCAPortal/src/main/resources/portal.properties +++ b/HIRS_AttestationCAPortal/src/main/resources/portal.properties @@ -10,28 +10,25 @@ # ACA Directories # root: the root directory of ACA related files # certificates: the directory for ACA certificate files -aca.directories.root = /etc/hirs/aca -aca.directories.certificates = ${aca.directories.root}/certificates - +aca.directories.root=/etc/hirs/aca +aca.directories.certificates=${aca.directories.root}/certificates # ACA certificate related properties. These are generic properties that apply to the creation of # any certificate that the ACA is responsible for creating. # validity: the number of days that credentials generated by the ACA are valid. -aca.certificates.validity = 3652 - +aca.certificates.validity=3652 # ACA key store properties # alias: the alias to reference the ACA key and certificate by # location: the absolute path to the ACA key store. # password: key store password -aca.keyStore.alias = HIRS_ACA_KEY -aca.keyStore.location = ${aca.directories.certificates}/keyStore.jks -aca.keyStore.password = - +aca.keyStore.alias=HIRS_ACA_KEY +aca.keyStore.location=${aca.directories.certificates}/keyStore.jks +aca.keyStore.password= # ACA setup/initialization properties. These properties are used exclusively by the ACA # initialization process. Generally these properties do not need to be modified # # keySize: the default key size of the ACA key pair stored within the trust store # subjectName: the CN of the generate X509 certificate # expiration: the number of days that the generated X509 certificate will expire -aca.setup.keyStore.keySize = 2048 -aca.setup.keyStore.subjectName = HIRS_AttestationCA_Endorsement -aca.setup.keyStore.expiration = ${aca.certificates.validity} \ No newline at end of file +aca.setup.keyStore.keySize=2048 +aca.setup.keyStore.subjectName=HIRS_AttestationCA_Endorsement +aca.setup.keyStore.expiration=${aca.certificates.validity} \ No newline at end of file diff --git a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/web.xml b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/web.xml index f7bf98b6..f6670d93 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/web.xml +++ b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/web.xml @@ -1,6 +1,6 @@ - HIRS Attestation CA Portal diff --git a/HIRS_AttestationCAPortal/src/main/webapp/lib/bootstrap-3.3.7/fonts/glyphicons-halflings-regular.svg b/HIRS_AttestationCAPortal/src/main/webapp/lib/bootstrap-3.3.7/fonts/glyphicons-halflings-regular.svg index 94fb5490..2ba280f4 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/lib/bootstrap-3.3.7/fonts/glyphicons-halflings-regular.svg +++ b/HIRS_AttestationCAPortal/src/main/webapp/lib/bootstrap-3.3.7/fonts/glyphicons-halflings-regular.svg @@ -1,288 +1,543 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/Readme.md b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/Readme.md index 09c8c8f7..250b83d8 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/Readme.md +++ b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/Readme.md @@ -1,26 +1,35 @@ # DataTables plug-in for jQuery -DataTables is a table enhancing plug-in for the [jQuery](//jquery.com) Javascript library, adding sorting, paging and filtering abilities to plain HTML tables with minimal effort. The stated goal of DataTables is: +DataTables is a table enhancing plug-in for the [jQuery](//jquery.com) Javascript library, adding sorting, paging and +filtering abilities to plain HTML tables with minimal effort. The stated goal of DataTables is: > To enhance the accessibility of data in HTML tables. To meet this goal, DataTables is developed with two distinct groups of users in mind: -* You the developers using DataTables. For developers DataTables provides a wide array of options for how data should be obtained, displayed and acted upon, along with an extensive API for accessing and manipulating the table. - -* End users. For those using the interface DataTables presents, actions to get the most from the information contained in tables, such as sorting and filtering, along with paging and scrolling of the data in table, are easy to use, intuitive and fast. +* You the developers using DataTables. For developers DataTables provides a wide array of options for how data should be + obtained, displayed and acted upon, along with an extensive API for accessing and manipulating the table. +* End users. For those using the interface DataTables presents, actions to get the most from the information contained + in tables, such as sorting and filtering, along with paging and scrolling of the data in table, are easy to use, + intuitive and fast. ## Installing DataTables -To use DataTables, the primary way to obtain the software is to use the [DataTables downloader](//datatables.net/download). You can also include the individual files from the [DataTables CDN](//cdn.datatables.net). See the [documentation](//datatables.net/manual/installation) for full details. +To use DataTables, the primary way to obtain the software is to use +the [DataTables downloader](//datatables.net/download). You can also include the individual files from +the [DataTables CDN](//cdn.datatables.net). See the [documentation](//datatables.net/manual/installation) for full +details. ### NPM and Bower -If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built from this repository under the name `datatables.net`. Styling packages for Bootstrap, Foundation and other styling libraries are also available by adding a suffix to the package name. - -Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has details on how to use package managers with DataTables. +If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built +from this repository under the name `datatables.net`. Styling packages for Bootstrap, Foundation and other styling +libraries are also available by adding a suffix to the package name. +Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation +pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has +details on how to use package managers with DataTables. ## Usage @@ -30,7 +39,9 @@ In its simplest case, DataTables can be initialised with a single line of Javasc $('table').dataTable(); ``` -where the jQuery selector is used to obtain a reference to the table you want to enhance with DataTables. Optional configuration parameters can be passed in to DataTables to have it perform certain actions by using a configuration object as the parameter passed in to the DataTables constructor. For example: +where the jQuery selector is used to obtain a reference to the table you want to enhance with DataTables. Optional +configuration parameters can be passed in to DataTables to have it perform certain actions by using a configuration +object as the parameter passed in to the DataTables constructor. For example: ```js $('table').dataTable( { @@ -43,17 +54,18 @@ will disable paging and enable scrolling. A full list of the options available for DataTables are available in the [documentation](//datatables.net). - ## Documentation -Full documentation of the DataTables options, API and plug-in interface are available on the [DataTables web-site](//datatables.net). The site also contains information on the wide variety of plug-ins that are available for DataTables, which can be used to enhance and customise your table even further. - +Full documentation of the DataTables options, API and plug-in interface are available on +the [DataTables web-site](//datatables.net). The site also contains information on the wide variety of plug-ins that are +available for DataTables, which can be used to enhance and customise your table even further. ## Support -Support for DataTables is available through the [DataTables forums](//datatables.net/forums) and [commercial support options](//datatables.net/support) are available. - +Support for DataTables is available through the [DataTables forums](//datatables.net/forums) +and [commercial support options](//datatables.net/support) are available. ## License -DataTables is release under the [MIT license](//datatables.net/license). You are free to use, modify and distribute this software, as long as the copyright header is left intact (specifically the comment block which starts with `/*!`. +DataTables is release under the [MIT license](//datatables.net/license). You are free to use, modify and distribute this +software, as long as the copyright header is left intact (specifically the comment block which starts with `/*!`. diff --git a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/AutoFill/Readme.md b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/AutoFill/Readme.md index d5f8110a..80461694 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/AutoFill/Readme.md +++ b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/AutoFill/Readme.md @@ -1,22 +1,28 @@ # AutoFill -AutoFill adds an Excel data fill like option to a DataTable to click and drag over multiple cells, filling in information over the selected cells and incrementing numbers as needed. - +AutoFill adds an Excel data fill like option to a DataTable to click and drag over multiple cells, filling in +information over the selected cells and incrementing numbers as needed. # Installation -To use AutoFill the best way to obtain the software is to use the [DataTables downloader](//datatables.net/download). You can also include the individual files from the [DataTables CDN](//cdn.datatables.net). See the [documentation](http://datatables.net/extensions/autofill/) for full details. +To use AutoFill the best way to obtain the software is to use the [DataTables downloader](//datatables.net/download). +You can also include the individual files from the [DataTables CDN](//cdn.datatables.net). See +the [documentation](http://datatables.net/extensions/autofill/) for full details. ## NPM and Bower -If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built from this repository under the name `datatables.net-autofill`. Styling packages for Bootstrap, Foundation and other styling libraries are also available by adding a suffix to the package name. - -Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has details on how to use package managers with DataTables. +If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built +from this repository under the name `datatables.net-autofill`. Styling packages for Bootstrap, Foundation and other +styling libraries are also available by adding a suffix to the package name. +Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation +pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has +details on how to use package managers with DataTables. # Basic usage -AutoFill is initialised using the `autoFill` option in the DataTables constructor. Further options can be specified using this option as an object - see the documentation for details. For example: +AutoFill is initialised using the `autoFill` option in the DataTables constructor. Further options can be specified +using this option as an object - see the documentation for details. For example: ```js $(document).ready( function () { @@ -26,14 +32,13 @@ $(document).ready( function () { } ); ``` - # Documentation / support * [Documentation](https://datatables.net/extensions/autofill/) * [DataTables support forums](http://datatables.net/forums) - # GitHub -If you fancy getting involved with the development of AutoFill and help make it better, please refer to its [GitHub repo](https://github.com/DataTables/AutoFill) +If you fancy getting involved with the development of AutoFill and help make it better, please refer to +its [GitHub repo](https://github.com/DataTables/AutoFill) diff --git a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/Buttons/Readme.md b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/Buttons/Readme.md index e418a2c8..8b0918f8 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/Buttons/Readme.md +++ b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/Buttons/Readme.md @@ -1,22 +1,30 @@ # Buttons -The Buttons extension for DataTables provides a common set of options, API methods and styling to display buttons on a page that will interact with a DataTable. Modules are also provided for data export, printing and column visibility control. - +The Buttons extension for DataTables provides a common set of options, API methods and styling to display buttons on a +page that will interact with a DataTable. Modules are also provided for data export, printing and column visibility +control. # Installation -To use Buttons the primary way to obtain the software is to use the [DataTables downloader](//datatables.net/download). You can also include the individual files from the [DataTables CDN](//cdn.datatables.net). See the [documentation](http://datatables.net/extensions/buttons/) for full details. +To use Buttons the primary way to obtain the software is to use the [DataTables downloader](//datatables.net/download). +You can also include the individual files from the [DataTables CDN](//cdn.datatables.net). See +the [documentation](http://datatables.net/extensions/buttons/) for full details. ## NPM and Bower -If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built from this repository under the name `datatables.net-buttons`. Styling packages for Bootstrap, Foundation and other styling libraries are also available by adding a suffix to the package name. - -Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has details on how to use package managers with DataTables. +If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built +from this repository under the name `datatables.net-buttons`. Styling packages for Bootstrap, Foundation and other +styling libraries are also available by adding a suffix to the package name. +Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation +pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has +details on how to use package managers with DataTables. # Basic usage -Buttons is initialised using the `buttons` option in the DataTables constructor, giving an array of the buttons that should be shown. Further options can be specified using this option as an object - see the documentation for details. For example: +Buttons is initialised using the `buttons` option in the DataTables constructor, giving an array of the buttons that +should be shown. Further options can be specified using this option as an object - see the documentation for details. +For example: ```js $(document).ready( function () { @@ -26,14 +34,13 @@ $(document).ready( function () { } ); ``` - # Documentation / support * [Documentation](https://datatables.net/extensions/buttons/) * [DataTables support forums](http://datatables.net/forums) - # GitHub -If you fancy getting involved with the development of Buttons and help make it better, please refer to its [GitHub repo](https://github.com/DataTables/Buttons) +If you fancy getting involved with the development of Buttons and help make it better, please refer to +its [GitHub repo](https://github.com/DataTables/Buttons) diff --git a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/ColReorder/Readme.md b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/ColReorder/Readme.md index f99171aa..02d9a4bf 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/ColReorder/Readme.md +++ b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/ColReorder/Readme.md @@ -1,22 +1,29 @@ # ColReorder -ColReorder adds the ability for the end user to click and drag column headers to reorder a table as they see fit, to DataTables. See the [documentation](http://datatables.net/extensions/colreorder/) for full details. - +ColReorder adds the ability for the end user to click and drag column headers to reorder a table as they see fit, to +DataTables. See the [documentation](http://datatables.net/extensions/colreorder/) for full details. # Installation -To use ColReorder the primary way to obtain the software is to use the [DataTables downloader](//datatables.net/download). You can also include the individual files from the [DataTables CDN](//cdn.datatables.net). See the [documentation](http://datatables.net/extensions/colreorder/) for full details. +To use ColReorder the primary way to obtain the software is to use +the [DataTables downloader](//datatables.net/download). You can also include the individual files from +the [DataTables CDN](//cdn.datatables.net). See the [documentation](http://datatables.net/extensions/colreorder/) for +full details. ## NPM and Bower -If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built from this repository under the name `datatables.net-colreorder`. Styling packages for Bootstrap, Foundation and other styling libraries are also available by adding a suffix to the package name. - -Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has details on how to use package managers with DataTables. +If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built +from this repository under the name `datatables.net-colreorder`. Styling packages for Bootstrap, Foundation and other +styling libraries are also available by adding a suffix to the package name. +Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation +pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has +details on how to use package managers with DataTables. # Basic usage -ColReorder is initialised using the `colReorder` option in the DataTables constructor - a simple boolean `true` will enable the feature. Further options can be specified using this option as an object - see the documentation for details. +ColReorder is initialised using the `colReorder` option in the DataTables constructor - a simple boolean `true` will +enable the feature. Further options can be specified using this option as an object - see the documentation for details. Example: @@ -28,7 +35,6 @@ $(document).ready( function () { } ); ``` - # Documentation / support * [Documentation](https://datatables.net/extensions/colreorder/) diff --git a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/FixedColumns/Readme.md b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/FixedColumns/Readme.md index d51f7eb3..6015f253 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/FixedColumns/Readme.md +++ b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/FixedColumns/Readme.md @@ -1,22 +1,31 @@ # FixedColumns -When making use of DataTables' x-axis scrolling feature (`scrollX`), you may wish to fix the left or right most columns in place. This extension for DataTables provides exactly this option (for non-scrolling tables, please use the FixedHeader extension, which can fix the header and footer). - +When making use of DataTables' x-axis scrolling feature (`scrollX`), you may wish to fix the left or right most columns +in place. This extension for DataTables provides exactly this option (for non-scrolling tables, please use the +FixedHeader extension, which can fix the header and footer). # Installation -To use FixedColumns the primary way to obtain the software is to use the [DataTables downloader](//datatables.net/download). You can also include the individual files from the [DataTables CDN](//cdn.datatables.net). See the [documentation](http://datatables.net/extensions/fixedcolumns/) for full details. +To use FixedColumns the primary way to obtain the software is to use +the [DataTables downloader](//datatables.net/download). You can also include the individual files from +the [DataTables CDN](//cdn.datatables.net). See the [documentation](http://datatables.net/extensions/fixedcolumns/) for +full details. ## NPM and Bower -If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built from this repository under the name `datatables.net-fixedcolumns`. Styling packages for Bootstrap, Foundation and other styling libraries are also available by adding a suffix to the package name. - -Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has details on how to use package managers with DataTables. +If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built +from this repository under the name `datatables.net-fixedcolumns`. Styling packages for Bootstrap, Foundation and other +styling libraries are also available by adding a suffix to the package name. +Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation +pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has +details on how to use package managers with DataTables. # Basic usage -FixedColumns is initialised using the `fixedColumns` option in the DataTables constructor - a simple boolean `true` will enable the feature. Further options can be specified using this option as an object - see the documentation for details. DataTables' scrolling options should also be enabled to use this feature. +FixedColumns is initialised using the `fixedColumns` option in the DataTables constructor - a simple boolean `true` will +enable the feature. Further options can be specified using this option as an object - see the documentation for details. +DataTables' scrolling options should also be enabled to use this feature. Example: @@ -32,13 +41,12 @@ $(document).ready(function() { } ); ``` - # Documentation / support * [Documentation](https://datatables.net/extensions/fixedcolumns/) * [DataTables support forums](http://datatables.net/forums) - # GitHub -If you fancy getting involved with the development of FixedColumns and help make it better, please refer to its [GitHub repo](https://github.com/DataTables/FixedColumns). +If you fancy getting involved with the development of FixedColumns and help make it better, please refer to +its [GitHub repo](https://github.com/DataTables/FixedColumns). diff --git a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/FixedHeader/Readme.md b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/FixedHeader/Readme.md index 28dbd752..0ba7b85c 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/FixedHeader/Readme.md +++ b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/FixedHeader/Readme.md @@ -1,22 +1,29 @@ # FixedHeader -The FixedHeader plug-in will freeze in place the header, footer and left and/or right most columns in a DataTable, ensuring that title information will remain always visible. - +The FixedHeader plug-in will freeze in place the header, footer and left and/or right most columns in a DataTable, +ensuring that title information will remain always visible. # Installation -To use FixedHeader the primary way to obtain the software is to use the [DataTables downloader](//datatables.net/download). You can also include the individual files from the [DataTables CDN](//cdn.datatables.net). See the [documentation](http://datatables.net/extensions/fixedheader/) for full details. +To use FixedHeader the primary way to obtain the software is to use +the [DataTables downloader](//datatables.net/download). You can also include the individual files from +the [DataTables CDN](//cdn.datatables.net). See the [documentation](http://datatables.net/extensions/fixedheader/) for +full details. ## NPM and Bower -If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built from this repository under the name `datatables.net-fixedheader`. Styling packages for Bootstrap, Foundation and other styling libraries are also available by adding a suffix to the package name. - -Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has details on how to use package managers with DataTables. +If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built +from this repository under the name `datatables.net-fixedheader`. Styling packages for Bootstrap, Foundation and other +styling libraries are also available by adding a suffix to the package name. +Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation +pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has +details on how to use package managers with DataTables. # Basic usage -FixedHeader is initialised using the `fixedHeader` option in the DataTables constructor - a simple boolean `true` will enable the feature. Further options can be specified using this option as an object - see the documentation for details. +FixedHeader is initialised using the `fixedHeader` option in the DataTables constructor - a simple boolean `true` will +enable the feature. Further options can be specified using this option as an object - see the documentation for details. Example: @@ -28,14 +35,13 @@ $(document).ready( function () { } ); ``` - # Documentation / support * [Documentation](https://datatables.net/extensions/fixedheader/) * [DataTables support forums](http://datatables.net/forums) - # GitHub -If you fancy getting involved with the development of FixedHeader and help make it better, please refer to its [GitHub repo](https://github.com/DataTables/FixedHeader). +If you fancy getting involved with the development of FixedHeader and help make it better, please refer to +its [GitHub repo](https://github.com/DataTables/FixedHeader). diff --git a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/KeyTable/Readme.md b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/KeyTable/Readme.md index ca9a26c5..79243e3b 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/KeyTable/Readme.md +++ b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/KeyTable/Readme.md @@ -1,22 +1,28 @@ # KeyTable -KeyTable provides Excel like cell navigation on any table. Events (focus, blur, action etc) can be assigned to individual cells, columns, rows or all cells. - +KeyTable provides Excel like cell navigation on any table. Events (focus, blur, action etc) can be assigned to +individual cells, columns, rows or all cells. # Installation -To use KeyTable the primary way to obtain the software is to use the [DataTables downloader](//datatables.net/download). You can also include the individual files from the [DataTables CDN](//cdn.datatables.net). See the [documentation](http://datatables.net/extensions/keytable/) for full details. +To use KeyTable the primary way to obtain the software is to use the [DataTables downloader](//datatables.net/download). +You can also include the individual files from the [DataTables CDN](//cdn.datatables.net). See +the [documentation](http://datatables.net/extensions/keytable/) for full details. ## NPM and Bower -If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built from this repository under the name `datatables.net-keytable`. Styling packages for Bootstrap, Foundation and other styling libraries are also available by adding a suffix to the package name. - -Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has details on how to use package managers with DataTables. +If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built +from this repository under the name `datatables.net-keytable`. Styling packages for Bootstrap, Foundation and other +styling libraries are also available by adding a suffix to the package name. +Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation +pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has +details on how to use package managers with DataTables. # Basic usage -KeyTable is initialised using the `keys` option in the DataTables constructor - a simple boolean `true` will enable the feature. Further options can be specified using this option as an object - see the documentation for details. +KeyTable is initialised using the `keys` option in the DataTables constructor - a simple boolean `true` will enable the +feature. Further options can be specified using this option as an object - see the documentation for details. ```js $(document).ready( function () { @@ -26,14 +32,13 @@ $(document).ready( function () { } ); ``` - # Documentation / support * [Documentation](https://datatables.net/extensions/keytable/) * [DataTables support forums](http://datatables.net/forums) - # GitHub -If you fancy getting involved with the development of KeyTable and help make it better, please refer to its [GitHub repo](https://github.com/DataTables/KeyTable). +If you fancy getting involved with the development of KeyTable and help make it better, please refer to +its [GitHub repo](https://github.com/DataTables/KeyTable). diff --git a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/Responsive/Readme.md b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/Responsive/Readme.md index 4bf8ee94..fb29bfb9 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/Responsive/Readme.md +++ b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/Responsive/Readme.md @@ -1,22 +1,29 @@ # Responsive -Responsive will automatically optimise the table's layout for different screen sizes through the dynamic column visibility control, making your tables useful on desktop and mobile screens. - +Responsive will automatically optimise the table's layout for different screen sizes through the dynamic column +visibility control, making your tables useful on desktop and mobile screens. # Installation -To use Responsive the primary way to obtain the software is to use the [DataTables downloader](//datatables.net/download). You can also include the individual files from the [DataTables CDN](//cdn.datatables.net). See the [documentation](http://datatables.net/extensions/responsive/) for full details. +To use Responsive the primary way to obtain the software is to use +the [DataTables downloader](//datatables.net/download). You can also include the individual files from +the [DataTables CDN](//cdn.datatables.net). See the [documentation](http://datatables.net/extensions/responsive/) for +full details. ## NPM and Bower -If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built from this repository under the name `datatables.net-responsive`. Styling packages for Bootstrap, Foundation and other styling libraries are also available by adding a suffix to the package name. - -Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has details on how to use package managers with DataTables. +If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built +from this repository under the name `datatables.net-responsive`. Styling packages for Bootstrap, Foundation and other +styling libraries are also available by adding a suffix to the package name. +Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation +pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has +details on how to use package managers with DataTables. # Basic usage -Responsive is initialised using the `responsive` option in the DataTables constructor - a simple boolean `true` will enable the feature. Further options can be specified using this option as an object - see the documentation for details. +Responsive is initialised using the `responsive` option in the DataTables constructor - a simple boolean `true` will +enable the feature. Further options can be specified using this option as an object - see the documentation for details. Example: @@ -28,14 +35,13 @@ $(document).ready( function () { } ); ``` - # Documentation / support * [Documentation](https://datatables.net/extensions/responsive/) * [DataTables support forums](http://datatables.net/forums) - # GitHub -If you fancy getting involved with the development of Responsive and help make it better, please refer to its [GitHub repo](https://github.com/DataTables/Responsive). +If you fancy getting involved with the development of Responsive and help make it better, please refer to +its [GitHub repo](https://github.com/DataTables/Responsive). diff --git a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/RowReorder/Readme.md b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/RowReorder/Readme.md index 8ffa0e6f..734d5d6c 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/RowReorder/Readme.md +++ b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/RowReorder/Readme.md @@ -1,22 +1,30 @@ # RowReorder -RowReorder adds the ability for rows in a DataTable to be reordered through user interaction with the table (click and drag / touch and drag). Integration with Editor's multi-row editing feature is also available to update rows immediately. - +RowReorder adds the ability for rows in a DataTable to be reordered through user interaction with the table (click and +drag / touch and drag). Integration with Editor's multi-row editing feature is also available to update rows +immediately. # Installation -To use RowReorder the primary way to obtain the software is to use the [DataTables downloader](//datatables.net/download). You can also include the individual files from the [DataTables CDN](//cdn.datatables.net). See the [documentation](http://datatables.net/extensions/rowreorder/) for full details. +To use RowReorder the primary way to obtain the software is to use +the [DataTables downloader](//datatables.net/download). You can also include the individual files from +the [DataTables CDN](//cdn.datatables.net). See the [documentation](http://datatables.net/extensions/rowreorder/) for +full details. ## NPM and Bower -If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built from this repository under the name `datatables.net-rowreorder`. Styling packages for Bootstrap, Foundation and other styling libraries are also available by adding a suffix to the package name. - -Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has details on how to use package managers with DataTables. +If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built +from this repository under the name `datatables.net-rowreorder`. Styling packages for Bootstrap, Foundation and other +styling libraries are also available by adding a suffix to the package name. +Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation +pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has +details on how to use package managers with DataTables. # Basic usage -RowReorder is initialised using the `rowReorder` option in the DataTables constructor - a simple boolean `true` will enable the feature. Further options can be specified using this option as an object - see the documentation for details. +RowReorder is initialised using the `rowReorder` option in the DataTables constructor - a simple boolean `true` will +enable the feature. Further options can be specified using this option as an object - see the documentation for details. Example: @@ -28,14 +36,13 @@ $(document).ready( function () { } ); ``` - # Documentation / support * [Documentation](https://datatables.net/extensions/rowreorder/) * [DataTables support forums](http://datatables.net/forums) - # GitHub -If you fancy getting involved with the development of RowReorder and help make it better, please refer to its [GitHub repo](https://github.com/DataTables/RowReorder). +If you fancy getting involved with the development of RowReorder and help make it better, please refer to +its [GitHub repo](https://github.com/DataTables/RowReorder). diff --git a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/Scroller/Readme.md b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/Scroller/Readme.md index 828c73de..25859e67 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/Scroller/Readme.md +++ b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/Scroller/Readme.md @@ -1,6 +1,11 @@ # Scroller -Scroller is a virtual rendering plug-in for DataTables which allows large datasets to be drawn on screen every quickly. What the virtual rendering means is that only the visible portion of the table (and a bit to either side to make the scrolling smooth) is drawn, while the scrolling container gives the visual impression that the whole table is visible. This is done by making use of the pagination abilities of DataTables and moving the table around in the scrolling container DataTables adds to the page. The scrolling container is forced to the height it would be for the full table display using an extra element. +Scroller is a virtual rendering plug-in for DataTables which allows large datasets to be drawn on screen every quickly. +What the virtual rendering means is that only the visible portion of the table (and a bit to either side to make the +scrolling smooth) is drawn, while the scrolling container gives the visual impression that the whole table is visible. +This is done by making use of the pagination abilities of DataTables and moving the table around in the scrolling +container DataTables adds to the page. The scrolling container is forced to the height it would be for the full table +display using an extra element. Key features include: @@ -10,21 +15,26 @@ Key features include: * Support for scrolling with millions of rows * Easy to use - # Installation -To use Scroller the primary way to obtain the software is to use the [DataTables downloader](//datatables.net/download). You can also include the individual files from the [DataTables CDN](//cdn.datatables.net). See the [documentation](http://datatables.net/extensions/scroller/) for full details. +To use Scroller the primary way to obtain the software is to use the [DataTables downloader](//datatables.net/download). +You can also include the individual files from the [DataTables CDN](//cdn.datatables.net). See +the [documentation](http://datatables.net/extensions/scroller/) for full details. ## NPM and Bower -If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built from this repository under the name `datatables.net-scroller`. Styling packages for Bootstrap, Foundation and other styling libraries are also available by adding a suffix to the package name. - -Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has details on how to use package managers with DataTables. +If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built +from this repository under the name `datatables.net-scroller`. Styling packages for Bootstrap, Foundation and other +styling libraries are also available by adding a suffix to the package name. +Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation +pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has +details on how to use package managers with DataTables. # Basic usage -Scroller is initialised using the `scroller` option in the DataTables constructor - a simple boolean `true` will enable the feature. Further options can be specified using this option as an object - see the documentation for details. +Scroller is initialised using the `scroller` option in the DataTables constructor - a simple boolean `true` will enable +the feature. Further options can be specified using this option as an object - see the documentation for details. ```js $(document).ready( function () { @@ -34,16 +44,17 @@ $(document).ready( function () { } ); ``` -Note that rows in the table must all be the same height. Information in a cell which expands on to multiple lines will cause some odd behaviour in the scrolling. Additionally, the table's `cellspacing` parameter must be set to 0, again to ensure the information display is correct. - +Note that rows in the table must all be the same height. Information in a cell which expands on to multiple lines will +cause some odd behaviour in the scrolling. Additionally, the table's `cellspacing` parameter must be set to 0, again to +ensure the information display is correct. # Documentation / support * [Documentation](https://datatables.net/extensions/scroller/) * [DataTables support forums](http://datatables.net/forums) - # GitHub -If you fancy getting involved with the development of Scroller and help make it better, please refer to its [GitHub repo](https://github.com/DataTables/Scroller) +If you fancy getting involved with the development of Scroller and help make it better, please refer to +its [GitHub repo](https://github.com/DataTables/Scroller) diff --git a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/Select/Readme.md b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/Select/Readme.md index 4d690da9..6a9f0767 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/Select/Readme.md +++ b/HIRS_AttestationCAPortal/src/main/webapp/lib/jquery.dataTables-1.10.13/extensions/Select/Readme.md @@ -1,22 +1,29 @@ # Select -Select adds item selection capabilities to a DataTable. Items can be rows, columns or cells, which can be selected independently, or together. Item selection can be particularly useful in interactive tables where users can perform some action on the table such as editing. - +Select adds item selection capabilities to a DataTable. Items can be rows, columns or cells, which can be selected +independently, or together. Item selection can be particularly useful in interactive tables where users can perform some +action on the table such as editing. # Installation -To use Select the primary way to obtain the software is to use the [DataTables downloader](//datatables.net/download). You can also include the individual files from the [DataTables CDN](//cdn.datatables.net). See the [documentation](http://datatables.net/extensions/select/) for full details. +To use Select the primary way to obtain the software is to use the [DataTables downloader](//datatables.net/download). +You can also include the individual files from the [DataTables CDN](//cdn.datatables.net). See +the [documentation](http://datatables.net/extensions/select/) for full details. ## NPM and Bower -If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built from this repository under the name `datatables.net-select`. Styling packages for Bootstrap, Foundation and other styling libraries are also available by adding a suffix to the package name. - -Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has details on how to use package managers with DataTables. +If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built +from this repository under the name `datatables.net-select`. Styling packages for Bootstrap, Foundation and other +styling libraries are also available by adding a suffix to the package name. +Please see the DataTables [NPM](//datatables.net/download/npm) and [Bower](//datatables.net/download/bower) installation +pages for further information. The [DataTables installation manual](//datatables.net/manual/installation) also has +details on how to use package managers with DataTables. # Basic usage -Select is initialised using the `select` option in the DataTables constructor - a simple boolean `true` will enable the feature. Further options can be specified using this option as an object - see the documentation for details. +Select is initialised using the `select` option in the DataTables constructor - a simple boolean `true` will enable the +feature. Further options can be specified using this option as an object - see the documentation for details. Example: @@ -28,14 +35,13 @@ $(document).ready( function () { } ); ``` - # Documentation / support * [Documentation](https://datatables.net/extensions/select/) * [DataTables support forums](http://datatables.net/forums) - # GitHub -If you fancy getting involved with the development of Select and help make it better, please refer to its [GitHub repo](https://github.com/DataTables/Select). +If you fancy getting involved with the development of Select and help make it better, please refer to +its [GitHub repo](https://github.com/DataTables/Select). diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/PageControllerTest.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/PageControllerTest.java index 7b70a1b9..b320cc74 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/PageControllerTest.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/PageControllerTest.java @@ -5,11 +5,6 @@ import hirs.attestationca.persist.entity.userdefined.certificate.CertificateAuth import hirs.attestationca.persist.entity.userdefined.certificate.EndorsementCredential; import hirs.attestationca.persist.entity.userdefined.certificate.IssuedAttestationCertificate; import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredential; -import java.io.IOException; -import java.net.URISyntaxException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; @@ -17,20 +12,29 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.Model; import org.springframework.web.context.WebApplicationContext; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + import static org.hamcrest.Matchers.equalTo; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; /** * Base class for PageController tests. - * */ @SpringBootTest @@ -39,22 +43,19 @@ import static org.hamcrest.Matchers.equalTo; @TestInstance(TestInstance.Lifecycle.PER_CLASS) // needed to use non-static BeforeAll public abstract class PageControllerTest { + // Pre-prefix path for all the Controllers. + // There's an option in Page to add prefix path used for some Controllers. + private static final String PRE_PREFIX_PATH = "/HIRS_AttestationCAPortal/portal/"; + // Represents the Page for the Controller under test. + private final Page page; // Contains server-side support for testing Spring MVC applications // via WebTestClient with MockMvc for server request handling. @Autowired private WebApplicationContext webApplicationContext; - // Used to set up mocked servlet environment to test the HTTP controller // endpoints without the need to launch the embedded servlet container. private MockMvc mockMvc; - // Represents the Page for the Controller under test. - private final Page page; - - // Pre-prefix path for all the Controllers. - // There's an option in Page to add prefix path used for some Controllers. - private static final String PRE_PREFIX_PATH = "/HIRS_AttestationCAPortal/portal/"; - /** * Constructor requiring the Page's display and routing specification. * @@ -64,6 +65,43 @@ public abstract class PageControllerTest { this.page = page; } + /** + * Returns a blank model for initPage tests. + * + * @return a blank model for initPage tests. + */ + protected static final Model getBlankModel() { + return new ExtendedModelMap(); + } + + /** + * If the AssertionError is a redirected URL error, check the results of the executed request + * for the actual redirected URL and throw a new error containing the comparison to the expected + * URL. + *

+ * If the error is not a redirected URL error, rethrow the original error. + * + * @param expectedURL the expected redirected URL AntMatcher pattern + * @param actions the results of the executed request + * @param err the AssertionError to indicate if the error is a redirected URL error + * @throws AssertionError with added information if a redirected URL error or the original error + */ + protected static final void enhanceRedirectedUrlError( + final String expectedURL, + final ResultActions actions, + final AssertionError err) throws AssertionError { + if ("Redirected URL".equals(err.getMessage())) { + final String actualURL = actions.andReturn().getResponse().getRedirectedUrl(); + final String msg + = err.getMessage() + ": " + + " expected [" + expectedURL + "]" + + " but found [" + actualURL + "]"; + throw new AssertionError(msg); + } else { + throw err; + } + } + /** * Returns the Page's display and routing specification. * @@ -82,49 +120,12 @@ public abstract class PageControllerTest { return mockMvc; } - /** - * Returns a blank model for initPage tests. - * - * @return a blank model for initPage tests. - */ - protected static final Model getBlankModel() { - return new ExtendedModelMap(); - } - - /** - * If the AssertionError is a redirected URL error, check the results of the executed request - * for the actual redirected URL and throw a new error containing the comparison to the expected - * URL. - * - * If the error is not a redirected URL error, rethrow the original error. - * - * @param expectedURL the expected redirected URL AntMatcher pattern - * @param actions the results of the executed request - * @param err the AssertionError to indicate if the error is a redirected URL error - * @throws AssertionError with added information if a redirected URL error or the original error - */ - protected static final void enhanceRedirectedUrlError( - final String expectedURL, - final ResultActions actions, - final AssertionError err) throws AssertionError { - if ("Redirected URL".equals(err.getMessage())) { - final String actualURL = actions.andReturn().getResponse().getRedirectedUrl(); - final String msg - = err.getMessage() + ": " - + " expected [" + expectedURL + "]" - + " but found [" + actualURL + "]"; - throw new AssertionError(msg); - } else { - throw err; - } - } - - /** * Construct a test certificate from the given parameters. - * @param the type of Certificate that will be created + * + * @param the type of Certificate that will be created * @param certificateClass the class of certificate to generate - * @param filename the location of the certificate to be used + * @param filename the location of the certificate to be used * @return the newly-constructed Certificate * @throws IOException if there is a problem constructing the test certificate */ @@ -138,11 +139,12 @@ public abstract class PageControllerTest { /** * Construct a test certificate from the given parameters. - * @param the type of Certificate that will be created - * @param certificateClass the class of certificate to generate - * @param filename the location of the certificate to be used + * + * @param the type of Certificate that will be created + * @param certificateClass the class of certificate to generate + * @param filename the location of the certificate to be used * @param endorsementCredential the endorsement credentials (can be null) - * @param platformCredentials the platform credentials (can be null) + * @param platformCredentials the platform credentials (can be null) * @return the newly-constructed Certificate * @throws IOException if there is a problem constructing the test certificate */ @@ -178,7 +180,9 @@ public abstract class PageControllerTest { } /** - * Create page path (add pre-prefix and prefix path) + * Create page path (add pre-prefix and prefix path). + * + * @return the page path */ public String getPagePath() { String pagePath = PRE_PREFIX_PATH + page.getPrefixPath() + page.getViewName(); @@ -221,4 +225,4 @@ public abstract class PageControllerTest { PageController.PAGES_ATTRIBUTE, equalTo(Page.values())) ); } -} \ No newline at end of file +} diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/PageTestConfiguration.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/PageTestConfiguration.java index 5fd2b98e..46bb3900 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/PageTestConfiguration.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/PageTestConfiguration.java @@ -1,18 +1,10 @@ package hirs.attestationca.portal.page; import hirs.attestationca.persist.entity.userdefined.certificate.CertificateAuthorityCredential; -import javax.sql.DataSource; -import java.io.IOException; -import java.net.URISyntaxException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.*; -import java.security.cert.X509Certificate; -import java.util.Properties; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.context.annotation.*; +import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; @@ -21,12 +13,24 @@ import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import javax.sql.DataSource; +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.GeneralSecurityException; +import java.security.KeyPairGenerator; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; +import java.util.Properties; + /** * A configuration class for testing Attestation CA Portal classes that require a database. * This class sets up a temporary in-memory database that is used for testing. * This class also creates beans that override beans in main class PersistenceJPAConfig. * A few 'dummy' beans had to be created to override PersistenceJPAConfig beans that were - * not needed and would interfere with the tests. + * not needed and would interfere with the tests. */ @TestConfiguration @EnableJpaRepositories(basePackages = "hirs.attestationca.persist.entity.manager") @@ -49,7 +53,7 @@ public class PageTestConfiguration { * * @return the {@link X509Certificate} of the ACA * @throws URISyntaxException if there's a syntax error on the path to the cert - * @throws IOException exception reading the file + * @throws IOException exception reading the file */ @Bean public X509Certificate acaCertificate() throws URISyntaxException, IOException { @@ -78,7 +82,7 @@ public class PageTestConfiguration { * hibernate configuration file. * * @return entity manager factory, which provides instances of EntityManager for connecting - * to same database. + * to same database. */ @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { @@ -121,10 +125,9 @@ public class PageTestConfiguration { public PrivateKey privateKey() { try { KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA"); - PrivateKey dummy_privKey = keyGenerator.generateKeyPair().getPrivate(); - return dummy_privKey; - } - catch (GeneralSecurityException e) { + PrivateKey dummyPrivKey = keyGenerator.generateKeyPair().getPrivate(); + return dummyPrivKey; + } catch (GeneralSecurityException e) { throw new AssertionError(e); } } @@ -137,10 +140,10 @@ public class PageTestConfiguration { public KeyStore keyStore() { // attempt to create the key store. if that fails, print a message before failing. try { - KeyStore dummy_keyStore = KeyStore.getInstance("JKS"); - dummy_keyStore.load(null); + KeyStore dummyKeyStore = KeyStore.getInstance("JKS"); + dummyKeyStore.load(null); - return dummy_keyStore; + return dummyKeyStore; } catch (Exception ex) { System.out.println("\nEncountered error while creating a fake (blank) key store for testing"); throw new BeanInitializationException(ex.getMessage(), ex); diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/CertificateDetailsPageControllerTest.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/CertificateDetailsPageControllerTest.java index d1c7859d..57e290a5 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/CertificateDetailsPageControllerTest.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/CertificateDetailsPageControllerTest.java @@ -12,13 +12,6 @@ import hirs.attestationca.persist.enums.HealthStatus; import hirs.attestationca.portal.page.Page; import hirs.attestationca.portal.page.PageController; import hirs.attestationca.portal.page.PageControllerTest; -import java.io.IOException; - -import java.security.Security; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -27,8 +20,15 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.Rollback; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import static org.hamcrest.Matchers.hasProperty; + +import java.io.IOException; +import java.security.Security; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasProperty; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; @@ -40,25 +40,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class CertificateDetailsPageControllerTest extends PageControllerTest { - // Base path for the page - private String pagePath; - - // Repository manager to handle data access between device entity and data storage in db - @Autowired - private DeviceRepository deviceRepository; - - // Repository manager to handle data access between certificate entity and data storage in db - @Autowired - private CertificateRepository certificateRepository; - - private CertificateAuthorityCredential caCertificate; - private CertificateAuthorityCredential caRootCertificate; - private PlatformCredential platformCredential; - private PlatformCredential platformCredential2; - private PlatformCredential platformCertificatePCI; - private EndorsementCredential endorsementCredential; - private IssuedAttestationCertificate issuedCredential; - // Random UUID for certificate search. private static final String ID = "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; private static final String TEST_CA_CERTIFICATE @@ -75,6 +56,21 @@ public class CertificateDetailsPageControllerTest extends PageControllerTest { = "/platform_credentials/basic_plat_cert_2-0.pem"; private static final String TEST_PLATFORM_CREDENTIAL_2_PCI = "/platform_credentials/pciids_plat_cert_2-0.pem"; + // Base path for the page + private final String pagePath; + // Repository manager to handle data access between device entity and data storage in db + @Autowired + private DeviceRepository deviceRepository; + // Repository manager to handle data access between certificate entity and data storage in db + @Autowired + private CertificateRepository certificateRepository; + private CertificateAuthorityCredential caCertificate; + private CertificateAuthorityCredential caRootCertificate; + private PlatformCredential platformCredential; + private PlatformCredential platformCredential2; + private PlatformCredential platformCertificatePCI; + private EndorsementCredential endorsementCredential; + private IssuedAttestationCertificate issuedCredential; /** * Constructor providing the Page's display and routing specification. @@ -239,7 +235,7 @@ public class CertificateDetailsPageControllerTest extends PageControllerTest { .getModelAndView() .getModel() .get(PolicyPageController.INITIAL_DATA); - assertEquals(caCertificate.getIssuer(), initialData.get("issuer")); + assertEquals(caCertificate.getIssuer(), initialData.get("issuer")); } @@ -268,7 +264,7 @@ public class CertificateDetailsPageControllerTest extends PageControllerTest { .getModel() .get(PolicyPageController.INITIAL_DATA); assertEquals(platformCredential.getIssuer(), initialData.get("issuer")); - assertEquals(((PlatformCredential) platformCredential).getCredentialType(), + assertEquals(platformCredential.getCredentialType(), initialData.get("credentialType")); } @@ -298,12 +294,13 @@ public class CertificateDetailsPageControllerTest extends PageControllerTest { .getModel() .get(PolicyPageController.INITIAL_DATA); assertEquals(platformCredential2.getIssuer(), initialData.get("issuer")); - assertEquals(((PlatformCredential) platformCredential2).getCredentialType(), + assertEquals(platformCredential2.getCredentialType(), initialData.get("credentialType")); // Check component identifier assertNotNull(initialData.get("componentsIdentifier")); List obj = (List) initialData.get("componentsIdentifier"); - assertEquals(7, obj.size()); + final int expectedSize = 7; + assertEquals(expectedSize, obj.size()); // Check platform properties assertNotNull(initialData.get("platformProperties")); @@ -337,12 +334,13 @@ public class CertificateDetailsPageControllerTest extends PageControllerTest { .getModel() .get(PolicyPageController.INITIAL_DATA); assertEquals(platformCertificatePCI.getIssuer(), initialData.get("issuer")); - assertEquals(((PlatformCredential) platformCertificatePCI).getCredentialType(), + assertEquals(platformCertificatePCI.getCredentialType(), initialData.get("credentialType")); // Check component identifier assertNotNull(initialData.get("componentsIdentifier")); List obj = (List) initialData.get("componentsIdentifier"); - assertEquals(14, obj.size()); + final int expectedSize = 14; + assertEquals(expectedSize, obj.size()); // Check platform properties assertNotNull(initialData.get("platformProperties")); @@ -376,7 +374,7 @@ public class CertificateDetailsPageControllerTest extends PageControllerTest { .getModel() .get(PolicyPageController.INITIAL_DATA); assertEquals(endorsementCredential.getIssuer(), initialData.get("issuer")); - assertEquals(((EndorsementCredential) endorsementCredential).getManufacturer(), + assertEquals(endorsementCredential.getManufacturer(), initialData.get("manufacturer")); } @@ -442,4 +440,4 @@ public class CertificateDetailsPageControllerTest extends PageControllerTest { //assertEquals(issuedCredential.getEndorsementCredential().getId().toString(), // initialData.get("endorsementID")); } -} \ No newline at end of file +} diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/DevicePageControllerTest.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/DevicePageControllerTest.java index 3ba0bcb9..398ea96d 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/DevicePageControllerTest.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/DevicePageControllerTest.java @@ -2,21 +2,24 @@ package hirs.attestationca.portal.page.controllers; import hirs.attestationca.persist.entity.manager.CertificateRepository; import hirs.attestationca.persist.entity.manager.DeviceRepository; +import hirs.attestationca.persist.entity.userdefined.Device; import hirs.attestationca.persist.entity.userdefined.certificate.EndorsementCredential; import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredential; -import hirs.attestationca.persist.entity.userdefined.Device; import hirs.attestationca.persist.enums.AppraisalStatus; import hirs.attestationca.persist.enums.HealthStatus; import hirs.attestationca.portal.page.PageControllerTest; -import java.io.IOException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import java.io.IOException; + import static hirs.attestationca.portal.page.Page.DEVICES; import static org.hamcrest.Matchers.hasSize; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Integration tests that test the URL End Points of DevicePageController. @@ -24,17 +27,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class DevicePageControllerTest extends PageControllerTest { - // Base path for the page - private String pagePath; - - // Repository manager to handle data access between device entity and data storage in db - @Autowired - private DeviceRepository deviceRepository; - - // Repository manager to handle data access between certificate entity and data storage in db - @Autowired - private CertificateRepository certificateRepository; - // Location of test certs private static final String TEST_ENDORSEMENT_CREDENTIAL = "/endorsement_credentials/tpmcert.pem"; @@ -42,6 +34,14 @@ public class DevicePageControllerTest extends PageControllerTest { = "/endorsement_credentials/ab21ccf2-tpmcert.pem"; private static final String TEST_PLATFORM_CREDENTIAL = "/platform_credentials/Intel_pc.cer"; + // Base path for the page + private final String pagePath; + // Repository manager to handle data access between device entity and data storage in db + @Autowired + private DeviceRepository deviceRepository; + // Repository manager to handle data access between certificate entity and data storage in db + @Autowired + private CertificateRepository certificateRepository; /** @@ -54,6 +54,7 @@ public class DevicePageControllerTest extends PageControllerTest { /** * Prepares a testing environment. + * * @throws IOException if there is a problem constructing the test certificate */ @BeforeAll @@ -63,8 +64,8 @@ public class DevicePageControllerTest extends PageControllerTest { Device device; // Create new device to be used in test and save it to db - device = new Device("Test Device",null, HealthStatus.TRUSTED, AppraisalStatus.Status.PASS, - null,false,"tmp_overrideReason", "tmp_summId"); + device = new Device("Test Device", null, HealthStatus.TRUSTED, AppraisalStatus.Status.PASS, + null, false, "tmp_overrideReason", "tmp_summId"); device = deviceRepository.save(device); // Upload and save EK Cert @@ -102,4 +103,4 @@ public class DevicePageControllerTest extends PageControllerTest { .andReturn(); } -} \ No newline at end of file +} diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/EndorsementKeyCredentialsPageControllerTest.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/EndorsementKeyCredentialsPageControllerTest.java index b6064600..d5aeb522 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/EndorsementKeyCredentialsPageControllerTest.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/EndorsementKeyCredentialsPageControllerTest.java @@ -6,8 +6,6 @@ import hirs.attestationca.persist.entity.userdefined.Certificate; import hirs.attestationca.persist.entity.userdefined.certificate.EndorsementCredential; import hirs.attestationca.portal.page.PageControllerTest; import hirs.attestationca.portal.page.PageMessages; -import java.io.IOException; -import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -18,8 +16,14 @@ import org.springframework.test.annotation.Rollback; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.web.servlet.FlashMap; + +import java.io.IOException; +import java.util.List; + import static hirs.attestationca.portal.page.Page.ENDORSEMENT_KEY_CREDENTIALS; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.springframework.test.annotation.DirtiesContext.MethodMode.BEFORE_METHOD; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -29,21 +33,17 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class EndorsementKeyCredentialsPageControllerTest extends PageControllerTest { - // Base path for the page - private String pagePath; - - // Repository manager to handle data access between certificate entity and data storage in db - @Autowired - private CertificateRepository certificateRepository; - - // Repository manager to handle data access between endorsement certificate entity and data storage in db - @Autowired - private EndorsementCredentialRepository endorsementCredentialRepository; - // Location of test certs private static final String EKCERT = "certificates/fakeIntelIntermediateCA.pem"; private static final String BADEKCERT = "certificates/badCert.pem"; - + // Base path for the page + private String pagePath; + // Repository manager to handle data access between certificate entity and data storage in db + @Autowired + private CertificateRepository certificateRepository; + // Repository manager to handle data access between endorsement certificate entity and data storage in db + @Autowired + private EndorsementCredentialRepository endorsementCredentialRepository; // A file that contains a cert that is not an EK Cert. Should be parsable as a general cert, // but should (eventually) not be stored as an EK because it isn't one. private MockMultipartFile nonEkCertFile; @@ -60,6 +60,7 @@ public class EndorsementKeyCredentialsPageControllerTest extends PageControllerT /** * Prepares tests. + * * @throws IOException if test resources are not found */ @BeforeAll @@ -79,6 +80,7 @@ public class EndorsementKeyCredentialsPageControllerTest extends PageControllerT * Tests uploading a cert that is not an Endorsement Credential. Eventually, this * should indicate a failure, but for now, EndorsementCredential just parses it as a * generic credential successfully. + * * @throws Exception if an exception occurs */ @Test @@ -128,13 +130,14 @@ public class EndorsementKeyCredentialsPageControllerTest extends PageControllerT /** * Tests that uploading something that is not a cert at all results in an error returned * to the web client. + * * @throws Exception an exception occurs */ @Test @Rollback @DirtiesContext(methodMode = BEFORE_METHOD) // clear endorsement cert from db public void uploadBadEndorsementCert() throws Exception { - + // perform upload. Attach csv file and add HTTP parameters for the baseline name and type. MvcResult result = getMockMvc().perform(MockMvcRequestBuilders .multipart(pagePath + "/upload") diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/IssuedCertificatesPageControllerTest.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/IssuedCertificatesPageControllerTest.java index d3fd2cbc..1001f286 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/IssuedCertificatesPageControllerTest.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/IssuedCertificatesPageControllerTest.java @@ -9,22 +9,23 @@ import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredent import hirs.attestationca.persist.enums.AppraisalStatus; import hirs.attestationca.persist.enums.HealthStatus; import hirs.attestationca.portal.page.PageControllerTest; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.Rollback; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; + import static hirs.attestationca.portal.page.Page.ISSUED_CERTIFICATES; import static org.hamcrest.Matchers.hasSize; -//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Integration tests that test the URL End Points of IssuedCertificatesPageController. @@ -32,20 +33,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class IssuedCertificatesPageControllerTest extends PageControllerTest { - // Base path for the page - private String pagePath; - - // Fake device to store in db for test - private Device device; - - // Repository manager to handle data access between device entity and data storage in db - @Autowired - private DeviceRepository deviceRepository; - - // Repository manager to handle data access between certificate entity and data storage in db - @Autowired - private CertificateRepository certificateRepository; - // Location of test certs private static final String TEST_ENDORSEMENT_CREDENTIAL = "/endorsement_credentials/tpmcert.pem"; @@ -55,7 +42,16 @@ public class IssuedCertificatesPageControllerTest extends PageControllerTest { = "/platform_credentials/Intel_pc2.pem"; private static final String ISSUED_CLIENT_CERT = "/certificates/sample_identity_cert.cer"; - + // Base path for the page + private String pagePath; + // Fake device to store in db for test + private Device device; + // Repository manager to handle data access between device entity and data storage in db + @Autowired + private DeviceRepository deviceRepository; + // Repository manager to handle data access between certificate entity and data storage in db + @Autowired + private CertificateRepository certificateRepository; // Certs objects private List platformCredentialList; private IssuedAttestationCertificate issued; @@ -71,14 +67,15 @@ public class IssuedCertificatesPageControllerTest extends PageControllerTest { /** * Prepares a testing environment. + * * @throws IOException if there is a problem constructing the test certificate */ @BeforeAll public void beforeMethod() throws IOException { // Create new device to be used in test and save it to db - device = new Device("Test Device",null, HealthStatus.TRUSTED, AppraisalStatus.Status.PASS, - null,false,"temp", "temp"); + device = new Device("Test Device", null, HealthStatus.TRUSTED, AppraisalStatus.Status.PASS, + null, false, "temp", "temp"); device = deviceRepository.save(device); // Upload and save EK Cert @@ -148,6 +145,7 @@ public class IssuedCertificatesPageControllerTest extends PageControllerTest { /** * Tests downloading the certificate. + * * @throws Exception when getting raw report */ @Test diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/PlatformCredentialsPageControllerTest.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/PlatformCredentialsPageControllerTest.java index c7fd0f1a..a48e0ea1 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/PlatformCredentialsPageControllerTest.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/PlatformCredentialsPageControllerTest.java @@ -4,6 +4,8 @@ import hirs.attestationca.persist.entity.manager.CertificateRepository; import hirs.attestationca.persist.entity.userdefined.Certificate; import hirs.attestationca.portal.page.PageControllerTest; import hirs.attestationca.portal.page.PageMessages; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.mock.web.MockMultipartFile; @@ -12,14 +14,14 @@ import org.springframework.test.annotation.Rollback; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.web.servlet.FlashMap; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; import static hirs.attestationca.portal.page.Page.PLATFORM_CREDENTIALS; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** @@ -28,18 +30,15 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class PlatformCredentialsPageControllerTest extends PageControllerTest { - // Base path for the page - private String pagePath; - - // Repository manager to handle data access between certificate entity and data storage in db - @Autowired - private CertificateRepository certificateRepository; - // Location of test certs private static final String REALPCCERT = "platform_credentials/Intel_pc.cer"; private static final String NONPCCERT = "certificates/fakeIntelIntermediateCA.pem"; private static final String BADPCCERT = "certificates/badCert.pem"; - + // Base path for the page + private final String pagePath; + // Repository manager to handle data access between certificate entity and data storage in db + @Autowired + private CertificateRepository certificateRepository; // A cert that is an actual PC cert file and should be parsable. private MockMultipartFile realPcCertFile; @@ -60,6 +59,7 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest { /** * Prepares tests. + * * @throws IOException if test resources are not found */ @BeforeAll @@ -83,6 +83,7 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest { /** * Tests uploading a cert that is a Platform Credential, and archiving it. + * * @throws Exception if an exception occurs */ @Test @@ -93,7 +94,8 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest { } /** - * Uploads test cert to db + * Uploads test cert to db. + * * @return the cert that was uploaded * @throws Exception if an exception occurs */ @@ -125,7 +127,9 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest { } /** - * Archives test cert that is in db by setting the archive flag + * Archives test cert that is in db by setting the archive flag. + * + * @param cert certificate. * @throws Exception if an exception occurs */ private void archiveTestCert(final Certificate cert) throws Exception { @@ -147,6 +151,7 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest { /** * Tests that uploading a certificate when an identical certificate is archived will cause * the existing certificate to be unarchived and updated. + * * @throws Exception if an exception occurs */ @Test @@ -171,7 +176,7 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest { assertEquals(1, pageMessages.getSuccess().size()); assertEquals(0, pageMessages.getError().size()); assertEquals("Pre-existing certificate found and unarchived (" - + pathTokens[1] + "): ", + + pathTokens[1] + "): ", pageMessages.getSuccess().get(0)); // verify there is still only one cert in db @@ -189,6 +194,7 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest { /** * Tests uploading a cert that is not a Platform Credential, which results in failure. + * * @throws Exception if an exception occurs */ @Test @@ -222,6 +228,7 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest { /** * Tests that uploading something that is not a cert at all results in an error returned * to the web client. + * * @throws Exception an exception occurs */ @Test diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/PolicyPageControllerTest.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/PolicyPageControllerTest.java index e551eeba..2033a3b9 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/PolicyPageControllerTest.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/PolicyPageControllerTest.java @@ -11,9 +11,15 @@ import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static hirs.attestationca.portal.page.Page.POLICY; -import static org.hamcrest.Matchers.*; -import static org.junit.jupiter.api.Assertions.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Integration tests that test the URL End Points of PolicyPageController. @@ -21,18 +27,18 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. public class PolicyPageControllerTest extends PageControllerTest { // Base path for the page - private String pagePath; + private final String pagePath; // Repository manager to handle data access between policy entity and data storage in db @Autowired private PolicyRepository policyRepository; - // Policy refers to the settings such as whether to validate endorsement credentials, platform credentials, etc + // Policy refers to the settings such as whether to validate endorsement credentials, platform credentials + // , etc private PolicySettings policy; /** * Constructor requiring the Page's display and routing specification. - * */ public PolicyPageControllerTest() { super(POLICY); @@ -40,7 +46,7 @@ public class PolicyPageControllerTest extends PageControllerTest { } /** - * Sets up policy + * Sets up policy. */ @BeforeAll public void setUpPolicy() { @@ -97,7 +103,7 @@ public class PolicyPageControllerTest extends PageControllerTest { ResultActions actions; //init the database - setPolicy_AllFalse(); + setPolicyAllToFalse(); policyRepository.save(policy); // perform the mock request @@ -128,7 +134,7 @@ public class PolicyPageControllerTest extends PageControllerTest { ResultActions actions; //init the database - setPolicy_AllFalse(); + setPolicyAllToFalse(); policy.setEcValidationEnabled(true); policyRepository.save(policy); @@ -183,7 +189,7 @@ public class PolicyPageControllerTest extends PageControllerTest { ResultActions actions; //init the database - setPolicy_AllFalse(); + setPolicyAllToFalse(); policy.setEcValidationEnabled(true); policyRepository.save(policy); @@ -229,6 +235,7 @@ public class PolicyPageControllerTest extends PageControllerTest { /** * Verifies the rest call for disabling the PC Validation policy setting. + * * @throws Exception if test fails */ @Test @@ -237,8 +244,8 @@ public class PolicyPageControllerTest extends PageControllerTest { ResultActions actions; //init the database - setPolicy_AllFalse(); - setPolicy_PcToTrue(); + setPolicyAllToFalse(); + setPolicyPcToTrue(); policyRepository.save(policy); // perform the mock request @@ -292,8 +299,8 @@ public class PolicyPageControllerTest extends PageControllerTest { ResultActions actions; //init the database - setPolicy_AllFalse(); - setPolicy_PcToTrue(); + setPolicyAllToFalse(); + setPolicyPcToTrue(); policyRepository.save(policy); // perform the mock request @@ -338,6 +345,7 @@ public class PolicyPageControllerTest extends PageControllerTest { /** * Verifies the rest call for disabling the PC attribute validation policy setting. + * * @throws Exception if test fails */ @Test @@ -345,8 +353,8 @@ public class PolicyPageControllerTest extends PageControllerTest { ResultActions actions; - setPolicy_AllFalse(); - setPolicy_PcAttributeToTrue(); + setPolicyAllToFalse(); + setPolicyPcAttributeToTrue(); policyRepository.save(policy); // perform the mock request @@ -369,10 +377,8 @@ public class PolicyPageControllerTest extends PageControllerTest { /** * Helper function to set policy member variable back to all false. * After this function, can set specific values to true and then need to save policy. - * - * @return void */ - private void setPolicy_AllFalse() { + private void setPolicyAllToFalse() { policy.setEcValidationEnabled(false); policy.setPcValidationEnabled(false); policy.setPcAttributeValidationEnabled(false); @@ -381,23 +387,19 @@ public class PolicyPageControllerTest extends PageControllerTest { /** * Helper function to set policy member variable - PC Validation to True - * Note: to set PC Validation to true, EC Validation must also be true - * - * @return void + * Note: to set PC Validation to true, EC Validation must also be true. */ - private void setPolicy_PcToTrue() { + private void setPolicyPcToTrue() { policy.setEcValidationEnabled(true); policy.setPcValidationEnabled(true); } /** * Helper function to set policy member variable - PC Attribute Validation to True - * Note: to set PC Attribute Validation to true, PC Validation must also be true - * - * @return void + * Note: to set PC Attribute Validation to true, PC Validation must also be true. */ - private void setPolicy_PcAttributeToTrue() { - setPolicy_PcToTrue(); + private void setPolicyPcAttributeToTrue() { + setPolicyPcToTrue(); policy.setPcAttributeValidationEnabled(true); } } diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/TrustChainManagementPageControllerTest.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/TrustChainManagementPageControllerTest.java index 4cef7ef7..b16f08c5 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/TrustChainManagementPageControllerTest.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/TrustChainManagementPageControllerTest.java @@ -21,7 +21,9 @@ import java.util.List; import static hirs.attestationca.portal.page.Page.TRUST_CHAIN; import static org.hamcrest.Matchers.hasEntry; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; @@ -33,20 +35,16 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class TrustChainManagementPageControllerTest extends PageControllerTest { - // Base path for the page - private String pagePath; - - // Repository manager to handle data access between certificate entity and data storage in db - @Autowired - private CertificateRepository certificateRepository; - - @Autowired - private X509Certificate acaCert; - // Location of test certs private static final String NONCACERT = "certificates/fakeIntelIntermediateCA.pem"; private static final String BADCERT = "certificates/badCert.pem"; - + // Base path for the page + private final String pagePath; + // Repository manager to handle data access between certificate entity and data storage in db + @Autowired + private CertificateRepository certificateRepository; + @Autowired + private X509Certificate acaCert; // A file that contains a cert that is not an UTC Cert. Should be parsable as a general // cert, but should (eventually) not be stored as an UTC because it isn't one. private MockMultipartFile nonCaCertFile; @@ -66,6 +64,7 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { /** * Prepares tests. + * * @throws IOException if test resources are not found */ @BeforeAll @@ -121,6 +120,7 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { /** * Tests downloading the certificate. + * * @throws Exception when getting raw report */ @Test @@ -129,10 +129,9 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { Certificate cert = uploadTestCert(); - StringBuilder fileName = new StringBuilder("attachment;filename=\""); - fileName.append("CertificateAuthorityCredential_"); - fileName.append(cert.getSerialNumber()); - fileName.append(".cer\""); + String fileName = "attachment;filename=\"" + "CertificateAuthorityCredential_" + + cert.getSerialNumber() + + ".cer\""; // verify cert file attachment and content getMockMvc() @@ -143,7 +142,7 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { .andExpect(status().isOk()) .andExpect(content().contentType("application/octet-stream")) .andExpect(header().string("Content-Disposition", - fileName.toString())) + fileName)) .andExpect(content().bytes(cert.getRawBytes())); } @@ -153,6 +152,7 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { * Currently this test may pass certs that meet some, but not all requirements * However the underlying code is looking for the basic elements of a CA certificate * generic credential successfully. + * * @throws Exception if an exception occurs */ @Test @@ -163,7 +163,8 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { } /** - * Uploads test cert to db + * Uploads test cert to db. + * * @return the cert that was uploaded * @throws Exception if an exception occurs */ @@ -181,8 +182,9 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { // verify redirection messages FlashMap flashMap = result.getFlashMap(); PageMessages pageMessages = (PageMessages) flashMap.get("messages"); - assertEquals("New certificate successfully uploaded (" + pathTokens[1] + "): ", pageMessages.getSuccess() - .get(0)); + assertEquals("New certificate successfully uploaded (" + pathTokens[1] + "): ", + pageMessages.getSuccess() + .get(0)); assertEquals(0, pageMessages.getError().size()); // verify the cert was actually stored @@ -198,7 +200,9 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { } /** - * Archives test cert that is in db by setting the archive flag + * Archives test cert that is in db by setting the archive flag. + * + * @param cert certificate. * @throws Exception if an exception occurs */ private void archiveTestCert(final Certificate cert) throws Exception { @@ -218,6 +222,7 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { /** * Tests that uploading a certificate when an identical certificate is archived will cause * the existing certificate to be unarchived and updated. + * * @throws Exception if an exception occurs */ // @Test @@ -258,6 +263,7 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { /** * Tests that uploading something that is not a cert at all results in an error returned * to the web client. + * * @throws Exception an exception occurs */ @Test diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/package-info.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/package-info.java new file mode 100644 index 00000000..f6439890 --- /dev/null +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.portal.page.controllers; diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/package-info.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/package-info.java new file mode 100644 index 00000000..5b9018e2 --- /dev/null +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.portal.page; diff --git a/HIRS_AttestationCAPortal/src/test/resources/application-test.properties b/HIRS_AttestationCAPortal/src/test/resources/application-test.properties index 9b1aa18d..de82685e 100644 --- a/HIRS_AttestationCAPortal/src/test/resources/application-test.properties +++ b/HIRS_AttestationCAPortal/src/test/resources/application-test.properties @@ -1,6 +1,5 @@ # need to override beans in PersistenceJPAConfig spring.main.allow-bean-definition-overriding=true - # need to override properties in application.properties and hibernate.properties -hibernate.dialect = org.hibernate.dialect.HSQLDialect -hibernate.hbm2ddl.auto = create \ No newline at end of file +hibernate.dialect=org.hibernate.dialect.HSQLDialect +hibernate.hbm2ddl.auto=create \ No newline at end of file diff --git a/HIRS_Utils/src/main/java/hirs/utils/rim/ReferenceManifestValidator.java b/HIRS_Utils/src/main/java/hirs/utils/rim/ReferenceManifestValidator.java index 16b4aeb0..8c83886d 100644 --- a/HIRS_Utils/src/main/java/hirs/utils/rim/ReferenceManifestValidator.java +++ b/HIRS_Utils/src/main/java/hirs/utils/rim/ReferenceManifestValidator.java @@ -177,7 +177,7 @@ public class ReferenceManifestValidator { * @param encodedPublicKey the encoded public key * @return true if the signature element is validated, false otherwise */ - @SuppressWarnings("magicnumber") + public boolean validateXmlSignature(final PublicKey publicKey, final String subjectKeyIdString, final byte[] encodedPublicKey) { diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index 79f9755e..d9d7c893 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -68,7 +68,9 @@ - + + + @@ -130,8 +132,9 @@ - - + + + diff --git a/config/checkstyle/suppressions.xml b/config/checkstyle/suppressions.xml index f0a4b442..31e31c3e 100644 --- a/config/checkstyle/suppressions.xml +++ b/config/checkstyle/suppressions.xml @@ -6,11 +6,15 @@ - - + + - - + + + + + + \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index be12868c..b4b6c6a7 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,3 +3,5 @@ includeGroups= org.gradle.daemon=true org.gradle.jvmargs=-Xms256m -Xmx1024m org.gradle.caching=true +#dependency versions +spotBugAnnotationVersion=4.8.6 \ No newline at end of file