From 89144f4a80c3a406a89bf49d1427d9de4bf4306f Mon Sep 17 00:00:00 2001 From: iadgovuser29 <33426478+iadgovuser29@users.noreply.github.com> Date: Fri, 12 Apr 2024 14:03:34 -0400 Subject: [PATCH] Creating HardwareManifest proto file --- .../dotnet-build-hardwaremanifest.yml | 25 ++ .../workflows/dotnet-build-paccor_scripts.yml | 29 ++ dotnet/HardwareManifestPlugin/.editorconfig | 2 +- .../HardwareManifestPlugin.sln | 11 +- .../HardwareManifestPlugin.csproj | 38 +- .../Resources/HardwareManifest.proto | 83 ++++ .../HardwareManifestPlugin/src/Convert.cs | 390 ++++++++++++++++++ .../src/HardwareManifest.cs | 41 ++ .../src/IHardwareManifest.cs | 113 +++-- .../src/NameAttributes.cs | 28 -- .../HardwareManifestPluginManager.csproj | 9 +- .../src/HardwareManifestPluginManagerUtils.cs | 130 +++--- .../src/PluginLoadContext.cs | 16 +- .../HardwareManifestPluginTests.cs | 23 ++ .../HardwareManifestPluginTests.csproj | 28 ++ dotnet/paccor_scripts/paccor_scripts.sln | 2 +- .../paccor_scripts/paccor_scripts.csproj | 10 +- .../paccor_scripts/sbom_buildlist_file.txt | 10 + .../paccor_scripts/sbom_cmds.txt | 3 + .../paccor_scripts/scripts/allcomponents.sh | 20 +- .../paccor_scripts/scripts/get_ek.sh | 147 ------- .../paccor_scripts/scripts/otherextensions.sh | 160 ------- .../paccor_scripts/scripts/pc_certgen.sh | 152 ------- .../scripts/referenceoptions.sh | 265 ------------ .../scripts/windows/allcomponents.ps1 | 24 +- .../paccor_scripts/scripts/windows/get_ek.ps1 | 27 -- .../scripts/windows/otherextensions.ps1 | 170 -------- .../scripts/windows/pc_certgen.ps1 | 170 -------- .../scripts/windows/referenceoptions.ps1 | 291 ------------- .../src/PaccorComponentScriptsPlugin.cs | 79 ++-- 30 files changed, 865 insertions(+), 1631 deletions(-) create mode 100644 .github/workflows/dotnet-build-hardwaremanifest.yml create mode 100644 .github/workflows/dotnet-build-paccor_scripts.yml create mode 100644 dotnet/HardwareManifestPlugin/HardwareManifestPlugin/Resources/HardwareManifest.proto create mode 100644 dotnet/HardwareManifestPlugin/HardwareManifestPlugin/src/Convert.cs create mode 100644 dotnet/HardwareManifestPlugin/HardwareManifestPlugin/src/HardwareManifest.cs delete mode 100644 dotnet/HardwareManifestPlugin/HardwareManifestPlugin/src/NameAttributes.cs create mode 100644 dotnet/HardwareManifestPlugin/HardwareManifestPluginTests/HardwareManifestPluginTests.cs create mode 100644 dotnet/HardwareManifestPlugin/HardwareManifestPluginTests/HardwareManifestPluginTests.csproj create mode 100644 dotnet/paccor_scripts/paccor_scripts/sbom_buildlist_file.txt create mode 100644 dotnet/paccor_scripts/paccor_scripts/sbom_cmds.txt delete mode 100644 dotnet/paccor_scripts/paccor_scripts/scripts/get_ek.sh delete mode 100644 dotnet/paccor_scripts/paccor_scripts/scripts/otherextensions.sh delete mode 100644 dotnet/paccor_scripts/paccor_scripts/scripts/pc_certgen.sh delete mode 100644 dotnet/paccor_scripts/paccor_scripts/scripts/referenceoptions.sh delete mode 100644 dotnet/paccor_scripts/paccor_scripts/scripts/windows/get_ek.ps1 delete mode 100644 dotnet/paccor_scripts/paccor_scripts/scripts/windows/otherextensions.ps1 delete mode 100644 dotnet/paccor_scripts/paccor_scripts/scripts/windows/pc_certgen.ps1 delete mode 100644 dotnet/paccor_scripts/paccor_scripts/scripts/windows/referenceoptions.ps1 diff --git a/.github/workflows/dotnet-build-hardwaremanifest.yml b/.github/workflows/dotnet-build-hardwaremanifest.yml new file mode 100644 index 0000000..4724fb9 --- /dev/null +++ b/.github/workflows/dotnet-build-hardwaremanifest.yml @@ -0,0 +1,25 @@ +name: .NET + +on: + push: + +jobs: + build: + + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 6.0.x + - name: Go to HardwareManifest directory + run: cd dotnet/HardwareManifest + - name: Restore dependencies + run: dotnet restore + - name: Build + run: dotnet build + - name: Test + run: dotnet test + - name: Pack + run: dotnet pack \ No newline at end of file diff --git a/.github/workflows/dotnet-build-paccor_scripts.yml b/.github/workflows/dotnet-build-paccor_scripts.yml new file mode 100644 index 0000000..0cb857c --- /dev/null +++ b/.github/workflows/dotnet-build-paccor_scripts.yml @@ -0,0 +1,29 @@ +name: .NET + +on: + push: + +jobs: + build: + + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 6.0.x + - name: Go to paccor_scripts directory + run: cd dotnet/paccor_scripts + - name: Restore dependencies + run: dotnet restore + - name: Build + run: dotnet build + - name: Test + run: dotnet test + - name: Pack + run: dotnet pack + - name: Publish + run: | + dotnet -r linux-x64 -c Release + dotnet -r win-x64 -c Release \ No newline at end of file diff --git a/dotnet/HardwareManifestPlugin/.editorconfig b/dotnet/HardwareManifestPlugin/.editorconfig index 13fe492..8bf5e6c 100644 --- a/dotnet/HardwareManifestPlugin/.editorconfig +++ b/dotnet/HardwareManifestPlugin/.editorconfig @@ -12,7 +12,7 @@ indent_style = space tab_width = 4 # New line preferences -end_of_line = crlf +end_of_line = lf insert_final_newline = false #### .NET Coding Conventions #### diff --git a/dotnet/HardwareManifestPlugin/HardwareManifestPlugin.sln b/dotnet/HardwareManifestPlugin/HardwareManifestPlugin.sln index 0319cbf..677cae0 100644 --- a/dotnet/HardwareManifestPlugin/HardwareManifestPlugin.sln +++ b/dotnet/HardwareManifestPlugin/HardwareManifestPlugin.sln @@ -5,7 +5,12 @@ VisualStudioVersion = 17.1.32421.90 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HardwareManifestPlugin", "HardwareManifestPlugin\HardwareManifestPlugin.csproj", "{53C81C44-E5AC-4A0E-B345-C1B7B29F4B6D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HardwareManifestPluginManager", "HardwareManifestPluginManager\HardwareManifestPluginManager.csproj", "{502E153C-EE54-4472-8241-41F43687FA96}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HardwareManifestPluginManager", "HardwareManifestPluginManager\HardwareManifestPluginManager.csproj", "{502E153C-EE54-4472-8241-41F43687FA96}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HardwareManifestPluginTests", "HardwareManifestPluginTests\HardwareManifestPluginTests.csproj", "{B7427D0D-A770-4EB0-BDD8-47E412C95740}" + ProjectSection(ProjectDependencies) = postProject + {53C81C44-E5AC-4A0E-B345-C1B7B29F4B6D} = {53C81C44-E5AC-4A0E-B345-C1B7B29F4B6D} + EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -21,6 +26,10 @@ Global {502E153C-EE54-4472-8241-41F43687FA96}.Debug|Any CPU.Build.0 = Debug|Any CPU {502E153C-EE54-4472-8241-41F43687FA96}.Release|Any CPU.ActiveCfg = Release|Any CPU {502E153C-EE54-4472-8241-41F43687FA96}.Release|Any CPU.Build.0 = Release|Any CPU + {B7427D0D-A770-4EB0-BDD8-47E412C95740}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B7427D0D-A770-4EB0-BDD8-47E412C95740}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B7427D0D-A770-4EB0-BDD8-47E412C95740}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B7427D0D-A770-4EB0-BDD8-47E412C95740}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/HardwareManifestPlugin.csproj b/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/HardwareManifestPlugin.csproj index ad14bdc..29847e0 100644 --- a/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/HardwareManifestPlugin.csproj +++ b/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/HardwareManifestPlugin.csproj @@ -6,7 +6,7 @@ enable NSA Cybersecurity Directorate paccor.HardwareManifestPlugin - 1.0.0 + 2.0.1 paccor;platform;certificate;hardware;manifest;interface README.md Apache-2.0 @@ -17,14 +17,16 @@ true snupkg - - - - + + + all + - + + + @@ -33,4 +35,28 @@ + + + + $(ProjectDir)Resources + $(ProjectDir)generated + + + $(protoc_linux64) + $(protoc_linux86) + $(protoc_macosx64) + $(protoc_macosx86) + $(protoc_windows64) + $(protoc_windows86) + + + + + + + + + + + diff --git a/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/Resources/HardwareManifest.proto b/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/Resources/HardwareManifest.proto new file mode 100644 index 0000000..e22e7fa --- /dev/null +++ b/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/Resources/HardwareManifest.proto @@ -0,0 +1,83 @@ +syntax = "proto3"; + +import "PlatformCertificateIM.proto"; + +package HardwareManifestProto; + +message ManifestV3 { + PlatformCertificateProto.PlatformIdentifierOtherName platformIdentifier = 1; + PlatformCertificateProto.PlatformConfiguration platformConfiguration = 2; +} + +message ManifestV2 { + SanPlatformFields PLATFORM = 1; // Subject Alt Name Platform Fields + repeated ComponentIdentifier COMPONENTS = 2; + repeated Property PROPERTIES = 3; + UriReference COMPONENTSURI = 4; + UriReference PROPERTIESURI = 5; +} + +message SanPlatformFields { + string PLATFORMMANUFACTURERSTR = 1; + string PLATFORMMODEL = 2; + string PLATFORMVERSION = 3; + string PLATFORMSERIAL = 4; + string PLATFORMMANUFACTURERID = 5; +} + +message ComponentIdentifier { + ComponentClass COMPONENTCLASS = 1; + string MANUFACTURER = 2; + string MODEL = 3; + string SERIAL = 4; + string REVISION = 5; + string MANUFACTURERID = 6; + string FIELDREPLACEABLE = 7; // true or false + repeated Address ADDRESSES = 8; + string STATUS = 9; // ADDED, MODIFIED, or REMOVED + CertificateIdentifier PLATFORMCERT = 10; + UriReference COMPONENTPLATFORMCERTURI = 11; + CertificateIdentifier CERTIFICATEIDENTIFIER = 12; +} + +message Property { + string PROPERTYNAME = 1; + string PROPERTYVALUE = 2; + string STATUS = 3; +} + +message ComponentClass { + string COMPONENTCLASSREGISTRY = 1; // OID + string COMPONENTCLASSVALUE = 2; // Hex String +} + +message Address { + oneof ADDRESSES_oneof { + string BLUETOOTHMAC = 1; + string ETHERNETMAC = 2; + string WLANMAC = 3; + } +} + +message HashedCertificateIdentifier { + string HASHALG = 1; // OID + string HASHVALUE = 2; // base64 encode the binary value +} + +message GenericCertificateIdentifier { + string ISSUER = 1; + string SERIAL = 2; +} + +message CertificateIdentifier { + HashedCertificateIdentifier ATTRIBUTECERTIDENTIFIER = 1; + GenericCertificateIdentifier GENERICCERTIDENTIFIER = 2; + HashedCertificateIdentifier HASHEDCERTIDENTIFIER = 3; +} + +message UriReference { + string UNIFORMRESOURCEIDENTIFIER = 1; + string HASHALG = 2; // OID + string HASHVALUE = 3; // base64 encode the binary value +} + diff --git a/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/src/Convert.cs b/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/src/Convert.cs new file mode 100644 index 0000000..ec004e7 --- /dev/null +++ b/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/src/Convert.cs @@ -0,0 +1,390 @@ +using Google.Protobuf; +using HardwareManifestProto; +using OidsProto; +using PlatformCertificateProto; + +namespace HardwareManifestPlugin { + public class Convert { + public static ManifestV3 FromManifestV2(ManifestV2 v2, string traitDescription, string traitDescriptionUri) { + // Wrap V2 Manifest with Trait details and return a V3 Manifest + ManifestV3 v3 = new(); + + // Convert Platform Fields + if (v2.PLATFORM != null) { + v3.PlatformIdentifier = new PlatformIdentifierOtherName { + TypeId = OidsUtils.Find(TCG_COMMON_NODE.TcgAtPlatformidentifier), + Value = new PlatformIdentifier() + }; + if (!string.IsNullOrEmpty(v2.PLATFORM.PLATFORMMANUFACTURERSTR)) { + v3.PlatformIdentifier.Value.PlatformManufacturer = new Manufacturer { + Utf8 = new UTF8StringTrait { + TraitId = OidsUtils.Find(TCG_TR_ID_NODE.TcgTrIdUtf8String), + TraitCategory = OidsUtils.Find(TCG_TR_CAT_NODE.TcgTrCatPlatformmanufacturer), + TraitRegistry = OidsUtils.Find(TCG_TR_REG_NODE.TcgTrRegNone), + Description = new UTF8String { + String = traitDescription + }, + DescriptionURI = new IA5String { + String = traitDescriptionUri + }, + TraitValue = new UTF8String { + String = v2.PLATFORM.PLATFORMMANUFACTURERSTR + } + } + }; + } + + if (!string.IsNullOrEmpty(v2.PLATFORM.PLATFORMMANUFACTURERID)) { + v3.PlatformIdentifier.Value.PlatformManufacturerIdentifier = new PENTrait { + TraitId = OidsUtils.Find(TCG_TR_ID_NODE.TcgTrIdPen), + TraitCategory = OidsUtils.Find(TCG_TR_CAT_NODE.TcgTrCatPlatformmanufactureridentifier), + TraitRegistry = OidsUtils.Find(TCG_TR_REG_NODE.TcgTrRegNone), + Description = new UTF8String { + String = traitDescription + }, + DescriptionURI = new IA5String { + String = traitDescriptionUri + }, + TraitValue = new ObjectIdentifier { + Oid = v2.PLATFORM.PLATFORMMANUFACTURERID + } + }; + } + + if (!string.IsNullOrEmpty(v2.PLATFORM.PLATFORMMODEL)) { + v3.PlatformIdentifier.Value.PlatformModel = new Model { + Utf8 = new UTF8StringTrait { + TraitId = OidsUtils.Find(TCG_TR_ID_NODE.TcgTrIdUtf8String), + TraitCategory = OidsUtils.Find(TCG_TR_CAT_NODE.TcgTrCatPlatformmodel), + TraitRegistry = OidsUtils.Find(TCG_TR_REG_NODE.TcgTrRegNone), + Description = new UTF8String { + String = traitDescription + }, + DescriptionURI = new IA5String { + String = traitDescriptionUri + }, + TraitValue = new UTF8String { + String = v2.PLATFORM.PLATFORMMODEL + } + } + }; + } + + if (!string.IsNullOrEmpty(v2.PLATFORM.PLATFORMSERIAL)) { + v3.PlatformIdentifier.Value.PlatformSerial = new Serial { + Utf8 = new UTF8StringTrait { + TraitId = OidsUtils.Find(TCG_TR_ID_NODE.TcgTrIdUtf8String), + TraitCategory = OidsUtils.Find(TCG_TR_CAT_NODE.TcgTrCatPlatformserial), + TraitRegistry = OidsUtils.Find(TCG_TR_REG_NODE.TcgTrRegNone), + Description = new UTF8String { + String = traitDescription + }, + DescriptionURI = new IA5String { + String = traitDescriptionUri + }, + TraitValue = new UTF8String { + String = v2.PLATFORM.PLATFORMSERIAL + } + } + }; + } + + if (!string.IsNullOrEmpty(v2.PLATFORM.PLATFORMVERSION)) { + v3.PlatformIdentifier.Value.PlatformVersion = new Revision { + Utf8 = new UTF8StringTrait { + TraitId = OidsUtils.Find(TCG_TR_ID_NODE.TcgTrIdUtf8String), + TraitCategory = OidsUtils.Find(TCG_TR_CAT_NODE.TcgTrCatPlatformversion), + TraitRegistry = OidsUtils.Find(TCG_TR_REG_NODE.TcgTrRegNone), + Description = new UTF8String { + String = traitDescription + }, + DescriptionURI = new IA5String { + String = traitDescriptionUri + }, + TraitValue = new UTF8String { + String = v2.PLATFORM.PLATFORMVERSION + } + } + }; + } + } + + // Convert Components + v3.PlatformConfiguration = new PlatformConfiguration(); + foreach (HardwareManifestProto.ComponentIdentifier component in v2.COMPONENTS) { + ComponentIdentifierTrait trait = new() { + ComponentIdentifierV11 = new ComponentIdentifierV11Trait { + TraitId = OidsUtils.Find(TCG_TR_ID_NODE.TcgTrIdComponentidentifierv11), + TraitCategory = OidsUtils.Find(TCG_TR_CAT_NODE.TcgTrCatComponentidentifierv11), + TraitRegistry = OidsUtils.Find(TCG_TR_REG_NODE.TcgTrRegNone), + Description = new UTF8String { + String = traitDescription + }, + DescriptionURI = new IA5String { + String = traitDescriptionUri + }, + TraitValue = new ComponentIdentifierV11() + } + }; + + // Copy component class + if (!string.IsNullOrEmpty(component.COMPONENTCLASS.COMPONENTCLASSVALUE)) { + byte[] componentClassValue = System.Convert.FromHexString(component.COMPONENTCLASS.COMPONENTCLASSVALUE); + trait.ComponentIdentifierV11.TraitValue.ComponentClass = new PlatformCertificateProto.ComponentClass { + ComponentClassRegistry = new ObjectIdentifier { + Oid = component.COMPONENTCLASS.COMPONENTCLASSREGISTRY + }, + ComponentClassValue = new OctetString { + Base64 = ByteString.CopyFrom(componentClassValue) + } + }; + } + + // Copy main strings + if (!string.IsNullOrEmpty(component.MANUFACTURER)) { + trait.ComponentIdentifierV11.TraitValue.ComponentManufacturer = new UTF8String { + String = component.MANUFACTURER + }; + } + + if (!string.IsNullOrEmpty(component.MODEL)) { + trait.ComponentIdentifierV11.TraitValue.ComponentModel = new UTF8String { + String = component.MODEL + }; + } + + if (!string.IsNullOrEmpty(component.SERIAL)) { + trait.ComponentIdentifierV11.TraitValue.ComponentSerial = new UTF8String { + String = component.SERIAL + }; + } + + if (!string.IsNullOrEmpty(component.REVISION)) { + trait.ComponentIdentifierV11.TraitValue.ComponentRevision = new UTF8String { + String = component.REVISION + }; + } + + if (!string.IsNullOrEmpty(component.MANUFACTURERID)) { + trait.ComponentIdentifierV11.TraitValue.ComponentManufacturerId = new ObjectIdentifier { + Oid = component.MANUFACTURERID + }; + } + + if (!string.IsNullOrEmpty(component.FIELDREPLACEABLE)) { + trait.ComponentIdentifierV11.TraitValue.FieldReplaceable = new Boolean { + Bool = bool.Parse(component.FIELDREPLACEABLE) + }; + } + + // Copy component addresses + foreach (Address address in component.ADDRESSES) { + ComponentAddress newAddress = new(); + switch (address.ADDRESSESOneofCase) { + case Address.ADDRESSESOneofOneofCase.BLUETOOTHMAC: + newAddress.AddressType = OidsUtils.Find(TCG_ADDRESS_NODE.TcgAddressBluetoothmac); + newAddress.AddressValue = new UTF8String { + String = address.BLUETOOTHMAC + }; + break; + case Address.ADDRESSESOneofOneofCase.ETHERNETMAC: + newAddress.AddressType = OidsUtils.Find(TCG_ADDRESS_NODE.TcgAddressEthernetmac); + newAddress.AddressValue = new UTF8String { + String = address.ETHERNETMAC + }; + break; + case Address.ADDRESSESOneofOneofCase.WLANMAC: + newAddress.AddressType = OidsUtils.Find(TCG_ADDRESS_NODE.TcgAddressWlanmac); + newAddress.AddressValue = new UTF8String { + String = address.WLANMAC + }; + break; + case Address.ADDRESSESOneofOneofCase.None: + default: + // Don't propagate unknown network address types + continue; + } + trait.ComponentIdentifierV11.TraitValue.ComponentAddresses.Add(newAddress); + } + + // Copy component hashed or attribute cert identifier, saving only the last entry + // Handle case where the ATTRIBUTECERTIDENTIFIER key is used within the PLATFORMCERT key + if (component.PLATFORMCERT != null) { + if (component.PLATFORMCERT.ATTRIBUTECERTIDENTIFIER != null) { + byte[] hvBytes = System.Text.Encoding.UTF8.GetBytes(component.PLATFORMCERT.ATTRIBUTECERTIDENTIFIER.HASHVALUE); + if (hvBytes.Length > 0) { + string hvBase64 = System.Convert.ToBase64String(hvBytes); + + trait.ComponentIdentifierV11.TraitValue.ComponentPlatformCert = new PlatformCertificateProto.CertificateIdentifier { + HashedCertIdentifier = new PlatformCertificateProto.HashedCertificateIdentifier { + HashAlgorithm = new AlgorithmIdentifier { + Algorithm = new ObjectIdentifier { + Oid = component.PLATFORMCERT.ATTRIBUTECERTIDENTIFIER.HASHALG + } + }, + HashOverSignatureValue = new OctetString { + Base64 = ByteString.FromBase64(hvBase64) + } + } + }; + } + } + + // Handle case where the HASHEDCERTIDENTIFIER key is used within the PLATFORMCERT key + if (component.PLATFORMCERT.HASHEDCERTIDENTIFIER != null) { + byte[] hvBytes = System.Text.Encoding.UTF8.GetBytes(component.PLATFORMCERT.HASHEDCERTIDENTIFIER.HASHVALUE); + if (hvBytes.Length > 0) { + string hvBase64 = System.Convert.ToBase64String(hvBytes); + + trait.ComponentIdentifierV11.TraitValue.ComponentPlatformCert = new PlatformCertificateProto.CertificateIdentifier { + HashedCertIdentifier = new PlatformCertificateProto.HashedCertificateIdentifier { + HashAlgorithm = new AlgorithmIdentifier { + Algorithm = new ObjectIdentifier { + Oid = component.PLATFORMCERT.HASHEDCERTIDENTIFIER.HASHALG + } + }, + HashOverSignatureValue = new OctetString { + Base64 = ByteString.FromBase64(hvBase64) + } + } + }; + } + } + } + + // Handle case where the ATTRIBUTECERTIDENTIFIER key is used within the CERTIFICATEIDENTIFIER key + if (component.CERTIFICATEIDENTIFIER != null) { + if (component.CERTIFICATEIDENTIFIER.ATTRIBUTECERTIDENTIFIER != null) { + byte[] hvBytes = System.Text.Encoding.UTF8.GetBytes(component.CERTIFICATEIDENTIFIER.ATTRIBUTECERTIDENTIFIER.HASHVALUE); + if (hvBytes.Length > 0) { + string hvBase64 = System.Convert.ToBase64String(hvBytes); + + trait.ComponentIdentifierV11.TraitValue.ComponentPlatformCert = new PlatformCertificateProto.CertificateIdentifier { + HashedCertIdentifier = new PlatformCertificateProto.HashedCertificateIdentifier { + HashAlgorithm = new AlgorithmIdentifier { + Algorithm = new ObjectIdentifier { + Oid = component.CERTIFICATEIDENTIFIER.ATTRIBUTECERTIDENTIFIER.HASHALG + } + }, + HashOverSignatureValue = new OctetString { + Base64 = ByteString.FromBase64(hvBase64) + } + } + }; + } + } + + // Handle case where the HASHEDCERTIDENTIFIER key is used within the CERTIFICATEIDENTIFIER key + if (component.CERTIFICATEIDENTIFIER.HASHEDCERTIDENTIFIER != null) { + byte[] hvBytes = System.Text.Encoding.UTF8.GetBytes(component.CERTIFICATEIDENTIFIER.HASHEDCERTIDENTIFIER.HASHVALUE); + if (hvBytes.Length > 0) { + string hvBase64 = System.Convert.ToBase64String(hvBytes); + + trait.ComponentIdentifierV11.TraitValue.ComponentPlatformCert = new PlatformCertificateProto.CertificateIdentifier { + HashedCertIdentifier = new PlatformCertificateProto.HashedCertificateIdentifier { + HashAlgorithm = new AlgorithmIdentifier { + Algorithm = new ObjectIdentifier { + Oid = component.CERTIFICATEIDENTIFIER.HASHEDCERTIDENTIFIER.HASHALG + } + }, + HashOverSignatureValue = new OctetString { + Base64 = ByteString.FromBase64(hvBase64) + } + } + }; + } + } + } + + // Copy component attribute status + if (component.STATUS != null) { + switch (component.STATUS) { + case "ADDED": + case "added": + trait.ComponentIdentifierV11.TraitValue.Status = AttributeStatus.Added; + break; + case "MODIFIED": + case "modified": + trait.ComponentIdentifierV11.TraitValue.Status = AttributeStatus.Modified; + break; + case "REMOVED": + case "removed": + trait.ComponentIdentifierV11.TraitValue.Status = AttributeStatus.Removed; + break; + default: + break; + } + } + + // Copy component generic cert identifier + if (component.CERTIFICATEIDENTIFIER != null) { + if (component.CERTIFICATEIDENTIFIER.GENERICCERTIDENTIFIER != null) { + trait.ComponentIdentifierV11.TraitValue.ComponentPlatformCert.GenericCertIdentifier = new IssuerSerial { + Issuer = new IssuerSerialDN { + RdnShorthand = component.CERTIFICATEIDENTIFIER.GENERICCERTIDENTIFIER.ISSUER + }, + Serial = new CertificateSerialNumber { + SerialNumber = new Integer { + Int = long.Parse(component.CERTIFICATEIDENTIFIER.GENERICCERTIDENTIFIER.SERIAL) + } + } + }; + } + } + + // Copy component platform cert uri + if (component.COMPONENTPLATFORMCERTURI != null) { + byte[] hvBytes = System.Text.Encoding.UTF8.GetBytes(component.COMPONENTPLATFORMCERTURI.HASHVALUE); + if (hvBytes.Length > 0) { + string hvBase64 = System.Convert.ToBase64String(hvBytes); + + trait.ComponentIdentifierV11.TraitValue.ComponentPlatformCertUri = new URIReference { + HashAlgorithm = new AlgorithmIdentifier { + Algorithm = new ObjectIdentifier { + Oid = component.COMPONENTPLATFORMCERTURI.HASHALG + } + }, + HashValue = new BitString { + Base64 = ByteString.FromBase64(hvBase64) + } + }; + } + + trait.ComponentIdentifierV11.TraitValue.ComponentPlatformCertUri.UniformResourceIdentifier.String = component.COMPONENTPLATFORMCERTURI.UNIFORMRESOURCEIDENTIFIER; + } + + // Save wrapped component identifier v11 + v3.PlatformConfiguration.PlatformComponents.Add(trait); + } + + // Convert Properties + foreach (HardwareManifestProto.Property property in v2.PROPERTIES) { + PlatformCertificateProto.Property newProperty = new() { + PropertyName = new UTF8String { + String = property.PROPERTYNAME + }, + PropertyValue = new UTF8String { + String = property.PROPERTYVALUE + } + }; + switch (property.STATUS) { + case "ADDED": + case "added": + newProperty.Status = AttributeStatus.Added; + break; + case "MODIFIED": + case "modified": + newProperty.Status = AttributeStatus.Modified; + break; + case "REMOVED": + case "removed": + newProperty.Status = AttributeStatus.Removed; + break; + } + v3.PlatformConfiguration.PlatformProperties.Add(newProperty); + } + + return v3; + } + } +} diff --git a/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/src/HardwareManifest.cs b/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/src/HardwareManifest.cs new file mode 100644 index 0000000..7cef540 --- /dev/null +++ b/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/src/HardwareManifest.cs @@ -0,0 +1,41 @@ +using HardwareManifestProto; + +namespace HardwareManifestPlugin { + public abstract class HardwareManifest : IHardwareManifest { + public string Name { + get; + protected set; + } = ""; + + public string Description { + get; + protected set; + } = ""; + + public bool CollectsV2HardwareInformation { + get; + protected set; + } = false; + + public bool CollectsV3HardwareInformation { + get; + protected set; + } = false; + + public ManifestV2 ManifestV2 { + get; + protected set; + } = new(); + + public ManifestV3 ManifestV3 { + get; + protected set; + } = new(); + + public abstract bool GatherHardwareIdentifiers(); + + public bool GatherHardwareIdentifiers(string[] args) { + return GatherHardwareIdentifiers(); + } + } +} diff --git a/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/src/IHardwareManifest.cs b/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/src/IHardwareManifest.cs index 232dba4..3ec99c8 100644 --- a/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/src/IHardwareManifest.cs +++ b/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/src/IHardwareManifest.cs @@ -1,61 +1,52 @@ -using PlatformCertificateFromProto; -using org.iso.standards.swid; - -namespace HardwareManifestPlugin { - public interface IHardwareManifest { - string Name { - get; - } - string Description { - get; - } - PlatformConfiguration PlatformConfiguration { - get; - } - PlatformConfigurationV2 PlatformConfigurationV2 { - get; - } - - NameAttributes NameAttributes { - get; - } - - SoftwareIdentity? SWID { - get; - } - - /// - /// Pass arguments to the Hardware Manifest Plugin, if needed. - /// - /// Command-line style arguments to be given to the plugin prior to hardware identifier collection. - void Configure(string[] args); - /// - /// Will this plugin collect hardware information into structures defined under tcg-at-platformConfiguration-v1? - /// - /// If true, the PlatformConfiguration property is expected to contain hardware information after GatherHardwareInformation is run. If false, the PlatformConfiguration property is expected to be null. - bool WillContainPlatformConfigurationV1(); - /// - /// Will this plugin collect hardware information into structures defined under tcg-at-platformConfiguration-v2? - /// - /// If true, the PlatformConfigurationV2 property is expected to contain hardware information after GatherHardwareInformation is run. If false, the PlatformConfigurationV2 property is expected to be null. - bool WillContainPlatformConfigurationV2(); - /// - /// Will this plugin collect hardware information into structures intended for the subject alternative name? - /// - /// If true, the NameAttributes property is expected to contain at least one hardware identifier intended for the subject alternative name after GatherHardwareInformation is run. Individually check each of the sub-properties of NameAttributes. If false, the NameAttributes property is expected to be null. - bool WillContainNameAttributes(); - /// - /// Was this plugin distributed with a SWID file? - /// - /// If true, the SWID property is expected to contain a complete SoftwareIdentity structure. The swidtag must provide integrity over That structure may contain a Signature. If false, the SWID property is expected to be empty. - bool ContainsSWID() { - return SWID != null; - } - - /// - /// Kick off the hardware collection procedure within the Hardware Manifest Plugin. - /// - /// The full manifest as a JSON string. - string GatherHardwareManifestAsJsonString(); - } -} +using HardwareManifestProto; + +namespace HardwareManifestPlugin { + public interface IHardwareManifest { + string Name { + get; + } + string Description { + get; + } + + public const int PluginMajorVersion = 2; + public const int PluginMinorVersion = 0; + public const int PluginRevision = 1; + + /// + /// Will this plugin collect hardware information into structures defined under tcg-at-platformConfiguration-v2? + /// + /// If true, the ManifestV2 property is expected to contain hardware information after GatherHardwareInformation is run. If false, the ManifestV2 property is not expected to be initialized. + bool CollectsV2HardwareInformation { + get; + } + /// + /// Will this plugin collect hardware information into structures defined under tcg-at-platformConfiguration-v3? + /// + /// If true, the ManifestV3 property is expected to contain hardware information after GatherHardwareInformation is run. If false, the ManifestV3 property is not expected to be initialized. + bool CollectsV3HardwareInformation { + get; + } + + ManifestV2 ManifestV2 { + get; + } + + ManifestV3 ManifestV3 { + get; + } + + /// + /// Kick off the hardware collection procedure within the Hardware Manifest Plugin. + /// + /// True if collection completed successfully. False otherwise. + bool GatherHardwareIdentifiers(); + + /// + /// Kick off the hardware collection procedure within the Hardware Manifest Plugin. + /// + /// Arguments can be passed to the function. + /// True if collection completed successfully. False otherwise. + bool GatherHardwareIdentifiers(string[] args); + } +} diff --git a/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/src/NameAttributes.cs b/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/src/NameAttributes.cs deleted file mode 100644 index ee074cd..0000000 --- a/dotnet/HardwareManifestPlugin/HardwareManifestPlugin/src/NameAttributes.cs +++ /dev/null @@ -1,28 +0,0 @@ -using PlatformCertificateFromProto; - -namespace HardwareManifestPlugin { - public class NameAttributes { - public PlatformManufacturerStr? PlatformManufacturerStr { - get; private set; - } - public PlatformModel? PlatformModel { - get; private set; - } - public PlatformSerial? PlatformSerial { - get; private set; - } - public PlatformVersion? PlatformVersion { - get; private set; - } - public PlatformManufacturerId? PlatformManufacturerId { - get; private set; - } - public NameAttributes(PlatformManufacturerStr ven, PlatformModel mn, PlatformSerial sn, PlatformVersion ver, PlatformManufacturerId venId) { - PlatformManufacturerStr = ven; - PlatformModel = mn; - PlatformSerial = sn; - PlatformVersion = ver; - PlatformManufacturerId = venId; - } - } -} diff --git a/dotnet/HardwareManifestPlugin/HardwareManifestPluginManager/HardwareManifestPluginManager.csproj b/dotnet/HardwareManifestPlugin/HardwareManifestPluginManager/HardwareManifestPluginManager.csproj index e84d3ca..1123074 100644 --- a/dotnet/HardwareManifestPlugin/HardwareManifestPluginManager/HardwareManifestPluginManager.csproj +++ b/dotnet/HardwareManifestPlugin/HardwareManifestPluginManager/HardwareManifestPluginManager.csproj @@ -1,4 +1,4 @@ - + net6.0 @@ -6,7 +6,7 @@ enable NSA Cybersecurity Directorate paccor.HardwareManifestPluginManager - 1.0.0 + 2.0.0 paccor;platform;certificate;hardware;manifest;plugin;manager README.md Apache-2.0 @@ -19,8 +19,7 @@ - - + @@ -29,7 +28,7 @@ - + diff --git a/dotnet/HardwareManifestPlugin/HardwareManifestPluginManager/src/HardwareManifestPluginManagerUtils.cs b/dotnet/HardwareManifestPlugin/HardwareManifestPluginManager/src/HardwareManifestPluginManagerUtils.cs index 7863112..5991bd9 100644 --- a/dotnet/HardwareManifestPlugin/HardwareManifestPluginManager/src/HardwareManifestPluginManagerUtils.cs +++ b/dotnet/HardwareManifestPlugin/HardwareManifestPluginManager/src/HardwareManifestPluginManagerUtils.cs @@ -1,65 +1,65 @@ -using HardwareManifestPlugin; -using org.iso.standards.swid; -using Serilog; -using System.Reflection; - -namespace HardwareManifestPluginManager { - public class HardwareManifestPluginManagerUtils { - private static readonly ILogger log = Log.ForContext(); - -#pragma warning disable CS8604 // Possible null reference argument. - public static readonly string pluginsPath = Path.Combine(Path.GetDirectoryName(Environment.ProcessPath), "plugins"); - public static readonly string trustPath = Path.Combine(Path.GetDirectoryName(Environment.ProcessPath), "trust"); -#pragma warning restore CS8604 // Possible null reference argument. - - public static List LoadPlugins(List names, bool swidEnforced) { - string[] pluginDlls = System.IO.Directory.GetFiles(pluginsPath, "*.dll"); - List manifests = new(); - List> namesWithArgs = new(); - foreach(string dllPath in pluginDlls) { - Assembly pluginAssembly = LoadAssemblyfromDll(dllPath); - IHardwareManifest? manifest = GatherManifestIfNameSelected(pluginAssembly, names); - if (manifest != null) { - bool trustManifest = !swidEnforced; - if (swidEnforced && manifest.ContainsSWID()) { - trustManifest = VerifySWIDWithEnvelopedSignature(manifest.SWID!); - } - if (trustManifest) { - manifests.Add(manifest); - log.Debug("Loading hardware manifest: " + manifest.Name); - } - } - } - if (names.Count > 0) { - log.Debug("There was no Hardware Manifest plugin with the name " + (names.Count > 1 ? "s" : "") + string.Join(",", names) + "."); - } - return manifests; - } - - private static Assembly LoadAssemblyfromDll(string relativePath) { - string fullPath = Path.GetFullPath(relativePath).Replace('\\', Path.DirectorySeparatorChar); - - log.Debug($"Seeing if this assembly implements IHardwareManifest: {fullPath}"); - PluginLoadContext loadContext = new(fullPath); - return loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(fullPath))); - } - - private static IHardwareManifest? GatherManifestIfNameSelected(Assembly assembly, List names) { - foreach (Type type in assembly.GetTypes()) { - if (typeof(IHardwareManifest).IsAssignableFrom(type)) { - if (Activator.CreateInstance(type) is IHardwareManifest result && names.Remove(result.Name)) { - log.Debug("Found " + result.Name + "."); - return result; - } - } - } - log.Debug($"Can't find any type which implements IHardwareManifest in {assembly}.\n"); - return null; - } - - private static bool VerifySWIDWithEnvelopedSignature(SoftwareIdentity SWID) { - log.Debug("SWID Signature Method not yet tested"); - return true; - } - } -} +using HardwareManifestPlugin; +using Serilog; +using System.Reflection; +using System.Xml; + +namespace HardwareManifestPluginManager { + public class HardwareManifestPluginManagerUtils { + private static readonly ILogger Log = Serilog.Log.ForContext(); + +#pragma warning disable CS8604 // Possible null reference argument. + public static readonly string PluginsPath = Path.Combine(Path.GetDirectoryName(Environment.ProcessPath), "plugins"); + public static readonly string TrustPath = Path.Combine(Path.GetDirectoryName(Environment.ProcessPath), "trust"); +#pragma warning restore CS8604 // Possible null reference argument. + + public static List LoadPlugins(List names, bool sbomExpected) { + string[] pluginDlls = System.IO.Directory.GetFiles(PluginsPath, "*.dll"); + List manifests = new(); + List> namesWithArgs = new(); + foreach(string dllPath in pluginDlls) { + Assembly pluginAssembly = LoadAssemblyFromDll(dllPath); + IHardwareManifest? manifest = GatherManifestIfNameSelected(pluginAssembly, names); + if (manifest != null) { + bool trustManifest = !sbomExpected; + if (sbomExpected) { + trustManifest = VerifySbom(manifest.Name); + } + if (trustManifest) { + manifests.Add(manifest); + Log.Debug("Loading hardware manifest: " + manifest.Name); + } + } + } + if (names.Count > 0) { + Log.Debug("There was no Hardware Manifest plugin with the name " + (names.Count > 1 ? "s" : "") + string.Join(",", names) + "."); + } + return manifests; + } + + private static Assembly LoadAssemblyFromDll(string relativePath) { + string fullPath = Path.GetFullPath(relativePath).Replace('\\', Path.DirectorySeparatorChar); + + Log.Debug($"Seeing if this assembly implements IHardwareManifest: {fullPath}"); + PluginLoadContext loadContext = new(fullPath); + return loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(fullPath))); + } + + private static IHardwareManifest? GatherManifestIfNameSelected(Assembly assembly, List names) { + foreach (Type type in assembly.GetTypes()) { + if (typeof(IHardwareManifest).IsAssignableFrom(type)) { + if (Activator.CreateInstance(type) is IHardwareManifest result && names.Remove(result.Name)) { + Log.Debug("Found " + result.Name + "."); + return result; + } + } + } + Log.Debug($"Can't find any type which implements IHardwareManifest in {assembly}.\n"); + return null; + } + + private static bool VerifySbom(string manifestName) { + Log.Debug("Sbom verification method not yet tested"); + return true; + } + } +} diff --git a/dotnet/HardwareManifestPlugin/HardwareManifestPluginManager/src/PluginLoadContext.cs b/dotnet/HardwareManifestPlugin/HardwareManifestPluginManager/src/PluginLoadContext.cs index e561c3a..3551618 100644 --- a/dotnet/HardwareManifestPlugin/HardwareManifestPluginManager/src/PluginLoadContext.cs +++ b/dotnet/HardwareManifestPlugin/HardwareManifestPluginManager/src/PluginLoadContext.cs @@ -10,23 +10,13 @@ public PluginLoadContext(string pluginPath) { } protected override Assembly? Load(AssemblyName assemblyName) { - if (assemblyName != null) { string? assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName); - if (assemblyPath != null) { - return LoadFromAssemblyPath(assemblyPath); - } - } - return null; + return assemblyPath != null ? LoadFromAssemblyPath(assemblyPath) : null; } protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { - if (unmanagedDllName != null) { - string? libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName); - if (libraryPath != null) { - return LoadUnmanagedDllFromPath(libraryPath); - } - } - return IntPtr.Zero; + string? libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName); + return libraryPath != null ? LoadUnmanagedDllFromPath(libraryPath) : IntPtr.Zero; } } } diff --git a/dotnet/HardwareManifestPlugin/HardwareManifestPluginTests/HardwareManifestPluginTests.cs b/dotnet/HardwareManifestPlugin/HardwareManifestPluginTests/HardwareManifestPluginTests.cs new file mode 100644 index 0000000..d070642 --- /dev/null +++ b/dotnet/HardwareManifestPlugin/HardwareManifestPluginTests/HardwareManifestPluginTests.cs @@ -0,0 +1,23 @@ +using HardwareManifestProto; +using NUnit.Framework; + +namespace HardwareManifestPluginTests { + public class HardwareManifestPluginTests { + public static readonly string TEST_STUFF_V2 = + "{\n \n \"PLATFORM\": {\n \"PLATFORMMANUFACTURERSTR\": \"Computer Manufacturer M0\",\"PLATFORMMODEL\": \"Computer Model ABC123Z\",\"PLATFORMVERSION\": \"1.0\",\"PLATFORMSERIAL\": \"Serial N839\"\n },\n \"COMPONENTS\": [\n {\n \"COMPONENTCLASS\": {\n \"COMPONENTCLASSREGISTRY\": \"2.23.133.18.3.1\",\n \"COMPONENTCLASSVALUE\": \"00020001\"\n },\"MANUFACTURER\": \"Computer Manufacturer M0\",\"MODEL\": \"31\",\"SERIAL\": \"Serial N839\",\"REVISION\": \"1.0\"\n },\n {\n \"COMPONENTCLASS\": {\n \"COMPONENTCLASSREGISTRY\": \"2.23.133.18.3.1\",\n \"COMPONENTCLASSVALUE\": \"00030003\"\n },\"MANUFACTURER\": \"Computer Manufacturer M0\",\"MODEL\": \"UP6502ZA\",\"FIELDREPLACEABLE\": \"true\",\"SERIAL\": \"Serial N7M0\",\"REVISION\": \"1.0\"\n },\n {\n \"COMPONENTCLASS\": {\n \"COMPONENTCLASSREGISTRY\": \"2.23.133.18.3.1\",\n \"COMPONENTCLASSVALUE\": \"00130003\"\n },\"MANUFACTURER\": \"Computer Manufacturer AM32\",\"MODEL\": \"Not Specified\",\"REVISION\": \"Rev 2Z.8\"\n },\n {\n \"COMPONENTCLASS\": {\n \"COMPONENTCLASSREGISTRY\": \"2.23.133.18.3.1\",\n \"COMPONENTCLASSVALUE\": \"00010002\"\n },\"MANUFACTURER\": \"Intel(R) Corporation\",\"MODEL\": \"198\",\"FIELDREPLACEABLE\": \"true\",\"SERIAL\": \"To Be Filled By O.E.M.\",\"REVISION\": \"12th Gen Intel(R) Core(TM) i7-12700H\"\n },\n {\n \"COMPONENTCLASS\": {\n \"COMPONENTCLASSREGISTRY\": \"2.23.133.18.3.1\",\n \"COMPONENTCLASSVALUE\": \"00060001\"\n },\"MANUFACTURER\": \"Computer Manufacturer WE2\",\"MODEL\": \"Computer Model K027\",\"FIELDREPLACEABLE\": \"true\",\"SERIAL\": \"00000000\",\"REVISION\": \"9876543210\"\n },\n {\n \"COMPONENTCLASS\": {\n \"COMPONENTCLASSREGISTRY\": \"2.23.133.18.3.1\",\n \"COMPONENTCLASSVALUE\": \"00060001\"\n },\"MANUFACTURER\": \"Computer Manufacturer WE2\",\"MODEL\": \"Computer Model K027\",\"FIELDREPLACEABLE\": \"true\",\"SERIAL\": \"00000000\",\"REVISION\": \"9876543210\"\n },\n {\n \"COMPONENTCLASS\": {\n \"COMPONENTCLASSREGISTRY\": \"2.23.133.18.3.1\",\n \"COMPONENTCLASSVALUE\": \"00060001\"\n },\"MANUFACTURER\": \"Computer Manufacturer WE2\",\"MODEL\": \"Computer Model K027\",\"FIELDREPLACEABLE\": \"true\",\"SERIAL\": \"00000000\",\"REVISION\": \"9876543210\"\n },\n {\n \"COMPONENTCLASS\": {\n \"COMPONENTCLASSREGISTRY\": \"2.23.133.18.3.1\",\n \"COMPONENTCLASSVALUE\": \"00060001\"\n },\"MANUFACTURER\": \"Computer Manufacturer WE2\",\"MODEL\": \"Computer Model K027\",\"FIELDREPLACEABLE\": \"true\",\"SERIAL\": \"00000000\",\"REVISION\": \"9876543210\"\n },\n {\n \"COMPONENTCLASS\": {\n \"COMPONENTCLASSREGISTRY\": \"2.23.133.18.3.1\",\n \"COMPONENTCLASSVALUE\": \"00060001\"\n },\"MANUFACTURER\": \"Computer Manufacturer WE2\",\"MODEL\": \"Computer Model K027\",\"FIELDREPLACEABLE\": \"true\",\"SERIAL\": \"00000000\",\"REVISION\": \"9876543210\"\n },\n {\n \"COMPONENTCLASS\": {\n \"COMPONENTCLASSREGISTRY\": \"2.23.133.18.3.1\",\n \"COMPONENTCLASSVALUE\": \"00060001\"\n },\"MANUFACTURER\": \"Computer Manufacturer WE2\",\"MODEL\": \"Computer Model K027\",\"FIELDREPLACEABLE\": \"true\",\"SERIAL\": \"00000000\",\"REVISION\": \"9876543210\"\n },\n {\n \"COMPONENTCLASS\": {\n \"COMPONENTCLASSREGISTRY\": \"2.23.133.18.3.1\",\n \"COMPONENTCLASSVALUE\": \"00060001\"\n },\"MANUFACTURER\": \"Computer Manufacturer WE2\",\"MODEL\": \"Computer Model K027\",\"FIELDREPLACEABLE\": \"true\",\"SERIAL\": \"00000000\",\"REVISION\": \"9876543210\"\n },\n {\n \"COMPONENTCLASS\": {\n \"COMPONENTCLASSREGISTRY\": \"2.23.133.18.3.1\",\n \"COMPONENTCLASSVALUE\": \"00060001\"\n },\"MANUFACTURER\": \"Computer Manufacturer WE2\",\"MODEL\": \"Computer Model K027\",\"FIELDREPLACEABLE\": \"true\",\"SERIAL\": \"00000000\",\"REVISION\": \"9876543210\"\n },\n {\n \"COMPONENTCLASS\": {\n \"COMPONENTCLASSREGISTRY\": \"2.23.133.18.3.1\",\n \"COMPONENTCLASSVALUE\": \"00090002\"\n },\"MANUFACTURER\": \"8086\",\"MODEL\": \"51F0\",\"FIELDREPLACEABLE\": \"true\",\"SERIAL\": \"Serial 27347E\",\"REVISION\": \"01\", \"ADDRESSES\": [{\n \"WLANMAC\": \"Serial 27347E\" }]\n },\n {\n \"COMPONENTCLASS\": {\n \"COMPONENTCLASSREGISTRY\": \"2.23.133.18.3.1\",\n \"COMPONENTCLASSVALUE\": \"00070002\"\n },\"MANUFACTURER\": \"Not Specified\",\"MODEL\": \"retrieving Valu\",\"FIELDREPLACEABLE\": \"true\"\n },\n {\n \"COMPONENTCLASS\": {\n \"COMPONENTCLASSREGISTRY\": \"2.23.133.18.3.1\",\n \"COMPONENTCLASSVALUE\": \"00050002\"\n },\"MANUFACTURER\": \"8086\",\"MODEL\": \"46A6\",\"FIELDREPLACEABLE\": \"true\",\"REVISION\": \"0C\"\n }\n ],\n \"PROPERTIES\": [\n {\n \"PROPERTYNAME\": \"caption\",\n \"PROPERTYVALUE\": \"Microsoft Windows 11 Pro\"\n }\n,\n {\n \"PROPERTYNAME\": \"caption\",\n \"PROPERTYVALUE\": \"Microsoft Windows 11 Pro\"\n }\n\n ]\n}"; + + public static readonly string TEST_STUFF_V3 = + "{ \"platformIdentifier\": { \"typeId\": { \"oid\": \"2.23.133.5.1.8\" }, \"value\": { \"platformManufacturer\": { \"utf8\": { \"traitId\": { \"oid\": \"2.23.133.19.1.18\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.1\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"string\": \"Computer Manufacturer M0\" } } }, \"platformModel\": { \"utf8\": { \"traitId\": { \"oid\": \"2.23.133.19.1.18\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.2\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"string\": \"Computer Model ABC123Z\" } } }, \"platformVersion\": { \"utf8\": { \"traitId\": { \"oid\": \"2.23.133.19.1.18\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.3\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"string\": \"1.0\" } } }, \"platformSerial\": { \"utf8\": { \"traitId\": { \"oid\": \"2.23.133.19.1.18\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.4\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"string\": \"Serial N839\" } } } } }, \"platformConfiguration\": { \"platformComponents\": [ { \"componentIdentifierV11\": { \"traitId\": { \"oid\": \"2.23.133.19.1.5\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.26\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"componentClass\": { \"componentClassRegistry\": { \"oid\": \"2.23.133.18.3.1\" }, \"componentClassValue\": { \"base64\": \"AAIAAQ==\" } }, \"componentManufacturer\": { \"string\": \"Computer Manufacturer M0\" }, \"componentModel\": { \"string\": \"31\" }, \"componentSerial\": { \"string\": \"Serial N839\" }, \"componentRevision\": { \"string\": \"1.0\" } } } }, { \"componentIdentifierV11\": { \"traitId\": { \"oid\": \"2.23.133.19.1.5\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.26\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"componentClass\": { \"componentClassRegistry\": { \"oid\": \"2.23.133.18.3.1\" }, \"componentClassValue\": { \"base64\": \"AAMAAw==\" } }, \"componentManufacturer\": { \"string\": \"Computer Manufacturer M0\" }, \"componentModel\": { \"string\": \"UP6502ZA\" }, \"componentSerial\": { \"string\": \"Serial N7M0\" }, \"componentRevision\": { \"string\": \"1.0\" }, \"fieldReplaceable\": { \"bool\": true } } } }, { \"componentIdentifierV11\": { \"traitId\": { \"oid\": \"2.23.133.19.1.5\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.26\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"componentClass\": { \"componentClassRegistry\": { \"oid\": \"2.23.133.18.3.1\" }, \"componentClassValue\": { \"base64\": \"ABMAAw==\" } }, \"componentManufacturer\": { \"string\": \"Computer Manufacturer AM32\" }, \"componentModel\": { \"string\": \"Not Specified\" }, \"componentRevision\": { \"string\": \"Rev 2Z.8\" } } } }, { \"componentIdentifierV11\": { \"traitId\": { \"oid\": \"2.23.133.19.1.5\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.26\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"componentClass\": { \"componentClassRegistry\": { \"oid\": \"2.23.133.18.3.1\" }, \"componentClassValue\": { \"base64\": \"AAEAAg==\" } }, \"componentManufacturer\": { \"string\": \"Intel(R) Corporation\" }, \"componentModel\": { \"string\": \"198\" }, \"componentSerial\": { \"string\": \"To Be Filled By O.E.M.\" }, \"componentRevision\": { \"string\": \"12th Gen Intel(R) Core(TM) i7-12700H\" }, \"fieldReplaceable\": { \"bool\": true } } } }, { \"componentIdentifierV11\": { \"traitId\": { \"oid\": \"2.23.133.19.1.5\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.26\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"componentClass\": { \"componentClassRegistry\": { \"oid\": \"2.23.133.18.3.1\" }, \"componentClassValue\": { \"base64\": \"AAYAAQ==\" } }, \"componentManufacturer\": { \"string\": \"Computer Manufacturer WE2\" }, \"componentModel\": { \"string\": \"Computer Model K027\" }, \"componentSerial\": { \"string\": \"00000000\" }, \"componentRevision\": { \"string\": \"9876543210\" }, \"fieldReplaceable\": { \"bool\": true } } } }, { \"componentIdentifierV11\": { \"traitId\": { \"oid\": \"2.23.133.19.1.5\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.26\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"componentClass\": { \"componentClassRegistry\": { \"oid\": \"2.23.133.18.3.1\" }, \"componentClassValue\": { \"base64\": \"AAYAAQ==\" } }, \"componentManufacturer\": { \"string\": \"Computer Manufacturer WE2\" }, \"componentModel\": { \"string\": \"Computer Model K027\" }, \"componentSerial\": { \"string\": \"00000000\" }, \"componentRevision\": { \"string\": \"9876543210\" }, \"fieldReplaceable\": { \"bool\": true } } } }, { \"componentIdentifierV11\": { \"traitId\": { \"oid\": \"2.23.133.19.1.5\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.26\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"componentClass\": { \"componentClassRegistry\": { \"oid\": \"2.23.133.18.3.1\" }, \"componentClassValue\": { \"base64\": \"AAYAAQ==\" } }, \"componentManufacturer\": { \"string\": \"Computer Manufacturer WE2\" }, \"componentModel\": { \"string\": \"Computer Model K027\" }, \"componentSerial\": { \"string\": \"00000000\" }, \"componentRevision\": { \"string\": \"9876543210\" }, \"fieldReplaceable\": { \"bool\": true } } } }, { \"componentIdentifierV11\": { \"traitId\": { \"oid\": \"2.23.133.19.1.5\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.26\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"componentClass\": { \"componentClassRegistry\": { \"oid\": \"2.23.133.18.3.1\" }, \"componentClassValue\": { \"base64\": \"AAYAAQ==\" } }, \"componentManufacturer\": { \"string\": \"Computer Manufacturer WE2\" }, \"componentModel\": { \"string\": \"Computer Model K027\" }, \"componentSerial\": { \"string\": \"00000000\" }, \"componentRevision\": { \"string\": \"9876543210\" }, \"fieldReplaceable\": { \"bool\": true } } } }, { \"componentIdentifierV11\": { \"traitId\": { \"oid\": \"2.23.133.19.1.5\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.26\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"componentClass\": { \"componentClassRegistry\": { \"oid\": \"2.23.133.18.3.1\" }, \"componentClassValue\": { \"base64\": \"AAYAAQ==\" } }, \"componentManufacturer\": { \"string\": \"Computer Manufacturer WE2\" }, \"componentModel\": { \"string\": \"Computer Model K027\" }, \"componentSerial\": { \"string\": \"00000000\" }, \"componentRevision\": { \"string\": \"9876543210\" }, \"fieldReplaceable\": { \"bool\": true } } } }, { \"componentIdentifierV11\": { \"traitId\": { \"oid\": \"2.23.133.19.1.5\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.26\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"componentClass\": { \"componentClassRegistry\": { \"oid\": \"2.23.133.18.3.1\" }, \"componentClassValue\": { \"base64\": \"AAYAAQ==\" } }, \"componentManufacturer\": { \"string\": \"Computer Manufacturer WE2\" }, \"componentModel\": { \"string\": \"Computer Model K027\" }, \"componentSerial\": { \"string\": \"00000000\" }, \"componentRevision\": { \"string\": \"9876543210\" }, \"fieldReplaceable\": { \"bool\": true } } } }, { \"componentIdentifierV11\": { \"traitId\": { \"oid\": \"2.23.133.19.1.5\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.26\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"componentClass\": { \"componentClassRegistry\": { \"oid\": \"2.23.133.18.3.1\" }, \"componentClassValue\": { \"base64\": \"AAYAAQ==\" } }, \"componentManufacturer\": { \"string\": \"Computer Manufacturer WE2\" }, \"componentModel\": { \"string\": \"Computer Model K027\" }, \"componentSerial\": { \"string\": \"00000000\" }, \"componentRevision\": { \"string\": \"9876543210\" }, \"fieldReplaceable\": { \"bool\": true } } } }, { \"componentIdentifierV11\": { \"traitId\": { \"oid\": \"2.23.133.19.1.5\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.26\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"componentClass\": { \"componentClassRegistry\": { \"oid\": \"2.23.133.18.3.1\" }, \"componentClassValue\": { \"base64\": \"AAYAAQ==\" } }, \"componentManufacturer\": { \"string\": \"Computer Manufacturer WE2\" }, \"componentModel\": { \"string\": \"Computer Model K027\" }, \"componentSerial\": { \"string\": \"00000000\" }, \"componentRevision\": { \"string\": \"9876543210\" }, \"fieldReplaceable\": { \"bool\": true } } } }, { \"componentIdentifierV11\": { \"traitId\": { \"oid\": \"2.23.133.19.1.5\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.26\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"componentClass\": { \"componentClassRegistry\": { \"oid\": \"2.23.133.18.3.1\" }, \"componentClassValue\": { \"base64\": \"AAkAAg==\" } }, \"componentManufacturer\": { \"string\": \"8086\" }, \"componentModel\": { \"string\": \"51F0\" }, \"componentSerial\": { \"string\": \"Serial 27347E\" }, \"componentRevision\": { \"string\": \"01\" }, \"fieldReplaceable\": { \"bool\": true }, \"componentAddresses\": [ { \"addressType\": { \"oid\": \"2.23.133.17.2\" }, \"addressValue\": { \"string\": \"Serial 27347E\" } } ] } } }, { \"componentIdentifierV11\": { \"traitId\": { \"oid\": \"2.23.133.19.1.5\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.26\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"componentClass\": { \"componentClassRegistry\": { \"oid\": \"2.23.133.18.3.1\" }, \"componentClassValue\": { \"base64\": \"AAcAAg==\" } }, \"componentManufacturer\": { \"string\": \"Not Specified\" }, \"componentModel\": { \"string\": \"retrieving Valu\" }, \"fieldReplaceable\": { \"bool\": true } } } }, { \"componentIdentifierV11\": { \"traitId\": { \"oid\": \"2.23.133.19.1.5\" }, \"traitCategory\": { \"oid\": \"2.23.133.19.2.26\" }, \"traitRegistry\": { \"oid\": \"2.23.133.19.3.1\" }, \"description\": { \"string\": \"paccor component gathering scripts\" }, \"descriptionURI\": { \"string\": \"https://github.com/nsacyber/paccor/scripts\" }, \"traitValue\": { \"componentClass\": { \"componentClassRegistry\": { \"oid\": \"2.23.133.18.3.1\" }, \"componentClassValue\": { \"base64\": \"AAUAAg==\" } }, \"componentManufacturer\": { \"string\": \"8086\" }, \"componentModel\": { \"string\": \"46A6\" }, \"componentRevision\": { \"string\": \"0C\" }, \"fieldReplaceable\": { \"bool\": true } } } } ], \"platformProperties\": [ { \"propertyName\": { \"string\": \"caption\" }, \"propertyValue\": { \"string\": \"Microsoft Windows 11 Pro\" } }, { \"propertyName\": { \"string\": \"caption\" }, \"propertyValue\": { \"string\": \"Microsoft Windows 11 Pro\" } } ] } }"; + + [Test] + public void TestConvertFromManifestV2() { + const string traitDescription = "paccor component gathering scripts"; + const string traitDescriptionUri = "https://github.com/nsacyber/paccor/scripts"; + var settings = Google.Protobuf.JsonParser.Settings.Default.WithIgnoreUnknownFields(true); + ManifestV2 v2 = new Google.Protobuf.JsonParser(settings).Parse(TEST_STUFF_V2); + ManifestV3 v3 = HardwareManifestPlugin.Convert.FromManifestV2(v2, traitDescription, traitDescriptionUri); + Assert.That(TEST_STUFF_V3, Is.EqualTo(v3.ToString())); + Console.WriteLine(v3); + } + } +} \ No newline at end of file diff --git a/dotnet/HardwareManifestPlugin/HardwareManifestPluginTests/HardwareManifestPluginTests.csproj b/dotnet/HardwareManifestPlugin/HardwareManifestPluginTests/HardwareManifestPluginTests.csproj new file mode 100644 index 0000000..6435d17 --- /dev/null +++ b/dotnet/HardwareManifestPlugin/HardwareManifestPluginTests/HardwareManifestPluginTests.csproj @@ -0,0 +1,28 @@ + + + + net6.0 + enable + enable + + false + true + + + + + + + + + + + + + + + + + + + diff --git a/dotnet/paccor_scripts/paccor_scripts.sln b/dotnet/paccor_scripts/paccor_scripts.sln index ce3e801..db7aab8 100644 --- a/dotnet/paccor_scripts/paccor_scripts.sln +++ b/dotnet/paccor_scripts/paccor_scripts.sln @@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.1.32421.90 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "paccor_scripts", "paccor_scripts\paccor_scripts.csproj", "{295D1CD3-9DA7-429F-B986-81656BCA6969}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "paccor_scripts", "paccor_scripts\paccor_scripts.csproj", "{295D1CD3-9DA7-429F-B986-81656BCA6969}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HardwareManifestPlugin", "..\HardwareManifestPlugin\HardwareManifestPlugin\HardwareManifestPlugin.csproj", "{E984C721-499B-44AA-A635-080DB8774591}" EndProject diff --git a/dotnet/paccor_scripts/paccor_scripts/paccor_scripts.csproj b/dotnet/paccor_scripts/paccor_scripts/paccor_scripts.csproj index 788c0f8..b9017ec 100644 --- a/dotnet/paccor_scripts/paccor_scripts/paccor_scripts.csproj +++ b/dotnet/paccor_scripts/paccor_scripts/paccor_scripts.csproj @@ -7,7 +7,7 @@ linux-x64;win-x64 NSA Cybersecurity Directorate paccor.paccor_scripts - 1.0.1 + 2.0.0 paccor;platform;certificate;hardware;manifest;scripts;component;class;registry;evidence;collection README.md Apache-2.0 @@ -21,8 +21,8 @@ - - + + @@ -46,7 +46,9 @@ - + + + diff --git a/dotnet/paccor_scripts/paccor_scripts/sbom_buildlist_file.txt b/dotnet/paccor_scripts/paccor_scripts/sbom_buildlist_file.txt new file mode 100644 index 0000000..ee2b0c3 --- /dev/null +++ b/dotnet/paccor_scripts/paccor_scripts/sbom_buildlist_file.txt @@ -0,0 +1,10 @@ +paccor_scripts.dll +scripts/allcomponents.sh +scripts/enterprise-numbers +scripts/hw.sh +scripts/nvme.sh +scripts/smbios.sh +scripts/windows/allcomponents.ps1 +scripts/windows/hw.ps1 +scripts/windows/nvme.ps1 +scripts/windows/SMBios.ps1 diff --git a/dotnet/paccor_scripts/paccor_scripts/sbom_cmds.txt b/dotnet/paccor_scripts/paccor_scripts/sbom_cmds.txt new file mode 100644 index 0000000..8fc56a6 --- /dev/null +++ b/dotnet/paccor_scripts/paccor_scripts/sbom_cmds.txt @@ -0,0 +1,3 @@ +dotnet tool install --global Microsoft.Sbom.DotNetTool +sbom-tool generate -b . -bl sbom_buildlist_file.txt -pn paccor_scripts -pv 1.0.0 -ps NSA -nsb https://github.com/nsacyber/paccor +sbom-tool validate -b . -o ./output.json -mi SPDX:2.2 \ No newline at end of file diff --git a/dotnet/paccor_scripts/paccor_scripts/scripts/allcomponents.sh b/dotnet/paccor_scripts/paccor_scripts/scripts/allcomponents.sh index c81b933..647f294 100644 --- a/dotnet/paccor_scripts/paccor_scripts/scripts/allcomponents.sh +++ b/dotnet/paccor_scripts/paccor_scripts/scripts/allcomponents.sh @@ -74,8 +74,13 @@ JSON_URI="UNIFORMRESOURCEIDENTIFIER" JSON_HASHALG="HASHALGORITHM" JSON_HASHVALUE="HASHVALUE" #### JSON Properties Keywords -JSON_NAME="NAME" -JSON_VALUE="VALUE" +JSON_NAME="PROPERTYNAME" +JSON_VALUE="PROPERTYVALUE" +JSON_PROP_STATUS="PROPERTYSTATUS" +#### JSON Status Keywords +JSON_STATUS_ADDED="ADDED" +JSON_STATUS_MODIFIED="MODIFIED" +JSON_STATUS_REMOVED="REMOVED" NOT_SPECIFIED="Not Specified" @@ -111,6 +116,13 @@ JSON_PROPERTY_TEMPLATE=' \"'"$JSON_VALUE"'\": \"%s\" } ' +JSON_PROPERTY_TEMPLATE_OPT=' + { + \"'"$JSON_NAME"'\": \"%s\", + \"'"$JSON_VALUE"'\": \"%s\", + \"'"$JSON_PROP_STATUS"'\": \"%s\" + } +' JSON_ADDRESSES_TEMPLATE=' \"'"$JSON_ADDRESSES"'\": [%s]' JSON_ETHERNETMAC_TEMPLATE=' { \"'"$JSON_ETHERNETMAC"'\": \"%s\" } ' @@ -208,7 +220,7 @@ queryForPen () { jsonProperty () { if [ -n "${1}" ] && [ -n "${2}" ]; then if [ -n "${3}" ]; then - printf "$JSON_PROPERTY_TEMPLATE" "${1}" "${2}" "${3}" + printf "$JSON_PROPERTY_TEMPLATE_OPT" "${1}" "${2}" "${3}" else printf "$JSON_PROPERTY_TEMPLATE" "${1}" "${2}" fi @@ -796,7 +808,7 @@ parseGfxData () { ### Gather property details property1=$(jsonProperty "uname -r" "$(uname -r)") ## Example1 -property2=$(jsonProperty "OS Release" "$(grep 'PRETTY_NAME=' /etc/os-release | sed 's/[^=]*=//' | sed -e 's/^[[:space:]\"]*//' | sed -e 's/[[:space:]\"]*$//')") ## Example2 +property2=$(jsonProperty "OS Release" "$(grep 'PRETTY_NAME=' /etc/os-release | sed 's/[^=]*=//' | sed -e 's/^[[:space:]\"]*//' | sed -e 's/[[:space:]\"]*$//')") # "$JSON_STATUS_ADDED") ## Example2 with optional third status argument ### Collate the component details componentsCPU=$(parseCpuData) diff --git a/dotnet/paccor_scripts/paccor_scripts/scripts/get_ek.sh b/dotnet/paccor_scripts/paccor_scripts/scripts/get_ek.sh deleted file mode 100644 index 5eb0617..0000000 --- a/dotnet/paccor_scripts/paccor_scripts/scripts/get_ek.sh +++ /dev/null @@ -1,147 +0,0 @@ -#!/bin/bash - - -## SET THESE ACCORDING TO YOUR TPM VERSION, AUTH SETTINGS, and EK NV INDEX -## Base constant values are chosen by default -TPM1_AUTH_SETTINGS="-z" -TPM1_EK_NV_INDEX="0x1000f000" - -TPM2_AUTH_SETTINGS="-a 0x40000001" # Add auth parameters as set for your TPM. i.e. -P 2a2b2c -TPM2_EK_NV_INDEX="0x1c00002" - - -## Shouldn't need to alter the code below this line, unless your TPM 2.0 resource manager was launched with custom settings. -if [ "$EUID" -ne 0 ]; then - echo "Please run as root" - exit 1 -fi - -# Determine TPM version -TPM_VER_1_2=$(dmesg | grep -i tpm | grep "1\.2") -TPM_VER_2_0=$(dmesg | grep -i tpm | grep "2\.0") - -distCmd= -if [ "$(. /etc/os-release; echo $NAME)" = "Ubuntu" ]; then - distCmd="apt" -else - distCmd="yum" -fi - -if [ -z "$TPM_VER_1_2" ] && [ -z "$TPM_VER_2_0" ]; then - tpmServerActive=$(ps -aux | grep "tpm_server" | grep -v "grep") - if [ -n "$tpmServerActive" ]; then - TPM_VER_2_0=1 - else - echo "Could not detect version of TPM. Please manually set in get_ek.sh" - exit 1 - fi -fi - -indexCmd= -readCmd= -sizeCmd= -offsetCmd= -ekCertSize= -nvBufferedRead= -maxReadSize=256 - -if [ -n "$TPM_VER_1_2" ]; then - indexCmd="-i ""$TPM1_EK_NV_INDEX" - ekCertSize=$(tpm_nvinfo | sed -n -e "/""$TPM1_EK_NV_INDEX""/,\$p" | sed -e '/^[ \t\r\n]*$/,$d' | grep "Size" | sed -E 's/^Size[ ]+:[ ]*([0-9]+) .*$/\1/') - readCmd="tpm_nvread ""$TPM1_AUTH_SETTINGS"" ""$indexCmd"" -s %s -n %s | sed -r \"s/[0-9a-f]+ ([ 0-9a-f]{48}).*/\\\\1/\" | tr -d [[:space:]]" - nvBufferedRead="1" -elif [ -n "$TPM_VER_2_0" ]; then - TPM2_TOOLS_VER_1=$("$distCmd" list installed tpm2-tools 2> /dev/null | grep --quiet -E "[ \t]+1\." && echo "1" || echo "") - TPM2_TOOLS_VER_2=$("$distCmd" list installed tpm2-tools 2> /dev/null | grep --quiet -E "[ \t]+2\." && echo "1" || echo "") - TPM2_TOOLS_VER_3=$("$distCmd" list installed tpm2-tools 2> /dev/null | grep --quiet -E "[ \t]+3\." && echo "1" || echo "") - TPM2_TOOLS_VER_4=$("$distCmd" list installed tpm2-tools 2> /dev/null | grep --quiet -E "[ \t]+[4-9]+\." && echo "1" || echo "") - indexCmd="-x ""$TPM2_EK_NV_INDEX" - - # Use tpm2_nvlist to see the size of the entry at the TPM2_EK_NV_INDEX - if [ -n "$TPM2_TOOLS_VER_1" ] || [ -n "$TPM2_TOOLS_VER_2" ]; then - resourceMgrActive=$(ps -aux | grep "resourcemgr" | grep -v "grep") - resourceMgrPort= - if [ -z "$resourceMgrActive" ]; then - echo "This version of tpm2-tools requires the resourcemgr service." - exit 1 - elif [ -n "$TPM2_TOOLS_VER_2" ]; then - resourceMgrPort="-p 2323" # default - fi - ekCertSize=$(tpm2_nvlist "$resourceMgrPort" | sed -n -e "/""$TPM2_EK_NV_INDEX""/,\$p" | sed -e '/}/,$d' | grep "size of" | sed 's/.*size.*://' | sed -e 's/^[[:space:]]*//' | sed -e 's/[[:space:]]$//') - readCmd="tpm2_nvread ""$resourceMgrPort"" ""$TPM2_AUTH_SETTINGS"" ""$indexCmd"" -s %s -o %s | sed -r -e 's/The size of data:[0-9]+//g' | perl -ne 's/([0-9a-f]{2})/print chr hex \$1/gie' | xxd -p -c ""$maxReadSize" - nvBufferedRead="1" - elif [ -n "$TPM2_TOOLS_VER_3" ] || [ -n "$TPM2_TOOLS_VER_4" ]; then - abrmdActive=$(ps -aux | grep "tpm2-abrmd" | grep -v "grep") - modeCmd="-T device" - if [ -n "$abrmdActive" ]; then - if [ -n "$TPM2_TOOLS_VER_3" ]; then - modeCmd="-T abrmd" - else - modeCmd="" - fi - fi - ekCertSize= - if [ -n "$TPM2_TOOLS_VER_3" ]; then - ekCertSize=$(tpm2_nvlist ""$modeCmd"" | sed -n -e "/""$TPM2_EK_NV_INDEX""/,\$p" | sed -e '/^[ \r\n\t]*$/,$d' | grep "size" | sed 's/.*size.*://' | sed -e 's/^[[:space:]]*//' | sed -e 's/[[:space:]]$//') - readCmd="tpm2_nvread ""$modeCmd"" ""$TPM2_AUTH_SETTINGS"" ""$indexCmd"" | xxd -p" - else - ekCertSize=$(tpm2_nvreadpublic $modeCmd 2> /dev/null | sed -n -e "/""$TPM2_EK_NV_INDEX""/,\$p" | sed -e '/^[ \r\n\t]*$/,$d' | grep "size" | sed 's/.*size.*://' | sed -e 's/^[[:space:]]*//' | sed -e 's/[[:space:]]$//') - readCmd="tpm2_nvread ""$TPM2_EK_NV_INDEX"" ""$modeCmd"" -C o 2> /dev/null | xxd -p" - fi - else - echo "Please install tpm2-tools" - exit 1 - fi -fi - -if [ -z "$ekCertSize" ]; then - echo "The size found at the given NV index was 0 bytes." - echo "1) Check the index given was accurate ("$TPM2_EK_NV_INDEX") and" - echo "2) that the auth parameters are right." - exit 1 -fi - -EK_CERT_HEX= -if [ -z "$nvBufferedRead" ]; then - EK_CERT_HEX=$(eval "$readCmd") -else - # Read maxByteSize at a time until the whole block is read - sizeToRead=$maxReadSize - offset=0 - while [ $offset -lt $ekCertSize ]; - do - if (($offset + $maxReadSize > $ekCertSize)); then - sizeToRead=$(($ekCertSize - $offset)) - else - sizeToRead=$maxReadSize - fi - - localReadCmd=$(printf "$readCmd" ""$sizeToRead"" ""$offset"") - blockRead=$(eval "$localReadCmd") - # Concatenate each block together - EK_CERT_HEX="$EK_CERT_HEX""$blockRead" - - offset=$(($offset + $sizeToRead)) - done -fi - -if [ -z "$EK_CERT_HEX" ]; then - echo "No data was read." - exit 1 -fi - -# Erase padding outside the certificate -EC_BLOB=$(echo -n "$EK_CERT_HEX" | sed 's/.\{2\}/& /g' | tr '[\r\n]+' ' ') # Separate each byte -EC_BYTE_START=$(echo -n "$EC_BLOB" | grep -b -o "30 82") # Look for the outer ASN1 Sequence -if [ -z "$EC_BYTE_START" ]; then - echo "Data did not contain an EK certificate." - exit 1 -fi -EC_BYTE_START=$(echo -n "$EC_BLOB" | grep -b -o "30 82" | sed -n '1p' | sed -r 's/^([0-9]+):.*$/\1/') # Get outer ASN1 Sequence position -EC_LENGTH=$(echo -n "$EC_BLOB" | awk -F"30 82" '{print $2}' | tr -d '[[:space:]]') # Get the certificate length -EC_LENGTH="16#""$EC_LENGTH" # Convert to decimal -EC_LENGTH=$(((( $EC_LENGTH ) + 4) * 2)) # Calculate the number of nibbles to retain as the EC_BLOB -EC_BLOB=$(echo -n "$EC_BLOB" | tail -c +"$EC_BYTE_START" | tr -d '[[:space:]]' | head -c "$EC_LENGTH") # truncate the extra bytes - -echo -n "$EC_BLOB" | xxd -r -p # User can convert to PEM/whatever else - diff --git a/dotnet/paccor_scripts/paccor_scripts/scripts/otherextensions.sh b/dotnet/paccor_scripts/paccor_scripts/scripts/otherextensions.sh deleted file mode 100644 index 8699eb9..0000000 --- a/dotnet/paccor_scripts/paccor_scripts/scripts/otherextensions.sh +++ /dev/null @@ -1,160 +0,0 @@ -#!/bin/bash - -### User customizable values -#### Certificate Policies is a mandatory extension. To add additional policies, more variables must be created and referenced below. -certPolicyOid1="1.2.3" # Replace with a real Certificate Policy OID -certPolicyQualifierCPS1="" -certPolicyQualifierUserNotice1="TCG Trusted Platform Endorsement" # Don't change this value. -#### Authority Information Access is an optional extension. To add additional access methods, more variables must be created and referenced below. -authorityInfoAccessMethod1="" # valid options are OCSP or CAISSUERS -authorityInfoAccessLocation1="" # DN -#### CRL Distribution is an optional extension. Leave any blank to omit the extension. -crlType="" # valid options are 0 or 1 -crlName="" # DN -crlReasonFlags="" # valid options are integers 0 thru 16 -crlIssuer="" # CRL issuer DN -#### Targeting Information is an optional extension. Leave the targetFile variable blank to omit the extension. -targetFile="" # provide comma separated file paths to EK certificates - -### The logic below can be changed by advanced users. -#### SHA-256 was assumed to be acceptable for each of the hashAlg choices for URI References -#### 2.16.840.1.101.3.4.2.1 is the oid for SHA-256. see https://tools.ietf.org/html/rfc5754 for other common hash algorithm IDs - -### JSON Structure Keywords -JSON_CERTIFICATEPOLICIES="CERTIFICATEPOLICIES" -JSON_POLICYIDENTIFIER="POLICYIDENTIFIER" -JSON_POLICYQUALIFIERS="POLICYQUALIFIERS" -JSON_POLICYQUALIFIERID="POLICYQUALIFIERID" -JSON_QUALIFIER="QUALIFIER" -JSON_CPS="CPS" -JSON_USERNOTICE="USERNOTICE" -JSON_AUTHORITYINFOACCESS="AUTHORITYINFOACCESS" -JSON_ACCESSMETHOD="ACCESSMETHOD" -JSON_ACCESSLOCATION="ACCESSLOCATION" -JSON_OCSP="OCSP" -JSON_CAISSUERS="CAISSUERS" -JSON_CRLDISTRIBUTION="CRLDISTRIBUTION" -JSON_DISTRIBUTIONNAME="DISTRIBUTIONNAME" -JSON_TYPE="TYPE" -JSON_NAME="NAME" -JSON_REASON="REASON" -JSON_ISSUER="ISSUER" -JSON_TARGETINGINFORMATION="TARGETINGINFORMATION" -JSON_FILE="FILE" - -### JSON Structure Format -JSON_OTHER_EXTENSIONS_TEMPLATE='{%s -}' -JSON_CERTIFICATE_POLICIES_TEMPLATE=' - \"'"$JSON_CERTIFICATEPOLICIES"'\": [ - %s - ]' -JSON_POLICY_IDENTIFIER_TEMPLATE='{ - \"'"$JSON_POLICYIDENTIFIER"'\": \"%s\", - \"'"$JSON_POLICYQUALIFIERS"'\": [ - %s - ] - }' -JSON_POLICY_QUALIFIER_TEMPLATE='{ - \"'"$JSON_POLICYQUALIFIERID"'\": \"%s\", - \"'"$JSON_QUALIFIER"'\": \"%s\" - }' -JSON_AUTHORITY_INFO_ACCESS_TEMPLATE=' - \"'"$JSON_AUTHORITYINFOACCESS"'\": [ - %s - ]' -JSON_AUTH_ACCESS_TEMPLATE='{ - \"'"$JSON_ACCESSMETHOD"'\": \"%s\", - \"'"$JSON_ACCESSLOCATION"'\": \"%s\" - }' -JSON_CRL_DISTRIBUTION_TEMPLATE=' - \"'"$JSON_CRLDISTRIBUTION"'\": { - \"'"$JSON_DISTRIBUTIONNAME"'\": { - \"'"$JSON_TYPE"'\": \"%s\", - \"'"$JSON_NAME"'\": \"%s\" - }, - \"'"$JSON_REASON"'\": \"%s\", - \"'"$JSON_ISSUER"'\": \"%s\" - } -' -JSON_TARGETING_INFORMATION_TEMPLATE=' - \"'"$JSON_TARGETINGINFORMATION"'\": [%s - ]' -JSON_TARGETING_INFORMATION_FILE_TEMPLATE=' - {\"'"$JSON_FILE"'\": \"%s\"} -' - -### JSON Constructor Aides -toCSV () { - old="$IFS" - IFS=',' - value="$*" - printf "$value" -} -jsonCertificatePolicies() { - printf "$JSON_CERTIFICATE_POLICIES_TEMPLATE" "$(toCSV "$@")" -} -jsonPolicyIdentifier() { - printf "$JSON_POLICY_IDENTIFIER_TEMPLATE" "${1}" "${2}" -} -jsonPolicyQualifierCPS() { - printf "$JSON_POLICY_QUALIFIER_TEMPLATE" "$JSON_CPS" "${1}" -} -jsonPolicyQualifierUserNotice() { - printf "$JSON_POLICY_QUALIFIER_TEMPLATE" "$JSON_USERNOTICE" "${1}" -} -jsonAuthInfoAccess() { - printf "$JSON_AUTHORITY_INFO_ACCESS_TEMPLATE" "$(toCSV "$@")" -} -jsonAuthInfoAccessElement() { - printf "$JSON_AUTH_ACCESS_TEMPLATE" "${1}" "${2}" -} -jsonCRLDist() { - printf "$JSON_CRL_DISTRIBUTION_TEMPLATE" "$crlType" "$crlName" "$crlReasonFlags" "$crlIssuer" -} -jsonTargetingInformation() { - targetInfo=() - targetFileSplit=$(echo "$targetFile" | sed -n 1'p' | tr ',' '\n') - while read file; do - formatted=$(printf "$JSON_TARGETING_INFORMATION_FILE_TEMPLATE" "$file") - targetInfo+=("$formatted") - done <<< "$targetFileSplit" - printf "$JSON_TARGETING_INFORMATION_TEMPLATE" "$(toCSV "${targetInfo[@]}")" -} - -jsonOtherExtensionsFile() { - # work on making this script more intuitive - usernotice1=$(jsonPolicyQualifierUserNotice "$certPolicyQualifierUserNotice1") - qualifier1="$usernotice1" - if [ -n "$certPolicyQualifierCPS1" ]; then - cps1=$(jsonPolicyQualifierCPS "$certPolicyQualifierCPS1") - qualifier1="$qualifier"",""$cps1" - fi - policyId1=$(jsonPolicyIdentifier "$certPolicyOid1" "$qualifier1") - certPolicies=$(jsonCertificatePolicies "$policyId1") - tmpData="$certPolicies" - - if [ -n "$authorityInfoAccessMethod1" ] && [ -n "$authorityInfoAccessLocation1" ]; then - access1=$(jsonAuthInfoAccessElement "$authorityInfoAccessMethod1" "$authorityInfoAccessLocation1") - access=$(jsonAuthInfoAccess "$access1") - tmpData="$tmpData"",""$access" - fi - - if [ -n "$crlType" ] && [ -n "$crlName" ] && [ -n "$crlReasonFlags" ] && [ -n "$crlIssuer" ]; then - crlName=$(jsonCRLDist) - tmpData="$tmpData"",""$crlName" - fi - - if [ -n "$targetFile" ]; then - targets=$(jsonTargetingInformation) - tmpData="$tmpData"",""$targets" - fi - - printf "$JSON_OTHER_EXTENSIONS_TEMPLATE" "$tmpData" -} - - -### Put it all together -finalData=$(jsonOtherExtensionsFile) -printf "$finalData""\n" - diff --git a/dotnet/paccor_scripts/paccor_scripts/scripts/pc_certgen.sh b/dotnet/paccor_scripts/paccor_scripts/scripts/pc_certgen.sh deleted file mode 100644 index 78ce795..0000000 --- a/dotnet/paccor_scripts/paccor_scripts/scripts/pc_certgen.sh +++ /dev/null @@ -1,152 +0,0 @@ -#!/bin/bash -############################################################################# -# Platform Certificate Test generator -# -# -# -########################################################################### - -toolpath="`dirname "$0"`" -timestamp=$(date +%Y%m%d%H%M%S) -#### Scripts and executable -componentlister_script="$toolpath""/allcomponents.sh" -policymaker_script="$toolpath""/referenceoptions.sh" -get_ek_script="$toolpath""/get_ek.sh" -extensions_script="$toolpath""/otherextensions.sh" -signer_bin="$toolpath""/../bin/signer" -validator_bin="$toolpath""/../bin/validator" -#### Files -workspace=$toolpath"/pc_testgen" -tmpspace="/tmp" -componentlist="$workspace""/localhost-componentlist.json" -policyreference="$workspace""/localhost-policyreference.json" -ekcert="$workspace""/ek.crt" -pccert="$workspace""/platform_cert.""$timestamp"".crt" -sigkey="$workspace""/private.pem" -pcsigncert="$workspace""/PCTestCA.example.com.pem" -extsettings="$workspace""/extentions.json" -### Certificate params -serialnumber="0001" -dateNotBefore="20180101" -dateNotAfter="20280101" -### Key Pair params -subjectDN="/C=US/O=example.com/OU=PCTest" -daysValid="3652" -sigalg="rsa:2048" - -if [ ! -d "$workspace" ]; then - if [ "$EUID" -ne 0 ] - then echo "The first time this script is run, this script requires root. Please run as root" - exit 1 - fi - mkdir "$workspace" - chmod -R 777 "$workspace" - if [ $? -ne 0 ]; then - echo "Failed to make a working directory in ""$workspace" - exit 1 - fi -fi - -# Step 1 get the ek (requires root) -if ! [ -e "$ekcert" ]; - then - echo "Retrieving Endorsement Certificate from the TPM" - bash "$get_ek_script" > "$ekcert" - if [ $? -ne 0 ]; then - echo "Failed to retrieve the ek cert from the TPM, exiting" - rm -f "$ekcert" - exit 1 - fi -else - echo "Endorsement Credential file exists, skipping retrieval" -fi - -# Step 2 create the components file (requires root) -if ! [ -e "$componentlist" ]; then - echo "Retrieving component info from this device" - bash "$componentlister_script" > "$componentlist" - if [ $? -ne 0 ]; then - echo "Failed to create a device component list, exiting" - rm -f "$componentlist" - exit 1 - fi -else - echo "Component file exists, skipping" -fi - -# Step 3 create the reference options file -if ! [ -e "$policyreference" ]; then - echo "Creating a Platform policy JSON file" - bash "$policymaker_script" > "$policyreference" - if [ $? -ne 0 ]; then - echo "Failed to create the policy reference, exiting" - rm -f "$policyreference" - exit 1 - fi -else - echo "Policy settings file exists, skipping" -fi - -# Step 4 create the extensions settings file -if ! [ -e "$extsettings" ]; then - echo "Creating an extensions JSON file" - bash "$extensions_script" > "$extsettings" - if [ $? -ne 0 ]; then - echo "Failed to create the extensions file, exiting" - rm -f "$extsettings" - exit 1 - fi -else - echo "Extensions file exists, skipping" -fi - -# Step 5 check for JSON errors -printf "Checking JSON files" -if ! cat "$componentlist" | jq -e . >/dev/null; then - echo "Component file has JSON errors, exiting" - exit 1 -fi - -if ! cat "$policyreference" | jq -e . >/dev/null; then - echo "Policy settings file has JSON errors, exiting" - exit 1 -fi - -if ! cat "$extsettings" | jq -e . >/dev/null; then - echo "Extensions file has JSON errors, exiting" - exit 1 -fi -printf "...OK\n" - -# Step 6 create a sample signing key pair -if ! [ -e "$pcsigncert" ]; then - echo "Creating a signing key for signing platform credentials" - $(openssl req -x509 -nodes -days "$daysValid" -newkey "$sigalg" -keyout "$sigkey" -out "$pcsigncert" -subj "$subjectDN" >> /dev/null) - if [ $? -ne 0 ]; then - echo "Failed to create the key pair, exiting" - exit 1 - fi -else - echo "Platform Signing file exists, skipping" -fi - -# Step 7 create and sign the new platform credential -echo "Generating a signed Platform Credential" -bash $signer_bin -x "$extsettings" -c "$componentlist" -e "$ekcert" -p "$policyreference" -k "$sigkey" -P "$pcsigncert" -N "$serialnumber" -b "$dateNotBefore" -a "$dateNotAfter" -f "$pccert" -if [ $? -ne 0 ]; then - echo "The signer could not produce a Platform Credential, exiting" - exit 1 -fi - -# Step 8 validate the signature -echo "Validating the signature" -bash $validator_bin -P "$pcsigncert" -X "$pccert" - -if [ $? -eq 0 ]; then - echo "PC Credential Creation Complete." - echo "Platform Credential has been placed in ""$pccert" -else - rm -f "$pccert" - echo "Error with signature validation of the credential." -fi - diff --git a/dotnet/paccor_scripts/paccor_scripts/scripts/referenceoptions.sh b/dotnet/paccor_scripts/paccor_scripts/scripts/referenceoptions.sh deleted file mode 100644 index ea1aef4..0000000 --- a/dotnet/paccor_scripts/paccor_scripts/scripts/referenceoptions.sh +++ /dev/null @@ -1,265 +0,0 @@ -#!/bin/bash - -### User customizable values -tcgPlatformSpecificationMajorVersion="1" # Released May 22, 2017 -tcgPlatformSpecificationMinorVersion="3" -tcgPlatformSpecificationRevision="22" -tcgPlatformSpecificationClass="00000001" # In HEX. For the Client (TPM_PS_PC) in the structures document. -tcgCredentialSpecificationMajorVersion="1" # Released Jan 16, 2018 -tcgCredentialSpecificationMinorVersion="1" -tcgCredentialSpecificationRevision="17" -platformConfigUri="" # URL to a platform configuration document -platformConfigLocalCopyForHashing="" -tbbSecurityAssertionVersion="1" # default is 1 for this version of credential specification -#### Common Criteria specific values -commonCriteriaMeasuresVersion="" # see reference publications at https://CommonCriteriaPortal.org/cc -assuranceLevel="" # valid options are 1 thru 7 -evaluationStatus="" # valid options: designedToMeet, evaluationInProgress, evaluationCompleted -ccPlus="" # default false, valid options: true, false -strengthOfFunction="" # valid options: basic, medium, high -profileOid="" # OID of the protection profile -profileUri="" -profileLocalCopyForHashing="" -targetOid="" -targetUri="" -targetLocalCopyForHashing="" -#### FIPS specific values -fipsVersion="" # see reference publications at https://csrc.nist.gov/Projects/Cryptographic-Module-Validation-Program/Standards -fipsLevel="" -fipsPlus="" # default false, valid options: true, false -#### Other TBB assertions -measurementRootType="" # valid options: static, dynamic, nonHost, hybrid, physical, virtual -iso9000Certified="false" # default false, valid options: true, false -iso9000Uri="" # This is referenced as a IA5String in v1 of the spec. - -### The logic below can be changed by advanced users. -#### SHA-256 was assumed to be acceptable for each of the hashAlg choices for URI References -#### 2.16.840.1.101.3.4.2.1 is the oid for SHA-256. see https://tools.ietf.org/html/rfc5754 for other common hash algorithm IDs - - -### JSON Structure Keywords -JSON_TCGPLATFORMSPECIFICATION="TCGPLATFORMSPECIFICATION" -JSON_TCGCREDENTIALSPECIFICATION="TCGCREDENTIALSPECIFICATION" -JSON_MAJORVERSION="MAJORVERSION" -JSON_MINORVERSION="MINORVERSION" -JSON_REVISION="REVISION" -JSON_PLATFORMCLASS="PLATFORMCLASS" -JSON_TBBSECURITYASSERTIONS="TBBSECURITYASSERTIONS" -JSON_VERSION="VERSION" -JSON_CCINFO="CCINFO" -JSON_ASSURANCELEVEL="ASSURANCELEVEL" -JSON_EVALUATIONSTATUS="EVALUATIONSTATUS" -JSON_PLUS="PLUS" -JSON_STRENGTHOFFUNCTION="STRENGTHOFFUNCTION" -JSON_PROFILEOID="PROFILEOID" -JSON_PROFILEURI="PROFILEURI" -JSON_TARGETOID="TARGETOID" -JSON_TARGETURI="TARGETURI" -JSON_FIPSLEVEL="FIPSLEVEL" -JSON_LEVEL="LEVEL" -JSON_MEASUREMENTROOTTYPE="RTMTYPE" -JSON_ISO9000CERTIFIED="ISO9000CERTIFIED" -JSON_ISO9000URI="ISO9000URI" -JSON_PLATFORMCONFIGURI="PLATFORMCONFIGURI" -#### JSON Platform URI Keywords -JSON_URI="UNIFORMRESOURCEIDENTIFIER" -JSON_HASHALG="HASHALGORITHM" -JSON_HASHVALUE="HASHVALUE" - -### JSON Structure Format -JSON_REFERENCE_OPTIONS_TEMPLATE='{ - %s -}' -JSON_PLATFORM_SPEC_TEMPLATE=' - \"'"$JSON_TCGPLATFORMSPECIFICATION"'\": { - \"'"$JSON_VERSION"'\": { - \"'"$JSON_MAJORVERSION"'\": \"%s\", - \"'"$JSON_MINORVERSION"'\": \"%s\", - \"'"$JSON_REVISION"'\": \"%s\" - }, - \"'"$JSON_PLATFORMCLASS"'\": \"%s\" - }' -JSON_CREDENTIAL_SPEC_TEMPLATE=' - \"'"$JSON_TCGCREDENTIALSPECIFICATION"'\": { - \"'"$JSON_MAJORVERSION"'\": \"%s\", - \"'"$JSON_MINORVERSION"'\": \"%s\", - \"'"$JSON_REVISION"'\": \"%s\" - }' -JSON_TBB_ASSERTIONS_TEMPLATE=' - \"'"$JSON_TBBSECURITYASSERTIONS"'\": { - \"'"$JSON_VERSION"'\": \"%s\", - \"'"$JSON_ISO9000CERTIFIED"'\": \"%s\"%s - }' -JSON_CC_INFO_TEMPLATE=' - \"'"$JSON_CCINFO"'\": { - \"'"$JSON_VERSION"'\": \"%s\", - \"'"$JSON_ASSURANCELEVEL"'\": \"%s\", - \"'"$JSON_EVALUATIONSTATUS"'\": \"%s\", - \"'"$JSON_PLUS"'\": \"%s\"%s - }' -JSON_STRENGTHOFFUNCTION_TEMPLATE=' - \"'"$JSON_STRENGTHOFFUNCTION"'\": \"%s\"' -JSON_PROFILEOID_TEMPLATE=' - \"'"$JSON_PROFILEOID"'\": \"%s\"' -JSON_TARGETOID_TEMPLATE=' - \"'"$JSON_TARGETOID"'\": \"%s\"' -JSON_FIPS_LEVEL_TEMPLATE=' - \"'"$JSON_FIPSLEVEL"'\": { - \"'"$JSON_VERSION"'\": \"%s\", - \"'"$JSON_LEVEL"'\": \"%s\", - \"'"$JSON_PLUS"'\": \"%s\" - }' -JSON_MEASUREMENTROOTTYPE_TEMPLATE=' - \"'"$JSON_MEASUREMENTROOTTYPE"'\": \"%s\"' -JSON_ISO9000CERTIFIED_TEMPLATE=' - \"'"$JSON_ISO9000CERTIFIED"'\": \"%s\"' -JSON_URIREFERENCE_TEMPLATE=' - \"%s\": { - %s - }' - -### JSON Constructor Aides -toCSV () { - old="$IFS" - IFS=',' - value="$*" - printf "$value" -} -jsonPlatformSpec() { - platformClass=$(printf "$tcgPlatformSpecificationClass" | xxd -r -p | base64 -w 0) - printf "$JSON_PLATFORM_SPEC_TEMPLATE" "$tcgPlatformSpecificationMajorVersion" "$tcgPlatformSpecificationMinorVersion" "$tcgPlatformSpecificationRevision" "$platformClass" -} -jsonCredentialSpec() { - printf "$JSON_CREDENTIAL_SPEC_TEMPLATE" "$tcgCredentialSpecificationMajorVersion" "$tcgCredentialSpecificationMinorVersion" "$tcgCredentialSpecificationRevision" -} -jsonStrengthOfFunction() { - if [ -n "$strengthOfFunction" ]; then - printf "$JSON_STRENGTHOFFUNCTION_TEMPLATE" "$strengthOfFunction" - fi -} -jsonProfileOid() { - if [ -n "$profileOid" ]; then - printf "$JSON_PROFILEOID_TEMPLATE" "$profileOid" - fi -} -jsonTargetOid() { - if [ -n "$targetOid" ]; then - printf "$JSON_TARGETOID_TEMPLATE" "$targetOid" - fi -} -jsonMeasurementRootType() { - if [ -n "$measurementRootType" ]; then - printf "$JSON_MEASUREMENTROOTTYPE_TEMPLATE" "$measurementRootType" - fi -} -jsonIso9000Certified() { - printf "$JSON_ISO9000CERTIFIED_TEMPLATE" "${1}" -} -jsonIso9000UriStr() { - printf '\"'"$JSON_ISO9000URI"'\": \"%s\"' "${1}" -} -jsonUri () { - printf '\"'"$JSON_URI"'\": \"%s\"' "${1}" -} -jsonHashAlg () { - printf '\"'"$JSON_HASHALG"'\": \"%s\"' "${1}" -} -jsonHashValue () { - printf '\"'"$JSON_HASHVALUE"'\": \"%s\"' "${1}" -} -jsonUriBuilder () { - ## Usage: Requires 3 parameters. See below for the assumed hashAlg. - ## ${1} - The json object name. i.e. JSON_PROFILEURI - ## ${2} - The URI - ## ${3} - Full path to the file to provide a hash over. - if [ $# -eq 3 ]; then - tmpUri=$(jsonUri "${2}") - tmpUriDetails="" - if [ -n "${2}" ]; then - tmpHashAlg="2.16.840.1.101.3.4.2.1" # OID for SHA256 - tmpHashValue=$(sha256sum "${3}" | sed -r 's/^([0-9a-f]+).*/\1/' | tr -d [:space:] | xxd -r -p | base64 -w 0) - tmpHashAlgStr=$(jsonHashAlg "$tmpHashAlg") - tmpHashValueStr=$(jsonHashValue "$tmpHashValue") - tmpUriDetails="$tmpHashAlgStr"",""$tmpHashValueStr" - fi - printf "$JSON_URIREFERENCE_TEMPLATE" "${1}" "$(toCSV "$tmpUri" "$tmpUriDetails")" - fi -} -jsonCcInfo() { - if [ -n "$commonCriteriaMeasuresVersion" ] && [ -n "$assuranceLevel" ] && [ -n "$evaluationStatus" ]; then - if [ -z "$ccPlus" ]; then - ccPlus="FALSE" - fi - tmpRest= - if [ -n "$strengthOfFunction" ]; then - tmpRest="$tmpRest"",""$(jsonStrengthOfFunction)" - fi - if [ -n "$profileOid" ]; then - tmpRest="$tmpRest"",""$(jsonProfileOid)" - fi - if [ -n "$profileUri" ] && [ -n "$profileLocalCopyForHashing" ]; then - tmpProfileUri=$(jsonUriBuilder "$JSON_PROFILEURI" "$profileUri" "$profileLocalCopyForHashing") - tmpRest="$tmpRest"",""$tmpProfileUri" - fi - if [ -n "$targetOid" ]; then - tmpRest="$tmpRest"",""$(jsonTargetOid)" - fi - if [ -n "$targetUri" ] && [ -n "$targetLocalCopyForHashing" ]; then - tmpTargetUri=$(jsonUriBuilder "$JSON_TARGETURI" "$targetUri" "$targetLocalCopyForHashing") - tmpRest="$tmpRest"",""$tmpTargetUri" - fi - - printf "$JSON_CC_INFO_TEMPLATE" "$commonCriteriaMeasuresVersion" "$assuranceLevel" "$evaluationStatus" "$ccPlus" "${tmpRest}" - fi -} -jsonFipsLevel() { - if [ -n "$fipsVersion" ] && [ -n "$fipsLevel" ]; then - if [ -z "$fipsPlus" ]; then - fipsPlus="FALSE" - fi - printf "$JSON_FIPS_LEVEL_TEMPLATE" "$fipsVersion" "$fipsLevel" "$fipsPlus" - fi -} -jsonTbbSecurityAssertions() { - if [ -z "$tbbSecurityAssertionVersion" ]; then - tbbSecurityAssertionVersion="1" - fi - if [ -z "$iso9000Certified" ]; then - iso9000Certified="FALSE" - fi - tmpRest= - finalCcInfo=$(jsonCcInfo) - if [ -n "$finalCcInfo" ]; then - tmpRest="$tmpRest"",""$finalCcInfo" - fi - finalFipsLevel=$(jsonFipsLevel) - if [ -n "$finalFipsLevel" ]; then - tmpRest="$tmpRest"",""$finalFipsLevel" - fi - if [ -n "$measurementRootType" ]; then - tmpRtmType=$(jsonMeasurementRootType) - tmpRest="$tmpRest"",""$tmpRtmType" - fi - if [ -n "$iso9000Uri" ]; then - tmpIso9000Uri=$(jsonIso9000UriStr "$iso9000Uri") - tmpRest="$tmpRest"",""$tmpIso9000Uri" - fi - - printf "$JSON_TBB_ASSERTIONS_TEMPLATE" "$tbbSecurityAssertionVersion" "$iso9000Certified" "$tmpRest" -} -jsonReferenceOptionsFile() { - tmpData=$(jsonPlatformSpec) - tmpData="$tmpData"",""$(jsonCredentialSpec)" - tmpData="$tmpData"",""$(jsonTbbSecurityAssertions)" - if [ -n "$platformConfigUri" ] && [ -n "$platformConfigLocalCopyForHashing" ]; then - tmpPlatformConfigUri=$(jsonUriBuilder "$JSON_PLATFORMCONFIGURI" "$platformConfigUri" "$platformConfigLocalCopyForHashing") - tmpData="$tmpData"",""$tmpPlatformConfigUri" - fi - printf "$JSON_REFERENCE_OPTIONS_TEMPLATE" "$tmpData" -} - - -### Put it all together -finalData=$(jsonReferenceOptionsFile) -printf "$finalData""\n" - diff --git a/dotnet/paccor_scripts/paccor_scripts/scripts/windows/allcomponents.ps1 b/dotnet/paccor_scripts/paccor_scripts/scripts/windows/allcomponents.ps1 index de9b5b6..44b4aa8 100644 --- a/dotnet/paccor_scripts/paccor_scripts/scripts/windows/allcomponents.ps1 +++ b/dotnet/paccor_scripts/paccor_scripts/scripts/windows/allcomponents.ps1 @@ -83,8 +83,13 @@ $JSON_URI="UNIFORMRESOURCEIDENTIFIER" $JSON_HASHALG="HASHALGORITHM" $JSON_HASHVALUE="HASHVALUE" #### JSON Properties Keywords -$JSON_NAME="NAME" -$JSON_VALUE="VALUE" +$JSON_NAME="PROPERTYNAME" +$JSON_VALUE="PROPERTYVALUE" +$JSON_PROP_STATUS="PROPERTYSTATUS" +#### JSON Status Keywords +$JSON_STATUS_ADDED="ADDED" +$JSON_STATUS_MODIFIED="MODIFIED" +$JSON_STATUS_REMOVED="REMOVED" $NOT_SPECIFIED="Not Specified" @@ -120,6 +125,13 @@ $JSON_PROPERTY_TEMPLATE=" `"$JSON_VALUE`": `"{1}`" }} " +$JSON_PROPERTY_TEMPLATE_OPT=" + {{ + `"$JSON_NAME`": `"{0}`", + `"$JSON_VALUE`": `"{1}`", + `"$JSON_PROP_STATUS`": `"{2}`" + }} +" $JSON_ADDRESSES_TEMPLATE=" `"$JSON_ADDRESSES`": [{0}]" $JSON_ETHERNETMAC_TEMPLATE=" {{ `"$JSON_ETHERNETMAC`": `"{0}`" }} " @@ -149,7 +161,6 @@ $JSON_COMPONENTPLATFORMCERTURI_TEMPLATE=' }}' $JSON_STATUS_TEMPLATE=" `"$JSON_STATUS`": {{ - }}" ### JSON Constructor Aides @@ -242,6 +253,8 @@ function queryForPen () { function jsonProperty () { if ($args.Length -eq 2) { echo ("$JSON_PROPERTY_TEMPLATE" -f "$($args[0])","$($args[1])") + } elseif ($args.Length -eq 3) { + echo ("$JSON_PROPERTY_TEMPLATE_OPT" -f "$($args[0])","$($args[1])","$($args[2])") } } function jsonUri () { @@ -853,10 +866,10 @@ $componentArray=(jsonComponentArray "$componentChassis" "$componentBaseboard" "$ Write-Progress -Id 1 -Activity "Gathering properties" -PercentComplete 80 $osCaption=((wmic os get caption /value | Select-String -Pattern "^.*=(.*)$").Matches.Groups[1].ToString().Trim()) $property1=(jsonProperty "caption" "$osCaption") ## Example1 -$property2= ## Example2 +$property2=(jsonProperty "caption" "$osCaption") # "$JSON_STATUS_ADDED") ## Example2 with optional third status argument ### Collate the property details -$propertyArray=(jsonPropertyArray "$property1") +$propertyArray=(jsonPropertyArray "$property1" "$property2") ### Collate the URI details, if parameters above are blank, the fields will be excluded from the final JSON structure $componentsUri="" @@ -874,4 +887,3 @@ $FINAL_JSON_OBJECT=(jsonIntermediateFile "$platform" "$componentArray" "$compone Write-Progress -Id 1 -Activity "Done" -PercentComplete 100 [IO.File]::WriteAllText($filename, "$FINAL_JSON_OBJECT") - diff --git a/dotnet/paccor_scripts/paccor_scripts/scripts/windows/get_ek.ps1 b/dotnet/paccor_scripts/paccor_scripts/scripts/windows/get_ek.ps1 deleted file mode 100644 index 41d0cfe..0000000 --- a/dotnet/paccor_scripts/paccor_scripts/scripts/windows/get_ek.ps1 +++ /dev/null @@ -1,27 +0,0 @@ -param( - [parameter(Mandatory=$true)] - [ValidateNotNull()] - [string]$filename -) - -(&{ - Write-Progress -Activity "Gathering an EK Certificate" -CurrentOperation "Verifying access to the TPM through Windows" -PercentComplete 0 - If( (New-Object Security.Principal.WindowsPrincipal( - [Security.Principal.WindowsIdentity]::GetCurrent()) - ).IsInRole( - [Security.Principal.WindowsBuiltInRole]::Administrator) - ) { - Write-Progress -Activity "Gathering an EK Certificate" -CurrentOperation "Accessing the TPM" -PercentComplete 10 - $data=(Get-TpmEndorsementKeyInfo).ManufacturerCertificates[0].GetRawCertData() - Write-Progress -Activity "EK Certificate Gathered" -CurrentOperation "Converting to Base64" -PercentComplete 75 - $base64 = [Convert]::ToBase64String($data,'InsertLineBreaks') - Write-Progress -Activity "EK Certificate Gathered" -CurrentOperation "Writing PEM" -PercentComplete 90 - $pem = ("-----BEGIN CERTIFICATE-----`n$base64`n-----END CERTIFICATE-----").Replace("`r`n", "`n") - [IO.File]::WriteAllText($filename, $pem) - Write-Progress "Done" -PercentComplete 100 - } - Else { - echo "Not admin" - } - } -) \ No newline at end of file diff --git a/dotnet/paccor_scripts/paccor_scripts/scripts/windows/otherextensions.ps1 b/dotnet/paccor_scripts/paccor_scripts/scripts/windows/otherextensions.ps1 deleted file mode 100644 index 0d75546..0000000 --- a/dotnet/paccor_scripts/paccor_scripts/scripts/windows/otherextensions.ps1 +++ /dev/null @@ -1,170 +0,0 @@ -param( - [parameter(Mandatory=$true)] - [ValidateNotNull()] - [string]$filename -) - -### User customizable values -#### Certificate Policies is a mandatory extension. To add additional policies, more variables must be created and referenced below. -$certPolicyOid1="1.2.3" # Replace with a real Certificate Policy OID -$certPolicyQualifierCPS1="" -$certPolicyQualifierUserNotice1="TCG Trusted Platform Endorsement" # Don't change this value. -#### Authority Information Access is an optional extension. To add additional access methods, more variables must be created and referenced below. -$authorityInfoAccessMethod1="" # valid options are OCSP or CAISSUERS -$authorityInfoAccessLocation1="" # DN -#### CRL Distribution is an optional extension. Leave any blank to omit the extension. -$crlType="" # valid options are 0 or 1 -$crlName="" # DN -$crlReasonFlags="" # valid options are integers 0 thru 16 -$crlIssuer="" # CRL issuer DN -#### Targeting Information is an optional extension. Leave the targetFile variable blank to omit the extension. -$targetFile="" # provide comma separated file paths to EK certificates - -### The logic below can be changed by advanced users. -#### SHA-256 was assumed to be acceptable for each of the hashAlg choices for URI References -#### 2.16.840.1.101.3.4.2.1 is the oid for SHA-256. see https://tools.ietf.org/html/rfc5754 for other common hash algorithm IDs - -### JSON Structure Keywords -$JSON_CERTIFICATEPOLICIES="CERTIFICATEPOLICIES" -$JSON_POLICYIDENTIFIER="POLICYIDENTIFIER" -$JSON_POLICYQUALIFIERS="POLICYQUALIFIERS" -$JSON_POLICYQUALIFIERID="POLICYQUALIFIERID" -$JSON_QUALIFIER="QUALIFIER" -$JSON_CPS="CPS" -$JSON_USERNOTICE="USERNOTICE" -$JSON_AUTHORITYINFOACCESS="AUTHORITYINFOACCESS" -$JSON_ACCESSMETHOD="ACCESSMETHOD" -$JSON_ACCESSLOCATION="ACCESSLOCATION" -$JSON_OCSP="OCSP" -$JSON_CAISSUERS="CAISSUERS" -$JSON_CRLDISTRIBUTION="CRLDISTRIBUTION" -$JSON_DISTRIBUTIONNAME="DISTRIBUTIONNAME" -$JSON_TYPE="TYPE" -$JSON_NAME="NAME" -$JSON_REASON="REASON" -$JSON_ISSUER="ISSUER" -$JSON_TARGETINGINFORMATION="TARGETINGINFORMATION" -$JSON_FILE="FILE" - -### JSON Structure Format -$JSON_OTHER_EXTENSIONS_TEMPLATE="{{ - {0} -}}" -$JSON_CERTIFICATE_POLICIES_TEMPLATE=" - `"$JSON_CERTIFICATEPOLICIES`": [ - {0} - ]" -$JSON_POLICY_IDENTIFIER_TEMPLATE="{{ - `"$JSON_POLICYIDENTIFIER`": `"{0}`", - `"$JSON_POLICYQUALIFIERS`": [ - {1} - ] - }}" -$JSON_POLICY_QUALIFIER_TEMPLATE="{{ - `"$JSON_POLICYQUALIFIERID`": `"{0}`", - `"$JSON_QUALIFIER`": `"{1}`" - }}" -$JSON_AUTHORITY_INFO_ACCESS_TEMPLATE=" - `"$JSON_AUTHORITYINFOACCESS`": [ - {0} - ]" -$JSON_AUTH_ACCESS_TEMPLATE="{{ - `"$JSON_ACCESSMETHOD`": `"{0}`", - `"$JSON_ACCESSLOCATION`": `"{1}`" - }}" -$JSON_CRL_DISTRIBUTION_TEMPLATE=" - `"$JSON_CRLDISTRIBUTION`": {{ - `"$JSON_DISTRIBUTIONNAME`": {{ - `"$JSON_TYPE`": `"{0}`", - `"$JSON_NAME`": `"{1}`" - }}, - `"$JSON_REASON`": `"{2}`", - `"$JSON_ISSUER`": `"{3}`" - }}" -$JSON_TARGETING_INFORMATION_TEMPLATE=" - `"$JSON_TARGETINGINFORMATION`": [{0} - ]" -$JSON_TARGETING_INFORMATION_FILE_TEMPLATE=" - {{ `"$JSON_FILE`": {0}}}" # {0} is not in quotes because the files will be escaped for JSON by powershell - -### JSON Constructor Aides -function toCSV() { - if ($args.Length -ne 0) { - for ($i=0; $i -lt $args[0].Length; $i++) { - $item=($args[0].Get($i)) - - if ($item) { - $value="$value,$($args[0].Get($i))" - } - } - echo "$value".Trim(" ", ",") - } -} -function jsonCertificatePolicies() { - echo ("$JSON_CERTIFICATE_POLICIES_TEMPLATE" -f "$(toCSV($args))") -} -function jsonPolicyIdentifier() { - echo ("$JSON_POLICY_IDENTIFIER_TEMPLATE" -f "$($args[0])","$($args[1])") -} -function jsonPolicyQualifierCPS() { - echo ("$JSON_POLICY_QUALIFIER_TEMPLATE" -f "$JSON_CPS","$($args[0])") -} -function jsonPolicyQualifierUserNotice() { - echo ("$JSON_POLICY_QUALIFIER_TEMPLATE" -f "$JSON_USERNOTICE","$($args[0])") -} -function jsonAuthInfoAccess() { - echo ("$JSON_AUTHORITY_INFO_ACCESS_TEMPLATE" -f "$(toCSV($args))") -} -function jsonAuthInfoAccessElement() { - echo ("$JSON_AUTH_ACCESS_TEMPLATE" -f "$($args[0])","$($args[1])") -} -function jsonCRLDist() { - echo ("$JSON_CRL_DISTRIBUTION_TEMPLATE" -f "$crlType","$crlName","$crlReasonFlags","$crlIssuer") -} -function jsonTargetingInformation() { - $targetInfo= @() - $targetFileSplit="$targetFile".Split(",") - for ($i = 0; $i -lt $targetFileSplit.Count ; $i++) { - $escaped=($targetFileSplit[$i] | ConvertTo-Json) - $formatted=("$JSON_TARGETING_INFORMATION_FILE_TEMPLATE" -f $escaped) - $targetInfo+=$formatted - } - echo ("$JSON_TARGETING_INFORMATION_TEMPLATE" -f "$(toCSV($targetInfo))") -} - -function jsonOtherExtensionsFile() { - # work on making this script more intuitive - $usernotice1=(jsonPolicyQualifierUserNotice "$certPolicyQualifierUserNotice1") - $qualifier1="$usernotice1" - if ($certPolicyQualifierCPS1) { - $cps1=(jsonPolicyQualifierCPS "$certPolicyQualifierCPS1") - $qualifier1+="," + "$cps1" - } - $policyId1=(jsonPolicyIdentifier "$certPolicyOid1" "$qualifier1") - $certPolicies=(jsonCertificatePolicies "$policyId1") - $tmpData="$certPolicies" - - if ($authorityInfoAccessMethod1 -and $authorityInfoAccessLocation1) { - $access1=(jsonAuthInfoAccessElement "$authorityInfoAccessMethod1" "$authorityInfoAccessLocation1") - $access=(jsonAuthInfoAccess "$access1") - $tmpData+="," + "$access" - } - - if ($crlType -and $crlName -and $crlReasonFlags -and $crlIssuer) { - $crlDist=(jsonCRLDist) - $tmpData+="," + "$crlDist" - } - - if ($targetFile) { - $targets=(jsonTargetingInformation) - $tmpData+="," + "$targets" - } - - echo ("$JSON_OTHER_EXTENSIONS_TEMPLATE" -f "$tmpData") -} - - -### Put it all together -$finalData=(jsonOtherExtensionsFile) - -[IO.File]::WriteAllText($filename, "$finalData") \ No newline at end of file diff --git a/dotnet/paccor_scripts/paccor_scripts/scripts/windows/pc_certgen.ps1 b/dotnet/paccor_scripts/paccor_scripts/scripts/windows/pc_certgen.ps1 deleted file mode 100644 index d4ed895..0000000 --- a/dotnet/paccor_scripts/paccor_scripts/scripts/windows/pc_certgen.ps1 +++ /dev/null @@ -1,170 +0,0 @@ -$toolpath=(Split-Path -parent $PSCommandPath) -$timestamp=(Get-Date -UFormat "%Y%m%d%H%M%S") -#### Scripts and executable -$componentlister_script="$toolpath" + "/allcomponents.ps1" -$policymaker_script="$toolpath" + "/referenceoptions.ps1" -$get_ek_script="$toolpath" + "/get_ek.ps1" -$extensions_script="$toolpath" + "/otherextensions.ps1" -$signer_bin="$toolpath" + "/../../bin/signer.bat" -$validator_bin="$toolpath" + "/../../bin/validator.bat" -#### Files -$workspace="$toolpath" + "/../pc_testgen" -$componentlist="$workspace" + "/localhost-componentlist.json" -$policyreference="$workspace" + "/localhost-policyreference.json" -$ekcert="$workspace" + "/ek.pem" -$pccert="$workspace" + "/platform_cert." + "$timestamp" + ".crt" -$sigkey="$workspace" + "/CAcert.p12" -$pcsigncert="$workspace" + "/PCTestCA.example.com.cer" -$extsettings="$workspace" + "/extentions.json" -### Certificate params -$serialnumber="0001" -$dateNotBefore="20180101" -$dateNotAfter="20280101" -### Key Pair params -$subjectDN="C=US,O=example.com,OU=PCTest" -$daysValid=(Get-Date).AddYears(10) -$sigalg="RSA" -$sigalgbits="2048" -$certStoreLocation="Cert:\CurrentUser\My\" -$pfxpassword="password" - -if (!(Test-Path -Path $workspace )) { - if( (New-Object Security.Principal.WindowsPrincipal( - [Security.Principal.WindowsIdentity]::GetCurrent()) - ).IsInRole( - [Security.Principal.WindowsBuiltInRole]::Administrator) - ) { - md "$workspace" -ea 0 - if(!$?) { - echo "Failed to make a working directory in " + "$workspace" - exit 1 - } - } else { - echo "The first time this script is run, this script requires administrator privileges. Please run as admin" - exit 1 - } -} - -# Step 1 get the ek (requires admin) -if (!(Test-Path "$ekcert" -PathType Leaf)) { - echo "Retrieving Endorsement Certificate from the TPM" - powershell -ExecutionPolicy Bypass "$get_ek_script" "$ekcert" - if (!$?) { - echo "Failed to retrieve the ek cert from the TPM, exiting" - Remove-Item "$ekcert" -Confirm:$false -Force - exit 1 - } -} else { - echo "Endorsement Credential file exists, skipping retrieval" -} - -# Step 2 create the components file (does not require admin on Windows) -if (!(Test-Path "$componentlist" -PathType Leaf)) { - echo "Retrieving component info from this device" - powershell -ExecutionPolicy Bypass "$componentlister_script" "$componentlist" - if (!$?) { - echo "Failed to create a device component list, exiting" - Remove-Item "$componentlist" -Confirm:$false -Force - exit 1 - } -} else { - echo "Component file exists, skipping" -} - -# Step 3 create the reference options file -if (!(Test-Path "$policyreference" -PathType Leaf)) { - echo "Creating a Platform policy JSON file" - powershell -ExecutionPolicy Bypass "$policymaker_script" "$policyreference" - if (!$?) { - echo "Failed to create the policy reference, exiting" - Remove-Item "$policyreference" -Confirm:$false -Force - exit 1 - } -} else { - echo "Policy settings file exists, skipping" -} - -# Step 4 create the extensions settings file -if (!(Test-Path "$extsettings" -PathType Leaf)) { - echo "Creating an extensions JSON file" - powershell -ExecutionPolicy Bypass "$extensions_script" "$extsettings" - if (!$?) { - echo "Failed to create the extensions file, exiting" - Remove-Item "$extsettings" -Confirm:$false -Force - exit 1 - } -} else { - echo "Extensions file exists, skipping" -} - -# Step 5 check for JSON errors -Write-Progress -Activity "Checking JSON files" -CurrentOperation "components" -PercentComplete 25 -try { - [IO.File]::ReadAllText("$componentlist") | ConvertFrom-Json -ErrorAction Stop > $null -} catch { - echo "Component file has JSON errors, exiting" - exit 1 -} -Write-Progress -Activity "Checking JSON files" -CurrentOperation "policy" -PercentComplete 50 -try { - [IO.File]::ReadAllText("$policyreference") | ConvertFrom-Json -ErrorAction Stop > $null -} catch { - echo "Policy settings file has JSON errors, exiting" - exit 1 -} -Write-Progress -Activity "Checking JSON files" -CurrentOperation "extensions" -PercentComplete 75 -try { - [IO.File]::ReadAllText("$extsettings") | ConvertFrom-Json -ErrorAction Stop > $null -} catch { - echo "Extensions file has JSON errors, exiting" - exit 1 -} -Write-Progress -Activity "Checking JSON files" -CurrentOperation "Done" -PercentComplete 100 -echo "All JSON structures look valid." - -# Step 6 create a sample signing key pair -if (!(Test-Path "$pcsigncert" -PathType Leaf)) { - echo "Creating a signing key for signing platform credentials" - $newcert=(New-SelfSignedCertificate -Type Custom -KeyExportPolicy Exportable -Subject "$subjectDN" -KeyUsage DigitalSignature -KeyAlgorithm "$sigalg" -KeyLength "$sigalgbits" -NotAfter "$daysValid" -CertStoreLocation "$certStoreLocation") - if (!$?) { - echo "Failed to create the key pair, exiting" - exit 1 - } - $passw=ConvertTo-SecureString -String "$pfxpassword" -Force -AsPlainText; - $certStoreAddress="$certStoreLocation" - $certStoreAddress+=($newcert.Thumbprint) - Export-PfxCertificate -Cert "$certStoreAddress" -FilePath "$sigkey" -Password $passw - if (!$?) { - echo "Failed to export the PFX file, exiting" - exit 1 - } - Export-Certificate -Cert "$certStoreAddress" -FilePath "$pcsigncert" - if (!$?) { - echo "Failed to export the certificate, exiting" - exit 1 - } - Get-ChildItem "$certStoreLocation" | Where-Object { $_.Thumbprint -match ($newcert.Thumbprint) } | Remove-Item -} else { - echo "Platform Signing file exists, skipping" -} - -# Step 7 create and sign the new platform credential -echo "Generating a signed Platform Credential" -& $signer_bin -x "$extsettings" -c "$componentlist" -e "$ekcert" -p "$policyreference" -k "$sigkey" -N "$serialnumber" -b "$dateNotBefore" -a "$dateNotAfter" -f "$pccert" -if (!$?) { - echo "The signer could not produce a Platform Credential, exiting" - exit 1 -} - -# Step 8 validate the signature -echo "Validating the signature" -& $validator_bin -P "$pcsigncert" -X "$pccert" - -if ($?) { - echo "PC Credential Creation Complete." - echo "Platform Credential has been placed in ""$pccert" -} else { - Remove-Item "$pccert" -Confirm:$false -Force - echo "Error with signature validation of the credential." -} - diff --git a/dotnet/paccor_scripts/paccor_scripts/scripts/windows/referenceoptions.ps1 b/dotnet/paccor_scripts/paccor_scripts/scripts/windows/referenceoptions.ps1 deleted file mode 100644 index 1c50b34..0000000 --- a/dotnet/paccor_scripts/paccor_scripts/scripts/windows/referenceoptions.ps1 +++ /dev/null @@ -1,291 +0,0 @@ -param( - [parameter(Mandatory=$true)] - [ValidateNotNull()] - [string]$filename -) - -### User customizable values -$tcgPlatformSpecificationMajorVersion="1" # Released May 22, 2017 -$tcgPlatformSpecificationMinorVersion="3" -$tcgPlatformSpecificationRevision="22" -$tcgPlatformSpecificationClass="00000001" # In HEX. For the Client (TPM_PS_PC) in the structures document. -$tcgCredentialSpecificationMajorVersion="1" # -$tcgCredentialSpecificationMinorVersion="1" -$tcgCredentialSpecificationRevision="17" -$platformConfigUri="" # URL to a platform configuration document -$platformConfigLocalCopyForHashing="" -$tbbSecurityAssertionVersion="1" # default is 1 for this version of credential specification -#### Common Criteria specific values -$commonCriteriaMeasuresVersion="" # see reference publications at https://CommonCriteriaPortal.org/cc -$assuranceLevel="" # valid options are 1 thru 7 -$evaluationStatus="" # valid options: designedToMeet, evaluationInProgress, evaluationCompleted -$ccPlus="" # default false, valid options: true, false -$strengthOfFunction="" # valid options: basic, medium, high -$profileOid="" # OID of the protection profile -$profileUri="" -$profileLocalCopyForHashing="" -$targetOid="" -$targetUri="" -$targetLocalCopyForHashing="" -#### FIPS specific values -$fipsVersion="" # see reference publications at https://csrc.nist.gov/Projects/Cryptographic-Module-Validation-Program/Standards -$fipsLevel="" -$fipsPlus="" # default false, valid options: true, false -#### Other TBB assertions -$measurementRootType="" # valid options: static, dynamic, nonHost, hybrid, physical, virtual -$iso9000Certified="false" # default false, valid options: true, false -$iso9000Uri="" # This is referenced as a IA5String in v1 of the spec. - -### The logic below can be changed by advanced users. -#### SHA-256 was assumed to be acceptable for each of the hashAlg choices for URI References -#### 2.16.840.1.101.3.4.2.1 is the oid for SHA-256. see https://tools.ietf.org/html/rfc5754 for other common hash algorithm IDs - - -### JSON Structure Keywords -$JSON_TCGPLATFORMSPECIFICATION="TCGPLATFORMSPECIFICATION" -$JSON_TCGCREDENTIALSPECIFICATION="TCGCREDENTIALSPECIFICATION" -$JSON_MAJORVERSION="MAJORVERSION" -$JSON_MINORVERSION="MINORVERSION" -$JSON_REVISION="REVISION" -$JSON_PLATFORMCLASS="PLATFORMCLASS" -$JSON_TBBSECURITYASSERTIONS="TBBSECURITYASSERTIONS" -$JSON_VERSION="VERSION" -$JSON_CCINFO="CCINFO" -$JSON_ASSURANCELEVEL="ASSURANCELEVEL" -$JSON_EVALUATIONSTATUS="EVALUATIONSTATUS" -$JSON_PLUS="PLUS" -$JSON_STRENGTHOFFUNCTION="STRENGTHOFFUNCTION" -$JSON_PROFILEOID="PROFILEOID" -$JSON_PROFILEURI="PROFILEURI" -$JSON_TARGETOID="TARGETOID" -$JSON_TARGETURI="TARGETURI" -$JSON_FIPSLEVEL="FIPSLEVEL" -$JSON_LEVEL="LEVEL" -$JSON_MEASUREMENTROOTTYPE="RTMTYPE" -$JSON_ISO9000CERTIFIED="ISO9000CERTIFIED" -$JSON_ISO9000URI="ISO9000URI" -$JSON_PLATFORMCONFIGURI="PLATFORMCONFIGURI" -#### JSON Platform URI Keywords -$JSON_URI="UNIFORMRESOURCEIDENTIFIER" -$JSON_HASHALG="HASHALGORITHM" -$JSON_HASHVALUE="HASHVALUE" - -### JSON Structure Format -$JSON_REFERENCE_OPTIONS_TEMPLATE="{{ - {0} -}}" -$JSON_PLATFORM_SPEC_TEMPLATE=" - `"$JSON_TCGPLATFORMSPECIFICATION`": {{ - `"$JSON_VERSION`": {{ - `"$JSON_MAJORVERSION`": `"{0}`", - `"$JSON_MINORVERSION`": `"{1}`", - `"$JSON_REVISION`": `"{2}`" - }}, - `"$JSON_PLATFORMCLASS`": `"{3}`" - }}" -$JSON_CREDENTIAL_SPEC_TEMPLATE=" - `"$JSON_TCGCREDENTIALSPECIFICATION`": {{ - `"$JSON_MAJORVERSION`": `"{0}`", - `"$JSON_MINORVERSION`": `"{1}`", - `"$JSON_REVISION`": `"{2}`" - }}" -$JSON_TBB_ASSERTIONS_TEMPLATE=" - `"$JSON_TBBSECURITYASSERTIONS`": {{ - `"$JSON_VERSION`": `"{0}`", - `"$JSON_ISO9000CERTIFIED`": `"{1}`"{2} - }}" -$JSON_CC_INFO_TEMPLATE=" - `"$JSON_CCINFO`": {{ - `"$JSON_VERSION`": `"{0}`", - `"$JSON_ASSURANCELEVEL`": `"{1}`", - `"$JSON_EVALUATIONSTATUS`": `"{2}`", - `"$JSON_PLUS`": `"{3}`"{4} - }}" -$JSON_STRENGTHOFFUNCTION_TEMPLATE=" - `"$JSON_STRENGTHOFFUNCTION`": `"{0}`"" -$JSON_PROFILEOID_TEMPLATE=" - `"$JSON_PROFILEOID`": `"{0}`"" -$JSON_TARGETOID_TEMPLATE=" - `"$JSON_TARGETOID`": `"{0}`"" -$JSON_FIPS_LEVEL_TEMPLATE=" - `"$JSON_FIPSLEVEL`": {{ - `"$JSON_VERSION`": `"{0}`", - `"$JSON_LEVEL`": `"{1}`", - `"$JSON_PLUS`": `"{2}`" - }}" -$JSON_MEASUREMENTROOTTYPE_TEMPLATE=" - `"$JSON_MEASUREMENTROOTTYPE`": `"{0}`"" -$JSON_ISO9000CERTIFIED_TEMPLATE=" - `"$JSON_ISO9000CERTIFIED`": `"{0}`"" -$JSON_URIREFERENCE_TEMPLATE=" - `"{0}`": {{ - {1} - }}" - -### JSON Constructor Aides -function toCSV() { - if ($args.Length -ne 0) { - for ($i=0; $i -lt $args[0].Length; $i++) { - $item=($args[0].Get($i)) - - if ($item) { - $value="$value,$($args[0].Get($i))" - } - } - echo "$value".Trim(" ", ",") - } -} -function HexToByteArray { # Powershell doesn't have a built in BinToHex function - Param ([String] $str ) - - if ($str.Length % 2 -ne 0) { - $str="0$str" - } - - if ($str.Length -ne 0) { - ,@($str -split '([a-f0-9]{2})' | foreach-object { - if ($_) { - [System.Convert]::ToByte($_,16) - } - }) - } -} - -function jsonPlatformSpec() { - $platformClass=([System.Convert]::ToBase64String($(HexToByteArray $(echo "$tcgPlatformSpecificationClass")))) - echo ("$JSON_PLATFORM_SPEC_TEMPLATE" -f "$tcgPlatformSpecificationMajorVersion","$tcgPlatformSpecificationMinorVersion","$tcgPlatformSpecificationRevision","$platformClass") -} -function jsonCredentialSpec() { - echo ("$JSON_CREDENTIAL_SPEC_TEMPLATE" -f "$tcgCredentialSpecificationMajorVersion","$tcgCredentialSpecificationMinorVersion","$tcgCredentialSpecificationRevision") -} -function jsonStrengthOfFunction() { - if ($strengthOfFunction) { - echo ("$JSON_STRENGTHOFFUNCTION_TEMPLATE" -f "$strengthOfFunction") - } -} -function jsonProfileOid() { - if ($profileOid) { - echo ("$JSON_PROFILEOID_TEMPLATE" -f "$profileOid") - } -} -function jsonTargetOid() { - if ($targetOid) { - echo ("$JSON_TARGETOID_TEMPLATE" -f "$targetOid") - } -} -function jsonMeasurementRootType() { - if ($measurementRootType) { - echo ("$JSON_MEASUREMENTROOTTYPE_TEMPLATE" -f "$measurementRootType") - } -} -function jsonIso9000Certified() { - echo ("$JSON_ISO9000CERTIFIED_TEMPLATE" -f "$($args[0])") -} -function jsonIso9000UriStr() { - echo ("`"$JSON_ISO9000URI`": `"{0}`"" -f "$($args[0])") -} -function jsonUri () { - echo ("`"$JSON_URI`": `"{0}`"" -f "$($args[0])") -} -function jsonHashAlg () { - echo ("`"$JSON_HASHALG`": `"{0}`"" -f "$($args[0])") -} -function jsonHashValue () { - echo ("`"$JSON_HASHVALUE`": `"{0}`"" -f "$($args[0])") -} -function jsonUriBuilder () { - ## Usage: Requires 3 parameters. See below for the assumed hashAlg. - ## ${1} - The json object name. i.e. JSON_PROFILEURI - ## ${2} - The URI - ## ${3} - Full path to the file to provide a hash over. - if ($args.Length -eq 3) { - $tmpUri=(jsonUri "$($args[1])") - $tmpUriDetails="" - if ($($args[1])) { - $tmpHashAlg="2.16.840.1.101.3.4.2.1" # OID for SHA256 - $tmpHashValue=([System.Convert]::ToBase64String($(HexToByteArray $(Get-FileHash "$($args[2])" -Algorithm SHA256).Hash.Trim()))) - $tmpHashAlgStr=(jsonHashAlg "$tmpHashAlg") - $tmpHashValueStr=(jsonHashValue "$tmpHashValue") - $tmpUriDetails="$tmpHashAlgStr" + "," + "$tmpHashValueStr" - } - echo ("$JSON_URIREFERENCE_TEMPLATE" -f "$($args[0])","$(toCSV "$tmpUri","$tmpUriDetails")") - } -} -function jsonCcInfo() { - if ($commonCriteriaMeasuresVersion -and $assuranceLevel -and $evaluationStatus) { - if ($ccPlus) { - $ccPlus="FALSE" - } - $tmpRest="" - if ($strengthOfFunction) { - $tmpRest="$tmpRest" + "," + (jsonStrengthOfFunction) - } - if ($profileOid) { - $tmpRest="$tmpRest" + "," + (jsonProfileOid) - } - if ($profileUri -and $profileLocalCopyForHashing) { - $tmpProfileUri=(jsonUriBuilder "$JSON_PROFILEURI" "$profileUri" "$profileLocalCopyForHashing") - $tmpRest+="," + "$tmpProfileUri" - } - if ($targetOid) { - $tmpRest+="," + (jsonTargetOid) - } - if ($targetUri -and $targetLocalCopyForHashing) { - $tmpTargetUri=(jsonUriBuilder "$JSON_TARGETURI" "$targetUri" "$targetLocalCopyForHashing") - $tmpRest+="," + "$tmpTargetUri" - } - - echo ("$JSON_CC_INFO_TEMPLATE" -f "$commonCriteriaMeasuresVersion","$assuranceLevel","$evaluationStatus","$ccPlus","$tmpRest") - } -} -function jsonFipsLevel() { - if ($fipsVersion -and $fipsLevel) { - if (-not $fipsPlus) { - $fipsPlus="FALSE" - } - echo ("$JSON_FIPS_LEVEL_TEMPLATE" -f "$fipsVersion","$fipsLevel","$fipsPlus") - } -} -function jsonTbbSecurityAssertions() { - if (-not $tbbSecurityAssertionVersion) { - $tbbSecurityAssertionVersion="1" - } - if (-not $iso9000Certified) { - $iso9000Certified="FALSE" - } - $tmpRest="" - $finalCcInfo=(jsonCcInfo) - if ($finalCcInfo) { - $tmpRest+="," + "$finalCcInfo" - } - $finalFipsLevel=(jsonFipsLevel) - if ($finalFipsLevel) { - $tmpRest=","+ "$finalFipsLevel" - } - if ($measurementRootType) { - $tmpRtmType=(jsonMeasurementRootType) - $tmpRest+="," + "$tmpRtmType" - } - if ($iso9000Uri) { - $tmpIso9000Uri=(jsonIso9000UriStr "$iso9000Uri") - $tmpRest+="," + "$tmpIso9000Uri" - } - - echo ("$JSON_TBB_ASSERTIONS_TEMPLATE" -f "$tbbSecurityAssertionVersion","$iso9000Certified","$tmpRest") -} -function jsonReferenceOptionsFile() { - $tmpData=(jsonPlatformSpec) - $tmpData+=","+(jsonCredentialSpec) - $tmpData+=","+(jsonTbbSecurityAssertions) - if ($platformConfigUri -and $platformConfigLocalCopyForHashing) { - $tmpPlatformConfigUri=(jsonUriBuilder "$JSON_PLATFORMCONFIGURI" "$platformConfigUri" "$platformConfigLocalCopyForHashing") - $tmpData+="," + "$tmpPlatformConfigUri" - } - echo ("$JSON_REFERENCE_OPTIONS_TEMPLATE" -f "$tmpData") -} - - -### Put it all together -$finalData=(jsonReferenceOptionsFile) - -[IO.File]::WriteAllText($filename, "$finalData") \ No newline at end of file diff --git a/dotnet/paccor_scripts/paccor_scripts/src/PaccorComponentScriptsPlugin.cs b/dotnet/paccor_scripts/paccor_scripts/src/PaccorComponentScriptsPlugin.cs index 0e6356c..0a411fb 100644 --- a/dotnet/paccor_scripts/paccor_scripts/src/PaccorComponentScriptsPlugin.cs +++ b/dotnet/paccor_scripts/paccor_scripts/src/PaccorComponentScriptsPlugin.cs @@ -1,42 +1,27 @@ -using HardwareManifestPlugin; -using org.iso.standards.swid; -using PlatformCertificateFromProto; -using System.Reflection; +using HardwareManifestProto; +using HardwareManifestPlugin; using System.Runtime.InteropServices; namespace paccor_scripts { - public class PaccorComponentScriptsPlugin : IHardwareManifest { - public static readonly string scripts = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(typeof(PaccorComponentScriptsPlugin).Assembly.Location)!, "scripts")); - public static readonly string linux_components = Path.GetFullPath(Path.Combine(scripts, "allcomponents.sh")); - public static readonly string win_path = Path.GetFullPath(Path.Combine(scripts, "windows")); - public static readonly string win_temp_output = Path.GetFullPath(Path.Combine(win_path, "out.json")); - public static readonly string win_components = Path.GetFullPath(Path.Combine(win_path, "allcomponents.ps1")); - public string Name { - get; private set; - } - - public string Description { - get; private set; - } - public SoftwareIdentity? SWID { - get; private set; - } - - PlatformConfiguration IHardwareManifest.PlatformConfiguration => throw new NotImplementedException(); - - PlatformConfigurationV2 IHardwareManifest.PlatformConfigurationV2 => throw new NotImplementedException(); - - NameAttributes IHardwareManifest.NameAttributes => throw new NotImplementedException(); + public sealed class PaccorComponentScriptsPlugin : HardwareManifest { + public static readonly string Scripts = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(typeof(PaccorComponentScriptsPlugin).Assembly.Location)!, "scripts")); + public static readonly string LinuxComponents = Path.GetFullPath(Path.Combine(Scripts, "allcomponents.sh")); + public static readonly string WinPath = Path.GetFullPath(Path.Combine(Scripts, "windows")); + public static readonly string WinTempOutput = Path.GetFullPath(Path.Combine(WinPath, "out.json")); + public static readonly string WinComponents = Path.GetFullPath(Path.Combine(WinPath, "allcomponents.ps1")); + public static readonly string TraitDescription = "paccor component gathering scripts"; + public static readonly string TraitDescriptionUri = "https://github.com/nsacyber/paccor/scripts"; public PaccorComponentScriptsPlugin() { Name = "paccor_scripts"; - Description = "paccor 1.1.4r6 component gathering scripts"; - SWID = null; + Description = "paccor component gathering scripts"; + CollectsV2HardwareInformation = true; + CollectsV2HardwareInformation = false; } - string IHardwareManifest.GatherHardwareManifestAsJsonString() { - string json = ""; + public override bool GatherHardwareIdentifiers() { + bool result = false; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Task> task = Task.Run(RunWindows); Tuple results = task.Result; @@ -45,44 +30,30 @@ string IHardwareManifest.GatherHardwareManifestAsJsonString() { } // The allcomponents powershell script writes output to a file to preserve binary data // that can get corrupted during redirection - if (System.IO.File.Exists(win_temp_output)) { - json = System.IO.File.ReadAllText(win_temp_output); - //System.IO.File.Delete(win_temp_output); + if (System.IO.File.Exists(WinTempOutput)) { + string json = System.IO.File.ReadAllText(WinTempOutput); + ManifestV2 = ManifestV2.Parser.WithDiscardUnknownFields(true).ParseJson(json); + result = true; } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - //await $"scripts/00magic.sh --param {arg}".Bash(this.logger); Task> task = Task.Run(RunLinux); Tuple results = task.Result; if (task.Exception != null) { throw task.Exception; } - json = results.Item3; + string json = results.Item3; + ManifestV2 = ManifestV2.Parser.WithDiscardUnknownFields(true).ParseJson(json); + result = true; } - return json; + return result; } private async Task> RunWindows() { - return await Path.GetFullPath(win_components).ToString().Powershell(win_temp_output); + return await Path.GetFullPath(WinComponents).ToString().Powershell(WinComponents); } private async Task> RunLinux() { - return await Path.GetFullPath(linux_components).ToString().Bash(); - } - - void IHardwareManifest.Configure(string[] args) { - // does nothing - } - - bool IHardwareManifest.WillContainPlatformConfigurationV1() { - return false; - } - - bool IHardwareManifest.WillContainPlatformConfigurationV2() { - return false; - } - - bool IHardwareManifest.WillContainNameAttributes() { - return false; + return await Path.GetFullPath(LinuxComponents).ToString().Bash(); } } }