issue_847: Applied formatting changes to entire CA module. Reduced errors by 100.

This commit is contained in:
TheSilentCoder 2024-10-21 13:46:57 -04:00
parent 99188f17c1
commit b3d1bd8fcc
88 changed files with 1713 additions and 1773 deletions

View File

@ -70,10 +70,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 +82,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_ProvisionerTPM2/src'
}
} }
}
} }
test { test {

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

@ -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 a
* typical String that can be searched by Hibernate without transformation. * 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,17 +42,17 @@ 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 a
* typical String that can be searched by Hibernate without transformation. * 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
*/ */

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

@ -30,7 +30,7 @@ public interface IDevIDCertificateRepository extends JpaRepository<IDevIDCertifi
Page<IDevIDCertificate> findByArchiveFlag(boolean archiveFlag, Pageable pageable); Page<IDevIDCertificate> findByArchiveFlag(boolean archiveFlag, Pageable pageable);
// /** // /**
// * Query that retrieves a list of IDevId certificates using the provided subject. // * Query that retrieves a list of IDevId certificates using the provided subject.
// * // *
// * @param subject string representation of the subject // * @param subject string representation of the subject
@ -56,7 +56,8 @@ public interface IDevIDCertificateRepository extends JpaRepository<IDevIDCertifi
// List<IDevIDCertificate> findBySubjectAndArchiveFlag(String subject, boolean archiveFlag); // List<IDevIDCertificate> findBySubjectAndArchiveFlag(String subject, boolean archiveFlag);
// //
// /** // /**
// * Query that retrieves a sorted list of IDevId certificates using the provided subject and archive flag. // * Query that retrieves a sorted list of IDevId certificates using the provided subject
// * and archive flag.
// * // *
// * @param subject string representation of the subject // * @param subject string representation of the subject
// * @param archiveFlag archive flag // * @param archiveFlag archive flag
@ -79,5 +80,6 @@ public interface IDevIDCertificateRepository extends JpaRepository<IDevIDCertifi
// * @param archiveFlag archive flag // * @param archiveFlag archive flag
// * @return an IDevId certificate // * @return an IDevId certificate
// */ // */
// IDevIDCertificate findBySubjectKeyIdStringAndArchiveFlag(String subjectKeyIdString, boolean archiveFlag); // IDevIDCertificate findBySubjectKeyIdStringAndArchiveFlag(String subjectKeyIdString,
// boolean archiveFlag);
} }

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

@ -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

@ -36,7 +36,7 @@ public class CertificateVariables {
* *
*/ */
public static final int MAX_NUMERIC_PRECISION = 49; public static final int MAX_NUMERIC_PRECISION = 49;
/** /**
* Can store up to 160 bit values. * Can store up to 160 bit values.
*/ */

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

@ -177,7 +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;
/** /**

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,6 @@ public class CommonCriteriaMeasures {
} }
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -278,7 +145,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 +153,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

@ -21,60 +21,14 @@ import org.bouncycastle.asn1.ASN1Sequence;
public class FIPSLevel { public class FIPSLevel {
private static final int MAX_SEQUENCE_SIZE = 3; private static final int MAX_SEQUENCE_SIZE = 3;
/** @Getter
* A type to handle the security Level used in the FIPS Level. @Setter
* 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 @Getter
@Setter
private SecurityLevel level; private SecurityLevel level;
@Getter @Setter @Getter
@Setter
private ASN1Boolean plus; private ASN1Boolean plus;
/** /**
@ -119,4 +73,56 @@ public class FIPSLevel {
+ ", plus=" + plus.toString() + ", plus=" + plus.toString()
+ '}'; + '}';
} }
/**
* A type to handle the security Level used in the FIPS Level.
* Ordering of enum types is intentional and their ordinal values correspond to enum
* values in the TCG spec.
*
* <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;
}
}
} }

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
*/ */
@ -96,7 +97,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

@ -8,7 +8,6 @@ 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 {
@ -22,13 +21,11 @@ import org.bouncycastle.asn1.DERUTF8String;
@AllArgsConstructor @AllArgsConstructor
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;

View File

@ -30,60 +30,6 @@ 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;
@ -105,6 +51,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
*/ */
@ -260,11 +207,11 @@ public class TBBSecurityAssertion {
//Optional values not null //Optional values not null
sb.append(", ccInfo="); sb.append(", ccInfo=");
if (ccInfo != null) { if (ccInfo != null) {
sb.append(ccInfo.toString()); sb.append(ccInfo);
} }
sb.append(", fipsLevel="); sb.append(", fipsLevel=");
if (fipsLevel != null) { if (fipsLevel != null) {
sb.append(fipsLevel.toString()); sb.append(fipsLevel);
} }
sb.append(", rtmType="); sb.append(", rtmType=");
if (rtmType != null) { if (rtmType != null) {
@ -279,4 +226,58 @@ public class TBBSecurityAssertion {
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>
* 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;
}
}
} }

View File

@ -14,19 +14,61 @@ 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).
*/ */
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED) @NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter @Setter @Getter
@Setter
@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(nullable = true)
private EkGenerationType ekGenType; //optional
@Column(nullable = true)
private EkGenerationLocation ekGenerationLocation; //optional
@Column(nullable = true)
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;
}
@Override
public String toString() {
return "TPMSecurityAssertions{"
+ "version=" + tpmSecAssertsVersion
+ ", fieldUpgradeable=" + fieldUpgradeable
+ ", ekGenType=" + ekGenType
+ ", ekGenLoc=" + ekGenerationLocation
+ ", ekCertGenLoc=" + ekCertificateGenerationLocation
+ '}';
}
// 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 +93,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 +115,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

