Applied checkstyles config to rimtool files

This commit is contained in:
chubtub 2024-11-13 14:03:11 -05:00
parent 9c0ff0384f
commit 198d6a54b8
10 changed files with 155 additions and 154 deletions

View File

@ -1,9 +1,9 @@
package hirs.swid;
import com.beust.jcommander.JCommander;
import hirs.swid.utils.Commander;
import hirs.swid.utils.TimestampArgumentValidator;
import hirs.utils.rim.ReferenceManifestValidator;
import com.beust.jcommander.JCommander;
import lombok.extern.log4j.Log4j2;
import java.io.File;
@ -13,6 +13,7 @@ import java.nio.file.Paths;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Log4j2
public class Main {
@ -33,7 +34,7 @@ public class Main {
for (String opt : unknownOpts) {
sb.append(opt + ", ");
}
exitWithErrorCode(sb.substring(0,sb.lastIndexOf(",")));
exitWithErrorCode(sb.substring(0, sb.lastIndexOf(",")));
} else if (commander.isHelp()) {
jc.usage();
System.out.println(commander.printHelpExamples());
@ -79,7 +80,7 @@ public class Main {
case "BASE":
gateway.setAttributesFile(attributesFile);
gateway.setRimEventLog(rimEventLog);
if (defaultKey){
if (defaultKey) {
gateway.setDefaultCredentials(true);
gateway.setJksTruststoreFile(SwidTagConstants.DEFAULT_KEYSTORE_FILE);
} else {

View File

@ -8,7 +8,6 @@ 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 {
@ -49,7 +48,7 @@ public class SwidTagConstants {
public static final String ROLE = "role";
public static final String THUMBPRINT = "thumbprint";
public static final String HREF = "href";
public static final String REL = "rel";
public static final String REL = "rel";
public static final String COLLOQUIAL_VERSION = "colloquialVersion";
public static final String EDITION = "edition";
public static final String PRODUCT = "product";
@ -78,12 +77,12 @@ public class SwidTagConstants {
public static final String SUPPORT_RIM_FORMAT_MISSING = "supportRIMFormat missing";
public static final String SUPPORT_RIM_URI_GLOBAL = "supportRIMURIGlobal";
public static final String DATETIME = "dateTime";
public static final String NIST_NS = "http://csrc.nist.gov/ns/swid/2015-extensions/1.0";
public static final String TCG_NS = "https://trustedcomputinggroup.org/wp-content/uploads/TCG_RIM_Model";
public static final String TCG_NS = "https://trustedcomputinggroup.org/wp-content/uploads/TCG_RIM_Model";
public static final String RFC3852_NS = "https://www.ietf.org/rfc/rfc3852.txt";
public static final String RFC3339_NS = "https://www.ietf.org/rfc/rfc3339.txt";
public static final String N8060_PFX = "n8060";
public static final String RIM_PFX = "rim";
public static final String RFC3852_PFX = "rcf3852";
@ -125,7 +124,7 @@ public class SwidTagConstants {
TCG_NS, PC_URI_LOCAL, RIM_PFX);
public static final QName _PC_URI_GLOBAL = new QName(
TCG_NS, PC_URI_GLOBAL, RIM_PFX);
public static final QName _RIM_LINK_HASH = new QName(
public static final QName _RIM_LINK_HASH = new QName(
TCG_NS, RIM_LINK_HASH, RIM_PFX);
public static final QName _SUPPORT_RIM_TYPE = new QName(
TCG_NS, SUPPORT_RIM_TYPE, RIM_PFX);

View File

@ -15,54 +15,54 @@ import java.util.List;
public class Commander {
@Parameter(description = "This parameter catches all unrecognized arguments.")
private List<String> unknownOptions = new ArrayList<>();
@Parameter(names = {"-h", "--help"}, help = true, description = "Print this help text.")
private boolean help;
private final List<String> unknownOptions = new ArrayList<>();
@Parameter(names = {"-c", "--create"}, order = 0,
description = "The type of RIM to create. A base RIM will be created by default.")
private String createType = "";
private final String createType = "";
@Parameter(names = {"-v", "--verify"}, validateWith = FileArgumentValidator.class,
description = "Specify a RIM file to verify.")
private String verifyFile = "";
private final String verifyFile = "";
@Parameter(names = {"-V", "--version"}, description = "Output the current version.")
private boolean version = false;
private final boolean version = false;
@Parameter(names = {"-a", "--attributes"}, validateWith = FileArgumentValidator.class,
description = "The configuration file holding attributes "
+ "to populate the base RIM with. An example file can be found in /opt/rimtool/data.")
private String attributesFile = "";
+ "to populate the base RIM with. An example file can be found in /opt/rimtool/data.")
private final String attributesFile = "";
@Parameter(names = {"-o", "--out"}, order = 2,
description = "The file to write the RIM out to. "
+ "The RIM will be written to stdout by default.")
private String outFile = "";
+ "The RIM will be written to stdout by default.")
private final String outFile = "";
@Parameter(names = {"--verbose"}, description = "Control output verbosity.")
private boolean verbose = false;
private final boolean verbose = false;
@Parameter(names = {"-t", "--truststore"}, validateWith = FileArgumentValidator.class,
description = "The truststore to sign the base RIM created "
+ "or to validate the signed base RIM.")
private String truststoreFile = "";
+ "or to validate the signed base RIM.")
private final String truststoreFile = "";
@Parameter(names = {"-k", "--privateKeyFile"},
validateWith = FileArgumentValidator.class,
description = "The private key used to sign the base RIM created by this tool.")
private String privateKeyFile = "";
private final String privateKeyFile = "";
@Parameter(names = {"-p", "--publicCertificate"},
validateWith = FileArgumentValidator.class,
description = "The public key certificate to embed in the base RIM created by "
+ "this tool.")
private String publicCertificate = "";
+ "this tool.")
private final String publicCertificate = "";
@Parameter(names = {"-e", "--embed-cert"}, order = 7,
description = "Embed the provided certificate in the signed swidtag.")
private boolean embedded = false;
private final boolean embedded = false;
@Parameter(names = {"-d", "--default-key"}, order = 8,
description = "Use the JKS keystore installed in /opt/rimtool/data.")
private boolean defaultKey = false;
private final boolean defaultKey = false;
@Parameter(names = {"-l", "--rimel"}, validateWith = FileArgumentValidator.class,
description = "The TCG eventlog file to use as a support RIM.")
private String rimEventLog = "";
private final String rimEventLog = "";
@Parameter(names = {"--timestamp"}, order = 10, variableArity = true,
description = "Add a timestamp to the signature. " +
"Currently only RFC3339 and RFC3852 are supported:\n" +
"\tRFC3339 [yyyy-MM-ddThh:mm:ssZ]\n\tRFC3852 <counterSignature.bin>")
private List<String> timestampArguments = new ArrayList<String>(2);
private final List<String> timestampArguments = new ArrayList<String>(2);
@Parameter(names = {"-h", "--help"}, help = true, description = "Print this help text.")
private boolean help;
public List<String> getUnknownOptions() {
return unknownOptions;
@ -83,7 +83,11 @@ public class Commander {
public boolean isVersion() {
return version;
}
public boolean isVerbose() { return verbose; }
public boolean isVerbose() {
return verbose;
}
public String getAttributesFile() {
return attributesFile;
}
@ -92,7 +96,9 @@ public class Commander {
return outFile;
}
public String getTruststoreFile() { return truststoreFile; }
public String getTruststoreFile() {
return truststoreFile;
}
public String getPrivateKeyFile() {
return privateKeyFile;
@ -102,32 +108,38 @@ 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;
}
public String printHelpExamples() {
StringBuilder sb = new StringBuilder();
sb.append("Create a base RIM: use the values in attributes.json; ");
sb.append("add support_rim.bin to the payload; ");
sb.append("sign it using privateKey.pem and cert.pem; embed cert.pem in the signature; ");
sb.append("add a RFC3852 timestamp; and write the data to base_rim.swidtag:\n\n");
sb.append("\t\t-c base -a attributes.json -l support_rim.bin "
String sb = "Create a base RIM: use the values in attributes.json; " +
"add support_rim.bin to the payload; " +
"sign it using privateKey.pem and cert.pem; embed cert.pem in the signature; " +
"add a RFC3852 timestamp; and write the data to base_rim.swidtag:\n\n" +
"\t\t-c base -a attributes.json -l support_rim.bin "
+ "-k privateKey.pem -p cert.pem -e --timestamp RFC3852 counterSignature.bin "
+ "-o base_rim.swidtag\n\n\n");
sb.append("Validate base_rim.swidtag: "
+ "-o base_rim.swidtag\n\n\n" +
"Validate base_rim.swidtag: "
+ "the payload <File> is validated with support_rim.bin; "
+ "and the signature is validated with ca.crt:\n\n");
sb.append("\t\t-v base_rim.swidtag -l support_rim.bin -t ca.crt\n\n\n");
+ "and the signature is validated with ca.crt:\n\n" +
"\t\t-v base_rim.swidtag -l support_rim.bin -t ca.crt\n\n\n";
return sb.toString();
return sb;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Creating: " + this.getCreateType() + System.lineSeparator());
@ -137,12 +149,12 @@ public class Commander {
if (!this.getTruststoreFile().isEmpty()) {
sb.append("Truststore file: " + this.getTruststoreFile() + System.lineSeparator());
} else if (!this.getPrivateKeyFile().isEmpty() &&
!this.getPublicCertificate().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()){
} else if (this.isDefaultKey()) {
sb.append("Truststore file: default (" + SwidTagConstants.DEFAULT_KEYSTORE_FILE + ")"
+ System.lineSeparator());
} else {

View File

@ -18,15 +18,14 @@ public class CreateArgumentValidator implements IParametersValidator {
/**
* This method validates the input parameter map.
* @param parameters
* Name-value-pairs of all parameters (e.g. "-host":"localhost").
*
* @param parameters Name-value-pairs of all parameters (e.g. "-host":"localhost").
* @throws ParameterException
*/
@Override
public void validate(Map<String, Object> parameters) throws ParameterException {
if (isValueNotNull(parameters,"--create")) {
if (isValueNotNull(parameters,"--verify")) {
if (isValueNotNull(parameters, "--create")) {
if (isValueNotNull(parameters, "--verify")) {
throw new ParameterException("Create and verify cannot be called together.");
} else {
for (String arg : requiredArgs) {
@ -44,17 +43,14 @@ public class CreateArgumentValidator implements IParametersValidator {
/**
* This method checks the given key for a null value
*
* @param parameters map
* @param key the key to check
* @param key the key to check
* @return true if not null, else false
*/
private boolean isValueNotNull(Map<String, Object> parameters, String key) {
Object object = parameters.get(key);
if (object == null) {
return false;
} else {
return true;
}
return object != null;
}
private void validateSigningCredentials(Map<String, Object> parameters) {
@ -64,8 +60,8 @@ public class CreateArgumentValidator implements IParametersValidator {
errorMessage += "Too many signing credentials given, either choose --default-key OR " +
"provide --privateKeyFile and --publicCertificate";
} else if (!isValueNotNull(parameters, "--default-key") &&
!isValueNotNull(parameters, "--privateKeyFile") &&
!isValueNotNull(parameters, "--publicCertificate")) {
!isValueNotNull(parameters, "--privateKeyFile") &&
!isValueNotNull(parameters, "--publicCertificate")) {
errorMessage += "No signing credentials given, either choose --default-key OR " +
"provide --privateKeyFile and --publicCertificate";
} else {

View File

@ -1,13 +1,13 @@
package hirs.swid.utils;
public class CredentialArgumentValidator {
private String truststoreFile;
private String certificateFile;
private String privateKeyFile;
private String format;
private boolean isValidating;
private String errorMessage;
private static final String PEM = "PEM";
private final String truststoreFile;
private final String certificateFile;
private final String privateKeyFile;
private final boolean isValidating;
private String format;
private String errorMessage;
public CredentialArgumentValidator(String truststoreFile,
String certificateFile,
@ -62,11 +62,11 @@ public class CredentialArgumentValidator {
return true;
} else {
if (certificateFile.isEmpty()) {
errorMessage = "A public certificate must be specified by \'-p\' " +
errorMessage = "A public certificate must be specified by '-p' " +
"for signing operations.";
}
if (privateKeyFile.isEmpty()) {
errorMessage = "A private key must be specified by \'-k\' " +
errorMessage = "A private key must be specified by '-k' " +
"for signing operations.";
}
return false;

View File

@ -16,48 +16,17 @@ public class CsvParser {
private static final char DEFAULT_SEPARATOR = ',';
private static final char DEFAULT_QUOTE = '"';
private List<String> content;
private final List<String> content;
public CsvParser(final File file) {
this(file.getAbsolutePath());
}
public CsvParser(final String csvfile) {
content = readerCsv(csvfile);
}
/**
* This method takes an existing csv file and reads the file by line and
* adds the contents to a list of Strings.
*
* @param file valid path to a csv file
* @return
*/
private List<String> readerCsv(final String file) {
String line = "";
String csvSplitBy = ",";
List<String> tempList = new LinkedList<>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
while ((line = br.readLine()) != null) {
if (line.length() > 0
&& line.contains(csvSplitBy)) {
tempList.add(line);
}
}
} catch (IOException ioEx) {
System.out.println(String.format("Error reading in CSV file...(%s)", file));
System.exit(1);
}
return tempList;
}
public final List<String> getContent() {
return Collections.unmodifiableList(content);
}
public static List<String> parseLine(String csvLine) {
return parseLine(csvLine, DEFAULT_SEPARATOR, DEFAULT_QUOTE);
}
@ -133,4 +102,35 @@ public class CsvParser {
return result;
}
/**
* This method takes an existing csv file and reads the file by line and
* adds the contents to a list of Strings.
*
* @param file valid path to a csv file
* @return
*/
private List<String> readerCsv(final String file) {
String line = "";
String csvSplitBy = ",";
List<String> tempList = new LinkedList<>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
while ((line = br.readLine()) != null) {
if (line.length() > 0
&& line.contains(csvSplitBy)) {
tempList.add(line);
}
}
} catch (IOException ioEx) {
System.out.printf("Error reading in CSV file...(%s)%n", file);
System.exit(1);
}
return tempList;
}
public final List<String> getContent() {
return Collections.unmodifiableList(content);
}
}

View File

@ -2,9 +2,9 @@ package hirs.swid.utils;
import com.beust.jcommander.IParameterValidator;
import com.beust.jcommander.ParameterException;
import lombok.extern.log4j.Log4j2;
import java.io.File;
import lombok.extern.log4j.Log4j2;
/**
* This class validates arguments that take a String path to a file.

View File

@ -23,47 +23,30 @@ public class HashSwid {
/**
* Getter method for the hash that uses 256 bit hash
*
* @param filepath the file to hash.
* @return
* @return
*/
public static String get256Hash(String filepath) throws Exception {
return getHashValue(filepath, SHA256);
}
/**
* Getter method for the hash that uses 384 bit hash
* @param filepath the file to hash.
* @return
*/
public String get384Hash(String filepath) throws Exception {
return getHashValue(filepath, SHA384);
}
/**
* Getter method for the hash that uses 512 bit hash
* @param filepath the file to hash.
* @return
*/
public String get512Hash(String filepath) throws Exception {
return getHashValue(filepath, SHA512);
}
/**
* This method creates the hash based on the provided algorithm
* only accessible through helper methods.
*
* <p>
* This method assumes an input file that is small enough to read in its
* entirety. Large files should be handled similarly to the public static
* getHashValue() below.
*
*
* @param filepath file contents to hash
* @param sha the algorithm to use for the hash
* @return
* @param sha the algorithm to use for the hash
* @return
*/
private static String getHashValue(String filepath, String sha) throws Exception {
String resultString = null;
try {
MessageDigest md = MessageDigest.getInstance(sha);
MessageDigest md = MessageDigest.getInstance(sha);
byte[] bytes = md.digest(Files.readAllBytes(Paths.get(filepath)));
StringBuilder sb = new StringBuilder();
@ -75,7 +58,7 @@ public class HashSwid {
String errorMessage = "Error hashing file " + filepath + ": ";
if (e instanceof UnsupportedEncodingException ||
e instanceof NoSuchAlgorithmException) {
errorMessage += ((Exception) e).getMessage();
errorMessage += e.getMessage();
} else if (e instanceof IOException) {
errorMessage += "error reading file.";
}
@ -88,8 +71,9 @@ public class HashSwid {
/**
* This method is a public access hash function that operates on a string
* value and uses default assumptions on the salt and algorithm
*
* @param value string object to hash
* @return
* @return
*/
public static String getHashValue(String value) {
byte[] buffer = new byte[8192];
@ -108,8 +92,8 @@ public class HashSwid {
} catch (UnsupportedEncodingException | NoSuchAlgorithmException grex) {
System.out.println(grex.getMessage());
} catch (IOException ioEx) {
System.out.println(String.format("%s: \n%s is not valid...",
ioEx.getMessage(), value));
System.out.printf("%s: \n%s is not valid...%n",
ioEx.getMessage(), value);
} finally {
try {
if (bis != null) {
@ -118,7 +102,7 @@ public class HashSwid {
} catch (IOException ioEx) {
// ignored, system issue that won't affect further execution
}
if (hash == null) {
return "";
}
@ -126,4 +110,24 @@ public class HashSwid {
return Base64.getEncoder().encodeToString(hash);
}
/**
* Getter method for the hash that uses 384 bit hash
*
* @param filepath the file to hash.
* @return
*/
public String get384Hash(String filepath) throws Exception {
return getHashValue(filepath, SHA384);
}
/**
* Getter method for the hash that uses 512 bit hash
*
* @param filepath the file to hash.
* @return
*/
public String get512Hash(String filepath) throws Exception {
return getHashValue(filepath, SHA512);
}
}

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.
@ -30,24 +31,16 @@ public class TimestampArgumentValidator {
if (isExactlyOneFormat(args)) {
if (args.get(0).equalsIgnoreCase("RFC3852")) {
if (args.size() > 1) {
if (isRfc3852FileValid(args.get(1))) {
return true;
} else {
return false;
}
} else if (args.size() == 1){
return isRfc3852FileValid(args.get(1));
} else if (args.size() == 1) {
System.out.println("Countersignature file is required for RFC3852 timestamps");
return false;
}
} else if (args.get(0).equalsIgnoreCase("RFC3339")) {
if (args.size() > 1) {
if (isRfc3339Format(args.get(1))) {
return true;
} else {
return false;
}
} else if (args.size() == 1) {
return true;
return isRfc3339Format(args.get(1));
} else {
return args.size() == 1;
}
} else {
System.out.println("Unsupported timestamp format specified");

View File

@ -18,15 +18,14 @@ public class VerifyArgumentValidator implements IParametersValidator {
/**
* This method validates the input parameter map.
* @param parameters
* Name-value-pairs of all parameters (e.g. "-host":"localhost").
*
* @param parameters Name-value-pairs of all parameters (e.g. "-host":"localhost").
* @throws ParameterException
*/
@Override
public void validate(Map<String, Object> parameters) throws ParameterException {
if (isValueNotNull(parameters,"--verify")) {
if (isValueNotNull(parameters,"--create")) {
if (isValueNotNull(parameters, "--verify")) {
if (isValueNotNull(parameters, "--create")) {
throw new ParameterException("Create and verify cannot be called together.");
} else {
for (String arg : requiredArgs) {
@ -43,16 +42,13 @@ public class VerifyArgumentValidator implements IParametersValidator {
/**
* This method checks the given key for a null value
*
* @param parameters map
* @param key the key to check
* @param key the key to check
* @return true if not null, else false
*/
private boolean isValueNotNull(Map<String, Object> parameters, String key) {
Object object = parameters.get(key);
if (object == null) {
return false;
} else {
return true;
}
return object != null;
}
}