From 39cfaa5facb339a926728f34700f48cb89136c68 Mon Sep 17 00:00:00 2001 From: Cyrus <24922493+cyrus-dev@users.noreply.github.com> Date: Mon, 21 Sep 2020 07:34:07 -0400 Subject: [PATCH 01/12] After discussion, the concept of a Support RIM was clarified and because of this the ReferenceManifest.java file has to be updated to treat the Support rim similarly to the Base (which is a binary file vs an XML file). This initial code push is the beginning of that --- .../config/checkstyle/suppressions.xml | 1 + ...eferenceManifestDetailsPageController.java | 25 +- .../ReferenceManifestPageController.java | 47 +- .../WEB-INF/jsp/reference-manifests.jsp | 2 + .../main/webapp/WEB-INF/jsp/rim-details.jsp | 25 +- .../data/persist/BaseReferenceManifest.java | 776 ++++++++++++++++ .../hirs/data/persist/ReferenceManifest.java | 826 +----------------- .../persist/SupportReferenceManifest.java | 46 + .../data/persist/certificate/Certificate.java | 2 +- .../persist/ReferenceManifestSelector.java | 19 +- .../java/hirs/tpm/eventlog/TCGEventLog.java | 7 +- .../java/hirs/tpm/eventlog/TpmPcrEvent.java | 1 + 12 files changed, 959 insertions(+), 818 deletions(-) create mode 100644 HIRS_Utils/src/main/java/hirs/data/persist/BaseReferenceManifest.java create mode 100644 HIRS_Utils/src/main/java/hirs/data/persist/SupportReferenceManifest.java diff --git a/HIRS_AttestationCAPortal/config/checkstyle/suppressions.xml b/HIRS_AttestationCAPortal/config/checkstyle/suppressions.xml index ec0b37b0..4e02338a 100644 --- a/HIRS_AttestationCAPortal/config/checkstyle/suppressions.xml +++ b/HIRS_AttestationCAPortal/config/checkstyle/suppressions.xml @@ -6,4 +6,5 @@ + diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java index 1637a3e4..32dea87b 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java @@ -124,10 +124,24 @@ public class ReferenceManifestDetailsPageController // Software Identity data.put("swidName", rim.getSwidName()); data.put("swidVersion", rim.getSwidVersion()); - data.put("swidCorpus", Boolean.toString(rim.isSwidCorpus())); - data.put("swidPatch", Boolean.toString(rim.isSwidPatch())); - data.put("swidSupplemental", Boolean.toString( - rim.isSwidSupplemental())); + if (rim.isSwidCorpus() == 1) { + data.put("swidCorpus", "True"); + } else { + data.put("swidCorpus", "False"); + } + if (rim.isSwidPatch() == 1) { + data.put("swidPatch", "True"); + } else { + data.put("swidPatch", "False"); + } + if (rim.isSwidSupplemental() == 1) { + data.put("swidSupplemental", "True"); + } else { + data.put("swidSupplemental", "False"); + } +// data.put("swidCorpus", (rim.isSwidCorpus() == 1) ? "True" : "False"); +// data.put("swidPatch", (rim.isSwidPatch() == 1) ? "True" : "False"); +// data.put("swidSupplemental", (rim.isSwidSupplemental() == 1) ? "True" : "False"); data.put("swidTagId", rim.getTagId()); // Entity data.put("entityName", rim.getEntityName()); @@ -137,7 +151,8 @@ public class ReferenceManifestDetailsPageController // Link data.put("linkHref", rim.getLinkHref()); data.put("linkRel", rim.getLinkRel()); - + data.put("supportBaseRimId", ""); + data.put("supportBaseRimTagId", ""); data.put("platformManufacturer", rim.getPlatformManufacturer()); data.put("platformManufacturerId", rim.getPlatformManufacturerId()); data.put("platformModel", rim.getPlatformModel()); diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java index df8acdf1..c320f9e4 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java @@ -10,6 +10,8 @@ import hirs.FilteredRecordsList; import hirs.attestationca.portal.datatables.OrderedListQueryDataTableAdapter; import hirs.attestationca.portal.page.PageMessages; import hirs.attestationca.portal.page.params.NoPageParams; +import hirs.data.persist.BaseReferenceManifest; +import hirs.data.persist.SupportReferenceManifest; import hirs.persist.DBManagerException; import hirs.persist.ReferenceManifestManager; import hirs.persist.CriteriaModifier; @@ -22,8 +24,6 @@ import java.net.URISyntaxException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.List; -import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.UUID; @@ -189,16 +189,20 @@ public class ReferenceManifestPageController final RedirectAttributes attr) throws URISyntaxException, Exception { Map model = new HashMap<>(); PageMessages messages = new PageMessages(); - List rims = new ArrayList<>(); String fileName; Path filePath; + Pattern pattern; + Matcher matcher; + boolean supportRIM = false; // loop through the files for (MultipartFile file : files) { fileName = file.getOriginalFilename(); - Pattern pattern = Pattern.compile(LOG_FILE_PATTERN); - Matcher matcher = pattern.matcher(fileName); - if (matcher.matches()) { + pattern = Pattern.compile(LOG_FILE_PATTERN); + matcher = pattern.matcher(fileName); + supportRIM = matcher.matches(); + + if (supportRIM) { filePath = Paths.get(String.format("%s/%s", SwidResource.RESOURCE_UPLOAD_FOLDER, file.getOriginalFilename())); @@ -215,16 +219,10 @@ public class ReferenceManifestPageController "%s successfully uploaded", file.getOriginalFilename()); messages.addSuccess(uploadCompletedMessage); LOGGER.info(uploadCompletedMessage); - } else { - // assume it is a swid tag, processing below will throw and error - // if it is not. - rims.add(file); } - } - for (MultipartFile file : rims) { //Parse reference manifests - ReferenceManifest rim = parseRIM(file, messages); + ReferenceManifest rim = parseRIM(file, supportRIM, messages); //Store only if it was parsed if (rim != null) { @@ -313,11 +311,16 @@ public class ReferenceManifestPageController response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { StringBuilder fileName = new StringBuilder("filename=\""); - fileName.append(referenceManifest.getSwidName()); - fileName.append("_["); - fileName.append(referenceManifest.getRimHash()); - fileName.append("]"); - fileName.append(".swidTag\""); + if (referenceManifest.getRimType().equals(ReferenceManifest.BASE_RIM)) { + BaseReferenceManifest bRim = (BaseReferenceManifest) referenceManifest; + fileName.append(bRim.getSwidName()); + fileName.append("_["); + fileName.append(referenceManifest.getRimHash()); + fileName.append("]"); + fileName.append(".swidTag\""); + } else { + // this needs to be updated for support rims + } // Set filename for download. response.setHeader("Content-Disposition", "attachment;" + fileName); @@ -360,7 +363,7 @@ public class ReferenceManifestPageController * @return a single or collection of reference manifest files. */ private ReferenceManifest parseRIM( - final MultipartFile file, + final MultipartFile file, final boolean supportRIM, final PageMessages messages) { byte[] fileBytes; @@ -378,7 +381,11 @@ public class ReferenceManifestPageController } try { - return new ReferenceManifest(fileBytes); + if (supportRIM) { + return new SupportReferenceManifest(fileBytes); + } else { + return new BaseReferenceManifest(fileBytes); + } // the this is a List is object is a JaxBElement that can // be matched up to the QName } catch (IOException ioEx) { diff --git a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/reference-manifests.jsp b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/reference-manifests.jsp index d99a1a91..b4d5cda5 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/reference-manifests.jsp +++ b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/reference-manifests.jsp @@ -30,6 +30,7 @@ Tag ID + Type Manufacturer Model Version @@ -44,6 +45,7 @@ var url = pagePath +'/list'; var columns = [ {data: 'tagId'}, + {data: 'rimType'}, {data: 'platformManufacturer'}, {data: 'platformModel'}, {data: 'firmwareVersion'}, diff --git a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp index 05090a0f..7cba9213 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp +++ b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp @@ -10,14 +10,31 @@ - Reference Integrity Manifest + ${initialData.rimType} Reference Integrity Manifest - + -
+
+ +
Base RIM
+
+ + + + ${initialData.supportBaseRimTagId} + + + + +
Base RIM not uploaded from the ACA RIM Page
+
+
+
+
+
Software Identity
@@ -168,7 +185,7 @@
- +
Support RIM file named ${resource.getName()} was not imported via the Reference Integrity Manifest page.
diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/BaseReferenceManifest.java b/HIRS_Utils/src/main/java/hirs/data/persist/BaseReferenceManifest.java new file mode 100644 index 00000000..c0d34018 --- /dev/null +++ b/HIRS_Utils/src/main/java/hirs/data/persist/BaseReferenceManifest.java @@ -0,0 +1,776 @@ +package hirs.data.persist; + +import hirs.persist.DBReferenceManifestManager; +import hirs.utils.xjc.BaseElement; +import hirs.utils.xjc.Directory; +import hirs.utils.xjc.FilesystemItem; +import hirs.utils.xjc.Meta; +import hirs.utils.xjc.ResourceCollection; +import hirs.utils.xjc.SoftwareIdentity; +import hirs.utils.xjc.SoftwareMeta; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.persistence.Column; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.UnmarshalException; +import javax.xml.bind.Unmarshaller; +import javax.xml.namespace.QName; +import javax.xml.validation.Schema; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class BaseReferenceManifest extends ReferenceManifest { + private static final Logger LOGGER = LogManager.getLogger(BaseReferenceManifest.class); + + private static JAXBContext jaxbContext; + + @Column + private String swidName = null; + @Column + private String swidVersion = null; + @Column(nullable = false) + private int swidCorpus = 0; + @Column(nullable = false) + private int swidPatch = 0; + @Column(nullable = false) + private int swidSupplemental = 0; + @Column + private String firmwareVersion = null; + @Column + private String colloquialVersion = null; + @Column + private String product = null; + @Column + private String revision = null; + @Column + private String edition = null; + @Column + private String rimLinkHash = null; + @Column + private String bindingSpec = null; + @Column + private String bindingSpecVersion = null; + @Column + private String platformVersion = null; + @Column + private String payloadType = null; + @Column + private String pcURIGlobal = null; + @Column + private String pcURILocal = null; + + private String entityName = null; + private String entityRegId = null; + private String entityRole = null; + private String entityThumbprint = null; + private String linkHref = null; + private String linkRel = null; + + /** + * + * @param fileName + * @param rimBytes + * @throws IOException + */ + public BaseReferenceManifest(final String fileName, final byte[] rimBytes) throws IOException { + this(rimBytes); + this.setFileName(fileName); + } + + /** + * Main constructor for the RIM object. This takes in a byte array of a + * valid swidtag file and parses the information. + * + * @param rimBytes byte array representation of the RIM + * @throws IOException if unable to unmarshal the string + */ + @SuppressWarnings("checkstyle:AvoidInlineConditionals") + public BaseReferenceManifest(final byte[] rimBytes) throws IOException { + super(rimBytes); + this.setRimType(BASE_RIM); + SoftwareIdentity si = validateSwidTag(new ByteArrayInputStream(rimBytes)); + + // begin parsing valid swid tag + if (si != null) { + setTagId(si.getTagId()); + this.swidName = si.getName(); + this.swidCorpus = si.isCorpus() ? 1 : 0; + this.swidPatch = si.isPatch() ? 1 : 0; + this.swidSupplemental = si.isSupplemental() ? 1 : 0; + this.swidVersion = si.getVersion(); + + for (Object object : si.getEntityOrEvidenceOrLink()) { + if (object instanceof JAXBElement) { + JAXBElement element = (JAXBElement) object; + String elementName = element.getName().getLocalPart(); + switch (elementName) { + case "Meta": + parseSoftwareMeta((SoftwareMeta) element.getValue()); + break; + case "Entity": + hirs.utils.xjc.Entity entity + = (hirs.utils.xjc.Entity) element.getValue(); + if (entity != null) { + this.entityName = entity.getName(); + this.entityRegId = entity.getRegid(); + StringBuilder sb = new StringBuilder(); + for (String role : entity.getRole()) { + sb.append(String.format("%s%n", role)); + } + this.entityRole = sb.toString(); + this.entityThumbprint = entity.getThumbprint(); + } + break; + case "Link": + hirs.utils.xjc.Link link + = (hirs.utils.xjc.Link) element.getValue(); + if (link != null) { + this.linkHref = link.getHref(); + this.linkRel = link.getRel(); + } + break; + case "Payload": + parseResource((ResourceCollection) element.getValue()); + break; + case "Signature": + // left blank for a followup issue enhancement + default: + } + } + } + } + } + + /** + * Default constructor necessary for Hibernate. + */ + protected BaseReferenceManifest() { + + } + + /** + * This method and code is pulled and adopted from the TCG Tool. Since this + * is taking in an file stored in memory through http, this was changed from + * a file to a stream as the input. + * + * @param fileStream stream of the swidtag file. + * @return a {@link SoftwareIdentity} object + * @throws IOException Thrown by the unmarhsallSwidTag method. + */ + private SoftwareIdentity validateSwidTag(final InputStream fileStream) throws IOException { + JAXBElement jaxbe = unmarshallSwidTag(fileStream); + SoftwareIdentity swidTag = (SoftwareIdentity) jaxbe.getValue(); + + LOGGER.info(String.format("SWID Tag found: %nname: %s;%ntagId: %s%n%s", + swidTag.getName(), swidTag.getTagId(), SCHEMA_STATEMENT)); + return swidTag; + } + + /** + * Helper method that is used to parse a specific element of the SwidTag + * based on an already established and stored byte array. + * + * @param elementName string of an xml tag in the file. + * @return the object value of the element, if it exists + */ + private BaseElement getBaseElementFromBytes(final String elementName) { + BaseElement baseElement = null; + + if (getRimBytes() != null && elementName != null) { + try { + SoftwareIdentity si = validateSwidTag(new ByteArrayInputStream(getRimBytes())); + JAXBElement element; + for (Object object : si.getEntityOrEvidenceOrLink()) { + if (object instanceof JAXBElement) { + element = (JAXBElement) object; + if (element.getName().getLocalPart().equals(elementName)) { + // found the element + baseElement = (BaseElement) element.getValue(); + } + } + } + + } catch (IOException ioEx) { + LOGGER.error("Failed to parse Swid Tag bytes.", ioEx); + } + } + + return baseElement; + } + + /** + * Default method for parsing the payload element. + * + * @return a collection of payload objects. + */ + public final List parseResource() { + return parseResource((ResourceCollection) this.getBaseElementFromBytes("Payload")); + } + + /** + * This method parses the payload method of a {@link ResourceCollection}. + * + * @param rc Resource Collection object. + * @return a collection of payload objects. + */ + public final List parseResource(final ResourceCollection rc) { + List resources = new ArrayList<>(); + + try { + if (rc != null) { + for (Meta meta : rc.getDirectoryOrFileOrProcess()) { + if (meta != null) { + if (meta instanceof Directory) { + Directory directory = (Directory) meta; + for (FilesystemItem fsi : directory.getDirectoryOrFile()) { + if (fsi != null) { + resources.add(new SwidResource( + (hirs.utils.xjc.File) fsi, null)); + } + } + } else if (meta instanceof hirs.utils.xjc.File) { + resources.add(new SwidResource((hirs.utils.xjc.File) meta, null)); + } + } + } + } + } catch (ClassCastException ccEx) { + LOGGER.error(ccEx); + LOGGER.error("At this time, the code does not support the " + + "particular formatting of this SwidTag's Payload."); + } + + return resources; + } + + /** + * This method unmarshalls the swidtag found at [path] and validates it + * according to the schema. + * + * @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 + */ + private JAXBElement unmarshallSwidTag(final InputStream stream) throws IOException { + JAXBElement jaxbe = null; + Schema schema; + + try { + schema = DBReferenceManifestManager.getSchemaObject(); + if (jaxbContext == null) { + jaxbContext = JAXBContext.newInstance(SCHEMA_PACKAGE); + } + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + unmarshaller.setSchema(schema); + jaxbe = (JAXBElement) unmarshaller.unmarshal(stream); + } catch (UnmarshalException umEx) { + LOGGER.error(String.format("Error validating swidtag file!%n%s%n%s", + umEx.getMessage(), umEx.toString())); + for (StackTraceElement ste : umEx.getStackTrace()) { + LOGGER.error(ste.toString()); + } + } catch (IllegalArgumentException iaEx) { + LOGGER.error("Input file empty."); + } catch (JAXBException jaxEx) { + for (StackTraceElement ste : jaxEx.getStackTrace()) { + LOGGER.error(ste.toString()); + } + } + + if (jaxbe != null) { + return jaxbe; + } else { + throw new IOException("Invalid Base RIM, swidtag format expected."); + } + } + + /** + * This is a helper method that parses the SoftwareMeta tag and stores the + * information in the class fields. + * + * @param softwareMeta The object to parse. + */ + private void parseSoftwareMeta(final SoftwareMeta softwareMeta) { + if (softwareMeta != null) { + for (Map.Entry entry + : softwareMeta.getOtherAttributes().entrySet()) { + switch (entry.getKey().getLocalPart()) { + case "colloquialVersion": + this.colloquialVersion = entry.getValue(); + break; + case "product": + this.product = entry.getValue(); + break; + case "revision": + this.revision = entry.getValue(); + break; + case "edition": + this.edition = entry.getValue(); + break; + case "rimLinkHash": + this.rimLinkHash = entry.getValue(); + break; + case "bindingSpec": + this.bindingSpec = entry.getValue(); + break; + case "bindingSpecVersion": + this.bindingSpecVersion = entry.getValue(); + break; + case "platformManufacturerId": + this.setPlatformManufacturerId(entry.getValue()); + break; + case "platformModel": + this.setPlatformModel(entry.getValue()); + break; + case "platformManufacturerStr": + this.setPlatformManufacturer(entry.getValue()); + break; + case "platformVersion": + this.platformVersion = entry.getValue(); + break; + case "payloadType": + this.payloadType = entry.getValue(); + break; + case "pcURIGlobal": + this.pcURIGlobal = entry.getValue(); + break; + case "pcURILocal": + this.pcURILocal = entry.getValue(); + break; + default: + } + } + } + } + + /** + * Getter for the SWID name parameter. + * + * @return string representation of the SWID name + */ + public String getSwidName() { + return swidName; + } + + /** + * Setter for the SWID name parameter. + * + * @param swidName string of the name + */ + public void setSwidName(final String swidName) { + this.swidName = swidName; + } + + /** + * Getter for the SWID version. + * + * @return string of the version number + */ + public String getSwidVersion() { + return swidVersion; + } + + /** + * Setter for the SWID version. + * + * @param swidVersion string of the version + */ + public void setSwidVersion(final String swidVersion) { + this.swidVersion = swidVersion; + } + + /** + * Getter for the corpus flag. + * + * @return int flag for corpus + */ + public int isSwidCorpus() { + return swidCorpus; + } + + /** + * Setter for the corpus flag. + * + * @param swidCorpus int value + */ + public void setSwidCorpus(final int swidCorpus) { + this.swidCorpus = swidCorpus; + } + + /** + * Getter for the patch flag. + * + * @return int flag for the patch flag + */ + public int isSwidPatch() { + return swidPatch; + } + + /** + * Setter for the patch flag. + * + * @param swidPatch int value + */ + public void setSwidPatch(final int swidPatch) { + this.swidPatch = swidPatch; + } + + /** + * Getter for the supplemental flag. + * + * @return int flag for the supplemental flag + */ + public int isSwidSupplemental() { + return swidSupplemental; + } + + /** + * Setter for the supplemental flag. + * + * @param swidSupplemental int value + */ + public void setSwidSupplemental(final int swidSupplemental) { + this.swidSupplemental = swidSupplemental; + } + + /** + * Getter for the firmware version info. + * + * @return string for the firmware version + */ + public String getFirmwareVersion() { + return firmwareVersion; + } + + /** + * Setter for the firmware version info. + * + * @param firmwareVersion passed in firmware version + */ + public void setFirmwareVersion(final String firmwareVersion) { + this.firmwareVersion = firmwareVersion; + } + + /** + * Getter for the Entity Name. + * + * @return string of the entity name. + */ + public String getEntityName() { + return entityName; + } + + /** + * Setter for the Entity Name. + * + * @param entityName string of the entity name. + */ + public void setEntityName(final String entityName) { + this.entityName = entityName; + } + + /** + * Getter for the Entity Reg ID. + * + * @return string of the entity reg id. + */ + public String getEntityRegId() { + return entityRegId; + } + + /** + * Setter for the Entity Reg ID. + * + * @param entityRegId string of the entity reg id. + */ + public void setEntityRegId(final String entityRegId) { + this.entityRegId = entityRegId; + } + + /** + * Getter for the Entity Role. + * + * @return string of the entity role. + */ + public String getEntityRole() { + return entityRole; + } + + /** + * Setter for the Entity Role. + * + * @param entityRole string of the entity role . + */ + public void setEntityRole(final String entityRole) { + this.entityRole = entityRole; + } + + /** + * Getter for the Entity thumbprint. + * + * @return string of the entity thumbprint. + */ + public String getEntityThumbprint() { + return entityThumbprint; + } + + /** + * Setter for the Entity Thumbprint. + * + * @param entityThumbprint string of the entity thumbprint. + */ + public void setEntityThumbprint(final String entityThumbprint) { + this.entityThumbprint = entityThumbprint; + } + + /** + * Getter for the Link Href. + * + * @return string of the link href. + */ + public String getLinkHref() { + return linkHref; + } + + /** + * Setter for the Link href. + * + * @param linkHref in string representation. + */ + public void setLinkHref(final String linkHref) { + this.linkHref = linkHref; + } + + /** + * Getter for the Link Rel. + * + * @return string of the link rel + */ + public String getLinkRel() { + return linkRel; + } + + /** + * Setter for the Link Rel. + * + * @param linkRel in string representation. + */ + public void setLinkRel(final String linkRel) { + this.linkRel = linkRel; + } + + /** + * Getter for Colloquial Version. + * + * @return string of the colloquial version. + */ + public String getColloquialVersion() { + return colloquialVersion; + } + + /** + * Setter for Colloquial Version. + * + * @param colloquialVersion in string representation. + */ + public void setColloquialVersion(final String colloquialVersion) { + this.colloquialVersion = colloquialVersion; + } + + /** + * Getter for Product. + * + * @return string of the product information + */ + public String getProduct() { + return product; + } + + /** + * Setter for the Product. + * + * @param product in string representation. + */ + public void setProduct(final String product) { + this.product = product; + } + + /** + * Getter for the Revision string. + * + * @return string of revision information. + */ + public String getRevision() { + return revision; + } + + /** + * Setter for the Revision. + * + * @param revision in string representation. + */ + public void setRevision(final String revision) { + this.revision = revision; + } + + /** + * Getter for the Edition. + * + * @return string of edition information. + */ + public String getEdition() { + return edition; + } + + /** + * Setter for the Edition string. + * + * @param edition in string representation. + */ + public void setEdition(final String edition) { + this.edition = edition; + } + + /** + * Getter for the RIM Link Hash. + * + * @return string of the RIM link hash. + */ + public String getRimLinkHash() { + return rimLinkHash; + } + + /** + * Setter for the RIM link hash. + * + * @param rimLinkHash in string representation. + */ + public void setRimLinkHash(final String rimLinkHash) { + this.rimLinkHash = rimLinkHash; + } + + /** + * Getter for the Binding Spec. + * + * @return string of Binding spec. + */ + public String getBindingSpec() { + return bindingSpec; + } + + /** + * Setter for the Binding Spec. + * + * @param bindingSpec in string representation. + */ + public void setBindingSpec(final String bindingSpec) { + this.bindingSpec = bindingSpec; + } + + /** + * Getter for the Binding Spec Version. + * + * @return string of binding spec version. + */ + public String getBindingSpecVersion() { + return bindingSpecVersion; + } + + /** + * Setter for the binding spec version. + * + * @param bindingSpecVersion in string representation. + */ + public void setBindingSpecVersion(final String bindingSpecVersion) { + this.bindingSpecVersion = bindingSpecVersion; + } + + /** + * Getter for the Platform Version. + * + * @return string of platform version. + */ + public String getPlatformVersion() { + return platformVersion; + } + + /** + * Setter for the Platform Version. + * + * @param platformVersion in string representation. + */ + public void setPlatformVersion(final String platformVersion) { + this.platformVersion = platformVersion; + } + + /** + * Getter for the Payload Type. + * + * @return string of payload type. + */ + public String getPayloadType() { + return payloadType; + } + + /** + * Setter for the Payload type. + * + * @param payloadType in string representation. + */ + public void setPayloadType(final String payloadType) { + this.payloadType = payloadType; + } + + /** + * Getter for the PC URI Global. + * + * @return string of Pc URI Global. + */ + public String getPcURIGlobal() { + return pcURIGlobal; + } + + /** + * Setter for the PC URI Global. + * + * @param pcURIGlobal in string representation. + */ + public void setPcURIGlobal(final String pcURIGlobal) { + this.pcURIGlobal = pcURIGlobal; + } + + /** + * Getter for the PC URI Local. + * + * @return string of PC URI Local. + */ + public String getPcURILocal() { + return pcURILocal; + } + + /** + * Setter for the PC URI Local. + * + * @param pcURILocal in string representation. + */ + public void setPcURILocal(final String pcURILocal) { + this.pcURILocal = pcURILocal; + } + + @Override + public String toString() { + return String.format("ReferenceManifest{swidName=%s," + + "platformManufacturer=%s," + + " platformModel=%s," + + "firmwareVersion=%s, firmwareVersion=%s, rimHash=%d}", + swidName, this.getPlatformManufacturer(), + this.getPlatformModel(), firmwareVersion, getTagId(), this.getRimHash()); + } +} diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/ReferenceManifest.java b/HIRS_Utils/src/main/java/hirs/data/persist/ReferenceManifest.java index e2bdeecb..b4cc61e2 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/ReferenceManifest.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/ReferenceManifest.java @@ -1,43 +1,22 @@ package hirs.data.persist; -import java.io.ByteArrayInputStream; -import java.io.IOException; import java.util.Arrays; -import java.util.Map; -import java.util.List; -import java.util.ArrayList; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Column; import javax.persistence.Entity; -import javax.xml.namespace.QName; -import javax.xml.bind.JAXBElement; import com.fasterxml.jackson.annotation.JsonIgnore; import com.google.common.base.Preconditions; -import hirs.persist.DBReferenceManifestManager; import hirs.persist.ReferenceManifestManager; import hirs.persist.ReferenceManifestSelector; -import hirs.utils.xjc.BaseElement; -import hirs.utils.xjc.ResourceCollection; -import hirs.utils.xjc.SoftwareIdentity; -import hirs.utils.xjc.SoftwareMeta; -import hirs.utils.xjc.Meta; -import hirs.utils.xjc.Directory; -import hirs.utils.xjc.FilesystemItem; -import java.io.InputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.persistence.Table; import javax.xml.XMLConstants; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.UnmarshalException; -import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.validation.Schema; /** * This class represents the Reference Integrity Manifest object that will be @@ -48,7 +27,9 @@ import javax.xml.validation.Schema; @XmlRootElement(name = "ReferenceManifest") @XmlAccessorType(XmlAccessType.FIELD) @Access(AccessType.FIELD) -public class ReferenceManifest extends ArchivableEntity { +public abstract class ReferenceManifest extends ArchivableEntity { + public static final String BASE_RIM = "Base"; + public static final String SUPPORT_RIM = "Support"; /** * String for the xml schema ios standard. @@ -69,7 +50,6 @@ public class ReferenceManifest extends ArchivableEntity { public static final String SCHEMA_PACKAGE = "hirs.utils.xjc"; private static final Logger LOGGER = LogManager.getLogger(ReferenceManifest.class); - private static JAXBContext jaxbContext; /** * This class enables the retrieval of PlatformCredentials by their @@ -97,53 +77,6 @@ public class ReferenceManifest extends ArchivableEntity { */ } - @Column - private String swidName = null; - @Column - private String swidVersion = null; - @Column - private boolean swidCorpus = false; - @Column - private boolean swidPatch = false; - @Column - private boolean swidSupplemental = false; - @Column - private String platformManufacturer = null; - @Column - private String platformManufacturerId = null; - @Column - private String platformModel = null; - @Column - private String firmwareVersion = null; - @Column - private String tagId = null; - @Column - private String rimType = null; - @Column - private String colloquialVersion = null; - @Column - private String product = null; - @Column - private String revision = null; - @Column - private String edition = null; - @Column - private String rimLinkHash = null; - @Column - private String bindingSpec = null; - @Column - private String bindingSpecVersion = null; - @Column - private String platformVersion = null; - @Column - private String payloadType = null; - @Column - private String pcURIGlobal = null; - @Column - private String pcURILocal = null; - @Column(columnDefinition = "blob", nullable = false) - @JsonIgnore - private byte[] rimBytes; /** * Holds the name of the 'rimHash' field. */ @@ -151,13 +84,21 @@ public class ReferenceManifest extends ArchivableEntity { @Column(nullable = false) @JsonIgnore private final int rimHash; - - private String entityName = null; - private String entityRegId = null; - private String entityRole = null; - private String entityThumbprint = null; - private String linkHref = null; - private String linkRel = null; + @Column(columnDefinition = "blob", nullable = false) + @JsonIgnore + private byte[] rimBytes; + @Column(nullable = false) + private String rimType = "Base"; + @Column + private String tagId = null; + @Column + private String platformManufacturer = null; + @Column + private String platformManufacturerId = null; + @Column + private String platformModel = null; + @Column(nullable = false) + private String fileName = null; /** * Get a Selector for use in retrieving ReferenceManifest. @@ -175,46 +116,12 @@ public class ReferenceManifest extends ArchivableEntity { */ protected ReferenceManifest() { super(); - this.swidName = null; - this.swidVersion = null; - this.swidVersion = null; - this.swidCorpus = false; - this.swidPatch = false; - this.swidSupplemental = false; - this.platformManufacturer = null; - this.platformManufacturerId = null; - this.platformModel = null; - this.firmwareVersion = null; - this.tagId = null; this.rimBytes = null; this.rimHash = 0; - this.linkHref = null; - this.linkRel = null; - this.entityName = null; - this.entityRegId = null; - this.entityRole = null; - this.entityThumbprint = null; - this.colloquialVersion = null; - this.product = null; - this.revision = null; - this.edition = null; - this.rimLinkHash = null; - this.bindingSpec = null; - this.bindingSpecVersion = null; - this.platformVersion = null; - this.payloadType = null; - this.pcURIGlobal = null; - this.pcURILocal = null; + this.rimType = null; } - /** - * Main constructor for the RIM object. This takes in a byte array of a - * valid swidtag file and parses the information. - * - * @param rimBytes byte array representation of the RIM - * @throws IOException if unable to unmarshal the string - */ - public ReferenceManifest(final byte[] rimBytes) throws IOException { + public ReferenceManifest(final byte[] rimBytes) { Preconditions.checkArgument(rimBytes != null, "Cannot construct a RIM from a null byte array"); @@ -222,345 +129,23 @@ public class ReferenceManifest extends ArchivableEntity { "Cannot construct a RIM from an empty byte array"); this.rimBytes = rimBytes.clone(); - - SoftwareIdentity si = validateSwidTag(new ByteArrayInputStream(rimBytes)); - - // begin parsing valid swid tag - if (si != null) { - this.tagId = si.getTagId(); - this.swidName = si.getName(); - this.swidCorpus = si.isCorpus(); - this.swidPatch = si.isPatch(); - this.swidSupplemental = si.isSupplemental(); - this.swidVersion = si.getVersion(); - - for (Object object : si.getEntityOrEvidenceOrLink()) { - if (object instanceof JAXBElement) { - JAXBElement element = (JAXBElement) object; - String elementName = element.getName().getLocalPart(); - switch (elementName) { - case "Meta": - parseSoftwareMeta((SoftwareMeta) element.getValue()); - break; - case "Entity": - hirs.utils.xjc.Entity entity - = (hirs.utils.xjc.Entity) element.getValue(); - if (entity != null) { - this.entityName = entity.getName(); - this.entityRegId = entity.getRegid(); - StringBuilder sb = new StringBuilder(); - for (String role : entity.getRole()) { - sb.append(String.format("%s%n", role)); - } - this.entityRole = sb.toString(); - this.entityThumbprint = entity.getThumbprint(); - } - break; - case "Link": - hirs.utils.xjc.Link link - = (hirs.utils.xjc.Link) element.getValue(); - if (link != null) { - this.linkHref = link.getHref(); - this.linkRel = link.getRel(); - } - break; - case "Payload": - parseResource((ResourceCollection) element.getValue()); - break; - case "Signature": - // left blank for a followup issue enhancement - default: - } - } - } - } - this.rimHash = Arrays.hashCode(this.rimBytes); } /** - * This method and code is pulled and adopted from the TCG Tool. Since this - * is taking in an file stored in memory through http, this was changed from - * a file to a stream as the input. - * - * @param fileStream stream of the swidtag file. - * @return a {@link SoftwareIdentity} object - * @throws IOException Thrown by the unmarhsallSwidTag method. + * Getter for the file name of the data that was uploaded. + * @return the file name */ - private SoftwareIdentity validateSwidTag(final InputStream fileStream) throws IOException { - JAXBElement jaxbe = unmarshallSwidTag(fileStream); - SoftwareIdentity swidTag = (SoftwareIdentity) jaxbe.getValue(); - - LOGGER.info(String.format("SWID Tag found: %nname: %s;%ntagId: %s%n%s", - swidTag.getName(), swidTag.getTagId(), SCHEMA_STATEMENT)); - return swidTag; + public String getFileName() { + return fileName; } /** - * Helper method that is used to parse a specific element of the SwidTag - * based on an already established and stored byte array. - * - * @param elementName string of an xml tag in the file. - * @return the object value of the element, if it exists + * Setter for the file name of the data that was uploaded. + * @param fileName file name to associate */ - private BaseElement getBaseElementFromBytes(final String elementName) { - BaseElement baseElement = null; - - if (rimBytes != null && elementName != null) { - try { - SoftwareIdentity si = validateSwidTag(new ByteArrayInputStream(this.rimBytes)); - JAXBElement element; - for (Object object : si.getEntityOrEvidenceOrLink()) { - if (object instanceof JAXBElement) { - element = (JAXBElement) object; - if (element.getName().getLocalPart().equals(elementName)) { - // found the element - baseElement = (BaseElement) element.getValue(); - } - } - } - - } catch (IOException ioEx) { - LOGGER.error("Failed to parse Swid Tag bytes.", ioEx); - } - } - - return baseElement; - } - - /** - * This is a helper method that parses the SoftwareMeta tag and stores the - * information in the class fields. - * - * @param softwareMeta The object to parse. - */ - private void parseSoftwareMeta(final SoftwareMeta softwareMeta) { - if (softwareMeta != null) { - for (Map.Entry entry - : softwareMeta.getOtherAttributes().entrySet()) { - switch (entry.getKey().getLocalPart()) { - case "colloquialVersion": - this.colloquialVersion = entry.getValue(); - break; - case "product": - this.product = entry.getValue(); - break; - case "revision": - this.revision = entry.getValue(); - break; - case "edition": - this.edition = entry.getValue(); - break; - case "rimLinkHash": - this.rimLinkHash = entry.getValue(); - break; - case "bindingSpec": - this.bindingSpec = entry.getValue(); - break; - case "bindingSpecVersion": - this.bindingSpecVersion = entry.getValue(); - break; - case "platformManufacturerId": - this.platformManufacturerId = entry.getValue(); - break; - case "platformModel": - this.platformModel = entry.getValue(); - break; - case "platformManufacturerStr": - this.platformManufacturer = entry.getValue(); - break; - case "platformVersion": - this.platformVersion = entry.getValue(); - break; - case "payloadType": - this.payloadType = entry.getValue(); - break; - case "pcURIGlobal": - this.pcURIGlobal = entry.getValue(); - break; - case "pcURILocal": - this.pcURILocal = entry.getValue(); - break; - default: - } - } - } - } - - /** - * Default method for parsing the payload element. - * - * @return a collection of payload objects. - */ - public final List parseResource() { - return parseResource((ResourceCollection) this.getBaseElementFromBytes("Payload")); - } - - /** - * This method parses the payload method of a {@link ResourceCollection}. - * - * @param rc Resource Collection object. - * @return a collection of payload objects. - */ - public final List parseResource(final ResourceCollection rc) { - List resources = new ArrayList<>(); - - try { - if (rc != null) { - for (Meta meta : rc.getDirectoryOrFileOrProcess()) { - if (meta != null) { - if (meta instanceof Directory) { - Directory directory = (Directory) meta; - for (FilesystemItem fsi : directory.getDirectoryOrFile()) { - if (fsi != null) { - resources.add(new SwidResource( - (hirs.utils.xjc.File) fsi, null)); - } - } - } else if (meta instanceof hirs.utils.xjc.File) { - resources.add(new SwidResource((hirs.utils.xjc.File) meta, null)); - } - } - } - } - } catch (ClassCastException ccEx) { - LOGGER.error(ccEx); - LOGGER.error("At this time, the code does not support the " - + "particular formatting of this SwidTag's Payload."); - } - - return resources; - } - - /** - * This method unmarshalls the swidtag found at [path] and validates it - * according to the schema. - * - * @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 - */ - private JAXBElement unmarshallSwidTag(final InputStream stream) throws IOException { - JAXBElement jaxbe = null; - Schema schema; - - try { - schema = DBReferenceManifestManager.getSchemaObject(); - if (jaxbContext == null) { - jaxbContext = JAXBContext.newInstance(SCHEMA_PACKAGE); - } - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - unmarshaller.setSchema(schema); - jaxbe = (JAXBElement) unmarshaller.unmarshal(stream); - } catch (UnmarshalException umEx) { - LOGGER.error(String.format("Error validating swidtag file!%n%s%n%s", - umEx.getMessage(), umEx.toString())); - for (StackTraceElement ste : umEx.getStackTrace()) { - LOGGER.error(ste.toString()); - } - } catch (IllegalArgumentException iaEx) { - LOGGER.error("Input file empty."); - } catch (JAXBException jaxEx) { - for (StackTraceElement ste : jaxEx.getStackTrace()) { - LOGGER.error(ste.toString()); - } - } - - if (jaxbe != null) { - return jaxbe; - } else { - throw new IOException("Invalid Base RIM, swidtag format expected."); - } - } - - /** - * Getter for the SWID name parameter. - * - * @return string representation of the SWID name - */ - public String getSwidName() { - return swidName; - } - - /** - * Setter for the SWID name parameter. - * - * @param swidName string of the name - */ - public void setSwidName(final String swidName) { - this.swidName = swidName; - } - - /** - * Getter for the SWID version. - * - * @return string of the version number - */ - public String getSwidVersion() { - return swidVersion; - } - - /** - * Setter for the SWID version. - * - * @param swidVersion string of the version - */ - public void setSwidVersion(final String swidVersion) { - this.swidVersion = swidVersion; - } - - /** - * Getter for the corpus flag. - * - * @return boolean flag for corpus - */ - public boolean isSwidCorpus() { - return swidCorpus; - } - - /** - * Setter for the corpus flag. - * - * @param swidCorpus boolean value - */ - public void setSwidCorpus(final boolean swidCorpus) { - this.swidCorpus = swidCorpus; - } - - /** - * Getter for the patch flag. - * - * @return boolean flag for the patch flag - */ - public boolean isSwidPatch() { - return swidPatch; - } - - /** - * Setter for the patch flag. - * - * @param swidPatch boolean value - */ - public void setSwidPatch(final boolean swidPatch) { - this.swidPatch = swidPatch; - } - - /** - * Getter for the supplemental flag. - * - * @return boolean flag for the supplemental flag - */ - public boolean isSwidSupplemental() { - return swidSupplemental; - } - - /** - * Setter for the supplemental flag. - * - * @param swidSupplemental boolean value - */ - public void setSwidSupplemental(final boolean swidSupplemental) { - this.swidSupplemental = swidSupplemental; + public void setFileName(final String fileName) { + this.fileName = fileName; } /** @@ -618,21 +203,21 @@ public class ReferenceManifest extends ArchivableEntity { } /** - * Getter for the firmware version info. + * Getter for the RIM Type (Primary, Supplemental, Patch). * - * @return string for the firmware version + * @return string for the RIM Type */ - public String getFirmwareVersion() { - return firmwareVersion; + public String getRimType() { + return rimType; } /** - * Setter for the firmware version info. + * Setter for the RIM Type. * - * @param firmwareVersion passed in firmware version + * @param rimType passed in RIM Type */ - public void setFirmwareVersion(final String firmwareVersion) { - this.firmwareVersion = firmwareVersion; + public void setRimType(final String rimType) { + this.rimType = rimType; } /** @@ -653,31 +238,17 @@ public class ReferenceManifest extends ArchivableEntity { this.tagId = tagId; } - /** - * Getter for the RIM Type (Primary, Supplemental, Patch). - * - * @return string for the RIM Type - */ - public String getRimType() { - return rimType; - } - - /** - * Setter for the RIM Type. - * - * @param timType passed in RIM Type - */ - public void setRimType(final String timType) { - this.rimType = timType; - } - /** * Getter for the Reference Integrity Manifest as a byte array. * * @return array of bytes */ + @JsonIgnore public byte[] getRimBytes() { - return rimBytes.clone(); + if (this.rimBytes != null) { + return this.rimBytes.clone(); + } + return null; } /** @@ -689,319 +260,8 @@ public class ReferenceManifest extends ArchivableEntity { return rimHash; } - /** - * Getter for the Entity Name. - * - * @return string of the entity name. - */ - public String getEntityName() { - return entityName; - } - - /** - * Setter for the Entity Name. - * - * @param entityName string of the entity name. - */ - public void setEntityName(final String entityName) { - this.entityName = entityName; - } - - /** - * Getter for the Entity Reg ID. - * - * @return string of the entity reg id. - */ - public String getEntityRegId() { - return entityRegId; - } - - /** - * Setter for the Entity Reg ID. - * - * @param entityRegId string of the entity reg id. - */ - public void setEntityRegId(final String entityRegId) { - this.entityRegId = entityRegId; - } - - /** - * Getter for the Entity Role. - * - * @return string of the entity role. - */ - public String getEntityRole() { - return entityRole; - } - - /** - * Setter for the Entity Role. - * - * @param entityRole string of the entity role . - */ - public void setEntityRole(final String entityRole) { - this.entityRole = entityRole; - } - - /** - * Getter for the Entity thumbprint. - * - * @return string of the entity thumbprint. - */ - public String getEntityThumbprint() { - return entityThumbprint; - } - - /** - * Setter for the Entity Thumbprint. - * - * @param entityThumbprint string of the entity thumbprint. - */ - public void setEntityThumbprint(final String entityThumbprint) { - this.entityThumbprint = entityThumbprint; - } - - /** - * Getter for the Link Href. - * - * @return string of the link href. - */ - public String getLinkHref() { - return linkHref; - } - - /** - * Setter for the Link href. - * - * @param linkHref in string representation. - */ - public void setLinkHref(final String linkHref) { - this.linkHref = linkHref; - } - - /** - * Getter for the Link Rel. - * - * @return string of the link rel - */ - public String getLinkRel() { - return linkRel; - } - - /** - * Setter for the Link Rel. - * - * @param linkRel in string representation. - */ - public void setLinkRel(final String linkRel) { - this.linkRel = linkRel; - } - - /** - * Getter for Colloquial Version. - * - * @return string of the colloquial version. - */ - public String getColloquialVersion() { - return colloquialVersion; - } - - /** - * Setter for Colloquial Version. - * - * @param colloquialVersion in string representation. - */ - public void setColloquialVersion(final String colloquialVersion) { - this.colloquialVersion = colloquialVersion; - } - - /** - * Getter for Product. - * - * @return string of the product information - */ - public String getProduct() { - return product; - } - - /** - * Setter for the Product. - * - * @param product in string representation. - */ - public void setProduct(final String product) { - this.product = product; - } - - /** - * Getter for the Revision string. - * - * @return string of revision information. - */ - public String getRevision() { - return revision; - } - - /** - * Setter for the Revision. - * - * @param revision in string representation. - */ - public void setRevision(final String revision) { - this.revision = revision; - } - - /** - * Getter for the Edition. - * - * @return string of edition information. - */ - public String getEdition() { - return edition; - } - - /** - * Setter for the Edition string. - * - * @param edition in string representation. - */ - public void setEdition(final String edition) { - this.edition = edition; - } - - /** - * Getter for the RIM Link Hash. - * - * @return string of the RIM link hash. - */ - public String getRimLinkHash() { - return rimLinkHash; - } - - /** - * Setter for the RIM link hash. - * - * @param rimLinkHash in string representation. - */ - public void setRimLinkHash(final String rimLinkHash) { - this.rimLinkHash = rimLinkHash; - } - - /** - * Getter for the Binding Spec. - * - * @return string of Binding spec. - */ - public String getBindingSpec() { - return bindingSpec; - } - - /** - * Setter for the Binding Spec. - * - * @param bindingSpec in string representation. - */ - public void setBindingSpec(final String bindingSpec) { - this.bindingSpec = bindingSpec; - } - - /** - * Getter for the Binding Spec Version. - * - * @return string of binding spec version. - */ - public String getBindingSpecVersion() { - return bindingSpecVersion; - } - - /** - * Setter for the binding spec version. - * - * @param bindingSpecVersion in string representation. - */ - public void setBindingSpecVersion(final String bindingSpecVersion) { - this.bindingSpecVersion = bindingSpecVersion; - } - - /** - * Getter for the Platform Version. - * - * @return string of platform version. - */ - public String getPlatformVersion() { - return platformVersion; - } - - /** - * Setter for the Platform Version. - * - * @param platformVersion in string representation. - */ - public void setPlatformVersion(final String platformVersion) { - this.platformVersion = platformVersion; - } - - /** - * Getter for the Payload Type. - * - * @return string of payload type. - */ - public String getPayloadType() { - return payloadType; - } - - /** - * Setter for the Payload type. - * - * @param payloadType in string representation. - */ - public void setPayloadType(final String payloadType) { - this.payloadType = payloadType; - } - - /** - * Getter for the PC URI Global. - * - * @return string of Pc URI Global. - */ - public String getPcURIGlobal() { - return pcURIGlobal; - } - - /** - * Setter for the PC URI Global. - * - * @param pcURIGlobal in string representation. - */ - public void setPcURIGlobal(final String pcURIGlobal) { - this.pcURIGlobal = pcURIGlobal; - } - - /** - * Getter for the PC URI Local. - * - * @return string of PC URI Local. - */ - public String getPcURILocal() { - return pcURILocal; - } - - /** - * Setter for the PC URI Local. - * - * @param pcURILocal in string representation. - */ - public void setPcURILocal(final String pcURILocal) { - this.pcURILocal = pcURILocal; - } - @Override - public String toString() { - return String.format("ReferenceManifest{swidName=%s," - + "platformManufacturer=%s," - + " platformModel=%s," - + "firmwareVersion=%s, firmwareVersion=%s, rimHash=%d}", - swidName, platformManufacturer, - platformModel, firmwareVersion, tagId, rimHash); + public int hashCode() { + return getRimHash(); } } diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/SupportReferenceManifest.java b/HIRS_Utils/src/main/java/hirs/data/persist/SupportReferenceManifest.java new file mode 100644 index 00000000..03ee6d9b --- /dev/null +++ b/HIRS_Utils/src/main/java/hirs/data/persist/SupportReferenceManifest.java @@ -0,0 +1,46 @@ +package hirs.data.persist; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.persistence.Column; +import java.io.IOException; + +/** + * Sub class that will just focus on PCR Values and Events + */ +public class SupportReferenceManifest extends ReferenceManifest { + private static final Logger LOGGER = LogManager.getLogger(SupportReferenceManifest.class); + + @Column(nullable = false) + @JsonIgnore + private int pcrHash; + + /** + * Main constructor for the RIM object. This takes in a byte array of a + * valid swidtag file and parses the information. + * + * @param rimBytes byte array representation of the RIM + * @throws IOException if unable to unmarshal the string + */ + public SupportReferenceManifest(final byte[] rimBytes) throws IOException { + super(rimBytes); + this.setRimType(SUPPORT_RIM); + } + + /** + * Default constructor necessary for Hibernate. + */ + protected SupportReferenceManifest() { + + } + + public int getPcrHash() { + return pcrHash; + } + + public void setPcrHash(final int pcrHash) { + this.pcrHash = pcrHash; + } +} diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/certificate/Certificate.java b/HIRS_Utils/src/main/java/hirs/data/persist/certificate/Certificate.java index a0d3487a..d483cbec 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/certificate/Certificate.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/certificate/Certificate.java @@ -1075,7 +1075,7 @@ public abstract class Certificate extends ArchivableEntity { */ @JsonIgnore public byte[] getRawBytes() { - if (null != this.certificateBytes) { + if (this.certificateBytes != null) { return this.certificateBytes.clone(); } return null; diff --git a/HIRS_Utils/src/main/java/hirs/persist/ReferenceManifestSelector.java b/HIRS_Utils/src/main/java/hirs/persist/ReferenceManifestSelector.java index 951f8cc2..f6c260e8 100644 --- a/HIRS_Utils/src/main/java/hirs/persist/ReferenceManifestSelector.java +++ b/HIRS_Utils/src/main/java/hirs/persist/ReferenceManifestSelector.java @@ -28,6 +28,7 @@ public abstract class ReferenceManifestSelector { private static final String PLATFORM_MANUFACTURER_ID = "platformManufacturerId"; private static final String PLATFORM_MODEL = "platformModel"; private static final String RIM_TYPE_FIELD = "rimType"; + private static final String RIM_FILENAME_FIELD = "fileName"; private final ReferenceManifestManager referenceManifestManager; @@ -116,6 +117,16 @@ public abstract class ReferenceManifestSelector { return this; } + /** + * Specif the file name of the object to grab. + * @param fileName the name of the file associated with the rim + * @return + */ + public ReferenceManifestSelector byFileName(final int fileName) { + setFieldValue(RIM_FILENAME_FIELD, fileName); + return this; + } + /** * Specify the RIM Type to match. * @param rimType the type of rim @@ -124,7 +135,7 @@ public abstract class ReferenceManifestSelector { public ReferenceManifestSelector byRimType(final String rimType) { setFieldValue(RIM_TYPE_FIELD, rimType); return this; - } + } /** * Set a field name and value to match. @@ -171,11 +182,11 @@ public abstract class ReferenceManifestSelector { * @return a matching RIM or null if none is found */ public hirs.data.persist.ReferenceManifest getRIM() { - Set certs = execute(); - if (certs.isEmpty()) { + Set rims = execute(); + if (rims.isEmpty()) { return null; } - return certs.iterator().next(); + return rims.iterator().next(); } /** diff --git a/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TCGEventLog.java b/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TCGEventLog.java index a3c960df..b849c9e3 100644 --- a/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TCGEventLog.java +++ b/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TCGEventLog.java @@ -77,6 +77,7 @@ public final class TCGEventLog { private boolean bEvent = false; /** Event Output Flag use. */ private boolean bCryptoAgile = false; + /** * Default blank object constructor. */ @@ -255,6 +256,8 @@ public final class TCGEventLog { } return pcrs; } + + /** * Returns a flag which is set if the event log follows the "Crypto Agile" Format Type. * A false implies the type is SHA1 format. @@ -263,6 +266,7 @@ public final class TCGEventLog { public boolean isCryptoAgile() { return bCryptoAgile; } + /** * Returns a list of event found in the Event Log. * @return an arraylist of event. @@ -270,6 +274,7 @@ public final class TCGEventLog { public ArrayList getEventList() { return eventList; } + /** * Returns a single PCR value given an index (PCR Number). * @@ -286,7 +291,7 @@ public final class TCGEventLog { */ public String toString() { StringBuilder sb = new StringBuilder(); - for (TpmPcrEvent event:eventList) { + for (TpmPcrEvent event : eventList) { sb.append(event.toString(bEvent, bHexEvent, bContent)); } sb.append("Event Log processing completed.\n"); diff --git a/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TpmPcrEvent.java b/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TpmPcrEvent.java index 2d124105..f9252e1a 100644 --- a/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TpmPcrEvent.java +++ b/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TpmPcrEvent.java @@ -176,6 +176,7 @@ public class TpmPcrEvent { public String getSpecErrataVersion() { return errata; } + /** * Sets the event data after processing. * From 36367829871aedfbebb84bc345db489fa7aa6146 Mon Sep 17 00:00:00 2001 From: Cyrus <24922493+cyrus-dev@users.noreply.github.com> Date: Thu, 24 Sep 2020 09:58:10 -0400 Subject: [PATCH 02/12] This commit adds functionality to display tpm even log information to the support RIM display page. Outstanding issues to implement: 1) add link to base from support RIM, 2) make event table scrollable --- .../SupplyChainValidationServiceImpl.java | 16 +- .../config/checkstyle/suppressions.xml | 1 - .../portal/datatables/DataTableResponse.java | 2 +- ...eferenceManifestDetailsPageController.java | 104 +-- .../ReferenceManifestPageController.java | 74 ++- .../main/webapp/WEB-INF/jsp/rim-details.jsp | 430 +++++++----- .../webapp/common/certificate_details.css | 3 +- ...enceManifestDetailsPageControllerTest.java | 3 +- .../data/persist/BaseReferenceManifest.java | 46 +- .../hirs/data/persist/ReferenceManifest.java | 86 ++- .../persist/SupportReferenceManifest.java | 84 ++- .../persist/ReferenceManifestSelector.java | 6 +- .../java/hirs/tpm/eventlog/TCGEventLog.java | 2 +- .../java/hirs/tpm/eventlog/TpmPcrEvent.java | 626 ++++++++++++------ .../hirs/tpm/eventlog/events/EvPostCode.java | 14 +- .../hirs/tpm/eventlog/uefi/UefiFirmware.java | 137 ++-- .../src/main/java/hirs/tcg_eventlog/Main.java | 289 ++++---- 17 files changed, 1208 insertions(+), 715 deletions(-) diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java index b6ffbcc1..31c40e3d 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java @@ -9,6 +9,7 @@ import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; +import hirs.data.persist.BaseReferenceManifest; import hirs.data.persist.TPMMeasurementRecord; import hirs.data.persist.SwidResource; import hirs.data.persist.PCRPolicy; @@ -335,13 +336,9 @@ public class SupplyChainValidationServiceImpl implements SupplyChainValidationSe fwStatus = new AppraisalStatus(PASS, SupplyChainCredentialValidator.FIRMWARE_VALID); - if (rim == null) { - fwStatus = new AppraisalStatus(FAIL, - String.format("Firmware validation failed: " - + "No associated RIM file could be found for %s", - manufacturer)); - } else { - List swids = rim.parseResource(); + if (rim instanceof BaseReferenceManifest) { + BaseReferenceManifest bRim = (BaseReferenceManifest) rim; + List swids = bRim.parseResource(); for (SwidResource swid : swids) { baseline = swid.getPcrValues() .toArray(new String[swid.getPcrValues().size()]); @@ -413,6 +410,11 @@ public class SupplyChainValidationServiceImpl implements SupplyChainValidationSe fwStatus = new AppraisalStatus(FAIL, "Associated Issued Attestation" + " Certificate can not be found."); } + } else { + fwStatus = new AppraisalStatus(FAIL, + String.format("Firmware validation failed: " + + "No associated RIM file could be found for %s", + manufacturer)); } return buildValidationRecord(SupplyChainValidation.ValidationType.FIRMWARE, diff --git a/HIRS_AttestationCAPortal/config/checkstyle/suppressions.xml b/HIRS_AttestationCAPortal/config/checkstyle/suppressions.xml index 4e02338a..ec0b37b0 100644 --- a/HIRS_AttestationCAPortal/config/checkstyle/suppressions.xml +++ b/HIRS_AttestationCAPortal/config/checkstyle/suppressions.xml @@ -6,5 +6,4 @@ - diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableResponse.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableResponse.java index 5a9a7ad2..aa1f0364 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableResponse.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableResponse.java @@ -27,7 +27,7 @@ public final class DataTableResponse { /** * Builds a data table response using a FilteredRecordList. - * @param recordList the filtered recordd list + * @param recordList the filtered record list * @param inputQuery the data table input (used for draw) */ public DataTableResponse(final FilteredRecordsList recordList, diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java index 32dea87b..9a7da962 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java @@ -1,7 +1,10 @@ package hirs.attestationca.portal.page.controllers; +import hirs.data.persist.BaseReferenceManifest; import hirs.data.persist.ReferenceManifest; +import hirs.data.persist.SupportReferenceManifest; import hirs.data.persist.SwidResource; +import hirs.persist.DBManagerException; import hirs.persist.ReferenceManifestManager; import hirs.tpm.eventlog.TCGEventLog; import hirs.attestationca.portal.page.Page; @@ -10,9 +13,6 @@ import hirs.attestationca.portal.page.PageMessages; import hirs.attestationca.portal.page.params.ReferenceManifestDetailsPageParams; import java.io.IOException; import java.nio.file.NoSuchFileException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.Arrays; @@ -20,6 +20,7 @@ import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.UUID; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; @@ -53,6 +54,7 @@ public class ReferenceManifestDetailsPageController } /** + * Returns the filePath for the view and the data model for the page. * * @param params The object to map url parameters into. * @param model The data model for the request. Can contain data from @@ -120,72 +122,75 @@ public class ReferenceManifestDetailsPageController .select(referenceManifestManager) .byEntityId(uuid).getRIM(); - if (rim != null) { + if (rim instanceof BaseReferenceManifest) { + BaseReferenceManifest bRim = (BaseReferenceManifest) rim; // Software Identity - data.put("swidName", rim.getSwidName()); - data.put("swidVersion", rim.getSwidVersion()); - if (rim.isSwidCorpus() == 1) { + data.put("swidName", bRim.getSwidName()); + data.put("swidVersion", bRim.getSwidVersion()); + if (bRim.isSwidCorpus() == 1) { data.put("swidCorpus", "True"); } else { data.put("swidCorpus", "False"); } - if (rim.isSwidPatch() == 1) { + if (bRim.isSwidPatch() == 1) { data.put("swidPatch", "True"); } else { data.put("swidPatch", "False"); } - if (rim.isSwidSupplemental() == 1) { + if (bRim.isSwidSupplemental() == 1) { data.put("swidSupplemental", "True"); } else { data.put("swidSupplemental", "False"); } -// data.put("swidCorpus", (rim.isSwidCorpus() == 1) ? "True" : "False"); -// data.put("swidPatch", (rim.isSwidPatch() == 1) ? "True" : "False"); -// data.put("swidSupplemental", (rim.isSwidSupplemental() == 1) ? "True" : "False"); data.put("swidTagId", rim.getTagId()); // Entity - data.put("entityName", rim.getEntityName()); - data.put("entityRegId", rim.getEntityRegId()); - data.put("entityRole", rim.getEntityRole()); - data.put("entityThumbprint", rim.getEntityThumbprint()); + data.put("entityName", bRim.getEntityName()); + data.put("entityRegId", bRim.getEntityRegId()); + data.put("entityRole", bRim.getEntityRole()); + data.put("entityThumbprint", bRim.getEntityThumbprint()); // Link - data.put("linkHref", rim.getLinkHref()); - data.put("linkRel", rim.getLinkRel()); + data.put("linkHref", bRim.getLinkHref()); + data.put("linkRel", bRim.getLinkRel()); data.put("supportBaseRimId", ""); data.put("supportBaseRimTagId", ""); - data.put("platformManufacturer", rim.getPlatformManufacturer()); - data.put("platformManufacturerId", rim.getPlatformManufacturerId()); - data.put("platformModel", rim.getPlatformModel()); - data.put("platformVersion", rim.getPlatformVersion()); - data.put("firmwareVersion", rim.getFirmwareVersion()); - data.put("payloadType", rim.getPayloadType()); - data.put("colloquialVersion", rim.getColloquialVersion()); - data.put("edition", rim.getEdition()); - data.put("product", rim.getProduct()); - data.put("revision", rim.getRevision()); - data.put("bindingSpec", rim.getBindingSpec()); - data.put("bindingSpecVersion", rim.getBindingSpecVersion()); - data.put("pcUriGlobal", rim.getPcURIGlobal()); - data.put("pcUriLocal", rim.getPcURILocal()); - data.put("rimLinkHash", rim.getRimLinkHash()); + data.put("platformManufacturer", bRim.getPlatformManufacturer()); + data.put("platformManufacturerId", bRim.getPlatformManufacturerId()); + data.put("platformModel", bRim.getPlatformModel()); + data.put("platformVersion", bRim.getPlatformVersion()); + data.put("firmwareVersion", bRim.getFirmwareVersion()); + data.put("payloadType", bRim.getPayloadType()); + data.put("colloquialVersion", bRim.getColloquialVersion()); + data.put("edition", bRim.getEdition()); + data.put("product", bRim.getProduct()); + data.put("revision", bRim.getRevision()); + data.put("bindingSpec", bRim.getBindingSpec()); + data.put("bindingSpecVersion", bRim.getBindingSpecVersion()); + data.put("pcUriGlobal", bRim.getPcURIGlobal()); + data.put("pcUriLocal", bRim.getPcURILocal()); + data.put("rimLinkHash", bRim.getRimLinkHash()); + data.put("rimType", bRim.getRimType()); + data.put("associatedRim", bRim.getAssociatedRim()); - // checkout later - data.put("rimType", rim.getRimType()); - List resources = rim.parseResource(); + List resources = bRim.parseResource(); String resourceFilename = null; TCGEventLog logProcessor; + // going to have to pull the filename and grab that from the DB + // to get the id to make the link try { for (SwidResource swidRes : resources) { resourceFilename = swidRes.getName(); - Path logPath = Paths.get(String.format("%s/%s", - SwidResource.RESOURCE_UPLOAD_FOLDER, - resourceFilename)); - if (Files.exists(logPath)) { - logProcessor = new TCGEventLog( - Files.readAllBytes(logPath)); + ReferenceManifest dbRim = ReferenceManifest.select( + referenceManifestManager).byFileName(resourceFilename).getRIM(); + + if (dbRim != null) { + logProcessor = new TCGEventLog(dbRim.getRimBytes()); swidRes.setPcrValues(Arrays.asList( logProcessor.getExpectedPCRValues())); + + if (bRim.getAssociatedRim() == null) { + bRim.setAssociatedRim(dbRim.getId()); + } } else { swidRes.setPcrValues(new ArrayList<>()); } @@ -194,12 +199,23 @@ public class ReferenceManifestDetailsPageController LOGGER.error(String.format("File Not found!: %s", resourceFilename)); LOGGER.error(nsfEx); + } catch (DBManagerException dbmEx) { + LOGGER.error(dbmEx); } + data.put("associatedRim", bRim.getAssociatedRim()); data.put("swidFiles", resources); + } else if (rim instanceof SupportReferenceManifest) { + SupportReferenceManifest sRim = (SupportReferenceManifest) rim; + data.put("baseRim", sRim.getFileName()); + data.put("associatedRim", sRim.getAssociatedRim()); + data.put("rimType", sRim.getRimType()); + + TCGEventLog logProcessor = new TCGEventLog(sRim.getRimBytes()); + data.put("events", logProcessor.getEventList()); } else { - LOGGER.error(String.format("Unable to find Reference Integrity " - + "Manifest with ID: %s", uuid)); + LOGGER.error(String.format("Unable to find Reference Integrity " + + "Manifest with ID: %s", uuid)); } return data; diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java index c320f9e4..f9a08d69 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java @@ -26,10 +26,9 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; +import java.util.Set; import java.util.UUID; -import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletResponse; @@ -202,27 +201,54 @@ public class ReferenceManifestPageController matcher = pattern.matcher(fileName); supportRIM = matcher.matches(); - if (supportRIM) { - filePath = Paths.get(String.format("%s/%s", - SwidResource.RESOURCE_UPLOAD_FOLDER, - file.getOriginalFilename())); - if (Files.notExists(Paths.get(SwidResource.RESOURCE_UPLOAD_FOLDER))) { - Files.createDirectory(Paths.get(SwidResource.RESOURCE_UPLOAD_FOLDER)); - } - if (Files.notExists(filePath)) { - Files.createFile(filePath); - } - - Files.write(filePath, file.getBytes()); - - String uploadCompletedMessage = String.format( - "%s successfully uploaded", file.getOriginalFilename()); - messages.addSuccess(uploadCompletedMessage); - LOGGER.info(uploadCompletedMessage); - } - //Parse reference manifests ReferenceManifest rim = parseRIM(file, supportRIM, messages); + // look for associated base/support + Set rims = ReferenceManifest + .select(referenceManifestManager).getRIMs(); + + // update information for associated support rims + if (supportRIM) { + for (ReferenceManifest element : rims) { + if (element instanceof BaseReferenceManifest) { + BaseReferenceManifest bRim = (BaseReferenceManifest) element; + for (SwidResource swid : bRim.parseResource()) { + if (swid.getName().equals(rim.getFileName())) { + rim.setFirmwareVersion(swid.getSize()); + rim.setPlatformManufacturer(element.getPlatformManufacturer()); + rim.setPlatformModel(element.getPlatformModel()); + rim.setTagId(element.getTagId()); + rim.setAssociatedRim(element.getId()); + break; + } + } + } + } + } else { + BaseReferenceManifest bRim = (BaseReferenceManifest) rim; + for (SwidResource swid : bRim.parseResource()) { + for (ReferenceManifest element : rims) { + if (element instanceof SupportReferenceManifest) { + SupportReferenceManifest sRim = (SupportReferenceManifest) element; + if (swid.getName().equals(sRim.getFileName())) { + sRim.setPlatformManufacturer(bRim.getPlatformManufacturer()); + sRim.setPlatformModel(bRim.getPlatformModel()); + sRim.setFirmwareVersion(swid.getSize()); + sRim.setTagId(bRim.getTagId()); + rim.setAssociatedRim(sRim.getId()); + try { + referenceManifestManager.update(sRim); + } catch (DBManagerException dbmEx) { + LOGGER.error(String.format("Couldn't update Base RIM %s with " + + "associated UUID %s", rim.getTagId(), + sRim.getId()), dbmEx); + } + break; + } + } + } + } + } //Store only if it was parsed if (rim != null) { @@ -320,6 +346,8 @@ public class ReferenceManifestPageController fileName.append(".swidTag\""); } else { // this needs to be updated for support rims + SupportReferenceManifest bRim = (SupportReferenceManifest) referenceManifest; + fileName.append(bRim.getFileName()); } // Set filename for download. @@ -382,9 +410,9 @@ public class ReferenceManifestPageController try { if (supportRIM) { - return new SupportReferenceManifest(fileBytes); + return new SupportReferenceManifest(fileName, fileBytes); } else { - return new BaseReferenceManifest(fileBytes); + return new BaseReferenceManifest(fileName, fileBytes); } // the this is a List is object is a JaxBElement that can // be matched up to the QName diff --git a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp index 7cba9213..46629bed 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp +++ b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp @@ -8,6 +8,7 @@ + ${initialData.rimType} Reference Integrity Manifest @@ -17,192 +18,267 @@
-
- -
Base RIM
-
- - - - ${initialData.supportBaseRimTagId} - - - - -
Base RIM not uploaded from the ACA RIM Page
-
-
-
-
-
-
-
Software Identity
-
-
SWID Name: ${initialData.swidName}
-
SWID Version: ${initialData.swidVersion}
-
SWID Tag ID: ${initialData.swidTagId}
-
SWID Tag Version: 
- -
SWID Corpus:  -
-
- -
SWID Patch:  -
-
- -
SWID Supplemental:  -
-
-
-
-
-
Entity
-
-
Entity Name: ${initialData.entityName}
- -
Entity Reg ID: ${initialData.entityRegId}
-
-
Entity Role: ${initialData.entityRole}
-
Entity Thumbprint: ${initialData.entityThumbprint}
-
-
-
-
Link
- -
-
-
Meta
- -
-
-
-
Payload/Support RIM(s)
-
-
- -
-
- -
- -
- -
-
-
- - ${resource.getName()} - -
- - -
- File Size: - ${resource.getSize()}
- Hash: - ${resource.getHashValue()}
- - RIM Format: - ${resource.getRimFormat()}
-
- - RIM Type: - ${resource.getRimType()}
-
- - URI Global: - ${resource.getRimUriGlobal()}
-
- -
- -
-
- -
-
- ${pcrValue.key} - ${pcrValue.value} + + + +
Base RIM not uploaded from the ACA RIM Page
+
+ +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Event #PCR IndexEvent TypeDigestEvent Content
${count}${event.getPcrIndex()}${event.getEventTypeStr()}${event.getEventDigestStr()}${event.getEventContentStr()}
+
+ + +
+
Software Identity
+
+
SWID Name: ${initialData.swidName}
+
SWID Version: ${initialData.swidVersion}
+
SWID Tag ID: ${initialData.swidTagId}
+
SWID Tag Version: 
+ +
SWID Corpus:  +
+
+ +
SWID Patch:  +
+
+ +
SWID Supplemental:  +
+
+
+
+
+
Entity
+
+
Entity Name: ${initialData.entityName}
+ +
Entity Reg ID: ${initialData.entityRegId}
+
+
Entity Role: ${initialData.entityRole}
+
Entity Thumbprint: ${initialData.entityThumbprint}
+
+
+
+
Link
+ +
+
+
Meta
+ +
+
+
Payload/Support RIM(s)
+
+
+ +
+
+ +
+ +
+ +
+
+
+ + + + ${resource.getName()} + + + ${resource.getName()} + + + +
+ + +
+ File Size: + ${resource.getSize()}
+ Hash: + ${resource.getHashValue()}
+ + RIM Format: + ${resource.getRimFormat()}
+
+ + RIM Type: + ${resource.getRimType()}
+
+ + URI Global: + ${resource.getRimUriGlobal()}
+
+ +
+ +
+
+ +
+
+ ${pcrValue.key} + ${pcrValue.value} +
+
+
- -
+
+
-
- -
- - -
Support RIM file named ${resource.getName()} was not imported via the Reference Integrity Manifest page.
-
- -
-
- -
- -
+ + +
Support RIM file named ${resource.getName()} was not imported via the Reference Integrity Manifest page.
+
+ +
+
+
+
+ +
+
+
+
-
-
+ +
+ diff --git a/HIRS_AttestationCAPortal/src/main/webapp/common/certificate_details.css b/HIRS_AttestationCAPortal/src/main/webapp/common/certificate_details.css index 070d2a14..5cafa466 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/common/certificate_details.css +++ b/HIRS_AttestationCAPortal/src/main/webapp/common/certificate_details.css @@ -16,6 +16,7 @@ font-weight: bold; margin: auto 0; } + #platformID { display: inline; } @@ -62,4 +63,4 @@ margin: 4px 2px; cursor: pointer; border-radius: 2px; -} +} \ No newline at end of file diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageControllerTest.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageControllerTest.java index 8245a924..17b5187d 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageControllerTest.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageControllerTest.java @@ -1,5 +1,6 @@ package hirs.attestationca.portal.page.controllers; +import hirs.data.persist.BaseReferenceManifest; import hirs.data.persist.ReferenceManifest; import hirs.persist.DBReferenceManifestManager; import hirs.attestationca.portal.page.Page; @@ -52,7 +53,7 @@ public class ReferenceManifestDetailsPageControllerTest extends PageControllerTe } catch (URISyntaxException e) { throw new IOException("Could not resolve path URI", e); } - referenceManifest = new ReferenceManifest(Files.readAllBytes(fPath)); + referenceManifest = new BaseReferenceManifest(Files.readAllBytes(fPath)); referenceManifestManager.save(referenceManifest); } diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/BaseReferenceManifest.java b/HIRS_Utils/src/main/java/hirs/data/persist/BaseReferenceManifest.java index c0d34018..85bb28b5 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/BaseReferenceManifest.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/BaseReferenceManifest.java @@ -12,6 +12,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.persistence.Column; +import javax.persistence.Entity; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; @@ -26,6 +27,10 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +/** + * + */ +@Entity public class BaseReferenceManifest extends ReferenceManifest { private static final Logger LOGGER = LogManager.getLogger(BaseReferenceManifest.class); @@ -35,14 +40,12 @@ public class BaseReferenceManifest extends ReferenceManifest { private String swidName = null; @Column private String swidVersion = null; - @Column(nullable = false) - private int swidCorpus = 0; - @Column(nullable = false) - private int swidPatch = 0; - @Column(nullable = false) - private int swidSupplemental = 0; @Column - private String firmwareVersion = null; + private int swidCorpus = 0; + @Column + private int swidPatch = 0; + @Column + private int swidSupplemental = 0; @Column private String colloquialVersion = null; @Column @@ -74,10 +77,11 @@ public class BaseReferenceManifest extends ReferenceManifest { private String linkRel = null; /** + * Support constructor for the RIM object. * - * @param fileName - * @param rimBytes - * @throws IOException + * @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. */ public BaseReferenceManifest(final String fileName, final byte[] rimBytes) throws IOException { this(rimBytes); @@ -440,24 +444,6 @@ public class BaseReferenceManifest extends ReferenceManifest { this.swidSupplemental = swidSupplemental; } - /** - * Getter for the firmware version info. - * - * @return string for the firmware version - */ - public String getFirmwareVersion() { - return firmwareVersion; - } - - /** - * Setter for the firmware version info. - * - * @param firmwareVersion passed in firmware version - */ - public void setFirmwareVersion(final String firmwareVersion) { - this.firmwareVersion = firmwareVersion; - } - /** * Getter for the Entity Name. * @@ -769,8 +755,8 @@ public class BaseReferenceManifest extends ReferenceManifest { return String.format("ReferenceManifest{swidName=%s," + "platformManufacturer=%s," + " platformModel=%s," - + "firmwareVersion=%s, firmwareVersion=%s, rimHash=%d}", + + "tagId=%s, rimHash=%d}", swidName, this.getPlatformManufacturer(), - this.getPlatformModel(), firmwareVersion, getTagId(), this.getRimHash()); + this.getPlatformModel(), getTagId(), this.getRimHash()); } } diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/ReferenceManifest.java b/HIRS_Utils/src/main/java/hirs/data/persist/ReferenceManifest.java index b4cc61e2..f6802122 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/ReferenceManifest.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/ReferenceManifest.java @@ -1,6 +1,7 @@ package hirs.data.persist; import java.util.Arrays; +import java.util.UUID; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Column; @@ -12,6 +13,8 @@ import hirs.persist.ReferenceManifestManager; import hirs.persist.ReferenceManifestSelector; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.hibernate.annotations.Type; + import javax.persistence.Table; import javax.xml.XMLConstants; import javax.xml.bind.annotation.XmlAccessType; @@ -28,7 +31,13 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.FIELD) @Access(AccessType.FIELD) public abstract class ReferenceManifest extends ArchivableEntity { + /** + * String for display of a Base RIM. + */ public static final String BASE_RIM = "Base"; + /** + * String for display of a Support RIM. + */ public static final String SUPPORT_RIM = "Support"; /** @@ -69,12 +78,6 @@ public abstract class ReferenceManifest extends ArchivableEntity { public Selector(final ReferenceManifestManager referenceManifestManager) { super(referenceManifestManager); } - - /** - * Specify a manufacturer that certificates must have to be considered as matching. - * @param rimType the manufacturer to query, not empty or null - * @return this instance (for chaining further calls) - */ } /** @@ -96,9 +99,14 @@ public abstract class ReferenceManifest extends ArchivableEntity { @Column private String platformManufacturerId = null; @Column + private String firmwareVersion = null; + @Column private String platformModel = null; @Column(nullable = false) private String fileName = null; + @Type(type = "uuid-char") + @Column + private UUID associatedRim; /** * Get a Selector for use in retrieving ReferenceManifest. @@ -119,8 +127,18 @@ public abstract class ReferenceManifest extends ArchivableEntity { this.rimBytes = null; this.rimHash = 0; this.rimType = null; + this.platformManufacturer = null; + this.platformManufacturerId = null; + this.platformModel = null; + this.fileName = BASE_RIM; + this.tagId = null; + this.associatedRim = null; } + /** + * Default constructor for ingesting the bytes of the file content. + * @param rimBytes - file contents. + */ public ReferenceManifest(final byte[] rimBytes) { Preconditions.checkArgument(rimBytes != null, "Cannot construct a RIM from a null byte array"); @@ -238,6 +256,40 @@ public abstract class ReferenceManifest extends ArchivableEntity { this.tagId = tagId; } + /** + * Getter for the firmware version info. + * + * @return string for the firmware version + */ + public String getFirmwareVersion() { + return firmwareVersion; + } + + /** + * Setter for the firmware version info. + * + * @param firmwareVersion passed in firmware version + */ + public void setFirmwareVersion(final String firmwareVersion) { + this.firmwareVersion = firmwareVersion; + } + + /** + * Getter for the associated RIM DB ID. + * @return UUID for the rim + */ + public UUID getAssociatedRim() { + return associatedRim; + } + + /** + * Setter for the associated RIM DB ID. + * @param associatedRim UUID for the rim + */ + public void setAssociatedRim(final UUID associatedRim) { + this.associatedRim = associatedRim; + } + /** * Getter for the Reference Integrity Manifest as a byte array. * @@ -264,4 +316,26 @@ public abstract class ReferenceManifest extends ArchivableEntity { public int hashCode() { return getRimHash(); } + + @Override + public boolean equals(final Object object) { + if (this == object) { + return true; + } + if (object == null || getClass() != object.getClass()) { + return false; + } + if (!super.equals(object)) { + return false; + } + ReferenceManifest that = (ReferenceManifest) object; + return rimHash == that.rimHash + && Arrays.equals(rimBytes, that.rimBytes) + && rimType.equals(that.rimType) + && tagId.equals(that.tagId) + && platformManufacturer.equals(that.platformManufacturer) + && platformManufacturerId.equals(that.platformManufacturerId) + && platformModel.equals(that.platformModel) + && fileName.equals(that.fileName); + } } diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/SupportReferenceManifest.java b/HIRS_Utils/src/main/java/hirs/data/persist/SupportReferenceManifest.java index 03ee6d9b..4d8c2d44 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/SupportReferenceManifest.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/SupportReferenceManifest.java @@ -1,21 +1,45 @@ package hirs.data.persist; import com.fasterxml.jackson.annotation.JsonIgnore; +import hirs.tpm.eventlog.TCGEventLog; +import hirs.tpm.eventlog.TpmPcrEvent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.persistence.Column; +import javax.persistence.Entity; import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; /** - * Sub class that will just focus on PCR Values and Events + * Sub class that will just focus on PCR Values and Events. */ +@Entity public class SupportReferenceManifest extends ReferenceManifest { private static final Logger LOGGER = LogManager.getLogger(SupportReferenceManifest.class); - @Column(nullable = false) + @Column @JsonIgnore - private int pcrHash; + private int pcrHash = 0; + + /** + * Support constructor for the RIM object. + * + * @param fileName - string representation of the uploaded file. + * @param rimBytes byte array representation of the RIM + * @throws IOException if unable to unmarshal the string + */ + public SupportReferenceManifest(final String fileName, + final byte[] rimBytes) throws IOException { + this(rimBytes); + this.setRimType(SUPPORT_RIM); + this.setFileName(fileName); + } /** * Main constructor for the RIM object. This takes in a byte array of a @@ -27,19 +51,71 @@ public class SupportReferenceManifest extends ReferenceManifest { public SupportReferenceManifest(final byte[] rimBytes) throws IOException { super(rimBytes); this.setRimType(SUPPORT_RIM); + this.pcrHash = 0; } /** * Default constructor necessary for Hibernate. */ protected SupportReferenceManifest() { - + super(); + this.pcrHash = 0; } + /** + * Getter method for the expected PCR values contained within the support + * RIM. + * @return a string array of the pcr values. + */ + public String[] getExpectedPCRList() { + try { + TCGEventLog logProcessor = new TCGEventLog(this.getRimBytes()); + this.pcrHash = Arrays.hashCode(logProcessor.getExpectedPCRValues()); + return logProcessor.getExpectedPCRValues(); + } catch (CertificateException cEx) { + LOGGER.error(cEx); + } catch (NoSuchAlgorithmException noSaEx) { + LOGGER.error(noSaEx); + } catch (IOException ioEx) { + LOGGER.error(ioEx); + } + + return new String[0]; + } + + /** + * Getter method for the event log that should be present in the support RIM. + * + * @return list of TPM PCR Events for display + */ + public List getEventLog() { + TCGEventLog logProcessor = null; + try { + logProcessor = new TCGEventLog(this.getRimBytes()); + return Collections.unmodifiableList(logProcessor.getEventList()); + } catch (CertificateException cEx) { + LOGGER.error(cEx); + } catch (NoSuchAlgorithmException noSaEx) { + LOGGER.error(noSaEx); + } catch (IOException ioEx) { + LOGGER.error(ioEx); + } + + return new ArrayList<>(); + } + + /** + * Getter for the PCR Hash contained in the support RIM. + * @return hash in int form + */ public int getPcrHash() { return pcrHash; } + /** + * Setter for the PCR Hash. + * @param pcrHash hash in int form + */ public void setPcrHash(final int pcrHash) { this.pcrHash = pcrHash; } diff --git a/HIRS_Utils/src/main/java/hirs/persist/ReferenceManifestSelector.java b/HIRS_Utils/src/main/java/hirs/persist/ReferenceManifestSelector.java index f6c260e8..344edc3c 100644 --- a/HIRS_Utils/src/main/java/hirs/persist/ReferenceManifestSelector.java +++ b/HIRS_Utils/src/main/java/hirs/persist/ReferenceManifestSelector.java @@ -118,11 +118,11 @@ public abstract class ReferenceManifestSelector { } /** - * Specif the file name of the object to grab. + * Specify the file name of the object to grab. * @param fileName the name of the file associated with the rim - * @return + * @return instance of the manifest in relation to the filename. */ - public ReferenceManifestSelector byFileName(final int fileName) { + public ReferenceManifestSelector byFileName(final String fileName) { setFieldValue(RIM_FILENAME_FIELD, fileName); return this; } diff --git a/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TCGEventLog.java b/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TCGEventLog.java index b849c9e3..a7f43de1 100644 --- a/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TCGEventLog.java +++ b/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TCGEventLog.java @@ -252,7 +252,7 @@ public final class TCGEventLog { public String[] getExpectedPCRValues() { String[] pcrs = new String[PCR_COUNT]; for (int i = 0; i < PCR_COUNT; i++) { - pcrs[i] = HexUtils.byteArrayToHexString(pcrList[i]); + pcrs[i] = Hex.encodeHexString(pcrList[i]); } return pcrs; } diff --git a/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TpmPcrEvent.java b/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TpmPcrEvent.java index f9252e1a..f7aec6ef 100644 --- a/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TpmPcrEvent.java +++ b/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TpmPcrEvent.java @@ -2,6 +2,7 @@ package hirs.tpm.eventlog; import java.io.ByteArrayInputStream; import java.io.IOException; +import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -25,51 +26,82 @@ import hirs.tpm.eventlog.uefi.UefiConstants; import hirs.tpm.eventlog.uefi.UefiFirmware; import hirs.tpm.eventlog.uefi.UefiVariable; import hirs.utils.HexUtils; +import org.apache.commons.codec.binary.Hex; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * Class to process a TCG_PCR_EVENT. * TCG_PCR_EVENT is used when the Event log uses the SHA1 Format as described in the * TCG Platform Firmware Profile (PFP) specification. * typedef struct { - * TCG_PCRINDEX PCRIndex; //PCR Index value that either - * //matches the PCRIndex of a - * //previous extend operation or - * //indicates that this Event Log - * //entry is not associated with - * //an extend operation - * TCG_EVENTTYPE EventType; //See Log event types defined in toStrng() - * TCG_DIGEST digest; //The hash of the event data - * UINT32 EventSize; //Size of the event data - * UINT8 Event[EventSize]; //The event data + * TCG_PCRINDEX PCRIndex; //PCR Index value that either + * //matches the PCRIndex of a + * //previous extend operation or + * //indicates that this Event Log + * //entry is not associated with + * //an extend operation + * TCG_EVENTTYPE EventType; //See Log event types defined in toStrng() + * TCG_DIGEST digest; //The hash of the event data + * UINT32 EventSize; //Size of the event data + * UINT8 Event[EventSize]; //The event data * } TCG_PCR_EVENT; */ public class TpmPcrEvent { - /** Log format. SHA1=1, Crytpo agile=2. */ - private int logFormat = -1; - /** PCR index. */ - private int pcrIndex = -1; - /** Event Type (long). */ - private long eventType = 0; - /** Event digest. */ - private byte[] digest = null; - /** Even data (no content). */ - private byte[] event; - /** Even content data. */ - private byte[] eventContent; - /** TCG Event Log spec version. */ - private String version = "Unknown"; - /** TCG Event Log errata version. */ - private String errata = "Unknown"; - /** Description for toString support. */ - private String description = ""; - /** Length (in bytes) of a pcr. */ - private int digestLength = 0; - /** Event hash for SHA1 event logs. */ - private byte[] eventDataSha1hash; - /** Event hash for Crypto Agile events. */ - private byte[] eventDataSha256hash; - /** Indent Offset. */ + private static final Logger LOGGER = LogManager.getLogger(TpmPcrEvent.class); + /** + * Indent Offset. + */ private static final int INDENT_3 = 3; + /** + * Log format. SHA1=1, Crytpo agile=2. + */ + private int logFormat = -1; + /** + * PCR index. + */ + private int pcrIndex = -1; + /** + * Event Type (long). + */ + private long eventType = 0; + /** + * Event digest. + */ + private byte[] digest = null; + /** + * Event data (no content). + */ + private byte[] event; + /** + * Event content data. + */ + private byte[] eventContent; + /** + * TCG Event Log spec version. + */ + private String version = "Unknown"; + /** + * TCG Event Log errata version. + */ + private String errata = "Unknown"; + /** + * Description for toString support. + */ + private String description = ""; + /** + * Length (in bytes) of a pcr. + */ + private int digestLength = 0; + /** + * Event hash for SHA1 event logs. + */ + private byte[] eventDataSha1hash; + /** + * Event hash for Crypto Agile events. + */ + private byte[] eventDataSha256hash; + private EvPostCode evPostCode; /** * Constructor. @@ -104,6 +136,14 @@ public class TpmPcrEvent { return digestCopy; } + /** + * Returns a hex representation of the event digest. + * @return hex string + */ + public String getEventDigestStr() { + return Hex.encodeHexString(this.digest); + } + /** * Sets the event PCR index value from a TCG Event. * @@ -122,22 +162,25 @@ public class TpmPcrEvent { return pcrIndex; } - /** Sets the Log Format for this TCG Event. - * 1 = SHA1 Format, 2 = Crypto Agile format. - * @param format indicates log format. - */ - protected void setLogFormat(final int format) { - logFormat = format; - } + /** + * Sets the Log Format for this TCG Event. + * 1 = SHA1 Format, 2 = Crypto Agile format. + * + * @param format indicates log format. + */ + protected void setLogFormat(final int format) { + logFormat = format; + } - /** - * Gets the Log Format for this TCG Event. - * 1 = SHA1 Format, 2 = Crypto Agile format. - * @return number representing the format. - */ - public int getLogFormat() { - return logFormat; - } + /** + * Gets the Log Format for this TCG Event. + * 1 = SHA1 Format, 2 = Crypto Agile format. + * + * @return number representing the format. + */ + public int getLogFormat() { + return logFormat; + } /** * Sets the EventType. @@ -157,6 +200,14 @@ public class TpmPcrEvent { return eventType; } + /** + * Returns a formatted string of the type for the event. + * @return a string formatted to be human readable + */ + public String getEventTypeStr() { + return String.format("0x%s %s", Long.toHexString(eventType), eventString((int) eventType)); + } + /** * Returns the version of the TCG Log Event specification pertaining to the log. * only updated if the event is a TCG_EfiSpecIdEvent. @@ -190,11 +241,13 @@ public class TpmPcrEvent { /** * Gets the Event Data (no event content) for the event. * event log format. + * * @return byte array holding the event structure. */ public byte[] getEvent() { return java.util.Arrays.copyOf(event, event.length); } + /** * Sets the event content after processing. * @@ -202,17 +255,168 @@ public class TpmPcrEvent { */ protected void setEventContent(final byte[] eventData) { eventContent = new byte[eventData.length]; + evPostCode = new EvPostCode(eventContent); System.arraycopy(eventData, 0, eventContent, 0, eventData.length); } /** * Gets the event Content Data (not the entire event structure). + * * @return byte array holding the events content field */ public byte[] getEventContent() { return java.util.Arrays.copyOf(eventContent, eventContent.length); } + /** + * A getter that parses the content based on the type and returns the proper string + * value for the content. + * @return an appended string of human readable data + */ + public String getEventContentStr() { + StringBuilder sb = new StringBuilder(); + + switch ((int) this.eventType) { + case EvConstants.EV_PREBOOT_CERT: + sb.append(" EV_PREBOOT_CERT"); + break; + case EvConstants.EV_POST_CODE: + sb.append(new EvPostCode(eventContent).toString()); + break; + case EvConstants.EV_UNUSED: + break; + case EvConstants.EV_NO_ACTION: + EvNoAction noAction = null; + try { + noAction = new EvNoAction(eventContent); + sb.append(noAction.toString()); + if (noAction.isSpecIDEvent()) { + // this should be in the constructor + EvEfiSpecIdEvent specID = noAction.getEvEfiSpecIdEvent(); + version = String.format("%s.%s", + specID.getVersionMajor(), + specID.getVersionMinor()); + errata = specID.getErrata(); + } + } catch (UnsupportedEncodingException ueEx) { + LOGGER.error(ueEx); + sb.append(ueEx.toString()); + } + break; + case EvConstants.EV_SEPARATOR: + if (EvPostCode.isAscii(eventContent) + && !this.isBlank(eventContent)) { + sb.append(String.format("Separator event content = %s", + new String(eventContent, StandardCharsets.UTF_8))); + } + break; + case EvConstants.EV_EVENT_TAG: + sb.append(new EvEventTag(eventContent).toString()); + break; + case EvConstants.EV_S_CRTM_CONTENTS: + sb.append(new EvSCrtmContents(eventContent).toString()); + break; + case EvConstants.EV_S_CRTM_VERSION: + try { + sb.append(new EvSCrtmVersion(eventContent).toString()); + } catch (UnsupportedEncodingException ueEx) { + LOGGER.error(ueEx); + sb.append(ueEx.toString()); + } + break; + case EvConstants.EV_CPU_MICROCODE: + case EvConstants.EV_PLATFORM_CONFIG_FLAGS: + case EvConstants.EV_TABLE_OF_DEVICES: + break; + case EvConstants.EV_COMPACT_HASH: + try { + sb.append(new EvCompactHash(eventContent).toString()); + } catch (UnsupportedEncodingException ueEx) { + LOGGER.error(ueEx); + sb.append(ueEx.toString()); + } + break; + case EvConstants.EV_IPL: + sb.append(new EvIPL(eventContent).toString()); + break; + case EvConstants.EV_IPL_PARTITION_DATA: + case EvConstants.EV_NONHOST_CODE: + case EvConstants.EV_NONHOST_CONFIG: + case EvConstants.EV_NONHOST_INFO: + case EvConstants.EV_EV_OMIT_BOOT_DEVICES_EVENTS: + case EvConstants.EV_EFI_EVENT_BASE: + break; + case EvConstants.EV_EFI_VARIABLE_DRIVER_CONFIG: + UefiVariable efiVar = null; + try { + efiVar = new UefiVariable(eventContent); + String efiVarDescription = efiVar.toString().replace("\n", "\n "); + sb.append(efiVarDescription.substring(0, + efiVarDescription.length() - INDENT_3)); + } catch (CertificateException cEx) { + LOGGER.error(cEx); + sb.append(cEx.toString()); + } catch (NoSuchAlgorithmException noSaEx) { + LOGGER.error(noSaEx); + sb.append(noSaEx.toString()); + } catch (IOException ioEx) { + LOGGER.error(ioEx); + sb.append(ioEx.toString()); + } + break; + case EvConstants.EV_EFI_VARIABLE_BOOT: + case EvConstants.EV_EFI_VARIABLE_AUTHORITY: + try { + sb.append(new UefiVariable(eventContent).toString()); + } catch (CertificateException cEx) { + LOGGER.error(cEx); + sb.append(cEx.toString()); + } catch (NoSuchAlgorithmException noSaEx) { + LOGGER.error(noSaEx); + sb.append(noSaEx.toString()); + } catch (IOException ioEx) { + LOGGER.error(ioEx); + sb.append(ioEx.toString()); + } + break; + case EvConstants.EV_EFI_BOOT_SERVICES_APPLICATION: + case EvConstants.EV_EFI_BOOT_SERVICES_DRIVER: // same as EV_EFI_BOOT_SERVICES_APP + try { + sb.append(new EvEfiBootServicesApp(eventContent).toString()); + } catch (UnsupportedEncodingException ueEx) { + LOGGER.error(ueEx); + sb.append(ueEx.toString()); + } + break; + case EvConstants.EV_EFI_RUNTIME_SERVICES_DRIVER: + break; + case EvConstants.EV_EFI_GPT_EVENT: + try { + sb.append(new EvEfiGptPartition(eventContent).toString()); + } catch (UnsupportedEncodingException ueEx) { + LOGGER.error(ueEx); + sb.append(ueEx.toString()); + } + break; + case EvConstants.EV_EFI_ACTION: + case EvConstants.EV_ACTION: + sb.append(new String(eventContent, StandardCharsets.UTF_8)); + break; + case EvConstants.EV_EFI_PLATFORM_FIRMWARE_BLOB: + sb.append(new UefiFirmware(eventContent).toString()); + break; + case EvConstants.EV_EFI_HANDOFF_TABLES: + sb.append(new EvEfiHandoffTable(eventContent).toString()); + break; + case EvConstants.EV_EFI_HCRTM_EVENT: + break; + default: + sb.append("Unknown Event found\n"); + } + + return sb.toString(); + } + /** * Sets the Digest Length. * Also the number of bytes expected within each PCR. @@ -234,25 +438,26 @@ public class TpmPcrEvent { /** * Parses the event content and creates a human readable description of each event. - * @param event the byte array holding the event data. + * + * @param event the byte array holding the event data. * @param eventContent the byte array holding the event content. - * @param eventNumber event position within the event log. + * @param eventNumber event position within the event log. * @return String description of the event. - * @throws CertificateException if the event contains an event that cannot be processed. + * @throws CertificateException if the event contains an event that cannot be processed. * @throws NoSuchAlgorithmException if an event contains an unsupported algorithm. - * @throws IOException if the event cannot be parsed. + * @throws IOException if the event cannot be parsed. */ - public String processEvent(final byte[] event, final byte[] eventContent, final int eventNumber) - throws CertificateException, NoSuchAlgorithmException, IOException { + public String processEvent(final byte[] event, final byte[] eventContent, final int eventNumber) + throws CertificateException, NoSuchAlgorithmException, IOException { int eventID = (int) eventType; description += "Event# " + eventNumber + ": "; description += "Index PCR[" + getPcrIndex() + "]\n"; description += "Event Type: 0x" + Long.toHexString(eventType) + " " + eventString(eventID); description += "\n"; if (logFormat == 1) { // Digest - description += "digest (SHA-1): " + HexUtils.byteArrayToHexString(this.digest); + description += "digest (SHA-1): " + Hex.encodeHexString(this.digest); } else { - description += "digest (SHA256): " + HexUtils.byteArrayToHexString(this.digest); + description += "digest (SHA256): " + Hex.encodeHexString(this.digest); } if (eventID != UefiConstants.SIZE_4) { description += "\n"; @@ -269,11 +474,11 @@ public class TpmPcrEvent { switch (eventID) { case EvConstants.EV_PREBOOT_CERT: description += " EV_PREBOOT_CERT" + "\n"; - break; + break; case EvConstants.EV_POST_CODE: EvPostCode postCode = new EvPostCode(eventContent); - description += "Event Content:\n" + postCode.toString(); - break; + description += "Event Content:\n" + postCode.toString(); + break; case EvConstants.EV_UNUSED: break; case EvConstants.EV_NO_ACTION: @@ -287,15 +492,15 @@ public class TpmPcrEvent { break; case EvConstants.EV_SEPARATOR: if (EvPostCode.isAscii(eventContent)) { - String seperatorEventData = new String(eventContent, StandardCharsets.UTF_8); - if (!this.isEmpty(eventContent)) { - description += "Seperator event content = " + seperatorEventData; + String separatorEventData = new String(eventContent, StandardCharsets.UTF_8); + if (!this.isBlank(eventContent)) { + description += "Separator event content = " + separatorEventData; } - } + } break; case EvConstants.EV_ACTION: description += "Event Content:\n" - + new String(eventContent, StandardCharsets.UTF_8); + + new String(eventContent, StandardCharsets.UTF_8); break; case EvConstants.EV_EVENT_TAG: EvEventTag eventTag = new EvEventTag(eventContent); @@ -316,7 +521,7 @@ public class TpmPcrEvent { case EvConstants.EV_TABLE_OF_DEVICES: break; case EvConstants.EV_COMPACT_HASH: - EvCompactHash compactHash = new EvCompactHash(eventContent); + EvCompactHash compactHash = new EvCompactHash(eventContent); description += "Event Content:\n" + compactHash.toString(); break; case EvConstants.EV_IPL: @@ -339,7 +544,7 @@ public class TpmPcrEvent { UefiVariable efiVar = new UefiVariable(eventContent); String efiVarDescription = efiVar.toString().replace("\n", "\n "); description += "Event Content:\n " + efiVarDescription.substring(0, - efiVarDescription.length() - INDENT_3); + efiVarDescription.length() - INDENT_3); break; case EvConstants.EV_EFI_VARIABLE_BOOT: description += "Event Content:\n" + new UefiVariable(eventContent).toString(); @@ -362,7 +567,7 @@ public class TpmPcrEvent { break; case EvConstants.EV_EFI_PLATFORM_FIRMWARE_BLOB: description += "Event Content:\n" - + new UefiFirmware(eventContent).toString(); + + new UefiFirmware(eventContent).toString(); break; case EvConstants.EV_EFI_HANDOFF_TABLES: EvEfiHandoffTable efiTable = new EvEfiHandoffTable(eventContent); @@ -373,7 +578,8 @@ public class TpmPcrEvent { case EvConstants.EV_EFI_VARIABLE_AUTHORITY: description += "Event Content:\n" + new UefiVariable(eventContent).toString(); break; - default: description += " Unknown Event found" + "\n"; + default: + description += " Unknown Event found" + "\n"; } return description; } @@ -381,152 +587,158 @@ public class TpmPcrEvent { /** * Converts the Event ID into a String As defined in the TCG PC Client FW Profile. * Event IDs have values larger than an integer,so a Long is used hold the value. + * * @param event the event id. * @return TCG defined String that represents the event id */ - private static String eventString(final long event) { + private static String eventString(final long event) { - if (event == EvConstants.EV_PREBOOT_CERT) { - return "EV_PREBOOT_CERT"; - } else if (event == EvConstants.EV_POST_CODE) { - return "EV_POST_CODE"; - } else if (event == EvConstants.EV_UNUSED) { - return "EV_Unused"; - } else if (event == EvConstants.EV_NO_ACTION) { - return "EV_NO_ACTION"; - } else if (event == EvConstants.EV_SEPARATOR) { - return "EV_SEPARATOR"; - } else if (event == EvConstants.EV_ACTION) { - return "EV_ACTION"; - } else if (event == EvConstants.EV_EVENT_TAG) { - return "EV_EVENT_TAG"; - } else if (event == EvConstants.EV_S_CRTM_CONTENTS) { - return "EV_S_CRTM_CONTENTS"; - } else if (event == EvConstants.EV_S_CRTM_VERSION) { - return "EV_S_CRTM_VERSION"; - } else if (event == EvConstants.EV_CPU_MICROCODE) { - return "EV_CPU_MICROCODE"; - } else if (event == EvConstants.EV_PLATFORM_CONFIG_FLAGS) { - return "EV_PLATFORM_CONFIG_FLAGS "; - } else if (event == EvConstants.EV_TABLE_OF_DEVICES) { - return "EV_TABLE_OF_DEVICES"; - } else if (event == EvConstants.EV_COMPACT_HASH) { - return "EV_COMPACT_HASH"; - } else if (event == EvConstants.EV_IPL) { - return "EV_IPL"; - } else if (event == EvConstants.EV_IPL_PARTITION_DATA) { - return "EV_IPL_PARTITION_DATA"; - } else if (event == EvConstants.EV_NONHOST_CODE) { - return "EV_NONHOST_CODE"; - } else if (event == EvConstants.EV_NONHOST_CONFIG) { - return "EV_NONHOST_CONFIG"; - } else if (event == EvConstants.EV_NONHOST_INFO) { - return "EV_NONHOST_INFO"; - } else if (event == EvConstants.EV_EV_OMIT_BOOT_DEVICES_EVENTS) { - return "EV_EV_OMIT_BOOT_DEVICES_EVENTS"; - } else if (event == EvConstants.EV_EFI_EVENT_BASE) { - return "EV_EFI_EVENT_BASE"; - } else if (event == EvConstants.EV_EFI_VARIABLE_DRIVER_CONFIG) { - return "EV_EFI_VARIABLE_DRIVER_CONFIG"; - } else if (event == EvConstants.EV_EFI_VARIABLE_BOOT) { - return "EV_EFI_VARIABLE_BOOT"; - } else if (event == EvConstants.EV_EFI_BOOT_SERVICES_APPLICATION) { - return "EV_EFI_BOOT_SERVICES_APPLICATION"; - } else if (event == EvConstants.EV_EFI_BOOT_SERVICES_DRIVER) { - return "EV_EFI_BOOT_SERVICES_DRIVER"; - } else if (event == EvConstants.EV_EFI_RUNTIME_SERVICES_DRIVER) { - return "EV_EFI_RUNTIME_SERVICES_DRIVER"; - } else if (event == EvConstants.EV_EFI_GPT_EVENT) { - return "EV_EFI_GPT_EVENT"; - } else if (event == EvConstants.EV_EFI_ACTION) { - return "EV_EFI_ACTION"; - } else if (event == EvConstants.EV_EFI_PLATFORM_FIRMWARE_BLOB) { - return "EV_EFI_PLATFORM_FIRMWARE_BLOB"; - } else if (event == EvConstants.EV_EFI_HANDOFF_TABLES) { - return "EV_EFI_HANDOFF_TABLES"; - } else if (event == EvConstants.EV_EFI_HCRTM_EVENT) { - return "EV_EFI_HCRTM_EVENT"; - } else if (event == EvConstants.EV_EFI_VARIABLE_AUTHORITY) { - return "EV_EFI_VARIABLE_AUTHORITY"; - } else { - return "Unknown Event ID " + event + " encountered"; - } - } + if (event == EvConstants.EV_PREBOOT_CERT) { + return "EV_PREBOOT_CERT"; + } else if (event == EvConstants.EV_POST_CODE) { + return "EV_POST_CODE"; + } else if (event == EvConstants.EV_UNUSED) { + return "EV_Unused"; + } else if (event == EvConstants.EV_NO_ACTION) { + return "EV_NO_ACTION"; + } else if (event == EvConstants.EV_SEPARATOR) { + return "EV_SEPARATOR"; + } else if (event == EvConstants.EV_ACTION) { + return "EV_ACTION"; + } else if (event == EvConstants.EV_EVENT_TAG) { + return "EV_EVENT_TAG"; + } else if (event == EvConstants.EV_S_CRTM_CONTENTS) { + return "EV_S_CRTM_CONTENTS"; + } else if (event == EvConstants.EV_S_CRTM_VERSION) { + return "EV_S_CRTM_VERSION"; + } else if (event == EvConstants.EV_CPU_MICROCODE) { + return "EV_CPU_MICROCODE"; + } else if (event == EvConstants.EV_PLATFORM_CONFIG_FLAGS) { + return "EV_PLATFORM_CONFIG_FLAGS "; + } else if (event == EvConstants.EV_TABLE_OF_DEVICES) { + return "EV_TABLE_OF_DEVICES"; + } else if (event == EvConstants.EV_COMPACT_HASH) { + return "EV_COMPACT_HASH"; + } else if (event == EvConstants.EV_IPL) { + return "EV_IPL"; + } else if (event == EvConstants.EV_IPL_PARTITION_DATA) { + return "EV_IPL_PARTITION_DATA"; + } else if (event == EvConstants.EV_NONHOST_CODE) { + return "EV_NONHOST_CODE"; + } else if (event == EvConstants.EV_NONHOST_CONFIG) { + return "EV_NONHOST_CONFIG"; + } else if (event == EvConstants.EV_NONHOST_INFO) { + return "EV_NONHOST_INFO"; + } else if (event == EvConstants.EV_EV_OMIT_BOOT_DEVICES_EVENTS) { + return "EV_EV_OMIT_BOOT_DEVICES_EVENTS"; + } else if (event == EvConstants.EV_EFI_EVENT_BASE) { + return "EV_EFI_EVENT_BASE"; + } else if (event == EvConstants.EV_EFI_VARIABLE_DRIVER_CONFIG) { + return "EV_EFI_VARIABLE_DRIVER_CONFIG"; + } else if (event == EvConstants.EV_EFI_VARIABLE_BOOT) { + return "EV_EFI_VARIABLE_BOOT"; + } else if (event == EvConstants.EV_EFI_BOOT_SERVICES_APPLICATION) { + return "EV_EFI_BOOT_SERVICES_APPLICATION"; + } else if (event == EvConstants.EV_EFI_BOOT_SERVICES_DRIVER) { + return "EV_EFI_BOOT_SERVICES_DRIVER"; + } else if (event == EvConstants.EV_EFI_RUNTIME_SERVICES_DRIVER) { + return "EV_EFI_RUNTIME_SERVICES_DRIVER"; + } else if (event == EvConstants.EV_EFI_GPT_EVENT) { + return "EV_EFI_GPT_EVENT"; + } else if (event == EvConstants.EV_EFI_ACTION) { + return "EV_EFI_ACTION"; + } else if (event == EvConstants.EV_EFI_PLATFORM_FIRMWARE_BLOB) { + return "EV_EFI_PLATFORM_FIRMWARE_BLOB"; + } else if (event == EvConstants.EV_EFI_HANDOFF_TABLES) { + return "EV_EFI_HANDOFF_TABLES"; + } else if (event == EvConstants.EV_EFI_HCRTM_EVENT) { + return "EV_EFI_HCRTM_EVENT"; + } else if (event == EvConstants.EV_EFI_VARIABLE_AUTHORITY) { + return "EV_EFI_VARIABLE_AUTHORITY"; + } else { + return "Unknown Event ID " + event + " encountered"; + } + } - /** - * Human readable output of a check of input against the current event hash. - * @return human readable string. - */ - private String eventHashCheck() { - String result = ""; - if (logFormat == 1) { - if (Arrays.equals(this.digest, eventDataSha1hash)) { result - += "Event digest matched hash of the event data " + "\n"; - } else { - result += "Event digest DID NOT match the hash of the event data :" - + HexUtils.byteArrayToHexString(getEventDigest()) + "\n"; - } + /** + * Human readable output of a check of input against the current event hash. + * + * @return human readable string. + */ + private String eventHashCheck() { + String result = ""; + if (logFormat == 1) { + if (Arrays.equals(this.digest, eventDataSha1hash)) { + result + += "Event digest matched hash of the event data " + "\n"; } else { - if (Arrays.equals(this.digest, eventDataSha256hash)) { - result += "Event digest matched hash of the event data " + "\n"; - } else { - result += "Event digest DID NOT match the hash of the event data :" - + HexUtils.byteArrayToHexString(getEventDigest()) + "\n"; - } - } - return result; - } + result += "Event digest DID NOT match the hash of the event data :" + + Hex.encodeHexString(getEventDigest()) + "\n"; + } + } else { + if (Arrays.equals(this.digest, eventDataSha256hash)) { + result += "Event digest matched hash of the event data " + "\n"; + } else { + result += "Event digest DID NOT match the hash of the event data :" + + Hex.encodeHexString(getEventDigest()) + "\n"; + } + } + return result; + } - /** - * Checks a byte array for all zeros. - * @param array holds data to check. - * @return true of all zeros are found. - */ - public boolean isEmpty(final byte[] array) { - for (int i = 0; i < array.length; i++) { - if (array[i] != 0) { - return false; - } - } - return true; - } + /** + * Checks a byte array for all zeros. + * + * @param array holds data to check. + * @return true of all zeros are found. + */ + public boolean isBlank(final byte[] array) { + for (int i = 0; i < array.length; i++) { + if (array[i] != 0) { + return false; + } + } + return true; + } - /** - * Human readable string representing the contents of the Event Log. - * @return Description of the log. - */ - public String toString() { + /** + * Human readable string representing the contents of the Event Log. + * + * @return Description of the log. + */ + public String toString() { return description + "\n"; - } + } - /** - * Human readable string representing the contents of the Event Log. - * @param bEvent event Flag. - * @param bContent content flag. - * @param bHexEvent hex event flag. - * @return Description of the log. - */ - public String toString(final boolean bEvent, final boolean bContent, final boolean bHexEvent) { - StringBuilder sb = new StringBuilder(); - if (bEvent) { - sb.append(description); - } - if (bHexEvent) { - if (bEvent || bContent) { - sb.append("\n"); - } - byte[] eventData = getEvent(); - sb.append("Event (Hex no Content) (" + eventData.length + " bytes): " - + HexUtils.byteArrayToHexString(eventData)); - } - if (bContent) { - byte[] evContent = getEventContent(); - if (bEvent) { - sb.append("\n"); - } - sb.append("Event content (Hex) (" + evContent.length + " bytes): " - + HexUtils.byteArrayToHexString(evContent)); - } + /** + * Human readable string representing the contents of the Event Log. + * + * @param bEvent event Flag. + * @param bContent content flag. + * @param bHexEvent hex event flag. + * @return Description of the log. + */ + public String toString(final boolean bEvent, final boolean bContent, final boolean bHexEvent) { + StringBuilder sb = new StringBuilder(); + if (bEvent) { + sb.append(description); + } + if (bHexEvent) { + if (bEvent || bContent) { + sb.append("\n"); + } + byte[] eventData = getEvent(); + sb.append("Event (Hex no Content) (" + eventData.length + " bytes): " + + Hex.encodeHexString(eventData)); + } + if (bContent) { + byte[] evContent = getEventContent(); + if (bEvent) { + sb.append("\n"); + } + sb.append("Event content (Hex) (" + evContent.length + " bytes): " + + Hex.encodeHexString(evContent)); + } return sb.toString() + "\n"; - } + } } diff --git a/HIRS_Utils/src/main/java/hirs/tpm/eventlog/events/EvPostCode.java b/HIRS_Utils/src/main/java/hirs/tpm/eventlog/events/EvPostCode.java index 6deb1ef3..fca2257b 100644 --- a/HIRS_Utils/src/main/java/hirs/tpm/eventlog/events/EvPostCode.java +++ b/HIRS_Utils/src/main/java/hirs/tpm/eventlog/events/EvPostCode.java @@ -34,19 +34,18 @@ public class EvPostCode { public EvPostCode(final byte[] postCode) { // 2 ways post code has been implemented, check for the ascii string first if (isAscii(postCode)) { - String info = new String(postCode, StandardCharsets.UTF_8); - codeInfo = info; + codeInfo = new String(postCode, StandardCharsets.UTF_8); bisString = true; - } else { - blob = new UefiFirmware(postCode); - } + } else { + blob = new UefiFirmware(postCode); + } } /** * Returns the UEFI Defined Firmware Blob information. * @return UEFI Defined Firmware Blob information. */ - public UefiFirmware getfirmwareBlob() { + public UefiFirmware getFirmwareBlob() { return blob; } @@ -75,12 +74,11 @@ public class EvPostCode { * @return true if byte array is a string. */ public static boolean isAscii(final byte[] postCode) { - boolean bisAscii = true; for (byte b : postCode) { if (!Character.isDefined(b)) { return false; } } - return bisAscii; + return true; } } diff --git a/HIRS_Utils/src/main/java/hirs/tpm/eventlog/uefi/UefiFirmware.java b/HIRS_Utils/src/main/java/hirs/tpm/eventlog/uefi/UefiFirmware.java index 5dd1d7c8..83f86987 100644 --- a/HIRS_Utils/src/main/java/hirs/tpm/eventlog/uefi/UefiFirmware.java +++ b/HIRS_Utils/src/main/java/hirs/tpm/eventlog/uefi/UefiFirmware.java @@ -1,73 +1,90 @@ package hirs.tpm.eventlog.uefi; import java.math.BigInteger; + import hirs.utils.HexUtils; /** * Class to process the PFP defined UEFI_PLATFORM_FIRMWARE_BLOB structure. - * + *

* typedef struct tdUEFI_PLATFORM_FIRMWARE_BLOB { - * UEFI_PHYSICAL_ADDRESS BlobBase; - * UINT64 BlobLength; + * UEFI_PHYSICAL_ADDRESS BlobBase; + * UINT64 BlobLength; * } UEFI_PLATFORM_FIRMWARE_BLOB; */ public class UefiFirmware { - private boolean berror = false; - /** byte array holding the firmwares physical address. */ - private byte[] physicalAddress = null; - /** byte array holding the uefi address length. */ - private byte[] addressLength = null; - /** uefi physical address. */ - private int blobAddress = 0; - /** uefi address length. */ - private int blobLength = 0; + private boolean bError = false; + /** + * byte array holding the firmwares physical address. + */ + private byte[] physicalAddress = null; + /** + * byte array holding the uefi address length. + */ + private byte[] addressLength = null; + /** + * uefi physical address. + */ + private int blobAddress = 0; + /** + * uefi address length. + */ + private int blobLength = 0; - /** - * UefiFirmware constructor. - * @param blob byte array holding a Firmware Blob. - */ - public UefiFirmware(final byte[] blob) { - if (blob.length != UefiConstants.SIZE_16) { - berror = true; - } else { - physicalAddress = new byte[UefiConstants.SIZE_8]; - addressLength = new byte[UefiConstants.SIZE_8]; - System.arraycopy(blob, 0, physicalAddress, 0, UefiConstants.SIZE_8); - System.arraycopy(blob, UefiConstants.SIZE_8, addressLength, 0, UefiConstants.SIZE_8); - byte[] lelength = HexUtils.leReverseByte(addressLength); - BigInteger bigIntLength = new BigInteger(lelength); - blobLength = bigIntLength.intValue(); - byte[]leAddress = HexUtils.leReverseByte(physicalAddress); - BigInteger bigIntAddress = new BigInteger(leAddress); - blobAddress = bigIntAddress.intValue(); - } -} -/** - * Returns the uefi firmware blobs physical address. - * @return uefi firmware address. - */ -public int getPhysicalAddress() { - return blobAddress; - } -/** - * Returns the length of the blobs physical address. - * @return length of the address. - */ -public int getBlobLength() { - return blobLength; -} -/** - * Returns a description of the firmware blobs location. - * @return a description of the the firmware blobs location. - */ -public String toString() { - String blobInfo = ""; - if (!berror) { - blobInfo += " Platform Firwmare Blob Address = " + Integer.toHexString(blobAddress); - blobInfo += " length = " + blobLength; - } else { - blobInfo += " Invalid Firmware Blob event encountered"; - } - return blobInfo; - } + /** + * UefiFirmware constructor. + * + * @param blob byte array holding a Firmware Blob. + */ + public UefiFirmware(final byte[] blob) { + if (blob.length != UefiConstants.SIZE_16) { + bError = true; + } else { + physicalAddress = new byte[UefiConstants.SIZE_8]; + addressLength = new byte[UefiConstants.SIZE_8]; + System.arraycopy(blob, 0, physicalAddress, 0, UefiConstants.SIZE_8); + System.arraycopy(blob, UefiConstants.SIZE_8, addressLength, 0, UefiConstants.SIZE_8); + byte[] lelength = HexUtils.leReverseByte(addressLength); + BigInteger bigIntLength = new BigInteger(lelength); + blobLength = bigIntLength.intValue(); + byte[] leAddress = HexUtils.leReverseByte(physicalAddress); + BigInteger bigIntAddress = new BigInteger(leAddress); + blobAddress = bigIntAddress.intValue(); + } + } + + /** + * Returns the uefi firmware blobs physical address. + * + * @return uefi firmware address. + */ + public int getPhysicalAddress() { + return blobAddress; + } + + /** + * Returns the length of the blobs physical address. + * + * @return length of the address. + */ + public int getBlobLength() { + return blobLength; + } + + /** + * Returns a description of the firmware blobs location. + * + * @return a description of the the firmware blobs location. + */ + public String toString() { + StringBuilder blobInfo = new StringBuilder(); + if (!bError) { + blobInfo.append(String.format(" Platform Firmware Blob Address = %s", + Integer.toHexString(blobAddress))); + blobInfo.append(String.format(" length = %d", blobLength)); + } else { + blobInfo.append(" Invalid Firmware Blob event encountered"); + } + return blobInfo.toString(); + } } diff --git a/tools/tcg_eventlog_tool/src/main/java/hirs/tcg_eventlog/Main.java b/tools/tcg_eventlog_tool/src/main/java/hirs/tcg_eventlog/Main.java index e3d5a4b6..81da7c90 100644 --- a/tools/tcg_eventlog_tool/src/main/java/hirs/tcg_eventlog/Main.java +++ b/tools/tcg_eventlog_tool/src/main/java/hirs/tcg_eventlog/Main.java @@ -26,145 +26,147 @@ final class Main { private static byte[] eventLog = null; private static boolean bContentFlag, bEventFlag, bHexEvent, bHexFlag, bPcrFlag = false; -/** - * Main Constructor. - * @param args command line parameters. - */ -public static void main(final String[] args) { -commander = new Commander(args); - if (!commander.getValidityFlag()) { - System.out.print("Program exiting without processs due to issues with" - + " parameters provided."); - System.exit(1); - } - if (commander.hasArguments()) { - if (commander.getDoneFlag()) { - System.exit(0); - } - if (commander.getHelpFlag()) { - commander.printHelp(""); - System.exit(0); - } - if (commander.getOutputFlag()) { - try { - outputStream = new FileOutputStream(commander.getOutputFileName()); - } catch (FileNotFoundException e) { - System.out.print("Error opening output file" + commander.getOutputFileName() - + "\nError was " + e.getMessage()); - System.exit(1); - } - } - if (commander.getFileFlag()) { - eventLog = openLog(commander.getInFileName()); - } - if (commander.getContentFlag()) { - bContentFlag = true; - } - if (commander.getDiffFlag()) { - bEventFlag = true; - String results = compareLogs(commander.getInFileName(), - commander.getInFile2Name()); - writeOut(results); - System.exit(0); - } - if (commander.getEventIdsFlag()) { - bEventFlag = true; - } - if (commander.getEventHexFlag()) { - bHexEvent = true; - } - if (commander.getPCRFlag()) { - bPcrFlag = true; - } - if (commander.getVerifyFile()) { - System.out.print("Verify option is not yet implemented"); + /** + * Main Constructor. + * + * @param args command line parameters. + */ + public static void main(final String[] args) { + commander = new Commander(args); + if (!commander.getValidityFlag()) { + System.out.print("Program exiting without processs due to issues with" + + " parameters provided."); System.exit(1); } - if (commander.getHexFlag()) { - bHexFlag = true; - } -} else { - System.out.print("Nothing to do: No Parameters provided."); - System.exit(1); -} // End commander processing - - try { - if (eventLog == null) { - eventLog = openLog(""); - } - // Main Event processing - TCGEventLog evLog = new TCGEventLog(eventLog, bEventFlag, bContentFlag, bHexEvent); - if (bPcrFlag) { - String[] pcrs = evLog.getExpectedPCRValues(); - int count = 0; - if (!bHexFlag) { - writeOut("Expected Platform Configuration Register (PCR) values" - + " derived from the Event Log: \n\n"); + if (commander.hasArguments()) { + if (commander.getDoneFlag()) { + System.exit(0); } - for (String pcr: pcrs) { - if (count++ == commander.getPcrNumber() || (commander.getPcrNumber() == -1)) { - if (bHexFlag) { - writeOut(pcr.toString() + "\n"); - } else { - writeOut(" pcr " + (count - 1) + " = " + pcr.toString() + "\n"); + if (commander.getHelpFlag()) { + commander.printHelp(""); + System.exit(0); + } + if (commander.getOutputFlag()) { + try { + outputStream = new FileOutputStream(commander.getOutputFileName()); + } catch (FileNotFoundException e) { + System.out.print("Error opening output file" + commander.getOutputFileName() + + "\nError was " + e.getMessage()); + System.exit(1); + } + } + if (commander.getFileFlag()) { + eventLog = openLog(commander.getInFileName()); + } + if (commander.getContentFlag()) { + bContentFlag = true; + } + if (commander.getDiffFlag()) { + bEventFlag = true; + String results = compareLogs(commander.getInFileName(), + commander.getInFile2Name()); + writeOut(results); + System.exit(0); + } + if (commander.getEventIdsFlag()) { + bEventFlag = true; + } + if (commander.getEventHexFlag()) { + bHexEvent = true; + } + if (commander.getPCRFlag()) { + bPcrFlag = true; + } + if (commander.getVerifyFile()) { + System.out.print("Verify option is not yet implemented"); + System.exit(1); + } + if (commander.getHexFlag()) { + bHexFlag = true; + } + } else { + System.out.print("Nothing to do: No Parameters provided."); + System.exit(1); + } // End commander processing + + try { + if (eventLog == null) { + eventLog = openLog(""); + } + // Main Event processing + TCGEventLog evLog = new TCGEventLog(eventLog, bEventFlag, bContentFlag, bHexEvent); + if (bPcrFlag) { + String[] pcrs = evLog.getExpectedPCRValues(); + int count = 0; + if (!bHexFlag) { + writeOut("Expected Platform Configuration Register (PCR) values" + + " derived from the Event Log: \n\n"); + } + for (String pcr : pcrs) { + if (count++ == commander.getPcrNumber() || (commander.getPcrNumber() == -1)) { + if (bHexFlag) { + writeOut(pcr.toString() + "\n"); + } else { + writeOut(" pcr " + (count - 1) + " = " + pcr.toString() + "\n"); + } } } - } - if (!bHexFlag) { - writeOut("\n----------------- End PCR Values ----------------- \n\n"); - } - } - - // General event log output - if (bEventFlag) { - if (!bHexFlag) { - if (evLog.isCryptoAgile()) { - writeOut("\nEvent Log follows the \"Crypto Agile\" format and has " - + evLog.getEventList().size() + " events:\n\n"); - } else { - writeOut("\nEvent Log follows the \"SHA1\" format and has " - + evLog.getEventList().size() + " events:\n\n"); + if (!bHexFlag) { + writeOut("\n----------------- End PCR Values ----------------- \n\n"); } } - int eventCount = 0; - for (TpmPcrEvent event: evLog.getEventList()) { + + // General event log output + if (bEventFlag) { + if (!bHexFlag) { + if (evLog.isCryptoAgile()) { + writeOut("\nEvent Log follows the \"Crypto Agile\" format and has " + + evLog.getEventList().size() + " events:\n\n"); + } else { + writeOut("\nEvent Log follows the \"SHA1\" format and has " + + evLog.getEventList().size() + " events:\n\n"); + } + } + int eventCount = 0; + for (TpmPcrEvent event : evLog.getEventList()) { if ((commander.getEventNumber() == eventCount++) - || commander.getEventNumber() == -1) { + || commander.getEventNumber() == -1) { if ((commander.getPcrNumber() == event.getPcrIndex()) || commander.getPcrNumber() == -1) { if (bHexFlag) { - if (bEventFlag || bHexEvent) { - writeOut(HexUtils.byteArrayToHexString(event.getEvent()) + "\n"); - } - if (bContentFlag) { - writeOut(HexUtils.byteArrayToHexString(event.getEventContent()) - + "\n"); - } + if (bEventFlag || bHexEvent) { + writeOut(HexUtils.byteArrayToHexString(event.getEvent()) + "\n"); + } + if (bContentFlag) { + writeOut(HexUtils.byteArrayToHexString(event.getEventContent()) + + "\n"); + } } else { - writeOut(event.toString(bEventFlag, bContentFlag, bHexEvent) + "\n"); + writeOut(event.toString(bEventFlag, bContentFlag, bHexEvent) + "\n"); } } + } } } + } catch (IOException i) { + System.out.print("IO error processing Event Log " + commander.getInFileName() + + "\nError was " + i.toString()); + System.exit(1); + } catch (CertificateException c) { + System.out.print("Certificate error processing Event Log " + commander.getInFileName() + + "\nError was " + c.toString()); + System.exit(1); + } catch (NoSuchAlgorithmException a) { + System.out.print("Algorithm error processing Event Log " + commander.getInFileName() + + "\nError was " + a.toString()); + System.exit(1); } - } catch (IOException i) { - System.out.print("IO error processing Event Log " + commander.getInFileName() - + "\nError was " + i.toString()); - System.exit(1); - } catch (CertificateException c) { - System.out.print("Certificate error processing Event Log " + commander.getInFileName() - + "\nError was " + c.toString()); - System.exit(1); - } catch (NoSuchAlgorithmException a) { - System.out.print("Algorithm error processing Event Log " + commander.getInFileName() - + "\nError was " + a.toString()); - System.exit(1); } -} /** * Opens a TCG Event log file. - * @param fileName Name of the log file. Will use a OS specific default. + * + * @param fileName Name of the log file. Will use a OS specific default. * @return a byte array holding the entire log */ public static byte[] openLog(final String fileName) { @@ -186,10 +188,10 @@ commander = new Commander(args); Path path = Paths.get(fName); rawLog = Files.readAllBytes(path); if (!bHexFlag) { - writeOut("tcg_eventlog_tool is opening file:" + path + "\n"); + writeOut("tcg_eventlog_tool is opening file:" + path + "\n"); } } catch (Exception e) { - String error = "Error reading event Log File: " + e.toString(); + String error = "Error reading event Log File: " + e.toString(); if (bDefault) { error += "\nTry using the -f option to specify an Event Log File"; } @@ -201,6 +203,7 @@ commander = new Commander(args); /** * Write data out to the system and/or a file. + * * @param data */ private static void writeOut(final String data) { @@ -219,6 +222,7 @@ commander = new Commander(args); /** * Compares 2 Event Logs and returns a string based upon the results. * Uses the Events digest field for comparisons. + * * @param logFileName1 Log file to use as a reference. * @param logFileName2 Log file to compare to the reference. * @return A sting containing human readable results. @@ -232,12 +236,12 @@ commander = new Commander(args); try { eventLog1 = new TCGEventLog(evLog); } catch (Exception e) { - sb.append("\nError processing event log " + logFileName1 + " : " + e.getMessage()); + sb.append("\nError processing event log " + logFileName1 + " : " + e.getMessage()); return sb.toString(); } try { eventLog2 = new TCGEventLog(evLog2); - ArrayList errors = diffEventLogs(eventLog1.getEventList(), + ArrayList errors = diffEventLogs(eventLog1.getEventList(), eventLog2.getEventList(), commander.getPcrNumber()); if (errors.isEmpty() && !bHexFlag) { sb.append("\nEvent Log " + logFileName1 + " MATCHED EventLog " + logFileName2); @@ -245,8 +249,8 @@ commander = new Commander(args); if (!errors.isEmpty() && !bHexFlag) { sb.append("\nEvent Log " + logFileName1 + " did NOT match EventLog " + logFileName2 + "\n"); - sb.append("There were " + errors.size() + " event mismatches: \n\n"); - } + sb.append("There were " + errors.size() + " event mismatches: \n\n"); + } for (TpmPcrEvent error : errors) { if (bHexFlag) { if (bEventFlag || bHexEvent) { @@ -254,51 +258,53 @@ commander = new Commander(args); } if (bContentFlag) { sb.append(HexUtils.byteArrayToHexString(error.getEventContent()) - + "\n"); + + "\n"); } - } else { - sb.append(error.toString(bEventFlag, bContentFlag, bHexEvent) + "\n"); - } + } else { + sb.append(error.toString(bEventFlag, bContentFlag, bHexEvent) + "\n"); + } } } } catch (IOException i) { System.out.print("IO error processing Event Log " + commander.getInFileName() - + "\nError was " + i.toString()); + + "\nError was " + i.toString()); System.exit(1); } catch (CertificateException c) { System.out.print("Certificate error processing Event Log " + commander.getInFileName() - + "\nError was " + c.toString()); + + "\nError was " + c.toString()); + System.exit(1); + } catch (NoSuchAlgorithmException a) { + System.out.print("Algorithm error processing Event Log " + commander.getInFileName() + + "\nError was " + a.toString()); System.exit(1); - } catch (NoSuchAlgorithmException a) { - System.out.print("Algorithm error processing Event Log " + commander.getInFileName() - + "\nError was " + a.toString()); - System.exit(1); } return sb.toString(); } + /** * Compare this event log against a second event log. * Returns a String Array of event descriptions in which the digests from the first - * did no match the second. Return value is null if all events matched. - * @param eventList initial events. + * did no match the second. Return value is null if all events matched. + * + * @param eventList initial events. * @param eventList2 events to compare against. - * @param pcr used as a filter. Use -1 to check all pcrs. + * @param pcr used as a filter. Use -1 to check all pcrs. * @return array list of strings. Null of no events mismatched. */ public static ArrayList diffEventLogs(final ArrayList eventList, - final ArrayList eventList2, final int pcr) { + final ArrayList eventList2, final int pcr) { ArrayList results = new ArrayList(); for (TpmPcrEvent event2 : eventList2) { if (pcr >= 0) { if (event2.getPcrIndex() == pcr) { if (!digestMatch(eventList, event2)) { results.add(event2); - } + } } } else { if (!digestMatch(eventList, event2)) { results.add(event2); - } + } } } return results; @@ -306,8 +312,9 @@ commander = new Commander(args); /** * Checks a digest from a single event against all digests with the same index in an Event Log. + * * @param eventLog The Reference Event log. - * @param event single event to match. + * @param event single event to match. * @return */ private static boolean digestMatch(final ArrayList eventLog, From 778380f70c2583433f74c8c7f53626a9e54e6b68 Mon Sep 17 00:00:00 2001 From: Cyrus <24922493+cyrus-dev@users.noreply.github.com> Date: Fri, 25 Sep 2020 08:57:12 -0400 Subject: [PATCH 03/12] This should finish off the code changes for issues #280. --- ...eferenceManifestDetailsPageController.java | 71 ++++++++++--------- .../ReferenceManifestPageController.java | 26 +++---- .../main/webapp/WEB-INF/jsp/rim-details.jsp | 20 +++++- .../src/main/webapp/common/rim_details.css | 36 ++++++++++ 4 files changed, 101 insertions(+), 52 deletions(-) create mode 100644 HIRS_AttestationCAPortal/src/main/webapp/common/rim_details.css diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java index 9a7da962..64cd88cc 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java @@ -4,21 +4,21 @@ import hirs.data.persist.BaseReferenceManifest; import hirs.data.persist.ReferenceManifest; import hirs.data.persist.SupportReferenceManifest; import hirs.data.persist.SwidResource; -import hirs.persist.DBManagerException; import hirs.persist.ReferenceManifestManager; import hirs.tpm.eventlog.TCGEventLog; import hirs.attestationca.portal.page.Page; import hirs.attestationca.portal.page.PageController; import hirs.attestationca.portal.page.PageMessages; import hirs.attestationca.portal.page.params.ReferenceManifestDetailsPageParams; + import java.io.IOException; -import java.nio.file.NoSuchFileException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.ArrayList; +import java.util.Set; import java.util.UUID; import org.apache.logging.log4j.LogManager; @@ -57,13 +57,13 @@ public class ReferenceManifestDetailsPageController * Returns the filePath for the view and the data model for the page. * * @param params The object to map url parameters into. - * @param model The data model for the request. Can contain data from - * redirect. + * @param model The data model for the request. Can contain data from + * redirect. * @return the path for the view and data model for the page. */ @Override public ModelAndView initPage(final ReferenceManifestDetailsPageParams params, - final Model model) { + final Model model) { // get the basic information to render the page ModelAndView mav = getBaseModelAndView(); PageMessages messages = new PageMessages(); @@ -106,16 +106,16 @@ public class ReferenceManifestDetailsPageController * This method takes the place of an entire class for a string builder. * Gathers all information and returns it for displays. * - * @param uuid database reference for the requested RIM. + * @param uuid database reference for the requested RIM. * @param referenceManifestManager the reference manifest manager. * @return mapping of the RIM information from the database. - * @throws java.io.IOException error for reading file bytes. + * @throws java.io.IOException error for reading file bytes. * @throws NoSuchAlgorithmException If an unknown Algorithm is encountered. - * @throws CertificateException if a certificate doesn't parse. + * @throws CertificateException if a certificate doesn't parse. */ public static HashMap getRimDetailInfo(final UUID uuid, - final ReferenceManifestManager referenceManifestManager) throws IOException, - CertificateException, NoSuchAlgorithmException { + final ReferenceManifestManager referenceManifestManager) throws IOException, + CertificateException, NoSuchAlgorithmException { HashMap data = new HashMap<>(); ReferenceManifest rim = ReferenceManifest @@ -169,7 +169,6 @@ public class ReferenceManifestDetailsPageController data.put("pcUriLocal", bRim.getPcURILocal()); data.put("rimLinkHash", bRim.getRimLinkHash()); data.put("rimType", bRim.getRimType()); - data.put("associatedRim", bRim.getAssociatedRim()); List resources = bRim.parseResource(); String resourceFilename = null; @@ -177,45 +176,49 @@ public class ReferenceManifestDetailsPageController // going to have to pull the filename and grab that from the DB // to get the id to make the link - try { - for (SwidResource swidRes : resources) { - resourceFilename = swidRes.getName(); - ReferenceManifest dbRim = ReferenceManifest.select( - referenceManifestManager).byFileName(resourceFilename).getRIM(); + for (SwidResource swidRes : resources) { + resourceFilename = swidRes.getName(); + ReferenceManifest dbRim = ReferenceManifest.select( + referenceManifestManager).byFileName(resourceFilename).getRIM(); - if (dbRim != null) { - logProcessor = new TCGEventLog(dbRim.getRimBytes()); - swidRes.setPcrValues(Arrays.asList( - logProcessor.getExpectedPCRValues())); + if (dbRim != null) { + logProcessor = new TCGEventLog(dbRim.getRimBytes()); + swidRes.setPcrValues(Arrays.asList( + logProcessor.getExpectedPCRValues())); - if (bRim.getAssociatedRim() == null) { - bRim.setAssociatedRim(dbRim.getId()); - } - } else { - swidRes.setPcrValues(new ArrayList<>()); + if (bRim.getAssociatedRim() == null) { + bRim.setAssociatedRim(dbRim.getId()); } + } else { + swidRes.setPcrValues(new ArrayList<>()); } - } catch (NoSuchFileException nsfEx) { - LOGGER.error(String.format("File Not found!: %s", - resourceFilename)); - LOGGER.error(nsfEx); - } catch (DBManagerException dbmEx) { - LOGGER.error(dbmEx); } data.put("associatedRim", bRim.getAssociatedRim()); data.put("swidFiles", resources); } else if (rim instanceof SupportReferenceManifest) { SupportReferenceManifest sRim = (SupportReferenceManifest) rim; - data.put("baseRim", sRim.getFileName()); + + if (sRim.getAssociatedRim() == null) { + Set rims = ReferenceManifest + .select(referenceManifestManager).getRIMs(); + for (ReferenceManifest dbRim : rims) { + if (dbRim instanceof BaseReferenceManifest + && dbRim.getTagId().equals(sRim.getTagId())) { + sRim.setAssociatedRim(dbRim.getId()); + break; + } + } + } + data.put("baseRim", sRim.getTagId()); data.put("associatedRim", sRim.getAssociatedRim()); data.put("rimType", sRim.getRimType()); TCGEventLog logProcessor = new TCGEventLog(sRim.getRimBytes()); data.put("events", logProcessor.getEventList()); } else { - LOGGER.error(String.format("Unable to find Reference Integrity " - + "Manifest with ID: %s", uuid)); + LOGGER.error(String.format("Unable to find Reference Integrity " + + "Manifest with ID: %s", uuid)); } return data; diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java index f9a08d69..9c8eb677 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java @@ -28,7 +28,6 @@ import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.UUID; -import java.nio.file.Path; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletResponse; @@ -189,7 +188,6 @@ public class ReferenceManifestPageController Map model = new HashMap<>(); PageMessages messages = new PageMessages(); String fileName; - Path filePath; Pattern pattern; Matcher matcher; boolean supportRIM = false; @@ -208,26 +206,24 @@ public class ReferenceManifestPageController .select(referenceManifestManager).getRIMs(); // update information for associated support rims - if (supportRIM) { - for (ReferenceManifest element : rims) { + for (ReferenceManifest element : rims) { + if (supportRIM) { if (element instanceof BaseReferenceManifest) { BaseReferenceManifest bRim = (BaseReferenceManifest) element; for (SwidResource swid : bRim.parseResource()) { if (swid.getName().equals(rim.getFileName())) { rim.setFirmwareVersion(swid.getSize()); - rim.setPlatformManufacturer(element.getPlatformManufacturer()); - rim.setPlatformModel(element.getPlatformModel()); - rim.setTagId(element.getTagId()); - rim.setAssociatedRim(element.getId()); + rim.setPlatformManufacturer(bRim.getPlatformManufacturer()); + rim.setPlatformModel(bRim.getPlatformModel()); + rim.setTagId(bRim.getTagId()); + rim.setAssociatedRim(bRim.getId()); break; } } } - } - } else { - BaseReferenceManifest bRim = (BaseReferenceManifest) rim; - for (SwidResource swid : bRim.parseResource()) { - for (ReferenceManifest element : rims) { + } else { + BaseReferenceManifest bRim = (BaseReferenceManifest) rim; + for (SwidResource swid : bRim.parseResource()) { if (element instanceof SupportReferenceManifest) { SupportReferenceManifest sRim = (SupportReferenceManifest) element; if (swid.getName().equals(sRim.getFileName())) { @@ -239,8 +235,8 @@ public class ReferenceManifestPageController try { referenceManifestManager.update(sRim); } catch (DBManagerException dbmEx) { - LOGGER.error(String.format("Couldn't update Base RIM %s with " - + "associated UUID %s", rim.getTagId(), + LOGGER.error(String.format("Couldn't update Support RIM " + + "%s with associated UUID %s", rim.getTagId(), sRim.getId()), dbmEx); } break; diff --git a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp index 46629bed..e801ab21 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp +++ b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp @@ -28,7 +28,6 @@ ${initialData.associatedRim} -

Base RIM not uploaded from the ACA RIM Page
@@ -54,18 +53,18 @@ ${count} - ${event.getPcrIndex()} + PCR${event.getPcrIndex()} ${event.getEventTypeStr()} ${event.getEventDigestStr()} ${event.getEventContentStr()} -
+
${initialData.events.size()} entries
@@ -279,6 +278,21 @@ } } } + window.onload = function() { + // Constant retrieved from server-side via JSP + var maxRows = 11; + + var table = document.getElementById('eventLog'); + var wrapper = table.parentNode; + var rowsInTable = table.rows.length; + var height = 0; + if (rowsInTable > maxRows) { + for (var i = 0; i < maxRows; i++) { + height += table.rows[i].clientHeight; + } + wrapper.style.height = height + "px"; + } + } diff --git a/HIRS_AttestationCAPortal/src/main/webapp/common/rim_details.css b/HIRS_AttestationCAPortal/src/main/webapp/common/rim_details.css new file mode 100644 index 00000000..36170572 --- /dev/null +++ b/HIRS_AttestationCAPortal/src/main/webapp/common/rim_details.css @@ -0,0 +1,36 @@ +#eventInput { + width: 100%; + font-size: 16px; /* Increase font-size */ + padding: 12px 20px 12px 40px; /* Add some padding */ + border: 1px solid #ddd; /* Add a grey border */ + margin-bottom: 12px; /* Add some space below the input */ +} + +#tableDivTag { + padding-top: 5px; + padding-left: 125px; + padding-right: 150px; + overflow-y: scroll; +} + +#eventLog { + border-collapse: collapse; /* Collapse borders */ + width: 100%; + border: 1px solid #ddd; /* Add a grey border */ + font-size: 14px; /* Increase font-size */ +} + +#eventLog th, #eventLog td { + text-align: left; /* Left-align text */ + padding: 10px; /* Add padding */ +} + +#eventLog tr { + /* Add a bottom border to all table rows */ + border-bottom: 1px solid #ddd; +} + +#eventLog tr.header, #eventLog tr:hover { + /* Add a grey background color to the table header and on hover */ + background-color: #f1f1f1; +} From 2cb7c26fc37983005587458bff74355b2deb3c0c Mon Sep 17 00:00:00 2001 From: Cyrus <24922493+cyrus-dev@users.noreply.github.com> Date: Tue, 29 Sep 2020 06:27:43 -0400 Subject: [PATCH 04/12] Simplified names of initialData fields for RIM details page/controller --- .../controllers/ReferenceManifestDetailsPageController.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java index 64cd88cc..aedd4d55 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java @@ -151,8 +151,8 @@ public class ReferenceManifestDetailsPageController // Link data.put("linkHref", bRim.getLinkHref()); data.put("linkRel", bRim.getLinkRel()); - data.put("supportBaseRimId", ""); - data.put("supportBaseRimTagId", ""); + data.put("supportRimId", ""); + data.put("supportRimTagId", ""); data.put("platformManufacturer", bRim.getPlatformManufacturer()); data.put("platformManufacturerId", bRim.getPlatformManufacturerId()); data.put("platformModel", bRim.getPlatformModel()); From 2b5720744580158f0cd919824ccf7b72a7836374 Mon Sep 17 00:00:00 2001 From: Cyrus <24922493+cyrus-dev@users.noreply.github.com> Date: Wed, 30 Sep 2020 07:51:27 -0400 Subject: [PATCH 05/12] Updated the Tag Version and version fields for Base and Support rims. In addition, adjusted the lay out of the support rim table so that the events column isn't as long. Instead, the full content shows up in an hover action. --- ...stractAttestationCertificateAuthority.java | 6 +++ ...eferenceManifestDetailsPageController.java | 2 +- .../ReferenceManifestPageController.java | 4 +- .../WEB-INF/jsp/reference-manifests.jsp | 2 +- .../main/webapp/WEB-INF/jsp/rim-details.jsp | 7 +--- .../src/main/webapp/common/rim_details.css | 10 +++++ .../data/persist/BaseReferenceManifest.java | 3 ++ .../hirs/data/persist/ReferenceManifest.java | 38 +++++++++---------- 8 files changed, 44 insertions(+), 28 deletions(-) diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/AbstractAttestationCertificateAuthority.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/AbstractAttestationCertificateAuthority.java index 46686746..f56cc6e3 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/AbstractAttestationCertificateAuthority.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/AbstractAttestationCertificateAuthority.java @@ -515,8 +515,14 @@ public abstract class AbstractAttestationCertificateAuthority if (request.getQuote() != null && !request.getQuote().isEmpty()) { parseTPMQuote(request.getQuote().toStringUtf8()); } + if (request.getPcrslist() != null) { + LOG.error(String.format("Not Null: %s", request.getPcrslist())); + } else { + LOG.error("The getPcrsList is null"); + } if (request.getPcrslist() != null && !request.getPcrslist().isEmpty()) { this.pcrValues = request.getPcrslist().toStringUtf8(); + LOG.error(String.format("%s", request.getPcrslist().toStringUtf8())); } // Get device name and device diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java index aedd4d55..4cb31788 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java @@ -127,6 +127,7 @@ public class ReferenceManifestDetailsPageController // Software Identity data.put("swidName", bRim.getSwidName()); data.put("swidVersion", bRim.getSwidVersion()); + data.put("swidTagVersion", bRim.getSwidTagVersion()); if (bRim.isSwidCorpus() == 1) { data.put("swidCorpus", "True"); } else { @@ -157,7 +158,6 @@ public class ReferenceManifestDetailsPageController data.put("platformManufacturerId", bRim.getPlatformManufacturerId()); data.put("platformModel", bRim.getPlatformModel()); data.put("platformVersion", bRim.getPlatformVersion()); - data.put("firmwareVersion", bRim.getFirmwareVersion()); data.put("payloadType", bRim.getPayloadType()); data.put("colloquialVersion", bRim.getColloquialVersion()); data.put("edition", bRim.getEdition()); diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java index 9c8eb677..2b4fc8f9 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java @@ -212,7 +212,7 @@ public class ReferenceManifestPageController BaseReferenceManifest bRim = (BaseReferenceManifest) element; for (SwidResource swid : bRim.parseResource()) { if (swid.getName().equals(rim.getFileName())) { - rim.setFirmwareVersion(swid.getSize()); + rim.setSwidTagVersion(bRim.getSwidTagVersion()); rim.setPlatformManufacturer(bRim.getPlatformManufacturer()); rim.setPlatformModel(bRim.getPlatformModel()); rim.setTagId(bRim.getTagId()); @@ -229,7 +229,7 @@ public class ReferenceManifestPageController if (swid.getName().equals(sRim.getFileName())) { sRim.setPlatformManufacturer(bRim.getPlatformManufacturer()); sRim.setPlatformModel(bRim.getPlatformModel()); - sRim.setFirmwareVersion(swid.getSize()); + sRim.setSwidTagVersion(bRim.getSwidTagVersion()); sRim.setTagId(bRim.getTagId()); rim.setAssociatedRim(sRim.getId()); try { diff --git a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/reference-manifests.jsp b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/reference-manifests.jsp index b4d5cda5..2f85be97 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/reference-manifests.jsp +++ b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/reference-manifests.jsp @@ -48,7 +48,7 @@ {data: 'rimType'}, {data: 'platformManufacturer'}, {data: 'platformModel'}, - {data: 'firmwareVersion'}, + {data: 'swidTagVersion'}, { data: 'id', orderable: false, diff --git a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp index e801ab21..319ef09d 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp +++ b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp @@ -56,7 +56,7 @@ PCR${event.getPcrIndex()} ${event.getEventTypeStr()} ${event.getEventDigestStr()} - ${event.getEventContentStr()} + ${event.getEventContentStr()} @@ -73,7 +73,7 @@
SWID Name: ${initialData.swidName}
SWID Version: ${initialData.swidVersion}
SWID Tag ID: ${initialData.swidTagId}
-
SWID Tag Version: 
+
SWID Tag Version: ${initialData.swidTagVersion}
SWID Corpus: 
@@ -127,9 +127,6 @@
Payload Type: ${initialData.payloadType}
- -
Firmware Version: ${initialData.firmwareVersion}
-
Binding Spec: ${initialData.bindingSpec}
Binding Spec Version: ${initialData.bindingSpecVersion}
diff --git a/HIRS_AttestationCAPortal/src/main/webapp/common/rim_details.css b/HIRS_AttestationCAPortal/src/main/webapp/common/rim_details.css index 36170572..0d01c08e 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/common/rim_details.css +++ b/HIRS_AttestationCAPortal/src/main/webapp/common/rim_details.css @@ -34,3 +34,13 @@ /* Add a grey background color to the table header and on hover */ background-color: #f1f1f1; } + +.dataCell { + display: table-cell; + padding: 2px 15px 2px 15px; + white-space: nowrap; + text-overflow: ellipsis; + overflow: hidden; + width: auto; + max-width: 1px; +} \ No newline at end of file diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/BaseReferenceManifest.java b/HIRS_Utils/src/main/java/hirs/data/persist/BaseReferenceManifest.java index 85bb28b5..a48f5693 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/BaseReferenceManifest.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/BaseReferenceManifest.java @@ -109,6 +109,9 @@ public class BaseReferenceManifest extends ReferenceManifest { this.swidPatch = si.isPatch() ? 1 : 0; this.swidSupplemental = si.isSupplemental() ? 1 : 0; this.swidVersion = si.getVersion(); + if (si.getTagVersion() != null) { + this.setSwidTagVersion(si.getTagVersion().toString()); + } for (Object object : si.getEntityOrEvidenceOrLink()) { if (object instanceof JAXBElement) { diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/ReferenceManifest.java b/HIRS_Utils/src/main/java/hirs/data/persist/ReferenceManifest.java index f6802122..0a94056c 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/ReferenceManifest.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/ReferenceManifest.java @@ -99,7 +99,7 @@ public abstract class ReferenceManifest extends ArchivableEntity { @Column private String platformManufacturerId = null; @Column - private String firmwareVersion = null; + private String swidTagVersion = null; @Column private String platformModel = null; @Column(nullable = false) @@ -238,6 +238,24 @@ public abstract class ReferenceManifest extends ArchivableEntity { this.rimType = rimType; } + /** + * Getter for the SWID tag version. + * + * @return string of the tag version number + */ + public String getSwidTagVersion() { + return swidTagVersion; + } + + /** + * Setter for the SWID tag version. + * + * @param swidTagVersion string of the version + */ + public void setSwidTagVersion(final String swidTagVersion) { + this.swidTagVersion = swidTagVersion; + } + /** * Getter for the RIM Tag ID. * @@ -256,24 +274,6 @@ public abstract class ReferenceManifest extends ArchivableEntity { this.tagId = tagId; } - /** - * Getter for the firmware version info. - * - * @return string for the firmware version - */ - public String getFirmwareVersion() { - return firmwareVersion; - } - - /** - * Setter for the firmware version info. - * - * @param firmwareVersion passed in firmware version - */ - public void setFirmwareVersion(final String firmwareVersion) { - this.firmwareVersion = firmwareVersion; - } - /** * Getter for the associated RIM DB ID. * @return UUID for the rim From f4aed453f893b9c30df8aca1d591cf4f3d27bda7 Mon Sep 17 00:00:00 2001 From: Cyrus <24922493+cyrus-dev@users.noreply.github.com> Date: Wed, 30 Sep 2020 10:02:33 -0400 Subject: [PATCH 06/12] Additional visual changes --- .../AbstractAttestationCertificateAuthority.java | 6 ------ .../controllers/ReferenceManifestDetailsPageController.java | 1 + .../src/main/webapp/WEB-INF/jsp/rim-details.jsp | 4 ++-- .../src/main/webapp/common/rim_details.css | 5 +++++ HIRS_ProvisionerTPM2/src/CommandTpm2.cpp | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/AbstractAttestationCertificateAuthority.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/AbstractAttestationCertificateAuthority.java index f56cc6e3..46686746 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/AbstractAttestationCertificateAuthority.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/AbstractAttestationCertificateAuthority.java @@ -515,14 +515,8 @@ public abstract class AbstractAttestationCertificateAuthority if (request.getQuote() != null && !request.getQuote().isEmpty()) { parseTPMQuote(request.getQuote().toStringUtf8()); } - if (request.getPcrslist() != null) { - LOG.error(String.format("Not Null: %s", request.getPcrslist())); - } else { - LOG.error("The getPcrsList is null"); - } if (request.getPcrslist() != null && !request.getPcrslist().isEmpty()) { this.pcrValues = request.getPcrslist().toStringUtf8(); - LOG.error(String.format("%s", request.getPcrslist().toStringUtf8())); } // Get device name and device diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java index 4cb31788..0faf6738 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java @@ -213,6 +213,7 @@ public class ReferenceManifestDetailsPageController data.put("baseRim", sRim.getTagId()); data.put("associatedRim", sRim.getAssociatedRim()); data.put("rimType", sRim.getRimType()); + data.put("tagId", sRim.getTagId()); TCGEventLog logProcessor = new TCGEventLog(sRim.getRimBytes()); data.put("events", logProcessor.getEventList()); diff --git a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp index 319ef09d..e852be97 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp +++ b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp @@ -26,7 +26,7 @@ - ${initialData.associatedRim} + ${initialData.tagId} @@ -55,7 +55,7 @@ ${count} PCR${event.getPcrIndex()} ${event.getEventTypeStr()} - ${event.getEventDigestStr()} + ${event.getEventDigestStr()} ${event.getEventContentStr()} diff --git a/HIRS_AttestationCAPortal/src/main/webapp/common/rim_details.css b/HIRS_AttestationCAPortal/src/main/webapp/common/rim_details.css index 0d01c08e..99056d8e 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/common/rim_details.css +++ b/HIRS_AttestationCAPortal/src/main/webapp/common/rim_details.css @@ -43,4 +43,9 @@ overflow: hidden; width: auto; max-width: 1px; +} + +.digestCell { + max-width: 150px; + word-wrap: break-word; } \ No newline at end of file diff --git a/HIRS_ProvisionerTPM2/src/CommandTpm2.cpp b/HIRS_ProvisionerTPM2/src/CommandTpm2.cpp index f2976299..4815bc18 100644 --- a/HIRS_ProvisionerTPM2/src/CommandTpm2.cpp +++ b/HIRS_ProvisionerTPM2/src/CommandTpm2.cpp @@ -522,8 +522,8 @@ string CommandTpm2::createNvWriteCommandArgs(const string& nvIndex, /** * Method to get a quote (signed pcr selection) from the TPM 2.0 device. * - * @param akLocation location of an activated AK pair - * @param pcrSelection selection of pcrs to sign + * @param nonce blob provided by the ACA when the Identity Claim Request + * @param pcr_election selection of pcrs to sign */ string CommandTpm2::getQuote(const string& pcr_selection, const string& nonce) { From 35dcc226a66a4f6e8f1d184efb95364ee2443c1e Mon Sep 17 00:00:00 2001 From: Cyrus <24922493+cyrus-dev@users.noreply.github.com> Date: Wed, 30 Sep 2020 11:33:28 -0400 Subject: [PATCH 07/12] Updated and fixed the difference in the code from the master branch merge --- .../AbstractAttestationCertificateAuthority.java | 7 ++++--- .../service/SupplyChainValidationServiceImpl.java | 6 ++++-- HIRS_Utils/src/main/java/hirs/data/persist/PCRPolicy.java | 6 ++++++ 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/AbstractAttestationCertificateAuthority.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/AbstractAttestationCertificateAuthority.java index f98b0569..8db7100e 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/AbstractAttestationCertificateAuthority.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/AbstractAttestationCertificateAuthority.java @@ -302,7 +302,6 @@ public abstract class AbstractAttestationCertificateAuthority // update the validation result in the device device.setSupplyChainStatus(summary.getOverallValidationResult()); deviceManager.updateDevice(device); - LOG.error("This is the device id? {} ", device.getId()); // check if supply chain validation succeeded. // If it did not, do not provide the IdentityResponseEnvelope if (summary.getOverallValidationResult() == AppraisalStatus.Status.PASS) { @@ -590,7 +589,9 @@ public abstract class AbstractAttestationCertificateAuthority LOG.error("Supply chain validation did not succeed. " + "Firmware Quote Validation failed. Result is: " + validationResult); - return new byte[]{}; + ProvisionerTpm2.CertificateResponse response = ProvisionerTpm2.CertificateResponse + .newBuilder().setCertificate(ByteString.EMPTY).build(); + return response.toByteArray(); } } else { LOG.error("Could not process credential request. Invalid nonce provided: " @@ -723,7 +724,7 @@ public abstract class AbstractAttestationCertificateAuthority } // Get TPM info, currently unimplemented - TPMInfo tpm = new TPMInfo(); + TPMInfo tpm; try { tpm = new TPMInfo(DeviceInfoReport.NOT_SPECIFIED, (short) 0, diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java index d0809e75..f813c372 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java @@ -429,7 +429,8 @@ public class SupplyChainValidationServiceImpl implements SupplyChainValidationSe + "No associated RIM file could be found for %s", manufacturer)); } else { - List swids = rim.parseResource(); + BaseReferenceManifest bRim = (BaseReferenceManifest) rim; + List swids = bRim.parseResource(); for (SwidResource swid : swids) { baseline = swid.getPcrValues() .toArray(new String[swid.getPcrValues().size()]); @@ -448,7 +449,8 @@ public class SupplyChainValidationServiceImpl implements SupplyChainValidationSe fwStatus.setMessage("Firmware validation of TPM Quote successful."); } else { - fwStatus.setMessage("Firmware validation of TPM Quote failed."); + fwStatus.setMessage("Firmware validation of TPM Quote failed." + + "\nPCR hash and Quote hash do not match."); } } diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/PCRPolicy.java b/HIRS_Utils/src/main/java/hirs/data/persist/PCRPolicy.java index 0c8eeafe..4f9722f6 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/PCRPolicy.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/PCRPolicy.java @@ -120,6 +120,12 @@ public final class PCRPolicy extends Policy { tpmQuote, pcrComposite); try { + /** + * The calculated string is being used in the contains method + * because the TPM Quote's hash isn't just for PCR values, + * it contains the calculated digest of the PCRs, along with + * other information. + */ String calculatedString = Hex.encodeHexString( pcrInfoShort.getCalculatedDigest()); validated = quoteString.contains(calculatedString); From cb4dc0aa7f8cc41f9bef7500ee9d675e884a9290 Mon Sep 17 00:00:00 2001 From: Cyrus <24922493+cyrus-dev@users.noreply.github.com> Date: Wed, 30 Sep 2020 12:26:46 -0400 Subject: [PATCH 08/12] Corrected checkstyles warning --- .../service/SupplyChainValidationServiceImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java index f813c372..e3af160d 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java @@ -449,8 +449,8 @@ public class SupplyChainValidationServiceImpl implements SupplyChainValidationSe fwStatus.setMessage("Firmware validation of TPM Quote successful."); } else { - fwStatus.setMessage("Firmware validation of TPM Quote failed." + - "\nPCR hash and Quote hash do not match."); + fwStatus.setMessage("Firmware validation of TPM Quote failed." + + "\nPCR hash and Quote hash do not match."); } } From 653acd270eeb96eaafae75055f1279d55d8975b7 Mon Sep 17 00:00:00 2001 From: Cyrus <24922493+cyrus-dev@users.noreply.github.com> Date: Thu, 1 Oct 2020 12:14:29 -0400 Subject: [PATCH 09/12] With the changes to how the ReferenceManifest is represented in the code and the previous firmware validation PR update, this branch wasn't properly updated for quote validation. The code was still pulling information for the baseline from an old source that wouldn't work anymore. Therefore all validations for the quote failed. The update now pulls the baseline information from the support RIM which is now stored in the database. --- .../SupplyChainValidationServiceImpl.java | 68 ++++++++++--------- .../hirs/data/persist/ReferenceManifest.java | 7 ++ 2 files changed, 44 insertions(+), 31 deletions(-) diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java index e3af160d..8ed6cdf1 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java @@ -7,6 +7,7 @@ import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import hirs.data.persist.BaseReferenceManifest; +import hirs.data.persist.SupportReferenceManifest; import hirs.data.persist.TPMMeasurementRecord; import hirs.data.persist.SwidResource; import hirs.data.persist.PCRPolicy; @@ -411,6 +412,7 @@ public class SupplyChainValidationServiceImpl implements SupplyChainValidationSe Level level = Level.ERROR; AppraisalStatus fwStatus = new AppraisalStatus(FAIL, SupplyChainCredentialValidator.FIRMWARE_VALID); + SupportReferenceManifest sRim = null; // check if the policy is enabled if (policy.isFirmwareValidationEnabled()) { @@ -418,45 +420,49 @@ public class SupplyChainValidationServiceImpl implements SupplyChainValidationSe String manufacturer = device.getDeviceInfo() .getHardwareInfo().getManufacturer(); - // need to get pcrs - ReferenceManifest rim = ReferenceManifest.select( - this.referenceManifestManager) - .byManufacturer(manufacturer) - .getRIM(); - if (rim == null) { - fwStatus = new AppraisalStatus(FAIL, - String.format("Firmware Quote validation failed: " - + "No associated RIM file could be found for %s", - manufacturer)); - } else { - BaseReferenceManifest bRim = (BaseReferenceManifest) rim; - List swids = bRim.parseResource(); - for (SwidResource swid : swids) { - baseline = swid.getPcrValues() - .toArray(new String[swid.getPcrValues().size()]); + try { + // need to get pcrs + Set rims = ReferenceManifest.select( + this.referenceManifestManager).getRIMs(); + for (ReferenceManifest r : rims) { + if (r instanceof SupportReferenceManifest + && r.getPlatformManufacturer().equals(manufacturer)) { + sRim = (SupportReferenceManifest) r; + } } - String pcrContent = new String(device.getDeviceInfo().getTPMInfo().getPcrValues()); - String[] storedPcrs = buildStoredPcrs(pcrContent, baseline[0].length()); - PCRPolicy pcrPolicy = policy.getPcrPolicy(); - pcrPolicy.setBaselinePcrs(baseline); - // grab the quote - byte[] hash = device.getDeviceInfo().getTPMInfo().getTpmQuoteHash(); - if (pcrPolicy.validateQuote(hash, storedPcrs)) { - level = Level.INFO; - fwStatus = new AppraisalStatus(PASS, - SupplyChainCredentialValidator.FIRMWARE_VALID); - fwStatus.setMessage("Firmware validation of TPM Quote successful."); - + if (sRim == null) { + fwStatus = new AppraisalStatus(FAIL, + String.format("Firmware Quote validation failed: " + + "No associated RIM file could be found for %s", + manufacturer)); } else { - fwStatus.setMessage("Firmware validation of TPM Quote failed." - + "\nPCR hash and Quote hash do not match."); + baseline = sRim.getExpectedPCRList(); + String pcrContent = new String(device.getDeviceInfo() + .getTPMInfo().getPcrValues()); + String[] storedPcrs = buildStoredPcrs(pcrContent, baseline[0].length()); + PCRPolicy pcrPolicy = policy.getPcrPolicy(); + pcrPolicy.setBaselinePcrs(baseline); + // grab the quote + byte[] hash = device.getDeviceInfo().getTPMInfo().getTpmQuoteHash(); + if (pcrPolicy.validateQuote(hash, storedPcrs)) { + level = Level.INFO; + fwStatus = new AppraisalStatus(PASS, + SupplyChainCredentialValidator.FIRMWARE_VALID); + fwStatus.setMessage("Firmware validation of TPM Quote successful."); + + } else { + fwStatus.setMessage("Firmware validation of TPM Quote failed." + + "\nPCR hash and Quote hash do not match."); + } } + } catch (Exception ex) { + LOGGER.error(ex); } quoteScv = buildValidationRecord(SupplyChainValidation .ValidationType.FIRMWARE, - fwStatus.getAppStatus(), fwStatus.getMessage(), rim, level); + fwStatus.getAppStatus(), fwStatus.getMessage(), sRim, level); // Generate validation summary, save it, and return it. List validations = new ArrayList<>(); diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/ReferenceManifest.java b/HIRS_Utils/src/main/java/hirs/data/persist/ReferenceManifest.java index 0a94056c..58f1a69b 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/ReferenceManifest.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/ReferenceManifest.java @@ -338,4 +338,11 @@ public abstract class ReferenceManifest extends ArchivableEntity { && platformModel.equals(that.platformModel) && fileName.equals(that.fileName); } + + @Override + public String toString() { + return String.format("Filename->%s%nPlatform Manufacturer->%s%n" + + "Platform Model->%s%nRIM Type->%s", this.getFileName(), + this.platformManufacturer, this.platformModel, this.getRimType()); + } } From 89fbaa05177059cbfc1b3c2314eb31cc3b8f42a8 Mon Sep 17 00:00:00 2001 From: Cyrus <24922493+cyrus-dev@users.noreply.github.com> Date: Mon, 5 Oct 2020 10:44:18 -0400 Subject: [PATCH 10/12] PCR policy matching wasn't propertly failing because the baseline from the support RIM was not properly populating. --- .../SupplyChainValidationServiceImpl.java | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java index 8ed6cdf1..37edc9bd 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java @@ -12,6 +12,7 @@ import hirs.data.persist.TPMMeasurementRecord; import hirs.data.persist.SwidResource; import hirs.data.persist.PCRPolicy; import hirs.data.persist.ArchivableEntity; +import hirs.tpm.eventlog.TCGEventLog; import hirs.validation.SupplyChainCredentialValidator; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -19,6 +20,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Import; import org.springframework.stereotype.Service; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; @@ -337,9 +339,23 @@ public class SupplyChainValidationServiceImpl implements SupplyChainValidationSe if (rim instanceof BaseReferenceManifest) { BaseReferenceManifest bRim = (BaseReferenceManifest) rim; List swids = bRim.parseResource(); + TCGEventLog logProcessor; for (SwidResource swid : swids) { - baseline = swid.getPcrValues() - .toArray(new String[swid.getPcrValues().size()]); + ReferenceManifest dbRim = ReferenceManifest.select( + referenceManifestManager).byFileName(swid.getName()).getRIM(); + + if (dbRim != null) { + try { + logProcessor = new TCGEventLog(dbRim.getRimBytes()); + baseline = logProcessor.getExpectedPCRValues(); + } catch (CertificateException cEx) { + LOGGER.error(cEx); + } catch (NoSuchAlgorithmException noSaEx) { + LOGGER.error(noSaEx); + } catch (IOException ioEx) { + LOGGER.error(ioEx); + } + } } pcrPolicy.setBaselinePcrs(baseline); From b42dfb577fe70d7f676fdc96b68aa312db7fd9d4 Mon Sep 17 00:00:00 2001 From: Cyrus <24922493+cyrus-dev@users.noreply.github.com> Date: Mon, 5 Oct 2020 11:37:38 -0400 Subject: [PATCH 11/12] The manufacturer look up for a RIM was inadequate. This change pulls down all RIMs and searches for the base RIM that matches instead of just pulling down a RIM by Manufacturer. --- .../SupplyChainValidationServiceImpl.java | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java index 37edc9bd..7474afe0 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java @@ -20,7 +20,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Import; import org.springframework.stereotype.Service; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; @@ -328,16 +327,21 @@ public class SupplyChainValidationServiceImpl implements SupplyChainValidationSe AppraisalStatus fwStatus = null; String manufacturer = device.getDeviceInfo() .getHardwareInfo().getManufacturer(); + ReferenceManifest baseRim = null; + Set rims = ReferenceManifest + .select(referenceManifestManager).getRIMs(); - ReferenceManifest rim = ReferenceManifest.select( - this.referenceManifestManager) - .byManufacturer(manufacturer) - .getRIM(); + for (ReferenceManifest rim : rims) { + if (rim instanceof BaseReferenceManifest + && rim.getPlatformManufacturer().equals(manufacturer)) { + baseRim = rim; + } + } fwStatus = new AppraisalStatus(PASS, SupplyChainCredentialValidator.FIRMWARE_VALID); - if (rim instanceof BaseReferenceManifest) { - BaseReferenceManifest bRim = (BaseReferenceManifest) rim; + if (baseRim != null) { + BaseReferenceManifest bRim = (BaseReferenceManifest) baseRim; List swids = bRim.parseResource(); TCGEventLog logProcessor; for (SwidResource swid : swids) { @@ -408,7 +412,7 @@ public class SupplyChainValidationServiceImpl implements SupplyChainValidationSe } return buildValidationRecord(SupplyChainValidation.ValidationType.FIRMWARE, - fwStatus.getAppStatus(), fwStatus.getMessage(), rim, level); + fwStatus.getAppStatus(), fwStatus.getMessage(), baseRim, level); } /** From 17728d3019d3066db78e3c59f1f20c983905d4e1 Mon Sep 17 00:00:00 2001 From: Cyrus <24922493+cyrus-dev@users.noreply.github.com> Date: Tue, 6 Oct 2020 07:42:15 -0400 Subject: [PATCH 12/12] Updated the error message for no associated RIM not found, cleaned up display of the event content and adjusted the column of the digest display. --- .../SupplyChainValidationServiceImpl.java | 5 +++-- .../main/webapp/WEB-INF/jsp/rim-details.jsp | 12 +++++------ .../src/main/webapp/common/rim_details.css | 6 +++++- .../java/hirs/tpm/eventlog/TpmPcrEvent.java | 21 ++++++++++++++++++- 4 files changed, 34 insertions(+), 10 deletions(-) diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java index 7474afe0..18cc6c5a 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/service/SupplyChainValidationServiceImpl.java @@ -327,6 +327,7 @@ public class SupplyChainValidationServiceImpl implements SupplyChainValidationSe AppraisalStatus fwStatus = null; String manufacturer = device.getDeviceInfo() .getHardwareInfo().getManufacturer(); + String model = device.getDeviceInfo().getHardwareInfo().getProductName(); ReferenceManifest baseRim = null; Set rims = ReferenceManifest .select(referenceManifestManager).getRIMs(); @@ -407,8 +408,8 @@ public class SupplyChainValidationServiceImpl implements SupplyChainValidationSe } else { fwStatus = new AppraisalStatus(FAIL, String.format("Firmware validation failed: " - + "No associated RIM file could be found for %s", - manufacturer)); + + "No associated RIM file could be found for %s:%s", + manufacturer, model)); } return buildValidationRecord(SupplyChainValidation.ValidationType.FIRMWARE, diff --git a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp index e852be97..21ae4324 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp +++ b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/jsp/rim-details.jsp @@ -40,10 +40,10 @@ - - + + - + @@ -52,11 +52,11 @@ - - + + - + diff --git a/HIRS_AttestationCAPortal/src/main/webapp/common/rim_details.css b/HIRS_AttestationCAPortal/src/main/webapp/common/rim_details.css index 99056d8e..ed7c6e70 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/common/rim_details.css +++ b/HIRS_AttestationCAPortal/src/main/webapp/common/rim_details.css @@ -46,6 +46,10 @@ } .digestCell { - max-width: 150px; + max-width: 200px; word-wrap: break-word; +} + +.pcrCell { + max-width: 50px; } \ No newline at end of file diff --git a/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TpmPcrEvent.java b/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TpmPcrEvent.java index f7aec6ef..3553decb 100644 --- a/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TpmPcrEvent.java +++ b/HIRS_Utils/src/main/java/hirs/tpm/eventlog/TpmPcrEvent.java @@ -414,7 +414,7 @@ public class TpmPcrEvent { sb.append("Unknown Event found\n"); } - return sb.toString(); + return cleanTextContent(sb.toString()); } /** @@ -741,4 +741,23 @@ public class TpmPcrEvent { } return sb.toString() + "\n"; } + + /** + * Remove bad visual value text. + * @param text content to operate over. + * @return cleared string + */ + public String cleanTextContent(final String text) { + String result; + // strips off all non-ASCII characters + result = text.replaceAll("[^\\x00-\\x7F]", ""); + + // erases all the ASCII control characters + result = result.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", ""); + + // removes non-printable characters from Unicode + result = result.replaceAll("\\p{C}", ""); + + return result.trim(); + } }
Event #PCR IndexEvent #PCR Index Event TypeDigestDigest Event Content
${count}PCR${event.getPcrIndex()}${count}PCR${event.getPcrIndex()} ${event.getEventTypeStr()} ${event.getEventDigestStr()}${event.getEventContentStr()}
${event.getEventContentStr()}