@ -13,15 +13,15 @@ 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 @EqualsAndHashCode
@NoArgsConstructor(access= AccessLevel.PROTECTED) @NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter @Getter
@Embeddable @Embeddable
public class TPMSpecification implements Serializable { public class TPMSpecification implements Serializable {
@ -37,8 +37,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,

View File

@ -10,27 +10,26 @@ 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.
*/ */

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

@ -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
*/ */
@ -99,7 +100,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 +111,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 {
@ -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,
@ -91,7 +90,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; 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

@ -34,6 +34,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 +57,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 +70,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 +112,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 +139,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,
@ -149,13 +154,18 @@ public class ComponentInfo extends ArchivableEntity {
/** /**
* Equals for the component info that just uses this classes attributes. * Equals for the component info that just uses this classes attributes.
*
* @param object the object to compare * @param object the object to compare
* @return the boolean result * @return the boolean result
*/ */
@Override @Override
public boolean equals(Object object) { public boolean equals(Object object) {
if (this == object) return true; if (this == object) {
if (object == null || getClass() != object.getClass()) return false; return true;
}
if (object == null || getClass() != object.getClass()) {
return false;
}
ComponentInfo that = (ComponentInfo) object; ComponentInfo that = (ComponentInfo) object;
return Objects.equals(deviceName, that.deviceName) return Objects.equals(deviceName, that.deviceName)
@ -169,6 +179,7 @@ public class ComponentInfo 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() {
@ -178,6 +189,7 @@ public class ComponentInfo extends ArchivableEntity {
/** /**
* Hash method for the attributes of this class. * Hash method for the attributes of this class.
*
* @return int value that represents this class * @return int value that represents this class
*/ */
@Override @Override

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,25 +68,16 @@ 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") @SuppressWarnings("parameternumber")
public TPMInfo(final String tpmMake, final short tpmVersionMajor, public TPMInfo(final String tpmMake, final short tpmVersionMajor,
@ -109,23 +100,15 @@ 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") @SuppressWarnings("parameternumber")
public TPMInfo(final String tpmMake, final short tpmVersionMajor, public TPMInfo(final String tpmMake, final short tpmVersionMajor,
@ -146,17 +129,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 +148,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 +189,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 +301,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

@ -63,9 +63,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 +84,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 +97,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 +125,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

@ -67,17 +67,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 +85,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 report,
* HardwareInfo object, cannot be null * 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,
@ -135,6 +124,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 +151,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 +177,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 +209,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");
@ -234,11 +223,12 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) {
if (!(o instanceof DeviceInfoReport)) { return true;
}
if (!(o instanceof DeviceInfoReport that)) {
return false; return false;
} }
DeviceInfoReport that = (DeviceInfoReport) o;
return Objects.equals(networkInfo, that.networkInfo) return Objects.equals(networkInfo, that.networkInfo)
&& Objects.equals(osInfo, that.osInfo) && Objects.equals(osInfo, that.osInfo)
&& Objects.equals(firmwareInfo, that.firmwareInfo) && Objects.equals(firmwareInfo, that.firmwareInfo)

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

@ -127,9 +127,11 @@ public class BaseReferenceManifest extends ReferenceManifest {
SwidTagConstants.SWIDTAG_NAMESPACE, SwidTagConstants.META).item(0); SwidTagConstants.SWIDTAG_NAMESPACE, SwidTagConstants.META).item(0);
setTagId(softwareIdentity.getAttribute(SwidTagConstants.TAGID)); setTagId(softwareIdentity.getAttribute(SwidTagConstants.TAGID));
this.swidName = softwareIdentity.getAttribute(SwidTagConstants.NAME); this.swidName = softwareIdentity.getAttribute(SwidTagConstants.NAME);
this.swidCorpus = Boolean.parseBoolean(softwareIdentity.getAttribute(SwidTagConstants.CORPUS)) ? 1 : 0; this.swidCorpus =
Boolean.parseBoolean(softwareIdentity.getAttribute(SwidTagConstants.CORPUS)) ? 1 : 0;
this.setSwidPatch(Boolean.parseBoolean(softwareIdentity.getAttribute(SwidTagConstants.PATCH))); this.setSwidPatch(Boolean.parseBoolean(softwareIdentity.getAttribute(SwidTagConstants.PATCH)));
this.setSwidSupplemental(Boolean.parseBoolean(softwareIdentity.getAttribute(SwidTagConstants.SUPPLEMENTAL))); this.setSwidSupplemental(
Boolean.parseBoolean(softwareIdentity.getAttribute(SwidTagConstants.SUPPLEMENTAL)));
this.setSwidVersion(softwareIdentity.getAttribute(SwidTagConstants.VERSION)); this.setSwidVersion(softwareIdentity.getAttribute(SwidTagConstants.VERSION));
this.setSwidTagVersion(softwareIdentity.getAttribute(SwidTagConstants.TAGVERSION)); this.setSwidTagVersion(softwareIdentity.getAttribute(SwidTagConstants.TAGVERSION));
@ -154,8 +156,10 @@ public class BaseReferenceManifest extends ReferenceManifest {
this.rimLinkHash = softwareMeta.getAttribute(SwidTagConstants._RIM_LINK_HASH_STR); this.rimLinkHash = softwareMeta.getAttribute(SwidTagConstants._RIM_LINK_HASH_STR);
this.bindingSpec = softwareMeta.getAttribute(SwidTagConstants._BINDING_SPEC_STR); this.bindingSpec = softwareMeta.getAttribute(SwidTagConstants._BINDING_SPEC_STR);
this.bindingSpecVersion = softwareMeta.getAttribute(SwidTagConstants._BINDING_SPEC_VERSION_STR); this.bindingSpecVersion = softwareMeta.getAttribute(SwidTagConstants._BINDING_SPEC_VERSION_STR);
this.setPlatformManufacturerId(softwareMeta.getAttribute(SwidTagConstants._PLATFORM_MANUFACTURER_ID_STR)); this.setPlatformManufacturerId(
this.setPlatformManufacturer(softwareMeta.getAttribute(SwidTagConstants._PLATFORM_MANUFACTURER_STR)); softwareMeta.getAttribute(SwidTagConstants._PLATFORM_MANUFACTURER_ID_STR));
this.setPlatformManufacturer(
softwareMeta.getAttribute(SwidTagConstants._PLATFORM_MANUFACTURER_STR));
this.setPlatformModel(softwareMeta.getAttribute(SwidTagConstants._PLATFORM_MODEL_STR)); this.setPlatformModel(softwareMeta.getAttribute(SwidTagConstants._PLATFORM_MODEL_STR));
this.platformVersion = softwareMeta.getAttribute(SwidTagConstants._PLATFORM_VERSION_STR); this.platformVersion = softwareMeta.getAttribute(SwidTagConstants._PLATFORM_VERSION_STR);
this.payloadType = softwareMeta.getAttribute(SwidTagConstants._PAYLOAD_TYPE_STR); this.payloadType = softwareMeta.getAttribute(SwidTagConstants._PAYLOAD_TYPE_STR);
@ -202,7 +206,6 @@ 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.
*
*/ */
private Element getDirectoryTag(final byte[] rimBytes) { private Element getDirectoryTag(final byte[] rimBytes) {
if (rimBytes == null || rimBytes.length == 0) { if (rimBytes == null || rimBytes.length == 0) {
@ -254,7 +257,6 @@ 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
*
*/ */
public List<SwidResource> getFileResources(final byte[] rimBytes) { public List<SwidResource> getFileResources(final byte[] rimBytes) {
Element directoryTag = getDirectoryTag(rimBytes); Element directoryTag = getDirectoryTag(rimBytes);
@ -353,9 +355,15 @@ public class BaseReferenceManifest extends ReferenceManifest {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) {
if (o == null || getClass() != o.getClass()) return false; return true;
if (!super.equals(o)) return false; }
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
BaseReferenceManifest that = (BaseReferenceManifest) o; BaseReferenceManifest that = (BaseReferenceManifest) o;
return swidCorpus == that.swidCorpus && Objects.equals(swidName, that.swidName) return swidCorpus == that.swidCorpus && Objects.equals(swidName, that.swidName)
&& Objects.equals(colloquialVersion, that.colloquialVersion) && Objects.equals(colloquialVersion, that.colloquialVersion)

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;
@ -31,10 +30,12 @@ public class EventLogMeasurements extends SupportReferenceManifest {
@Column @Column
@JsonIgnore @JsonIgnore
@Getter @Setter @Getter
@Setter
private int pcrHash = 0; private int pcrHash = 0;
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
@Getter @Setter @Getter
@Setter
private AppraisalStatus.Status overallValidationResult = AppraisalStatus.Status.FAIL; private AppraisalStatus.Status overallValidationResult = AppraisalStatus.Status.FAIL;
/** /**
@ -74,6 +75,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() {

View File

@ -8,7 +8,6 @@ import jakarta.persistence.Entity;
import jakarta.persistence.Table; import jakarta.persistence.Table;
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;
@ -25,7 +24,7 @@ import java.util.UUID;
@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 {
@ -88,18 +87,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,
@ -124,6 +124,7 @@ public class ReferenceDigestValue extends AbstractEntity {
/** /**
* the object that contains the raw bytes for this RDV. * the object that contains the raw bytes for this RDV.
*
* @return the raw bytes * @return the raw bytes
*/ */
public byte[] getContentBlob() { public byte[] getContentBlob() {
@ -132,7 +133,8 @@ public class ReferenceDigestValue extends AbstractEntity {
/** /**
* 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 +153,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

@ -71,6 +71,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() {
@ -113,6 +114,7 @@ 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() {
@ -121,9 +123,15 @@ public class SupportReferenceManifest extends ReferenceManifest {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) {
if (o == null || getClass() != o.getClass()) return false; return true;
if (!super.equals(o)) return false; }
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
SupportReferenceManifest that = (SupportReferenceManifest) o; SupportReferenceManifest that = (SupportReferenceManifest) o;
return pcrHash == that.pcrHash && updated == that.updated; return pcrHash == that.pcrHash && updated == that.updated;
} }

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

@ -22,18 +22,24 @@ public enum HealthStatus {
*/ */
UNKNOWN("unknown"); UNKNOWN("unknown");
private String healthStatus; private final String healthStatus;
/** /**
* Creates a new <code>HealthStatus</code> object given a String. * Creates a new <code>HealthStatus</code> object given a String.
* *
* @param healthStatus * @param healthStatus "trusted", "untrusted", or "unknown"
* "trusted", "untrusted", or "unknown"
*/ */
HealthStatus(final String healthStatus) { HealthStatus(final String healthStatus) {
this.healthStatus = healthStatus; this.healthStatus = healthStatus;
} }
public static boolean isValidStatus(final String healthStatus) {
return Arrays.stream(HealthStatus.values())
.map(HealthStatus::name)
.collect(Collectors.toSet())
.contains(healthStatus);
}
/** /**
* Returns the health status. * Returns the health status.
* *
@ -47,11 +53,4 @@ public enum HealthStatus {
public String toString() { public String toString() {
return getStatus(); return getStatus();
} }
}
public static boolean isValidStatus(final String healthStatus) {
return Arrays.stream(HealthStatus.values())
.map(HealthStatus::name)
.collect(Collectors.toSet())
.contains(healthStatus);
}
}

View File

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

View File

@ -54,8 +54,9 @@ public class AbstractProcessor {
/** /**
* 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) {
@ -66,17 +67,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();
@ -132,8 +134,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
*/ */
@ -162,7 +164,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
@ -193,7 +195,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
*/ */
@ -229,22 +232,22 @@ 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, boolean isLDevID) {
List<IssuedAttestationCertificate> issuedAc; List<IssuedAttestationCertificate> issuedAc;
boolean generateCertificate = true; boolean generateCertificate = true;
PolicyRepository scp = getPolicyRepository(); PolicyRepository scp = getPolicyRepository();
@ -260,23 +263,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 &&
: policySettings.isGenerateOnExpiration())) { (isLDevID ? policySettings.isDevIdExpirationFlag()
: 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;
}
} }
} }
} }
@ -297,7 +299,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

@ -30,22 +30,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,
@ -170,10 +171,12 @@ public class CertificateRequestProcessor extends AbstractProcessor {
ByteString ldevidCertificateBytes = ByteString ByteString ldevidCertificateBytes = ByteString
.copyFrom(derEncodedLdevidCertificate); .copyFrom(derEncodedLdevidCertificate);
boolean generateAtt = saveAttestationCertificate(certificateRepository, derEncodedAttestationCertificate, boolean generateAtt = saveAttestationCertificate(certificateRepository,
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);
@ -186,8 +189,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);
@ -200,7 +202,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(certificateBytes); builder = builder.setCertificate(certificateBytes);
@ -221,7 +224,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

@ -22,9 +22,10 @@ public final class CredentialManagementHelper {
/** /**
* Parses and stores the EK in the cert manager. If the cert is already present and archived, * Parses and stores the EK in the cert manager. If the cert is already present and archived,
* it is unarchived. * it is unarchived.
*
* @param certificateRepository the certificate manager used for storage * @param certificateRepository the certificate manager used for storage
* @param endorsementBytes the raw EK bytes used for parsing * @param endorsementBytes the raw EK bytes used for parsing
* @param deviceName the host name * @param deviceName the host name
* @return the parsed, valid EK * @return the parsed, valid EK
* @throws IllegalArgumentException if the provided bytes are not a valid EK. * @throws IllegalArgumentException if the provided bytes are not a valid EK.
*/ */
@ -63,7 +64,7 @@ public final class CredentialManagementHelper {
if (existingCredential == null) { if (existingCredential == null) {
log.info("No Endorsement Credential found with hash: " + certificateHash); log.info("No Endorsement Credential found with hash: " + certificateHash);
endorsementCredential.setDeviceName(deviceName); endorsementCredential.setDeviceName(deviceName);
return (EndorsementCredential) certificateRepository.save(endorsementCredential); return certificateRepository.save(endorsementCredential);
} else if (existingCredential.isArchived()) { } else if (existingCredential.isArchived()) {
// if the EK is stored in the DB and it's archived, unarchive. // if the EK is stored in the DB and it's archived, unarchive.
log.info("Unarchiving credential"); log.info("Unarchiving credential");
@ -77,9 +78,10 @@ public final class CredentialManagementHelper {
/** /**
* Parses and stores the PC in the cert manager. If the cert is already present and archived, * Parses and stores the PC in the cert manager. If the cert is already present and archived,
* it is unarchived. * it is unarchived.
*
* @param certificateRepository the certificate manager used for storage * @param certificateRepository the certificate manager used for storage
* @param platformBytes the raw PC bytes used for parsing * @param platformBytes the raw PC bytes used for parsing
* @param deviceName the host name of the associated machine * @param deviceName the host name of the associated machine
* @return the parsed, valid PC, or null if the provided bytes are not a valid EK. * @return the parsed, valid PC, or null if the provided bytes are not a valid EK.
*/ */
public static PlatformCredential storePlatformCredential( public static PlatformCredential storePlatformCredential(
@ -129,7 +131,7 @@ public final class CredentialManagementHelper {
} }
} }
platformCredential.setDeviceName(deviceName); platformCredential.setDeviceName(deviceName);
return (PlatformCredential) certificateRepository.save(platformCredential); return certificateRepository.save(platformCredential);
} else if (existingCredential.isArchived()) { } else if (existingCredential.isArchived()) {
// if the PC is stored in the DB and it's archived, unarchive. // if the PC is stored in the DB and it's archived, unarchive.
log.info("Unarchiving credential"); log.info("Unarchiving credential");

View File

@ -12,6 +12,7 @@ import org.bouncycastle.asn1.x500.AttributeTypeAndValue;
import org.bouncycastle.asn1.x500.RDN; import org.bouncycastle.asn1.x500.RDN;
import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x500.X500NameBuilder; import org.bouncycastle.asn1.x500.X500NameBuilder;
import org.bouncycastle.asn1.x509.AttributeCertificateInfo;
import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier; import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage; import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.Extension;
@ -21,7 +22,6 @@ import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.GeneralNamesBuilder; import org.bouncycastle.asn1.x509.GeneralNamesBuilder;
import org.bouncycastle.asn1.x509.KeyPurposeId; import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.TBSCertificate; import org.bouncycastle.asn1.x509.TBSCertificate;
import org.bouncycastle.asn1.x509.AttributeCertificateInfo;
import java.io.IOException; import java.io.IOException;
import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateEncodingException;
@ -35,17 +35,16 @@ import java.util.Collection;
@Log4j2 @Log4j2
public final class IssuedCertificateAttributeHelper { public final class IssuedCertificateAttributeHelper {
/**
* The extended key usage extension.
*/
public static final Extension EXTENDED_KEY_USAGE_EXTENSION;
private static final String TPM_ID_LABEL_OID = "2.23.133.2.15"; private static final String TPM_ID_LABEL_OID = "2.23.133.2.15";
/** /**
* Object Identifier TCPA at TPM ID Label. * Object Identifier TCPA at TPM ID Label.
*/ */
public static final ASN1ObjectIdentifier TCPA_AT_TPM_ID_LABEL = public static final ASN1ObjectIdentifier TCPA_AT_TPM_ID_LABEL =
new ASN1ObjectIdentifier(TPM_ID_LABEL_OID); new ASN1ObjectIdentifier(TPM_ID_LABEL_OID);
/**
* The extended key usage extension.
*/
public static final Extension EXTENDED_KEY_USAGE_EXTENSION;
private static final ASN1ObjectIdentifier TCG_KP_AIK_CERTIFICATE_ATTRIBUTE = private static final ASN1ObjectIdentifier TCG_KP_AIK_CERTIFICATE_ATTRIBUTE =
new ASN1ObjectIdentifier("2.23.133.8.3"); new ASN1ObjectIdentifier("2.23.133.8.3");
@ -69,6 +68,7 @@ public final class IssuedCertificateAttributeHelper {
/** /**
* This method builds the AKI extension that will be stored in the generated * This method builds the AKI extension that will be stored in the generated
* Attestation Issued Certificate. * Attestation Issued Certificate.
*
* @param endorsementCredential EK object to pull AKI from. * @param endorsementCredential EK object to pull AKI from.
* @return the AKI extension. * @return the AKI extension.
* @throws IOException on bad get instance for AKI. * @throws IOException on bad get instance for AKI.
@ -93,11 +93,12 @@ public final class IssuedCertificateAttributeHelper {
/** /**
* Builds the subject alternative name based on the supplied certificates. * Builds the subject alternative name based on the supplied certificates.
*
* @param endorsementCredential the endorsement credential * @param endorsementCredential the endorsement credential
* @param platformCredentials the platform credentials * @param platformCredentials the platform credentials
* @param hostName the host name * @param hostName the host name
* @return the subject alternative name extension * @return the subject alternative name extension
* @throws IOException an IO exception occurs building the extension * @throws IOException an IO exception occurs building the extension
* @throws IllegalArgumentException if the host name is null * @throws IllegalArgumentException if the host name is null
*/ */
public static Extension buildSubjectAlternativeNameFromCerts( public static Extension buildSubjectAlternativeNameFromCerts(
@ -178,14 +179,11 @@ public final class IssuedCertificateAttributeHelper {
populateRdnAttributesInNameBuilder(nameBuilder, rdns); populateRdnAttributesInNameBuilder(nameBuilder, rdns);
} else { } else {
log.error("No RDNs in endorsement credential attributes"); log.error("No RDNs in endorsement credential attributes");
return;
} }
} catch (CertificateEncodingException e) { } catch (CertificateEncodingException e) {
log.error("Certificate encoding exception", e); log.error("Certificate encoding exception", e);
return;
} catch (IOException e) { } catch (IOException e) {
log.error("Error creating x509 cert from endorsement credential", e); log.error("Error creating x509 cert from endorsement credential", e);
return;
} }
} }

View File

@ -3,7 +3,6 @@ package hirs.attestationca.persist.provision.helper;
import com.google.protobuf.ByteString; 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.userdefined.info.TPMInfo;
import hirs.attestationca.persist.exceptions.CertificateProcessingException; import hirs.attestationca.persist.exceptions.CertificateProcessingException;
import hirs.attestationca.persist.exceptions.IdentityProcessingException; import hirs.attestationca.persist.exceptions.IdentityProcessingException;
import hirs.attestationca.persist.exceptions.UnexpectedServerException; import hirs.attestationca.persist.exceptions.UnexpectedServerException;
@ -14,7 +13,6 @@ import hirs.structs.elements.tpm.IdentityRequest;
import hirs.structs.elements.tpm.SymmetricKey; import hirs.structs.elements.tpm.SymmetricKey;
import hirs.structs.elements.tpm.SymmetricKeyParams; import hirs.structs.elements.tpm.SymmetricKeyParams;
import hirs.utils.HexUtils; import hirs.utils.HexUtils;
import hirs.utils.enums.DeviceInfoEnums;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
@ -54,16 +52,16 @@ public final class ProvisionUtils {
* The default size for IV blocks. * The default size for IV blocks.
*/ */
public final static int DEFAULT_IV_SIZE = 16; public final static int DEFAULT_IV_SIZE = 16;
/**
* Defines the well known exponent.
* https://en.wikipedia.org/wiki/65537_(number)#Applications
*/
private final static BigInteger EXPONENT = new BigInteger("010001", DEFAULT_IV_SIZE);
public static final int HMAC_SIZE_LENGTH_BYTES = 2; public static final int HMAC_SIZE_LENGTH_BYTES = 2;
public static final int HMAC_KEY_LENGTH_BYTES = 32; public static final int HMAC_KEY_LENGTH_BYTES = 32;
public static final int SEED_LENGTH = 32; public static final int SEED_LENGTH = 32;
public static final int MAX_SECRET_LENGTH = 32; public static final int MAX_SECRET_LENGTH = 32;
public static final int AES_KEY_LENGTH_BYTES = 16; public static final int AES_KEY_LENGTH_BYTES = 16;
/**
* Defines the well known exponent.
* https://en.wikipedia.org/wiki/65537_(number)#Applications
*/
private final static BigInteger EXPONENT = new BigInteger("010001", DEFAULT_IV_SIZE);
private static final int TPM2_CREDENTIAL_BLOB_SIZE = 392; private static final int TPM2_CREDENTIAL_BLOB_SIZE = 392;
private static final int RSA_MODULUS_LENGTH = 256; private static final int RSA_MODULUS_LENGTH = 256;
// Constants used to parse out the ak name from the ak public data. Used in generateAkName // Constants used to parse out the ak name from the ak public data. Used in generateAkName
@ -77,8 +75,8 @@ public final class ProvisionUtils {
* *
* @param identityClaim byte array that should be converted to a Protobuf IdentityClaim * @param identityClaim byte array that should be converted to a Protobuf IdentityClaim
* object * object
* @throws {@link IdentityProcessingException} if byte array could not be parsed
* @return the Protobuf generated Identity Claim object * @return the Protobuf generated Identity Claim object
* @throws {@link IdentityProcessingException} if byte array could not be parsed
*/ */
public static ProvisionerTpm2.IdentityClaim parseIdentityClaim(final byte[] identityClaim) { public static ProvisionerTpm2.IdentityClaim parseIdentityClaim(final byte[] identityClaim) {
try { try {
@ -93,8 +91,8 @@ public final class ProvisionUtils {
* Helper method to extract a DER encoded ASN.1 certificate from an X509 certificate. * Helper method to extract a DER encoded ASN.1 certificate from an X509 certificate.
* *
* @param certificate the X509 certificate to be converted to DER encoding * @param certificate the X509 certificate to be converted to DER encoding
* @throws {@link UnexpectedServerException} if error occurs during encoding retrieval
* @return the byte array representing the DER encoded certificate * @return the byte array representing the DER encoded certificate
* @throws {@link UnexpectedServerException} if error occurs during encoding retrieval
*/ */
public static byte[] getDerEncodedCertificate(final X509Certificate certificate) { public static byte[] getDerEncodedCertificate(final X509Certificate certificate) {
try { try {
@ -109,6 +107,7 @@ public final class ProvisionUtils {
/** /**
* Parse public key from public data segment generated by TPM 2.0. * Parse public key from public data segment generated by TPM 2.0.
*
* @param publicArea the public area segment to parse * @param publicArea the public area segment to parse
* @return the RSA public key of the supplied public data * @return the RSA public key of the supplied public data
*/ */
@ -128,8 +127,7 @@ public final class ProvisionUtils {
/** /**
* Constructs a public key where the modulus is in raw form. * Constructs a public key where the modulus is in raw form.
* *
* @param modulus * @param modulus in byte array form
* in byte array form
* @return public key using specific modulus and the well known exponent * @return public key using specific modulus and the well known exponent
*/ */
public static PublicKey assemblePublicKey(final byte[] modulus) { public static PublicKey assemblePublicKey(final byte[] modulus) {
@ -139,8 +137,7 @@ public final class ProvisionUtils {
/** /**
* Constructs a public key where the modulus is Hex encoded. * Constructs a public key where the modulus is Hex encoded.
* *
* @param modulus * @param modulus hex encoded modulus
* hex encoded modulus
* @return public key using specific modulus and the well known exponent * @return public key using specific modulus and the well known exponent
*/ */
public static PublicKey assemblePublicKey(final String modulus) { public static PublicKey assemblePublicKey(final String modulus) {
@ -169,8 +166,8 @@ public final class ProvisionUtils {
* {@link hirs.structs.elements.tpm.IdentityRequest} using the cipher transformation. * {@link hirs.structs.elements.tpm.IdentityRequest} using the cipher transformation.
* *
* @param asymmetricBlob to be decrypted * @param asymmetricBlob to be decrypted
* @param scheme to decrypt with * @param scheme to decrypt with
* @param privateKey cipher private key * @param privateKey cipher private key
* @return decrypted blob * @return decrypted blob
*/ */
public static byte[] decryptAsymmetricBlob(final byte[] asymmetricBlob, public static byte[] decryptAsymmetricBlob(final byte[] asymmetricBlob,
@ -197,8 +194,8 @@ public final class ProvisionUtils {
return cipher.doFinal(); return cipher.doFinal();
} catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException } catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException
| BadPaddingException | IllegalBlockSizeException | BadPaddingException | IllegalBlockSizeException
| InvalidAlgorithmParameterException e) { | InvalidAlgorithmParameterException e) {
throw new IdentityProcessingException( throw new IdentityProcessingException(
"Encountered error while decrypting asymmetric blob of an identity request: " "Encountered error while decrypting asymmetric blob of an identity request: "
+ e.getMessage(), e); + e.getMessage(), e);
@ -210,14 +207,14 @@ public final class ProvisionUtils {
* {@link hirs.structs.elements.tpm.IdentityRequest} using the specified symmetric key * {@link hirs.structs.elements.tpm.IdentityRequest} using the specified symmetric key
* and cipher transformation. * and cipher transformation.
* *
* @param symmetricBlob to be decrypted * @param symmetricBlob to be decrypted
* @param symmetricKey to use to decrypt * @param symmetricKey to use to decrypt
* @param iv to use with decryption cipher * @param iv to use with decryption cipher
* @param transformation of the cipher * @param transformation of the cipher
* @return decrypted symmetric blob * @return decrypted symmetric blob
*/ */
public static byte[] decryptSymmetricBlob(final byte[] symmetricBlob, final byte[] symmetricKey, public static byte[] decryptSymmetricBlob(final byte[] symmetricBlob, final byte[] symmetricKey,
final byte[] iv, final String transformation) { final byte[] iv, final String transformation) {
try { try {
// create a cipher from the specified transformation // create a cipher from the specified transformation
Cipher cipher = Cipher.getInstance(transformation); Cipher cipher = Cipher.getInstance(transformation);
@ -231,8 +228,8 @@ public final class ProvisionUtils {
// decrypt the symmetric blob // decrypt the symmetric blob
return cipher.doFinal(symmetricBlob); return cipher.doFinal(symmetricBlob);
} catch (IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException } catch (IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException
| BadPaddingException | NoSuchPaddingException | BadPaddingException | NoSuchPaddingException
| InvalidAlgorithmParameterException exception) { | InvalidAlgorithmParameterException exception) {
log.error("Encountered error while decrypting symmetric blob of an identity request: " log.error("Encountered error while decrypting symmetric blob of an identity request: "
+ exception.getMessage(), exception); + exception.getMessage(), exception);
} }
@ -261,16 +258,16 @@ public final class ProvisionUtils {
* key to generate an HMAC to cover the encrypted secret and the ak name. The output is an * key to generate an HMAC to cover the encrypted secret and the ak name. The output is an
* encrypted blob that acts as the first part of a challenge-response authentication mechanism * encrypted blob that acts as the first part of a challenge-response authentication mechanism
* to validate an identity claim. * to validate an identity claim.
* * <p>
* Equivalent to calling tpm2_makecredential using tpm2_tools. * Equivalent to calling tpm2_makecredential using tpm2_tools.
* *
* @param ek endorsement key in the identity claim * @param ek endorsement key in the identity claim
* @param ak attestation key in the identity claim * @param ak attestation key in the identity claim
* @param secret a nonce * @param secret a nonce
* @return the encrypted blob forming the identity claim challenge * @return the encrypted blob forming the identity claim challenge
*/ */
public static ByteString tpm20MakeCredential(final RSAPublicKey ek, final RSAPublicKey ak, public static ByteString tpm20MakeCredential(final RSAPublicKey ek, final RSAPublicKey ak,
final byte[] secret) { final byte[] secret) {
// check size of the secret // check size of the secret
if (secret.length > MAX_SECRET_LENGTH) { if (secret.length > MAX_SECRET_LENGTH) {
throw new IllegalArgumentException("Secret must be " + MAX_SECRET_LENGTH throw new IllegalArgumentException("Secret must be " + MAX_SECRET_LENGTH
@ -284,7 +281,8 @@ public final class ProvisionUtils {
// encrypt seed with pubEk // encrypt seed with pubEk
Cipher asymCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding"); Cipher asymCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
OAEPParameterSpec oaepSpec = new OAEPParameterSpec("SHA-256", "MGF1", OAEPParameterSpec oaepSpec = new OAEPParameterSpec("SHA-256", "MGF1",
MGF1ParameterSpec.SHA256, new PSource.PSpecified("IDENTITY\0".getBytes(StandardCharsets.UTF_8))); MGF1ParameterSpec.SHA256,
new PSource.PSpecified("IDENTITY\0".getBytes(StandardCharsets.UTF_8)));
asymCipher.init(Cipher.PUBLIC_KEY, ek, oaepSpec); asymCipher.init(Cipher.PUBLIC_KEY, ek, oaepSpec);
asymCipher.update(seed); asymCipher.update(seed);
byte[] encSeed = asymCipher.doFinal(); byte[] encSeed = asymCipher.doFinal();
@ -339,8 +337,8 @@ public final class ProvisionUtils {
return ByteString.copyFrom(bytesToReturn); return ByteString.copyFrom(bytesToReturn);
} catch (BadPaddingException | IllegalBlockSizeException | NoSuchAlgorithmException } catch (BadPaddingException | IllegalBlockSizeException | NoSuchAlgorithmException
| InvalidKeyException | InvalidAlgorithmParameterException | InvalidKeyException | InvalidAlgorithmParameterException
| NoSuchPaddingException e) { | NoSuchPaddingException e) {
throw new IdentityProcessingException( throw new IdentityProcessingException(
"Encountered error while making the identity claim challenge: " "Encountered error while making the identity claim challenge: "
+ e.getMessage(), e); + e.getMessage(), e);
@ -351,13 +349,13 @@ public final class ProvisionUtils {
* Generate asymmetric contents part of the identity response. * Generate asymmetric contents part of the identity response.
* *
* @param identityKey identity requests symmetric contents, otherwise, the identity proof * @param identityKey identity requests symmetric contents, otherwise, the identity proof
* @param sessionKey identity response session key * @param sessionKey identity response session key
* @param publicKey of the EK certificate contained within the identity proof * @param publicKey of the EK certificate contained within the identity proof
* @return encrypted asymmetric contents * @return encrypted asymmetric contents
*/ */
public static byte[] generateAsymmetricContents(final byte[] identityKey, public static byte[] generateAsymmetricContents(final byte[] identityKey,
final byte[] sessionKey, final byte[] sessionKey,
final PublicKey publicKey) { final PublicKey publicKey) {
try { try {
// create a SHA1 digest of the identity key // create a SHA1 digest of the identity key
MessageDigest md = MessageDigest.getInstance("SHA-1"); MessageDigest md = MessageDigest.getInstance("SHA-1");
@ -382,8 +380,8 @@ public final class ProvisionUtils {
return cipher.doFinal(asymmetricContents); return cipher.doFinal(asymmetricContents);
} catch (NoSuchAlgorithmException | IllegalBlockSizeException | NoSuchPaddingException } catch (NoSuchAlgorithmException | IllegalBlockSizeException | NoSuchPaddingException
| InvalidKeyException | BadPaddingException | InvalidKeyException | BadPaddingException
| InvalidAlgorithmParameterException e) { | InvalidAlgorithmParameterException e) {
throw new CertificateProcessingException( throw new CertificateProcessingException(
"Encountered error while generating ACA session key: " + e.getMessage(), e); "Encountered error while generating ACA session key: " + e.getMessage(), e);
} }
@ -421,12 +419,12 @@ public final class ProvisionUtils {
/** /**
* Generate the Identity Response using the identity credential and the session key. * Generate the Identity Response using the identity credential and the session key.
* *
* @param credential the identity credential * @param credential the identity credential
* @param symmetricKey generated session key for this request/response chain * @param symmetricKey generated session key for this request/response chain
* @return identity response for an identity request * @return identity response for an identity request
*/ */
public static SymmetricAttestation generateAttestation(final X509Certificate credential, public static SymmetricAttestation generateAttestation(final X509Certificate credential,
final SymmetricKey symmetricKey) { final SymmetricKey symmetricKey) {
try { try {
// initialize the symmetric cipher // initialize the symmetric cipher
Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
@ -463,8 +461,8 @@ public final class ProvisionUtils {
return attestation; return attestation;
} catch (BadPaddingException | IllegalBlockSizeException | NoSuchAlgorithmException } catch (BadPaddingException | IllegalBlockSizeException | NoSuchAlgorithmException
| InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException
| CertificateEncodingException exception) { | CertificateEncodingException exception) {
throw new CertificateProcessingException( throw new CertificateProcessingException(
"Encountered error while generating Identity Response: " "Encountered error while generating Identity Response: "
+ exception.getMessage(), exception); + exception.getMessage(), exception);
@ -473,8 +471,8 @@ public final class ProvisionUtils {
@SuppressWarnings("magicnumber") @SuppressWarnings("magicnumber")
public static byte[] assembleCredential(final byte[] topSize, final byte[] integrityHmac, public static byte[] assembleCredential(final byte[] topSize, final byte[] integrityHmac,
final byte[] encryptedSecret, final byte[] encryptedSecret,
final byte[] encryptedSeed) { final byte[] encryptedSeed) {
/* /*
* Credential structure breakdown with endianness: * Credential structure breakdown with endianness:
* 0-1 topSize (2), LE * 0-1 topSize (2), LE
@ -503,6 +501,7 @@ public final class ProvisionUtils {
/** /**
* Determines the AK name from the AK Modulus. * Determines the AK name from the AK Modulus.
*
* @param akModulus modulus of an attestation key * @param akModulus modulus of an attestation key
* @return the ak name byte array * @return the ak name byte array
* @throws java.security.NoSuchAlgorithmException Underlying SHA256 method used a bad algorithm * @throws java.security.NoSuchAlgorithmException Underlying SHA256 method used a bad algorithm
@ -526,24 +525,24 @@ public final class ProvisionUtils {
* multiple contexts are not supported in this implementation. This should work for all uses of * multiple contexts are not supported in this implementation. This should work for all uses of
* the KDF for TPM2_MakeCredential. * the KDF for TPM2_MakeCredential.
* *
* @param seed random value used to generate the key * @param seed random value used to generate the key
* @param label first portion of message used to generate key * @param label first portion of message used to generate key
* @param context second portion of message used to generate key * @param context second portion of message used to generate key
* @param sizeInBytes size of key to generate in bytes * @param sizeInBytes size of key to generate in bytes
* @return the derived key * @return the derived key
* @throws NoSuchAlgorithmException Wrong crypto algorithm selected * @throws NoSuchAlgorithmException Wrong crypto algorithm selected
* @throws java.security.InvalidKeyException Invalid key used * @throws java.security.InvalidKeyException Invalid key used
*/ */
@SuppressWarnings("magicnumber") @SuppressWarnings("magicnumber")
public static byte[] cryptKDFa(final byte[] seed, final String label, final byte[] context, public static byte[] cryptKDFa(final byte[] seed, final String label, final byte[] context,
final int sizeInBytes) final int sizeInBytes)
throws NoSuchAlgorithmException, InvalidKeyException { throws NoSuchAlgorithmException, InvalidKeyException {
ByteBuffer b = ByteBuffer.allocate(4); ByteBuffer b = ByteBuffer.allocate(4);
b.putInt(1); b.putInt(1);
byte[] counter = b.array(); byte[] counter = b.array();
// get the label // get the label
String labelWithEnding = label; String labelWithEnding = label;
if (label.charAt(label.length() - 1) != "\0".charAt(0)) { if (label.charAt(label.length() - 1) != '\u0000') {
labelWithEnding = label + "\0"; labelWithEnding = label + "\0";
} }
byte[] labelBytes = labelWithEnding.getBytes(StandardCharsets.UTF_8); byte[] labelBytes = labelWithEnding.getBytes(StandardCharsets.UTF_8);
@ -580,6 +579,7 @@ public final class ProvisionUtils {
/** /**
* This method takes the provided TPM Quote and splits it between the PCR * This method takes the provided TPM Quote and splits it between the PCR
* quote and the signature hash. * quote and the signature hash.
*
* @param tpmQuote contains hash values for the quote and the signature * @param tpmQuote contains hash values for the quote and the signature
*/ */
public static String parseTPMQuoteHash(final String tpmQuote) { public static String parseTPMQuoteHash(final String tpmQuote) {
@ -598,6 +598,7 @@ public final class ProvisionUtils {
/** /**
* This method takes the provided TPM Quote and splits it between the PCR * This method takes the provided TPM Quote and splits it between the PCR
* quote and the signature hash. * quote and the signature hash.
*
* @param tpmQuote contains hash values for the quote and the signature * @param tpmQuote contains hash values for the quote and the signature
*/ */
public static String parseTPMQuoteSignature(final String tpmQuote) { public static String parseTPMQuoteSignature(final String tpmQuote) {
@ -612,6 +613,7 @@ public final class ProvisionUtils {
/** /**
* Computes the sha256 hash of the given blob. * Computes the sha256 hash of the given blob.
*
* @param blob byte array to take the hash of * @param blob byte array to take the hash of
* @return sha256 hash of blob * @return sha256 hash of blob
* @throws NoSuchAlgorithmException improper algorithm selected * @throws NoSuchAlgorithmException improper algorithm selected
@ -625,8 +627,7 @@ public final class ProvisionUtils {
/** /**
* Generates a array of random bytes. * Generates a array of random bytes.
* *
* @param numberOfBytes * @param numberOfBytes to be generated
* to be generated
* @return byte array filled with the specified number of bytes. * @return byte array filled with the specified number of bytes.
*/ */
public static byte[] generateRandomBytes(final int numberOfBytes) { public static byte[] generateRandomBytes(final int numberOfBytes) {

View File

@ -18,7 +18,6 @@ import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredent
import hirs.attestationca.persist.entity.userdefined.info.ComponentInfo; import hirs.attestationca.persist.entity.userdefined.info.ComponentInfo;
import hirs.attestationca.persist.entity.userdefined.report.DeviceInfoReport; import hirs.attestationca.persist.entity.userdefined.report.DeviceInfoReport;
import hirs.attestationca.persist.enums.AppraisalStatus; import hirs.attestationca.persist.enums.AppraisalStatus;
import hirs.attestationca.persist.validation.CertificateAttributeScvValidator;
import hirs.attestationca.persist.validation.CredentialValidator; import hirs.attestationca.persist.validation.CredentialValidator;
import hirs.attestationca.persist.validation.FirmwareScvValidator; import hirs.attestationca.persist.validation.FirmwareScvValidator;
import hirs.utils.BouncyCastleUtils; import hirs.utils.BouncyCastleUtils;
@ -258,7 +257,7 @@ public class ValidationService {
* include the trust chain if it exists in this class' CertificateManager. * include the trust chain if it exists in this class' CertificateManager.
* Returns the certificate authority credentials in a KeyStore. * Returns the certificate authority credentials in a KeyStore.
* *
* @param certificate the credential whose CA chain should be retrieved * @param certificate the credential whose CA chain should be retrieved
* @param caCredentialRepository db service to get CA Certs * @param caCredentialRepository db service to get CA Certs
* @return A keystore containing all relevant CA credentials to the given * @return A keystore containing all relevant CA credentials to the given
* certificate's organization or null if the keystore can't be assembled * certificate's organization or null if the keystore can't be assembled
@ -318,7 +317,8 @@ public class ValidationService {
certAuthsWithMatchingIssuer = caCredentialRepository.findBySubject(credential.getIssuer()); certAuthsWithMatchingIssuer = caCredentialRepository.findBySubject(credential.getIssuer());
} else { } else {
//Get certificates by subject organization //Get certificates by subject organization
certAuthsWithMatchingIssuer = caCredentialRepository.findBySubjectSorted(credential.getIssuerSorted()); certAuthsWithMatchingIssuer =
caCredentialRepository.findBySubjectSorted(credential.getIssuerSorted());
} }
} else { } else {
certAuthsWithMatchingIssuer.add(skiCA); certAuthsWithMatchingIssuer.add(skiCA);

View File

@ -24,7 +24,7 @@ import java.util.UUID;
* This class is used to select one or many certificates in conjunction * This class is used to select one or many certificates in conjunction
* with a {@link }. To make use of this object, * with a {@link }. To make use of this object,
* use (some CertificateImpl).select(CertificateManager). * use (some CertificateImpl).select(CertificateManager).
* * <p>
* This class loosely follows the builder pattern. It is instantiated with * This class loosely follows the builder pattern. It is instantiated with
* the type of certificate that should be retrieved. It is possible to * the type of certificate that should be retrieved. It is possible to
* further specify which certificate(s) should be retrieved by using an * further specify which certificate(s) should be retrieved by using an
@ -32,10 +32,10 @@ import java.util.UUID;
* restrict the result set. At any time, the results may be retrieved * restrict the result set. At any time, the results may be retrieved
* by using one of the get* methods according to the form the * by using one of the get* methods according to the form the
* results should be in. * results should be in.
* * <p>
* If no matching certificates were found for the query, the returned * If no matching certificates were found for the query, the returned
* value may empty or null, depending on the return type. * value may empty or null, depending on the return type.
* * <p>
* For example, to retrieve all platform certificates: * For example, to retrieve all platform certificates:
* *
* <pre> * <pre>
@ -45,7 +45,7 @@ import java.util.UUID;
* .getCertificates(); * .getCertificates();
* } * }
* </pre> * </pre>
* * <p>
* To retrieve all CA certificates in a KeyStore: * To retrieve all CA certificates in a KeyStore:
* *
* <pre> * <pre>
@ -55,7 +55,7 @@ import java.util.UUID;
* .getKeyStore(); * .getKeyStore();
* } * }
* </pre> * </pre>
* * <p>
* To retrieve all CA certificates matching a certain issuer in X509 format: * To retrieve all CA certificates matching a certain issuer in X509 format:
* *
* <pre> * <pre>
@ -91,7 +91,7 @@ public abstract class CertificateSelector<T extends Certificate> {
* Construct a new CertificateSelector that will use the given {@link } to * Construct a new CertificateSelector that will use the given {@link } to
* retrieve certificates of the given type. * retrieve certificates of the given type.
* *
* @param certificateClass the class of certificate to be retrieved * @param certificateClass the class of certificate to be retrieved
* @param excludeArchivedCertificates true if excluding archived certificates * @param excludeArchivedCertificates true if excluding archived certificates
*/ */
public CertificateSelector( public CertificateSelector(
@ -105,6 +105,7 @@ public abstract class CertificateSelector<T extends Certificate> {
this.fieldValueSelections = new HashMap<>(); this.fieldValueSelections = new HashMap<>();
this.excludeArchivedCertificates = excludeArchivedCertificates; this.excludeArchivedCertificates = excludeArchivedCertificates;
} }
/** /**
* Specify the entity id that certificates must have to be considered * Specify the entity id that certificates must have to be considered
* as matching. * as matching.
@ -249,6 +250,7 @@ public abstract class CertificateSelector<T extends Certificate> {
/** /**
* Specify the authority key identifier to find certificate(s). * Specify the authority key identifier to find certificate(s).
*
* @param authorityKeyIdentifier the string of the AKI associated with the certificate. * @param authorityKeyIdentifier the string of the AKI associated with the certificate.
* @return this instance * @return this instance
*/ */
@ -289,7 +291,7 @@ public abstract class CertificateSelector<T extends Certificate> {
/** /**
* Set a field name and value to match. * Set a field name and value to match.
* *
* @param name the field name to query * @param name the field name to query
* @param value the value to query * @param value the value to query
*/ */
protected void setFieldValue(final String name, final Object value) { protected void setFieldValue(final String name, final Object value) {
@ -307,8 +309,7 @@ public abstract class CertificateSelector<T extends Certificate> {
); );
} }
if (value instanceof byte[]) { if (value instanceof byte[] valueBytes) {
byte[] valueBytes = (byte[]) value;
Preconditions.checkArgument( Preconditions.checkArgument(
ArrayUtils.isNotEmpty(valueBytes), ArrayUtils.isNotEmpty(valueBytes),
@ -329,7 +330,7 @@ public abstract class CertificateSelector<T extends Certificate> {
* *
* @return a KeyStore populated with the matching certificates, if any * @return a KeyStore populated with the matching certificates, if any
* @throws KeyStoreException if there is a problem instantiating a JKS-formatted KeyStore * @throws KeyStoreException if there is a problem instantiating a JKS-formatted KeyStore
* @throws IOException if there is a problem populating the keystore * @throws IOException if there is a problem populating the keystore
*/ */
public KeyStore getKeyStore() throws KeyStoreException, IOException { public KeyStore getKeyStore() throws KeyStoreException, IOException {
KeyStore keyStore = KeyStore.getInstance("JKS"); KeyStore keyStore = KeyStore.getInstance("JKS");
@ -350,7 +351,7 @@ public abstract class CertificateSelector<T extends Certificate> {
* of this {@link CertificateSelector}. * of this {@link CertificateSelector}.
* *
* @return a Criterion that can be used to query for certificates matching the configuration of * @return a Criterion that can be used to query for certificates matching the configuration of
* this instance * this instance
*/ */
Predicate[] getCriterion(final CriteriaBuilder criteriaBuilder) { Predicate[] getCriterion(final CriteriaBuilder criteriaBuilder) {
Predicate[] predicates = new Predicate[fieldValueSelections.size()]; Predicate[] predicates = new Predicate[fieldValueSelections.size()];
@ -359,7 +360,8 @@ public abstract class CertificateSelector<T extends Certificate> {
int i = 0; int i = 0;
for (Map.Entry<String, Object> fieldValueEntry : fieldValueSelections.entrySet()) { for (Map.Entry<String, Object> fieldValueEntry : fieldValueSelections.entrySet()) {
predicates[i++] = criteriaBuilder.equal(root.get(fieldValueEntry.getKey()), fieldValueEntry.getValue()); predicates[i++] =
criteriaBuilder.equal(root.get(fieldValueEntry.getKey()), fieldValueEntry.getValue());
} }
if (this.excludeArchivedCertificates) { if (this.excludeArchivedCertificates) {
@ -378,6 +380,7 @@ public abstract class CertificateSelector<T extends Certificate> {
/** /**
* Configures the selector to query for archived and unarchived certificates. * Configures the selector to query for archived and unarchived certificates.
*
* @return the selector * @return the selector
*/ */
public CertificateSelector<T> includeArchived() { public CertificateSelector<T> includeArchived() {

View File

@ -12,9 +12,7 @@ import org.apache.commons.lang3.StringUtils;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import java.util.UUID; import java.util.UUID;
/** /**
@ -60,7 +58,7 @@ public abstract class ReferenceManifestSelector<T extends ReferenceManifest> {
/** /**
* Standard Constructor for the Selector. * Standard Constructor for the Selector.
* *
* @param referenceTypeClass the type of Reference Manifest to process. * @param referenceTypeClass the type of Reference Manifest to process.
* @param excludeArchivedRims true if excluding archived RIMs * @param excludeArchivedRims true if excluding archived RIMs
*/ */
public ReferenceManifestSelector(final Class<T> referenceTypeClass, public ReferenceManifestSelector(final Class<T> referenceTypeClass,
@ -88,6 +86,7 @@ public abstract class ReferenceManifestSelector<T extends ReferenceManifest> {
/** /**
* Specify the file name of the object to grab. * Specify the file name of the object to grab.
*
* @param fileName the name of the file associated with the rim * @param fileName the name of the file associated with the rim
* @return instance of the manifest in relation to the filename. * @return instance of the manifest in relation to the filename.
*/ */
@ -98,6 +97,7 @@ public abstract class ReferenceManifestSelector<T extends ReferenceManifest> {
/** /**
* Specify the RIM Type to match. * Specify the RIM Type to match.
*
* @param rimType the type of rim * @param rimType the type of rim
* @return this instance * @return this instance
*/ */
@ -109,7 +109,7 @@ public abstract class ReferenceManifestSelector<T extends ReferenceManifest> {
/** /**
* Set a field name and value to match. * Set a field name and value to match.
* *
* @param name the field name to query * @param name the field name to query
* @param value the value to query * @param value the value to query
*/ */
protected void setFieldValue(final String name, final Object value) { protected void setFieldValue(final String name, final Object value) {
@ -127,8 +127,7 @@ public abstract class ReferenceManifestSelector<T extends ReferenceManifest> {
); );
} }
if (value instanceof byte[]) { if (value instanceof byte[] valueBytes) {
byte[] valueBytes = (byte[]) value;
Preconditions.checkArgument( Preconditions.checkArgument(
ArrayUtils.isNotEmpty(valueBytes), ArrayUtils.isNotEmpty(valueBytes),
@ -155,7 +154,8 @@ public abstract class ReferenceManifestSelector<T extends ReferenceManifest> {
int i = 0; int i = 0;
for (Map.Entry<String, Object> fieldValueEntry : fieldValueSelections.entrySet()) { for (Map.Entry<String, Object> fieldValueEntry : fieldValueSelections.entrySet()) {
predicates[i++] = criteriaBuilder.equal(root.get(fieldValueEntry.getKey()), fieldValueEntry.getValue()); predicates[i++] =
criteriaBuilder.equal(root.get(fieldValueEntry.getKey()), fieldValueEntry.getValue());
} }
if (this.excludeArchivedRims) { if (this.excludeArchivedRims) {

View File

@ -25,13 +25,13 @@ import java.util.List;
* was removed. This change was not TCG-compliant, as the auto-generated code * was removed. This change was not TCG-compliant, as the auto-generated code
* would produce something like: * would produce something like:
* <p>&nbsp; * <p>&nbsp;
* <pre> * <pre>
* &lt;PcrValue PcrNumber="0"&gt;06fl7EXo34MWxuLq9kcXI9la9NA=&lt;/ns3:PcrValue&gt; * &lt;PcrValue PcrNumber="0"&gt;06fl7EXo34MWxuLq9kcXI9la9NA=&lt;/ns3:PcrValue&gt;
* </pre> * </pre>
* <p> * <p>
* but using TPMMeasurementRecords result in something like: * but using TPMMeasurementRecords result in something like:
* <p>&nbsp; * <p>&nbsp;
* <pre> * <pre>
* &lt;PcrValue PcrNumber="2"&gt; * &lt;PcrValue PcrNumber="2"&gt;
* &lt;hash&gt; * &lt;hash&gt;
* &lt;digest&gt;AAECAwQFBgcICQoLDA0ODxAREhM=&lt;/digest&gt; * &lt;digest&gt;AAECAwQFBgcICQoLDA0ODxAREhM=&lt;/digest&gt;
@ -39,14 +39,13 @@ import java.util.List;
* &lt;/hash&gt; * &lt;/hash&gt;
* &lt;/PcrValue&gt; * &lt;/PcrValue&gt;
* </pre> * </pre>
*
*/ */
@Log4j2 @Log4j2
@XmlAccessorType(XmlAccessType.FIELD) @XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PcrComposite", @XmlType(name = "PcrComposite",
namespace = "http://www.trustedcomputinggroup.org/XML/SCHEMA/" namespace = "http://www.trustedcomputinggroup.org/XML/SCHEMA/"
+ "Integrity_Report_v1_0#", propOrder = {"pcrSelection", + "Integrity_Report_v1_0#", propOrder = {"pcrSelection",
"valueSize", "pcrValueList" }) "valueSize", "pcrValueList"})
@Embeddable @Embeddable
public class PcrComposite { public class PcrComposite {
@ -69,11 +68,9 @@ public class PcrComposite {
/** /**
* Constructor used to create a PcrComposite object. * Constructor used to create a PcrComposite object.
* *
* @param pcrSelection * @param pcrSelection {@link PcrSelection } object, identifies which TPM PCRs are
* {@link PcrSelection } object, identifies which TPM PCRs are * quoted
* quoted * @param pcrValueList List of TPMMeasurementRecords representing the PCR values
* @param pcrValueList
* List of TPMMeasurementRecords representing the PCR values
*/ */
public PcrComposite(final PcrSelection pcrSelection, public PcrComposite(final PcrSelection pcrSelection,
final List<TPMMeasurementRecord> pcrValueList) { final List<TPMMeasurementRecord> pcrValueList) {
@ -90,13 +87,11 @@ public class PcrComposite {
} }
/** /**
* Gets the value of the valueSize property, the length in bytes of the * Gets the value of the valueSize property, the length in bytes of the
* array of PcrValue complex types. * array of PcrValue complex types.
* *
* @return int value representing the valueSize * @return int value representing the valueSize
*
*/ */
@XmlElement(name = "ValueSize", required = true) @XmlElement(name = "ValueSize", required = true)
public final int getValueSize() { public final int getValueSize() {

View File

@ -39,7 +39,7 @@ import java.util.List;
@XmlType(name = "PcrInfoShort", @XmlType(name = "PcrInfoShort",
namespace = "http://www.trustedcomputinggroup.org/XML/SCHEMA/" namespace = "http://www.trustedcomputinggroup.org/XML/SCHEMA/"
+ "Integrity_Report_v1_0#", propOrder = {"pcrSelection", + "Integrity_Report_v1_0#", propOrder = {"pcrSelection",
"localityAtRelease", "compositeHash", "pcrComposite" }) "localityAtRelease", "compositeHash", "pcrComposite"})
@Embeddable @Embeddable
public class PcrInfoShort { public class PcrInfoShort {
@ -77,16 +77,12 @@ public class PcrInfoShort {
/** /**
* Constructor used to create a PcrInfoShort object. * Constructor used to create a PcrInfoShort object.
* *
* @param pcrSelection * @param pcrSelection PcrSelection defines which TPM PCRs are used in the TPM Quote.
* PcrSelection defines which TPM PCRs are used in the TPM Quote. * @param localityAtRelease short value includes locality information to provide the
* @param localityAtRelease * requestor a more complete view of the current platform
* short value includes locality information to provide the * configuration
* requestor a more complete view of the current platform * @param compositeHash A hash of PcrComposite
* configuration * @param pcrComposite A structure containing the actual values of the PCRs quoted.
* @param compositeHash
* A hash of PcrComposite
* @param pcrComposite
* A structure containing the actual values of the PCRs quoted.
*/ */
public PcrInfoShort(final PcrSelection pcrSelection, public PcrInfoShort(final PcrSelection pcrSelection,
final short localityAtRelease, final byte[] compositeHash, final short localityAtRelease, final byte[] compositeHash,
@ -126,8 +122,7 @@ public class PcrInfoShort {
* collected PCR values match the digest in the quote. * collected PCR values match the digest in the quote.
* *
* @return byte array containing the digest * @return byte array containing the digest
* @throws NoSuchAlgorithmException * @throws NoSuchAlgorithmException if MessageDigest doesn't recognize "SHA-1" or "SHA-256"
* if MessageDigest doesn't recognize "SHA-1" or "SHA-256"
*/ */
public final byte[] getCalculatedDigest() throws NoSuchAlgorithmException { public final byte[] getCalculatedDigest() throws NoSuchAlgorithmException {
if (this.isTpm1()) { if (this.isTpm1()) {
@ -159,7 +154,7 @@ public class PcrInfoShort {
byteBuffer.put(this.pcrSelection.getValue()); byteBuffer.put(this.pcrSelection.getValue());
byteBuffer.putInt(pcrComposite.getValueSize()); byteBuffer.putInt(pcrComposite.getValueSize());
for (TPMMeasurementRecord record: pcrComposite.getPcrValueList()) { for (TPMMeasurementRecord record : pcrComposite.getPcrValueList()) {
byteBuffer.put(record.getHash().getDigest()); byteBuffer.put(record.getHash().getDigest());
} }

View File

@ -6,7 +6,6 @@ import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlSchemaType; import jakarta.xml.bind.annotation.XmlSchemaType;
import jakarta.xml.bind.annotation.XmlType; import jakarta.xml.bind.annotation.XmlType;
import lombok.extern.java.Log;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
@ -27,12 +26,11 @@ import java.util.Arrays;
@Embeddable @Embeddable
public class PcrSelection { public class PcrSelection {
private static final int MAX_SIZE_PCR_ARRAY = 3;
/** /**
* All PCRs are on. * All PCRs are on.
*/ */
public static final int ALL_PCRS_ON = 0xffffff; public static final int ALL_PCRS_ON = 0xffffff;
private static final int MAX_SIZE_PCR_ARRAY = 3;
@XmlAttribute(name = "PcrSelect", required = true) @XmlAttribute(name = "PcrSelect", required = true)
private final byte[] pcrSelect; private final byte[] pcrSelect;
@ -50,9 +48,7 @@ public class PcrSelection {
* Each byte represents 8 PCRs. Byte 0 indicates PCRs 0-7, byte 1 8-15 and * Each byte represents 8 PCRs. Byte 0 indicates PCRs 0-7, byte 1 8-15 and
* so on. For each byte, the individual bits represent a corresponding PCR. * so on. For each byte, the individual bits represent a corresponding PCR.
* *
* @param pcrSelect * @param pcrSelect byte array indicating which PCRS are selected
* byte array indicating which PCRS are selected
*
*/ */
public PcrSelection(final byte[] pcrSelect) { public PcrSelection(final byte[] pcrSelect) {
if (pcrSelect == null) { if (pcrSelect == null) {
@ -74,8 +70,7 @@ public class PcrSelection {
* selection value. For example, to select the first 3 PCRs, one would use * selection value. For example, to select the first 3 PCRs, one would use
* the long value 7 (b0000 0000 0000 0111). * the long value 7 (b0000 0000 0000 0111).
* *
* @param pcrSelectLong * @param pcrSelectLong long value representing the bits to be selected
* long value representing the bits to be selected
*/ */
public PcrSelection(final long pcrSelectLong) { public PcrSelection(final long pcrSelectLong) {
if (pcrSelectLong > ALL_PCRS_ON) { if (pcrSelectLong > ALL_PCRS_ON) {

View File

@ -72,19 +72,13 @@ public final class InetAddressType implements UserType {
* Converts the IP address that is stored as a <code>String</code> and * Converts the IP address that is stored as a <code>String</code> and
* converts it to an <code>InetAddress</code>. * converts it to an <code>InetAddress</code>.
* *
* @param rs * @param rs result set
* result set * @param index column names
* @param index * @param session session
* column names * @param owner owner
* @param session
* session
* @param owner
* owner
* @return InetAddress of String * @return InetAddress of String
* @throws HibernateException * @throws HibernateException if unable to convert the String to an InetAddress
* if unable to convert the String to an InetAddress * @throws SQLException if unable to retrieve the String from the result set
* @throws SQLException
* if unable to retrieve the String from the result set
*/ */
@Override @Override
public Object nullSafeGet(final ResultSet rs, final int index, public Object nullSafeGet(final ResultSet rs, final int index,
@ -107,9 +101,9 @@ public final class InetAddressType implements UserType {
* Converts the <code>InetAddress</code> <code>value</code> to a * Converts the <code>InetAddress</code> <code>value</code> to a
* <code>String</code> and stores it in the database. * <code>String</code> and stores it in the database.
* *
* @param st prepared statement * @param st prepared statement
* @param value InetAddress * @param value InetAddress
* @param index index * @param index index
* @param session session * @param session session
* @throws SQLException if unable to set the value in the result set * @throws SQLException if unable to set the value in the result set
*/ */
@ -165,7 +159,7 @@ public final class InetAddressType implements UserType {
* immutable. * immutable.
* *
* @param cached cached * @param cached cached
* @param owner owner * @param owner owner
* @return cached * @return cached
*/ */
@Override @Override
@ -178,8 +172,8 @@ public final class InetAddressType implements UserType {
* immutable. * immutable.
* *
* @param original original * @param original original
* @param target target * @param target target
* @param owner owner * @param owner owner
* @return original * @return original
*/ */
@Override @Override

View File

@ -26,7 +26,7 @@ import java.util.Objects;
* Hibernate. This class provides the mapping from <code>X509Certificate</code> * Hibernate. This class provides the mapping from <code>X509Certificate</code>
* to Hibernate commands to JDBC. * to Hibernate commands to JDBC.
*/ */
@NoArgsConstructor(access= AccessLevel.PUBLIC) @NoArgsConstructor(access = AccessLevel.PUBLIC)
public final class X509CertificateType implements UserType { public final class X509CertificateType implements UserType {
@Override @Override
@ -73,19 +73,13 @@ public final class X509CertificateType implements UserType {
* Converts the X509Certificate that is stored as a <code>String</code> and * Converts the X509Certificate that is stored as a <code>String</code> and
* converts it to an <code>X509Certificate</code>. * converts it to an <code>X509Certificate</code>.
* *
* @param rs * @param rs result set
* result set * @param names column names
* @param names * @param session session
* column names * @param owner owner
* @param session
* session
* @param owner
* owner
* @return X509Certificate of String * @return X509Certificate of String
* @throws HibernateException * @throws HibernateException if unable to convert the String to an X509Certificate
* if unable to convert the String to an X509Certificate * @throws SQLException if unable to retrieve the String from the result set
* @throws SQLException
* if unable to retrieve the String from the result set
*/ */
@Override @Override
public Object nullSafeGet(final ResultSet rs, final int names, public Object nullSafeGet(final ResultSet rs, final int names,
@ -111,9 +105,9 @@ public final class X509CertificateType implements UserType {
* Converts the <code>X509Certificate</code> <code>value</code> to a * Converts the <code>X509Certificate</code> <code>value</code> to a
* <code>String</code> and stores it in the database. * <code>String</code> and stores it in the database.
* *
* @param st prepared statement * @param st prepared statement
* @param value X509Certificate * @param value X509Certificate
* @param index index * @param index index
* @param session session * @param session session
* @throws SQLException if unable to set the value in the result set * @throws SQLException if unable to set the value in the result set
*/ */
@ -131,7 +125,7 @@ public final class X509CertificateType implements UserType {
} catch (Exception e) { } catch (Exception e) {
final String msg = final String msg =
String.format("unable to convert certificate: %s", String.format("unable to convert certificate: %s",
value.toString()); value);
throw new HibernateException(msg, e); throw new HibernateException(msg, e);
} }
} }
@ -178,7 +172,7 @@ public final class X509CertificateType implements UserType {
* immutable. * immutable.
* *
* @param cached cached * @param cached cached
* @param owner owner * @param owner owner
* @return cached * @return cached
*/ */
@Override @Override
@ -191,8 +185,8 @@ public final class X509CertificateType implements UserType {
* immutable. * immutable.
* *
* @param original original * @param original original
* @param target target * @param target target
* @param owner owner * @param owner owner
* @return original * @return original
*/ */
@Override @Override

View File

@ -3,7 +3,6 @@ package hirs.attestationca.persist.util;
import hirs.attestationca.persist.entity.userdefined.certificate.ComponentResult; import hirs.attestationca.persist.entity.userdefined.certificate.ComponentResult;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentIdentifier; import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentIdentifier;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.V2.ComponentIdentifierV2; import hirs.attestationca.persist.entity.userdefined.certificate.attributes.V2.ComponentIdentifierV2;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.bouncycastle.asn1.DERUTF8String; import org.bouncycastle.asn1.DERUTF8String;
@ -35,6 +34,7 @@ public final class AcaPciIds {
/** /**
* Iterate through all components and translate PCI hardware IDs as necessary. It will only * Iterate through all components and translate PCI hardware IDs as necessary. It will only
* translate ComponentIdentifierV2+ objects as it relies on Component Class information. * translate ComponentIdentifierV2+ objects as it relies on Component Class information.
*
* @param components List of ComponentIdentifiers. * @param components List of ComponentIdentifiers.
* @return the translated list of ComponentIdentifiers. * @return the translated list of ComponentIdentifiers.
*/ */
@ -58,6 +58,7 @@ public final class AcaPciIds {
/** /**
* Iterate through all components and translate PCI hardware IDs as necessary. It will only * Iterate through all components and translate PCI hardware IDs as necessary. It will only
* translate ComponentResults objects as it relies on Component Class information. * translate ComponentResults objects as it relies on Component Class information.
*
* @param componentResults List of ComponentResults. * @param componentResults List of ComponentResults.
* @return the translated list of ComponentResults. * @return the translated list of ComponentResults.
*/ */
@ -75,6 +76,7 @@ public final class AcaPciIds {
/** /**
* Translate Vendor and Device IDs, if found, in ComponentIdentifierV2 objects. * Translate Vendor and Device IDs, if found, in ComponentIdentifierV2 objects.
* It will only translate ID values, any other value will pass through. * It will only translate ID values, any other value will pass through.
*
* @param component ComponentIdentifierV2 object. * @param component ComponentIdentifierV2 object.
* @return the translated ComponentIdentifierV2 object. * @return the translated ComponentIdentifierV2 object.
*/ */
@ -113,6 +115,7 @@ public final class AcaPciIds {
/** /**
* Translate Vendor and Device IDs, if found, in ComponentResult objects. * Translate Vendor and Device IDs, if found, in ComponentResult objects.
* It will only translate ID values, any other value will pass through. * It will only translate ID values, any other value will pass through.
*
* @param componentResult ComponentResult object. * @param componentResult ComponentResult object.
* @return the translated ComponentResult object. * @return the translated ComponentResult object.
*/ */

View File

@ -1,8 +1,6 @@
package hirs.attestationca.persist.util; package hirs.attestationca.persist.util;
import hirs.attestationca.persist.entity.userdefined.certificate.CertificateVariables; import hirs.attestationca.persist.entity.userdefined.certificate.CertificateVariables;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Base64;
@ -17,6 +15,7 @@ public final class CredentialHelper {
/** /**
* Small method to check if the certificate is a PEM. * Small method to check if the certificate is a PEM.
*
* @param possiblePEM header information * @param possiblePEM header information
* @return true if it is. * @return true if it is.
*/ */
@ -27,6 +26,7 @@ public final class CredentialHelper {
/** /**
* Small method to check if there are multi pem files * Small method to check if there are multi pem files
*
* @param possiblePEM header information * @param possiblePEM header information
* @return true if it is. * @return true if it is.
*/ */
@ -45,6 +45,7 @@ public final class CredentialHelper {
/** /**
* Method to remove header footer information from PEM * Method to remove header footer information from PEM
*
* @param pemFile string representation of the file * @param pemFile string representation of the file
* @return a cleaned up raw byte object * @return a cleaned up raw byte object
*/ */
@ -59,6 +60,7 @@ public final class CredentialHelper {
/** /**
* The method is used to remove unwanted spaces and other artifacts from the certificate. * The method is used to remove unwanted spaces and other artifacts from the certificate.
*
* @param certificateBytes raw byte form * @param certificateBytes raw byte form
* @return a cleaned up byte form * @return a cleaned up byte form
*/ */
@ -112,6 +114,7 @@ public final class CredentialHelper {
/** /**
* Return the string associated with the boolean slot. * Return the string associated with the boolean slot.
*
* @param bit associated with the location in the array. * @param bit associated with the location in the array.
* @return string value of the bit set. * @return string value of the bit set.
*/ */
@ -157,6 +160,7 @@ public final class CredentialHelper {
* This method is to take the DNs from certificates and sort them in an order * This method is to take the DNs from certificates and sort them in an order
* that will be used to lookup issuer certificates. This will not be stored in * that will be used to lookup issuer certificates. This will not be stored in
* the certificate, just the DB for lookup. * the certificate, just the DB for lookup.
*
* @param distinguishedName the original DN string. * @param distinguishedName the original DN string.
* @return a modified string of sorted DNs * @return a modified string of sorted DNs
*/ */

View File

@ -33,8 +33,8 @@ public class CredentialValidator extends SupplyChainCredentialValidator {
/** /**
* Checks if the endorsement credential is valid. * Checks if the endorsement credential is valid.
* *
* @param ec the endorsement credential to verify. * @param ec the endorsement credential to verify.
* @param trustStore trust store holding trusted certificates. * @param trustStore trust store holding trusted certificates.
* @param acceptExpired whether or not to accept expired and not yet valid certificates * @param acceptExpired whether or not to accept expired and not yet valid certificates
* as valid. * as valid.
* @return the result of the validation. * @return the result of the validation.
@ -98,8 +98,8 @@ public class CredentialValidator extends SupplyChainCredentialValidator {
/** /**
* Checks if the platform credential is valid. * Checks if the platform credential is valid.
* *
* @param pc The platform credential to verify. * @param pc The platform credential to verify.
* @param trustStore trust store holding trusted certificates. * @param trustStore trust store holding trusted certificates.
* @param acceptExpired whether or not to accept expired certificates as valid. * @param acceptExpired whether or not to accept expired certificates as valid.
* @return The result of the validation. * @return The result of the validation.
*/ */
@ -163,16 +163,17 @@ public class CredentialValidator extends SupplyChainCredentialValidator {
/** /**
* Checks if the platform credential's attributes are valid. * Checks if the platform credential's attributes are valid.
* @param platformCredential The platform credential to verify. *
* @param deviceInfoReport The device info report containing * @param platformCredential The platform credential to verify.
* serial number of the platform to be validated. * @param deviceInfoReport The device info report containing
* @param endorsementCredential The endorsement credential supplied from the same * serial number of the platform to be validated.
* identity request as the platform credential. * @param endorsementCredential The endorsement credential supplied from the same
* @param componentResultRepository db access to component result of mismatching * identity request as the platform credential.
* @param componentAttributeRepository db access to component attribute match status * @param componentResultRepository db access to component result of mismatching
* @param componentInfos list of device components * @param componentAttributeRepository db access to component attribute match status
* @param provisionSessionId UUID associated with this run of the provision * @param componentInfos list of device components
* @param ignoreRevisionAttribute policy flag to ignore the revision attribute * @param provisionSessionId UUID associated with this run of the provision
* @param ignoreRevisionAttribute policy flag to ignore the revision attribute
* @return The result of the validation. * @return The result of the validation.
*/ */
public static AppraisalStatus validatePlatformCredentialAttributes( public static AppraisalStatus validatePlatformCredentialAttributes(
@ -223,16 +224,17 @@ public class CredentialValidator extends SupplyChainCredentialValidator {
/** /**
* Checks if the delta credential's attributes are valid. * Checks if the delta credential's attributes are valid.
* @param deviceInfoReport The device info report containing *
* serial number of the platform to be validated. * @param deviceInfoReport The device info report containing
* @param basePlatformCredential the base credential from the same identity request * serial number of the platform to be validated.
* * as the delta credential. * @param basePlatformCredential the base credential from the same identity request
* @param deltaMapping delta certificates associated with the * * as the delta credential.
* * delta supply validation. * @param deltaMapping delta certificates associated with the
* @param componentInfos list of device components * * delta supply validation.
* @param componentResultRepository repository for component results * @param componentInfos list of device components
* @param componentResultRepository repository for component results
* @param componentAttributeRepository repository for the attribute status * @param componentAttributeRepository repository for the attribute status
* @param provisionSessionId the session id to share * @param provisionSessionId the session id to share
* @return the result of the validation. * @return the result of the validation.
*/ */
public static AppraisalStatus validateDeltaPlatformCredentialAttributes( public static AppraisalStatus validateDeltaPlatformCredentialAttributes(

View File

@ -63,13 +63,38 @@ public class PcrValidator {
*/ */
public PcrValidator(final String[] pcrValues) { public PcrValidator(final String[] pcrValues) {
baselinePcrs = new String[TPMMeasurementRecord.MAX_PCR_ID + 1]; baselinePcrs = new String[TPMMeasurementRecord.MAX_PCR_ID + 1];
for (int i = 0; i <= TPMMeasurementRecord.MAX_PCR_ID; i++) { System.arraycopy(pcrValues, 0, baselinePcrs, 0, TPMMeasurementRecord.MAX_PCR_ID + 1);
baselinePcrs[i] = pcrValues[i]; }
public static String[] buildStoredPcrs(final String pcrContent, final int algorithmLength) {
// we have a full set of PCR values
String[] pcrSet = pcrContent.split("\\n");
String[] storedPcrs = new String[TPMMeasurementRecord.MAX_PCR_ID + 1];
// we need to scroll through the entire list until we find
// a matching hash length
int offset = 1;
for (int i = 0; i < pcrSet.length; i++) {
if (pcrSet[i].contains("sha")) {
// entered a new set, check size
if (pcrSet[i + offset].split(":")[1].trim().length()
== algorithmLength) {
// found the matching set
for (int j = 0; j <= TPMMeasurementRecord.MAX_PCR_ID; j++) {
storedPcrs[j] = pcrSet[++i].split(":")[1].trim();
}
break;
}
}
} }
return storedPcrs;
} }
/** /**
* Getter for the array of baseline PCRs. * Getter for the array of baseline PCRs.
*
* @return instance of the PCRs. * @return instance of the PCRs.
*/ */
public String[] getBaselinePcrs() { public String[] getBaselinePcrs() {
@ -78,6 +103,7 @@ public class PcrValidator {
/** /**
* Setter for the array of baseline PCRs. * Setter for the array of baseline PCRs.
*
* @param baselinePcrs instance of the PCRs. * @param baselinePcrs instance of the PCRs.
*/ */
public void setBaselinePcrs(final String[] baselinePcrs) { public void setBaselinePcrs(final String[] baselinePcrs) {
@ -88,7 +114,7 @@ public class PcrValidator {
* Compares the baseline pcr list and the quote pcr list. If the * Compares the baseline pcr list and the quote pcr list. If the
* ignore flags are set, 10 and 17-19 will be skipped for comparison. * ignore flags are set, 10 and 17-19 will be skipped for comparison.
* *
* @param storedPcrs non-baseline pcr list * @param storedPcrs non-baseline pcr list
* @param policySettings db entity that holds all of policy * @param policySettings db entity that holds all of policy
* @return a StringBuilder that is empty if everything passes. * @return a StringBuilder that is empty if everything passes.
*/ */
@ -128,9 +154,10 @@ public class PcrValidator {
/** /**
* Checks that the expected FM events occurring. There are policy options that * Checks that the expected FM events occurring. There are policy options that
* will ignore certin PCRs, Event Types and Event Variables present. * will ignore certin PCRs, Event Types and Event Variables present.
*
* @param tcgMeasurementLog Measurement log from the client * @param tcgMeasurementLog Measurement log from the client
* @param eventValueMap The events stored as baseline to compare * @param eventValueMap The events stored as baseline to compare
* @param policySettings db entity that holds all of policy * @param policySettings db entity that holds all of policy
* @return the events that didn't pass * @return the events that didn't pass
*/ */
public List<TpmPcrEvent> validateTpmEvents(final TCGEventLog tcgMeasurementLog, public List<TpmPcrEvent> validateTpmEvents(final TCGEventLog tcgMeasurementLog,
@ -151,11 +178,11 @@ public class PcrValidator {
log.info(String.format("GPT Ignored -> %s", tpe)); log.info(String.format("GPT Ignored -> %s", tpe));
} else if (policySettings.isIgnoreOsEvtEnabled() && ( } else if (policySettings.isIgnoreOsEvtEnabled() && (
tpe.getEventTypeStr().contains(EVT_EFI_BOOT) tpe.getEventTypeStr().contains(EVT_EFI_BOOT)
|| tpe.getEventTypeStr().contains(EVT_EFI_VAR))) { || tpe.getEventTypeStr().contains(EVT_EFI_VAR))) {
log.info(String.format("OS Evt Ignored -> %s", tpe)); log.info(String.format("OS Evt Ignored -> %s", tpe));
} else if (policySettings.isIgnoreOsEvtEnabled() && ( } else if (policySettings.isIgnoreOsEvtEnabled() && (
tpe.getEventTypeStr().contains(EVT_EFI_CFG) tpe.getEventTypeStr().contains(EVT_EFI_CFG)
&& tpe.getEventContentStr().contains("SecureBoot"))) { && tpe.getEventContentStr().contains("SecureBoot"))) {
log.info(String.format("OS Evt Config Ignored -> %s", tpe)); log.info(String.format("OS Evt Config Ignored -> %s", tpe));
} else { } else {
if (!eventValueMap.containsKey(tpe.getEventDigestStr())) { if (!eventValueMap.containsKey(tpe.getEventDigestStr())) {
@ -171,8 +198,8 @@ public class PcrValidator {
/** /**
* Compares hashs to validate the quote from the client. * Compares hashs to validate the quote from the client.
* *
* @param tpmQuote the provided quote * @param tpmQuote the provided quote
* @param storedPcrs values from the RIM file * @param storedPcrs values from the RIM file
* @param policySettings db entity that holds all of policy * @param policySettings db entity that holds all of policy
* @return true if validated, false if not * @return true if validated, false if not
*/ */
@ -211,10 +238,10 @@ public class PcrValidator {
try { try {
// The calculated string is being used in the contains method // The calculated string is being used in the contains method
// because the TPM Quote's hash isn't just for PCR values, // because the TPM Quote's hash isn't just for PCR values,
// it contains the calculated digest of the PCRs, along with // it contains the calculated digest of the PCRs, along with
// other information. // other information.
String calculatedString = Hex.encodeHexString( String calculatedString = Hex.encodeHexString(
pcrInfoShort.getCalculatedDigest()); pcrInfoShort.getCalculatedDigest());
log.debug("Validating PCR information with the following:" + log.debug("Validating PCR information with the following:" +
@ -230,30 +257,4 @@ public class PcrValidator {
return validated; return validated;
} }
public static String[] buildStoredPcrs(final String pcrContent, final int algorithmLength) {
// we have a full set of PCR values
String[] pcrSet = pcrContent.split("\\n");
String[] storedPcrs = new String[TPMMeasurementRecord.MAX_PCR_ID + 1];
// we need to scroll through the entire list until we find
// a matching hash length
int offset = 1;
for (int i = 0; i < pcrSet.length; i++) {
if (pcrSet[i].contains("sha")) {
// entered a new set, check size
if (pcrSet[i + offset].split(":")[1].trim().length()
== algorithmLength) {
// found the matching set
for (int j = 0; j <= TPMMeasurementRecord.MAX_PCR_ID; j++) {
storedPcrs[j] = pcrSet[++i].split(":")[1].trim();
}
break;
}
}
}
return storedPcrs;
}
} }

View File

@ -36,7 +36,7 @@ import java.util.Set;
@Log4j2 @Log4j2
@NoArgsConstructor @NoArgsConstructor
public class SupplyChainCredentialValidator { public class SupplyChainCredentialValidator {
/** /**
* used to identify and clear a nuc * used to identify and clear a nuc
@ -78,13 +78,10 @@ public class SupplyChainCredentialValidator {
* continue to try to find the signing cert of the intermediate cert. It will continue searching * continue to try to find the signing cert of the intermediate cert. It will continue searching
* until it follows the chain up to a root (self-signed) cert. * until it follows the chain up to a root (self-signed) cert.
* *
* @param cert * @param cert certificate to validate
* certificate to validate * @param trustStore trust store holding trusted root certificates and intermediate certificates
* @param trustStore
* trust store holding trusted root certificates and intermediate certificates
* @return the certificate chain if validation is successful * @return the certificate chain if validation is successful
* @throws SupplyChainValidatorException * @throws SupplyChainValidatorException if the verification is not successful
* if the verification is not successful
*/ */
public static String verifyCertificate(final X509AttributeCertificateHolder cert, public static String verifyCertificate(final X509AttributeCertificateHolder cert,
final KeyStore trustStore) throws SupplyChainValidatorException { final KeyStore trustStore) throws SupplyChainValidatorException {
@ -122,13 +119,10 @@ public class SupplyChainCredentialValidator {
* continue to try to find the signing cert of the intermediate cert. It will continue searching * continue to try to find the signing cert of the intermediate cert. It will continue searching
* until it follows the chain up to a root (self-signed) cert. * until it follows the chain up to a root (self-signed) cert.
* *
* @param cert * @param cert certificate to validate
* certificate to validate * @param trustStore trust store holding trusted root certificates and intermediate certificates
* @param trustStore
* trust store holding trusted root certificates and intermediate certificates
* @return the certificate chain if validation is successful * @return the certificate chain if validation is successful
* @throws SupplyChainValidatorException * @throws SupplyChainValidatorException if the verification is not successful
* if the verification is not successful
*/ */
public static boolean verifyCertificate(final X509Certificate cert, public static boolean verifyCertificate(final X509Certificate cert,
final KeyStore trustStore) throws SupplyChainValidatorException { final KeyStore trustStore) throws SupplyChainValidatorException {
@ -164,12 +158,10 @@ public class SupplyChainCredentialValidator {
* to find the signing cert of the intermediate cert. It will continue searching until it * to find the signing cert of the intermediate cert. It will continue searching until it
* follows the chain up to a root (self-signed) cert. * follows the chain up to a root (self-signed) cert.
* *
* @param cert * @param cert certificate to validate
* certificate to validate * @param additionalCerts Set of certs to validate against
* @param additionalCerts
* Set of certs to validate against
* @return String status of the cert chain validation - * @return String status of the cert chain validation -
* blank if successful, error message otherwise * blank if successful, error message otherwise
* @throws SupplyChainValidatorException tried to validate using null certificates * @throws SupplyChainValidatorException tried to validate using null certificates
*/ */
public static String validateCertChain(final X509AttributeCertificateHolder cert, public static String validateCertChain(final X509AttributeCertificateHolder cert,
@ -227,12 +219,10 @@ public class SupplyChainCredentialValidator {
* to find the signing cert of the intermediate cert. It will continue searching until it * to find the signing cert of the intermediate cert. It will continue searching until it
* follows the chain up to a root (self-signed) cert. * follows the chain up to a root (self-signed) cert.
* *
* @param cert * @param cert certificate to validate
* certificate to validate * @param additionalCerts Set of certs to validate against
* @param additionalCerts
* Set of certs to validate against
* @return String status of the cert chain validation - * @return String status of the cert chain validation -
* blank if successful, error message otherwise * blank if successful, error message otherwise
* @throws SupplyChainValidatorException tried to validate using null certificates * @throws SupplyChainValidatorException tried to validate using null certificates
*/ */
public static String validateCertChain(final X509Certificate cert, public static String validateCertChain(final X509Certificate cert,
@ -277,7 +267,8 @@ public class SupplyChainCredentialValidator {
/** /**
* Parses the output from PACCOR's allcomponents.sh script into ComponentInfo objects. * Parses the output from PACCOR's allcomponents.sh script into ComponentInfo objects.
* @param hostName the host machine associated with the component *
* @param hostName the host machine associated with the component
* @param paccorOutput the output from PACCOR's allcomoponents.sh * @param paccorOutput the output from PACCOR's allcomoponents.sh
* @return a list of ComponentInfo objects built from paccorOutput * @return a list of ComponentInfo objects built from paccorOutput
* @throws java.io.IOException if something goes wrong parsing the JSON * @throws java.io.IOException if something goes wrong parsing the JSON
@ -333,10 +324,8 @@ public class SupplyChainCredentialValidator {
* Checks if the issuer info of an attribute cert matches the supposed signing cert's * Checks if the issuer info of an attribute cert matches the supposed signing cert's
* distinguished name. * distinguished name.
* *
* @param cert * @param cert the attribute certificate with the signature to validate
* the attribute certificate with the signature to validate * @param signingCert the certificate with the public key to validate
* @param signingCert
* the certificate with the public key to validate
* @return boolean indicating if the names * @return boolean indicating if the names
* @throws SupplyChainValidatorException tried to validate using null certificates * @throws SupplyChainValidatorException tried to validate using null certificates
*/ */
@ -359,10 +348,8 @@ public class SupplyChainCredentialValidator {
* Checks if the issuer info of a public-key cert matches the supposed signing cert's * Checks if the issuer info of a public-key cert matches the supposed signing cert's
* distinguished name. * distinguished name.
* *
* @param cert * @param cert the public-key certificate with the signature to validate
* the public-key certificate with the signature to validate * @param signingCert the certificate with the public key to validate
* @param signingCert
* the certificate with the public key to validate
* @return boolean indicating if the names * @return boolean indicating if the names
* @throws SupplyChainValidatorException tried to validate using null certificates * @throws SupplyChainValidatorException tried to validate using null certificates
*/ */
@ -387,10 +374,8 @@ public class SupplyChainCredentialValidator {
* Checks if the signature of an attribute cert is validated against the signing cert's public * Checks if the signature of an attribute cert is validated against the signing cert's public
* key. * key.
* *
* @param cert * @param cert the public-key certificate with the signature to validate
* the public-key certificate with the signature to validate * @param signingCert the certificate with the public key to validate
* @param signingCert
* the certificate with the public key to validate
* @return boolean indicating if the validation passed * @return boolean indicating if the validation passed
* @throws SupplyChainValidatorException tried to validate using null certificates * @throws SupplyChainValidatorException tried to validate using null certificates
*/ */
@ -423,10 +408,8 @@ public class SupplyChainCredentialValidator {
* Checks if the signature of a public-key cert is validated against the signing cert's public * Checks if the signature of a public-key cert is validated against the signing cert's public
* key. * key.
* *
* @param cert * @param cert the attribute certificate with the signature to validate
* the attribute certificate with the signature to validate * @param signingCert the certificate with the public key to validate
* @param signingCert
* the certificate with the public key to validate
* @return boolean indicating if the validation passed * @return boolean indicating if the validation passed
* @throws SupplyChainValidatorException tried to validate using null certificates * @throws SupplyChainValidatorException tried to validate using null certificates
*/ */
@ -442,10 +425,8 @@ public class SupplyChainCredentialValidator {
/** /**
* Checks if an X509 Attribute Certificate is valid directly against a public key. * Checks if an X509 Attribute Certificate is valid directly against a public key.
* *
* @param cert * @param cert the attribute certificate with the signature to validate
* the attribute certificate with the signature to validate * @param signingKey the key to use to check the attribute cert
* @param signingKey
* the key to use to check the attribute cert
* @return boolean indicating if the validation passed * @return boolean indicating if the validation passed
* @throws SupplyChainValidatorException tried to validate using null certificates * @throws SupplyChainValidatorException tried to validate using null certificates
*/ */
@ -472,8 +453,7 @@ public class SupplyChainCredentialValidator {
* Checks whether given X.509 public-key certificate is self-signed. If the cert can be * Checks whether given X.509 public-key certificate is self-signed. If the cert can be
* verified using its own public key, that means it was self-signed. * verified using its own public key, that means it was self-signed.
* *
* @param cert * @param cert X.509 Certificate
* X.509 Certificate
* @return boolean indicating if the cert was self-signed * @return boolean indicating if the cert was self-signed
*/ */
private static boolean isSelfSigned(final X509Certificate cert) private static boolean isSelfSigned(final X509Certificate cert)

View File

@ -11,10 +11,8 @@ public class SupplyChainValidatorException extends Exception {
* Creates a new <code>SupplyChainValidatorException</code> that has the message * Creates a new <code>SupplyChainValidatorException</code> that has the message
* <code>message</code> and <code>Throwable</code> cause <code>cause</code>. * <code>message</code> and <code>Throwable</code> cause <code>cause</code>.
* *
* @param message * @param message exception message
* exception message * @param cause root cause
* @param cause
* root cause
*/ */
public SupplyChainValidatorException(final String message, final Throwable cause) { public SupplyChainValidatorException(final String message, final Throwable cause) {
super(message, cause); super(message, cause);
@ -24,8 +22,7 @@ public class SupplyChainValidatorException extends Exception {
* Creates a new <code>SupplyChainValidatorException</code> that has the <code>String</code> * Creates a new <code>SupplyChainValidatorException</code> that has the <code>String</code>
* message <code>message</code>. * message <code>message</code>.
* *
* @param message * @param message exception message
* exception message
*/ */
public SupplyChainValidatorException(final String message) { public SupplyChainValidatorException(final String message) {
super(message); super(message);
@ -35,8 +32,7 @@ public class SupplyChainValidatorException extends Exception {
* Creates a new <code>SupplyChainValidatorException</code> that has the <code>Throwable</code> * Creates a new <code>SupplyChainValidatorException</code> that has the <code>Throwable</code>
* cause <code>cause</code>. * cause <code>cause</code>.
* *
* @param cause * @param cause root cause
* root cause
*/ */
public SupplyChainValidatorException(final Throwable cause) { public SupplyChainValidatorException(final Throwable cause) {
super(cause); super(cause);

View File

@ -1,6 +1,6 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output indent="no" /> <xsl:output indent="no"/>
<xsl:strip-space elements="*"/> <xsl:strip-space elements="*"/>
<xsl:template match="@*|node()"> <xsl:template match="@*|node()">
<xsl:copy> <xsl:copy>

View File

@ -72,62 +72,10 @@ import static org.mockito.Mockito.when;
@TestInstance(TestInstance.Lifecycle.PER_CLASS) // needed to use non-static BeforeAll @TestInstance(TestInstance.Lifecycle.PER_CLASS) // needed to use non-static BeforeAll
public class AttestationCertificateAuthorityTest { public class AttestationCertificateAuthorityTest {
/**
* This internal class handles setup for testing the function
* generateCredential() from class AbstractProcessor. Because the
* function is Protected and in a different package than the test,
* it cannot be accessed directly.
*/
@Nested
public class AccessAbstractProcessor extends AbstractProcessor {
/**
* Constructor.
*
* @param privateKey the private key of the ACA
* @param validDays int for the time in which a certificate is valid.
*/
public AccessAbstractProcessor(final PrivateKey privateKey,
final int validDays) {
super(privateKey, validDays);
}
/**
* Public wrapper for the protected function generateCredential(), to access for testing.
*
* @param publicKey cannot be null
* @param endorsementCredential the endorsement credential
* @param platformCredentials the set of platform credentials
* @param deviceName The host name used in the subject alternative name
* @param acaCertificate the aca certificate
* @return the generated X509 certificate
*/
public X509Certificate accessGenerateCredential(final PublicKey publicKey,
final EndorsementCredential endorsementCredential,
final List<PlatformCredential> platformCredentials,
final String deviceName,
final X509Certificate acaCertificate) {
return generateCredential(publicKey,
endorsementCredential,
platformCredentials,
deviceName,
acaCertificate);
}
}
// object in test
private AttestationCertificateAuthority aca;
private AccessAbstractProcessor abstractProcessor;
// test key pair
private KeyPair keyPair;
// length of IV used in PKI // length of IV used in PKI
private static final int ENCRYPTION_IV_LEN = 16; private static final int ENCRYPTION_IV_LEN = 16;
// length of secret key used in PKI // length of secret key used in PKI
private static final int SECRETKEY_LEN = 128; private static final int SECRETKEY_LEN = 128;
private static final String EK_PUBLIC_PATH = "/tpm2/ek.pub"; private static final String EK_PUBLIC_PATH = "/tpm2/ek.pub";
private static final String AK_PUBLIC_PATH = "/tpm2/ak.pub"; private static final String AK_PUBLIC_PATH = "/tpm2/ak.pub";
private static final String AK_NAME_PATH = "/tpm2/ak.name"; private static final String AK_NAME_PATH = "/tpm2/ak.name";
@ -167,7 +115,11 @@ public class AttestationCertificateAuthorityTest {
private static final String AK_NAME_HEX = "00 0b 6e 8f 79 1c 7e 16 96 1b 11 71 65 9c e0 cd" private static final String AK_NAME_HEX = "00 0b 6e 8f 79 1c 7e 16 96 1b 11 71 65 9c e0 cd"
+ "ae 0d 4d aa c5 41 be 58 89 74 67 55 96 c2 5e 38" + "ae 0d 4d aa c5 41 be 58 89 74 67 55 96 c2 5e 38"
+ "e2 94"; + "e2 94";
// object in test
private AttestationCertificateAuthority aca;
private AccessAbstractProcessor abstractProcessor;
// test key pair
private KeyPair keyPair;
/** /**
* Registers bouncy castle as a security provider. Normally the JEE container will handle this, * Registers bouncy castle as a security provider. Normally the JEE container will handle this,
@ -199,7 +151,7 @@ public class AttestationCertificateAuthorityTest {
@Test @Test
public void testProcessIdentityClaimTpm2NullRequest() { public void testProcessIdentityClaimTpm2NullRequest() {
assertThrows(IllegalArgumentException.class, () -> assertThrows(IllegalArgumentException.class, () ->
aca.processIdentityClaimTpm2(null)); aca.processIdentityClaimTpm2(null));
} }
/** /**
@ -209,7 +161,7 @@ public class AttestationCertificateAuthorityTest {
public void testGetPublicKey() { public void testGetPublicKey() {
// encoded byte array to be returned by public key // encoded byte array to be returned by public key
byte[] encoded = new byte[]{0, 1, 0, 1, 0}; byte[] encoded = new byte[] {0, 1, 0, 1, 0};
// create mocks for testing // create mocks for testing
X509Certificate acaCertificate = mock(X509Certificate.class); X509Certificate acaCertificate = mock(X509Certificate.class);
@ -260,7 +212,7 @@ public class AttestationCertificateAuthorityTest {
/** /**
* Tests {@link ProvisionUtils#decryptSymmetricBlob( * Tests {@link ProvisionUtils#decryptSymmetricBlob(
* byte[], byte[], byte[], String)}. *byte[], byte[], byte[], String)}.
* *
* @throws Exception during aca processing * @throws Exception during aca processing
*/ */
@ -315,7 +267,7 @@ public class AttestationCertificateAuthorityTest {
/** /**
* Tests {@link ProvisionUtils#generateAsymmetricContents( * Tests {@link ProvisionUtils#generateAsymmetricContents(
* byte[], byte[], PublicKey)}. *byte[], byte[], PublicKey)}.
* *
* @throws Exception during aca processing * @throws Exception during aca processing
*/ */
@ -323,7 +275,7 @@ public class AttestationCertificateAuthorityTest {
public void testGenerateAsymmetricContents() throws Exception { public void testGenerateAsymmetricContents() throws Exception {
// "encoded" identity proof (returned by struct converter) // "encoded" identity proof (returned by struct converter)
byte[] identityProofEncoded = new byte[]{0, 0, 1, 1}; byte[] identityProofEncoded = new byte[] {0, 0, 1, 1};
// generate a random session key to be used for encryption and decryption // generate a random session key to be used for encryption and decryption
byte[] sessionKey = new byte[ENCRYPTION_IV_LEN]; byte[] sessionKey = new byte[ENCRYPTION_IV_LEN];
@ -478,10 +430,10 @@ public class AttestationCertificateAuthorityTest {
assertEquals("", certificate.getSubjectX500Principal().getName()); assertEquals("", certificate.getSubjectX500Principal().getName());
assertEquals("exampleIdLabel", assertEquals("exampleIdLabel",
((X500Name) GeneralNames.fromExtensions(((TBSCertificate.getInstance( ((X500Name) GeneralNames.fromExtensions(((TBSCertificate.getInstance(
certificate.getTBSCertificate()).getExtensions())), Extension. certificate.getTBSCertificate()).getExtensions())), Extension.
subjectAlternativeName).getNames()[0].getName()).getRDNs( subjectAlternativeName).getNames()[0].getName()).getRDNs(
IssuedCertificateAttributeHelper.TCPA_AT_TPM_ID_LABEL)[0].getFirst() IssuedCertificateAttributeHelper.TCPA_AT_TPM_ID_LABEL)[0].getFirst()
.getValue().toString()); .getValue().toString());
assertArrayEquals(modulus, resultMod); assertArrayEquals(modulus, resultMod);
@ -540,8 +492,9 @@ public class AttestationCertificateAuthorityTest {
/** /**
* Tests parsing the EK from the TPM2 output file. * Tests parsing the EK from the TPM2 output file.
*
* @throws URISyntaxException incorrect resource path * @throws URISyntaxException incorrect resource path
* @throws IOException unable to read from file * @throws IOException unable to read from file
*/ */
@Test @Test
public void testParseEk() throws URISyntaxException, IOException { public void testParseEk() throws URISyntaxException, IOException {
@ -567,8 +520,9 @@ public class AttestationCertificateAuthorityTest {
/** /**
* Tests parsing the AK public key from the TPM2 output file. * Tests parsing the AK public key from the TPM2 output file.
*
* @throws URISyntaxException incorrect resource path * @throws URISyntaxException incorrect resource path
* @throws IOException unable to read from file * @throws IOException unable to read from file
*/ */
@Test @Test
public void testParseAk() throws URISyntaxException, IOException { public void testParseAk() throws URISyntaxException, IOException {
@ -594,8 +548,9 @@ public class AttestationCertificateAuthorityTest {
/** /**
* Tests parsing the AK name from the TPM2 output file. * Tests parsing the AK name from the TPM2 output file.
* @throws URISyntaxException incorrect resource path *
* @throws IOException unable to read from file * @throws URISyntaxException incorrect resource path
* @throws IOException unable to read from file
* @throws NoSuchAlgorithmException inavlid algorithm * @throws NoSuchAlgorithmException inavlid algorithm
*/ */
@Test @Test
@ -624,8 +579,9 @@ public class AttestationCertificateAuthorityTest {
* and ekPubPath are correct. Your output file will be * and ekPubPath are correct. Your output file will be
* HIRS_AttestationCA/src/test/resources/tpm2/test/make.blob and the nonce used will be * HIRS_AttestationCA/src/test/resources/tpm2/test/make.blob and the nonce used will be
* output as HIRS_AttestationCA/src/test/resources/tpm2/test/secret.blob * output as HIRS_AttestationCA/src/test/resources/tpm2/test/secret.blob
*
* @throws URISyntaxException invalid file path * @throws URISyntaxException invalid file path
* @throws IOException unable to read file * @throws IOException unable to read file
*/ */
@Disabled @Disabled
@Test @Test
@ -647,7 +603,7 @@ public class AttestationCertificateAuthorityTest {
ByteString blob = ProvisionUtils.tpm20MakeCredential(ekPub, akPub, nonce); ByteString blob = ProvisionUtils.tpm20MakeCredential(ekPub, akPub, nonce);
Path resources = Objects.requireNonNull(Paths.get(Objects.requireNonNull(this.getClass().getResource( Path resources = Objects.requireNonNull(Paths.get(Objects.requireNonNull(this.getClass().getResource(
"/").toURI())) "/").toURI()))
.getParent().getParent().getParent().getParent()); .getParent().getParent().getParent().getParent());
Path makeBlob = resources.resolve("src/test/resources/tpm2/test/make.blob"); Path makeBlob = resources.resolve("src/test/resources/tpm2/test/make.blob");
Files.write(makeBlob, blob.toByteArray()); Files.write(makeBlob, blob.toByteArray());
@ -754,4 +710,48 @@ public class AttestationCertificateAuthorityTest {
// return the cipher text // return the cipher text
return cipher.doFinal(blob); return cipher.doFinal(blob);
} }
/**
* This internal class handles setup for testing the function
* generateCredential() from class AbstractProcessor. Because the
* function is Protected and in a different package than the test,
* it cannot be accessed directly.
*/
@Nested
public class AccessAbstractProcessor extends AbstractProcessor {
/**
* Constructor.
*
* @param privateKey the private key of the ACA
* @param validDays int for the time in which a certificate is valid.
*/
public AccessAbstractProcessor(final PrivateKey privateKey,
final int validDays) {
super(privateKey, validDays);
}
/**
* Public wrapper for the protected function generateCredential(), to access for testing.
*
* @param publicKey cannot be null
* @param endorsementCredential the endorsement credential
* @param platformCredentials the set of platform credentials
* @param deviceName The host name used in the subject alternative name
* @param acaCertificate the aca certificate
* @return the generated X509 certificate
*/
public X509Certificate accessGenerateCredential(final PublicKey publicKey,
final EndorsementCredential endorsementCredential,
final List<PlatformCredential> platformCredentials,
final String deviceName,
final X509Certificate acaCertificate) {
return generateCredential(publicKey,
endorsementCredential,
platformCredentials,
deviceName,
acaCertificate);
}
}
} }

View File

@ -1,20 +1,20 @@
package hirs.attestationca.persist.entity.tpm; package hirs.attestationca.persist.entity.tpm;
import hirs.attestationca.persist.entity.manager.TPM2ProvisionerStateRepository; import hirs.attestationca.persist.entity.manager.TPM2ProvisionerStateRepository;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Random; import java.util.Random;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** /**
* Contains unit tests for {@link TPM2ProvisionerState}. * Contains unit tests for {@link TPM2ProvisionerState}.
*/ */
@ -88,9 +88,10 @@ public class TPM2ProvisionerStateTest {
/** /**
* Test that {@link TPM2ProvisionerState#getTPM2ProvisionerState( * Test that {@link TPM2ProvisionerState#getTPM2ProvisionerState(
* TPM2ProvisionerStateRepository, byte[])} works. *TPM2ProvisionerStateRepository, byte[])} works.
* {@link TPM2ProvisionerState#getTPM2ProvisionerState( * {@link TPM2ProvisionerState#getTPM2ProvisionerState(
* TPM2ProvisionerStateRepository, byte[])}, null is returned. *TPM2ProvisionerStateRepository, byte[])}, null is returned.
*
* @throws IOException this will never happen * @throws IOException this will never happen
*/ */
@Test @Test
@ -116,7 +117,8 @@ public class TPM2ProvisionerStateTest {
/** /**
* Test that if a null is passed as a nonce to * Test that if a null is passed as a nonce to
* {@link TPM2ProvisionerState#getTPM2ProvisionerState( * {@link TPM2ProvisionerState#getTPM2ProvisionerState(
* TPM2ProvisionerStateRepository, byte[])}, null is returned. *TPM2ProvisionerStateRepository, byte[])}, null is returned.
*
* @throws IOException this will never happen * @throws IOException this will never happen
*/ */
@Test @Test
@ -139,7 +141,8 @@ public class TPM2ProvisionerStateTest {
/** /**
* Test that if a nonce that is less than 8 bytes is passed to * Test that if a nonce that is less than 8 bytes is passed to
* {@link TPM2ProvisionerState#getTPM2ProvisionerState( * {@link TPM2ProvisionerState#getTPM2ProvisionerState(
* TPM2ProvisionerStateRepository, byte[])}, null is returned. *TPM2ProvisionerStateRepository, byte[])}, null is returned.
*
* @throws IOException this will never happen * @throws IOException this will never happen
*/ */
@Test @Test

View File

@ -33,7 +33,6 @@ import java.util.Objects;
/** /**
* Class with definitions and functions common to multiple Userdefined Entity object tests. * Class with definitions and functions common to multiple Userdefined Entity object tests.
*
*/ */
public class AbstractUserdefinedEntityTest { public class AbstractUserdefinedEntityTest {
@ -58,54 +57,45 @@ public class AbstractUserdefinedEntityTest {
*/ */
public static final String FAKE_ROOT_CA_SUBJECT_KEY_IDENTIFIER_HEX = public static final String FAKE_ROOT_CA_SUBJECT_KEY_IDENTIFIER_HEX =
"58ec313a1699f94c1c8c4e2c6412402b258f0177"; "58ec313a1699f94c1c8c4e2c6412402b258f0177";
/**
* Location of a test identity certificate.
*/
private static final String TEST_IDENTITY_CERT = "/tpm/sample_identity_cert.cer";
/** /**
* Location of a test platform attribute cert. * Location of a test platform attribute cert.
*/ */
public static final String TEST_PLATFORM_CERT_1 = public static final String TEST_PLATFORM_CERT_1 =
"/validation/platform_credentials/Intel_pc1.cer"; "/validation/platform_credentials/Intel_pc1.cer";
/** /**
* Location of another, slightly different platform attribute cert. * Location of another, slightly different platform attribute cert.
*/ */
public static final String TEST_PLATFORM_CERT_2 = public static final String TEST_PLATFORM_CERT_2 =
"/validation/platform_credentials/Intel_pc2.cer"; "/validation/platform_credentials/Intel_pc2.cer";
/** /**
* Location of another, slightly different platform attribute cert. * Location of another, slightly different platform attribute cert.
*/ */
public static final String TEST_PLATFORM_CERT_3 = public static final String TEST_PLATFORM_CERT_3 =
"/validation/platform_credentials/Intel_pc3.cer"; "/validation/platform_credentials/Intel_pc3.cer";
/** /**
* Platform cert with comma separated baseboard and chassis serial number. * Platform cert with comma separated baseboard and chassis serial number.
*/ */
public static final String TEST_PLATFORM_CERT_4 = public static final String TEST_PLATFORM_CERT_4 =
"/validation/platform_credentials/Intel_pc4.pem"; "/validation/platform_credentials/Intel_pc4.pem";
/** /**
* Another platform cert with comma separated baseboard and chassis serial number. * Another platform cert with comma separated baseboard and chassis serial number.
*/ */
public static final String TEST_PLATFORM_CERT_5 = public static final String TEST_PLATFORM_CERT_5 =
"/validation/platform_credentials/Intel_pc5.pem"; "/validation/platform_credentials/Intel_pc5.pem";
/** /**
* Location of another, slightly different platform attribute cert. * Location of another, slightly different platform attribute cert.
*/ */
public static final String TEST_PLATFORM_CERT_6 = public static final String TEST_PLATFORM_CERT_6 =
"/validation/platform_credentials/TPM_INTC_Platform_Cert_RSA.txt"; "/validation/platform_credentials/TPM_INTC_Platform_Cert_RSA.txt";
private static final Logger LOGGER = LogManager.getLogger(DeviceInfoReportTest.class);
/** /**
* Dummy message for supply chain validation test. * Dummy message for supply chain validation test.
*/ */
public static final String VALIDATION_MESSAGE = "Some message."; public static final String VALIDATION_MESSAGE = "Some message.";
/**
* Location of a test identity certificate.
*/
private static final String TEST_IDENTITY_CERT = "/tpm/sample_identity_cert.cer";
private static final Logger LOGGER = LogManager.getLogger(DeviceInfoReportTest.class);
/** /**
* Construct a test certificate from the given parameters. * Construct a test certificate from the given parameters.
@ -294,8 +284,8 @@ public class AbstractUserdefinedEntityTest {
/** /**
* Construct a SupplyChainValidation for use in tests according to the provided parameters. * Construct a SupplyChainValidation for use in tests according to the provided parameters.
* *
* @param type the type of validation * @param type the type of validation
* @param result the appraisal result * @param result the appraisal result
* @param certificates the certificates related to this validation * @param certificates the certificates related to this validation
* @return the resulting SupplyChainValidation object * @return the resulting SupplyChainValidation object
*/ */

View File

@ -21,11 +21,12 @@ import java.security.cert.X509Certificate;
import java.util.Arrays; import java.util.Arrays;
import java.util.Objects; import java.util.Objects;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* This class tests functionality of the {@link Certificate} class. * This class tests functionality of the {@link Certificate} class.
@ -88,6 +89,37 @@ public class CertificateTest extends AbstractUserdefinedEntityTest {
private static final String EK_CERT_WITH_PADDED_BYTES = private static final String EK_CERT_WITH_PADDED_BYTES =
"/certificates/ek_cert_with_padded_bytes.cer"; "/certificates/ek_cert_with_padded_bytes.cer";
/**
* Construct a CertificateAuthorityCredential from the given parameters.
*
* @param filename the location of the certificate to be used
* @return the newly-constructed Certificate
* @throws IOException if there is a problem constructing the test certificate
*/
public static Certificate getTestCertificate(
final String filename) throws IOException {
return getTestCertificate(CertificateAuthorityCredential.class, filename);
}
private static X509Certificate readX509Certificate(final String resourceName)
throws IOException {
CertificateFactory cf;
try {
cf = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
throw new IOException("Cannot get X509 CertificateFactory instance", e);
}
try (FileInputStream certInputStream = new FileInputStream(Paths.get(
Objects.requireNonNull(CertificateTest.class.getResource(
resourceName)).toURI()).toFile()
)) {
return (X509Certificate) cf.generateCertificate(certInputStream);
} catch (CertificateException | URISyntaxException e) {
throw new IOException("Cannot read certificate", e);
}
}
/** /**
* Tests that a certificate can be constructed from a byte array. * Tests that a certificate can be constructed from a byte array.
@ -132,7 +164,7 @@ public class CertificateTest extends AbstractUserdefinedEntityTest {
public void testConstructCertFromEmptyByteArray() public void testConstructCertFromEmptyByteArray()
throws IOException, CertificateException { throws IOException, CertificateException {
assertThrows(IllegalArgumentException.class, () -> assertThrows(IllegalArgumentException.class, () ->
new CertificateAuthorityCredential(new byte[]{})); new CertificateAuthorityCredential(new byte[] {}));
} }
/** /**
@ -293,7 +325,7 @@ public class CertificateTest extends AbstractUserdefinedEntityTest {
attrCertHolder.getIssuer().getNames()[0].toString(), attrCertHolder.getIssuer().getNames()[0].toString(),
platformCert.getIssuer() platformCert.getIssuer()
); );
assertEquals(null, platformCert.getSubject()); assertNull(platformCert.getSubject());
assertArrayEquals(null, platformCert.getEncodedPublicKey()); assertArrayEquals(null, platformCert.getEncodedPublicKey());
assertArrayEquals(attrCertHolder.getSignature(), platformCert.getSignature()); assertArrayEquals(attrCertHolder.getSignature(), platformCert.getSignature());
assertEquals(attrCertHolder.getNotBefore(), platformCert.getBeginValidity()); assertEquals(attrCertHolder.getNotBefore(), platformCert.getBeginValidity());
@ -492,36 +524,4 @@ public class CertificateTest extends AbstractUserdefinedEntityTest {
).hashCode() ).hashCode()
); );
} }
/**
* Construct a CertificateAuthorityCredential from the given parameters.
*
* @param filename the location of the certificate to be used
* @return the newly-constructed Certificate
* @throws IOException if there is a problem constructing the test certificate
*/
public static Certificate getTestCertificate(
final String filename) throws IOException {
return getTestCertificate(CertificateAuthorityCredential.class, filename);
}
private static X509Certificate readX509Certificate(final String resourceName)
throws IOException {
CertificateFactory cf;
try {
cf = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
throw new IOException("Cannot get X509 CertificateFactory instance", e);
}
try (FileInputStream certInputStream = new FileInputStream(Paths.get(
Objects.requireNonNull(CertificateTest.class.getResource(
resourceName)).toURI()).toFile()
)) {
return (X509Certificate) cf.generateCertificate(certInputStream);
} catch (CertificateException | URISyntaxException e) {
throw new IOException("Cannot read certificate", e);
}
}
} }

View File

@ -11,7 +11,6 @@ import static org.junit.jupiter.api.Assertions.assertNull;
/** /**
* This is the test class for the <code>Device</code> class. * This is the test class for the <code>Device</code> class.
*
*/ */
public final class DeviceTest extends AbstractUserdefinedEntityTest { public final class DeviceTest extends AbstractUserdefinedEntityTest {
@ -113,7 +112,7 @@ public final class DeviceTest extends AbstractUserdefinedEntityTest {
*/ */
@Test @Test
public void testSetHealthStatus() { public void testSetHealthStatus() {
final Device device = new Device("test-device", null, HealthStatus.UNKNOWN, final Device device = new Device("test-device", null, HealthStatus.UNKNOWN,
AppraisalStatus.Status.UNKNOWN, null, false, AppraisalStatus.Status.UNKNOWN, null, false,
null, null); null, null);
device.setHealthStatus(HealthStatus.TRUSTED); device.setHealthStatus(HealthStatus.TRUSTED);

View File

@ -1,10 +1,11 @@
package hirs.attestationca.persist.entity.userdefined; package hirs.attestationca.persist.entity.userdefined;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* Unit test class for PolicySettings. * Unit test class for PolicySettings.
*/ */

View File

@ -26,16 +26,28 @@ public class SupplyChainValidationSummaryTest extends AbstractUserdefinedEntityT
/** /**
* Test device. * Test device.
*
*/ */
private Device device; private Device device;
/** /**
* List of test certificates. * List of test certificates.
*
*/ */
private List<ArchivableEntity> certificates; private List<ArchivableEntity> certificates;
/**
* Utility method for getting a <code>Device</code> that can be used for
* testing.
*
* @param name name for the <code>Device</code>
* @return device
*/
public static Device getTestDevice(final String name) {
final DeviceInfoReport deviceInfo = getTestDeviceInfoReport();
return new Device(name, deviceInfo, HealthStatus.UNKNOWN,
AppraisalStatus.Status.UNKNOWN, null,
false, null, null);
}
/** /**
* Create a set of certificates and a device for use by these tests. * Create a set of certificates and a device for use by these tests.
* *
@ -152,28 +164,12 @@ public class SupplyChainValidationSummaryTest extends AbstractUserdefinedEntityT
assertNotNull(twoBadValidations.getCreateTime()); assertNotNull(twoBadValidations.getCreateTime());
} }
/**
* Utility method for getting a <code>Device</code> that can be used for
* testing.
*
* @param name name for the <code>Device</code>
*
* @return device
*/
public static Device getTestDevice(final String name) {
final DeviceInfoReport deviceInfo = getTestDeviceInfoReport();
return new Device(name, deviceInfo, HealthStatus.UNKNOWN,
AppraisalStatus.Status.UNKNOWN, null,
false, null, null);
}
/** /**
* Utility method for getting a <code>SupplyChainValidationSummary</code> that can be used for * Utility method for getting a <code>SupplyChainValidationSummary</code> that can be used for
* testing. * testing.
* *
* @param numberOfValidations number of validations for the <code>SupplyChainValidationSummary</code> * @param numberOfValidations number of validations for the <code>SupplyChainValidationSummary</code>
* @param numFail number of failed validations * @param numFail number of failed validations
*
* @return device * @return device
*/ */
private SupplyChainValidationSummary getTestSummary( private SupplyChainValidationSummary getTestSummary(
@ -199,10 +195,7 @@ public class SupplyChainValidationSummaryTest extends AbstractUserdefinedEntityT
Collection<SupplyChainValidation> validations = new HashSet<>(); Collection<SupplyChainValidation> validations = new HashSet<>();
for (int i = 0; i < numberOfValidations; i++) { for (int i = 0; i < numberOfValidations; i++) {
boolean successful = true; boolean successful = i < (numberOfValidations - numFail);
if (i >= (numberOfValidations - numFail)) {
successful = false;
}
AppraisalStatus.Status result = AppraisalStatus.Status.FAIL; AppraisalStatus.Status result = AppraisalStatus.Status.FAIL;
if (successful) { if (successful) {

View File

@ -14,6 +14,22 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
*/ */
class SupplyChainValidationTest extends AbstractUserdefinedEntityTest { class SupplyChainValidationTest extends AbstractUserdefinedEntityTest {
/**
* Construct a SupplyChainValidation for use in tests. It will have a validation
* type of ENDORSEMENT_CREDENTIAL, will represent a successful validation, and will use
* multiple test certificates.
*
* @return the test SupplyChainValidation
* @throws IOException if there si
*/
public static SupplyChainValidation getTestSupplyChainValidation() throws IOException {
return getTestSupplyChainValidation(
SupplyChainValidation.ValidationType.ENDORSEMENT_CREDENTIAL,
AppraisalStatus.Status.PASS,
getAllTestCertificates()
);
}
/** /**
* Test that this class' getter methods work properly. * Test that this class' getter methods work properly.
* *
@ -79,20 +95,4 @@ class SupplyChainValidationTest extends AbstractUserdefinedEntityTest {
VALIDATION_MESSAGE VALIDATION_MESSAGE
); );
} }
/**
* Construct a SupplyChainValidation for use in tests. It will have a validation
* type of ENDORSEMENT_CREDENTIAL, will represent a successful validation, and will use
* multiple test certificates.
*
* @return the test SupplyChainValidation
* @throws IOException if there si
*/
public static SupplyChainValidation getTestSupplyChainValidation() throws IOException {
return getTestSupplyChainValidation(
SupplyChainValidation.ValidationType.ENDORSEMENT_CREDENTIAL,
AppraisalStatus.Status.PASS,
getAllTestCertificates()
);
}
} }

View File

@ -2,8 +2,6 @@ package hirs.attestationca.persist.entity.userdefined.certificate;
import hirs.attestationca.persist.entity.userdefined.AbstractUserdefinedEntityTest; import hirs.attestationca.persist.entity.userdefined.AbstractUserdefinedEntityTest;
import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.binary.Hex;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.IOException; import java.io.IOException;
@ -12,6 +10,9 @@ import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/** /**
* Tests that CertificateAuthorityCredential properly parses its fields. * Tests that CertificateAuthorityCredential properly parses its fields.
*/ */
@ -21,10 +22,10 @@ public class CertificateAuthorityCredentialTest extends AbstractUserdefinedEntit
* Tests that a CertificateAuthorityCredential can be created from an X.509 certificate and * Tests that a CertificateAuthorityCredential can be created from an X.509 certificate and
* that the subject key identifier is correctly extracted. * that the subject key identifier is correctly extracted.
* *
* @throws IOException if the certificate could not be constructed properly * @throws IOException if the certificate could not be constructed properly
* @throws CertificateException if there is a problem with the KeyStore or de/serializing the * @throws CertificateException if there is a problem with the KeyStore or de/serializing the
* certificate * certificate
* @throws URISyntaxException if there is a problem constructing the path to the certificate * @throws URISyntaxException if there is a problem constructing the path to the certificate
*/ */
@Test @Test
public void testGetSubjectKeyIdentifier() public void testGetSubjectKeyIdentifier()

View File

@ -1,10 +1,7 @@
package hirs.attestationca.persist.entity.userdefined.certificate; package hirs.attestationca.persist.entity.userdefined.certificate;
import static org.junit.jupiter.api.Assertions.assertEquals; import hirs.attestationca.persist.entity.userdefined.certificate.attributes.TPMSecurityAssertions;
import static org.junit.jupiter.api.Assertions.assertNotEquals; import hirs.attestationca.persist.entity.userdefined.certificate.attributes.TPMSpecification;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.IOException; import java.io.IOException;
@ -12,8 +9,11 @@ import java.math.BigInteger;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.TPMSecurityAssertions;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.TPMSpecification; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* Tests for the EndorsementCredential class. * Tests for the EndorsementCredential class.
@ -32,6 +32,7 @@ public class EndorsementCredentialTest {
/** /**
* Tests the successful parsing of an EC using a test cert from STM. * Tests the successful parsing of an EC using a test cert from STM.
*
* @throws IOException test failed due to invalid certificate parsing * @throws IOException test failed due to invalid certificate parsing
*/ */
@Test @Test
@ -65,6 +66,7 @@ public class EndorsementCredentialTest {
/** /**
* Tests the successful parsing of an EC using a test cert from NUC 1. * Tests the successful parsing of an EC using a test cert from NUC 1.
*
* @throws IOException test failed due to invalid certificate parsing * @throws IOException test failed due to invalid certificate parsing
*/ */
@Test @Test
@ -99,6 +101,7 @@ public class EndorsementCredentialTest {
/** /**
* Tests the successful parsing of an EC using a test cert from NUC 1, * Tests the successful parsing of an EC using a test cert from NUC 1,
* using the static builder method. * using the static builder method.
*
* @throws IOException test failed due to invalid certificate parsing * @throws IOException test failed due to invalid certificate parsing
*/ */
@Test @Test
@ -134,6 +137,7 @@ public class EndorsementCredentialTest {
/** /**
* Tests the successful parsing of an EC using a test cert from NUC 2. * Tests the successful parsing of an EC using a test cert from NUC 2.
*
* @throws IOException test failed due to invalid certificate parsing * @throws IOException test failed due to invalid certificate parsing
*/ */
@Test @Test
@ -167,6 +171,7 @@ public class EndorsementCredentialTest {
/** /**
* Tests that different EC certificates aren't the same, even if their attributes are the same. * Tests that different EC certificates aren't the same, even if their attributes are the same.
*
* @throws IOException test failed due to invalid certificate parsing * @throws IOException test failed due to invalid certificate parsing
*/ */
@Test @Test

View File

@ -12,7 +12,6 @@ import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Base64;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
@ -23,6 +22,8 @@ import java.util.Calendar;
import java.util.List; import java.util.List;
import java.util.TimeZone; import java.util.TimeZone;
import static org.junit.jupiter.api.Assertions.fail;
/** /**
* Tests that a PlatformCredential parses its fields correctly. * Tests that a PlatformCredential parses its fields correctly.
*/ */
@ -169,7 +170,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
* extension but is missing the subject alternative name extension. This certificate * extension but is missing the subject alternative name extension. This certificate
* also has a policy extension, but it is not currently parsed. * also has a policy extension, but it is not currently parsed.
* *
* @throws IOException if an IO error occurs during processing * @throws IOException if an IO error occurs during processing
* @throws URISyntaxException if there is a problem constructing the cert's URI * @throws URISyntaxException if there is a problem constructing the cert's URI
*/ */
@Test @Test
@ -206,7 +207,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
Assertions.assertEquals(credential.getCredentialType(), "TCPA Trusted Platform Endorsement"); Assertions.assertEquals(credential.getCredentialType(), "TCPA Trusted Platform Endorsement");
// the platform certificate in this test does not contain the following information // the platform certificate in this test does not contain the following information
Assertions.assertEquals(credential.getPlatformSerial(), null); Assertions.assertNull(credential.getPlatformSerial());
Assertions.assertEquals(credential.getMajorVersion(), 1); Assertions.assertEquals(credential.getMajorVersion(), 1);
Assertions.assertEquals(credential.getMinorVersion(), 2); Assertions.assertEquals(credential.getMinorVersion(), 2);
Assertions.assertEquals(credential.getRevisionLevel(), 1); Assertions.assertEquals(credential.getRevisionLevel(), 1);
@ -218,7 +219,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
* extension but is missing the subject alternative name extension. This certificate * extension but is missing the subject alternative name extension. This certificate
* also has a policy extension, but it is not currently parsed. * also has a policy extension, but it is not currently parsed.
* *
* @throws IOException if an IO error occurs during processing * @throws IOException if an IO error occurs during processing
* @throws URISyntaxException if there is a problem constructing the cert's URI * @throws URISyntaxException if there is a problem constructing the cert's URI
*/ */
@Test @Test
@ -255,7 +256,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
Assertions.assertEquals(credential.getCredentialType(), "TCPA Trusted Platform Endorsement"); Assertions.assertEquals(credential.getCredentialType(), "TCPA Trusted Platform Endorsement");
// the platform certificate in this test does not contain the following information // the platform certificate in this test does not contain the following information
Assertions.assertEquals(credential.getPlatformSerial(), null); Assertions.assertNull(credential.getPlatformSerial());
Assertions.assertEquals(credential.getMajorVersion(), 1); Assertions.assertEquals(credential.getMajorVersion(), 1);
Assertions.assertEquals(credential.getMinorVersion(), 2); Assertions.assertEquals(credential.getMinorVersion(), 2);
Assertions.assertEquals(credential.getRevisionLevel(), 1); Assertions.assertEquals(credential.getRevisionLevel(), 1);
@ -266,7 +267,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
* Tests the parsing of a platform credential that has a combined baseboard and chassis * Tests the parsing of a platform credential that has a combined baseboard and chassis
* serial number in one attribute can be parsed. * serial number in one attribute can be parsed.
* *
* @throws IOException if an IO error occurs during processing * @throws IOException if an IO error occurs during processing
* @throws URISyntaxException if there is a problem constructing the cert's URI * @throws URISyntaxException if there is a problem constructing the cert's URI
*/ */
@Test @Test
@ -311,7 +312,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
* Tests the parsing another platform credential that has a combined baseboard and chassis * Tests the parsing another platform credential that has a combined baseboard and chassis
* serial number in one attribute can be parsed. * serial number in one attribute can be parsed.
* *
* @throws IOException if an IO error occurs during processing * @throws IOException if an IO error occurs during processing
* @throws URISyntaxException if there is a problem constructing the cert's URI * @throws URISyntaxException if there is a problem constructing the cert's URI
*/ */
@Test @Test
@ -355,7 +356,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
/** /**
* Tests isIssuer of a platform credential. * Tests isIssuer of a platform credential.
* *
* @throws IOException if an IO error occurs during processing * @throws IOException if an IO error occurs during processing
* @throws URISyntaxException if there is a problem constructing the cert's URI * @throws URISyntaxException if there is a problem constructing the cert's URI
*/ */
@Test @Test
@ -376,7 +377,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
/** /**
* Tests platform Configuration Values. * Tests platform Configuration Values.
* *
* @throws IOException if an IO error occurs during processing * @throws IOException if an IO error occurs during processing
* @throws URISyntaxException if there is a problem constructing the cert's URI * @throws URISyntaxException if there is a problem constructing the cert's URI
*/ */
@Test @Test
@ -398,37 +399,30 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
ComponentIdentifier component; ComponentIdentifier component;
//Check component #2 //Check component #2
component = (ComponentIdentifier) allComponents.get(1); component = allComponents.get(1);
Assertions.assertTrue(component.getComponentManufacturer() Assertions.assertEquals("Intel Corporation", component.getComponentManufacturer()
.getString() .getString());
.equals("Intel Corporation")); Assertions.assertEquals("NUC7i5DNB", component.getComponentModel()
Assertions.assertTrue(component.getComponentModel() .getString());
.getString() Assertions.assertEquals("BTDN732000QM", component.getComponentSerial()
.equals("NUC7i5DNB")); .getString());
Assertions.assertTrue(component.getComponentSerial()
.getString()
.equals("BTDN732000QM"));
//Check component #3 //Check component #3
component = (ComponentIdentifier) allComponents.get(2); component = allComponents.get(2);
Assertions.assertTrue(component.getComponentManufacturer() Assertions.assertEquals("Intel(R) Corporation", component.getComponentManufacturer()
.getString() .getString());
.equals("Intel(R) Corporation")); Assertions.assertEquals("Core i5", component.getComponentModel().getString());
Assertions.assertTrue(component.getComponentModel().getString().equals("Core i5"));
Assertions.assertTrue(component.getFieldReplaceable().isTrue()); Assertions.assertTrue(component.getFieldReplaceable().isTrue());
//Check component #5 //Check component #5
component = (ComponentIdentifier) allComponents.get(4); component = allComponents.get(4);
Assertions.assertTrue(component.getComponentModel() Assertions.assertEquals("Ethernet Connection I219-LM", component.getComponentModel()
.getString() .getString());
.equals("Ethernet Connection I219-LM")); Assertions.assertEquals("8c:0f:6f:72:c6:c5", component.getComponentAddress().get(0)
Assertions.assertTrue(component.getComponentAddress().get(0)
.getAddressValue() .getAddressValue()
.getString() .getString());
.equals("8c:0f:6f:72:c6:c5")); Assertions.assertEquals("ethernet mac", component.getComponentAddress().get(0)
Assertions.assertTrue(component.getComponentAddress().get(0) .getAddressTypeValue());
.getAddressTypeValue()
.equals("ethernet mac"));
//Check Platform Properties //Check Platform Properties
List<PlatformProperty> platformProperties = platformConfig.getPlatformProperties(); List<PlatformProperty> platformProperties = platformConfig.getPlatformProperties();
@ -441,22 +435,22 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
PlatformProperty property; PlatformProperty property;
//Check property #1 //Check property #1
property = (PlatformProperty) platformProperties.get(0); property = platformProperties.get(0);
Assertions.assertTrue(property.getPropertyName().getString().equals("vPro")); Assertions.assertEquals("vPro", property.getPropertyName().getString());
Assertions.assertTrue(property.getPropertyValue().getString().equals("true")); Assertions.assertEquals("true", property.getPropertyValue().getString());
//Check property #2 //Check property #2
property = (PlatformProperty) platformProperties.get(1); property = platformProperties.get(1);
Assertions.assertTrue(property.getPropertyName().getString().equals("AMT")); Assertions.assertEquals("AMT", property.getPropertyName().getString());
Assertions.assertTrue(property.getPropertyValue().getString().equals("true")); Assertions.assertEquals("true", property.getPropertyValue().getString());
//Check Platform Properties URI //Check Platform Properties URI
URIReference platformPropertyUri = platformConfig.getPlatformPropertiesUri(); URIReference platformPropertyUri = platformConfig.getPlatformPropertiesUri();
Assertions.assertNotNull(platformPropertyUri); Assertions.assertNotNull(platformPropertyUri);
Assertions.assertTrue(platformPropertyUri.getUniformResourceIdentifier() Assertions.assertEquals("https://www.intel.com/platformproperties.xml",
.getString() platformPropertyUri.getUniformResourceIdentifier()
.equals("https://www.intel.com/platformproperties.xml")); .getString());
Assertions.assertNull(platformPropertyUri.getHashAlgorithm()); Assertions.assertNull(platformPropertyUri.getHashAlgorithm());
Assertions.assertNull(platformPropertyUri.getHashValue()); Assertions.assertNull(platformPropertyUri.getHashValue());
} }
@ -464,7 +458,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
/** /**
* Tests Platform Configuration Values. View platform Properties * Tests Platform Configuration Values. View platform Properties
* *
* @throws IOException if an IO error occurs during processing * @throws IOException if an IO error occurs during processing
* @throws URISyntaxException if there is a problem constructing the cert's URI * @throws URISyntaxException if there is a problem constructing the cert's URI
*/ */
@Test @Test
@ -489,20 +483,20 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
PlatformProperty property; PlatformProperty property;
//Check property #1 //Check property #1
property = (PlatformProperty) platformProperties.get(0); property = platformProperties.get(0);
Assertions.assertTrue(property.getPropertyName().getString().equals("vPro")); Assertions.assertEquals("vPro", property.getPropertyName().getString());
Assertions.assertTrue(property.getPropertyValue().getString().equals("true")); Assertions.assertEquals("true", property.getPropertyValue().getString());
//Check property #2 //Check property #2
property = (PlatformProperty) platformProperties.get(1); property = platformProperties.get(1);
Assertions.assertTrue(property.getPropertyName().getString().equals("AMT")); Assertions.assertEquals("AMT", property.getPropertyName().getString());
Assertions.assertTrue(property.getPropertyValue().getString().equals("true")); Assertions.assertEquals("true", property.getPropertyValue().getString());
} }
/** /**
* Tests Platform Configuration Values. View platform Properties * Tests Platform Configuration Values. View platform Properties
* *
* @throws IOException if an IO error occurs during processing * @throws IOException if an IO error occurs during processing
* @throws URISyntaxException if there is a problem constructing the cert's URI * @throws URISyntaxException if there is a problem constructing the cert's URI
*/ */
@Test @Test
@ -524,25 +518,20 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
ComponentIdentifier component; ComponentIdentifier component;
//Check component #2 //Check component #2
component = (ComponentIdentifier) allComponents.get(1); component = allComponents.get(1);
Assertions.assertTrue(component.getComponentManufacturer() Assertions.assertEquals("Intel(R) Corporation", component.getComponentManufacturer()
.getString() .getString());
.equals("Intel(R) Corporation")); Assertions.assertEquals("Intel(R) Core(TM) i5-7300U CPU @ 2.60GHz", component.getComponentModel()
Assertions.assertTrue(component.getComponentModel() .getString());
.getString()
.equals("Intel(R) Core(TM) i5-7300U CPU @ 2.60GHz"));
//Check component #3 //Check component #3
component = (ComponentIdentifier) allComponents.get(2); component = allComponents.get(2);
Assertions.assertTrue(component.getComponentModel() Assertions.assertEquals("BIOS", component.getComponentModel()
.getString() .getString());
.equals("BIOS")); Assertions.assertEquals(ComponentIdentifier.NOT_SPECIFIED_COMPONENT, component.getComponentSerial()
Assertions.assertTrue(component.getComponentSerial() .getString());
.getString() Assertions.assertEquals("DNKBLi5v.86A.0019.2017.0804.1146", component.getComponentRevision()
.equals(ComponentIdentifier.NOT_SPECIFIED_COMPONENT)); .getString());
Assertions.assertTrue(component.getComponentRevision()
.getString()
.equals("DNKBLi5v.86A.0019.2017.0804.1146"));
//Check Platform Properties //Check Platform Properties
List<PlatformProperty> platformProperties = platformConfig.getPlatformProperties(); List<PlatformProperty> platformProperties = platformConfig.getPlatformProperties();
@ -556,26 +545,26 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
URIReference platformPropertyUri = platformConfig.getPlatformPropertiesUri(); URIReference platformPropertyUri = platformConfig.getPlatformPropertiesUri();
Assertions.assertNotNull(platformPropertyUri); Assertions.assertNotNull(platformPropertyUri);
Assertions.assertTrue(platformPropertyUri.getUniformResourceIdentifier() Assertions.assertEquals("https://www.intel.com/platformproperties.xml",
.getString() platformPropertyUri.getUniformResourceIdentifier()
.equals("https://www.intel.com/platformproperties.xml")); .getString());
Assertions.assertNull(platformPropertyUri.getHashAlgorithm()); Assertions.assertNull(platformPropertyUri.getHashAlgorithm());
Assertions.assertNull(platformPropertyUri.getHashValue()); Assertions.assertNull(platformPropertyUri.getHashValue());
//Test TBBSecurityAssertion //Test TBBSecurityAssertion
TBBSecurityAssertion tbbSec = platformCert.getTBBSecurityAssertion(); TBBSecurityAssertion tbbSec = platformCert.getTBBSecurityAssertion();
Assertions.assertNotNull(tbbSec); Assertions.assertNotNull(tbbSec);
Assertions.assertTrue(tbbSec.getCcInfo().getVersion().getString().equals("3.1")); Assertions.assertEquals("3.1", tbbSec.getCcInfo().getVersion().getString());
Assertions.assertTrue(tbbSec.getCcInfo().getProfileOid().getId().equals("1.2.3.4.5.6")); Assertions.assertEquals("1.2.3.4.5.6", tbbSec.getCcInfo().getProfileOid().getId());
Assertions.assertTrue(tbbSec.getFipsLevel().getVersion().getString().equals("140-2")); Assertions.assertEquals("140-2", tbbSec.getFipsLevel().getVersion().getString());
Assertions.assertTrue(tbbSec.getIso9000Uri().getString() Assertions.assertEquals("https://www.intel.com/isocertification.pdf",
.equals("https://www.intel.com/isocertification.pdf")); tbbSec.getIso9000Uri().getString());
} }
/** /**
* Tests Platform Configuration Values. View platform Properties * Tests Platform Configuration Values. View platform Properties
* *
* @throws IOException if an IO error occurs during processing * @throws IOException if an IO error occurs during processing
* @throws URISyntaxException if there is a problem constructing the cert's URI * @throws URISyntaxException if there is a problem constructing the cert's URI
*/ */
@Test @Test
@ -597,24 +586,20 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
ComponentIdentifier component; ComponentIdentifier component;
//Check component #1 //Check component #1
component = (ComponentIdentifier) allComponents.get(0); component = allComponents.get(0);
Assertions.assertTrue(component.getComponentModel() Assertions.assertEquals("NUC7i5DNB", component.getComponentModel()
.getString() .getString());
.equals("NUC7i5DNB")); Assertions.assertEquals("J57626-401", component.getComponentRevision()
Assertions.assertTrue(component.getComponentRevision() .getString());
.getString()
.equals("J57626-401"));
//Check component #7 //Check component #7
component = (ComponentIdentifier) allComponents.get(6); component = allComponents.get(6);
Assertions.assertTrue(component.getComponentAddress().size() > 0); Assertions.assertTrue(component.getComponentAddress().size() > 0);
Assertions.assertTrue(component.getComponentAddress().get(0) Assertions.assertEquals("8c:0f:6f:72:c6:c5", component.getComponentAddress().get(0)
.getAddressValue() .getAddressValue()
.getString() .getString());
.equals("8c:0f:6f:72:c6:c5")); Assertions.assertEquals("ethernet mac", component.getComponentAddress().get(0)
Assertions.assertTrue(component.getComponentAddress().get(0) .getAddressTypeValue());
.getAddressTypeValue()
.equals("ethernet mac"));
//Check Platform Properties //Check Platform Properties
List<PlatformProperty> platformProperties = platformConfig.getPlatformProperties(); List<PlatformProperty> platformProperties = platformConfig.getPlatformProperties();
@ -628,27 +613,27 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
URIReference platformPropertyUri = platformConfig.getPlatformPropertiesUri(); URIReference platformPropertyUri = platformConfig.getPlatformPropertiesUri();
Assertions.assertNotNull(platformPropertyUri); Assertions.assertNotNull(platformPropertyUri);
Assertions.assertTrue(platformPropertyUri.getUniformResourceIdentifier() Assertions.assertEquals("https://www.intel.com/platformproperties.xml",
.getString() platformPropertyUri.getUniformResourceIdentifier()
.equals("https://www.intel.com/platformproperties.xml")); .getString());
Assertions.assertNull(platformPropertyUri.getHashAlgorithm()); Assertions.assertNull(platformPropertyUri.getHashAlgorithm());
Assertions.assertNull(platformPropertyUri.getHashValue()); Assertions.assertNull(platformPropertyUri.getHashValue());
//Test TBBSecurityAssertion //Test TBBSecurityAssertion
TBBSecurityAssertion tbbSec = platformCert.getTBBSecurityAssertion(); TBBSecurityAssertion tbbSec = platformCert.getTBBSecurityAssertion();
Assertions.assertNotNull(tbbSec); Assertions.assertNotNull(tbbSec);
Assertions.assertTrue(tbbSec.getCcInfo().getVersion().getString().equals("3.1")); Assertions.assertEquals("3.1", tbbSec.getCcInfo().getVersion().getString());
Assertions.assertTrue(tbbSec.getCcInfo().getProfileOid().getId().equals("1.2.3.4.5.6")); Assertions.assertEquals("1.2.3.4.5.6", tbbSec.getCcInfo().getProfileOid().getId());
Assertions.assertTrue(tbbSec.getFipsLevel().getVersion().getString().equals("140-2")); Assertions.assertEquals("140-2", tbbSec.getFipsLevel().getVersion().getString());
Assertions.assertTrue(tbbSec.getIso9000Uri().getString() Assertions.assertEquals("https://www.intel.com/isocertification.pdf",
.equals("https://www.intel.com/isocertification.pdf")); tbbSec.getIso9000Uri().getString());
} }
/** /**
* Tests Platform Configuration Values. View platform Properties * Tests Platform Configuration Values. View platform Properties
* *
* @throws IOException if an IO error occurs during processing * @throws IOException if an IO error occurs during processing
* @throws URISyntaxException if there is a problem constructing the cert's URI * @throws URISyntaxException if there is a problem constructing the cert's URI
*/ */
@Test @Test
@ -675,25 +660,25 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
PlatformProperty property; PlatformProperty property;
//Check property #1 //Check property #1
property = (PlatformProperty) platformProperties.get(0); property = platformProperties.get(0);
Assertions.assertTrue(property.getPropertyName().getString().equals("AMT")); Assertions.assertEquals("AMT", property.getPropertyName().getString());
Assertions.assertTrue(property.getPropertyValue().getString().equals("true")); Assertions.assertEquals("true", property.getPropertyValue().getString());
//Check property #2 //Check property #2
property = (PlatformProperty) platformProperties.get(1); property = platformProperties.get(1);
Assertions.assertTrue(property.getPropertyName().getString().equals("vPro Enabled")); Assertions.assertEquals("vPro Enabled", property.getPropertyName().getString());
Assertions.assertTrue(property.getPropertyValue().getString().equals("true")); Assertions.assertEquals("true", property.getPropertyValue().getString());
//Check property #3 //Check property #3
property = (PlatformProperty) platformProperties.get(2); property = platformProperties.get(2);
Assertions.assertTrue(property.getPropertyName().getString().equals("DropShip Enabled")); Assertions.assertEquals("DropShip Enabled", property.getPropertyName().getString());
Assertions.assertTrue(property.getPropertyValue().getString().equals("false")); Assertions.assertEquals("false", property.getPropertyValue().getString());
} }
/** /**
* Tests Platform Configuration Values. View platform Properties * Tests Platform Configuration Values. View platform Properties
* *
* @throws IOException if an IO error occurs during processing * @throws IOException if an IO error occurs during processing
* @throws URISyntaxException if there is a problem constructing the cert's URI * @throws URISyntaxException if there is a problem constructing the cert's URI
*/ */
@Test @Test
@ -705,7 +690,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
PlatformCredential platformCert = new PlatformCredential(certPath); PlatformCredential platformCert = new PlatformCredential(certPath);
PlatformConfiguration platformConfig = platformCert.getPlatformConfiguration(); PlatformConfiguration platformConfig = platformCert.getPlatformConfiguration();
Assertions.assertTrue(platformConfig instanceof PlatformConfigurationV2); Assertions.assertInstanceOf(PlatformConfigurationV2.class, platformConfig);
Assertions.assertEquals(platformConfig.getPlatformPropertiesUri() Assertions.assertEquals(platformConfig.getPlatformPropertiesUri()
.getUniformResourceIdentifier().toString(), .getUniformResourceIdentifier().toString(),
"https://www.intel.com/platformproperties.xml"); "https://www.intel.com/platformproperties.xml");
@ -721,7 +706,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
* Tests Platform Configuration Values. View platform Properties * Tests Platform Configuration Values. View platform Properties
* *
* @throws URISyntaxException if there is a problem constructing the cert's URI * @throws URISyntaxException if there is a problem constructing the cert's URI
* @throws IOException if there is a problem reading the cert file * @throws IOException if there is a problem reading the cert file
*/ */
@Test @Test
public final void testSmallNewPlatformCredential() throws URISyntaxException, IOException { public final void testSmallNewPlatformCredential() throws URISyntaxException, IOException {
@ -734,7 +719,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
/** /**
* Tests Platform Configuration Values. View platform Properties * Tests Platform Configuration Values. View platform Properties
* *
* @throws IOException if an IO error occurs during processing * @throws IOException if an IO error occurs during processing
* @throws URISyntaxException if there is a problem constructing the cert's URI * @throws URISyntaxException if there is a problem constructing the cert's URI
*/ */
@Test @Test
@ -748,7 +733,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
/** /**
* Tests Platform Configuration Values. View platform Properties * Tests Platform Configuration Values. View platform Properties
* *
* @throws IOException if an IO error occurs during processing * @throws IOException if an IO error occurs during processing
* @throws URISyntaxException if there is a problem constructing the cert's URI * @throws URISyntaxException if there is a problem constructing the cert's URI
*/ */
@Test @Test
@ -762,7 +747,7 @@ public class PlatformCredentialTest extends AbstractUserdefinedEntityTest {
/** /**
* Tests Platform Configuration Values. View platform Properties * Tests Platform Configuration Values. View platform Properties
* *
* @throws IOException if an IO error occurs during processing * @throws IOException if an IO error occurs during processing
* @throws URISyntaxException if there is a problem constructing the cert's URI * @throws URISyntaxException if there is a problem constructing the cert's URI
*/ */
@Test @Test

View File

@ -1,12 +1,13 @@
package hirs.attestationca.persist.entity.userdefined.certificate.attributes; package hirs.attestationca.persist.entity.userdefined.certificate.attributes;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.nio.file.Paths; import java.nio.file.Paths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/** /**
* Tests for the ComponentClassTest class. * Tests for the ComponentClassTest class.
*/ */
@ -16,6 +17,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -32,6 +34,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -47,6 +50,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -59,8 +63,10 @@ public class ComponentClassTest {
assertEquals(resultComponent, "Unknown"); assertEquals(resultComponent, "Unknown");
assertEquals(resultCategory, "None"); assertEquals(resultCategory, "None");
} }
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -76,6 +82,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -91,6 +98,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -106,6 +114,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -121,6 +130,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -136,6 +146,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -151,6 +162,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -166,6 +178,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -181,6 +194,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -196,6 +210,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -211,6 +226,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -226,6 +242,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -241,6 +258,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -256,6 +274,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test
@ -271,6 +290,7 @@ public class ComponentClassTest {
/** /**
* Test of getComponent method, of class ComponentClass. * Test of getComponent method, of class ComponentClass.
*
* @throws URISyntaxException if there is a problem constructing the URI * @throws URISyntaxException if there is a problem constructing the URI
*/ */
@Test @Test

View File

@ -1,9 +1,10 @@
package hirs.attestationca.persist.entity.userdefined.certificate.attributes; package hirs.attestationca.persist.entity.userdefined.certificate.attributes;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
/** /**
* Tests for the TPMSecurityAssertions class. * Tests for the TPMSecurityAssertions class.
@ -28,7 +29,6 @@ public class TPMSecurityAssertionsTest {
assertNull(TPMSecurityAssertions.EkGenerationType.values()[4]); assertNull(TPMSecurityAssertions.EkGenerationType.values()[4]);
fail(); fail();
} catch (ArrayIndexOutOfBoundsException e) { } catch (ArrayIndexOutOfBoundsException e) {
return;
} }
} }
@ -48,7 +48,6 @@ public class TPMSecurityAssertionsTest {
assertNull(TPMSecurityAssertions.EkGenerationLocation.values()[3]); assertNull(TPMSecurityAssertions.EkGenerationLocation.values()[3]);
fail(); fail();
} catch (ArrayIndexOutOfBoundsException e) { } catch (ArrayIndexOutOfBoundsException e) {
return;
} }
} }
} }

View File

@ -1,12 +1,13 @@
package hirs.attestationca.persist.entity.userdefined.info; package hirs.attestationca.persist.entity.userdefined.info;
import hirs.utils.enums.PortalScheme; import hirs.utils.enums.PortalScheme;
import org.junit.jupiter.api.Test;
import java.net.InetAddress; import java.net.InetAddress;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
/** /**
* Provides tests for PortalInfo. * Provides tests for PortalInfo.
@ -56,6 +57,7 @@ public class PortalInfoTest {
/** /**
* Test that the ip address can be set and retrieved via an InetAddress. * Test that the ip address can be set and retrieved via an InetAddress.
*
* @throws Exception If there is a problem with InetAddress. * @throws Exception If there is a problem with InetAddress.
*/ */
@Test @Test
@ -70,6 +72,7 @@ public class PortalInfoTest {
/** /**
* Test that the ip address can be set and retrieved via a String. * Test that the ip address can be set and retrieved via a String.
*
* @throws Exception If there is a problem with InetAddress. * @throws Exception If there is a problem with InetAddress.
*/ */
@Test @Test

View File

@ -1,15 +1,16 @@
package hirs.attestationca.persist.entity.userdefined.info; package hirs.attestationca.persist.entity.userdefined.info;
import static hirs.utils.enums.DeviceInfoEnums.NOT_SPECIFIED;
import hirs.attestationca.persist.entity.userdefined.AbstractUserdefinedEntityTest; import hirs.attestationca.persist.entity.userdefined.AbstractUserdefinedEntityTest;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.Test;
import static hirs.utils.enums.DeviceInfoEnums.NOT_SPECIFIED;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
/** /**
* TPMInfoTest is a unit test class for TPMInfo. * TPMInfoTest is a unit test class for TPMInfo.
@ -53,7 +54,7 @@ public class TPMInfoTest extends AbstractUserdefinedEntityTest {
assertEquals(tpmInfo.getTpmVersionMinor(), (short) 0); assertEquals(tpmInfo.getTpmVersionMinor(), (short) 0);
assertEquals(tpmInfo.getTpmVersionRevMajor(), (short) 0); assertEquals(tpmInfo.getTpmVersionRevMajor(), (short) 0);
assertEquals(tpmInfo.getTpmVersionRevMinor(), (short) 0); assertEquals(tpmInfo.getTpmVersionRevMinor(), (short) 0);
assertEquals(tpmInfo.getIdentityCertificate(), null); assertNull(tpmInfo.getIdentityCertificate());
} }
/** /**
@ -63,7 +64,7 @@ public class TPMInfoTest extends AbstractUserdefinedEntityTest {
public final void tpmMakeNullTest() { public final void tpmMakeNullTest() {
assertThrows(IllegalArgumentException.class, () -> assertThrows(IllegalArgumentException.class, () ->
new TPMInfo(null, VERSION_MAJOR, VERSION_MINOR, VERSION_REV_MAJOR, new TPMInfo(null, VERSION_MAJOR, VERSION_MINOR, VERSION_REV_MAJOR,
VERSION_REV_MINOR, getTestIdentityCertificate())); VERSION_REV_MINOR, getTestIdentityCertificate()));
} }
/** /**
@ -73,7 +74,7 @@ public class TPMInfoTest extends AbstractUserdefinedEntityTest {
public final void tpmMakeLongTest() { public final void tpmMakeLongTest() {
assertThrows(IllegalArgumentException.class, () -> assertThrows(IllegalArgumentException.class, () ->
new TPMInfo(LONG_TPM_MAKE, VERSION_MAJOR, VERSION_MINOR, VERSION_REV_MAJOR, new TPMInfo(LONG_TPM_MAKE, VERSION_MAJOR, VERSION_MINOR, VERSION_REV_MAJOR,
VERSION_REV_MINOR, getTestIdentityCertificate())); VERSION_REV_MINOR, getTestIdentityCertificate()));
} }
/** /**
@ -84,7 +85,7 @@ public class TPMInfoTest extends AbstractUserdefinedEntityTest {
public final void testTPMInfoInvalidVersionMajor() { public final void testTPMInfoInvalidVersionMajor() {
assertThrows(IllegalArgumentException.class, () -> assertThrows(IllegalArgumentException.class, () ->
new TPMInfo(TPM_MAKE, (short) -1, VERSION_MINOR, VERSION_REV_MAJOR, new TPMInfo(TPM_MAKE, (short) -1, VERSION_MINOR, VERSION_REV_MAJOR,
VERSION_REV_MINOR, getTestIdentityCertificate())); VERSION_REV_MINOR, getTestIdentityCertificate()));
} }
/** /**
@ -95,7 +96,7 @@ public class TPMInfoTest extends AbstractUserdefinedEntityTest {
public final void testTPMInfoInvalidVersionMinor() { public final void testTPMInfoInvalidVersionMinor() {
assertThrows(IllegalArgumentException.class, () -> assertThrows(IllegalArgumentException.class, () ->
new TPMInfo(TPM_MAKE, VERSION_MAJOR, (short) -1, VERSION_REV_MAJOR, new TPMInfo(TPM_MAKE, VERSION_MAJOR, (short) -1, VERSION_REV_MAJOR,
VERSION_REV_MINOR, getTestIdentityCertificate())); VERSION_REV_MINOR, getTestIdentityCertificate()));
} }
/** /**
@ -106,7 +107,7 @@ public class TPMInfoTest extends AbstractUserdefinedEntityTest {
public final void testTPMInfoInvalidVersionRevMajor() { public final void testTPMInfoInvalidVersionRevMajor() {
assertThrows(IllegalArgumentException.class, () -> assertThrows(IllegalArgumentException.class, () ->
new TPMInfo(TPM_MAKE, VERSION_MAJOR, VERSION_MINOR, (short) -1, new TPMInfo(TPM_MAKE, VERSION_MAJOR, VERSION_MINOR, (short) -1,
VERSION_REV_MINOR, getTestIdentityCertificate())); VERSION_REV_MINOR, getTestIdentityCertificate()));
} }
/** /**
@ -117,7 +118,7 @@ public class TPMInfoTest extends AbstractUserdefinedEntityTest {
public final void testTPMInfoInvalidVersionRevMinor() { public final void testTPMInfoInvalidVersionRevMinor() {
assertThrows(IllegalArgumentException.class, () -> assertThrows(IllegalArgumentException.class, () ->
new TPMInfo(TPM_MAKE, VERSION_MAJOR, VERSION_MINOR, VERSION_REV_MAJOR, new TPMInfo(TPM_MAKE, VERSION_MAJOR, VERSION_MINOR, VERSION_REV_MAJOR,
(short) -1, getTestIdentityCertificate())); (short) -1, getTestIdentityCertificate()));
} }
/** /**

View File

@ -5,14 +5,13 @@ import hirs.utils.digest.Digest;
import hirs.utils.digest.DigestAlgorithm; import hirs.utils.digest.DigestAlgorithm;
import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.binary.Hex;
import org.junit.jupiter.api.Test;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
/** /**

View File

@ -1,14 +1,14 @@
package hirs.attestationca.persist.entity.userdefined.report; package hirs.attestationca.persist.entity.userdefined.report;
import hirs.attestationca.persist.entity.userdefined.AbstractUserdefinedEntityTest; import hirs.attestationca.persist.entity.userdefined.AbstractUserdefinedEntityTest;
import hirs.attestationca.persist.entity.userdefined.info.FirmwareInfo;
import hirs.attestationca.persist.entity.userdefined.info.HardwareInfo;
import hirs.attestationca.persist.entity.userdefined.info.NetworkInfo;
import hirs.attestationca.persist.entity.userdefined.info.OSInfo; import hirs.attestationca.persist.entity.userdefined.info.OSInfo;
import hirs.attestationca.persist.entity.userdefined.info.TPMInfo; import hirs.attestationca.persist.entity.userdefined.info.TPMInfo;
import hirs.attestationca.persist.entity.userdefined.info.NetworkInfo;
import hirs.attestationca.persist.entity.userdefined.info.HardwareInfo;
import hirs.attestationca.persist.entity.userdefined.info.FirmwareInfo;
import hirs.utils.VersionHelper; import hirs.utils.VersionHelper;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@ -16,14 +16,13 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
* Unit test class for DeviceInfoReports. * Unit test class for DeviceInfoReports.
*/ */
public class DeviceInfoReportTest extends AbstractUserdefinedEntityTest { public class DeviceInfoReportTest extends AbstractUserdefinedEntityTest {
private static final String EXPECTED_CLIENT_VERSION = VersionHelper.getVersion();
private final NetworkInfo networkInfo = createTestNetworkInfo(); private final NetworkInfo networkInfo = createTestNetworkInfo();
private final OSInfo osInfo = createTestOSInfo(); private final OSInfo osInfo = createTestOSInfo();
private final FirmwareInfo firmwareInfo = createTestFirmwareInfo(); private final FirmwareInfo firmwareInfo = createTestFirmwareInfo();
private final HardwareInfo hardwareInfo = createTestHardwareInfo(); private final HardwareInfo hardwareInfo = createTestHardwareInfo();
private final TPMInfo tpmInfo = createTPMInfo(); private final TPMInfo tpmInfo = createTPMInfo();
private static final String EXPECTED_CLIENT_VERSION = VersionHelper.getVersion();
/** /**
* Tests instantiation of a DeviceInfoReport. * Tests instantiation of a DeviceInfoReport.
*/ */

View File

@ -20,13 +20,12 @@ import static org.mockito.Mockito.verify;
*/ */
public class CredentialManagementHelperTest { public class CredentialManagementHelperTest {
@Mock
private CertificateRepository certificateRepository;
private static final String EK_HEADER_TRUNCATED private static final String EK_HEADER_TRUNCATED
= "/certificates/nuc-1/ek_cert_7_byte_header_removed.cer"; = "/certificates/nuc-1/ek_cert_7_byte_header_removed.cer";
private static final String EK_UNTOUCHED private static final String EK_UNTOUCHED
= "/certificates/nuc-1/ek_cert_untouched.cer"; = "/certificates/nuc-1/ek_cert_untouched.cer";
@Mock
private CertificateRepository certificateRepository;
/** /**
* Setup mocks. * Setup mocks.
@ -39,6 +38,7 @@ public class CredentialManagementHelperTest {
/** /**
* Tests exception generated if providing a null cert repository. * Tests exception generated if providing a null cert repository.
*
* @throws IOException if an IO error occurs * @throws IOException if an IO error occurs
*/ */
@Test @Test
@ -47,7 +47,7 @@ public class CredentialManagementHelperTest {
String path = CredentialManagementHelperTest.class.getResource(EK_UNTOUCHED).getPath(); String path = CredentialManagementHelperTest.class.getResource(EK_UNTOUCHED).getPath();
byte[] ekBytes = IOUtils.toByteArray(new FileInputStream(path)); byte[] ekBytes = IOUtils.toByteArray(new FileInputStream(path));
assertThrows(IllegalArgumentException.class, () -> assertThrows(IllegalArgumentException.class, () ->
CredentialManagementHelper.storeEndorsementCredential(null, ekBytes, "testName")); CredentialManagementHelper.storeEndorsementCredential(null, ekBytes, "testName"));
} }
/** /**
@ -56,7 +56,8 @@ public class CredentialManagementHelperTest {
@Test @Test
public void processNullEndorsementCredential() { public void processNullEndorsementCredential() {
assertThrows(IllegalArgumentException.class, () -> assertThrows(IllegalArgumentException.class, () ->
CredentialManagementHelper.storeEndorsementCredential(certificateRepository, null, "testName")); CredentialManagementHelper.storeEndorsementCredential(certificateRepository, null,
"testName"));
} }
/** /**
@ -65,8 +66,8 @@ public class CredentialManagementHelperTest {
@Test @Test
public void processEmptyEndorsementCredential() { public void processEmptyEndorsementCredential() {
assertThrows(IllegalArgumentException.class, () -> assertThrows(IllegalArgumentException.class, () ->
CredentialManagementHelper.storeEndorsementCredential( CredentialManagementHelper.storeEndorsementCredential(
certificateRepository, new byte[0], "testName")); certificateRepository, new byte[0], "testName"));
} }
/** /**
@ -87,11 +88,13 @@ public class CredentialManagementHelperTest {
public void processInvalidEndorsementCredentialCase2() { public void processInvalidEndorsementCredentialCase2() {
byte[] ekBytes = new byte[] {1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0}; byte[] ekBytes = new byte[] {1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0};
assertThrows(IllegalArgumentException.class, () -> assertThrows(IllegalArgumentException.class, () ->
CredentialManagementHelper.storeEndorsementCredential(certificateRepository, ekBytes, "testName")); CredentialManagementHelper.storeEndorsementCredential(certificateRepository, ekBytes,
"testName"));
} }
/** /**
* Tests processing a valid EK with the 7 byte header in tact. * Tests processing a valid EK with the 7 byte header in tact.
*
* @throws IOException if an IO error occurs * @throws IOException if an IO error occurs
*/ */
@Test @Test
@ -105,6 +108,7 @@ public class CredentialManagementHelperTest {
/** /**
* Tests processing a valid EK with the 7 byte header already stripped. * Tests processing a valid EK with the 7 byte header already stripped.
*
* @throws IOException if an IO error occurs * @throws IOException if an IO error occurs
*/ */
@Test @Test

View File

@ -1,7 +1,7 @@
package hirs.attestationca.persist.provision.helper; package hirs.attestationca.persist.provision.helper;
import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredential;
import hirs.attestationca.persist.entity.userdefined.certificate.EndorsementCredential; import hirs.attestationca.persist.entity.userdefined.certificate.EndorsementCredential;
import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredential;
import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.ASN1TaggedObject; import org.bouncycastle.asn1.ASN1TaggedObject;
@ -51,23 +51,25 @@ public class IssuedCertificateAttributeHelperTest {
/** /**
* Test that provide a null host name and is rejected. * Test that provide a null host name and is rejected.
*
* @throws IOException an IO error occurs * @throws IOException an IO error occurs
*/ */
@Test @Test
public void rejectNullHostName() throws IOException { public void rejectNullHostName() throws IOException {
assertThrows(IllegalArgumentException.class, () -> assertThrows(IllegalArgumentException.class, () ->
IssuedCertificateAttributeHelper.buildSubjectAlternativeNameFromCerts(null, null, "")); IssuedCertificateAttributeHelper.buildSubjectAlternativeNameFromCerts(null, null, ""));
} }
/** /**
* Test that subject alt name can be built without an EC or PC. * Test that subject alt name can be built without an EC or PC.
*
* @throws IOException an IO error occurs * @throws IOException an IO error occurs
*/ */
@Test @Test
public void buildAttributesNoEndorsementNoPlatform() throws IOException { public void buildAttributesNoEndorsementNoPlatform() throws IOException {
Extension subjectAlternativeName = Extension subjectAlternativeName =
IssuedCertificateAttributeHelper.buildSubjectAlternativeNameFromCerts( IssuedCertificateAttributeHelper.buildSubjectAlternativeNameFromCerts(
null, new ArrayList<PlatformCredential>(), TEST_HOSTNAME); null, new ArrayList<PlatformCredential>(), TEST_HOSTNAME);
Map<String, String> subjectAlternativeNameAttrMap = getSubjectAlternativeNameAttributes( Map<String, String> subjectAlternativeNameAttrMap = getSubjectAlternativeNameAttributes(
subjectAlternativeName); subjectAlternativeName);
@ -83,7 +85,8 @@ public class IssuedCertificateAttributeHelperTest {
/** /**
* Test that subject alt name can be built with an EC but no PC. * Test that subject alt name can be built with an EC but no PC.
* @throws IOException an IO error occurs *
* @throws IOException an IO error occurs
* @throws URISyntaxException unrecognized URI for EC Path * @throws URISyntaxException unrecognized URI for EC Path
*/ */
@Test @Test
@ -114,7 +117,8 @@ public class IssuedCertificateAttributeHelperTest {
/** /**
* Test that subject alt name can be built with an PC but no EC. * Test that subject alt name can be built with an PC but no EC.
* @throws IOException an IO error occurs *
* @throws IOException an IO error occurs
* @throws URISyntaxException unrecognized URI for PC Path * @throws URISyntaxException unrecognized URI for PC Path
*/ */
@Test @Test
@ -147,7 +151,8 @@ public class IssuedCertificateAttributeHelperTest {
/** /**
* Test that subject alt name can be built with a PC and an EC. * Test that subject alt name can be built with a PC and an EC.
* @throws IOException an IO error occurs *
* @throws IOException an IO error occurs
* @throws URISyntaxException unrecognized URI for EC or PC Path * @throws URISyntaxException unrecognized URI for EC or PC Path
*/ */
@Test @Test

View File

@ -1,26 +1,20 @@
package hirs.attestationca.persist.validation; package hirs.attestationca.persist.validation;
import hirs.attestationca.persist.entity.ArchivableEntity;
import hirs.attestationca.persist.entity.userdefined.Certificate; import hirs.attestationca.persist.entity.userdefined.Certificate;
import hirs.attestationca.persist.entity.userdefined.SupplyChainValidation;
import hirs.attestationca.persist.entity.userdefined.certificate.CertificateAuthorityCredential; import hirs.attestationca.persist.entity.userdefined.certificate.CertificateAuthorityCredential;
import hirs.attestationca.persist.entity.userdefined.certificate.EndorsementCredential; import hirs.attestationca.persist.entity.userdefined.certificate.EndorsementCredential;
import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredential; import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredential;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentClass; import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentIdentifier;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.V2.AttributeStatus;
import hirs.attestationca.persist.entity.userdefined.info.ComponentInfo; import hirs.attestationca.persist.entity.userdefined.info.ComponentInfo;
import hirs.attestationca.persist.entity.userdefined.info.HardwareInfo;
import hirs.attestationca.persist.entity.userdefined.info.OSInfo;
import hirs.attestationca.persist.entity.userdefined.info.NetworkInfo;
import hirs.attestationca.persist.entity.userdefined.info.FirmwareInfo; import hirs.attestationca.persist.entity.userdefined.info.FirmwareInfo;
import hirs.attestationca.persist.entity.userdefined.info.HardwareInfo;
import hirs.attestationca.persist.entity.userdefined.info.NetworkInfo;
import hirs.attestationca.persist.entity.userdefined.info.OSInfo;
import hirs.attestationca.persist.entity.userdefined.info.TPMInfo; import hirs.attestationca.persist.entity.userdefined.info.TPMInfo;
import hirs.attestationca.persist.entity.userdefined.info.component.NICComponentInfo; import hirs.attestationca.persist.entity.userdefined.info.component.NICComponentInfo;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentIdentifier;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.V2.ComponentIdentifierV2;
import hirs.attestationca.persist.entity.userdefined.report.DeviceInfoReport; import hirs.attestationca.persist.entity.userdefined.report.DeviceInfoReport;
import hirs.attestationca.persist.enums.AppraisalStatus; import hirs.attestationca.persist.enums.AppraisalStatus;
import hirs.utils.enums.DeviceInfoEnums; import hirs.utils.enums.DeviceInfoEnums;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.bouncycastle.asn1.ASN1Boolean; import org.bouncycastle.asn1.ASN1Boolean;
import org.bouncycastle.asn1.DERUTF8String; import org.bouncycastle.asn1.DERUTF8String;
@ -39,18 +33,10 @@ import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@ -81,17 +67,22 @@ import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException; import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec; import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Date;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
import java.util.UUID; import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** /**
* Tests the SupplyChainCredentialValidator and CredentialValidator class. * Tests the SupplyChainCredentialValidator and CredentialValidator class.
* Migration note: Tests specifically for test Intel Nuc Platform Credentials * Migration note: Tests specifically for test Intel Nuc Platform Credentials
@ -100,24 +91,6 @@ import java.util.UUID;
*/ */
public class SupplyChainCredentialValidatorTest { public class SupplyChainCredentialValidatorTest {
private static final String JSON_FILE = "/config/component-class.json";
private static final String SAMPLE_PACCOR_OUTPUT_TXT = "/hirs/validation/sample_paccor_output.txt";
private static final String SAMPLE_PACCOR_OUTPUT_NOT_SPECIFIED_TXT
= "/hirs/validation/sample_paccor_output_not_specified_values.txt";
private static final String SAMPLE_TEST_PACCOR_CERT
= "/validation/platform_credentials_2/paccor_platform_cert.crt";
private static final String SAMPLE_PACCOR_OUTPUT_WITH_EXTRA_COMPONENT_TXT
= "/hirs/validation/sample_paccor_output_with_extra_component.txt";
private static HardwareInfo hardwareInfo;
private final SupplyChainCredentialValidator supplyChainCredentialValidator =
new SupplyChainCredentialValidator();
private final CredentialValidator credentialValidator =
new CredentialValidator();
private static KeyStore keyStore;
private static KeyStore emptyKeyStore;
/** /**
* File name used to initialize a test KeyStore. * File name used to initialize a test KeyStore.
*/ */
@ -126,17 +99,21 @@ public class SupplyChainCredentialValidatorTest {
* SecureRandom instance. * SecureRandom instance.
*/ */
static final SecureRandom SECURE_RANDOM = new SecureRandom(); static final SecureRandom SECURE_RANDOM = new SecureRandom();
private static final String JSON_FILE = "/config/component-class.json";
private static final String SAMPLE_PACCOR_OUTPUT_TXT = "/hirs/validation/sample_paccor_output.txt";
private static final String SAMPLE_PACCOR_OUTPUT_NOT_SPECIFIED_TXT
= "/hirs/validation/sample_paccor_output_not_specified_values.txt";
private static final String SAMPLE_TEST_PACCOR_CERT
= "/validation/platform_credentials_2/paccor_platform_cert.crt";
private static final String SAMPLE_PACCOR_OUTPUT_WITH_EXTRA_COMPONENT_TXT
= "/hirs/validation/sample_paccor_output_with_extra_component.txt";
private static final String TEST_SIGNING_KEY = "/validation/platform_credentials/ca.pub"; private static final String TEST_SIGNING_KEY = "/validation/platform_credentials/ca.pub";
private static final String TEST_PLATFORM_CRED = private static final String TEST_PLATFORM_CRED =
"/validation/platform_credentials/plat_cert1.pem"; "/validation/platform_credentials/plat_cert1.pem";
private static final String TEST_PLATFORM_CRED2 = private static final String TEST_PLATFORM_CRED2 =
"/validation/platform_credentials/pciids_plat_cert_2-0.pem"; "/validation/platform_credentials/pciids_plat_cert_2-0.pem";
private static final String TEST_PLATFORM_CRED_BASE_CHASIS_COMBO = private static final String TEST_PLATFORM_CRED_BASE_CHASIS_COMBO =
"/validation/platform_credentials/Intel_pc5.pem"; "/validation/platform_credentials/Intel_pc5.pem";
private static final String TEST_BOARD_SERIAL_NUMBER = "GETY421001GV"; private static final String TEST_BOARD_SERIAL_NUMBER = "GETY421001GV";
private static final String TEST_CHASSIS_SERIAL_NUMBER = "G6YK42300C87"; private static final String TEST_CHASSIS_SERIAL_NUMBER = "G6YK42300C87";
private static final String TEST_EK_CERT = "/certificates/nuc-2/tpmcert.pem"; private static final String TEST_EK_CERT = "/certificates/nuc-2/tpmcert.pem";
@ -145,20 +122,16 @@ public class SupplyChainCredentialValidatorTest {
private static final String TEST_COMPONENT_MODEL = "platform2018"; private static final String TEST_COMPONENT_MODEL = "platform2018";
private static final String TEST_COMPONENT_REVISION = "1.0"; private static final String TEST_COMPONENT_REVISION = "1.0";
private static final String BAD_SERIAL = "BAD_SERIAL"; private static final String BAD_SERIAL = "BAD_SERIAL";
//-------Actual ST Micro Endorsement Credential Certificate Chain!-------------- //-------Actual ST Micro Endorsement Credential Certificate Chain!--------------
private static final String EK_CERT = ""; private static final String EK_CERT = "";
private static final String INT_CA_CERT02 = "/certificates/fakestmtpmekint02.pem"; private static final String INT_CA_CERT02 = "/certificates/fakestmtpmekint02.pem";
//-------Generated Intel Credential Certificate Chain-------------- //-------Generated Intel Credential Certificate Chain--------------
private static final String INTEL_PLATFORM_CERT = private static final String INTEL_PLATFORM_CERT =
"/validation/platform_credentials/plat_cert3.pem"; "/validation/platform_credentials/plat_cert3.pem";
private static final String INTEL_PLATFORM_CERT_2 = private static final String INTEL_PLATFORM_CERT_2 =
"/validation/platform_credentials/Intel_pc2.pem"; "/validation/platform_credentials/Intel_pc2.pem";
private static final String INTEL_PLATFORM_CERT_3 = private static final String INTEL_PLATFORM_CERT_3 =
"/validation/platform_credentials/pciids_plat_cert_2-0.pem"; "/validation/platform_credentials/pciids_plat_cert_2-0.pem";
private static final String INTEL_INT_CA = private static final String INTEL_INT_CA =
"/validation/platform_credentials/intel_chain/root/intermediate1.crt"; "/validation/platform_credentials/intel_chain/root/intermediate1.crt";
private static final String FAKE_ROOT_CA = private static final String FAKE_ROOT_CA =
@ -166,7 +139,6 @@ public class SupplyChainCredentialValidatorTest {
private static final String PLATFORM_MANUFACTURER = "Intel"; private static final String PLATFORM_MANUFACTURER = "Intel";
private static final String PLATFORM_MODEL = "S2600KP"; private static final String PLATFORM_MODEL = "S2600KP";
private static final String PLATFORM_VERSION = "H76962-350"; private static final String PLATFORM_VERSION = "H76962-350";
//-------Original Intel Credential Certificate Chain-------------- //-------Original Intel Credential Certificate Chain--------------
private static final String INTEL_PLATFORM_CERT_ORIG = private static final String INTEL_PLATFORM_CERT_ORIG =
"/certificates/fakeIntel_S2600KP_F00F00F00F00.pem"; "/certificates/fakeIntel_S2600KP_F00F00F00F00.pem";
@ -174,38 +146,36 @@ public class SupplyChainCredentialValidatorTest {
"/certificates/fakeIntelIntermediateCA.pem"; "/certificates/fakeIntelIntermediateCA.pem";
private static final String FAKE_ROOT_CA_ORIG = private static final String FAKE_ROOT_CA_ORIG =
"/certificates/fakeCA.pem"; "/certificates/fakeCA.pem";
//-------Fake SGI Credential Certificate Chain-------------- //-------Fake SGI Credential Certificate Chain--------------
private static final String SGI_PLATFORM_CERT = "/certificates/fakeSGI_J2_F00F00F0.pem"; private static final String SGI_PLATFORM_CERT = "/certificates/fakeSGI_J2_F00F00F0.pem";
private static final String SGI_INT_CA = "/certificates/fakeSGIIntermediateCA.pem"; private static final String SGI_INT_CA = "/certificates/fakeSGIIntermediateCA.pem";
private static final String SGI_CRED_SERIAL_NUMBER = "F00F00F0"; private static final String SGI_CRED_SERIAL_NUMBER = "F00F00F0";
//-------Actual Intel NUC Platform -------------- //-------Actual Intel NUC Platform --------------
private static final String NUC_PLATFORM_CERT = private static final String NUC_PLATFORM_CERT =
"/certificates/Intel_nuc_pc.pem"; "/certificates/Intel_nuc_pc.pem";
private static final String NUC_PLATFORM_CERT_SERIAL_NUMBER = "GETY421001DY"; private static final String NUC_PLATFORM_CERT_SERIAL_NUMBER = "GETY421001DY";
private static final String NUC_PLATFORM_CERT2 = private static final String NUC_PLATFORM_CERT2 =
"/certificates/Intel_nuc_pc2.pem"; "/certificates/Intel_nuc_pc2.pem";
private static final String NUC_PLATFORM_CERT_SERIAL_NUMBER2 = "GETY4210001M"; private static final String NUC_PLATFORM_CERT_SERIAL_NUMBER2 = "GETY4210001M";
private static final String INTEL_SIGNING_KEY = "/certificates/IntelSigningKey_20April2017.pem"; private static final String INTEL_SIGNING_KEY = "/certificates/IntelSigningKey_20April2017.pem";
private static final String NEW_NUC1 = private static final String NEW_NUC1 =
"/validation/platform_credentials/Intel_pc3.cer"; "/validation/platform_credentials/Intel_pc3.cer";
private static HardwareInfo hardwareInfo;
private static KeyStore keyStore;
private static KeyStore emptyKeyStore;
private final SupplyChainCredentialValidator supplyChainCredentialValidator =
new SupplyChainCredentialValidator();
private final CredentialValidator credentialValidator =
new CredentialValidator();
/** /**
* Sets up a KeyStore for testing. * Sets up a KeyStore for testing.
* *
* @throws KeyStoreException * @throws KeyStoreException if no Provider supports a KeyStoreSpi implementation for the specified type.
* if no Provider supports a KeyStoreSpi implementation for the specified type. * @throws NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found
* @throws NoSuchAlgorithmException * @throws CertificateException if any of the certificates in the keystore could not be loaded
* if the algorithm used to check the integrity of the keystore cannot be found * @throws IOException if there is an I/O or format problem with the keystore data, if a password is
* @throws CertificateException * required but not given, or if the given password was incorrect
* if any of the certificates in the keystore could not be loaded
* @throws IOException
* if there is an I/O or format problem with the keystore data, if a password is
* required but not given, or if the given password was incorrect
*/ */
@BeforeAll @BeforeAll
public static void setUp() throws KeyStoreException, NoSuchAlgorithmException, public static void setUp() throws KeyStoreException, NoSuchAlgorithmException,
@ -234,13 +204,178 @@ public class SupplyChainCredentialValidatorTest {
} }
} }
private static DeviceInfoReport setupDeviceInfoReport() {
hardwareInfo = new HardwareInfo(
"ACME",
"anvil",
"3.0",
"1234",
"567",
"890");
DeviceInfoReport deviceInfoReport = mock(DeviceInfoReport.class);
when(deviceInfoReport.getHardwareInfo()).thenReturn(hardwareInfo);
return deviceInfoReport;
}
private static DeviceInfoReport setupDeviceInfoReportWithComponents() throws IOException {
return setupDeviceInfoReportWithComponents(SAMPLE_PACCOR_OUTPUT_TXT);
}
private static DeviceInfoReport setupDeviceInfoReportWithNotSpecifiedComponents()
throws IOException {
return setupDeviceInfoReportWithComponents(SAMPLE_PACCOR_OUTPUT_NOT_SPECIFIED_TXT);
}
private static DeviceInfoReport setupDeviceInfoReportWithComponents(
final String paccorOutputResource) throws IOException {
DeviceInfoReport deviceInfoReport = setupDeviceInfoReport();
URL url = SupplyChainCredentialValidator.class.getResource(paccorOutputResource);
String paccorOutputString = IOUtils.toString(url, StandardCharsets.UTF_8);
when(deviceInfoReport.getPaccorOutputString()).thenReturn(paccorOutputString);
return deviceInfoReport;
}
/**
* Creates a new RSA 1024-bit KeyPair using a Bouncy Castle Provider.
*
* @return new KeyPair
*/
private static KeyPair createKeyPair() {
final int keySize = 1024;
KeyPairGenerator gen;
KeyPair keyPair = null;
try {
gen = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
gen.initialize(keySize, SECURE_RANDOM);
keyPair = gen.generateKeyPair();
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
fail("Error occurred while generating key pair", e);
}
return keyPair;
}
/**
* Create a new X.509 attribute certificate given the holder cert, the signing cert, and the
* signing key.
*
* @param targetCert X509Certificate that will be the holder of the attribute cert
* @param signingCert X509Certificate used to sign the new attribute cert
* @param caPrivateKey PrivateKey used to sign the new attribute cert
* @return new X509AttributeCertificate
*/
private static X509AttributeCertificateHolder createAttributeCert(
final X509Certificate targetCert, final X509Certificate signingCert,
final PrivateKey caPrivateKey) {
X509AttributeCertificateHolder cert = null;
try {
final int timeRange = 50000;
AttributeCertificateHolder holder =
new AttributeCertificateHolder(new X509CertificateHolder(
targetCert.getEncoded()));
AttributeCertificateIssuer issuer =
new AttributeCertificateIssuer(new X500Name(signingCert
.getSubjectX500Principal().getName()));
BigInteger serialNumber = BigInteger.ONE;
Date notBefore = new Date(System.currentTimeMillis() - timeRange);
Date notAfter = new Date(System.currentTimeMillis() + timeRange);
X509v2AttributeCertificateBuilder builder =
new X509v2AttributeCertificateBuilder(holder, issuer, serialNumber, notBefore,
notAfter);
ContentSigner signer =
new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC")
.build(caPrivateKey);
cert = builder.build(signer);
} catch (CertificateEncodingException | IOException | OperatorCreationException e) {
fail("Exception occurred while creating a cert", e);
}
return cert;
}
/**
* Create a new X.509 public-key certificate signed by the given certificate.
*
* @param keyPair KeyPair to create the cert for
* @param signingKey PrivateKey of the signing cert
* @param signingCert signing cert
* @return new X509Certificate
*/
private static X509Certificate createCertSignedByAnotherCert(final KeyPair keyPair,
final PrivateKey signingKey,
final X509Certificate signingCert) {
final int timeRange = 10000;
X509Certificate cert = null;
try {
X500Name issuerName = new X500Name(signingCert.getSubjectX500Principal().getName());
X500Name subjectName = new X500Name("CN=Test V3 Certificate");
BigInteger serialNumber = BigInteger.ONE;
Date notBefore = new Date(System.currentTimeMillis() - timeRange);
Date notAfter = new Date(System.currentTimeMillis() + timeRange);
X509v3CertificateBuilder builder =
new JcaX509v3CertificateBuilder(issuerName, serialNumber, notBefore, notAfter,
subjectName, keyPair.getPublic());
ContentSigner signer =
new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build(signingKey);
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(
builder.build(signer));
} catch (Exception e) {
fail("Exception occurred while creating a cert", e);
}
return cert;
}
/**
* Creates a self-signed X.509 public-key certificate.
*
* @param pair KeyPair to create the cert for
* @return self-signed X509Certificate
*/
private static X509Certificate createSelfSignedCertificate(final KeyPair pair) {
Security.addProvider(new BouncyCastleProvider());
final int timeRange = 10000;
X509Certificate cert = null;
try {
X500Name issuerName = new X500Name("CN=Test Self-Signed V3 Certificate");
X500Name subjectName = new X500Name("CN=Test Self-Signed V3 Certificate");
BigInteger serialNumber = BigInteger.ONE;
Date notBefore = new Date(System.currentTimeMillis() - timeRange);
Date notAfter = new Date(System.currentTimeMillis() + timeRange);
X509v3CertificateBuilder builder =
new JcaX509v3CertificateBuilder(issuerName, serialNumber, notBefore, notAfter,
subjectName, pair.getPublic());
ContentSigner signer =
new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build(
pair.getPrivate());
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(
builder.build(signer));
} catch (Exception e) {
fail("Exception occurred while creating a cert", e);
}
return cert;
}
private static InetAddress getTestIpAddress() {
try {
return InetAddress.getByAddress(new byte[] {127, 0, 0, 1});
} catch (UnknownHostException e) {
return null;
}
}
/** /**
* Checks if the ST Micro Endorsement Credential can be validated against the * Checks if the ST Micro Endorsement Credential can be validated against the
* ST/GlobalSIgn Certificate Chain. * ST/GlobalSIgn Certificate Chain.
* @throws IOException if error occurs while reading files *
* @throws URISyntaxException if error occurs while reading files * @throws IOException if error occurs while reading files
* @throws URISyntaxException if error occurs while reading files
* @throws CertificateException if error occurs while processing X509 Certs * @throws CertificateException if error occurs while processing X509 Certs
* @throws KeyStoreException if error occurs while processing Keystore * @throws KeyStoreException if error occurs while processing Keystore
*/ */
@Test @Test
public final void testValidateEndorsementCredential() public final void testValidateEndorsementCredential()
@ -267,7 +402,7 @@ public class SupplyChainCredentialValidatorTest {
ekcert, keyStore, true); ekcert, keyStore, true);
assertEquals(AppraisalStatus.Status.PASS, result.getAppStatus()); assertEquals(AppraisalStatus.Status.PASS, result.getAppStatus());
assertEquals(SupplyChainCredentialValidator.ENDORSEMENT_VALID, result.getMessage()); assertEquals(SupplyChainCredentialValidator.ENDORSEMENT_VALID, result.getMessage());
} finally { } finally {
keyStore.deleteEntry("Intel Intermediate Cert"); keyStore.deleteEntry("Intel Intermediate Cert");
keyStore.deleteEntry("CA cert"); keyStore.deleteEntry("CA cert");
} }
@ -277,10 +412,10 @@ public class SupplyChainCredentialValidatorTest {
* Validates a generated cert chain pretending to be from Intel. Credential was generated * Validates a generated cert chain pretending to be from Intel. Credential was generated
* with an intermediate CA. This tests the entire chain of validation back to the root CA. * with an intermediate CA. This tests the entire chain of validation back to the root CA.
* *
* @throws IOException if error occurs while reading files * @throws IOException if error occurs while reading files
* @throws KeyStoreException if there's an issue string certs to the keystore * @throws KeyStoreException if there's an issue string certs to the keystore
* @throws CertificateException if error occurs while ingesting a certificate * @throws CertificateException if error occurs while ingesting a certificate
* @throws URISyntaxException if a URI can't be processed * @throws URISyntaxException if a URI can't be processed
*/ */
@Test @Test
public final void validateIntelPlatformCredentials() public final void validateIntelPlatformCredentials()
@ -288,13 +423,13 @@ public class SupplyChainCredentialValidatorTest {
Certificate intermediatecacert = Certificate intermediatecacert =
new CertificateAuthorityCredential(Files.readAllBytes(Paths.get( new CertificateAuthorityCredential(Files.readAllBytes(Paths.get(
Objects.requireNonNull(getClass().getResource(INTEL_INT_CA)).toURI())) Objects.requireNonNull(getClass().getResource(INTEL_INT_CA)).toURI()))
); );
Certificate rootcacert = Certificate rootcacert =
new CertificateAuthorityCredential(Files.readAllBytes(Paths.get( new CertificateAuthorityCredential(Files.readAllBytes(Paths.get(
Objects.requireNonNull(getClass().getResource(FAKE_ROOT_CA)).toURI())) Objects.requireNonNull(getClass().getResource(FAKE_ROOT_CA)).toURI()))
); );
try { try {
keyStore.setCertificateEntry("CA cert", rootcacert.getX509Certificate()); keyStore.setCertificateEntry("CA cert", rootcacert.getX509Certificate());
@ -354,9 +489,9 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Checks if the Platform Credential contains the serial number from * Checks if the Platform Credential contains the serial number from
* the device in the platform serial number field. * the device in the platform serial number field.
* @throws Exception If there are errors.
* *
* */ * @throws Exception If there are errors.
*/
// @Test // @Test
public final void validatePlatformCredentialWithDeviceBaseboard() public final void validatePlatformCredentialWithDeviceBaseboard()
throws Exception { throws Exception {
@ -377,7 +512,7 @@ public class SupplyChainCredentialValidatorTest {
AppraisalStatus result = AppraisalStatus result =
CredentialValidator.validatePlatformCredentialAttributes(pc, CredentialValidator.validatePlatformCredentialAttributes(pc,
deviceInfoReport, ec, null, null, deviceInfoReport, ec, null, null,
Collections.emptyList(), UUID.randomUUID(), false); Collections.emptyList(), UUID.randomUUID(), false);
assertEquals(AppraisalStatus.Status.PASS, result.getAppStatus()); assertEquals(AppraisalStatus.Status.PASS, result.getAppStatus());
assertEquals(SupplyChainCredentialValidator.PLATFORM_ATTRIBUTES_VALID, assertEquals(SupplyChainCredentialValidator.PLATFORM_ATTRIBUTES_VALID,
result.getMessage()); result.getMessage());
@ -414,10 +549,10 @@ public class SupplyChainCredentialValidatorTest {
result.getMessage()); result.getMessage());
} }
/** /**
* Checks if the NUC Platform Credential contains the serial number from * Checks if the NUC Platform Credential contains the serial number from
* the device as a baseboard component in the serial number field. * the device as a baseboard component in the serial number field.
*
* @throws Exception If there are errors. * @throws Exception If there are errors.
*/ */
// @Test // @Test
@ -462,7 +597,7 @@ public class SupplyChainCredentialValidatorTest {
byte[] certBytes = Files.readAllBytes(Paths.get( byte[] certBytes = Files.readAllBytes(Paths.get(
Objects.requireNonNull(SupplyChainCredentialValidatorTest.class. Objects.requireNonNull(SupplyChainCredentialValidatorTest.class.
getResource(INTEL_PLATFORM_CERT_2)).toURI())); getResource(INTEL_PLATFORM_CERT_2)).toURI()));
PlatformCredential pc = new PlatformCredential(certBytes); PlatformCredential pc = new PlatformCredential(certBytes);
@ -530,7 +665,7 @@ public class SupplyChainCredentialValidatorTest {
PlatformCredential pc = new PlatformCredential(certBytes); PlatformCredential pc = new PlatformCredential(certBytes);
EndorsementCredential ec = new EndorsementCredential(Files.readAllBytes(Paths.get( EndorsementCredential ec = new EndorsementCredential(Files.readAllBytes(Paths.get(
Objects.requireNonNull(getClass().getResource(TEST_EK_CERT)).toURI()))); Objects.requireNonNull(getClass().getResource(TEST_EK_CERT)).toURI())));
AppraisalStatus result = AppraisalStatus result =
CredentialValidator.validatePlatformCredentialAttributes(pc, CredentialValidator.validatePlatformCredentialAttributes(pc,
@ -544,6 +679,7 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Checks if the Platform Credential validator appropriately fails * Checks if the Platform Credential validator appropriately fails
* when there are no serial numbers returned from the device. * when there are no serial numbers returned from the device.
*
* @throws Exception If there are errors. * @throws Exception If there are errors.
*/ */
// @Test // @Test
@ -578,6 +714,7 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Checks if the Platform Credential validator appropriately fails * Checks if the Platform Credential validator appropriately fails
* when there are no serial numbers matching any of the platform info from the device. * when there are no serial numbers matching any of the platform info from the device.
*
* @throws Exception If there are errors. * @throws Exception If there are errors.
*/ */
// @Test // @Test
@ -611,10 +748,10 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Checks if a cert can be validated against the given public key. * Checks if a cert can be validated against the given public key.
* *
* @throws IOException if error occurs while reading files * @throws IOException if error occurs while reading files
* @throws InvalidKeySpecException if error occurs while generating the PublicKey * @throws InvalidKeySpecException if error occurs while generating the PublicKey
* @throws NoSuchAlgorithmException if error occurs while getting RSA KeyFactory * @throws NoSuchAlgorithmException if error occurs while getting RSA KeyFactory
* @throws URISyntaxException if error occurs constructing test cert path * @throws URISyntaxException if error occurs constructing test cert path
* @throws SupplyChainValidatorException if error occurs due to using null certificates * @throws SupplyChainValidatorException if error occurs due to using null certificates
*/ */
@Test @Test
@ -643,8 +780,8 @@ public class SupplyChainCredentialValidatorTest {
* Negative test to check if validation against a public key can fail. Generates a random * Negative test to check if validation against a public key can fail. Generates a random
* key pair and attempts to validate it against the Intel cert, which is expected to fail. * key pair and attempts to validate it against the Intel cert, which is expected to fail.
* *
* @throws IOException if error occurs while reading files * @throws IOException if error occurs while reading files
* @throws URISyntaxException if an error occurs while constructing test resource's URI * @throws URISyntaxException if an error occurs while constructing test resource's URI
* @throws SupplyChainValidatorException if error occurs due to using null certificates * @throws SupplyChainValidatorException if error occurs due to using null certificates
*/ */
@Test @Test
@ -899,7 +1036,7 @@ public class SupplyChainCredentialValidatorTest {
* validation passes. This should result in an error as keystores should never * validation passes. This should result in an error as keystores should never
* be empty. * be empty.
* *
* @throws IOException an error occurs when parsing the certificate * @throws IOException an error occurs when parsing the certificate
* @throws URISyntaxException an error occurs parsing the certificate file path * @throws URISyntaxException an error occurs parsing the certificate file path
*/ */
@Test @Test
@ -907,7 +1044,7 @@ public class SupplyChainCredentialValidatorTest {
throws URISyntaxException, IOException { throws URISyntaxException, IOException {
byte[] certBytes = Files.readAllBytes(Paths.get( byte[] certBytes = Files.readAllBytes(Paths.get(
Objects.requireNonNull(SupplyChainCredentialValidatorTest.class.getResource( Objects.requireNonNull(SupplyChainCredentialValidatorTest.class.getResource(
INTEL_PLATFORM_CERT)).toURI())); INTEL_PLATFORM_CERT)).toURI()));
PlatformCredential pc = new PlatformCredential(certBytes); PlatformCredential pc = new PlatformCredential(certBytes);
@ -939,7 +1076,7 @@ public class SupplyChainCredentialValidatorTest {
* Verifies that a null check is performed on the keyStore * Verifies that a null check is performed on the keyStore
* when validating platform credentials. * when validating platform credentials.
* *
* @throws IOException an error occurs when parsing the certificate * @throws IOException an error occurs when parsing the certificate
* @throws URISyntaxException an error occurs parsing the certificate file path * @throws URISyntaxException an error occurs parsing the certificate file path
*/ */
@Test @Test
@ -947,7 +1084,7 @@ public class SupplyChainCredentialValidatorTest {
throws URISyntaxException, IOException { throws URISyntaxException, IOException {
byte[] certBytes = Files.readAllBytes(Paths.get( byte[] certBytes = Files.readAllBytes(Paths.get(
Objects.requireNonNull(SupplyChainCredentialValidatorTest.class.getResource( Objects.requireNonNull(SupplyChainCredentialValidatorTest.class.getResource(
INTEL_PLATFORM_CERT)).toURI())); INTEL_PLATFORM_CERT)).toURI()));
PlatformCredential pc = new PlatformCredential(certBytes); PlatformCredential pc = new PlatformCredential(certBytes);
@ -964,7 +1101,7 @@ public class SupplyChainCredentialValidatorTest {
* Verifies that a null check is performed on the device info report * Verifies that a null check is performed on the device info report
* when validating platform credentials. * when validating platform credentials.
* *
* @throws IOException an error occurs when parsing the certificate * @throws IOException an error occurs when parsing the certificate
* @throws URISyntaxException an error occurs parsing the certificate file path * @throws URISyntaxException an error occurs parsing the certificate file path
*/ */
// @Test // @Test
@ -972,7 +1109,7 @@ public class SupplyChainCredentialValidatorTest {
throws URISyntaxException, IOException { throws URISyntaxException, IOException {
byte[] certBytes = Files.readAllBytes(Paths.get( byte[] certBytes = Files.readAllBytes(Paths.get(
Objects.requireNonNull(SupplyChainCredentialValidatorTest.class.getResource( Objects.requireNonNull(SupplyChainCredentialValidatorTest.class.getResource(
INTEL_PLATFORM_CERT_2)).toURI())); INTEL_PLATFORM_CERT_2)).toURI()));
PlatformCredential pc = new PlatformCredential(certBytes); PlatformCredential pc = new PlatformCredential(certBytes);
@ -992,9 +1129,10 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Tests that issuer/subject distinguished names can be properly verified as equal even * Tests that issuer/subject distinguished names can be properly verified as equal even
* if their elements are in different orders. * if their elements are in different orders.
* @throws URISyntaxException failed to read certificate *
* @throws IOException failed to read certificate * @throws URISyntaxException failed to read certificate
* @throws KeyStoreException failed to read key store * @throws IOException failed to read certificate
* @throws KeyStoreException failed to read key store
* @throws SupplyChainValidatorException missing credential * @throws SupplyChainValidatorException missing credential
*/ */
@ -1023,9 +1161,10 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Tests that issuer/subject distinguished names can be properly verified as being unequal * Tests that issuer/subject distinguished names can be properly verified as being unequal
* if their elements don't match. * if their elements don't match.
* @throws URISyntaxException failed to read certificate *
* @throws IOException failed to read certificate * @throws URISyntaxException failed to read certificate
* @throws KeyStoreException failed to read key store * @throws IOException failed to read certificate
* @throws KeyStoreException failed to read key store
* @throws SupplyChainValidatorException missing credential * @throws SupplyChainValidatorException missing credential
*/ */
@Test @Test
@ -1038,7 +1177,7 @@ public class SupplyChainCredentialValidatorTest {
byte[] certBytes = Files.readAllBytes(Paths.get( byte[] certBytes = Files.readAllBytes(Paths.get(
Objects.requireNonNull(SupplyChainCredentialValidator.class. Objects.requireNonNull(SupplyChainCredentialValidator.class.
getResource(NEW_NUC1)).toURI())); getResource(NEW_NUC1)).toURI()));
PlatformCredential pc = new PlatformCredential(certBytes); PlatformCredential pc = new PlatformCredential(certBytes);
@ -1052,9 +1191,10 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Tests that issuer/subject distinguished names can be properly verified as equal. * Tests that issuer/subject distinguished names can be properly verified as equal.
* @throws URISyntaxException failed to read certificate *
* @throws IOException failed to read certificate * @throws URISyntaxException failed to read certificate
* @throws KeyStoreException failed to read key store * @throws IOException failed to read certificate
* @throws KeyStoreException failed to read key store
* @throws SupplyChainValidatorException missing credential * @throws SupplyChainValidatorException missing credential
*/ */
@Test @Test
@ -1082,9 +1222,10 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Tests that issuer/subject distinguished names can be properly verified as being unequal * Tests that issuer/subject distinguished names can be properly verified as being unequal
* if their elements don't match. * if their elements don't match.
* @throws URISyntaxException failed to read certificate *
* @throws IOException failed to read certificate * @throws URISyntaxException failed to read certificate
* @throws KeyStoreException failed to read key store * @throws IOException failed to read certificate
* @throws KeyStoreException failed to read key store
* @throws SupplyChainValidatorException missing credential * @throws SupplyChainValidatorException missing credential
*/ */
@Test @Test
@ -1097,7 +1238,7 @@ public class SupplyChainCredentialValidatorTest {
byte[] certBytes = Files.readAllBytes(Paths.get( byte[] certBytes = Files.readAllBytes(Paths.get(
Objects.requireNonNull(SupplyChainCredentialValidator.class. Objects.requireNonNull(SupplyChainCredentialValidator.class.
getResource(TEST_EK_CERT)).toURI())); getResource(TEST_EK_CERT)).toURI()));
EndorsementCredential ec = new EndorsementCredential(certBytes); EndorsementCredential ec = new EndorsementCredential(certBytes);
@ -1109,38 +1250,6 @@ public class SupplyChainCredentialValidatorTest {
x509Cert, caX509)); x509Cert, caX509));
} }
private static DeviceInfoReport setupDeviceInfoReport() {
hardwareInfo = new HardwareInfo(
"ACME",
"anvil",
"3.0",
"1234",
"567",
"890");
DeviceInfoReport deviceInfoReport = mock(DeviceInfoReport.class);
when(deviceInfoReport.getHardwareInfo()).thenReturn(hardwareInfo);
return deviceInfoReport;
}
private static DeviceInfoReport setupDeviceInfoReportWithComponents() throws IOException {
return setupDeviceInfoReportWithComponents(SAMPLE_PACCOR_OUTPUT_TXT);
}
private static DeviceInfoReport setupDeviceInfoReportWithNotSpecifiedComponents()
throws IOException {
return setupDeviceInfoReportWithComponents(SAMPLE_PACCOR_OUTPUT_NOT_SPECIFIED_TXT);
}
private static DeviceInfoReport setupDeviceInfoReportWithComponents(
final String paccorOutputResource) throws IOException {
DeviceInfoReport deviceInfoReport = setupDeviceInfoReport();
URL url = SupplyChainCredentialValidator.class.getResource(paccorOutputResource);
String paccorOutputString = IOUtils.toString(url, StandardCharsets.UTF_8);
when(deviceInfoReport.getPaccorOutputString()).thenReturn(paccorOutputString);
return deviceInfoReport;
}
/** /**
* Tests that isMatch works correctly in comparing component info to component identifier. * Tests that isMatch works correctly in comparing component info to component identifier.
*/ */
@ -1199,7 +1308,7 @@ public class SupplyChainCredentialValidatorTest {
List<ComponentInfo> deviceInfoComponents List<ComponentInfo> deviceInfoComponents
= SupplyChainCredentialValidator.getComponentInfoFromPaccorOutput( = SupplyChainCredentialValidator.getComponentInfoFromPaccorOutput(
deviceInfoReport.getNetworkInfo().getHostname(), deviceInfoReport.getNetworkInfo().getHostname(),
deviceInfoReport.getPaccorOutputString()); deviceInfoReport.getPaccorOutputString());
List<ComponentIdentifier> componentIdentifierList = new ArrayList<>(); List<ComponentIdentifier> componentIdentifierList = new ArrayList<>();
for (ComponentInfo deviceInfoComponent : deviceInfoComponents) { for (ComponentInfo deviceInfoComponent : deviceInfoComponents) {
@ -1231,6 +1340,7 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Tests that TPM 2.0 Platform Credentials validate correctly against the device info report * Tests that TPM 2.0 Platform Credentials validate correctly against the device info report
* when there are no components. * when there are no components.
*
* @throws IOException if unable to set up DeviceInfoReport from resource file * @throws IOException if unable to set up DeviceInfoReport from resource file
*/ */
// @Test // @Test
@ -1251,6 +1361,7 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Tests that TPM 2.0 Platform Credentials validate correctly against the device info report * Tests that TPM 2.0 Platform Credentials validate correctly against the device info report
* when there are components present. * when there are components present.
*
* @throws IOException if unable to set up DeviceInfoReport from resource file * @throws IOException if unable to set up DeviceInfoReport from resource file
*/ */
// @Test // @Test
@ -1271,6 +1382,7 @@ public class SupplyChainCredentialValidatorTest {
* Tests that TPM 2.0 Platform Credentials validate correctly against the device info report * Tests that TPM 2.0 Platform Credentials validate correctly against the device info report
* when there are components present, and when the PlatformSerial field holds the system's * when there are components present, and when the PlatformSerial field holds the system's
* serial number instead of the baseboard serial number. * serial number instead of the baseboard serial number.
*
* @throws IOException if unable to set up DeviceInfoReport from resource file * @throws IOException if unable to set up DeviceInfoReport from resource file
*/ */
// @Test // @Test
@ -1293,7 +1405,8 @@ public class SupplyChainCredentialValidatorTest {
* Tests that TPM 2.0 Platform Credentials validate correctly against the device info report * Tests that TPM 2.0 Platform Credentials validate correctly against the device info report
* when there are components present, and when the PlatformSerial field holds the system's * when there are components present, and when the PlatformSerial field holds the system's
* serial number instead of the baseboard serial number. * serial number instead of the baseboard serial number.
* @throws IOException if unable to set up DeviceInfoReport from resource file *
* @throws IOException if unable to set up DeviceInfoReport from resource file
* @throws URISyntaxException failed to read certificate * @throws URISyntaxException failed to read certificate
*/ */
// @Test // @Test
@ -1302,8 +1415,8 @@ public class SupplyChainCredentialValidatorTest {
DeviceInfoReport deviceInfoReport = setupDeviceInfoReportWithNotSpecifiedComponents(); DeviceInfoReport deviceInfoReport = setupDeviceInfoReportWithNotSpecifiedComponents();
PlatformCredential platformCredential = new PlatformCredential( PlatformCredential platformCredential = new PlatformCredential(
Files.readAllBytes(Paths.get( Files.readAllBytes(Paths.get(
Objects.requireNonNull(SupplyChainCredentialValidator.class.getResource( Objects.requireNonNull(SupplyChainCredentialValidator.class.getResource(
SAMPLE_TEST_PACCOR_CERT)).toURI()))); SAMPLE_TEST_PACCOR_CERT)).toURI())));
AppraisalStatus appraisalStatus = CertificateAttributeScvValidator AppraisalStatus appraisalStatus = CertificateAttributeScvValidator
.validatePlatformCredentialAttributesV2p0(platformCredential, deviceInfoReport, null, null, .validatePlatformCredentialAttributesV2p0(platformCredential, deviceInfoReport, null, null,
@ -1313,6 +1426,7 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Tests that the SupplyChainCredentialValidator fails when required fields are null. * Tests that the SupplyChainCredentialValidator fails when required fields are null.
*
* @throws IOException if unable to set up DeviceInfoReport from resource file * @throws IOException if unable to set up DeviceInfoReport from resource file
*/ */
// @Test // @Test
@ -1425,6 +1539,7 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Tests that the SupplyChainCredentialValidator fails when required fields contain only empty * Tests that the SupplyChainCredentialValidator fails when required fields contain only empty
* strings. * strings.
*
* @throws IOException if unable to set up DeviceInfoReport from resource file * @throws IOException if unable to set up DeviceInfoReport from resource file
*/ */
// @Test // @Test
@ -1484,7 +1599,7 @@ public class SupplyChainCredentialValidatorTest {
result = CertificateAttributeScvValidator result = CertificateAttributeScvValidator
.validatePlatformCredentialAttributesV2p0(platformCredential, .validatePlatformCredentialAttributesV2p0(platformCredential,
deviceInfoReport, null, null, deviceInfoReport, null, null,
Collections.emptyList(), UUID.randomUUID(), false); Collections.emptyList(), UUID.randomUUID(), false);
assertEquals(AppraisalStatus.Status.PASS, result.getAppStatus()); assertEquals(AppraisalStatus.Status.PASS, result.getAppStatus());
assertEquals(SupplyChainCredentialValidator.PLATFORM_ATTRIBUTES_VALID, assertEquals(SupplyChainCredentialValidator.PLATFORM_ATTRIBUTES_VALID,
result.getMessage()); result.getMessage());
@ -1514,9 +1629,9 @@ public class SupplyChainCredentialValidatorTest {
Collections.emptyList(), UUID.randomUUID(), false); Collections.emptyList(), UUID.randomUUID(), false);
assertEquals(AppraisalStatus.Status.FAIL, result.getAppStatus()); assertEquals(AppraisalStatus.Status.FAIL, result.getAppStatus());
assertEquals("Component manufacturer is empty\n" assertEquals("Component manufacturer is empty\n"
+ "There are unmatched components:\n" + "There are unmatched components:\n"
+ "Manufacturer=, Model=Core i7, Serial=Not Specified," + "Manufacturer=, Model=Core i7, Serial=Not Specified,"
+ " Revision=Intel(R) Core(TM) i7-4790 CPU @ 3.60GHz;\n", + " Revision=Intel(R) Core(TM) i7-4790 CPU @ 3.60GHz;\n",
result.getMessage()); result.getMessage());
platformCredential = setupMatchingPlatformCredential(deviceInfoReport); platformCredential = setupMatchingPlatformCredential(deviceInfoReport);
@ -1541,6 +1656,7 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Tests that {@link SupplyChainCredentialValidator} failes when a component exists in the * Tests that {@link SupplyChainCredentialValidator} failes when a component exists in the
* platform credential, but not in the device info report. * platform credential, but not in the device info report.
*
* @throws IOException if unable to set up DeviceInfoReport from resource file * @throws IOException if unable to set up DeviceInfoReport from resource file
*/ */
// @Test // @Test
@ -1577,7 +1693,7 @@ public class SupplyChainCredentialValidatorTest {
Collections.emptyList(), UUID.randomUUID(), false); Collections.emptyList(), UUID.randomUUID(), false);
assertEquals(AppraisalStatus.Status.FAIL, result.getAppStatus()); assertEquals(AppraisalStatus.Status.FAIL, result.getAppStatus());
assertEquals("There are unmatched components:\n" assertEquals("There are unmatched components:\n"
+ "Manufacturer=ACME, Model=TNT, Serial=2, Revision=1.1;\n", + "Manufacturer=ACME, Model=TNT, Serial=2, Revision=1.1;\n",
result.getMessage()); result.getMessage());
} }
@ -1585,6 +1701,7 @@ public class SupplyChainCredentialValidatorTest {
* Tests that SupplyChainCredentialValidator passes when everything matches but there are * Tests that SupplyChainCredentialValidator passes when everything matches but there are
* extra components in the device info report that are not represented in the platform * extra components in the device info report that are not represented in the platform
* credential. * credential.
*
* @throws IOException if unable to set up DeviceInfoReport from resource file * @throws IOException if unable to set up DeviceInfoReport from resource file
*/ */
// @Test // @Test
@ -1617,6 +1734,7 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Tests that SupplyChainCredentialValidator fails when a component is found in the platform * Tests that SupplyChainCredentialValidator fails when a component is found in the platform
* credential without a manufacturer or model. * credential without a manufacturer or model.
*
* @throws IOException if unable to set up DeviceInfoReport from resource file * @throws IOException if unable to set up DeviceInfoReport from resource file
*/ */
// @Test // @Test
@ -1644,9 +1762,9 @@ public class SupplyChainCredentialValidatorTest {
Collections.emptyList(), UUID.randomUUID(), false); Collections.emptyList(), UUID.randomUUID(), false);
assertEquals(AppraisalStatus.Status.FAIL, result.getAppStatus()); assertEquals(AppraisalStatus.Status.FAIL, result.getAppStatus());
assertEquals("Component manufacturer is empty\n" assertEquals("Component manufacturer is empty\n"
+ "There are unmatched components:\n" + "There are unmatched components:\n"
+ "Manufacturer=, Model=Core i7, Serial=Not Specified," + "Manufacturer=, Model=Core i7, Serial=Not Specified,"
+ " Revision=Intel(R) Core(TM) i7-4790 CPU @ 3.60GHz;\n", + " Revision=Intel(R) Core(TM) i7-4790 CPU @ 3.60GHz;\n",
result.getMessage()); result.getMessage());
platformCredential = setupMatchingPlatformCredential(deviceInfoReport); platformCredential = setupMatchingPlatformCredential(deviceInfoReport);
@ -1673,6 +1791,7 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Tests that SupplyChainCredentialValidator passes when a component on the system has a * Tests that SupplyChainCredentialValidator passes when a component on the system has a
* matching component in the platform certificate, except the serial value is missing. * matching component in the platform certificate, except the serial value is missing.
*
* @throws IOException if unable to set up DeviceInfoReport from resource file * @throws IOException if unable to set up DeviceInfoReport from resource file
*/ */
// @Test // @Test
@ -1704,6 +1823,7 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Tests that SupplyChainCredentialValidator passes when a component on the system has a * Tests that SupplyChainCredentialValidator passes when a component on the system has a
* matching component in the platform certificate, except the revision value is missing. * matching component in the platform certificate, except the revision value is missing.
*
* @throws IOException if unable to set up DeviceInfoReport from resource file * @throws IOException if unable to set up DeviceInfoReport from resource file
*/ */
// @Test // @Test
@ -1736,6 +1856,7 @@ public class SupplyChainCredentialValidatorTest {
* Tests that SupplyChainCredentialValidator passes when a component on the system has a * Tests that SupplyChainCredentialValidator passes when a component on the system has a
* matching component in the platform certificate, except the serial and revision values * matching component in the platform certificate, except the serial and revision values
* are missing. * are missing.
*
* @throws IOException if unable to set up DeviceInfoReport from resource file * @throws IOException if unable to set up DeviceInfoReport from resource file
*/ */
// @Test // @Test
@ -1768,7 +1889,8 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Tests that SupplyChainCredentialValidator passes with a base and delta certificate where * Tests that SupplyChainCredentialValidator passes with a base and delta certificate where
* the base serial number and delta holder serial number match. * the base serial number and delta holder serial number match.
* @throws java.io.IOException Reading file for the certificates *
* @throws java.io.IOException Reading file for the certificates
* @throws java.net.URISyntaxException when loading certificates bytes * @throws java.net.URISyntaxException when loading certificates bytes
*/ */
// @Test // @Test
@ -1904,7 +2026,8 @@ public class SupplyChainCredentialValidatorTest {
/** /**
* Tests that SupplyChainCredentialValidator fails when a component needs to * Tests that SupplyChainCredentialValidator fails when a component needs to
* be replaced but hasn't been by a delta certificate. * be replaced but hasn't been by a delta certificate.
* @throws java.io.IOException Reading file for the certificates *
* @throws java.io.IOException Reading file for the certificates
* @throws java.net.URISyntaxException when loading certificates bytes * @throws java.net.URISyntaxException when loading certificates bytes
*/ */
// @Test // @Test
@ -2014,136 +2137,6 @@ public class SupplyChainCredentialValidatorTest {
// result.getMessage()); // result.getMessage());
} }
/**
* Creates a new RSA 1024-bit KeyPair using a Bouncy Castle Provider.
*
* @return new KeyPair
*/
private static KeyPair createKeyPair() {
final int keySize = 1024;
KeyPairGenerator gen;
KeyPair keyPair = null;
try {
gen = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
gen.initialize(keySize, SECURE_RANDOM);
keyPair = gen.generateKeyPair();
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
fail("Error occurred while generating key pair", e);
}
return keyPair;
}
/**
* Create a new X.509 attribute certificate given the holder cert, the signing cert, and the
* signing key.
*
* @param targetCert
* X509Certificate that will be the holder of the attribute cert
* @param signingCert
* X509Certificate used to sign the new attribute cert
* @param caPrivateKey
* PrivateKey used to sign the new attribute cert
* @return new X509AttributeCertificate
*/
private static X509AttributeCertificateHolder createAttributeCert(
final X509Certificate targetCert, final X509Certificate signingCert,
final PrivateKey caPrivateKey) {
X509AttributeCertificateHolder cert = null;
try {
final int timeRange = 50000;
AttributeCertificateHolder holder =
new AttributeCertificateHolder(new X509CertificateHolder(
targetCert.getEncoded()));
AttributeCertificateIssuer issuer =
new AttributeCertificateIssuer(new X500Name(signingCert
.getSubjectX500Principal().getName()));
BigInteger serialNumber = BigInteger.ONE;
Date notBefore = new Date(System.currentTimeMillis() - timeRange);
Date notAfter = new Date(System.currentTimeMillis() + timeRange);
X509v2AttributeCertificateBuilder builder =
new X509v2AttributeCertificateBuilder(holder, issuer, serialNumber, notBefore,
notAfter);
ContentSigner signer =
new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC")
.build(caPrivateKey);
cert = builder.build(signer);
} catch (CertificateEncodingException | IOException | OperatorCreationException e) {
fail("Exception occurred while creating a cert", e);
}
return cert;
}
/**
* Create a new X.509 public-key certificate signed by the given certificate.
*
* @param keyPair
* KeyPair to create the cert for
* @param signingKey
* PrivateKey of the signing cert
* @param signingCert
* signing cert
* @return new X509Certificate
*/
private static X509Certificate createCertSignedByAnotherCert(final KeyPair keyPair,
final PrivateKey signingKey, final X509Certificate signingCert) {
final int timeRange = 10000;
X509Certificate cert = null;
try {
X500Name issuerName = new X500Name(signingCert.getSubjectX500Principal().getName());
X500Name subjectName = new X500Name("CN=Test V3 Certificate");
BigInteger serialNumber = BigInteger.ONE;
Date notBefore = new Date(System.currentTimeMillis() - timeRange);
Date notAfter = new Date(System.currentTimeMillis() + timeRange);
X509v3CertificateBuilder builder =
new JcaX509v3CertificateBuilder(issuerName, serialNumber, notBefore, notAfter,
subjectName, keyPair.getPublic());
ContentSigner signer =
new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build(signingKey);
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(
builder.build(signer));
} catch (Exception e) {
fail("Exception occurred while creating a cert", e);
}
return cert;
}
/**
* Creates a self-signed X.509 public-key certificate.
*
* @param pair
* KeyPair to create the cert for
* @return self-signed X509Certificate
*/
private static X509Certificate createSelfSignedCertificate(final KeyPair pair) {
Security.addProvider(new BouncyCastleProvider());
final int timeRange = 10000;
X509Certificate cert = null;
try {
X500Name issuerName = new X500Name("CN=Test Self-Signed V3 Certificate");
X500Name subjectName = new X500Name("CN=Test Self-Signed V3 Certificate");
BigInteger serialNumber = BigInteger.ONE;
Date notBefore = new Date(System.currentTimeMillis() - timeRange);
Date notAfter = new Date(System.currentTimeMillis() + timeRange);
X509v3CertificateBuilder builder =
new JcaX509v3CertificateBuilder(issuerName, serialNumber, notBefore, notAfter,
subjectName, pair.getPublic());
ContentSigner signer =
new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build(
pair.getPrivate());
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(
builder.build(signer));
} catch (Exception e) {
fail("Exception occurred while creating a cert", e);
}
return cert;
}
private DeviceInfoReport buildReport(final HardwareInfo givenHardwareInfo) { private DeviceInfoReport buildReport(final HardwareInfo givenHardwareInfo) {
final InetAddress ipAddress = getTestIpAddress(); final InetAddress ipAddress = getTestIpAddress();
final byte[] macAddress = new byte[] {11, 22, 33, 44, 55, 66}; final byte[] macAddress = new byte[] {11, 22, 33, 44, 55, 66};
@ -2156,11 +2149,4 @@ public class SupplyChainCredentialValidatorTest {
return new DeviceInfoReport(networkInfo, osInfo, return new DeviceInfoReport(networkInfo, osInfo,
firmwareInfo, givenHardwareInfo, tpmInfo); firmwareInfo, givenHardwareInfo, tpmInfo);
} }
private static InetAddress getTestIpAddress() {
try {
return InetAddress.getByAddress(new byte[] {127, 0, 0, 1});
} catch (UnknownHostException e) {
return null;
}
}
} }