Merge commit 'de17aee' into v3_issue-877

This commit is contained in:
iadgovuser59 2024-11-18 12:27:09 -05:00
commit 8951faabe6
304 changed files with 6704 additions and 13239 deletions

View File

@ -84,4 +84,4 @@ HEALTHCHECK --start-period=50s --interval=1s --timeout=90s CMD curl -f https://l
WORKDIR /hirs WORKDIR /hirs
# On container launch, the database will be set up. Then bootRun should utilize build artifacts stored in the image. # On container launch, the database will be set up. Then bootRun should utilize build artifacts stored in the image.
CMD ["bash", "-c", "/hirs/package/linux/aca/aca_setup.sh --unattended && /tmp/hirs_add_aca_tls_path_to_os.sh && /hirs/package/linux/aca/aca_bootRun.sh"] CMD ["bash", "-c", "/hirs/package/linux/aca/aca_check_env.sh && /hirs/package/linux/aca/aca_setup.sh --unattended && /tmp/hirs_add_aca_tls_path_to_os.sh && /hirs/package/linux/aca/aca_bootRun.sh"]

View File

@ -54,6 +54,9 @@ dependencies {
testImplementation 'org.mockito:mockito-core:4.2.0' testImplementation 'org.mockito:mockito-core:4.2.0'
testImplementation 'org.springframework:spring-test:6.0.8' testImplementation 'org.springframework:spring-test:6.0.8'
compileOnly "com.github.spotbugs:spotbugs-annotations:${spotBugAnnotationVersion}"
annotationProcessor "com.github.spotbugs:spotbugs-annotations:${spotBugAnnotationVersion}"
// spring management // spring management
compileOnly libs.lombok compileOnly libs.lombok
implementation libs.lombok implementation libs.lombok
@ -70,10 +73,10 @@ configurations.checkstyle {
} }
} }
checkstyleMain { checkstyleMain {
source ='src/main/java' source = 'src/main/java'
} }
checkstyleTest { checkstyleTest {
source ='src/test/java' source = 'src/test/java'
} }
tasks.withType(Checkstyle) { tasks.withType(Checkstyle) {
reports { reports {
@ -82,16 +85,16 @@ tasks.withType(Checkstyle) {
} }
} }
protobuf { protobuf {
protoc { protoc {
artifact = 'com.google.protobuf:protoc:3.24.3' artifact = 'com.google.protobuf:protoc:3.24.3'
} }
} }
sourceSets { sourceSets {
main { main {
proto { proto {
srcDir '../HIRS_ProvisionerTPM2/src' srcDir '../HIRS_Provisioner.NET/hirs/Resources'
}
} }
}
} }
test { test {

View File

@ -7,10 +7,10 @@
dir=$(pwd) dir=$(pwd)
# Relative paths are different when building locally versus on CI # Relative paths are different when building locally versus on CI
if [[ "$dir" == *"package"* ]]; then if [[ "$dir" == *"package"* ]]; then
SRC_DIR=$dir/../../../../../../HIRS_ProvisionerTPM2/src SRC_DIR=$dir/../../../../../../HIRS_Provisioner.NET/hirs/Resources
DEST_DIR=$dir/../src/main/java DEST_DIR=$dir/../src/main/java
else else
SRC_DIR=../../HIRS_ProvisionerTPM2/src SRC_DIR=../../HIRS_Provisioner.NET/hirs/Resources
DEST_DIR=../src/main/java DEST_DIR=../src/main/java
fi fi
protoc -I=$SRC_DIR --java_out=$DEST_DIR $SRC_DIR/ProvisionerTpm2.proto protoc -I=$SRC_DIR --java_out=$DEST_DIR $SRC_DIR/ProvisionerTpm2.proto

View File

@ -2,18 +2,18 @@
<!-- Docs at http://findbugs.sourceforge.net/manual/filter.html --> <!-- Docs at http://findbugs.sourceforge.net/manual/filter.html -->
<FindBugsFilter> <FindBugsFilter>
<Match> <Match>
<Package name="~hirs\.attestationca\.configuration.*" /> <Package name="~hirs\.attestationca\.configuration.*"/>
</Match> </Match>
<Match> <Match>
<!-- https://github.com/spotbugs/spotbugs/pull/2748 --> <!-- https://github.com/spotbugs/spotbugs/pull/2748 -->
<Bug pattern="CT_CONSTRUCTOR_THROW" /> <Bug pattern="CT_CONSTRUCTOR_THROW"/>
</Match> </Match>
<!-- roughly 55 instances of this appear --> <!-- roughly 55 instances of this appear -->
<Match> <Match>
<Bug pattern="EI_EXPOSE_REP" /> <Bug pattern="EI_EXPOSE_REP"/>
</Match> </Match>
<Match> <Match>
<Bug pattern="EI_EXPOSE_REP2" /> <Bug pattern="EI_EXPOSE_REP2"/>
</Match> </Match>
<Match> <Match>
<Class name="hirs.attestationca.persist.AttestationCertificateAuthorityTest"/> <Class name="hirs.attestationca.persist.AttestationCertificateAuthorityTest"/>

View File

@ -45,44 +45,42 @@ public abstract class AttestationCertificateAuthority {
* A handle to the service used to validate the supply chain. * A handle to the service used to validate the supply chain.
*/ */
private final SupplyChainValidationService supplyChainValidationService; 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<TPM2ProvisionerState> 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 * Container wired application configuration property identifying the number of days that
* certificates issued by this ACA are valid for. * certificates issued by this ACA are valid for.
*/ */
private Integer validDays = 1; 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<TPM2ProvisionerState> tpm2ProvisionerStateDBManager;
private final ReferenceDigestValueRepository referenceDigestValueRepository;
private final PolicyRepository policyRepository;
private final TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository;
private CertificateRequestProcessor certificateRequestHandler;
private IdentityClaimProcessor identityClaimHandler;
/** /**
* Constructor. * Constructor.
* @param supplyChainValidationService the supply chain service *
* @param privateKey the ACA private key * @param supplyChainValidationService the supply chain service
* @param acaCertificate the ACA certificate * @param privateKey the ACA private key
* @param structConverter the struct converter * @param acaCertificate the ACA certificate
* @param componentResultRepository the component result manager * @param structConverter the struct converter
* @param componentInfoRepository the component info manager * @param componentResultRepository the component result manager
* @param certificateRepository the certificate manager * @param componentInfoRepository the component info manager
* @param referenceManifestRepository the Reference Manifest manager * @param certificateRepository the certificate manager
* @param validDays the number of days issued certs are valid * @param issuedCertificateRepository the issued certificate repository
* @param deviceRepository the device manager * @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 referenceDigestValueRepository the reference event manager
* @param policyRepository policy setting repository * @param policyRepository policy setting repository
* @param tpm2ProvisionerStateRepository tpm2 provisioner state repository * @param tpm2ProvisionerStateRepository tpm2 provisioner state repository
*/ */
@SuppressWarnings("checkstyle:parameternumber")
public AttestationCertificateAuthority( public AttestationCertificateAuthority(
final SupplyChainValidationService supplyChainValidationService, final SupplyChainValidationService supplyChainValidationService,
final PrivateKey privateKey, final X509Certificate acaCertificate, final PrivateKey privateKey, final X509Certificate acaCertificate,
@ -121,14 +119,31 @@ public abstract class AttestationCertificateAuthority {
deviceRepository, tpm2ProvisionerStateRepository, policyRepository); 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) { byte[] processIdentityClaimTpm2(final byte[] identityClaim) {
return this.identityClaimHandler.processIdentityClaimTpm2(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) { byte[] processCertificateRequest(final byte[] certificateRequest) {
return this.certificateRequestHandler.processCertificateRequest(certificateRequest); return this.certificateRequestHandler.processCertificateRequest(certificateRequest);
} }
/**
* Retrieves the encoded public key.
*
* @return encoded public key
*/
public byte[] getPublicKey() { public byte[] getPublicKey() {
return acaCertificate.getPublicKey().getEncoded(); return acaCertificate.getPublicKey().getEncoded();
} }

View File

@ -4,10 +4,13 @@ import jakarta.persistence.criteria.CriteriaQuery;
/** /**
* Allows a user of the DBManager to modify the criteria object before processing. * Allows a user of the DBManager to modify the criteria object before processing.
*
* @param <T> the parameter type
*/ */
public interface CriteriaModifier<T> { public interface CriteriaModifier<T> {
/** /**
* Allows a client to modify the criteria object by reference. * Allows a client to modify the criteria object by reference.
*
* @param criteria The hibernate criteria builder object * @param criteria The hibernate criteria builder object
*/ */
void modify(CriteriaQuery<T> criteria); void modify(CriteriaQuery<T> criteria);

View File

@ -12,8 +12,7 @@ public class DBManagerException extends RuntimeException {
* Creates a new <code>DBManagerException</code> that has the message * Creates a new <code>DBManagerException</code> that has the message
* <code>msg</code>. * <code>msg</code>.
* *
* @param msg * @param msg exception message
* exception message
*/ */
public DBManagerException(final String msg) { public DBManagerException(final String msg) {
super(msg); super(msg);
@ -23,8 +22,7 @@ public class DBManagerException extends RuntimeException {
* Creates a new <code>DBManagerException</code> that wraps the given * Creates a new <code>DBManagerException</code> that wraps the given
* <code>Throwable</code>. * <code>Throwable</code>.
* *
* @param t * @param t root cause
* root cause
*/ */
public DBManagerException(final Throwable t) { public DBManagerException(final Throwable t) {
super(t); super(t);
@ -34,13 +32,11 @@ public class DBManagerException extends RuntimeException {
* Creates a new <code>DBManagerException</code> that has the message * Creates a new <code>DBManagerException</code> that has the message
* <code>msg</code> and wraps the root cause. * <code>msg</code> and wraps the root cause.
* *
* @param msg * @param msg exception message
* exception message * @param t root cause
* @param t
* root cause
*/ */
public DBManagerException(final String msg, final Throwable t) { public DBManagerException(final String msg, final Throwable t) {
super(msg, t); super(msg, t);
} }
} }

View File

@ -14,8 +14,10 @@ import java.util.ArrayList;
* @param <T> Class accepts generic for the list of data records. * @param <T> Class accepts generic for the list of data records.
*/ */
@Data @Data
@EqualsAndHashCode(callSuper=false) @EqualsAndHashCode(callSuper = false)
public class FilteredRecordsList<T> extends ArrayList<T> { public class FilteredRecordsList<T> extends ArrayList<T> {
private long recordsTotal, recordsFiltered; private long recordsTotal;
private long recordsFiltered;
} }

View File

@ -5,6 +5,7 @@ import java.util.Map;
/** /**
* Interface defining methods for getting ordered lists from a data source. Includes * Interface defining methods for getting ordered lists from a data source. Includes
* properties for sorting, paging, and searching. * properties for sorting, paging, and searching.
*
* @param <T> the record type, T. * @param <T> the record type, T.
*/ */
public interface OrderedListQuerier<T> { public interface OrderedListQuerier<T> {
@ -14,16 +15,16 @@ public interface OrderedListQuerier<T> {
* direction (ASC, DESC) that is provided by the user. This method helps * direction (ASC, DESC) that is provided by the user. This method helps
* support the server-side processing in the JQuery DataTables. * support the server-side processing in the JQuery DataTables.
* *
* @param clazz class type of <code>T</code>s to search for (may be null to * @param clazz class type of <code>T</code>s to search for (may be null to
* use Class&lt;T&gt;) * use Class&lt;T&gt;)
* @param columnToOrder Column to be ordered * @param columnToOrder Column to be ordered
* @param ascending direction of sort * @param ascending direction of sort
* @param firstResult starting point of first result in set * @param firstResult starting point of first result in set
* @param maxResults total number we want returned for display in table * @param maxResults total number we want returned for display in table
* @param search string of criteria to be matched to visible columns * @param search string of criteria to be matched to visible columns
* @param searchableColumns Map of String and boolean values with column * @param searchableColumns Map of String and boolean values with column
* headers and whether they should be searched. Boolean is true if field provides a * headers and whether they should be searched. Boolean is true if field provides
* typical String that can be searched by Hibernate without transformation. * a typical String that can be searched by Hibernate without transformation.
* @return FilteredRecordsList object with query data * @return FilteredRecordsList object with query data
* @throws DBManagerException if unable to create the list * @throws DBManagerException if unable to create the list
*/ */
@ -41,21 +42,20 @@ public interface OrderedListQuerier<T> {
* support the server-side processing in the JQuery DataTables. For entities that support * support the server-side processing in the JQuery DataTables. For entities that support
* soft-deletes, the returned list does not contain <code>T</code>s that have been soft-deleted. * soft-deletes, the returned list does not contain <code>T</code>s that have been soft-deleted.
* *
* @param clazz class type of <code>T</code>s to search for (may be null to * @param clazz class type of <code>T</code>s to search for (may be null to
* use Class&lt;T&gt;) * use Class&lt;T&gt;)
* @param columnToOrder Column to be ordered * @param columnToOrder Column to be ordered
* @param ascending direction of sort * @param ascending direction of sort
* @param firstResult starting point of first result in set * @param firstResult starting point of first result in set
* @param maxResults total number we want returned for display in table * @param maxResults total number we want returned for display in table
* @param search string of criteria to be matched to visible columns * @param search string of criteria to be matched to visible columns
* @param searchableColumns Map of String and boolean values with column * @param searchableColumns Map of String and boolean values with column
* headers and whether they should be searched. Boolean is true if field provides a * headers and whether they should be searched. Boolean is true if field provides
* typical String that can be searched by Hibernate without transformation. * a typical String that can be searched by Hibernate without transformation.
* @param criteriaModifier a way to modify the criteria used in the query * @param criteriaModifier a way to modify the criteria used in the query
* @return FilteredRecordsList object with query data * @return FilteredRecordsList object with query data
* @throws DBManagerException if unable to create the list * @throws DBManagerException if unable to create the list
*/ */
@SuppressWarnings("checkstyle:parameternumber")
FilteredRecordsList<T> getOrderedList( FilteredRecordsList<T> getOrderedList(
Class<? extends T> clazz, String columnToOrder, Class<? extends T> clazz, String columnToOrder,
boolean ascending, int firstResult, boolean ascending, int firstResult,

View File

@ -33,13 +33,13 @@ import java.security.cert.X509Certificate;
// detects if file exists, if not, ignore errors // detects if file exists, if not, ignore errors
@PropertySource(value = "file:/etc/hirs/aca/application.properties", @PropertySource(value = "file:/etc/hirs/aca/application.properties",
ignoreResourceNotFound = true), ignoreResourceNotFound = true),
@PropertySource(value = "file:C:/ProgramData/hirs/aca/application.win.properties", @PropertySource(value = "file:C:/ProgramData/hirs/aca/application.win.properties",
ignoreResourceNotFound = true) ignoreResourceNotFound = true)
}) })
@RestController @RestController
@RequestMapping("/HIRS_AttestationCA") @RequestMapping("/HIRS_AttestationCA")
public class RestfulAttestationCertificateAuthority extends AttestationCertificateAuthority implements RestfulInterface { public class RestfulAttestationCertificateAuthority extends AttestationCertificateAuthority
implements RestfulInterface {
/** /**
* Constructor. * Constructor.
@ -47,8 +47,11 @@ public class RestfulAttestationCertificateAuthority extends AttestationCertifica
* @param supplyChainValidationService scp service * @param supplyChainValidationService scp service
* @param privateKey the ACA private key * @param privateKey the ACA private key
* @param acaCertificate the ACA certificate * @param acaCertificate the ACA certificate
* @param structConverter the struct converter
* @param componentResultRepository the component result repository * @param componentResultRepository the component result repository
* @param componentInfoRepository the component info repository
* @param certificateRepository the certificate manager * @param certificateRepository the certificate manager
* @param issuedCertificateRepository the issued certificate repository
* @param referenceManifestRepository the referenceManifestManager * @param referenceManifestRepository the referenceManifestManager
* @param validDays the number of days issued certs are valid * @param validDays the number of days issued certs are valid
* @param deviceRepository the device manager * @param deviceRepository the device manager
@ -56,11 +59,11 @@ public class RestfulAttestationCertificateAuthority extends AttestationCertifica
* @param policyRepository the provisioning policy entity * @param policyRepository the provisioning policy entity
* @param tpm2ProvisionerStateRepository the provisioner state * @param tpm2ProvisionerStateRepository the provisioner state
*/ */
@SuppressWarnings({"checkstyle:parameternumber"})
@Autowired @Autowired
public RestfulAttestationCertificateAuthority( public RestfulAttestationCertificateAuthority(
final SupplyChainValidationService supplyChainValidationService, final SupplyChainValidationService supplyChainValidationService,
final PrivateKey privateKey, final X509Certificate acaCertificate, final PrivateKey privateKey,
final X509Certificate acaCertificate,
final StructConverter structConverter, final StructConverter structConverter,
final ComponentResultRepository componentResultRepository, final ComponentResultRepository componentResultRepository,
final ComponentInfoRepository componentInfoRepository, final ComponentInfoRepository componentInfoRepository,
@ -82,7 +85,7 @@ public class RestfulAttestationCertificateAuthority extends AttestationCertifica
/** /**
* Listener for identity requests from TPM 2.0 provisioning. * Listener for identity requests from TPM 2.0 provisioning.
* * <p>
* Processes a given IdentityClaim and generates a response * Processes a given IdentityClaim and generates a response
* containing an encrypted nonce to be returned by the client in * containing an encrypted nonce to be returned by the client in
* a future handshake request. * 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. * the client's desired attestation key, if the correct nonce is supplied.
* *
* @param certificateRequest request containing nonce from earlier identity * @param certificateRequest request containing nonce from earlier identity
* * claim handshake * * claim handshake
* @return The response to the client provisioner. * @return The response to the client provisioner.
*/ */
@Override @Override
@ -121,8 +124,8 @@ public class RestfulAttestationCertificateAuthority extends AttestationCertifica
* (non-javadoc) * (non-javadoc)
* <p> * <p>
* Wrap the {@link AttestationCertificateAuthority#getPublicKey()} with a Spring * 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 * {@link org.springframework.web.bind.annotation.RequestMapping} such that Spring can serialize
* HTTP Request. * the certificate to be returned to an HTTP Request.
*/ */
@Override @Override
@ResponseBody @ResponseBody

View File

@ -5,8 +5,20 @@ package hirs.attestationca.persist;
*/ */
public interface RestfulInterface { 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); 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); byte[] processCertificateRequest(byte[] certificateRequest);
} }

View File

@ -32,7 +32,7 @@ public abstract class AbstractEntity implements Serializable {
@Getter @Getter
private UUID id; private UUID id;
@Column (name = "create_time") @Column(name = "create_time")
private Date createTime; private Date createTime;
/** /**
@ -47,9 +47,10 @@ public abstract class AbstractEntity implements Serializable {
/** /**
* Setter for the UUID that can not be null * Setter for the UUID that can not be null
* and can not be overridden. * and can not be overridden.
*
* @param id - primary able key * @param id - primary able key
*/ */
public void setId(UUID id) { public void setId(final UUID id) {
if (id != null) { if (id != null) {
this.id = id; this.id = id;
} }
@ -74,6 +75,11 @@ public abstract class AbstractEntity implements Serializable {
createTime.setTime(new Date().getTime()); createTime.setTime(new Date().getTime());
} }
/**
* Generates an integer hash code for this entity.
*
* @return hash code
*/
@Override @Override
public int hashCode() { public int hashCode() {
if (id != null) { if (id != null) {
@ -82,6 +88,13 @@ public abstract class AbstractEntity implements Serializable {
return super.hashCode(); 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 @Override
public boolean equals(final Object object) { public boolean equals(final Object object) {
if (this == object) { if (this == object) {

View File

@ -6,7 +6,11 @@ import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType; import jakarta.persistence.GenerationType;
import jakarta.persistence.Id; import jakarta.persistence.Id;
import jakarta.persistence.Table; import jakarta.persistence.Table;
import lombok.*; import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
/** /**
* The <code>Appraiser</code> class represents an appraiser that can appraise a <code>Report</code>. * The <code>Appraiser</code> class represents an appraiser that can appraise a <code>Report</code>.

View File

@ -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 * Signals that this entity has been archived, by setting the archivedTime to the current date
* and time. * and time.
* *
* @return * @return true if time was null and date was set.
* true if time was null and date was set. * false is archived time is already set, signifying the entity has been archived.
* false is archived time is already set, signifying the entity has been archived.
*/ */
public final boolean archive() { public final boolean archive() {
if (this.archivedTime == null) { if (this.archivedTime == null) {
@ -73,8 +72,7 @@ public abstract class ArchivableEntity extends AbstractEntity {
* purposes so the reason for action taken can be referenced. * purposes so the reason for action taken can be referenced.
* *
* @param description - description of the action taken for resolution * @param description - description of the action taken for resolution
* @return * @return boolean result is dependent on the return value of the archive() method
* boolean result is dependent on the return value of the archive() method
*/ */
public final boolean archive(final String description) { public final boolean archive(final String description) {
if (archive()) { if (archive()) {
@ -90,7 +88,7 @@ public abstract class ArchivableEntity extends AbstractEntity {
* entity has not been resolved, then null is returned. * entity has not been resolved, then null is returned.
* *
* @return archivedTime * @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() { public final Date getArchivedTime() {
if (archivedTime == null) { 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 * 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. * not been archived. If the time is already null then this call was unnecessary.
* *
* @return * @return true if the time is changed to null.
* true if the time is changed to null. * false if time was already set to null.
* false if time was already set to null.
*/ */
public final boolean restore() { public final boolean restore() {
if (this.archivedTime != null) { if (this.archivedTime != null) {

View File

@ -16,7 +16,7 @@ import jakarta.persistence.MappedSuperclass;
@Inheritance(strategy = InheritanceType.JOINED) @Inheritance(strategy = InheritanceType.JOINED)
@Access(AccessType.FIELD) @Access(AccessType.FIELD)
@MappedSuperclass @MappedSuperclass
public abstract class Policy extends UserDefinedEntity { public abstract class Policy extends UserDefinedEntity {
/** /**
* Default empty constructor is required for Hibernate. It is protected to * Default empty constructor is required for Hibernate. It is protected to
@ -29,8 +29,7 @@ public abstract class Policy extends UserDefinedEntity {
/** /**
* Creates a new <code>Policy</code> with the specified name. * Creates a new <code>Policy</code> with the specified name.
* *
* @param name * @param name name
* name
*/ */
public Policy(final String name) { public Policy(final String name) {
super(name); super(name);
@ -40,10 +39,8 @@ public abstract class Policy extends UserDefinedEntity {
* Creates a new <code>Policy</code> with the specified name and * Creates a new <code>Policy</code> with the specified name and
* description. * description.
* *
* @param name * @param name name (required)
* name (required) * @param description description (may be null)
* @param description
* description (may be null)
*/ */
public Policy(final String name, final String description) { public Policy(final String name, final String description) {
super(name, description); super(name, description);

View File

@ -4,9 +4,9 @@ import jakarta.persistence.Column;
import jakarta.persistence.MappedSuperclass; import jakarta.persistence.MappedSuperclass;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import lombok.NonNull;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import lombok.NonNull;
/** /**
* An abstract archivable entity that can be given a user-defined name and description. * 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 { public abstract class UserDefinedEntity extends ArchivableEntity {
@Column(nullable = false, unique = true) @Column(nullable = false, unique = true)
@NonNull private String name; @NonNull
private String name;
@ToString.Exclude @ToString.Exclude
@Column(nullable = false, unique = false) @Column(nullable = false, unique = false)
@NonNull private String description = ""; @NonNull
private String description = "";
/** /**
* Default empty constructor is required for Hibernate. It is protected to * Default empty constructor is required for Hibernate. It is protected to
@ -47,8 +49,7 @@ public abstract class UserDefinedEntity extends ArchivableEntity {
* an instance of <code>UserDefinedEntity</code> and its name is the same as this * an instance of <code>UserDefinedEntity</code> and its name is the same as this
* <code>UserDefinedEntity</code>. Otherwise this returns false. * <code>UserDefinedEntity</code>. Otherwise this returns false.
* *
* @param other * @param other other object to test for equals
* other object to test for equals
* @return true if other is <code>Baseline</code> and has same name * @return true if other is <code>Baseline</code> and has same name
*/ */
@Override @Override
@ -56,11 +57,10 @@ public abstract class UserDefinedEntity extends ArchivableEntity {
if (this == other) { if (this == other) {
return true; return true;
} }
if (!(other instanceof UserDefinedEntity)) { if (!(other instanceof UserDefinedEntity entity)) {
return false; return false;
} }
final UserDefinedEntity entity = (UserDefinedEntity) other;
return this.getName().equals(entity.getName()); return this.getName().equals(entity.getName());
} }

View File

@ -12,12 +12,77 @@ import java.util.UUID;
@Repository @Repository
public interface CACredentialRepository extends JpaRepository<CertificateAuthorityCredential, UUID> { public interface CACredentialRepository extends JpaRepository<CertificateAuthorityCredential, UUID> {
/**
* 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<CertificateAuthorityCredential> findByArchiveFlag(boolean archiveFlag); List<CertificateAuthorityCredential> 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<CertificateAuthorityCredential> findByArchiveFlag(boolean archiveFlag, Pageable pageable); Page<CertificateAuthorityCredential> 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<CertificateAuthorityCredential> findBySubject(String subject); List<CertificateAuthorityCredential> 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<CertificateAuthorityCredential> findBySubjectSorted(String subject); List<CertificateAuthorityCredential> 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<CertificateAuthorityCredential> findBySubjectAndArchiveFlag(String subject, boolean archiveFlag); List<CertificateAuthorityCredential> findBySubjectAndArchiveFlag(String subject, boolean archiveFlag);
List<CertificateAuthorityCredential> 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<CertificateAuthorityCredential> 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 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);
} }

View File

@ -16,26 +16,129 @@ import java.util.UUID;
@Repository @Repository
public interface CertificateRepository extends JpaRepository<Certificate, UUID> { public interface CertificateRepository extends JpaRepository<Certificate, UUID> {
/**
* 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) @Query(value = "SELECT * FROM Certificate where id = ?1", nativeQuery = true)
Certificate getCertificate(UUID uuid); 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) @Query(value = "SELECT * FROM Certificate where subject = ?1 AND DTYPE = ?2", nativeQuery = true)
List<Certificate> findBySubject(String subject, String dType); List<Certificate> 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) @Query(value = "SELECT * FROM Certificate where subjectSorted = ?1 AND DTYPE = ?2", nativeQuery = true)
List<Certificate> findBySubjectSorted(String subjectSorted, String dType); List<Certificate> 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) @Query(value = "SELECT * FROM Certificate where DTYPE = ?1", nativeQuery = true)
List<Certificate> findByType(String dType); List<Certificate> 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) @Query(value = "SELECT * FROM Certificate where serialNumber = ?1 AND DTYPE = ?2", nativeQuery = true)
Certificate findBySerialNumber(BigInteger serialNumber, String dType); 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<PlatformCredential> byBoardSerialNumber(String boardSerialNumber); List<PlatformCredential> 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); 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<PlatformCredential> getByHolderSerialNumber(BigInteger holderSerialNumber); List<PlatformCredential> 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) @Query(value = "SELECT * FROM Certificate where certificateHash = ?1 AND DTYPE = ?2", nativeQuery = true)
Certificate findByCertificateHash(int certificateHash, String dType); 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); 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); 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<IssuedAttestationCertificate> findByDeviceIdAndIsLDevID(UUID deviceId, boolean isLDevID, Sort sort); List<IssuedAttestationCertificate> 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); Certificate findByCertificateHash(int certificateHash);
} }

View File

@ -10,6 +10,7 @@ public interface ComponentAttributeRepository extends JpaRepository<ComponentAtt
/** /**
* Query to look up Attribute Results based on the PlatformCredential's * Query to look up Attribute Results based on the PlatformCredential's
* db component id. * db component id.
*
* @param componentId the unique id for the component identifier * @param componentId the unique id for the component identifier
* @return a list of attribute results * @return a list of attribute results
*/ */
@ -17,6 +18,7 @@ public interface ComponentAttributeRepository extends JpaRepository<ComponentAtt
/** /**
* Query to look up Attribute Results based on the validation id. * Query to look up Attribute Results based on the validation id.
*
* @param provisionSessionId unique id generated to link supply chain summary * @param provisionSessionId unique id generated to link supply chain summary
* @return a list of attribute results * @return a list of attribute results
*/ */
@ -24,9 +26,11 @@ public interface ComponentAttributeRepository extends JpaRepository<ComponentAtt
/** /**
* Query to look up Attribute Results based on the component id and the session id. * Query to look up Attribute Results based on the component id and the session id.
* @param componentId the unique id for the component identifier *
* @param componentId the unique id for the component identifier
* @param provisionSessionId unique id generated to link supply chain summary * @param provisionSessionId unique id generated to link supply chain summary
* @return a list of attribute results * @return a list of attribute results
*/ */
List<ComponentAttributeResult> findByComponentIdAndProvisionSessionId(UUID componentId, UUID provisionSessionId); List<ComponentAttributeResult> findByComponentIdAndProvisionSessionId(UUID componentId,
UUID provisionSessionId);
} }

View File

@ -9,6 +9,7 @@ import java.util.UUID;
public interface ComponentInfoRepository extends JpaRepository<ComponentInfo, UUID> { public interface ComponentInfoRepository extends JpaRepository<ComponentInfo, UUID> {
/** /**
* Query that retrieves device components by device name. * Query that retrieves device components by device name.
*
* @param deviceName string for the host name * @param deviceName string for the host name
* @return a list of device components * @return a list of device components
*/ */
@ -17,7 +18,8 @@ public interface ComponentInfoRepository extends JpaRepository<ComponentInfo, UU
/** /**
* Query that retrieves device components by device name and * Query that retrieves device components by device name and
* the component serial number. * the component serial number.
* @param deviceName string for the host name *
* @param deviceName string for the host name
* @param componentSerial string for the component serial * @param componentSerial string for the component serial
* @return a list of device components * @return a list of device components
*/ */

View File

@ -12,6 +12,7 @@ public interface ComponentResultRepository extends JpaRepository<ComponentResult
/** /**
* Query based on the device serial number. * Query based on the device serial number.
*
* @param boardSerialNumber variable holding the device serial number * @param boardSerialNumber variable holding the device serial number
* @return a list of component result. * @return a list of component result.
*/ */
@ -19,16 +20,18 @@ public interface ComponentResultRepository extends JpaRepository<ComponentResult
/** /**
* Query based on the device serial number. * Query based on the device serial number.
*
* @param boardSerialNumber variable holding the device serial number * @param boardSerialNumber variable holding the device serial number
* @param delta flag indicating if the component is associated with a delta certificate * @param delta flag indicating if the component is associated with a delta certificate
* @return a list of component result. * @return a list of component result.
*/ */
List<ComponentResult> findByBoardSerialNumberAndDelta(String boardSerialNumber, boolean delta); List<ComponentResult> findByBoardSerialNumberAndDelta(String boardSerialNumber, boolean delta);
/** /**
* Query based on certificate serial number and device serial number. * Query based on certificate serial number and device serial number.
*
* @param certificateSerialNumber certificate specific 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. * @return a list of component result.
*/ */
List<ComponentResult> findByCertificateSerialNumberAndBoardSerialNumber( List<ComponentResult> findByCertificateSerialNumberAndBoardSerialNumber(

View File

@ -8,5 +8,11 @@ import java.util.UUID;
@Repository @Repository
public interface DeviceRepository extends JpaRepository<Device, UUID> { public interface DeviceRepository extends JpaRepository<Device, UUID> {
/**
* Query that retrieves a device using the provided device name.
*
* @param deviceName device name
* @return a device
*/
Device findByName(String deviceName); Device findByName(String deviceName);
} }

View File

@ -13,9 +13,44 @@ import java.util.UUID;
@Repository @Repository
public interface EndorsementCredentialRepository extends JpaRepository<EndorsementCredential, UUID> { public interface EndorsementCredentialRepository extends JpaRepository<EndorsementCredential, UUID> {
/**
* Query that retrieves a list of endorsement credentials using the provided archive flag.
*
* @param archiveFlag archive flag
* @return a list of endorsement credentials
*/
List<EndorsementCredential> findByArchiveFlag(boolean archiveFlag); List<EndorsementCredential> 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<EndorsementCredential> findByArchiveFlag(boolean archiveFlag, Pageable pageable); Page<EndorsementCredential> 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); 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); 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<EndorsementCredential> findByDeviceId(UUID deviceId); List<EndorsementCredential> findByDeviceId(UUID deviceId);
} }

View File

@ -12,14 +12,74 @@ import java.util.UUID;
@Repository @Repository
public interface IDevIDCertificateRepository extends JpaRepository<IDevIDCertificate, UUID> { public interface IDevIDCertificateRepository extends JpaRepository<IDevIDCertificate, UUID> {
/**
* Query that retrieves a list of IDevId certificates using the provided archive flag.
*
* @param archiveFlag archive flag
* @return a list of IDevId certificates
*/
List<IDevIDCertificate> findByArchiveFlag(boolean archiveFlag); List<IDevIDCertificate> findByArchiveFlag(boolean archiveFlag);
Page<IDevIDCertificate> findByArchiveFlag(boolean archiveFlag, Pageable pageable); /**
/*List<IDevIDCertificate> findBySubject(String subject); * Query that retrieves a page of IDevId certificates using the provided archive flag and pageable value.
List<IDevIDCertificate> findBySubjectSorted(String subject); *
List<IDevIDCertificate> findBySubjectAndArchiveFlag(String subject, boolean archiveFlag); * @param archiveFlag archive flag
List<IDevIDCertificate> findBySubjectSortedAndArchiveFlag(String subject, boolean archiveFlag); * @param pageable pageable value
IDevIDCertificate findBySubjectKeyIdentifier(byte[] subjectKeyIdentifier); * @return a page of IDevId certificates
IDevIDCertificate findBySubjectKeyIdStringAndArchiveFlag(String subjectKeyIdString, boolean archiveFlag);
*/ */
} Page<IDevIDCertificate> 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<IDevIDCertificate> 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<IDevIDCertificate> 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<IDevIDCertificate> 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<IDevIDCertificate> 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);
}

View File

@ -12,7 +12,29 @@ import java.util.UUID;
@Repository @Repository
public interface IssuedCertificateRepository extends JpaRepository<IssuedAttestationCertificate, UUID> { public interface IssuedCertificateRepository extends JpaRepository<IssuedAttestationCertificate, UUID> {
/**
* 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<IssuedAttestationCertificate> findByArchiveFlag(boolean archiveFlag); List<IssuedAttestationCertificate> 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<IssuedAttestationCertificate> findByArchiveFlag(boolean archiveFlag, Pageable pageable); Page<IssuedAttestationCertificate> 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<IssuedAttestationCertificate> findByDeviceId(UUID deviceId); List<IssuedAttestationCertificate> findByDeviceId(UUID deviceId);
} }

View File

@ -12,7 +12,29 @@ import java.util.UUID;
@Repository @Repository
public interface PlatformCertificateRepository extends JpaRepository<PlatformCredential, UUID> { public interface PlatformCertificateRepository extends JpaRepository<PlatformCredential, UUID> {
/**
* Query that retrieves a list of platform credentials using the provided archive flag.
*
* @param archiveFlag archive flag
* @return a list of platform credentials
*/
List<PlatformCredential> findByArchiveFlag(boolean archiveFlag); List<PlatformCredential> 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<PlatformCredential> findByArchiveFlag(boolean archiveFlag, Pageable pageable); Page<PlatformCredential> 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<PlatformCredential> findByDeviceId(UUID deviceId); List<PlatformCredential> findByDeviceId(UUID deviceId);
} }

View File

@ -8,5 +8,12 @@ import java.util.UUID;
@Repository @Repository
public interface PolicyRepository extends JpaRepository<PolicySettings, UUID> { public interface PolicyRepository extends JpaRepository<PolicySettings, UUID> {
/**
* Query that retrieves policy settings using the provided name.
*
* @param name name
* @return policy settings
*/
PolicySettings findByName(String name); PolicySettings findByName(String name);
} }

View File

@ -10,10 +10,52 @@ import java.util.UUID;
@Repository @Repository
public interface ReferenceDigestValueRepository extends JpaRepository<ReferenceDigestValue, UUID> { public interface ReferenceDigestValueRepository extends JpaRepository<ReferenceDigestValue, UUID> {
/**
* 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<ReferenceDigestValue> findByModel(String model); List<ReferenceDigestValue> 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<ReferenceDigestValue> findByManufacturer(String manufacturer); List<ReferenceDigestValue> 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<ReferenceDigestValue> findValuesByBaseRimId(UUID associatedRimId); List<ReferenceDigestValue> 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<ReferenceDigestValue> findBySupportRimId(UUID supportRimId); List<ReferenceDigestValue> 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<ReferenceDigestValue> findBySupportRimHash(String supportRimHash); List<ReferenceDigestValue> 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<ReferenceDigestValue> findByManufacturerAndModel(String manufacturer, String model); List<ReferenceDigestValue> findByManufacturerAndModel(String manufacturer, String model);
} }

View File

@ -15,36 +15,193 @@ import java.util.UUID;
@Repository @Repository
public interface ReferenceManifestRepository extends JpaRepository<ReferenceManifest, UUID> { public interface ReferenceManifestRepository extends JpaRepository<ReferenceManifest, UUID> {
/**
* 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); 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); 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); 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); 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<BaseReferenceManifest> getBaseByManufacturerModel(String manufacturer, String model); List<BaseReferenceManifest> 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<BaseReferenceManifest> getByManufacturer(String manufacturer, String dType); List<BaseReferenceManifest> 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); 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<BaseReferenceManifest> findAllBaseRims(); List<BaseReferenceManifest> 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<SupportReferenceManifest> findAllSupportRims(); List<SupportReferenceManifest> 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); 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); 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); 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<SupportReferenceManifest> byDeviceName(String deviceName); List<SupportReferenceManifest> 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); 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<SupportReferenceManifest> getSupportByManufacturerModel(String manufacturer, String model); List<SupportReferenceManifest> 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); 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<ReferenceManifest> findByDeviceName(String deviceName); List<ReferenceManifest> 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<ReferenceManifest> findByArchiveFlag(boolean archiveFlag); List<ReferenceManifest> 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<ReferenceManifest> findByArchiveFlag(boolean archiveFlag, Pageable pageable); Page<ReferenceManifest> findByArchiveFlag(boolean archiveFlag, Pageable pageable);
} }

View File

@ -9,6 +9,19 @@ import java.util.UUID;
@Repository @Repository
public interface SupplyChainValidationRepository extends JpaRepository<SupplyChainValidation, UUID> { public interface SupplyChainValidationRepository extends JpaRepository<SupplyChainValidation, UUID> {
/**
* 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<SupplyChainValidation> findByValidationType(String validateType); List<SupplyChainValidation> 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<SupplyChainValidation> findByValidationResult(String validationResult); List<SupplyChainValidation> findByValidationResult(String validationResult);
} }

View File

@ -7,12 +7,34 @@ import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.util.UUID;
import java.util.List; import java.util.List;
import java.util.UUID;
@Repository @Repository
public interface SupplyChainValidationSummaryRepository extends JpaRepository<SupplyChainValidationSummary, UUID> { public interface SupplyChainValidationSummaryRepository
extends JpaRepository<SupplyChainValidationSummary, UUID> {
/**
* 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); 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<SupplyChainValidationSummary> findByArchiveFlagFalse(); List<SupplyChainValidationSummary> 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<SupplyChainValidationSummary> findByArchiveFlagFalse(Pageable pageable); Page<SupplyChainValidationSummary> findByArchiveFlagFalse(Pageable pageable);
} }

View File

@ -7,5 +7,11 @@ import org.springframework.stereotype.Repository;
@Repository @Repository
public interface TPM2ProvisionerStateRepository extends JpaRepository<TPM2ProvisionerState, Long> { public interface TPM2ProvisionerStateRepository extends JpaRepository<TPM2ProvisionerState, Long> {
/**
* 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); TPM2ProvisionerState findByFirstPartOfNonce(Long findByFirstPartOfNonce);
} }

View File

@ -0,0 +1 @@
package hirs.attestationca.persist.entity.manager;

View File

@ -35,12 +35,12 @@ public class TPM2ProvisionerState {
private byte[] identityClaim; private byte[] identityClaim;
@Column(nullable = false) @Column(nullable = false)
private Date timestamp = new Date(); private final Date timestamp = new Date();
/** /**
* Constructor. * Constructor.
* *
* @param nonce the nonce * @param nonce the nonce
* @param identityClaim the identity claim * @param identityClaim the identity claim
*/ */
public TPM2ProvisionerState(final byte[] nonce, final byte[] identityClaim) { 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. * Convenience method for finding the {@link TPM2ProvisionerState} associated with the nonce.
* *
* @param tpm2ProvisionerStateRepository the {@link TPM2ProvisionerStateRepository} * @param tpm2ProvisionerStateRepository the {@link TPM2ProvisionerStateRepository}
* to use when looking for the * to use when looking for the
* {@link TPM2ProvisionerState} * {@link TPM2ProvisionerState}
* @param nonce the nonce to use as the key for the {@link TPM2ProvisionerState} * @param nonce the nonce to use as the key for the {@link TPM2ProvisionerState}
* @return the {@link TPM2ProvisionerState} associated with the nonce; * @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( public static TPM2ProvisionerState getTPM2ProvisionerState(
final TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository, final TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository,
@ -114,4 +96,22 @@ public class TPM2ProvisionerState {
} }
return null; 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);
}
} }

View File

@ -0,0 +1 @@
package hirs.attestationca.persist.entity.tpm;

View File

@ -14,19 +14,20 @@ import jakarta.persistence.OneToOne;
import jakarta.persistence.Table; import jakarta.persistence.Table;
import lombok.AccessLevel; import lombok.AccessLevel;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.Objects;
@Entity @Entity
@Table(name = "Device") @Table(name = "Device")
@Setter @Setter
@NoArgsConstructor(access = AccessLevel.PROTECTED) @NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor @AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class Device extends AbstractEntity { public class Device extends AbstractEntity {
@Getter @Getter
@ -34,7 +35,7 @@ public class Device extends AbstractEntity {
private String name; private String name;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER,
optional = true, orphanRemoval = true) orphanRemoval = true)
private DeviceInfoReport deviceInfo; private DeviceInfoReport deviceInfo;
@Getter @Getter
@ -65,6 +66,11 @@ public class Device extends AbstractEntity {
@Column(name = "summary_id") @Column(name = "summary_id")
private String summaryId; private String summaryId;
/**
* Constructor creates a Device object using the provided device info report.
*
* @param deviceInfoReport device information report
*/
public Device(final DeviceInfoReport deviceInfoReport) { public Device(final DeviceInfoReport deviceInfoReport) {
super(); super();
if (deviceInfoReport != null) { if (deviceInfoReport != null) {
@ -94,6 +100,7 @@ public class Device extends AbstractEntity {
/** /**
* Getter for the report time stamp. * Getter for the report time stamp.
*
* @return a cloned version * @return a cloned version
*/ */
public Timestamp getLastReportTimestamp() { public Timestamp getLastReportTimestamp() {
@ -106,39 +113,22 @@ public class Device extends AbstractEntity {
/** /**
* Setter for the report time stamp. * Setter for the report time stamp.
* @param lastReportTimestamp *
* @param lastReportTimestamp last reported time
*/ */
public void setLastReportTimestamp(final Timestamp lastReportTimestamp) { public void setLastReportTimestamp(final Timestamp lastReportTimestamp) {
this.lastReportTimestamp = (Timestamp) lastReportTimestamp.clone(); 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() { public String toString() {
return String.format("Device Name: %s%nStatus: %s%nSummary: %s%n", 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())); (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);
}
}

View File

@ -23,6 +23,29 @@ import lombok.extern.log4j.Log4j2;
@XmlAccessorType(XmlAccessType.FIELD) @XmlAccessorType(XmlAccessType.FIELD)
public abstract class ExaminableRecord { 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. * State capturing if a record was examined during appraisal or not.
*/ */
@ -42,26 +65,4 @@ public abstract class ExaminableRecord {
*/ */
IGNORED 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;
}
} }

View File

@ -105,8 +105,7 @@ public class PolicySettings extends UserDefinedEntity {
/** /**
* Constructor used to initialize PolicySettings object. * Constructor used to initialize PolicySettings object.
* *
* @param name * @param name A name used to uniquely identify and reference the Supply Chain policy.
* A name used to uniquely identify and reference the Supply Chain policy.
*/ */
public PolicySettings(final String name) { public PolicySettings(final String name) {
super(name); super(name);
@ -115,10 +114,8 @@ public class PolicySettings extends UserDefinedEntity {
/** /**
* Constructor used to initialize PolicySettings object. * Constructor used to initialize PolicySettings object.
* *
* @param name * @param name A name used to uniquely identify and reference the supply chain policy.
* 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 description
* Optional description of the policy that can be added by the user
*/ */
public PolicySettings(final String name, final String description) { public PolicySettings(final String name, final String description) {
super(name, description); super(name, description);

View File

@ -10,6 +10,7 @@ import jakarta.persistence.Entity;
import jakarta.persistence.Inheritance; import jakarta.persistence.Inheritance;
import jakarta.persistence.InheritanceType; import jakarta.persistence.InheritanceType;
import jakarta.persistence.Table; import jakarta.persistence.Table;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
@ -28,14 +29,16 @@ import java.util.UUID;
* This class represents the Reference Integrity Manifest object that will be * This class represents the Reference Integrity Manifest object that will be
* loaded into the DB and displayed in the ACA. * loaded into the DB and displayed in the ACA.
*/ */
@Getter @ToString @Getter
@Setter
@ToString
@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = false) @EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = false)
@Log4j2 @Log4j2
@Entity @Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE) @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "ReferenceManifest") @Table(name = "ReferenceManifest")
@Access(AccessType.FIELD) @Access(AccessType.FIELD)
public class ReferenceManifest extends ArchivableEntity { public class ReferenceManifest extends ArchivableEntity {
/** /**
* Holds the name of the 'hexDecHash' field. * 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"; public static final String SCHEMA_PACKAGE = "hirs.utils.xjc";
@Setter(AccessLevel.NONE)
@EqualsAndHashCode.Include @EqualsAndHashCode.Include
@Column(columnDefinition = "mediumblob", nullable = false) @Column(columnDefinition = "mediumblob", nullable = false)
private byte[] rimBytes; private final byte[] rimBytes;
@Setter
@EqualsAndHashCode.Include @EqualsAndHashCode.Include
@Column(nullable = false) @Column(nullable = false)
private String rimType = "Base"; private String rimType = "Base";
@Setter
@Column @Column
private String tagId = null; private String tagId = null;
@Setter
@Column @Column
private boolean swidPatch = false; private boolean swidPatch = false;
@Setter
@Column @Column
private boolean swidSupplemental = false; private boolean swidSupplemental = false;
@Setter
@Column @Column
private String platformManufacturer = null; private String platformManufacturer = null;
@Setter
@Column @Column
private String platformManufacturerId = null; private String platformManufacturerId = null;
@Setter
@Column @Column
private String swidTagVersion = null; private String swidTagVersion = null;
@Setter
@Column @Column
private String swidVersion = null; private String swidVersion = null;
@Setter
@Column @Column
private String platformModel = null; private String platformModel = null;
@Setter
@Column(nullable = false) @Column(nullable = false)
private String fileName = null; private String fileName = null;
@Setter
@JdbcTypeCode(java.sql.Types.VARCHAR) @JdbcTypeCode(java.sql.Types.VARCHAR)
@Column @Column
private UUID associatedRim; private UUID associatedRim;
@Setter
@Column @Column
private String deviceName; private String deviceName;
@Setter
@Column @Column
private String hexDecHash = ""; private String hexDecHash = "";
@Setter
@Column @Column
private String eventLogHash = ""; private String eventLogHash = "";
@Setter
@Column @Column
@JsonIgnore @JsonIgnore
private String base64Hash = ""; private String base64Hash = "";
@ -141,6 +145,7 @@ public class ReferenceManifest extends ArchivableEntity {
/** /**
* Default constructor for ingesting the bytes of the file content. * Default constructor for ingesting the bytes of the file content.
*
* @param rimBytes - file contents. * @param rimBytes - file contents.
*/ */
public ReferenceManifest(final byte[] rimBytes) { public ReferenceManifest(final byte[] rimBytes) {
@ -183,10 +188,20 @@ public class ReferenceManifest extends ArchivableEntity {
return null; 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() { public boolean isBase() {
return rimType.equals(BASE_RIM); 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() { public boolean isSupport() {
return rimType.equals(SUPPORT_RIM); return rimType.equals(SUPPORT_RIM);
} }

View File

@ -2,7 +2,6 @@ package hirs.attestationca.persist.entity.userdefined;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import hirs.attestationca.persist.entity.ArchivableEntity; import hirs.attestationca.persist.entity.ArchivableEntity;
import hirs.attestationca.persist.entity.userdefined.rim.BaseReferenceManifest;
import hirs.attestationca.persist.enums.AppraisalStatus; import hirs.attestationca.persist.enums.AppraisalStatus;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
@ -10,6 +9,7 @@ import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn; import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable; import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany; import jakarta.persistence.ManyToMany;
import lombok.AccessLevel;
import lombok.Getter; import lombok.Getter;
import java.util.ArrayList; import java.util.ArrayList;
@ -19,51 +19,24 @@ import java.util.List;
/** /**
* Stores results of a single element of the supply chain validation process. * Stores results of a single element of the supply chain validation process.
*/ */
@Getter
@Entity @Entity
public class SupplyChainValidation extends ArchivableEntity { 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 @Column
private final ValidationType validationType; private final ValidationType validationType;
@Getter
@Column @Column
private final AppraisalStatus.Status validationResult; private final AppraisalStatus.Status validationResult;
@Getter(AccessLevel.NONE)
@ManyToMany(fetch = FetchType.EAGER) @ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "CertificatesUsedToValidate", @JoinTable(name = "CertificatesUsedToValidate",
joinColumns = { @JoinColumn(name = "validation_id", nullable = false) }) joinColumns = {@JoinColumn(name = "validation_id", nullable = false)})
private final List<Certificate> certificatesUsed; private final List<Certificate> certificatesUsed;
@Getter
@Column(length = RESULT_MESSAGE_LENGTH) @Column(length = RESULT_MESSAGE_LENGTH)
private final String message; private final String message;
@Getter
@Column @Column
private String rimId; private String rimId;
@ -81,10 +54,10 @@ public class SupplyChainValidation extends ArchivableEntity {
/** /**
* Construct a new SupplyChainValidation instance. * 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 validationResult whether the validation was successful or not
* @param certificatesUsed certificates used, if any, in the validation process; not null * @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, public SupplyChainValidation(final ValidationType validationType,
final AppraisalStatus.Status validationResult, final AppraisalStatus.Status validationResult,
@ -122,4 +95,29 @@ public class SupplyChainValidation extends ArchivableEntity {
public List<Certificate> getCertificatesUsed() { public List<Certificate> getCertificatesUsed() {
return Collections.unmodifiableList(certificatesUsed); 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
}
} }

View File

@ -32,7 +32,6 @@ import java.util.Set;
import java.util.UUID; import java.util.UUID;
/** /**
* A container class to group multiple related {@link SupplyChainValidation} instances * A container class to group multiple related {@link SupplyChainValidation} instances
* together. * together.
@ -40,12 +39,10 @@ import java.util.UUID;
@Entity @Entity
public class SupplyChainValidationSummary extends ArchivableEntity { public class SupplyChainValidationSummary extends ArchivableEntity {
private static final String DEVICE_ID_FIELD = "device.id";
@ManyToOne @ManyToOne
@JoinColumn(name = "device_id") @JoinColumn(name = "device_id")
private final Device device; private final Device device;
private static final String DEVICE_ID_FIELD = "device.id";
@Getter @Getter
@Column @Column
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
@ -72,120 +69,11 @@ public class SupplyChainValidationSummary extends ArchivableEntity {
this.message = Strings.EMPTY; this.message = Strings.EMPTY;
} }
/**
* This class enables the retrieval of SupplyChainValidationSummaries by their attributes.
*/
public static class Selector {
private final CrudRepository<SupplyChainValidationSummary, UUID>
supplyChainValidationSummaryCrudManager;
private final Map<String, Object> 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<SupplyChainValidationSummary, UUID>
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<SupplyChainValidationSummary> query = criteriaBuilder.createQuery(SupplyChainValidationSummary.class);
Root<SupplyChainValidationSummary> root = query.from(SupplyChainValidationSummary.class);
int i = 0;
for (Map.Entry<String, Object> 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<SupplyChainValidationSummary, UUID> certMan) {
return new SupplyChainValidationSummary.Selector(certMan);
}
/** /**
* Construct a new SupplyChainValidationSummary. * 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 * @param validations a Collection of Validations that should comprise this summary; not null
* @param provisionSessionId randomly generated UUID to associate with results * @param provisionSessionId randomly generated UUID to associate with results
*/ */
public SupplyChainValidationSummary(final Device device, public SupplyChainValidationSummary(final Device device,
@ -198,7 +86,7 @@ public class SupplyChainValidationSummary extends ArchivableEntity {
/** /**
* Construct a new SupplyChainValidationSummary. * 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 * @param validations a Collection of Validations that should comprise this summary; not null
*/ */
public SupplyChainValidationSummary(final Device device, public SupplyChainValidationSummary(final Device device,
@ -221,6 +109,18 @@ public class SupplyChainValidationSummary extends ArchivableEntity {
this.message = status.getMessage(); 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<SupplyChainValidationSummary, UUID> certMan) {
return new SupplyChainValidationSummary.Selector(certMan);
}
/** /**
* This retrieves the device associated with the supply chain validation summaries. * 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, return new AppraisalStatus(AppraisalStatus.Status.PASS,
Strings.EMPTY); Strings.EMPTY);
} }
/**
* This class enables the retrieval of SupplyChainValidationSummaries by their attributes.
*/
public static class Selector {
private final CrudRepository<SupplyChainValidationSummary, UUID>
supplyChainValidationSummaryCrudManager;
private final Map<String, Object> 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<SupplyChainValidationSummary, UUID>
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<SupplyChainValidationSummary> query =
criteriaBuilder.createQuery(SupplyChainValidationSummary.class);
Root<SupplyChainValidationSummary> root = query.from(SupplyChainValidationSummary.class);
int i = 0;
for (Map.Entry<String, Object> 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;
}
}
} }

View File

@ -3,6 +3,7 @@ package hirs.attestationca.persist.entity.userdefined.certificate;
import hirs.attestationca.persist.entity.userdefined.Certificate; import hirs.attestationca.persist.entity.userdefined.Certificate;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import lombok.AccessLevel;
import lombok.Getter; import lombok.Getter;
import org.apache.commons.codec.binary.Hex; 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 * This class persists Certificate Authority credentials by extending the base Certificate
* class with fields unique to CA credentials. * class with fields unique to CA credentials.
*/ */
@Getter
@Entity @Entity
public class CertificateAuthorityCredential extends Certificate { 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. * Holds the name of the 'subjectKeyIdentifier' field.
*/ */
public static final String SUBJECT_KEY_IDENTIFIER_FIELD = "subjectKeyIdentifier"; 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 CA_BYTE_SIZE = 20;
private static final int PREFIX_BYTE_SIZE = 4; private static final int PREFIX_BYTE_SIZE = 4;
@Getter(AccessLevel.NONE)
@Column @Column
private final byte[] subjectKeyIdentifier; 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 * 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. * manufacturer-provided CAs, and is therefore not currently parsed.
*/ */
@Getter
@Column @Column
private final String credentialType = "TCPA Trusted Platform Module Endorsement"; private final String credentialType = "TCPA Trusted Platform Module Endorsement";
@Column
private String subjectKeyIdString;
/** /**
* Construct a new CertificateAuthorityCredential given its binary contents. The given * Construct a new CertificateAuthorityCredential given its binary contents. The given
* certificate should represent either an X509 certificate or X509 attribute certificate. * certificate should represent either an X509 certificate or X509 attribute certificate.
@ -111,6 +112,13 @@ public class CertificateAuthorityCredential extends Certificate {
return null; 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) { private byte[] truncatePrefixBytes(final byte[] certificateBytes) {
byte[] temp = new byte[CA_BYTE_SIZE]; byte[] temp = new byte[CA_BYTE_SIZE];
System.arraycopy(certificateBytes, PREFIX_BYTE_SIZE, temp, 0, 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; 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) { public boolean equals(final Object o) {
if (this == o) { if (this == o) {
return true; return true;
@ -140,12 +154,17 @@ public class CertificateAuthorityCredential extends Certificate {
return Arrays.equals(subjectKeyIdentifier, that.subjectKeyIdentifier); return Arrays.equals(subjectKeyIdentifier, that.subjectKeyIdentifier);
} }
/**
* Creates an integer hash code.
*
* @return an integer hash code
*/
@Override @Override
@SuppressWarnings({"checkstyle:magicnumber", "checkstyle:avoidinlineconditionals"})
public int hashCode() { public int hashCode() {
final int hashCodeConst = 31;
int result = super.hashCode(); int result = super.hashCode();
result = 31 * result + (credentialType != null ? credentialType.hashCode() : 0); result = hashCodeConst * result + credentialType.hashCode();
result = 31 * result + Arrays.hashCode(subjectKeyIdentifier); result = hashCodeConst * result + Arrays.hashCode(subjectKeyIdentifier);
return result; return result;
} }
} }

View File

@ -1,47 +1,179 @@
package hirs.attestationca.persist.entity.userdefined.certificate; 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_HEADER = "-----BEGIN CERTIFICATE-----";
/**
*
*/
public static final String PEM_FOOTER = "-----END 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_HEADER = "-----BEGIN ATTRIBUTE CERTIFICATE-----";
/**
*
*/
public static final String PEM_ATTRIBUTE_FOOTER = "-----END 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 String MALFORMED_CERT_MESSAGE = "Malformed certificate detected.";
/**
*
*/
public static final int MAX_CERT_LENGTH_BYTES = 2048; 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 MAX_PUB_KEY_MODULUS_HEX_LENGTH = 1024;
/**
*
*/
public static final int KEY_USAGE_BIT0 = 0; public static final int KEY_USAGE_BIT0 = 0;
/**
*
*/
public static final int KEY_USAGE_BIT1 = 1; public static final int KEY_USAGE_BIT1 = 1;
/**
*
*/
public static final int KEY_USAGE_BIT2 = 2; public static final int KEY_USAGE_BIT2 = 2;
/**
*
*/
public static final int KEY_USAGE_BIT3 = 3; public static final int KEY_USAGE_BIT3 = 3;
/**
*
*/
public static final int KEY_USAGE_BIT4 = 4; public static final int KEY_USAGE_BIT4 = 4;
/**
*
*/
public static final int KEY_USAGE_BIT5 = 5; public static final int KEY_USAGE_BIT5 = 5;
/**
*
*/
public static final int KEY_USAGE_BIT6 = 6; public static final int KEY_USAGE_BIT6 = 6;
/**
*
*/
public static final int KEY_USAGE_BIT7 = 7; public static final int KEY_USAGE_BIT7 = 7;
/**
*
*/
public static final int KEY_USAGE_BIT8 = 8; public static final int KEY_USAGE_BIT8 = 8;
/**
*
*/
public static final String KEY_USAGE_DS = "DIGITAL SIGNATURE"; public static final String KEY_USAGE_DS = "DIGITAL SIGNATURE";
/**
*
*/
public static final String KEY_USAGE_NR = "NON-REPUDIATION"; public static final String KEY_USAGE_NR = "NON-REPUDIATION";
/**
*
*/
public static final String KEY_USAGE_KE = "KEY ENCIPHERMENT"; public static final String KEY_USAGE_KE = "KEY ENCIPHERMENT";
/**
*
*/
public static final String KEY_USAGE_DE = "DATA 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_KA = "KEY AGREEMENT";
/**
*
*/
public static final String KEY_USAGE_KC = "KEY CERT SIGN"; 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_CS = "CRL SIGN";
/**
*
*/
public static final String KEY_USAGE_EO = "ENCIPHER ONLY"; public static final String KEY_USAGE_EO = "ENCIPHER ONLY";
/**
*
*/
public static final String KEY_USAGE_DO = "DECIPHER 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_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 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 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 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 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 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_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 RSA512_256_OID = "1.2.840.113549.1.1.16";
/**
*
*/
public static final String RSA256_STRING = "SHA256WithRSA"; public static final String RSA256_STRING = "SHA256WithRSA";
/**
*
*/
public static final String RSA384_STRING = "SHA384WithRSA"; public static final String RSA384_STRING = "SHA384WithRSA";
/**
*
*/
public static final String RSA224_STRING = "SHA224WithRSA"; public static final String RSA224_STRING = "SHA224WithRSA";
/**
*
*/
public static final String RSA512_STRING = "SHA512WithRSA"; public static final String RSA512_STRING = "SHA512WithRSA";
/**
*
*/
public static final String RSA512_224_STRING = "SHA512-224WithRSA"; public static final String RSA512_224_STRING = "SHA512-224WithRSA";
/**
*
*/
public static final String RSA512_256_STRING = "SHA512-256WithRSA"; public static final String RSA512_256_STRING = "SHA512-256WithRSA";
/**
*
*/
public static final String ECDSA_STRING = "SHA256WithECDSA"; public static final String ECDSA_STRING = "SHA256WithECDSA";
/**
*
*/
public static final String ECDSA_SHA224_STRING = "SHA224WithECDSA"; public static final String ECDSA_SHA224_STRING = "SHA224WithECDSA";
/**
* Private constructor was created to silence checkstyle error.
*/
private CertificateVariables() {
}
} }

View File

@ -26,50 +26,80 @@ import java.util.Objects;
@NoArgsConstructor(access = AccessLevel.PROTECTED) @NoArgsConstructor(access = AccessLevel.PROTECTED)
public class ComponentResult extends ArchivableEntity { public class ComponentResult extends ArchivableEntity {
// String value for the Manufacturer title /**
* String value for the Manufacturer title.
*/
public static final String ATTRIBUTE_MANUFACTURER = "Manufacturer"; 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"; 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"; 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"; public static final String ATTRIBUTE_REVISION = "Revision";
// embedded component info
/**
* Embedded component info.
*/
@Setter @Setter
private String manufacturer; private String manufacturer;
@Setter @Setter
private String model; private String model;
@Setter @Setter
private String serialNumber; private String serialNumber;
@Setter @Setter
private String revisionNumber; private String revisionNumber;
private boolean fieldReplaceable = false; private boolean fieldReplaceable = false;
// this is a string because component class doesn't inherit serializable. // this is a string because component class doesn't inherit serializable.
@Setter @Setter
private String componentClassValue; private String componentClassValue;
private String componentClassStr; private String componentClassStr;
private String componentClassType; private String componentClassType;
private AttributeStatus attributeStatus; private AttributeStatus attributeStatus;
private String componentAddress; private String componentAddress;
private boolean version2 = false; private boolean version2 = false;
@Setter @Setter
private boolean delta = false; private boolean delta = false;
@Setter @Setter
private boolean failedValidation; private boolean failedValidation;
private String certificateType; private String certificateType;
private String issuerDN; private String issuerDN;
private String certificateSerialNumber;
private String boardSerialNumber;
private String uniformResourceIdentifier;
private String certificateSerialNumber;
private String boardSerialNumber;
private String uniformResourceIdentifier;
/** /**
* Default constructor. * 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 certificateSerialNumber unique number associated with header info.
* @param certificateType parameter holds version 1.2 or 2.0. * @param certificateType parameter holds version 1.2 or 2.0.
* @param componentIdentifier object with information from the platform certificate components. * @param componentIdentifier object with information from the platform certificate components.
*/ */
public ComponentResult(final String boardSerialNumber, final String certificateSerialNumber, public ComponentResult(final String boardSerialNumber, final String certificateSerialNumber,
final String certificateType, final String certificateType,
@ -94,10 +124,9 @@ public class ComponentResult extends ArchivableEntity {
// V2 fields // V2 fields
if (componentIdentifier.isVersion2() 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 // 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. // but find bugs is throwing a flag because instanceof isn't being used.
ComponentIdentifierV2 ciV2 = (ComponentIdentifierV2) componentIdentifier;
this.componentClassValue = ciV2.getComponentClass().getComponentIdentifier(); this.componentClassValue = ciV2.getComponentClass().getComponentIdentifier();
this.componentClassStr = ciV2.getComponentClass().toString(); this.componentClassStr = ciV2.getComponentClass().toString();
this.componentClassType = ciV2.getComponentClass().getRegistryType(); 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 * This method is only used by the certificate-details.jsp page. This
* method splits the compiled string of addresses into the component address * method splits the compiled string of addresses into the component address
* object for display on the jsp page. * object for display on the jsp page.
*
* @return a collection of component addresses. * @return a collection of component addresses.
*/ */
public List<ComponentAddress> getComponentAddresses() { public List<ComponentAddress> getComponentAddresses() {
@ -135,6 +165,7 @@ public class ComponentResult extends ArchivableEntity {
/** /**
* Returns a hash code that is associated with common fields for components. * Returns a hash code that is associated with common fields for components.
*
* @return int value of the elements * @return int value of the elements
*/ */
public int hashCommonElements() { public int hashCommonElements() {
@ -144,6 +175,7 @@ public class ComponentResult extends ArchivableEntity {
/** /**
* The string method for log entries. * The string method for log entries.
*
* @return a string for the component result * @return a string for the component result
*/ */
public String toString() { public String toString() {

View File

@ -12,12 +12,13 @@ import java.nio.file.Path;
* This class persists Conformance credentials by extending the base Certificate * This class persists Conformance credentials by extending the base Certificate
* class with fields unique to Conformance credentials. * class with fields unique to Conformance credentials.
*/ */
@NoArgsConstructor(access= AccessLevel.PROTECTED) @NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity @Entity
public class ConformanceCredential extends Certificate { 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<ConformanceCredential> { // public static class Selector extends CertificateSelector<ConformanceCredential> {
// /** // /**
// * Construct a new CertificateSelector that will use the given {@link CertificateManager} to // * 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. // * Get a Selector for use in retrieving ConformanceCredentials.
* // *
* @param certMan the CertificateManager to be used to retrieve persisted certificates // * @param certMan the CertificateManager to be used to retrieve persisted certificates
* @return a ConformanceCredential.Selector instance to use for retrieving certificates // * @return a ConformanceCredential.Selector instance to use for retrieving certificates
*/ // */
// public static Selector select(final CertificateManager certMan) { // public static Selector select(final CertificateManager certMan) {
// return new Selector(certMan); // return new Selector(certMan);
// } // }

View File

@ -18,26 +18,25 @@ import java.util.UUID;
* *
* @see Certificate * @see Certificate
*/ */
@NoArgsConstructor(access= AccessLevel.PACKAGE) @Setter
@Getter
@NoArgsConstructor(access = AccessLevel.PACKAGE)
@MappedSuperclass @MappedSuperclass
public abstract class DeviceAssociatedCertificate extends Certificate { 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. * Holds the name of the entity 'DEVICE_ID' field.
*/ */
protected static final String DEVICE_ID_FIELD = "device_id"; 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 * 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. * should represent either an X509 certificate or X509 attribute certificate.

View File

@ -1,5 +1,6 @@
package hirs.attestationca.persist.entity.userdefined.certificate; 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.TPMSecurityAssertions;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.TPMSpecification; import hirs.attestationca.persist.entity.userdefined.certificate.attributes.TPMSpecification;
import jakarta.persistence.Column; import jakarta.persistence.Column;
@ -53,16 +54,18 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
/** /**
*
* This class persists an Endorsement Credential by extending the base Certificate * This class persists an Endorsement Credential by extending the base Certificate
* class with fields unique to Endorsement credentials, as defined in the Trusted * class with fields unique to Endorsement credentials, as defined in the Trusted
* Computing Group Credential Profiles, specification v.1.2. * Computing Group Credential Profiles, specification v.1.2.
* * <p>
* trustedcomputinggroup.org/wp-content/uploads/Credential_Profiles_V1.2_Level2_Revision8.pdf * trustedcomputinggroup.org/wp-content/uploads/Credential_Profiles_V1.2_Level2_Revision8.pdf
*/ */
@Log4j2 @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) @EqualsAndHashCode(callSuper = false)
@NoArgsConstructor(access= AccessLevel.PROTECTED) @NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity @Entity
public class EndorsementCredential extends DeviceAssociatedCertificate { 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 * 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 @Getter
@Column @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 @Getter
@Column @Column
@ -131,22 +150,6 @@ public class EndorsementCredential extends DeviceAssociatedCertificate {
@Embedded @Embedded
private TPMSecurityAssertions tpmSecurityAssertions = null; //optional 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 @Transient
private Set<String> expectedOids; private Set<String> expectedOids;
@ -180,6 +183,7 @@ public class EndorsementCredential extends DeviceAssociatedCertificate {
* Parses the bytes as an EK. If parsing fails initially, the optionally present header * 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 * is removed and tried again. The cert header, if present, contains some certificate length
* information which isn't needed for parsing. * information which isn't needed for parsing.
*
* @param certificateBytes the bytes of the EC * @param certificateBytes the bytes of the EC
* @return the EC if a valid credential, null otherwise * @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 * 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 * matching OID keys are found, their values are encoded in the fields of the current
* EndorsementCredential object. * EndorsementCredential object.
*
* @throws IOException the input certificate bytes were not readable into an X509 * @throws IOException the input certificate bytes were not readable into an X509
* certificate format * certificate format
*/ */
@ -264,13 +269,13 @@ public class EndorsementCredential extends DeviceAssociatedCertificate {
value = entry.getValue(); value = entry.getValue();
if (oid.equals(TPM_MODEL)) { if (oid.equals(TPM_MODEL)) {
model = value.toString(); model = value.toString();
log.debug("Found TPM Model: " + model); log.debug("Found TPM Model: {}", model);
} else if (oid.equals(TPM_VERSION)) { } else if (oid.equals(TPM_VERSION)) {
version = value.toString(); version = value.toString();
log.debug("Found TPM Version: " + version); log.debug("Found TPM Version: {}", version);
} else if (oid.equals(TPM_MANUFACTURER)) { } else if (oid.equals(TPM_MANUFACTURER)) {
manufacturer = value.toString(); 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 * 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 * patterns that correspond to the TPM Security Assertions and TPM Specification and set
* those fields appropriately. * 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 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 * @throws IOException parsing individual subcomponents failed
*/ */
private void parseSequence(final ASN1Sequence seq, final boolean addToMapping, 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); ASN1Integer revision = (ASN1Integer) seq.getObjectAt(ASN1_REV_INDEX);
tpmSpecification = new TPMSpecification(family.getString(), level.getValue(), tpmSpecification = new TPMSpecification(family.getString(), level.getValue(),
revision.getValue()); revision.getValue());
log.debug("Found TPM Spec:" + tpmSpecification.toString()); log.debug("Found TPM Spec:{}", tpmSpecification);
} else if (addToMapping && key.equals(TPM_SECURITY_ASSERTIONS)) { } else if (addToMapping && key.equals(TPM_SECURITY_ASSERTIONS)) {
// Parse TPM Security Assertions // Parse TPM Security Assertions
int seqPosition = 0; int seqPosition = 0;
@ -341,7 +347,7 @@ public class EndorsementCredential extends DeviceAssociatedCertificate {
tpmSecurityAssertions = new TPMSecurityAssertions(ver.getValue(), tpmSecurityAssertions = new TPMSecurityAssertions(ver.getValue(),
fieldUpgradeable.isTrue()); fieldUpgradeable.isTrue());
log.debug("Found TPM Assertions: " + tpmSecurityAssertions.toString()); log.debug("Found TPM Assertions: {}", tpmSecurityAssertions);
// Iterate through remaining fields to set optional attributes // Iterate through remaining fields to set optional attributes
int tag; int tag;
ASN1TaggedObject obj; ASN1TaggedObject obj;
@ -392,13 +398,13 @@ public class EndorsementCredential extends DeviceAssociatedCertificate {
* Parses the many different types of ASN1Primitives and searches for specific OID * 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 * key/value pairs. Works by traversing the entire ASN1Primitive tree with a single
* pass and populates relevant fields in the EndorsementCredential object. * 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 * @param addToMapping whether or not the current component has been matched as the
* value in an expected TPM OID key/value pair * 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. * @throws IOException parsing of subcomponents in the tree failed.
*/ */
@SuppressWarnings("checkstyle:methodlength")
private void parseSingle(final ASN1Primitive component, final boolean addToMapping, private void parseSingle(final ASN1Primitive component, final boolean addToMapping,
final String key) throws IOException { final String key) throws IOException {
// null check the key if addToMapping is true // null check the key if addToMapping is true
@ -421,13 +427,11 @@ public class EndorsementCredential extends DeviceAssociatedCertificate {
parsedFields.put(key, ((ASN1ObjectIdentifier) component).getId()); parsedFields.put(key, ((ASN1ObjectIdentifier) component).getId());
} }
} else if (component instanceof ASN1TaggedObject) { } else if (component instanceof ASN1TaggedObject taggedObj) {
ASN1TaggedObject taggedObj = (ASN1TaggedObject) component;
parseSingle(taggedObj.getBaseObject().toASN1Primitive(), addToMapping, key); 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 // this may contain parseable data or may just be a OID key-pair value
ASN1OctetString octStr = (ASN1OctetString) component;
byte[] bytes = octStr.getOctets(); byte[] bytes = octStr.getOctets();
ByteArrayInputStream inStream = new ByteArrayInputStream(bytes); ByteArrayInputStream inStream = new ByteArrayInputStream(bytes);
ASN1InputStream octIn = new ASN1InputStream(inStream); 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 // 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 // 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 // ceases to be the case, we need to switch to this parsing to be more like
// parseSequences in the future // parseSequences in the future
ASN1Set set = (ASN1Set) component;
Enumeration setContents = set.getObjects(); Enumeration setContents = set.getObjects();
ASN1Encodable subComp; ASN1Encodable subComp;
while (setContents.hasMoreElements()) { while (setContents.hasMoreElements()) {
@ -563,7 +566,7 @@ public class EndorsementCredential extends DeviceAssociatedCertificate {
} else { } else {
// there are some deprecated types that we don't parse // there are some deprecated types that we don't parse
log.error("Unparsed type: " + component.getClass()); log.error("Unparsed type: {}", component.getClass());
} }
} }
} }

View File

@ -4,10 +4,15 @@ import hirs.attestationca.persist.entity.userdefined.Certificate;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.Transient; import jakarta.persistence.Transient;
import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.binary.Hex; import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.*; 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.CertificatePolicies;
import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.PolicyInformation; import org.bouncycastle.asn1.x509.PolicyInformation;
@ -15,23 +20,15 @@ import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; 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.nio.file.Path;
import java.time.Instant; import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Set;
@Entity @Entity
@Getter
@EqualsAndHashCode(callSuper = true)
@Log4j2 @Log4j2
public class IDevIDCertificate extends Certificate { 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_FIXED = "2.23.133.11.1.2";
private static final String POLICY_QUALIFIER_VERIFIED_TPM_RESTRICTED = "2.23.133.11.1.3"; private static final String POLICY_QUALIFIER_VERIFIED_TPM_RESTRICTED = "2.23.133.11.1.3";
@Getter
@Transient @Transient
private byte[] subjectAltName; private byte[] subjectAltName;
/** /**
* Corresponds to the hwType field found in a Hardware Module Name (if present). * Corresponds to the hwType field found in a Hardware Module Name (if present).
*/ */
@Getter
@Column @Column
private String hwType; private String hwType;
/** /**
* Corresponds to the serial number found in a Hardware Module Name (if present). * Corresponds to the serial number found in a Hardware Module Name (if present).
*/ */
@Getter
@Column @Column
private byte[] hwSerialNum; private byte[] hwSerialNum;
/** /**
* TPM policy qualifiers (TCG only). * TPM policy qualifiers (TCG only).
*/ */
@Getter
@Column @Column
private String tpmPolicies; 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 * Obtains TPM policy qualifiers from the Certificate Policies extension, if present. These policy
* specified in the TCG document "TPM 2.0 Keys for Device Identity and Attestation". * 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. * @return A {@link java.util.Map} containing the policy qualifiers obtained.
* @throws IOException if policy qualifiers cannot be parsed from extension value * @throws IOException if policy qualifiers cannot be parsed from extension value
*/ */
public Map<String, Boolean> getTPMPolicyQualifiers(byte[] policyBytes) throws IOException { public Map<String, Boolean> getTPMPolicyQualifiers(final byte[] policyBytes) throws IOException {
CertificatePolicies certPolicies = CertificatePolicies certPolicies =
CertificatePolicies.getInstance(JcaX509ExtensionUtils.parseExtensionValue(policyBytes)); CertificatePolicies.getInstance(JcaX509ExtensionUtils.parseExtensionValue(policyBytes));
Map<String, Boolean> policyQualifiers = new HashMap<>(); Map<String, Boolean> policyQualifiers = new HashMap<>();
@ -154,6 +148,7 @@ public class IDevIDCertificate extends Certificate {
/** /**
* Parses fields related to IDevID certificates. * Parses fields related to IDevID certificates.
*
* @throws IOException if a problem is encountered during parsing * @throws IOException if a problem is encountered during parsing
*/ */
private void parseIDevIDCertificate() throws IOException { private void parseIDevIDCertificate() throws IOException {
@ -170,13 +165,13 @@ public class IDevIDCertificate extends Certificate {
ASN1OctetString obj = (ASN1OctetString) input.readObject(); ASN1OctetString obj = (ASN1OctetString) input.readObject();
boolean tcgOid = false; boolean tcgOid = false;
// Parse the otherName structure. According to the specification "TPM 2.0 Keys for Device Identity and // Parse the otherName structure. According to the specification "TPM 2.0 Keys for Device Identity
// Attestation", otherName can contain up to two structures: HardwareModuleName and PermanentIdentifier. // and Attestation", otherName can contain up to two structures: HardwareModuleName and
// Currently, this parser only supports HardwareModuleName (if present). // PermanentIdentifier. Currently, this parser only supports HardwareModuleName (if present).
if (obj != null) { if (obj != null) {
// Parse Hardware Module Name structure, comprised of a hwType and hwSerialNum, and associated OID // Parse Hardware Module Name structure, comprised of a hwType and hwSerialNum,
// See also RFC 4108 // and associated OID. See also RFC 4108
ASN1Sequence seq1 = ASN1Sequence.getInstance(obj.getOctets()); ASN1Sequence seq1 = ASN1Sequence.getInstance(obj.getOctets());
// Iterate over GeneralNames sequence until HardwareModuleName is found // Iterate over GeneralNames sequence until HardwareModuleName is found
@ -207,23 +202,24 @@ public class IDevIDCertificate extends Certificate {
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
// Some certs have been found to contain tagged objects for hwSerialNum. // Some certs have been found to contain tagged objects for hwSerialNum.
// Handle this as a special case. // 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 { try {
tagObj1 = ASN1TaggedObject.getInstance(seq1.getObjectAt(1)); tagObj1 = ASN1TaggedObject.getInstance(seq1.getObjectAt(1));
obj2 = ASN1OctetString.getInstance(tagObj1, false); obj2 = ASN1OctetString.getInstance(tagObj1, false);
} } catch (Exception i) { // Invalid object found
catch (Exception i) { // Invalid object found
log.warn("Invalid object found for hwSerialNum."); log.warn("Invalid object found for hwSerialNum.");
break; break;
} }
} }
// If an OID corresponding to TPM 2.0 for hwType is supported, according to the // If an OID corresponding to TPM 2.0 for hwType is supported, according
// specification "TPM 2.0 Keys for Device Identity and Attestation", the contents of // to the specification "TPM 2.0 Keys for Device Identity and Attestation",
// the hwSerialNum field will be parsed accordingly. // the contents of the hwSerialNum field will be parsed accordingly.
hwType = obj1.toString(); hwType = obj1.toString();
if (hasTCGOIDs()) { if (hasTCGOIDs()) {
tcgOid = true; tcgOid = true;
} }
// Convert octet string to byte array // 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 // Check for certificate policy qualifiers, which should be present for IDevIDs if in compliance
// TCG specification. // with the TCG specification. For interoperability reasons, this will only log a warning
// For interoperability reasons, this will only log a warning if a TCG OID is specified above. // if a TCG OID is specified above.
byte[] policyBytes = getX509Certificate().getExtensionValue(Extension.certificatePolicies.getId()); byte[] policyBytes =
getX509Certificate().getExtensionValue(Extension.certificatePolicies.getId());
Map<String, Boolean> policyQualifiers = null; Map<String, Boolean> policyQualifiers = null;
if (policyBytes != null) { if (policyBytes != null) {
@ -257,22 +254,23 @@ public class IDevIDCertificate extends Certificate {
}); });
tpmPolicies = qualifierSB.toString(); tpmPolicies = qualifierSB.toString();
failCondition = !(policyQualifiers.get("verifiedTPMResidency") && failCondition = !(policyQualifiers.get("verifiedTPMResidency")
(policyQualifiers.get("verifiedTPMFixed") || && (policyQualifiers.get("verifiedTPMFixed")
policyQualifiers.get("verifiedTPMRestricted"))); || policyQualifiers.get("verifiedTPMRestricted")));
} else { } else {
failCondition = true; failCondition = true;
} }
if (failCondition) { if (failCondition) {
log.warn("TPM policy qualifiers not found, or do not meet logical criteria. Certificate may not " + log.warn(
"be in compliance with TCG specification."); "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 // Log a warning if notAfter field has an expiry date that is not indefinite
if (!this.getEndValidity().toInstant().equals(Instant.ofEpochSecond(UNDEFINED_EXPIRY_DATE))) { 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 " + log.warn("IDevID does not contain an indefinite expiry date. This may indicate an invalid "
"certificate."); + "certificate.");
} }
input.close(); 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 * Function to check whether a given IDevID certificate has TCG OIDs, in order to check compliance with
* fields. * various fields.
* *
* @return a boolean value * @return a boolean value
*/ */
public boolean hasTCGOIDs() { public boolean hasTCGOIDs() {
if (this.getHwType() != null) { if (this.getHwType() != null) {
return this.getHwType().equals(HWTYPE_TCG_TPM2_OID); return this.getHwType().equals(HWTYPE_TCG_TPM2_OID);
} } else {
else {
return false; 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;
}
}

View File

@ -18,8 +18,8 @@ import java.util.List;
/** /**
* Represents an issued attestation certificate to a HIRS Client. * Represents an issued attestation certificate to a HIRS Client.
*/ */
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter @Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity @Entity
public class IssuedAttestationCertificate extends DeviceAssociatedCertificate { 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"; public static final String AIC_TYPE_LABEL = "TCPA Trusted Platform Identity";
@Column
private boolean isLDevID;
@ManyToOne(fetch = FetchType.EAGER) @ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "ek_id") @JoinColumn(name = "ek_id")
private EndorsementCredential endorsementCredential; private EndorsementCredential endorsementCredential;
@ -36,19 +39,19 @@ public class IssuedAttestationCertificate extends DeviceAssociatedCertificate {
@JoinColumn(name = "pc_id") @JoinColumn(name = "pc_id")
private List<PlatformCredential> platformCredentials; private List<PlatformCredential> platformCredentials;
@Column
public boolean isLDevID;
/** /**
* Constructor. * Constructor.
* @param certificateBytes the issued certificate bytes *
* @param certificateBytes the issued certificate bytes
* @param endorsementCredential the endorsement credential * @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 * @throws IOException if there is a problem extracting information from the certificate
*/ */
public IssuedAttestationCertificate(final byte[] certificateBytes, public IssuedAttestationCertificate(final byte[] certificateBytes,
final EndorsementCredential endorsementCredential, final EndorsementCredential endorsementCredential,
final List<PlatformCredential> platformCredentials, boolean isLDevID) final List<PlatformCredential> platformCredentials,
final boolean isLDevID)
throws IOException { throws IOException {
super(certificateBytes); super(certificateBytes);
this.endorsementCredential = endorsementCredential; this.endorsementCredential = endorsementCredential;
@ -58,9 +61,11 @@ public class IssuedAttestationCertificate extends DeviceAssociatedCertificate {
/** /**
* Constructor. * Constructor.
* @param certificatePath path to certificate *
* @param certificatePath path to certificate
* @param endorsementCredential the endorsement credential * @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 * @throws IOException if there is a problem extracting information from the certificate
*/ */
public IssuedAttestationCertificate(final Path certificatePath, public IssuedAttestationCertificate(final Path certificatePath,
@ -70,8 +75,4 @@ public class IssuedAttestationCertificate extends DeviceAssociatedCertificate {
throws IOException { throws IOException {
this(readBytes(certificatePath), endorsementCredential, platformCredentials, isLDevID); this(readBytes(certificatePath), endorsementCredential, platformCredentials, isLDevID);
} }
public List<PlatformCredential> getPlatformCredentials() {
return new ArrayList<>(platformCredentials);
}
} }

View File

@ -46,7 +46,6 @@ import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID;
/** /**
* This class persists Platform credentials by extending the base Certificate * This class persists Platform credentials by extending the base Certificate
@ -61,24 +60,29 @@ import java.util.UUID;
@Entity @Entity
public class PlatformCredential extends DeviceAssociatedCertificate { 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; private static final int TCG_SPECIFICATION_LENGTH = 3;
// These are Object Identifiers (OIDs) for sections in the credentials // 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_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"; private static final String POLICY_QUALIFIER_USER_NOTICE = "1.3.6.1.5.5.7.2.2";
// OID for TCG Attributes // OID for TCG Attributes
private static final String PLATFORM_MANUFACTURER = "2.23.133.2.4"; 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_MODEL = "2.23.133.2.5";
private static final String PLATFORM_VERSION = "2.23.133.2.6"; 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_SERIAL = "2.23.133.2.23";
private static final String PLATFORM_BASEBOARD_CHASSIS_COMBINED = "2.23.133.5.1.6"; private static final String PLATFORM_BASEBOARD_CHASSIS_COMBINED = "2.23.133.5.1.6";
// OID for TCG Platform Class Common Attributes // 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_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_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_VERSION_2_0 = "2.23.133.5.1.5";
private static final String PLATFORM_SERIAL_2_0 = "2.23.133.5.1.6"; private static final String PLATFORM_SERIAL_2_0 = "2.23.133.5.1.6";
// OID for Certificate Attributes // OID for Certificate Attributes
private static final String TCG_PLATFORM_SPECIFICATION = "2.23.133.2.17"; private static final String TCG_PLATFORM_SPECIFICATION = "2.23.133.2.17";
private static final String TPM_SECURITY_ASSERTION = "2.23.133.2.18"; 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. // number of extra bytes potentially present in a cert header.
private static final int PC_CERT_HEADER_BYTE_COUNT = 8; private static final int PC_CERT_HEADER_BYTE_COUNT = 8;
private static final String MANUFACTURER_FIELD = "manufacturer";
/** private static final String MODEL_FIELD = "model";
* TCPA Trusted Platform Endorsement. private static final String VERSION_FIELD = "version";
*/ private static final String PLATFORM_SERIAL_FIELD = "platformSerial";
public static final String CERTIFICATE_TYPE_1_2 = "TCPA Trusted Platform Endorsement"; private static final String CHASSIS_SERIAL_NUMBER_FIELD = "chassisSerialNumber";
/**
* TCG Trusted Platform Endorsement.
*/
public static final String CERTIFICATE_TYPE_2_0 = "TCG Trusted Platform Endorsement";
@Column @Column
private String credentialType = null; private String credentialType = null;
@ -132,23 +131,18 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
@Column @Column
private boolean platformBase = false; private boolean platformBase = false;
private static final String MANUFACTURER_FIELD = "manufacturer";
@Column @Column
private String manufacturer = null; private String manufacturer = null;
private static final String MODEL_FIELD = "model";
@Column @Column
private String model = null; private String model = null;
private static final String VERSION_FIELD = "version";
@Column @Column
private String version = null; private String version = null;
private static final String PLATFORM_SERIAL_FIELD = "platformSerial";
@Column @Column
private String platformSerial = null; private String platformSerial = null;
private static final String CHASSIS_SERIAL_NUMBER_FIELD = "chassisSerialNumber";
@Column @Column
private String chassisSerialNumber; private String chassisSerialNumber;
@ -175,6 +169,7 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
@Column(length = MAX_MESSAGE_LENGTH) @Column(length = MAX_MESSAGE_LENGTH)
private String componentFailures = Strings.EMPTY; private String componentFailures = Strings.EMPTY;
@Column(length = MAX_MESSAGE_LENGTH) @Column(length = MAX_MESSAGE_LENGTH)
private String componentFailureMessage = Strings.EMPTY; private String componentFailureMessage = Strings.EMPTY;
@ -182,6 +177,7 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
private EndorsementCredential endorsementCredential = null; private EndorsementCredential endorsementCredential = null;
private String platformChainType = Strings.EMPTY; private String platformChainType = Strings.EMPTY;
private boolean isDeltaChain = false; private boolean isDeltaChain = false;
/** /**
@ -190,7 +186,7 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
* or X509 attribute certificate. * or X509 attribute certificate.
* *
* @param certificateBytes the contents of a certificate file * @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\ * @throws IOException if there is a problem extracting information from the certificate\
*/ */
public PlatformCredential(final byte[] certificateBytes, public PlatformCredential(final byte[] certificateBytes,
@ -223,40 +219,11 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
this(readBytes(certificatePath), true); 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 * 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 * is removed and tried again. The cert header, if present, contains some certificate length
* information which isn't needed for parsing. * information which isn't needed for parsing.
*
* @param certificateBytes the bytes of the PC * @param certificateBytes the bytes of the PC
* @return the PC if a valid credential, null otherwise * @return the PC if a valid credential, null otherwise
*/ */
@ -285,6 +252,103 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
return credential; 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<String, String> getPolicyQualifier(
final AttributeCertificateInfo certificate) {
Preconditions.checkArgument(certificate.getExtensions() != null,
"Platform certificate should have extensions.");
CertificatePolicies certPolicies
= CertificatePolicies.fromExtensions(certificate.getExtensions());
Map<String, String> 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 { private void parseFields() throws IOException {
AttributeCertificateInfo certificate = getAttributeCertificate().getAcinfo(); AttributeCertificateInfo certificate = getAttributeCertificate().getAcinfo();
Map<String, String> policyQualifier = getPolicyQualifier(certificate); Map<String, String> policyQualifier = getPolicyQualifier(certificate);
@ -340,6 +404,7 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
/** /**
* Parse a 1.2 Platform Certificate (Attribute Certificate). * Parse a 1.2 Platform Certificate (Attribute Certificate).
*
* @param certificate Attribute Certificate * @param certificate Attribute Certificate
*/ */
private void parseAttributeCert(final AttributeCertificateInfo certificate) { private void parseAttributeCert(final AttributeCertificateInfo certificate) {
@ -347,14 +412,14 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
= certificate.getExtensions().getExtension(Extension.subjectAlternativeName); = certificate.getExtensions().getExtension(Extension.subjectAlternativeName);
// It contains a Subject Alternative Name Extension // It contains a Subject Alternative Name Extension
if (subjectAlternativeNameExtension != null) { if (subjectAlternativeNameExtension != null) {
GeneralNames gnames = GeneralNames.getInstance( GeneralNames gnames = GeneralNames.getInstance(
subjectAlternativeNameExtension.getParsedValue()); subjectAlternativeNameExtension.getParsedValue());
for (GeneralName gname : gnames.getNames()) { for (GeneralName gname : gnames.getNames()) {
// Check if it's a directoryName [4] Name type // Check if it's a directoryName [4] Name type
if (gname.getTagNo() == GeneralName.directoryName) { if (gname.getTagNo() == GeneralName.directoryName) {
X500Name name = X500Name.getInstance(gname.getName()); X500Name name = X500Name.getInstance(gname.getName());
for (RDN rdn: name.getRDNs()) { for (RDN rdn : name.getRDNs()) {
for (AttributeTypeAndValue attTV: rdn.getTypesAndValues()) { for (AttributeTypeAndValue attTV : rdn.getTypesAndValues()) {
switch (attTV.getType().toString()) { switch (attTV.getType().toString()) {
case PLATFORM_MANUFACTURER: case PLATFORM_MANUFACTURER:
this.manufacturer = attTV.getValue().toString(); this.manufacturer = attTV.getValue().toString();
@ -392,6 +457,7 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
/** /**
* Parse a 2.0 Platform Certificate (Attribute Certificate). * Parse a 2.0 Platform Certificate (Attribute Certificate).
*
* @param certificate Attribute Certificate * @param certificate Attribute Certificate
*/ */
private void parseAttributeCert2(final AttributeCertificateInfo 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 // Check if it's a directoryName [4] Name type
if (gname.getTagNo() == GeneralName.directoryName) { if (gname.getTagNo() == GeneralName.directoryName) {
X500Name name = X500Name.getInstance(gname.getName()); X500Name name = X500Name.getInstance(gname.getName());
for (RDN rdn: name.getRDNs()) { for (RDN rdn : name.getRDNs()) {
for (AttributeTypeAndValue attTV: rdn.getTypesAndValues()) { for (AttributeTypeAndValue attTV : rdn.getTypesAndValues()) {
switch (attTV.getType().toString()) { switch (attTV.getType().toString()) {
case PLATFORM_MANUFACTURER_2_0: case PLATFORM_MANUFACTURER_2_0:
this.manufacturer = attTV.getValue().toString(); this.manufacturer = attTV.getValue().toString();
@ -440,6 +506,7 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
/** /**
* Get the x509 Platform Certificate version. * Get the x509 Platform Certificate version.
*
* @return a big integer representing the certificate version. * @return a big integer representing the certificate version.
*/ */
@Override @Override
@ -458,6 +525,7 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
/** /**
* Get the cPSuri from the Certificate Policies. * Get the cPSuri from the Certificate Policies.
*
* @return cPSuri from the CertificatePolicies. * @return cPSuri from the CertificatePolicies.
* @throws IOException when reading the certificate. * @throws IOException when reading the certificate.
*/ */
@ -473,9 +541,10 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
/** /**
* Get the Platform Configuration Attribute from the Platform Certificate. * Get the Platform Configuration Attribute from the Platform Certificate.
*
* @return a map with all the attributes * @return a map with all the attributes
* @throws IllegalArgumentException when there is a parsing error * @throws IllegalArgumentException when there is a parsing error
* @throws IOException when reading the certificate. * @throws IOException when reading the certificate.
*/ */
public Map<String, Object> getAllAttributes() public Map<String, Object> getAllAttributes()
throws IllegalArgumentException, IOException { throws IllegalArgumentException, IOException {
@ -523,10 +592,11 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
/** /**
* Get the specified attribute from the Platform Certificate. * Get the specified attribute from the Platform Certificate.
*
* @param attributeName to retrieve from the map. * @param attributeName to retrieve from the map.
* @return an Object with the attribute. * @return an Object with the attribute.
* @throws IllegalArgumentException when there is a parsing error * @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) public Object getAttribute(final String attributeName)
throws IllegalArgumentException, IOException { throws IllegalArgumentException, IOException {
@ -535,9 +605,10 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
/** /**
* Get the Platform Configuration Attribute from the Platform Certificate. * Get the Platform Configuration Attribute from the Platform Certificate.
*
* @return a map with the Platform Configuration information. * @return a map with the Platform Configuration information.
* @throws IllegalArgumentException when there is a parsing error * @throws IllegalArgumentException when there is a parsing error
* @throws IOException when reading the certificate. * @throws IOException when reading the certificate.
*/ */
public PlatformConfiguration getPlatformConfiguration() public PlatformConfiguration getPlatformConfiguration()
throws IllegalArgumentException, IOException { throws IllegalArgumentException, IOException {
@ -552,9 +623,10 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
/** /**
* Get the Platform Configuration URI Attribute from the Platform Certificate. * Get the Platform Configuration URI Attribute from the Platform Certificate.
*
* @return an URIReference object to the Platform Configuration URI. * @return an URIReference object to the Platform Configuration URI.
* @throws IllegalArgumentException when there is a parsing error * @throws IllegalArgumentException when there is a parsing error
* @throws IOException when reading the certificate. * @throws IOException when reading the certificate.
*/ */
public URIReference getPlatformConfigurationURI() public URIReference getPlatformConfigurationURI()
throws IllegalArgumentException, IOException { throws IllegalArgumentException, IOException {
@ -567,9 +639,10 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
/** /**
* Get the TBB Security Assertion from the Platform Certificate. * Get the TBB Security Assertion from the Platform Certificate.
*
* @return a TBBSecurityAssertion object. * @return a TBBSecurityAssertion object.
* @throws IllegalArgumentException when there is a parsing error * @throws IllegalArgumentException when there is a parsing error
* @throws IOException when reading the certificate. * @throws IOException when reading the certificate.
*/ */
public TBBSecurityAssertion getTBBSecurityAssertion() public TBBSecurityAssertion getTBBSecurityAssertion()
throws IllegalArgumentException, IOException { throws IllegalArgumentException, IOException {
@ -612,6 +685,7 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
/** /**
* Get the list of component identifiers if there are any. * Get the list of component identifiers if there are any.
*
* @return the list of component identifiers if there are any * @return the list of component identifiers if there are any
*/ */
public List<ComponentIdentifier> getComponentIdentifiers() { public List<ComponentIdentifier> getComponentIdentifiers() {
@ -626,76 +700,4 @@ public class PlatformCredential extends DeviceAssociatedCertificate {
} }
return Collections.emptyList(); 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<String, String> getPolicyQualifier(
final AttributeCertificateInfo certificate) {
Preconditions.checkArgument(certificate.getExtensions() != null,
"Platform certificate should have extensions.");
CertificatePolicies certPolicies
= CertificatePolicies.fromExtensions(certificate.getExtensions());
Map<String, String> 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;
}
} }

View File

@ -25,7 +25,8 @@ import org.bouncycastle.asn1.ASN1TaggedObject;
* targetUri [4] IMPLICIT URIReference OPTIONAL } * targetUri [4] IMPLICIT URIReference OPTIONAL }
* </pre> * </pre>
*/ */
@Getter @Setter @Getter
@Setter
public class CommonCriteriaMeasures { public class CommonCriteriaMeasures {
private static final int STRENGTH_OF_FUNCTION = 0; 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 PROFILE_URI = 2;
private static final int TARGET_OID = 3; private static final int TARGET_OID = 3;
private static final int TARGET_URI = 4; 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.
*
* <pre>
* EvaluationStatus ::= ENUMERATED {
* designedToMeet (0),
* evaluationInProgress (1),
* evaluationCompleted (2) }
* </pre>
*/
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.
*
* <pre>
* StrengthOfFunction ::= ENUMERATED {
* basic (0),
* medium (1),
* high (2) }
* </pre>
*/
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.
*
* <pre>
* EvaluationAssuranceLevel ::= ENUMERATED {
* levell (1),
* level2 (2),
* level3 (3),
* level4 (4),
* level5 (5),
* level6 (6),
* level7 (7) }
* </pre>
*/
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 ASN1IA5String version;
private EvaluationAssuranceLevel assuranceLevel; private EvaluationAssuranceLevel assuranceLevel;
private EvaluationStatus evaluationStatus; private EvaluationStatus evaluationStatus;
@ -194,6 +61,7 @@ public class CommonCriteriaMeasures {
/** /**
* Constructor given the SEQUENCE that contains Common Criteria Measures. * Constructor given the SEQUENCE that contains Common Criteria Measures.
*
* @param sequence containing the the common criteria measures * @param sequence containing the the common criteria measures
* @throws IllegalArgumentException if there was an error on the parsing * @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 @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -278,7 +150,7 @@ public class CommonCriteriaMeasures {
} }
sb.append(", profileUri="); sb.append(", profileUri=");
if (profileUri != null) { if (profileUri != null) {
sb.append(profileUri.toString()); sb.append(profileUri);
} }
sb.append(", targetOid="); sb.append(", targetOid=");
if (targetOid != null) { if (targetOid != null) {
@ -286,10 +158,148 @@ public class CommonCriteriaMeasures {
} }
sb.append(", targetUri="); sb.append(", targetUri=");
if (targetUri != null) { if (targetUri != null) {
sb.append(targetUri.toString()); sb.append(targetUri);
} }
sb.append("}"); sb.append("}");
return sb.toString(); 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.
*
* <pre>
* EvaluationStatus ::= ENUMERATED {
* designedToMeet (0),
* evaluationInProgress (1),
* evaluationCompleted (2) }
* </pre>
*/
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.
*
* <pre>
* StrengthOfFunction ::= ENUMERATED {
* basic (0),
* medium (1),
* high (2) }
* </pre>
*/
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.
*
* <pre>
* EvaluationAssuranceLevel ::= ENUMERATED {
* levell (1),
* level2 (2),
* level3 (3),
* level4 (4),
* level5 (5),
* level6 (6),
* level7 (7) }
* </pre>
*/
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;
}
}
} }

View File

@ -27,12 +27,17 @@ public class ComponentAddress {
public static final int IDENTIFIER_NUMBER = 2; public static final int IDENTIFIER_NUMBER = 2;
private static final String ETHERNET_MAC = "2.23.133.17.1"; 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 WLAN_MAC = "2.23.133.17.2";
private static final String BLUETOOTH_MAC = "2.23.133.17.3"; private static final String BLUETOOTH_MAC = "2.23.133.17.3";
private ASN1ObjectIdentifier addressType; private ASN1ObjectIdentifier addressType;
private ASN1UTF8String addressValue; private ASN1UTF8String addressValue;
private String addressTypeString; private String addressTypeString;
private String addressValueString; private String addressValueString;
/** /**
@ -62,27 +67,24 @@ public class ComponentAddress {
/** /**
* Get the string value for the address type. * Get the string value for the address type.
*
* @return the string value for the address type * @return the string value for the address type
*/ */
public String getAddressTypeValue() { public String getAddressTypeValue() {
String typeValue; return switch (this.addressType.getId()) {
switch (this.addressType.getId()) { case ETHERNET_MAC -> "ethernet mac";
case ETHERNET_MAC: case WLAN_MAC -> "wlan mac";
typeValue = "ethernet mac"; case BLUETOOTH_MAC -> "bluetooth mac";
break; default -> "unknown mac";
case WLAN_MAC: };
typeValue = "wlan mac";
break;
case BLUETOOTH_MAC:
typeValue = "bluetooth mac";
break;
default:
typeValue = "unknown mac";
break;
}
return typeValue;
} }
/**
* Creates a string representation of the Component Address object.
*
* @return a string representation of the Component Address object.
*/
@Override @Override
public String toString() { public String toString() {
return "ComponentAddress{" return "ComponentAddress{"

View File

@ -6,7 +6,6 @@ import lombok.AccessLevel;
import lombok.Getter; import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import java.util.UUID; 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 * 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 * value from what the device has listed, this class represents which attribute
* of that component mismatched. * of that component mismatched.
* * <p>
* If this is a delta issue, the component ID would be set to null if the * If this is a delta issue, the component ID would be set to null if the
* remove or modified don't exist. * remove or modified don't exist.
*/ */
@Entity @Entity
@Getter @Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED) @NoArgsConstructor(access = AccessLevel.PROTECTED)
public class ComponentAttributeResult extends ArchivableEntity { public class ComponentAttributeResult extends ArchivableEntity {
private UUID componentId; private UUID componentId;
@Setter @Setter
private UUID provisionSessionId; private UUID provisionSessionId;
// this is used to identify Revision for the ignore policy // this is used to identify Revision for the ignore policy
@Setter @Setter
private String attribute; private String attribute;
private String expectedValue; private String expectedValue;
private String actualValue; private String actualValue;
/** /**
* Default constructor that populates the expected and actual values. * 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 expectedValue platform certificate value
* @param actualValue paccor value from the device * @param actualValue paccor value from the device
*/ */
public ComponentAttributeResult(final UUID componentId, public ComponentAttributeResult(final UUID componentId,
final String expectedValue, final String expectedValue,
@ -48,10 +52,11 @@ public class ComponentAttributeResult extends ArchivableEntity {
/** /**
* Default constructor that populates the expected and actual values. * 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 provisionSessionId an id for the associated provision
* @param expectedValue platform certificate value * @param expectedValue platform certificate value
* @param actualValue paccor value from the device * @param actualValue paccor value from the device
*/ */
public ComponentAttributeResult(final UUID componentId, public ComponentAttributeResult(final UUID componentId,
final UUID provisionSessionId, final UUID provisionSessionId,
@ -65,6 +70,8 @@ public class ComponentAttributeResult extends ArchivableEntity {
/** /**
* This method is used to check the mismatched status flag for * This method is used to check the mismatched status flag for
* displaying red if there is a failure. * displaying red if there is a failure.
*
* @return true if there is status match, false otherwise
*/ */
public boolean checkMatchedStatus() { public boolean checkMatchedStatus() {
return this.actualValue.equals(this.expectedValue); 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. * For the state of the object, this shouldn't be negative.
*
* @return the string value of the attribute name * @return the string value of the attribute name
*/ */
public String getAttribute() { public String getAttribute() {

View File

@ -23,39 +23,52 @@ import java.nio.file.Path;
* componentClassRegistry ComponentClassRegistry, * componentClassRegistry ComponentClassRegistry,
* componentClassValue OCTET STRING SIZE(4) ) } * componentClassValue OCTET STRING SIZE(4) ) }
* </pre> * </pre>
* * <p>
* A note for the future. * 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 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 String SMBIOS_COMPONENT_REGISTRY = "2.23.133.18.3.3";
private static final Path WINDOWS_JSON_PATH = FileSystems.getDefault().getPath( private static final Path WINDOWS_JSON_PATH = FileSystems.getDefault().getPath(
"C:/", "ProgramData", "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( private static final Path JSON_PATH = WINDOWS_JSON_PATH.toFile().exists() ? WINDOWS_JSON_PATH
"/etc", "hirs", "aca", "default-properties", "component-class.json"); : FileSystems.getDefault().getPath(
"/etc", "hirs", "aca", "default-properties", "component-class.json");
private static final String OTHER_STRING = "Other"; private static final String OTHER_STRING = "Other";
private static final String UNKNOWN_STRING = "Unknown"; private static final String UNKNOWN_STRING = "Unknown";
private static final String NONE_STRING = "None"; private static final String NONE_STRING = "None";
// Used to indicate that the component string value provided is erroneous // Used to indicate that the component string value provided is erroneous
private static final String ERROR = "-1"; private static final String ERROR = "-1";
private static final int MID_INDEX = 4; private static final int MID_INDEX = 4;
/** /**
* All TCG categories have Other and Unknown as the first 2 values. * All TCG categories have Other and Unknown as the first 2 values.
*/ */
private static final String OTHER = "0000"; private static final String OTHER = "0000";
private static final String UNKNOWN = "0001"; private static final String UNKNOWN = "0001";
@Getter private final String registryType;
private String category, categoryStr;
@Getter private final String componentIdentifier;
private String component, componentStr;
@Getter private String category;
private String registryType;
@Getter private String categoryStr;
private String componentIdentifier;
private String component;
private String componentStr;
/** /**
* Default class constructor. * Default class constructor.
@ -68,7 +81,7 @@ public class ComponentClass {
* Class Constructor that takes a String representation of the component * Class Constructor that takes a String representation of the component
* value. * 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 * @param componentIdentifier component value
*/ */
public ComponentClass(final String registryOid, final String componentIdentifier) { 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 * Class Constructor that takes a String representation of the component
* value. * value.
* *
* @param componentClassPath file path for the json * @param componentClassPath file path for the json
* @param componentIdentifier component value * @param componentIdentifier component value
*/ */
public ComponentClass(final Path componentClassPath, final String componentIdentifier) { 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 * component value. Sets main class variables to default values and then
* matches the value against defined values in the associated JSON file. * matches the value against defined values in the associated JSON file.
* *
* @param registryOid the decimal notation for the type of registry * @param registryOid the decimal notation for the type of registry
* @param componentClassPath file path for the json * @param componentClassPath file path for the json
* @param componentIdentifier component value * @param componentIdentifier component value
*/ */
public ComponentClass(final String registryOid, public ComponentClass(final String registryOid,
@ -106,11 +119,11 @@ public class ComponentClass {
this.componentIdentifier = verifyComponentValue(componentIdentifier); this.componentIdentifier = verifyComponentValue(componentIdentifier);
} }
switch (registryOid) { this.registryType = switch (registryOid) {
case TCG_COMPONENT_REGISTRY -> registryType = "TCG"; case TCG_COMPONENT_REGISTRY -> "TCG";
case SMBIOS_COMPONENT_REGISTRY -> registryType = "SMBIOS"; case SMBIOS_COMPONENT_REGISTRY -> "SMBIOS";
default -> registryType = UNKNOWN_STRING; default -> UNKNOWN_STRING;
} };
switch (this.componentIdentifier) { switch (this.componentIdentifier) {
case OTHER: 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 * This method converts the string representation of the component ID into
* an integer. Or throws and error if the format is in error. * an integer. Or throws and error if the format is in error.
@ -248,4 +176,93 @@ public class ComponentClass {
return componentValue; 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();
}
}
}
}
} }

View File

@ -44,13 +44,11 @@ public class ComponentIdentifier {
* Maximum number of configurations. * Maximum number of configurations.
*/ */
public static final int CONFIGMAX = 32; 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. * Static variable indicated array position for the serial number.
*/ */
protected static final int COMPONENT_SERIAL = 0; protected static final int COMPONENT_SERIAL = 0;
// optional sequence objects
/** /**
* Static variable indicated array position for the revision info. * Static variable indicated array position for the revision info.
*/ */
@ -68,13 +66,22 @@ public class ComponentIdentifier {
*/ */
protected static final int COMPONENT_ADDRESS = 4; protected static final int COMPONENT_ADDRESS = 4;
private static final int MANDATORY_ELEMENTS = 2;
private DERUTF8String componentManufacturer; private DERUTF8String componentManufacturer;
private DERUTF8String componentModel; private DERUTF8String componentModel;
private DERUTF8String componentSerial; private DERUTF8String componentSerial;
private DERUTF8String componentRevision; private DERUTF8String componentRevision;
private ASN1ObjectIdentifier componentManufacturerId; private ASN1ObjectIdentifier componentManufacturerId;
private ASN1Boolean fieldReplaceable; private ASN1Boolean fieldReplaceable;
private List<ComponentAddress> componentAddress; private List<ComponentAddress> componentAddress;
private boolean validationResult = true; private boolean validationResult = true;
/** /**
@ -93,13 +100,13 @@ public class ComponentIdentifier {
/** /**
* Constructor given the components values. * Constructor given the components values.
* *
* @param componentManufacturer represents the component manufacturer * @param componentManufacturer represents the component manufacturer
* @param componentModel represents the component model * @param componentModel represents the component model
* @param componentSerial represents the component serial number * @param componentSerial represents the component serial number
* @param componentRevision represents the component revision * @param componentRevision represents the component revision
* @param componentManufacturerId represents the component manufacturer ID * @param componentManufacturerId represents the component manufacturer ID
* @param fieldReplaceable represents if the component is replaceable * @param fieldReplaceable represents if the component is replaceable
* @param componentAddress represents a list of addresses * @param componentAddress represents a list of addresses
*/ */
public ComponentIdentifier(final DERUTF8String componentManufacturer, public ComponentIdentifier(final DERUTF8String componentManufacturer,
final DERUTF8String componentModel, final DERUTF8String componentModel,
@ -119,6 +126,7 @@ public class ComponentIdentifier {
/** /**
* Constructor given the SEQUENCE that contains Component Identifier. * Constructor given the SEQUENCE that contains Component Identifier.
*
* @param sequence containing the component identifier * @param sequence containing the component identifier
* @throws IllegalArgumentException if there was an error on the parsing * @throws IllegalArgumentException if there was an error on the parsing
*/ */
@ -194,21 +202,10 @@ public class ComponentIdentifier {
} }
/** /**
* Getter for the component addresses. * Creates a string representation of the Component Identifier object.
* @return a collection of component addresses *
* @return a string representation of the Component Identifier object.
*/ */
public List<ComponentAddress> getComponentAddress() {
return componentAddress.stream().toList();
}
/**
* Setter for the list of component addresses.
* @param componentAddress collection of addresses
*/
public void setComponentAddress(List<ComponentAddress> componentAddress) {
this.componentAddress = componentAddress.stream().toList();
}
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -230,7 +227,7 @@ public class ComponentIdentifier {
} }
sb.append(", fieldReplaceable="); sb.append(", fieldReplaceable=");
if (fieldReplaceable != null) { if (fieldReplaceable != null) {
sb.append(fieldReplaceable.toString()); sb.append(fieldReplaceable);
} }
sb.append(", componentAddress="); sb.append(", componentAddress=");
if (!componentAddress.isEmpty()) { if (!componentAddress.isEmpty()) {

View File

@ -3,6 +3,7 @@ package hirs.attestationca.persist.entity.userdefined.certificate.attributes;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString;
import org.bouncycastle.asn1.ASN1Boolean; import org.bouncycastle.asn1.ASN1Boolean;
import org.bouncycastle.asn1.ASN1Enumerated; import org.bouncycastle.asn1.ASN1Enumerated;
import org.bouncycastle.asn1.ASN1IA5String; import org.bouncycastle.asn1.ASN1IA5String;
@ -17,64 +18,18 @@ import org.bouncycastle.asn1.ASN1Sequence;
* plus BOOLEAN DEFAULT FALSE } * plus BOOLEAN DEFAULT FALSE }
* </pre> * </pre>
*/ */
@Getter
@Setter
@AllArgsConstructor @AllArgsConstructor
@ToString
public class FIPSLevel { public class FIPSLevel {
private static final int MAX_SEQUENCE_SIZE = 3; 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.
*
* <pre>
* SecurityLevel ::= ENUMERATED {
* level1 (1),
* level2 (2),
* level3 (3),
* level4 (4) }
* </pre>
*/
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; private ASN1IA5String version;
@Getter @Setter
private SecurityLevel level; private SecurityLevel level;
@Getter @Setter
private ASN1Boolean plus; private ASN1Boolean plus;
/** /**
@ -111,12 +66,39 @@ public class FIPSLevel {
} }
} }
@Override /**
public String toString() { * A type to handle the security Level used in the FIPS Level.
return "FIPSLevel{" * Ordering of enum types is intentional and their ordinal values correspond to enum
+ "version=" + version.getString() * values in the TCG spec.
+ ", level=" + level.getValue() *
+ ", plus=" + plus.toString() * <pre>
+ '}'; * SecurityLevel ::= ENUMERATED {
* level1 (1),
* level2 (2),
* level3 (3),
* level4 (4) }
* </pre>
*/
@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;
} }
} }

View File

@ -15,10 +15,12 @@ import java.util.List;
@AllArgsConstructor @AllArgsConstructor
public abstract class PlatformConfiguration { public abstract class PlatformConfiguration {
private ArrayList<ComponentIdentifier> componentIdentifier = new ArrayList<>(); private ArrayList<ComponentIdentifier> componentIdentifier = new ArrayList<>();
@Getter @Setter @Getter
@Setter
private URIReference componentIdentifierUri; private URIReference componentIdentifierUri;
private ArrayList<PlatformProperty> platformProperties = new ArrayList<>(); private ArrayList<PlatformProperty> platformProperties = new ArrayList<>();
@Getter @Setter @Getter
@Setter
private URIReference platformPropertiesUri; private URIReference platformPropertiesUri;
/** /**
@ -34,10 +36,10 @@ public abstract class PlatformConfiguration {
/** /**
* Constructor given the Platform Configuration values. * Constructor given the Platform Configuration values.
* *
* @param componentIdentifier list containing all the components inside the * @param componentIdentifier list containing all the components inside the
* Platform Configuration. * Platform Configuration.
* @param platformProperties list containing all the properties inside the * @param platformProperties list containing all the properties inside the
* Platform Configuration. * Platform Configuration.
* @param platformPropertiesUri object containing the URI Reference * @param platformPropertiesUri object containing the URI Reference
*/ */
public PlatformConfiguration(final List<ComponentIdentifier> componentIdentifier, public PlatformConfiguration(final List<ComponentIdentifier> componentIdentifier,
@ -55,8 +57,16 @@ public abstract class PlatformConfiguration {
return Collections.unmodifiableList(componentIdentifier); return Collections.unmodifiableList(componentIdentifier);
} }
/**
* @param componentIdentifier the componentIdentifier to set
*/
public void setComponentIdentifier(final List<ComponentIdentifier> componentIdentifier) {
this.componentIdentifier = new ArrayList<>(componentIdentifier);
}
/** /**
* Add function for the component identifier array. * Add function for the component identifier array.
*
* @param componentIdentifier object to add * @param componentIdentifier object to add
* @return status of the add, if successful or not * @return status of the add, if successful or not
*/ */
@ -68,13 +78,6 @@ public abstract class PlatformConfiguration {
return false; return false;
} }
/**
* @param componentIdentifier the componentIdentifier to set
*/
public void setComponentIdentifier(final List<ComponentIdentifier> componentIdentifier) {
this.componentIdentifier = new ArrayList<>(componentIdentifier);
}
/** /**
* @return the platformProperties * @return the platformProperties
*/ */
@ -82,8 +85,16 @@ public abstract class PlatformConfiguration {
return Collections.unmodifiableList(platformProperties); return Collections.unmodifiableList(platformProperties);
} }
/**
* @param platformProperties the platformProperties to set
*/
public void setPlatformProperties(final List<PlatformProperty> platformProperties) {
this.platformProperties = new ArrayList<>(platformProperties);
}
/** /**
* Add function for the platform property array. * Add function for the platform property array.
*
* @param platformProperty property object to add * @param platformProperty property object to add
* @return status of the add, if successful or not * @return status of the add, if successful or not
*/ */
@ -94,11 +105,4 @@ public abstract class PlatformConfiguration {
return false; return false;
} }
/**
* @param platformProperties the platformProperties to set
*/
public void setPlatformProperties(final List<PlatformProperty> platformProperties) {
this.platformProperties = new ArrayList<>(platformProperties);
}
} }

View File

@ -25,6 +25,7 @@ public class PlatformConfigurationV1 extends PlatformConfiguration {
/** /**
* Constructor given the SEQUENCE that contains Platform Configuration. * Constructor given the SEQUENCE that contains Platform Configuration.
*
* @param sequence containing the Platform Configuration. * @param sequence containing the Platform Configuration.
* @throws IllegalArgumentException if there was an error on the parsing * @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 @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -96,7 +102,7 @@ public class PlatformConfigurationV1 extends PlatformConfiguration {
} }
sb.append(", platformPropertiesUri="); sb.append(", platformPropertiesUri=");
if (getPlatformPropertiesUri() != null) { if (getPlatformPropertiesUri() != null) {
sb.append(getPlatformPropertiesUri().toString()); sb.append(getPlatformPropertiesUri());
} }
sb.append("}"); sb.append("}");

View File

@ -3,12 +3,12 @@ package hirs.attestationca.persist.entity.userdefined.certificate.attributes;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString;
import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1UTF8String; import org.bouncycastle.asn1.ASN1UTF8String;
import org.bouncycastle.asn1.DERUTF8String; import org.bouncycastle.asn1.DERUTF8String;
/** /**
*
* Basic class that handles a single property for the platform configuration. * Basic class that handles a single property for the platform configuration.
* <pre> * <pre>
* Properties ::= SEQUENCE { * Properties ::= SEQUENCE {
@ -20,16 +20,17 @@ import org.bouncycastle.asn1.DERUTF8String;
@Getter @Getter
@Setter @Setter
@AllArgsConstructor @AllArgsConstructor
@ToString
public class PlatformProperty { public class PlatformProperty {
private static final String NOT_SPECIFIED = "Not Specified";
/** /**
* Number of identifiers for version 1. * Number of identifiers for version 1.
*/ */
protected static final int IDENTIFIER_NUMBER = 2; protected static final int IDENTIFIER_NUMBER = 2;
private static final String NOT_SPECIFIED = "Not Specified";
private ASN1UTF8String propertyName; private ASN1UTF8String propertyName;
private ASN1UTF8String propertyValue; private ASN1UTF8String propertyValue;
/** /**
@ -57,12 +58,4 @@ public class PlatformProperty {
this.propertyName = ASN1UTF8String.getInstance(sequence.getObjectAt(0)); this.propertyName = ASN1UTF8String.getInstance(sequence.getObjectAt(0));
this.propertyValue = ASN1UTF8String.getInstance(sequence.getObjectAt(1)); this.propertyValue = ASN1UTF8String.getInstance(sequence.getObjectAt(1));
} }
@Override
public String toString() {
return "PlatformProperty{"
+ "propertyName=" + propertyName.getString()
+ ", propertyValue=" + propertyValue.getString()
+ "}";
}
} }

View File

@ -2,6 +2,8 @@ package hirs.attestationca.persist.entity.userdefined.certificate.attributes;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.bouncycastle.asn1.ASN1Boolean; import org.bouncycastle.asn1.ASN1Boolean;
import org.bouncycastle.asn1.ASN1Enumerated; import org.bouncycastle.asn1.ASN1Enumerated;
import org.bouncycastle.asn1.ASN1IA5String; import org.bouncycastle.asn1.ASN1IA5String;
@ -24,71 +26,26 @@ import java.math.BigInteger;
* iso9000Uri IA5STRING (SIZE (1..URIMAX)) OPTIONAL } * iso9000Uri IA5STRING (SIZE (1..URIMAX)) OPTIONAL }
* </pre> * </pre>
*/ */
@Setter
@Getter
@AllArgsConstructor @AllArgsConstructor
@ToString
public class TBBSecurityAssertion { public class TBBSecurityAssertion {
private static final int CCINFO = 0; private static final int CCINFO = 0;
private static final int FIPSLEVEL = 1; private static final int FIPSLEVEL = 1;
private static final int RTMTYPE = 2; 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.
*
* <pre>
* MeasurementRootType ::= ENUMERATED {
* static (0),
* dynamic (1),
* nonHost (2),
* hybrid (3),
* physical (4),
* virtual (5) }
* </pre>
*/
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 ASN1Integer version;
private CommonCriteriaMeasures ccInfo; private CommonCriteriaMeasures ccInfo;
private FIPSLevel fipsLevel; private FIPSLevel fipsLevel;
private MeasurementRootType rtmType; private MeasurementRootType rtmType;
private ASN1Boolean iso9000Certified; private ASN1Boolean iso9000Certified;
private ASN1IA5String iso9000Uri; private ASN1IA5String iso9000Uri;
/** /**
@ -105,6 +62,7 @@ public class TBBSecurityAssertion {
/** /**
* Constructor given the SEQUENCE that contains a TBBSecurityAssertion Object. * Constructor given the SEQUENCE that contains a TBBSecurityAssertion Object.
*
* @param sequence containing the the TBB Security Assertion * @param sequence containing the the TBB Security Assertion
* @throws IllegalArgumentException if there was an error on the parsing * @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.
*
* <pre>
* MeasurementRootType ::= ENUMERATED {
* static (0),
* dynamic (1),
* nonHost (2),
* hybrid (3),
* physical (4),
* virtual (5) }
* </pre>
*/ */
public ASN1Integer getVersion() { public enum MeasurementRootType {
return version; /**
} * 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
* @param version the version to set private final String value;
*/
public void setVersion(final ASN1Integer version) {
this.version = version;
}
/** /**
* @return the ccInfo * Basic constructor.
*/ *
public CommonCriteriaMeasures getCcInfo() { * @param value string containing the value.
return ccInfo; */
} MeasurementRootType(final String value) {
this.value = value;
/**
* @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());
} }
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();
} }
} }

View File

@ -7,6 +7,7 @@ import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
import lombok.ToString;
import java.io.Serializable; import java.io.Serializable;
import java.math.BigInteger; 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 * A class to represent the TPM Security Assertions in an Endorsement Credential as
* defined by the TCG spec for TPM 1.2. * defined by the TCG spec for TPM 1.2.
* * <p>
* https://www.trustedcomputinggroup.org/wp-content/uploads/IWG-Credential_Profiles_V1_R0.pdf * https://www.trustedcomputinggroup.org/wp-content/uploads/IWG-Credential_Profiles_V1_R0.pdf
* * <p>
* Future iterations of this code may want to reference * Future iterations of this code may want to reference
* www.trustedcomputinggroup.org/wp-content/uploads/Credential_Profile_EK_V2.0_R14_published.pdf * www.trustedcomputinggroup.org/wp-content/uploads/Credential_Profile_EK_V2.0_R14_published.pdf
* for specifications for TPM 2.0 (pg. 19). * for specifications for TPM 2.0 (pg. 19).
*/ */
@Getter
@Setter
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED) @NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter @Setter @ToString
@Embeddable @Embeddable
public class TPMSecurityAssertions implements Serializable { 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 * 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 * 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 * Generated externally and then inserted under a controlled environment during
* manufacturing. Can be revoked. Enum value of 3. * 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. * Generated by the endorsement key certificate signer. Enum value of 2.
*/ */
EK_CERT_SIGNER; 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
+ '}';
} }
} }

View File

@ -6,6 +6,7 @@ import lombok.AccessLevel;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable; import java.io.Serializable;
import java.math.BigInteger; import java.math.BigInteger;
@ -13,16 +14,17 @@ import java.math.BigInteger;
/** /**
* A class to represent the TPM Specification in an Endorsement Credential as * A class to represent the TPM Specification in an Endorsement Credential as
* defined by the TCG spec for TPM 1.2. * defined by the TCG spec for TPM 1.2.
* * <p>
* https://www.trustedcomputinggroup.org/wp-content/uploads/IWG-Credential_Profiles_V1_R0.pdf * https://www.trustedcomputinggroup.org/wp-content/uploads/IWG-Credential_Profiles_V1_R0.pdf
* * <p>
* Future iterations of this code may want to reference * Future iterations of this code may want to reference
* www.trustedcomputinggroup.org/wp-content/uploads/Credential_Profile_EK_V2.0_R14_published.pdf * www.trustedcomputinggroup.org/wp-content/uploads/Credential_Profile_EK_V2.0_R14_published.pdf
* for specifications for TPM 2.0. * for specifications for TPM 2.0.
*/ */
@EqualsAndHashCode
@NoArgsConstructor(access= AccessLevel.PROTECTED)
@Getter @Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@ToString
@EqualsAndHashCode
@Embeddable @Embeddable
public class TPMSpecification implements Serializable { public class TPMSpecification implements Serializable {
@ -37,8 +39,9 @@ public class TPMSpecification implements Serializable {
/** /**
* Standard constructor. * 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. * @param revision the specification revision.
*/ */
public TPMSpecification(final String family, final BigInteger level, public TPMSpecification(final String family, final BigInteger level,
@ -47,13 +50,4 @@ public class TPMSpecification implements Serializable {
this.level = level; this.level = level;
this.revision = revision; this.revision = revision;
} }
@Override
public String toString() {
return "TPMSpecification{"
+ "family='" + family + '\''
+ ", level=" + level
+ ", revision=" + revision
+ '}';
}
} }

View File

@ -10,27 +10,30 @@ import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
/** /**
*
* Basic class that handle a URIReference object. * Basic class that handle a URIReference object.
* <pre> * <pre>
* URIReference ::= SEQUENCE { * URIReference ::= SEQUENCE {
* uniformResourceIdentifier IA5String (SIZE (1..URIMAX)), * uniformResourceIdentifier IA5String (SIZE (1..URIMAX)),
* hashAlgorithm AlgorithmIdentifier OPTIONAL, * hashAlgorithm AlgorithmIdentifier OPTIONAL,
* hashValue BIT STRING OPTIONAL * hashValue BIT STRING OPTIONAL
} * }
* </pre> * </pre>
*/ */
@Getter @Setter @Getter
@Setter
@AllArgsConstructor @AllArgsConstructor
public class URIReference { 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 ASN1IA5String uniformResourceIdentifier;
private AlgorithmIdentifier hashAlgorithm; private AlgorithmIdentifier hashAlgorithm;
@JsonIgnore @JsonIgnore
private ASN1BitString hashValue; private ASN1BitString hashValue;
private static final int PLATFORM_PROPERTIES_URI_MAX = 3;
private static final int PLATFORM_PROPERTIES_URI_MIN = 1;
/** /**
* Default constructor. * 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 @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();

View File

@ -51,6 +51,7 @@ public class CertificateIdentifier {
/** /**
* Primary constructor for the parsing of the sequence. * Primary constructor for the parsing of the sequence.
*
* @param sequence containing the name and value of the Certificate Identifier * @param sequence containing the name and value of the Certificate Identifier
*/ */
public CertificateIdentifier(final ASN1Sequence sequence) { public CertificateIdentifier(final ASN1Sequence sequence) {
@ -103,6 +104,7 @@ public class CertificateIdentifier {
/** /**
* String for the internal data stored. * String for the internal data stored.
*
* @return String representation of the data. * @return String representation of the data.
*/ */
@Override @Override
@ -114,11 +116,11 @@ public class CertificateIdentifier {
sb.append(", hashSigValue").append(hashSigValue); sb.append(", hashSigValue").append(hashSigValue);
sb.append(", issuerDN="); sb.append(", issuerDN=");
if (issuerDN != null) { if (issuerDN != null) {
sb.append(issuerDN.toString()); sb.append(issuerDN);
} }
sb.append(", certificateSerialNumber="); sb.append(", certificateSerialNumber=");
if (certificateSerialNumber != null) { if (certificateSerialNumber != null) {
sb.append(certificateSerialNumber.toString()); sb.append(certificateSerialNumber);
} }
sb.append("}"); sb.append("}");

View File

@ -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.ComponentClass;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentIdentifier; import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentIdentifier;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.URIReference; import hirs.attestationca.persist.entity.userdefined.certificate.attributes.URIReference;
import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.bouncycastle.asn1.ASN1Boolean; import org.bouncycastle.asn1.ASN1Boolean;
@ -16,7 +17,6 @@ import org.bouncycastle.asn1.ASN1UTF8String;
import org.bouncycastle.asn1.DERUTF8String; import org.bouncycastle.asn1.DERUTF8String;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@ -40,17 +40,24 @@ import java.util.stream.Collectors;
*/ */
@Getter @Getter
@Setter @Setter
@EqualsAndHashCode(callSuper = true)
public class ComponentIdentifierV2 extends ComponentIdentifier { public class ComponentIdentifierV2 extends ComponentIdentifier {
private static final int MANDATORY_ELEMENTS = 3; private static final int MANDATORY_ELEMENTS = 3;
// Additional optional identifiers for version 2 // Additional optional identifiers for version 2
private static final int COMPONENT_PLATFORM_CERT = 5; private static final int COMPONENT_PLATFORM_CERT = 5;
private static final int COMPONENT_PLATFORM_URI = 6; private static final int COMPONENT_PLATFORM_URI = 6;
private static final int ATTRIBUTE_STATUS = 7; private static final int ATTRIBUTE_STATUS = 7;
private ComponentClass componentClass; private ComponentClass componentClass;
private CertificateIdentifier certificateIdentifier; private CertificateIdentifier certificateIdentifier;
private URIReference componentPlatformUri; private URIReference componentPlatformUri;
private AttributeStatus attributeStatus; private AttributeStatus attributeStatus;
/** /**
@ -67,19 +74,18 @@ public class ComponentIdentifierV2 extends ComponentIdentifier {
/** /**
* Constructor given the components values. * Constructor given the components values.
* *
* @param componentClass represent the component type * @param componentClass represent the component type
* @param componentManufacturer represents the component manufacturer * @param componentManufacturer represents the component manufacturer
* @param componentModel represents the component model * @param componentModel represents the component model
* @param componentSerial represents the component serial number * @param componentSerial represents the component serial number
* @param componentRevision represents the component revision * @param componentRevision represents the component revision
* @param componentManufacturerId represents the component manufacturer ID * @param componentManufacturerId represents the component manufacturer ID
* @param fieldReplaceable represents if the component is replaceable * @param fieldReplaceable represents if the component is replaceable
* @param componentAddress represents a list of addresses * @param componentAddress represents a list of addresses
* @param certificateIdentifier object representing certificate Id * @param certificateIdentifier object representing certificate Id
* @param componentPlatformUri object containing the URI Reference * @param componentPlatformUri object containing the URI Reference
* @param attributeStatus object containing enumerated status * @param attributeStatus object containing enumerated status
*/ */
@SuppressWarnings("checkstyle:parameternumber")
public ComponentIdentifierV2(final ComponentClass componentClass, public ComponentIdentifierV2(final ComponentClass componentClass,
final DERUTF8String componentManufacturer, final DERUTF8String componentManufacturer,
final DERUTF8String componentModel, final DERUTF8String componentModel,
@ -103,6 +109,7 @@ public class ComponentIdentifierV2 extends ComponentIdentifier {
/** /**
* Constructor given the SEQUENCE that contains Component Identifier. * Constructor given the SEQUENCE that contains Component Identifier.
*
* @param sequence containing the component identifier * @param sequence containing the component identifier
* @throws IllegalArgumentException if there was an error on the parsing * @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()); ASN1OctetString.getInstance(componentIdSeq.getObjectAt(tag)).toString());
// Mandatory values // 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++))); this.setComponentModel((DERUTF8String) ASN1UTF8String.getInstance(sequence.getObjectAt(tag++)));
// Continue reading the sequence if it does contain more than 2 values // Continue reading the sequence if it does contain more than 2 values
@ -200,24 +208,11 @@ public class ComponentIdentifierV2 extends ComponentIdentifier {
return true; return true;
} }
@Override /**
public boolean equals(Object o) { * Creates a string representation of the Component Identifier V2 object.
if (this == o) return true; *
if (o == null || getClass() != o.getClass()) return false; * @return a string representation of the Component Identifier V2 object.
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);
}
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -241,7 +236,7 @@ public class ComponentIdentifierV2 extends ComponentIdentifier {
} }
sb.append(", fieldReplaceable="); sb.append(", fieldReplaceable=");
if (getFieldReplaceable() != null) { if (getFieldReplaceable() != null) {
sb.append(getFieldReplaceable().toString()); sb.append(getFieldReplaceable());
} }
sb.append(", componentAddress="); sb.append(", componentAddress=");
if (getComponentAddress().size() > 0) { if (getComponentAddress().size() > 0) {
@ -252,11 +247,11 @@ public class ComponentIdentifierV2 extends ComponentIdentifier {
} }
sb.append(", certificateIdentifier="); sb.append(", certificateIdentifier=");
if (certificateIdentifier != null) { if (certificateIdentifier != null) {
sb.append(certificateIdentifier.toString()); sb.append(certificateIdentifier);
} }
sb.append(", componentPlatformUri="); sb.append(", componentPlatformUri=");
if (componentPlatformUri != null) { if (componentPlatformUri != null) {
sb.append(componentPlatformUri.toString()); sb.append(componentPlatformUri);
} }
sb.append(", status="); sb.append(", status=");
if (attributeStatus != null) { if (attributeStatus != null) {

View File

@ -29,6 +29,7 @@ public class PlatformConfigurationV2 extends PlatformConfiguration {
/** /**
* Constructor given the SEQUENCE that contains Platform Configuration. * Constructor given the SEQUENCE that contains Platform Configuration.
*
* @param sequence containing the the Platform Configuration. * @param sequence containing the the Platform Configuration.
* @throws IllegalArgumentException if there was an error on the parsing * @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 @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -99,7 +105,7 @@ public class PlatformConfigurationV2 extends PlatformConfiguration {
} }
sb.append(", componentIdentifierUri="); sb.append(", componentIdentifierUri=");
if (getComponentIdentifierUri() != null) { if (getComponentIdentifierUri() != null) {
sb.append(getComponentIdentifierUri().toString()); sb.append(getComponentIdentifierUri());
} }
sb.append(", platformProperties="); sb.append(", platformProperties=");
if (getPlatformProperties().size() > 0) { if (getPlatformProperties().size() > 0) {
@ -110,7 +116,7 @@ public class PlatformConfigurationV2 extends PlatformConfiguration {
} }
sb.append(", platformPropertiesUri="); sb.append(", platformPropertiesUri=");
if (getPlatformPropertiesUri() != null) { if (getPlatformPropertiesUri() != null) {
sb.append(getPlatformPropertiesUri().toString()); sb.append(getPlatformPropertiesUri());
} }
sb.append("}"); sb.append("}");

View File

@ -8,7 +8,6 @@ import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1UTF8String; import org.bouncycastle.asn1.ASN1UTF8String;
/** /**
*
* Basic class that handles a single property for the platform configuration. * Basic class that handles a single property for the platform configuration.
* <pre> * <pre>
* Properties ::= SEQUENCE { * Properties ::= SEQUENCE {
@ -18,10 +17,10 @@ import org.bouncycastle.asn1.ASN1UTF8String;
* *
* </pre> * </pre>
*/ */
@Setter
@Getter
public class PlatformPropertyV2 extends PlatformProperty { public class PlatformPropertyV2 extends PlatformProperty {
@Getter
@Setter
private AttributeStatus attributeStatus; private AttributeStatus attributeStatus;
/** /**
@ -35,8 +34,8 @@ public class PlatformPropertyV2 extends PlatformProperty {
/** /**
* Constructor given the name and value for the platform property. * Constructor given the name and value for the platform property.
* *
* @param propertyName string containing the property name * @param propertyName string containing the property name
* @param propertyValue string containing the property value * @param propertyValue string containing the property value
* @param attributeStatus enumerated object with the status of the property * @param attributeStatus enumerated object with the status of the property
*/ */
public PlatformPropertyV2(final ASN1UTF8String propertyName, final ASN1UTF8String propertyValue, public PlatformPropertyV2(final ASN1UTF8String propertyName, final ASN1UTF8String propertyValue,
@ -84,6 +83,12 @@ public class PlatformPropertyV2 extends PlatformProperty {
return getAttributeStatus() != AttributeStatus.REMOVED; return getAttributeStatus() != AttributeStatus.REMOVED;
} }
/**
* Creates a string representation of the PlatformPropertyV2 object.
*
* @return a string representation of the PlatformPropertyV2 object
*/
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -91,7 +96,7 @@ public class PlatformPropertyV2 extends PlatformProperty {
sb.append("PropertyName=").append(getPropertyName().getString()); sb.append("PropertyName=").append(getPropertyName().getString());
sb.append(", propertyValue=").append(getPropertyValue().getString()); sb.append(", propertyValue=").append(getPropertyValue().getString());
if (attributeStatus != null) { if (attributeStatus != null) {
sb.append(", attributeStatus=").append(attributeStatus.toString()); sb.append(", attributeStatus=").append(attributeStatus);
} }
sb.append("}"); sb.append("}");

View File

@ -1 +1 @@
package hirs.attestationca.persist.entity.userdefined.certificate.attributes.V2; package hirs.attestationca.persist.entity.userdefined.certificate.attributes.V2;

View File

@ -1 +1 @@
package hirs.attestationca.persist.entity.userdefined.certificate.attributes; package hirs.attestationca.persist.entity.userdefined.certificate.attributes;

View File

@ -1 +1 @@
package hirs.attestationca.persist.entity.userdefined.certificate; package hirs.attestationca.persist.entity.userdefined.certificate;

View File

@ -9,6 +9,7 @@ import jakarta.persistence.DiscriminatorType;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlElement;
import lombok.AccessLevel; import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
@ -24,6 +25,7 @@ import java.util.Objects;
@Entity @Entity
@Getter @Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED) @NoArgsConstructor(access = AccessLevel.PROTECTED)
@EqualsAndHashCode(callSuper = false)
@DiscriminatorColumn(name = "componentTypeEnum", discriminatorType = DiscriminatorType.STRING) @DiscriminatorColumn(name = "componentTypeEnum", discriminatorType = DiscriminatorType.STRING)
public class ComponentInfo extends ArchivableEntity { public class ComponentInfo extends ArchivableEntity {
@ -34,6 +36,7 @@ public class ComponentInfo extends ArchivableEntity {
@Column(nullable = false) @Column(nullable = false)
private String deviceName; private String deviceName;
@XmlElement @XmlElement
@Column(nullable = false) @Column(nullable = false)
private String componentManufacturer; private String componentManufacturer;
@ -56,10 +59,11 @@ public class ComponentInfo extends ArchivableEntity {
/** /**
* Base constructor for children. * Base constructor for children.
*
* @param componentManufacturer Component Manufacturer (must not be null) * @param componentManufacturer Component Manufacturer (must not be null)
* @param componentModel Component Model (must not be null) * @param componentModel Component Model (must not be null)
* @param componentSerial Component Serial Number (can be null) * @param componentSerial Component Serial Number (can be null)
* @param componentRevision Component Revision or Version (can be null) * @param componentRevision Component Revision or Version (can be null)
*/ */
public ComponentInfo(final String componentManufacturer, public ComponentInfo(final String componentManufacturer,
final String componentModel, final String componentModel,
@ -68,13 +72,15 @@ public class ComponentInfo extends ArchivableEntity {
this(DeviceInfoEnums.NOT_SPECIFIED, componentManufacturer, componentModel, this(DeviceInfoEnums.NOT_SPECIFIED, componentManufacturer, componentModel,
componentSerial, componentRevision); componentSerial, componentRevision);
} }
/** /**
* Constructor. * 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 componentManufacturer Component Manufacturer (must not be null)
* @param componentModel Component Model (must not be null) * @param componentModel Component Model (must not be null)
* @param componentSerial Component Serial Number (can be null) * @param componentSerial Component Serial Number (can be null)
* @param componentRevision Component Revision or Version (can be null) * @param componentRevision Component Revision or Version (can be null)
*/ */
public ComponentInfo(final String deviceName, public ComponentInfo(final String deviceName,
final String componentManufacturer, final String componentManufacturer,
@ -108,12 +114,13 @@ public class ComponentInfo extends ArchivableEntity {
/** /**
* Constructor. * 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 componentManufacturer Component Manufacturer (must not be null)
* @param componentModel Component Model (must not be null) * @param componentModel Component Model (must not be null)
* @param componentSerial Component Serial Number (can be null) * @param componentSerial Component Serial Number (can be null)
* @param componentRevision Component Revision or Version (can be null) * @param componentRevision Component Revision or Version (can be null)
* @param componentClass Component Class (can be null) * @param componentClass Component Class (can be null)
*/ */
public ComponentInfo(final String deviceName, public ComponentInfo(final String deviceName,
final String componentManufacturer, final String componentManufacturer,
@ -134,9 +141,9 @@ public class ComponentInfo extends ArchivableEntity {
* manufacturer and model are considered valid. * manufacturer and model are considered valid.
* *
* @param componentManufacturer a String containing a component's manufacturer * @param componentManufacturer a String containing a component's manufacturer
* @param componentModel a String representing a component's model * @param componentModel a String representing a component's model
* @param componentSerial a String representing a component's serial number * @param componentSerial a String representing a component's serial number
* @param componentRevision a String representing a component's revision * @param componentRevision a String representing a component's revision
* @return true if the component is valid, false if not * @return true if the component is valid, false if not
*/ */
public static boolean isComplete(final String componentManufacturer, public static boolean isComplete(final String componentManufacturer,
@ -147,43 +154,13 @@ public class ComponentInfo extends ArchivableEntity {
|| StringUtils.isEmpty(componentModel)); || 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. * Returns a hash code that is associated with common fields for components.
*
* @return int value of the elements * @return int value of the elements
*/ */
public int hashCommonElements() { public int hashCommonElements() {
return Objects.hash(componentManufacturer, componentModel, return Objects.hash(componentManufacturer, componentModel,
componentSerial, componentRevision, componentClass); 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);
}
} }

View File

@ -33,8 +33,8 @@ public class FirmwareInfo implements Serializable {
/** /**
* Constructor used to create a populated firmware info object. * Constructor used to create a populated firmware info object.
* *
* @param biosVendor String bios vendor name, i.e. Dell Inc. * @param biosVendor String bios vendor name, i.e. Dell Inc.
* @param biosVersion String bios version info, i.e. A11 * @param biosVersion String bios version info, i.e. A11
* @param biosReleaseDate String bios release date info, i.e. 03/12/2013 * @param biosReleaseDate String bios release date info, i.e. 03/12/2013
*/ */
public FirmwareInfo(final String biosVendor, final String biosVersion, public FirmwareInfo(final String biosVendor, final String biosVersion,

View File

@ -48,11 +48,11 @@ public class HardwareInfo implements Serializable {
/** /**
* Constructor used to create a populated firmware info object. * Constructor used to create a populated firmware info object.
* *
* @param manufacturer String manufacturer name * @param manufacturer String manufacturer name
* @param productName String product name info * @param productName String product name info
* @param version String bios release date info * @param version String bios release date info
* @param systemSerialNumber String device serial number * @param systemSerialNumber String device serial number
* @param chassisSerialNumber String device chassis serial number * @param chassisSerialNumber String device chassis serial number
* @param baseboardSerialNumber String device baseboard serial number * @param baseboardSerialNumber String device baseboard serial number
*/ */
public HardwareInfo( public HardwareInfo(
@ -80,19 +80,19 @@ public class HardwareInfo implements Serializable {
if (!StringUtils.isBlank(systemSerialNumber)) { if (!StringUtils.isBlank(systemSerialNumber)) {
this.systemSerialNumber = StringValidator.check(systemSerialNumber, this.systemSerialNumber = StringValidator.check(systemSerialNumber,
"systemSerialNumber") "systemSerialNumber")
.maxLength(DeviceInfoEnums.LONG_STRING_LENGTH).getValue(); .maxLength(DeviceInfoEnums.LONG_STRING_LENGTH).getValue();
} }
if (!StringUtils.isBlank(chassisSerialNumber)) { if (!StringUtils.isBlank(chassisSerialNumber)) {
this.chassisSerialNumber = StringValidator.check(chassisSerialNumber, this.chassisSerialNumber = StringValidator.check(chassisSerialNumber,
"chassisSerialNumber") "chassisSerialNumber")
.maxLength(DeviceInfoEnums.LONG_STRING_LENGTH).getValue(); .maxLength(DeviceInfoEnums.LONG_STRING_LENGTH).getValue();
} }
if (!StringUtils.isBlank(baseboardSerialNumber)) { if (!StringUtils.isBlank(baseboardSerialNumber)) {
this.baseboardSerialNumber = StringValidator.check( this.baseboardSerialNumber = StringValidator.check(
baseboardSerialNumber, "baseboardSerialNumber") baseboardSerialNumber, "baseboardSerialNumber")
.maxLength(DeviceInfoEnums.LONG_STRING_LENGTH).getValue(); .maxLength(DeviceInfoEnums.LONG_STRING_LENGTH).getValue();
} }
} }

View File

@ -10,47 +10,42 @@ import lombok.extern.log4j.Log4j2;
import java.io.Serializable; import java.io.Serializable;
import java.net.InetAddress; import java.net.InetAddress;
import java.util.Arrays;
import java.util.Objects;
/** /**
* This class is used to represent the network info of a device. * This class is used to represent the network info of a device.
*/ */
@Log4j2 @Log4j2
@Embeddable @Embeddable
@EqualsAndHashCode
public class NetworkInfo implements Serializable { public class NetworkInfo implements Serializable {
private static final int NUM_MAC_ADDRESS_BYTES = 6; private static final int NUM_MAC_ADDRESS_BYTES = 6;
@XmlElement @XmlElement
@Getter @Getter
@Column(length = DeviceInfoEnums.LONG_STRING_LENGTH, nullable = true) @Column(length = DeviceInfoEnums.LONG_STRING_LENGTH)
private String hostname; private String hostname;
@XmlElement @XmlElement
@Getter @Getter
// @XmlJavaTypeAdapter(value = InetAddressXmlAdapter.class) // @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") // @JsonSubTypes.Type(type = "hirs.data.persist.type.InetAddressType")
private InetAddress ipAddress; private InetAddress ipAddress;
@XmlElement @XmlElement
@Column(length = NUM_MAC_ADDRESS_BYTES, nullable = true) @Column(length = NUM_MAC_ADDRESS_BYTES)
@SuppressWarnings("checkstyle:magicnumber")
private byte[] macAddress; private byte[] macAddress;
/** /**
* Constructor used to create a NetworkInfo object. * Constructor used to create a NetworkInfo object.
* *
* @param hostname * @param hostname String representing the hostname information for the device,
* String representing the hostname information for the device, * can be null if hostname unknown
* can be null if hostname unknown * @param ipAddress InetAddress object representing the IP address for the device,
* @param ipAddress * can be null if IP address unknown
* InetAddress object representing the IP address for the device, * @param macAddress byte array representing the MAC address for the device, can be
* can be null if IP address unknown * null if MAC address is 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, public NetworkInfo(final String hostname, final InetAddress ipAddress,
final byte[] macAddress) { final byte[] macAddress) {
@ -72,7 +67,7 @@ public class NetworkInfo implements Serializable {
* Used to retrieve the MAC address of the device. * Used to retrieve the MAC address of the device.
* *
* @return a String representing the MAC address, may return null if no * @return a String representing the MAC address, may return null if no
* value is set * value is set
*/ */
public final byte[] getMacAddress() { public final byte[] getMacAddress() {
if (macAddress == null) { 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) { private void setMacAddress(final byte[] macAddress) {
StringBuilder sb; StringBuilder sb;
if (macAddress == null) { if (macAddress == null) {
@ -114,22 +99,13 @@ public class NetworkInfo implements Serializable {
this.macAddress = macAddress; this.macAddress = macAddress;
} }
@Override private void setHostname(final String hostname) {
public boolean equals(Object o) { log.debug("setting hostname to: {}", hostname);
if (this == o) return true; this.hostname = hostname;
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);
} }
@Override private void setIpAddress(final InetAddress ipAddress) {
public int hashCode() { log.debug("setting IP address to: {}", ipAddress);
int result = Objects.hash(hostname, ipAddress); this.ipAddress = ipAddress;
result = 31 * result + Arrays.hashCode(macAddress);
return result;
} }
} }

View File

@ -47,16 +47,11 @@ public class OSInfo implements Serializable {
* Fedora), and distribution release (7.0.1406). Distribution only makes * Fedora), and distribution release (7.0.1406). Distribution only makes
* sense for Linux, so distribution and distributionRelease may be null. * sense for Linux, so distribution and distributionRelease may be null.
* *
* @param osName * @param osName String OS name (Linux | Mac OS X | Windows 7)
* String OS name (Linux | Mac OS X | Windows 7) * @param osVersion String OS version (i.e. 3.10.0-123.el7.x86_64)
* @param osVersion * @param osArch String OS architecture (x86_64)
* String OS version (i.e. 3.10.0-123.el7.x86_64) * @param distribution String distribution (CentOS | Fedora)
* @param osArch * @param distributionRelease String distribution release (7.0.1406)
* 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, public OSInfo(final String osName, final String osVersion,
final String osArch, final String distribution, final String osArch, final String distribution,

View File

@ -38,10 +38,11 @@ public class RIMInfo implements Serializable {
/** /**
* Constructor for the initial values of the class. * Constructor for the initial values of the class.
*
* @param rimManufacturer string of the rimManufacturer * @param rimManufacturer string of the rimManufacturer
* @param model string of the model * @param model string of the model
* @param fileHash string of the file hash * @param fileHash string of the file hash
* @param pcrHash string of the pcr hash * @param pcrHash string of the pcr hash
*/ */
public RIMInfo(final String rimManufacturer, final String model, public RIMInfo(final String rimManufacturer, final String model,
final String fileHash, final String pcrHash) { final String fileHash, final String pcrHash) {

View File

@ -68,27 +68,17 @@ public class TPMInfo implements Serializable {
/** /**
* Constructor used to create a TPMInfo object. * Constructor used to create a TPMInfo object.
* *
* @param tpmMake * @param tpmMake String representing the make information for the TPM,
* String representing the make information for the TPM, * NullPointerException thrown if null
* NullPointerException thrown if null * @param tpmVersionMajor short representing the major version number for the TPM
* @param tpmVersionMajor * @param tpmVersionMinor short representing the minor version number for the TPM
* short representing the major version number for the TPM * @param tpmVersionRevMajor short representing the major revision number for the TPM
* @param tpmVersionMinor * @param tpmVersionRevMinor short representing the minor revision number for the TPM
* short representing the minor version number for the TPM * @param identityCertificate byte array with the value of the identity certificate
* @param tpmVersionRevMajor * @param pcrValues short representing the major revision number for the TPM
* short representing the major revision number for the TPM * @param tpmQuoteHash short representing the minor revision number for the TPM
* @param tpmVersionRevMinor * @param tpmQuoteSignature byte array with the value of the identity certificate
* 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, public TPMInfo(final String tpmMake, final short tpmVersionMajor,
final short tpmVersionMinor, final short tpmVersionRevMajor, final short tpmVersionMinor, final short tpmVersionRevMajor,
final short tpmVersionRevMinor, final short tpmVersionRevMinor,
@ -109,25 +99,16 @@ public class TPMInfo implements Serializable {
* Constructor used to create a TPMInfo object without an identity * Constructor used to create a TPMInfo object without an identity
* certificate. * certificate.
* *
* @param tpmMake * @param tpmMake String representing the make information for the TPM,
* String representing the make information for the TPM, * NullPointerException thrown if null
* NullPointerException thrown if null * @param tpmVersionMajor short representing the major version number for the TPM
* @param tpmVersionMajor * @param tpmVersionMinor short representing the minor version number for the TPM
* short representing the major version number for the TPM * @param tpmVersionRevMajor short representing the major revision number for the TPM
* @param tpmVersionMinor * @param tpmVersionRevMinor short representing the minor revision number for the TPM
* short representing the minor version number for the TPM * @param pcrValues short representing the major revision number for the TPM
* @param tpmVersionRevMajor * @param tpmQuoteHash short representing the minor revision number for the TPM
* short representing the major revision number for the TPM * @param tpmQuoteSignature byte array with the value of the identity certificate
* @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, public TPMInfo(final String tpmMake, final short tpmVersionMajor,
final short tpmVersionMinor, final short tpmVersionRevMajor, final short tpmVersionMinor, final short tpmVersionRevMajor,
final short tpmVersionRevMinor, final byte[] pcrValues, 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 * Constructor used to create a TPMInfo object without an identity
* certificate. * certificate.
* *
* @param tpmMake * @param tpmMake String representing the make information for the TPM,
* String representing the make information for the TPM, * NullPointerException thrown if null
* NullPointerException thrown if null * @param tpmVersionMajor short representing the major version number for the TPM
* @param tpmVersionMajor * @param tpmVersionMinor short representing the minor version number for the TPM
* short representing the major version number for the TPM * @param tpmVersionRevMajor short representing the major revision number for the TPM
* @param tpmVersionMinor * @param tpmVersionRevMinor short representing the minor revision number for the TPM
* 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, public TPMInfo(final String tpmMake, final short tpmVersionMajor,
final short tpmVersionMinor, final short tpmVersionRevMajor, 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 * Constructor used to create a TPMInfo object without an identity
* certificate. * certificate.
* *
* @param tpmMake * @param tpmMake String representing the make information for the TPM,
* String representing the make information for the TPM, * NullPointerException thrown if null
* NullPointerException thrown if null * @param tpmVersionMajor short representing the major version number for the TPM
* @param tpmVersionMajor * @param tpmVersionMinor short representing the minor version number for the TPM
* short representing the major version number for the TPM * @param tpmVersionRevMajor short representing the major revision number for the TPM
* @param tpmVersionMinor * @param tpmVersionRevMinor short representing the minor revision number for the TPM
* short representing the minor version number for the TPM * @param identityCertificate byte array with the value of the identity certificate
* @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, public TPMInfo(final String tpmMake, final short tpmVersionMajor,
final short tpmVersionMinor, final short tpmVersionRevMajor, final short tpmVersionMinor, final short tpmVersionRevMajor,
@ -217,30 +187,67 @@ public class TPMInfo implements Serializable {
return identityCertificate; 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. * Getter for the tpmQuote passed up by the client.
*
* @return a byte blob of quote * @return a byte blob of quote
*/ */
public final byte[] getTpmQuoteHash() { public final byte[] getTpmQuoteHash() {
return tpmQuoteHash.clone(); 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. * Getter for the quote signature.
*
* @return a byte blob. * @return a byte blob.
*/ */
public final byte[] getTpmQuoteSignature() { public final byte[] getTpmQuoteSignature() {
return tpmQuoteSignature.clone(); 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. * Getter for the pcr values.
*
* @return a byte blob for the pcrValues. * @return a byte blob for the pcrValues.
*/ */
public final byte[] getPcrValues() { public final byte[] getPcrValues() {
return pcrValues.clone(); 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) { private void setTPMMake(final String tpmMake) {
log.debug("setting TPM make info: {}", tpmMake); log.debug("setting TPM make info: {}", tpmMake);
this.tpmMake = StringValidator.check(tpmMake, "tpmMake") this.tpmMake = StringValidator.check(tpmMake, "tpmMake")
@ -292,38 +299,4 @@ public class TPMInfo implements Serializable {
tpmVersionRevMinor); tpmVersionRevMinor);
this.tpmVersionRevMinor = 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();
}
}
} }

View File

@ -0,0 +1 @@
package hirs.attestationca.persist.entity.userdefined.info.component;

View File

@ -0,0 +1 @@
package hirs.attestationca.persist.entity.userdefined.info;

View File

@ -1 +1 @@
package hirs.attestationca.persist.entity.userdefined; package hirs.attestationca.persist.entity.userdefined;

View File

@ -26,7 +26,7 @@ import org.apache.commons.codec.binary.Hex;
@Log4j2 @Log4j2
@Getter @Getter
@ToString @ToString
@EqualsAndHashCode @EqualsAndHashCode(callSuper = false)
@Embeddable @Embeddable
@XmlAccessorType(XmlAccessType.FIELD) @XmlAccessorType(XmlAccessType.FIELD)
public final class TPMMeasurementRecord extends ExaminableRecord { 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; public static final int SHA_256_BYTE_LENGTH = 64;
@Column(name = "pcr", nullable = false) @Column(name = "pcr", nullable = false)
@XmlAttribute(name = "PcrNumber", required = true) @XmlAttribute(name = "PcrNumber", required = true)
private final int pcrId; private final int pcrId;
@ -63,9 +62,8 @@ public final class TPMMeasurementRecord extends ExaminableRecord {
* Constructor initializes values associated with TPMMeasurementRecord. * Constructor initializes values associated with TPMMeasurementRecord.
* *
* @param pcrId is the TPM PCR index. pcrId must be between 0 and 23. * @param pcrId is the TPM PCR index. pcrId must be between 0 and 23.
* @param hash * @param hash represents the measurement digest found at the particular PCR
* represents the measurement digest found at the particular PCR * index.
* index.
* @throws IllegalArgumentException if pcrId is not valid * @throws IllegalArgumentException if pcrId is not valid
*/ */
public TPMMeasurementRecord(final int pcrId, final Digest hash) public TPMMeasurementRecord(final int pcrId, final Digest hash)
@ -85,8 +83,8 @@ public final class TPMMeasurementRecord extends ExaminableRecord {
* Constructor initializes values associated with TPMMeasurementRecord. * Constructor initializes values associated with TPMMeasurementRecord.
* *
* @param pcrId is the TPM PCR index. pcrId must be between 0 and 23. * @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 * @param hash represents the measurement digest found at the particular PCR
* index. * index.
* @throws DecoderException if there is a decode issue with string hex. * @throws DecoderException if there is a decode issue with string hex.
*/ */
public TPMMeasurementRecord(final int pcrId, final String hash) public TPMMeasurementRecord(final int pcrId, final String hash)
@ -98,18 +96,26 @@ public final class TPMMeasurementRecord extends ExaminableRecord {
* Constructor initializes values associated with TPMMeasurementRecord. * Constructor initializes values associated with TPMMeasurementRecord.
* *
* @param pcrId is the TPM PCR index. pcrId must be between 0 and 23. * @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 * @param hash represents the measurement digest found at the particular PCR
* index. * index.
*/ */
public TPMMeasurementRecord(final int pcrId, final byte[] hash) { public TPMMeasurementRecord(final int pcrId, final byte[] hash) {
this(pcrId, new Digest(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. * Helper method to determine if a PCR ID number is valid.
* *
* @param pcrId * @param pcrId int to check
* int to check
*/ */
public static void checkForValidPcrId(final int pcrId) { public static void checkForValidPcrId(final int pcrId) {
if (pcrId < MIN_PCR_ID || pcrId > MAX_PCR_ID) { if (pcrId < MIN_PCR_ID || pcrId > MAX_PCR_ID) {
@ -118,13 +124,4 @@ public final class TPMMeasurementRecord extends ExaminableRecord {
throw new IllegalArgumentException(msg); throw new IllegalArgumentException(msg);
} }
} }
/**
* Default constructor necessary for Hibernate.
*/
protected TPMMeasurementRecord() {
super();
this.pcrId = -1;
this.hash = null;
}
} }

View File

@ -0,0 +1 @@
package hirs.attestationca.persist.entity.userdefined.record;

View File

@ -1,5 +1,6 @@
package hirs.attestationca.persist.entity.userdefined.report; 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.AbstractEntity;
import hirs.attestationca.persist.entity.userdefined.info.FirmwareInfo; import hirs.attestationca.persist.entity.userdefined.info.FirmwareInfo;
import hirs.attestationca.persist.entity.userdefined.info.HardwareInfo; import hirs.attestationca.persist.entity.userdefined.info.HardwareInfo;
@ -13,6 +14,8 @@ import jakarta.persistence.Embedded;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.Transient; import jakarta.persistence.Transient;
import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlElement;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
@ -20,16 +23,19 @@ import lombok.extern.log4j.Log4j2;
import java.io.Serializable; import java.io.Serializable;
import java.net.InetAddress; import java.net.InetAddress;
import java.util.Objects;
/** /**
* A <code>DeviceInfoReport</code> is a <code>Report</code> used to transfer the * A <code>DeviceInfoReport</code> is a <code>Report</code> used to transfer the
* information about the device. This <code>Report</code> includes the network, * information about the device. This <code>Report</code> includes the network,
* OS, and TPM information. * 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 @NoArgsConstructor
@Getter @EqualsAndHashCode(callSuper = false)
@Log4j2
@Entity @Entity
public class DeviceInfoReport extends AbstractEntity implements Serializable { public class DeviceInfoReport extends AbstractEntity implements Serializable {
@ -49,14 +55,18 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable {
@Embedded @Embedded
private HardwareInfo hardwareInfo; private HardwareInfo hardwareInfo;
@Setter(AccessLevel.PRIVATE)
@Getter
@XmlElement @XmlElement
@Embedded @Embedded
private TPMInfo tpmInfo; private TPMInfo tpmInfo;
@Getter
@XmlElement @XmlElement
@Column(nullable = false) @Column(nullable = false)
private String clientApplicationVersion; private String clientApplicationVersion;
@Getter
@Setter @Setter
@XmlElement @XmlElement
@Transient @Transient
@ -67,17 +77,12 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable {
* information cannot be changed after the <code>DeviceInfoReport</code> is * information cannot be changed after the <code>DeviceInfoReport</code> is
* created. * created.
* *
* @param networkInfo * @param networkInfo NetworkInfo object, cannot be null
* NetworkInfo object, cannot be null * @param osInfo OSInfo object, cannot be null
* @param osInfo * @param firmwareInfo FirmwareInfo object, cannot be null
* OSInfo object, cannot be null * @param hardwareInfo HardwareInfo object, cannot be null
* @param firmwareInfo * @param tpmInfo TPMInfo object, may be null if a TPM is not available on the
* FirmwareInfo object, cannot be null * device
* @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, public DeviceInfoReport(final NetworkInfo networkInfo, final OSInfo osInfo,
final FirmwareInfo firmwareInfo, final HardwareInfo hardwareInfo, final FirmwareInfo firmwareInfo, final HardwareInfo hardwareInfo,
@ -90,20 +95,14 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable {
* information cannot be changed after the <code>DeviceInfoReport</code> is * information cannot be changed after the <code>DeviceInfoReport</code> is
* created. * created.
* *
* @param networkInfo * @param networkInfo NetworkInfo object, cannot be null
* NetworkInfo object, cannot be null * @param osInfo OSInfo object, cannot be null
* @param osInfo * @param firmwareInfo FirmwareInfo object, cannot be null
* OSInfo object, cannot be null * @param hardwareInfo HardwareInfo object, cannot be null
* @param firmwareInfo * @param tpmInfo TPMInfo object, may be null if a TPM is not available on the
* FirmwareInfo object, cannot be null * device
* @param hardwareInfo * @param clientApplicationVersion string representing the version of the client that submitted this
* HardwareInfo object, cannot be null * report, 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, public DeviceInfoReport(final NetworkInfo networkInfo, final OSInfo osInfo,
final FirmwareInfo firmwareInfo, final HardwareInfo hardwareInfo, final FirmwareInfo firmwareInfo, final HardwareInfo hardwareInfo,
@ -112,7 +111,7 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable {
setOSInfo(osInfo); setOSInfo(osInfo);
setFirmwareInfo(firmwareInfo); setFirmwareInfo(firmwareInfo);
setHardwareInfo(hardwareInfo); setHardwareInfo(hardwareInfo);
setTPMInfo(tpmInfo); setTpmInfo(tpmInfo);
this.clientApplicationVersion = clientApplicationVersion; this.clientApplicationVersion = clientApplicationVersion;
} }
@ -135,6 +134,14 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable {
networkInfo.getIpAddress(), networkInfo.getMacAddress()); 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 <code>DeviceInfoReport</code>. * Retrieves the OSInfo for this <code>DeviceInfoReport</code>.
* *
@ -154,6 +161,14 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable {
return osInfo; 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 <code>DeviceInfoReport</code>. * Retrieves the FirmwareInfo for this <code>DeviceInfoReport</code>.
* *
@ -172,6 +187,14 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable {
return firmwareInfo; 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 <code>DeviceInfoReport</code>. * Retrieves the OSInfo for this <code>DeviceInfoReport</code>.
* *
@ -196,30 +219,6 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable {
return hardwareInfo; 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) { private void setHardwareInfo(final HardwareInfo hardwareInfo) {
if (hardwareInfo == null) { if (hardwareInfo == null) {
log.error("HardwareInfo cannot be null"); log.error("HardwareInfo cannot be null");
@ -227,31 +226,6 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable {
} }
this.hardwareInfo = hardwareInfo; 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);
}
} }

View File

@ -0,0 +1 @@
package hirs.attestationca.persist.entity.userdefined.report;

View File

@ -6,11 +6,27 @@ import lombok.Setter;
/** /**
* An <code>CertificateValidationResult</code> represents the result of a certificate validation * An <code>CertificateValidationResult</code> represents the result of a certificate validation
* operation. * operation.
*
*/ */
@Getter @Getter
@Setter @Setter
public class CertificateValidationResult { 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. * Enum used to represent certificate validation status.
*/ */
@ -31,21 +47,4 @@ public class CertificateValidationResult {
*/ */
ERROR 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;
}
} }

View File

@ -0,0 +1 @@
package hirs.attestationca.persist.entity.userdefined.result;

View File

@ -10,6 +10,7 @@ import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.UnmarshalException; import jakarta.xml.bind.UnmarshalException;
import jakarta.xml.bind.Unmarshaller; import jakarta.xml.bind.Unmarshaller;
import lombok.AccessLevel; import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
@ -33,7 +34,6 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
/** /**
* *
@ -42,6 +42,7 @@ import java.util.Objects;
@Getter @Getter
@Setter @Setter
@NoArgsConstructor(access = AccessLevel.PROTECTED) @NoArgsConstructor(access = AccessLevel.PROTECTED)
@EqualsAndHashCode(callSuper = true)
@Entity @Entity
public class BaseReferenceManifest extends ReferenceManifest { public class BaseReferenceManifest extends ReferenceManifest {
/** /**
@ -53,43 +54,60 @@ public class BaseReferenceManifest extends ReferenceManifest {
@Column @Column
private String swidName = null; private String swidName = null;
@Column @Column
private int swidCorpus = 0; private int swidCorpus = 0;
@Column @Column
private String colloquialVersion = null; private String colloquialVersion = null;
@Column @Column
private String product = null; private String product = null;
@Column @Column
private String revision = null; private String revision = null;
@Column @Column
private String edition = null; private String edition = null;
@Column @Column
private String rimLinkHash = null; private String rimLinkHash = null;
@Column @Column
private String bindingSpec = null; private String bindingSpec = null;
@Column @Column
private String bindingSpecVersion = null; private String bindingSpecVersion = null;
@Column @Column
private String platformVersion = null; private String platformVersion = null;
@Column @Column
private String payloadType = null; private String payloadType = null;
@Column @Column
private String pcURIGlobal = null; private String pcURIGlobal = null;
@Column @Column
private String pcURILocal = null; private String pcURILocal = null;
private String entityName = null; private String entityName = null;
private String entityRegId = null; private String entityRegId = null;
private String entityRole = null; private String entityRole = null;
private String entityThumbprint = null; private String entityThumbprint = null;
private String linkHref = null; private String linkHref = null;
private String linkRel = null; private String linkRel = null;
/** /**
* Support constructor for the RIM object. * Support constructor for the RIM object.
* *
* @param rimBytes - the file content of the uploaded file. * @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 { public BaseReferenceManifest(final byte[] rimBytes) throws UnmarshalException {
this("", rimBytes); this("", rimBytes);
@ -101,7 +119,7 @@ public class BaseReferenceManifest extends ReferenceManifest {
* *
* @param fileName - string representation of the uploaded file. * @param fileName - string representation of the uploaded file.
* @param rimBytes byte array representation of the RIM * @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) public BaseReferenceManifest(final String fileName, final byte[] rimBytes)
throws UnmarshalException { throws UnmarshalException {
@ -205,6 +223,9 @@ public class BaseReferenceManifest extends ReferenceManifest {
* This method validates the .swidtag file at the given filepath against the * 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 * schema. A successful validation results in the output of the tag's name
* and tagId attributes, otherwise a generic error message is printed. * 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) { private Element getDirectoryTag(final byte[] rimBytes) {
if (rimBytes == null || rimBytes.length == 0) { 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. * and tagId attributes, otherwise a generic error message is printed.
* *
* @param byteArrayInputStream the location of the file to be validated * @param byteArrayInputStream the location of the file to be validated
* @return an element
*/ */
private Element getDirectoryTag(final ByteArrayInputStream byteArrayInputStream) { private Element getDirectoryTag(final ByteArrayInputStream byteArrayInputStream) {
Document document = null; Document document = null;
try { try {
document = unmarshallSwidTag(byteArrayInputStream); document = unmarshallSwidTag(byteArrayInputStream);
} catch (UnmarshalException e) { } catch (UnmarshalException e) {
log.error("Error while parsing Directory tag: " + e.getMessage()); log.error("Error while parsing Directory tag: {}", e.getMessage());
} }
if (document != null) { if (document != null) {
Element softwareIdentity = 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<SwidResource> getFileResources() { public List<SwidResource> getFileResources() {
return getFileResources(getRimBytes()); return getFileResources(getRimBytes());
@ -256,6 +280,7 @@ 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.
* *
* @param rimBytes the bytes to find the files * @param rimBytes the bytes to find the files
* @return a list of swid resources
*/ */
public List<SwidResource> getFileResources(final byte[] rimBytes) { public List<SwidResource> getFileResources(final byte[] rimBytes) {
Element directoryTag = getDirectoryTag(rimBytes); Element directoryTag = getDirectoryTag(rimBytes);
@ -352,49 +377,11 @@ public class BaseReferenceManifest extends ReferenceManifest {
return document; return document;
} }
@Override /**
public boolean equals(Object o) { * Creates a string representation of the Base Reference Manifest object.
if (this == o) { *
return true; * @return a string representation of the Base Reference Manifest object.
} */
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);
}
@Override @Override
public String toString() { public String toString() {
return String.format("ReferenceManifest{swidName=%s," return String.format("ReferenceManifest{swidName=%s,"

View File

@ -1,7 +1,6 @@
package hirs.attestationca.persist.entity.userdefined.rim; package hirs.attestationca.persist.entity.userdefined.rim;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import hirs.attestationca.persist.entity.userdefined.ReferenceManifest;
import hirs.attestationca.persist.enums.AppraisalStatus; import hirs.attestationca.persist.enums.AppraisalStatus;
import hirs.utils.tpm.eventlog.TCGEventLog; import hirs.utils.tpm.eventlog.TCGEventLog;
import hirs.utils.tpm.eventlog.TpmPcrEvent; import hirs.utils.tpm.eventlog.TpmPcrEvent;
@ -9,6 +8,7 @@ import jakarta.persistence.Column;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.EnumType; import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated; import jakarta.persistence.Enumerated;
import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
@ -25,16 +25,18 @@ import java.util.Collection;
* Similar to {@link SupportReferenceManifest} * Similar to {@link SupportReferenceManifest}
* however this is the live log from the client. * however this is the live log from the client.
*/ */
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
@Log4j2 @Log4j2
@Entity @Entity
public class EventLogMeasurements extends SupportReferenceManifest { public class EventLogMeasurements extends SupportReferenceManifest {
@Column @Column
@JsonIgnore @JsonIgnore
@Getter @Setter
private int pcrHash = 0; private int pcrHash = 0;
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
@Getter @Setter
private AppraisalStatus.Status overallValidationResult = AppraisalStatus.Status.FAIL; 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 * Getter method for the expected PCR values contained within the support
* RIM. * RIM.
*
* @return a string array of the pcr values. * @return a string array of the pcr values.
*/ */
public String[] getExpectedPCRList() { public String[] getExpectedPCRList() {
@ -81,12 +84,8 @@ public class EventLogMeasurements extends SupportReferenceManifest {
TCGEventLog logProcessor = new TCGEventLog(this.getRimBytes()); TCGEventLog logProcessor = new TCGEventLog(this.getRimBytes());
this.pcrHash = Arrays.hashCode(logProcessor.getExpectedPCRValues()); this.pcrHash = Arrays.hashCode(logProcessor.getExpectedPCRValues());
return logProcessor.getExpectedPCRValues(); return logProcessor.getExpectedPCRValues();
} catch (CertificateException cEx) { } catch (CertificateException | NoSuchAlgorithmException | IOException exception) {
log.error(cEx); log.error(exception);
} catch (NoSuchAlgorithmException noSaEx) {
log.error(noSaEx);
} catch (IOException ioEx) {
log.error(ioEx);
} }
return new String[0]; return new String[0];
@ -102,32 +101,10 @@ public class EventLogMeasurements extends SupportReferenceManifest {
try { try {
logProcessor = new TCGEventLog(this.getRimBytes()); logProcessor = new TCGEventLog(this.getRimBytes());
return logProcessor.getEventList(); return logProcessor.getEventList();
} catch (CertificateException cEx) { } catch (CertificateException | NoSuchAlgorithmException | IOException exception) {
log.error(cEx); log.error(exception);
} catch (NoSuchAlgorithmException noSaEx) {
log.error(noSaEx);
} catch (IOException ioEx) {
log.error(ioEx);
} }
return new ArrayList<>(); 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();
}
}

View File

@ -6,9 +6,9 @@ import jakarta.persistence.AccessType;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.Table; import jakarta.persistence.Table;
import lombok.AccessLevel;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
@ -22,48 +22,50 @@ import java.util.UUID;
* Digest Value, Event Type, index, RIM Tagid * Digest Value, Event Type, index, RIM Tagid
*/ */
@Getter @Getter
@Setter
@Builder @Builder
@AllArgsConstructor @AllArgsConstructor
@Entity @Entity
@EqualsAndHashCode(callSuper=false) @EqualsAndHashCode(callSuper = false)
@Table(name = "ReferenceDigestValue") @Table(name = "ReferenceDigestValue")
@Access(AccessType.FIELD) @Access(AccessType.FIELD)
public class ReferenceDigestValue extends AbstractEntity { public class ReferenceDigestValue extends AbstractEntity {
@Setter
@JdbcTypeCode(java.sql.Types.VARCHAR) @JdbcTypeCode(java.sql.Types.VARCHAR)
@Column @Column
private UUID baseRimId; private UUID baseRimId;
@Setter
@JdbcTypeCode(java.sql.Types.VARCHAR) @JdbcTypeCode(java.sql.Types.VARCHAR)
@Column @Column
private UUID supportRimId; private UUID supportRimId;
@Setter
@Column(nullable = false) @Column(nullable = false)
private String manufacturer; private String manufacturer;
@Setter
@Column(nullable = false) @Column(nullable = false)
private String model; private String model;
@Setter
@Column(nullable = false) @Column(nullable = false)
private int pcrIndex; private int pcrIndex;
@Setter
@Column(nullable = false) @Column(nullable = false)
private String digestValue; private String digestValue;
@Setter
@Column(nullable = false) @Column(nullable = false)
private String supportRimHash; private String supportRimHash;
@Setter
@Column(nullable = false) @Column(nullable = false)
private String eventType; private String eventType;
@Column(columnDefinition = "blob", nullable = true)
@Setter(AccessLevel.NONE)
@Column(columnDefinition = "blob")
private byte[] contentBlob; private byte[] contentBlob;
@Setter
@Column(nullable = false) @Column(nullable = false)
private boolean matchFail; private boolean matchFail;
@Setter
@Column(nullable = false) @Column(nullable = false)
private boolean patched; private boolean patched;
@Setter
@Column(nullable = false) @Column(nullable = false)
private boolean updated; private boolean updated;
@ -88,18 +90,19 @@ public class ReferenceDigestValue extends AbstractEntity {
/** /**
* Default Constructor with parameters for all associated data. * 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 baseRimId the UUID of the associated record
* @param manufacturer associated creator for this information * @param supportRimId the UUID of the associated record
* @param model the specific device type * @param manufacturer associated creator for this information
* @param pcrIndex the event number * @param model the specific device type
* @param digestValue the key digest value * @param pcrIndex the event number
* @param digestValue the key digest value
* @param supportRimHash the support file's hash value * @param supportRimHash the support file's hash value
* @param eventType the event type to store * @param eventType the event type to store
* @param matchFail the status of the baseline check * @param matchFail the status of the baseline check
* @param patched the status of the value being updated to patch * @param patched the status of the value being updated to patch
* @param updated the status of the value being updated with info * @param updated the status of the value being updated with info
* @param contentBlob the data value of the content * @param contentBlob the data value of the content
*/ */
public ReferenceDigestValue(final UUID baseRimId, final UUID supportRimId, public ReferenceDigestValue(final UUID baseRimId, final UUID supportRimId,
final String manufacturer, final String model, final String manufacturer, final String model,
@ -108,6 +111,8 @@ public class ReferenceDigestValue extends AbstractEntity {
final String eventType, final boolean matchFail, final String eventType, final boolean matchFail,
final boolean patched, final boolean updated, final boolean patched, final boolean updated,
final byte[] contentBlob) { final byte[] contentBlob) {
this.baseRimId = baseRimId; this.baseRimId = baseRimId;
this.supportRimId = supportRimId; this.supportRimId = supportRimId;
this.manufacturer = manufacturer; this.manufacturer = manufacturer;
@ -122,17 +127,10 @@ public class ReferenceDigestValue extends AbstractEntity {
this.contentBlob = Arrays.clone(contentBlob); 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. * 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 * @param baseRimId the main id to update
*/ */
public void updateInfo(final SupportReferenceManifest support, final UUID baseRimId) { 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. * Returns a string of the classes fields.
*
* @return a string * @return a string
*/ */
public String toString() { public String toString() {

View File

@ -6,6 +6,7 @@ import hirs.utils.tpm.eventlog.TCGEventLog;
import hirs.utils.tpm.eventlog.TpmPcrEvent; import hirs.utils.tpm.eventlog.TpmPcrEvent;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
@ -16,7 +17,6 @@ import java.security.cert.CertificateException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Objects;
/** /**
* Sub class that will just focus on PCR Values and Events. * Sub class that will just focus on PCR Values and Events.
@ -24,12 +24,14 @@ import java.util.Objects;
@Log4j2 @Log4j2
@Getter @Getter
@Setter @Setter
@EqualsAndHashCode(callSuper = true)
@Entity @Entity
public class SupportReferenceManifest extends ReferenceManifest { public class SupportReferenceManifest extends ReferenceManifest {
@Column @Column
@JsonIgnore @JsonIgnore
private int pcrHash = 0; private int pcrHash = 0;
@Column @Column
private boolean updated = false; private boolean updated = false;
@ -71,6 +73,7 @@ public class SupportReferenceManifest extends ReferenceManifest {
/** /**
* Getter method for the expected PCR values contained within the support * Getter method for the expected PCR values contained within the support
* RIM. * RIM.
*
* @return a string array of the pcr values. * @return a string array of the pcr values.
*/ */
public String[] getExpectedPCRList() { public String[] getExpectedPCRList() {
@ -78,12 +81,8 @@ public class SupportReferenceManifest extends ReferenceManifest {
TCGEventLog logProcessor = new TCGEventLog(this.getRimBytes()); TCGEventLog logProcessor = new TCGEventLog(this.getRimBytes());
this.pcrHash = Arrays.hashCode(logProcessor.getExpectedPCRValues()); this.pcrHash = Arrays.hashCode(logProcessor.getExpectedPCRValues());
return logProcessor.getExpectedPCRValues(); return logProcessor.getExpectedPCRValues();
} catch (CertificateException cEx) { } catch (CertificateException | NoSuchAlgorithmException | IOException exception) {
log.error(cEx); log.error(exception);
} catch (NoSuchAlgorithmException noSaEx) {
log.error(noSaEx);
} catch (IOException ioEx) {
log.error(ioEx);
} }
return new String[0]; return new String[0];
@ -99,12 +98,8 @@ public class SupportReferenceManifest extends ReferenceManifest {
try { try {
logProcessor = new TCGEventLog(this.getRimBytes()); logProcessor = new TCGEventLog(this.getRimBytes());
return logProcessor.getEventList(); return logProcessor.getEventList();
} catch (CertificateException cEx) { } catch (CertificateException | NoSuchAlgorithmException | IOException exception) {
log.error(cEx); log.error(exception);
} catch (NoSuchAlgorithmException noSaEx) {
log.error(noSaEx);
} catch (IOException ioEx) {
log.error(ioEx);
} }
return new ArrayList<>(); return new ArrayList<>();
@ -113,23 +108,10 @@ public class SupportReferenceManifest extends ReferenceManifest {
/** /**
* This is a method to indicate whether or not this support * This is a method to indicate whether or not this support
* rim is a base log file. * rim is a base log file.
*
* @return flag for base. * @return flag for base.
*/ */
public boolean isBaseSupport() { public boolean isBaseSupport() {
return !this.isSwidSupplemental() && !this.isSwidPatch(); 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);
}
} }

View File

@ -1 +1 @@
package hirs.attestationca.persist.entity.userdefined.rim; package hirs.attestationca.persist.entity.userdefined.rim;

View File

@ -9,6 +9,35 @@ import lombok.Setter;
@Getter @Getter
@Setter @Setter
public class AppraisalStatus { 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. * Enum used to represent appraisal status.
*/ */
@ -33,31 +62,4 @@ public class AppraisalStatus {
*/ */
UNKNOWN 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;
}
} }

View File

@ -1,11 +1,18 @@
package hirs.attestationca.persist.enums; package hirs.attestationca.persist.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
import java.util.Arrays; import java.util.Arrays;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* <code>HealthStatus</code> is used to represent the health of a device. * <code>HealthStatus</code> is used to represent the health of a device.
*/ */
@Getter
@AllArgsConstructor
@ToString
public enum HealthStatus { public enum HealthStatus {
/** /**
* The trusted state, no issues with the device. * The trusted state, no issues with the device.
@ -22,36 +29,18 @@ public enum HealthStatus {
*/ */
UNKNOWN("unknown"); UNKNOWN("unknown");
private String healthStatus; private final String healthStatus;
/** /**
* Creates a new <code>HealthStatus</code> object given a String. * Determines if the provided health status is a valid health status.
* *
* @param healthStatus * @param healthStatus string representation of the healh status
* "trusted", "untrusted", or "unknown" * @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) { public static boolean isValidStatus(final String healthStatus) {
return Arrays.stream(HealthStatus.values()) return Arrays.stream(HealthStatus.values())
.map(HealthStatus::name) .map(HealthStatus::name)
.collect(Collectors.toSet()) .collect(Collectors.toSet())
.contains(healthStatus); .contains(healthStatus);
} }
} }

View File

@ -1 +1 @@
package hirs.attestationca.persist.enums; package hirs.attestationca.persist.enums;

View File

@ -0,0 +1 @@
package hirs.attestationca.persist.exceptions;

View File

@ -0,0 +1 @@
package hirs.attestationca.persist;

View File

@ -43,22 +43,23 @@ import java.util.Date;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
@Getter
@Log4j2 @Log4j2
@NoArgsConstructor @NoArgsConstructor
public class AbstractProcessor { public class AbstractProcessor {
@Getter
private int validDays; private int validDays;
@Getter
private PrivateKey privateKey; private PrivateKey privateKey;
@Setter @Setter
@Getter
private PolicyRepository policyRepository; private PolicyRepository policyRepository;
/** /**
* Default constructor that sets main class fields. * Default constructor that sets main class fields.
*
* @param privateKey private key used for communication authentication * @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, public AbstractProcessor(final PrivateKey privateKey,
final int validDays) { final int validDays) {
@ -69,17 +70,18 @@ public class AbstractProcessor {
/** /**
* Generates a credential using the specified public key. * Generates a credential using the specified public key.
* *
* @param publicKey cannot be null * @param publicKey cannot be null
* @param endorsementCredential the endorsement credential * @param endorsementCredential the endorsement credential
* @param platformCredentials the set of platform credentials * @param platformCredentials the set of platform credentials
* @param deviceName The host name used in the subject alternative name * @param deviceName The host name used in the subject alternative name
* @param acaCertificate object used to create credential * @param acaCertificate object used to create credential
* @return identity credential * @return identity credential
*/ */
protected X509Certificate generateCredential(final PublicKey publicKey, protected X509Certificate generateCredential(final PublicKey publicKey,
final EndorsementCredential endorsementCredential, final EndorsementCredential endorsementCredential,
final List<PlatformCredential> platformCredentials, final List<PlatformCredential> platformCredentials,
final String deviceName, final X509Certificate acaCertificate) { final String deviceName,
final X509Certificate acaCertificate) {
try { try {
// have the certificate expire in the configured number of days // have the certificate expire in the configured number of days
Calendar expiry = Calendar.getInstance(); Calendar expiry = Calendar.getInstance();
@ -149,8 +151,8 @@ public class AbstractProcessor {
* IdentityClaim. Will also check if the Endorsement Credential was already uploaded. * IdentityClaim. Will also check if the Endorsement Credential was already uploaded.
* Persists the Endorsement Credential if it does not already exist. * Persists the Endorsement Credential if it does not already exist.
* *
* @param identityClaim a Protobuf generated Identity Claim object * @param identityClaim a Protobuf generated Identity Claim object
* @param ekPub the endorsement public key from the Identity Claim object * @param ekPub the endorsement public key from the Identity Claim object
* @param certificateRepository db connector from certificates * @param certificateRepository db connector from certificates
* @return the Endorsement Credential, if one exists, null otherwise * @return the Endorsement Credential, if one exists, null otherwise
*/ */
@ -179,7 +181,7 @@ public class AbstractProcessor {
* IdentityClaim and Endorsement Credential. Persists the Platform Credentials if they * IdentityClaim and Endorsement Credential. Persists the Platform Credentials if they
* do not already exist. * 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 * @param endorsementCredential an endorsement credential to check if platform credentials
* exist * exist
* @param certificateRepository db connector from certificates * @param certificateRepository db connector from certificates
@ -210,7 +212,8 @@ public class AbstractProcessor {
/** /**
* Gets the Endorsement Credential from the DB given the EK public key. * 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 * @param certificateRepository db store manager for certificates
* @return the Endorsement credential, if found, otherwise null * @return the Endorsement credential, if found, otherwise null
*/ */
@ -246,22 +249,23 @@ public class AbstractProcessor {
* Helper method to create an {@link IssuedAttestationCertificate} object, set its * Helper method to create an {@link IssuedAttestationCertificate} object, set its
* corresponding device and persist it. * 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 * @param derEncodedAttestationCertificate the byte array representing the Attestation
* certificate * certificate
* @param endorsementCredential the endorsement credential used to generate the AC * @param endorsementCredential the endorsement credential used to generate the AC
* @param platformCredentials the platform credentials 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 device the device to which the attestation certificate is tied
* @param isLDevID whether the certificate is a ldevid * @param isLDevID whether the certificate is a ldevid
* @return whether the certificate was saved successfully * @return whether the certificate was saved successfully
* @throws {@link CertificateProcessingException} if error occurs in persisting the Attestation * @throws {@link CertificateProcessingException} if error occurs in persisting the Attestation
* Certificate * Certificate
*/ */
public boolean saveAttestationCertificate(final CertificateRepository certificateRepository, public boolean saveAttestationCertificate(final CertificateRepository certificateRepository,
final byte[] derEncodedAttestationCertificate, final byte[] derEncodedAttestationCertificate,
final EndorsementCredential endorsementCredential, final EndorsementCredential endorsementCredential,
final List<PlatformCredential> platformCredentials, final List<PlatformCredential> platformCredentials,
final Device device, boolean isLDevID) { final Device device,
final boolean isLDevID) {
List<IssuedAttestationCertificate> issuedAc; List<IssuedAttestationCertificate> issuedAc;
boolean generateCertificate = true; boolean generateCertificate = true;
PolicyRepository scp = getPolicyRepository(); PolicyRepository scp = getPolicyRepository();
@ -277,23 +281,22 @@ public class AbstractProcessor {
policySettings = scp.findByName("Default"); policySettings = scp.findByName("Default");
Sort sortCriteria = Sort.by(Sort.Direction.DESC, "endValidity"); 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() generateCertificate = isLDevID ? policySettings.isIssueDevIdCertificate()
: policySettings.isIssueAttestationCertificate(); : policySettings.isIssueAttestationCertificate();
if (issuedAc != null && issuedAc.size() > 0 && (isLDevID ? policySettings.isDevIdExpirationFlag() if (issuedAc != null && issuedAc.size() > 0
&& (isLDevID ? policySettings.isDevIdExpirationFlag()
: policySettings.isGenerateOnExpiration())) { : policySettings.isGenerateOnExpiration())) {
if (issuedAc.get(0).getEndValidity().after(currentDate)) { if (issuedAc.get(0).getEndValidity().after(currentDate)) {
// so the issued AC is not expired // so the issued AC is not expired
// however are we within the threshold // however are we within the threshold
days = ProvisionUtils.daysBetween(currentDate, issuedAc.get(0).getEndValidity()); days = ProvisionUtils.daysBetween(currentDate, issuedAc.get(0).getEndValidity());
if (days < Integer.parseInt(isLDevID ? policySettings.getDevIdReissueThreshold() generateCertificate =
: policySettings.getReissueThreshold())) { days < Integer.parseInt(isLDevID ? policySettings.getDevIdReissueThreshold()
generateCertificate = true; : policySettings.getReissueThreshold());
} else {
generateCertificate = false;
}
} }
} }
} }
@ -314,7 +317,7 @@ public class AbstractProcessor {
} }
private List<PlatformCredential> getPlatformCredentials(final CertificateRepository certificateRepository, private List<PlatformCredential> getPlatformCredentials(final CertificateRepository certificateRepository,
final EndorsementCredential ec) { final EndorsementCredential ec) {
List<PlatformCredential> credentials = null; List<PlatformCredential> credentials = null;
if (ec == null) { if (ec == null) {

View File

@ -1,6 +1,5 @@
package hirs.attestationca.persist.provision; package hirs.attestationca.persist.provision;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.InvalidProtocolBufferException;
import hirs.attestationca.configuration.provisionerTpm2.ProvisionerTpm2; import hirs.attestationca.configuration.provisionerTpm2.ProvisionerTpm2;
import hirs.attestationca.persist.entity.manager.CertificateRepository; import hirs.attestationca.persist.entity.manager.CertificateRepository;
@ -30,22 +29,23 @@ import java.util.List;
@Log4j2 @Log4j2
public class CertificateRequestProcessor extends AbstractProcessor { public class CertificateRequestProcessor extends AbstractProcessor {
private SupplyChainValidationService supplyChainValidationService; private final SupplyChainValidationService supplyChainValidationService;
private CertificateRepository certificateRepository; private final CertificateRepository certificateRepository;
private DeviceRepository deviceRepository; private final DeviceRepository deviceRepository;
private X509Certificate acaCertificate; private final X509Certificate acaCertificate;
private TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository; private final TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository;
/** /**
* Constructor. * Constructor.
* @param supplyChainValidationService object that is used to run provisioning *
* @param certificateRepository db connector for all certificates. * @param supplyChainValidationService object that is used to run provisioning
* @param deviceRepository database connector for Devices. * @param certificateRepository db connector for all certificates.
* @param privateKey private key used for communication authentication * @param deviceRepository database connector for Devices.
* @param acaCertificate object used to create credential * @param privateKey private key used for communication authentication
* @param validDays int for the time in which a certificate is valid. * @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 tpm2ProvisionerStateRepository db connector for provisioner state.
* @param policyRepository db connector for policies. * @param policyRepository db connector for policies.
*/ */
public CertificateRequestProcessor(final SupplyChainValidationService supplyChainValidationService, public CertificateRequestProcessor(final SupplyChainValidationService supplyChainValidationService,
final CertificateRepository certificateRepository, 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 // We validated the nonce and made use of the identity claim so state can be deleted
tpm2ProvisionerStateRepository.delete(tpm2ProvisionerState); tpm2ProvisionerStateRepository.delete(tpm2ProvisionerState);
boolean generateAtt = saveAttestationCertificate(certificateRepository,
boolean generateAtt = saveAttestationCertificate(certificateRepository, derEncodedAttestationCertificate, derEncodedAttestationCertificate,
endorsementCredential, platformCredentials, device, false); endorsementCredential, platformCredentials, device, false);
boolean generateLDevID = saveAttestationCertificate(certificateRepository, derEncodedLdevidCertificate, boolean generateLDevID =
endorsementCredential, platformCredentials, device, true); saveAttestationCertificate(certificateRepository, derEncodedLdevidCertificate,
endorsementCredential, platformCredentials, device, true);
ProvisionerTpm2.CertificateResponse.Builder builder = ProvisionerTpm2.CertificateResponse. ProvisionerTpm2.CertificateResponse.Builder builder = ProvisionerTpm2.CertificateResponse.
newBuilder().setStatus(ProvisionerTpm2.ResponseStatus.PASS); newBuilder().setStatus(ProvisionerTpm2.ResponseStatus.PASS);
@ -184,8 +185,7 @@ public class CertificateRequestProcessor extends AbstractProcessor {
ProvisionerTpm2.CertificateResponse response = builder.build(); ProvisionerTpm2.CertificateResponse response = builder.build();
return response.toByteArray(); return response.toByteArray();
} } else {
else {
byte[] derEncodedAttestationCertificate = ProvisionUtils.getDerEncodedCertificate( byte[] derEncodedAttestationCertificate = ProvisionUtils.getDerEncodedCertificate(
attestationCertificate); attestationCertificate);
String pemEncodedAttestationCertificate = ProvisionUtils.getPemEncodedCertificate( String pemEncodedAttestationCertificate = ProvisionUtils.getPemEncodedCertificate(
@ -197,7 +197,8 @@ public class CertificateRequestProcessor extends AbstractProcessor {
ProvisionerTpm2.CertificateResponse.Builder builder = ProvisionerTpm2.CertificateResponse. ProvisionerTpm2.CertificateResponse.Builder builder = ProvisionerTpm2.CertificateResponse.
newBuilder().setStatus(ProvisionerTpm2.ResponseStatus.PASS); newBuilder().setStatus(ProvisionerTpm2.ResponseStatus.PASS);
boolean generateAtt = saveAttestationCertificate(certificateRepository, derEncodedAttestationCertificate, boolean generateAtt = saveAttestationCertificate(certificateRepository,
derEncodedAttestationCertificate,
endorsementCredential, platformCredentials, device, false); endorsementCredential, platformCredentials, device, false);
if (generateAtt) { if (generateAtt) {
builder = builder.setCertificate(pemEncodedAttestationCertificate); builder = builder.setCertificate(pemEncodedAttestationCertificate);
@ -218,7 +219,7 @@ public class CertificateRequestProcessor extends AbstractProcessor {
} }
} else { } else {
log.error("Could not process credential request. Invalid nonce provided: " 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."); throw new CertificateProcessingException("Invalid nonce given in request by client.");
} }
} }

View File

@ -1,6 +1,5 @@
package hirs.attestationca.persist.provision; package hirs.attestationca.persist.provision;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.google.protobuf.ByteString; import com.google.protobuf.ByteString;
import hirs.attestationca.configuration.provisionerTpm2.ProvisionerTpm2; import hirs.attestationca.configuration.provisionerTpm2.ProvisionerTpm2;
import hirs.attestationca.persist.entity.manager.CertificateRepository; import hirs.attestationca.persist.entity.manager.CertificateRepository;
@ -69,27 +68,36 @@ import java.util.regex.Pattern;
@Log4j2 @Log4j2
public class IdentityClaimProcessor extends AbstractProcessor { public class IdentityClaimProcessor extends AbstractProcessor {
private static final String PCR_QUOTE_MASK = "0,1,2,3,4,5,6,7,8,9,10,11,12,13,"
+ "14,15,16,17,18,19,20,21,22,23";
private static final int NUM_OF_VARIABLES = 5;
/** /**
* Number of bytes to include in the TPM2.0 nonce. * Number of bytes to include in the TPM2.0 nonce.
*/ */
public static final int NONCE_LENGTH = 20; public static final int NONCE_LENGTH = 20;
private static final String PCR_QUOTE_MASK = "0,1,2,3,4,5,6,7,8,9,10,11,12,13,"
+ "14,15,16,17,18,19,20,21,22,23";
private static final int NUM_OF_VARIABLES = 5;
private static final int MAC_BYTES = 6; private static final int MAC_BYTES = 6;
private SupplyChainValidationService supplyChainValidationService; private final SupplyChainValidationService supplyChainValidationService;
private CertificateRepository certificateRepository; private final CertificateRepository certificateRepository;
private ComponentResultRepository componentResultRepository; private final ComponentResultRepository componentResultRepository;
private ComponentInfoRepository componentInfoRepository; private final ComponentInfoRepository componentInfoRepository;
private ReferenceManifestRepository referenceManifestRepository; private final ReferenceManifestRepository referenceManifestRepository;
private ReferenceDigestValueRepository referenceDigestValueRepository; private final ReferenceDigestValueRepository referenceDigestValueRepository;
private DeviceRepository deviceRepository; private final DeviceRepository deviceRepository;
private TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository; private final TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository;
/** /**
* Constructor. * 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( public IdentityClaimProcessor(
final SupplyChainValidationService supplyChainValidationService, final SupplyChainValidationService supplyChainValidationService,
@ -116,8 +124,8 @@ public class IdentityClaimProcessor extends AbstractProcessor {
* Basic implementation of the ACA processIdentityClaimTpm2 method. Parses the claim, * Basic implementation of the ACA processIdentityClaimTpm2 method. Parses the claim,
* stores the device info, performs supply chain validation, generates a nonce, * stores the device info, performs supply chain validation, generates a nonce,
* and wraps that nonce with the make credential process before returning it to the client. * and wraps that nonce with the make credential process before returning it to the client.
* attCert.setPcrValues(pcrValues); * attCert.setPcrValues(pcrValues);
*
* @param identityClaim the request to process, cannot be null * @param identityClaim the request to process, cannot be null
* @return an identity claim response for the specified request containing a wrapped blob * @return an identity claim response for the specified request containing a wrapped blob
*/ */
@ -147,7 +155,7 @@ public class IdentityClaimProcessor extends AbstractProcessor {
} }
} }
ByteString blobStr = ByteString.copyFrom(new byte[]{}); ByteString blobStr = ByteString.copyFrom(new byte[] {});
if (validationResult == AppraisalStatus.Status.PASS) { if (validationResult == AppraisalStatus.Status.PASS) {
RSAPublicKey akPub = ProvisionUtils.parsePublicKey(claim.getAkPublicArea().toByteArray()); RSAPublicKey akPub = ProvisionUtils.parsePublicKey(claim.getAkPublicArea().toByteArray());
byte[] nonce = ProvisionUtils.generateRandomBytes(NONCE_LENGTH); byte[] nonce = ProvisionUtils.generateRandomBytes(NONCE_LENGTH);
@ -157,8 +165,8 @@ public class IdentityClaimProcessor extends AbstractProcessor {
String pcrQuoteMask = PCR_QUOTE_MASK; String pcrQuoteMask = PCR_QUOTE_MASK;
String strNonce = HexUtils.byteArrayToHexString(nonce); String strNonce = HexUtils.byteArrayToHexString(nonce);
log.info("Sending nonce: " + strNonce); log.info("Sending nonce: {}", strNonce);
log.info("Persisting claim of length: " + identityClaim.length); log.info("Persisting claim of length: {}", identityClaim.length);
tpm2ProvisionerStateRepository.save(new TPM2ProvisionerState(nonce, identityClaim)); tpm2ProvisionerStateRepository.save(new TPM2ProvisionerState(nonce, identityClaim));
@ -173,8 +181,7 @@ public class IdentityClaimProcessor extends AbstractProcessor {
.build(); .build();
return response.toByteArray(); return response.toByteArray();
} else { } else {
log.error("Supply chain validation did not succeed. Result is: " log.error("Supply chain validation did not succeed. Result is: {}", validationResult);
+ validationResult);
// empty response // empty response
ProvisionerTpm2.IdentityClaimResponse response ProvisionerTpm2.IdentityClaimResponse response
= ProvisionerTpm2.IdentityClaimResponse.newBuilder() = ProvisionerTpm2.IdentityClaimResponse.newBuilder()
@ -195,7 +202,8 @@ public class IdentityClaimProcessor extends AbstractProcessor {
private AppraisalStatus.Status doSupplyChainValidation( private AppraisalStatus.Status doSupplyChainValidation(
final ProvisionerTpm2.IdentityClaim claim, final PublicKey ekPub) { final ProvisionerTpm2.IdentityClaim claim, final PublicKey ekPub) {
// attempt to find an endorsement credential to validate // attempt to find an endorsement credential to validate
EndorsementCredential endorsementCredential = parseEcFromIdentityClaim(claim, ekPub, certificateRepository); EndorsementCredential endorsementCredential =
parseEcFromIdentityClaim(claim, ekPub, certificateRepository);
// attempt to find platform credentials to validate // attempt to find platform credentials to validate
List<PlatformCredential> platformCredentials = parsePcsFromIdentityClaim(claim, List<PlatformCredential> platformCredentials = parsePcsFromIdentityClaim(claim,
@ -283,10 +291,10 @@ public class IdentityClaimProcessor extends AbstractProcessor {
/** /**
* Converts a protobuf DeviceInfo object to a HIRS Utils DeviceInfoReport object. * Converts a protobuf DeviceInfo object to a HIRS Utils DeviceInfoReport object.
*
* @param claim the protobuf serialized identity claim containing the device info * @param claim the protobuf serialized identity claim containing the device info
* @return a HIRS Utils DeviceInfoReport representation of device info * @return a HIRS Utils DeviceInfoReport representation of device info
*/ */
@SuppressWarnings("methodlength")
private DeviceInfoReport parseDeviceInfo(final ProvisionerTpm2.IdentityClaim claim) private DeviceInfoReport parseDeviceInfo(final ProvisionerTpm2.IdentityClaim claim)
throws NoSuchAlgorithmException { throws NoSuchAlgorithmException {
ProvisionerTpm2.DeviceInfo dv = claim.getDv(); ProvisionerTpm2.DeviceInfo dv = claim.getDv();
@ -348,87 +356,87 @@ public class IdentityClaimProcessor extends AbstractProcessor {
String defaultClientName = String.format("%s_%s", String defaultClientName = String.format("%s_%s",
dv.getHw().getManufacturer(), dv.getHw().getManufacturer(),
dv.getHw().getProductName()); dv.getHw().getProductName());
BaseReferenceManifest dbBaseRim = null; BaseReferenceManifest baseRim = null;
SupportReferenceManifest support = null; SupportReferenceManifest supportRim = null;
EventLogMeasurements measurements; EventLogMeasurements integrityMeasurements;
boolean isReplacement = false; boolean isReplacement = false;
String replacementRimId = ""; String replacementRimId = "";
String tagId = ""; String tagId = "";
String fileName = ""; String fileName = "";
Pattern pattern = Pattern.compile("([^\\s]+(\\.(?i)(rimpcr|rimel|bin|log))$)"); Pattern pattern = Pattern.compile("([^\\s]+(\\.(?i)(rimpcr|rimel|bin|log))$)");
Matcher matcher; Matcher matcher;
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
if (dv.getSwidfileCount() > 0) { if (dv.getSwidfileCount() > 0) {
for (ByteString swidFile : dv.getSwidfileList()) { for (ByteString swidFile : dv.getSwidfileList()) {
try { try {
dbBaseRim = (BaseReferenceManifest) referenceManifestRepository baseRim = (BaseReferenceManifest) referenceManifestRepository
.findByBase64Hash(Base64.getEncoder() .findByBase64Hash(Base64.getEncoder()
.encodeToString(messageDigest .encodeToString(messageDigest
.digest(swidFile.toByteArray()))); .digest(swidFile.toByteArray())));
if (dbBaseRim == null) { if (baseRim == null) {
/* /*
Either the swidFile does not have a corresponding base RIM in the backend Either the swidFile does not have a corresponding base RIM in the backend
or it was deleted. Check if there is a replacement by comparing tagId against or it was deleted. Check if there is a replacement by comparing tagId against
all other base RIMs, and then set the corresponding support rim's deviceName. all other base RIMs, and then set the corresponding support rim's deviceName.
*/ */
dbBaseRim = new BaseReferenceManifest( baseRim = new BaseReferenceManifest(
String.format("%s.swidtag", String.format("%s.swidtag",
defaultClientName), defaultClientName),
swidFile.toByteArray()); swidFile.toByteArray());
List<BaseReferenceManifest> baseRims = referenceManifestRepository.findAllBaseRims(); List<BaseReferenceManifest> baseRims = referenceManifestRepository.findAllBaseRims();
for (BaseReferenceManifest bRim : baseRims) { for (BaseReferenceManifest bRim : baseRims) {
if (bRim.getTagId().equals(dbBaseRim.getTagId())) { if (bRim.getTagId().equals(baseRim.getTagId())) {
dbBaseRim = bRim; baseRim = bRim;
replacementRimId = dbBaseRim.getAssociatedRim().toString(); replacementRimId = baseRim.getAssociatedRim().toString();
isReplacement = true; isReplacement = true;
break; break;
} }
} }
dbBaseRim.setDeviceName(dv.getNw().getHostname()); baseRim.setDeviceName(dv.getNw().getHostname());
this.referenceManifestRepository.save(dbBaseRim); this.referenceManifestRepository.save(baseRim);
} else if (dbBaseRim.isArchived()) { } else if (baseRim.isArchived()) {
/* /*
This block accounts for RIMs that may have been soft-deleted (archived) This block accounts for RIMs that may have been soft-deleted (archived)
in an older version of the ACA. in an older version of the ACA.
*/ */
List<ReferenceManifest> rims = referenceManifestRepository.findByArchiveFlag(false); List<ReferenceManifest> rims = referenceManifestRepository.findByArchiveFlag(false);
for (ReferenceManifest rim : rims) { for (ReferenceManifest rim : rims) {
if (rim.isBase() && rim.getTagId().equals(dbBaseRim.getTagId()) && if (rim.isBase() && rim.getTagId().equals(baseRim.getTagId())
rim.getCreateTime().after(dbBaseRim.getCreateTime())) { && rim.getCreateTime().after(baseRim.getCreateTime())) {
dbBaseRim.setDeviceName(null); baseRim.setDeviceName(null);
dbBaseRim = (BaseReferenceManifest) rim; baseRim = (BaseReferenceManifest) rim;
dbBaseRim.setDeviceName(dv.getNw().getHostname()); baseRim.setDeviceName(dv.getNw().getHostname());
} }
} }
if (dbBaseRim.isArchived()) { if (baseRim.isArchived()) {
throw new Exception("Unable to locate an unarchived base RIM."); throw new Exception("Unable to locate an unarchived base RIM.");
} else { } else {
this.referenceManifestRepository.save(dbBaseRim); this.referenceManifestRepository.save(baseRim);
} }
} else { } else {
dbBaseRim.setDeviceName(dv.getNw().getHostname()); baseRim.setDeviceName(dv.getNw().getHostname());
this.referenceManifestRepository.save(dbBaseRim); this.referenceManifestRepository.save(baseRim);
} }
tagId = dbBaseRim.getTagId(); tagId = baseRim.getTagId();
} catch (UnmarshalException e) { } catch (UnmarshalException e) {
log.error(e); log.error(e);
} catch (Exception ex) { } 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 { } else {
log.warn(String.format("%s did not send swid tag file...", log.warn("{} did not send swid tag file...", dv.getNw().getHostname());
dv.getNw().getHostname()));
} }
if (dv.getLogfileCount() > 0) { if (dv.getLogfileCount() > 0) {
for (ByteString logFile : dv.getLogfileList()) { for (ByteString logFile : dv.getLogfileList()) {
try { try {
support = (SupportReferenceManifest) referenceManifestRepository.findByHexDecHashAndRimType( supportRim =
(SupportReferenceManifest) referenceManifestRepository.findByHexDecHashAndRimType(
Hex.encodeHexString(messageDigest.digest(logFile.toByteArray())), Hex.encodeHexString(messageDigest.digest(logFile.toByteArray())),
ReferenceManifest.SUPPORT_RIM); ReferenceManifest.SUPPORT_RIM);
if (support == null) { if (supportRim == null) {
/* /*
Either the logFile does not have a corresponding support RIM in the backend Either the logFile does not have a corresponding support RIM in the backend
or it was deleted. The support RIM for a replacement base RIM is handled or it was deleted. The support RIM for a replacement base RIM is handled
@ -438,97 +446,98 @@ public class IdentityClaimProcessor extends AbstractProcessor {
Optional<ReferenceManifest> replacementRim = Optional<ReferenceManifest> replacementRim =
referenceManifestRepository.findById(UUID.fromString(replacementRimId)); referenceManifestRepository.findById(UUID.fromString(replacementRimId));
if (replacementRim.isPresent()) { if (replacementRim.isPresent()) {
support = (SupportReferenceManifest) replacementRim.get(); supportRim = (SupportReferenceManifest) replacementRim.get();
support.setDeviceName(dv.getNw().getHostname()); supportRim.setDeviceName(dv.getNw().getHostname());
} else { } else {
throw new Exception("Unable to locate support RIM " + replacementRimId); throw new Exception("Unable to locate support RIM " + replacementRimId);
} }
} else { } else {
support = new SupportReferenceManifest( supportRim = new SupportReferenceManifest(
String.format("%s.rimel", String.format("%s.rimel",
defaultClientName), defaultClientName),
logFile.toByteArray()); logFile.toByteArray());
// this is a validity check // this is a validity check
new TCGEventLog(support.getRimBytes()); new TCGEventLog(supportRim.getRimBytes());
// no issues, continue // no issues, continue
support.setPlatformManufacturer(dv.getHw().getManufacturer()); supportRim.setPlatformManufacturer(dv.getHw().getManufacturer());
support.setPlatformModel(dv.getHw().getProductName()); supportRim.setPlatformModel(dv.getHw().getProductName());
support.setFileName(String.format("%s_[%s].rimel", defaultClientName, supportRim.setFileName(String.format("%s_[%s].rimel", defaultClientName,
support.getHexDecHash().substring( supportRim.getHexDecHash().substring(
support.getHexDecHash().length() - NUM_OF_VARIABLES))); supportRim.getHexDecHash().length() - NUM_OF_VARIABLES)));
} }
support.setDeviceName(dv.getNw().getHostname()); supportRim.setDeviceName(dv.getNw().getHostname());
this.referenceManifestRepository.save(support); this.referenceManifestRepository.save(supportRim);
} else if (support.isArchived()) { } else if (supportRim.isArchived()) {
/* /*
This block accounts for RIMs that may have been soft-deleted (archived) This block accounts for RIMs that may have been soft-deleted (archived)
in an older version of the ACA. in an older version of the ACA.
*/ */
List<ReferenceManifest> rims = referenceManifestRepository.findByArchiveFlag(false); List<ReferenceManifest> rims = referenceManifestRepository.findByArchiveFlag(false);
for (ReferenceManifest rim : rims) { for (ReferenceManifest rim : rims) {
if (rim.isSupport() && if (rim.isSupport()
rim.getTagId().equals(support.getTagId()) && && rim.getTagId().equals(supportRim.getTagId())
rim.getCreateTime().after(support.getCreateTime())) { && rim.getCreateTime().after(supportRim.getCreateTime())) {
support.setDeviceName(null); supportRim.setDeviceName(null);
support = (SupportReferenceManifest) rim; supportRim = (SupportReferenceManifest) rim;
support.setDeviceName(dv.getNw().getHostname()); supportRim.setDeviceName(dv.getNw().getHostname());
} }
} }
if (support.isArchived()) { if (supportRim.isArchived()) {
throw new Exception("Unable to locate an unarchived support RIM."); throw new Exception("Unable to locate an unarchived support RIM.");
} else { } else {
this.referenceManifestRepository.save(support); this.referenceManifestRepository.save(supportRim);
} }
} else { } else {
support.setDeviceName(dv.getNw().getHostname()); supportRim.setDeviceName(dv.getNw().getHostname());
this.referenceManifestRepository.save(support); this.referenceManifestRepository.save(supportRim);
} }
} catch (IOException ioEx) { } catch (IOException ioEx) {
log.error(ioEx); log.error(ioEx);
} catch (Exception ex) { } 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 { } else {
log.warn(String.format("%s did not send support RIM file...", log.warn("{} did not send support RIM file...", dv.getNw().getHostname());
dv.getNw().getHostname()));
} }
//update Support RIMs and Base RIMs. //update Support RIMs and Base RIMs.
for (ByteString swidFile : dv.getSwidfileList()) { for (ByteString swidFile : dv.getSwidfileList()) {
dbBaseRim = (BaseReferenceManifest) referenceManifestRepository baseRim = (BaseReferenceManifest) referenceManifestRepository
.findByBase64Hash(Base64.getEncoder().encodeToString(messageDigest.digest( .findByBase64Hash(Base64.getEncoder().encodeToString(messageDigest.digest(
swidFile.toByteArray()))); swidFile.toByteArray())));
if (dbBaseRim != null) { if (baseRim != null) {
// get file name to use // get file name to use
for (SwidResource swid : dbBaseRim.getFileResources()) { for (SwidResource swid : baseRim.getFileResources()) {
matcher = pattern.matcher(swid.getName()); matcher = pattern.matcher(swid.getName());
if (matcher.matches()) { if (matcher.matches()) {
//found the file name //found the file name
int dotIndex = swid.getName().lastIndexOf("."); int dotIndex = swid.getName().lastIndexOf(".");
fileName = swid.getName().substring(0, dotIndex); fileName = swid.getName().substring(0, dotIndex);
dbBaseRim.setFileName(String.format("%s.swidtag", baseRim.setFileName(String.format("%s.swidtag",
fileName)); fileName));
} }
// now update support rim // now update support rim
SupportReferenceManifest dbSupport = (SupportReferenceManifest) referenceManifestRepository SupportReferenceManifest dbSupport =
.findByHexDecHashAndRimType(swid.getHashValue(), ReferenceManifest.SUPPORT_RIM); (SupportReferenceManifest) referenceManifestRepository
.findByHexDecHashAndRimType(swid.getHashValue(),
ReferenceManifest.SUPPORT_RIM);
if (dbSupport != null) { if (dbSupport != null) {
dbSupport.setFileName(swid.getName()); dbSupport.setFileName(swid.getName());
dbSupport.setSwidTagVersion(dbBaseRim.getSwidTagVersion()); dbSupport.setSwidTagVersion(baseRim.getSwidTagVersion());
dbSupport.setTagId(dbBaseRim.getTagId()); dbSupport.setTagId(baseRim.getTagId());
dbSupport.setSwidTagVersion(dbBaseRim.getSwidTagVersion()); dbSupport.setSwidTagVersion(baseRim.getSwidTagVersion());
dbSupport.setSwidVersion(dbBaseRim.getSwidVersion()); dbSupport.setSwidVersion(baseRim.getSwidVersion());
dbSupport.setSwidPatch(dbBaseRim.isSwidPatch()); dbSupport.setSwidPatch(baseRim.isSwidPatch());
dbSupport.setSwidSupplemental(dbBaseRim.isSwidSupplemental()); dbSupport.setSwidSupplemental(baseRim.isSwidSupplemental());
dbBaseRim.setAssociatedRim(dbSupport.getId()); baseRim.setAssociatedRim(dbSupport.getId());
dbSupport.setUpdated(true); dbSupport.setUpdated(true);
dbSupport.setAssociatedRim(dbBaseRim.getId()); dbSupport.setAssociatedRim(baseRim.getId());
this.referenceManifestRepository.save(dbSupport); this.referenceManifestRepository.save(dbSupport);
} }
} }
this.referenceManifestRepository.save(dbBaseRim); this.referenceManifestRepository.save(baseRim);
} }
} }
@ -539,40 +548,40 @@ public class IdentityClaimProcessor extends AbstractProcessor {
fileName = String.format("%s.measurement", fileName = String.format("%s.measurement",
dv.getNw().getHostname()); dv.getNw().getHostname());
try { try {
EventLogMeasurements temp = new EventLogMeasurements(fileName, EventLogMeasurements deviceLiveLog = new EventLogMeasurements(fileName,
dv.getLivelog().toByteArray()); dv.getLivelog().toByteArray());
// find previous version. // find previous version.
measurements = referenceManifestRepository integrityMeasurements = referenceManifestRepository
.byMeasurementDeviceName(dv.getNw().getHostname()); .byMeasurementDeviceName(dv.getNw().getHostname());
if (measurements != null) { if (integrityMeasurements != null) {
// Find previous log and delete it // Find previous log and delete it
referenceManifestRepository.delete(measurements); referenceManifestRepository.delete(integrityMeasurements);
} }
List<BaseReferenceManifest> baseRims = referenceManifestRepository List<BaseReferenceManifest> baseRims = referenceManifestRepository
.getBaseByManufacturerModel(dv.getHw().getManufacturer(), .getBaseByManufacturerModel(dv.getHw().getManufacturer(),
dv.getHw().getProductName()); dv.getHw().getProductName());
measurements = temp; integrityMeasurements = deviceLiveLog;
measurements.setPlatformManufacturer(dv.getHw().getManufacturer()); integrityMeasurements.setPlatformManufacturer(dv.getHw().getManufacturer());
measurements.setPlatformModel(dv.getHw().getProductName()); integrityMeasurements.setPlatformModel(dv.getHw().getProductName());
if (tagId != null && !tagId.trim().isEmpty()) { if (tagId != null && !tagId.trim().isEmpty()) {
measurements.setTagId(tagId); integrityMeasurements.setTagId(tagId);
} }
measurements.setDeviceName(dv.getNw().getHostname()); integrityMeasurements.setDeviceName(dv.getNw().getHostname());
measurements.archive(); integrityMeasurements.archive();
this.referenceManifestRepository.save(measurements); this.referenceManifestRepository.save(integrityMeasurements);
for (BaseReferenceManifest baseRim : baseRims) { for (BaseReferenceManifest bRim : baseRims) {
if (baseRim != null) { if (bRim != null) {
// pull the base versions of the swidtag and rimel and set the // pull the base versions of the swidtag and rimel and set the
// event log hash for use during provision // event log hash for use during provision
SupportReferenceManifest sBaseRim = referenceManifestRepository SupportReferenceManifest sBaseRim = referenceManifestRepository
.getSupportRimEntityById(baseRim.getAssociatedRim()); .getSupportRimEntityById(bRim.getAssociatedRim());
baseRim.setEventLogHash(temp.getHexDecHash()); bRim.setEventLogHash(deviceLiveLog.getHexDecHash());
sBaseRim.setEventLogHash(temp.getHexDecHash()); sBaseRim.setEventLogHash(deviceLiveLog.getHexDecHash());
referenceManifestRepository.save(baseRim); referenceManifestRepository.save(bRim);
referenceManifestRepository.save(sBaseRim); referenceManifestRepository.save(sBaseRim);
} }
} }
@ -580,11 +589,10 @@ public class IdentityClaimProcessor extends AbstractProcessor {
log.error(ioEx); log.error(ioEx);
} }
} else { } else {
log.warn(String.format("%s did not send bios measurement log...", log.warn("{} did not send bios measurement log...", dv.getNw().getHostname());
dv.getNw().getHostname()));
} }
// Get TPM info, currently unimplemented // Get TPM info, currently unimplemented
TPMInfo tpmInfo = new TPMInfo(DeviceInfoEnums.NOT_SPECIFIED, TPMInfo tpmInfo = new TPMInfo(DeviceInfoEnums.NOT_SPECIFIED,
(short) 0, (short) 0,
(short) 0, (short) 0,
@ -608,11 +616,11 @@ public class IdentityClaimProcessor extends AbstractProcessor {
List<SupportReferenceManifest> patchRims = new ArrayList<>(); List<SupportReferenceManifest> patchRims = new ArrayList<>();
List<SupportReferenceManifest> dbSupportRims = this.referenceManifestRepository List<SupportReferenceManifest> dbSupportRims = this.referenceManifestRepository
.getSupportByManufacturerModel(manufacturer, model); .getSupportByManufacturerModel(manufacturer, model);
List<ReferenceDigestValue> sourcedValues = referenceDigestValueRepository List<ReferenceDigestValue> expectedValues = referenceDigestValueRepository
.findByManufacturerAndModel(manufacturer, model); .findByManufacturerAndModel(manufacturer, model);
Map<String, ReferenceDigestValue> digestValueMap = new HashMap<>(); Map<String, ReferenceDigestValue> digestValueMap = new HashMap<>();
sourcedValues.stream().forEach((rdv) -> { expectedValues.stream().forEach((rdv) -> {
digestValueMap.put(rdv.getDigestValue(), rdv); digestValueMap.put(rdv.getDigestValue(), rdv);
}); });
@ -628,11 +636,12 @@ public class IdentityClaimProcessor extends AbstractProcessor {
} }
if (baseSupportRim != null if (baseSupportRim != null
&& referenceDigestValueRepository.findBySupportRimHash(baseSupportRim.getHexDecHash()).isEmpty()) { && referenceDigestValueRepository.findBySupportRimHash(baseSupportRim.getHexDecHash())
.isEmpty()) {
try { try {
TCGEventLog logProcessor = new TCGEventLog(baseSupportRim.getRimBytes()); TCGEventLog eventLog = new TCGEventLog(baseSupportRim.getRimBytes());
ReferenceDigestValue rdv; ReferenceDigestValue rdv;
for (TpmPcrEvent tpe : logProcessor.getEventList()) { for (TpmPcrEvent tpe : eventLog.getEventList()) {
rdv = new ReferenceDigestValue(baseSupportRim.getAssociatedRim(), rdv = new ReferenceDigestValue(baseSupportRim.getAssociatedRim(),
baseSupportRim.getId(), manufacturer, model, tpe.getPcrIndex(), baseSupportRim.getId(), manufacturer, model, tpe.getPcrIndex(),
tpe.getEventDigestStr(), baseSupportRim.getHexDecHash(), tpe.getEventDigestStr(), baseSupportRim.getHexDecHash(),
@ -644,8 +653,8 @@ public class IdentityClaimProcessor extends AbstractProcessor {
// since I have the base already I don't have to care about the backward // since I have the base already I don't have to care about the backward
// linkage // linkage
for (SupportReferenceManifest supplemental : supplementalRims) { for (SupportReferenceManifest supplemental : supplementalRims) {
logProcessor = new TCGEventLog(supplemental.getRimBytes()); eventLog = new TCGEventLog(supplemental.getRimBytes());
for (TpmPcrEvent tpe : logProcessor.getEventList()) { for (TpmPcrEvent tpe : eventLog.getEventList()) {
// all RDVs will have the same base rim // all RDVs will have the same base rim
rdv = new ReferenceDigestValue(baseSupportRim.getAssociatedRim(), rdv = new ReferenceDigestValue(baseSupportRim.getAssociatedRim(),
supplemental.getId(), manufacturer, model, tpe.getPcrIndex(), supplemental.getId(), manufacturer, model, tpe.getPcrIndex(),
@ -679,16 +688,15 @@ public class IdentityClaimProcessor extends AbstractProcessor {
ReferenceDigestValue dbRdv; ReferenceDigestValue dbRdv;
String patchedValue; String patchedValue;
for (SupportReferenceManifest patch : patchRims) { for (SupportReferenceManifest patch : patchRims) {
logProcessor = new TCGEventLog(patch.getRimBytes()); eventLog = new TCGEventLog(patch.getRimBytes());
for (TpmPcrEvent tpe : logProcessor.getEventList()) { for (TpmPcrEvent tpe : eventLog.getEventList()) {
patchedValue = tpe.getEventDigestStr(); patchedValue = tpe.getEventDigestStr();
dbRdv = digestValueMap.get(patchedValue); dbRdv = digestValueMap.get(patchedValue);
if (dbRdv == null) { if (dbRdv == null) {
log.error(String.format("Patching value does not exist (%s)", log.error("Patching value does not exist ({})", patchedValue);
patchedValue));
} else { } else {
// WIP - Until we get patch examples // WIP - Until we get patch examples
dbRdv.setPatched(true); dbRdv.setPatched(true);
} }
} }
@ -721,7 +729,7 @@ public class IdentityClaimProcessor extends AbstractProcessor {
} }
private int handleDeviceComponents(final String hostName, final String paccorString) { private int handleDeviceComponents(final String hostName, final String paccorString) {
int deviceComponents = 0 ; int deviceComponents = 0;
Map<Integer, ComponentInfo> componentInfoMap = new HashMap<>(); Map<Integer, ComponentInfo> componentInfoMap = new HashMap<>();
try { try {
List<ComponentInfo> componentInfos = SupplyChainCredentialValidator List<ComponentInfo> componentInfos = SupplyChainCredentialValidator

Some files were not shown because too many files have changed in this diff Show More