Merge branch 'issue-504'

This commit is contained in:
chubtub 2023-04-17 12:16:03 -04:00
commit 610e1f316c
13 changed files with 588 additions and 304 deletions

Binary file not shown.

View File

@ -12,22 +12,43 @@ import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.util.encoders.DecoderException;
import java.io.*;
import java.security.*;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;
import java.security.UnrecoverableEntryException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;
/**
* This class parses private key, public key, and certificate for use in their respective java.security objects.
* This class parses private key, public key, and certificates for use in
* their respective java.security objects.
*/
public class CredentialParser {
private static final String X509 = "X.509";
private static final String JKS = "JKS";
private static final String PEM = "PEM";
private static final String DEFAULT_ALGORITHM = "RSA";
private static final String PKCS1_HEADER = "-----BEGIN RSA PRIVATE KEY-----";
private static final String PKCS1_FOOTER = "-----END RSA PRIVATE KEY-----";
private static final String PKCS8_HEADER = "-----BEGIN PRIVATE KEY-----";
@ -54,14 +75,94 @@ public class CredentialParser {
return publicKey;
}
public void parseJKSCredentials(String jksKeystore) {
/**
* This method parses the CA cert chain, private key, and public key from
* a JKS truststore.
*
* @param jksKeystore the truststore file
*/
public List<X509Certificate> parseJKSCredentials(String jksKeystore,
String alias,
String password) {
ArrayList<X509Certificate> keystoreAsList = new ArrayList<>();
try {
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream(jksKeystore), password.toCharArray());
for (Certificate cert : keystore.getCertificateChain(alias)) {
keystoreAsList.add((X509Certificate) cert);
}
KeyStore.PrivateKeyEntry privateKeyEntry =
parseKeystorePrivateKey(jksKeystore,
SwidTagConstants.DEFAULT_PRIVATE_KEY_ALIAS,
SwidTagConstants.DEFAULT_KEYSTORE_PASSWORD);
(KeyStore.PrivateKeyEntry) keystore.getEntry(alias,
new KeyStore.PasswordProtection(password.toCharArray()));
certificate = (X509Certificate) privateKeyEntry.getCertificate();
privateKey = privateKeyEntry.getPrivateKey();
publicKey = certificate.getPublicKey();
} catch (KeyStoreException e) {
System.out.println("JKS keystore type not supported");
} catch (FileNotFoundException e) {
System.out.println("Unable to locate " + jksKeystore);
} catch (IOException e) {
if (e.getCause() instanceof UnrecoverableKeyException) {
System.out.println("Password is incorrect, please resubmit");
} else if (password.isEmpty()) {
System.out.println("No password given, please resubmit");
} else {
System.out.println("Error importing keystore data:");
e.printStackTrace();
}
} catch (NoSuchAlgorithmException e) {
System.out.println("Unable to verify keystore integrity");
e.printStackTrace();
} catch (CertificateException e) {
System.out.println("Error loading certificates from keystore:");
e.printStackTrace();
} catch (UnrecoverableEntryException e) {
e.printStackTrace();
}
return keystoreAsList;
}
/**
* Convenience method for parsing the default JKS.
*/
public List<X509Certificate> parseDefaultCredentials() {
return parseJKSCredentials(SwidTagConstants.DEFAULT_KEYSTORE_FILE,
SwidTagConstants.DEFAULT_PRIVATE_KEY_ALIAS,
SwidTagConstants.DEFAULT_KEYSTORE_PASSWORD);
}
/**
* This method returns the X509Certificate object from a PEM truststore.
*
* @param truststore the PEM truststore
* @return a list of X509 certs
*/
public List<X509Certificate> parseCertsFromPEM(String truststore) {
return parsePEMCertificates(truststore);
}
public void parsePEMCredentials(List<X509Certificate> truststore, String privateKeyFile)
throws Exception {
byte[] challengeString = new byte[15];
for (X509Certificate cert : truststore) {
certificate = cert;
privateKey = parsePEMPrivateKey(privateKeyFile, DEFAULT_ALGORITHM);
publicKey = certificate.getPublicKey();
SecureRandom.getInstanceStrong().nextBytes(challengeString);
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(challengeString);
byte[] signedChallenge = signature.sign();
signature.initVerify(publicKey);
signature.update(challengeString);
if (signature.verify(signedChallenge)) {
System.out.println("Matched private key to truststore certificate");
break;
} else {
publicKey = null;
}
}
}
public void parsePEMCredentials(String certificateFile, String privateKeyFile)
@ -70,7 +171,7 @@ public class CredentialParser {
if (certificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal())) {
throw new CertificateException("Signing certificate cannot be self-signed!");
}
privateKey = parsePEMPrivateKey(privateKeyFile, "RSA");
privateKey = parsePEMPrivateKey(privateKeyFile, DEFAULT_ALGORITHM);
publicKey = certificate.getPublicKey();
}
@ -78,6 +179,7 @@ public class CredentialParser {
* This method extracts certificate bytes from a string. The bytes are assumed to be
* PEM format, and a header and footer are concatenated with the input string to
* facilitate proper parsing.
*
* @param pemString the input string
* @return an X509Certificate created from the string
* @throws CertificateException if instantiating the CertificateFactory errors
@ -96,21 +198,11 @@ public class CredentialParser {
}
}
/**
* This method returns the X509Certificate object from a PEM certificate file.
* @param certificateFile
* @return
* @throws FileNotFoundException
*/
public List<X509Certificate> parseCertsFromPEM(String certificateFile)
throws FileNotFoundException {
return parsePEMCertificates(certificateFile);
}
/**
* This method returns the X509Certificate found in a PEM file.
* Unchecked typcase warnings are suppressed because the CertificateFactory
* implements X509Certificate objects explicitly.
*
* @param filename pem file
* @return a list containing all X509Certificates extracted
*/
@ -136,7 +228,8 @@ public class CredentialParser {
} catch (CertificateException e) {
System.out.println("Error in certificate factory: " + e.getMessage());
} catch (IOException e) {
System.out.println("Error reading from input stream: " + e.getMessage());
System.out.println("Error reading from input stream: " + filename);
e.printStackTrace();
} finally {
try {
if (fis != null) {
@ -158,6 +251,7 @@ public class CredentialParser {
* Both PKCS1 and PKCS8 formats are handled.
* Algorithm argument is present to allow handling of multiple encryption algorithms,
* but for now it is always RSA.
*
* @param filename
* @return
*/
@ -218,6 +312,7 @@ public class CredentialParser {
/**
* This method reads a PKCS1 keypair from a PEM file.
*
* @param filename
* @return
*/
@ -232,12 +327,15 @@ public class CredentialParser {
/**
* This method returns the private key from a JKS keystore.
*
* @param keystoreFile
* @param alias
* @param password
* @return KeyStore.PrivateKeyEntry
*/
private KeyStore.PrivateKeyEntry parseKeystorePrivateKey(String keystoreFile, String alias, String password) {
private KeyStore.PrivateKeyEntry parseKeystorePrivateKey(String keystoreFile,
String alias,
String password) {
KeyStore keystore = null;
KeyStore.PrivateKeyEntry privateKey = null;
try {
@ -247,7 +345,8 @@ public class CredentialParser {
new KeyStore.PasswordProtection(password.toCharArray()));
} catch (FileNotFoundException e) {
System.out.println("Cannot locate keystore " + keystoreFile);
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableEntryException | CertificateException | IOException e) {
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableEntryException |
CertificateException | IOException e) {
e.printStackTrace();
}
@ -256,6 +355,7 @@ public class CredentialParser {
/**
* This method returns the authorityInfoAccess from an X509Certificate.
*
* @return
* @throws IOException
*/
@ -279,6 +379,7 @@ public class CredentialParser {
/**
* This method returns the subjectKeyIdentifier from the local X509Certificate.
*
* @return the String representation of the subjectKeyIdentifier
* @throws IOException
*/
@ -293,6 +394,7 @@ public class CredentialParser {
/**
* This method returns the subjectKeyIdentifier from a given X509Certificate.
*
* @param certificate the cert to pull the subjectKeyIdentifier from
* @return the String representation of the subjectKeyIdentifier
* @throws IOException

View File

@ -1,7 +1,8 @@
package hirs.swid;
import hirs.swid.utils.Commander;
import com.beust.jcommander.JCommander;
import hirs.swid.utils.Commander;
import hirs.swid.utils.CredentialArgumentValidator;
import hirs.swid.utils.TimestampArgumentValidator;
import java.util.List;
@ -14,6 +15,7 @@ public class Main {
jc.parse(args);
SwidTagGateway gateway;
SwidTagValidator validator;
CredentialArgumentValidator caValidator;
if (commander.isHelp()) {
jc.usage();
@ -26,28 +28,28 @@ public class Main {
String rimel = commander.getRimEventLog();
String certificateFile = commander.getPublicCertificate();
String trustStore = commander.getTruststoreFile();
if (!verifyFile.isEmpty()) {
if (!rimel.isEmpty()) {
boolean defaultKey = commander.isDefaultKey();
validator.setRimEventLog(rimel);
}
if (!trustStore.isEmpty()) {
validator.setTrustStoreFile(trustStore);
}
if (!certificateFile.isEmpty()) {
System.out.println("A single cert cannot be used for verification. " +
"The signing cert will be searched for in the trust store.");
}
validator.validateSwidTag(verifyFile);
if (defaultKey) {
validator.validateSwidTag(verifyFile, "DEFAULT");
} else {
System.out.println("Need a RIM file to validate!");
caValidator = new CredentialArgumentValidator(trustStore,
certificateFile, "", "", "", true);
if (caValidator.isValid()) {
validator.setTrustStoreFile(trustStore);
validator.validateSwidTag(verifyFile, caValidator.getFormat());
} else {
System.out.println("Invalid combination of credentials given: "
+ caValidator.getErrorMessage());
System.exit(1);
}
}
} else {
gateway = new SwidTagGateway();
System.out.println(commander.toString());
String createType = commander.getCreateType().toUpperCase();
String attributesFile = commander.getAttributesFile();
String jksTruststoreFile = commander.getTruststoreFile();
String truststoreFile = commander.getTruststoreFile();
String certificateFile = commander.getPublicCertificate();
String privateKeyFile = commander.getPrivateKeyFile();
boolean embeddedCert = commander.isEmbedded();
@ -58,30 +60,27 @@ public class Main {
if (!attributesFile.isEmpty()) {
gateway.setAttributesFile(attributesFile);
}
if (!jksTruststoreFile.isEmpty()) {
if (defaultKey) {
gateway.setDefaultCredentials(true);
gateway.setJksTruststoreFile(jksTruststoreFile);
} else if (!certificateFile.isEmpty() && !privateKeyFile.isEmpty()) {
gateway.setTruststoreFile(SwidTagConstants.DEFAULT_KEYSTORE_FILE);
} else {
gateway.setDefaultCredentials(false);
caValidator = new CredentialArgumentValidator(truststoreFile,
certificateFile, privateKeyFile, "", "", false);
if (caValidator.isValid()) {
gateway.setTruststoreFile(truststoreFile);
gateway.setPemCertificateFile(certificateFile);
gateway.setPemPrivateKeyFile(privateKeyFile);
} else {
System.out.println("Invalid combination of credentials given: "
+ caValidator.getErrorMessage());
System.exit(1);
}
if (embeddedCert) {
gateway.setEmbeddedCert(true);
}
} else if (defaultKey){
gateway.setDefaultCredentials(true);
gateway.setJksTruststoreFile(SwidTagConstants.DEFAULT_KEYSTORE_FILE);
} else {
System.out.println("A private key (-k) and public certificate (-p) " +
"are required, or the default key (-d) must be indicated.");
System.exit(1);
}
if (rimEventLog.isEmpty()) {
System.out.println("Error: a support RIM is required!");
System.exit(1);
} else {
gateway.setRimEventLog(rimEventLog);
}
List<String> timestampArguments = commander.getTimestampArguments();
if (timestampArguments.size() > 0) {
if (new TimestampArgumentValidator(timestampArguments).isValid()) {

View File

@ -8,13 +8,12 @@ import javax.xml.namespace.QName;
* This class contains the String constants that are referenced by the gateway
* class. It is expected that member properties of this class will expand as
* more functionality is added to SwidTagGateway.
*
*/
public class SwidTagConstants {
public static final String DEFAULT_KEYSTORE_FILE = "/opt/hirs/rimtool/keystore.jks";
public static final String DEFAULT_KEYSTORE_FILE = "keystore.jks";//"/opt/hirs/rimtool/keystore.jks";
public static final String DEFAULT_KEYSTORE_PASSWORD = "password";
public static final String DEFAULT_PRIVATE_KEY_ALIAS = "selfsigned";
public static final String DEFAULT_PRIVATE_KEY_ALIAS = "1";
public static final String DEFAULT_ATTRIBUTES_FILE = "/opt/hirs/rimtool/rim_fields.json";
public static final String DEFAULT_ENGLISH = "en";

View File

@ -84,7 +84,7 @@ public class SwidTagGateway {
private Marshaller marshaller;
private String attributesFile;
private boolean defaultCredentials;
private String jksTruststoreFile;
private String truststoreFile;
private String pemPrivateKeyFile;
private String pemCertificateFile;
private boolean embeddedCert;
@ -102,6 +102,7 @@ public class SwidTagGateway {
marshaller = jaxbContext.createMarshaller();
attributesFile = SwidTagConstants.DEFAULT_ATTRIBUTES_FILE;
defaultCredentials = true;
truststoreFile = "";
pemCertificateFile = "";
embeddedCert = false;
rimEventLog = "";
@ -133,12 +134,12 @@ public class SwidTagGateway {
}
/**
* Setter for JKS keystore file
* Setter for keystore file
*
* @param jksTruststoreFile
* @param truststoreFile
*/
public void setJksTruststoreFile(final String jksTruststoreFile) {
this.jksTruststoreFile = jksTruststoreFile;
public void setTruststoreFile(final String truststoreFile) {
this.truststoreFile = truststoreFile;
}
/**
@ -179,6 +180,7 @@ public class SwidTagGateway {
/**
* Setter for timestamp format in XML signature
*
* @param timestampFormat
*/
public void setTimestampFormat(String timestampFormat) {
@ -187,6 +189,7 @@ public class SwidTagGateway {
/**
* Setter for timestamp input - RFC3852 + file or RFC3339 + value
*
* @param timestampArgument
*/
public void setTimestampArgument(String timestampArgument) {
@ -531,6 +534,7 @@ public class SwidTagGateway {
addNonNullAttribute(attributes, key, value);
}
}
/**
* This utility method checks if an attribute value is empty before adding it to the map.
*
@ -593,14 +597,19 @@ public class SwidTagGateway {
PrivateKey privateKey;
CredentialParser cp = new CredentialParser();
if (defaultCredentials) {
cp.parseJKSCredentials(jksTruststoreFile);
cp.parseDefaultCredentials();
privateKey = cp.getPrivateKey();
KeyName keyName = kiFactory.newKeyName(cp.getCertificateSubjectKeyIdentifier());
keyInfoElements.add(keyName);
} else {
if (!truststoreFile.isEmpty()) {
List<X509Certificate> truststore = cp.parseCertsFromPEM(truststoreFile);
cp.parsePEMCredentials(truststore, pemPrivateKeyFile);
} else {
cp.parsePEMCredentials(pemCertificateFile, pemPrivateKeyFile);
X509Certificate certificate = cp.getCertificate();
}
privateKey = cp.getPrivateKey();
X509Certificate certificate = cp.getCertificate();
if (embeddedCert) {
ArrayList<Object> x509Content = new ArrayList<Object>();
x509Content.add(certificate.getSubjectX500Principal().getName());
@ -608,6 +617,8 @@ public class SwidTagGateway {
X509Data data = kiFactory.newX509Data(x509Content);
keyInfoElements.add(data);
} else {
KeyName keyName = kiFactory.newKeyName(cp.getCertificateSubjectKeyIdentifier());
keyInfoElements.add(keyName);
keyInfoElements.add(kiFactory.newKeyValue(certificate.getPublicKey()));
}
}
@ -646,6 +657,7 @@ public class SwidTagGateway {
/**
* This method creates a timestamp element and populates it with data according to
* the RFC format set in timestampFormat. The element is returned within an XMLObject.
*
* @param doc the Document representing the XML to be signed
* @param sigFactory the SignatureFactory object
* @return an XMLObject containing the timestamp element

View File

@ -36,7 +36,6 @@ import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
@ -74,6 +73,7 @@ public class SwidTagValidator {
/**
* Setter for rimel file path.
*
* @param rimEventLog the rimel file
*/
public void setRimEventLog(String rimEventLog) {
@ -82,6 +82,7 @@ public class SwidTagValidator {
/**
* Setter for the truststore file path.
*
* @param trustStoreFile the truststore
*/
public void setTrustStoreFile(String trustStoreFile) {
@ -99,6 +100,7 @@ public class SwidTagValidator {
System.out.println("Error initializing JAXBContext: " + e.getMessage());
}
}
/**
* This method validates the .swidtag file at the given filepath against the
* schema. A successful validation results in the output of the tag's name
@ -106,9 +108,10 @@ public class SwidTagValidator {
*
* @param path the location of the file to be validated
*/
public boolean validateSwidTag(String path) {
public boolean validateSwidTag(String path, String format) {
Document document = unmarshallSwidTag(path);
Element softwareIdentity = (Element) document.getElementsByTagName("SoftwareIdentity").item(0);
Element softwareIdentity =
(Element) document.getElementsByTagName("SoftwareIdentity").item(0);
StringBuilder si = new StringBuilder("Base RIM detected:\n");
si.append("SoftwareIdentity name: " + softwareIdentity.getAttribute("name") + "\n");
si.append("SoftwareIdentity tagId: " + softwareIdentity.getAttribute("tagId") + "\n");
@ -120,8 +123,14 @@ public class SwidTagValidator {
System.out.println(e.getMessage());
return false;
}
System.out.println("Signature core validity: " + validateSignedXMLDocument(document));
boolean swidtagValidity = validateSignedXMLDocument(document, format);
if (swidtagValidity) {
System.out.println("Signature core validity: true");
return true;
} else {
System.out.println("Signature core validity: false");
return false;
}
}
/**
@ -153,15 +162,22 @@ public class SwidTagValidator {
* Next, the signature is inspected for two things:
* 1. valid signature
* 2. valid certificate chain
*
* @param doc XML document
* @return true if both the signature and cert chain are valid; false otherwise
*/
private boolean validateSignedXMLDocument(Document doc) {
private boolean validateSignedXMLDocument(Document doc, String credentialFormat) {
try {
DOMValidateContext context;
CredentialParser cp = new CredentialParser();
X509Certificate signingCert = null;
switch (credentialFormat) {
case "DEFAULT":
trustStore = cp.parseDefaultCredentials();
break;
case "PEM":
trustStore = cp.parseCertsFromPEM(trustStoreFile);
}
X509KeySelector keySelector = new X509KeySelector();
NodeList nodes = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nodes.getLength() == 0) {
@ -204,8 +220,6 @@ public class SwidTagValidator {
cp.setCertificate(signingCert);
System.out.println(System.lineSeparator() + cp.getCertificateAuthorityInfoAccess());
return signatureIsValid;
} catch (FileNotFoundException e) {
System.out.println("Error parsing truststore: " + e.getMessage());
} catch (NoSuchAlgorithmException e) {
System.out.println("Error instantiating a KeyFactory to generate pk: "
+ e.getMessage());
@ -214,7 +228,7 @@ public class SwidTagValidator {
} catch (MarshalException | XMLSignatureException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return false;
@ -239,6 +253,7 @@ public class SwidTagValidator {
* This method extracts a public key from either an X509Certificate element
* or a KeyValue element. If the public key's algorithm matches the declared
* algorithm it is returned in a KeySelecctorResult.
*
* @param keyinfo the KeyInfo element
* @param purpose
* @param algorithm the encapsulating signature's declared signing algorithm
@ -302,6 +317,7 @@ public class SwidTagValidator {
/**
* This method checks that the signature and public key algorithms match.
*
* @param uri to match the signature algorithm
* @param name to match the public key algorithm
* @return true if both match, false otherwise
@ -314,6 +330,7 @@ public class SwidTagValidator {
/**
* This method validates the cert chain for a given certificate. The truststore is iterated
* over until a root CA is found, otherwise an error is returned.
*
* @param cert the certificate at the start of the chain
* @return true if the chain is valid
* @throws Exception if a valid chain is not found in the truststore
@ -356,6 +373,7 @@ public class SwidTagValidator {
/**
* This method checks if cert's issuerDN matches issuer's subjectDN.
*
* @param cert the signed certificate
* @param issuer the signing certificate
* @return true if they match, false if not
@ -372,6 +390,7 @@ public class SwidTagValidator {
/**
* This method checks if cert's signature matches signer's public key.
*
* @param cert the signed certificate
* @param signer the signing certificate
* @return true if they match
@ -404,6 +423,7 @@ public class SwidTagValidator {
/**
* This method checks if a given certificate is self signed or not.
*
* @param cert the cert to check
* @return true if self signed, false if not
*/
@ -413,6 +433,7 @@ public class SwidTagValidator {
/**
* This method compares a public key against those in the truststore.
*
* @param pk a public key
* @return true if pk is found in the trust store, false otherwise
*/
@ -485,6 +506,7 @@ public class SwidTagValidator {
/**
* This method strips all whitespace from an xml file, including indents and spaces
* added for human-readability.
*
* @param path to the xml file
* @return Document object without whitespace
*/

View File

@ -43,9 +43,9 @@ public class Commander {
description = "Embed the provided certificate in the signed swidtag.")
private boolean embedded = false;
@Parameter(names = {"-d", "--default-key"}, order = 8,
description = "Use default signing credentials.")
description = "Use keystore.jks from the rimtool installation to sign.")
private boolean defaultKey = false;
@Parameter(names = {"-l", "--rimel <path>"}, order = 9,
@Parameter(names = {"-l", "--rimel <path>"}, order = 9, required = true,
description = "The TCG eventlog file to use as a support RIM.")
private String rimEventLog = "";
@Parameter(names = {"--timestamp"}, order = 10, variableArity = true,
@ -74,7 +74,9 @@ public class Commander {
return verifyFile;
}
public String getTruststoreFile() { return truststoreFile; }
public String getTruststoreFile() {
return truststoreFile;
}
public String getPrivateKeyFile() {
return privateKeyFile;
@ -84,11 +86,17 @@ public class Commander {
return publicCertificate;
}
public boolean isEmbedded() { return embedded; }
public boolean isEmbedded() {
return embedded;
}
public boolean isDefaultKey() { return defaultKey; }
public boolean isDefaultKey() {
return defaultKey;
}
public String getRimEventLog() { return rimEventLog; }
public String getRimEventLog() {
return rimEventLog;
}
public List<String> getTimestampArguments() {
return timestampArguments;
@ -119,25 +127,22 @@ public class Commander {
return sb.toString();
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Creating: " + this.getCreateType() + System.lineSeparator());
sb.append("Using attributes file: " + this.getAttributesFile() + System.lineSeparator());
sb.append("Write to: " + this.getOutFile() + System.lineSeparator());
sb.append("Verify file: " + this.getVerifyFile() + System.lineSeparator());
if (!this.getTruststoreFile().isEmpty()) {
if (this.isDefaultKey()) {
sb.append("Truststore file: default (" + SwidTagConstants.DEFAULT_KEYSTORE_FILE + ")"
+ System.lineSeparator());
} else {
sb.append("Truststore file: " + this.getTruststoreFile() + System.lineSeparator());
} else if (!this.getPrivateKeyFile().isEmpty() &&
!this.getPublicCertificate().isEmpty()) {
sb.append("Private key file: " + this.getPrivateKeyFile() + System.lineSeparator());
sb.append("Public certificate: " + this.getPublicCertificate()
+ System.lineSeparator());
sb.append("Embedded certificate: " + this.isEmbedded() + System.lineSeparator());
} else if (this.isDefaultKey()){
sb.append("Truststore file: default (" + SwidTagConstants.DEFAULT_KEYSTORE_FILE + ")"
+ System.lineSeparator());
} else {
sb.append("Signing credential: (none given)" + System.lineSeparator());
}
sb.append("Event log support RIM: " + this.getRimEventLog() + System.lineSeparator());
List<String> timestampArguments = this.getTimestampArguments();

View File

@ -0,0 +1,79 @@
package hirs.swid.utils;
public class CredentialArgumentValidator {
private String truststoreFile;
private String certificateFile;
private String privateKeyFile;
private String password;
private String alias;
private String format;
private boolean isValidating;
private String errorMessage;
private static final String JKS = "JKS";
private static final String PEM = "PEM";
public CredentialArgumentValidator(String truststoreFile,
String certificateFile,
String privateKeyFile,
String password,
String alias,
boolean isValidating) {
this.truststoreFile = truststoreFile;
this.certificateFile = certificateFile;
this.privateKeyFile = privateKeyFile;
this.password = password;
this.alias = alias;
this.isValidating = isValidating;
errorMessage = "";
}
/**
* Getter for format property
*
* @return string
*/
public String getFormat() {
return format;
}
/**
* Getter for error message
*
* @return string
*/
public String getErrorMessage() {
return errorMessage;
}
/**
* This method checks for the following valid configurations of input arguments:
* 1. truststore + password + alias (JKS format)
* 2. truststore + private key (PEM format)
* 3. truststore only for validating (PEM format)
* 4. certificate + private key (PEM format)
* 5. certificate only for validating (PEM format)
*
* @return true if the above are found, false otherwise
*/
public boolean isValid() {
if (!truststoreFile.isEmpty()) {
if (!password.isEmpty() && !alias.isEmpty()) {
format = JKS;
return true;
} else if (!privateKeyFile.isEmpty() || isValidating) {
format = PEM;
return true;
} else {
errorMessage = "A JKS truststore needs a password and alias; " +
"a PEM truststore needs a private key file.";
return false;
}
} else if (!certificateFile.isEmpty() && !privateKeyFile.isEmpty()) {
format = PEM;
return true;
} else {
errorMessage = "A public certificate must be accompanied by a private key file.";
return false;
}
}
}

View File

@ -11,6 +11,7 @@ import java.util.regex.Pattern;
public class TimestampArgumentValidator {
List<String> args;
/**
* This class handles validation of the --timestamp commandline parameter.
* Currently only RFC3339 and RFC3852 formats are supported.

View File

@ -1,21 +1,24 @@
package hirs.swid;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
public class TestSwidTagGateway {
private SwidTagGateway gateway;
private SwidTagValidator validator;
private final String JKS = "JKS";
private final String PEM = "PEM";
private final String DEFAULT_OUTPUT = "generated_swidTag.swidtag";
private final String BASE_USER_CERT = "generated_user_cert.swidtag";
private final String BASE_USER_CERT_EMBED = "generated_user_cert_embed.swidtag";
private final String BASE_TRUSTSTORE_EMBED = "generated_truststore_embed.swidtag";
private final String BASE_DEFAULT_CERT = "generated_default_cert.swidtag";
private final String BASE_RFC3339_TIMESTAMP = "generated_timestamp_rfc3339.swidtag";
private final String BASE_RFC3852_TIMESTAMP = "generated_timestamp_rfc3852.swidtag";
@ -58,7 +61,7 @@ public class TestSwidTagGateway {
* where RimSignCert.pem has the AIA extension.
*/
@Test
public void testCreateBaseUserCertNotEmbedded() {
public void testCreateBasePemCertNotEmbedded() {
gateway.setDefaultCredentials(false);
gateway.setPemCertificateFile(SIGNING_CERT_FILE);
gateway.setPemPrivateKeyFile(PRIVATE_KEY_FILE);
@ -67,7 +70,7 @@ public class TestSwidTagGateway {
expectedFile = TestSwidTagGateway.class.getClassLoader()
.getResourceAsStream(BASE_USER_CERT);
Assert.assertTrue(compareFileBytesToExpectedFile(DEFAULT_OUTPUT));
Assert.assertTrue(validator.validateSwidTag(DEFAULT_OUTPUT));
Assert.assertTrue(validator.validateSwidTag(DEFAULT_OUTPUT, PEM));
}
/**
@ -77,8 +80,9 @@ public class TestSwidTagGateway {
* -v [base RIM] -l TpmLog.bin -t RimCertChain.pem
*/
@Test
public void testCreateBaseUserCertEmbedded() {
public void testCreateBasePemCertEmbedded() {
gateway.setDefaultCredentials(false);
gateway.setTruststoreFile("");
gateway.setPemCertificateFile(SIGNING_CERT_FILE);
gateway.setPemPrivateKeyFile(PRIVATE_KEY_FILE);
gateway.setEmbeddedCert(true);
@ -86,7 +90,27 @@ public class TestSwidTagGateway {
expectedFile = TestSwidTagGateway.class.getClassLoader()
.getResourceAsStream(BASE_USER_CERT_EMBED);
Assert.assertTrue(compareFileBytesToExpectedFile(DEFAULT_OUTPUT));
Assert.assertTrue(validator.validateSwidTag(DEFAULT_OUTPUT));
Assert.assertTrue(validator.validateSwidTag(DEFAULT_OUTPUT, PEM));
}
/**
* This test corresponds to:
* -c base -l TpmLog.bin -t RimCertChain.pem -k privateRimKey.pem -e
* And then validates it:
* -v [base RIM] -l TpmLog.bin -t RimCertChain.pem
*/
@Test
public void testCreateBasePemTruststoreEmbedded() {
gateway.setDefaultCredentials(false);
gateway.setTruststoreFile(CA_CHAIN_FILE);
gateway.setPemCertificateFile("");
gateway.setPemPrivateKeyFile(PRIVATE_KEY_FILE);
gateway.setEmbeddedCert(true);
gateway.generateSwidTag(DEFAULT_OUTPUT);
expectedFile = TestSwidTagGateway.class.getClassLoader()
.getResourceAsStream(BASE_TRUSTSTORE_EMBED);
Assert.assertTrue(compareFileBytesToExpectedFile(DEFAULT_OUTPUT));
Assert.assertTrue(validator.validateSwidTag(DEFAULT_OUTPUT, PEM));
}
/**
@ -96,12 +120,12 @@ public class TestSwidTagGateway {
@Test
public void testCreateBaseDefaultCert() {
gateway.setDefaultCredentials(true);
gateway.setJksTruststoreFile(JKS_KEYSTORE_FILE);
gateway.setTruststoreFile(JKS_KEYSTORE_FILE);
gateway.generateSwidTag(DEFAULT_OUTPUT);
expectedFile = TestSwidTagGateway.class.getClassLoader()
.getResourceAsStream(BASE_DEFAULT_CERT);
Assert.assertTrue(compareFileBytesToExpectedFile(DEFAULT_OUTPUT));
Assert.assertTrue(validator.validateSwidTag(DEFAULT_OUTPUT));
Assert.assertTrue(validator.validateSwidTag(DEFAULT_OUTPUT, "DEFAULT"));
}
/**
@ -111,14 +135,14 @@ public class TestSwidTagGateway {
@Test
public void testCreateTimestampRfc3339() {
gateway.setDefaultCredentials(true);
gateway.setJksTruststoreFile(JKS_KEYSTORE_FILE);
gateway.setTruststoreFile(JKS_KEYSTORE_FILE);
gateway.setTimestampFormat("RFC3339");
gateway.setTimestampArgument("2023-01-01T00:00:00Z");
gateway.generateSwidTag(DEFAULT_OUTPUT);
expectedFile = TestSwidTagGateway.class.getClassLoader()
.getResourceAsStream(BASE_RFC3339_TIMESTAMP);
Assert.assertTrue(compareFileBytesToExpectedFile(DEFAULT_OUTPUT));
Assert.assertTrue(validator.validateSwidTag(DEFAULT_OUTPUT));
Assert.assertTrue(validator.validateSwidTag(DEFAULT_OUTPUT, "DEFAULT"));
}
/**
@ -128,30 +152,19 @@ public class TestSwidTagGateway {
@Test
public void testCreateTimestampRfc3852() {
gateway.setDefaultCredentials(true);
gateway.setJksTruststoreFile(JKS_KEYSTORE_FILE);
gateway.setTruststoreFile(JKS_KEYSTORE_FILE);
gateway.setTimestampFormat("RFC3852");
gateway.setTimestampArgument(RFC3852_COUNTERSIGNATURE_FILE);
gateway.generateSwidTag(DEFAULT_OUTPUT);
expectedFile = TestSwidTagGateway.class.getClassLoader()
.getResourceAsStream(BASE_RFC3852_TIMESTAMP);
Assert.assertTrue(compareFileBytesToExpectedFile(DEFAULT_OUTPUT));
Assert.assertTrue(validator.validateSwidTag(DEFAULT_OUTPUT));
}
/**
* This test corresponds to the arguments:
* -v <path>
*/
public void testValidateSwidTag() {
String filepath = TestSwidTagGateway.class.getClassLoader()
.getResource(BASE_USER_CERT).getPath();
System.out.println("Validating file at " + filepath);
Assert.assertTrue(validator.validateSwidTag(filepath));
Assert.assertTrue(validator.validateSwidTag(DEFAULT_OUTPUT, "DEFAULT"));
}
/**
* This method compares two files by bytes to determine if they are the same or not.
*
* @param file to be compared to the expected value.
* @return true if they are equal, false if not.
*/

View File

@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<SoftwareIdentity xmlns="http://standards.iso.org/iso/19770/-2/2015/schema.xsd" xmlns:ns2="http://www.w3.org/2000/09/xmldsig#" corpus="false" name="Example.com BIOS" patch="false" supplemental="false" tagId="94f6b457-9ac9-4d35-9b3f-78804173b65as" tagVersion="0" version="01" versionScheme="multipartnumeric" xml:lang="en">
<Entity name="Example Inc" regid="http://Example.com" role="softwareCreator tagCreator"/>
<Link href="https://Example.com/support/ProductA/firmware/installfiles" rel="installationmedia"/>
<Meta xmlns:n8060="http://csrc.nist.gov/ns/swid/2015-extensions/1.0" xmlns:rim="https://trustedcomputinggroup.org/wp-content/uploads/TCG_RIM_Model" n8060:colloquialVersion="Firmware_2019" n8060:edition="12" n8060:product="ProductA" n8060:revision="r2" rim:PayloadType="direct" rim:bindingSpec="PC Client RIM" rim:bindingSpecVersion="1.2" rim:firmwareManufacturerId="00213022" rim:firmwareManufacturerStr="BIOSVendorA" rim:firmwareModel="A0" rim:firmwareVersion="12" rim:pcURIGlobal="https://Example.com/support/ProductA/" rim:pcURIlocal="/boot/tcg/manifest/switag/" rim:platformManufacturerId="00201234" rim:platformManufacturerStr="Example.com" rim:platformModel="ProductA" rim:platformVersion="01"/>
<Payload>
<Directory name="rim">
<File xmlns:SHA256="http://www.w3.org/2001/04/xmlenc#sha256" SHA256:hash="4479ca722623f8c47b703996ced3cbd981b06b1ae8a897db70137e0b7c546848" name="Example.com.BIOS.01.rimel" size="7549"/>
</Directory>
</Payload>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
<Reference URI="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
<DigestValue>DJMc0n3VHHwU+F3HNpiY/l3EMcjRZAQOYlrjhD5v9qE=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>ojJ6v8ToxLWWekCKmBoZ+Yg2V4MYMPbKB9FjDs/QG/AMP+LKjnb55Z7FSLhC8+CvvShKPAoS9mv1&#13;
QepwI17NEqbfnC1U4WH0u578A3J6wiHMXIDnIQqKAAXb8v2c/wjMDArzFl8CXmDA7HUDIt+3C4VC&#13;
tA598YY7o0Hf6hK5qO8oWGQxXUKfpUwvtGLxHpbDWYFuVSPa+uk6OTzutt/QyzTERzxyO9Le1i6K&#13;
nrpzh4lgHn6EfGs6HR1ffdHQ069q0bE61zDx0VC18nK9DmszW6p6FlMzApiTVW/4PiVt+dSFeVGR&#13;
9///OdtxcoBCeofDDFPRyO+s+kY1pXd92Q3nfg==</SignatureValue>
<KeyInfo>
<X509Data>
<X509SubjectName>CN=example.RIM.signer,OU=PCClient,O=Example,ST=VA,C=US</X509SubjectName>
<X509Certificate>MIIDoTCCAomgAwIBAgIJAIKly+6bklZlMA0GCSqGSIb3DQEBCwUAMFMxCzAJBgNVBAYTAlVTMQsw&#13;
CQYDVQQIDAJWQTEQMA4GA1UECgwHRXhhbXBsZTERMA8GA1UECwwIUENDbGllbnQxEjAQBgNVBAMM&#13;
CUV4YW1wbGVDQTAeFw0yMDA2MTExNjUzMDFaFw0zMDA0MjAxNjUzMDFaMFwxCzAJBgNVBAYTAlVT&#13;
MQswCQYDVQQIDAJWQTEQMA4GA1UECgwHRXhhbXBsZTERMA8GA1UECwwIUENDbGllbnQxGzAZBgNV&#13;
BAMMEmV4YW1wbGUuUklNLnNpZ25lcjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKd1&#13;
lWGkSRuxAAY2wHag2GVxUk1dZx2PTpfQOflvLeccAVwa8mQhlsRERq+QK8ilj8Xfqs44/nBaccZD&#13;
OjdfIxIUCMfwhGXjxCaqZbgTucNsExDnu4arTGraoAwzHg0cVLiKT/Cxj9NL4dcMgxRXsPdHfXb0&#13;
923C7xYd2t2qfW05umgaj7qeQl6c68CFNsGX4JA8rWFQZvvGx5DGlK4KTcjPuQQINs5fxasNKqLY&#13;
2hq+z82x/rqwr2hmyizD6FpFSyIABPEMPfB036GEhRwu1WEMkq8yIp2jgRUoFYke9pB3ph9pVow0&#13;
Hh4mNFSKD4pP41VSKY1nus83mdkuukPy5o0CAwEAAaNvMG0wHQYDVR0OBBYEFC/euOfQMKIgnaoB&#13;
hhqWT+3s8rzBMB8GA1UdIwQYMBaAFEahuO3bpnFf0NLneoo8XW6aw5Y4MAkGA1UdEwQCMAAwCwYD&#13;
VR0PBAQDAgbAMBMGA1UdJQQMMAoGCCsGAQUFBwMDMA0GCSqGSIb3DQEBCwUAA4IBAQC1mG0naE0W&#13;
4E9vujPhygf7LXHMFkMPs5uWyvkxe4zWgTg0RHTClbOFJQJ+pGLOcthSG6vIC6xYJxT5EKtB9rzR&#13;
lEYHOi4MxuwXz9rLWQhA2zdbSo54Fb/BPoca5K9kxvAanRltEfqEFhCcRmqIX1i6mpOWiZsrdMs7&#13;
IflHKBsylUTn+v636BAz3p2H8/lpJbF4LUFUxFU5FWB3tLuasxYTsbeE6YyNAnQIS95ML7c5H8z2&#13;
aEQs5TCNHZJDyc0PZT2aPOuEj5lGv9oyBHbYDitszUWSVxF7z86uVGmYR/2oTIj6tqb+IwuvFtnO&#13;
wiXFRS5ctLCdESr3SjdQF5wmIN4n</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
</SoftwareIdentity>

View File

@ -26,6 +26,7 @@ tA598YY7o0Hf6hK5qO8oWGQxXUKfpUwvtGLxHpbDWYFuVSPa+uk6OTzutt/QyzTERzxyO9Le1i6K&#13
nrpzh4lgHn6EfGs6HR1ffdHQ069q0bE61zDx0VC18nK9DmszW6p6FlMzApiTVW/4PiVt+dSFeVGR&#13;
9///OdtxcoBCeofDDFPRyO+s+kY1pXd92Q3nfg==</SignatureValue>
<KeyInfo>
<KeyName>2fdeb8e7d030a2209daa01861a964fedecf2bcc1</KeyName>
<KeyValue>
<RSAKeyValue>
<Modulus>p3WVYaRJG7EABjbAdqDYZXFSTV1nHY9Ol9A5+W8t5xwBXBryZCGWxERGr5AryKWPxd+qzjj+cFpx&#13;