Updated the structure

This commit is contained in:
Cyrus 2023-02-23 12:28:52 -05:00
parent 1f77f3fe26
commit 7cdbc74506
154 changed files with 6949 additions and 843 deletions

View File

@ -2,6 +2,7 @@ plugins {
id 'application'
id 'java'
id 'war'
id "nebula.ospackage" version "9.1.1"
id 'org.springframework.boot' version '3.0.1'
id 'io.spring.dependency-management' version '1.1.0'
}
@ -30,6 +31,8 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.projectlombok:lombok'
implementation 'org.bouncycastle:bcmail-jdk15on:1.70'
implementation 'org.springframework.plugin:spring-plugin-core:3.0.0'
implementation 'org.apache.httpcomponents:httpclient:4.5.7'
implementation 'com.google.guava:guava:31.1-jre'
@ -44,7 +47,7 @@ dependencies {
implementation 'com.fasterxml.jackson.core:jackson-databind:2.14.2'
implementation "org.glassfish.jaxb:jaxb-runtime:4.0.1"
implementation 'jakarta.xml.bind:jakarta.xml.bind-api:4.0.0'
implementation 'com.sun.xml.bind:jaxb-impl:4.0.2'
// implementation 'com.sun.xml.bind:jaxb-impl:4.0.2' //creates duplicate error
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
annotationProcessor 'org.projectlombok:lombok'

View File

@ -12,6 +12,6 @@ dir=$(pwd)
XSD_FILE=$SRC_DIR/main/resources/swid_schema.xsd
if [ ! -d "$DEST_DIR/hirs/attestationca/portal/utils/xjc" ]; then
xjc -p hirs.attestationca.portal.utils.xjc $XSD_FILE -d $DEST_DIR -quiet
if [ ! -d "$DEST_DIR/hirs/attestationca/utils/xjc" ]; then
xjc -p hirs.attestationca.utils.xjc $XSD_FILE -d $DEST_DIR -quiet
fi

View File

@ -1 +0,0 @@
package hirs.attestationca.portal.enums;

View File

@ -1,4 +1,4 @@
package hirs.attestationca.portal.entity;
package hirs.attestationca.portal.persist.entity;
import jakarta.persistence.Column;
import jakarta.persistence.GeneratedValue;
@ -10,6 +10,7 @@ import lombok.ToString;
import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;
import org.hibernate.annotations.JdbcTypeCode;
import java.io.Serializable;
import java.util.Date;
@ -31,6 +32,7 @@ public abstract class AbstractEntity implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue(generator = "uuid2", strategy=GenerationType.AUTO)
@JdbcTypeCode(java.sql.Types.VARCHAR)
@Getter
private UUID id;

View File

@ -1,4 +1,4 @@
package hirs.attestationca.portal.entity;
package hirs.attestationca.portal.persist.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;

View File

@ -1,4 +1,4 @@
package hirs.attestationca.portal.entity;
package hirs.attestationca.portal.persist.entity;
import jakarta.persistence.Column;
import jakarta.persistence.MappedSuperclass;

View File

@ -1,4 +1,4 @@
package hirs.attestationca.portal.entity;
package hirs.attestationca.portal.persist.entity;
import jakarta.persistence.Access;
import jakarta.persistence.AccessType;
@ -60,10 +60,10 @@ public abstract class Policy extends UserDefinedEntity {
}
/**
* When {@link Policy} are serialized to be sent to the browser, this can be used
* to determine the type of {@link Policy}.
* When {@link hirs.attestationca.portal.persist.entity.Policy} are serialized to be sent to the browser, this can be used
* to determine the type of {@link hirs.attestationca.portal.persist.entity.Policy}.
*
* @return The class name for the {@link Policy}
* @return The class name for the {@link hirs.attestationca.portal.persist.entity.Policy}
*/
public String getType() {
return this.getClass().getSimpleName();

View File

@ -1,4 +1,4 @@
package hirs.attestationca.portal.entity;
package hirs.attestationca.portal.persist.entity;
import jakarta.persistence.Column;

View File

@ -1,6 +1,6 @@
package hirs.attestationca.portal.entity.manager;
package hirs.attestationca.portal.persist.entity.manager;
import hirs.attestationca.portal.entity.userdefined.Device;
import hirs.attestationca.persist.entity.userdefined.Device;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

View File

@ -1,6 +1,6 @@
package hirs.attestationca.portal.entity.manager;
package hirs.attestationca.portal.persist.entity.manager;
import hirs.attestationca.portal.entity.userdefined.ReferenceManifest;
import hirs.attestationca.persist.entity.userdefined.ReferenceManifest;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.UUID;

View File

@ -1,6 +1,6 @@
package hirs.attestationca.portal.entity.manager;
package hirs.attestationca.portal.persist.entity.manager;
import hirs.attestationca.portal.entity.userdefined.SupplyChainSettings;
import hirs.attestationca.persist.entity.userdefined.SupplyChainSettings;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

View File

@ -1,4 +1,4 @@
/**
* This package has objects for hibernate entity.
*/
package hirs.attestationca.portal.entity;
package hirs.attestationca.portal.persist.entity;

View File

@ -1,10 +1,10 @@
package hirs.attestationca.portal.entity.userdefined;
package hirs.attestationca.portal.persist.entity.userdefined;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.base.Preconditions;
import hirs.attestationca.portal.entity.ArchivableEntity;
import hirs.attestationca.portal.entity.userdefined.certificate.CertificateVariables;
import hirs.attestationca.portal.utils.HexUtils;
import hirs.attestationca.persist.entity.ArchivableEntity;
import hirs.attestationca.persist.entity.userdefined.certificate.CertificateVariables;
import hirs.attestationca.utils.HexUtils;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Transient;
@ -280,7 +280,7 @@ public abstract class Certificate extends ArchivableEntity {
* should represent either an X509 certificate or X509 attribute certificate.
*
* @param certificatePath the path on disk to a certificate
* @throws IOException if there is a problem reading the file
* @throws java.io.IOException if there is a problem reading the file
*/
public Certificate(final Path certificatePath) throws IOException {
this(readBytes(certificatePath));
@ -291,7 +291,7 @@ public abstract class Certificate extends ArchivableEntity {
* represent either an X509 certificate or X509 attribute certificate.
*
* @param certificateBytes the contents of a certificate file
* @throws IOException if there is a problem extracting information from the certificate
* @throws java.io.IOException if there is a problem extracting information from the certificate
*/
@SuppressWarnings("methodlength")
public Certificate(final byte[] certificateBytes) throws IOException {
@ -573,7 +573,7 @@ public abstract class Certificate extends ArchivableEntity {
* @param issuer the other certificate to check (must be an X509Certificate,
* not an X509AttributeCertificateHolder)
* @return whether or not the other certificate is the issuer for this certificate
* @throws IOException if there is an issue deserializing either certificate
* @throws java.io.IOException if there is an issue deserializing either certificate
*/
public String isIssuer(final Certificate issuer) throws IOException {
String isIssuer = "Certificate signature failed to verify";
@ -629,7 +629,7 @@ public abstract class Certificate extends ArchivableEntity {
* Retrieve the original X509 certificate.
*
* @return the original X509 certificate
* @throws IOException if there is a problem deserializing the certificate as an X509 cert
* @throws java.io.IOException if there is a problem deserializing the certificate as an X509 cert
*/
@JsonIgnore
public X509Certificate getX509Certificate() throws IOException {
@ -857,7 +857,7 @@ public abstract class Certificate extends ArchivableEntity {
* Retrieve the original X509 attribute certificate.
*
* @return the original X509 attribute certificate
* @throws IOException if there is a problem deserializing the certificate as an X509
* @throws java.io.IOException if there is a problem deserializing the certificate as an X509
* attribute cert
*/
@JsonIgnore
@ -869,7 +869,7 @@ public abstract class Certificate extends ArchivableEntity {
* Retrieve the original Attribute Certificate.
*
* @return the original Attribute Certificate
* @throws IOException if there is a problem deserializing the certificate as an X509
* @throws java.io.IOException if there is a problem deserializing the certificate as an X509
* attribute cert
*/
@JsonIgnore
@ -962,7 +962,7 @@ public abstract class Certificate extends ArchivableEntity {
* Gets the raw bytes for the certificate.
* @param certificatePath path to the certificate file
* @return bytes from the certificate file
* @throws IOException if there is a problem reading the file
* @throws java.io.IOException if there is a problem reading the file
*/
public static byte[] readBytes(final Path certificatePath) throws IOException {
Preconditions.checkArgument(
@ -978,7 +978,7 @@ public abstract class Certificate extends ArchivableEntity {
*
* @param certificate the certificate holding a public key
* @return a BigInteger representing its public key's modulus or null if none found
* @throws IOException if there is an issue decoding the encoded public key
* @throws java.io.IOException if there is an issue decoding the encoded public key
*/
public static BigInteger getPublicKeyModulus(final X509Certificate certificate)
throws IOException {
@ -1003,7 +1003,7 @@ public abstract class Certificate extends ArchivableEntity {
*
* @param publicKey the public key
* @return a BigInteger representing the public key's modulus
* @throws IOException if there is an issue decoding the public key
* @throws java.io.IOException if there is an issue decoding the public key
*/
public static BigInteger getPublicKeyModulus(final PublicKey publicKey) throws IOException {
ASN1Primitive publicKeyASN1 = ASN1Primitive.fromByteArray(publicKey.getEncoded());

View File

@ -1,8 +1,8 @@
package hirs.attestationca.portal.entity.userdefined;
package hirs.attestationca.portal.persist.entity.userdefined;
import hirs.attestationca.portal.entity.AbstractEntity;
import hirs.attestationca.portal.enums.AppraisalStatus;
import hirs.attestationca.portal.enums.HealthStatus;
import hirs.attestationca.persist.entity.AbstractEntity;
import hirs.attestationca.persist.enums.AppraisalStatus;
import hirs.attestationca.persist.enums.HealthStatus;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;

View File

@ -1,6 +1,6 @@
package hirs.attestationca.portal.entity.userdefined;
package hirs.attestationca.portal.persist.entity.userdefined;
import hirs.attestationca.portal.entity.ArchivableEntity;
import hirs.attestationca.persist.entity.ArchivableEntity;
import jakarta.persistence.Access;
import jakarta.persistence.AccessType;
import jakarta.persistence.Column;

View File

@ -1,8 +1,8 @@
package hirs.attestationca.portal.entity.userdefined;
package hirs.attestationca.portal.persist.entity.userdefined;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.base.Preconditions;
import hirs.attestationca.portal.entity.ArchivableEntity;
import hirs.attestationca.persist.entity.ArchivableEntity;
import jakarta.persistence.Access;
import jakarta.persistence.AccessType;
import jakarta.persistence.Column;

View File

@ -0,0 +1,41 @@
package hirs.attestationca.portal.persist.entity.userdefined;
import hirs.attestationca.persist.entity.AbstractEntity;
import jakarta.persistence.Access;
import jakarta.persistence.AccessType;
import jakarta.persistence.Entity;
import jakarta.persistence.Inheritance;
import jakarta.persistence.InheritanceType;
/**
* A <code>Report</code> represents an integrity report to be appraised by an
* <code>Appraiser</code>. An <code>Appraiser</code> validates the integrity of
* a client's platform with an integrity report. Example reports include an IMA
* report and TPM report.
* <p>
* This <code>Report</code> class contains minimal information because each
* report is vastly different. There is an identification number in case the
* <code>Report</code> is stored in a database, and there is a report type. The
* report type is used to determine which <code>Appraiser</code>s can appraise
* the report.
*/
@Entity
@Access(AccessType.FIELD)
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Report extends AbstractEntity {
/**
* Default constructor.
*/
protected Report() {
super();
}
/**
* Returns a <code>String</code> that indicates this report type. The report
* type is used to find an <code>Appraiser</code> that can appraise this
* <code>Report</code>.
*
* @return report type
*/
public abstract String getReportType();
}

View File

@ -1,6 +1,6 @@
package hirs.attestationca.portal.entity.userdefined;
package hirs.attestationca.portal.persist.entity.userdefined;
import hirs.attestationca.portal.entity.UserDefinedEntity;
import hirs.attestationca.persist.entity.UserDefinedEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;

View File

@ -0,0 +1,151 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate;
import hirs.attestationca.persist.entity.userdefined.Certificate;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import lombok.Getter;
import org.apache.commons.codec.binary.Hex;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
/**
* This class persists Certificate Authority credentials by extending the base Certificate
* class with fields unique to CA credentials.
*/
@Entity
public class CertificateAuthorityCredential extends Certificate {
@SuppressWarnings("PMD.AvoidUsingHardCodedIP")
private static final String SUBJECT_KEY_IDENTIFIER_EXTENSION = "2.5.29.14";
/**
* Holds the name of the 'subjectKeyIdentifier' field.
*/
public static final String SUBJECT_KEY_IDENTIFIER_FIELD = "subjectKeyIdentifier";
private static final int CA_BYTE_SIZE = 20;
private static final int PREFIX_BYTE_SIZE = 4;
@Column
private final byte[] subjectKeyIdentifier;
@Getter
@Column
private String subjectKeyIdString;
/**
* this field is part of the TCG CA specification, but has not yet been found in
* manufacturer-provided CAs, and is therefore not currently parsed.
*/
@Getter
@Column
private final String credentialType = "TCPA Trusted Platform Module Endorsement";
/**
* Construct a new CertificateAuthorityCredential given its binary contents. The given
* certificate should represent either an X509 certificate or X509 attribute certificate.
*
* @param certificateBytes the contents of a certificate file
* @throws java.io.IOException if there is a problem extracting information from the certificate
*/
public CertificateAuthorityCredential(final byte[] certificateBytes)
throws IOException {
super(certificateBytes);
byte[] tempBytes = getX509Certificate()
.getExtensionValue(SUBJECT_KEY_IDENTIFIER_EXTENSION);
if (tempBytes != null && tempBytes.length > CA_BYTE_SIZE) {
this.subjectKeyIdentifier = truncatePrefixBytes(tempBytes);
} else {
this.subjectKeyIdentifier =
getX509Certificate().getExtensionValue(SUBJECT_KEY_IDENTIFIER_EXTENSION);
}
if (this.subjectKeyIdentifier != null) {
this.subjectKeyIdString = Hex.encodeHexString(this.subjectKeyIdentifier);
}
}
/**
* Construct a new CertificateAuthorityCredential by parsing the file at the given path.
* The given certificate should represent either an X509 certificate or X509 attribute
* certificate.
*
* @param certificatePath the path on disk to a certificate
* @throws java.io.IOException if there is a problem reading the file
*/
public CertificateAuthorityCredential(final Path certificatePath)
throws IOException {
super(certificatePath);
byte[] tempBytes = getX509Certificate()
.getExtensionValue(SUBJECT_KEY_IDENTIFIER_EXTENSION);
if (tempBytes.length > CA_BYTE_SIZE) {
this.subjectKeyIdentifier = truncatePrefixBytes(tempBytes);
} else {
this.subjectKeyIdentifier =
getX509Certificate().getExtensionValue(SUBJECT_KEY_IDENTIFIER_EXTENSION);
}
if (this.subjectKeyIdentifier != null) {
this.subjectKeyIdString = Hex.encodeHexString(this.subjectKeyIdentifier);
}
}
/**
* Default constructor for Hibernate.
*/
protected CertificateAuthorityCredential() {
subjectKeyIdentifier = null;
}
/**
* @return this certificate's subject key identifier.
*/
public byte[] getSubjectKeyIdentifier() {
if (subjectKeyIdentifier != null) {
return subjectKeyIdentifier.clone();
}
return null;
}
private byte[] truncatePrefixBytes(final byte[] certificateBytes) {
byte[] temp = new byte[CA_BYTE_SIZE];
System.arraycopy(certificateBytes, PREFIX_BYTE_SIZE, temp, 0, CA_BYTE_SIZE);
return temp;
}
@Override
@SuppressWarnings("checkstyle:avoidinlineconditionals")
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
CertificateAuthorityCredential that = (CertificateAuthorityCredential) o;
// if (!Objects.equals(credentialType, that.credentialType)) {
// return false;
// }
return Arrays.equals(subjectKeyIdentifier, that.subjectKeyIdentifier);
}
@Override
@SuppressWarnings({"checkstyle:magicnumber", "checkstyle:avoidinlineconditionals"})
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (credentialType != null ? credentialType.hashCode() : 0);
result = 31 * result + Arrays.hashCode(subjectKeyIdentifier);
return result;
}
}

View File

@ -0,0 +1,47 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate;
public class CertificateVariables {
public static final String PEM_HEADER = "-----BEGIN CERTIFICATE-----";
public static final String PEM_FOOTER = "-----END CERTIFICATE-----";
public static final String PEM_ATTRIBUTE_HEADER = "-----BEGIN ATTRIBUTE CERTIFICATE-----";
public static final String PEM_ATTRIBUTE_FOOTER = "-----END ATTRIBUTE CERTIFICATE-----";
public static final String MALFORMED_CERT_MESSAGE = "Malformed certificate detected.";
public static final int MAX_CERT_LENGTH_BYTES = 2048;
public static final int MAX_NUMERIC_PRECISION = 49; // Can store up to 160 bit values
public static final int MAX_PUB_KEY_MODULUS_HEX_LENGTH = 1024;
public static final int KEY_USAGE_BIT0 = 0;
public static final int KEY_USAGE_BIT1 = 1;
public static final int KEY_USAGE_BIT2 = 2;
public static final int KEY_USAGE_BIT3 = 3;
public static final int KEY_USAGE_BIT4 = 4;
public static final int KEY_USAGE_BIT5 = 5;
public static final int KEY_USAGE_BIT6 = 6;
public static final int KEY_USAGE_BIT7 = 7;
public static final int KEY_USAGE_BIT8 = 8;
public static final String KEY_USAGE_DS = "DIGITAL SIGNATURE";
public static final String KEY_USAGE_NR = "NON-REPUDIATION";
public static final String KEY_USAGE_KE = "KEY ENCIPHERMENT";
public static final String KEY_USAGE_DE = "DATA ENCIPHERMENT";
public static final String KEY_USAGE_KA = "KEY AGREEMENT";
public static final String KEY_USAGE_KC = "KEY CERT SIGN";
public static final String KEY_USAGE_CS = "CRL SIGN";
public static final String KEY_USAGE_EO = "ENCIPHER ONLY";
public static final String KEY_USAGE_DO = "DECIPHER ONLY";
public static final String ECDSA_OID = "1.2.840.10045.4.3.2";
public static final String ECDSA_SHA224_OID = "1.2.840.10045.4.1";
public static final String RSA256_OID = "1.2.840.113549.1.1.11";
public static final String RSA384_OID = "1.2.840.113549.1.1.12";
public static final String RSA512_OID = "1.2.840.113549.1.1.13";
public static final String RSA224_OID = "1.2.840.113549.1.1.14";
public static final String RSA512_224_OID = "1.2.840.113549.1.1.15";
public static final String RSA512_256_OID = "1.2.840.113549.1.1.16";
public static final String RSA256_STRING = "SHA256WithRSA";
public static final String RSA384_STRING = "SHA384WithRSA";
public static final String RSA224_STRING = "SHA224WithRSA";
public static final String RSA512_STRING = "SHA512WithRSA";
public static final String RSA512_224_STRING = "SHA512-224WithRSA";
public static final String RSA512_256_STRING = "SHA512-256WithRSA";
public static final String ECDSA_STRING = "SHA256WithECDSA";
public static final String ECDSA_SHA224_STRING = "SHA224WithECDSA";
}

View File

@ -0,0 +1,65 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate;
import hirs.attestationca.persist.entity.userdefined.Certificate;
import jakarta.persistence.Entity;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.io.IOException;
import java.nio.file.Path;
/**
* This class persists Conformance credentials by extending the base Certificate
* class with fields unique to Conformance credentials.
*/
@NoArgsConstructor(access= AccessLevel.PROTECTED)
@Entity
public class ConformanceCredential extends Certificate {
/**
* This class enables the retrieval of ConformanceCredentials by their attributes.
*/
// public static class Selector extends CertificateSelector<ConformanceCredential> {
// /**
// * Construct a new CertificateSelector that will use the given {@link CertificateManager} to
// * retrieve one or many ConformanceCredentials.
// *
// * @param certificateManager the certificate manager to be used to retrieve certificates
// */
// public Selector(final CertificateManager certificateManager) {
// super(certificateManager, ConformanceCredential.class);
// }
// }
/**
* Get a Selector for use in retrieving ConformanceCredentials.
*
* @param certMan the CertificateManager to be used to retrieve persisted certificates
* @return a ConformanceCredential.Selector instance to use for retrieving certificates
*/
// public static Selector select(final CertificateManager certMan) {
// return new Selector(certMan);
// }
/**
* Construct a new ConformanceCredential given its binary contents. The given certificate
* should represent either an X509 certificate or X509 attribute certificate.
*
* @param certificateBytes the contents of a certificate file
* @throws java.io.IOException if there is a problem extracting information from the certificate
*/
public ConformanceCredential(final byte[] certificateBytes) throws IOException {
super(certificateBytes);
}
/**
* Construct a new ConformanceCredential by parsing the file at the given path. The given
* certificate should represent either an X509 certificate or X509 attribute certificate.
*
* @param certificatePath the path on disk to a certificate
* @throws java.io.IOException if there is a problem reading the file
*/
public ConformanceCredential(final Path certificatePath) throws IOException {
super(certificatePath);
}
}

View File

@ -0,0 +1,69 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate;
import hirs.attestationca.persist.entity.userdefined.Certificate;
import hirs.attestationca.persist.entity.userdefined.Device;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.MappedSuperclass;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.io.IOException;
import java.nio.file.Path;
/**
* A Certificate that is associated with a single device.
*
* @see Certificate
*/
@NoArgsConstructor(access= AccessLevel.PACKAGE)
@MappedSuperclass
public abstract class DeviceAssociatedCertificate extends Certificate {
// a device can have multiple certs of this type.
@Getter
@Setter
@ManyToOne
@JoinColumn(name = "device_id")
private Device device;
/**
* Holds the name of the entity 'DEVICE_ID' field.
*/
protected static final String DEVICE_ID_FIELD = "device.id";
/**
* 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.
*
* @param certificatePath the path on disk to a certificate
* @throws java.io.IOException if there is a problem reading the file
*/
DeviceAssociatedCertificate(final Path certificatePath) throws IOException {
super(certificatePath);
}
/**
* Construct a new Certificate given its binary contents. The given certificate should
* represent either an X509 certificate or X509 attribute certificate.
*
* @param certificateBytes the contents of a certificate file
* @throws java.io.IOException if there is a problem extracting information from the certificate
*/
DeviceAssociatedCertificate(final byte[] certificateBytes) throws IOException {
super(certificateBytes);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
if (device != null) {
sb.append(String.format("%nDevice -> %s", getDevice().toString()));
}
return sb.toString();
}
}

View File

@ -0,0 +1,716 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.TPMSecurityAssertions;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.TPMSpecification;
import jakarta.persistence.Column;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.Transient;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bouncycastle.asn1.ASN1ApplicationSpecific;
import org.bouncycastle.asn1.ASN1BitString;
import org.bouncycastle.asn1.ASN1Boolean;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1Enumerated;
import org.bouncycastle.asn1.ASN1GeneralizedTime;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Null;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.ASN1UTCTime;
import org.bouncycastle.asn1.DERBMPString;
import org.bouncycastle.asn1.DERExternal;
import org.bouncycastle.asn1.DERGeneralString;
import org.bouncycastle.asn1.DERIA5String;
import org.bouncycastle.asn1.DERNumericString;
import org.bouncycastle.asn1.DERPrintableString;
import org.bouncycastle.asn1.DERT61String;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.asn1.DERUTF8String;
import org.bouncycastle.asn1.DERUniversalString;
import org.bouncycastle.asn1.DERVisibleString;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Path;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
*
* This class persists Certificate Authority credentials by extending the base Certificate
* class with fields unique to Endorsement credentials, as defined in the Trusted
* Computing Group Credential Profiles, specification v.1.2.
*
* trustedcomputinggroup.org/wp-content/uploads/Credential_Profiles_V1.2_Level2_Revision8.pdf
*/
@EqualsAndHashCode
@NoArgsConstructor(access= AccessLevel.PROTECTED)
@Entity
public class EndorsementCredential extends DeviceAssociatedCertificate {
// Indices for ASN1 OBJ items needed for parsing information
private static final int ASN1_OBJ_ID = 0;
private static final int ASN1_OBJ_PRIMITIVE = 1;
private static final int ASN1_FAMILY_INDEX = 0;
private static final int ASN1_LEVEL_INDEX = 1;
private static final int ASN1_REV_INDEX = 2;
private static final int ASN1_VER_INDEX = 0;
private static final int ASN1_UPGRADEABLE_INDEX = 1;
private static final int EK_LOC_VAL_MIN = 0;
private static final int EK_LOC_VAL_MAX = 2;
private static final int EK_TYPE_VAL_MIN = 0;
private static final int EK_TYPE_VAL_MAX = 3;
// EK Tag index values
private static final int EK_TYPE_TAG = 0;
private static final int EK_LOC_TAG = 1;
private static final int EK_CERT_LOC_TAG = 2;
private static final int ASN1_SEQ_UNKNOWN_SIZE = 2;
private static final int ASN1_SEQ_KNOWN_SIZE = 3;
private static final String TPM_MODEL = "2.23.133.2.2";
private static final String TPM_VERSION = "2.23.133.2.3";
private static final String TPM_MANUFACTURER = "2.23.133.2.1";
private static final String TPM_SPECIFICATION = "2.23.133.2.16";
private static final String TPM_SECURITY_ASSERTIONS = "2.23.133.2.18";
private static final String CREDENTIAL_TYPE_LABEL = "1.3.6.1.5.5.7.2.2";
// number of extra bytes potentially present in a cert header.
private static final int EK_CERT_HEADER_BYTE_COUNT = 7;
private static final Logger LOG = LogManager.getLogger(EndorsementCredential.class);
/**
* This class enables the retrieval of EndorsementCredential by their attributes.
*/
// public static class Selector extends CertificateSelector<EndorsementCredential> {
// /**
// * Construct a new CertificateSelector that will use the given {@link CertificateManager} to
// * retrieve one or many EndorsementCredentials.
// *
// * @param certificateManager the certificate manager to be used to retrieve certificates
// */
// public Selector(final CertificateManager certificateManager) {
// super(certificateManager, EndorsementCredential.class);
// }
//
// /**
// * Specify a manufacturer that certificates must have to be considered as matching.
// * @param manufacturer the manufacturer to query, not empty or null
// * @return this instance (for chaining further calls)
// */
// public Selector byManufacturer(final String manufacturer) {
// setFieldValue(MANUFACTURER_FIELD, manufacturer);
// return this;
// }
//
// /**
// * Specify a model that certificates must have to be considered as matching.
// * @param model the model to query, not empty or null
// * @return this instance (for chaining further calls)
// */
// public Selector byModel(final String model) {
// setFieldValue(MODEL_FIELD, model);
// return this;
// }
//
// /**
// * Specify a version that certificates must have to be considered as matching.
// * @param version the version to query, not empty or null
// * @return this instance (for chaining further calls)
// */
// public Selector byVersion(final String version) {
// setFieldValue(VERSION_FIELD, version);
// return this;
// }
//
// /**
// * Specify a device id that certificates must have to be considered
// * as matching.
// *
// * @param device the device id to query
// * @return this instance (for chaining further calls)
// */
// public Selector byDeviceId(final UUID device) {
// setFieldValue(DEVICE_ID_FIELD, device);
// return this;
// }
// }
//
// /**
// * Get a Selector for use in retrieving EndorsementCredentials.
// *
// * @param certMan the CertificateManager to be used to retrieve persisted certificates
// * @return a EndorsementCredential.Selector instance to use for retrieving certificates
// */
// public static Selector select(final CertificateManager certMan) {
// return new Selector(certMan);
// }
/**
* this field is part of the TCG EC specification, but has not yet been found in
* manufacturer-provided ECs, and is therefore not currently parsed
*/
@Getter
@Column
private String credentialType = "TCPA Trusted Platform Module Endorsement";
private static final String MANUFACTURER_FIELD = "manufacturer";
@Getter
@Column
private String manufacturer = null;
private static final String MODEL_FIELD = "model";
@Getter
@Column
private String model = null;
private static final String VERSION_FIELD = "version";
@Getter
@Column
private String version = null;
@Getter
@Embedded
private TPMSpecification tpmSpecification = null;
@Getter
@Embedded
private TPMSecurityAssertions tpmSecurityAssertions = null; //optional
/*
* this field is part of the TCG EC specification, but has not yet been found in
* manufacturer-provided ECs, and is therefore not currently parsed
*/
@Getter
@Column(nullable = true)
private String policyReference = null; // optional
/*
* this field is part of the TCG EC specification, but has not yet been found in
* manufacturer-provided ECs, and is therefore not currently parsed
*/
@Getter
@Column(nullable = true)
private String revocationLocator = null; // optional
@Transient
private Set<String> expectedOids;
@Transient
private Map<String, Object> parsedFields;
private static final Logger LOGGER = LogManager.getLogger(EndorsementCredential.class);
/**
* Construct a new EndorsementCredential given its binary contents. The given
* certificate should represent either an X509 certificate or X509 attribute certificate.
*
* @param certificateBytes the contents of a certificate file
* @throws java.io.IOException if there is a problem extracting information from the certificate
*/
public EndorsementCredential(final byte[] certificateBytes) throws IOException {
super(certificateBytes);
parseCertificate();
}
/**
* Construct a new EndorsementCredential by parsing the file at the given path. The given
* certificate should represent either an X509 certificate or X509 attribute certificate.
*
* @param certificatePath the path on disk to a certificate
* @throws java.io.IOException if there is a problem reading the file
*/
public EndorsementCredential(final Path certificatePath) throws IOException {
this(readBytes(certificatePath));
}
/**
* Parses the bytes as an EK. If parsing fails initially, the optionally present header
* is removed and tried again. The cert header, if present, contains some certificate length
* information which isn't needed for parsing.
* @param certificateBytes the bytes of the EC
* @return the EC if a valid credential, null otherwise
*/
public static EndorsementCredential parseWithPossibleHeader(final byte[] certificateBytes) {
try {
// first, attempt parsing as is
return new EndorsementCredential(certificateBytes);
} catch (Exception e) {
// attempt parsing again after removing extra header bytes.
if (certificateBytes.length <= EK_CERT_HEADER_BYTE_COUNT) {
throw new IllegalArgumentException("EK parsing failed (only one attempt "
+ "possible", e);
}
}
LOG.debug("Attempting parse after removing extra header bytes");
try {
byte[] truncatedBytes = ArrayUtils.subarray(
certificateBytes, EK_CERT_HEADER_BYTE_COUNT,
certificateBytes.length);
return new EndorsementCredential(truncatedBytes);
} catch (Exception e) {
throw new IllegalArgumentException("Failed to parse EK after multiple attempts", e);
}
}
/**
* Sets up the OID fields for the parser to search for and prepares a
* hashmap field to hold the discovered values. Must be called once before
* an ASN1Primitive can be parsed.
*/
private void prepareParser() {
expectedOids = new HashSet<>();
expectedOids.add(TPM_MODEL);
expectedOids.add(TPM_VERSION);
expectedOids.add(TPM_MANUFACTURER);
expectedOids.add(TPM_SPECIFICATION);
expectedOids.add(TPM_SECURITY_ASSERTIONS);
expectedOids.add(CREDENTIAL_TYPE_LABEL);
parsedFields = new HashMap<>();
}
/**
* Takes the bytes of an X509 certificate and parses them to extract the relevant fields of an
* Endorsement Credential Certificate. This works by making a single pass through all of the
* ASN1Primitives in the certificate and searches for matching OID keys of specific values. If
* matching OID keys are found, their values are encoded in the fields of the current
* EndorsementCredential object.
* @throws java.io.IOException the input certificate bytes were not readable into an X509
* certificate format
*/
private void parseCertificate() throws IOException {
prepareParser();
// although we start with a byte representation, we need to change the encoding to
// make it parseable
ASN1InputStream asn1In = null;
try {
X509Certificate ec = super.getX509Certificate();
asn1In = new ASN1InputStream(ec.getEncoded());
ASN1Primitive obj = asn1In.readObject();
ASN1Sequence seq;
while (obj != null) {
seq = ASN1Sequence.getInstance(obj);
parseSequence(seq, false, null);
obj = asn1In.readObject();
}
} catch (CertificateException e) {
throw new IOException("Couldn't read certificate bytes");
} finally {
if (asn1In != null) {
asn1In.close();
}
}
String oid;
Object value;
// unpack fields from parsedFields and set field values
for (Map.Entry<String, Object> entry : parsedFields.entrySet()) {
oid = entry.getKey();
value = entry.getValue();
if (oid.equals(TPM_MODEL)) {
model = value.toString();
LOGGER.debug("Found TPM Model: " + model);
} else if (oid.equals(TPM_VERSION)) {
version = value.toString();
LOGGER.debug("Found TPM Version: " + version);
} else if (oid.equals(TPM_MANUFACTURER)) {
manufacturer = value.toString();
LOGGER.debug("Found TPM Manufacturer: " + manufacturer);
}
}
}
/**
* Parses the ASN1Sequence type by iteratively unpacking each successive element. If,
* however, the method is set to add the sequence to the OID mapping, it may search for
* patterns that correspond to the TPM Security Assertions and TPM Specification and set
* those fields appropriately.
* @param seq the sequence to parse
* @param addToMapping whether or not to store the sequence value as an OID key/value value
* @param key the associated OID key with this value necessary if addToMapping is true
* @throws java.io.IOException parsing individual subcomponents failed
*/
private void parseSequence(final ASN1Sequence seq, final boolean addToMapping,
final String key) throws IOException {
// need to check if an OID/Value pair
// it is possible these pairs could be in a larger sequence of size != 2
// but it appears that all expected TPM related fields are of size 2.
// The other larger ones are only used for generic X509 fields, which we
// don't need to extract here.
if (seq.size() == ASN1_SEQ_UNKNOWN_SIZE) {
ASN1Encodable obj1 = seq.getObjectAt(ASN1_OBJ_ID);
ASN1Encodable obj2 = seq.getObjectAt(ASN1_OBJ_PRIMITIVE);
if (obj1 instanceof ASN1ObjectIdentifier) {
String oid = ((ASN1ObjectIdentifier) obj1).getId();
if (expectedOids.contains(oid)) {
// parse and put object 2
parseSingle((ASN1Primitive) obj2, true, oid);
} else {
// there may be subfields that are expected, so continue parsing
parseSingle((ASN1Primitive) obj2, false, null);
}
}
// The next two are special sequences that have already been matched with an OID.
} else if (addToMapping && key.equals(TPM_SPECIFICATION)
&& seq.size() == ASN1_SEQ_KNOWN_SIZE) {
// Parse TPM Specification
DERUTF8String family = (DERUTF8String) seq.getObjectAt(ASN1_FAMILY_INDEX);
ASN1Integer level = (ASN1Integer) seq.getObjectAt(ASN1_LEVEL_INDEX);
ASN1Integer revision = (ASN1Integer) seq.getObjectAt(ASN1_REV_INDEX);
tpmSpecification = new TPMSpecification(family.getString(), level.getValue(),
revision.getValue());
LOGGER.debug("Found TPM Spec:" + tpmSpecification.toString());
} else if (addToMapping && key.equals(TPM_SECURITY_ASSERTIONS)) {
// Parse TPM Security Assertions
int seqPosition = 0;
ASN1Integer ver;
// Parse Security Assertions Version
if (seq.getObjectAt(seqPosition) instanceof ASN1Integer) {
ver = (ASN1Integer) seq.getObjectAt(seqPosition);
seqPosition++;
} else {
// Default value of 1 if field not found
ver = new ASN1Integer(BigInteger.ONE);
}
ASN1Boolean fieldUpgradeable;
// Parse Security Assertions Field Upgradeable
if (seq.getObjectAt(seqPosition) instanceof ASN1Boolean) {
fieldUpgradeable = (ASN1Boolean) seq.getObjectAt(seqPosition);
seqPosition++;
} else {
// Default value of false if field not found
fieldUpgradeable = ASN1Boolean.getInstance(false);
}
tpmSecurityAssertions = new TPMSecurityAssertions(ver.getValue(),
fieldUpgradeable.isTrue());
LOGGER.debug("Found TPM Assertions: " + tpmSecurityAssertions.toString());
// Iterate through remaining fields to set optional attributes
int tag;
DERTaggedObject obj;
for (int i = seqPosition; i < seq.size(); i++) {
if (seq.getObjectAt(i) instanceof DERTaggedObject) {
obj = (DERTaggedObject) seq.getObjectAt(i);
tag = obj.getTagNo();
if (tag == EK_TYPE_TAG) {
int ekGenTypeVal = ((ASN1Enumerated) obj.getObject()).getValue().intValue();
if (ekGenTypeVal >= EK_TYPE_VAL_MIN && ekGenTypeVal <= EK_TYPE_VAL_MAX) {
TPMSecurityAssertions.EkGenerationType ekGenType
= TPMSecurityAssertions.EkGenerationType.values()[ekGenTypeVal];
tpmSecurityAssertions.setEkGenType(ekGenType);
}
} else if (tag == EK_LOC_TAG) {
int ekGenLocVal = ((ASN1Enumerated) obj.getObject()).getValue().intValue();
if (ekGenLocVal >= EK_LOC_VAL_MIN && ekGenLocVal <= EK_LOC_VAL_MAX) {
TPMSecurityAssertions.EkGenerationLocation ekGenLocation
= TPMSecurityAssertions.EkGenerationLocation.values()[ekGenLocVal];
tpmSecurityAssertions.setEkGenerationLocation(ekGenLocation);
}
} else if (tag == EK_CERT_LOC_TAG) {
int ekCertGenLocVal = ((ASN1Enumerated) obj.getObject())
.getValue().intValue();
if (ekCertGenLocVal >= EK_LOC_VAL_MIN
&& ekCertGenLocVal <= EK_LOC_VAL_MAX) {
TPMSecurityAssertions.EkGenerationLocation ekCertGenLoc
= TPMSecurityAssertions.EkGenerationLocation.
values()[ekCertGenLocVal];
tpmSecurityAssertions.setEkGenerationLocation(ekCertGenLoc);
}
}
// ccInfo, fipsLevel, iso9000Certified, and iso9000Uri still to be implemented
}
// Will need additional else if case in the future for instanceof ASN1Boolean when
// supporting TPMSecurityAssertions iso9000Certified field, which could be either
// DERTaggedObject or ASN1Boolean
}
} else {
//parse the elements of the sequence individually
for (ASN1Encodable component : seq) {
parseSingle((ASN1Primitive) component, false, null);
}
}
}
/**
* Parses the many different types of ASN1Primitives and searches for specific OID
* key/value pairs. Works by traversing the entire ASN1Primitive tree with a single
* pass and populates relevant fields in the EndorsementCredential object.
* @param component the ASN1Primitive to parse
* @param addToMapping whether or not the current component has been matched as the
* value in an expected TPM OID key/value pair
* @param key if addToMapping is true, the key in the OID key/value pair
* @throws java.io.IOException parsing of subcomponents in the tree failed.
*/
@SuppressWarnings("checkstyle:methodlength")
private void parseSingle(final ASN1Primitive component, final boolean addToMapping,
final String key) throws IOException {
// null check the key if addToMapping is true
if (addToMapping && StringUtils.isEmpty(key)) {
throw new IllegalArgumentException("Key cannot be empty if adding to field mapping");
}
if (component instanceof ASN1Sequence) {
parseSequence((ASN1Sequence) component, addToMapping, key);
} else if (component instanceof DERUTF8String) {
if (addToMapping) {
DERUTF8String nameData = (DERUTF8String) component;
parsedFields.put(key, nameData.getString());
}
} else if (component instanceof ASN1ObjectIdentifier) {
if (addToMapping) {
// shouldn't ever be reached, but just in case
parsedFields.put(key, ((ASN1ObjectIdentifier) component).getId());
}
} else if (component instanceof ASN1TaggedObject) {
ASN1TaggedObject taggedObj = (ASN1TaggedObject) component;
parseSingle(taggedObj.getObject(), addToMapping, key);
} else if (component instanceof ASN1OctetString) {
// this may contain parseable data or may just be a OID key-pair value
ASN1OctetString octStr = (ASN1OctetString) component;
byte[] bytes = octStr.getOctets();
ByteArrayInputStream inStream = new ByteArrayInputStream(bytes);
ASN1InputStream octIn = new ASN1InputStream(inStream);
try {
ASN1Encodable newComp = octIn.readObject();
parseSingle((ASN1Primitive) newComp, false, null);
} catch (IOException e) {
// this means octet string didn't contain parsable data, so store the
// value as is
if (addToMapping) {
parsedFields.put(key, bytes);
}
} finally {
if (octIn != null) {
octIn.close();
}
}
} else if (component instanceof ASN1Set) {
// all ECs seen to this point use sets differently than sequences and their sets
// don't contain top level OIDs, so we can parse everything term by term, if that
// ceases to be the case, we need to switch to this parsing to be more like
// parseSequences in the future
ASN1Set set = (ASN1Set) component;
Enumeration setContents = set.getObjects();
ASN1Encodable subComp;
while (setContents.hasMoreElements()) {
subComp = (ASN1Encodable) setContents.nextElement();
if (subComp instanceof ASN1ObjectIdentifier) {
LOGGER.warn("OID in top level of ASN1Set");
}
parseSingle((ASN1Primitive) subComp, addToMapping, key);
}
} else if (component instanceof ASN1Boolean) {
if (addToMapping) {
boolean fieldVal = ((ASN1Boolean) component).isTrue();
parsedFields.put(key, fieldVal);
}
} else if (component instanceof ASN1BitString) {
// I don't think this contains more fields and needs to be reparsed,
// though not 100% sure
if (addToMapping) {
byte[] bytes = ((ASN1BitString) component).getBytes();
parsedFields.put(key, bytes);
}
} else if (component instanceof ASN1Integer) {
if (addToMapping) {
BigInteger bigInt = ((ASN1Integer) component).getValue();
parsedFields.put(key, bigInt);
}
} else if (component instanceof ASN1Null) {
if (addToMapping) {
parsedFields.put(key, null);
}
} else if (component instanceof ASN1UTCTime) {
if (addToMapping) {
try {
parsedFields.put(key, ((ASN1UTCTime) component).getDate());
} catch (ParseException pe) {
pe.printStackTrace();
}
}
} else if (component instanceof DERPrintableString) {
if (addToMapping) {
parsedFields.put(key, ((DERPrintableString) component).getString());
}
} else if (component instanceof ASN1Enumerated) {
if (addToMapping) {
BigInteger value = ((ASN1Enumerated) component).getValue();
parsedFields.put(key, value);
}
// after about this point, I doubt we'll see any of the following field types, but
// in the interest of completeness and robustness, they are still parsed
} else if (component instanceof DERIA5String) {
if (addToMapping) {
String ia5Str = ((DERIA5String) component).getString();
parsedFields.put(key, ia5Str);
}
} else if (component instanceof DERNumericString) {
if (addToMapping) {
String numStr = ((DERNumericString) component).getString();
parsedFields.put(key, numStr);
}
} else if (component instanceof ASN1GeneralizedTime) {
if (addToMapping) {
try {
parsedFields.put(key, ((ASN1GeneralizedTime) component).getDate());
} catch (ParseException e) {
e.printStackTrace();
}
}
} else if (component instanceof ASN1ApplicationSpecific) {
parseSingle(((ASN1ApplicationSpecific) component).getObject(), addToMapping, key);
} else if (component instanceof DERBMPString) {
if (addToMapping) {
String bmpStr = ((DERBMPString) component).getString();
parsedFields.put(key, bmpStr);
}
} else if (component instanceof DERExternal) {
parseSingle(((DERExternal) component).getExternalContent(), addToMapping, key);
} else if (component instanceof DERGeneralString) {
if (addToMapping) {
String generalStr = ((DERGeneralString) component).getString();
parsedFields.put(key, generalStr);
}
} else if (component instanceof DERT61String) {
if (addToMapping) {
String t61Str = ((DERT61String) component).getString();
parsedFields.put(key, t61Str);
}
} else if (component instanceof DERUniversalString) {
if (addToMapping) {
String univStr = ((DERUniversalString) component).getString();
parsedFields.put(key, univStr);
}
} else if (component instanceof DERVisibleString) {
if (addToMapping) {
String visStr = ((DERVisibleString) component).getString();
parsedFields.put(key, visStr);
}
} else {
// there are some deprecated types that we don't parse
LOGGER.error("Unparsed type: " + component.getClass());
}
}
/**
* Get the credential type label.
* @return the credential type label.
*/
public String getCredentialType() {
return credentialType;
}
/**
* Get the TPM Manufacturer.
* @return the TPM Manufacturer.
*/
public String getManufacturer() {
return manufacturer;
}
/**
* Get the TPM model.
* @return the TPM model.
*/
public String getModel() {
return model;
}
/**
* Get the TPM version.
* @return the TPM version.
*/
public String getVersion() {
return version;
}
/**
* Get the TPM specification.
* @return the TPM specification.
*/
public TPMSpecification getTpmSpecification() {
return tpmSpecification;
}
/**
* Get the TPM security assertions.
* @return the TPM security assertions.
*/
public TPMSecurityAssertions getTpmSecurityAssertions() {
return tpmSecurityAssertions;
}
/**
* Get the policy reference.
* @return the policy reference.
*/
public String getPolicyReference() {
return policyReference;
}
/**
* Get the revocation locator.
* @return the revocation locator.
*/
public String getRevocationLocator() {
return revocationLocator;
}
}

View File

@ -0,0 +1,105 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.ManyToOne;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Set;
/**
* Represents an issued attestation certificate to a HIRS Client.
*/
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
@Entity
public class IssuedAttestationCertificate extends DeviceAssociatedCertificate {
/**
* AIC label that must be used.
*/
public static final String AIC_TYPE_LABEL = "TCPA Trusted Platform Identity";
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "ek_id")
private EndorsementCredential endorsementCredential;
@ManyToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "pc_id")
private Set<PlatformCredential> platformCredentials;
/**
* This class enables the retrieval of IssuedAttestationCertificate by their attributes.
*/
// public static class Selector extends CertificateSelector<IssuedAttestationCertificate> {
// /**
// * Construct a new CertificateSelector that will use the given {@link CertificateManager} to
// * retrieve one or many IssuedAttestationCertificate.
// *
// * @param certificateManager the certificate manager to be used to retrieve certificates
// */
// public Selector(final CertificateManager certificateManager) {
// super(certificateManager, IssuedAttestationCertificate.class);
// }
//
// /**
// * Specify a device id that certificates must have to be considered
// * as matching.
// *
// * @param device the device id to query
// * @return this instance (for chaining further calls)
// */
// public Selector byDeviceId(final UUID device) {
// setFieldValue(DEVICE_ID_FIELD, device);
// return this;
// }
// }
//
// /**
// * Get a Selector for use in retrieving IssuedAttestationCertificate.
// *
// * @param certMan the CertificateManager to be used to retrieve persisted certificates
// * @return a IssuedAttestationCertificate.Selector instance to use for retrieving certificates
// */
// public static IssuedAttestationCertificate.Selector select(final CertificateManager certMan) {
// return new IssuedAttestationCertificate.Selector(certMan);
// }
/**
* Constructor.
* @param certificateBytes the issued certificate bytes
* @param endorsementCredential the endorsement credential
* @param platformCredentials the platform credentials
* @throws java.io.IOException if there is a problem extracting information from the certificate
*/
public IssuedAttestationCertificate(final byte[] certificateBytes,
final EndorsementCredential endorsementCredential,
final Set<PlatformCredential> platformCredentials)
throws IOException {
super(certificateBytes);
this.endorsementCredential = endorsementCredential;
this.platformCredentials = platformCredentials;
}
/**
* Constructor.
* @param certificatePath path to certificate
* @param endorsementCredential the endorsement credential
* @param platformCredentials the platform credentials
* @throws java.io.IOException if there is a problem extracting information from the certificate
*/
public IssuedAttestationCertificate(final Path certificatePath,
final EndorsementCredential endorsementCredential,
final Set<PlatformCredential> platformCredentials)
throws IOException {
this(readBytes(certificatePath), endorsementCredential, platformCredentials);
}
}

View File

@ -0,0 +1,796 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate;
import com.google.common.base.Preconditions;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentIdentifier;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.PlatformConfiguration;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.PlatformConfigurationV1;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.TBBSecurityAssertion;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.URIReference;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.V2.PlatformConfigurationV2;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Transient;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.util.Strings;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERIA5String;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.x500.AttributeTypeAndValue;
import org.bouncycastle.asn1.x500.RDN;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.Attribute;
import org.bouncycastle.asn1.x509.AttributeCertificate;
import org.bouncycastle.asn1.x509.AttributeCertificateInfo;
import org.bouncycastle.asn1.x509.CertificatePolicies;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.PolicyInformation;
import org.bouncycastle.asn1.x509.PolicyQualifierInfo;
import org.bouncycastle.asn1.x509.UserNotice;
import org.bouncycastle.operator.ContentVerifier;
import org.bouncycastle.operator.ContentVerifierProvider;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class persists Platform credentials by extending the base Certificate
* class with fields unique to a Platform credentials, as defined in the Trusted
* Computing Group Credential Profiles, specification v.1.2.
*/
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
public class PlatformCredential extends DeviceAssociatedCertificate {
private static final Logger LOGGER = LogManager.getLogger(PlatformCredential.class);
private static final int TCG_SPECIFICATION_LENGTH = 3;
// These are Object Identifiers (OIDs) for sections in the credentials
private static final String POLICY_QUALIFIER_CPSURI = "1.3.6.1.5.5.7.2.1";
private static final String POLICY_QUALIFIER_USER_NOTICE = "1.3.6.1.5.5.7.2.2";
// OID for TCG Attributes
private static final String PLATFORM_MANUFACTURER = "2.23.133.2.4";
private static final String PLATFORM_MODEL = "2.23.133.2.5";
private static final String PLATFORM_VERSION = "2.23.133.2.6";
private static final String PLATFORM_SERIAL = "2.23.133.2.23";
private static final String PLATFORM_BASEBOARD_CHASSIS_COMBINED = "2.23.133.5.1.6";
// OID for TCG Platform Class Common Attributes
private static final String PLATFORM_MANUFACTURER_2_0 = "2.23.133.5.1.1";
private static final String PLATFORM_MODEL_2_0 = "2.23.133.5.1.4";
private static final String PLATFORM_VERSION_2_0 = "2.23.133.5.1.5";
private static final String PLATFORM_SERIAL_2_0 = "2.23.133.5.1.6";
// OID for Certificate Attributes
private static final String TCG_PLATFORM_SPECIFICATION = "2.23.133.2.17";
private static final String TPM_SECURITY_ASSERTION = "2.23.133.2.18";
private static final String TBB_SECURITY_ASSERTION = "2.23.133.2.19";
private static final String TCG_CREDENTIAL_SPECIFICATION = "2.23.133.2.23";
private static final String PLATFORM_CONFIGURATION_URI = "2.23.133.5.1.3";
private static final String PLATFORM_CONFIGURATION = "2.23.133.5.1.7.1";
private static final String PLATFORM_CONFIGURATION_V2 = "2.23.133.5.1.7.2";
private static final String PLATFORM_CREDENTIAL_TYPE = "2.23.133.2.25";
private static final String PLATFORM_BASE_CERT = "2.23.133.8.2";
private static final String PLATFORM_DELTA_CERT = "2.23.133.8.5";
/**
* TCG Platform Specification values
* At this time these are placeholder values.
*/
private static final Map<String, String> TCG_PLATFORM_MAP = new HashMap<String, String>() {{
put("#00000000", "Unclassified");
put("#00000001", "PC Client");
put("#00000002", "PDA");
put("#00000003", "CELLPHONE");
put("#00000004", "SERVER");
put("#00000005", "PERIPHERAL");
put("#00000006", "TSS");
put("#00000007", "STORAGE");
put("#00000008", "AUTHENTICATION");
put("#00000009", "EMBEDDED");
put("#00000010", "HARD COPY");
put("#00000011", "INFRASTRUCTURE");
put("#00000012", "VIRTUALIZATION");
put("#00000013", "TNC");
put("#00000014", "MULTI-TENANT");
}};
// number of extra bytes potentially present in a cert header.
private static final int PC_CERT_HEADER_BYTE_COUNT = 8;
/**
* TCPA Trusted Platform Endorsement.
*/
public static final String CERTIFICATE_TYPE_1_2 = "TCPA Trusted Platform Endorsement";
/**
* TCG Trusted Platform Endorsement.
*/
public static final String CERTIFICATE_TYPE_2_0 = "TCG Trusted Platform Endorsement";
/**
* This class enables the retrieval of PlatformCredentials by their attributes.
*/
// public static class Selector extends CertificateSelector<PlatformCredential> {
// /**
// * Construct a new CertificateSelector that will use the given {@link CertificateManager} to
// * retrieve one or many PlatformCredentials.
// *
// * @param certificateManager the certificate manager to be used to retrieve certificates
// */
// public Selector(final CertificateManager certificateManager) {
// super(certificateManager, PlatformCredential.class);
// }
//
// /**
// * Specify a manufacturer that certificates must have to be considered as matching.
// * @param manufacturer the manufacturer to query, not empty or null
// * @return this instance (for chaining further calls)
// */
// public Selector byManufacturer(final String manufacturer) {
// setFieldValue(MANUFACTURER_FIELD, manufacturer);
// return this;
// }
//
// /**
// * Specify a model that certificates must have to be considered as matching.
// * @param model the model to query, not empty or null
// * @return this instance (for chaining further calls)
// */
// public Selector byModel(final String model) {
// setFieldValue(MODEL_FIELD, model);
// return this;
// }
//
// /**
// * Specify a version that certificates must have to be considered as matching.
// * @param version the version to query, not empty or null
// * @return this instance (for chaining further calls)
// */
// public Selector byVersion(final String version) {
// setFieldValue(VERSION_FIELD, version);
// return this;
// }
//
// /**
// * Specify a serial number that certificates must have to be considered as matching.
// * @param serialNumber the serial number to query, not empty or null
// * @return this instance (for chaining further calls)
// */
// public Selector bySerialNumber(final String serialNumber) {
// setFieldValue(SERIAL_NUMBER_FIELD, serialNumber);
// return this;
// }
//
// /**
// * Specify a board serial number that certificates must have to be considered as matching.
// * @param boardSerialNumber the board serial number to query, not empty or null
// * @return this instance (for chaining further calls)
// */
// public Selector byBoardSerialNumber(final String boardSerialNumber) {
// setFieldValue(PLATFORM_SERIAL_FIELD, boardSerialNumber);
// return this;
// }
//
// /**
// * Specify a chassis serial number that certificates must have to be considered as matching.
// * @param chassisSerialNumber the board serial number to query, not empty or null
// * @return this instance (for chaining further calls)
// */
// public Selector byChassisSerialNumber(final String chassisSerialNumber) {
// setFieldValue(CHASSIS_SERIAL_NUMBER_FIELD, chassisSerialNumber);
// return this;
// }
//
// /**
// * Specify a device id that certificates must have to be considered
// * as matching.
// *
// * @param device the device id to query
// * @return this instance (for chaining further calls)
// */
// public Selector byDeviceId(final UUID device) {
// setFieldValue(DEVICE_ID_FIELD, device);
// return this;
// }
// }
@Column
private String credentialType = null;
@Column
private boolean platformBase = false;
private static final String MANUFACTURER_FIELD = "manufacturer";
@Column
private String manufacturer = null;
private static final String MODEL_FIELD = "model";
@Column
private String model = null;
private static final String VERSION_FIELD = "version";
@Column
private String version = null;
private static final String PLATFORM_SERIAL_FIELD = "platformSerial";
@Column
private String platformSerial = null;
private static final String CHASSIS_SERIAL_NUMBER_FIELD = "chassisSerialNumber";
@Column
private String chassisSerialNumber;
@Column
private int majorVersion = 0;
@Column
private int minorVersion = 0;
@Column
private int revisionLevel = 0;
@Column
private int tcgCredentialMajorVersion = 0;
@Column
private int tcgCredentialMinorVersion = 0;
@Column
private int tcgCredentialRevisionLevel = 0;
@Column
private String platformClass = null;
@Column(length = MAX_MESSAGE_LENGTH)
private String componentFailures = Strings.EMPTY;
@Transient
private EndorsementCredential endorsementCredential = null;
private String platformChainType = Strings.EMPTY;
private boolean isDeltaChain = false;
/**
* Get a Selector for use in retrieving PlatformCredentials.
*
* @param certMan the CertificateManager to be used to retrieve persisted certificates
* @return a PlatformCredential.Selector instance to use for retrieving certificates
*/
// public static Selector select(final CertificateManager certMan) {
// return new Selector(certMan);
// }
/**
* Construct a new PlatformCredential given its binary contents. ParseFields is
* optionally run. The given certificate should represent either an X509 certificate
* or X509 attribute certificate.
*
* @param certificateBytes the contents of a certificate file
* @param parseFields boolean True to parse fields
* @throws java.io.IOException if there is a problem extracting information from the certificate\
*/
public PlatformCredential(final byte[] certificateBytes,
final boolean parseFields) throws IOException {
super(certificateBytes);
if (parseFields) {
parseFields();
}
}
/**
* Construct a new PlatformCredential given its binary contents. The given
* certificate should represent either an X509 certificate or X509 attribute certificate.
*
* @param certificateBytes the contents of a certificate file
* @throws java.io.IOException if there is a problem extracting information from the certificate
*/
public PlatformCredential(final byte[] certificateBytes) throws IOException {
this(certificateBytes, true);
}
/**
* Construct a new PlatformCredential by parsing the file at the given path. The given
* certificate should represent either an X509 certificate or X509 attribute certificate.
*
* @param certificatePath the path on disk to a certificate
* @throws java.io.IOException if there is a problem reading the file
*/
public PlatformCredential(final Path certificatePath) throws IOException {
this(readBytes(certificatePath), true);
}
/**
* Validate the signature on the attribute certificate in this holder.
*
* @param verifierProvider a ContentVerifierProvider that can generate a
* verifier for the signature.
* @return true if the signature is valid, false otherwise.
* @throws java.io.IOException if the signature cannot be processed or is inappropriate.
*/
public boolean isSignatureValid(final ContentVerifierProvider verifierProvider)
throws IOException {
AttributeCertificate attCert = getAttributeCertificate();
AttributeCertificateInfo acinfo = getAttributeCertificate().getAcinfo();
// Check if the algorithm identifier is the same
if (!isAlgIdEqual(acinfo.getSignature(), attCert.getSignatureAlgorithm())) {
throw new IOException("signature invalid - algorithm identifier mismatch");
}
ContentVerifier verifier;
try {
// Set ContentVerifier with the signature that will verify
verifier = verifierProvider.get((acinfo.getSignature()));
} catch (Exception e) {
throw new IOException("unable to process signature: " + e.getMessage(), e);
}
return verifier.verify(attCert.getSignatureValue().getOctets());
}
/**
* Parses the bytes as an PC. If parsing fails initially, the optionally present header
* is removed and tried again. The cert header, if present, contains some certificate length
* information which isn't needed for parsing.
* @param certificateBytes the bytes of the PC
* @return the PC if a valid credential, null otherwise
*/
public static PlatformCredential parseWithPossibleHeader(final byte[] certificateBytes) {
PlatformCredential credential = null;
try {
// first, attempt parsing as is
credential = new PlatformCredential(certificateBytes);
} catch (Exception e) {
// attempt parsing again after removing extra header bytes.
if (certificateBytes.length > PC_CERT_HEADER_BYTE_COUNT) {
LOGGER.debug("Attempting parse after removing extra header bytes");
try {
byte[] truncatedBytes = ArrayUtils.subarray(
certificateBytes, PC_CERT_HEADER_BYTE_COUNT,
certificateBytes.length);
credential = new PlatformCredential(truncatedBytes);
} catch (Exception e1) {
LOGGER.warn("Failed to parse PC after multiple attempts", e1);
}
} else {
LOGGER.warn("EK parsing failed (only one attempt possible)", e);
}
}
return credential;
}
private void parseFields() throws IOException {
AttributeCertificateInfo certificate = getAttributeCertificate().getAcinfo();
Map<String, String> policyQualifier = getPolicyQualifier(certificate);
credentialType = policyQualifier.get("userNotice");
// Parse data based on certificate type (1.2 vs 2.0)
switch (credentialType) {
case CERTIFICATE_TYPE_1_2:
parseAttributeCert(certificate);
break;
case CERTIFICATE_TYPE_2_0:
parseAttributeCert2(certificate);
break;
default:
throw new IOException("Invalid Attribute Credential Type: " + credentialType);
}
// Get TCG Platform Specification Information
for (ASN1Encodable enc : certificate.getAttributes().toArray()) {
Attribute attr = Attribute.getInstance(enc);
if (attr.getAttrType().toString().equals(TCG_PLATFORM_SPECIFICATION)) {
ASN1Sequence tcgPlatformSpecification
= ASN1Sequence.getInstance(attr.getAttrValues().getObjectAt(0));
ASN1Sequence tcgSpecificationVersion
= ASN1Sequence.getInstance(tcgPlatformSpecification.getObjectAt(0));
this.majorVersion = Integer.parseInt(
tcgSpecificationVersion.getObjectAt(0).toString());
this.minorVersion = Integer.parseInt(
tcgSpecificationVersion.getObjectAt(1).toString());
this.revisionLevel = Integer.parseInt(
tcgSpecificationVersion.getObjectAt(2).toString());
this.platformClass = tcgPlatformSpecification.getObjectAt(1).toString();
} else if (attr.getAttrType().toString().equals(PLATFORM_CREDENTIAL_TYPE)) {
ASN1Sequence tcgPlatformType = ASN1Sequence.getInstance(
attr.getAttrValues().getObjectAt(0));
ASN1ObjectIdentifier platformOid = ASN1ObjectIdentifier.getInstance(
tcgPlatformType.getObjectAt(0));
if (platformOid.getId().equals(PLATFORM_BASE_CERT)) {
this.platformBase = true;
this.platformChainType = "Base";
this.isDeltaChain = true;
} else if (platformOid.getId().equals(PLATFORM_DELTA_CERT)) {
this.platformBase = false;
this.platformChainType = "Delta";
this.isDeltaChain = true;
}
}
}
}
/**
* Parse a 1.2 Platform Certificate (Attribute Certificate).
* @param certificate Attribute Certificate
*/
private void parseAttributeCert(final AttributeCertificateInfo certificate) {
Extension subjectAlternativeNameExtension
= certificate.getExtensions().getExtension(Extension.subjectAlternativeName);
// It contains a Subject Alternative Name Extension
if (subjectAlternativeNameExtension != null) {
GeneralNames gnames = GeneralNames.getInstance(
subjectAlternativeNameExtension.getParsedValue());
for (GeneralName gname : gnames.getNames()) {
// Check if it's a directoryName [4] Name type
if (gname.getTagNo() == GeneralName.directoryName) {
X500Name name = X500Name.getInstance(gname.getName());
for (RDN rdn: name.getRDNs()) {
for (AttributeTypeAndValue attTV: rdn.getTypesAndValues()) {
switch (attTV.getType().toString()) {
case PLATFORM_MANUFACTURER:
this.manufacturer = attTV.getValue().toString();
break;
case PLATFORM_MODEL:
this.model = attTV.getValue().toString();
break;
case PLATFORM_VERSION:
this.version = attTV.getValue().toString();
break;
case PLATFORM_SERIAL:
this.platformSerial = attTV.getValue().toString();
break;
case PLATFORM_BASEBOARD_CHASSIS_COMBINED:
String[] combinedValues = attTV.getValue()
.toString()
.split(",");
if (combinedValues.length != 2) {
LOGGER.warn("Unable to parse combined "
+ "baseboard/chassis SN field");
} else {
this.chassisSerialNumber = combinedValues[0];
this.platformSerial = combinedValues[1];
}
break;
default:
break;
}
}
}
}
}
}
}
/**
* Parse a 2.0 Platform Certificate (Attribute Certificate).
* @param certificate Attribute Certificate
*/
private void parseAttributeCert2(final AttributeCertificateInfo certificate)
throws IOException {
Extension subjectAlternativeNameExtension
= certificate.getExtensions().getExtension(Extension.subjectAlternativeName);
// It contains a Subject Alternative Name Extension
if (subjectAlternativeNameExtension != null) {
GeneralNames gnames = GeneralNames.getInstance(
subjectAlternativeNameExtension.getParsedValue());
for (GeneralName gname : gnames.getNames()) {
// Check if it's a directoryName [4] Name type
if (gname.getTagNo() == GeneralName.directoryName) {
X500Name name = X500Name.getInstance(gname.getName());
for (RDN rdn: name.getRDNs()) {
for (AttributeTypeAndValue attTV: rdn.getTypesAndValues()) {
switch (attTV.getType().toString()) {
case PLATFORM_MANUFACTURER_2_0:
this.manufacturer = attTV.getValue().toString();
break;
case PLATFORM_MODEL_2_0:
this.model = attTV.getValue().toString();
break;
case PLATFORM_VERSION_2_0:
this.version = attTV.getValue().toString();
break;
case PLATFORM_SERIAL_2_0:
this.platformSerial = attTV.getValue().toString();
break;
default:
break;
}
}
}
}
}
}
// Get all the attributes map to check for validity
try {
getAllAttributes();
} catch (IllegalArgumentException ex) {
throw new IOException(ex.getMessage());
}
}
/**
* Get the x509 Platform Certificate version.
* @return a big integer representing the certificate version.
*/
@Override
public int getX509CredentialVersion() {
try {
return getAttributeCertificate()
.getAcinfo()
.getVersion()
.getValue().intValue();
} catch (IOException ex) {
LOGGER.warn("X509 Credential Version not found.");
LOGGER.error(ex);
return Integer.MAX_VALUE;
}
}
/**
* Get the cPSuri from the Certificate Policies.
* @return cPSuri from the CertificatePolicies.
* @throws java.io.IOException when reading the certificate.
*/
public String getCPSuri() throws IOException {
Map<String, String> policyQualifier
= getPolicyQualifier(getAttributeCertificate().getAcinfo());
if (policyQualifier.get("cpsURI") != null && !policyQualifier.get("cpsURI").isEmpty()) {
return policyQualifier.get("cpsURI");
}
return null;
}
/**
* Get the Platform Configuration Attribute from the Platform Certificate.
* @return a map with all the attributes
* @throws IllegalArgumentException when there is a parsing error
* @throws java.io.IOException when reading the certificate.
*/
public Map<String, Object> getAllAttributes()
throws IllegalArgumentException, IOException {
Map<String, Object> attributes = new HashMap<>();
ASN1Sequence attributeSequence;
// Check all attributes for Platform Configuration
for (ASN1Encodable enc: getAttributeCertificate().getAcinfo().getAttributes().toArray()) {
Attribute attr = Attribute.getInstance(enc);
attributeSequence
= ASN1Sequence.getInstance(attr.getAttrValues().getObjectAt(0));
// Parse sequence based on the attribute OID
switch (attr.getAttrType().getId()) {
case TBB_SECURITY_ASSERTION:
attributes.put("tbbSecurityAssertion",
new TBBSecurityAssertion(attributeSequence));
break;
case PLATFORM_CONFIGURATION_URI:
attributes.put("platformConfigurationURI",
new URIReference(attributeSequence));
break;
case PLATFORM_CONFIGURATION:
attributes.put("platformConfiguration",
new PlatformConfigurationV1(attributeSequence));
break;
case PLATFORM_CONFIGURATION_V2:
attributes.put("platformConfiguration",
new PlatformConfigurationV2(attributeSequence));
break;
case TCG_PLATFORM_SPECIFICATION:
case PLATFORM_CREDENTIAL_TYPE:
// handled in parseFields
break;
case TCG_CREDENTIAL_SPECIFICATION:
getTCGCredentialSpecification(attributeSequence);
break;
default:
// No class defined for this attribute
LOGGER.warn("No class defined for attribute with OID: "
+ attr.getAttrType().getId());
break;
}
}
return attributes;
}
/**
* Get the specified attribute from the Platform Certificate.
* @param attributeName to retrieve from the map.
* @return an Object with the attribute.
* @throws IllegalArgumentException when there is a parsing error
* @throws java.io.IOException when reading the certificate.
*/
public Object getAttribute(final String attributeName)
throws IllegalArgumentException, IOException {
return getAllAttributes().get(attributeName);
}
/**
* Get the Platform Configuration Attribute from the Platform Certificate.
* @return a map with the Platform Configuration information.
* @throws IllegalArgumentException when there is a parsing error
* @throws java.io.IOException when reading the certificate.
*/
public PlatformConfiguration getPlatformConfiguration()
throws IllegalArgumentException, IOException {
if (getAttribute("platformConfiguration") != null
&& getAttribute("platformConfiguration") instanceof PlatformConfiguration) {
return (PlatformConfiguration) getAttribute("platformConfiguration");
}
return null;
}
/**
* Get the Platform Configuration URI Attribute from the Platform Certificate.
* @return an URIReference object to the Platform Configuration URI.
* @throws IllegalArgumentException when there is a parsing error
* @throws java.io.IOException when reading the certificate.
*/
public URIReference getPlatformConfigurationURI()
throws IllegalArgumentException, IOException {
if (getAttribute("platformConfigurationURI") != null
&& getAttribute("platformConfigurationURI") instanceof URIReference) {
return (URIReference) getAttribute("platformConfigurationURI");
}
return null;
}
/**
* Get the TBB Security Assertion from the Platform Certificate.
* @return a TBBSecurityAssertion object.
* @throws IllegalArgumentException when there is a parsing error
* @throws java.io.IOException when reading the certificate.
*/
public TBBSecurityAssertion getTBBSecurityAssertion()
throws IllegalArgumentException, IOException {
if (getAttribute("tbbSecurityAssertion") != null
&& getAttribute("tbbSecurityAssertion") instanceof TBBSecurityAssertion) {
return (TBBSecurityAssertion) getAttribute("tbbSecurityAssertion");
}
return null;
}
/**
* This method sets the TCG Credential fields from a certificate, if provided.
*
* @param attributeSequence The sequence associated with 2.23.133.2.23
*/
private void getTCGCredentialSpecification(final ASN1Sequence attributeSequence) {
try {
this.tcgCredentialMajorVersion = Integer.parseInt(
attributeSequence.getObjectAt(0).toString());
this.tcgCredentialMinorVersion = Integer.parseInt(
attributeSequence.getObjectAt(1).toString());
this.tcgCredentialRevisionLevel = Integer.parseInt(
attributeSequence.getObjectAt(2).toString());
} catch (NumberFormatException nfEx) {
// ill-formed ASN1
String fieldContents = attributeSequence.toString();
if (fieldContents != null && fieldContents.contains(",")) {
fieldContents = fieldContents.replaceAll("[^a-zA-Z0-9,]", "");
String[] fields = fieldContents.split(",");
if (fields.length == TCG_SPECIFICATION_LENGTH) {
this.tcgCredentialMajorVersion = Integer.parseInt(fields[0]);
this.tcgCredentialMinorVersion = Integer.parseInt(fields[1]);
this.tcgCredentialRevisionLevel = Integer.parseInt(fields[2]);
}
}
}
}
/**
* Get the list of component identifiers if there are any.
* @return the list of component identifiers if there are any
*/
public List<ComponentIdentifier> getComponentIdentifiers() {
try {
PlatformConfiguration platformConfig = getPlatformConfiguration();
if (platformConfig != null) {
return platformConfig.getComponentIdentifier();
}
} catch (IOException e) {
LOGGER.error("Unable to parse Platform Configuration from Credential or find"
+ "component identifiers");
}
return Collections.emptyList();
}
/**
* Verify if the AlgorithmIdentifiers are equal.
*
* @param id1 AlgorithIdentifier one
* @param id2 AlgorithIdentifier two
* @return True if are the same, False if not
*/
public static boolean isAlgIdEqual(final AlgorithmIdentifier id1,
final AlgorithmIdentifier id2) {
if (!id1.getAlgorithm().equals(id2.getAlgorithm())) {
return false;
}
if (id1.getParameters() == null) {
if (id2.getParameters() != null && !id2.getParameters().equals(DERNull.INSTANCE)) {
return false;
}
return true;
}
if (id2.getParameters() == null) {
if (id1.getParameters() != null && !id1.getParameters().equals(DERNull.INSTANCE)) {
return false;
}
return true;
}
return id1.getParameters().equals(id2.getParameters());
}
/**
* Get the PolicyQualifier from the Certificate Policies Extension.
*
* @param certificate Attribute Certificate information
* @return Policy Qualifier from the Certificate Policies Extension
*/
public static Map<String, String> getPolicyQualifier(
final AttributeCertificateInfo certificate) {
Preconditions.checkArgument(certificate.getExtensions() != null,
"Platform certificate should have extensions.");
CertificatePolicies certPolicies
= CertificatePolicies.fromExtensions(certificate.getExtensions());
Map<String, String> policyQualifiers = new HashMap<>();
String userNoticeQualifier = "";
String cpsURI = "";
if (certPolicies != null) {
// Must contain at least one Policy
for (PolicyInformation policy : certPolicies.getPolicyInformation()) {
for (ASN1Encodable pQualifierInfo: policy.getPolicyQualifiers().toArray()) {
PolicyQualifierInfo info = PolicyQualifierInfo.getInstance(pQualifierInfo);
// Subtract the data based on the OID
switch (info.getPolicyQualifierId().getId()) {
case POLICY_QUALIFIER_CPSURI:
cpsURI = DERIA5String.getInstance(info.getQualifier()).getString();
break;
case POLICY_QUALIFIER_USER_NOTICE:
UserNotice userNotice = UserNotice.getInstance(info.getQualifier());
userNoticeQualifier = userNotice.getExplicitText().getString();
break;
default:
break;
}
}
}
}
// Add to map
policyQualifiers.put("userNotice", userNoticeQualifier);
policyQualifiers.put("cpsURI", cpsURI);
return policyQualifiers;
}
}

View File

@ -0,0 +1,300 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes;
import lombok.Getter;
import lombok.Setter;
import org.bouncycastle.asn1.ASN1Boolean;
import org.bouncycastle.asn1.ASN1Enumerated;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.DERIA5String;
/**
* Basic class that handle CommonCriteriaMeasures for the Platform Certificate
* Attribute.
* <pre>
* CommonCriteriaMeasures ::= SEQUENCE {
* version IA5STRING (SIZE (1..STRMAX)), "2.2" or "3.1";
* assurancelevel EvaluationAssuranceLevel,
* evaluationStatus EvaluationStatus,
* plus BOOLEAN DEFAULT FALSE,
* strengthOfFunction [0] IMPLICIT StrengthOfFunction OPTIONAL,
* profileOid [1] IMPLICIT OBJECT IDENTIFIER OPTIONAL,
* profileUri [2] IMPLICIT URIReference OPTIONAL,
* targetOid [3] IMPLICIT OBJECT IDENTIFIER OPTIONAL,
* targetUri [4] IMPLICIT URIReference OPTIONAL }
* </pre>
*/
@Getter @Setter
public class CommonCriteriaMeasures {
private static final int STRENGTH_OF_FUNCTION = 0;
private static final int PROFILE_OID = 1;
private static final int PROFILE_URI = 2;
private static final int TARGET_OID = 3;
private static final int TARGET_URI = 4;
/**
* A type to handle the evaluation status used in the Common Criteria Measurement.
* Ordering of enum types is intentional and their ordinal values correspond to enum
* values in the TCG spec.
*
* <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 DERIA5String version;
private EvaluationAssuranceLevel assuranceLevel;
private EvaluationStatus evaluationStatus;
private ASN1Boolean plus;
private StrengthOfFunction strengthOfFunction;
private ASN1ObjectIdentifier profileOid;
private URIReference profileUri;
private ASN1ObjectIdentifier targetOid;
private URIReference targetUri;
/**
* Default constructor.
*/
public CommonCriteriaMeasures() {
this.version = null;
this.assuranceLevel = null;
this.evaluationStatus = null;
this.plus = ASN1Boolean.FALSE;
this.strengthOfFunction = null;
this.profileOid = null;
this.profileUri = null;
this.targetOid = null;
this.targetUri = null;
}
/**
* Constructor given the SEQUENCE that contains Common Criteria Measures.
* @param sequence containing the the common criteria measures
* @throws IllegalArgumentException if there was an error on the parsing
*/
public CommonCriteriaMeasures(final ASN1Sequence sequence) throws IllegalArgumentException {
//Get all the mandatory values
int index = 0;
version = DERIA5String.getInstance(sequence.getObjectAt(index));
++index;
ASN1Enumerated enumarated = ASN1Enumerated.getInstance(sequence.getObjectAt(index));
++index;
//Throw exception when is not between 1 and 7
if (enumarated.getValue().intValue() <= 0
|| enumarated.getValue().intValue() > EvaluationAssuranceLevel.values().length) {
throw new IllegalArgumentException("Invalid assurance level.");
}
assuranceLevel = EvaluationAssuranceLevel.values()[enumarated.getValue().intValue() - 1];
enumarated = ASN1Enumerated.getInstance(sequence.getObjectAt(index));
++index;
evaluationStatus = EvaluationStatus.values()[enumarated.getValue().intValue()];
//Default plus value
plus = ASN1Boolean.FALSE;
//Current sequence index
if (sequence.getObjectAt(index).toASN1Primitive() instanceof ASN1Boolean) {
plus = ASN1Boolean.getInstance(sequence.getObjectAt(index));
index++;
}
//Optional values (default to null or empty)
strengthOfFunction = null;
profileOid = null;
profileUri = null;
targetOid = null;
targetUri = null;
//Sequence for the URIReference
ASN1Sequence uriSequence;
//Continue reading the sequence
for (; index < sequence.size(); index++) {
ASN1TaggedObject taggedObj = ASN1TaggedObject.getInstance(sequence.getObjectAt(index));
switch (taggedObj.getTagNo()) {
case STRENGTH_OF_FUNCTION:
enumarated = ASN1Enumerated.getInstance(taggedObj, false);
strengthOfFunction
= StrengthOfFunction.values()[enumarated.getValue().intValue()];
break;
case PROFILE_OID:
profileOid = ASN1ObjectIdentifier.getInstance(taggedObj, false);
break;
case PROFILE_URI:
uriSequence = ASN1Sequence.getInstance(taggedObj, false);
profileUri = new URIReference(uriSequence);
break;
case TARGET_OID:
targetOid = ASN1ObjectIdentifier.getInstance(taggedObj, false);
break;
case TARGET_URI:
uriSequence = ASN1Sequence.getInstance(taggedObj, false);
targetUri = new URIReference(uriSequence);
break;
default:
throw new IllegalArgumentException("Common criteria measures contains "
+ "invalid tagged object.");
}
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ComponentIdentifier{");
sb.append("version=").append(version.toString());
sb.append(", assuranceLevel=").append(assuranceLevel.getValue());
sb.append(", evaluationStatus=").append(evaluationStatus.getValue());
sb.append(", plus=").append(plus.toString());
//Not null optional objects
sb.append(", strengthOfFunction=");
if (strengthOfFunction != null) {
sb.append(strengthOfFunction.getValue());
}
sb.append(", profileOid=");
if (profileOid != null) {
sb.append(profileOid.getId());
}
sb.append(", profileUri=");
if (profileUri != null) {
sb.append(profileUri.toString());
}
sb.append(", targetOid=");
if (targetOid != null) {
sb.append(targetOid.getId());
}
sb.append(", targetUri=");
if (targetUri != null) {
sb.append(targetUri.toString());
}
sb.append("}");
return sb.toString();
}
}

View File

@ -0,0 +1,91 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERUTF8String;
/**
* Basic class that handle component addresses from the component identifier.
* <pre>
* componentAddress ::= SEQUENCE {
* addressType AddressType,
* addressValue UTF8String (SIZE (1..STRMAX)) }
* where STRMAX is 256
* </pre>
*/
@Getter
@Setter
@AllArgsConstructor
public class ComponentAddress {
/**
* Number of identifiers that a component address must have.
*/
public static final int IDENTIFIER_NUMBER = 2;
private static final String ETHERNET_MAC = "2.23.133.17.1";
private static final String WLAN_MAC = "2.23.133.17.2";
private static final String BLUETOOTH_MAC = "2.23.133.17.3";
private ASN1ObjectIdentifier addressType;
private DERUTF8String addressValue;
/**
* Default constructor.
*/
public ComponentAddress() {
addressType = null;
addressValue = null;
}
/**
* Constructor given the SEQUENCE that contains the type and value for the
* component address.
*
* @param sequence containing the type and value for the component address
* @throws IllegalArgumentException if there was an error on the parsing
*/
public ComponentAddress(final ASN1Sequence sequence) throws IllegalArgumentException {
//Check if the sequence contains the two values required
if (sequence.size() != IDENTIFIER_NUMBER) {
throw new IllegalArgumentException("Component address does not contain "
+ "all the required fields.");
}
addressType = ASN1ObjectIdentifier.getInstance(sequence.getObjectAt(0));
addressValue = DERUTF8String.getInstance(sequence.getObjectAt(1));
}
/**
* Get the string value for the address type.
* @return the string value for the address type
*/
public String getAddressTypeValue() {
String typeValue;
switch (this.addressType.getId()) {
case ETHERNET_MAC:
typeValue = "ethernet mac";
break;
case WLAN_MAC:
typeValue = "wlan mac";
break;
case BLUETOOTH_MAC:
typeValue = "bluetooth mac";
break;
default:
typeValue = "unknown mac";
break;
}
return typeValue;
}
@Override
public String toString() {
return "ComponentAddress{"
+ "addressType=" + addressType.getId()
+ ", addressValue=" + addressValue.getString()
+ '}';
}
}

View File

@ -0,0 +1,248 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonObject.Member;
import hirs.attestationca.utils.JsonUtils;
import lombok.Getter;
import java.nio.file.FileSystems;
import java.nio.file.Path;
/**
* <p>
* This class parses the associated component identifier located in Platform
* Certificates and maps them to the corresponding string representation found
* in the associated JSON file. If the value can not be found, either because
* the provided value is malformed or doesn't exist in the mapping, then values
* returned will not match what is expected. This class will return Unknown as a
* category and None as the component which is not a valid mapping. This is
* because None is a category and Unknown is a component identifier.
* </p>
* <pre>
* componentClass ::= SEQUENCE {
* componentClassRegistry ComponentClassRegistry,
* componentClassValue OCTET STRING SIZE(4) ) }
* </pre>
*
* A note for the future.
*/
public class ComponentClass {
private static final String TCG_COMPONENT_REGISTRY = "2.23.133.18.3.1";
private static final String SMBIOS_COMPONENT_REGISTRY = "2.23.133.18.3.3";
private static final Path JSON_PATH = FileSystems.getDefault()
.getPath("/opt", "hirs", "default-properties", "component-class.json");
// private static final Path JSON_PATH = FileSystems.getDefault()
// .getPath("/opt", "hirs", "default-properties", "component-class.json");
private static final String OTHER_STRING = "Other";
private static final String UNKNOWN_STRING = "Unknown";
private static final String NONE_STRING = "None";
// Used to indicate that the component string value provided is erroneous
private static final String ERROR = "-1";
private static final int MID_INDEX = 4;
/**
* All TCG categories have Other and Unknown as the first 2 values.
*/
private static final String OTHER = "0000";
private static final String UNKNOWN = "0001";
@Getter
private String category, categoryStr;
@Getter
private String component, componentStr;
private String registryType;
private String componentIdentifier;
/**
* Default class constructor.
*/
public ComponentClass() {
this("TCG", JSON_PATH, UNKNOWN);
}
/**
* Class Constructor that takes a String representation of the component
* value.
*
* @param registryOid the decimal notation for the type of registry
* @param componentIdentifier component value
*/
public ComponentClass(final String registryOid, final String componentIdentifier) {
this(registryOid, JSON_PATH, componentIdentifier);
}
/**
* Class Constructor that takes a String representation of the component
* value.
*
* @param componentClassPath file path for the json
* @param componentIdentifier component value
*/
public ComponentClass(final Path componentClassPath, final String componentIdentifier) {
this(TCG_COMPONENT_REGISTRY, componentClassPath, componentIdentifier);
}
/**
* Main Class Constructor that takes in an integer representation of the
* component value. Sets main class variables to default values and then
* matches the value against defined values in the associated JSON file.
*
* @param registryOid the decimal notation for the type of registry
* @param componentClassPath file path for the json
* @param componentIdentifier component value
*/
public ComponentClass(final String registryOid,
final Path componentClassPath,
final String componentIdentifier) {
this.category = OTHER;
this.component = NONE_STRING;
if (componentIdentifier == null || componentIdentifier.isEmpty()) {
this.componentIdentifier = "";
} else {
this.componentIdentifier = verifyComponentValue(componentIdentifier);
}
switch (registryOid) {
case TCG_COMPONENT_REGISTRY -> registryType = "TCG";
case SMBIOS_COMPONENT_REGISTRY -> registryType = "SMBIOS";
default -> registryType = UNKNOWN_STRING;
}
switch (this.componentIdentifier) {
case OTHER:
this.categoryStr = NONE_STRING;
this.component = OTHER;
this.componentStr = OTHER_STRING;
break;
case UNKNOWN:
case "":
this.categoryStr = NONE_STRING;
this.component = UNKNOWN;
this.componentStr = UNKNOWN_STRING;
break;
case ERROR:
// Number Format Exception
break;
default:
this.category = this.componentIdentifier.substring(0, MID_INDEX) + this.category;
this.component = OTHER + this.componentIdentifier.substring(MID_INDEX);
findStringValues(JsonUtils.getSpecificJsonObject(componentClassPath, registryType));
break;
}
}
/**
* This is the main way this class will be referenced and how it
* will be displayed on the portal.
* @return String combination of category and component.
*/
@Override
public String toString() {
String resultString;
if (componentStr.equals(UNKNOWN_STRING) || component.equals(OTHER_STRING)) {
resultString = String.format("%s%n%s", registryType, categoryStr);
} else {
resultString = String.format("%s%n%s - %s", registryType, categoryStr, componentStr);
}
return resultString;
}
/**
* Getter for the Category mapped to the associated value in.
*
* @param categories a JSON object associated with mapped categories in file
* {}@link componentIdentifier}.
*/
private void findStringValues(final JsonObject categories) {
String categoryID;
String componentMask;
boolean found = false;
if (categories != null) {
for (String name : categories.names()) {
categoryID = verifyComponentValue(categories.get(name)
.asObject().get("ID").asString());
componentMask = componentIdentifier.substring(MID_INDEX);
// check for the correct flag
if (categoryMatch(componentIdentifier.substring(0, MID_INDEX),
categoryID.substring(0, MID_INDEX))) {
found = true;
JsonObject componentTypes = categories.get(name)
.asObject().get("Types").asObject();
categoryStr = name;
switch (componentMask) {
case OTHER -> componentStr = OTHER_STRING;
case UNKNOWN -> componentStr = UNKNOWN_STRING;
default -> getComponent(componentTypes);
}
}
}
}
if (!found) {
this.categoryStr = NONE_STRING;
this.componentStr = UNKNOWN_STRING;
}
}
/**
* Returns the value of the comparison between a category and the what's in the id.
* @param category the category to compare
* @param componentId the id value to compare
* @return true if they match
*/
public boolean categoryMatch(final String category, final String componentId) {
return category.equals(componentId);
}
/**
* Getter for the component associated with the component JSON Object mapped
* in the JSON file.
*
* @param components JSON Object for the categories components
*/
private void getComponent(final JsonObject components) {
String typeID;
if (components != null) {
for (Member member : components) {
typeID = verifyComponentValue(member.getName());
if (component.equals(typeID)) {
componentStr = member.getValue().asString();
}
}
}
}
/**
* This method converts the string representation of the component ID into
* an integer. Or throws and error if the format is in error.
*
* @param component string representation of the component ID
* @return the int representation of the component
*/
private static String verifyComponentValue(final String component) {
String componentValue = ERROR;
if (component != null) {
try {
if (component.contains("x")) {
componentValue = component.substring(component.indexOf("x") + 1);
} else {
if (component.contains("#")) {
componentValue = component.replace("#", "");
} else {
return component;
}
}
} catch (NumberFormatException nfEx) {
//invalid entry
}
}
return componentValue;
}
}

View File

@ -0,0 +1,231 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.asn1.ASN1Boolean;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.DERUTF8String;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* Basic class that handle component identifiers from the Platform Configuration
* Attribute.
* <pre>
* ComponentIdentifier ::= SEQUENCE {
* componentManufacturer UTF8String (SIZE (1..STRMAX)),
* componentModel UTF8String (SIZE (1..STRMAX)),
* componentSerial[0] IMPLICIT UTF8String (SIZE (1..STRMAX)) OPTIONAL,
* componentRevision [1] IMPLICIT UTF8String (SIZE (1..STRMAX)) OPTIONAL,
* componentManufacturerId [2] IMPLICIT PrivateEnterpriseNumber OPTIONAL,
* fieldReplaceable [3] IMPLICIT BOOLEAN OPTIONAL,
* componentAddress [4] IMPLICIT
* SEQUENCE(SIZE(1..CONFIGMAX)) OF ComponentAddress OPTIONAL}
* where STRMAX is 256, CONFIGMAX is 32
* </pre>
*/
@Getter
@Setter
@AllArgsConstructor
@EqualsAndHashCode
public class ComponentIdentifier {
/**
* Variable for components that aren't set.
*/
public static final String EMPTY_COMPONENT = "[Empty]";
/**
* Variable for components that aren't set.
*/
public static final String NOT_SPECIFIED_COMPONENT = "Not Specified";
/**
* Maximum number of configurations.
*/
public static final int CONFIGMAX = 32;
private static final int MANDATORY_ELEMENTS = 2;
// optional sequence objects
/**
* Static variable indicated array position for the serial number.
*/
protected static final int COMPONENT_SERIAL = 0;
/**
* Static variable indicated array position for the revision info.
*/
protected static final int COMPONENT_REVISION = 1;
/**
* Static variable indicated array position for the manufacturer id.
*/
protected static final int COMPONENT_MANUFACTURER_ID = 2;
/**
* Static variable indicated array position for the field replaceable value.
*/
protected static final int FIELD_REPLACEABLE = 3;
/**
* Static variable indicated array position for the component address.
*/
protected static final int COMPONENT_ADDRESS = 4;
private DERUTF8String componentManufacturer;
private DERUTF8String componentModel;
private DERUTF8String componentSerial;
private DERUTF8String componentRevision;
private ASN1ObjectIdentifier componentManufacturerId;
private ASN1Boolean fieldReplaceable;
private List<ComponentAddress> componentAddress;
private boolean validationResult = true;
/**
* Default constructor.
*/
public ComponentIdentifier() {
componentManufacturer = new DERUTF8String(NOT_SPECIFIED_COMPONENT);
componentModel = new DERUTF8String(NOT_SPECIFIED_COMPONENT);
componentSerial = new DERUTF8String(StringUtils.EMPTY);
componentRevision = new DERUTF8String(StringUtils.EMPTY);
componentManufacturerId = null;
fieldReplaceable = null;
componentAddress = new ArrayList<>();
}
/**
* Constructor given the components values.
*
* @param componentManufacturer represents the component manufacturer
* @param componentModel represents the component model
* @param componentSerial represents the component serial number
* @param componentRevision represents the component revision
* @param componentManufacturerId represents the component manufacturer ID
* @param fieldReplaceable represents if the component is replaceable
* @param componentAddress represents a list of addresses
*/
public ComponentIdentifier(final DERUTF8String componentManufacturer,
final DERUTF8String componentModel,
final DERUTF8String componentSerial,
final DERUTF8String componentRevision,
final ASN1ObjectIdentifier componentManufacturerId,
final ASN1Boolean fieldReplaceable,
final List<ComponentAddress> componentAddress) {
this.componentManufacturer = componentManufacturer;
this.componentModel = componentModel;
this.componentSerial = componentSerial;
this.componentRevision = componentRevision;
this.componentManufacturerId = componentManufacturerId;
this.fieldReplaceable = fieldReplaceable;
this.componentAddress = componentAddress;
}
/**
* Constructor given the SEQUENCE that contains Component Identifier.
* @param sequence containing the the component identifier
* @throws IllegalArgumentException if there was an error on the parsing
*/
public ComponentIdentifier(final ASN1Sequence sequence) throws IllegalArgumentException {
// set all optional values to default in case they aren't set.
this();
//Check if it have a valid number of identifiers
if (sequence.size() < MANDATORY_ELEMENTS) {
throw new IllegalArgumentException("Component identifier do not have required values.");
}
//Mandatory values
componentManufacturer = DERUTF8String.getInstance(sequence.getObjectAt(0));
componentModel = DERUTF8String.getInstance(sequence.getObjectAt(1));
//Continue reading the sequence if it does contain more than 2 values
for (int i = 2; i < sequence.size(); i++) {
ASN1TaggedObject taggedObj = ASN1TaggedObject.getInstance(sequence.getObjectAt(i));
switch (taggedObj.getTagNo()) {
case COMPONENT_SERIAL:
componentSerial = DERUTF8String.getInstance(taggedObj, false);
break;
case COMPONENT_REVISION:
componentRevision = DERUTF8String.getInstance(taggedObj, false);
break;
case COMPONENT_MANUFACTURER_ID:
componentManufacturerId = ASN1ObjectIdentifier.getInstance(taggedObj, false);
break;
case FIELD_REPLACEABLE:
fieldReplaceable = ASN1Boolean.getInstance(taggedObj, false);
break;
case COMPONENT_ADDRESS:
ASN1Sequence addressesSequence = ASN1Sequence.getInstance(taggedObj, false);
componentAddress = retrieveComponentAddress(addressesSequence);
break;
default:
throw new IllegalArgumentException("Component identifier contains "
+ "invalid tagged object.");
}
}
}
/**
* Get all the component addresses inside the sequence.
*
* @param sequence that contains the component addresses.
* @return list of component addresses inside the sequence
* @throws IllegalArgumentException if there was an error on the parsing
*/
public static List<ComponentAddress> retrieveComponentAddress(final ASN1Sequence sequence)
throws IllegalArgumentException {
List<ComponentAddress> addresses;
addresses = new ArrayList<>();
if (sequence.size() > CONFIGMAX) {
throw new IllegalArgumentException("Component identifier contains invalid number "
+ "of component addresses.");
}
//Get the components
for (int i = 0; i < sequence.size(); i++) {
ASN1Sequence address = ASN1Sequence.getInstance(sequence.getObjectAt(i));
addresses.add(new ComponentAddress(address));
}
return Collections.unmodifiableList(addresses);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ComponentIdentifier{");
sb.append("componentManufacturer=").append(componentManufacturer.getString());
sb.append(", componentModel=").append(componentModel.getString());
//Optional not null values
sb.append(", componentSerial=");
if (componentSerial != null) {
sb.append(componentSerial.getString());
}
sb.append(", componentRevision=");
if (componentRevision != null) {
sb.append(componentRevision.getString());
}
sb.append(", componentManufacturerId=");
if (componentManufacturerId != null) {
sb.append(componentManufacturerId.getId());
}
sb.append(", fieldReplaceable=");
if (fieldReplaceable != null) {
sb.append(fieldReplaceable.toString());
}
sb.append(", componentAddress=");
if (componentAddress.size() > 0) {
sb.append(componentAddress
.stream()
.map(Object::toString)
.collect(Collectors.joining(",")));
}
sb.append(", certificateIdentifier=");
sb.append("}");
return sb.toString();
}
}

View File

@ -0,0 +1,122 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.bouncycastle.asn1.ASN1Boolean;
import org.bouncycastle.asn1.ASN1Enumerated;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERIA5String;
/**
* Basic class that handle FIPS Level.
* <pre>
* FIPSLevel ::= SEQUENCE {
* version IA5STRING (SIZE (1..STRMAX)), -- "140-1" or "140-2"
* level SecurityLevel,
* plus BOOLEAN DEFAULT FALSE }
* </pre>
*/
@AllArgsConstructor
public class FIPSLevel {
private static final int MAX_SEQUENCE_SIZE = 3;
/**
* A type to handle the security Level used in the FIPS Level.
* Ordering of enum types is intentional and their ordinal values correspond to enum
* values in the TCG spec.
*
* <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 DERIA5String version;
@Getter @Setter
private SecurityLevel level;
@Getter @Setter
private ASN1Boolean plus;
/**
* Default constructor.
*/
public FIPSLevel() {
version = null;
level = null;
plus = null;
}
/**
* Constructor given the SEQUENCE that contains the FIPLevel Object.
*
* @param sequence containing the FIPS Level Object
* @throws IllegalArgumentException if there was an error on the parsing
*/
public FIPSLevel(final ASN1Sequence sequence) throws IllegalArgumentException {
//Get version
version = DERIA5String.getInstance(sequence.getObjectAt(0));
//Get and validate level
ASN1Enumerated enumarated = ASN1Enumerated.getInstance(sequence.getObjectAt(1));
//Throw exception when is not between 1 and 7
if (enumarated.getValue().intValue() <= 0
|| enumarated.getValue().intValue() > SecurityLevel.values().length) {
throw new IllegalArgumentException("Invalid security level on FIPSLevel.");
}
level = SecurityLevel.values()[enumarated.getValue().intValue() - 1];
//Check if there is another value on the sequence for the plus
plus = ASN1Boolean.FALSE; //Default to false
if (sequence.size() == MAX_SEQUENCE_SIZE) {
plus = ASN1Boolean.getInstance(sequence.getObjectAt(2));
}
}
@Override
public String toString() {
return "FIPSLevel{"
+ "version=" + version.getString()
+ ", level=" + level.getValue()
+ ", plus=" + plus.toString()
+ '}';
}
}

View File

@ -0,0 +1,104 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Abstract class that provides base info for Platform Configuration of
* the Platform Certificate Attribute.
*/
@AllArgsConstructor
public abstract class PlatformConfiguration {
private List<ComponentIdentifier> componentIdentifier;
@Getter @Setter
private URIReference componentIdentifierUri;
private List<PlatformProperty> platformProperties;
@Getter @Setter
private URIReference platformPropertiesUri;
/**
* Default constructor.
*/
public PlatformConfiguration() {
this.componentIdentifier = new ArrayList<>();
this.componentIdentifierUri = null;
this.platformProperties = new ArrayList<>();
this.platformPropertiesUri = null;
}
/**
* Constructor given the Platform Configuration values.
*
* @param componentIdentifier list containing all the components inside the
* Platform Configuration.
* @param platformProperties list containing all the properties inside the
* Platform Configuration.
* @param platformPropertiesUri object containing the URI Reference
*/
public PlatformConfiguration(final List<ComponentIdentifier> componentIdentifier,
final List<PlatformProperty> platformProperties,
final URIReference platformPropertiesUri) {
this.componentIdentifier = componentIdentifier;
this.platformProperties = platformProperties;
this.platformPropertiesUri = platformPropertiesUri;
}
/**
* @return the componentIdentifier
*/
public List<ComponentIdentifier> getComponentIdentifier() {
return Collections.unmodifiableList(componentIdentifier);
}
/**
* Add function for the component identifier array.
* @param componentIdentifier object to add
* @return status of the add, if successful or not
*/
protected boolean add(final ComponentIdentifier componentIdentifier) {
if (this.componentIdentifier != null) {
return this.componentIdentifier.add(componentIdentifier);
}
return false;
}
/**
* @param componentIdentifier the componentIdentifier to set
*/
public void setComponentIdentifier(final List<ComponentIdentifier> componentIdentifier) {
this.componentIdentifier = componentIdentifier;
}
/**
* @return the platformProperties
*/
public List<PlatformProperty> getPlatformProperties() {
return Collections.unmodifiableList(platformProperties);
}
/**
* Add function for the platform property array.
* @param platformProperty property object to add
* @return status of the add, if successful or not
*/
protected boolean add(final PlatformProperty platformProperty) {
if (this.platformProperties != null) {
return this.platformProperties.add(platformProperty);
}
return false;
}
/**
* @param platformProperties the platformProperties to set
*/
public void setPlatformProperties(final List<PlatformProperty> platformProperties) {
this.platformProperties = platformProperties;
}
}

View File

@ -0,0 +1,105 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1TaggedObject;
import java.util.ArrayList;
import java.util.stream.Collectors;
/**
* Basic class that handle Platform Configuration for the Platform Certificate
* Attribute.
* <pre>
* PlatformConfiguration ::= SEQUENCE {
* componentIdentifier [0] IMPLICIT SEQUENCE(SIZE(1..CONFIGMAX)) OF
* ComponentIdentifier OPTIONAL,
* platformProperties [1] IMPLICIT SEQUENCE(SIZE(1..CONFIGMAX)) OF Properties OPTIONAL,
* platformPropertiesUri [2] IMPLICIT URIReference OPTIONAL }
* </pre>
*/
public class PlatformConfigurationV1 extends PlatformConfiguration {
private static final int COMPONENT_IDENTIFIER = 0;
private static final int PLATFORM_PROPERTIES = 1;
private static final int PLATFORM_PROPERTIES_URI = 2;
/**
* Constructor given the SEQUENCE that contains Platform Configuration.
* @param sequence containing the the Platform Configuration.
* @throws IllegalArgumentException if there was an error on the parsing
*/
public PlatformConfigurationV1(final ASN1Sequence sequence) throws IllegalArgumentException {
//Default values
setComponentIdentifier(new ArrayList<>());
setPlatformProperties(new ArrayList<>());
setPlatformPropertiesUri(null);
for (int i = 0; i < sequence.size(); i++) {
ASN1TaggedObject taggedSequence
= ASN1TaggedObject.getInstance(sequence.getObjectAt(i));
//Set information based on the set tagged
switch (taggedSequence.getTagNo()) {
case COMPONENT_IDENTIFIER:
//Get componentIdentifier
ASN1Sequence componentConfiguration
= ASN1Sequence.getInstance(taggedSequence, false);
//Get and set all the component values
for (int j = 0; j < componentConfiguration.size(); j++) {
//DERSequence with the components
ASN1Sequence component
= ASN1Sequence.getInstance(componentConfiguration.getObjectAt(j));
add(new ComponentIdentifier(component));
}
break;
case PLATFORM_PROPERTIES:
//Get platformProperties
ASN1Sequence properties = ASN1Sequence.getInstance(taggedSequence, false);
//Get and set all the properties values
for (int j = 0; j < properties.size(); j++) {
//DERSequence with the components
ASN1Sequence property = ASN1Sequence.getInstance(properties.getObjectAt(j));
add(new PlatformProperty(property));
}
break;
case PLATFORM_PROPERTIES_URI:
//Get platformPropertiesURI
ASN1Sequence propertiesUri = ASN1Sequence.getInstance(taggedSequence, false);
//Save properties URI
setPlatformPropertiesUri(new URIReference(propertiesUri));
break;
default:
break;
}
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("PlatformConfiguration{");
sb.append("componentIdentifier=");
if (getComponentIdentifier().size() > 0) {
sb.append(getComponentIdentifier()
.stream()
.map(Object::toString)
.collect(Collectors.joining(",")));
}
sb.append(", platformProperties=");
if (getPlatformProperties().size() > 0) {
sb.append(getPlatformProperties()
.stream()
.map(Object::toString)
.collect(Collectors.joining(",")));
}
sb.append(", platformPropertiesUri=");
if (getPlatformPropertiesUri() != null) {
sb.append(getPlatformPropertiesUri().toString());
}
sb.append("}");
return sb.toString();
}
}

View File

@ -0,0 +1,67 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERUTF8String;
/**
*
* Basic class that handles a single property for the platform configuration.
* <pre>
* Properties ::= SEQUENCE {
* propertyName UTF8String (SIZE (1..STRMAX)),
* propertyValue UTF8String (SIZE (1..STRMAX) }
*
* </pre>
*/
@Getter
@Setter
@AllArgsConstructor
public class PlatformProperty {
private static final String NOT_SPECIFIED = "Not Specified";
/**
* Number of identifiers for version 1.
*/
protected static final int IDENTIFIER_NUMBER = 2;
private DERUTF8String propertyName;
private DERUTF8String propertyValue;
/**
* Default constructor.
*/
public PlatformProperty() {
this.propertyName = new DERUTF8String(NOT_SPECIFIED);
this.propertyValue = new DERUTF8String(NOT_SPECIFIED);
}
/**
* Constructor given the SEQUENCE that contains the name and value for the
* platform property.
*
* @param sequence containing the name and value of the platform property
* @throws IllegalArgumentException if there was an error on the parsing
*/
public PlatformProperty(final ASN1Sequence sequence) throws IllegalArgumentException {
// Check if the sequence contains the two values required
if (sequence.size() != IDENTIFIER_NUMBER) {
throw new IllegalArgumentException("Platform properties does not contain all "
+ "the required fields.");
}
this.propertyName = DERUTF8String.getInstance(sequence.getObjectAt(0));
this.propertyValue = DERUTF8String.getInstance(sequence.getObjectAt(1));
}
@Override
public String toString() {
return "PlatformProperty{"
+ "propertyName=" + propertyName.getString()
+ ", propertyValue=" + propertyValue.getString()
+ "}";
}
}

View File

@ -0,0 +1,282 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.bouncycastle.asn1.ASN1Boolean;
import org.bouncycastle.asn1.ASN1Enumerated;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.DERIA5String;
import java.math.BigInteger;
/**
* Basic class that handle component identifiers from the Platform Configuration
* Attribute.
* <pre>
* TBBSecurityAssertions ::= SEQUENCE {
* version Version DEFAULT v1,
* ccInfo [0] IMPLICIT CommonCriteriaMeasures OPTIONAL,
* fipsLevel [1] IMPLICIT FIPSLevel OPTIONAL,
* rtmType [2] IMPLICIT MeasurementRootType OPTIONAL,
* iso9000Certified BOOLEAN DEFAULT FALSE,
* iso9000Uri IA5STRING (SIZE (1..URIMAX)) OPTIONAL }
* </pre>
*/
@AllArgsConstructor
public class TBBSecurityAssertion {
private static final int CCINFO = 0;
private static final int FIPSLEVEL = 1;
private static final int RTMTYPE = 2;
/**
* A type to handle the evaluation status used in the Common Criteria Measurement.
* Ordering of enum types is intentional and their ordinal values correspond to enum
* values in the TCG spec.
*
* <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 CommonCriteriaMeasures ccInfo;
private FIPSLevel fipsLevel;
private MeasurementRootType rtmType;
private ASN1Boolean iso9000Certified;
private DERIA5String iso9000Uri;
/**
* Default constructor.
*/
public TBBSecurityAssertion() {
version = null;
ccInfo = null;
fipsLevel = null;
rtmType = null;
iso9000Certified = null;
iso9000Uri = null;
}
/**
* Constructor given the SEQUENCE that contains a TBBSecurityAssertion Object.
* @param sequence containing the the TBB Security Assertion
* @throws IllegalArgumentException if there was an error on the parsing
*/
public TBBSecurityAssertion(final ASN1Sequence sequence) throws IllegalArgumentException {
int index = 0;
//sequence size
int sequenceSize = sequence.size();
//Default values
version = new ASN1Integer(BigInteger.valueOf(0)); //Default v1 (0)
ccInfo = null;
fipsLevel = null;
rtmType = null;
iso9000Certified = ASN1Boolean.FALSE;
iso9000Uri = null;
// Only contains defaults
if (sequence.size() == 0) {
return;
}
// Get version if present
if (sequence.getObjectAt(index).toASN1Primitive() instanceof ASN1Integer) {
version = ASN1Integer.getInstance(sequence.getObjectAt(index));
index++;
}
// Check if it's a tag value
while (index < sequenceSize
&& sequence.getObjectAt(index).toASN1Primitive() instanceof ASN1TaggedObject) {
ASN1TaggedObject taggedObj = ASN1TaggedObject.getInstance(sequence.getObjectAt(index));
switch (taggedObj.getTagNo()) {
case CCINFO:
ASN1Sequence cciSequence = ASN1Sequence.getInstance(taggedObj, false);
ccInfo = new CommonCriteriaMeasures(cciSequence);
break;
case FIPSLEVEL:
ASN1Sequence fipsSequence = ASN1Sequence.getInstance(taggedObj, false);
fipsLevel = new FIPSLevel(fipsSequence);
break;
case RTMTYPE:
ASN1Enumerated enumerated = ASN1Enumerated.getInstance(taggedObj, false);
rtmType = MeasurementRootType.values()[enumerated.getValue().intValue()];
break;
default:
throw new IllegalArgumentException("TBB Security Assertion contains "
+ "invalid tagged object.");
}
index++;
}
// Check if it's a boolean
if (index < sequenceSize
&& sequence.getObjectAt(index).toASN1Primitive() instanceof ASN1Boolean) {
iso9000Certified = ASN1Boolean.getInstance(sequence.getObjectAt(index));
index++;
}
// Check if it's a IA5String
if (index < sequenceSize
&& sequence.getObjectAt(index).toASN1Primitive() instanceof DERIA5String) {
iso9000Uri = DERIA5String.getInstance(sequence.getObjectAt(index));
}
}
/**
* @return the version
*/
public ASN1Integer getVersion() {
return version;
}
/**
* @param version the version to set
*/
public void setVersion(final ASN1Integer version) {
this.version = version;
}
/**
* @return the ccInfo
*/
public CommonCriteriaMeasures getCcInfo() {
return ccInfo;
}
/**
* @param ccInfo the ccInfo to set
*/
public void setCcInfo(final CommonCriteriaMeasures ccInfo) {
this.ccInfo = ccInfo;
}
/**
* @return the fipsLevel
*/
public FIPSLevel getFipsLevel() {
return fipsLevel;
}
/**
* @param fipsLevel the fipsLevel to set
*/
public void setFipsLevel(final FIPSLevel fipsLevel) {
this.fipsLevel = fipsLevel;
}
/**
* @return the rtmType
*/
public MeasurementRootType getRtmType() {
return rtmType;
}
/**
* @param rtmType the rtmType to set
*/
public void setRtmType(final MeasurementRootType rtmType) {
this.rtmType = rtmType;
}
/**
* @return the iso9000Certified
*/
public ASN1Boolean getIso9000Certified() {
return iso9000Certified;
}
/**
* @param iso9000Certified the iso9000Certified to set
*/
public void setIso9000Certified(final ASN1Boolean iso9000Certified) {
this.iso9000Certified = iso9000Certified;
}
/**
* @return the iso9000Uri
*/
public DERIA5String getIso9000Uri() {
return iso9000Uri;
}
/**
* @param iso9000Uri the iso9000Uri to set
*/
public void setIso9000Uri(final DERIA5String iso9000Uri) {
this.iso9000Uri = iso9000Uri;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("TBBSecurityAssertion{");
sb.append("version=").append(version.toString());
//Optional values not null
sb.append(", ccInfo=");
if (ccInfo != null) {
sb.append(ccInfo.toString());
}
sb.append(", fipsLevel=");
if (fipsLevel != null) {
sb.append(fipsLevel.toString());
}
sb.append(", rtmType=");
if (rtmType != null) {
sb.append(rtmType.getValue());
}
sb.append(", iso9000Certified=").append(iso9000Certified.toString());
sb.append(", iso9000Uri=");
if (iso9000Uri != null) {
sb.append(iso9000Uri.getString());
}
sb.append("}");
return sb.toString();
}
}

View File

@ -0,0 +1,121 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.math.BigInteger;
/**
* A class to represent the TPM Security Assertions in an Endorsement Credential as
* defined by the TCG spec for TPM 1.2.
*
* https://www.trustedcomputinggroup.org/wp-content/uploads/IWG-Credential_Profiles_V1_R0.pdf
*
* Future iterations of this code may want to reference
* www.trustedcomputinggroup.org/wp-content/uploads/Credential_Profile_EK_V2.0_R14_published.pdf
* for specifications for TPM 2.0 (pg. 19).
*/
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter @Setter
@Embeddable
public class TPMSecurityAssertions {
/**
* 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
* and their ordinal values correspond to enum values in the TCG spec.
*/
public enum EkGenerationType {
/**
* Generated internally within the TPM and cannot be revoked. Enum value of 0.
*/
INTERNAL,
/**
* Generated externally and then inserted under a controlled environment during
* manufacturing. Cannot be revoked. Enum value of 1.
*/
INJECTED,
/**
* Generated internally within the TPM and can be revoked. Enum value of 2.
*/
INTERNAL_REVOCABLE,
/**
* Generated externally and then inserted under a controlled environment during
* manufacturing. Can be revoked. Enum value of 3.
*/
INJECTED_REVOCABLE;
}
/**
* A type to handle the different endorsement key generation locations used in
* specifying the endorsement key generation location and the endorsement key
* certificate generation location in the TPM Assertions field of an endorsement
* credential. Ordering of enum types is intentional and their ordinal values
* correspond to enum values in the TCG spec.
*/
public enum EkGenerationLocation {
/**
* Generated by the TPM Manufacturer. Enum value of 0.
*/
TPM_MANUFACTURER,
/**
* Generated by the Platform Manufacturer. Enum value of 1.
*/
PLATFORM_MANUFACTURER,
/**
* Generated by the endorsement key certificate signer. Enum value of 2.
*/
EK_CERT_SIGNER;
}
@Column
private BigInteger tpmSecAssertsVersion; //default v1
@Column
private boolean fieldUpgradeable; //default false
@Column(nullable = true)
private EkGenerationType ekGenType; //optional
@Column(nullable = true)
private EkGenerationLocation ekGenerationLocation; //optional
@Column(nullable = true)
private EkGenerationLocation ekCertificateGenerationLocation; //optional
// Future work (may need to create other classes):
//private CommonCriteriaMeasures commCritMeasures; //optional
//private FIPSLevel fipsLevel; //optional
//private boolean iso9000Certified; //default false
//private IA5String iso9000Uri; //optional
/**
* Standard constructor that sets required fields. Use accessor methods
* to set optional fields.
* @param version the version of the security assertions
* @param fieldUpgradeable whether or not the security assertions are
* field upgradeable.
*/
public TPMSecurityAssertions(final BigInteger version, final boolean fieldUpgradeable) {
this.tpmSecAssertsVersion = version;
this.fieldUpgradeable = fieldUpgradeable;
}
@Override
public String toString() {
return "TPMSecurityAssertions{"
+ "version=" + tpmSecAssertsVersion
+ ", fieldUpgradeable=" + fieldUpgradeable
+ ", ekGenType=" + ekGenType
+ ", ekGenLoc=" + ekGenerationLocation
+ ", ekCertGenLoc=" + ekCertificateGenerationLocation
+ '}';
}
}

View File

@ -0,0 +1,58 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.math.BigInteger;
/**
* A class to represent the TPM Specification in an Endorsement Credential as
* defined by the TCG spec for TPM 1.2.
*
* https://www.trustedcomputinggroup.org/wp-content/uploads/IWG-Credential_Profiles_V1_R0.pdf
*
* Future iterations of this code may want to reference
* www.trustedcomputinggroup.org/wp-content/uploads/Credential_Profile_EK_V2.0_R14_published.pdf
* for specifications for TPM 2.0.
*/
@EqualsAndHashCode
@NoArgsConstructor(access= AccessLevel.PROTECTED)
@Getter
@Embeddable
public class TPMSpecification {
@Column
private String family;
@Column
private BigInteger level;
@Column
private BigInteger revision;
/**
* Standard constructor.
* @param family the specification family.
* @param level the specification level.
* @param revision the specification revision.
*/
public TPMSpecification(final String family, final BigInteger level,
final BigInteger revision) {
this.family = family;
this.level = level;
this.revision = revision;
}
@Override
public String toString() {
return "TPMSpecification{"
+ "family='" + family + '\''
+ ", level=" + level
+ ", revision=" + revision
+ '}';
}
}

View File

@ -0,0 +1,91 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERIA5String;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
/**
*
* Basic class that handle a URIReference object.
* <pre>
* URIReference ::= SEQUENCE {
* uniformResourceIdentifier IA5String (SIZE (1..URIMAX)),
* hashAlgorithm AlgorithmIdentifier OPTIONAL,
* hashValue BIT STRING OPTIONAL
}
* </pre>
*/
@Getter @Setter
@AllArgsConstructor
public class URIReference {
private DERIA5String uniformResourceIdentifier;
private AlgorithmIdentifier hashAlgorithm;
@JsonIgnore
private DERBitString hashValue;
private static final int PLATFORM_PROPERTIES_URI_MAX = 3;
private static final int PLATFORM_PROPERTIES_URI_MIN = 1;
/**
* Default constructor.
*/
public URIReference() {
this.uniformResourceIdentifier = null;
this.hashAlgorithm = null;
this.hashValue = null;
}
/**
* Constructor given the SEQUENCE that contains the URIReference values.
*
* @param sequence containing the name and value of the platform property
* @throws IllegalArgumentException if there was an error on the parsing
*/
public URIReference(final ASN1Sequence sequence) throws IllegalArgumentException {
//Check if the sequence contains the two values required
if (sequence.size() > PLATFORM_PROPERTIES_URI_MAX
|| sequence.size() < PLATFORM_PROPERTIES_URI_MIN) {
throw new IllegalArgumentException("PlatformPropertiesURI contains invalid "
+ "number of fields.");
}
//Get the Platform Configuration URI values
for (int j = 0; j < sequence.size(); j++) {
if (sequence.getObjectAt(j) instanceof DERIA5String) {
this.uniformResourceIdentifier = DERIA5String.getInstance(sequence.getObjectAt(j));
} else if ((sequence.getObjectAt(j) instanceof AlgorithmIdentifier)
|| (sequence.getObjectAt(j) instanceof ASN1Sequence)) {
this.hashAlgorithm =
AlgorithmIdentifier.getInstance(sequence.getObjectAt(j));
} else if (sequence.getObjectAt(j) instanceof DERBitString) {
this.hashValue = DERBitString.getInstance(sequence.getObjectAt(j));
} else {
throw new IllegalArgumentException("Unexpected DER type found. "
+ sequence.getObjectAt(j).getClass().getName() + " found at index " + j + ".");
}
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("URIReference{");
sb.append("uniformResourceIdentifier=").append(uniformResourceIdentifier.getString());
//Check of optional values are not null
sb.append(", hashAlgorithm=");
if (hashAlgorithm != null) {
sb.append(hashAlgorithm.getAlgorithm().getId());
}
sb.append(", hashValue=");
if (hashValue != null) {
sb.append(hashValue.getString());
}
sb.append("}");
return sb.toString();
}
}

View File

@ -0,0 +1,40 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes.V2;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
/**
* 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>
* AttributeStatus ::= ENUMERATED {
* added (0),
* modified (1),
* removed (2) }
* </pre>
*/
@AllArgsConstructor
public enum AttributeStatus {
/**
* Attribute Status for ADDED.
*/
ADDED("added"),
/**
* Attribute Status for MODIFIED.
*/
MODIFIED("modified"),
/**
* Attribute Status for REMOVED.
*/
REMOVED("removed"),
/**
* Attribute Status for EMPTY.
*/
EMPTY_STATUS(StringUtils.EMPTY);
@Getter
private final String value;
}

View File

@ -0,0 +1,127 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes.V2;
import lombok.Getter;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x509.GeneralName;
import java.math.BigInteger;
/**
* Basic class that handles a the attribute associate with a Certificate
* Identifier for the component.
* <pre>
* CertificateIdentifier::= SEQUENCE {
* attributeCertIdentifier [0] IMPLICIT AttributeCertificateIdentifier OPTIONAL
* genericCertIdentifier [1] IMPLICIT IssuerSerial OPTIONAL }
*
* AttributeCertificateIdentifier ::= SEQUENCE {
* hashAlgorithm AlgorithmIdentifier,
* hashOverSignatureValue OCTET STRING }
*
* IssuerSerial ::= SEQUENCE {
* issuer GeneralNames,
* serial CertificateSerialNumber }
* </pre>
*/
@Getter
public class CertificateIdentifier {
private static final String NOT_SPECIFIED = "Not Specified";
private static final int SEQUENCE_NUMBER = 2;
private static final int ATTRIBUTE_ID_INDEX = 0;
private static final int GENERIC_ID_INDEX = 1;
private String hashAlgorithm;
private String hashSigValue;
private GeneralName issuerDN;
private BigInteger certificateSerialNumber;
/**
* Default constructor.
*/
public CertificateIdentifier() {
hashAlgorithm = NOT_SPECIFIED;
hashSigValue = null;
issuerDN = null;
certificateSerialNumber = BigInteger.ZERO;
}
/**
* Primary constructor for the parsing of the sequence.
* @param sequence containing the name and value of the Certificate Identifier
*/
public CertificateIdentifier(final ASN1Sequence sequence) {
this();
ASN1TaggedObject taggedObj;
for (int i = 0; i < sequence.size(); i++) {
taggedObj = ASN1TaggedObject.getInstance(sequence.getObjectAt(i));
switch (taggedObj.getTagNo()) {
case ATTRIBUTE_ID_INDEX:
// attributecertificateidentifier
parseAttributeCertId(ASN1Sequence.getInstance(taggedObj, false));
break;
case GENERIC_ID_INDEX:
// issuerserial
parseGenericCertId(ASN1Sequence.getInstance(taggedObj, false));
break;
default:
break;
}
}
}
private void parseAttributeCertId(final ASN1Sequence attrCertSeq) {
//Check if it have a valid number of identifiers
if (attrCertSeq.size() != SEQUENCE_NUMBER) {
throw new IllegalArgumentException("CertificateIdentifier"
+ ".AttributeCertificateIdentifier does not have required values.");
}
hashAlgorithm = attrCertSeq.getObjectAt(0).toString();
hashSigValue = attrCertSeq.getObjectAt(1).toString();
}
private void parseGenericCertId(final ASN1Sequence issuerSerialSeq) {
//Check if it have a valid number of identifiers
if (issuerSerialSeq.size() != SEQUENCE_NUMBER) {
throw new IllegalArgumentException("CertificateIdentifier"
+ ".GenericCertificateIdentifier does not have required values.");
}
ASN1Sequence derSequence = DERSequence.getInstance(issuerSerialSeq.getObjectAt(0));
ASN1TaggedObject taggedObj = ASN1TaggedObject.getInstance(derSequence.getObjectAt(0));
issuerDN = GeneralName.getInstance(taggedObj);
certificateSerialNumber = ASN1Integer.getInstance(issuerSerialSeq
.getObjectAt(1)).getValue();
}
/**
* String for the internal data stored.
* @return String representation of the data.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("CertificateIdentifier{");
sb.append("hashAlgorithm=").append(hashAlgorithm);
sb.append(", hashSigValue").append(hashSigValue);
sb.append(", issuerDN=");
if (issuerDN != null) {
sb.append(issuerDN.toString());
}
sb.append(", certificateSerialNumber=");
if (certificateSerialNumber != null) {
sb.append(certificateSerialNumber.toString());
}
sb.append("}");
return sb.toString();
}
}

View File

@ -0,0 +1,251 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes.V2;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentAddress;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentClass;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentIdentifier;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.URIReference;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.bouncycastle.asn1.ASN1Boolean;
import org.bouncycastle.asn1.ASN1Enumerated;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERUTF8String;
import java.util.List;
import java.util.stream.Collectors;
/**
* Basic class that handle component identifiers from the Platform Configuration
* Attribute.
* <pre>
* ComponentIdentifier ::= SEQUENCE {
* componentManufacturer UTF8String (SIZE (1..STRMAX)),
* componentModel UTF8String (SIZE (1..STRMAX)),
* componentSerial[0] IMPLICIT UTF8String (SIZE (1..STRMAX)) OPTIONAL,
* componentRevision [1] IMPLICIT UTF8String (SIZE (1..STRMAX)) OPTIONAL,
* componentManufacturerId [2] IMPLICIT PrivateEnterpriseNumber OPTIONAL,
* fieldReplaceable [3] IMPLICIT BOOLEAN OPTIONAL,
* componentAddress [4] IMPLICIT
* SEQUENCE(SIZE(1..CONFIGMAX)) OF ComponentAddress OPTIONAL
* componentPlatformCert [5] IMPLICIT CertificateIdentifier OPTIONAL,
* componentPlatformCertUri [6] IMPLICIT URIReference OPTIONAL,
* status [7] IMPLICIT AttributeStatus OPTIONAL }
* where STRMAX is 256, CONFIGMAX is 32
* </pre>
*/
@Getter
@Setter
@EqualsAndHashCode
public class ComponentIdentifierV2 extends ComponentIdentifier {
private static final int MANDATORY_ELEMENTS = 3;
// Additional optional identifiers for version 2
private static final int COMPONENT_PLATFORM_CERT = 5;
private static final int COMPONENT_PLATFORM_URI = 6;
private static final int ATTRIBUTE_STATUS = 7;
private ComponentClass componentClass;
private CertificateIdentifier certificateIdentifier;
private URIReference componentPlatformUri;
private AttributeStatus attributeStatus;
/**
* Default constructor.
*/
public ComponentIdentifierV2() {
super();
componentClass = new ComponentClass();
certificateIdentifier = null;
componentPlatformUri = null;
attributeStatus = AttributeStatus.EMPTY_STATUS;
}
/**
* Constructor given the components values.
*
* @param componentClass represent the component type
* @param componentManufacturer represents the component manufacturer
* @param componentModel represents the component model
* @param componentSerial represents the component serial number
* @param componentRevision represents the component revision
* @param componentManufacturerId represents the component manufacturer ID
* @param fieldReplaceable represents if the component is replaceable
* @param componentAddress represents a list of addresses
* @param certificateIdentifier object representing certificate Id
* @param componentPlatformUri object containing the URI Reference
* @param attributeStatus object containing enumerated status
*/
@SuppressWarnings("checkstyle:parameternumber")
public ComponentIdentifierV2(final ComponentClass componentClass,
final DERUTF8String componentManufacturer,
final DERUTF8String componentModel,
final DERUTF8String componentSerial,
final DERUTF8String componentRevision,
final ASN1ObjectIdentifier componentManufacturerId,
final ASN1Boolean fieldReplaceable,
final List<ComponentAddress> componentAddress,
final CertificateIdentifier certificateIdentifier,
final URIReference componentPlatformUri,
final AttributeStatus attributeStatus) {
super(componentManufacturer, componentModel, componentSerial,
componentRevision, componentManufacturerId, fieldReplaceable,
componentAddress);
this.componentClass = componentClass;
// additional optional component identifiers
this.certificateIdentifier = certificateIdentifier;
this.componentPlatformUri = componentPlatformUri;
this.attributeStatus = attributeStatus;
}
/**
* Constructor given the SEQUENCE that contains Component Identifier.
* @param sequence containing the the component identifier
* @throws IllegalArgumentException if there was an error on the parsing
*/
public ComponentIdentifierV2(final ASN1Sequence sequence)
throws IllegalArgumentException {
super();
// Check if it have a valid number of identifiers
if (sequence.size() < MANDATORY_ELEMENTS) {
throw new IllegalArgumentException("Component identifier do not have required values.");
}
int tag = 0;
ASN1Sequence componentIdSeq = ASN1Sequence.getInstance(sequence.getObjectAt(tag));
componentClass = new ComponentClass(componentIdSeq.getObjectAt(tag++).toString(),
DEROctetString.getInstance(componentIdSeq.getObjectAt(tag)).toString());
// Mandatory values
this.setComponentManufacturer(DERUTF8String.getInstance(sequence.getObjectAt(tag++)));
this.setComponentModel(DERUTF8String.getInstance(sequence.getObjectAt(tag++)));
// Continue reading the sequence if it does contain more than 2 values
for (int i = tag; i < sequence.size(); i++) {
ASN1TaggedObject taggedObj = ASN1TaggedObject.getInstance(sequence.getObjectAt(i));
switch (taggedObj.getTagNo()) {
case COMPONENT_SERIAL:
this.setComponentSerial(DERUTF8String.getInstance(taggedObj, false));
break;
case COMPONENT_REVISION:
this.setComponentRevision(DERUTF8String.getInstance(taggedObj, false));
break;
case COMPONENT_MANUFACTURER_ID:
this.setComponentManufacturerId(ASN1ObjectIdentifier
.getInstance(taggedObj, false));
break;
case FIELD_REPLACEABLE:
this.setFieldReplaceable(ASN1Boolean.getInstance(taggedObj, false));
break;
case COMPONENT_ADDRESS:
ASN1Sequence addressesSequence = ASN1Sequence.getInstance(taggedObj, false);
this.setComponentAddress(retrieveComponentAddress(addressesSequence));
break;
case COMPONENT_PLATFORM_CERT:
ASN1Sequence ciSequence = ASN1Sequence.getInstance(taggedObj, false);
certificateIdentifier = new CertificateIdentifier(ciSequence);
break;
case COMPONENT_PLATFORM_URI:
ASN1Sequence uriSequence = ASN1Sequence.getInstance(taggedObj, false);
this.componentPlatformUri = new URIReference(uriSequence);
break;
case ATTRIBUTE_STATUS:
ASN1Enumerated enumerated = ASN1Enumerated.getInstance(taggedObj, false);
this.attributeStatus = AttributeStatus.values()[
enumerated.getValue().intValue()];
break;
default:
throw new IllegalArgumentException("Component identifier contains "
+ "invalid tagged object.");
}
}
}
/**
* @return true if the component has been modified.
*/
public final boolean isAdded() {
return getAttributeStatus() == AttributeStatus.ADDED;
}
/**
* @return true if the component has been modified.
*/
public final boolean isModified() {
return getAttributeStatus() == AttributeStatus.MODIFIED;
}
/**
* @return true if the component has been removed.
*/
public final boolean isRemoved() {
return getAttributeStatus() == AttributeStatus.REMOVED;
}
/**
* @return true if the component status wasn't set.
*/
public final boolean isEmpty() {
return (getAttributeStatus() == AttributeStatus.EMPTY_STATUS)
|| (getAttributeStatus() == null);
}
/**
* @return indicates the type of platform certificate.
*/
public boolean isVersion2() {
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ComponentIdentifierV2{");
sb.append("componentClass=").append(componentClass);
sb.append(", componentManufacturer=").append(getComponentManufacturer()
.getString());
sb.append(", componentModel=").append(getComponentModel().getString());
// Optional not null values
sb.append(", componentSerial=");
if (getComponentSerial() != null) {
sb.append(getComponentSerial().getString());
}
sb.append(", componentRevision=");
if (getComponentRevision() != null) {
sb.append(getComponentRevision().getString());
}
sb.append(", componentManufacturerId=");
if (getComponentManufacturerId() != null) {
sb.append(getComponentManufacturerId().getId());
}
sb.append(", fieldReplaceable=");
if (getFieldReplaceable() != null) {
sb.append(getFieldReplaceable().toString());
}
sb.append(", componentAddress=");
if (getComponentAddress().size() > 0) {
sb.append(getComponentAddress()
.stream()
.map(Object::toString)
.collect(Collectors.joining(",")));
}
sb.append(", certificateIdentifier=");
if (certificateIdentifier != null) {
sb.append(certificateIdentifier.toString());
}
sb.append(", componentPlatformUri=");
if (componentPlatformUri != null) {
sb.append(componentPlatformUri.toString());
}
sb.append(", status=");
if (attributeStatus != null) {
sb.append(attributeStatus.getValue());
}
sb.append("}");
return sb.toString();
}
}

View File

@ -0,0 +1,119 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes.V2;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.PlatformConfiguration;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.URIReference;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1TaggedObject;
import java.util.ArrayList;
import java.util.stream.Collectors;
/**
* Basic class that handle Platform Configuration for the Platform Certificate
* Attribute.
* <pre>
* PlatformConfiguration ::= SEQUENCE {
* componentIdentifier [0] IMPLICIT SEQUENCE(SIZE(1..CONFIGMAX)) OF
* ComponentIdentifier OPTIONAL,
* componentIdentifiersUri [1] IMPLICIT URIReference OPTIONAL
* platformProperties [2] IMPLICIT SEQUENCE(SIZE(1..CONFIGMAX)) OF Properties OPTIONAL,
* platformPropertiesUri [3] IMPLICIT URIReference OPTIONAL }
* </pre>
*/
public class PlatformConfigurationV2 extends PlatformConfiguration {
private static final int COMPONENT_IDENTIFIER = 0;
private static final int COMPONENT_IDENTIFIER_URI = 1;
private static final int PLATFORM_PROPERTIES = 2;
private static final int PLATFORM_PROPERTIES_URI = 3;
/**
* Constructor given the SEQUENCE that contains Platform Configuration.
* @param sequence containing the the Platform Configuration.
* @throws IllegalArgumentException if there was an error on the parsing
*/
public PlatformConfigurationV2(final ASN1Sequence sequence) throws IllegalArgumentException {
//Default values
setComponentIdentifier(new ArrayList<>());
setComponentIdentifierUri(null);
setPlatformProperties(new ArrayList<>());
setPlatformPropertiesUri(null);
for (int i = 0; i < sequence.size(); i++) {
ASN1TaggedObject taggedSequence
= ASN1TaggedObject.getInstance(sequence.getObjectAt(i));
//Set information based on the set tagged
switch (taggedSequence.getTagNo()) {
case COMPONENT_IDENTIFIER:
//Get componentIdentifier
ASN1Sequence componentConfiguration
= ASN1Sequence.getInstance(taggedSequence, false);
//Get and set all the component values
for (int j = 0; j < componentConfiguration.size(); j++) {
//DERSequence with the components
ASN1Sequence component
= ASN1Sequence.getInstance(componentConfiguration.getObjectAt(j));
add(new ComponentIdentifierV2(component));
}
break;
case COMPONENT_IDENTIFIER_URI:
//Get componentIdentifierURI
ASN1Sequence componentUri = ASN1Sequence.getInstance(taggedSequence, false);
//Save Component Identifier URI
setComponentIdentifierUri(new URIReference(componentUri));
break;
case PLATFORM_PROPERTIES:
//Get platformProperties
ASN1Sequence properties = ASN1Sequence.getInstance(taggedSequence, false);
//Get and set all the properties values
for (int j = 0; j < properties.size(); j++) {
//DERSequence with the components
ASN1Sequence property = ASN1Sequence.getInstance(properties.getObjectAt(j));
add(new PlatformPropertyV2(property));
}
break;
case PLATFORM_PROPERTIES_URI:
//Get platformPropertiesURI
ASN1Sequence propertiesUri = ASN1Sequence.getInstance(taggedSequence, false);
//Save properties URI
setPlatformPropertiesUri(new URIReference(propertiesUri));
break;
default:
break;
}
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("PlatformConfiguration{");
sb.append("componentIdentifier=");
if (getComponentIdentifier().size() > 0) {
sb.append(getComponentIdentifier()
.stream()
.map(Object::toString)
.collect(Collectors.joining(",")));
}
sb.append(", componentIdentifierUri=");
if (getComponentIdentifierUri() != null) {
sb.append(getComponentIdentifierUri().toString());
}
sb.append(", platformProperties=");
if (getPlatformProperties().size() > 0) {
sb.append(getPlatformProperties()
.stream()
.map(Object::toString)
.collect(Collectors.joining(",")));
}
sb.append(", platformPropertiesUri=");
if (getPlatformPropertiesUri() != null) {
sb.append(getPlatformPropertiesUri().toString());
}
sb.append("}");
return sb.toString();
}
}

View File

@ -0,0 +1,100 @@
package hirs.attestationca.portal.persist.entity.userdefined.certificate.attributes.V2;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.PlatformProperty;
import lombok.Getter;
import lombok.Setter;
import org.bouncycastle.asn1.ASN1Enumerated;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERUTF8String;
/**
*
* Basic class that handles a single property for the platform configuration.
* <pre>
* Properties ::= SEQUENCE {
* propertyName UTF8String (SIZE (1..STRMAX)),
* propertyValue UTF8String (SIZE (1..STRMAX),
* status [0] IMPLICIT AttributeStatus OPTIONAL }
*
* </pre>
*/
public class PlatformPropertyV2 extends PlatformProperty {
@Getter
@Setter
private AttributeStatus attributeStatus;
/**
* Default constructor.
*/
public PlatformPropertyV2() {
super();
this.attributeStatus = AttributeStatus.EMPTY_STATUS;
}
/**
* Constructor given the name and value for the platform property.
*
* @param propertyName string containing the property name
* @param propertyValue string containing the property value
* @param attributeStatus enumerated object with the status of the property
*/
public PlatformPropertyV2(final DERUTF8String propertyName, final DERUTF8String propertyValue,
final AttributeStatus attributeStatus) {
super(propertyName, propertyValue);
this.attributeStatus = attributeStatus;
}
/**
* Constructor given the SEQUENCE that contains the name and value for the
* platform property.
*
* @param sequence containing the name and value of the platform property
* @throws IllegalArgumentException if there was an error on the parsing
*/
public PlatformPropertyV2(final ASN1Sequence sequence) throws IllegalArgumentException {
// Check if the sequence contains the two values required
if (sequence.size() < IDENTIFIER_NUMBER) {
throw new IllegalArgumentException("Platform properties does not contain all "
+ "the required fields.");
}
setPropertyName(DERUTF8String.getInstance(sequence.getObjectAt(0)));
setPropertyValue(DERUTF8String.getInstance(sequence.getObjectAt(1)));
// optional value which is a placeholder for now
if (sequence.size() > IDENTIFIER_NUMBER
&& sequence.getObjectAt(2) instanceof ASN1Enumerated) {
ASN1Enumerated enumerated = ASN1Enumerated.getInstance(sequence.getObjectAt(2));
this.attributeStatus = AttributeStatus.values()[enumerated.getValue().intValue()];
}
}
/**
* @return true if the property has been modified.
*/
public final boolean isModified() {
return getAttributeStatus() == AttributeStatus.MODIFIED;
}
/**
* @return true if the property has been removed.
*/
public final boolean isRemoved() {
return getAttributeStatus() != AttributeStatus.REMOVED;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("PlatformPropertyV2{");
sb.append("PropertyName=").append(getPropertyName().getString());
sb.append(", propertyValue=").append(getPropertyValue().getString());
if (attributeStatus != null) {
sb.append(", attributeStatus=").append(attributeStatus.toString());
}
sb.append("}");
return sb.toString();
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,60 @@
package hirs.attestationca.portal.persist.entity.userdefined.info;
import hirs.attestationca.persist.entity.userdefined.report.DeviceInfoReport;
import hirs.attestationca.utils.StringValidator;
import jakarta.persistence.Column;
import jakarta.xml.bind.annotation.XmlElement;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import java.io.Serializable;
/**
* Used for representing the firmware info of a device, such as the BIOS information.
*/
@ToString
@EqualsAndHashCode
@Getter
public class FirmwareInfo implements Serializable {
@XmlElement
@Column(length = DeviceInfoReport.LONG_STRING_LENGTH, nullable = false)
private final String biosVendor;
@XmlElement
@Column(length = DeviceInfoReport.LONG_STRING_LENGTH, nullable = false)
private final String biosVersion;
@XmlElement
@Column(length = DeviceInfoReport.SHORT_STRING_LENGTH, nullable = false)
private final String biosReleaseDate;
/**
* Constructor used to create a populated firmware info object.
*
* @param biosVendor String bios vendor name, i.e. Dell Inc.
* @param biosVersion String bios version info, i.e. A11
* @param biosReleaseDate String bios release date info, i.e. 03/12/2013
*/
public FirmwareInfo(final String biosVendor, final String biosVersion,
final String biosReleaseDate) {
this.biosVendor = StringValidator.check(biosVendor, "biosVendor")
.notBlank().maxLength(DeviceInfoReport.LONG_STRING_LENGTH).getValue();
this.biosVersion = StringValidator.check(biosVersion, "biosVersion")
.notBlank().maxLength(DeviceInfoReport.LONG_STRING_LENGTH).getValue();
this.biosReleaseDate = StringValidator.check(biosReleaseDate, "biosReleaseDate")
.notBlank().maxLength(DeviceInfoReport.SHORT_STRING_LENGTH).getValue();
}
/**
* Default constructor, useful for hibernate and marshalling and unmarshalling.
*/
public FirmwareInfo() {
this(DeviceInfoReport.NOT_SPECIFIED,
DeviceInfoReport.NOT_SPECIFIED,
DeviceInfoReport.NOT_SPECIFIED);
}
}

View File

@ -0,0 +1,122 @@
package hirs.attestationca.portal.persist.entity.userdefined.info;
import hirs.attestationca.persist.entity.userdefined.report.DeviceInfoReport;
import hirs.attestationca.utils.StringValidator;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import jakarta.xml.bind.annotation.XmlElement;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import java.io.Serializable;
/**
* Used for representing the hardware info of a device.
*/
@EqualsAndHashCode
@Getter
@Embeddable
public class HardwareInfo implements Serializable {
@XmlElement
@Column(length = DeviceInfoReport.LONG_STRING_LENGTH, nullable = false)
private String manufacturer = DeviceInfoReport.NOT_SPECIFIED;
@XmlElement
@Column(length = DeviceInfoReport.LONG_STRING_LENGTH, nullable = false)
private String productName = DeviceInfoReport.NOT_SPECIFIED;
@XmlElement
@Column(length = DeviceInfoReport.MED_STRING_LENGTH, nullable = false)
private String version = DeviceInfoReport.NOT_SPECIFIED;
@XmlElement
@Column(length = DeviceInfoReport.LONG_STRING_LENGTH, nullable = false)
private String systemSerialNumber = DeviceInfoReport.NOT_SPECIFIED;
@XmlElement
@Column(length = DeviceInfoReport.LONG_STRING_LENGTH, nullable = false)
private String chassisSerialNumber = DeviceInfoReport.NOT_SPECIFIED;
@XmlElement
@Column(length = DeviceInfoReport.LONG_STRING_LENGTH, nullable = false)
private String baseboardSerialNumber = DeviceInfoReport.NOT_SPECIFIED;
/**
* Constructor used to create a populated firmware info object.
*
* @param manufacturer String manufacturer name
* @param productName String product name info
* @param version String bios release date info
* @param systemSerialNumber String device serial number
* @param chassisSerialNumber String device chassis serial number
* @param baseboardSerialNumber String device baseboard serial number
*/
public HardwareInfo(
final String manufacturer,
final String productName,
final String version,
final String systemSerialNumber,
final String chassisSerialNumber,
final String baseboardSerialNumber) {
if (!StringUtils.isBlank(manufacturer)) {
this.manufacturer = StringValidator.check(manufacturer, "manufacturer")
.maxLength(DeviceInfoReport.LONG_STRING_LENGTH).getValue();
}
if (!StringUtils.isBlank(productName)) {
this.productName = StringValidator.check(productName, "productName")
.maxLength(DeviceInfoReport.LONG_STRING_LENGTH).getValue();
}
if (!StringUtils.isBlank(version)) {
this.version = StringValidator.check(version, "version")
.maxLength(DeviceInfoReport.MED_STRING_LENGTH).getValue();
}
if (!StringUtils.isBlank(systemSerialNumber)) {
this.systemSerialNumber = StringValidator.check(systemSerialNumber,
"systemSerialNumber")
.maxLength(DeviceInfoReport.LONG_STRING_LENGTH).getValue();
}
if (!StringUtils.isBlank(chassisSerialNumber)) {
this.chassisSerialNumber = StringValidator.check(chassisSerialNumber,
"chassisSerialNumber")
.maxLength(DeviceInfoReport.LONG_STRING_LENGTH).getValue();
}
if (!StringUtils.isBlank(baseboardSerialNumber)) {
this.baseboardSerialNumber = StringValidator.check(
baseboardSerialNumber, "baseboardSerialNumber")
.maxLength(DeviceInfoReport.LONG_STRING_LENGTH).getValue();
}
}
/**
* Default constructor, useful for hibernate and marshalling and unmarshalling.
*/
public HardwareInfo() {
this(
DeviceInfoReport.NOT_SPECIFIED,
DeviceInfoReport.NOT_SPECIFIED,
DeviceInfoReport.NOT_SPECIFIED,
DeviceInfoReport.NOT_SPECIFIED,
DeviceInfoReport.NOT_SPECIFIED,
DeviceInfoReport.NOT_SPECIFIED
);
}
@Override
public String toString() {
return "HardwareInfo{"
+ "manufacturer='" + manufacturer + '\''
+ ", productName='" + productName + '\''
+ ", version='" + version + '\''
+ ", systemSerialNumber='" + systemSerialNumber + '\''
+ ", chassisSerialNumber='" + chassisSerialNumber + '\''
+ ", baseboardSerialNumber='" + baseboardSerialNumber + '\''
+ '}';
}
}

View File

@ -0,0 +1,113 @@
package hirs.attestationca.portal.persist.entity.userdefined.info;
import hirs.attestationca.persist.entity.userdefined.report.DeviceInfoReport;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.annotations.Type;
import java.io.Serializable;
import java.net.InetAddress;
/**
* This class is used to represent the network info of a device.
*/
@EqualsAndHashCode
@Embeddable
public class NetworkInfo implements Serializable {
private static final Logger LOGGER = LogManager
.getLogger(NetworkInfo.class);
private static final int NUM_MAC_ADDRESS_BYTES = 6;
@XmlElement
@Setter
@Getter
@Column(length = DeviceInfoReport.LONG_STRING_LENGTH, nullable = true)
private String hostname;
@XmlElement
@XmlJavaTypeAdapter(value = InetAddressXmlAdapter.class)
@Setter
@Getter
@Column(length = DeviceInfoReport.SHORT_STRING_LENGTH, nullable = true)
@Type(type = "hirs.attestationca.persist.type.InetAddressType")
private InetAddress ipAddress;
@XmlElement
@Column(length = NUM_MAC_ADDRESS_BYTES, nullable = true)
@SuppressWarnings("checkstyle:magicnumber")
private byte[] macAddress;
/**
* Constructor used to create a NetworkInfo object.
*
* @param hostname
* String representing the hostname information for the device,
* can be null if hostname unknown
* @param ipAddress
* InetAddress object representing the IP address for the device,
* can be null if IP address unknown
* @param macAddress
* byte array representing the MAC address for the device, can be
* null if MAC address is unknown
*/
public NetworkInfo(final String hostname, final InetAddress ipAddress,
final byte[] macAddress) {
setHostname(hostname);
setIpAddress(ipAddress);
setMacAddress(macAddress);
}
/**
* Default constructor necessary for marshalling/unmarshalling XML objects.
*/
protected NetworkInfo() {
this.hostname = null;
this.ipAddress = null;
this.macAddress = null;
}
/**
* Used to retrieve the MAC address of the device.
*
* @return a String representing the MAC address, may return null if no
* value is set
*/
public final byte[] getMacAddress() {
if (macAddress == null) {
return null;
} else {
return macAddress.clone();
}
}
private void setMacAddress(final byte[] macAddress) {
StringBuilder sb;
if (macAddress == null) {
sb = null;
} else {
if (macAddress.length != NUM_MAC_ADDRESS_BYTES) {
LOGGER.error(
"MAC address is only {} bytes, must be {} bytes or "
+ "null", macAddress.length,
NUM_MAC_ADDRESS_BYTES);
throw new IllegalArgumentException(
"MAC address is invalid size");
}
sb = new StringBuilder();
for (byte b : macAddress) {
sb.append(String.format("%02X ", b));
}
}
LOGGER.debug("setting MAC address to: {}", sb);
this.macAddress = macAddress;
}
}

View File

@ -0,0 +1,99 @@
package hirs.attestationca.portal.persist.entity.userdefined.info;
import hirs.attestationca.persist.entity.userdefined.report.DeviceInfoReport;
import hirs.attestationca.utils.StringValidator;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import jakarta.xml.bind.annotation.XmlElement;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.Serializable;
/**
* This class is used to represent the OS info of a device.
*/
@EqualsAndHashCode
@ToString
@Getter
@Embeddable
public class OSInfo implements Serializable {
private static final Logger LOGGER = LogManager.getLogger(OSInfo.class);
@XmlElement
@Column(length = DeviceInfoReport.LONG_STRING_LENGTH, nullable = false)
private final String osName;
@XmlElement
@Column(length = DeviceInfoReport.LONG_STRING_LENGTH, nullable = false)
private final String osVersion;
@XmlElement
@Column(length = DeviceInfoReport.SHORT_STRING_LENGTH, nullable = false)
private final String osArch;
@XmlElement
@Column(length = DeviceInfoReport.SHORT_STRING_LENGTH, nullable = true)
private final String distribution;
@XmlElement
@Column(length = DeviceInfoReport.SHORT_STRING_LENGTH, nullable = true)
private final String distributionRelease;
/**
* Constructor used to create an OSInfo object. This constructor takes an OS
* name (Linux | Mac OS X | Windows 7), an OS version (i.e.
* 3.10.0-123.el7.x86_64), OS architecture (x86_64), distribution (CentOS |
* Fedora), and distribution release (7.0.1406). Distribution only makes
* sense for Linux, so distribution and distributionRelease may be null.
*
* @param osName
* String OS name (Linux | Mac OS X | Windows 7)
* @param osVersion
* String OS version (i.e. 3.10.0-123.el7.x86_64)
* @param osArch
* String OS architecture (x86_64)
* @param distribution
* String distribution (CentOS | Fedora)
* @param distributionRelease
* String distribution release (7.0.1406)
*/
public OSInfo(final String osName, final String osVersion,
final String osArch, final String distribution,
final String distributionRelease) {
LOGGER.debug("setting OS name information to: {}", osName);
this.osName = StringValidator.check(osName, "osName")
.notNull().maxLength(DeviceInfoReport.LONG_STRING_LENGTH).getValue();
LOGGER.debug("setting OS version information to: {}", osVersion);
this.osVersion = StringValidator.check(osVersion, "osVersion")
.notNull().maxLength(DeviceInfoReport.LONG_STRING_LENGTH).getValue();
LOGGER.debug("setting OS arch information to: {}", osArch);
this.osArch = StringValidator.check(osArch, "osArch")
.notNull().maxLength(DeviceInfoReport.SHORT_STRING_LENGTH).getValue();
LOGGER.debug("setting OS distribution information to: {}", distribution);
this.distribution = StringValidator.check(distribution, "distribution")
.maxLength(DeviceInfoReport.SHORT_STRING_LENGTH).getValue();
LOGGER.debug("setting OS distribution release information to: {}",
distributionRelease);
this.distributionRelease = StringValidator.check(distributionRelease, "distributionRelease")
.maxLength(DeviceInfoReport.SHORT_STRING_LENGTH).getValue();
}
/**
* Default constructor necessary for marshalling/unmarshalling XML objects.
*/
public OSInfo() {
this(DeviceInfoReport.NOT_SPECIFIED,
DeviceInfoReport.NOT_SPECIFIED,
DeviceInfoReport.NOT_SPECIFIED,
DeviceInfoReport.NOT_SPECIFIED,
DeviceInfoReport.NOT_SPECIFIED);
}
}

View File

@ -0,0 +1,66 @@
package hirs.attestationca.portal.persist.entity.userdefined.info;
import hirs.attestationca.persist.entity.userdefined.report.DeviceInfoReport;
import hirs.attestationca.utils.StringValidator;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import jakarta.xml.bind.annotation.XmlElement;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import java.io.Serializable;
@Getter
@EqualsAndHashCode
@Embeddable
public class RIMInfo implements Serializable {
@XmlElement
@Column(length = DeviceInfoReport.MED_STRING_LENGTH, nullable = false)
private final String rimManufacturer;
@XmlElement
@Column(length = DeviceInfoReport.MED_STRING_LENGTH, nullable = false)
private final String model;
@XmlElement
@Column(length = DeviceInfoReport.MED_STRING_LENGTH, nullable = false)
private final String fileHash;
@XmlElement
@Column(length = DeviceInfoReport.MED_STRING_LENGTH, nullable = false)
private final String pcrHash;
/**
* Constructor for the initial values of the class.
* @param rimManufacturer string of the rimManufacturer
* @param model string of the model
* @param fileHash string of the file hash
* @param pcrHash string of the pcr hash
*/
public RIMInfo(final String rimManufacturer, final String model,
final String fileHash, final String pcrHash) {
this.rimManufacturer = StringValidator.check(rimManufacturer, "rimManufacturer")
.notBlank().maxLength(DeviceInfoReport.MED_STRING_LENGTH).getValue();
this.model = StringValidator.check(model, "model")
.notBlank().maxLength(DeviceInfoReport.MED_STRING_LENGTH).getValue();
this.fileHash = StringValidator.check(fileHash, "fileHash")
.notBlank().maxLength(DeviceInfoReport.MED_STRING_LENGTH).getValue();
this.pcrHash = StringValidator.check(pcrHash, "pcrHash")
.notBlank().maxLength(DeviceInfoReport.MED_STRING_LENGTH).getValue();
}
/**
* Default no parameter constructor.
*/
public RIMInfo() {
this(DeviceInfoReport.NOT_SPECIFIED, DeviceInfoReport.NOT_SPECIFIED,
DeviceInfoReport.NOT_SPECIFIED, DeviceInfoReport.NOT_SPECIFIED);
}
@Override
public String toString() {
return String.format("%s, %s, %s, %s", rimManufacturer, model,
fileHash, pcrHash);
}
}

View File

@ -0,0 +1,316 @@
package hirs.attestationca.portal.persist.entity.userdefined.info;
import com.fasterxml.jackson.annotation.JsonIgnore;
import hirs.attestationca.persist.entity.userdefined.report.DeviceInfoReport;
import hirs.attestationca.utils.StringValidator;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import jakarta.persistence.Lob;
import jakarta.xml.bind.annotation.XmlElement;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.Serializable;
import java.security.cert.X509Certificate;
/**
* This class is used to represent the TPM information for a device.
*/
@Getter
@EqualsAndHashCode
@Embeddable
public class TPMInfo implements Serializable {
private static final Logger LOGGER = LogManager.getLogger(TPMInfo.class);
private static final int MAX_BLOB_SIZE = 65535;
@XmlElement
@Column(length = DeviceInfoReport.MED_STRING_LENGTH, nullable = true)
private String tpmMake;
@XmlElement
@Column(nullable = true)
private short tpmVersionMajor;
@XmlElement
@Column(nullable = true)
private short tpmVersionMinor;
@XmlElement
@Column(nullable = true)
private short tpmVersionRevMajor;
@XmlElement
@Column(nullable = true)
private short tpmVersionRevMinor;
@XmlElement
// @XmlJavaTypeAdapter(X509CertificateAdapter.class)
@Lob
// @Type(type = "hirs.attestationca.persist.type.X509CertificateType")
@JsonIgnore
private X509Certificate identityCertificate;
@Column(nullable = true, length = MAX_BLOB_SIZE)
private byte[] pcrValues;
@Column(nullable = true, length = MAX_BLOB_SIZE)
private byte[] tpmQuoteHash;
@Column(nullable = true, length = MAX_BLOB_SIZE)
private byte[] tpmQuoteSignature;
/**
* Constructor used to create a TPMInfo object.
*
* @param tpmMake
* String representing the make information for the TPM,
* NullPointerException thrown if null
* @param tpmVersionMajor
* short representing the major version number for the TPM
* @param tpmVersionMinor
* short representing the minor version number for the TPM
* @param tpmVersionRevMajor
* short representing the major revision number for the TPM
* @param tpmVersionRevMinor
* short representing the minor revision number for the TPM
* @param identityCertificate
* byte array with the value of the identity certificate
* @param pcrValues
* short representing the major revision number for the TPM
* @param tpmQuoteHash
* short representing the minor revision number for the TPM
* @param tpmQuoteSignature
* byte array with the value of the identity certificate
*/
@SuppressWarnings("parameternumber")
public TPMInfo(final String tpmMake, final short tpmVersionMajor,
final short tpmVersionMinor, final short tpmVersionRevMajor,
final short tpmVersionRevMinor,
final X509Certificate identityCertificate, final byte[] pcrValues,
final byte[] tpmQuoteHash, final byte[] tpmQuoteSignature) {
setTPMMake(tpmMake);
setTPMVersionMajor(tpmVersionMajor);
setTPMVersionMinor(tpmVersionMinor);
setTPMVersionRevMajor(tpmVersionRevMajor);
setTPMVersionRevMinor(tpmVersionRevMinor);
setIdentityCertificate(identityCertificate);
setPcrValues(pcrValues);
setTpmQuoteHash(tpmQuoteHash);
setTpmQuoteSignature(tpmQuoteSignature);
}
/**
* Constructor used to create a TPMInfo object without an identity
* certificate.
*
* @param tpmMake
* String representing the make information for the TPM,
* NullPointerException thrown if null
* @param tpmVersionMajor
* short representing the major version number for the TPM
* @param tpmVersionMinor
* short representing the minor version number for the TPM
* @param tpmVersionRevMajor
* short representing the major revision number for the TPM
* @param tpmVersionRevMinor
* short representing the minor revision number for the TPM
* @param pcrValues
* short representing the major revision number for the TPM
* @param tpmQuoteHash
* short representing the minor revision number for the TPM
* @param tpmQuoteSignature
* byte array with the value of the identity certificate
*/
@SuppressWarnings("parameternumber")
public TPMInfo(final String tpmMake, final short tpmVersionMajor,
final short tpmVersionMinor, final short tpmVersionRevMajor,
final short tpmVersionRevMinor, final byte[] pcrValues,
final byte[] tpmQuoteHash, final byte[] tpmQuoteSignature) {
setTPMMake(tpmMake);
setTPMVersionMajor(tpmVersionMajor);
setTPMVersionMinor(tpmVersionMinor);
setTPMVersionRevMajor(tpmVersionRevMajor);
setTPMVersionRevMinor(tpmVersionRevMinor);
setPcrValues(pcrValues);
setTpmQuoteHash(tpmQuoteHash);
setTpmQuoteSignature(tpmQuoteSignature);
}
/**
* Constructor used to create a TPMInfo object without an identity
* certificate.
*
* @param tpmMake
* String representing the make information for the TPM,
* NullPointerException thrown if null
* @param tpmVersionMajor
* short representing the major version number for the TPM
* @param tpmVersionMinor
* short representing the minor version number for the TPM
* @param tpmVersionRevMajor
* short representing the major revision number for the TPM
* @param tpmVersionRevMinor
* short representing the minor revision number for the TPM
*/
public TPMInfo(final String tpmMake, final short tpmVersionMajor,
final short tpmVersionMinor, final short tpmVersionRevMajor,
final short tpmVersionRevMinor) {
this(tpmMake, tpmVersionMajor, tpmVersionMinor, tpmVersionRevMajor,
tpmVersionRevMinor, null,
new byte[0], new byte[0], new byte[0]);
}
/**
* Constructor used to create a TPMInfo object without an identity
* certificate.
*
* @param tpmMake
* String representing the make information for the TPM,
* NullPointerException thrown if null
* @param tpmVersionMajor
* short representing the major version number for the TPM
* @param tpmVersionMinor
* short representing the minor version number for the TPM
* @param tpmVersionRevMajor
* short representing the major revision number for the TPM
* @param tpmVersionRevMinor
* short representing the minor revision number for the TPM
* @param identityCertificate
* byte array with the value of the identity certificate
*/
public TPMInfo(final String tpmMake, final short tpmVersionMajor,
final short tpmVersionMinor, final short tpmVersionRevMajor,
final short tpmVersionRevMinor,
final X509Certificate identityCertificate) {
this(tpmMake, tpmVersionMajor, tpmVersionMinor, tpmVersionRevMajor,
tpmVersionRevMinor, identityCertificate,
new byte[0], new byte[0], new byte[0]);
}
/**
* Default constructor used for marshalling/unmarshalling XML objects.
*/
public TPMInfo() {
this(DeviceInfoReport.NOT_SPECIFIED,
(short) 0,
(short) 0,
(short) 0,
(short) 0,
new byte[0],
new byte[0],
new byte[0]);
identityCertificate = null;
}
/**
* Getter for the tpmQuote passed up by the client.
* @return a byte blob of quote
*/
public final byte[] getTpmQuoteHash() {
return tpmQuoteHash.clone();
}
/**
* Getter for the quote signature.
* @return a byte blob.
*/
public final byte[] getTpmQuoteSignature() {
return tpmQuoteSignature.clone();
}
/**
* Getter for the pcr values.
* @return a byte blob for the pcrValues.
*/
public final byte[] getPcrValues() {
return pcrValues.clone();
}
private void setTPMMake(final String tpmMake) {
LOGGER.debug("setting TPM make info: {}", tpmMake);
this.tpmMake = StringValidator.check(tpmMake, "tpmMake")
.notNull().maxLength(DeviceInfoReport.MED_STRING_LENGTH).getValue();
}
private void setTPMVersionMajor(final short tpmVersionMajor) {
if (tpmVersionMajor < 0) {
LOGGER.error("TPM major version number cannot be negative: {}",
tpmVersionMajor);
throw new IllegalArgumentException(
"negative TPM major version number");
}
LOGGER.debug("setting TPM major version number: {}", tpmVersionMajor);
this.tpmVersionMajor = tpmVersionMajor;
}
private void setTPMVersionMinor(final short tpmVersionMinor) {
if (tpmVersionMinor < 0) {
LOGGER.error("TPM minor version number cannot be negative: {}",
tpmVersionMinor);
throw new IllegalArgumentException(
"negative TPM minor version number");
}
LOGGER.debug("setting TPM minor version number: {}", tpmVersionMinor);
this.tpmVersionMinor = tpmVersionMinor;
}
private void setTPMVersionRevMajor(final short tpmVersionRevMajor) {
if (tpmVersionRevMajor < 0) {
LOGGER.error("TPM major revision number cannot be negative: {}",
tpmVersionRevMajor);
throw new IllegalArgumentException(
"negative TPM major revision number");
}
LOGGER.debug("setting TPM major revision version number: {}",
tpmVersionRevMajor);
this.tpmVersionRevMajor = tpmVersionRevMajor;
}
private void setTPMVersionRevMinor(final short tpmVersionRevMinor) {
if (tpmVersionRevMinor < 0) {
LOGGER.error("TPM minor revision number cannot be negative: {}",
tpmVersionRevMinor);
throw new IllegalArgumentException(
"negative TPM minor revision number");
}
LOGGER.debug("setting TPM minor revision version number: {}",
tpmVersionRevMinor);
this.tpmVersionRevMinor = tpmVersionRevMinor;
}
private void setIdentityCertificate(
final X509Certificate identityCertificate) {
if (identityCertificate == null) {
LOGGER.error("identity certificate cannot be null");
throw new NullPointerException("identityCertificate");
}
LOGGER.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.portal.persist.entity.userdefined;

View File

@ -0,0 +1,289 @@
package hirs.attestationca.portal.persist.entity.userdefined.report;
import hirs.attestationca.persist.entity.userdefined.Report;
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.utils.VersionHelper;
import jakarta.persistence.Column;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.Transient;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.logging.Logger;
import static org.apache.logging.log4j.LogManager.getLogger;
/**
* A <code>DeviceInfoReport</code> is a <code>Report</code> used to transfer the
* information about the device. This <code>Report</code> includes the network,
* OS, and TPM information.
*/
@Entity
public class DeviceInfoReport extends Report implements Serializable {
private static final Logger LOGGER = getLogger(DeviceInfoReport.class);
/**
* A variable used to describe unavailable hardware, firmware, or OS info.
*/
public static final String NOT_SPECIFIED = "Not Specified";
/**
* Constant variable representing the various Short sized strings.
*/
public static final int SHORT_STRING_LENGTH = 32;
/**
* Constant variable representing the various Medium sized strings.
*/
public static final int MED_STRING_LENGTH = 64;
/**
* Constant variable representing the various Long sized strings.
*/
public static final int LONG_STRING_LENGTH = 255;
@Embedded
private NetworkInfo networkInfo;
@Embedded
private OSInfo osInfo;
@Embedded
private FirmwareInfo firmwareInfo;
@Embedded
private HardwareInfo hardwareInfo;
@Embedded
private TPMInfo tpmInfo;
@Getter
@Column(nullable = false)
private String clientApplicationVersion;
@Getter
@Setter
@Transient
private String paccorOutputString;
/**
* Default constructor necessary for marshalling/unmarshalling.
*/
public DeviceInfoReport() {
/* do nothing */
}
/**
* Constructor used to create a <code>DeviceInfoReport</code>. The
* information cannot be changed after the <code>DeviceInfoReport</code> is
* created.
*
* @param networkInfo
* NetworkInfo object, cannot be null
* @param osInfo
* OSInfo object, cannot be null
* @param firmwareInfo
* FirmwareInfo object, cannot be null
* @param hardwareInfo
* HardwareInfo object, cannot be null
* @param tpmInfo
* TPMInfo object, may be null if a TPM is not available on the
* device
*/
public DeviceInfoReport(final NetworkInfo networkInfo, final OSInfo osInfo,
final FirmwareInfo firmwareInfo, final HardwareInfo hardwareInfo,
final TPMInfo tpmInfo) {
this(networkInfo, osInfo, firmwareInfo, hardwareInfo, tpmInfo, VersionHelper.getVersion());
}
/**
* Constructor used to create a <code>DeviceInfoReport</code>. The
* information cannot be changed after the <code>DeviceInfoReport</code> is
* created.
*
* @param networkInfo
* NetworkInfo object, cannot be null
* @param osInfo
* OSInfo object, cannot be null
* @param firmwareInfo
* FirmwareInfo object, cannot be null
* @param hardwareInfo
* HardwareInfo object, cannot be null
* @param tpmInfo
* TPMInfo object, may be null if a TPM is not available on the
* device
* @param clientApplicationVersion
* string representing the version of the client that submitted this report,
* cannot be null
*/
public DeviceInfoReport(final NetworkInfo networkInfo, final OSInfo osInfo,
final FirmwareInfo firmwareInfo, final HardwareInfo hardwareInfo,
final TPMInfo tpmInfo, final String clientApplicationVersion) {
setNetworkInfo(networkInfo);
setOSInfo(osInfo);
setFirmwareInfo(firmwareInfo);
setHardwareInfo(hardwareInfo);
setTPMInfo(tpmInfo);
this.clientApplicationVersion = clientApplicationVersion;
}
/**
* Retrieves the NetworkInfo for this <code>DeviceInfoReport</code>.
*
* @return networkInfo
*/
public final NetworkInfo getNetworkInfo() {
/*
* Hibernate bug requires this
* https://hibernate.atlassian.net/browse/HHH-7610
* without null may be returned, which this interface does not support
*/
if (networkInfo == null) {
networkInfo = new NetworkInfo(null, null, null);
}
return networkInfo;
}
/**
* Retrieves the OSInfo for this <code>DeviceInfoReport</code>.
*
* @return osInfo
*/
public final OSInfo getOSInfo() {
/*
* Hibernate bug requires this
* https://hibernate.atlassian.net/browse/HHH-7610
* without null may be returned, which this interface does not support
*/
if (osInfo == null) {
osInfo = new OSInfo(NOT_SPECIFIED, NOT_SPECIFIED,
NOT_SPECIFIED, NOT_SPECIFIED, NOT_SPECIFIED);
}
return osInfo;
}
/**
* Retrieves the FirmwareInfo for this <code>DeviceInfoReport</code>.
*
* @return osInfo
*/
public final FirmwareInfo getFirmwareInfo() {
/*
* Hibernate bug requires this
* https://hibernate.atlassian.net/browse/HHH-7610
* without null may be returned, which this interface does not support
*/
if (firmwareInfo == null) {
firmwareInfo = new FirmwareInfo(NOT_SPECIFIED,
NOT_SPECIFIED, NOT_SPECIFIED);
}
return firmwareInfo;
}
/**
* Retrieves the OSInfo for this <code>DeviceInfoReport</code>.
*
* @return osInfo
*/
public HardwareInfo getHardwareInfo() {
/*
* Hibernate bug requires this
* https://hibernate.atlassian.net/browse/HHH-7610
* without null may be returned, which this interface does not support
*/
if (hardwareInfo == null) {
hardwareInfo = new HardwareInfo(
NOT_SPECIFIED,
NOT_SPECIFIED,
NOT_SPECIFIED,
NOT_SPECIFIED,
NOT_SPECIFIED,
NOT_SPECIFIED
);
}
return hardwareInfo;
}
/**
* Retrieves the TPMInfo for this <code>DeviceInfoReport</code>. TPMInfo may
* be null if a TPM is not available on the device.
*
* @return tpmInfo, may be null if a TPM is not available on the device
*/
public final TPMInfo getTPMInfo() {
return tpmInfo;
}
@Override
public String getReportType() {
return this.getClass().getName();
}
/**
* Searches the given set of TPMBaselines for matching device info fields that
* are determined critical to detecting a kernel update.
* @param tpmBaselines Iterable&lt;TPMBaseline&gt; set of TPMBaseline objects.
* @return True, if one of the TPM baselines in the set has the same kernel-specific
* info as this DeviceinfoReport.
*/
public final boolean matchesKernelInfo(final Iterable<TpmWhiteListBaseline> tpmBaselines) {
boolean match = false;
if (tpmBaselines != null) {
// Retrieve the fields which indicate a kernel update
final OSInfo kernelOSInfo = getOSInfo();
// perform the search
for (final TpmWhiteListBaseline baseline : tpmBaselines) {
final OSInfo baselineOSInfo = baseline.getOSInfo();
if(baselineOSInfo.getOSName().equalsIgnoreCase(kernelOSInfo.getOSName())
&& baselineOSInfo.getOSVersion().equalsIgnoreCase(kernelOSInfo.getOSVersion())) {
match = true;
break;
}
}
}
return match;
}
private void setNetworkInfo(NetworkInfo networkInfo) {
if (networkInfo == null) {
LOGGER.error("NetworkInfo cannot be null");
throw new NullPointerException("network info");
}
this.networkInfo = networkInfo;
}
private void setOSInfo(OSInfo osInfo) {
if (osInfo == null) {
LOGGER.error("OSInfo cannot be null");
throw new NullPointerException("os info");
}
this.osInfo = osInfo;
}
private void setFirmwareInfo(FirmwareInfo firmwareInfo) {
if (firmwareInfo == null) {
LOGGER.error("FirmwareInfo cannot be null");
throw new NullPointerException("firmware info");
}
this.firmwareInfo = firmwareInfo;
}
private void setHardwareInfo(HardwareInfo hardwareInfo) {
if (hardwareInfo == null) {
LOGGER.error("HardwareInfo cannot be null");
throw new NullPointerException("hardware info");
}
this.hardwareInfo = hardwareInfo;
}
private void setTPMInfo(TPMInfo tpmInfo) {
this.tpmInfo = tpmInfo;
}
}

View File

@ -0,0 +1,51 @@
package hirs.attestationca.portal.persist.entity.userdefined.result;
import lombok.Getter;
import lombok.Setter;
/**
* An <code>CertificateValidationResult</code> represents the result of a certificate validation
* operation.
*
*/
@Getter
@Setter
public class CertificateValidationResult {
/**
* Enum used to represent certificate validation status.
*/
public enum CertificateValidationStatus {
/**
* Represents a passing validation.
*/
PASS,
/**
* Represents a failed validation.
*/
FAIL,
/**
* Represents a validation 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

@ -1,18 +1,18 @@
package hirs.attestationca.portal.entity.userdefined.rim;
package hirs.attestationca.portal.persist.entity.userdefined.rim;
import com.fasterxml.jackson.annotation.JsonIgnore;
import hirs.attestationca.portal.entity.userdefined.ReferenceManifest;
import hirs.attestationca.portal.service.ReferenceManifestServiceImpl;
import hirs.attestationca.portal.utils.SwidResource;
import hirs.attestationca.portal.utils.xjc.BaseElement;
import hirs.attestationca.portal.utils.xjc.Directory;
import hirs.attestationca.portal.utils.xjc.File;
import hirs.attestationca.portal.utils.xjc.FilesystemItem;
import hirs.attestationca.portal.utils.xjc.Link;
import hirs.attestationca.portal.utils.xjc.Meta;
import hirs.attestationca.portal.utils.xjc.ResourceCollection;
import hirs.attestationca.portal.utils.xjc.SoftwareIdentity;
import hirs.attestationca.portal.utils.xjc.SoftwareMeta;
import hirs.attestationca.persist.entity.userdefined.ReferenceManifest;
import hirs.attestationca.persist.service.ReferenceManifestServiceImpl;
import hirs.attestationca.utils.SwidResource;
import hirs.attestationca.utils.xjc.BaseElement;
import hirs.attestationca.utils.xjc.Directory;
import hirs.attestationca.utils.xjc.File;
import hirs.attestationca.utils.xjc.FilesystemItem;
import hirs.attestationca.utils.xjc.Link;
import hirs.attestationca.utils.xjc.Meta;
import hirs.attestationca.utils.xjc.ResourceCollection;
import hirs.attestationca.utils.xjc.SoftwareIdentity;
import hirs.attestationca.utils.xjc.SoftwareMeta;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.xml.bind.JAXBContext;
@ -98,7 +98,7 @@ public class BaseReferenceManifest extends ReferenceManifest {
*
* @param fileName - string representation of the uploaded file.
* @param rimBytes - the file content of the uploaded file.
* @throws IOException - thrown if the file is invalid.
* @throws java.io.IOException - thrown if the file is invalid.
*/
public BaseReferenceManifest(final String fileName, final byte[] rimBytes) throws IOException {
this(rimBytes);
@ -110,7 +110,7 @@ public class BaseReferenceManifest extends ReferenceManifest {
* valid swidtag file and parses the information.
*
* @param rimBytes byte array representation of the RIM
* @throws IOException if unable to unmarshal the string
* @throws java.io.IOException if unable to unmarshal the string
*/
@SuppressWarnings("checkstyle:AvoidInlineConditionals")
public BaseReferenceManifest(final byte[] rimBytes) throws IOException {
@ -150,8 +150,8 @@ public class BaseReferenceManifest extends ReferenceManifest {
parseSoftwareMeta((SoftwareMeta) element.getValue());
break;
case "Entity":
hirs.attestationca.portal.utils.xjc.Entity entity
= (hirs.attestationca.portal.utils.xjc.Entity) element.getValue();
hirs.attestationca.utils.xjc.Entity entity
= (hirs.attestationca.utils.xjc.Entity) element.getValue();
if (entity != null) {
this.entityName = entity.getName();
this.entityRegId = entity.getRegid();
@ -249,7 +249,7 @@ public class BaseReferenceManifest extends ReferenceManifest {
*
* @param fileStream stream of the swidtag file.
* @return a {@link SoftwareIdentity} object
* @throws IOException Thrown by the unmarhsallSwidTag method.
* @throws java.io.IOException Thrown by the unmarhsallSwidTag method.
*/
private SoftwareIdentity validateSwidTag(final InputStream fileStream) throws IOException {
JAXBElement jaxbe = unmarshallSwidTag(fileStream);
@ -298,7 +298,7 @@ public class BaseReferenceManifest extends ReferenceManifest {
*
* @param stream to the input swidtag
* @return the SoftwareIdentity element at the root of the swidtag
* @throws IOException if the swidtag cannot be unmarshalled or validated
* @throws java.io.IOException if the swidtag cannot be unmarshalled or validated
*/
private JAXBElement unmarshallSwidTag(final InputStream stream) throws IOException {
JAXBElement jaxbe = null;

View File

@ -1,8 +1,8 @@
package hirs.attestationca.portal.entity.userdefined.rim;
package hirs.attestationca.portal.persist.entity.userdefined.rim;
import com.fasterxml.jackson.annotation.JsonIgnore;
import hirs.attestationca.portal.entity.userdefined.ReferenceManifest;
import hirs.attestationca.portal.enums.AppraisalStatus;
import hirs.attestationca.persist.entity.userdefined.ReferenceManifest;
import hirs.attestationca.persist.enums.AppraisalStatus;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
@ -16,7 +16,7 @@ import java.io.IOException;
/**
* Sub class that will just focus on PCR Values and Events.
* Similar to {@link hirs.attestationca.portal.entity.userdefined.rim.SupportReferenceManifest}
* Similar to {@link main.java.hirs.attestationca.entity.userdefined.rim.SupportReferenceManifest}
* however this is the live log from the client.
*/
@Entity

View File

@ -1,9 +1,9 @@
package hirs.attestationca.portal.entity.userdefined.rim;
package hirs.attestationca.portal.persist.entity.userdefined.rim;
import com.fasterxml.jackson.annotation.JsonIgnore;
import hirs.attestationca.portal.entity.userdefined.ReferenceManifest;
import hirs.attestationca.portal.utils.tpm.eventlog.TCGEventLog;
import hirs.attestationca.portal.utils.tpm.eventlog.TpmPcrEvent;
import hirs.attestationca.persist.entity.userdefined.ReferenceManifest;
import hirs.attestationca.utils.tpm.eventlog.TCGEventLog;
import hirs.attestationca.utils.tpm.eventlog.TpmPcrEvent;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import lombok.Getter;
@ -41,7 +41,7 @@ public class SupportReferenceManifest extends ReferenceManifest {
*
* @param fileName - string representation of the uploaded file.
* @param rimBytes byte array representation of the RIM
* @throws IOException if unable to unmarshal the string
* @throws java.io.IOException if unable to unmarshal the string
*/
public SupportReferenceManifest(final String fileName,
final byte[] rimBytes) throws IOException {
@ -56,7 +56,7 @@ public class SupportReferenceManifest extends ReferenceManifest {
* valid swidtag file and parses the information.
*
* @param rimBytes byte array representation of the RIM
* @throws IOException if unable to unmarshal the string
* @throws java.io.IOException if unable to unmarshal the string
*/
public SupportReferenceManifest(final byte[] rimBytes) throws IOException {
this("blank.rimel", rimBytes);

View File

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

View File

@ -1,4 +1,4 @@
package hirs.attestationca.portal.enums;
package hirs.attestationca.portal.persist.enums;
/**
* Class to capture appraisal results and corresponding messages.

View File

@ -1,4 +1,4 @@
package hirs.attestationca.portal.enums;
package hirs.attestationca.portal.persist.enums;
import java.util.Arrays;
import java.util.stream.Collectors;

View File

@ -1,6 +1,6 @@
package hirs.attestationca.portal.enums;
package hirs.attestationca.portal.persist.enums;
import hirs.attestationca.portal.utils.VersionHelper;
import hirs.attestationca.utils.VersionHelper;
/**
* Contains attributes required to display a portal page and its menu link.

View File

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

View File

@ -1,4 +1,4 @@
package hirs.attestationca.portal.service;
package hirs.attestationca.portal.persist.service;
public class DbServiceImpl {
/**

View File

@ -0,0 +1,4 @@
package hirs.attestationca.portal.persist.service;
public interface DefaultService {
}

View File

@ -1,9 +1,9 @@
package hirs.attestationca.portal.service;
package hirs.attestationca.portal.persist.service;
import hirs.attestationca.portal.entity.manager.DeviceRepository;
import hirs.attestationca.portal.entity.userdefined.Device;
import hirs.attestationca.portal.enums.AppraisalStatus;
import hirs.attestationca.portal.enums.HealthStatus;
import hirs.attestationca.persist.entity.manager.DeviceRepository;
import hirs.attestationca.persist.entity.userdefined.Device;
import hirs.attestationca.persist.enums.AppraisalStatus;
import hirs.attestationca.persist.enums.HealthStatus;
import jakarta.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

View File

@ -1,7 +1,7 @@
package hirs.attestationca.portal.service;
package hirs.attestationca.portal.persist.service;
import hirs.attestationca.portal.entity.manager.ReferenceManifestRepository;
import hirs.attestationca.portal.entity.userdefined.ReferenceManifest;
import hirs.attestationca.persist.entity.manager.ReferenceManifestRepository;
import hirs.attestationca.persist.entity.userdefined.ReferenceManifest;
import jakarta.persistence.EntityManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

View File

@ -1,7 +1,7 @@
package hirs.attestationca.portal.service;
package hirs.attestationca.portal.persist.service;
import hirs.attestationca.portal.entity.manager.SettingsRepository;
import hirs.attestationca.portal.entity.userdefined.SupplyChainSettings;
import hirs.attestationca.persist.entity.manager.SettingsRepository;
import hirs.attestationca.persist.entity.userdefined.SupplyChainSettings;
import jakarta.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

View File

@ -0,0 +1,192 @@
package hirs.attestationca.portal.persist.type;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.StringType;
import org.hibernate.type.descriptor.java.StringJavaType;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;
/**
* This is a class for persisting <code>InetAddress</code> objects via
* Hibernate. This class provides the mapping from <code>InetAddress</code> to
* Hibernate commands to JDBC.
*/
@NoArgsConstructor(access = AccessLevel.PUBLIC)
public final class InetAddressType implements UserType {
/**
* Returns varchar type.
*
* @return varchar type
*/
@Override
public int getSqlType() {
return new StringJavaType.INSTANCE.sqlType();
}
/**
* Returns the <code>InetAddress</code> class.
*
* @return <code>InetAddress</code> class
*/
@Override
public Class returnedClass() {
return InetAddress.class;
}
/**
* Compares x and y using {@link java.util.Objects#equals(Object, Object)}.
*
* @param x x
* @param y y
* @return value from equals call
*/
@Override
public boolean equals(final Object x, final Object y) {
return Objects.equals(x, y);
}
/**
* Returns the hash code of x, which will be the same as from
* <code>InetAddress</code>.
*
* @param x x
* @return hash value of x
*/
@Override
public int hashCode(final Object x) {
assert x != null;
return x.hashCode();
}
/**
* Converts the IP address that is stored as a <code>String</code> and
* converts it to an <code>InetAddress</code>.
*
* @param rs
* result set
* @param names
* column names
* @param session
* session
* @param owner
* owner
* @return InetAddress of String
* @throws HibernateException
* if unable to convert the String to an InetAddress
* @throws java.sql.SQLException
* if unable to retrieve the String from the result set
*/
@Override
public Object nullSafeGet(final ResultSet rs, final String[] names,
final SharedSessionContractImplementor session, final Object owner)
throws HibernateException, SQLException {
final String ip = StringJavaType.INSTANCE.getReplacement(rs.toString(), names[0],
session);
if (ip == null) {
return null;
}
try {
return InetAddress.getByName(ip);
} catch (UnknownHostException e) {
final String msg = String.format("unable to convert ip address: %s", ip);
throw new HibernateException(msg, e);
}
}
/**
* Converts the <code>InetAddress</code> <code>value</code> to a
* <code>String</code> and stores it in the database.
*
* @param st prepared statement
* @param value InetAddress
* @param index index
* @param session session
* @throws java.sql.SQLException if unable to set the value in the result set
*/
@Override
public void nullSafeSet(final PreparedStatement st, final Object value,
final int index, final SharedSessionContractImplementor session)
throws SQLException {
if (value == null) {
StringJavaType.INSTANCE.set(st, null, index, session);
} else {
final InetAddress address = (InetAddress) value;
final String ip = address.getHostAddress();
StringJavaType.INSTANCE.set(st, ip, index, session);
}
}
/**
* Returns <code>value</code> since <code>InetAddress</code> is immutable.
*
* @param value value
* @return value
* @throws HibernateException will never be thrown
*/
@Override
public Object deepCopy(final Object value) throws HibernateException {
return value;
}
/**
* Returns false because <code>InetAddress</code> is immutable.
*
* @return false
*/
@Override
public boolean isMutable() {
return false;
}
/**
* Returns <code>value</code> because <code>InetAddress</code> is
* immutable.
*
* @param value value
* @return value
*/
@Override
public Serializable disassemble(final Object value) {
return (Serializable) value;
}
/**
* Returns <code>cached</code> because <code>InetAddress</code> is
* immutable.
*
* @param cached cached
* @param owner owner
* @return cached
*/
@Override
public Object assemble(final Serializable cached, final Object owner) {
return cached;
}
/**
* Returns the <code>original</code> because <code>InetAddress</code> is
* immutable.
*
* @param original original
* @param target target
* @param owner owner
* @return original
*/
@Override
public Object replace(final Object original, final Object target,
final Object owner) {
return original;
}
}

View File

@ -0,0 +1,203 @@
package hirs.attestationca.portal.persist.type;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
import javax.sql.rowset.serial.SerialBlob;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.sql.Blob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
/**
* This is a class for persisting <code>X509Certificate</code> objects via
* Hibernate. This class provides the mapping from <code>X509Certificate</code>
* to Hibernate commands to JDBC.
*/
@NoArgsConstructor(access= AccessLevel.PUBLIC)
public final class X509CertificateType implements UserType {
@Override
public int getSqlType() {
return Types.BLOB;
}
/**
* Returns the <code>X509Certificate</code> class.
*
* @return <code>X509Certificate</code> class
*/
@Override
public Class returnedClass() {
return X509Certificate.class;
}
/**
* Compares x and y using {@link java.util.Objects#equals(Object, Object)}.
*
* @param x x
* @param y y
* @return value from equals call
*/
@Override
public boolean equals(final Object x, final Object y) {
return Objects.equals(x, y);
}
/**
* Returns the hash code of x, which will be the same as from
* <code>X509Certificate</code>.
*
* @param x x
* @return hash value of x
*/
@Override
public int hashCode(final Object x) {
assert x != null;
return x.hashCode();
}
/**
* Converts the X509Certificate that is stored as a <code>String</code> and
* converts it to an <code>X509Certificate</code>.
*
* @param rs
* result set
* @param names
* column names
* @param session
* session
* @param owner
* owner
* @return X509Certificate of String
* @throws HibernateException
* if unable to convert the String to an X509Certificate
* @throws java.sql.SQLException
* if unable to retrieve the String from the result set
*/
@Override
public Object nullSafeGet(final ResultSet rs, final int names,
final SharedSessionContractImplementor session, final Object owner)
throws HibernateException, SQLException {
final Blob cert = rs.getBlob(names);
if (cert == null) {
return null;
}
try {
InputStream inputStream = new ByteArrayInputStream(
cert.getBytes(1, (int) cert.length()));
CertificateFactory cf = CertificateFactory.getInstance("X.509");
return cf.generateCertificate(inputStream);
} catch (CertificateException e) {
final String msg = String.format(
"unable to convert certificate: %s", cert);
throw new HibernateException(msg, e);
}
}
/**
* Converts the <code>X509Certificate</code> <code>value</code> to a
* <code>String</code> and stores it in the database.
*
* @param st prepared statement
* @param value X509Certificate
* @param index index
* @param session session
* @throws java.sql.SQLException if unable to set the value in the result set
*/
@Override
public void nullSafeSet(final PreparedStatement st, final Object value,
final int index, final SharedSessionContractImplementor session)
throws SQLException {
if (value == null) {
st.setString(index, null);
} else {
try {
Blob blob =
new SerialBlob(((Certificate) value).getEncoded());
st.setBlob(index, blob);
} catch (Exception e) {
final String msg =
String.format("unable to convert certificate: %s",
value.toString());
throw new HibernateException(msg, e);
}
}
}
/**
* Returns <code>value</code> since <code>X509Certificate</code> is
* immutable.
*
* @param value value
* @return value
* @throws HibernateException will never be thrown
*/
@Override
public Object deepCopy(final Object value) throws HibernateException {
return value;
}
/**
* Returns false because <code>X509Certificate</code> is immutable.
*
* @return false
*/
@Override
public boolean isMutable() {
return false;
}
/**
* Returns <code>value</code> because <code>X509Certificate</code> is
* immutable.
*
* @param value value
* @return value
*/
@Override
public Serializable disassemble(final Object value) {
return (Serializable) value;
}
/**
* Returns <code>cached</code> because <code>X509Certificate</code> is
* immutable.
*
* @param cached cached
* @param owner owner
* @return cached
*/
@Override
public Object assemble(final Serializable cached, final Object owner) {
return cached;
}
/**
* Returns the <code>original</code> because <code>X509Certificate</code> is
* immutable.
*
* @param original original
* @param target target
* @param owner owner
* @return original
*/
@Override
public Object replace(final Object original, final Object target,
final Object owner) {
return original;
}
}

View File

@ -1,4 +1,4 @@
package hirs.attestationca.portal;
package hirs.attestationca.portal.portal;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -11,7 +11,7 @@ import java.util.Collections;
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan({"hirs.attestationca.portal", "hirs.attestationca.portal.page.controllers", "hirs.attestationca.portal.entity", "hirs.attestationca.portal.service"})
@ComponentScan({"hirs.attestationca.portal", "hirs.attestationca.portal.page.controllers", "hirs.attestationca.persist.entity", "hirs.attestationca.persist.entity.service"})
public class HIRSApplication extends SpringBootServletInitializer {
@Override

View File

@ -1,6 +1,6 @@
package hirs.attestationca.portal;
package hirs.attestationca.portal.portal;
import hirs.attestationca.portal.service.SettingsServiceImpl;
import hirs.attestationca.persist.service.SettingsServiceImpl;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;
import org.apache.logging.log4j.LogManager;

View File

@ -1,4 +1,4 @@
package hirs.attestationca.portal;
package hirs.attestationca.portal.portal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
@ -22,8 +22,8 @@ import java.util.Properties;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:hibernate.properties" })
@ComponentScan({ "hirs.attestationca.portal" })
@EnableJpaRepositories(basePackages = "hirs.attestationca.portal.entity")
@ComponentScan({ "hirs.attestationca.portal.page" })
@EnableJpaRepositories(basePackages = "hirs.attestationca.persist")
public class PersistenceJPAConfig {
@Autowired
@ -33,7 +33,7 @@ public class PersistenceJPAConfig {
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean entityManagerBean = new LocalContainerEntityManagerFactoryBean();
entityManagerBean.setDataSource(dataSource());
entityManagerBean.setPackagesToScan(new String[] {"hirs.attestationca.portal.entity"});
entityManagerBean.setPackagesToScan(new String[] {"hirs.attestationca.persist"});
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
entityManagerBean.setJpaVendorAdapter(vendorAdapter);

View File

@ -1,4 +1,4 @@
package hirs.attestationca.portal.datatables;
package hirs.attestationca.portal.portal.datatables;
import lombok.AccessLevel;
import lombok.Getter;

View File

@ -1,4 +1,4 @@
/**
* Root Package for HIRS Attestation CA Portal.
*/
package hirs.attestationca.portal;
package hirs.attestationca.portal.portal;

View File

@ -1,7 +1,7 @@
package hirs.attestationca.portal.page;
package hirs.attestationca.portal.portal.page;
import hirs.attestationca.portal.enums.Page;
import hirs.attestationca.portal.utils.BannerConfiguration;
import hirs.attestationca.persist.enums.Page;
import hirs.attestationca.utils.BannerConfiguration;
import lombok.AllArgsConstructor;
import org.apache.http.client.utils.URIBuilder;
import org.apache.logging.log4j.LogManager;
@ -116,7 +116,7 @@ public abstract class PageController<P extends PageParams> {
* @param model The model data to pass to the page.
* @param attr The request's RedirectAttributes to hold the model data.
* @return RedirectView back to the page with the specified parameters.
* @throws URISyntaxException if malformed URI
* @throws java.net.URISyntaxException if malformed URI
*/
protected final RedirectView redirectToSelf(
final P params,
@ -134,7 +134,7 @@ public abstract class PageController<P extends PageParams> {
* @param model The model data to pass to the page.
* @param attr The request's RedirectAttributes to hold the model data.
* @return RedirectView back to the page with the specified parameters.
* @throws URISyntaxException if malformed URI
* @throws java.net.URISyntaxException if malformed URI
*/
protected final RedirectView redirectTo(
final Page newPage,

View File

@ -1,4 +1,4 @@
package hirs.attestationca.portal.page;
package hirs.attestationca.portal.portal.page;
import java.util.ArrayList;
import java.util.Collections;

View File

@ -1,4 +1,4 @@
package hirs.attestationca.portal.page;
package hirs.attestationca.portal.portal.page;
import java.util.LinkedHashMap;

View File

@ -1,6 +1,6 @@
package hirs.attestationca.portal.page;
package hirs.attestationca.portal.portal.page;
import hirs.attestationca.portal.entity.userdefined.SupplyChainSettings;
import hirs.attestationca.persist.entity.userdefined.SupplyChainSettings;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

View File

@ -1,13 +1,13 @@
package hirs.attestationca.portal.page.controllers;
package hirs.attestationca.portal.portal.page.controllers;
import hirs.attestationca.portal.entity.manager.DeviceRepository;
import hirs.attestationca.portal.entity.userdefined.Device;
import hirs.attestationca.portal.enums.AppraisalStatus;
import hirs.attestationca.portal.enums.HealthStatus;
import hirs.attestationca.portal.enums.Page;
import hirs.attestationca.persist.entity.manager.DeviceRepository;
import hirs.attestationca.persist.entity.userdefined.Device;
import hirs.attestationca.persist.enums.AppraisalStatus;
import hirs.attestationca.persist.enums.HealthStatus;
import hirs.attestationca.persist.enums.Page;
import hirs.attestationca.portal.page.PageController;
import hirs.attestationca.portal.page.params.NoPageParams;
import hirs.attestationca.portal.service.DeviceServiceImpl;
import hirs.attestationca.persist.service.DeviceServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

View File

@ -1,4 +1,4 @@
package hirs.attestationca.portal.page.controllers;
package hirs.attestationca.portal.portal.page.controllers;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;

View File

@ -1,6 +1,6 @@
package hirs.attestationca.portal.page.controllers;
package hirs.attestationca.portal.portal.page.controllers;
import hirs.attestationca.portal.enums.Page;
import hirs.attestationca.persist.enums.Page;
import hirs.attestationca.portal.page.PageController;
import hirs.attestationca.portal.page.params.NoPageParams;
import org.springframework.stereotype.Controller;

View File

@ -1,13 +1,13 @@
package hirs.attestationca.portal.page.controllers;
package hirs.attestationca.portal.portal.page.controllers;
import hirs.attestationca.portal.entity.userdefined.SupplyChainSettings;
import hirs.attestationca.portal.enums.Page;
import hirs.attestationca.persist.entity.userdefined.SupplyChainSettings;
import hirs.attestationca.persist.enums.Page;
import hirs.attestationca.portal.page.PageController;
import hirs.attestationca.portal.page.PageMessages;
import hirs.attestationca.portal.page.PolicyPageModel;
import hirs.attestationca.portal.page.params.NoPageParams;
import hirs.attestationca.portal.service.SettingsServiceImpl;
import hirs.attestationca.portal.utils.exception.PolicyManagerException;
import hirs.attestationca.persist.service.SettingsServiceImpl;
import hirs.attestationca.utils.exception.PolicyManagerException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
@ -102,7 +102,7 @@ public class PolicyPageController extends PageController<NoPageParams> {
* @param attr RedirectAttributes used to forward data back to the original
* page.
* @return View containing the url and parameters
* @throws URISyntaxException if malformed URI
* @throws java.net.URISyntaxException if malformed URI
*/
@RequestMapping(value = "update-pc-validation", method = RequestMethod.POST)
public RedirectView updatePcVal(@ModelAttribute final PolicyPageModel ppModel,
@ -153,7 +153,7 @@ public class PolicyPageController extends PageController<NoPageParams> {
* @param attr RedirectAttributes used to forward data back to the original
* page.
* @return View containing the url and parameters
* @throws URISyntaxException if malformed URI
* @throws java.net.URISyntaxException if malformed URI
*/
@RequestMapping(value = "update-pc-attribute-validation", method = RequestMethod.POST)
public RedirectView updatePcAttributeVal(@ModelAttribute final PolicyPageModel ppModel,
@ -202,7 +202,7 @@ public class PolicyPageController extends PageController<NoPageParams> {
* @param ppModel The data posted by the form mapped into an object.
* @param attr RedirectAttributes used to forward data back to the original page.
* @return View containing the url and parameters
* @throws URISyntaxException if malformed URI
* @throws java.net.URISyntaxException if malformed URI
*/
@RequestMapping(value = "update-issue-attestation", method = RequestMethod.POST)
public RedirectView updateAttestationVal(@ModelAttribute final PolicyPageModel ppModel,
@ -246,7 +246,7 @@ public class PolicyPageController extends PageController<NoPageParams> {
* @param ppModel The data posted by the form mapped into an object.
* @param attr RedirectAttributes used to forward data back to the original page.
* @return View containing the url and parameters
* @throws URISyntaxException if malformed URI
* @throws java.net.URISyntaxException if malformed URI
*/
@RequestMapping(value = "update-issue-devid", method = RequestMethod.POST)
public RedirectView updateDevIdVal(@ModelAttribute final PolicyPageModel ppModel,
@ -291,7 +291,7 @@ public class PolicyPageController extends PageController<NoPageParams> {
* @param ppModel The data posted by the form mapped into an object.
* @param attr RedirectAttributes used to forward data back to the original page.
* @return View containing the url and parameters
* @throws URISyntaxException if malformed URI
* @throws java.net.URISyntaxException if malformed URI
*/
@RequestMapping(value = "update-expire-on", method = RequestMethod.POST)
public RedirectView updateExpireOnVal(@ModelAttribute final PolicyPageModel ppModel,
@ -361,7 +361,7 @@ public class PolicyPageController extends PageController<NoPageParams> {
* @param ppModel The data posted by the form mapped into an object.
* @param attr RedirectAttributes used to forward data back to the original page.
* @return View containing the url and parameters
* @throws URISyntaxException if malformed URI
* @throws java.net.URISyntaxException if malformed URI
*/
@RequestMapping(value = "update-devid-expire-on", method = RequestMethod.POST)
public RedirectView updateDevIdExpireOnVal(@ModelAttribute final PolicyPageModel ppModel,
@ -431,7 +431,7 @@ public class PolicyPageController extends PageController<NoPageParams> {
* @param ppModel The data posted by the form mapped into an object.
* @param attr RedirectAttributes used to forward data back to the original page.
* @return View containing the url and parameters
* @throws URISyntaxException if malformed URI
* @throws java.net.URISyntaxException if malformed URI
*/
@RequestMapping(value = "update-threshold", method = RequestMethod.POST)
public RedirectView updateThresholdVal(@ModelAttribute final PolicyPageModel ppModel,
@ -502,7 +502,7 @@ public class PolicyPageController extends PageController<NoPageParams> {
* @param ppModel The data posted by the form mapped into an object.
* @param attr RedirectAttributes used to forward data back to the original page.
* @return View containing the url and parameters
* @throws URISyntaxException if malformed URI
* @throws java.net.URISyntaxException if malformed URI
*/
@RequestMapping(value = "update-devid-threshold", method = RequestMethod.POST)
public RedirectView updateDevIdThresholdVal(@ModelAttribute final PolicyPageModel ppModel,
@ -572,7 +572,7 @@ public class PolicyPageController extends PageController<NoPageParams> {
* @param attr RedirectAttributes used to forward data back to the original
* page.
* @return View containing the url and parameters
* @throws URISyntaxException if malformed URI
* @throws java.net.URISyntaxException if malformed URI
*/
@RequestMapping(value = "update-ec-validation", method = RequestMethod.POST)
public RedirectView updateEcVal(@ModelAttribute final PolicyPageModel ppModel,
@ -624,7 +624,7 @@ public class PolicyPageController extends PageController<NoPageParams> {
* @param attr RedirectAttributes used to forward data back to the original
* page.
* @return View containing the url and parameters
* @throws URISyntaxException if malformed URI
* @throws java.net.URISyntaxException if malformed URI
*/
@RequestMapping(value = "update-firmware-validation", method = RequestMethod.POST)
public RedirectView updateFirmwareVal(@ModelAttribute final PolicyPageModel ppModel,
@ -681,7 +681,7 @@ public class PolicyPageController extends PageController<NoPageParams> {
* @param attr RedirectAttributes used to forward data back to the original
* page.
* @return View containing the url and parameters
* @throws URISyntaxException if malformed URI
* @throws java.net.URISyntaxException if malformed URI
*/
@RequestMapping(value = "update-ima-ignore", method = RequestMethod.POST)
public RedirectView updateIgnoreIma(@ModelAttribute final PolicyPageModel ppModel,
@ -732,7 +732,7 @@ public class PolicyPageController extends PageController<NoPageParams> {
* @param attr RedirectAttributes used to forward data back to the original
* page.
* @return View containing the url and parameters
* @throws URISyntaxException if malformed URI
* @throws java.net.URISyntaxException if malformed URI
*/
@RequestMapping(value = "update-tboot-ignore", method = RequestMethod.POST)
public RedirectView updateIgnoreTboot(@ModelAttribute final PolicyPageModel ppModel,
@ -783,7 +783,7 @@ public class PolicyPageController extends PageController<NoPageParams> {
* @param attr RedirectAttributes used to forward data back to the original
* page.
* @return View containing the url and parameters
* @throws URISyntaxException if malformed URI
* @throws java.net.URISyntaxException if malformed URI
*/
@RequestMapping(value = "update-gpt-ignore", method = RequestMethod.POST)
public RedirectView updateIgnoreGptEvents(@ModelAttribute final PolicyPageModel ppModel,
@ -834,7 +834,7 @@ public class PolicyPageController extends PageController<NoPageParams> {
* @param attr RedirectAttributes used to forward data back to the original
* page.
* @return View containing the url and parameters
* @throws URISyntaxException if malformed URI
* @throws java.net.URISyntaxException if malformed URI
*/
@RequestMapping(value = "update-os-evt-ignore", method = RequestMethod.POST)
public RedirectView updateIgnoreOsEvents(

View File

@ -1,4 +1,4 @@
package hirs.attestationca.portal.page.params;
package hirs.attestationca.portal.portal.page.params;
import hirs.attestationca.portal.page.PageParams;
import java.util.LinkedHashMap;

View File

@ -1,4 +0,0 @@
package hirs.attestationca.portal.service;
public interface DefaultService {
}

View File

@ -43,7 +43,7 @@ public class BannerConfiguration {
* Verify if the file exist, if it does it will get all the
* properties values and save them on the class.
*
* @throws IOException the banner level for the web site.
* @throws java.io.IOException the banner level for the web site.
*/
public BannerConfiguration() throws IOException {
if (!Files.exists(BANNER_PROPERTIES_PATH)) {

View File

@ -0,0 +1,49 @@
package hirs.attestationca.portal.utils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bouncycastle.asn1.x500.X500Name;
/**
* Utilities class specific for additional Bouncy Castle functionality.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class BouncyCastleUtils {
private static final String SEPARATOR_COMMA = ",";
private static final String SEPARATOR_PLUS = "+";
private static final Logger LOGGER = LogManager.getLogger(BouncyCastleUtils.class);
/**
* This method can be used to compare the distinguished names given from
* certificates. This compare uses X500Name class in bouncy castle, which
* compares the RDNs and not the string itself. The method will check for
* '+' and replace them, X500Name doesn't do this.
*
* @param nameValue1 first general name to be used
* @param nameValue2 second general name to be used
* @return true if the values match based on the RDNs, false if not
*/
public static boolean x500NameCompare(final String nameValue1, final String nameValue2) {
if (nameValue1 == null || nameValue2 == null) {
throw new IllegalArgumentException("Provided DN string is null.");
}
boolean result = false;
X500Name x500Name1;
X500Name x500Name2;
try {
x500Name1 = new X500Name(nameValue1.replace(SEPARATOR_PLUS, SEPARATOR_COMMA));
x500Name2 = new X500Name(nameValue2.replace(SEPARATOR_PLUS, SEPARATOR_COMMA));
result = x500Name1.equals(x500Name2);
} catch (IllegalArgumentException iaEx) {
LOGGER.error(iaEx.toString());
}
return result;
}
}

View File

@ -1,6 +1,6 @@
package hirs.attestationca.portal.utils;
import hirs.attestationca.portal.entity.userdefined.SupplyChainSettings;
import hirs.attestationca.persist.entity.userdefined.SupplyChainSettings;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

View File

@ -0,0 +1,110 @@
package hirs.attestationca.portal.utils;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* A simple utility that exposes a fluent way to validate Strings. Can easily be generalized to
* any type of data. See example usage in StringValidationTest.
*/
public final class StringValidator {
private static final Logger DEFAULT_LOGGER = LogManager.getLogger();
@Getter
private final String value;
private final String fieldName;
private final Logger logger;
/**
* Begins a validation operation.
*
* @param value the value to check
* @param fieldName the name of the field (to be used in error reporting)
* @return a Validation object, upon which validation methods can be called
*/
public static StringValidator check(final String value, final String fieldName) {
return new StringValidator(value, fieldName, null);
}
/**
* Begins a validation operation.
*
* @param value the value to check
* @param fieldName the name of the field (to be used in error reporting)
* @param logger a logger to use in lieu of Validation's logger
* @return a Validation object, upon which validation methods can be called
*/
public static StringValidator check(final String value, final String fieldName,
final Logger logger) {
return new StringValidator(value, fieldName, logger);
}
private StringValidator(final String value, final String fieldName, final Logger logger) {
this.value = value;
this.fieldName = fieldName;
if (logger == null) {
this.logger = DEFAULT_LOGGER;
} else {
this.logger = logger;
}
}
/**
* Assert that the given field is not null. Throws an IllegalArgumentException if the value
* is indeed null.
*
* @return this Validation object for further validation
*/
public StringValidator notNull() {
if (value == null) {
String message = String.format("Field %s is null", fieldName);
logger.error(message);
throw new IllegalArgumentException(message);
}
return this;
}
/**
* Assert that the given field is not blank (empty or null.) Throws an IllegalArgumentException
* if the value is indeed blank.
*
* @return this Validation object for further validation
*/
public StringValidator notBlank() {
if (StringUtils.isBlank(value)) {
String message = String.format("Field %s is blank (empty or null)", fieldName);
logger.error(message);
throw new IllegalArgumentException(message);
}
return this;
}
/**
* Assert that the given field is not longer than the given value. Throws an
* IllegalArgumentException if the value exceeds this length. A null value will pass
* this validation.
*
* @param maxLength the maximum length of the String
* @return this Validation object for further validation
*/
public StringValidator maxLength(final int maxLength) {
if (value == null) {
return this;
}
if (value.length() > maxLength) {
String message = String.format(
"Field %s is too large (%d > %d) with value %s",
fieldName, value.length(), maxLength, value
);
logger.error(message);
throw new IllegalArgumentException(message);
}
return this;
}
}

View File

@ -1,12 +1,12 @@
package hirs.attestationca.portal.utils;
import com.google.common.base.Preconditions;
import hirs.attestationca.portal.utils.digest.DigestAlgorithm;
import hirs.attestationca.utils.digest.DigestAlgorithm;
import lombok.Getter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import hirs.attestationca.portal.utils.xjc.File;
import hirs.attestationca.utils.xjc.File;
import javax.xml.namespace.QName;
import java.math.BigInteger;
import java.util.Map;

View File

@ -47,7 +47,7 @@ public final class VersionHelper {
* Read the symbolic link to VERSION in the top level HIRS directory.
* @param filename "VERSION"
* @return the version number from the file
* @throws IOException
* @throws java.io.IOException
*/
private static String getFileContents(final String filename) throws IOException {
URL url = Resources.getResource(filename);

View File

@ -11,11 +11,11 @@ import java.util.regex.Pattern;
/**
* This abstract class represents a message digest. Extending classes include
* {@link hirs.attestationca.portal.utils.digest.Digest} and {@link hirs.attestationca.portal.utils.digest.OptionalDigest}.
* {@link main.java.hirs.attestationca.utils.digest.Digest} and {@link main.java.hirs.attestationca.utils.digest.OptionalDigest}.
* <p>
* Two classes were made to facilitate persisting them with Hibernate in different ways.
* To persist non-nullable entries in an embedded collection, use {@link hirs.attestationca.portal.utils.digest.Digest} (see
* {@link TPMBaseline} for reference.) To persist nullable entries, use {@link hirs.attestationca.portal.utils.digest.OptionalDigest}
* To persist non-nullable entries in an embedded collection, use {@link main.java.hirs.attestationca.utils.digest.Digest} (see
* {@link TPMBaseline} for reference.) To persist nullable entries, use {@link main.java.hirs.attestationca.utils.digest.OptionalDigest}
* (see {@link ImaBlacklistRecord} for reference.)
*/
public abstract class AbstractDigest {
@ -66,7 +66,7 @@ public abstract class AbstractDigest {
}
if (digest.length != algorithm.getLengthInBytes()) {
throw new AbstractDigest.IllegalDigestLength(algorithm, digest);
throw new IllegalDigestLength(algorithm, digest);
}
}
@ -157,7 +157,7 @@ public abstract class AbstractDigest {
}
/**
* Parses a {@link DigestAlgorithm} from a String returned by {@link AbstractDigest#toString()}.
* Parses a {@link hirs.attestationca.portal.utils.digest.DigestAlgorithm} from a String returned by {@link hirs.attestationca.portal.utils.digest.AbstractDigest#toString()}.
*
* @param digest the digest string as computed above
* @return the DigestAlgorithm component of the String
@ -167,7 +167,7 @@ public abstract class AbstractDigest {
}
/**
* Parses a digest from a String returned by {@link AbstractDigest#toString()}.
* Parses a digest from a String returned by {@link hirs.attestationca.portal.utils.digest.AbstractDigest#toString()}.
*
* @param digest the digest string as computed above
* @return the byte array representing the actual digest

View File

@ -2,7 +2,7 @@ package hirs.attestationca.portal.utils.digest;
/**
* Enumeration identifying the different outcomes of a comparison between
* two {@link Digest} objects.
* two {@link hirs.attestationca.portal.utils.digest.Digest} objects.
*
*/
public enum DigestComparisonResultType {

View File

@ -11,12 +11,12 @@ import jakarta.xml.bind.annotation.XmlElement;
import java.util.Arrays;
/**
* This class is identical to {@link Digest} except its fields are nullable. However, in practice,
* This class is identical to {@link hirs.attestationca.portal.utils.digest.Digest} except its fields are nullable. However, in practice,
* an instance of this class cannot have null values assigned to its fields. The fields are marked
* as nullable to allow Hibernate to set a reference an embedded instance of this class to null
* (as there is no way for Hibernate to distinguish between a null reference and completely
* null fields on an embedded entity.) Otherwise, there is no operational difference between
* this class and {@link Digest}.
* this class and {@link hirs.attestationca.portal.utils.digest.Digest}.
*/
@Embeddable
@Access(AccessType.FIELD)

View File

@ -1,9 +1,9 @@
package hirs.attestationca.portal.utils.tpm.eventlog;
import hirs.attestationca.portal.utils.digest.AbstractDigest;
import hirs.attestationca.portal.utils.HexUtils;
import hirs.attestationca.portal.utils.tpm.eventlog.events.EvConstants;
import hirs.attestationca.portal.utils.tpm.eventlog.uefi.UefiConstants;
import hirs.attestationca.utils.HexUtils;
import hirs.attestationca.utils.digest.AbstractDigest;
import hirs.attestationca.utils.tpm.eventlog.events.EvConstants;
import hirs.attestationca.utils.tpm.eventlog.uefi.UefiConstants;
import lombok.Getter;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

View File

@ -1,6 +1,6 @@
package hirs.attestationca.portal.utils.tpm.eventlog;
import hirs.attestationca.portal.utils.HexUtils;
import hirs.attestationca.utils.HexUtils;
import lombok.AccessLevel;
import lombok.Getter;

View File

@ -1,21 +1,21 @@
package hirs.attestationca.portal.utils.tpm.eventlog;
import hirs.attestationca.portal.utils.HexUtils;
import hirs.attestationca.portal.utils.tpm.eventlog.events.EvCompactHash;
import hirs.attestationca.portal.utils.tpm.eventlog.events.EvConstants;
import hirs.attestationca.portal.utils.tpm.eventlog.events.EvEfiBootServicesApp;
import hirs.attestationca.portal.utils.tpm.eventlog.events.EvEfiGptPartition;
import hirs.attestationca.portal.utils.tpm.eventlog.events.EvEfiHandoffTable;
import hirs.attestationca.portal.utils.tpm.eventlog.events.EvEfiSpecIdEvent;
import hirs.attestationca.portal.utils.tpm.eventlog.events.EvEventTag;
import hirs.attestationca.portal.utils.tpm.eventlog.events.EvIPL;
import hirs.attestationca.portal.utils.tpm.eventlog.events.EvNoAction;
import hirs.attestationca.portal.utils.tpm.eventlog.events.EvPostCode;
import hirs.attestationca.portal.utils.tpm.eventlog.events.EvSCrtmContents;
import hirs.attestationca.portal.utils.tpm.eventlog.events.EvSCrtmVersion;
import hirs.attestationca.portal.utils.tpm.eventlog.uefi.UefiConstants;
import hirs.attestationca.portal.utils.tpm.eventlog.uefi.UefiFirmware;
import hirs.attestationca.portal.utils.tpm.eventlog.uefi.UefiVariable;
import hirs.attestationca.utils.HexUtils;
import hirs.attestationca.utils.tpm.eventlog.events.EvCompactHash;
import hirs.attestationca.utils.tpm.eventlog.events.EvConstants;
import hirs.attestationca.utils.tpm.eventlog.events.EvEfiGptPartition;
import hirs.attestationca.utils.tpm.eventlog.events.EvEfiHandoffTable;
import hirs.attestationca.utils.tpm.eventlog.events.EvEfiSpecIdEvent;
import hirs.attestationca.utils.tpm.eventlog.events.EvEventTag;
import hirs.attestationca.utils.tpm.eventlog.events.EvIPL;
import hirs.attestationca.utils.tpm.eventlog.events.EvNoAction;
import hirs.attestationca.utils.tpm.eventlog.events.EvSCrtmContents;
import hirs.attestationca.utils.tpm.eventlog.events.EvSCrtmVersion;
import hirs.attestationca.utils.tpm.eventlog.uefi.UefiConstants;
import hirs.attestationca.utils.tpm.eventlog.events.EvEfiBootServicesApp;
import hirs.attestationca.utils.tpm.eventlog.events.EvPostCode;
import hirs.attestationca.utils.tpm.eventlog.uefi.UefiFirmware;
import hirs.attestationca.utils.tpm.eventlog.uefi.UefiVariable;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

View File

@ -1,8 +1,8 @@
package hirs.attestationca.portal.utils.tpm.eventlog;
import hirs.attestationca.portal.utils.HexUtils;
import hirs.attestationca.portal.utils.tpm.eventlog.events.EvConstants;
import hirs.attestationca.portal.utils.tpm.eventlog.uefi.UefiConstants;
import hirs.attestationca.utils.HexUtils;
import hirs.attestationca.utils.tpm.eventlog.events.EvConstants;
import hirs.attestationca.utils.tpm.eventlog.uefi.UefiConstants;
import java.io.ByteArrayInputStream;
import java.io.IOException;

View File

@ -1,8 +1,8 @@
package hirs.attestationca.portal.utils.tpm.eventlog;
import hirs.attestationca.portal.utils.HexUtils;
import hirs.attestationca.portal.utils.tpm.eventlog.events.EvConstants;
import hirs.attestationca.portal.utils.tpm.eventlog.uefi.UefiConstants;
import hirs.attestationca.utils.HexUtils;
import hirs.attestationca.utils.tpm.eventlog.events.EvConstants;
import hirs.attestationca.utils.tpm.eventlog.uefi.UefiConstants;
import java.io.ByteArrayInputStream;
import java.io.IOException;

View File

@ -1,7 +1,7 @@
package hirs.attestationca.portal.utils.tpm.eventlog.events;
import hirs.attestationca.portal.utils.HexUtils;
import hirs.attestationca.portal.utils.tpm.eventlog.uefi.UefiConstants;
import hirs.attestationca.utils.HexUtils;
import hirs.attestationca.utils.tpm.eventlog.uefi.UefiConstants;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

View File

@ -1,8 +1,8 @@
package hirs.attestationca.portal.utils.tpm.eventlog.events;
import hirs.attestationca.portal.utils.HexUtils;
import hirs.attestationca.portal.utils.tpm.eventlog.uefi.UefiConstants;
import hirs.attestationca.portal.utils.tpm.eventlog.uefi.UefiDevicePath;
import hirs.attestationca.utils.HexUtils;
import hirs.attestationca.utils.tpm.eventlog.uefi.UefiConstants;
import hirs.attestationca.utils.tpm.eventlog.uefi.UefiDevicePath;
import lombok.Getter;
import java.io.UnsupportedEncodingException;

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