pax_global_header00006660000000000000000000000064131354315510014513gustar00rootroot0000000000000052 comment=27d34a61cb947780ab58508dfea70e696cff185c tpm2-tools-2.1.0/000077500000000000000000000000001313543155100135335ustar00rootroot00000000000000tpm2-tools-2.1.0/.ci/000077500000000000000000000000001313543155100142045ustar00rootroot00000000000000tpm2-tools-2.1.0/.ci/travis-build-and-run-tests.sh000077500000000000000000000023401313543155100216510ustar00rootroot00000000000000#!/usr/bin/env bash # all command failures are fatal set -e # Do not run tests when building on coverity_scan branch if [ "${COVERITY_SCAN_BRANCH}" == 1 ]; then echo "Coverity scan branch detected, not running build nor tests...exiting!" exit 0 fi # Bootstrap in the tpm2.0-tss tools directory ./bootstrap # Make a build variant directory and change to it mkdir ./build pushd ./build # Test building without tcti tabrmd ../configure --enable-unit --without-tcti-tabrmd make -j$(nproc) make -j$(nproc) check make -j$(nproc) clean # Test building without tcti socket ../configure --enable-unit --without-tcti-socket make -j$(nproc) make -j$(nproc) check make -j$(nproc) clean # Test building wihtout tcti device ../configure --enable-unit --without-tcti-device make -j$(nproc) make -j$(nproc) check make -j$(nproc) clean # Build all device TCTIs ../configure --enable-unit make -j$(nproc) make -j$(nproc) check # no clean here, keep artifacts for system testing # Move out of build back to the tpm2.0-tools directory popd # Switch over to the test directory pushd ./test/system # Run the tests on ALL device TCTIs configuration PATH=$(pwd)/../../build/tools:${PATH} ./test_all.sh # done go back to tpm2.0-tools directory popd exit 0 tpm2-tools-2.1.0/.ci/travis-tss-install.sh000077500000000000000000000034561313543155100203360ustar00rootroot00000000000000#!/bin/bash # Copyright (c) 2017, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. # This script is a wrapper around the the 'make install' command for the # TSS source code. This is a workaround for a travis-ci quirk that causes # any command run under 'sudo' to be unable to run clang. This script fixes # up the borked PATH, moves to the directory where we built the TSS and then # runs 'make install' # see: https://github.com/travis-ci/travis-ci/issues/3088 PATH=${PATH}:/usr/local/clang/bin (pushd ${TRAVIS_BUILD_DIR}/TPM2.0-TSS && \ make install && \ popd) tpm2-tools-2.1.0/.gitignore000066400000000000000000000020621313543155100155230ustar00rootroot00000000000000.deps/ .dirstamp *.log *.o *.a *.trs aclocal.m4 autom4te.cache/ compile config.guess config.log config.status config.sub configure depcomp install-sh m4/ libtool ltmain.sh missing Makefile Makefile.in man/man8/* tools/.dirstamp tools/libcommon.a tools/tpm2_activatecredential tools/tpm2_dump_capability tools/tpm2_hash tools/tpm2_nvlist tools/tpm2_nvread tools/tpm2_rsaencrypt tools/tpm2_nvrelease tools/tpm2_create tools/tpm2_getrandom tools/tpm2_nvwrite tools/tpm2_getpubak tools/tpm2_akparse tools/tpm2_rsadecrypt tools/tpm2_sign tools/tpm2_hmac tools/tpm2_nvdefine tools/tpm2_nvreadlock tools/tpm2_load tools/tpm2_readpublic tools/tpm2_unseal tools/tpm2_encryptdecrypt tools/tpm2_makecredential tools/tpm2_certify tools/tpm2_verifysignature tools/tpm2_createprimary tools/tpm2_quote tools/tpm2_listpcrs tools/tpm2_listpersistent tools/tpm2_evictcontrol tools/tpm2_getpubek tools/tpm2_takeownership tools/tpm2_loadexternal tools/tpm2_getmanufec tools/tpm2_send_command tools/tpm2_startup tools/tpm2_rc_decode test-driver test/tpm2-rc-decode_unit test/tpm2-rc-entry_unit tpm2-tools-2.1.0/.travis.yml000066400000000000000000000062121313543155100156450ustar00rootroot00000000000000dist: trusty # This is a lie: we don't need sudo but this is required to get an # Ubuntu image with a libc that isn't ancient, and with cmocka libs. sudo: required language: c compiler: - gcc addons: coverity_scan: project: name: "01org/tpm2.0-tools" description: "Build submitted via Travis CI" notification_email: william.c.roberts@intel.com build_command_prepend: "./bootstrap && ./configure && make clean" build_command: "make -j4" branch_pattern: coverity_scan apt: packages: - autoconf-archive - openssl - libssl-dev - libcurl4-openssl-dev - libdbus-1-dev - libglib2.0-dev env: global: # The next declaration is the encrypted COVERITY_SCAN_TOKEN, created # via the "travis encrypt" command using the project repo's public key - secure: "RL61KKDlkyCIE6ZTV9HxnVIcrb5fsNQBKbq7d9vN7QqzAKbd1qedr7kzWZ+DMTi3F1e562DAzNPwNTN6KoLtXx0PxM3ETj1q/O1F5mk22gakLRpZAt0OowCEscSuzcMXdEcVxlNVB4Q3OM2OVJHgwJmh/pB05hx76xIfrrGkl+A8jc4zfjaHtUaTMFKUmeSuKwvTcMylbMVhCfuE9ALtvn6LssZ/roTQhsQ4f78X6grUKHvtQbXzQemTxjZD1mpmjGPlTAU9AnAvb8DmVmWNWyf3uNVElHeeplYLhiDkWPomm84oBH8Npxl+GRmvvmAsuCOkfE0AoC7WL4cFzvsFQ7iZcioF6MFoQH+QVZCvsRPRzxs36tJUXteNJZm4PBnpPpgnrRYx0VqMZ4CQLqZVPwlZUB0VC9amM1xYO/QRETV1XfcS7GqGH+G3hXR3ApyYPX2gLl8fy1M1RawdIGKOZXTo44pBOM1iws+Hrc2rqg5NFamfT4FIO1O9z3kHVEkh5AlTyYa7HJ5iuUb8ilyzZ7MI0Xlw4CJYNgzF/3TGk0cFMghJ/YY0Zd5CoVkBK31ENJ06k21DfuD4xyFVz4HpZJzcoJufkbXSc9HbGNKWgxAEzQrUDDQk9zaPzUe4hTVFYc3mQLKO/FPo+OQ/xxOsZIVAqYZD7xtbX+c6cBVFdks=" before_install: - echo -n | openssl s_client -connect scan.coverity.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | sudo tee -a /etc/ssl/certs/ca- install: - wget https://downloads.sourceforge.net/project/ibmswtpm2/ibmtpm532.tar - sha256sum ibmtpm532.tar | grep -q abc0b420257917ccb42a9750588565d5e84a2b4e99a6f9f46c3dad1f9912864f - mkdir ibmtpm532 && pushd ibmtpm532 && tar xzf ../ibmtpm532.tar && pushd ./src && make - ./tpm_server & - popd && popd - git clone https://github.com/01org/TPM2.0-TSS.git - pushd TPM2.0-TSS - ./bootstrap && ./configure && make -j$(nproc) - sudo ../.ci/travis-tss-install.sh - popd - sudo ldconfig /usr/local/lib - git clone https://github.com/01org/tpm2-abrmd.git - pushd tpm2-abrmd - ./bootstrap && ./configure --with-dbuspolicydir=/etc/dbus-1/system.d && make -j$(nproc) && sudo make install && popd - sudo mkdir -p /var/lib/tpm - sudo groupadd tss && sudo useradd -M -d /var/lib/tpm -s /bin/false -g tss tss - sudo pkill -HUP dbus-daemon - sudo -u tss tpm2-abrmd --tcti=socket & - wget http://mirrors.kernel.org/ubuntu/pool/universe/c/cmocka/libcmocka-dev_1.0.1-2_amd64.deb - wget http://mirrors.kernel.org/ubuntu/pool/universe/c/cmocka/libcmocka0_1.0.1-2_amd64.deb - sha256sum libcmocka-dev_1.0.1-2_amd64.deb | grep -q edb0dcfa14893b0a03375c4fe3b852043ce8fca8f2397cde340562554f6d50eb - sha256sum libcmocka0_1.0.1-2_amd64.deb | grep -q 797155b45a8288a860c4ed9dd3f161420f09ebf362de30166d9f6b98bfc27dd0 - sudo dpkg -i libcmocka0_1.0.1-2_amd64.deb - sudo dpkg -i libcmocka-dev_1.0.1-2_amd64.deb script: - ./.ci/travis-build-and-run-tests.sh tpm2-tools-2.1.0/AUTHORS000066400000000000000000000011151313543155100146010ustar00rootroot00000000000000The tpm2.0-tools project was created by Gang Wei at Intel Inc. A list of MUCH-APPRECIATED contributors follows. If you are not on this list but feel you should be, please contact the current maintainer(s). * atomsoftwarestudios * Benyu Xu * DamienMolina * Dandan Tu * Dewei Zhang * Erez Geva * Gang "Jimmy" Wei * Imran Desai * jethrogb * Philip Tricca tpm2-tools-2.1.0/Android.mk000066400000000000000000000057211313543155100154510ustar00rootroot00000000000000LOCAL_PATH := $(call my-dir) # This project TPM2_TPM_BASE=. # Download from https://github.com/01org/TPM2.0-TSS TPM2_TSS_BASE=tss define add_tss_inlude $(foreach d,$(1),$(LOCAL_PATH)/$(TPM2_TSS_BASE)/$(d)) endef TSS2_CFLAGS := -DSAPI_CLIENT # Here come the Version TPM_CFLAGS := -DVERSION=\"0.98\" $(TSS2_CFLAGS) TSS2_INCLUDE := $(call add_tss_inlude,include sysapi/include common) TSS2_TEST_INCLUDE := $(TSS2_INCLUDE) $(call add_tss_inlude,test/common/sample test/tpmclient resourcemgr) TPM_INCLUDE := $(TSS2_TEST_INCLUDE) $(call add_tss_inlude,include/tss2 include/tcti) include $(CLEAR_VARS) LOCAL_MODULE := libtss2 LOCAL_MODULE_TAGS := optional LOCAL_CFLAGS := $(TSS2_CFLAGS) LOCAL_C_INCLUDES := $(TSS2_INCLUDE) LOCAL_SRC_FILES := $(call all-c-files-under,$(TPM2_TSS_BASE)/sysapi $(TPM2_TSS_BASE)/tcti $(TPM2_TSS_BASE)/common) \ $(call all-cpp-files-under,$(TPM2_TSS_BASE)/tcti $(TPM2_TSS_BASE)/common) include $(BUILD_SHARED_LIBRARY) include $(CLEAR_VARS) LOCAL_MODULE := resourcemgr LOCAL_MODULE_TAGS := optional LOCAL_CFLAGS := $(TSS2_CFLAGS) LOCAL_C_INCLUDES := $(TSS2_INCLUDE) LOCAL_SRC_FILES := $(call all-c-files-under,$(TPM2_TSS_BASE)/resourcemgr) LOCAL_SHARED_LIBRARIES := libtss2 LOCAL_MODULE_PATH := $(TARGET_OUT_OPTIONAL_EXECUTABLES) include $(BUILD_EXECUTABLE) # The common testing functions call the testing application, so it must be static library! include $(CLEAR_VARS) LOCAL_MODULE := libtss2_test LOCAL_MODULE_TAGS := optional LOCAL_CFLAGS := $(TSS2_CFLAGS) LOCAL_C_INCLUDES := $(TSS2_TEST_INCLUDE) LOCAL_SRC_FILES := $(call all-c-files-under,$(TPM2_TSS_BASE)/test/common/sample) include $(BUILD_STATIC_LIBRARY) define add_tss_test_tgt include $$(CLEAR_VARS) LOCAL_MODULE := $(1) LOCAL_MODULE_TAGS := optional LOCAL_CFLAGS := $$(TSS2_CFLAGS) LOCAL_C_INCLUDES := $$(TSS2_TEST_INCLUDE) LOCAL_SRC_FILES := $$(TPM2_TSS_BASE)/test/$(1)/$(1).cpp LOCAL_SHARED_LIBRARIES := libtss2 LOCAL_STATIC_LIBRARIES := libtss2_test LOCAL_MODULE_PATH := $$(TARGET_OUT_OPTIONAL_EXECUTABLES) include $$(BUILD_EXECUTABLE) endef $(eval $(call add_tss_test_tgt,tpmtest)) $(eval $(call add_tss_test_tgt,tpmclient)) # The common source functions call the testing application, so it must be static library! include $(CLEAR_VARS) LOCAL_MODULE := libtpm_test LOCAL_MODULE_TAGS := optional LOCAL_CFLAGS := $(TPM_CFLAGS) LOCAL_C_INCLUDES := $(TPM_INCLUDE) LOCAL_SRC_FILES := $(TPM2_TPM_BASE)/sapi-tools/common.cpp include $(BUILD_STATIC_LIBRARY) define add_tpm_tgt include $$(CLEAR_VARS) LOCAL_MODULE := $(1) LOCAL_MODULE_TAGS := optional LOCAL_CFLAGS := $$(TPM_CFLAGS) LOCAL_C_INCLUDES := $$(TPM_INCLUDE) LOCAL_SRC_FILES := $$(TPM2_TPM_BASE)/sapi-tools/$(1).$(2) LOCAL_SHARED_LIBRARIES := libtss2 LOCAL_STATIC_LIBRARIES := libtpm_test libtss2_test LOCAL_MODULE_PATH := $$(TARGET_OUT_OPTIONAL_EXECUTABLES) include $$(BUILD_EXECUTABLE) endef $(foreach name,$(wildcard $(LOCAL_PATH)/$(TPM2_TPM_BASE)/sapi-tools/tpm2_*.cpp),$(eval $(call add_tpm_tgt,$(basename $(notdir $(name))),cpp))) tpm2-tools-2.1.0/CHANGELOG000066400000000000000000000051011313543155100147420ustar00rootroot00000000000000v2.1.0 - 2017-7-24 * Fix readx and writex on multiple EINTR returns. * Add support for the tabrmd TCTI. This is the new default. * Change default socket port from 2323 (the old resourcemgr) to 2321 (default simulator port). * Cherry-pick fix for CVE-2017-7524. * Fix tpm2_listpcr command line option handling. * Fix tpm2_getmanufec memory issues. v2.0 - 2017-03-29 * Tracked on the milestone: https://github.com/01org/tpm2.0-tools/milestone/2 * Reworked all the tools to support configurable TCTIs, based on build time configuration, one can specify the tcti via the --tcti (-T) option to all tools. * tpm2_getrandom interface made -s a positional argument. * Numerous bug fixes. v1.1 - 2016-11-04 Added * travis ci support. * Allow for unit tests to be enabled selectively. * tpm2_rc_decode tool: Decode TPM_RC error codes. * Android Make file * tpm2_listpersistent: list all persistent objects * test scripts for tpm2-tools * tpm2_nvreadlock * tpm2_getmanufec: retrieve EC from tpm manufacturer server. * Copy 'common' and 'sample' code from the TPM2.0-TSS repo. Modified * tpm2_takeownership: update option -c to use lockout password to clear. * tpm2_listpcrs: add options -L and -s, rewrite to increase performance. * tpm2_quote: added -L option to support selection of multiple banks. * tpm2_quote: add -q option to get qualifying data. * configure: Use pkg-config to get info about libcurl and libcrypto. * configure: Use pkg-config to locate SAPI and TCTI headers / libraries. * tpm2_x: Add -X option to enable password input in Hex format. * tpm2_nvdefine: Change -X option to -I. * tpm2-nvwrite: fix for unable to write 1024B+ data. * tpm2_getmanufec: Fix base64 encoding. * tpm2_x: fixed a lot of TPM2B failures caused by wrong initialization. * tpm2_getmanufec: let configure handle libs. * tpm2_getmanufec: Convert from dos to unix format. * build: Check for TSS2 library @ configure time. * build: Detect required TSS2 and TCTI headers. * build: Use libtool to build the common library * build: Install all binaries into sbin. * build: Build common sources into library. * build: Move all source files to 'src'. * Makefile.am: Move all build rules into single Makefile.am. * everything: Use new TCTI headers and fixup API calls. * everything: Update source to cope with sapi header cleanup. * tpm2_activatecredential: Updated to support TCG compatible EK * tpm2_getpubak: Updated to use TCG compatible EK * tpm2_getpubek: fix ek creation to follow TCG EK profile spec. Removed * Windows related code * depenedency on the TPM2.0-TSS repo source code v1.0 - 2015-10-19 * 1.0 release * 29 tools included tpm2-tools-2.1.0/CONTRIBUTING000066400000000000000000000021731313543155100153700ustar00rootroot00000000000000Guidelines for submitting bugs: All non security bugs can be filed on the Issues tracker: https://github.com/01org/tpm2.0-tools/issues Security sensitive bugs should be emailed to a maintainer or to Intel via the guidelines here: https://security-center.intel.com/VulnerabilityHandlingGuidelines.aspx Guidelines for submitting changes: All changes should be introduced via github pull requests. This allows anyone to comment and provide feedback in lieu of having a mailing list. For pull requests opened by non-maintainers, any maintainer may review and merge that pull request. For maintainers, they either must have their pull request reviewed by another maintainer if possible, or leave the PR open for at least 24 hours, we consider this the window for comments. All tests must pass on Travis CI for the merge to occur. All changes must not introduce superfluous whitespace changes or whitespace errors. All changes should adhere to the coding standard documented under misc. Guideline for merging changes: Changes should be merged with the "rebase" option on github to avoid merge commits. This provides for a clear linear history. tpm2-tools-2.1.0/INSTALL000066400000000000000000000012561313543155100145700ustar00rootroot00000000000000To build and install the tpm2.0-tools software the following software is required: GNU Autoconf GNU Automake GNU Libtool pkg-config C compiler C Library Development Libraries and Header Files (for pthreads headers) TPM2.0 TSS socket TCTI library and header files TPM2.0 TSS SAPI library and header files OpenSSL library and header files Curl library and header files To obtain the tpm2.0-tools sources you must clone them as below: git clone https://github.com/01org/tpm2.0-tools To compile tpm2.0-tools execute the following commands from the root of the source directory: $ ./bootstrap $ ./configure $ make $ sudo make install All executables are generated under ./src/ directory. tpm2-tools-2.1.0/LICENSE000066400000000000000000000027341313543155100145460ustar00rootroot00000000000000Copyright (c) 2015, Intel Corporation Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. tpm2-tools-2.1.0/MAINTAINERS000066400000000000000000000001761313543155100152340ustar00rootroot00000000000000William Roberts Gang "Jimmy" Wei Philip Tricca tpm2-tools-2.1.0/Makefile.am000066400000000000000000000211561313543155100155740ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2015, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; ACLOCAL_AMFLAGS = -I m4 INCLUDE_DIRS = -I$(srcdir)/src -I$(srcdir)/lib LIB_COMMON := lib/libcommon.a AM_CFLAGS := $(INCLUDE_DIRS) $(TPM20_TSS_CFLAGS) $(EXTRA_CFLAGS) $(TCTI_TABRMD_CFLAGS) $(CRYPTO_CFLAGS) AM_LDFLAGS := $(EXTRA_LDFLAGS) LDADD = $(LIB_COMMON) $(TPM20_TSS_LIBS) $(TCTI_SOCK_LIBS) $(TCTI_DEV_LIBS) $(TCTI_TABRMD_LIBS) $(CRYPTO_LIBS) sbin_PROGRAMS = \ tools/tpm2_create \ tools/tpm2_createprimary \ tools/tpm2_load \ tools/tpm2_send_command \ tools/tpm2_dump_capability \ tools/tpm2_listpcrs \ tools/tpm2_listpersistent \ tools/tpm2_startup \ tools/tpm2_rc_decode \ tools/tpm2_verifysignature \ tools/tpm2_getmanufec \ tools/tpm2_quote \ tools/tpm2_takeownership \ tools/tpm2_getpubek \ tools/tpm2_getpubak \ tools/tpm2_akparse \ tools/tpm2_hash \ tools/tpm2_activatecredential \ tools/tpm2_makecredential \ tools/tpm2_nvlist \ tools/tpm2_nvread \ tools/tpm2_nvreadlock \ tools/tpm2_nvwrite \ tools/tpm2_nvdefine \ tools/tpm2_nvrelease \ tools/tpm2_hmac \ tools/tpm2_certify \ tools/tpm2_readpublic \ tools/tpm2_getrandom \ tools/tpm2_encryptdecrypt \ tools/tpm2_evictcontrol \ tools/tpm2_loadexternal \ tools/tpm2_rsadecrypt \ tools/tpm2_rsaencrypt \ tools/tpm2_sign \ tools/tpm2_unseal noinst_LIBRARIES = $(LIB_COMMON) lib_libcommon_a_SOURCES = \ lib/context-util.c \ lib/files.c \ lib/log.c \ lib/options.c \ lib/password_util.c \ lib/pcr.c \ lib/rc-decode.c \ lib/string-bytes.c \ lib/tpm2-header.c \ lib/tpm_hash.c \ lib/tpm_hmac.c \ lib/tpm_kdfa.c \ lib/tpm_session.c tools_tpm2_create_SOURCES = tools/tpm2_create.c tools/main.c tools_tpm2_createprimary_SOURCES = tools/tpm2_createprimary.c tools/main.c tools_tpm2_dump_capability_SOURCES = tools/tpm2_dump_capability.c tools/main.c tools_tpm2_listpcrs_SOURCES = tools/tpm2_listpcrs.c tools/main.c tools_tpm2_listpersistent_SOURCES = tools/tpm2_listpersistent.c tools/main.c tools_tpm2_load_SOURCES = tools/tpm2_load.c tools/main.c tools_tpm2_send_command_SOURCES = tools/tpm2_send_command.c tools/main.c tools_tpm2_startup_SOURCES = tools/tpm2_startup.c tools/main.c tools_tpm2_verifysignature_SOURCES = tools/tpm2_verifysignature.c tools/main.c tools_tpm2_getmanufec_CFLAG = $(AM_CFLAGS) $(CURL_CFLAGS) tools_tpm2_getmanufec_LDADD = $(LDADD) $(CURL_LIBS) tools_tpm2_getmanufec_SOURCES = tools/tpm2_getmanufec.c tools/main.c tools_tpm2_quote_SOURCES = tools/tpm2_quote.c tools/main.c tools_tpm2_takeownership_SOURCES = tools/tpm2_takeownership.c tools/main.c tools_tpm2_getpubek_SOURCES = tools/tpm2_getpubek.c tools/main.c tools_tpm2_getpubak_SOURCES = tools/tpm2_getpubak.c tools/main.c tools_tpm2_akparse_SOURCES = tools/tpm2_akparse.c tools/main.c tools_tpm2_hash_SOURCES = tools/tpm2_hash.c tools/main.c tools_tpm2_activatecredential_SOURCES = tools/tpm2_activatecredential.c tools/main.c tools_tpm2_makecredential_SOURCES = tools/tpm2_makecredential.c tools/main.c tools_tpm2_nvlist_SOURCES = tools/tpm2_nvlist.c tools/main.c tools_tpm2_nvread_SOURCES = tools/tpm2_nvread.c tools/main.c tools_tpm2_nvreadlock_SOURCES = tools/tpm2_nvreadlock.c tools/main.c tools_tpm2_nvwrite_SOURCES = tools/tpm2_nvwrite.c tools/main.c tools_tpm2_nvdefine_SOURCES = tools/tpm2_nvdefine.c tools/main.c tools_tpm2_nvrelease_SOURCES = tools/tpm2_nvrelease.c tools/main.c tools_tpm2_hmac_SOURCES = tools/tpm2_hmac.c tools/main.c tools_tpm2_certify_SOURCES = tools/tpm2_certify.c tools/main.c tools_tpm2_readpublic_SOURCES = tools/tpm2_readpublic.c tools/main.c tools_tpm2_getrandom_SOURCES = tools/tpm2_getrandom.c tools/main.c tools_tpm2_encryptdecrypt_SOURCES = tools/tpm2_encryptdecrypt.c tools/main.c tools_tpm2_evictcontrol_SOURCES = tools/tpm2_evictcontrol.c tools/main.c tools_tpm2_loadexternal_SOURCES = tools/tpm2_loadexternal.c tools/main.c tools_tpm2_rsadecrypt_SOURCES = tools/tpm2_rsadecrypt.c tools/main.c tools_tpm2_rsaencrypt_SOURCES = tools/tpm2_rsaencrypt.c tools/main.c tools_tpm2_sign_SOURCES = tools/tpm2_sign.c tools/main.c tools_tpm2_unseal_SOURCES = tools/tpm2_unseal.c tools/main.c # rc_decode does not use common main, since it does not need a dynamic TCTI. tools_tpm2_rc_decode_SOURCES = lib/rc-decode.c tools/tpm2_rc_decode.c if UNIT TESTS = $(check_PROGRAMS) check_PROGRAMS = \ test/unit/tpm2-rc-decode_unit \ test/unit/tpm2-rc-entry_unit \ test/unit/test_string_bytes \ test/unit/test_files test_unit_tpm2_rc_decode_unit_CFLAGS = $(AM_CFLAGS) $(CMOCKA_CFLAGS) test_unit_tpm2_rc_decode_unit_LDADD = $(CMOCKA_LIBS) $(LIB_COMMON) test_unit_tpm2_rc_decode_unit_SOURCES = test/unit/tpm2-rc-decode_unit.c test_unit_tpm2_rc_entry_unit_CFLAGS = $(AM_CFLAGS) $(CMOCKA_CFLAGS) test_unit_tpm2_rc_entry_unit_LDADD = $(CMOCKA_LIBS) $(LIB_COMMON) test_unit_tpm2_rc_entry_unit_SOURCES = test/unit/tpm2-rc-entry_unit.c test_unit_test_string_bytes_CFLAGS = $(AM_CFLAGS) $(CMOCKA_CFLAGS) test_unit_test_string_bytes_LDADD = $(CMOCKA_LIBS) $(LIB_COMMON) test_unit_test_string_bytes_SOURCES = test/unit/test_string_bytes.c test_unit_test_files_CFLAGS = $(AM_CFLAGS) $(CMOCKA_CFLAGS) test_unit_test_files_LDADD = $(LIB_COMMON) $(CMOCKA_LIBS) $(TPM20_TSS_LIBS) \ $(TCTI_SOCK_LIBS) $(TCTI_DEV_LIBS) test_unit_test_files_SOURCES = test/unit/test_files.c endif man8_MANS = \ man/man8/tpm2_createprimary.8 \ man/man8/tpm2_dump_capability.8 \ man/man8/tpm2_send_command.8 \ man/man8/tpm2_startup.8 \ man/man8/tpm2_listpcrs.8 \ man/man8/tpm2_quote.8 \ man/man8/tpm2_takeownership.8 \ man/man8/tpm2_getpubek.8 \ man/man8/tpm2_getpubak.8 \ man/man8/tpm2_getmanufec.8 \ man/man8/tpm2_akparse.8 \ man/man8/tpm2_makecredential.8 \ man/man8/tpm2_activatecredential.8 \ man/man8/tpm2_hash.8 \ man/man8/tpm2_nvlist.8 \ man/man8/tpm2_nvread.8 \ man/man8/tpm2_nvreadlock.8 \ man/man8/tpm2_nvwrite.8 \ man/man8/tpm2_nvdefine.8 \ man/man8/tpm2_nvrelease.8 \ man/man8/tpm2_create.8 \ man/man8/tpm2_hmac.8 \ man/man8/tpm2_certify.8 \ man/man8/tpm2_readpublic.8 \ man/man8/tpm2_getrandom.8 \ man/man8/tpm2_encryptdecrypt.8 \ man/man8/tpm2_evictcontrol.8 \ man/man8/tpm2_load.8 \ man/man8/tpm2_loadexternal.8 \ man/man8/tpm2_rsadecrypt.8 \ man/man8/tpm2_rsaencrypt.8 \ man/man8/tpm2_sign.8 \ man/man8/tpm2_unseal.8 \ man/man8/tpm2_verifysignature.8 \ man/man8/tpm2_listpersistent.8 \ man/man8/tpm2_rc_decode.8 man/man8/%.8 : man/%.8.in man/tcti-options.troff man/tcti-environment.troff rm -f $@ mkdir -p man/man8 if HAVE_TCTI_DEV echo ".nr HAVE_TCTI_DEV 1" >> $@ endif if HAVE_TCTI_SOCK echo ".nr HAVE_TCTI_SOCK 1" >> $@ endif sed -e '/@COMMON_OPTIONS_INCLUDE@/r man/common-options.troff' \ -e '/@COMMON_OPTIONS_INCLUDE@/d' \ -e '/@TCTI_OPTIONS_INCLUDE@/r man/tcti-options.troff' \ -e '/@TCTI_OPTIONS_INCLUDE@/d' \ -e '/@TCTI_ENVIRONMENT_INCLUDE@/r man/tcti-environment.troff' \ -e '/@TCTI_ENVIRONMENT_INCLUDE@/d' \ < $< >> $@ CLEANFILES = $(man8_MANS) tpm2-tools-2.1.0/README.md000066400000000000000000000020121313543155100150050ustar00rootroot00000000000000[![Build Status](https://travis-ci.org/01org/tpm2.0-tools.svg?branch=master)](https://travis-ci.org/01org/tpm2.0-tools) Coverity Scan Build Status **This site contains the code for the TPM (Trusted Platform Module) 2.0 tools based on TPM2.0-TSS** ## Build and Installation instructions: Instructions for building and installing the tpm2.0-tools are provided in the [INSTALL](https://github.com/01org/tpm2.0-tools/blob/master/INSTALL) file. **For more details on this code and how to use it, the [manual](https://github.com/01org/tpm2.0-tools/blob/master/manual) file is a good place to start.** ## Resources TPM 2.0 specifications can be found at [Trusted Computing Group](http://www.trustedcomputinggroup.org/). ## Contributing Instructions for contributing to the project are provided in the [CONTRIBUTING](https://github.com/01org/tpm2.0-tools/blob/master/CONTRIBUTING) file. tpm2-tools-2.1.0/RELEASE000066400000000000000000000044021313543155100145360ustar00rootroot00000000000000 Release Instructions The general release process will be to fork a branch at each major release followed by a ".X". For example, the major version 2 branches will be 2.X. Release canidates, will be tagged, signed and pushed to github, and marked under releases as "pre-release", starting with rc0. The release notes on github will contain the CHANGELOG contents for the running rc series. An example can be found here: * https://github.com/01org/tpm2.0-tools/releases/tag/2.1.0-rc0 Release candidates will also be announced on the mailing list. When a rc has gone 1 week without new changes, a release will be conducted. When a release is cut, the process is the same as an rc, with the exception that it is not marked as "pre-release" on github. The release notes should include everything from the last release to the latest release. Version Information Releases shall be tagged following semantic version guidelines found at: http://semver.org/ Versions after v1.1.0 will no longer have the "v" prefix. Autoconf now sets the VERSION #define based on the output of git describe. See commit 2e8a07bc for the details. Version tags after v1.1.0 shall be signed. Valid known public keys can be reached by referencing the annotated tags listed below: william-roberts-pub Verifying tags Import the key into your keyring: $ git show [annotated-tag-name] | gpg --import Example: $ git show william-roberts-pub | gpg --import Verify the release tag: $ git tag --verify [signed-tag-name] Signing Release Tags Ensure you have a key set up: $ gpg --list-keys If you don't generate one: $ gpg --gen-key Add that key to the gitconfig: $ git config user.signingkey [gpg-key-id] Make sure that key is reachable as an object in the repository: $ gpg -a --export [gpg-key-id] | git hash-object -w --stdin [object SHA] $ git tag -a [your-name-here]-pub [object SHA] Make sure you push that tag: $ git push origin [your-name-here]-pub NOTE: this assumes origin is the tpm2.0-tools official repo. After that, you can sign tags: $ git tag --sign [signed-tag-name] Push the tag to the repo: $ git push origin [signed-tag-name] NOTE: this assumes origin is the tpm2.0-tools official repo. A lot of this git/gpg information was edited from: https://blog.thesoftwarecraft.com/2013/03/signing-git-tags.htmltpm2-tools-2.1.0/bootstrap000077500000000000000000000000471313543155100154770ustar00rootroot00000000000000#! /bin/sh autoreconf --install --sym tpm2-tools-2.1.0/configure.ac000066400000000000000000000130321313543155100160200ustar00rootroot00000000000000AC_INIT([tpm2.0-tools], [m4_esyscmd_s([git describe --tags --always --dirty])]) AC_CONFIG_MACRO_DIR([m4]) AC_PROG_CC LT_INIT AM_INIT_AUTOMAKE([foreign subdir-objects]) AC_CONFIG_FILES([Makefile]) PKG_CHECK_MODULES([SAPI],[sapi]) # disable libtcti-device selectively (enabled by default) AC_ARG_WITH( [tcti-device], [AS_HELP_STRING([--with-tcti-device], [Build tools with support for the device TCTI.])], [], [with_tcti_device=check]) AS_IF( [test "x$with_tcti_device" != "xno"], [PKG_CHECK_MODULES( [TCTI_DEV], [tcti-device], [AC_DEFINE([HAVE_TCTI_DEV],[1]) with_tcti_device=yes], [if test "x$with_tcti_device" = "xyes"; then AC_MSG_FAILURE([--with-tcti-device option provided but libtcti-device not detected.]) fi])]) AM_CONDITIONAL([HAVE_TCTI_DEV],[test "x$with_tcti_device" = "xyes"]) # disable libtcti-socket selectively (enabled by default) AC_ARG_WITH( [tcti-socket], [AS_HELP_STRING([--with-tcti-socket], [Build tools with support for the socket TCTI.])], [], [with_tcti_socket=check]) AS_IF( [test "x$with_tcti_socket" != "xno"], [PKG_CHECK_MODULES( [TCTI_SOCK], [tcti-socket], [AC_DEFINE([HAVE_TCTI_SOCK],[1]) with_tcti_socket=yes], [if test "x$with_tcti_socket" = "xyes"; then AC_MSG_FAILURE([--with-tcti-socket option provided but libtcti-socket not detected.]) fi])]) AM_CONDITIONAL([HAVE_TCTI_SOCK],[test "x$with_tcti_socket" = "xyes"]) # selectively disable libtcti-tabrmd AC_ARG_WITH( [tcti-tabrmd], [AS_HELP_STRING([--with-tcti-tabrmd], [Build tools with support for the tabrmd TCTI.])], [], [with_tcti_tabrmd=check]) AS_IF( [test "x$with_tcti_tabrmd" != "xno"], [PKG_CHECK_MODULES( [TCTI_TABRMD], [tcti-tabrmd], [AC_DEFINE([HAVE_TCTI_TABRMD], [1]) with_tcti_tabrmd=yes], [if test "x$with_tcti_tabrmd" = "xyes"; then AC_MSG_FAILURE([--with-tcti-tabrmd option provided but libtcti-tabrmd not detected.]) fi])]) AM_CONDITIONAL([HAVE_TCTI_TABRMD],[test "x$with_tcti_tabrmd" = "xyes"]) # ensure we have at least one TCTI enabled, can't do much without one AS_IF( [test "x$with_tcti_device" != "xyes" -a \ "x$with_tcti_socket" != "xyes" -a \ "x$with_tcti_tabrmd" != "xyes"], [AC_MSG_ERROR( [no TCTIs: at least one TCTI library must be enabled], [1])]) PKG_CHECK_MODULES([CRYPTO],[libcrypto]) PKG_CHECK_MODULES([CURL],[libcurl]) AC_ARG_ENABLE([unit], [AS_HELP_STRING([--enable-unit], [build cmocka unit tests (default is no)])], [enable_unit=$enableval], [enable_unit=no]) AS_IF([test "x$enable_unit" != xno], [PKG_CHECK_MODULES([CMOCKA], [cmocka], [AC_DEFINE([HAVE_CMOCKA], [1])])]) AM_CONDITIONAL([UNIT], [test "x$enable_unit" != xno]) AC_ARG_ENABLE([hardening], [AS_HELP_STRING([--enable-hardening], [Enable compiler and linker options to frustrate memory corruption exploits @<:@yes@:>@])], [hardening="$enableval"], [hardening="yes"]) # Good information on adding flags, and dealing with compilers can be found here: # https://github.com/zcash/zcash/issues/1832 # https://github.com/kmcallister/autoharden/ AS_IF([test x"$hardening" != x"no"], [ AC_DEFUN([add_hardened_c_flag], [ AX_CHECK_COMPILE_FLAG([$1], [EXTRA_CFLAGS="$EXTRA_CFLAGS $1"], [AC_MSG_ERROR([Cannot enable $1, consider configuring with --disable-hardening])] ) ]) AC_DEFUN([add_hardened_ld_flag], [ AX_CHECK_LINK_FLAG([$1], [EXTRA_LDFLAGS="$EXTRA_LDFLAGS $1"], [AC_MSG_ERROR([Cannot enable $1, consider configuring with --disable-hardening])] ) ]) AC_DEFUN([add_hardened_define_flag], [ AX_CHECK_PREPROC_FLAG([$1], [EXTRA_CFLAGS="$EXTRA_CFLAGS $1"], [AC_MSG_ERROR([Cannot enable $1, consider configuring with --disable-hardening])] ) ]) add_hardened_c_flag([-Wall]) add_hardened_c_flag([-Wextra]) add_hardened_c_flag([-Werror]) add_hardened_c_flag([-Wformat]) add_hardened_c_flag([-Wformat-security]) add_hardened_c_flag([-Wstack-protector]) add_hardened_c_flag([-fstack-protector-all]) add_hardened_define_flag([-D_FORTIFY_SOURCE=2]) add_hardened_define_flag([-U_FORTIFY_SOURCE]) add_hardened_c_flag([-fPIC]) add_hardened_ld_flag([[-shared]]) add_hardened_c_flag([-fPIE]) add_hardened_ld_flag([[-pie]]) add_hardened_ld_flag([[-Wl,-z,relro]]) add_hardened_ld_flag([[-Wl,-z,now]]) ], [ AC_MSG_WARN([Compiling with --disable-hardening is dangerous! you should consider fixing the configure script compiler flags and submitting patches upstream!]) ]) # -D_GNU_SOURCE is required for execvpe() in options.c AX_CHECK_PREPROC_FLAG([-D_GNU_SOURCE], [EXTRA_CFLAGS="$EXTRA_CFLAGS -D_GNU_SOURCE"], [AC_MSG_ERROR([Cannot enable -D_GNU_SOURCE])] ) # Best attempt, strip unused stuff from the binary to reduce size. # Rather than nesting these and making them ugly just use a counter. AX_CHECK_COMPILE_FLAG([-fdata-sections], [strip+="y"]) AX_CHECK_COMPILE_FLAG([-ffunction-sections], [strip+="y"]) AX_CHECK_LINK_FLAG([[-Wl,--gc-sections]], [strip+="y"]) AS_IF([test x"$strip" == x"yyy"], [ EXTRA_CFLAGS="$EXTRA_CFLAGS -fdata-sections -ffunction-sections" EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,--gc-sections" ], AC_MSG_NOTICE([Not using compiler options to reduce binary size!]) ) AC_SUBST([EXTRA_CFLAGS]) AC_SUBST([EXTRA_LDFLAGS]) AC_OUTPUT tpm2-tools-2.1.0/lib/000077500000000000000000000000001313543155100143015ustar00rootroot00000000000000tpm2-tools-2.1.0/lib/context-util.c000066400000000000000000000203031313543155100171020ustar00rootroot00000000000000/* * Copyright (c) 2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #ifdef HAVE_TCTI_DEV #include #endif #ifdef HAVE_TCTI_SOCK #include #endif #ifdef HAVE_TCTI_TABRMD #include #endif #include "context-util.h" #include "log.h" /* * Initialize a TSS2_TCTI_CONTEXT for the device TCTI. */ #ifdef HAVE_TCTI_DEV TSS2_TCTI_CONTEXT* tcti_device_init (char const *device_file) { TCTI_DEVICE_CONF conf = { .device_path = device_file, .logCallback = NULL, .logData = NULL, }; size_t size; TSS2_RC rc; TSS2_TCTI_CONTEXT *tcti_ctx; rc = InitDeviceTcti (NULL, &size, 0); if (rc != TSS2_RC_SUCCESS) { fprintf (stderr, "Failed to get allocation size for device tcti context: " "0x%x\n", rc); return NULL; } tcti_ctx = (TSS2_TCTI_CONTEXT*)calloc (1, size); if (tcti_ctx == NULL) { fprintf (stderr, "Allocation for device TCTI context failed: %s\n", strerror (errno)); return NULL; } rc = InitDeviceTcti (tcti_ctx, &size, &conf); if (rc != TSS2_RC_SUCCESS) { fprintf (stderr, "Failed to initialize device TCTI context: 0x%x\n", rc); free (tcti_ctx); return NULL; } return tcti_ctx; } #endif /* * Initialize a socket TCTI instance using the provided options structure. * The address and port are the only configuration options used. Callbacks * for logging are set to NULL. * The caller is returned a TCTI context structure that is allocated by this * function. This structure must be freed by the caller. */ #ifdef HAVE_TCTI_SOCK TSS2_TCTI_CONTEXT* tcti_socket_init (char const *address, uint16_t port) { TCTI_SOCKET_CONF conf = { .hostname = address, .port = port, .logCallback = NULL, .logBufferCallback = NULL, .logData = NULL, }; size_t size; TSS2_RC rc; TSS2_TCTI_CONTEXT *tcti_ctx; rc = InitSocketTcti (NULL, &size, &conf, 0); if (rc != TSS2_RC_SUCCESS) { fprintf (stderr, "Faled to get allocation size for tcti context: " "0x%x\n", rc); return NULL; } tcti_ctx = (TSS2_TCTI_CONTEXT*)calloc (1, size); if (tcti_ctx == NULL) { fprintf (stderr, "Allocation for tcti context failed: %s\n", strerror (errno)); return NULL; } rc = InitSocketTcti (tcti_ctx, &size, &conf, 0); if (rc != TSS2_RC_SUCCESS) { fprintf (stderr, "Failed to initialize tcti context: 0x%x\n", rc); free (tcti_ctx); return NULL; } return tcti_ctx; } #endif #ifdef HAVE_TCTI_TABRMD TSS2_TCTI_CONTEXT* tcti_tabrmd_init (void) { TSS2_TCTI_CONTEXT *tcti_ctx; TSS2_RC rc; size_t size; rc = tss2_tcti_tabrmd_init(NULL, &size); if (rc != TSS2_RC_SUCCESS) { LOG_ERR ("Failed to get size for TABRMD TCTI context: 0x%" PRIx32, rc); return NULL; } tcti_ctx = (TSS2_TCTI_CONTEXT*)calloc (1, size); if (tcti_ctx == NULL) { LOG_ERR ("Allocation for TABRMD TCTI context failed: %s", strerror (errno)); return NULL; } rc = tss2_tcti_tabrmd_init (tcti_ctx, &size); if (rc != TSS2_RC_SUCCESS) { LOG_ERR ("Failed to initialize TABRMD TCTI context: 0x%" PRIx32, rc); free (tcti_ctx); return NULL; } return tcti_ctx; } #endif /* * Initialize a SAPI context using the TCTI context provided by the caller. * This function allocates memory for the SAPI context and returns it to the * caller. This memory must be freed by the caller. */ static TSS2_SYS_CONTEXT* sapi_ctx_init (TSS2_TCTI_CONTEXT *tcti_ctx) { TSS2_SYS_CONTEXT *sapi_ctx; TSS2_RC rc; size_t size; TSS2_ABI_VERSION abi_version = { .tssCreator = TSSWG_INTEROP, .tssFamily = TSS_SAPI_FIRST_FAMILY, .tssLevel = TSS_SAPI_FIRST_LEVEL, .tssVersion = TSS_SAPI_FIRST_VERSION, }; size = Tss2_Sys_GetContextSize (0); sapi_ctx = (TSS2_SYS_CONTEXT*)calloc (1, size); if (sapi_ctx == NULL) { fprintf (stderr, "Failed to allocate 0x%zx bytes for the SAPI context\n", size); return NULL; } rc = Tss2_Sys_Initialize (sapi_ctx, size, tcti_ctx, &abi_version); if (rc != TSS2_RC_SUCCESS) { fprintf (stderr, "Failed to initialize SAPI context: 0x%x\n", rc); free (sapi_ctx); return NULL; } return sapi_ctx; } /* * Initialize a SAPI context. Get configuration data from the provided * structure. */ TSS2_SYS_CONTEXT* sapi_init_from_options (common_opts_t *options) { TSS2_TCTI_CONTEXT *tcti_ctx; TSS2_SYS_CONTEXT *sapi_ctx; tcti_ctx = tcti_init_from_options (options); if (tcti_ctx == NULL) return NULL; sapi_ctx = sapi_ctx_init (tcti_ctx); if (sapi_ctx == NULL) return NULL; return sapi_ctx; } /* * Initialize a TSS2_TCTI_CONTEXT using whatever TCTI data is in the options * structure. This is a mechanism that allows the calling application to be * mostly ignorant of which TCTI they're creating / initializing. */ TSS2_TCTI_CONTEXT* tcti_init_from_options (common_opts_t *options) { switch (options->tcti_type) { #ifdef HAVE_TCTI_DEV case DEVICE_TCTI: return tcti_device_init (options->device_file); #endif #ifdef HAVE_TCTI_SOCK case SOCKET_TCTI: return tcti_socket_init (options->socket_address, options->socket_port); #endif #ifdef HAVE_TCTI_TABRMD case TABRMD_TCTI: return tcti_tabrmd_init (); #endif default: return NULL; } } /* * Teardown the provided TCTI context. This includes finalizing the * context and freeing the data for the context. */ void tcti_teardown (TSS2_TCTI_CONTEXT *tcti_context) { if (tcti_context == NULL) return; tss2_tcti_finalize (tcti_context); free (tcti_context); } /* * Teardown the provided SAPI context. This includes finalizing the * context and freeing the data for the context. */ void sapi_teardown (TSS2_SYS_CONTEXT *sapi_context) { if (sapi_context == NULL) return; Tss2_Sys_Finalize (sapi_context); free (sapi_context); } /* * Teardown and free the resoruces associted with a SAPI context structure. * This includes tearing down the TCTI as well. */ void sapi_teardown_full (TSS2_SYS_CONTEXT *sapi_context) { TSS2_TCTI_CONTEXT *tcti_context = NULL; TSS2_RC rc; rc = Tss2_Sys_GetTctiContext (sapi_context, &tcti_context); if (rc != TSS2_RC_SUCCESS) return; sapi_teardown (sapi_context); tcti_teardown (tcti_context); } tpm2-tools-2.1.0/lib/context-util.h000066400000000000000000000042041313543155100171110ustar00rootroot00000000000000/* * Copyright (c) 2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CONTEXT_UTIL_H #define CONTEXT_UTIL_H #include #include "options.h" /* * functions to setup TCTIs and SAPI contexts using data from the common * options */ TSS2_TCTI_CONTEXT* tcti_init_from_options (common_opts_t *options); TSS2_SYS_CONTEXT* sapi_init_from_options (common_opts_t *options); void tcti_teardown (TSS2_TCTI_CONTEXT *tcti_context); void sapi_teardown (TSS2_SYS_CONTEXT *sapi_context); void sapi_teardown_full (TSS2_SYS_CONTEXT *sapi_context); #endif /* CONTEXT_UTIL_H */ tpm2-tools-2.1.0/lib/files.c000066400000000000000000000271541313543155100155600ustar00rootroot00000000000000#include #include #include #include #include "files.h" #include "log.h" #include "string-bytes.h" static bool get_file_size(FILE *fp, long *file_size, const char *path) { long current = ftell(fp); if (current < 0) { LOG_ERR("Error getting current file offset for file \"%s\" error: %s", path, strerror(errno)); return false; } int rc = fseek(fp, 0, SEEK_END); if (rc < 0) { LOG_ERR("Error seeking to end of file \"%s\" error: %s", path, strerror(errno)); return false; } long size = ftell(fp); if (size < 0) { LOG_ERR("ftell on file \"%s\" failed: %s", path, strerror(errno)); return false; } rc = fseek(fp, current, SEEK_SET); if (rc < 0) { LOG_ERR("Could not restore initial stream position for file \"%s\" failed: %s", path, strerror(errno)); return false; } *file_size = size; return true; } bool files_load_bytes_from_file(const char *path, UINT8 *buf, UINT16 *size) { if (!buf || !size || !path) { return false; } FILE *f = fopen(path, "rb"); if (!f) { LOG_ERR("Could not open file \"%s\" error %s", path, strerror(errno)); return false; } long file_size; bool result = get_file_size(f, &file_size, path); if (!result) { /* get_file_size() logs errors */ goto err; } /* max is bounded on UINT16 */ if (file_size > *size) { LOG_ERR( "File \"%s\" size is larger than buffer, got %ld expected less than %u", path, file_size, *size); goto err; } result = files_read_bytes(f, buf, file_size); if (!result) { LOG_ERR("Could not read data from file \"%s\"", path); goto err; } *size = file_size; /* result set on files_read_bytes */ err: fclose(f); return result; } bool files_save_bytes_to_file(const char *path, UINT8 *buf, UINT16 size) { if (!path || !buf) { return false; } FILE *fp = fopen(path, "wb+"); if (!fp) { LOG_ERR("Could not open file \"%s\", error: %s", path, strerror(errno)); return false; } bool result = files_write_bytes(fp, buf, size); if (!result) { LOG_ERR("Could not write data to file \"%s\"", path); } fclose(fp); return result; } /* * Current version to write TPMS_CONTEXT to disk. */ #define CONTEXT_VERSION 1 bool files_save_tpm_context_to_file(TSS2_SYS_CONTEXT *sysContext, TPM_HANDLE handle, const char *path) { TPMS_CONTEXT context; TPM_RC rval = Tss2_Sys_ContextSave(sysContext, handle, &context); if (rval != TPM_RC_SUCCESS) { LOG_ERR( "Tss2_Sys_ContextSave: Saving handle 0x%x context failed. TPM Error:0x%x", handle, rval); return false; } FILE *f = fopen(path, "w+b"); if (!f) { LOG_ERR("Error opening file \"%s\" due to error: %s", path, strerror(errno)); return false; } /* * Saving the TPMS_CONTEXT structure to disk, format: * TPM2.0-TOOLS HEADER * U32 hiearchy * U32 savedHandle * U64 sequence * U16 contextBlobLength * BYTE[] contextBlob */ bool result = files_write_header(f, CONTEXT_VERSION); if (!result) { LOG_ERR("Could not write header for file: \"%s\"", path); goto out; } // UINT32 result = files_write_32(f, context.hierarchy); if (!result) { LOG_ERR("Could not write hierarchy for file: \"%s\"", path); goto out; } result = files_write_32(f, context.savedHandle); if (!result) { LOG_ERR("Could not write savedHandle for file: \"%s\"", path); goto out; } // UINT64 result = files_write_64(f, context.sequence); if (!result) { LOG_ERR("Could not write sequence for file: \"%s\"", path); goto out; } // U16 LENGTH result = files_write_16(f, context.contextBlob.t.size); if (!result) { LOG_ERR("Could not write contextBob size file: \"%s\"", path); goto out; } // BYTE[] contextBlob result = files_write_bytes(f, context.contextBlob.t.buffer, context.contextBlob.t.size); if (!result) { LOG_ERR("Could not write contextBlob buffer for file: \"%s\"", path); } /* result is set by file_write_bytes() */ out: fclose(f); return result; } bool file_load_tpm_context_from_file(TSS2_SYS_CONTEXT *sapi_context, TPM_HANDLE *handle, const char *path) { TPM_RC rval; FILE *f = fopen(path, "rb"); if (!f) { LOG_ERR("Error opening file \"%s\" due to error: %s", path, strerror(errno)); return false; } /* * Reading the TPMS_CONTEXT structure to disk, format: * TPM2.0-TOOLS HEADER * U32 hiearchy * U32 savedHandle * U64 sequence * U16 contextBlobLength * BYTE[] contextBlob */ UINT32 version; TPMS_CONTEXT context; bool result = files_read_header(f, &version); if (!result) { LOG_WARN( "The tpm context file \"%s\" does not appear in the proper format, assuming old format, this will be converted on the next save.", path); rewind(f); result = files_read_bytes(f, (UINT8 *) &context, sizeof(context)); if (!result) { LOG_ERR("Could not load file \"%s\" into tpm context", path); goto out; } /* Success load the context into the TPM */ goto load_to_tpm; } if (version != CONTEXT_VERSION) { LOG_ERR("Unsupported context file format version found, got: %"PRIu32, version); result = false; goto out; } result = files_read_32(f, &context.hierarchy); if (!result) { LOG_ERR("Error reading hierarchy!"); goto out; } result = files_read_32(f, &context.savedHandle); if (!result) { LOG_ERR("Error reading savedHandle!"); goto out; } result = files_read_64(f, &context.sequence); if (!result) { LOG_ERR("Error reading sequence!"); goto out; } result = files_read_16(f, &context.contextBlob.t.size); if (!result) { LOG_ERR("Error reading contextBlob.size!"); goto out; } if (context.contextBlob.t.size > sizeof(context.contextBlob.t.buffer)) { LOG_ERR( "Size mismatch found on contextBlob, got %"PRIu16" expected less than or equal to %zu", context.contextBlob.t.size, sizeof(context.contextBlob.t.buffer)); result = false; goto out; } result = files_read_bytes(f, context.contextBlob.t.buffer, context.contextBlob.t.size); if (!result) { LOG_ERR("Error reading contextBlob.size!"); goto out; } load_to_tpm: rval = Tss2_Sys_ContextLoad(sapi_context, &context, handle); if (rval != TPM_RC_SUCCESS) { LOG_ERR("ContextLoad Error. TPM Error:0x%x", rval); result = false; goto out; } result = true; out: fclose(f); return result; } bool files_does_file_exist(const char *path) { if (!path) { LOG_ERR("Path cannot be NULL"); return false; } FILE *fp = fopen(path,"rb"); if (fp) { fclose(fp); LOG_ERR("Path: %s already exists. Please rename or delete the file!", path); return true; } return false; } bool files_get_file_size(const char *path, long *file_size) { bool result = false; if (!path) { LOG_ERR("Must specify a path argument, cannot be NULL!"); return false; } if (!file_size) { LOG_ERR("Must specify a file size argument, cannot be NULL!"); return false; } FILE *fp = fopen(path,"rb"); if(!fp) { LOG_ERR("Could not open file: \"%s\" error: %s", path, strerror(errno)); return false; } result = get_file_size(fp, file_size, path); fclose(fp); return result; } /** * This is the magic for the file header. The header is organized * as a big endian U32 (BEU32) of MAGIC followed by a BEU32 of the * version number. Tools can define their own, individual file * formats as they make sense, but they should always have the header. */ static const UINT32 MAGIC = 0xBADCC0DE; /** * Writes size bytes to a file, continuing on EINTR short writes. * @param f * The file to write to. * @param data * The data to write. * @param size * The size, in bytes, of that data. * @return * True on success, False otherwise. */ static bool writex(FILE *f, UINT8 *data, size_t size) { size_t wrote = 0; size_t index = 0; do { wrote = fwrite(&data[index], 1, size, f); if (wrote != size) { if (errno != EINTR) { return false; } /* continue on EINTR */ } size -= wrote; index += wrote; } while (size > 0); return true; } /** * Reads size bytes from a file, continuing on EINTR short reads. * @param f * The file to read from. * @param data * The data buffer to read into. * @param size * The size of the buffer, which is also the amount of bytes to read. * @return * True on success, False otherwise. */ static bool readx(FILE *f, UINT8 *data, size_t size) { size_t bread = 0; size_t index = 0; do { bread = fread(&data[index], 1, size, f); if (bread != size) { if (feof(f) || (errno != EINTR)) { return false; } /* continue on EINTR */ } size -= bread; index += bread; } while (size > 0); return true; } #define BAIL_ON_NULL(param, x) \ do { \ if (!x) { \ LOG_ERR(param" must be specified"); \ return false; \ } \ } while(0) #define BE_CONVERT(value, size) \ do { \ if (!string_bytes_is_host_big_endian()) { \ value = string_bytes_endian_convert_##size(value); \ } \ } while (0) #define FILE_WRITE(size) \ bool files_write_##size(FILE *out, UINT##size data) { \ BAIL_ON_NULL("FILE", out); \ BE_CONVERT(data, size); \ return writex(out, (UINT8 *)&data, sizeof(data)); \ } #define FILE_READ(size) \ bool files_read_##size(FILE *out, UINT##size *data) { \ BAIL_ON_NULL("FILE", out); \ BAIL_ON_NULL("data", data); \ bool res = readx(out, (UINT8 *)data, sizeof(*data)); \ if (res) { \ BE_CONVERT(*data, size); \ } \ return res; \ } /* * all the files_read|write_bytes_16|32|64 functions */ FILE_READ(16); FILE_WRITE(16) FILE_READ(32); FILE_WRITE(32) FILE_READ(64) FILE_WRITE(64) bool files_read_bytes(FILE *out, UINT8 bytes[], size_t len) { BAIL_ON_NULL("FILE", out); BAIL_ON_NULL("bytes", bytes); return readx(out, bytes, len); } bool files_write_bytes(FILE *out, uint8_t bytes[], size_t len) { BAIL_ON_NULL("FILE", out); BAIL_ON_NULL("bytes", bytes); return writex(out, bytes, len); } bool files_write_header(FILE *out, UINT32 version) { BAIL_ON_NULL("FILE", out); bool res = files_write_32(out, MAGIC); if (!res) { return false; } return files_write_32(out, version); } bool files_read_header(FILE *out, uint32_t *version) { BAIL_ON_NULL("FILE", out); BAIL_ON_NULL("version", version); UINT32 magic; bool res = files_read_32(out, &magic); if (!res) { return false; } if (magic != MAGIC) { LOG_ERR("Found magic 0x%x did not match expected magic of 0x%x!", magic, MAGIC); return false; } return files_read_32(out, version); } tpm2-tools-2.1.0/lib/files.h000066400000000000000000000112051313543155100155530ustar00rootroot00000000000000#ifndef FILES_H #define FILES_H #include #include #include /** * Reads a series of bytes froma file as a byte array. This is similar to files_read_bytes(), * but opens and closes the FILE for the caller. Size is both an input and output value where * the size value is the max buffer size on call and the returned size is how much was read. * * This interface could be cleaned up in a later revision. * @param path * The path to the file to open. * @param buf * The buffer to read the data into * @param size * The max size of the buffer on call, and the size of the data read on return. * @return * True on success, false otherwise. */ bool files_load_bytes_from_file(const char *path, UINT8 *buf, UINT16 *size); /** * Similar to files_write_bytes(), in that it writes an array of bytes to disk, * but this routine opens and closes the file on the callers behalf. * @param path * The path to the file to write the data to. * @param buf * The buffer of data to write * @param size * The size of the data to write in bytes. * @return * True on success, false otherwise. */ bool files_save_bytes_to_file(const char *path, UINT8 *buf, UINT16 size); /** * Saves the TPM context for an object handle to disk by calling Tss2_Sys_ContextSave() and serializing the * resulting TPMS_CONTEXT structure to disk. * @param sapi_context * The system api context * @param handle * The object handle for the object to save. * @param path * The output path of the file. * * @return * True on success, False on error. */ bool files_save_tpm_context_to_file(TSS2_SYS_CONTEXT *sapi_context, TPM_HANDLE handle, const char *path); /** * Loads a TPM object context from disk. * @param sapi_context * The system API context * @param handle * The object handle that was saved. * @param path * The path to the input file. * @return * True on Success, false on error. */ bool file_load_tpm_context_from_file(TSS2_SYS_CONTEXT *sapi_context, TPM_HANDLE *handle, const char *path); /** * Checks a file for existence. * @param path * The file to check for existence. * @return * true if a file exists with read permissions, false if it doesn't exist or an error occurs. * */ bool files_does_file_exist(const char *path); /** * Retrieves a files size given a file path. * @param path * The path of the file to retreive the size of. * @param file_size * A pointer to a long to return the file size. The * pointed to value is valid only on a true return. * * @return * True for success or False for error. */ bool files_get_file_size(const char *path, long *file_size); /** * Writes a TPM2.0 header to a file. * @param f * The file to write to. * @param version * The version number of the format of the file. * @return * True on success, false on error. */ bool files_write_header(FILE *f, UINT32 version); /** * Reads a TPM2.0 header from a file. * @param f * The file to read. * @param version * The version that was found. * @return * True on Success, False on error. */ bool files_read_header(FILE *f, UINT32 *version); /** * Writes a 16 bit value to the file in big endian, converting * if needed. * @param out * The file to write. * @param data * The 16 bit value to write. * @return * True on success, False on error. */ bool files_write_16(FILE *out, UINT16 data); /** * Same as files_write_16 but for 32 bit values. */ bool files_write_32(FILE *out, UINT32 data); /** * Same as files_write_16 but for 64 bit values. */ bool files_write_64(FILE *out, UINT64 data); /** * Writes a byte array out to a file. * @param out * The file to write to. * @param data * The data to write. * @param size * The size of the data to write in bytes. * @return * True on success, False otherwise. */ bool files_write_bytes(FILE *out, UINT8 data[], size_t size); /** * Reads a 16 bit value from a file converting from big endian to host * endianess. * @param out * The file to read from. * @param data * The data that is read, valid on a true return. * @return * True on success, False on error. */ bool files_read_16(FILE *out, UINT16 *data); /** * Same as files_read_16 but for 32 bit values. */ bool files_read_32(FILE *out, UINT32 *data); /** * Same as files_read_16 but for 64 bit values. */ bool files_read_64(FILE *out, UINT64 *data); /** * Reads len bytes from a file. * @param out * The file to read from. * @param data * The buffer to read into, only valid on a True return. * @param size * The number of bytes to read. * @return * True on success, False otherwise. */ bool files_read_bytes(FILE *out, UINT8 data[], size_t size); #endif /* FILES_H */ tpm2-tools-2.1.0/lib/log.c000066400000000000000000000030441313543155100152270ustar00rootroot00000000000000#include #include #include #include "log.h" /* * Note that the logging library is not thread safe, thus calls on separate * threads will yield an interleaved output on stderr. */ static log_level current_log_level = log_level_warning; bool log_set_level (log_level value) { bool result = false; if (value >= log_level_error || value <= log_level_verbose) { current_log_level = value; result = true; } return result; } static const char * get_level_msg (log_level level) { const char *value = "UNK"; switch (level) { case log_level_error: value = "ERROR"; break; case log_level_warning: value = "WARN"; break; case log_level_verbose: value = "INFO"; } return value; } void _log (log_level level, const char *file, unsigned lineno, const char *fmt, ...) { /* Skip printing messages outside of the log level */ if (level > current_log_level) return; va_list argptr; va_start(argptr, fmt); /* Verbose output prints file and line on error */ if (current_log_level >= log_level_verbose) fprintf (stderr, "%s on line: \"%u\" in file: \"%s\": ", get_level_msg (level), lineno, file); else fprintf (stderr, "%s: ", get_level_msg (level)); /* Print the user supplied message */ vfprintf (stderr, fmt, argptr); /* always add a new line so the user doesn't have to */ fprintf (stderr, "\n"); va_end(argptr); } tpm2-tools-2.1.0/lib/log.h000066400000000000000000000026051313543155100152360ustar00rootroot00000000000000#ifndef SRC_LOG_H_ #define SRC_LOG_H_ #include #include typedef enum log_level log_level; /* * Prints an error message. The fmt and variadic arguments mirror printf. * * Use this to log all error conditions. */ #define LOG_ERR(fmt, ...) _log(log_level_error, __FILE__, __LINE__, fmt, ##__VA_ARGS__) /* * Prints an warning message. The fmt and variadic arguments mirror printf. * * Use this to log a warning. A warning is when something is wrong, but it is not a fatal * issue. */ #define LOG_WARN(fmt, ...) _log(log_level_warning, __FILE__, __LINE__, fmt, ##__VA_ARGS__) /* * Prints an informational message. The fmt and variadic arguments mirror printf. * * Informational messages are only shown when verboseness is increased. Valid messages * would be debugging type messages where additional, extraneous information is printed. */ #define LOG_INFO(fmt, ...) _log(log_level_verbose, __FILE__, __LINE__, fmt, ##__VA_ARGS__) enum log_level { log_level_error, log_level_warning, log_level_verbose }; /** * Sets the log level so only messages <= to it print. * @param level * The logging level to set. * @return * True if i succeeds, false if level is out of bounds. */ bool log_set_level (log_level level); void _log (log_level level, const char *file, unsigned lineno, const char *fmt, ...) __attribute__ ((format (printf, 4, 5))); #endif /* SRC_LOG_H_ */ tpm2-tools-2.1.0/lib/options.c000066400000000000000000000272431313543155100161500ustar00rootroot00000000000000/* * Copyright (c) 2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include "log.h" #include "options.h" #include "string-bytes.h" /* * A structure to map a string name to an element in the TCTI_TYPE * enumeration. */ typedef struct { char *name; TCTI_TYPE type; } tcti_map_entry_t; /* * A table of tcti_map_entry_t structures. This is how we map a string * provided on the command line to the enumeration. */ tcti_map_entry_t tcti_map_table[] = { #ifdef HAVE_TCTI_DEV { .name = "device", .type = DEVICE_TCTI, }, #endif #ifdef HAVE_TCTI_SOCK { .name = "socket", .type = SOCKET_TCTI, }, #endif #ifdef HAVE_TCTI_TABRMD { .name = "tabrmd", .type = TABRMD_TCTI, }, #endif { .name = "unknown", .type = UNKNOWN_TCTI, }, }; /* * Convert from a string to an element in the TCTI_TYPE enumeration. * An unkonwn name / string will map to UNKNOWN_TCTI. */ TCTI_TYPE tcti_type_from_name (char const *tcti_str) { int i; if (tcti_str == NULL) goto out; for (i = 0; i < N_TCTI; ++i) if (strcmp (tcti_str, tcti_map_table[i].name) == 0) return tcti_map_table[i].type; out: return UNKNOWN_TCTI; } /* * Convert from an element in the TCTI_TYPE enumeration to a string * representation. */ char * tcti_name_from_type (TCTI_TYPE tcti_type) { int i; for (i = 0; i < N_TCTI; ++i) if (tcti_type == tcti_map_table[i].type) return tcti_map_table[i].name; return NULL; } /* * Test a common_opts_t structure to be sure the member data has been * populated. We don't do any tests on the data for appropriate formats * (like testing socket_address for a valid IP address). * return 0 if sanity test passes * return 1 if help message was explicitly requested * return 2 if sanity test fails */ int sanity_check_common (common_opts_t *opts) { if (opts->help) return 1; switch (opts->tcti_type) { #ifdef HAVE_TCTI_DEV case DEVICE_TCTI: if (opts->device_file == NULL) { fprintf (stderr, "missing --device-file, see --help\n"); return 2; } break; #endif #ifdef HAVE_TCTI_SOCK case SOCKET_TCTI: if (opts->socket_address == NULL) { fprintf (stderr, "missing --socket-address, see --help\n"); return 2; } if (opts->socket_port == 0) { fprintf (stderr, "missing --socket-port, see --help\n"); return 2; } break; #endif #ifdef HAVE_TCTI_TABRMD case TABRMD_TCTI: /* no options for this one yet */ break; #endif default: fprintf (stderr, "invalid TCTI, see --help\n"); return 2; } return 0; } /* * Populate the provided common_opts_t structure with data provided through * the environment. */ void get_common_opts_from_env (common_opts_t *common_opts) { char *env_str, *end_ptr; if (common_opts == NULL) return; env_str = getenv (TPM2TOOLS_ENV_TCTI_NAME); if (env_str != NULL) common_opts->tcti_type = tcti_type_from_name (env_str); env_str = getenv (TPM2TOOLS_ENV_DEVICE_FILE); if (env_str != NULL) common_opts->device_file = env_str; env_str = getenv (TPM2TOOLS_ENV_SOCKET_ADDRESS); if (env_str != NULL) common_opts->socket_address = env_str; env_str = getenv (TPM2TOOLS_ENV_SOCKET_PORT); if (env_str != NULL) common_opts->socket_port = strtol (env_str, &end_ptr, 10); } /* * Append a string to the parameter argv array. We realloc this array adding * a new char* to point to the appended entry. The argc parameter is updated * to account for the new element in the array. We return the address of the * newly reallocated array. If the realloc fails we return NULL. */ char** append_arg_to_vector (int* argc, char* argv[], char* arg_string) { char **new_argv; ++(*argc); new_argv = realloc (argv, sizeof (char*) * (*argc)); if (new_argv != NULL) { new_argv[*argc - 1] = arg_string; } else { LOG_ERR("Failed to realloc new_argv to append string %s: %s\n", arg_string, strerror (errno)); } return new_argv; } /* * Get data from the environment and the caller (by way of the argument * vector) to populate the provided common_opts_t structure. The data we get * from the command line / argument vector takes presedence so we fill in the * structure with data from the environment first, then from argv. Anything * retrieved from the environment will just be over written with whatever we * get from argv. * All options from argv that aren't from the common option set are ignored * and copied to a newly allocated vector. These are assumed to be options * specific to the tool. This new augmented argument vector and count are * returned to the caller through the argc_param and argv_param. The vector * must be freed by the caller. */ int get_common_opts (int *argc_param, char **argv_param[], common_opts_t *common_opts) { int argc = *argc_param; char **argv = *argv_param; int c = 0, option_index = 0; char *arg_str = "-T:d:R:p:hvV"; struct option long_options [] = { { .name = "tcti", .has_arg = required_argument, .flag = NULL, .val = 'T', }, #ifdef HAVET_TCTI_DEV { .name = "device-file", .has_arg = required_argument, .flag = NULL, .val = 'd', }, #endif #ifdef HAVE_TCTI_SOCK { .name = "socket-address", .has_arg = required_argument, .flag = NULL, .val = 'R', }, { .name = "socket-port", .has_arg = required_argument, .flag = NULL, .val = 'p', }, #endif #ifdef HAVE_TCTI_TABRMD /* no options for this TCTI yet */ #endif { .name = "help", .has_arg = no_argument, .flag = &common_opts->help, .val = true, }, { .name = "verbose", .has_arg = no_argument, .flag = NULL, .val = 'V', }, { .name = "version", .has_arg = no_argument, .flag = NULL, .val = 'v', }, { NULL }, }; /* * Start by populating the provided common_opts_t structure with data * provided in the environment. Whatever we get here will be overriden * by stuff from argv. */ get_common_opts_from_env (common_opts); /* * Keep getopt_long quiet when we see options that aren't in the 'common' * category. Reset option processing. */ char **new_argv = { NULL, }; int new_argc = 1; extern int opterr, optind; opterr = 0; optind = 1; new_argv = calloc (1, sizeof (char*)); if (new_argv == NULL) { fprintf (stderr, "Failed to allocate memory for tool argument " "vector: %s\n", strerror (errno)); return 2; } new_argv[0] = argv[0]; while ((c = getopt_long (argc, argv, arg_str, long_options, &option_index)) != -1) { switch (c) { case 1: { /* positional arguments */ char **tmp = append_arg_to_vector (&new_argc, new_argv, optarg); if (tmp == NULL) { free(new_argv); return 2; } new_argv = tmp; } break; case 'T': common_opts->tcti_type = tcti_type_from_name (optarg); break; #ifdef HAVE_TCTI_DEV case 'd': common_opts->device_file = optarg; break; #endif #ifdef HAVE_TCTI_SOCK case 'R': common_opts->socket_address = optarg; break; case 'p': { bool res = string_bytes_get_uint16(optarg, &common_opts->socket_port); if (!res) { LOG_ERR("Could not convert port to a 16 bit unsigned number, " "got: %s", optarg); free(new_argv); return 2; } } break; #endif #ifdef HAVE_TCTI_TABRMD /* No options for this TCTI yet. */ #endif case 'h': common_opts->help = true; break; case 'V': common_opts->verbose = true; break; case 'v': common_opts->version = true; break; case '?': { char **tmp = append_arg_to_vector (&new_argc, new_argv, argv[optind - 1]); if (tmp == NULL) { free(new_argv); return 2; } new_argv = tmp; } break; } } /* return the new argument vector info to the caller */ *argc_param = new_argc; *argv_param = new_argv; return 0; } /* * Dump the contents of the common_opts_t structure to stdout. */ void dump_common_opts (common_opts_t *opts) { printf ("common_opts_t:\n"); printf (" tcti_type: %s\n", tcti_name_from_type (opts->tcti_type)); #ifdef HAVE_TCTI_DEV printf (" device_file_name: %s\n", opts->device_file); #endif #ifdef HAVE_TCTI_SOCK printf (" address: %s\n", opts->socket_address); printf (" port: %d\n", opts->socket_port); #endif #ifdef HAVE_TCTI_TABRMD /* No options for this TCTI yet. */ #endif printf (" help: %s\n", opts->help ? "true" : "false"); printf (" verbose: %s\n", opts->verbose ? "true" : "false"); printf (" version: %s\n", opts->version ? "true" : "false"); } /* * Execute man page for the appropriate command. */ void execute_man (char *prog_name, char *envp[]) { char *argv[] = { "/man", // ARGv[0] needs to be something. basename(prog_name), NULL }; printf("%s\n", basename(prog_name)); execvpe ("man", argv, envp); } tpm2-tools-2.1.0/lib/options.h000066400000000000000000000112261313543155100161470ustar00rootroot00000000000000/* * Copyright (c) 2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef OPTIONS_H #define OPTIONS_H #include #include #include /* * Default TCTI: this is a bit awkward since we allow users to enable / * disable TCTIs using ./configure --with/--without magic. * As simply put as possible: * if the socket TCTI is enabled, it's the default. * else if the device TCTI is enabled it's the default. * We do this to preserve the current default / expected behavior (use of * the socket TCTI). */ #ifdef HAVE_TCTI_TABRMD #define TCTI_DEFAULT TABRMD_TCTI #define TCTI_DEFAULT_STR "tabrmd" #elif HAVE_TCTI_SOCK #define TCTI_DEFAULT SOCKET_TCTI #define TCTI_DEFAULT_STR "socket" #elif HAVE_TCTI_DEV #define TCTI_DEFAULT DEVICE_TCTI #define TCTI_DEFAULT_STR "device" #endif /* Defaults for Device TCTI */ #define TCTI_DEVICE_DEFAULT_PATH "/dev/tpm0" /* Deafults for Socket TCTI connections, port default is for resourcemgr */ #define TCTI_SOCKET_DEFAULT_ADDRESS "127.0.0.1" #define TCTI_SOCKET_DEFAULT_PORT 2321 /* Environment variables usable as alternatives to command line options */ #define TPM2TOOLS_ENV_TCTI_NAME "TPM2TOOLS_TCTI_NAME" #define TPM2TOOLS_ENV_DEVICE_FILE "TPM2TOOLS_DEVICE_FILE" #define TPM2TOOLS_ENV_SOCKET_ADDRESS "TPM2TOOLS_SOCKET_ADDRESS" #define TPM2TOOLS_ENV_SOCKET_PORT "TPM2TOOLS_SOCKET_PORT" #define COMMON_OPTS_INITIALIZER { \ .tcti_type = TCTI_DEFAULT, \ .device_file = TCTI_DEVICE_DEFAULT_PATH, \ .socket_address = TCTI_SOCKET_DEFAULT_ADDRESS, \ .socket_port = TCTI_SOCKET_DEFAULT_PORT, \ .help = false, \ .verbose = false, \ .version = false, \ } typedef enum { #ifdef HAVE_TCTI_DEV DEVICE_TCTI, #endif #ifdef HAVE_TCTI_SOCK SOCKET_TCTI, #endif #ifdef HAVE_TCTI_TABRMD TABRMD_TCTI, #endif UNKNOWN_TCTI, N_TCTI, } TCTI_TYPE; typedef struct { TCTI_TYPE tcti_type; char *device_file; char *socket_address; uint16_t socket_port; int help; int verbose; int version; } common_opts_t; /* functions to get common options from the user and to print helpful stuff */ void dump_common_opts (common_opts_t *opts); int get_common_opts (int *argc, char **argv[], common_opts_t *common_opts); int sanity_check_common (common_opts_t *opts); void execute_man (char *cmd_name, char *envp[]); /* inline functions to print messages related to option processing*/ static inline void showArgError (const char *arg, const char *name) { printf("Argument error: %s\n",arg); printf("Please type \"%s -h\" get the usage!\n", name); } static inline void showArgMismatch (const char *name) { printf("Argument mismatched!\n"); printf("Please type \"%s -h\" get the usage!\n", name); } static inline void showVersion (const char *name) { printf("%s, version %s\n", name, VERSION); } #endif /* OPTIONS_H */ tpm2-tools-2.1.0/lib/password_util.c000066400000000000000000000027711313543155100173530ustar00rootroot00000000000000#include #include #include "log.h" #include "password_util.h" #include "string-bytes.h" #define PASSWORD_MAX (sizeof(((TPM2B_DIGEST *)NULL)->t.buffer)) bool password_util_to_auth(TPM2B_AUTH *password, bool is_hex, const char *description, TPM2B_AUTH *auth) { if (is_hex) { auth->t.size = sizeof(auth) - 2; /* this routine is safe on overlapping memory areas */ if (hex2ByteStructure((char *)password->t.buffer, &auth->t.size, auth->t.buffer) != 0) { LOG_ERR("Failed to convert hex format password for %s.", description); return false; } /* * we only claim sanity on same memory, not overlapping, but well use * memove anyways at the expense of speed. */ } else if (password != auth) { memmove(auth, password, sizeof(*auth)); } return true; } bool password_util_copy_password(const char *password, const char *description, TPM2B_AUTH *dest) { if (!password) { LOG_ERR("Please input the %s password!", description); return false; } if (!dest || !description) { return false; } size_t len = strlen(password); if (len >= PASSWORD_MAX) { LOG_ERR("Over-length password for %s. Got %zu expected less than %zu!", description, len, PASSWORD_MAX); return false; } dest->t.size = len; snprintf((char *)dest->t.buffer, PASSWORD_MAX, "%s", password); return true; } tpm2-tools-2.1.0/lib/password_util.h000066400000000000000000000025221313543155100173520ustar00rootroot00000000000000#ifndef SRC_PASSWORD_UTIL_H_ #define SRC_PASSWORD_UTIL_H_ #include /** * Copies a password stored in a TPM2B_AUTH structure, converting from hex if necessary, into * another TPM2B_AUTh structure. Source password and auth structures can be the same pointer. * @param password * The source password. * @param is_hex * True if the password contained in password is hex encoded. * @param description * The description of the key used for error reporting. * @param auth * The destination auth structure to copy the key into. * @return * True on success and False on failure. */ bool password_util_to_auth(TPM2B_AUTH *password, bool is_hex, const char *description, TPM2B_AUTH *auth); /** * Copies a C string password into a TPM2B_AUTH structure. It logs an error on failure. * * Note: Use of a TPM2B_AUTH structure is for proper size allocation reporting and having * a size parameter to avoid duplicate strlen() calls. * * @param password * The C string password to copy. * @param description * A description of the password being copied for error reporting purposes. * @param dest * The destination TPM2B_AUTH structure. * @return * True on success, False on error. */ bool password_util_copy_password(const char *password, const char *description, TPM2B_AUTH *dest); #endif /* SRC_PASSWORD_UTIL_H_ */ tpm2-tools-2.1.0/lib/pcr.c000066400000000000000000000052621313543155100152360ustar00rootroot00000000000000#include #include #include #include #include "pcr.h" #include "string-bytes.h" static int pcr_get_id(const char *arg, UINT32 *pcrId) { UINT32 n = 0; if(arg == NULL || pcrId == NULL) return -1; if(!string_bytes_get_uint32(arg, &n)) return -2; if(n > 23) return -3; *pcrId = n; return 0; } static int pcr_parse_selection(const char *str, int len, TPMS_PCR_SELECTION *pcrSel) { const char *strLeft; char buf[7]; if (str == NULL || len == 0) return -1; strLeft = memchr(str, ':', len); if (strLeft == NULL) { return -1; } if ((size_t)(strLeft - str) > sizeof(buf) - 1) { return -1; } snprintf(buf, strLeft - str + 1, "%s", str); if (!string_bytes_get_uint16(buf, &pcrSel->hash)) { return -1; } strLeft++; if (strLeft - str >= len) { return -1; } if (pcr_parse_list(strLeft, str + len - strLeft, pcrSel)) { return -1; } return 0; } int pcr_parse_selections(const char *arg, TPML_PCR_SELECTION *pcrSels) { const char *strLeft = arg; const char *strCurrent = arg; int lenCurrent = 0; if (arg == NULL || pcrSels == NULL) { return -1; } pcrSels->count = 0; do { strCurrent = strLeft; strLeft = strchr(strCurrent, '+'); if (strLeft) { lenCurrent = strLeft - strCurrent; strLeft++; } else lenCurrent = strlen(strCurrent); if (pcr_parse_selection(strCurrent, lenCurrent, &pcrSels->pcrSelections[pcrSels->count])) return -1; pcrSels->count++; } while (strLeft); if (pcrSels->count == 0) { return -1; } return 0; } int pcr_parse_list(const char *str, int len, TPMS_PCR_SELECTION *pcrSel) { char buf[4]; const char *strCurrent; int lenCurrent; UINT32 pcr; if (str == NULL || len == 0) { return -1; } pcrSel->sizeofSelect = 3; pcrSel->pcrSelect[0] = 0; pcrSel->pcrSelect[1] = 0; pcrSel->pcrSelect[2] = 0; do { strCurrent = str; str = memchr(strCurrent, ',', len); if (str) { lenCurrent = str - strCurrent; str++; len -= lenCurrent + 1; } else { lenCurrent = len; len = 0; } if ((size_t)lenCurrent > sizeof(buf) - 1) { return -1; } snprintf(buf, lenCurrent + 1, "%s", strCurrent); if (pcr_get_id(buf, &pcr) != 0) { return -1; } pcrSel->pcrSelect[pcr / 8] |= (1 << (pcr % 8)); } while (str); return 0; } tpm2-tools-2.1.0/lib/pcr.h000066400000000000000000000003531313543155100152370ustar00rootroot00000000000000#ifndef SRC_PCR_H_ #define SRC_PCR_H_ #include int pcr_parse_selections(const char *arg, TPML_PCR_SELECTION *pcrSels); int pcr_parse_list(const char *str, int len, TPMS_PCR_SELECTION *pcrSel); #endif /* SRC_PCR_H_ */ tpm2-tools-2.1.0/lib/rc-decode.c000066400000000000000000000756621313543155100163120ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2016, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include "rc-decode.h" /* Array of RC_VER1 error codes from TPM 2.0, Part 2, Table 17 * The error code is in the lower 7 bits [06:00] but the identifiers are * defined as RC_VER1 + 0xXXX. When looking up values you must include bit * 8 in the comparison or mask out bit 8. */ struct tpm2_rc_entry tpm2_ver1_entry [] = { { /* 0x000 */ .id = TPM_RC_INITIALIZE, .name = "TPM_RC_INITIALIZE", .description = "TPM not initialized", }, { /* 0x001 */ .id = TPM_RC_FAILURE, .name = "TPM_RC_FAILURE", .description = "commands not being accepted because of a TPM failure", }, { /* 0x003 */ .id = TPM_RC_SEQUENCE, .name = "TPM_RC_SEQUENCE", .description = "improper use of a sequence handle", }, { /* 0x00B */ .id = TPM_RC_PRIVATE, .name = "TPM_RC_PRIVATE", .description = NULL, }, { /* 0x019 */ .id = TPM_RC_HMAC, .name = "TPM_RC_HMAC", .description = NULL, }, { /* 0x020 */ .id = TPM_RC_DISABLED, .name = "TPM_RC_DISABLED", .description = NULL, }, { /* 0x021 */ .id = TPM_RC_EXCLUSIVE, .name = "TPM_RC_EXCLUSIVE", .description = "command failed because audit sequence required exclusivity", }, { /* 0x024 */ .id = TPM_RC_AUTH_TYPE, .name = "TPM_RC_AUTH_TYPE", .description = "authorization handle is not correct for command", }, { /* 0x025 */ .id = TPM_RC_AUTH_MISSING, .name = "TPM_RC_AUTH_MISSING", .description = "command requires an authorization session for handle and it is not present.", }, { /* 0x026 */ .id = TPM_RC_POLICY, .name = "TPM_RC_POLICY", .description = "policy Failure In Math Operation or an invalid authPolicy value", }, { /* 0x027 */ .id = TPM_RC_PCR, .name = "TPM_RC_PCR", .description = "PCR check fail", }, { /* 0x028 */ .id = TPM_RC_PCR_CHANGED, .name = "TPM_RC_PCR_CHANGED", .description = "PCR have changed since checked.", }, { /* 0x02D */ .id = TPM_RC_UPGRADE, .name = "TPM_RC_UPGRADE", .description = "for all commands other than TPM2_FieldUpgradeData(), this code indicates that the TPM is in field upgrade mode; for TPM2_FieldUpgradeData(), this code indicates that the TPM is not in field upgrade mode", }, { /* 0x02E */ .id = TPM_RC_TOO_MANY_CONTEXTS, .name = "TPM_RC_TOO_MANY_CONTEXTS", .description = "context ID counter is at maximum.", }, { /* 0x02F */ .id = TPM_RC_AUTH_UNAVAILABLE, .name = "TPM_RC_AUTH_UNAVAILABLE", .description = "authValue or authPolicy is not available for selected entity.", }, { /* 0x030 */ .id = TPM_RC_REBOOT, .name = "TPM_RC_REBOOT", .description = "a _TPM_Init and Startup(CLEAR) is required before the TPM can resume operation.", }, { /* 0x0x031 */ .id = TPM_RC_UNBALANCED, .name = "TPM_RC_UNBALANCED", .description = "the protection algorithms (hash and symmetric) are not reasonably balanced. The digest size of the hash must be larger than the key size of the symmetric algorithm.", }, { /* 0x042 */ .id = TPM_RC_COMMAND_SIZE, .name = "TPM_RC_COMMAND_SIZE", .description = "command commandSize value is inconsistent with contents of the command buffer; either the size is not the same as the octets loaded by the hardware interface layer or the value is not large enough to hold a command header", }, { /* 0x043 */ .id = TPM_RC_COMMAND_CODE, .name = "TPM_RC_COMMAND_CODE", .description = "command code not supported", }, { /* 0x044 */ .id = TPM_RC_AUTHSIZE, .name = "TPM_RC_AUTHSIZE", .description = "the value of authorizationSize is out of range or the number of octets in the Authorization Area is greater than required", }, { /* 0x045 */ .id = TPM_RC_AUTH_CONTEXT, .name = "TPM_RC_AUTH_CONTEXT", .description = "use of an authorization session with a context command or another command that cannot have an authorization session.", }, { /* 0x046 */ .id = TPM_RC_NV_RANGE, .name = "TPM_RC_NV_RANGE", .description = "NV offset+size is out of range.", }, { /* 0x047 */ .id = TPM_RC_NV_SIZE, .name = "TPM_RC_NV_SIZE", .description = "Requested allocation size is larger than allowed.", }, { /* 0x048 */ .id = TPM_RC_NV_LOCKED, .name = "TPM_RC_NV_LOCKED", .description = "NV access locked.", }, { /* 0x049 */ .id = TPM_RC_NV_AUTHORIZATION, .name = "TPM_RC_NV_AUTHORIZATION", .description = "NV access authorization fails in command actions (this failure does not affect lockout.action)", }, { /* 0x04A */ .id = TPM_RC_NV_UNINITIALIZED, .name = "TPM_RC_NV_UNINITIALIZED", .description = "an NV Index is used before being initialized or the state saved by TPM2_Shutdown(STATE) could not be restored", }, { /* 0x04B */ .id = TPM_RC_NV_SPACE, .name = "TPM_RC_NV_SPACE", .description = "insufficient space for NV allocation", }, { /* 0x04C */ .id = TPM_RC_NV_DEFINED, .name = "TPM_RC_NV_DEFINED", .description = "NV Index or persistend object already defined", }, { /* 0x050 */ .id = TPM_RC_BAD_CONTEXT, .name = "TPM_RC_BAD_CONTEXT", .description = "context in TPM2_ContextLoad() is not valid", }, { /* 0x051 */ .id = TPM_RC_CPHASH, .name = "TPM_RC_CPHASH", .description = "cpHash value already set or not correct for use", }, { /* 0x052 */ .id = TPM_RC_PARENT, .name = "TPM_RC_PARENT", .description = "handle for parent is not a valid parent", }, { /* 0x053 */ .id = TPM_RC_NEEDS_TEST, .name = "TPM_RC_NEEDS_TEST", .description = "some function needs testing.", }, { /* 0x054 */ .id = TPM_RC_NO_RESULT, .name = "TPM_RC_NO_RESULT", .description = "returned when an internal function cannot process a request due to an unspecified problem. This code is usually related to invalid parameters that are not properly filtered by the input unmarshaling code.", }, { /* 0x055 */ .id = TPM_RC_SENSITIVE, .name = "TPM_RC_SENSITIVE", .description = "the sensitive area did not unmarshal correctly after decryption – this code is used in lieu of the other unmarshaling errors so that an attacker cannot determine where the unmarshaling error occurred", }, { /* 0x07F */ .id = RC_MAX_FM0, .name = "RC_MAX_FM0", .description = "largest version 1 code that is not a warning", } }; /* Array of RC_FMT1 error codes from TPM 2.0, Part 2, Table 17 * The error code is in the lower 6 bits [05:00] but the identifiers are * defined as RC_FMT1 + 0xXXX. When looking up values you must include bit * 7 in the comparison or mask it out. */ struct tpm2_rc_entry tpm2_fmt1_entry [] = { { /* 0x001 */ .id = TPM_RC_ASYMMETRIC, .name = "TPM_RC_ASYMMETRIC", .description = "asymmetric algorithm not supported or not correct", }, { /* 0x002 */ .id = TPM_RC_ATTRIBUTES, .name = "TPM_RC_ATTRIBUTES", .description = "inconsistent attributes", }, { /* 0x003 */ .id = TPM_RC_HASH, .name = "TPM_RC_HASH", .description = "hash algorithm not supported or not appropriate", }, { /* 0x004 */ .id = TPM_RC_VALUE, .name = "TPM_RC_VALUE", .description = "value is out of range or is not correct for the context", }, { /* 0x005 */ .id = TPM_RC_HIERARCHY, .name = "TPM_RC_HIERARCHY", .description = "hierarchy is not enabled or is not correct for the use", }, { /* 0x007 */ .id = TPM_RC_KEY_SIZE, .name = "TPM_RC_KEY_SIZE", .description = "key size is not supported", }, { /* 0x008 */ .id = TPM_RC_MGF, .name = "TPM_RC_MGF", .description = "mask generation function not supported", }, { /* 0x009 */ .id = TPM_RC_MODE, .name = "TPM_RC_MODE", .description = "mode of operation not supported", }, { /* 0x00A */ .id = TPM_RC_TYPE, .name = "TPM_RC_TYPE", .description = "the type of the value is not appropriate for the use", }, { /* 0x00B */ .id = TPM_RC_HANDLE, .name = "TPM_RC_HANDLE", .description = "the handle is not correct for the use", }, { /* 0x00C */ .id = TPM_RC_KDF, .name = "TPM_RC_KDF", .description = "unsupported key derivation function or function not appropriate for use", }, { /* 0x00D */ .id = TPM_RC_RANGE, .name = "TPM_RC_RANGE", .description = "value was out of allowed range.", }, { /* 0x00E */ .id = TPM_RC_AUTH_FAIL, .name = "TPM_RC_AUTH_FAIL", .description = "the authorization HMAC check failed and DA counter incremented", }, { /* 0x00F */ .id = TPM_RC_NONCE, .name = "TPM_RC_NONCE", .description = "invalid nonce size", }, { /* 0x010 */ .id = TPM_RC_PP, .name = "TPM_RC_PP", .description = "authorization requires assertion of PP", }, { /* 0x012 */ .id = TPM_RC_SCHEME, .name = "TPM_RC_SCHEME", .description = "unsupported or incompatible scheme", }, { /* 0x015 */ .id = TPM_RC_SIZE, .name = "TPM_RC_SIZE", .description = "structure is the wrong size", }, { /* 0x016 */ .id = TPM_RC_SYMMETRIC, .name = "TPM_RC_SYMMETRIC", .description = "unsupported symmetric algorithm or key size, or not appropriate for instance", }, { /* 0x017 */ .id = TPM_RC_TAG, .name = "TPM_RC_TAG", .description = "incorrect structure tag", }, { /* 0x018 */ .id = TPM_RC_SELECTOR, .name = "TPM_RC_SELECTOR", .description = "union selector is incorrect", }, { /* 0x01A */ .id = TPM_RC_INSUFFICIENT, .name = "TPM_RC_INSUFFICIENT", .description = "the TPM was unable to unmarshal a value because there were not enough octets in the input buffer", }, { /* 0x01B */ .id = TPM_RC_SIGNATURE, .name = "TPM_RC_SIGNATURE", .description = "the signature is not valid", }, { /* 0x01C */ .id = TPM_RC_KEY, .name = "TPM_RC_KEY", .description = "key fields are not compatible with the selected use", }, { /* 0x0x01D */ .id = TPM_RC_POLICY_FAIL, .name = "TPM_RC_POLICY_FAIL", .description = "a policy check failed", }, { /* 0x01F */ .id = TPM_RC_INTEGRITY, .name = "TPM_RC_INTEGRITY", .description = "integrity check failed", }, { /* 0x020 */ .id = TPM_RC_TICKET, .name = "TPM_RC_TICKET", .description = "invalid ticket", }, { /* 0x021 */ .id = TPM_RC_RESERVED_BITS, .name = "TPM_RC_RESERVED_BITS", .description = "reserved bits not set to zero as required", }, { /* 0x022 */ .id = TPM_RC_BAD_AUTH, .name = "TPM_RC_BAD_AUTH", .description = "authorization failure without DA implications", }, { /* 0x023 */ .id = TPM_RC_EXPIRED, .name = "TPM_RC_EXPIRED", .description = "the policy has expired", }, { /* 0x024 */ .id = TPM_RC_POLICY_CC, .name = "TPM_RC_POLICY_CC", .description = "the commandCode in the policy is not the commandCode of the command or the command code in a policy command references a command that is not implemented", }, { /* 0x025 */ .id = TPM_RC_BINDING, .name = "TPM_RC_BINDING", .description = "public and sensitive portions of an object are not cryptographically bound", }, { /* 0x026 */ .id = TPM_RC_CURVE, .name = "TPM_RC_CURVE", .description = "curve not supported", }, { /* 0x027 */ .id = TPM_RC_ECC_POINT, .name = "TPM_RC_ECC_POINT", .description = "point is not on the required curve.", } }; /* Array of RC_WARN error codes from TPM 2.0, Part 2, Table 17. These are * implicitly RC_VER1 codes, but not errors, warnings. Index in this array * corresponds to the error code in the lower 6 bits [05:00]. Again, the * identifiers in the ID field have a constant added to the error code. This * time it's RC_WARN (0x900). */ struct tpm2_rc_entry tpm2_warn_entry [] = { { /* 0x001 */ .id = TPM_RC_CONTEXT_GAP, .name = "TPM_RC_CONTEXT_GAP", .description = "gap for context ID is too large", }, { /* 0x002 */ .id = TPM_RC_OBJECT_MEMORY, .name = "TPM_RC_OBJECT_MEMORY", .description = "out of memory for object contexts", }, { /* 0x003 */ .id = TPM_RC_SESSION_MEMORY, .name = "TPM_RC_SESSION_MEMORY", .description = "out of memory for session contexts", }, { /* 0x004 */ .id = TPM_RC_MEMORY, .name = "TPM_RC_MEMORY", .description = "out of shared object/session memory or need space for internal operations", }, { /* 0x005 */ .id = TPM_RC_SESSION_HANDLES, .name = "TPM_RC_SESSION_HANDLES", .description = "out of session handles – a session must be flushed before a new session may be created", }, { /* 0x006 */ .id = TPM_RC_OBJECT_HANDLES, .name = "TPM_RC_OBJECT_HANDLES", .description = "out of object handles – the handle space for objects is depleted and a reboot is required NOTE: This cannot occur on the reference implementation. NOTE: There is no reason why an implementation would implement a design that would deplete handle space. Platform specifications are encouraged to forbid it.", }, { /* 0x007 */ .id = TPM_RC_LOCALITY, .name = "TPM_RC_LOCALITY", .description = "bad locality", }, { /* 0x008 */ .id = TPM_RC_YIELDED, .name = "TPM_RC_YIELDED", .description = "the TPM has suspended operation on the command; forward progress was made and the command may be retried. See TPM 2.0 Part 1, “Multi-tasking.†NOTE: This cannot occur on the reference implementation.", }, { /* 0x009 */ .id = TPM_RC_CANCELED, .name = "TPM_RC_CANCELED", .description = "the command was canceled", }, { /* 0x00A */ .id = TPM_RC_TESTING, .name = "TPM_RC_TESTING", .description = "TPM is performing self-tests", }, { /* 0x010 */ .id = TPM_RC_REFERENCE_H0, .name = "TPM_RC_REFERENCE_H0", .description = "the 1st handle in the handle area references a transient object or session that is not loaded", }, { /* 0x011 */ .id = TPM_RC_REFERENCE_H1, .name = "TPM_RC_REFERENCE_H1", .description = "the 2nd handle in the handle area references a transient object or session that is not loaded", }, { /* 0x012 */ .id = TPM_RC_REFERENCE_H2, .name = "TPM_RC_REFERENCE_H2", .description = "the 3rd handle in the handle area references a transient object or session that is not loaded", }, { /* 0x013 */ .id = TPM_RC_REFERENCE_H3, .name = "TPM_RC_REFERENCE_H3", .description = "the 4th handle in the handle area references a transient object or session that is not loaded", }, { /* 0x014 */ .id = TPM_RC_REFERENCE_H4, .name = "TPM_RC_REFERENCE_H4", .description = "the 5th handle in the handle area references a transient object or session that is not loaded", }, { /* 0x015 */ .id = TPM_RC_REFERENCE_H5, .name = "TPM_RC_REFERENCE_H5", .description = "the 6th handle in the handle area references a transient object or session that is not loaded", }, { /* 0x016 */ .id = TPM_RC_REFERENCE_H6, .name = "TPM_RC_REFERENCE_H6", .description = "the 7th handle in the handle area references a transient object or session that is not loaded", }, { /* 0x018 */ .id = TPM_RC_REFERENCE_S0, .name = "TPM_RC_REFERENCE_S0", .description = "the 1st authorization session handle references a session that is not loaded", }, { /* 0x019 */ .id = TPM_RC_REFERENCE_S1, .name = "TPM_RC_REFERENCE_S1", .description = "the 2nd authorization session handle references a session that is not loaded", }, { /* 0x01A */ .id = TPM_RC_REFERENCE_S2, .name = "TPM_RC_REFERENCE_S2", .description = "the 3rd authorization session handle references a session that is not loaded", }, { /* 0x01B */ .id = TPM_RC_REFERENCE_S3, .name = "TPM_RC_REFERENCE_S3", .description = "the 4th authorization session handle references a session that is not loaded", }, { /* 0x01C */ .id = TPM_RC_REFERENCE_S4, .name = "TPM_RC_REFERENCE_S4", .description = "the 5th session handle references a session that is not loaded", }, { /* 0x01D */ .id = TPM_RC_REFERENCE_S5, .name = "TPM_RC_REFERENCE_S5", .description = "the 6th session handle references a session that is not loaded", }, { /* 0x01E */ .id = TPM_RC_REFERENCE_S6, .name = "TPM_RC_REFERENCE_S6", .description = "the 7th authorization session handle references a session that is not loaded", }, { /* 0x020 */ .id = TPM_RC_NV_RATE, .name = "TPM_RC_NV_RATE", .description = "the TPM is rate-limiting accesses to prevent wearout of NV", }, { /* 0x021 */ .id = TPM_RC_LOCKOUT, .name = "TPM_RC_LOCKOUT", .description = "authorizations for objects subject to DA protection are not allowed at this time because the TPM is in DA lockout mode", }, { /* 0x022 */ .id = TPM_RC_RETRY, .name = "TPM_RC_RETRY", .description = "the TPM was not able to start the command", }, { /* 0x023 */ .id = TPM_RC_NV_UNAVAILABLE, .name = "TPM_RC_NV_UNAVAILABLE", .description = "the command may require writing of NV and NV is not current accessible", }, { /* 0x7F */ .id = TPM_RC_NOT_USED, .name = "TPM_RC_NOT_USED", .description = "this value is reserved and shall not be returned by the TPM", } }; /* Array of position error codes from TPM 2.0 Part 2, Table 17. These are * implicitly associated with RC_FMT1 codes. */ tpm2_rc_entry_t tpm2_position_entry [] = { { /* 0x100 */ .id = TPM_RC_1, .name = "TPM_RC_1", .description = NULL, }, { /* 0x200 */ .id = TPM_RC_2, .name = "TPM_RC_2", .description = NULL, }, { /* 0x300 */ .id = TPM_RC_3, .name = "TPM_RC_3", .description = NULL, }, { /* 0x400 */ .id = TPM_RC_4, .name = "TPM_RC_4", .description = NULL, }, { /* 0x500 */ .id = TPM_RC_5, .name = "TPM_RC_5", .description = NULL, }, { /* 0x600 */ .id = TPM_RC_6, .name = "TPM_RC_6", .description = NULL, }, { /* 0x700 */ .id = TPM_RC_7, .name = "TPM_RC_7", .description = NULL, }, { /* 0x800 */ .id = TPM_RC_8, .name = "TPM_RC_8", .description = NULL, }, { /* 0x900 */ .id = TPM_RC_9, .name = "TPM_RC_9", .description = NULL, }, { /* 0xA00 */ .id = TPM_RC_A, .name = "TPM_RC_A", .description = NULL, }, { /* 0xB00 */ .id = TPM_RC_B, .name = "TPM_RC_B", .description = NULL, }, { /* 0xC00 */ .id = TPM_RC_C, .name = "TPM_RC_C", .description = NULL, }, { /* 0xD00 */ .id = TPM_RC_D, .name = "TPM_RC_D", .description = NULL, }, { /* 0xE00 */ .id = TPM_RC_E, .name = "TPM_RC_E", .description = NULL, }, { /* 0xF00 */ .id = TPM_RC_F, .name = "TPM_RC_F", .description = NULL, } }; /* Array of tpm2_rc_entrys for layers defined in the TSS spec. */ struct tpm2_rc_entry tpm2_tss_layer_entry [] = { { /* 0x0 * The spec calls this TSS2_TPM_RC_LEVEL and it's defined as bits * [15:12] not [23:16] like the error layer / levels. */ .id = TSS2_TPM_ERROR_LEVEL, .name = "TSS2_TPM_ERROR_LEVEL", .description = "Error produced by the TPM", }, { /* 10 << 16 = 0xA0000 */ .id = TSS2_TCTI_ERROR_LEVEL, .name = "TSS2_TCTI_ERROR_LEVEL", .description = "Error from the TCTI" }, { /* 8 << 16 = 0x80000 */ .id = TSS2_SYS_ERROR_LEVEL, .name = "TSS2_SYS_ERROR_LEVEL", .description = "Error from the SAPI", }, { /* 9 << 16 = 0x90000 */ .id = TSS2_SYS_PART2_ERROR_LEVEL, .name = "TSS2_SYS_PART2_RC_LEVEL", .description = "Error from the SAPI duplicating TPM error check" } }; /* Array of TSS2 error codes from TSS System API section 6.1.2. * Index in this array corresponds to the error code in the lower 12 bits * 11:00]. Undefined error codes will have NULL data in the array. */ struct tpm2_rc_entry tpm2_tss_base_rc_entry [] = { { /* 0x01 */ .id = TSS2_BASE_RC_GENERAL_FAILURE, .name = "TSS2_BASE_RC_GENERAL_FAILURE", .description = "Catch all for all errors not otherwise specifed", }, { /* 0x02 */ .id = TSS2_BASE_RC_NOT_IMPLEMENTED, .name = "TSS2_BASE_RC_NOT_IMPLEMENTED", .description = "If called functionality isn't implemented", }, { /* 0x03 */ .id = TSS2_BASE_RC_BAD_CONTEXT, .name = "TSS2_BASE_RC_BAD_CONTEXT", .description = "A context structure is bad", }, { /* 0x04 */ .id = TSS2_BASE_RC_ABI_MISMATCH, .name = "TSS2_BASE_RC_ABI_MISMATCH", .description = "Passed in ABI version doesn't match called module's ABI version", }, { /* 0x05 */ .id = TSS2_BASE_RC_BAD_REFERENCE, .name = "TSS2_BASE_RC_BAD_REFERENCE", .description = "A pointer is NULL that isn't allowed to be NULL.", }, { /* 0x06 */ .id = TSS2_BASE_RC_INSUFFICIENT_BUFFER, .name = "TSS2_BASE_RC_INSUFFICIENT_BUFFER", .description = "A buffer isn't large enough", }, { /* 0x07 */ .id = TSS2_BASE_RC_BAD_SEQUENCE, .name = "TSS2_BASE_RC_BAD_SEQUENCE", .description = "Function called in the wrong order", }, { /* 0x08 */ .id = TSS2_BASE_RC_NO_CONNECTION, .name = "TSS2_BASE_RC_NO_CONNECTION", .description = "Fails to connect to next lower layer", }, { /* 0x09 */ .id = TSS2_BASE_RC_TRY_AGAIN, .name = "TSS2_BASE_RC_TRY_AGAIN", .description = "Operation timed out; function must be called again to be completed", }, { /* 0x0A */ .id = TSS2_BASE_RC_IO_ERROR, .name = "TSS2_BASE_RC_IO_ERROR", .description = "IO failure", }, { /* 0x0B */ .id = TSS2_BASE_RC_BAD_VALUE, .name = "TSS2_BASE_RC_BAD_VALUE", .description = "A parameter has a bad value", }, { /* 0x0C */ .id = TSS2_BASE_RC_NOT_PERMITTED, .name = "TSS2_BASE_RC_NOT_PERMITTED", .description = "Operation not permitted.", }, { /* 0x0D */ .id = TSS2_BASE_RC_INVALID_SESSIONS, .name = "TSS2_BASE_RC_INVALID_SESSIONS", .description = "Session structures were sent, but command doesn't use them or doesn't use the specifed number of them", }, { /* 0x0E */ .id = TSS2_BASE_RC_NO_DECRYPT_PARAM, .name = "TSS2_BASE_RC_NO_DECRYPT_PARAM", .description = "If function called that uses decrypt parameter, but command doesn't support decrypt parameter.", }, { /* 0x0F */ .id = TSS2_BASE_RC_NO_ENCRYPT_PARAM, .name = "TSS2_BASE_RC_NO_ENCRYPT_PARAM", .description = "If function called that uses encrypt parameter, but command doesn't support decrypt parameter.", }, { /* 0x10 */ .id = TSS2_BASE_RC_BAD_SIZE, .name = "TSS2_BASE_RC_BAD_SIZE", .description = "If size of a paremeter is incorrect", }, { /* 0x11 */ .id = TSS2_BASE_RC_MALFORMED_RESPONSE, .name = "TSS2_BASE_RC_MALFORMED_RESPONSE", .description = "Response is malformed", }, { /* 0x12 */ .id = TSS2_BASE_RC_INSUFFICIENT_CONTEXT, .name = "TSS2_BASE_RC_INSUFFICIENT_CONTEXT", .description = "Context not large enough", }, { /* 0x13 */ .id = TSS2_BASE_RC_INSUFFICIENT_RESPONSE, .name = "TSS2_BASE_RC_INSUFFICIENT_RESPONSE", .description = "Response is not long enough", }, { /* 0x14 */ .id = TSS2_BASE_RC_INCOMPATIBLE_TCTI, .name = "TSS2_BASE_RC_INCOMPATIBLE_TCTI", .description = "Unknown or unusable TCTI version", }, { /* 0x15 */ .id = TSS2_BASE_RC_NOT_SUPPORTED, .name = "TSS2_BASE_RC_NOT_SUPPORTED", .description = "Functionality not supported.", }, { /* 0x16 */ .id = TSS2_BASE_RC_BAD_TCTI_STRUCTURE, .name = "TSS2_BASE_RC_BAD_TCTI_STRUCTURE", .description = "TCTI context is bad.", } }; /* char* tpm2_strrc (TPM_RC rc, char *out_str, size_t out_str_size) { if (is_tpm2_rc_format_zero (rc)) return tpm2_fmt0_entry [rc].description; else if (is_tpm2_rc_format_one (rc)) return tpm2_fmt1_entry [rc].description; else return NULL; } */ /* Functions to lookup / retrieve entries from the arrays of tpm2_rc_entry_t's * None of these functions check the format of the TPM_RC before doing the * lookup. They just mask out the irrelevant bits and do the lookup doing the * remainder. "irrelevant bits" is determined by the 'select_func' parameter. * This is a function to mask out "irrelevant bits". The same function is * applied to both the source RC and the RCs in the 'id' field of the array. */ #define STR_ENTRY_ARRAY_LENGTH(name) (sizeof (name) / sizeof (struct tpm2_rc_entry)) #define STR_ENTRY_ARRAY_LOOKUP(rc, array, select_func) \ unsigned i; \ for (i = 0; i < STR_ENTRY_ARRAY_LENGTH (array); ++i) \ if (select_func (rc) == select_func (array[i].id)) \ return &array[i]; \ return NULL; tpm2_rc_entry_t* tpm2_get_tss_base_rc_entry (TPM_RC rc) { STR_ENTRY_ARRAY_LOOKUP (rc, tpm2_tss_base_rc_entry, tpm2_rc_get_tss_err_code); } tpm2_rc_entry_t* tpm2_get_parameter_entry (TPM_RC rc) { STR_ENTRY_ARRAY_LOOKUP (rc, tpm2_position_entry, tpm2_rc_get_parameter_number); } tpm2_rc_entry_t* tpm2_get_handle_entry (TPM_RC rc) { STR_ENTRY_ARRAY_LOOKUP (rc, tpm2_position_entry, tpm2_rc_get_handle_number); } tpm2_rc_entry_t* tpm2_get_session_entry (TPM_RC rc) { STR_ENTRY_ARRAY_LOOKUP (rc, tpm2_position_entry, tpm2_rc_get_session_number); } tpm2_rc_entry_t* tpm2_get_layer_entry (TPM_RC rc) { STR_ENTRY_ARRAY_LOOKUP (rc, tpm2_tss_layer_entry, tpm2_rc_get_layer); } tpm2_rc_entry_t* tpm2_get_fmt0_entry (TPM_RC rc) { STR_ENTRY_ARRAY_LOOKUP (rc, tpm2_ver1_entry, tpm2_rc_get_code_7bit); } tpm2_rc_entry_t* tpm2_get_fmt1_entry (TPM_RC rc) { STR_ENTRY_ARRAY_LOOKUP (rc, tpm2_fmt1_entry, tpm2_rc_get_code_6bit); } tpm2_rc_entry_t* tpm2_get_warn_entry (TPM_RC rc) { STR_ENTRY_ARRAY_LOOKUP (rc, tpm2_warn_entry, tpm2_rc_get_code_6bit); } tpm2-tools-2.1.0/lib/rc-decode.h000066400000000000000000000217371313543155100163110ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2016, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #ifndef RC_DECODE_H #define RC_DECODE_H #include #include /* struct / type used to map TPM_RC error code parts to string representations of * their identifier and description. */ typedef struct tpm2_rc_entry { uint32_t id; char *name; char *description; } tpm2_rc_entry_t; /* To understand the TPM_RC you need to read a 2 different parts of the * spec: * Section 39.4 of TPM 2.0 Part 1: Architecture * Section 6.6 of TPM 2.0 Part 2: Structures * * The notion of RC levels only exists for the TSS. See the TSS system API * specification section 6.1.2 for details. */ /* Macros to determine whether or not a specific bit in position 'pos' from * variable 'var' is set. */ #define IS_BIT_SET(var, pos) ((1 << (pos)) & (var)) #define IS_BIT_CLEAR(var, pos) !IS_BIT_SET(var, pos) /* useful masks not defined in the spec */ /* bits [06:00] */ #define TPM_RC_7BIT_ERROR_MASK 0x7f /* bits [05:00] */ #define TPM_RC_6BIT_ERROR_MASK 0x3f /* bits [11:08] */ #define TPM_RC_PARAMETER_MASK 0xf00 /* bits [10:08] */ #define TPM_RC_HANDLE_MASK 0x700 #define TPM_RC_SESSION_MASK 0x700 /* "Format Zero" response codes have bit 7 clear. * Format zero RCs could be in a number of formats: * - A TPM 1.2 RC * - A vendor defined error code * - A 6 bit warning code * - A 6 bit error code */ static inline bool tpm2_rc_is_format_zero (TPM_RC response_code) { if (IS_BIT_CLEAR (response_code, 7)) return true; else return false; } /* "Format One" response codes have bit 7 set. * These RCs have two components: * - A 5 bit error code in bits [05:00] * - A 4 bit parameter identifier in [11:08] or a 3 bit handle / session * identifier in bits [10:08] */ static inline int tpm2_rc_is_format_one (TPM_RC response_code) { if (IS_BIT_SET (response_code, 7)) return true; else return false; } /* Determine whether or not a response code (TPM_RC) is in the 1.2 format or * the 2.0 format. */ static inline bool tpm2_rc_is_tpm2 (TPM_RC response_code) { /* if bit 7 & 8 are both 0, TPM_RC is 1.2 format */ if (IS_BIT_CLEAR (response_code, 7) && IS_BIT_CLEAR (response_code, 8)) return false; else return true; } static inline bool tpm2_rc_is_tpm12 (TPM_RC response_code) { if (!tpm2_rc_is_tpm2 (response_code)) return true; else return false; } /* Determine whether or not a response code (TPM_RC) is a vendor defined code. * Vendor defined TPM2 response codes have bit 8 and 10 set, and bit 7 clear. */ static inline bool tpm2_rc_is_vendor_defined (TPM_RC response_code) { if (IS_BIT_CLEAR (response_code, 7) && IS_BIT_SET (response_code, 8) && IS_BIT_SET (response_code, 10)) { return true; } else { return false; } } /* Determine whether or not bits [06:00] contain a warning code. * Warning codes have bit 8 and 11 set, and bits 7 and 10 clear. */ static inline bool tpm2_rc_is_warning_code (TPM_RC response_code) { if (IS_BIT_CLEAR (response_code, 7) && IS_BIT_SET (response_code, 8) && IS_BIT_CLEAR (response_code, 10) && IS_BIT_SET (response_code, 11)) { return true; } else { return false; } } /* Determine whether or not bits [06:00] contain an error code. * Error codes have bit 8 set, and bits 7, 10 and 11 clear. */ static inline bool tpm2_rc_is_error_code (TPM_RC response_code) { if (IS_BIT_CLEAR (response_code, 7) && IS_BIT_SET (response_code, 8) && IS_BIT_CLEAR (response_code, 10) && IS_BIT_CLEAR (response_code, 11)) { return 1; } else { return 0; } } /* Determine whether or not bits [05:00] contain and error code with a * parameter number in bits [11:08]. * Bit 6 and 7 are set. */ static inline bool tpm2_rc_is_error_code_with_parameter (TPM_RC response_code) { if (IS_BIT_SET (response_code, 6) && IS_BIT_SET (response_code, 7)) return true; else return false; } /* Determine whether or not bits [05:00] contain an error code with a * handle number in bits [10:08] * Bit 7 set, bits 6 and 11 clear. */ static inline bool tpm2_rc_is_error_code_with_handle (TPM_RC response_code) { if (IS_BIT_CLEAR (response_code, 6) && IS_BIT_SET (response_code, 7) && IS_BIT_CLEAR (response_code, 11)) { return true; } else { return false; } } /* Determine whether or not bits [05:00] contain an error code with a * session number in bits [10:08] * Bit 6 clear, bits 7 and 11 set. */ static inline bool tpm2_rc_is_error_code_with_session (TPM_RC response_code) { if (IS_BIT_CLEAR (response_code, 6) && IS_BIT_SET (response_code, 7) && IS_BIT_SET (response_code, 11)) { return true; } else { return false; } } /* Isolate bits [06:00] of the TPM_RC. * The 7bit warning or error code is only valid if the RC is a "format zero" * RC. */ static inline UINT32 tpm2_rc_get_code_7bit (TPM_RC response_code) { return TPM_RC_7BIT_ERROR_MASK & response_code; } /* Isolate bits [05:00] of the TPM_RC. * The 6bit error code is only valid if the RC is a "format one" RC. */ static inline UINT32 tpm2_rc_get_code_6bit (TPM_RC response_code) { return TPM_RC_6BIT_ERROR_MASK & response_code; } /* Isolate bits [11:08] of the TPM_RC. * The 4 it parameter code is only valid if the RC is a "format one" RC * with bit 6 set. Test for this with the * tpm2_rc_is_error_code_with_parameters function. */ static inline UINT32 tpm2_rc_get_parameter_number (TPM_RC response_code) { return TPM_RC_PARAMETER_MASK & response_code; } /* Isolate bits [10:08] of the TPM_RC. * The 3 bit handle / session code is only valid if the RC is a "format one" * RC with bits 6 clear. */ static inline UINT32 tpm2_rc_get_handle_number (TPM_RC response_code) { return TPM_RC_HANDLE_MASK & response_code; } static inline UINT32 tpm2_rc_get_session_number (TPM_RC response_code) { return TPM_RC_SESSION_MASK & response_code; } /* Isolate the error level component of the TPM_RC in bits [23:16] */ static inline UINT32 tpm2_rc_get_layer (TPM_RC response_code) { return TSS2_ERROR_LEVEL_MASK & response_code; } /* This function returns true if the error code indicates that it came from a * TSS component. False otherwise (which indicates it came from the TPM). */ static inline bool tpm2_rc_is_from_tss (TPM_RC response_code) { if (tpm2_rc_get_layer (response_code)) return true; else return false; } /* Isolate the error code from a TSS layer. It's not entirely clear to me * from the spec what the right mask is here. Bits [23:16] are for the layer * indicator but it says nothing else about which bits mean what. It makes * sense to assume that the lower 2 bytes hold the error code but the top * byte (AFAIK) is unaccounted for. * So I'm masking [31:24] as well as the ayer indicator. */ static inline UINT32 tpm2_rc_get_tss_err_code (TPM_RC response_code) { return 0X0000ffff & response_code; } /* Functions to retrieve tpm2_rc_entry with strings for RC decoding. */ tpm2_rc_entry_t* tpm2_get_tss_base_rc_entry (TPM_RC rc); tpm2_rc_entry_t* tpm2_get_parameter_entry (TPM_RC rc); tpm2_rc_entry_t* tpm2_get_handle_entry (TPM_RC rc); tpm2_rc_entry_t* tpm2_get_session_entry (TPM_RC rc); tpm2_rc_entry_t* tpm2_get_layer_entry (TPM_RC rc); tpm2_rc_entry_t* tpm2_get_fmt0_entry (TPM_RC rc); tpm2_rc_entry_t* tpm2_get_fmt1_entry (TPM_RC rc); tpm2_rc_entry_t* tpm2_get_warn_entry (TPM_RC rc); #endif /* RC_DECODE_H */ tpm2-tools-2.1.0/lib/string-bytes.c000066400000000000000000000076501313543155100171070ustar00rootroot00000000000000#include #include #include #include #include "string-bytes.h" bool string_bytes_concat_buffer(TPM2B_MAX_BUFFER *result, TPM2B *append) { if (!result || !append) { return false; } if ((result->t.size + append->size) < result->t.size) { return false; } if ((result->t.size + append->size) > MAX_DIGEST_BUFFER) { return false; } memcpy(&result->t.buffer[result->t.size], append->buffer, append->size); result->t.size += append->size; return true; } bool string_bytes_get_uint16(const char *str, uint16_t *value) { uint32_t tmp; bool result = string_bytes_get_uint32(str, &tmp); if (!result) { return false; } /* overflow on 16 bits? */ if (tmp > UINT16_MAX) { return false; } *value = (uint16_t)tmp; return true; } bool string_bytes_get_uint32(const char *str, uint32_t *value) { char *endptr; if (str == NULL || *str == '\0') { return false; } /* clear errno before the call, should be 0 afterwards */ errno = 0; uint32_t tmp = strtoul(str, &endptr, 0); if (errno) { return false; } /* * The entire string should be able to be converted or fail * We already checked that str starts with a null byte, so no * need to check that again per the man page. */ if (*endptr != '\0') { return false; } *value = tmp; return true; } int str2ByteStructure(const char *inStr, UINT16 *byteLength, BYTE *byteBuffer) { if(inStr == NULL || byteLength == NULL || byteBuffer == NULL) return -1; if(*byteLength <= strlen(inStr)) return -2; *byteLength = strlen(inStr); memcpy(byteBuffer, inStr, *byteLength); byteBuffer[*byteLength] = '\0'; return 0; } int hex2ByteStructure(const char *inStr, UINT16 *byteLength, BYTE *byteBuffer) { int strLength;//if the inStr likes "1a2b...", no prefix "0x" int i = 0; if(inStr == NULL || byteLength == NULL || byteBuffer == NULL) return -1; strLength = strlen(inStr); if(strLength%2) return -2; for(i = 0; i < strLength; i++) { if(!isxdigit(inStr[i])) return -3; } if(*byteLength < strLength/2) return -4; *byteLength = strLength/2; for(i = 0; i < *byteLength; i++) { char tmpStr[4] = {0}; tmpStr[0] = inStr[i*2]; tmpStr[1] = inStr[i*2+1]; byteBuffer[i] = strtol(tmpStr, NULL, 16); } return 0; } void string_bytes_print_tpm2b(TPM2B *buffer) { unsigned i; for (i = 0; i < buffer->size; i++) { printf("%2.2x ", buffer->buffer[i]); if (((i + 1) % 16) == 0) { printf("\n"); } } printf("\n"); } /* TODO OPTIMIZE ME */ UINT16 string_bytes_copy_tpm2b(TPM2B *dest, TPM2B *src) { int i; UINT16 rval = 0; if (dest != 0) { if (src == 0) { dest->size = 0; rval = 0; } else { dest->size = src->size; for (i = 0; i < src->size; i++) dest->buffer[i] = src->buffer[i]; rval = (sizeof(UINT16) + src->size); } } else { rval = 0; } return rval; } bool string_bytes_is_host_big_endian(void) { uint32_t test_word; uint8_t *test_byte; test_word = 0xFF000000; test_byte = (uint8_t *) (&test_word); return test_byte[0] == 0xFF; } #define STRING_BYTES_ENDIAN_CONVERT(size) \ UINT##size string_bytes_endian_convert_##size(UINT##size data) { \ \ UINT##size converted; \ UINT8 *bytes = (UINT8 *)&data; \ UINT8 *tmp = (UINT8 *)&converted; \ \ size_t i; \ for(i=0; i < sizeof(UINT##size); i ++) { \ tmp[i] = bytes[sizeof(UINT##size) - i - 1]; \ } \ \ return converted; \ } STRING_BYTES_ENDIAN_CONVERT(16) STRING_BYTES_ENDIAN_CONVERT(32) STRING_BYTES_ENDIAN_CONVERT(64) tpm2-tools-2.1.0/lib/string-bytes.h000066400000000000000000000044441313543155100171120ustar00rootroot00000000000000#ifndef STRING_BYTES_H #define STRING_BYTES_H #include #include #include #define BUFFER_SIZE(type, field) (sizeof((((type *)NULL)->t.field))) #define TPM2B_TYPE_INIT(type, field) { .t = { .size = BUFFER_SIZE(type, field), }, } int str2ByteStructure(const char *inStr, UINT16 *byteLenth, BYTE *byteBuffer); int hex2ByteStructure(const char *inStr, UINT16 *byteLenth, BYTE *byteBuffer); /** * Appends a TPM2B buffer to a MAX buffer. * @param result * The MAX buffer to append to * @param append * The buffer to append to result. * @return * true on success, false otherwise. */ bool string_bytes_concat_buffer(TPM2B_MAX_BUFFER *result, TPM2B *append); /** * Converts a numerical string into a uint32 value. * @param str * The numerical string to convert. * @param value * The value to store the conversion into. * @return * true on success, false otherwise. */ bool string_bytes_get_uint32(const char *str, uint32_t *value); /** * Converts a numerical string into a uint16 value. * @param str * The numerical string to convert. * @param value * The value to store the conversion into. * @return * true on success, false otherwise. */ bool string_bytes_get_uint16(const char *str, uint16_t *value); /** * Prints a TPM2B as a hex dump * @param buffer the TPM2B to print. */ void string_bytes_print_tpm2b(TPM2B *buffer); /** * Copies a tpm2b from dest to src and clears dest if src is NULL. * If src is NULL, it is a NOP. * @param dest * The destination TPM2B * @param src * The source TPM2B * @return * The number of bytes copied. */ UINT16 string_bytes_copy_tpm2b(TPM2B *dest, TPM2B *src); /** * Checks if the host is big endian * @return * True of the host is big endian false otherwise. */ bool string_bytes_is_host_big_endian(void); /** * Swaps the endianess of 16 bit value. * @param data * A 16 bit value to swap the endianess on. * @return * The 16 bit value with the endianess swapped. */ UINT16 string_bytes_endian_convert_16(UINT16 data); /** * Just like string_bytes_endian_convert_16 but for 32 bit values. */ UINT32 string_bytes_endian_convert_32(UINT32 data); /** * Just like string_bytes_endian_convert_16 but for 64 bit values. */ UINT64 string_bytes_endian_convert_64(UINT64 data); #endif /* STRING_BYTES_H */ tpm2-tools-2.1.0/lib/tpm2-header.c000066400000000000000000000066731313543155100165710ustar00rootroot00000000000000/* * Copyright (c) 2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include #include /* * Extract the 'tag' field from the tpm command header. This is a * TPMI_ST_COMMAND_TAG, which is a fancy word for UINT16 */ TPMI_ST_COMMAND_TAG get_command_tag (uint8_t *command_header) { return be16toh (*(TPMI_ST_COMMAND_TAG*)command_header); } /* * Get the commandSize field from the tpm command buffer supplied in the * 'command_header' parameter. We assume that the command buffer is a valid TPM * command (or response) and so it must be at least COMMAND_HEADER_SIZE * bytes long. * NOTE: The TPM2 architecture spec states in section 18.2.2 that the * commandSize field from the header is the total size of the * command. This includes the header itself. */ UINT32 get_command_size (uint8_t *command_header) { return be32toh (*(UINT32*)(command_header + sizeof (TPMI_ST_COMMAND_TAG))); } /* * Extract the commandCode from a tpm command buffer. It is the 3rd field * in the header so we do some pointer math to get the offset. */ TPM_CC get_command_code (uint8_t *command_header) { return be32toh (*(TPM_CC*)(command_header + sizeof (TPMI_ST_COMMAND_TAG) + sizeof (UINT32))); } /* * Get the 'tag' field from a TPM response buffer. This is the first field * in the header. */ TPM_ST get_response_tag (uint8_t *response_header) { return be16toh (*(TPM_ST*)response_header); } /* * Get the 'responseSize' field from a TPM response header. */ UINT32 get_response_size (uint8_t *response_header) { return be32toh (*(UINT32*)(response_header + sizeof (TPM_ST))); } /* * Get the responseCode field from the TPM response buffer supplied in the * 'response_header' parameter. We assume that the response buffer is a valid TPM * response header so it must be at least RESPONSE_HEADER_SIZE bytes long. */ TSS2_RC get_response_code (uint8_t *response_header) { return be32toh (*(TSS2_RC*)(response_header + sizeof (TPM_ST) + sizeof (UINT32))); } tpm2-tools-2.1.0/lib/tpm2-header.h000066400000000000000000000041631313543155100165660ustar00rootroot00000000000000/* * Copyright (c) 2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TPM2_HEADER_H #define TPM2_HEADER_H #include #include TPMI_ST_COMMAND_TAG get_command_tag (uint8_t *command_header); UINT32 get_command_size (uint8_t *command_header); TPM_CC get_command_code (uint8_t *command_header); TPM_ST get_response_tag (uint8_t *response_header); UINT32 get_response_size (uint8_t *response_header); TSS2_RC get_response_code (uint8_t *response_header); #endif /* TPM2_HEADER_H */ tpm2-tools-2.1.0/lib/tpm_hash.c000066400000000000000000000056711313543155100162610ustar00rootroot00000000000000#include #include UINT32 tpm_hash(TSS2_SYS_CONTEXT *sapi_context, TPMI_ALG_HASH hashAlg, UINT16 size, BYTE *data, TPM2B_DIGEST *result) { TPM2B_MAX_BUFFER dataSizedBuffer; dataSizedBuffer.t.size = size; memcpy(dataSizedBuffer.t.buffer, data, size); return Tss2_Sys_Hash(sapi_context, 0, &dataSizedBuffer, hashAlg, TPM_RH_NULL, result, 0, 0); } static TPM_RC hash_sequence_ex(TSS2_SYS_CONTEXT *sapi_context, TPMI_ALG_HASH hashAlg, UINT32 numBuffers, TPM2B_MAX_BUFFER *bufferList, TPM2B_DIGEST *result) { TPM_RC rval; TPM2B_AUTH nullAuth; TPMI_DH_OBJECT sequenceHandle; TPM2B emptyBuffer; TPMT_TK_HASHCHECK validation; TPMS_AUTH_COMMAND cmdAuth; TPMS_AUTH_COMMAND *cmdSessionArray[1] = { &cmdAuth }; TSS2_SYS_CMD_AUTHS cmdAuthArray = { 1, &cmdSessionArray[0] }; nullAuth.t.size = 0; emptyBuffer.size = 0; // Set result size to 0, in case any errors occur result->b.size = 0; // Init input sessions struct cmdAuth.sessionHandle = TPM_RS_PW; cmdAuth.nonce.t.size = 0; *((UINT8 *) ((void *) &cmdAuth.sessionAttributes)) = 0; cmdAuth.hmac.t.size = 0; rval = Tss2_Sys_HashSequenceStart(sapi_context, 0, &nullAuth, hashAlg, &sequenceHandle, 0); if (rval != TPM_RC_SUCCESS) { return rval; } unsigned i; for (i = 0; i < numBuffers; i++) { rval = Tss2_Sys_SequenceUpdate(sapi_context, sequenceHandle, &cmdAuthArray, &bufferList[i], 0); if (rval != TPM_RC_SUCCESS) { return rval; } } rval = Tss2_Sys_SequenceComplete(sapi_context, sequenceHandle, &cmdAuthArray, (TPM2B_MAX_BUFFER *) &emptyBuffer, TPM_RH_PLATFORM, result, &validation, 0); if (rval != TPM_RC_SUCCESS) { return rval; } return rval; } int tpm_hash_compute_data(TSS2_SYS_CONTEXT *sapi_context, BYTE *buffer, UINT16 length, TPMI_ALG_HASH halg, TPM2B_DIGEST *result) { if (length <= MAX_DIGEST_BUFFER) { if (tpm_hash(sapi_context, halg, length, buffer, result) == TPM_RC_SUCCESS) return 0; else return -1; } UINT8 numBuffers = (length - 1) / MAX_DIGEST_BUFFER + 1; TPM2B_MAX_BUFFER *bufferList = (TPM2B_MAX_BUFFER *) calloc(numBuffers, sizeof(TPM2B_MAX_BUFFER)); if (bufferList == NULL) return -2; UINT32 i; for (i = 0; i < (UINT32)(numBuffers - 1); i++) { bufferList[i].t.size = MAX_DIGEST_BUFFER; memcpy(bufferList[i].t.buffer, buffer + i * MAX_DIGEST_BUFFER, MAX_DIGEST_BUFFER); } bufferList[i].t.size = length - i * MAX_DIGEST_BUFFER; memcpy(bufferList[i].t.buffer, buffer + i * MAX_DIGEST_BUFFER, bufferList[i].t.size); TPM_RC rval = hash_sequence_ex(sapi_context, halg, numBuffers, bufferList, result); free(bufferList); return rval == TPM_RC_SUCCESS ? 0 : -3; } tpm2-tools-2.1.0/lib/tpm_hash.h000066400000000000000000000005411313543155100162550ustar00rootroot00000000000000#ifndef SRC_TPM_HASH_H_ #define SRC_TPM_HASH_H_ #include UINT32 tpm_hash(TSS2_SYS_CONTEXT *sapi_context, TPMI_ALG_HASH hashAlg, UINT16 size, BYTE *data, TPM2B_DIGEST *result); int tpm_hash_compute_data(TSS2_SYS_CONTEXT *sapi_context, BYTE *buffer, UINT16 length, TPMI_ALG_HASH halg, TPM2B_DIGEST *result); #endif /* SRC_TPM_HASH_H_ */ tpm2-tools-2.1.0/lib/tpm_hmac.c000066400000000000000000000124521313543155100162410ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include "string-bytes.h" static UINT32 LoadExternalHMACKey(TSS2_SYS_CONTEXT *sapi_contex, TPMI_ALG_HASH hashAlg, TPM2B *key, TPM_HANDLE *keyHandle, TPM2B_NAME *keyName ) { TPM2B keyAuth = { .size = 0, }; TPM2B_SENSITIVE inPrivate; TPM2B_PUBLIC inPublic; inPrivate.t.sensitiveArea.sensitiveType = TPM_ALG_KEYEDHASH; inPrivate.t.size = string_bytes_copy_tpm2b( &(inPrivate.t.sensitiveArea.authValue.b), &keyAuth); inPrivate.t.sensitiveArea.seedValue.b.size = 0; inPrivate.t.size += string_bytes_copy_tpm2b( &inPrivate.t.sensitiveArea.sensitive.bits.b, key); inPrivate.t.size += 2 * sizeof( UINT16 ); inPublic.t.publicArea.type = TPM_ALG_KEYEDHASH; inPublic.t.publicArea.nameAlg = TPM_ALG_NULL; *( UINT32 *)&( inPublic.t.publicArea.objectAttributes )= 0; inPublic.t.publicArea.objectAttributes.sign = 1; inPublic.t.publicArea.objectAttributes.userWithAuth = 1; inPublic.t.publicArea.authPolicy.t.size = 0; inPublic.t.publicArea.parameters.keyedHashDetail.scheme.scheme = TPM_ALG_HMAC; inPublic.t.publicArea.parameters.keyedHashDetail.scheme.details.hmac.hashAlg = hashAlg; inPublic.t.publicArea.unique.keyedHash.t.size = 0; keyName->t.size = sizeof( TPM2B_NAME ) - 2; return Tss2_Sys_LoadExternal(sapi_contex, 0, &inPrivate, &inPublic, TPM_RH_NULL, keyHandle, keyName, 0 ); } // // This function does an HMAC on a null-terminated list of input buffers. // TPM_RC tpm_hmac(TSS2_SYS_CONTEXT *sapi_context, TPMI_ALG_HASH hashAlg, TPM2B *key, TPM2B **bufferList, TPM2B_DIGEST *result ) { TPMI_DH_OBJECT sequenceHandle; TPM2B emptyBuffer; TPMT_TK_HASHCHECK validation; TPMS_AUTH_COMMAND sessionData = { .sessionHandle = TPM_RS_PW, .nonce = { .t = { .size = 0 }, }, .sessionAttributes = { .val = 0 }, }; TPMS_AUTH_COMMAND *sessionDataArray[1]; TSS2_SYS_CMD_AUTHS sessionsData; TPMS_AUTH_RESPONSE *sessionDataOutArray[1]; TPMS_AUTH_RESPONSE sessionDataOut; TSS2_SYS_RSP_AUTHS sessionsDataOut; UINT32 rval; TPM_HANDLE keyHandle; TPM2B_NAME keyName; TPM2B_AUTH nullAuth = { .t = { .size = 0 }, }; TPM2B keyAuth = { .size = 0, .buffer = { 0 } }; sessionDataArray[0] = &sessionData; sessionDataOutArray[0] = &sessionDataOut; // Set result size to 0, in case any errors occur result->b.size = 0; rval = LoadExternalHMACKey(sapi_context, hashAlg, key, &keyHandle, &keyName ); if( rval != TPM_RC_SUCCESS ) { return( rval ); } // Init input sessions struct string_bytes_copy_tpm2b( &sessionData.hmac.b, &keyAuth ); sessionsData.cmdAuthsCount = 1; sessionsData.cmdAuths = &sessionDataArray[0]; // Init sessions out struct sessionsDataOut.rspAuthsCount = 1; sessionsDataOut.rspAuths = &sessionDataOutArray[0]; emptyBuffer.size = 0; rval = Tss2_Sys_HMAC_Start( sapi_context, keyHandle, &sessionsData, &nullAuth, hashAlg, &sequenceHandle, 0 ); if( rval != TPM_RC_SUCCESS ) return( rval ); unsigned i; for( i = 0; bufferList[i] != 0; i++ ) { rval = Tss2_Sys_SequenceUpdate ( sapi_context, sequenceHandle, &sessionsData, (TPM2B_MAX_BUFFER *)( bufferList[i] ), &sessionsDataOut ); if( rval != TPM_RC_SUCCESS ) return( rval ); } result->t.size = sizeof( TPM2B_DIGEST ) - 2; rval = Tss2_Sys_SequenceComplete ( sapi_context, sequenceHandle, &sessionsData, ( TPM2B_MAX_BUFFER *)&emptyBuffer, TPM_RH_PLATFORM, result, &validation, &sessionsDataOut ); if( rval != TPM_RC_SUCCESS ) return( rval ); rval = Tss2_Sys_FlushContext( sapi_context, keyHandle ); return rval; } tpm2-tools-2.1.0/lib/tpm_hmac.h000066400000000000000000000040171313543155100162440ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #ifndef SRC_TPM_HMAC_H_ #define SRC_TPM_HMAC_H_ /** * Replaces TpmHmac. * @param sapi_context * The system api context from execute_tool() * @param hashAlg * The algorithm to perform * @param key * The key * @param bufferList * The list of NULL terminated buffers to perform the hmac on. * @param result * The tpm error code, TPM_RC_SUCCESS on success. * @return */ TPM_RC tpm_hmac(TSS2_SYS_CONTEXT *sapi_context, TPMI_ALG_HASH hashAlg, TPM2B *key, TPM2B **bufferList, TPM2B_DIGEST *result ); #endif /* SRC_TPM_HMAC_H_ */ tpm2-tools-2.1.0/lib/tpm_kdfa.c000066400000000000000000000114501313543155100162330ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include "string-bytes.h" #include "tpm_hmac.h" #include "log.h" static const EVP_MD *tpm_algorithm_to_openssl_digest(TPMI_ALG_HASH algorithm) { switch(algorithm) { case TPM_ALG_SHA1: return EVP_sha1(); case ALG_SHA256_VALUE: return EVP_sha256(); case TPM_ALG_SHA384: return EVP_sha384(); case TPM_ALG_SHA512: return EVP_sha512(); default: return NULL; } /* no return, not possible */ } TPM_RC tpm_kdfa(TPMI_ALG_HASH hashAlg, TPM2B *key, char *label, TPM2B *contextU, TPM2B *contextV, UINT16 bits, TPM2B_MAX_BUFFER *resultKey ) { TPM2B_DIGEST tpm2bLabel, tpm2bBits, tpm2b_i_2; UINT8 *tpm2bBitsPtr = &tpm2bBits.t.buffer[0]; UINT8 *tpm2b_i_2Ptr = &tpm2b_i_2.t.buffer[0]; TPM2B_DIGEST *bufferList[8]; UINT32 bitsSwizzled, i_Swizzled; TPM_RC rval = TPM_RC_SUCCESS; int i, j; UINT16 bytes = bits / 8; resultKey->t .size = 0; tpm2b_i_2.t.size = 4; tpm2bBits.t.size = 4; bitsSwizzled = string_bytes_endian_convert_32( bits ); *(UINT32 *)tpm2bBitsPtr = bitsSwizzled; for(i = 0; label[i] != 0 ;i++ ); tpm2bLabel.t.size = i+1; for( i = 0; i < tpm2bLabel.t.size; i++ ) { tpm2bLabel.t.buffer[i] = label[i]; } resultKey->t.size = 0; i = 1; const EVP_MD *md = tpm_algorithm_to_openssl_digest(hashAlg); if (!md) { LOG_ERR("Algorithm not supported for hmac: %x", hashAlg); return TPM_RC_HASH; } HMAC_CTX ctx; HMAC_CTX_init(&ctx); int rc = HMAC_Init_ex(&ctx, key->buffer, key->size, md, NULL); if (!rc) { LOG_ERR("HMAC Init failed: %s", ERR_error_string(rc, NULL)); return TPM_RC_MEMORY; } // TODO Why is this a loop? It appears to only execute once. while( resultKey->t.size < bytes ) { TPM2B_DIGEST tmpResult; // Inner loop i_Swizzled = string_bytes_endian_convert_32( i ); *(UINT32 *)tpm2b_i_2Ptr = i_Swizzled; j = 0; bufferList[j++] = (TPM2B_DIGEST *)&(tpm2b_i_2.b); bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bLabel.b); bufferList[j++] = (TPM2B_DIGEST *)contextU; bufferList[j++] = (TPM2B_DIGEST *)contextV; bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bBits.b); bufferList[j] = (TPM2B_DIGEST *)0; int c; for(c=0; c < j; c++) { TPM2B_DIGEST *digest = bufferList[c]; int rc = HMAC_Update(&ctx, digest->b.buffer, digest->b.size); if (!rc) { LOG_ERR("HMAC Update failed: %s", ERR_error_string(rc, NULL)); rval = TPM_RC_MEMORY; goto err; } } unsigned size = sizeof(tmpResult.t.buffer); int rc = HMAC_Final(&ctx, tmpResult.t.buffer, &size); if (!rc) { LOG_ERR("HMAC Final failed: %s", ERR_error_string(rc, NULL)); rval = TPM_RC_MEMORY; goto err; } tmpResult.t.size = size; bool res = string_bytes_concat_buffer(resultKey, &(tmpResult.b)); if (!res) { rval = TSS2_SYS_RC_BAD_VALUE; goto err; } } // Truncate the result to the desired size. resultKey->t.size = bytes; err: HMAC_CTX_cleanup(&ctx); return rval; } tpm2-tools-2.1.0/lib/tpm_kdfa.h000066400000000000000000000036251313543155100162450ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #ifndef SRC_TPM_KDFA_H_ #define SRC_TPM_KDFA_H_ #include /* TODO DOCUMENT ME */ /** * * @param hashAlg * @param key * @param label * @param contextU * @param contextV * @param bits * @param resultKey * @return */ TPM_RC tpm_kdfa(TPMI_ALG_HASH hashAlg, TPM2B *key, char *label, TPM2B *contextU, TPM2B *contextV, UINT16 bits, TPM2B_MAX_BUFFER *resultKey ); #endif /* SRC_TPM_KDFA_H_ */ tpm2-tools-2.1.0/lib/tpm_session.c000066400000000000000000000223221313543155100170110ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include "string-bytes.h" #include "tpm_kdfa.h" #include "tpm_session.h" /* for APP_RC_CREATE_SESSION_KEY_FAILED error code */ #define SESSIONS_ARRAY_COUNT MAX_NUM_SESSIONS+1 typedef struct { SESSION session; void *nextEntry; } SESSION_LIST_ENTRY; static SESSION_LIST_ENTRY *local_sessions_list = 0; static INT16 local_session_entries_used = 0; /* * GetDigestSize() was taken from the TSS code base * and moved here since it was not part of the public * exxported API at the time. */ typedef struct { TPM_ALG_ID algId; UINT16 size; // Size of digest } HASH_SIZE_INFO; HASH_SIZE_INFO hashSizes[] = { {TPM_ALG_SHA1, SHA1_DIGEST_SIZE}, {TPM_ALG_SHA256, SHA256_DIGEST_SIZE}, #ifdef TPM_ALG_SHA384 {TPM_ALG_SHA384, SHA384_DIGEST_SIZE}, #endif #ifdef TPM_ALG_SHA512 {TPM_ALG_SHA512, SHA512_DIGEST_SIZE}, #endif {TPM_ALG_SM3_256, SM3_256_DIGEST_SIZE}, {TPM_ALG_NULL,0} }; static UINT16 GetDigestSize( TPM_ALG_ID authHash ) { UINT32 i; for(i = 0; i < (sizeof(hashSizes)/sizeof(HASH_SIZE_INFO)); i++ ) { if( hashSizes[i].algId == authHash ) return hashSizes[i].size; } // If not found, return 0 size, and let TPM handle the error. return( 0 ); } static TPM_RC AddSession( SESSION_LIST_ENTRY **sessionEntry ) { SESSION_LIST_ENTRY **newEntry; // find end of list. for( newEntry = &local_sessions_list; *newEntry != 0; *newEntry = ( (SESSION_LIST_ENTRY *)*newEntry)->nextEntry ) ; // allocate space for session structure. *newEntry = malloc( sizeof( SESSION_LIST_ENTRY ) ); if( *newEntry != 0 ) { *sessionEntry = *newEntry; (*sessionEntry)->nextEntry = 0; local_session_entries_used++; return TPM_RC_SUCCESS; } else { return TSS2_APP_RC_SESSION_SLOT_NOT_FOUND; } } static void DeleteSession( SESSION *session ) { SESSION_LIST_ENTRY *predSession; void *newNextEntry; if( session == &local_sessions_list->session ) local_sessions_list = 0; else { // Find predecessor. for( predSession = local_sessions_list; predSession != 0 && &( ( ( SESSION_LIST_ENTRY *)predSession->nextEntry )->session ) != session; predSession = predSession->nextEntry ) ; if( predSession != 0 ) { local_session_entries_used--; newNextEntry = &( (SESSION_LIST_ENTRY *)predSession->nextEntry)->nextEntry; free( predSession->nextEntry ); predSession->nextEntry = newNextEntry; } } } // // This is a wrapper function around the TPM2_StartAuthSession command. // It performs the command, calculates the session key, and updates a // SESSION structure. // static TPM_RC StartAuthSession(TSS2_SYS_CONTEXT *sapi_context, SESSION *session ) { TPM_RC rval; TPM2B_ENCRYPTED_SECRET key; char label[] = "ATH"; UINT16 bytes; int i; key.t.size = 0; if( session->nonceOlder.t.size == 0 ) { /* this is an internal routine to TSS and should be removed */ session->nonceOlder.t.size = GetDigestSize( TPM_ALG_SHA1 ); for( i = 0; i < session->nonceOlder.t.size; i++ ) session->nonceOlder.t.buffer[i] = 0; } session->nonceNewer.t.size = session->nonceOlder.t.size; rval = Tss2_Sys_StartAuthSession( sapi_context, session->tpmKey, session->bind, 0, &( session->nonceOlder ), &( session->encryptedSalt ), session->sessionType, &( session->symmetric ), session->authHash, &( session->sessionHandle ), &( session->nonceNewer ), 0 ); if( rval == TPM_RC_SUCCESS ) { if( session->tpmKey == TPM_RH_NULL ) session->salt.t.size = 0; if( session->bind == TPM_RH_NULL ) session->authValueBind.t.size = 0; if( session->tpmKey == TPM_RH_NULL && session->bind == TPM_RH_NULL ) { session->sessionKey.b.size = 0; } else { // Generate the key used as input to the KDF. // Generate the key used as input to the KDF. bool result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->authValueBind.b ) ); if (!result) { return TSS2_SYS_RC_BAD_VALUE; } result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->salt.b ) ); if (!result) { return TSS2_SYS_RC_BAD_VALUE; } bytes = GetDigestSize( session->authHash ); if( key.t.size == 0 ) { session->sessionKey.t.size = 0; } else { rval = tpm_kdfa(session->authHash, &(key.b), label, &( session->nonceNewer.b ), &( session->nonceOlder.b ), bytes * 8, (TPM2B_MAX_BUFFER *)&( session->sessionKey ) ); } if( rval != TPM_RC_SUCCESS ) { return( TSS2_APP_RC_CREATE_SESSION_KEY_FAILED ); } } session->nonceTpmDecrypt.b.size = 0; session->nonceTpmEncrypt.b.size = 0; session->nvNameChanged = 0; } return rval; } TPM_RC tpm_session_auth_end( SESSION *session ) { TPM_RC rval = TPM_RC_SUCCESS; DeleteSession( session ); return rval; } // // This version of StartAuthSession initializes the fields // of the session structure using the passed in // parameters, then calls StartAuthSession // with just a pointer to the session structure. // This allows all params to be set in one line of code when // the function is called; cleaner this way, for // some uses. // TPM_RC tpm_session_start_auth_with_params(TSS2_SYS_CONTEXT *sapi_context, SESSION **session, TPMI_DH_OBJECT tpmKey, TPM2B_MAX_BUFFER *salt, TPMI_DH_ENTITY bind, TPM2B_AUTH *bindAuth, TPM2B_NONCE *nonceCaller, TPM2B_ENCRYPTED_SECRET *encryptedSalt, TPM_SE sessionType, TPMT_SYM_DEF *symmetric, TPMI_ALG_HASH algId ) { TPM_RC rval; SESSION_LIST_ENTRY *sessionEntry; rval = AddSession( &sessionEntry ); if( rval == TSS2_RC_SUCCESS ) { *session = &sessionEntry->session; // Copy handles to session struct. (*session)->bind = bind; (*session)->tpmKey = tpmKey; // Copy nonceCaller to nonceOlder in session struct. // This will be used as nonceCaller when StartAuthSession // is called. memcpy( &(*session)->nonceOlder.b, &nonceCaller->b, sizeof(nonceCaller->b)); // Copy encryptedSalt memcpy( &(*session)->encryptedSalt.b, &encryptedSalt->b, sizeof(encryptedSalt->b)); // Copy sessionType. (*session)->sessionType = sessionType; // Init symmetric. (*session)->symmetric.algorithm = symmetric->algorithm; (*session)->symmetric.keyBits.sym = symmetric->keyBits.sym; (*session)->symmetric.mode.sym = symmetric->mode.sym; (*session)->authHash = algId; // Copy bind' authValue. if( bindAuth == 0 ) { (*session)->authValueBind.b.size = 0; } else { memcpy( &( (*session)->authValueBind.b ), &( bindAuth->b ), sizeof(bindAuth->b)); } // Calculate sessionKey if( (*session)->tpmKey == TPM_RH_NULL ) { (*session)->salt.t.size = 0; } else { memcpy( &(*session)->salt.b, &salt->b, sizeof(salt->b)); } if( (*session)->bind == TPM_RH_NULL ) (*session)->authValueBind.t.size = 0; rval = StartAuthSession(sapi_context, *session ); } else { DeleteSession( *session ); } return( rval ); } tpm2-tools-2.1.0/lib/tpm_session.h000066400000000000000000000135211313543155100170170ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #ifndef SRC_TPM_SESSION_H_ #define SRC_TPM_SESSION_H_ #include typedef struct { // Inputs to StartAuthSession; these need to be saved // so that HMACs can be calculated. TPMI_DH_OBJECT tpmKey; TPMI_DH_ENTITY bind; TPM2B_ENCRYPTED_SECRET encryptedSalt; TPM2B_MAX_BUFFER salt; TPM_SE sessionType; TPMT_SYM_DEF symmetric; TPMI_ALG_HASH authHash; // Outputs from StartAuthSession; these also need // to be saved for calculating HMACs and // other session related functions. TPMI_SH_AUTH_SESSION sessionHandle; TPM2B_NONCE nonceTPM; // Internal state for the session TPM2B_DIGEST sessionKey; TPM2B_DIGEST authValueBind; // authValue of bind object TPM2B_NONCE nonceNewer; TPM2B_NONCE nonceOlder; TPM2B_NONCE nonceTpmDecrypt; TPM2B_NONCE nonceTpmEncrypt; TPM2B_NAME name; // Name of the object the session handle // points to. Used for computing HMAC for // any HMAC sessions present. // void *hmacPtr; // Pointer to HMAC field in the marshalled // data stream for the session. // This allows the function to calculate // and fill in the HMAC after marshalling // of all the inputs. // // This is only used if the session is an // HMAC session. // UINT8 nvNameChanged; // Used for some special case code // dealing with the NV written state. } SESSION; enum TSS2_APP_RC_CODE { APP_RC_PASSED, APP_RC_GET_NAME_FAILED, APP_RC_CREATE_SESSION_KEY_FAILED, APP_RC_SESSION_SLOT_NOT_FOUND, APP_RC_BAD_ALGORITHM, APP_RC_SYS_CONTEXT_CREATE_FAILED, APP_RC_GET_SESSION_STRUCT_FAILED, APP_RC_GET_SESSION_ALG_ID_FAILED, APP_RC_INIT_SYS_CONTEXT_FAILED, APP_RC_TEARDOWN_SYS_CONTEXT_FAILED, APP_RC_BAD_LOCALITY }; // Add this to application-specific error codes so they overlap // with TSS ones which may be re-used for app level errors. #define APP_RC_OFFSET 0x100 // These are app specific error codes, so they have // APP_RC_OFFSET added. #define TSS2_APP_RC_PASSED (APP_RC_PASSED + APP_RC_OFFSET + TSS2_APP_ERROR_LEVEL) #define TSS2_APP_RC_GET_NAME_FAILED (APP_RC_GET_NAME_FAILED + APP_RC_OFFSET + TSS2_APP_ERROR_LEVEL) #define TSS2_APP_RC_CREATE_SESSION_KEY_FAILED (APP_RC_CREATE_SESSION_KEY_FAILED + APP_RC_OFFSET + TSS2_APP_ERROR_LEVEL) #define TSS2_APP_RC_SESSION_SLOT_NOT_FOUND (APP_RC_SESSION_SLOT_NOT_FOUND + APP_RC_OFFSET + TSS2_APP_ERROR_LEVEL) #define TSS2_APP_RC_BAD_ALGORITHM (APP_RC_BAD_ALGORITHM + APP_RC_OFFSET + TSS2_APP_ERROR_LEVEL) #define TSS2_APP_RC_SYS_CONTEXT_CREATE_FAILED (APP_RC_SYS_CONTEXT_CREATE_FAILED + APP_RC_OFFSET + TSS2_APP_ERROR_LEVEL) #define TSS2_APP_RC_GET_SESSION_STRUCT_FAILED (APP_RC_GET_SESSION_STRUCT_FAILED + APP_RC_OFFSET + TSS2_APP_ERROR_LEVEL) #define TSS2_APP_RC_GET_SESSION_ALG_ID_FAILED (APP_RC_GET_SESSION_ALG_ID_FAILED + APP_RC_OFFSET + TSS2_APP_ERROR_LEVEL) #define TSS2_APP_RC_INIT_SYS_CONTEXT_FAILED (APP_RC_INIT_SYS_CONTEXT_FAILED + APP_RC_OFFSET + TSS2_APP_ERROR_LEVEL) #define TSS2_APP_RC_TEARDOWN_SYS_CONTEXT_FAILED (APP_RC_TEARDOWN_SYS_CONTEXT_FAILED + APP_RC_OFFSET + TSS2_APP_ERROR_LEVEL) #define TSS2_APP_RC_BAD_LOCALITY (APP_RC_BAD_LOCALITY + APP_RC_OFFSET + TSS2_APP_ERROR_LEVEL) /* TODO DOCUMENT ME */ /** * * @param sapi_context * @param session * @param tpmKey * @param salt * @param bind * @param bindAuth * @param nonceCaller * @param encryptedSalt * @param sessionType * @param symmetric * @param algId * @return */ TPM_RC tpm_session_start_auth_with_params(TSS2_SYS_CONTEXT *sapi_context, SESSION **session, TPMI_DH_OBJECT tpmKey, TPM2B_MAX_BUFFER *salt, TPMI_DH_ENTITY bind, TPM2B_AUTH *bindAuth, TPM2B_NONCE *nonceCaller, TPM2B_ENCRYPTED_SECRET *encryptedSalt, TPM_SE sessionType, TPMT_SYM_DEF *symmetric, TPMI_ALG_HASH algId ); /** * * @param session * @return */ TPM_RC tpm_session_auth_end( SESSION *session); #endif /* SRC_TPM_SESSION_H_ */ tpm2-tools-2.1.0/man/000077500000000000000000000000001313543155100143065ustar00rootroot00000000000000tpm2-tools-2.1.0/man/common-options.troff000066400000000000000000000006121313543155100203300ustar00rootroot00000000000000.TP [\fBCOMMON OPTIONS\fR ] This collection of options are common to many programs and provide information that many users may expect. .TP \fB\-h,\ \-\-help\fR Display a manual describing the tool and its usage. .TP \fB\-v,\ \-\-version\fR Display version information for this tool. .TP \fB\-V,\ \-\-verbose\fR Increase the information that the tool prints to the console during its execution. tpm2-tools-2.1.0/man/tcti-environment.troff000066400000000000000000000015141313543155100206560ustar00rootroot00000000000000.TP \fBENVIRONMENT: TCTI\fR This collection of environment variables that may be used to configure the varous TCTI modules available. The values passed through these variables can be overridden on a per-command basis using the available command line options. .TP \fBTPM2TOOLS_TCTI_NAME\fR Select the TCTI used for communication with the next component down the TSS stack. In most configurations this will be the TPM but it could be a simulator or proxy. See '\fBOPTIONS\fR' section for the names of supported TCTIs. .TP .if (\n[HAVE_TCTI_DEV]) \{ \fBTPM2TOOLS_DEVICE_FILE\fR Specify the TPM device file for use by the device TCTI. \} .if (\n[HAVE_TCTI_SOCK]) \{ .TP \fBTPM2TOOLS_SOCKET_ADDRESS\fR Specify the domain name or IP address used by the socket TCTI. .TP \fBTPM2TOOLS_SOCKET_PORT\fR Specify the port number used by the socket TCTI. \} tpm2-tools-2.1.0/man/tcti-options.troff000066400000000000000000000015651313543155100200130ustar00rootroot00000000000000.TP [\fBTCTI OPTIONS\fR ] This collection of options are used to configure the varous TCTI modules available. .TP \fB\-T,\ \-\-tcti\fR Select the TCTI used for communication with the next component down the TSS stack. In most configurations this will be the TPM but it could be a simulator or proxy. Supported TCTIs are .if (\n[HAVE_TCTI_DEV]) or \fB\*(lqdevice\*(rq\fR .if (\n[HAVE_TCTI_SOCK]) or \fB\*(lqsocket\*(rq\fR .if (\n[HAVE_TCTI_TABRMD]) or \fB\*(lqtabrmd\*(rq\fR \[char46] .TP .if (\n[HAVE_TCTI_DEV]) \{ \fB\-d,\ \-\-device-file\fR Specify the TPM device file for use by the device TCTI. The default is /dev/tpm0. \} .if (\n[HAVE_TCTI_SOCK]) \{ .TP \fB\-R,\ \-\-socket-address\fR Specify the domain name or IP address used by the socket TCTI. The default is 127.0.0.1. .TP \fB\-p,\ \-\-socket-port\fR Specify the port number used by the socket TCTI. The default is 2321. \} tpm2-tools-2.1.0/man/tpm2_activatecredential.8.in000066400000000000000000000074621313543155100216120ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_activatecredential 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_activatecredential\ - Verify that the given content is protected with given keyHandle for given handle, and then decrypt and return the secret, if any passwd option is missing, assume NULL. Currently only support using TCG profile compliant EK as the keyHandle. .SH SYNOPSIS .B tpm2_activatecredential[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-handle\fR|\fB\-\-context\fR|\fB\-\-keyHandle\fR|\fB\-\-keyContext\fR|\fB\-\-Password\fR|\fB\-\-endorsePasswd\fR|\fB\-\-inFile\fR|\fB\-\-outFile\fR|\fB\-\-passwdInHex\fR|\fB ] .PP Verify that the given content is protected with given keyHandle for given handle, and then decrypt and return the secret, if any passwd option is missing, assume NULL. Currently only support using TCG profile compliant EK as the keyHandle. .SH DESCRIPTION .B tpm2_activatecredential Verify that the given content is protected with given keyHandle for given handle, and then decrypt and return the secret, if any passwd option is missing, assume NULL. Currently only support using TCG profile compliant EK as the keyHandle. .SH OPTIONS .TP \fB\-H ,\-\-handle\fR Handle of the object associated with the created certificate by CA .TP \fB\-c ,\-\-context\fR filename for handle context .TP \fB\-k ,\-\-keyHandle\fR Loaded key used to decrypt the the random seed .TP \fB\-C ,\-\-keyContext\fR filename for keyHandle context .TP \fB\-P ,\-\-Password\fR the handle's password, optional .TP \fB\-e ,\-\-endorsePasswd\fR the endorsement password, optional .TP \fB\-f ,\-\-inFile\fR Input file path, containing the two structures needed by tpm2_activatecredential function .TP \fB\-o ,\-\-outFile\fR Output file path, record the secret to decrypt the certificate .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format. @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_activatecredential .PP .nf .RS tpm2_activatecredential -H 0x81010002 -k 0x81010001 -P abc123 -e abc123 -f -o tpm2_activatecredential -c ak.context -C ek.context -P abc123 -e abc123 -f -o tpm2_activatecredential -H 0x81010002 -k 0x81010001 -P 123abc -e 1a1b1c -X -f -o .RE .fi tpm2-tools-2.1.0/man/tpm2_akparse.8.in000066400000000000000000000046651313543155100174070ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_akparse 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_akparse\ - parse the algorithm and key values in TPM2B_PUBLIC struct which input via file inputFile, and output the key into file akKeyFile. .SH SYNOPSIS .B tpm2_akparse[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-f\fR|\fB\-k\fR ] .PP parse the algorithm and key values in TPM2B_PUBLIC struct which input via file inputFile, and output the key into file akKeyFile. .SH DESCRIPTION .B tpm2_akparse parse the algorithm and key values in TPM2B_PUBLIC struct which input via file inputFile, and output the key into file akKeyFile. .SH OPTIONS .TP \fB\-f\fR Specifies the file to be parsed .TP \fB\-k\fR Specifies the file used to save the parsed data @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_akparse .PP .nf .RS tpm2_akparse -f ./ak.data -k ./ak.key .RE .fi tpm2-tools-2.1.0/man/tpm2_certify.8.in000066400000000000000000000114001313543155100174070ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_certify 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_certify\ - prove that an object with a specific Name is loaded in the TPM. By certifying that the object is loaded, the TPM warrants that a public area with a given Name is self-consistent and associated with a valid sensitive area. If a relying party has a public area that has the same Name as a Name certified with this command, then the values in that public area are correct. The object may be any object that is loaded with TPM2_Load() or TPM2_CreatePrimary(). An object that only has its public area loaded cannot be certified. .SH SYNOPSIS .B tpm2_certify[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-objHandle\fR|\fB\-\-objContext\fR|\fB\-\-keyHandle\fR|\fB\-\-keyContext\fR|\fB\-\-pwdo\fR|\fB\-\-pwdk\fR|\fB\-\-halg\fR|\fB\-\-attestFile\fR|\fB\-\-sigFile\fR|\fB\-\-passwdInHex\fR|\fB ] .PP prove that an object with a specific Name is loaded in the TPM. By certifying that the object is loaded, the TPM warrants that a public area with a given Name is self-consistent and associated with a valid sensitive area. If a relying party has a public area that has the same Name as a Name certified with this command, then the values in that public area are correct. The object may be any object that is loaded with TPM2_Load() or TPM2_CreatePrimary(). An object that only has its public area loaded cannot be certified. .SH DESCRIPTION .B tpm2_certify prove that an object with a specific Name is loaded in the TPM. By certifying that the object is loaded, the TPM warrants that a public area with a given Name is self-consistent and associated with a valid sensitive area. If a relying party has a public area that has the same Name as a Name certified with this command, then the values in that public area are correct. The object may be any object that is loaded with TPM2_Load() or TPM2_CreatePrimary(). An object that only has its public area loaded cannot be certified. .SH OPTIONS .TP \fB\-H ,\-\-objHandle\fR handle of the object to be certified .TP \fB\-C ,\-\-objContext\fR filename of the object context to be certified .TP \fB\-k ,\-\-keyHandle\fR handle of the key used to sign the attestation structure .TP \fB\-c ,\-\-keyContext\fR filename of the key context used to sign the attestation structure .TP \fB\-P ,\-\-pwdo\fR the object handle's password, optional .TP \fB\-K ,\-\-pwdk\fR the keyHandle's password, optional .TP \fB\-g ,\-\-halg\fR the hash algorithm used to digest the message 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 .TP \fB\-a ,\-\-attestFile\fR output file name, record the attestation structure .TP \fB\-s ,\-\-sigFile\fR output file name, record the signature structure .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format. @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_certify .PP .nf .RS tpm2_certify -H 0x81010002 -k 0x81010001 -P 0x0011 -K 0x00FF -g 0x00B -a -s tpm2_certify -C obj.context -c key.context -P 0x0011 -K 0x00FF -g 0x00B -a -s tpm2_certify -H 0x81010002 -k 0x81010001 -P 0011 -K 00FF -X -g 0x00B -a -s .RE .fi tpm2-tools-2.1.0/man/tpm2_create.8.in000066400000000000000000000072621313543155100172200ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_create 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_create\ - create an object that can be loaded into a TPM using tpm2_load. The object will need to be loaded before it may be used. .SH SYNOPSIS .B tpm2_create[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-parent\fR|\fB\-\-contextParent\fR|\fB\-\-pwdp\fR|\fB\-\-pwdk\fR|\fB\-\-halg\fR|\fB\-\-kalg\fR|\fB\-\-objectAttribute\fR|\fB\-\-inFile\fR|\fB\-\-pol\fR|\fB\-\-opu\fR|\fB\-\-opr\fR|\fB\-\-passwdInHex\fR|\fB ] .PP create an object that can be loaded into a TPM using tpm2_load. The object will need to be loaded before it may be used. .SH DESCRIPTION .B tpm2_create create an object that can be loaded into a TPM using tpm2_load. The object will need to be loaded before it may be used. .SH OPTIONS .TP \fB\-H ,\-\-parent\fR parent handle .TP \fB\-c ,\-\-contextParent\fR filename for parent context .TP \fB\-P ,\-\-pwdp\fR password for parent key, optional .TP \fB\-K ,\-\-pwdk\fR password for key, optional .TP \fB\-g ,\-\-halg\fR algorithm used for computing the Name of the object 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 .TP \fB\-G ,\-\-kalg\fR algorithm associated with this object 0x0001 TPM_ALG_RSA 0x0008 TPM_ALG_KEYEDHASH 0x0023 TPM_ALG_ECC 0x0025 TPM_ALG_SYMCIPHER .TP \fB\-A ,\-\-objectAttribute\fR object attributes, optional .TP \fB\-I ,\-\-inFile\fR data file to be sealed, optional .TP \fB\-L ,\-\-pol\fR the input policy file, optional .TP \fB\-o ,\-\-opu\fR the output file which contains the public key, optional .TP \fB\-O ,\-\-opr\fR the output file which contains the private key, optional .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format. @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_create .PP .nf .RS tpm2_create -H 0x81010001 -P abc123 -K def456 -g 0x000B -G 0x0008 -I data.File -o opu.File tpm2_create -c parent.context -P abc123 -K def456 -g 0x000B -G 0x0008 -I data.File -o opu.File tpm2_create -H 0x81010001 -P 123abc -K 456def -X -g 0x000B -G 0x0008 -I data.File -o opu.File .RE .fi tpm2-tools-2.1.0/man/tpm2_createprimary.8.in000066400000000000000000000101661313543155100206210ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_createprimary 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_createprimary \- Create a primary key under a primary seed or a temporary primary key under the TPM_RH_NULL hierarchy. .SH SYNOPSIS .B tpm2_createprimary [\fBCOMMON OPTIONS\fR] [\fBTCTI OPTIONS\fR] [\fB\-A\fR|\fB\-\-auth\fR=][o|p|e|n] [\fB\-P\fR|\fB\-\-pwdp\fB=][string] [\fB\-K\fR|\fB\-\-pwdk\fR=][string] [\fB\-g\fR|\fB\-\-halg\fR=][0x4|0xB|0xC|0xD|0x12] [\fB\-G\fR|\fB\-\-kalg\fR=][0x1|0x8|0x23|0x25] [\fB\-C\fR|\fB\-\-context\fR=][filepath] [\fB\-X\fR|\fB\-\-passwdInHex\fR [\fB\-d\fR|\fB\-\-debugLevel\fR=][0|1|2|3] .PP .SH DESCRIPTION This command is used to create a Primary Object under one of the Primary Seeds or a Temporary Object under TPM_RH_NULL. The command uses a TPM2B_PUBLIC as a template for the object to be created. The command will create and load a Primary Object. The sensitive area is not returned. .SH OPTIONS .TP \fB\-A\fR,\ \fB\-\-auth\fR=[o|p|e|n] Specify the hierarchy under which the object is created. This will also dictate which authorization secret (if any) must be supplied. .br Supported options are: 'o' for TPM_RH_OWNER 'p' for TPM_RH_PLATFORM 'e' for TPM_RH_ENDORSEMENT 'n' for TPM_RH_NULL .TP \fB\-P\fR,\ \fB\-\-pwdp\fR=[string] Optional authorization string if authorization is required to create object under the specified hierarchy. .TP \fB\-K\fR,\ \fB\-\-pwdk\fR=[string] Optional authorization string for the newly created object. .TP \fB\-g\fR,\ \fB\-\-halg\fR=[0x4|0xB|0xC|0xD|0x12] Hash algorithm used in the computation of the object name. .br Supported options are: '0x4' for TPM_ALG_SHA1 '0xB' for TPM_ALG_SHA256 '0xC' for TPM_ALG_SHA384 '0xD' for TPM_ALG_SHA256 '0x12' for TPM_ALG_SM3_256 .br \fBNOTE\fR: Your TPM may not support all algorithms. .TP \fB\-G\fR,\ \fB\-\-kalg\fR=[0x1|0x8|0x23|0x25] Algorithm type for generated key. .br Supported options are: '0x1' for TPM_ALG_RSA '0x8' for TPM_ALG_KEYEDHASH '0x23' for TPM_ALG_ECC '0x25' for TPM_ALG_SYMCIPHER .TP \fB\-C\fR,\ \fB\-\-context\fR=[filepath] An optional file used to store the object context returned. .TP \fB\-X\fR,\ \fB\-\-passwdInHex\fR A flag used to indicate that the supplied passwords are hex strings. .TP \fB\-d\fR,\ \fB\-\-debugLevel\fR=[0|1|2|3] Control the verbosity of debug output from the tool. .tr Supported values are: '0' is the default '1' displays test app send / receive byte streams '2' displays resource manager send / receive byte streams '3' displays the resource manager tables @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT @TCTI_ENVIRONMENT_INCLUDE@ tpm2-tools-2.1.0/man/tpm2_dump_capability.8.in000066400000000000000000000047361313543155100211260ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_dump_capability 8 "NOVEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_dump_capability \- Display TPM capabilities in a human readable form. .SH SYNOPSIS .B tpm2_dump_capability [ \fBCOMMON OPTIONS\fR ] [ \fBTCTI OPTIONS\fR ] [ -\fB\-c\fR|\fB\-\-capability\fR]=capability_type .PP .SH DESCRIPTION Query the TPM for it's capabilities / properties and dump them to the console. This is a thin wrapper around the GetCapability command. .SH OPTIONS .TP [-c|--capability] - The name of the capability group to query. Currently supported capability groups are: \fB\*(lqproperties-fixed\*(rq\fR - Display fixed TPM properties. \fB\*(lqproperties-variable\*(rq\fR - Display variable TPM properties. \fB\*(lqalgorithms\*(rq\fR - Display data about supported algorithms. \fB\*(lqcommands\*(rq\fR - Display data about supported commands. @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT @TCTI_ENVIRONMENT_INCLUDE@ tpm2-tools-2.1.0/man/tpm2_encryptdecrypt.8.in000066400000000000000000000062341313543155100210320ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_encryptdecrypt 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_encryptdecrypt\ - performs symmetric encryption or decryption. keyHandle shall reference a symmetric cipher object. .SH SYNOPSIS .B tpm2_encryptdecrypt[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-keyHandle\fR|\fB\-\-keyContext\fR|\fB\-\-pwdk\fR|\fB\-\-decrypt\fR|\fB\-\-inFile\fR|\fB\-\-outFile\fR|\fB\-\-passwdInHex\fR|\fB ] .PP performs symmetric encryption or decryption. keyHandle shall reference a symmetric cipher object. .SH DESCRIPTION .B tpm2_encryptdecrypt performs symmetric encryption or decryption. keyHandle shall reference a symmetric cipher object. .SH OPTIONS .TP \fB\-k ,\-\-keyHandle\fR the symmetric key used for the operation (encryption/decryption) .TP \fB\-c ,\-\-keyContext\fR filename of the key context used for the operation .TP \fB\-P ,\-\-pwdk\fR the password of key, optional .TP \fB\-D ,\-\-decrypt\fR the operation type, default NO, optional YES the operation is decryption NO the operation is encryption .TP \fB\-I ,\-\-inFile\fR Input file path, containing the data to be operated .TP \fB\-o ,\-\-outFile\fR Output file path, record the operated data .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format. @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_encryptdecrypt .PP .nf .RS tpm2_encryptdecrypt -k 0x81010001 -P abc123 -D NO -I -o tpm2_encryptdecrypt -c key.context -P abc123 -D NO -I -o tpm2_encryptdecrypt -k 0x81010001 -P 123abca -X -D NO -I -o .RE .fi tpm2-tools-2.1.0/man/tpm2_evictcontrol.8.in000066400000000000000000000055761313543155100204760ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_evictcontrol 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_evictcontrol\ - allows a transient object to be made persistent or a persistent object to be evicted. .SH SYNOPSIS .B tpm2_evictcontrol[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-auth\fR|\fB\-\-handle\fR|\fB\-\-context\fR|\fB\-\-persistent\fR|\fB\-\-pwda\fR|\fB\-\-passwdInHex\fR|\fB ] .PP allows a transient object to be made persistent or a persistent object to be evicted. .SH DESCRIPTION .B tpm2_evictcontrol allows a transient object to be made persistent or a persistent object to be evicted. .SH OPTIONS .TP \fB\-A ,\-\-auth\fR the authorization used to authorize the commands o TPM_RH_OWNER p TPM_RH_PLATFORM .TP \fB\-H ,\-\-handle\fR the handle of a loaded object .TP \fB\-c ,\-\-context\fR filename for object context .TP \fB\-S ,\-\-persistent\fR the persistent handle for objectHandle .TP \fB\-P ,\-\-pwda\fR authrization password, optional .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format. @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_evictcontrol .PP .nf .RS tpm2_evictcontrol -A o -c object.context -S 0x81010002 -P abc123 tpm2_evictcontrol -A o -H 0x81010002 -S 0x81010002 -P abc123 tpm2_evictcontrol -A o -H 0x81010002 -S 0x81010002 -P 123abc -X .RE .fi tpm2-tools-2.1.0/man/tpm2_getmanufec.8.in000066400000000000000000000102311313543155100200610ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_getmanufec 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_getmanufec\ - Retrieve the Endorsement Credential Certificate for the TPM endorsement key from the TPM manufacturer's endorsement certificate hosting server .SH SYNOPSIS .B tpm2_getmanufec[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-endorsePasswd\fR|\fB\-\-ownerPasswd\fR|\fB\-\-ekPasswd\fR|\fB\-\-handle\fR|\fB\-\-alg\fR|\fB\-\-file\fR|\fB\-\-NonPersistent\fR|\fB\-\-OfflineProv\fR|\fB\-\-ECcertFile\fR|\fB\-\-EKserverAddr\fR|\fB\-\-SSL_NO_VERIFY\fR|\fB\-\-passwdInHex\fR|\fB ] .PP Retrieve the Endorsement Credential Certificate for the TPM endorsement key from the TPM manufacturer's endorsement certificate hosting server .SH DESCRIPTION .B tpm2_getmanufec Retrieve the Endorsement Credential Certificate for the TPM endorsement key from the TPM manufacturer's endorsement certificate hosting server .SH OPTIONS .TP \fB\-e ,\-\-endorsePasswd\fR specifies current endorse password (string, optional,default:NULL). .TP \fB\-o ,\-\-ownerPasswd\fR specifies current owner password (string, optional,default:NULL). .TP \fB\-P ,\-\-ekPasswd\fR specifies the EK password when created (string,optional,default:NULL). .TP \fB\-H ,\-\-handle\fR specifies the handle used to make EK persistent (hex). .TP \fB\-g ,\-\-alg\fR specifies the algorithm type of EK (default:0x01/TPM_ALG_RSA). .TP \fB\-f ,\-\-file\fR specifies the file used to save the public portion of EK. .TP \fB\-N ,\-\-NonPersistent\fR specifies to readout the EK public without making it persistent .TP \fB\-O ,\-\-OfflineProv\fR specifies that the file specifier from '-f' is an EK retrieved from offline platform that needs to be provisioned .TP \fB\-E ,\-\-ECcertFile\fR specifies the file used to save the Endorsement Credentials retrieved from the TPM manufacturer provisioning server .TP \fB\-S ,\-\-EKserverAddr\fR specifies to attempt retrieving the Endorsement Credentials from the specified TPM manufacturer provisioning server .TP \fB\-U ,\-\-SSL_NO_VERIFY\fR specifies to attempt connecting with the TPM manufacturer provisioning server with SSL_NO_VERIFY option .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_getmanufec .PP .nf .RS tpm2_getmanufec -e abc123 -o abc123 -P passwd -H 0x81010001-g 0x01 -O -N -U -E ECcert.bin -f ek.bin -S https://tpm.manufacturer.com/ekcertserver/ tpm2_getmanufec -e 1a1b1c -o 1a1b1c -P 123abc -X -H 0x81010001-g 0x01 -O -N -U -E ECcert.bin -f ek.bin -S https://tpm.manufacturer.com/ekcertserver/ .RE .fi tpm2-tools-2.1.0/man/tpm2_getpubak.8.in000066400000000000000000000107031313543155100175510ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_getpubak 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_getpubak\ - Generate attestation key with given algorithm under endorsement hierarchy, make it persistent with given ak handle, and return pub AK and AK name, if any passwd option is missing, assume NULL, default type/alg is 0x1(RSA), default digestAlg is 0xb(SHA256), default signAlg is 0x14(RSASSA) for RSA, 0x18(ECDSA) for ECC .SH SYNOPSIS .B tpm2_getpubak[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-endorsePasswd\fR|\fB\-\-akPasswd\fR|\fB\-\-ownerPasswd\fR|\fB\-\-ekHandle\fR|\fB\-\-akHandle\fR|\fB\-\-alg\fR|\fB\-\-digestAlg\fR|\fB\-\-signAlg\fR|\fB\-\-file\fR|\fB\-\-akName\fR|\fB\-\-passwdInHex\fR|\fB ] .PP Generate attestation key with given algorithm under endorsement hierarchy, make it persistent with given ak handle, and return pub AK and AK name, if any passwd option is missing, assume NULL, default type/alg is 0x1(RSA), default digestAlg is 0xb(SHA256), default signAlg is 0x14(RSASSA) for RSA, 0x18(ECDSA) for ECC .SH DESCRIPTION .B tpm2_getpubak Generate attestation key with given algorithm under endorsement hierarchy, make it persistent with given ak handle, and return pub AK and AK name, if any passwd option is missing, assume NULL, default type/alg is 0x1(RSA), default digestAlg is 0xb(SHA256), default signAlg is 0x14(RSASSA) for RSA, 0x18(ECDSA) for ECC .SH OPTIONS .TP \fB\-e ,\-\-endorsePasswd\fR specifies current endorsement password (string,optional,default:NULL). .TP \fB\-P ,\-\-akPasswd\fR specifies the AK password when created (string,optional,default:NULL). .TP \fB\-o ,\-\-ownerPasswd\fR specifies current owner password (string,optional,default:NULL). .TP \fB\-E ,\-\-ekHandle\fR specifies the handle of EK (hex). .TP \fB\-k ,\-\-akHandle\fR specifies the handle used to make AK persistent (hex). .TP \fB\-g ,\-\-alg\fR specifies the algorithm type of AK (default:0x01/TPM_ALG_RSA): TPM_ALG_RSA 0x0001 TPM_ALG_KEYEDHASH 0x0008 TPM_ALG_ECC 0x0023 .TP \fB\-D ,\-\-digestAlg\fR specifies the algorithm of digest. 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 .TP \fB\-s ,\-\-signAlg\fR specifies the algorithm of sign. 0x0005 TPM_ALG_HMAC 0x0014 TPM_ALG_RSASSA 0x0016 TPM_ALG_RSAPSS 0x0018 TPM_ALG_ECDSA 0x001A TPM_ALG_ECDAA 0x001B TPM_ALG_SM2 0x001C TPM_ALG_ECSCHNORR .TP \fB\-f ,\-\-file\fR specifies the file used to save the public portion of AK. .TP \fB\-n ,\-\-akName\fR specifies the file used to save the ak name. .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format. @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_getpubak .PP .nf .RS tpm2_getpubak -e abc123 -P abc123 -o passwd -E 0x81010001 -k 0x81010002 -f ./ak.pub -n ./ak.name tpm2_getpubak -e 1a1b1c -P 123abc -o 1a1b1c -X -E 0x81010001 -k 0x81010002 -f ./ak.pub -n ./ak.name .RE .fi tpm2-tools-2.1.0/man/tpm2_getpubek.8.in000066400000000000000000000077661313543155100175740ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_getpubek 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_getpubek\ - Generate TCG profile compliant endorsement key(endorsement hierarchy primary object), make it persistent with give ek handle, and return public EK, if any passwd option is missing, assume NULL, default type/alg is 0x1(RSA) Refer to: http://www.trustedcomputinggroup.org/files/static_page_files/7CAA5687-1A4B-B294-D04080D058E86C5F/Credential_Profile_EK_V2.0_R14_published.pdf .SH SYNOPSIS .B tpm2_getpubek[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-endorsePasswd\fR|\fB\-\-ownerPasswd\fR|\fB\-\-ekPasswd\fR|\fB\-\-handle\fR|\fB\-\-alg\fR|\fB\-\-file\fR|\fB\-\-passwdInHex\fR|\fB ] .PP Generate TCG profile compliant endorsement key(endorsement hierarchy primary object), make it persistent with give ek handle, and return public EK, if any passwd option is missing, assume NULL, default type/alg is 0x1(RSA) Refer to: http://www.trustedcomputinggroup.org/files/static_page_files/7CAA5687-1A4B-B294-D04080D058E86C5F/Credential_Profile_EK_V2.0_R14_published.pdf .SH DESCRIPTION .B tpm2_getpubek Generate TCG profile compliant endorsement key(endorsement hierarchy primary object), make it persistent with give ek handle, and return public EK, if any passwd option is missing, assume NULL, default type/alg is 0x1(RSA) Refer to: http://www.trustedcomputinggroup.org/files/static_page_files/7CAA5687-1A4B-B294-D04080D058E86C5F/Credential_Profile_EK_V2.0_R14_published.pdf .SH OPTIONS .TP \fB\-e ,\-\-endorsePasswd\fR specifies current endorse password (string, optional, default:NULL). .TP \fB\-o ,\-\-ownerPasswd\fR specifies current owner password (string, optional, default:NULL). .TP \fB\-P ,\-\-ekPasswd\fR specifies the EK password when created (string, optional, default:NULL). .TP \fB\-H ,\-\-handle\fR specifies the handle used to make EK persistent (hex). .TP \fB\-g ,\-\-alg\fR specifies the algorithm type of EK (default:0x01/TPM_ALG_RSA). TPM_ALG_RSA 0x0001 TPM_ALG_KEYEDHASH 0x0008 TPM_ALG_ECC 0x0023 TPM_ALG_SYMCIPHER 0x0025 .TP \fB\-f ,\-\-file\fR specifies the file used to save the public portion of EK. .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_getpubek .PP .nf .RS tpm2_getpubek -e abc123 -o abc123 -P passwd -H 0x81010001 -g 0x01 -f ek.pub tpm2_getpubek -e 1a1b1c -o 1a1b1c -P 123abc -X -H 0x81010001 -g 0x01 -f ek.pub .RE .fi tpm2-tools-2.1.0/man/tpm2_getrandom.8.in000066400000000000000000000043231313543155100177300ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_getrandom 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_getrandom\ - returns the next SIZE octets from the random number generator. .SH SYNOPSIS .B tpm2_getrandom[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ -\-output\fR|\fB ] SIZE .PP returns the next SIZE octets from the random number generator. .SH DESCRIPTION .B tpm2_getrandom returns the next SIZE octets from the random number generator. .SH OPTIONS .TP \fB\-o ,\-\-output\fR specifies the filename of output. @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_getrandom .PP .nf .RS tpm2_getrandom -o random.out 20 tpm2_getrandom 8 .RE .fi tpm2-tools-2.1.0/man/tpm2_hash.8.in000066400000000000000000000064111313543155100166730ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_hash 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_hash\ - performs a hash operation on a data buffer and returns the results. If the results of the hash will be used in a signing operation that uses a restricted signing key, then the ticket returned by this command can indicate that the hash is safe to sign. .SH SYNOPSIS .B tpm2_hash[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-hierarchy\fR|\fB\-\-halg\fR|\fB\-\-infile\fR|\fB\-\-outfile\fR|\fB\-\-ticket\fR|\fB ] .PP performs a hash operation on a data buffer and returns the results. If the results of the hash will be used in a signing operation that uses a restricted signing key, then the ticket returned by this command can indicate that the hash is safe to sign. .SH DESCRIPTION .B tpm2_hash performs a hash operation on a data buffer and returns the results. If the results of the hash will be used in a signing operation that uses a restricted signing key, then the ticket returned by this command can indicate that the hash is safe to sign. .SH OPTIONS .TP \fB\-H ,\-\-hierarchy\fR hierarchy to use for the ticket e TPM_RH_ENDORSEMENT o TPM_RH_OWNER p TPM_RH_PLATFORM n TPM_RH_NULL .TP \fB\-g ,\-\-halg\fR algorithm for the hash being computed 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 .TP \fB\-I ,\-\-infile\fR file containning the data to be hashed .TP \fB\-o ,\-\-outfile\fR file record the hash result .TP \fB\-t ,\-\-ticket\fR file record the ticket @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_hash .PP .nf .RS tpm2_hash -H -g 0x004 -I -o -t .RE .fi tpm2-tools-2.1.0/man/tpm2_hmac.8.in000066400000000000000000000063721313543155100166660ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_hmac 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_hmac\ - performs an HMAC on the supplied data using the indicated hash algorithm. The caller shall provide proper authorization for use of handle. .SH SYNOPSIS .B tpm2_hmac[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-keyHandle\fR|\fB\-\-keyContext\fR|\fB\-\-pwdk\fR|\fB\-\-halg\fR|\fB\-\-infile\fR|\fB\-\-outfile\fR|\fB\-\-passwdInHex\fR|\fB ] .PP performs an HMAC on the supplied data using the indicated hash algorithm. The caller shall provide proper authorization for use of handle. .SH DESCRIPTION .B tpm2_hmac performs an HMAC on the supplied data using the indicated hash algorithm. The caller shall provide proper authorization for use of handle. .SH OPTIONS .TP \fB\-k ,\-\-keyHandle\fR handle for the symmetric signing key providing the HMAC key .TP \fB\-c ,\-\-keyContext\fR filename of the key context used for the operation .TP \fB\-P ,\-\-pwdk\fR the keyHandle's password, optional .TP \fB\-g ,\-\-halg\fR algorithm for the hash being computed 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 .TP \fB\-I ,\-\-infile\fR file containning the data to be HMACed .TP \fB\-o ,\-\-outfile\fR file record the HMAC result .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format. @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_hmac .PP .nf .RS tpm2_hmac -k 0x81010002 -P abc123 -g 0x004 -I -o tpm2_hmac -c key.context -P abc123 -g 0x004 -I -o tpm2_hmac -k 0x81010002 -P 123abc -X -g 0x004 -I -o .RE .fi tpm2-tools-2.1.0/man/tpm2_listpcrs.8.in000066400000000000000000000074341313543155100176210ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_listpcrs 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_listpcrs\ - display all PCR values in given algorithm with -g, display given PCR values in given algorithms with -L, or if no algorithm is given, output all algs. Output file just contains all returned PCR values in binary format and in 0~23 order and in the requested order if multiple algs were requested. Assume the caller know the pcr value length corresponding to the given bank/algorithm. .SH SYNOPSIS .B tpm2_listpcrs[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-algorithim\fR|\fB\-\-output\fR|\fB\-\-selList\fR|\fB\-\-algs\fR|\fB ] .PP display all PCR values in given algorithm with -g, display given PCR values in given algorithms with -L, or if no algorithm is given, output all algs. Output file just contains all returned PCR values in binary format and in 0~23 order and in the requested order if multiple algs were requested. Assume the caller know the pcr value length corresponding to the given bank/algorithm. .SH DESCRIPTION .B tpm2_listpcrs display all PCR values in given algorithm with -g, display given PCR values in given algorithms with -L, or if no algorithm is given, output all algs. Output file just contains all returned PCR values in binary format and in 0~23 order and in the requested order if multiple algs were requested. Assume the caller know the pcr value length corresponding to the given bank/algorithm. .SH OPTIONS .TP \fB\-g ,\-\-algorithim\fR The algorithm id, optional 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 .TP \fB\-o ,\-\-output\fR The file to hold the PCR values in binary format, optional .TP \fB\-L ,\-\-selList\fR The list of pcr banks and selected PCRs' ids (0~23) for each bank .TP \fB\-s ,\-\-algs\fR Show the supported algs in the PCR banks @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_listpcrs .PP .nf .RS display all PCR values: tpm2_listpcrs display the PCR values with specified bank: tpm2_listpcrs -g 0x04 display the PCR values with specified banks and store in a file: tpm2_listpcrs -L 0x04:16,17,18+0x0b:16,17,18 -o pcrs display the supported algs in the PCR banks: tpm2_listpcrs -s .RE .fi tpm2-tools-2.1.0/man/tpm2_listpersistent.8.in000066400000000000000000000040651313543155100210470ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_listpersistent 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_listpersistent\ - display all defined persistent objects. .SH SYNOPSIS .B tpm2_listpersistent [ COMMON OPTIONS ] [ TCTI OPTIONS ] .PP display all defined persistent objects. .SH DESCRIPTION .B tpm2_listpersistent display all defined persistent objects. .SH OPTIONS @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT @TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_listpersistent .PP .nf .RS tpm2_listpersistent .RE .fi tpm2-tools-2.1.0/man/tpm2_load.8.in000066400000000000000000000057761313543155100167040ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_load 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_load\ - load objects into the TPM, both pub/priv portion are needed. .SH SYNOPSIS .B tpm2_load[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-parent\fR|\fB\-\-contextParent\fR|\fB\-\-pwdp\fR|\fB\-\-pubfile\fR|\fB\-\-privfile\fR|\fB\-\-name\fR|\fB\-\-context\fR|\fB\-\-passwdInHex\fR|\fB ] .PP load objects into the TPM, both pub/priv portion are needed. .SH DESCRIPTION .B tpm2_load load objects into the TPM, both pub/priv portion are needed. .SH OPTIONS .TP \fB\-H ,\-\-parent\fR parent handle .TP \fB\-c ,\-\-contextParent\fR filename for parent context .TP \fB\-P ,\-\-pwdp\fR parent key password, optional .TP \fB\-u ,\-\-pubfile\fR The public portion of the object .TP \fB\-r ,\-\-privfile\fR The sensitive portion of the object .TP \fB\-n ,\-\-name\fR Output file name, containing the name structure .TP \fB\-C ,\-\-context\fR The file to save the object context, optional .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format. @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_load .PP .nf .RS tpm2_load -H 0x80000000 -P abc123 -u -r -n tpm2_load -c parent.context -P abc123 -u -r -n -C object.context tpm2_load -H 0x80000000 -P 123abc -X -u -r -n .RE .fi tpm2-tools-2.1.0/man/tpm2_loadexternal.8.in000066400000000000000000000062031313543155100204310ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_loadexternal 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_loadexternal\ - load an object that is not a Protected Object into the TPM. The command allows loading of a public area or both a public and a sensitive area. .SH SYNOPSIS .B tpm2_loadexternal[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-hierarchy\fR|\fB\-\-pubfile\fR|\fB\-\-privfile\fR|\fB\-\-context\fR|\fB ] .PP load an object that is not a Protected Object into the TPM. The command allows loading of a public area or both a public and a sensitive area. .SH DESCRIPTION .B tpm2_loadexternal load an object that is not a Protected Object into the TPM. The command allows loading of a public area or both a public and a sensitive area. .SH OPTIONS .TP \fB\-H ,\-\-hierarchy\fR Hierarchy with which the object area is associated e TPM_RH_ENDORSEMENT o TPM_RH_OWNER p TPM_RH_PLATFORM n TPM_RH_NULL .TP \fB\-u ,\-\-pubfile\fR The public portion of the object .TP \fB\-r ,\-\-privfile\fR The sensitive portion of the object, optional .TP \fB\-C ,\-\-context\fR The file to save the object context, optional @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_loadexternal .PP .nf .RS Load a public area generated by tpm2_create, tpm2_readpublic or manually tpm2_loadexternal -H -u -C object.context Load a key with sensitive area. Both the public & the senstive areas shall be generated externally. *DON'T* use the areas generated by tpm2_create. tpm2_loadexternal -H n -u -r -C object.context .RE .fi tpm2-tools-2.1.0/man/tpm2_makecredential.8.in000066400000000000000000000053211313543155100207170ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_makecredential 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_makecredential\ - Use the given tpm public key to protect the given secret which are used to encrypt the AK cert. .SH SYNOPSIS .B tpm2_makecredential[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-encKey\fR|\fB\-\-sec\fR|\fB\-\-name\fR|\fB\-\-outFile\fR|\fB ] .PP Use the given tpm public key to protect the given secret which are used to encrypt the AK cert. .SH DESCRIPTION .B tpm2_makecredential Use the given tpm public key to protect the given secret which are used to encrypt the AK cert. .SH OPTIONS .TP \fB\-e ,\-\-encKey\fR A tpm Public Key which was used to wrap the seed .TP \fB\-s ,\-\-sec\fR The secret which will be protected by the key derived from the random seed .TP \fB\-n ,\-\-name\fR The name of the key for which certificate is to be created .TP \fB\-o ,\-\-outFile\fR output file path, recording the two structures output by tpm2_makecredential function @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_makecredential .PP .nf .RS tpm2_makecredential -e -s -n -o .RE .fi tpm2-tools-2.1.0/man/tpm2_nvdefine.8.in000066400000000000000000000057011313543155100175470ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_nvdefine 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_nvdefine\ - Define NV index with given auth value, if passwd not given, assume NULL .SH SYNOPSIS .B tpm2_nvdefine[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-index\fR|\fB\-\-authHandle\fR|\fB\-\-size\fR|\fB\-\-attribute\fR|\fB\-\-handlePasswd\fR|\fB\-\-indexPasswd\fR|\fB\-\-passwdInHex\fR|\fB ] .PP Define NV index with given auth value, if passwd not given, assume NULL .SH DESCRIPTION .B tpm2_nvdefine Define NV index with given auth value, if passwd not given, assume NULL .SH OPTIONS .TP \fB\-x ,\-\-index\fR specifies the index of the NV area. .TP \fB\-a ,\-\-authHandle\fR specifies the handle used to authorize: 0x40000001 (TPM_RH_OWNER) 0x4000000C (TPM_RH_PLATFORM) .TP \fB\-s ,\-\-size\fR specifies the size of data area. .TP \fB\-t ,\-\-attribute\fR specifies the value of attribute in publicInfo struct (need calculate outside). .TP \fB\-P ,\-\-handlePasswd\fR specifies the password of authHandle. .TP \fB\-I ,\-\-indexPasswd\fR specifies the password of NV Index when created. .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_nvdefine .PP .nf .RS tpm2_nvdefine -x 0x1500016 -a 0x40000001 -s 32 -t 0x2000A tpm2_nvdefine -x 0x1500016 -a 0x40000001 -s 32 -t 0x2000A -I 1a1b1c -X .RE .fi tpm2-tools-2.1.0/man/tpm2_nvlist.8.in000066400000000000000000000037541313543155100172760ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_nvlist 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_nvlist\ - display all defined NV indices. .SH SYNOPSIS .B tpm2_nvlist[ COMMON OPTIONS ] [ TCTI OPTIONS ] .PP display all defined NV indices. .SH DESCRIPTION .B tpm2_nvlist display all defined NV indices. .SH OPTIONS @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_nvlist .PP .nf .RS tpm2_nvlist .RE .fi tpm2-tools-2.1.0/man/tpm2_nvread.8.in000066400000000000000000000056201313543155100172300ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_nvread 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_nvread\ - read content from NV index, if any passwd option is missing, assume NULL. .SH SYNOPSIS .B tpm2_nvread[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-index\fR|\fB\-\-authHandle\fR|\fB\-\-handlePasswd\fR|\fB\-\-size\fR|\fB\-\-offset\fR|\fB\-\-passwdInHex\fR|\fB ] .PP read content from NV index, if any passwd option is missing, assume NULL. .SH DESCRIPTION .B tpm2_nvread read content from NV index, if any passwd option is missing, assume NULL. .SH OPTIONS .TP \fB\-x ,\-\-index\fR specifies the index of the NV area. .TP \fB\-a ,\-\-authHandle\fR specifies the handle used to authorize: 0x40000001 (TPM_RH_OWNER) 0x4000000C (TPM_RH_PLATFORM) {NV_INDEX_FIRST:NV_INDEX_LAST} .TP \fB\-P ,\-\-handlePasswd\fR specifies the password of authHandle. .TP \fB\-s ,\-\-size\fR specifies the number of octets to read. .TP \fB\-o ,\-\-offset\fR specifies octet offset into the area This value shall be less than or equal to the size of the nvIndex data. .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_nvread .PP .nf .RS tpm2_nvread -x 0x1500016 -a 0x40000001 -P passwd -s 32 -o 0 tpm2_nvread -x 0x1500016 -a 0x40000001 -P 1a1b1c -s 32 -o 0 -X .RE .fi tpm2-tools-2.1.0/man/tpm2_nvreadlock.8.in000066400000000000000000000052261313543155100201030ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_nvreadlock 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_nvreadlock\ - lock the NV index for further reads until the machine is restarted .SH SYNOPSIS .B tpm2_nvreadlock[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-index\fR|\fB\-\-authHandle\fR|\fB\-\-handlePasswd\fR|\fB\-\-passwdInHex\fR|\fB ] .PP lock the NV index for further reads until the machine is restarted .SH DESCRIPTION .B tpm2_nvreadlock lock the NV index for further reads until the machine is restarted .SH OPTIONS .TP \fB\-x ,\-\-index\fR specifies the index of the NV area. .TP \fB\-a ,\-\-authHandle\fR specifies the handle used to authorize: 0x40000001 (TPM_RH_OWNER) 0x4000000C (TPM_RH_PLATFORM) {NV_INDEX_FIRST:NV_INDEX_LAST} .TP \fB\-P ,\-\-handlePasswd\fR specifies the password of authHandle. .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_nvreadlock .PP .nf .RS tpm2_nvreadlock -x 0x1500016 -a 0x40000001 -P passwd tpm2_nvreadlock -x 0x1500016 -a 0x40000001 -P 1a1b1c -X .RE .fi tpm2-tools-2.1.0/man/tpm2_nvrelease.8.in000066400000000000000000000051451313543155100177370ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_nvrelease 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_nvrelease\ - release NV index, if any passwd option is missing, assume NULL. .SH SYNOPSIS .B tpm2_nvrelease[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-index\fR|\fB\-\-authHandle\fR|\fB\-\-handlePasswd\fR|\fB\-\-passwdInHex\fR|\fB ] .PP release NV index, if any passwd option is missing, assume NULL. .SH DESCRIPTION .B tpm2_nvrelease release NV index, if any passwd option is missing, assume NULL. .SH OPTIONS .TP \fB\-x ,\-\-index\fR specifies the index of the NV area. .TP \fB\-a ,\-\-authHandle\fR specifies the handle used to authorize: 0x40000001 (TPM_RH_OWNER) 0x4000000C (TPM_RH_PLATFORM) .TP \fB\-P ,\-\-handlePasswd\fR specifies the password of authHandle. .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_nvrelease .PP .nf .RS tpm2_nvrelease -x 0x1500016 -a 0x40000001 -P passwd tpm2_nvrelease -x 0x1500016 -a 0x40000001 -P 1a1b1c -X .RE .fi tpm2-tools-2.1.0/man/tpm2_nvwrite.8.in000066400000000000000000000054531313543155100174530ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_nvwrite 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_nvwrite\ - write content from a file to a specified index, if any passwd option is missing, assume NULL. .SH SYNOPSIS .B tpm2_nvwrite[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-index\fR|\fB\-\-authHandle\fR|\fB\-\-handlePasswd\fR|\fB\-\-file\fR|\fB\-\-passwdInHex\fR|\fB ] .PP write content from a file to a specified index, if any passwd option is missing, assume NULL. .SH DESCRIPTION .B tpm2_nvwrite write content from a file to a specified index, if any passwd option is missing, assume NULL. .SH OPTIONS .TP \fB\-x ,\-\-index\fR specifies the index of the NV area. .TP \fB\-a ,\-\-authHandle\fR specifies the handle used to authorize: 0x40000001 (TPM_RH_OWNER) 0x4000000C (TPM_RH_PLATFORM) {NV_INDEX_FIRST:NV_INDEX_LAST} .TP \fB\-P ,\-\-handlePasswd\fR specifies the password of authHandle. .TP \fB\-f ,\-\-file\fR specifies the nv data file. .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_nvwrite .PP .nf .RS tpm2_nvwrite -x 0x1500016 -a 0x40000001 -P passwd -f nv.data tpm2_nvwrite -x 0x1500016 -a 0x40000001 -P 1a1b1c -X -f nv.data .RE .fi tpm2-tools-2.1.0/man/tpm2_quote.8.in000066400000000000000000000063761313543155100171170ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_quote 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_quote\ - Provide quote and signature for given list of PCRs in given algorithm/banks. .SH SYNOPSIS .B tpm2_quote[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-akHandle\fR|\fB\-\-akContext\fR|\fB\-\-akPassword\fR|\fB\-\-idList\fR|\fB\-\-algorithm\fR|\fB\-\-selList\fR|\fB\-\-outFile\fR|\fB\-\-passwdInHex\fR|\fB\-\-qualifyData\fR|\fB ] .PP Provide quote and signature for given list of PCRs in given algorithm/banks. .SH DESCRIPTION .B tpm2_quote Provide quote and signature for given list of PCRs in given algorithm/banks. .SH OPTIONS .TP \fB\-k ,\-\-akHandle\fR Handle of existing AK .TP \fB\-c ,\-\-akContext\fR filename for the existing AK's context .TP \fB\-P ,\-\-akPassword\fR AK handle's Password .TP \fB\-l ,\-\-idList\fR The list of selected PCRs' ids, 0~23 .TP \fB\-g ,\-\-algorithm\fR The algorithm id .TP \fB\-L ,\-\-selList\fR The list of pcr banks and selected PCRs' ids (0~23) for each bank .TP \fB\-o ,\-\-outFile\fR output file path, recording the two structures output by tpm2_quote function .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format. .TP \fB\-q ,\-\-qualifyData\fR Data given as a Hex string to qualify the quote, optional. @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_quote .PP .nf .RS tpm2_quote -k 0x81010002 -P abc123 -g 0x4 -l 16,17,18 -o outFile001 tpm2_quote -c ak.context -P abc123 -g 0x4 -l 16,17,18 -o outFile001 tpm2_quote -k 0x81010002 -g 0x4 -l 16,17,18 -o outFile001 tpm2_quote -c ak.context -g 0x4 -l 16,17,18 -o outFile001 tpm2_quote -k 0x81010002 -P 123abc -X -L 0x4:16,17,18+0xb:16,17,18 -o outFile001 -q 11aa22bb .RE .fi tpm2-tools-2.1.0/man/tpm2_rc_decode.8.in000066400000000000000000000040021313543155100176510ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_rc_decode 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_rc_decode\ - convert error codes from the SAPI and TCTI into human readable errors. Analogous to strerror(3), but for the tpm2 stack. .SH SYNOPSIS .B tpm2_rc_decode .IR error_code .PP Convert a hex error_code into an error message. .SH DESCRIPTION .B tpm2_rc_decode Convert a hex error_code into an error message. .SH EXAMPLES .B tpm2_rc_decode .PP .nf .RS tpm2_rc_decode 0x100 .RE .fi tpm2-tools-2.1.0/man/tpm2_readpublic.8.in000066400000000000000000000046221313543155100200640ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_readpublic 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_readpublic\ - Access to the public area of a loaded object. .SH SYNOPSIS .B tpm2_readpublic[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-object\fR|\fB\-\-contextObject\fR|\fB\-\-opu\fR|\fB ] .PP Access to the public area of a loaded object. .SH DESCRIPTION .B tpm2_readpublic Access to the public area of a loaded object. .SH OPTIONS .TP \fB\-H ,\-\-object\fR The loaded object handle .TP \fB\-c ,\-\-contextObject\fR filename for object context .TP \fB\-o ,\-\-opu\fR The output file path, recording the public portion of the object @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_readpublic .PP .nf .RS tpm2_readpublic -H 0x81010002 --opu tpm2_readpublic -c obj.context --opu .RE .fi tpm2-tools-2.1.0/man/tpm2_rsadecrypt.8.in000066400000000000000000000066041313543155100201340ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_rsadecrypt 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_rsadecrypt\ - performs RSA decryption using the indicated padding scheme according to IETF RFC 3447 (PKCS#1). The scheme of keyHandle should not be TPM_ALG_NULL. The key referenced by keyHandle is required to be an RSA key (TPM_RC_KEY) with the decrypt attribute SET (TPM_RC_ATTRIBUTES). .SH SYNOPSIS .B tpm2_rsadecrypt[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-keyHandle\fR|\fB\-\-keyContext\fR|\fB\-\-pwdk\fR|\fB\-\-inFile\fR|\fB\-\-outFile\fR|\fB\-\-passwdInHex\fR|\fB ] .PP performs RSA decryption using the indicated padding scheme according to IETF RFC 3447 (PKCS#1). The scheme of keyHandle should not be TPM_ALG_NULL. The key referenced by keyHandle is required to be an RSA key (TPM_RC_KEY) with the decrypt attribute SET (TPM_RC_ATTRIBUTES). .SH DESCRIPTION .B tpm2_rsadecrypt performs RSA decryption using the indicated padding scheme according to IETF RFC 3447 (PKCS#1). The scheme of keyHandle should not be TPM_ALG_NULL. The key referenced by keyHandle is required to be an RSA key (TPM_RC_KEY) with the decrypt attribute SET (TPM_RC_ATTRIBUTES). .SH OPTIONS .TP \fB\-k ,\-\-keyHandle\fR the public portion of RSA key to use for decryption .TP \fB\-c ,\-\-keyContext\fR filename of the key context used for the operation .TP \fB\-P ,\-\-pwdk\fR the password of key, optional .TP \fB\-I ,\-\-inFile\fR Input file path, containing the data to be decrypted .TP \fB\-o ,\-\-outFile\fR Output file path, record the decrypted data .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format. @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_rsadecrypt .PP .nf .RS tpm2_rsadecrypt -k 0x81010001 -I -o tpm2_rsadecrypt -k 0x81010001 -P 123abc -X -I -o .RE .fi tpm2-tools-2.1.0/man/tpm2_rsaencrypt.8.in000066400000000000000000000062641313543155100201500ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_rsaencrypt 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_rsaencrypt\ - performs RSA encryption using the indicated padding scheme according to IETF RFC 3447. The scheme of keyHandle should not be TPM_ALG_NULL. The key referenced by keyHandle is required to be an RSA key (TPM_RC_KEY) with the decrypt attribute SET (TPM_RC_ATTRIBUTES). .SH SYNOPSIS .B tpm2_rsaencrypt[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-keyHandle\fR|\fB\-\-keyContext\fR|\fB\-\-inFile\fR|\fB\-\-outFile\fR|\fB ] .PP performs RSA encryption using the indicated padding scheme according to IETF RFC 3447. The scheme of keyHandle should not be TPM_ALG_NULL. The key referenced by keyHandle is required to be an RSA key (TPM_RC_KEY) with the decrypt attribute SET (TPM_RC_ATTRIBUTES). .SH DESCRIPTION .B tpm2_rsaencrypt performs RSA encryption using the indicated padding scheme according to IETF RFC 3447. The scheme of keyHandle should not be TPM_ALG_NULL. The key referenced by keyHandle is required to be an RSA key (TPM_RC_KEY) with the decrypt attribute SET (TPM_RC_ATTRIBUTES). .SH OPTIONS .TP \fB\-k ,\-\-keyHandle\fR the public portion of RSA key to use for encryption .TP \fB\-c ,\-\-keyContext\fR filename of the key context used for the operation .TP \fB\-I ,\-\-inFile\fR Input file path, containing the data to be encrypted .TP \fB\-o ,\-\-outFile\fR Output file path, record the encrypted data @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_rsaencrypt .PP .nf .RS tpm2_rsaencrypt -k 0x81010001 -I -o tpm2_rsaencrypt -c key.context -I -o .RE .fi tpm2-tools-2.1.0/man/tpm2_send_command.8.in000066400000000000000000000050641313543155100204020ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_send_command 8 "NOVEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_send_command \- Send a command to the TPM using the specified TCTI. .SH SYNOPSIS .B tpm2_send_command [\fBCOMMON OPTIONS\fR ] [\fBTCTI OPTIONS\fR ] .SH DESCRIPTION .B tpm2_send_command is a command line tool used to send a TPM command to the TPM. The command is read from stdin as a binary stream and transmitted to the TPM using the TCTI specified by the caller. The response received from the TPM is written to stdout. Likely the caller will want to redirect this to a file or into a program to decode and display the response in a human readable form. .SH OPTIONS @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT @TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES Assuming that the caller has a binary TPM command buffer in a file named .\"cmd.bin\" .B tpm2_send_command may be used to send this to the TPM simulator using the following command: .PP .nf .RS tpm2_send_command --tcti=device < tpm2-command.bin > tpm2-response.bin .RE .fi tpm2-tools-2.1.0/man/tpm2_sign.8.in000066400000000000000000000100541313543155100167060ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_sign 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_sign\ - sign an externally provided hash with the specified symmetric or asymmetric signing key. If keyHandle references a restricted signing key, then validation shall be provided, indicating that the TPM performed the hash of the data and validation shall indicate that hashed data did not start with TPM_GENERATED_VALUE. The scheme of keyHandle should not be TPM_ALG_NULL. .SH SYNOPSIS .B tpm2_sign[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-keyHandle\fR|\fB\-\-keyContext\fR|\fB\-\-pwdk\fR|\fB\-\-halg\fR|\fB\-\-msg\fR|\fB\-\-ticket\fR|\fB\-\-sig\fR|\fB\-\-passwdInHex\fR|\fB ] .PP sign an externally provided hash with the specified symmetric or asymmetric signing key. If keyHandle references a restricted signing key, then validation shall be provided, indicating that the TPM performed the hash of the data and validation shall indicate that hashed data did not start with TPM_GENERATED_VALUE. The scheme of keyHandle should not be TPM_ALG_NULL. .SH DESCRIPTION .B tpm2_sign sign an externally provided hash with the specified symmetric or asymmetric signing key. If keyHandle references a restricted signing key, then validation shall be provided, indicating that the TPM performed the hash of the data and validation shall indicate that hashed data did not start with TPM_GENERATED_VALUE. The scheme of keyHandle should not be TPM_ALG_NULL. .SH OPTIONS .TP \fB\-k ,\-\-keyHandle\fR Handle of key that will perform signing .TP \fB\-c ,\-\-keyContext\fR filename of the key context used for the operation .TP \fB\-P ,\-\-pwdk\fR the password of key, optional .TP \fB\-g ,\-\-halg\fR the hash algorithm used to digest the message 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 .TP \fB\-m ,\-\-msg\fR the message file, containning the content to be digested .TP \fB\-t ,\-\-ticket\fR the ticket file, containning the validation structure, optional .TP \fB\-s ,\-\-sig\fR the signature file, record the signature structure .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format. @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_sign .PP .nf .RS tpm2_sign -k 0x81010001 -P abc123 -g 0x000B -m -s -t tpm2_sign -c key.context - abc123 -g 0x000B -m -s -t tpm2_sign -k 0x81010001 -P 123abc -X -g 0x000B -m -s -t .RE .fi tpm2-tools-2.1.0/man/tpm2_startup.8.in000066400000000000000000000050501313543155100174500ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_startup 8 "NOVEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_startup \- Send a TPM2_Startup command with either TPM_SU_CLEAR or TPM_SU_STATE. .SH SYNOPSIS .B tpm2_startup [ \fBCOMMON OPTIONS\fR ] [ \fBTCTI OPTIONS\fR ] [ \fB\-\-clear\fR|\fB\-\-state\fR ] .PP Send a TPM2_Startup command, with the startupType set to TPM_SU_CLEAR using the specified TCTI. .SH DESCRIPTION .B tpm2_send_command is a command line tool used to send a TPM command to the TPM. The command is read from stdin as a binary stream and transmitted to the TPM using the TCTI specified by the caller. The response received from the TPM is written to stdout. Likely the caller will want to redirect this to a file or into a program to decode and display the response in a human readable form. .SH OPTIONS .TP \fB\-c,\ \-\-clear\fR Startup type sent will be TPM_SU_CLEAR. .TP \fB\-s,\ \-\-state\fR Startup type sent will be TPM2_SU_STATE. @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT @TCTI_ENVIRONMENT_INCLUDE@ tpm2-tools-2.1.0/man/tpm2_takeownership.8.in000066400000000000000000000070101313543155100206270ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_takeownership 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_takeownership\ - Inserting authorization values for the ownerAuth, endorsementAuth, and lockoutAuth, if any passwd option is missing, assume NULL. .SH SYNOPSIS .B tpm2_takeownership[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-ownerPasswd\fR|\fB\-\-endorsePasswd\fR|\fB\-\-lockPasswd\fR|\fB\-\-oldOwnerPasswd\fR|\fB\-\-oldEndorsePasswd\fR|\fB\-\-oldLockPasswd\fR|\fB\-\-passwdInHex\fR|\fB\-\-clear\fR|\fB ] .PP Inserting authorization values for the ownerAuth, endorsementAuth, and lockoutAuth, if any passwd option is missing, assume NULL. .SH DESCRIPTION .B tpm2_takeownership Inserting authorization values for the ownerAuth, endorsementAuth, and lockoutAuth, if any passwd option is missing, assume NULL. .SH OPTIONS .TP \fB\-o ,\-\-ownerPasswd\fR new Owner authorization value (string, optional, default:NULL). .TP \fB\-e ,\-\-endorsePasswd\fR new Endorsement authorization value (string, optional, default:NULL). .TP \fB\-l ,\-\-lockPasswd\fR new Lockout authorization value (string, optional, default:NULL). .TP \fB\-O ,\-\-oldOwnerPasswd\fR old Owner authorization (string, optional, default:NULL). .TP \fB\-E ,\-\-oldEndorsePasswd\fR old Endorsement authorization (string, optional, default:NULL). .TP \fB\-L ,\-\-oldLockPasswd\fR old Lockout authorization (string, optional, default:NULL). .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format .TP \fB\-c ,\-\-clear\fR [-L [-X]] clears the 3 authorizations values with lockout auth. @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_takeownership .PP .nf .RS Set ownerAuth, endorsementAuth and lockoutAuth to emptyAuth: tpm2_takeownership -c -L old Set ownerAuth, endorsementAuth and lockoutAuth to a newAuth: tpm2_takeownership -o new -e new -l new -O old -E old -L old tpm2_takeownership -o 2a2b2c -e 2a2b2c -l 2a2b2c -O 1a1b1c -E 1a1b1c -L 1a1b1c -X .RE .fi tpm2-tools-2.1.0/man/tpm2_unseal.8.in000066400000000000000000000051601313543155100172370ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_unseal 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_unseal\ - returns the data in a loaded Sealed Data Object. .SH SYNOPSIS .B tpm2_unseal[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-item\fR|\fB\-\-itemContext\fR|\fB\-\-pwdi\fR|\fB\-\-outfile\fR|\fB\-\-passwdInHex\fR|\fB ] .PP returns the data in a loaded Sealed Data Object. .SH DESCRIPTION .B tpm2_unseal returns the data in a loaded Sealed Data Object. .SH OPTIONS .TP \fB\-H ,\-\-item\fR item handle, handle of a loaded data object .TP \fB\-c ,\-\-itemContext\fR filename for item context .TP \fB\-P ,\-\-pwdi\fR item handle password, optional .TP \fB\-o ,\-\-outfile\fR Output file name, containing the unsealed data .TP \fB\-X ,\-\-passwdInHex\fR passwords given by any options are hex format. @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_unseal .PP .nf .RS tpm2_unseal -H 0x81010001 -P abc123 -o tpm2_unseal -c item.context -P abc123 -o tpm2_unseal -H 0x81010001 -P 123abc -X -o .RE .fi tpm2-tools-2.1.0/man/tpm2_verifysignature.8.in000066400000000000000000000106271313543155100212020ustar00rootroot00000000000000.\" Copyright (c) 2016, Intel Corporation .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" 3. Neither the name of Intel Corporation nor the names of its contributors .\" may be used to endorse or promote products derived from this software without .\" specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF .\" THE POSSIBILITY OF SUCH DAMAGE. .TH tpm2_verifysignature 8 "DECEMBER 2016" Intel "tpm2.0-tools" .SH NAME tpm2_verifysignature\ - uses loaded keys to validate a signature on a message with the message digest passed to the TPM. If the signature check succeeds, then the TPM will produce a TPMT_TK_VERIFIED. Otherwise, the TPM shall return TPM_RC_SIGNATURE. If keyHandle references an asymmetric key, only the public portion of the key needs to be loaded. If keyHandle references a symmetric key, both the public and private portions need to be loaded. .SH SYNOPSIS .B tpm2_verifysignature[ COMMON OPTIONS ] [ TCTI OPTIONS ] [ \fB\-\-keyHandle\fR|\fB\-\-keyContext\fR|\fB\-\-halg\fR|\fB\-\-msg\fR|\fB\-\-digest\fR|\fB\-\-sig\fR|\fB\-\-raw\fR|\fB\-\-ticket\fR|\fB ] .PP uses loaded keys to validate a signature on a message with the message digest passed to the TPM. If the signature check succeeds, then the TPM will produce a TPMT_TK_VERIFIED. Otherwise, the TPM shall return TPM_RC_SIGNATURE. If keyHandle references an asymmetric key, only the public portion of the key needs to be loaded. If keyHandle references a symmetric key, both the public and private portions need to be loaded. .SH DESCRIPTION .B tpm2_verifysignature uses loaded keys to validate a signature on a message with the message digest passed to the TPM. If the signature check succeeds, then the TPM will produce a TPMT_TK_VERIFIED. Otherwise, the TPM shall return TPM_RC_SIGNATURE. If keyHandle references an asymmetric key, only the public portion of the key needs to be loaded. If keyHandle references a symmetric key, both the public and private portions need to be loaded. .SH OPTIONS .TP \fB\-k ,\-\-keyHandle\fR handle of public key that will be used in the validation .TP \fB\-c ,\-\-keyContext\fR filename of the key context used for the operation .TP \fB\-g ,\-\-halg\fR the hash algorithm used to digest the message 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 .TP \fB\-m ,\-\-msg\fR the input message file, containning the content to be digested .TP \fB\-D ,\-\-digest\fR the input hash file, containning the hash of the message. If this argument been chosed, the argument '-m(--msg)' and '-g(--halg)' is no need .TP \fB\-s ,\-\-sig\fR the input signature file, containning the signature to be tested .TP \fB\-r ,\-\-raw\fR set the input signature file to raw type, default TPMT_SIGNATURE, optional .TP \fB\-t ,\-\-ticket\fR the ticket file, record the validation structure @COMMON_OPTIONS_INCLUDE@ @TCTI_OPTIONS_INCLUDE@ .SH ENVIRONMENT\@TCTI_ENVIRONMENT_INCLUDE@ .SH EXAMPLES .B tpm2_verifysignature .PP .nf .RS tpm2_verifysignature -k 0x81010001 -g 0x000B -m -s -t tpm2_verifysignature -k 0x81010001 -D -s -t tpm2_verifysignature -c key.context -g 0x000B -m -s -t .RE .fi tpm2-tools-2.1.0/manual000066400000000000000000001211711313543155100147360ustar00rootroot00000000000000tpm2.0-tools Manual =================== 1. Common steps before running any tools from tpm2.0-tools First of all, clone TPM2.0-TSS and follow the build process to install it. Then follow below steps for tpm2.0-tools. Build: $ ./bootstrap $ ./configure $ make Install: $ sudo make install Launch resourcemgr daemon: $ resourcemgr or $ resourcemgr -sim -tpmhost The resourcemgr can connect to either physical tpm or remote MS/IBM simulator, refer to the help of resourcemgr for details. 2. running tools All tool executables are built under ./tools/. So once resourcemgr is up: $ cd ./tools $ ./tpm2_xxx -x... Or if the tools are installed: $ tpm2_xxx -x... 3. tool usages common options This collection of options are common to many programs and provide information that many users may expect. -h, --help Display a manual describing the tool and its usage. -v, --version Display version information for this tool. -V, --verbose Increase the information that the tool prints to the console during its execution. tcti options (depends on configure time options for tcti's.) This collection of options are used to configure the varous TCTI modules available. -T, --tcti Select the TCTI used for communication with the next component down the TSS stack. In most configurations this will be the TPM but it could be a simulator or proxy. Supported TCTIs are or “device†or “socket†. -d, --device-file Specify the TPM device file for use by the device TCTI. The default is /dev/tpm0. -R, --socket-address Specify the domain name or IP address used by the socket TCTI. The default is 127.0.0.1. -p, --socket-port Specify the port number used by the socket TCTI. The default is 2321. Subset 1: NV tools ------------------ * tpm2_nvdefine Define NV index with given auth value, if passwd not given, assume NULL Usage: tpm2_nvdefine [-x/--index ] [-a/--authHandle ] [-s/--size ] [-t/--attribute ] [-P/--handlePasswd ] [-I/--indexPasswd ] [-X/--passwdInHex] where: -x/--index specifies the index of the NV area. -a/--authHandle specifies the handle used to authorize: 0x40000001 (TPM_RH_OWNER) 0x4000000C (TPM_RH_PLATFORM) -s/--size specifies the size of data area. -t/--attribute specifies the value of attribute in publicInfo struct (need calculate outside). -P/--handlePasswd specifies the password of authHandle. -I/--indexPasswd specifies the password of NV Index when created. -X/--passwdInHex passwords given by any options are hex format example: tpm2_nvdefine -x 0x1500016 -a 0x40000001 -s 32 -t 0x2000A tpm2_nvdefine -x 0x1500016 -a 0x40000001 -s 32 -t 0x2000A -I 1a1b1c -X * tpm2_nvrelease release NV index, if any passwd option is missing, assume NULL. Usage: tpm2_nvrelease [-x/--index ] [-a/--authHandle ] [-P/--handlePasswd ] [-X/--passwdInHex] where: -x/--index specifies the index of the NV area. -a/--authHandle specifies the handle used to authorize: 0x40000001 (TPM_RH_OWNER) 0x4000000C (TPM_RH_PLATFORM) -P/--handlePasswd specifies the password of authHandle. -X/--passwdInHex passwords given by any options are hex format example: tpm2_nvrelease -x 0x1500016 -a 0x40000001 -P passwd tpm2_nvrelease -x 0x1500016 -a 0x40000001 -P 1a1b1c -X * tpm2_nvread read content from NV index, if any passwd option is missing, assume NULL. Usage: tpm2_nvread [-x/--index ] [-a/--authHandle ] [-P/--handlePasswd ] [-s/--size ] [-o/--offset ] [-X/--passwdInHex] where: -x/--index specifies the index of the NV area. -a/--authHandle specifies the handle used to authorize: 0x40000001 (TPM_RH_OWNER) 0x4000000C (TPM_RH_PLATFORM) {NV_INDEX_FIRST:NV_INDEX_LAST} -P/--handlePasswd specifies the password of authHandle. -s/--size specifies the number of octets to read. -o/--offset specifies octet offset into the area This value shall be less than or equal to the size of the nvIndex data. -X/--passwdInHex passwords given by any options are hex format example: tpm2_nvread -x 0x1500016 -a 0x40000001 -P passwd -s 32 -o 0 tpm2_nvread -x 0x1500016 -a 0x40000001 -P 1a1b1c -s 32 -o 0 -X * tpm2_nvreadlock lock the NV index for further reads until the machine is restarted Usage: tpm2_nvreadlock [-x/--index ] [-a/--authHandle ] [-P/--handlePasswd ] [-X/--passwdInHex] where: -x/--index specifies the index of the NV area. -a/--authHandle specifies the handle used to authorize: 0x40000001 (TPM_RH_OWNER) 0x4000000C (TPM_RH_PLATFORM) {NV_INDEX_FIRST:NV_INDEX_LAST} -P/--handlePasswd specifies the password of authHandle. -X/--passwdInHex passwords given by any options are hex format example: tpm2_nvreadlock -x 0x1500016 -a 0x40000001 -P passwd tpm2_nvreadlock -x 0x1500016 -a 0x40000001 -P 1a1b1c -X * tpm2_nvwrite write content from a file to a specified index, if any passwd option is missing, assume NULL. Usage: tpm2_nvwrite [-x/--index ] [-a/--authHandle ] [-P/--handlePasswd ] [-f/--file ] [-X/--passwdInHex] where: -x/--index specifies the index of the NV area. -a/--authHandle specifies the handle used to authorize: 0x40000001 (TPM_RH_OWNER) 0x4000000C (TPM_RH_PLATFORM) {NV_INDEX_FIRST:NV_INDEX_LAST} -P/--handlePasswd specifies the password of authHandle. -f/--file specifies the nv data file. -X/--passwdInHex passwords given by any options are hex format example: tpm2_nvwrite -x 0x1500016 -a 0x40000001 -P passwd -f nv.data tpm2_nvwrite -x 0x1500016 -a 0x40000001 -P 1a1b1c -X -f nv.data * tpm2_nvlist display all defined NV indices. Usage: tpm2_nvlist example: tpm2_nvlist Subset 2: Attestation tools --------------------------- * tpm2_takeownership Inserting authorization values for the ownerAuth, endorsementAuth, and lockoutAuth, if any passwd option is missing, assume NULL. Usage: tpm2_takeownership [-e/--endorsePasswd ] [-o/--ownerPasswd ] [-l/--lockPasswd ] [-E/--oldEndorsePasswd ] [-O/--oldOwnerPasswd ] [-L/--oldLockPasswd ] [-X/--passwdInHex] where: -o/--ownerPasswd new Owner authorization value (string, optional, default:NULL). -e/--endorsePasswd new Endorsement authorization value (string, optional, default:NULL). -l/--lockPasswd new Lockout authorization value (string, optional, default:NULL). -O/--oldOwnerPasswd old Owner authorization (string, optional, default:NULL). -E/--oldEndorsePasswd old Endorsement authorization (string, optional, default:NULL). -L/--oldLockPasswd old Lockout authorization (string, optional, default:NULL). -X/--passwdInHex passwords given by any options are hex format -c/--clear [-L [-X]] clears the 3 authorizations values with lockout auth. example: Set ownerAuth, endorsementAuth and lockoutAuth to emptyAuth: tpm2_takeownership -c -L old Set ownerAuth, endorsementAuth and lockoutAuth to a newAuth: tpm2_takeownership -o new -e new -l new -O old -E old -L old tpm2_takeownership -o 2a2b2c -e 2a2b2c -l 2a2b2c -O 1a1b1c -E 1a1b1c -L 1a1b1c -X * tpm2_getpubek Generate TCG profile compliant endorsement key(endorsement hierarchy primary object), make it persistent with give ek handle, and return public EK, if any passwd option is missing, assume NULL, default type/alg is 0x1(RSA) Refer to: http://www.trustedcomputinggroup.org/files/static_page_files/7CAA5687-1A4B-B294-D04080D058E86C5F/Credential_Profile_EK_V2.0_R14_published.pdf Usage: tpm2_getpubek [-e/--endorsePasswd ] [-o/--ownerPasswd ] [-P/--ekPasswd ] [-H/--handle ] [-g/--alg ] [-f/--file ] [-X/--passwdInHex] where: -e/--endorsePasswd specifies current endorse password (string, optional, default:NULL). -o/--ownerPasswd specifies current owner password (string, optional, default:NULL). -P/--ekPasswd specifies the EK password when created (string, optional, default:NULL). -H/--handle specifies the handle used to make EK persistent (hex). -g/--alg specifies the algorithm type of EK (default:0x01/TPM_ALG_RSA). TPM_ALG_RSA 0x0001 TPM_ALG_KEYEDHASH 0x0008 TPM_ALG_ECC 0x0023 TPM_ALG_SYMCIPHER 0x0025 -f/--file specifies the file used to save the public portion of EK. -X/--passwdInHex passwords given by any options are hex format example: tpm2_getpubek -e abc123 -o abc123 -P passwd -H 0x81010001 -g 0x01 -f ek.pub tpm2_getpubek -e 1a1b1c -o 1a1b1c -P 123abc -X -H 0x81010001 -g 0x01 -f ek.pub * tpm2_getmanufec Retrieve the Endorsement Credential Certificate for the TPM endorsement key from the TPM manufacturer's endorsement certificate hosting server Usage: tpm2_getmanufec [-e/--endorsePasswd ] [-o/--ownerPasswd ] [-P/--ekPasswd ] [-H/--handle ] [-g/--alg ] [-f/--file ] [-S/--EKserverAddr ] [-E/--ECcertFile ] [-X/--passwdInHex] where: -e/--endorsePasswd specifies current endorse password (string, optional,default:NULL). -o/--ownerPasswd specifies current owner password (string, optional,default:NULL). -P/--ekPasswd specifies the EK password when created (string,optional,default:NULL). -H/--handle specifies the handle used to make EK persistent (hex). -g/--alg specifies the algorithm type of EK (default:0x01/TPM_ALG_RSA). -f/--file specifies the file used to save the public portion of EK. -N/--NonPersistent specifies to readout the EK public without making it persistent -O/--OfflineProv specifies that the file specifier from '-f' is an EK retrieved from offline platform that needs to be provisioned -E/--ECcertFile specifies the file used to save the Endorsement Credentials retrieved from the TPM manufacturer provisioning server -S/--EKserverAddr specifies to attempt retrieving the Endorsement Credentials from the specified TPM manufacturer provisioning server -U/--SSL_NO_VERIFY specifies to attempt connecting with the TPM manufacturer provisioning server with SSL_NO_VERIFY option -X/--passwdInHex passwords given by any options are hex format example: tpm2_getmanufec -e abc123 -o abc123 -P passwd -H 0x81010001-g 0x01 -O -N -U -E ECcert.bin -f ek.bin -S https://tpm.manufacturer.com/ekcertserver/ tpm2_getmanufec -e 1a1b1c -o 1a1b1c -P 123abc -X -H 0x81010001-g 0x01 -O -N -U -E ECcert.bin -f ek.bin -S https://tpm.manufacturer.com/ekcertserver/ * tpm2_getpubak Generate attestation key with given algorithm under endorsement hierarchy, make it persistent with given ak handle, and return pub AK and AK name, if any passwd option is missing, assume NULL, default type/alg is 0x1(RSA), default digestAlg is 0xb(SHA256), default signAlg is 0x14(RSASSA) for RSA, 0x18(ECDSA) for ECC Usage: tpm2_getpubak [-e/--endorsePasswd ] [-P/--akPasswd ] [-o/--ownerPasswd ] [-E/--ekHandle ] [-k/--akHandle ] [-g/--alg ] [-D/--digestAlg ] [-s/--signAlg ] [-f/--file ] [-n/--akName ] [-X/--passwdInHex] where: -e/--endorsePasswd specifies current endorsement password (string,optional,default:NULL). -P/--akPasswd specifies the AK password when created (string,optional,default:NULL). -o/--ownerPasswd specifies current owner password (string,optional,default:NULL). -E/--ekHandle specifies the handle of EK (hex). -k/--akHandle specifies the handle used to make AK persistent (hex). -g/--alg specifies the algorithm type of AK (default:0x01/TPM_ALG_RSA): TPM_ALG_RSA 0x0001 TPM_ALG_KEYEDHASH 0x0008 TPM_ALG_ECC 0x0023 -D/--digestAlg specifies the algorithm of digest. 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 -s/--signAlg specifies the algorithm of sign. 0x0005 TPM_ALG_HMAC 0x0014 TPM_ALG_RSASSA 0x0016 TPM_ALG_RSAPSS 0x0018 TPM_ALG_ECDSA 0x001A TPM_ALG_ECDAA 0x001B TPM_ALG_SM2 0x001C TPM_ALG_ECSCHNORR -f/--file specifies the file used to save the public portion of AK. -n/--akName specifies the file used to save the ak name. -X/--passwdInHex passwords given by any options are hex format. example: tpm2_getpubak -e abc123 -P abc123 -o passwd -E 0x81010001 -k 0x81010002 -f ./ak.pub -n ./ak.name tpm2_getpubak -e 1a1b1c -P 123abc -o 1a1b1c -X -E 0x81010001 -k 0x81010002 -f ./ak.pub -n ./ak.name * tpm2_akparse parse the algorithm and key values in TPM2B_PUBLIC struct which input via file inputFile, and output the key into file akKeyFile. Usage: tpm2_akparse [-f inputFile][-k akKeyFile] where: -f Specifies the file used to be parsed. -k Specifies the file used to save ak key. example: tpm2_akparse -f ./ak.data -k ./ak.key * tpm2_makecredential Use the given tpm public key to protect the given secret which are used to encrypt the AK cert. Usage: -e, --encKey A tpm Public Key which was used to wrap the seed -s, --sec The secret which will be protected by the key derived from the random seed -n, --name The name of the key for which certificate is to be created -o, --outFile output file path, recording the two structures output by tpm2_makecredential function example: tpm2_makecredential -e -s -n -o * tpm2_activatecredential Verify that the given content is protected with given keyHandle for given handle, and then decrypt and return the secret, if any passwd option is missing, assume NULL. Currently only support using TCG profile compliant EK as the keyHandle. Usage: -H, --handle Handle of the object associated with the created certificate by CA -c, --context filename for handle context -k, --keyHandle Loaded key used to decrypt the the random seed -C, --keyContext filename for keyHandle context -P, --Password the handle's password, optional -e, --endorsePasswd the endorsement password, optional -f, --inFile Input file path, containing the two structures needed by tpm2_activatecredential function -o, --outFile Output file path, record the secret to decrypt the certificate -X, --passwdInHex passwords given by any options are hex format. example: tpm2_activatecredential -H 0x81010002 -k 0x81010001 -P abc123 -e abc123 -f -o tpm2_activatecredential -c ak.context -C ek.context -P abc123 -e abc123 -f -o tpm2_activatecredential -H 0x81010002 -k 0x81010001 -P 123abc -e 1a1b1c -X -f -o * tpm2_listpcrs display all PCR values in given algorithm with -g, display given PCR values in given algorithms with -L, or if no algorithm is given, output all algs. Output file just contains all returned PCR values in binary format and in 0~23 order and in the requested order if multiple algs were requested. Assume the caller know the pcr value length corresponding to the given bank/algorithm. Usage: -g, --algorithim The algorithm id, optional 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 -o, --output The file to hold the PCR values in binary format, optional -L, --selList The list of pcr banks and selected PCRs' ids (0~23) for each bank -s, --algs Show the supported algs in the PCR banks example: display all PCR values: tpm2_listpcrs display the PCR values with specified bank: tpm2_listpcrs -g 0x04 display the PCR values with specified banks and store in a file: tpm2_listpcrs -L 0x04:16,17,18+0x0b:16,17,18 -o pcrs display the supported algs in the PCR banks: tpm2_listpcrs -s * tpm2_quote Provide quote and signature for given list of PCRs in given algorithm/banks. Usage: -k, --akHandle Handle of existing AK -c, --akContext filename for the existing AK's context -P, --akPassword AK handle's Password -l, --idList The list of selected PCRs' ids, 0~23 -g, --algorithm The algorithm id -L, --selList The list of pcr banks and selected PCRs' ids (0~23) for each bank -o, --outFile output file path, recording the two structures output by tpm2_quote function -X, --passwdInHex passwords given by any options are hex format. -q, --qualifyData Data given as a Hex string to qualify the quote, optional. Note: -L option & -g/-l options are mutually exclusive. -g/-l can be used to specify PCRs in one bank, and -L can be used to specify PCRs in any number of existing banks. example: tpm2_quote -k 0x81010002 -P abc123 -g 0x4 -l 16,17,18 -o outFile001 tpm2_quote -c ak.context -P abc123 -g 0x4 -l 16,17,18 -o outFile001 tpm2_quote -k 0x81010002 -g 0x4 -l 16,17,18 -o outFile001 tpm2_quote -c ak.context -g 0x4 -l 16,17,18 -o outFile001 tpm2_quote -k 0x81010002 -P 123abc -X -L 0x4:16,17,18+0xb:16,17,18 -o outFile001 -q 11aa22bb * tpm2_listpersistent display all defined persistent objects. Usage: tpm2_listpersistent example: tpm2_listpersistent Subset 3: Key management tools ------------------------------ * tpm2_createprimary create a Primary Object under one of the Primary Seeds or a Temporary Object under TPM_RH_NULL. Usage: -A, --auth the authorization used to authorize thecommands o TPM_RH_OWNER p TPM_RH_PLATFORM e TPM_RH_ENDORSEMENT n TPM_RH_NULL -P, --pwdp password for hierarchy, optional -K, --pwdk password for key, optional -g, --halg algorithm used for computing the Name of the object 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 -G, --kalg algorithm associated with this object 0x0001 TPM_ALG_RSA 0x0008 TPM_ALG_KEYEDHASH 0x0023 TPM_ALG_ECC 0x0025 TPM_ALG_SYMCIPHER -C, --context The file to save the object context, optional -X, --passwdInHex passwords given by any options are hex format. example: tpm2_createprimary -A e -P abc123 -K def456 -g 0x000B -G 0x0008 tpm2_createprimary -A e -P abc123 -K def456 -g 0x000B -G 0x0008 -C ek.context tpm2_createprimary -A e -P 1a2b3c -K 456def -X -g 0x000B -G 0x0008 * tpm2_create create an object that can be loaded into a TPM using tpm2_load. The object will need to be loaded before it may be used. Usage: -H, --parent parent handle -c, --contextParent filename for parent context -P, --pwdp password for parent key, optional -K, --pwdk password for key, optional -g, --halg algorithm used for computing the Name of the object 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 -G, --kalg algorithm associated with this object 0x0001 TPM_ALG_RSA 0x0008 TPM_ALG_KEYEDHASH 0x0023 TPM_ALG_ECC 0x0025 TPM_ALG_SYMCIPHER -A, --objectAttribute object attributes, optional -I, --inFile data file to be sealed, optional -L, --pol the input policy file, optional -o, --opu the output file which contains the public key, optional -O, --opr the output file which contains the private key, optional -X, --passwdInHex passwords given by any options are hex format. example: tpm2_create -H 0x81010001 -P abc123 -K def456 -g 0x000B -G 0x0008 -I data.File -o opu.File tpm2_create -c parent.context -P abc123 -K def456 -g 0x000B -G 0x0008 -I data.File -o opu.File tpm2_create -H 0x81010001 -P 123abc -K 456def -X -g 0x000B -G 0x0008 -I data.File -o opu.File * tpm2_evictcontrol allows a transient object to be made persistent or a persistent object to be evicted. Usage: -A, --auth the authorization used to authorize the commands o TPM_RH_OWNER p TPM_RH_PLATFORM -H, --handle the handle of a loaded object -c, --context filename for object context -S, --persistent the persistent handle for objectHandle -P, --pwda authrization password, optional -X, --passwdInHex passwords given by any options are hex format. example: tpm2_evictcontrol -A o -c object.context -S 0x81010002 -P abc123 tpm2_evictcontrol -A o -H 0x81010002 -S 0x81010002 -P abc123 tpm2_evictcontrol -A o -H 0x81010002 -S 0x81010002 -P 123abc -X * tpm2_load load objects into the TPM, both pub/priv portion are needed. Usage: -H, --parent parent handle -c, --contextParent filename for parent context -P, --pwdp parent key password, optional -u, --pubfile The public portion of the object -r, --privfile The sensitive portion of the object -n, --name Output file name, containing the name structure -C, --context The file to save the object context, optional -X, --passwdInHex passwords given by any options are hex format. example: tpm2_load -H 0x80000000 -P abc123 -u -r -n tpm2_load -c parent.context -P abc123 -u -r -n -C object.context tpm2_load -H 0x80000000 -P 123abc -X -u -r -n * tpm2_loadexternal load an object that is not a Protected Object into the TPM. The command allows loading of a public area or both a public and a sensitive area. Usage: -H, --hierarchy Hierarchy with which the object area is associated e TPM_RH_ENDORSEMENT o TPM_RH_OWNER p TPM_RH_PLATFORM n TPM_RH_NULL -u, --pubfile The public portion of the object -r, --privfile The sensitive portion of the object, optional -C, --context The file to save the object context, optional example: Load a public area generated by tpm2_create, tpm2_readpublic or manually tpm2_loadexternal -H -u -C object.context Load a key with sensitive area. Both the public & the senstive areas shall be generated externally. *DON'T* use the areas generated by tpm2_create. tpm2_loadexternal -H n -u -r -C object.context Subset 4: Encryption tools -------------------------- * tpm2_encryptdecrypt performs symmetric encryption or decryption. keyHandle shall reference a symmetric cipher object. Usage: -k, --keyHandle the symmetric key used for the operation (encryption/decryption) -c, --keyContext filename of the key context used for the operation -P, --pwdk the password of key, optional -D, --decrypt the operation type, default NO, optional YES the operation is decryption NO the operation is encryption -I, --inFile Input file path, containing the data to be operated -o, --outFile Output file path, record the operated data -X, --passwdInHex passwords given by any options are hex format. example: tpm2_encryptdecrypt -k 0x81010001 -P abc123 -D NO -I -o tpm2_encryptdecrypt -c key.context -P abc123 -D NO -I -o tpm2_encryptdecrypt -k 0x81010001 -P 123abca -X -D NO -I -o * tpm2_rsaencrypt performs RSA encryption using the indicated padding scheme according to IETF RFC 3447. The scheme of keyHandle should not be TPM_ALG_NULL. The key referenced by keyHandle is required to be an RSA key (TPM_RC_KEY) with the decrypt attribute SET (TPM_RC_ATTRIBUTES). Usage: -k, --keyHandle the public portion of RSA key to use for encryption -c, --keyContext filename of the key context used for the operation -I, --inFile Input file path, containing the data to be encrypted -o, --outFile Output file path, record the encrypted data example: tpm2_rsaencrypt -k 0x81010001 -I -o tpm2_rsaencrypt -c key.context -I -o * tpm2_rsadecrypt performs RSA decryption using the indicated padding scheme according to IETF RFC 3447 (PKCS#1). The scheme of keyHandle should not be TPM_ALG_NULL. The key referenced by keyHandle is required to be an RSA key (TPM_RC_KEY) with the decrypt attribute SET (TPM_RC_ATTRIBUTES). Usage: -k, --keyHandle the public portion of RSA key to use for decryption -c, --keyContext filename of the key context used for the operation -P, --pwdk the password of key, optional -I, --inFile Input file path, containing the data to be decrypted -o, --outFile Output file path, record the decrypted data -X, --passwdInHex passwords given by any options are hex format. example: tpm2_rsadecrypt -k 0x81010001 -I -o tpm2_rsadecrypt -k 0x81010001 -P 123abc -X -I -o * tpm2_unseal returns the data in a loaded Sealed Data Object. Usage: -H, --item item handle, handle of a loaded data object -c, --itemContext filename for item context -P, --pwdi item handle password, optional -o, --outfile Output file name, containing the unsealed data -X, --passwdInHex passwords given by any options are hex format. example: tpm2_unseal -H 0x81010001 -P abc123 -o tpm2_unseal -c item.context -P abc123 -o tpm2_unseal -H 0x81010001 -P 123abc -X -o Subset 5: Signing tools ----------------------- * tpm2_sign sign an externally provided hash with the specified symmetric or asymmetric signing key. If keyHandle references a restricted signing key, then validation shall be provided, indicating that the TPM performed the hash of the data and validation shall indicate that hashed data did not start with TPM_GENERATED_VALUE. The scheme of keyHandle should not be TPM_ALG_NULL. Usage: -k, --keyHandle Handle of key that will perform signing -c, --keyContext filename of the key context used for the operation -P, --pwdk the password of key, optional -g, --halg the hash algorithm used to digest the message 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 -m, --msg the message file, containning the content to be digested -t, --ticket the ticket file, containning the validation structure, optional -s, --sig the signature file, record the signature structure -X, --passwdInHex passwords given by any options are hex format. example: tpm2_sign -k 0x81010001 -P abc123 -g 0x000B -m -s -t tpm2_sign -c key.context - abc123 -g 0x000B -m -s -t tpm2_sign -k 0x81010001 -P 123abc -X -g 0x000B -m -s -t * tpm2_verifysignature uses loaded keys to validate a signature on a message with the message digest passed to the TPM. If the signature check succeeds, then the TPM will produce a TPMT_TK_VERIFIED. Otherwise, the TPM shall return TPM_RC_SIGNATURE. If keyHandle references an asymmetric key, only the public portion of the key needs to be loaded. If keyHandle references a symmetric key, both the public and private portions need to be loaded. Usage: -k, --keyHandle handle of public key that will be used in the validation -c, --keyContext filename of the key context used for the operation -g, --halg the hash algorithm used to digest the message 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 -m, --msg the input message file, containning the content to be digested -D, --digest the input hash file, containning the hash of the message. If this argument been chosed, the argument '-m(--msg)' and '-g(--halg)' is no need -s, --sig the input signature file, containning the signature to be tested -r, --raw set the input signature file to raw type, default TPMT_SIGNATURE, optional -t, --ticket the ticket file, record the validation structure example: tpm2_verifysignature -k 0x81010001 -g 0x000B -m -s -t tpm2_verifysignature -k 0x81010001 -D -s -t tpm2_verifysignature -c key.context -g 0x000B -m -s -t * tpm2_certify prove that an object with a specific Name is loaded in the TPM. By certifying that the object is loaded, the TPM warrants that a public area with a given Name is self-consistent and associated with a valid sensitive area. If a relying party has a public area that has the same Name as a Name certified with this command, then the values in that public area are correct. The object may be any object that is loaded with TPM2_Load() or TPM2_CreatePrimary(). An object that only has its public area loaded cannot be certified. Usage: -H, --objHandle handle of the object to be certified -C, --objContext filename of the object context to be certified -k, --keyHandle handle of the key used to sign the attestation structure -c, --keyContext filename of the key context used to sign the attestation structure -P, --pwdo the object handle's password, optional -K, --pwdk the keyHandle's password, optional -g, --halg the hash algorithm used to digest the message 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 -a, --attestFile output file name, record the attestation structure -s, --sigFile output file name, record the signature structure -X, --passwdInHex passwords given by any options are hex format. example: tpm2_certify -H 0x81010002 -k 0x81010001 -P 0x0011 -K 0x00FF -g 0x00B -a -s tpm2_certify -C obj.context -c key.context -P 0x0011 -K 0x00FF -g 0x00B -a -s tpm2_certify -H 0x81010002 -k 0x81010001 -P 0011 -K 00FF -X -g 0x00B -a -s Subset 6: utilities ------------------- * tpm2_getrandom returns the next bytesRequested octets from the random number generator. Usage: tpm2_getrandom [-s/--size ] [-o/--of ] where: -s/--size specifies the size of the bytesRequested. -o/--of specifies the filename of output. example: tpm2_getrandom -s 20 -o random.out * tpm2_hash performs a hash operation on a data buffer and returns the results. If the results of the hash will be used in a signing operation that uses a restricted signing key, then the ticket returned by this command can indicate that the hash is safe to sign. Usage: -H, --hierarchy hierarchy to use for the ticket e TPM_RH_ENDORSEMENT o TPM_RH_OWNER p TPM_RH_PLATFORM n TPM_RH_NULL -g, --halg algorithm for the hash being computed 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 -I, --infile file containning the data to be hashed -o, --outfile file record the hash result -t, --ticket file record the ticket example: tpm2_hash -H -g 0x004 -I -o -t * tpm2_hmac performs an HMAC on the supplied data using the indicated hash algorithm. The caller shall provide proper authorization for use of handle. Usage: -k, --keyHandle handle for the symmetric signing key providing the HMAC key -c, --keyContext filename of the key context used for the operation -P, --pwdk the keyHandle's password, optional -g, --halg algorithm for the hash being computed 0x0004 TPM_ALG_SHA1 0x000B TPM_ALG_SHA256 0x000C TPM_ALG_SHA384 0x000D TPM_ALG_SHA512 0x0012 TPM_ALG_SM3_256 -I, --infile file containning the data to be HMACed -o, --outfile file record the HMAC result -X, --passwdInHex passwords given by any options are hex format. example: tpm2_hmac -k 0x81010002 -P abc123 -g 0x004 -I -o tpm2_hmac -c key.context -P abc123 -g 0x004 -I -o tpm2_hmac -k 0x81010002 -P 123abc -X -g 0x004 -I -o * tpm2_readpublic Access to the public area of a loaded object. Usage: -H, --object The loaded object handle -c, --contextObject filename for object context -o, --opu The output file path, recording the public portion of the object example: tpm2_readpublic -H 0x81010002 --opu tpm2_readpublic -c obj.context --opu tpm2-tools-2.1.0/misc/000077500000000000000000000000001313543155100144665ustar00rootroot00000000000000tpm2-tools-2.1.0/misc/coding_standard_c.txt000066400000000000000000000227041313543155100206610ustar00rootroot00000000000000TPM2.0-tools Coding Standard Golden rule Code should hold as close to the C99 standard as possible with the exception that GCC specific extensions are generally accepted. The code must compile without warnings (for the primary target compiler) if the compiler is instructed to report all warnings. If some warning is unavoidable, the offensive line must be documented as to why it can not be changed to remove the warning. [1] It may also be possible to suppress specific warnings dependent on compiler options – this is acceptable but could also be dangerous if the suppression has too large a scope. Commenting There are four acceptable commenting styles: block, critical-line, next-line, and line. Block comments indicate many lines of code below are being covered by the comment. These are useful as file, function, algorithmic, or multi-line equation level comments. Next-line comments apply only to the line of code immediately beneath them. Critical-line comments are equivalent to next-liners, but they are formatted like block comments to indicate the line of code following (or the comment itself) is more important than normal. Each of these three comments are formatted so that the initial "/*" is left with the code/scope to which it applies. Line comments apply to the line on which they appear, always to the right of all code on the line. Line comments are preferred over next-liners because they do not interrupt the vertical flow of code... use the next-line style if the line of code would exceed 80 characters when a line comment is added. Next-line and line comments should be used sparingly... since they are rarely complete sentences, it is often better in the long run to rewrite the line of code to be understandable alone or in the context of a block comment. /* * This block comment could apply to some function and describe its inner * workings. Notice these sentences have traditional capitalization and * punctuation... that's because it has to be read in a way completely * unlike the Post-It style content of next-line and line comments. */ /* * This line or comment is important... at least more than usual */ /* the next line is regular, but needs a comment */ // This is also acceptable for a line comment. // This is not an acceptable block comment. // These read very imbalanced. // Don't do this. “The size of the comment should be proportional to the size of the code that it refers to. Consequently, properties of code that can fit within a single 24-line screen should not be commented unless they are not obvious. By contrast, even obvious global properties and invariants may need to be made explicit. This doesn't have to be through comments, though. The assert() macro is an excellent executable comment.†[2] All source files and functions require leading block comments for consistency. Naming conventions Variable names should clearly imply what their values mean... do not rely on the types of variables to do this. Multiple word names are descriptive and most easily read if words are separated with the underscore character, “_â€. DoNotUseCamelBackStyle because ItIsNotAs easy to read, especially when actual whitespace IsAddedFor syntactical purposes. It is common practice to keep variable and function names completely lowercase. Constants are usually lowercase as well, but some groups prefer the standard of all-caps so they have the “eye feel†of older #define macros. unsigned int table_index = find_index(jacket_table, “colorâ€, COLOR_RED); Boolean variables should be named to reflect the true condition... even if the variable is used to detect false conditions. Boolean variables should be declared as type bool using . int last_item = 0; while(!last_item) { /* ... */ } int char_found = is_alpha(c); Single letter variable names should be avoided. Exceptions are: “iâ€,â€jâ€, and “k†are loop counters or temporary array indexes “m†and “n†are row and column indexes for multidimensional arrays “c†and “s†are temporary/parameter characters or strings “râ€, “gâ€, “bâ€, and “a†are red, green, blue, and alpha levels, but only when they are used together “xâ€, “yâ€, and “z†are coordinate values Abbreviated words in variable names should be avoided. Exceptions are: “char†= character “col†= column. Typically there is also “row†so it is not confused with color “cnt†= count “pos†= position “rem†= remainder Function names should follow the naming conventions of variables and clearly imply not only what the function does, but also the nature of what it returns (if anything). Functions that return boolean integers should be named to reflect the true condition... even if they are created to detect false conditions. Functions should never be hidden in conditional statements, with the exception of loops where it makes the code simpler. bool is_number_prime = is_prime(i); if(is_number_prime) { /* ... */ } while(!labeled_correctly(sample[i])) { /* ... */ } A function that is exported for use in multiple source files should be prefixed with the source file (or object module) name it was defined in (not declared... infinite declarations are allowed, but only one definition). For example, the file list.c may contain the implementation of a dynamic list ADT including an exported method for creating a list instance and an internal (static) method for overflow checking. The first function might be named “list_createâ€, and the second, “is_overflowedâ€. A function used only within its definition source file should be declared static (as should all variables global to only one file's scope), have no prefix, and must not be declared in any header files. A function used externally from its definition source file should be declared extern in the source's associated header file. Files Typically, every header file has the same base filename as an associated source file. Each header file is bound by conditional compilation commands using an all caps and underscored variant of the complete filename. Header files should never define functions or variables. /* * File: basic_file.h * Header file block comment */ #ifndef BASIC_FILE_H #define BASIC_FILE_H /* standard #includes */ /* project #includes */ /* type/constant definitions */ /* extern variable declarations */ /* extern function declarations */ #endif /* BASIC_FILE_H */ /* * File: basic_file.c * Source file block comment... */ /* standard #includes */ /* project #includes */ #include “basic_file.h†/* externalized variable definitions */ /* static variables (locally global) */ /* static function declarations */ /* externalized function definitions */ /* static function definitions */ Header files should only #include what is necessary to allow a file that includes it to compile. Associated source files will always #include the header of the same name, but should #include files whose resources are used within the source even if they are already included in that header. This provides a complete context for readers of the source file... i.e., they don't have to search through headers to determine where a resource came from. For example, consider a header and source that use FILE pointers declared in stdio.h. The header must #include to ensure files that include it will be able to compile. The corresponding source #includes the associated header and therefore receives the benefit of stdio.h automatically. The source would be unnerving if the FILE type was used and stdio.h was not #included. Variable Scope and types Variables should be declared and scoped to the smallest scope of use. /* This should be avoided */ void foo() { unsigned i; do_something(); for(i=0; i < 100; i++) { do_more(i); } } /* Proper variable scope */ void foo() { do_something(); unsigned i; for(i=0; i < 100; i++) { do_more(i); } } This promotes descriptive variable names as well as dissuading variable re-use when not proper. Also, it promotes a locality, where one can identify the variable and it's corresponding usage in code. Variables should only be of a signed type if something should ever be negative. A common, incorrect use, is to declare loop indices as int instead of unsigned. Formatting Always use space characters, 4 spaces per level of indentation. Block statements encapsulated with braces should place the opening brace on the same line after the end of the conditional statement or function parameter list, and the closing brace at the same column position as the beginning of the conditional statement or function return parameter, on the line immediately after the end of the block. if(some_int > 0) { statement1; statement2; } void some_function(arg1, arg2) { statement1; statement2; } Conditional statements (such as if, else, while, for, switch, etc) should always be followed by such block statements, even if they contain only one line statement. These formatting conditions are contrary to Kernighan and Ritchie's “one true brace styleâ€. [3] Line Length should not exceed 80 characters and should be split on the nearest whitespace or delimiter character. Formatters: Code formatters can found under misc/formatters References 1: Alan Bridger, Mick Brooks, and Jim Pisano, C Coding Standards, 2001, http://www.alma.nrao.edu/development/computing/docs/joint/0009/2001-02-28.pdf 2: Jim Larson, Standards and Style for Coding in ANSI C, 1996, http://www.jetcafe.org/jim/c-style.html 3: Brian Kernighan, Dennis Ritchie, The C Programing Language, 1988 tpm2-tools-2.1.0/misc/formatters/000077500000000000000000000000001313543155100166545ustar00rootroot00000000000000tpm2-tools-2.1.0/misc/formatters/tpm2.0-eclipse-cdt-formatter.xml000066400000000000000000000425201313543155100246140ustar00rootroot00000000000000 tpm2-tools-2.1.0/scripts/000077500000000000000000000000001313543155100152225ustar00rootroot00000000000000tpm2-tools-2.1.0/scripts/utils/000077500000000000000000000000001313543155100163625ustar00rootroot00000000000000tpm2-tools-2.1.0/scripts/utils/intelEKcert2PemDer.sh000077500000000000000000000036621313543155100223200ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/sh certBasename=$( echo $(basename $1) | cut -f 1 -d '.') sed -i 's/-/+/g;s/_/\//g;s/%3D/=/g;s/^{.*certificate":"//g;s/"}$//g;' $1 cat $1 | base64 --decode > $certBasename.cer openssl x509 -in $certBasename.cer -inform DER -out $certBasename.pem -outform PEM tpm2-tools-2.1.0/scripts/utils/tcgRSApub2PemDer.sh000077500000000000000000000040541313543155100217350ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash echo 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA' | base64 -d > header.bin echo '02 03' | xxd -r -p >mid-header.bin echo '01 00 01' | xxd -r -p >exponent.bin dd if=$1 of=modulus.bin bs=1 count=256 skip=102 cat header.bin modulus.bin mid-header.bin exponent.bin > $1.cer openssl rsa -in $1.cer -inform DER -pubin > $1.pem rm header.bin modulus.bin mid-header.bin exponent.bin tpm2-tools-2.1.0/test/000077500000000000000000000000001313543155100145125ustar00rootroot00000000000000tpm2-tools-2.1.0/test/.gitignore000066400000000000000000000001641313543155100165030ustar00rootroot00000000000000# Ignore everything * # But not these files... !.gitignore !README.md !get-capability-tpm-prop-fixed.bin !*.sh !*.c tpm2-tools-2.1.0/test/system/000077500000000000000000000000001313543155100160365ustar00rootroot00000000000000tpm2-tools-2.1.0/test/system/README.md000066400000000000000000000015661313543155100173250ustar00rootroot00000000000000**these are some scripts for the testing of TPM (Trusted Platform Module) 2.0 tools ** Below are script instructions: ##1: integration testing test_smoking.sh is a quick & brief testing for all tpm-tools. test_all.sh runs all separated .sh. ##2: separated testing There are some separated .sh for each of tpm2-tool. Name convention is test_tpm2_xxx.sh. ##3: algorithm testing Named as test_algs_tpm2_XXX.sh, test all algorithms involved in the parameters of tpm2-tools. A part of test_tpm2_XXX_all.sh also contain algorithm testing. ##4: others test_tpm2_XXX_func.sh for adding some test cases in furture. ##Condition and Operation instructions: 1.TPM is initialized 2.install tpm2-tools 3.must start resourcemgr before run all test scripts 4.clean up all log files 5.run xxx.sh for automatic test 6.results are printed to stdout and an exit code of 0 indicates success. tpm2-tools-2.1.0/test/system/fixtures/000077500000000000000000000000001313543155100177075ustar00rootroot00000000000000tpm2-tools-2.1.0/test/system/fixtures/get-capability-tpm-prop-fixed.bin000066400000000000000000000000261313543155100261460ustar00rootroot00000000000000€ztpm2-tools-2.1.0/test/system/test_algs.sh000077500000000000000000000065131313543155100203670ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; ###this script use for test the implementation of all algorithms involved createprimary &create/load #!/bin/sh halg_p= kalg_p= halg_c= kalg_c= rm *.log context* op* name.load* for halg_p in 0x0004 0x000B 0x000C 0x000D 0x0012 # for halg_p in 0x0004 0x000B 0x000C do for kalg_p in 0x0001 0x0008 0x0023 0x0025 do tpm2_createprimary -A e -g $halg_p -G $kalg_p -C context.p_"$halg_p"_"$kalg_p" if [ $? != 0 ];then echo "createprimary for context.p_"$halg_p"_"$kalg_p" fail, please check the environment or parameters!" fi ############create & load key context############ for halg_c in 0x0004 0x000B 0x000C 0x000D 0x0012 do for kalg_c in 0x0001 0x0008 0x0023 0x0025 do tpm2_create -g $halg_c -G $kalg_c -o opu_"$halg_p""$kalg_p"_"$halg_c""$kalg_c" -O opr_"$halg_p""$kalg_p"_"$halg_c""$kalg_c" -c context.p_"$halg_p"_"$kalg_p" if [ $? != 0 ];then echo "create used context.p_"$halg_p"_"$kalg_p" with algs:"$halg_c""$kalg_c" fail, please check the environment or parameters!" echo "create used context.p_"$halg_p"_"$kalg_p" with algs:"$halg_c""$kalg_c" fail" >>create_error.log else tpm2_load -c context.p_"$halg_p"_"$kalg_p" -u opu_"$halg_p""$kalg_p"_"$halg_c""$kalg_c" -r opr_"$halg_p""$kalg_p"_"$halg_c""$kalg_c" -n name.load_"$halg_p""$kalg_p"_"$halg_c""$kalg_c" -C context_load_"$halg_p""$kalg_p"_"$halg_c""$kalg_c" if [ $? != 0 ];then echo "load for context.p_"$halg_p"_"$kalg_p" fail, please check the environment or parameters!" echo "load context.p_"$halg_p"_"$kalg_p" for create context_load_"$halg_p""$kalg_p"_"$halg_c""$kalg_c" fail" >>load_error.log fi fi done done done done tpm2-tools-2.1.0/test/system/test_algs_tpm2_encryptdecrypt.sh000077500000000000000000000057521313543155100244740ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/sh ##before this script, you should make sure all kinds of context already loaded context_p= halg= new_path=`dirname $0` PATH="$PATH":"$new_path" ctx_count=`ls |grep -c context_load` if [ $ctx_count -le 1 ];then echo "we should execute test_algs.sh first!" wait 5 test_algs.sh fi rm test_algs_encryptdecrypt_*.log if [ ! -e "secret.data" ] then echo "12345678" > secret.data fi #for halg_p in 0x0004 0x000B 0x000C 0x000D 0x0012 for context_p in `ls context_load*` do tpm2_encryptdecrypt -c $context_p -D NO -I secret.data -o endecrypt_"$context_p".f if [ $? != 0 ];then echo "encryptdecrypt for endecrypt_"$context_p".f fail, please check the environment or parameters!" echo "encryptdecrypt for endecrypt_"$context_p".f fail" >>test_encryptdecrypt_error.log else echo "encryptdecrypt for endecrypt_"$context_p".f pass" >>test_encryptdecrypt_pass.log tpm2_encryptdecrypt -c $context_p -D YES -I endecrypt_"$context_p".f -o decrypt_"$context_p".f if [ $? != 0 ];then echo "encryptdecrypt for decrypt_"$context_p".f fail, please check the environment or parameters!" echo "encryptdecrypt for decrypt_"$context_p".f fail" >>test_encryptdecrypt_error.log else echo "encryptdecrypt for decrypt_"$context_p".f pass" >>test_encryptdecrypt_pass.log fi fi done tpm2-tools-2.1.0/test/system/test_algs_tpm2_getpubak.sh000077500000000000000000000055701313543155100232150ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash handle_ek=0x81010005 ##ek_e=1 ek_alg=0x0001 handle_ak=0x81010006 ak_alg= digestAlg= signAlg= fail() { echo "$1 test fail, please check the environment or parameters!" echo ""$1" fail" >>test_getpubak_error.log } Pass() { echo ""$1" pass" >>test_getpubak_pass.log } rm test_getpub*.log rm ak.pub* tpm2_getpubek -H "$handle_ek" -g $ek_alg -f ek.pub_"$ek_alg" if [ $? != 0 ];then fail getpubek exit 1 fi ## ./tpm2_getpubak -e "$handle_ek" -k $handle_ak -g $ak_alg -D $digestAlg -s $signAlg -f ak.pub_"$kalg_p"_"$halg"_"$digestAlg"_"$signAlg" -n ak.name_"$kalg_p"_"$halg"_"$digestAlg"_"$signAlg" for ak_alg in 0x0001 0x0008 0x0023 do for digestAlg in 0x0004 0x000B 0x000C 0x000D 0x0012 do for signAlg in 0x0005 0x0014 0x0016 0x0018 0x001A 0x001B 0x001C do tpm2_getpubak -E "$handle_ek" -k $handle_ak -g $ak_alg -D $digestAlg -s $signAlg -f ak.pub_"$ak_alg"_"$digestAlg"_"$signAlg" -n ak.name_"$ak_alg"_"$digestAlg"_"$signAlg" if [ $? != 0 ];then fail "Ak_alg_"$ak_alg"_"$digestAlg"_"$signAlg"" else Pass "Ak_alg_"$ak_alg"_"$digestAlg"_"$signAlg"" fi handle_ak=$(($handle_ak+0x1)) val=`echo 'obase=16; '$handle_ak''|bc` handle_ak=0x"$val" done done done tpm2-tools-2.1.0/test/system/test_algs_tpm2_getpubek.sh000077500000000000000000000043621313543155100232170ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash #handle_ek=0x81010003 ek_e=1 handle_k= kalg_p= halg= digestAlg= signAlg= fail() { echo "getpubek for ek.pub_"$1" fail, please check the environment or parameters!" echo "getpubek for ek.pub_"$1" fail" >>test_getpubek_error.log } Pass() { echo "getpubek for ek.pub_"$1" pass" >>test_getpubak_pass.log } rm test_getpub*.log rm ek.pub* for kalg_p in 0x0001 0x0008 0x0023 0x0025 do ##echo $ek_e tpm2_getpubek -H 0x8101000"$ek_e" -g $kalg_p -f ek.pub_"$kalg_p" if [ $? != 0 ];then fail "$kalg_p" else Pass "$kalg_p" fi ek_e=$(($ek_e+2)) done tpm2-tools-2.1.0/test/system/test_algs_tpm2_hmac.sh000077500000000000000000000050511313543155100223150ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/sh context_p= halg= ctx_count= new_path=`dirname $0` PATH="$PATH":"$new_path" ctx_count=`ls |grep -c context_load` if [ $ctx_count -le 1 ];then echo "we should execute test_algs.sh first!" wait 5 test_algs.sh fi rm -f test_hmac_*.log if [ ! -e "secret.data" ] then echo "12345678" > secret.data fi #for halg_p in 0x0004 0x000B 0x000C 0x000D 0x0012 for context_p in `ls context_load*` do for halg in 0x0004 0x000B 0x000C do ## echo "halg_p: "$halg_p" kalg_p: "$kalg_p"" >>test.log tpm2_hmac -c $context_p -g $halg -I secret.data -o hmac_out_"$context_p"_"$halg_h" if [ $? != 0 ];then echo "hmac for hmac_out_"$context_p"_"$halg" fail, please check the environment or parameters!" echo "hmac for hmac_out_"$context_p"_"$halg" fail" >>test_hmac_error.log else echo "hmac for hmac_out_"$context_p"_"$halg" pass" >>test_hmac_pass.log fi done done tpm2-tools-2.1.0/test/system/test_algs_tpm2_quote.sh000077500000000000000000000047111313543155100225440ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/sh ##before this script, you should make sure all kinds of context already loaded context_p= halg= new_path=`dirname $0` PATH="$PATH":"$new_path" ctx_count=`ls |grep -c context_load` if [ $ctx_count -le 1 ];then echo "we should execute test_algs.sh first!" wait 5 test_algs.sh fi rm test_quote_*.log for context_p in `ls context_load*` do for halg in 0x0004 0x000B 0x000C 0x000D 0x0012 do tpm2_quote -c $context_p -g $halg -l 16,17,18 -o quote_out_"$context_p"_"$halg_h"_"$halg" if [ $? != 0 ];then echo "quote for quote_"$context_p"_"$halg" fail, please check the environment or parameters!" echo " quote for quote_"$context_p"_"$halg" fail" >>test_quote_error.log else echo "quote for quote_"$context_p"_"$halg" pass" >>test_quote_pass.log fi done done tpm2-tools-2.1.0/test/system/test_algs_tpm2_readpublic.sh000077500000000000000000000044401313543155100235200ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash context_p= halg= new_path=`dirname $0` PATH="$PATH":"$new_path" ctx_count=`ls |grep -c context_load` if [ $ctx_count -le 1 ];then echo "we should execute test_algs.sh first!" wait 5 test_algs.sh fi rm test_readpublic_*.log for context_p in `ls context_load*` do tpm2_readpublic -c $context_p -o rd-opu_"$context_p" if [ $? != 0 ];then echo "readpublic for "$context_p" fail, please check the environment or parameters!" echo "readpublic for "$context_p" fail" >>test_readpublic_error.log else echo "readpublic for "$context_p" pass" >>test_readpublic__pass.log fi done tpm2-tools-2.1.0/test/system/test_algs_tpm2_sign.sh000077500000000000000000000051061313543155100223460ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/sh ##before this script, you should make sure all kinds of context already loaded context_p= halg= new_path=`dirname $0` PATH="$PATH":"$new_path" ctx_count=`ls |grep -c context_load` if [ $ctx_count -le 1 ];then echo "we should execute test_algs.sh first!" wait 5 test_algs.sh fi rm test_algs_sign_*.log sign_* if [ ! -e "secret.data" ] then echo "12345678" > secret.data fi #for halg_p in 0x0004 0x000B 0x000C 0x000D 0x0012 for context_p in `ls context_load*` do for halg in 0x0004 0x000B 0x000C do tpm2_sign -c $context_p -g $halg -m secret.data -s sign_"$context_p"_"$halg_h"_"$halg" if [ $? != 0 ];then echo "sign for sign_"$context_p"_"$halg" fail, please check the environment or parameters!" echo " sign for sign_"$context_p"_"$halg" fail" >>test_algs_sign_error.log else echo "sign for sign_"$context_p"_"$halg" pass" >>test_algs_sign_pass.log fi done done tpm2-tools-2.1.0/test/system/test_algs_tpm2_unseal.sh000077500000000000000000000074711313543155100227040ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/sh context_p= halg_p= kalg_p= halg_c= kalg_c= rm *.log context* op* name.load* if [ ! -e "secret.data" ] then echo "12345678" > secret.data fi for halg_p in 0x0004 0x000B 0x000C 0x000D 0x0012 do for kalg_p in 0x0001 0x0008 0x0023 0x0025 do tpm2_createprimary -A p -g $halg_p -G $kalg_p -C context.p_"$halg_p"_"$kalg_p" if [ $? != 0 ];then echo "createprimary for context.p_"$halg_p"_"$kalg_p" fail, please check the environment or parameters!" continue fi ############create & load key context############ for halg_c in 0x0004 0x000B 0x000C 0x000D 0x0012 do for kalg_c in 0x0001 0x0008 0x0023 0x0025 do tpm2_create -g $halg_c -G $kalg_c -o opu_"$halg_p""$kalg_p"_"$halg_c""$kalg_c" -O opr_"$halg_p""$kalg_p"_"$halg_c""$kalg_c" -I secret.data -c context.p_"$halg_p"_"$kalg_p" if [ $? != 0 ];then echo "create used context.p_"$halg_p"_"$kalg_p" with algs:"$halg_c""$kalg_c" fail, please check the environment or parameters!" echo "create used context.p_"$halg_p"_"$kalg_p" with algs:"$halg_c""$kalg_c" fail" >>create_error.log else tpm2_load -c context.p_"$halg_p"_"$kalg_p" -u opu_"$halg_p""$kalg_p"_"$halg_c""$kalg_c" -r opr_"$halg_p""$kalg_p"_"$halg_c""$kalg_c" -n name.load_"$halg_p""$kalg_p"_"$halg_c""$kalg_c" -C context_load_"$halg_p""$kalg_p"_"$halg_c""$kalg_c" if [ $? != 0 ];then echo "load for context.p_"$halg_p"_"$kalg_p" fail, please check the environment or parameters!" echo "load context.p_"$halg_p"_"$kalg_p" for create context_load_"$halg_p""$kalg_p"_"$halg_c""$kalg_c" fail" >>load_error.log fi fi done done done done #ctx_count=`ls |grep -c context_load` #if [ $ctx_count -le 1 ];then # echo "we should execute test_algs.sh first!" # wait 5 # ./test_algs.sh #fi rm test_unseal_*.log usl_* for context_p in `ls context_load*` do tpm2_unseal -c $context_p -o usl_"$context_p".out if [ $? != 0 ];then echo "unseal fail, please check the environment or parameters!" echo "unseal for_"$context_p" fail" >>test_unseal_error.log else echo "unseal for_"$context_p" pass" >>test_unseal_pass.log fi done tpm2-tools-2.1.0/test/system/test_algs_tpm2_verifysignature.sh000077500000000000000000000063351313543155100246410ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/sh ##before this script, you should make sure all kinds of context already loaded context_p= halg= new_path=`dirname $0` PATH="$PATH":"$new_path" ctx_count=`ls |grep -c context_load` if [ $ctx_count -le 1 ];then echo "we should execute test_algs.sh first!" wait 5 test_algs.sh fi rm test_algs_*.log sign_* verifysig_* tickt_verify* if [ ! -e "secret.data" ] then echo "12345678" > secret.data fi #for halg_p in 0x0004 0x000B 0x000C 0x000D 0x0012 for context_p in `ls context_load*` do for halg in 0x0004 0x000B 0x000C do tpm2_sign -c $context_p -g $halg -m secret.data -s sign_"$context_p"_"$halg" if [ $? != 0 ];then echo "sign for sign_"$context_p"_"$halg" fail, please check the environment or parameters!" echo " sign for sign_"$context_p"_"$halg" fail" >>test_algs_sign_error.log else echo "sign for sign_"$context_p"_"$halg" pass" >>test_algs_sign_pass.log for halg_ver in 0x0004 0x000B 0x000C 0x000D 0x0012 do tpm2_verifysignature -c $context_p -g $halg_ver -m secret.data -s sign_"$context_p"_"$halg" -t tickt_verify_sign_"$context_p"_"$halg"_"$halg_ver".out if [ $? != 0 ];then echo "verifysignature for sign_"$context_p"_"$halg"_"$halg_ver" fail, please check the environment or parameters!" echo " verifysignature for sign_"$context_p"_"$halg"_"$halg_ver" fail" >>test_algs_verifysignature_error.log else echo " verifysignature for sign_"$context_p"_"$halg"_"$halg_ver" pass" >>test_algs_verifysignature_pass.log fi done fi done done tpm2-tools-2.1.0/test/system/test_all.sh000077500000000000000000000065211313543155100202100ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash SRC_DIR=`realpath ../../tools/` PATH=$SRC_DIR:$PATH pass=0 fail=0 fail_summary="" test_wrapper() { ./$1 if [ $? -eq 0 ]; then echo -e "\033[32m $1 pass \033[0m" let "pass++" else echo -e "\033[31m $1 Fail \033[0m" let "fail++" fail_summary="$fail_summary\n$1" fi # Scripts are sloppy, perform cleanup rm `find . -maxdepth 1 -type f ! -name '*.sh' ! -name 'README.md'` 2>/dev/null sleep 1 } test_wrapper test_tpm2_takeownership_all.sh test_wrapper test_tpm2_nv.sh test_wrapper test_tpm2_listpcrs.sh test_wrapper test_tpm2_getrandom.sh #test_wrapper test_tpm2_createprimary_all.sh #test_wrapper test_tpm2_create_all.sh test_wrapper test_tpm2_load.sh test_wrapper test_tpm2_loadexternal.sh test_wrapper test_tpm2_evictcontrol.sh test_wrapper test_tpm2_hash.sh test_wrapper test_tpm2_hmac.sh test_wrapper test_tpm2_quote.sh test_wrapper test_tpm2_unseal.sh test_wrapper test_tpm2_akparse.sh test_wrapper test_tpm2_certify.sh test_wrapper test_tpm2_evictcontrol.sh test_wrapper test_tpm2_getpubek.sh test_wrapper test_tpm2_getpubak.sh test_wrapper test_tpm2_makecredential.sh test_wrapper test_tpm2_activecredential.sh test_wrapper test_tpm2_readpublic.sh test_wrapper test_tpm2_rsaencrypt.sh test_wrapper test_tpm2_rsadecrypt.sh test_wrapper test_tpm2_encryptdecrypt.sh test_wrapper test_tpm2_sign.sh test_wrapper test_tpm2_verifysignature.sh test_wrapper test_tpm2_send_command.sh test_wrapper test_tpm2_dump_capability.sh test_wrapper test_tpm2_startup.sh test_wrapper test_tpm2_getmanufec.sh echo -e "\033[32m Tests passed: $pass \033[0m" echo -e "\033[31m Tests Failed: $fail \033[0m" if [ $fail -gt 0 ]; then echo -e "$fail_summary" fi exit $fail tpm2-tools-2.1.0/test/system/test_smoking.sh000077500000000000000000000201301313543155100210770ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/sh new_path=`dirname $0` PATH="$PATH":"$new_path" ekHandle=0x81010007 akHandle=0x81010008 fail() { echo "$1 test fail, please check the environment or parameters!" exit 1 } Pass() { echo ""$1" pass" >>test_getpubak_pass.log } rm *.out tpm2_takeownership -c if [ $? != 0 ];then fail takeownership fi test_tpm2_nv.sh tpm2_getpubek -H $ekHandle -g 0x01 -f ek.pub1.out if [ $? != 0 ];then fail getpubek fi tpm2_getpubak -E $ekHandle -k $akHandle -f ak.pub1.out -n ak.name_1.out |tee output_ak if [ $? != 0 ] || [ ! -e ak.name_1.out ];then fail getpubak fi grep -A 3 "Name of loaded key:" output_ak|tr "\n" " " >grep.txt Loadkeyname=`sed -e 's/ //g' grep.txt | awk -F':' '{print $2}'` echo 123456 | xxd -r -ps > secret.data tpm2_makecredential -e ek.pub1.out -s secret.data -n $Loadkeyname -o makecredential.out if [ $? != 0 ];then fail makecredential fi tpm2_activatecredential -H $akHandle -k $ekHandle -f makecredential.out -o act_credential.out if [ $? != 0 ];then fail activatecredential fi tpm2_akparse -f ak.pub1.out -k akparse.out if [ $? != 0 ];then fail akparse fi ##### getrandom & hash tpm2_getrandom -o random.out 20 if [ $? != 0 ];then fail getrandom fi tpm2_hash -H n -g 0x004 -I random.out -o hash.out -t hash_tk.out if [ $? != 0 ];then fail hash fi ############context ############## ###unseal tpm2_createprimary -A p -g 0x0004 -G 0x001 -C context.p1.out if [ $? != 0 ];then fail createprimary fi tpm2_create -c context.p1.out -g 0x000B -G 0x0008 -o opu1.out -O opr1.out -I secret.data if [ $? != 0 ];then fail create fi tpm2_load -c context.p1.out -u opu1.out -r opr1.out -n name.load.1.out -C context_load_out1.out if [ $? != 0 ];then fail load fi tpm2_unseal -c context_load_out1.out -o usl.data.out if [ $? != 0 ];then fail unseal fi #####quote tpm2_createprimary -A p -g 0x000B -G 0x001 -C context.p2.out if [ $? != 0 ];then fail createprimary fi tpm2_create -c context.p2.out -g 0x000B -G 0x0008 -o opu2.out -O opr2.out if [ $? != 0 ];then fail create fi tpm2_load -c context.p2.out -u opu2.out -r opr2.out -n name.load_2.out -C context_load_out2.out if [ $? != 0 ];then fail load fi tpm2_quote -c context_load_out2.out -g 0x4 -l 16,17,18 -o quote_outFile.out if [ $? != 0 ];then fail quote fi ######Hmac tpm2_createprimary -A e -g 0x000B -G 0x0001 -C context.p3.out if [ $? != 0 ];then fail createprimary fi tpm2_create -c context.p3.out -g 0x000B -G 0x0008 -o opu3.out -O opr3.out if [ $? != 0 ];then fail create fi tpm2_load -c context.p3.out -u opu3.out -r opr3.out -n name.load.3.out -C context_load_out3.out if [ $? != 0 ];then fail load fi tpm2_hmac -c context_load_out3.out -g 0x00B -I secret.data -o hmac.out if [ $? != 0 ];then fail hmac fi ######readpublic tpm2_createprimary -A e -g 0x000B -G 0x0001 -C context.p4.out if [ $? != 0 ];then fail createprimary fi tpm2_create -c context.p4.out -g 0x000B -G 0x0008 -o opu4.out -O opr4.out if [ $? != 0 ];then fail create fi tpm2_load -c context.p4.out -u opu4.out -r opr4.out -n name.load.4.out -C context_load_out4.out if [ $? != 0 ];then fail load fi tpm2_readpublic -c context_load_out4.out -o rd-opu.out if [ $? != 0 ];then fail readpublic fi ######evictcontrol tpm2_createprimary -A e -g 0x000B -G 0x0001 -C context.p5.out if [ $? != 0 ];then fail createprimary fi tpm2_create -g 0x000B -G 0x0008 -o opu5.out -O opr5.out -c context.p5.out if [ $? != 0 ];then fail create fi tpm2_load -c context.p5.out -u opu5.out -r opr5.out -n name.load5.out -C context_load_out5.out if [ $? != 0 ];then fail load fi tpm2_evictcontrol -A o -c context_load_out5.out -S 0x81010003 if [ $? != 0 ];then fail evictontronl else tpm2_evictcontrol -A o -H 0x81010003 -S 0x81010003 if [ $? != 0 ];then fail evictcontrol_release_Handle fi fi #####rsaencrypt & rsadecrypt tpm2_createprimary -A e -g 0x000B -G 0x0001 -C context.p6.out if [ $? != 0 ];then fail createprimary fi tpm2_create -g 0x000B -G 0x0001 -o opu6.out -O opr6.out -c context.p6.out if [ $? != 0 ];then fail create fi tpm2_loadexternal -H n -u opu6.out -C context_loadexternal_out6.out if [ $? != 0 ];then fail loadexternal fi tpm2_rsaencrypt -c context_loadexternal_out6.out -I secret.data -o rsa_en.out if [ $? != 0 ];then fail rsa_encrypt fi tpm2_load -c context.p6.out -u opu6.out -r opr6.out -n name.load6.out -C context_load_out6.out if [ $? != 0 ];then fail load fi tpm2_rsadecrypt -c context_load_out6.out -I rsa_en.out -o rsa_de.out if [ $? != 0 ];then fail rsa_decrypt fi #####sign tpm2_createprimary -A e -g 0x000B -G 0x0001 -C context.p7.out if [ $? != 0 ];then fail createprimary fi tpm2_create -g 0x000B -G 0x0008 -o opu7.out -O opr7.out -c context.p7.out if [ $? != 0 ];then fail create fi tpm2_load -c context.p7.out -u opu7.out -r opr7.out -n name.load7.out -C context_load_out7.out if [ $? != 0 ];then fail load fi tpm2_sign -c context_load_out7.out -g 0x00B -m secret.data -s sign.f.out if [ $? != 0 ];then fail sign fi tpm2_verifysignature -c context_load_out7.out -g 0x000B -m secret.data -s sign.f.out -t tickt_verify_sign.out if [ $? != 0 ];then fail verifysignature fi ######encryptdecrypt tpm2_createprimary -A e -g 0x000B -G 0x0001 -C context.p8.out if [ $? != 0 ];then fail createprimary fi tpm2_create -g 0x000B -G 0x0025 -o opu8.out -O opr8.out -c context.p8.out if [ $? != 0 ];then fail create fi tpm2_load -c context.p8.out -u opu8.out -r opr8.out -n name.load8.out -C context_load_out8.out if [ $? != 0 ];then fail load fi tpm2_encryptdecrypt -c context_load_out8.out -D NO -I secret.data -o endecrypt.out if [ $? != 0 ];then fail encrypt fi tpm2_encryptdecrypt -c context_load_out8.out -D YES -I endecrypt.out -o endecrypt_de.out if [ $? != 0 ];then fail decrypt fi ######certify tpm2_createprimary -A e -g 0x000B -G 0x0001 -C context.p9.out if [ $? != 0 ];then fail createprimary fi tpm2_create -g 0x000B -G 0x0001 -o opu9.out -O opr9.out -c context.p9.out if [ $? != 0 ];then fail create fi tpm2_load -c context.p9.out -u opu9.out -r opr9.out -n name.load9.out -C context_load_out9.out -d 3 if [ $? != 0 ];then fail load fi tpm2_certify -C context.p9.out -c context_load_out9.out -g 0x000B -a attest.out -s certify_signature.out if [ $? != 0 ];then fail certify fi tpm2_listpcrs if [ $? != 0 ];then fail listpcrs fi tpm2-tools-2.1.0/test/system/test_tpm2_activecredential.sh000077500000000000000000000060121313543155100237030ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash handle_ek=0x81010009 handle_ak=0x8101000a ek_alg=0x001 ak_alg=0x0001 digestAlg=0x000B signAlg=0x0014 file_input_data=secret.data output_ek_pub=ek_pub.out output_ak_pub=ak_pub.out output_ak_pub_name=ak_name_pub.out output_mkcredential=mkcredential.out output_actcredential=actcredential.out fail() { echo "$1 test fail, please check the environment or parameters!" exit 1 } rm $output_ek_pub $output_ak_pub $output_ak_pub_name $output_mkcredential $output_actcredential -rf if [ ! -e "$file_input_data" ] then echo "12345678" > $file_input_data fi tpm2_getpubek -H $handle_ek -g $ek_alg -f $output_ek_pub if [ $? != 0 ] || [ ! -e $output_ek_pub ];then fail getpubek fi tpm2_getpubak -E $handle_ek -k $handle_ak -g $ak_alg -D $digestAlg -s $signAlg -f $output_ak_pub -n $output_ak_pub_name |tee output_ak if [ $? != 0 ] || [ ! -e output_ak ];then fail getpubak fi grep -A 3 "Name of loaded key:" output_ak|tr "\n" " " >grep.txt Loadkeyname=`sed -e 's/ //g' grep.txt | awk -F':' '{print $2}'` tpm2_makecredential -e $output_ek_pub -s $file_input_data -n $Loadkeyname -o $output_mkcredential if [ $? != 0 ];then fail makecredential fi tpm2_activatecredential -H $handle_ak -k $handle_ek -f $output_mkcredential -o $output_actcredential if [ $? != 0 ];then fail activatecredential fi echo "activcredential successfully!" tpm2-tools-2.1.0/test/system/test_tpm2_akparse.sh000077500000000000000000000040651313543155100220310ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash new_path=`dirname $0` PATH="$PATH":"$new_path" file_input_data=ak_pub.out output_akparse=akparse.out rm $output_ekparse -rf if [ ! -e "$file_input_data" ] then test_tpm2_getpubak.sh fi tpm2_akparse -f $file_input_data -k $output_akparse if [ $? != 0 ];then echo "akparse fail, please check the environment or parameters!" exit 1 fi echo "akparse successfully!" tpm2-tools-2.1.0/test/system/test_tpm2_certify.sh000077500000000000000000000060021313543155100220410ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash file_primary_key_ctx=context.p_B1 file_certify_key_pub=opuB1_B8 file_certify_key_priv=oprB1_B8 file_certify_key_ctx=context_load_out_B1_B8 file_certify_key_name=name.load.B1_B8 file_output_attest=attest.out file_output_signature=certify_signature.out alg_hash=0x000B alg_primary_key=0x0001 alg_certify_key=0x0001 rm $file_primary_key_ctx $file_certify_key_pub $file_certify_key_priv $file_certify_key_ctx $file_certify_key_name $file_output_attest $file_output_signature -rf tpm2_takeownership -c tpm2_createprimary -A e -g $alg_hash -G $alg_primary_key -C $file_primary_key_ctx if [ $? != 0 ];then echo "createprimary fail, please check the environment or parameters!" exit 1 fi tpm2_create -g $alg_hash -G $alg_certify_key -o $file_certify_key_pub -O $file_certify_key_priv -c $file_primary_key_ctx if [ $? != 0 ];then echo "create fail, please check the environment or parameters!" exit 1 fi tpm2_load -c $file_primary_key_ctx -u $file_certify_key_pub -r $file_certify_key_priv -n $file_certify_key_name -C $file_certify_key_ctx if [ $? != 0 ];then echo "load fail, please check the environment or parameters!" exit 1 fi tpm2_certify -C $file_primary_key_ctx -c $file_certify_key_ctx -g $alg_hash -a $file_output_attest -s $file_output_signature if [ $? != 0 ];then echo "certify fail, please check the environment or parameters!" exit 1 fi tpm2-tools-2.1.0/test/system/test_tpm2_create_all.sh000077500000000000000000000046701313543155100225000ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/sh new_path=`dirname $0` PATH="$PATH":"$new_path" pCtx= gAlg= GAlg= rm create.error.log ctx_count=`ls |grep -c context_load` if [ $ctx_count -le 1 ];then echo "we should execute test_tpm2_createprimary_all.sh first!" wait 5 test_tpm2_createprimary_all.sh fi for pCtx in `ls ctx.cpri*` do for gAlg in 0x04 0x0B 0x0C 0x0D 0x12 do for GAlg in 0x01 0x08 0x23 0x25 do tpm2_create -c $pCtx -g $gAlg -G $GAlg -o opu."$pCtx".g"$gAlg".G"$GAlg" -O opr."$pCtx".g"$gAlg".G"$GAlg" if [ $? != 0 ];then echo "tpm2_create error: pCtx=$pCtx gAlg=$gAlg GAlg=$GAlg" echo "tpm2_create error: pCtx=$pCtx gAlg=$gAlg GAlg=$GAlg" >> create.error.log fi done done done tpm2-tools-2.1.0/test/system/test_tpm2_createprimary_all.sh000077500000000000000000000044441313543155100241030ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/sh Atype= gAlg= GAlg= rm createprimary.error.log rf for gAlg in 0x04 0x0B 0x0C 0x0D 0x12 do for GAlg in 0x01 0x08 0x23 0x25 do for Atype in o e p n do tpm2_createprimary -A $Atype -g $gAlg -G $GAlg -C ctx.cpri."$Atype".g"$gAlg".G"$GAlg" if [ $? != 0 ];then echo "tpm2_createprimary error: Atype=$Atype gAlg=$gAlg GAlg=$GAlg" echo "tpm2_createprimary error: Atype=$Atype gAlg=$gAlg GAlg=$GAlg" >> createprimary.error.log fi done done done tpm2-tools-2.1.0/test/system/test_tpm2_dump_capability.sh000077500000000000000000000044301313543155100235450ustar00rootroot00000000000000#!/bin/sh #;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; tpm2_dump_capability --capability="properties-fixed" if [ $? -ne 0 ]; then echo "tpm2_dump_capability failed to get fixed properties" exit 1 fi tpm2_dump_capability --capability="properties-variable" if [ $? -ne 0 ]; then echo "tpm2_dump_capability failed to get variable properties" exit 1 fi tpm2_dump_capability --capability="algorithms" if [ $? -ne 0 ]; then echo "tpm2_dump_capability failed to get algorithms" exit 1 fi tpm2_dump_capability --capability="commands" if [ $? -ne 0 ]; then echo "tpm2_dump_capability failed to get commands" exit 1 fi echo "tpm2_dump_capability success." exit 0 tpm2-tools-2.1.0/test/system/test_tpm2_encryptdecrypt.sh000077500000000000000000000070561313543155100234650ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash alg_primary_obj=0x0004 alg_primary_key=0x0001 alg_create_obj=0x000B alg_create_key=0x0025 file_input_data=secret.data file_primary_key_ctx=context.p_"$alg_primary_obj"_"$alg_primary_key" file_en_decrypt_key_pub=opu_"$alg_create_obj"_"$alg_create_key" file_en_decrypt_key_priv=opr_"$alg_create_obj"_"$alg_create_key" file_en_decrypt_key_name=name.load_"$alg_primary_obj"_"$alg_primary_key"-"$alg_create_obj"_"$alg_create_key" file_en_decrypt_key_ctx=ctx_load_out_"$alg_primary_obj"_"$alg_primary_key"-"$alg_create_obj"_"$alg_create_key" file_encrypt_output_data=encrypt_"$file_en_decrypt_key_ctx" file_decrypt_output_data=decrypt_"$file_en_decrypt_key_ctx" fail() { echo "$1 test fail, please check the environment or parameters!" exit 1 } Pass() { echo ""$1" pass" >>test_getpubak_pass.log } rm $file_primary_key_ctx $file_en_decrypt_key_pub $file_en_decrypt_key_priv $file_en_decrypt_key_name $file_en_decrypt_key_ctx $file_encrypt_output_data $file_decrypt_output_data -rf if [ ! -e "$file_input_data" ] then echo "12345678" > $file_input_data fi tpm2_takeownership -c tpm2_createprimary -A e -g $alg_primary_obj -G $alg_primary_key -C $file_primary_key_ctx if [ $? != 0 ];then fail createprimary fi tpm2_create -g $alg_create_obj -G $alg_create_key -o $file_en_decrypt_key_pub -O $file_en_decrypt_key_priv -c $file_primary_key_ctx if [ $? != 0 ];then fail create fi tpm2_load -c $file_primary_key_ctx -u $file_en_decrypt_key_pub -r $file_en_decrypt_key_priv -n $file_en_decrypt_key_name -C $file_en_decrypt_key_ctx if [ $? != 0 ];then fail load fi tpm2_encryptdecrypt -c $file_en_decrypt_key_ctx -D NO -I secret.data -o $file_encrypt_output_data if [ $? != 0 ];then fail decrypt fi tpm2_encryptdecrypt -c $file_en_decrypt_key_ctx -D YES -I $file_encrypt_output_data -o $file_decrypt_output_data if [ $? != 0 ];then fail decrypt fi echo "encryptdecrypt test OK!" tpm2-tools-2.1.0/test/system/test_tpm2_evictcontrol.sh000077500000000000000000000061001313543155100231060ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash file_primary_key_ctx=context.p_B1 file_evict_key_pub=opuB1_B8 file_evict_key_priv=oprB1_B8 file_evict_key_ctx=context_load_out_B1_B8 file_evict_key_name=name.load.B1_B8 persistentHandle=0x81010003 alg_hash=0x000B alg_primary_key=0x0001 alg_evict_key=0x0008 rm $file_primary_key_ctx $file_evict_key_pub $file_evict_key_priv $file_evict_key_ctx $file_evict_key_name $file_output_data -rf tpm2_takeownership -c tpm2_createprimary -A e -g $alg_hash -G $alg_primary_key -C $file_primary_key_ctx if [ $? != 0 ];then echo "createprimary fail, please check the environment or parameters!" exit 1 fi tpm2_create -g $alg_hash -G $alg_evict_key -o $file_evict_key_pub -O $file_evict_key_priv -c $file_primary_key_ctx if [ $? != 0 ];then echo "create fail, please check the environment or parameters!" exit 1 fi tpm2_load -c $file_primary_key_ctx -u $file_evict_key_pub -r $file_evict_key_priv -n $file_evict_key_name -C $file_evict_key_ctx if [ $? != 0 ];then echo "load fail, please check the environment or parameters!" exit 1 fi tpm2_evictcontrol -A o -c $file_evict_key_ctx -S $persistentHandle if [ $? != 0 ];then echo "evictontronl persistentHandle fail, please check the environment or parameters!" exit 1 else tpm2_evictcontrol -A o -H $persistentHandle -S $persistentHandle if [ $? != 0 ];then echo "evictcontrol release Handle fail, please check the environment or parameters!" exit 1 fi fi tpm2-tools-2.1.0/test/system/test_tpm2_getmanufec.sh000077500000000000000000000060441313543155100225200ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash echo "3a01000001000b00b20003002000837197674484b3f81a90cc8d46a5d724fd52\ d76e06520b64f2a1da1b331469aa000000000000000000000000000000000000\ 0000000000000000000000000000000006008000430010000000000000080000\ 000000000001c320e2f244a8601aacf3e01d26c665249935562de1da197e9e7f\ 076c469613cfb653e98ec2c386fc1d133f2c8c6cc338b732f0b208bd838a877a\ 3e5bbc3e1d4084e835c7c8906a1c05b4d2d30fdbebc1dbad950fa6b165bd4b6a\ 864603146164c0c4f59d489011ef1f928deea6e90061f3d375e5646273151ef6\ 22252098be1a4ab01dc0a12227c609fdaceb115af408d4693a6f49919774695b\ 0c12bc18a1ff7120a7337b2fb5f1951d8bb7f094d5b554c11c9523b30729fe64\ 787d0a13b9e630488dab4dfd86634a5270ec72fcc5a44dc679a8f32938dd8197\ e29dae839f5b4ca0f5de27c9522c23c54e1c2ce57859525118bd4470b18180ee\ f78ae4267bcd0000" | xxd -r -p > test_ek.pub tpm2_getmanufec -g 0x01 -O -N -U -E ECcert.bin -f test_ek.pub -S https://ekop.intel.com/ekcertservice/ if [ $? != 0 ];then echo "tpm2_getmanufec command failed, please check the environment or parameters!" exit 1 fi if [ $(md5sum ECcert.bin| awk '{ print $1 }') != "56af9eb8a271bbf7ac41b780acd91ff5" ]; then echo "Failed: retrieving endorsement certificate" exit 1 else echo "Successful: retrieving endorsement certificate" fi if [ ! -f ECcert.bin ]; then echo "ECcert.bin File not found!" else rm -f ECcert.bin fi if [ ! -f test_ek.pub ]; then echo "ECcert.bin File not found!" else rm -f test_ek.pub fi tpm2-tools-2.1.0/test/system/test_tpm2_getpubak.sh000077500000000000000000000045731313543155100222110ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash handle_ek=0x8101000b handle_ak=0x8101000c ek_alg=0x001 ak_alg=0x0001 digestAlg=0x000B signAlg=0x0014 output_ek_pub=ek_pub.out output_ak_pub=ak_pub.out output_ak_pub_name=ak_name_pub.out rm $output_ek_pub $output_ak_pub $output_ak_pub_name -rf tpm2_getpubek -H $handle_ek -g $ek_alg -f $output_ek_pub if [ $? != 0 ] || [ ! -e $output_ek_pub ];then echo "getpubek fail, please check the environment or parameters!" exit 1 fi tpm2_getpubak -E $handle_ek -k $handle_ak -g $ak_alg -D $digestAlg -s $signAlg -f $output_ak_pub -n $output_ak_pub_name if [ $? != 0 ] || [ ! -e $output_ak_pub ];then echo "getpubak fail, please check the environment or parameters!" exit 1 fi echo "getpubak successfully!" tpm2-tools-2.1.0/test/system/test_tpm2_getpubek.sh000077500000000000000000000040061313543155100222040ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash handle_ek=0x81010005 ek_alg=0x001 output_ek_pub=ek_pub.out if [ -f $output_ek_pub ]; then rm $output_ek_pub fi tpm2_getpubek -H $handle_ek -g $ek_alg -f $output_ek_pub if [ $? != 0 ] || [ ! -e $output_ek_pub ];then echo "getpubek fail, please check the environment or parameters!" exit 1 fi echo "getpubek successfully!" tpm2-tools-2.1.0/test/system/test_tpm2_getrandom.sh000077500000000000000000000036031313543155100223600ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/sh size=32 rm -f random.out tpm2_getrandom -o random.out 32 if [ $? != 0 ];then echo "getrandom test fail, please check the environment or parameters!" exit 1 else echo "getrandom succeed" fi tpm2-tools-2.1.0/test/system/test_tpm2_getrandom_func.sh000077500000000000000000000044621313543155100233770ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/sh #this script for tpm2_getrandom verification LOG_FILE=random_pass_count.log if [ -e "$LOG_FILE" ];then rm -f "$LOG_FILE" fi i= #for((i=1;i<=10;i++)); do for i in `seq 100`; do tpm2_getrandom o random_"$i".out 32 if [ $? != 0 ];then echo " create random_"$i".out fail, please check the environment or parameters!" exit 2 else echo "create random_"$i".out Pass" >>$LOG_FILE fi done for a in `seq 99` ;do b=$(($a+1)) while [ $b -le 100 ]; do diff "random_"$a".out" "random_"$b".out" >/dev/null if [ $? -eq 0 ];then echo "random test fial" exit 1 fi b=$(($b+1)) done done echo "random test Pass" tpm2-tools-2.1.0/test/system/test_tpm2_hash.sh000077500000000000000000000042611313543155100213240ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/sh #this script is for hash case testing halg=0x000B Hierarchy=e rm -f hash_out_"$Hierarchy"_"$halg" hash_tk_"$Hierarchy"_"$halg" if [ ! -f hash.in ];then echo "T0naX0u123abc" >hash.in fi tpm2_hash -H $Hierarchy -g $halg -I hash.in -o hash_out_"$Hierarchy"_"$halg" -t hash_tk_"$Hierarchy"_"$halg" if [ $? != 0 ];then echo "hash forHierarchy:"$Hierarchy"halg:"$halg" fail, please check the environment or parameters!" exit 1 else echo "hash for Hierarchy:"$Hierarchy"halg:"$halg" succed" fi tpm2-tools-2.1.0/test/system/test_tpm2_hash_all.sh000077500000000000000000000043341313543155100221550ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/sh #this script is for hash case testing halg= Hierarchy= rm test_hash.log if [ ! -f hash.in ];then echo "T0naX0u123abc" >hash.in fi for Hierarchy in e o p n do for halg in 0x0004 0x000B 0x000C 0x000D 0x0012 do tpm2_hash -H $Hierarchy -g $halg -I hash.in -o hash_out_"$Hierarchy"_"$halg" -t hash_tk_"$Hierarchy"_"$halg" if [ $? != 0 ];then echo "hash for hash_out_"$Hierarchy"_"$halg" fail, please check the environment or parameters!" else echo "hash for hash_out_"$Hierarchy"_"$halg" pass" >>test_hash_pass.log fi done done tpm2-tools-2.1.0/test/system/test_tpm2_hmac.sh000077500000000000000000000071031313543155100213070ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash alg_primary_obj=0x000B alg_primary_key=0x0001 alg_create_obj=0x000B alg_create_key=0x0008 halg=0x000B handle_hmac_key=0x81010013 file_primary_key_ctx=context.p_"$alg_primary_obj"_"$alg_primary_key" file_hmac_key_pub=opu_"$alg_create_obj"_"$alg_create_key" file_hmac_key_priv=opr_"$alg_create_obj"_"$alg_create_key" file_hmac_key_name=name.load_"$alg_primary_obj"_"$alg_primary_key"-"$alg_create_obj"_"$alg_create_key" file_hmac_key_ctx=ctx_load_out_"$alg_primary_obj"_"$alg_primary_key"-"$alg_create_obj"_"$alg_create_key" file_hmac_output=hmac_"$file_hmac_key_ctx" file_input_data=secret.data fail() { echo "$1 test fail, please check the environment or parameters!" exit 1 } Pass() { echo ""$1" pass" >>test_getpubak_pass.log } rm $file_primary_key_ctx $file_hmac_key_pub $file_hmac_key_priv $file_hmac_key_name $file_hmac_key_ctx $file_hmac_output -rf if [ ! -e "$file_input_data" ] then echo "12345678" > $file_input_data fi tpm2_takeownership -c tpm2_createprimary -A e -g $alg_primary_obj -G $alg_primary_key -C $file_primary_key_ctx if [ $? != 0 ];then fail createprimary fi tpm2_create -g $alg_create_obj -G $alg_create_key -o $file_hmac_key_pub -O $file_hmac_key_priv -c $file_primary_key_ctx if [ $? != 0 ];then fail create fi tpm2_load -c $file_primary_key_ctx -u $file_hmac_key_pub -r $file_hmac_key_priv -n $file_hmac_key_name -C $file_hmac_key_ctx if [ $? != 0 ];then fail load fi tpm2_hmac -c $file_hmac_key_ctx -g $halg -I $file_input_data -o $file_hmac_output if [ $? != 0 ];then fail hmac fi ####handle test rm -f $file_hmac_output tpm2_evictcontrol -A o -c $file_hmac_key_ctx -S $handle_hmac_key |tee evict.log c1="$?" grep "persistentHandle: "$handle_hmac_key"" evict.log c2="$?" if [ $c1 != 0 ] || [ $c2 != 0 ];then fail evict fi tpm2_hmac -k $handle_hmac_key -g $halg -I $file_input_data -o $file_hmac_output if [ $? != 0 ];then fail hmac fi tpm2-tools-2.1.0/test/system/test_tpm2_listpcrs.sh000077500000000000000000000040531313543155100222430ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash tpm2_listpcrs if [ $? != 0 ];then echo "listpcrs fail!" exit 1 fi tpm2_listpcrs -g 0x04 if [ $? != 0 ];then echo "listpcrs fail!" exit 1 fi rm -rf pcrs tpm2_listpcrs -L 0x04:17,18,19+0x0b:0,17,18,19 -o pcrs if [ $? != 0 ];then echo "listpcrs fail!" exit 1 fi tpm2_listpcrs -s if [ $? != 0 ];then echo "listpcrs fail!" exit 1 fi echo "listpcrs OK!" tpm2-tools-2.1.0/test/system/test_tpm2_load.sh000077500000000000000000000071571313543155100213270ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash alg_primary_obj=0x000B alg_primary_key=0x0001 alg_create_obj=0x000B alg_create_key=0x0008 alg_load=0x0004 file_primary_key_ctx=context.p_"$alg_primary_obj"_"$alg_primary_key" file_load_key_pub=opu_"$alg_create_obj"_"$alg_create_key" file_load_key_priv=opr_"$alg_create_obj"_"$alg_create_key" file_load_key_name=name.load_"$alg_primary_obj"_"$alg_primary_key"-"$alg_create_obj"_"$alg_create_key" file_load_key_ctx=ctx_load_out_"$alg_primary_obj"_"$alg_primary_key"-"$alg_create_obj"_"$alg_create_key" file_load_output=load_"$file_load_key_ctx" Handle_parent=0x81010018 Handle_ek_load=0x81010017 fail() { echo "$1 test fail, please check the environment or parameters!" # echo ""$1" fail" >>test_encryptdecrypt_error.log exit 1 } Pass() { echo ""$1" pass" >>test_getpubak_pass.log } rm $file_primary_key_ctx $file_load_key_pub $file_load_key_priv $file_load_key_name $file_load_key_ctx $file_load_output -rf tpm2_takeownership -c tpm2_createprimary -A e -g $alg_primary_obj -G $alg_primary_key -C $file_primary_key_ctx if [ $? != 0 ];then fail createprimary fi tpm2_create -g $alg_create_obj -G $alg_create_key -o $file_load_key_pub -O $file_load_key_priv -c $file_primary_key_ctx if [ $? != 0 ];then fail create fi tpm2_load -c $file_primary_key_ctx -u $file_load_key_pub -r $file_load_key_priv -n $file_load_key_name -C $file_load_key_ctx if [ $? != 0 ];then fail load fi #####handle test rm $file_load_key_pub $file_load_key_priv $file_load_key_name $file_load_key_ctx $file_load_output -rf tpm2_evictcontrol -A o -c $file_primary_key_ctx -S $Handle_parent if [ $? != 0 ];then fail evict fi tpm2_create -H $Handle_parent -g $alg_create_obj -G $alg_create_key -o $file_load_key_pub -O $file_load_key_priv if [ $? != 0 ];then fail create fi tpm2_load -H $Handle_parent -u $file_load_key_pub -r $file_load_key_priv -n $file_load_key_name -C $file_load_key_ctx if [ $? != 0 ];then fail load fi echo "load test OK!" tpm2-tools-2.1.0/test/system/test_tpm2_loadexternal.sh000077500000000000000000000075131313543155100230660ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash alg_primary_obj=0x000B alg_primary_key=0x0001 alg_create_obj=0x000B alg_create_key=0x0008 file_primary_key_ctx=context.p_"$alg_primary_obj"_"$alg_primary_key" file_loadexternal_key_pub=opu_"$alg_create_obj"_"$alg_create_key" file_loadexternal_key_priv=opr_"$alg_create_obj"_"$alg_create_key" file_loadexternal_key_name=name.loadexternal_"$alg_primary_obj"_"$alg_primary_key"-"$alg_create_obj"_"$alg_create_key" file_loadexternal_key_ctx=ctx_loadexternal_out_"$alg_primary_obj"_"$alg_primary_key"-"$alg_create_obj"_"$alg_create_key" file_loadexternal_output=loadexternal_"$file_loadexternal_key_ctx" Handle_parent=0x81010019 fail() { echo "$1 test fail, please check the environment or parameters!" # echo ""$1" fail" >>test_encryptdecrypt_error.log exit 1 } Pass() { echo ""$1" pass" >>test_getpubak_pass.log } rm $file_primary_key_ctx $file_loadexternal_key_pub $file_loadexternal_key_priv $file_loadexternal_key_name $file_loadexternal_key_ctx $file_loadexternal_output -rf tpm2_takeownership -c tpm2_createprimary -A e -g $alg_primary_obj -G $alg_primary_key -C $file_primary_key_ctx if [ $? != 0 ];then fail createprimary fi tpm2_create -g $alg_create_obj -G $alg_create_key -o $file_loadexternal_key_pub -O $file_loadexternal_key_priv -c $file_primary_key_ctx if [ $? != 0 ];then fail create fi ##tpm2_loadexternalexternal -H n -u $file_loadexternal_key_pub -r $file_loadexternal_key_priv -n $file_loadexternal_key_name -C $file_loadexternal_key_ctx tpm2_loadexternal -H n -u $file_loadexternal_key_pub -C $file_loadexternal_key_ctx if [ $? != 0 ];then fail loadexternal fi #####handle test rm $file_loadexternal_key_pub $file_loadexternal_key_priv $file_loadexternal_key_name $file_loadexternal_key_ctx $file_loadexternal_output -rf tpm2_evictcontrol -A o -c $file_primary_key_ctx -S $Handle_parent if [ $? != 0 ];then fail evict fi tpm2_create -H $Handle_parent -g $alg_create_obj -G $alg_create_key -o $file_loadexternal_key_pub -O $file_loadexternal_key_priv if [ $? != 0 ];then fail create fi tpm2_loadexternal -H n -u $file_loadexternal_key_pub if [ $? != 0 ];then fail loadexternal fi echo "loadexternal test OK!" tpm2-tools-2.1.0/test/system/test_tpm2_makecredential.sh000077500000000000000000000056141313543155100233540ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash handle_ek=0x81010007 handle_ak=0x81010008 ek_alg=0x001 ak_alg=0x0001 digestAlg=0x000B signAlg=0x0014 file_input_data=secret.data output_ek_pub=ek_pub.out output_ak_pub=ak_pub.out output_ak_pub_name=ak_name_pub.out output_mkcredential=mkcredential.out rm $output_ek_pub $output_ak_pub $output_ak_pub_name $output_mkcredential -rf if [ ! -e "$file_input_data" ] then echo "12345678" > $file_input_data fi tpm2_getpubek -H $handle_ek -g $ek_alg -f $output_ek_pub if [ $? != 0 ] || [ ! -e $output_ek_pub ];then echo "getpubek fail, please check the environment or parameters!" exit 1 fi tpm2_getpubak -E $handle_ek -k $handle_ak -g $ak_alg -D $digestAlg -s $signAlg -f $output_ak_pub -n $output_ak_pub_name |tee output_ak if [ $? != 0 ] || [ ! -e output_ak ];then echo "getpubak fail, please check the environment or parameters!" exit 1 fi grep -A 3 "Name of loaded key:" output_ak|tr "\n" " " >grep.txt Loadkeyname=`sed -e 's/ //g' grep.txt | awk -F':' '{print $2}'` tpm2_makecredential -e $output_ek_pub -s $file_input_data -n $Loadkeyname -o $output_mkcredential if [ $? != 0 ];then echo "makecredential fail, please check the environment or parameters!" exit 1 fi echo "makecredential successfully!" tpm2-tools-2.1.0/test/system/test_tpm2_nv.sh000077500000000000000000000053721313543155100210300ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash nv_test_index=0x1500018 nv_auth_handle=0x40000001 tpm2_takeownership -c if [ $? != 0 ];then echo "clean ownership Fail!" exit 1 fi tpm2_nvlist|grep -i $nv_test_index if [ $? = 0 ];then tpm2_nvrelease -x $nv_test_index -a $nv_auth_handle if [ $? != 0 ];then echo "please release the nv index $nv_test_index first!" exit 1 fi fi tpm2_nvdefine -x $nv_test_index -a $nv_auth_handle -s 32 -t 0x2000A if [ $? != 0 ];then echo "nvdefine fail,Please check your environment!" exit 1 fi if [ ! -f nv.test_w ];then echo "please123abc" >nv.test_w fi tpm2_nvwrite -x $nv_test_index -a $nv_auth_handle -f nv.test_w if [ $? != 0 ];then echo "nvwrite fail!" exit 1 fi tpm2_nvread -x $nv_test_index -a $nv_auth_handle -s 32 -o 0 if [ $? != 0 ];then echo "nvread fail!" exit 1 fi tpm2_nvlist|grep -i $nv_test_index if [ $? != 0 ];then echo "nvlist fail or double check the define index!" exit 1 fi tpm2_nvrelease -x $nv_test_index -a $nv_auth_handle if [ $? != 0 ];then echo "nvrelease fail or double check the define index!" exit 1 else echo "release the nv index OK!" fi tpm2-tools-2.1.0/test/system/test_tpm2_quote.sh000077500000000000000000000111361313543155100215350ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash alg_primary_obj=0x000B alg_primary_key=0x0001 alg_create_obj=0x000B alg_create_key=0x0008 alg_quote=0x0004 alg_quote1=0x000b file_primary_key_ctx=context.p_"$alg_primary_obj"_"$alg_primary_key" file_quote_key_pub=opu_"$alg_create_obj"_"$alg_create_key" file_quote_key_priv=opr_"$alg_create_obj"_"$alg_create_key" file_quote_key_name=name.load_"$alg_primary_obj"_"$alg_primary_key"-"$alg_create_obj"_"$alg_create_key" file_quote_key_ctx=ctx_load_out_"$alg_primary_obj"_"$alg_primary_key"-"$alg_create_obj"_"$alg_create_key" file_quote_output=quote_"$file_quote_key_ctx" Handle_ak_quote=0x81010016 Handle_ek_quote=0x81010017 nonce=12345abcde12345abcde12345abcde12345abcde12345abcde12345abcde12345abcde12345abcde12345abcde12345abcde fail() { echo "$1 test fail, please check the environment or parameters!" # echo ""$1" fail" >>test_encryptdecrypt_error.log exit 1 } Pass() { echo ""$1" pass" >>test_getpubak_pass.log } rm $file_primary_key_ctx $file_quote_key_pub $file_quote_key_priv $file_quote_key_name $file_quote_key_ctx $file_quote_output -rf tpm2_takeownership -c tpm2_createprimary -A e -g $alg_primary_obj -G $alg_primary_key -C $file_primary_key_ctx if [ $? != 0 ];then fail createprimary exit 1 fi tpm2_create -g $alg_create_obj -G $alg_create_key -o $file_quote_key_pub -O $file_quote_key_priv -c $file_primary_key_ctx if [ $? != 0 ];then fail create exit 1 fi tpm2_load -c $file_primary_key_ctx -u $file_quote_key_pub -r $file_quote_key_priv -n $file_quote_key_name -C $file_quote_key_ctx if [ $? != 0 ];then fail load fi tpm2_quote -c $file_quote_key_ctx -g $alg_quote -l 16,17,18 -o $file_quote_output -q $nonce if [ $? != 0 ];then fail quote fi rm $file_quote_output -rf tpm2_quote -c $file_quote_key_ctx -L $alg_quote:16,17,18+$alg_quote1:16,17,18 -o $file_quote_output -q $nonce if [ $? != 0 ];then fail quote fi #####handle testing tpm2_evictcontrol -A o -c $file_quote_key_ctx -S $Handle_ak_quote if [ $? != 0 ];then fail evict fi rm quote_handle_output_"$Handle_ak_quote" -rf tpm2_quote -k $Handle_ak_quote -g $alg_quote -l 16,17,18 -o quote_handle_output_"$Handle_ak_quote" -q $nonce if [ $? != 0 ];then fail quote_handle fi rm quote_handle_output_"$Handle_ak_quote" -rf tpm2_quote -k $Handle_ak_quote -L $alg_quote:16,17,18+$alg_quote1:16,17,18 -o quote_handle_output_"$Handle_ak_quote" -q $nonce if [ $? != 0 ];then fail quote_handle fi #####AK Handle_ak_quote=$(($Handle_ak_quote+0x2)) val=`echo 'obase=16;'$Handle_ak_quote''|bc` Handle_ak_quote=0x"$val" tpm2_getpubek -H $Handle_ek_quote -g 0x01 -f ek.pub2 if [ $? != 0 ];then fail getpubek fi tpm2_getpubak -E $Handle_ek_quote -k $Handle_ak_quote -f ak.pub2 -n ak.name_2 if [ $? != 0 ];then fail getpubak fi rm quote_handle_output_"$Handle_ak_quote" -rf tpm2_quote -k $Handle_ak_quote -g $alg_quote -l 16,17,18 -o quote_handle_output_"$Handle_ak_quote" -q $nonce if [ $? != 0 ];then fail quote_handle_ak fi echo "quote test OK!" tpm2-tools-2.1.0/test/system/test_tpm2_readpublic.sh000077500000000000000000000066321313543155100225170ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash alg_primary_obj=0x000B alg_primary_key=0x0001 alg_create_obj=0x000B alg_create_key=0x0008 file_primary_key_ctx=context.p_"$alg_primary_obj"_"$alg_primary_key" file_readpub_key_pub=opu_"$alg_create_obj"_"$alg_create_key" file_readpub_key_priv=opr_"$alg_create_obj"_"$alg_create_key" file_readpub_key_name=name.load_"$alg_primary_obj"_"$alg_primary_key"-"$alg_create_obj"_"$alg_create_key" file_readpub_key_ctx=ctx_load_out_"$alg_primary_obj"_"$alg_primary_key"-"$alg_create_obj"_"$alg_create_key" file_readpub_output=readpub_"$file_readpub_key_ctx" Handle_readpub=0x81010014 fail() { echo "$1 test fail, please check the environment or parameters!" exit 1 } Pass() { echo ""$1" pass" >>test_getpubak_pass.log } rm $file_primary_key_ctx $file_readpub_key_pub $file_readpub_key_priv $file_readpub_key_name $file_readpub_key_ctx $file_readpub_output -rf tpm2_takeownership -c tpm2_createprimary -A e -g $alg_primary_obj -G $alg_primary_key -C $file_primary_key_ctx if [ $? != 0 ];then fail createprimary fi tpm2_create -g $alg_create_obj -G $alg_create_key -o $file_readpub_key_pub -O $file_readpub_key_priv -c $file_primary_key_ctx if [ $? != 0 ];then fail create fi tpm2_load -c $file_primary_key_ctx -u $file_readpub_key_pub -r $file_readpub_key_priv -n $file_readpub_key_name -C $file_readpub_key_ctx if [ $? != 0 ];then fail load fi tpm2_readpublic -c $file_readpub_key_ctx -o $file_readpub_output if [ $? != 0 ];then fail decrypt fi #####handle testing tpm2_evictcontrol -A o -c $file_readpub_key_ctx -S $Handle_readpub if [ $? != 0 ];then fail evict fi rm $file_readpub_output -rf tpm2_readpublic -H $Handle_readpub -o $file_readpub_output if [ $? != 0 ];then fail readpublic_handle fi echo "readpublic test OK!" tpm2-tools-2.1.0/test/system/test_tpm2_rsadecrypt.sh000077500000000000000000000071141313543155100225610ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash file_primary_key_ctx=context.p_B1 file_rsaencrypt_key_pub=opuB1_B8 file_rsaencrypt_key_priv=oprB1_B8 file_rsaencrypt_key_ctx=context_loadext_out_B1_B8 file_rsadecrypt_key_ctx=context_load_out_B1_B8 file_rsaencrypt_key_name=name.load.B1_B8 file_rsa_en_output_data=rsa_en.out file_rsa_de_output_data=rsa_de.out file_input_data=secret.data alg_hash=0x000B alg_primary_key=0x0001 alg_rsaencrypt_key=0x0001 if [ ! -e "$file_input_data" ] then echo "12345678" > $file_input_data fi rm $file_primary_key_ctx $file_rsaencrypt_key_pub $file_rsaencrypt_key_priv $file_rsaencrypt_key_ctx $file_rsaencrypt_key_name $file_output_data $file_rsa_en_output_data $file_rsa_de_output_data -rf tpm2_takeownership -c tpm2_createprimary -A e -g $alg_hash -G $alg_primary_key -C $file_primary_key_ctx if [ $? != 0 ];then echo "createprimary fail, please check the environment or parameters!" exit 1 fi tpm2_create -g $alg_hash -G $alg_rsaencrypt_key -o $file_rsaencrypt_key_pub -O $file_rsaencrypt_key_priv -c $file_primary_key_ctx if [ $? != 0 ];then echo "create fail, please check the environment or parameters!" exit 1 fi tpm2_loadexternal -H n -u $file_rsaencrypt_key_pub -C $file_rsaencrypt_key_ctx if [ $? != 0 ];then echo "loadexternal fail, please check the environment or parameters!" exit 1 fi tpm2_rsaencrypt -c $file_rsaencrypt_key_ctx -I $file_input_data -o $file_rsa_en_output_data if [ $? != 0 ];then echo "rsa encrypt fail, please check the environment or parameters!" exit 1 fi tpm2_load -c $file_primary_key_ctx -u $file_rsaencrypt_key_pub -r $file_rsaencrypt_key_priv -n $file_rsaencrypt_key_name -C $file_rsadecrypt_key_ctx if [ $? != 0 ];then echo "load fail, please check the environment or parameters!" exit 1 fi tpm2_rsadecrypt -c $file_rsadecrypt_key_ctx -I $file_rsa_en_output_data -o $file_rsa_de_output_data if [ $? != 0 ];then echo "rsa decrypt fail, please check the environment or parameters!" exit 1 fi tpm2-tools-2.1.0/test/system/test_tpm2_rsaencrypt.sh000077500000000000000000000061621313543155100225750ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash file_primary_key_ctx=context.p_B1 file_rsaencrypt_key_pub=opuB1_B8 file_rsaencrypt_key_priv=oprB1_B8 file_rsaencrypt_key_ctx=context_load_out_B1_B8 file_rsaencrypt_key_name=name.load.B1_B8 file_rsa_en_output_data=rsa_en.out file_input_data=secret.data alg_hash=0x000B alg_primary_key=0x0001 alg_rsaencrypt_key=0x0001 if [ ! -e "$file_input_data" ] then echo "12345678" > $file_input_data fi rm $file_primary_key_ctx $file_rsaencrypt_key_pub $file_rsaencrypt_key_priv $file_rsaencrypt_key_ctx $file_rsaencrypt_key_name $file_output_data $file_rsa_en_output_data -rf tpm2_takeownership -c tpm2_createprimary -A e -g $alg_hash -G $alg_primary_key -C $file_primary_key_ctx if [ $? != 0 ];then echo "createprimary fail, please check the environment or parameters!" exit 1 fi tpm2_create -g $alg_hash -G $alg_rsaencrypt_key -o $file_rsaencrypt_key_pub -O $file_rsaencrypt_key_priv -c $file_primary_key_ctx if [ $? != 0 ];then echo "create fail, please check the environment or parameters!" exit 1 fi tpm2_loadexternal -H n -u $file_rsaencrypt_key_pub -C $file_rsaencrypt_key_ctx if [ $? != 0 ];then echo "loadexternal fail, please check the environment or parameters!" exit 1 fi #./tpm2_rsaencrypt -c context_loadexternal_out6.out -I secret.data -o rsa_en.out tpm2_rsaencrypt -c $file_rsaencrypt_key_ctx -I $file_input_data -o $file_rsa_en_output_data if [ $? != 0 ];then echo "rsa encrypt fail, please check the environment or parameters!" exit 1 fi tpm2-tools-2.1.0/test/system/test_tpm2_send_command.sh000077500000000000000000000040331313543155100230250ustar00rootroot00000000000000#!/bin/sh #;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; # assume this script is run from the test/ directory TPM2_COMMAND_FILE=fixtures/get-capability-tpm-prop-fixed.bin if [ ! -f "${TPM2_COMMAND_FILE}" ]; then echo "No TPM2 command file, cannot run $0" exit 1 fi tpm2_send_command < ${TPM2_COMMAND_FILE} > /dev/null if [ $? -ne 0 ]; then echo "tpm2_send_command failed." exit 1 fi echo "tpm2_send_command success" tpm2-tools-2.1.0/test/system/test_tpm2_sign.sh000077500000000000000000000065431313543155100213460ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash file_primary_key_ctx=context.p_B1 file_signing_key_pub=opuB1_B8 file_signing_key_priv=oprB1_B8 file_signing_key_ctx=context_load_out_B1_B8 file_signing_key_name=name.load.B1_B8 file_input_data=secret.data file_output_data=sig.4 handle_signing_key=0x81010005 alg_hash=0x000B alg_primary_key=0x0001 alg_signing_key=0x0008 fail() { echo "$1 test fail, please check the environment or parameters!" exit 1 } Pass() { echo ""$1" pass" >>test_getpubak_pass.log } if [ ! -e "$file_input_data" ] then echo "12345678" > $file_input_data fi rm $file_primary_key_ctx $file_signing_key_pub $file_signing_key_priv $file_signing_key_ctx $file_signing_key_name $file_output_data -rf tpm2_takeownership -c tpm2_createprimary -A e -g $alg_hash -G $alg_primary_key -C $file_primary_key_ctx if [ $? != 0 ];then fail createprimary fi tpm2_create -g $alg_hash -G $alg_signing_key -o $file_signing_key_pub -O $file_signing_key_priv -c $file_primary_key_ctx if [ $? != 0 ];then fail create fi tpm2_load -c $file_primary_key_ctx -u $file_signing_key_pub -r $file_signing_key_priv -n $file_signing_key_name -C $file_signing_key_ctx if [ $? != 0 ];then fail load fi tpm2_sign -c $file_signing_key_ctx -g $alg_hash -m $file_input_data -s $file_output_data if [ ! -e "$file_output_data" ];then fail sign else rm $file_output_data -rf fi tpm2_evictcontrol -A o -c $file_signing_key_ctx -S $handle_signing_key |tee evict.log c1="$?" grep "persistentHandle: "$handle_signing_key"" evict.log c2="$?" if [ $c1 != 0 ] || [ $c2 != 0 ];then fail evictcontrol fi tpm2_sign -k $handle_signing_key -g $alg_hash -m $file_input_data -s $file_output_data if [ $? != 0 ];then fail sign fi tpm2-tools-2.1.0/test/system/test_tpm2_startup.sh000077500000000000000000000036101313543155100221000ustar00rootroot00000000000000#!/bin/sh #;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; tpm2_startup --clear if [ $? -ne 0 ]; then echo "tpm2_startup --clear failed." exit 1 fi tpm2_startup --state if [ $? -ne 0 ]; then echo "tpm2_startup --state failed." exit 1 fi echo "tpm2_startup success" exit 0 tpm2-tools-2.1.0/test/system/test_tpm2_takeownership_all.sh000077500000000000000000000046171313543155100241210ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash ownerPasswd=abc123 endorsePasswd=abc123 lockPasswd=abc123 new_ownerPasswd=newpswd new_endorsePasswd=newpswd new_lockPasswd=newpswd tpm2_takeownership -c if [ $? != 0 ];then echo "clean ownership Fail!" exit 1 fi tpm2_takeownership -o $ownerPasswd -e $endorsePasswd -l $lockPasswd if [ $? != 0 ];then echo "take ownership Fail, check your envirnoment!" exit 1 fi tpm2_takeownership -O $ownerPasswd -E $endorsePasswd -L $lockPasswd -o $new_ownerPasswd -e $new_endorsePasswd -l $new_lockPasswd if [ $? != 0 ];then echo "re-take ownership Fail, check your envirnoment!" exit 1 fi tpm2_takeownership -c -L $new_lockPasswd if [ $? != 0 ];then echo "clean ownership fail with lock password!" exit 1 fi tpm2-tools-2.1.0/test/system/test_tpm2_unseal.sh000077500000000000000000000073461313543155100216770ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash alg_primary_obj=0x0004 alg_primary_key=0x0001 alg_create_obj=0x000B alg_create_key=0x0008 file_input_data=secret.data file_primary_key_ctx=context.p_"$alg_primary_obj"_"$alg_primary_key" file_unseal_key_pub=opu_"$alg_create_obj"_"$alg_create_key" file_unseal_key_priv=opr_"$alg_create_obj"_"$alg_create_key" file_unseal_key_ctx=ctx_load_out_"$alg_primary_obj"_"$alg_primary_key"-"$alg_create_obj"_"$alg_create_key" file_unseal_key_name=name.load_"$alg_primary_obj"_"$alg_primary_key"-"$alg_create_obj"_"$alg_create_key" file_unseal_output_data=usl_"$file_unseal_key_ctx" rm $file_primary_key_ctx $file_unseal_key_pub $file_unseal_key_priv $file_unseal_key_ctx $file_unseal_key_name $file_unseal_output_data -rf if [ ! -e "$file_input_data" ] then echo "12345678" > $file_input_data fi tpm2_takeownership -c tpm2_createprimary -A p -g $alg_primary_obj -G $alg_primary_key -C $file_primary_key_ctx if [ $? != 0 ];then echo "createprimary fail, please check the environment or parameters!" exit 1 fi #./tpm2_create -g 0x000B -G 0x0008 -o opu9.out -O opr9.out -c context.p9.out -I secret.data tpm2_create -g $alg_create_obj -G $alg_create_key -o $file_unseal_key_pub -O $file_unseal_key_priv -I $file_input_data -c $file_primary_key_ctx if [ $? != 0 ];then echo "create fail, please check the environment or parameters!" exit 1 fi #./tpm2_load -c context.p9.out -u opu9.out -r opr9.out -n name.load9.out -C context_load_out9.out tpm2_load -c $file_primary_key_ctx -u $file_unseal_key_pub -r $file_unseal_key_priv -n $file_unseal_key_name -C $file_unseal_key_ctx if [ $? != 0 ];then echo "load fail, please check the environment or parameters!" exit 1 fi #tpm2_unseal -c context_load_out1.out -o usl.data.out tpm2_unseal -c $file_unseal_key_ctx -o $file_unseal_output_data if [ $? != 0 ];then echo "unseal fail, please check the environment or parameters!" exit 1 fi ###handle test blocked ##tpm2_evictcontrol -A p -c $file_unseal_key_ctx -S 0x81010015 --Fail to evict ##tpm2_evictcontrol -A o -c context_load_out4 -S 0x81010015 (0x285) ##tpm2_unseal -H 0x81010015 -o usl_handle tpm2-tools-2.1.0/test/system/test_tpm2_verifysignature.sh000077500000000000000000000105521313543155100236270ustar00rootroot00000000000000#;**********************************************************************; # # Copyright (c) 2016, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. #;**********************************************************************; #!/bin/bash file_primary_key_ctx=context.p_B1 file_signing_key_pub=opuB1_B8 file_signing_key_priv=oprB1_B8 file_signing_key_ctx=context_load_out_B1_B8 file_signing_key_name=name.load.B1_B8 file_input_data=secret.data file_output_data=sig.4 file_verify_tk_data=tickt_verify_sig.4 file_input_data_hash=secret_hash.data file_input_data_hash_tk=secret_hash_tk.data handle_signing_key=0x81010005 alg_hash=0x000B alg_primary_key=0x0001 alg_signing_key=0x0001 fail() { echo "$1 test fail, please check the environment or parameters!" exit 1 } Pass() { echo ""$1" pass" >>test_getpubak_pass.log } if [ ! -e "$file_input_data" ] then echo "12345678" > $file_input_data fi rm $file_primary_key_ctx $file_signing_key_pub $file_signing_key_priv $file_signing_key_ctx $file_signing_key_name $file_output_data $file_verify_tk_data $file_input_data_hash $file_input_data_hash_tk -rf tpm2_takeownership -c tpm2_createprimary -A e -g $alg_hash -G $alg_primary_key -C $file_primary_key_ctx if [ $? != 0 ];then fail createprimary fi tpm2_create -g $alg_hash -G $alg_signing_key -o $file_signing_key_pub -O $file_signing_key_priv -c $file_primary_key_ctx if [ $? != 0 ];then fail create fi tpm2_load -c $file_primary_key_ctx -u $file_signing_key_pub -r $file_signing_key_priv -n $file_signing_key_name -C $file_signing_key_ctx if [ $? != 0 ];then fail load fi tpm2_sign -c $file_signing_key_ctx -g $alg_hash -m $file_input_data -s $file_output_data if [ ! -e "$file_output_data" ];then echo "no outputfile,sign test Fail!" exit 1 fi #tpm2_verifysignature -c context_load_out_6 -g 0x000B -m secret.data -s sign.f1 -t tickt_verify_sign.out tpm2_verifysignature -c $file_signing_key_ctx -g $alg_hash -m $file_input_data -s $file_output_data -t $file_verify_tk_data if [ $? != 0 ];then fail verifysignature fi #./tpm2_hash -H n -g 0x00B -I secret.data -o hash.f.01 -t hash.tk.f.01 tpm2_hash -H n -g $alg_hash -I $file_input_data -o $file_input_data_hash -t $file_input_data_hash_tk if [ ! -e "$file_input_data_hash" ];then echo "hash $file_input_data Fail!" exit 1 fi rm $file_verify_tk_data -rf tpm2_verifysignature -c $file_signing_key_ctx -D $file_input_data_hash -s $file_output_data -t $file_verify_tk_data if [ $? != 0 ];then fail verifysignature fi rm $file_verify_tk_data $file_signing_key_ctx -rf tpm2_loadexternal -H n -u $file_signing_key_pub -C $file_signing_key_ctx if [ ! -e "$file_signing_key_ctx" ];then fail Loadexternal fi ###need debug 0x2cb error first ## tpm2_verifysignature -c $file_signing_key_ctx -g $alg_hash -m $file_input_data -s $file_output_data -t $file_verify_tk_data if [ $? != 0 ];then fail verifysignature fi tpm2-tools-2.1.0/test/unit/000077500000000000000000000000001313543155100154715ustar00rootroot00000000000000tpm2-tools-2.1.0/test/unit/test_files.c000066400000000000000000000203601313543155100177770ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2016, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include #include "files.h" typedef struct test_file test_file; struct test_file { char *path; FILE *file; }; static test_file *test_file_new(void) { test_file *tf = malloc(sizeof(test_file)); if (!tf) { return NULL; } tf->path = strdup("xxx_test_files_xxx.test"); if (!tf->path) { free(tf); return NULL; } tf->file = fopen(tf->path, "w+b"); if (!tf->file) { free(tf->path); free(tf); return NULL; } return tf; } static void test_file_free(test_file *tf) { assert_non_null(tf); int rc = remove(tf->path); assert_return_code(rc, errno); free(tf->path); fclose(tf->file); free(tf); } static int test_setup(void **state) { test_file *tf = test_file_new(); assert_non_null(tf); *state = tf; return 0; } static int test_teardown(void **state) { test_file *tf = (test_file *)*state; test_file_free(tf); return 0; } static test_file *test_file_from_state(void **state) { test_file *f = (test_file *)*state; assert_non_null(f); return f; } #define READ_WRITE_TEST(size, expected) \ static void test_file_read_write_##size(void **state) { \ \ FILE *f = test_file_from_state(state)->file; \ \ bool res = files_write_##size(f, expected); \ assert_true(res); \ \ rewind(f); \ \ UINT##size found; \ res = files_read_##size(f, &found); \ assert_true(res); \ \ assert_int_equal(found, expected); \ } READ_WRITE_TEST(16, 0xABCD) READ_WRITE_TEST(32, 0x11223344) READ_WRITE_TEST(64, 0x1122334455667788) static void test_file_read_write_bytes(void **state) { FILE *f = test_file_from_state(state)->file; UINT8 expected[1024]; memset(expected, 0xBB, sizeof(expected)); bool res = files_write_bytes(f, expected, sizeof(expected)); assert_true(res); rewind(f); UINT8 found[1024] = { 0 }; res = files_read_bytes(f, found, sizeof(found)); assert_memory_equal(expected, found, sizeof(found)); } static void test_file_read_write_0_bytes(void **state) { FILE *f = test_file_from_state(state)->file; UINT8 data[1]; bool res = files_write_bytes(f, data, 0); assert_true(res); res = files_read_bytes(f, data, 0); assert_true(res); } static void test_file_read_write_header(void **state) { FILE *f = test_file_from_state(state)->file; UINT32 expected = 0xAABBCCDD; bool res = files_write_header(f, expected); assert_true(res); rewind(f); UINT32 found; res = files_read_header(f, &found); assert_true(res); assert_int_equal(expected, found); } #define READ_WRITE_TEST_BAD_PARAMS(size) \ static void test_file_read_write_bad_params_##size(void **state) { \ \ UINT##size expected = 42; \ FILE *f = test_file_from_state(state)->file; \ bool res = files_write_##size(NULL, expected); \ assert_false(res); \ \ UINT##size found; \ res = files_read_##size(NULL, &found); \ assert_false(res); \ \ res = files_read_##size(f, NULL); \ assert_false(res); \ \ res = files_read_##size(NULL, NULL); \ assert_false(res); \ } READ_WRITE_TEST_BAD_PARAMS(16) READ_WRITE_TEST_BAD_PARAMS(32) READ_WRITE_TEST_BAD_PARAMS(64) static void test_file_read_write_bad_params_bytes(void **state) { FILE *f = test_file_from_state(state)->file; UINT8 data[1]; bool res = files_write_bytes(f, NULL, sizeof(data)); assert_false(res); res = files_write_bytes(NULL, data, sizeof(data)); assert_false(res); res = files_read_bytes(f, NULL, sizeof(data)); assert_false(res); res = files_read_bytes(NULL, data, sizeof(data)); assert_false(res); } static void test_file_size(void **state) { test_file *tf = test_file_from_state(state); UINT8 data[128] = { 0 }; bool res = files_write_bytes(tf->file, data, sizeof(data)); assert_true(res); int rc = fflush(tf->file); assert_return_code(rc, errno); long file_size; res = files_get_file_size(tf->path, &file_size); assert_true(res); assert_int_equal(file_size, sizeof(data)); } static void test_file_size_bad_args(void **state) { long file_size; bool res = files_get_file_size("this_should_be_a_bad_path", &file_size); assert_false(res); res = files_get_file_size(NULL, &file_size); assert_false(res); test_file *tf = test_file_from_state(state); res = files_get_file_size(tf->path, NULL); assert_false(res); } static void test_file_exists(void **state) { test_file *tf = test_file_from_state(state); bool res = files_does_file_exist(tf->path); assert_true(res); } static void test_file_exists_bad_args(void **state) { (void) state; bool res = files_does_file_exist("this_should_be_a_bad_path"); assert_false(res); res = files_does_file_exist(NULL); assert_false(res); } int main(int argc, char* argv[]) { (void)argc; (void)argv; const struct CMUnitTest tests[] = { cmocka_unit_test_setup_teardown(test_file_read_write_16, test_setup, test_teardown), cmocka_unit_test_setup_teardown(test_file_read_write_32, test_setup, test_teardown), cmocka_unit_test_setup_teardown(test_file_read_write_64, test_setup, test_teardown), cmocka_unit_test_setup_teardown(test_file_read_write_bytes, test_setup, test_teardown), cmocka_unit_test_setup_teardown(test_file_read_write_0_bytes, test_setup, test_teardown), cmocka_unit_test_setup_teardown(test_file_read_write_header, test_setup, test_teardown), cmocka_unit_test_setup_teardown(test_file_read_write_bad_params_16, test_setup, test_teardown), cmocka_unit_test_setup_teardown(test_file_read_write_bad_params_32, test_setup, test_teardown), cmocka_unit_test_setup_teardown(test_file_read_write_bad_params_64, test_setup, test_teardown), cmocka_unit_test_setup_teardown(test_file_read_write_bad_params_bytes, test_setup, test_teardown), cmocka_unit_test_setup_teardown(test_file_size, test_setup, test_teardown), cmocka_unit_test_setup_teardown(test_file_size_bad_args, test_setup, test_teardown), cmocka_unit_test_setup_teardown(test_file_exists, test_setup, test_teardown), cmocka_unit_test_setup_teardown(test_file_exists_bad_args, test_setup, test_teardown), }; return cmocka_run_group_tests(tests, NULL, NULL); } tpm2-tools-2.1.0/test/unit/test_string_bytes.c000066400000000000000000000052321313543155100214120ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2016, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include "string-bytes.h" static void test_is_big_endian(void **state) { uint16_t test = 0xFF00; uint8_t *b = (uint8_t *)&test; (void)state; bool test_host_is_big_endian = b[0] == 0xFF; bool host_is_big_endian = string_bytes_is_host_big_endian(); assert_true(test_host_is_big_endian == host_is_big_endian); } #define TEST_ENDIAN_CONVERT(size, value, expected) \ static void test_convert_##size(void **state) { \ \ (void)state; \ UINT##size test = string_bytes_endian_convert_##size(value); \ assert_int_equal(test, expected); \ } TEST_ENDIAN_CONVERT(16, 0xFF00, 0x00FF) TEST_ENDIAN_CONVERT(32, 0xAABBCCDD, 0xDDCCBBAA) TEST_ENDIAN_CONVERT(64, 0x0011223344556677, 0x7766554433221100) int main(int argc, char* argv[]) { (void)argc; (void)argv; const struct CMUnitTest tests[] = { cmocka_unit_test(test_is_big_endian), cmocka_unit_test(test_convert_16), cmocka_unit_test(test_convert_32), cmocka_unit_test(test_convert_64), }; return cmocka_run_group_tests(tests, NULL, NULL); } tpm2-tools-2.1.0/test/unit/tpm2-rc-decode_unit.c000066400000000000000000000460551313543155100214130ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2016, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include "rc-decode.h" #define TPM_RC_ALL_1 0xffffffff /* Check our ability to determine RC format. The spec is massively (IMHO) * confusing on this point. See section 6.6.3 from part 2 for some clarity. * specifically the NOTE immediately before table 17 */ static void tpm2_rc_is_format_zero_true (void **state) { (void) state; TPM_RC rc = 0xffffff7f; assert_true (tpm2_rc_is_format_zero (rc)); } static void tpm2_rc_is_format_zero_false (void **state) { (void) state; TPM_RC rc = TPM_RC_ALL_1; assert_false (tpm2_rc_is_format_zero (rc)); } static void tpm2_rc_is_format_one_true (void **state) { (void) state; TPM_RC rc = TPM_RC_ALL_1; assert_true (tpm2_rc_is_format_one (rc)); } static void tpm2_rc_is_format_one_false (void **state) { (void) state; TPM_RC rc = 0xffffff7f; assert_false (tpm2_rc_is_format_one (rc)); } /* Bits 7 and 8 in the TPM_RC are set to 0 for TPM1.2 return codes. * Here we test to be sure the is_tpm2_rc function identifies this RC as such. * All other bits in the RC are set to 1 since the comparison is done using a * logical AND operation. */ static void tpm2_rc_is_tpm12_true (void **state) { (void) state; /* bits 7 & 8 clear */ TPM_RC rc = 0xfffffe7f; assert_true (tpm2_rc_is_tpm12 (rc)); } static void tpm2_rc_is_tpm12_false (void **state) { (void) state; TPM_RC rc = 0xfffffe7f; assert_false (tpm2_rc_is_tpm2 (rc)); } /* If either of bits 7 or 8 are set the response code is a TPM2 response. * The next 3 tests go through the 3 possible permutations (01, 10 & 11) * for these two bits. */ static void tpm2_rc_is_tpm2_01 (void **state) { (void) state; /* bit 7 set, bit 8 clear */ TPM_RC rc = 0xfffffeff; assert_true (tpm2_rc_is_tpm2 (rc)); } static void tpm2_rc_is_tpm2_10 (void **state) { (void) state; /* bit 7 clear, bit 8 set */ TPM_RC rc = 0xffffff7f; assert_true (tpm2_rc_is_tpm2 (rc)); } static void tpm2_rc_is_tpm2_11 (void **state) { (void) state; /* bit 7 and 8 set */ TPM_RC rc = TPM_RC_ALL_1; assert_true (tpm2_rc_is_tpm2 (rc)); } /* Vendor defined response codes have bit 8 and 10 set and bit 7 cleared. */ static void tpm2_rc_is_vendor_defined_code_all_but_7 (void **state) { (void) state; /* bit 7 clear, bit 8 and 10 set */ TPM_RC rc = 0xffffff7f; assert_true (tpm2_rc_is_vendor_defined (rc)); } /* Negative case for bit 7 */ static void tpm2_rc_is_vendor_defined_code_7_set (void **state) { (void) state; /* bit 7, 8 and 10 set */ TPM_RC rc = TPM_RC_ALL_1; assert_false (tpm2_rc_is_vendor_defined (rc)); } /* Negative case for bit 8 */ static void tpm2_rc_is_vendor_defined_code_8_unset (void **state) { (void) state; /* bit 7 and 8 clear, bit 10 set */ TPM_RC rc = 0xfffffe7f; assert_false (tpm2_rc_is_vendor_defined (rc)); } /* Negative case for bit 10 */ static void tpm2_rc_is_vendor_defined_code_10_unset (void **state) { (void) state; /* bit 7 and 10 clear, bit 8 set */ TPM_RC rc = 0xfffffb7f; assert_false (tpm2_rc_is_vendor_defined (rc)); } /* Case to show that an unrelated bit has no effect. */ static void tpm2_rc_is_vendor_defined_code_no_9 (void **state) { (void) state; /* bit 7 and 9 clear, bit 8 and 10 set */ TPM_RC rc = 0xfffffd7f; assert_true (tpm2_rc_is_vendor_defined (rc)); } /* Warning codes have bit 8 and 11 set, and bits 7 and 10 clear. */ static void tpm2_rc_is_warning_code_success (void **state) { (void) state; /* bit 7 and 10 clear, bit 8 and 11 set */ TPM_RC rc = 0xfffff97f; assert_true (tpm2_rc_is_warning_code (rc)); } /* Negitive case for bit 8 */ static void tpm2_rc_is_warning_code_8_unset (void **state) { (void) state; /* bit 7, 8 and 10 clear, bit 11 set */ TPM_RC rc = 0xfffffa7f; assert_false (tpm2_rc_is_warning_code (rc)); } /* Negative case for bit 7 */ static void tpm2_rc_is_warning_code_7_set (void **state) { (void) state; /* bit 7, 8 and 11 set, bit 10 clear */ TPM_RC rc = 0xfffff9ff; assert_false (tpm2_rc_is_warning_code (rc)); } /* Negative case for bit 10 */ static void tpm2_rc_is_warning_code_10_set (void **state) { (void) state; /* bit 8, 10 and 11 set, bit 7 clear */ TPM_RC rc = 0xfffff7f; assert_false (tpm2_rc_is_warning_code (rc)); } /* Negative case for bit 11 */ static void tpm2_rc_is_warning_code_11_unset (void **state) { (void) state; /* bit 8 set, bits 7, 10 and 11 clear */ TPM_RC rc = 0xfffff37f; assert_false (tpm2_rc_is_warning_code (rc)); } /* Error code in bit [6:0] if bit 8 set, and bit 7, 10 and 11 clear. */ static void tpm2_rc_is_error_code_success (void **state) { (void) state; TPM_RC rc = 0xfffff37f; assert_true (tpm2_rc_is_error_code (rc)); } /* Negative case for bit 8 */ static void tpm2_rc_is_error_code_8_unset (void **state) { (void) state; /* bit 7, 8, 10 and 11 clear */ TPM_RC rc = 0xfffff27f; assert_false (tpm2_rc_is_error_code (rc)); } /* Negative case for bit 7 */ static void tpm2_rc_is_error_code_7_set (void **state) { (void) state; /* bit 7 and 8 set, bit 10 and 11 clear*/ TPM_RC rc = 0xfffff3ff; assert_false (tpm2_rc_is_error_code (rc)); } /* Negative case for bit 10 */ static void tpm2_rc_is_error_code_10_set (void **state) { (void) state; /* bit 8 and 10 set, bit 7 and 11 clear */ TPM_RC rc = 0xfffff77f; assert_false (tpm2_rc_is_error_code (rc)); } /* Negative case for bit 11 */ static void tpm2_rc_is_error_code_11_set (void **state) { (void) state; /* bit 8 and 11 set, bit 7 and 10 clear*/ TPM_RC rc = 0xfffffb7f; assert_false (tpm2_rc_is_error_code (rc)); } /* Error code in bits [5:0] with parameter number in bits [11:8] when * bits 6 and 7 are set. */ static void tpm2_rc_is_error_code_with_parameter_success (void **state) { (void) state; TPM_RC rc = TPM_RC_ALL_1; assert_true (tpm2_rc_is_error_code_with_parameter (rc)); } /* Negative case for bit 6 */ static void tpm2_rc_is_error_code_with_parameter_6_unset (void **state) { (void) state; /* bit 6 clear, bit 7 set */ TPM_RC rc = 0xffffffbf; assert_false (tpm2_rc_is_error_code_with_parameter (rc)); } /* Negative case for bit 7 */ static void tpm2_rc_is_error_code_with_parameter_7_unset (void **state) { (void) state; /* bit 6 set, bit 7 clear */ TPM_RC rc = 0xffffff7f; assert_false (tpm2_rc_is_error_code_with_parameter (rc)); } /* Error code in bits [5:0] with handle number in bits [10:8] when * bit 7 is set and bits 6 and 11 are clear. */ static void tpm2_rc_is_error_code_with_handle_success (void **state) { (void) state; TPM_RC rc = 0xfffff7bf; assert_true (tpm2_rc_is_error_code_with_handle (rc)); } /* Negative case for bit 6 */ static void tpm2_rc_is_error_code_with_handle_6_set (void **state) { (void) state; /* bit 6 and 7 set, bit 11 clear*/ TPM_RC rc = 0xfffff7ff; assert_false (tpm2_rc_is_error_code_with_handle (rc)); } /* Negative case for bit 7 */ static void tpm2_rc_is_error_code_with_handle_7_unset (void **state) { (void) state; /* bit 6, 7 and 11 clear */ TPM_RC rc = 0xfffff73f; assert_false (tpm2_rc_is_error_code_with_handle (rc)); } /* Negative case for bit 11 */ static void tpm2_rc_is_error_code_with_handle_11_set (void **state) { (void) state; /* bit 6 clear, bit 7 and 11 clear */ TPM_RC rc = 0xffffffbf; assert_false (tpm2_rc_is_error_code_with_handle (rc)); } /* Error code in bits [05:00] with session number in bits [10:08] when * bit 6 is clear and bits 7 and 11 set. */ static void tpm2_rc_is_error_code_with_session_success (void **state) { (void) state; /* bit 6 clear, bits 7 & 11 set */ TPM_RC rc = 0xffffffbf; assert_true (tpm2_rc_is_error_code_with_session (rc)); } /* Negative case for bit 6 */ static void tpm2_rc_is_error_code_with_session_6_set (void **state) { (void) state; /* bits 6, 7 & 11 set */ TPM_RC rc = TPM_RC_ALL_1; assert_false (tpm2_rc_is_error_code_with_session (rc)); } /* Negative case for bit 7 */ static void tpm2_rc_is_error_code_with_session_7_unset (void **state) { (void) state; /* bits 6 & 7 clear, bit 11 set */ TPM_RC rc = 0xffffff3f; assert_false (tpm2_rc_is_error_code_with_session (rc)); } /* Negative case for bit 11 */ static void tpm2_rc_is_error_code_with_session_11_unset (void **state) { (void) state; /* bits 6 & 11 clear, bit 7 set */ TPM_RC rc = 0xfffff7bf; assert_false (tpm2_rc_is_error_code_with_session (rc)); } /* Isolate bits [06:00] of the TPM_RC. * The first of these tests ensures that when all bits are set that we only * get back an int with the bits [06:00] set. */ static void tpm2_rc_get_code_7bit_all (void **state) { (void) state; TPM_RC rc = TPM_RC_ALL_1; assert_int_equal (tpm2_rc_get_code_6bit (rc), 0x0000003f); } static void tpm2_rc_get_code_7bit_general_failure (void **state) { (void) state; TPM_RC rc = ~TPM_RC_6BIT_ERROR_MASK | TSS2_BASE_RC_GENERAL_FAILURE; assert_int_equal (tpm2_rc_get_code_6bit (rc), TSS2_BASE_RC_GENERAL_FAILURE); } /* Isolate bits [05:00] of the TPM_RC. * This test ensures that the tpm2_rc_get_code_6bit returns only bits [05:00] * unmodified. */ static void tpm2_rc_get_code_6bit_all (void **state) { (void) state; TPM_RC rc = TPM_RC_ALL_1; assert_int_equal (tpm2_rc_get_code_6bit (rc), 0x0000003f); } static void tpm2_rc_get_code_6bit_general_failure (void **state) { (void) state; TPM_RC rc = ~TPM_RC_6BIT_ERROR_MASK | TSS2_BASE_RC_GENERAL_FAILURE; assert_int_equal (tpm2_rc_get_code_6bit (rc), TSS2_BASE_RC_GENERAL_FAILURE); } /* Isolate bits [11:08] from the TPM_RC. */ static void tpm2_rc_get_parameter_number_f (void **state) { (void) state; TPM_RC rc = ~TPM_RC_PARAMETER_MASK | TPM_RC_F; assert_int_equal (tpm2_rc_get_parameter_number (rc), TPM_RC_F); } static void tpm2_rc_get_parameter_number_9 (void **state) { (void) state; TPM_RC rc = ~TPM_RC_PARAMETER_MASK | TPM_RC_9; assert_int_equal (tpm2_rc_get_parameter_number (rc), TPM_RC_9); } /* Isolate bits [10:08] from the TPM_RC. */ static void tpm2_rc_get_handle_number_1 (void **state) { (void) state; TPM_RC rc = ~TPM_RC_HANDLE_MASK | TPM_RC_1; assert_int_equal (tpm2_rc_get_handle_number (rc), TPM_RC_1); } /* The largest handle number possible */ static void tpm2_rc_get_handle_number_7 (void **state) { (void) state; TPM_RC rc = ~TPM_RC_HANDLE_MASK | TPM_RC_7; assert_int_equal (tpm2_rc_get_handle_number (rc), TPM_RC_7); } /* A negative case to test for handle numbers beyond what's possible */ static void tpm2_rc_get_handle_number_f (void **state) { (void) state; TPM_RC rc = ~TPM_RC_HANDLE_MASK | TPM_RC_F; assert_int_not_equal (tpm2_rc_get_handle_number (rc), TPM_RC_F); } /* Isolate bits [10:08] from the TPM_RC. This is redundant but it tests * the functions that expose functionality which are themselves redundant. */ static void tpm2_rc_get_session_number_1 (void **state) { (void) state; TPM_RC rc = ~TPM_RC_SESSION_MASK | TPM_RC_1; assert_int_equal (tpm2_rc_get_session_number (rc), TPM_RC_1); } static void tpm2_rc_get_session_number_7 (void **state) { (void) state; TPM_RC rc = ~TPM_RC_SESSION_MASK | TPM_RC_7; assert_int_equal (tpm2_rc_get_session_number (rc), TPM_RC_7); } static void tpm2_rc_get_session_number_f (void **state) { (void) state; TPM_RC rc = ~TPM_RC_SESSION_MASK | TPM_RC_F; assert_int_not_equal (tpm2_rc_get_session_number (rc), TPM_RC_F); } /* Isolate the various error layers. To test this we set every bit in the RC * and then selectively disable bits using a logical AND to make the error * level meaningful. We then compare the result of the tpm2_rc_get_level * function to the level that we set to be sure that all other bits were * cleared. */ static void tpm2_rc_get_layer_tpm (void **state) { (void) state; TPM_RC rc = ~TSS2_ERROR_LEVEL_MASK | TSS2_TPM_ERROR_LEVEL; assert_int_equal (tpm2_rc_get_layer (rc), TSS2_TPM_ERROR_LEVEL); } static void tpm2_rc_get_layer_sys (void **state) { (void) state; TPM_RC rc = ~TSS2_ERROR_LEVEL_MASK | TSS2_SYS_ERROR_LEVEL; assert_int_equal (tpm2_rc_get_layer (rc), TSS2_SYS_ERROR_LEVEL); } static void tpm2_rc_get_layer_tcti (void **state) { (void) state; TPM_RC rc = ~TSS2_ERROR_LEVEL_MASK | TSS2_TCTI_ERROR_LEVEL; assert_int_equal (tpm2_rc_get_layer (rc), TSS2_TCTI_ERROR_LEVEL); } /* Check our ability to determine the source of the */ static void tpm2_rc_is_from_tss_sys (void **state) { (void) state; TPM_RC rc = ~TSS2_ERROR_LEVEL_MASK | TSS2_SYS_ERROR_LEVEL; assert_true (tpm2_rc_is_from_tss (rc)); } static void tpm2_rc_is_from_tss_tpm (void **state) { (void) state; TPM_RC rc = ~TSS2_ERROR_LEVEL_MASK | TSS2_TPM_ERROR_LEVEL; assert_false (tpm2_rc_is_from_tss (rc)); } static void tpm2_rc_is_from_tss_tcti (void **state) { (void) state; TPM_RC rc = ~TSS2_ERROR_LEVEL_MASK | TSS2_TCTI_ERROR_LEVEL; assert_true (tpm2_rc_is_from_tss (rc)); } /* Isolate the base error code from a TSS error. */ static void tpm2_rc_get_tss_err_code_general_from_tcti (void **state) { (void) state; TPM_RC rc = TSS2_TCTI_RC_GENERAL_FAILURE; assert_int_equal (TSS2_BASE_RC_GENERAL_FAILURE, tpm2_rc_get_tss_err_code (rc)); } static void tpm2_rc_get_tss_err_code_try_again_from_tcti (void **state) { (void) state; TPM_RC rc = TSS2_TCTI_RC_TRY_AGAIN; assert_int_equal (TSS2_BASE_RC_TRY_AGAIN, tpm2_rc_get_tss_err_code (rc)); } static void tpm2_rc_get_tss_err_code_abi_mismatch_from_sys (void **state) { (void) state; TPM_RC rc = TSS2_SYS_RC_ABI_MISMATCH; assert_int_equal (TSS2_BASE_RC_ABI_MISMATCH, tpm2_rc_get_tss_err_code (rc)); } static void tpm2_rc_get_tss_err_code_bad_size_from_sys (void **state) { (void) state; TPM_RC rc = TSS2_SYS_RC_BAD_SIZE; assert_int_equal (TSS2_BASE_RC_BAD_SIZE, tpm2_rc_get_tss_err_code (rc)); } int main (int argc, char* argv[]) { (void)argc; (void)argv; const struct CMUnitTest tests[] = { cmocka_unit_test (tpm2_rc_is_format_zero_true), cmocka_unit_test (tpm2_rc_is_format_zero_false), cmocka_unit_test (tpm2_rc_is_format_one_true), cmocka_unit_test (tpm2_rc_is_format_one_false), cmocka_unit_test (tpm2_rc_is_tpm12_true), cmocka_unit_test (tpm2_rc_is_tpm12_false), cmocka_unit_test (tpm2_rc_is_tpm2_01), cmocka_unit_test (tpm2_rc_is_tpm2_10), cmocka_unit_test (tpm2_rc_is_tpm2_11), cmocka_unit_test (tpm2_rc_is_vendor_defined_code_all_but_7), cmocka_unit_test (tpm2_rc_is_vendor_defined_code_7_set), cmocka_unit_test (tpm2_rc_is_vendor_defined_code_8_unset), cmocka_unit_test (tpm2_rc_is_vendor_defined_code_10_unset), cmocka_unit_test (tpm2_rc_is_vendor_defined_code_no_9), cmocka_unit_test (tpm2_rc_is_warning_code_success), cmocka_unit_test (tpm2_rc_is_warning_code_8_unset), cmocka_unit_test (tpm2_rc_is_warning_code_7_set), cmocka_unit_test (tpm2_rc_is_warning_code_10_set), cmocka_unit_test (tpm2_rc_is_warning_code_11_unset), cmocka_unit_test (tpm2_rc_is_error_code_success), cmocka_unit_test (tpm2_rc_is_error_code_8_unset), cmocka_unit_test (tpm2_rc_is_error_code_7_set), cmocka_unit_test (tpm2_rc_is_error_code_10_set), cmocka_unit_test (tpm2_rc_is_error_code_11_set), cmocka_unit_test (tpm2_rc_is_error_code_with_parameter_success), cmocka_unit_test (tpm2_rc_is_error_code_with_parameter_6_unset), cmocka_unit_test (tpm2_rc_is_error_code_with_parameter_7_unset), cmocka_unit_test (tpm2_rc_is_error_code_with_handle_success), cmocka_unit_test (tpm2_rc_is_error_code_with_handle_6_set), cmocka_unit_test (tpm2_rc_is_error_code_with_handle_7_unset), cmocka_unit_test (tpm2_rc_is_error_code_with_handle_11_set), cmocka_unit_test (tpm2_rc_is_error_code_with_session_success), cmocka_unit_test (tpm2_rc_is_error_code_with_session_6_set), cmocka_unit_test (tpm2_rc_is_error_code_with_session_7_unset), cmocka_unit_test (tpm2_rc_is_error_code_with_session_11_unset), cmocka_unit_test (tpm2_rc_get_code_7bit_all), cmocka_unit_test (tpm2_rc_get_code_7bit_general_failure), cmocka_unit_test (tpm2_rc_get_code_6bit_all), cmocka_unit_test (tpm2_rc_get_code_6bit_general_failure), cmocka_unit_test (tpm2_rc_get_parameter_number_f), cmocka_unit_test (tpm2_rc_get_parameter_number_9), cmocka_unit_test (tpm2_rc_get_handle_number_1), cmocka_unit_test (tpm2_rc_get_handle_number_7), cmocka_unit_test (tpm2_rc_get_handle_number_f), cmocka_unit_test (tpm2_rc_get_session_number_1), cmocka_unit_test (tpm2_rc_get_session_number_7), cmocka_unit_test (tpm2_rc_get_session_number_f), cmocka_unit_test (tpm2_rc_get_layer_tpm), cmocka_unit_test (tpm2_rc_get_layer_sys), cmocka_unit_test (tpm2_rc_get_layer_tcti), cmocka_unit_test (tpm2_rc_is_from_tss_tpm), cmocka_unit_test (tpm2_rc_is_from_tss_sys), cmocka_unit_test (tpm2_rc_is_from_tss_tcti), cmocka_unit_test (tpm2_rc_get_tss_err_code_general_from_tcti), cmocka_unit_test (tpm2_rc_get_tss_err_code_try_again_from_tcti), cmocka_unit_test (tpm2_rc_get_tss_err_code_abi_mismatch_from_sys), cmocka_unit_test (tpm2_rc_get_tss_err_code_bad_size_from_sys), }; return cmocka_run_group_tests(tests, NULL, NULL); } tpm2-tools-2.1.0/test/unit/tpm2-rc-entry_unit.c000066400000000000000000000253061313543155100213250ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2016, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include "rc-decode.h" /* Lookup an error code using the provided function. Assert that the returned * id matches the one that we looked up. * tpm_rc: TPM_RC we're looking up * lookup_func: function to lookup the TPM_RC */ #define LOOKUP_SUCCESS(tpm_rc, lookup_func) \ LOOKUP_EXPECTED_SUCCESS (tpm_rc, tpm_rc, lookup_func); /* Same as LOOKUP_SUCCESS but expect a failure. */ #define LOOKUP_FAILURE(tpm_rc, lookup_func) \ TPM_RC rc = (tpm_rc); \ tpm2_rc_entry_t *entry = NULL; \ entry = (lookup_func)(rc); \ assert_null (entry); /* Lookup TPM_RC and compare to expected value. Assert success condition. * tpm_rc: TPM_RC we're looking up * layer: expected layer * lookup_func: function to lookup the layer from the provided TPM_RC */ #define LOOKUP_EXPECTED_SUCCESS(rc_in, rc_expect, lookup_func) \ TPM_RC rc = (rc_in); \ tpm2_rc_entry_t *entry = NULL; \ entry = (lookup_func)(rc); \ assert_non_null (entry); \ assert_int_equal ((rc_expect), entry->id); /* Check for match in tpm2_tss_base_rc_entry table. */ static void tpm2_rc_entry_tss_base_rc_general (void **state) { (void) state; LOOKUP_SUCCESS (TSS2_BASE_RC_GENERAL_FAILURE, tpm2_get_tss_base_rc_entry); } static void tpm2_rc_entry_tss_base_rc_insufficient_buffer (void **state) { (void) state; LOOKUP_SUCCESS (TSS2_BASE_RC_INSUFFICIENT_BUFFER, tpm2_get_tss_base_rc_entry); } /* Check for non-existant error codes in the tpm2_tss_base_rc_entry table */ static void tpm2_rc_entry_tss_base_rc_bad_min (void **state) { (void) state; LOOKUP_FAILURE (0x0, tpm2_get_tss_base_rc_entry); } static void tpm2_rc_entry_tss_base_rc_bad_max (void **state) { (void) state; LOOKUP_FAILURE (0xffff, tpm2_get_tss_base_rc_entry); } /* Check for match in tpm2_tss_base_rc_entry with TCTI layer indicator set */ static void tpm2_rc_entry_tss_tcti_rc_general (void **state) { (void) state; LOOKUP_EXPECTED_SUCCESS (TSS2_TCTI_RC_INSUFFICIENT_BUFFER, TSS2_BASE_RC_INSUFFICIENT_BUFFER, tpm2_get_tss_base_rc_entry); } /* Check for match in tpm2_tss_base_rc_entry with SAPI (aka SYS) layer set */ static void tpm2_rc_entry_tss_sapi_rc_bad_value (void **state) { (void) state; LOOKUP_EXPECTED_SUCCESS (TSS2_SYS_RC_BAD_VALUE, TSS2_BASE_RC_BAD_VALUE, tpm2_get_tss_base_rc_entry); } /* Check for match in tpm2_position_entry for the first parameter indicator. * NOTE: The parameter indicator is ignored. In reality this should be checked * first. */ static void tpm2_rc_entry_parameter_1 (void **state) { (void) state; LOOKUP_EXPECTED_SUCCESS (TPM_RC_P + TPM_RC_1, TPM_RC_1, tpm2_get_parameter_entry); } static void tpm2_rc_entry_parameter_a (void **state) { (void) state; LOOKUP_EXPECTED_SUCCESS (TPM_RC_P + TPM_RC_A, TPM_RC_A, tpm2_get_parameter_entry); } /* same for tpm2_handle_entry */ static void tpm2_rc_entry_handle_3 (void **state) { (void) state; LOOKUP_EXPECTED_SUCCESS (TPM_RC_H + TPM_RC_3, TPM_RC_3, tpm2_get_handle_entry); } static void tpm2_rc_entry_handle_7 (void **state) { (void) state; LOOKUP_EXPECTED_SUCCESS (TPM_RC_H + TPM_RC_7, TPM_RC_7, tpm2_get_handle_entry); } /* same for tpm2_session_entry */ static void tpm2_rc_entry_session_2 (void **state) { (void) state; LOOKUP_EXPECTED_SUCCESS (TPM_RC_H + TPM_RC_2, TPM_RC_2, tpm2_get_session_entry); } static void tpm2_rc_entry_session_5 (void **state) { (void) state; LOOKUP_EXPECTED_SUCCESS (TPM_RC_H + TPM_RC_5, TPM_RC_5, tpm2_get_session_entry); } /* Check for match in tpm2_tss_layer_entry for the TCTI layer. */ static void tpm2_rc_entry_layer_tcti_from_general_failure (void **state) { (void) state; LOOKUP_EXPECTED_SUCCESS (TSS2_TCTI_RC_GENERAL_FAILURE, TSS2_TCTI_ERROR_LEVEL, tpm2_get_layer_entry); } static void tpm2_rc_entry_layer_tcti_from_not_permitted (void **state) { (void) state; LOOKUP_EXPECTED_SUCCESS (TSS2_TCTI_RC_NOT_PERMITTED, TSS2_TCTI_ERROR_LEVEL, tpm2_get_layer_entry); } /* Check for match in tpm2_tss_layer_entry for the SAPI (aka SYS) layer */ static void tpm2_rc_entry_layer_sapi_from_no_encrypt_param (void **state) { (void) state; LOOKUP_EXPECTED_SUCCESS (TSS2_SYS_RC_NO_ENCRYPT_PARAM, TSS2_SYS_ERROR_LEVEL, tpm2_get_layer_entry); } static void tpm2_rc_entry_layer_sapi_from_bad_tcti_structure (void **state) { (void) state; LOOKUP_EXPECTED_SUCCESS (TSS2_SYS_RC_BAD_TCTI_STRUCTURE, TSS2_SYS_ERROR_LEVEL, tpm2_get_layer_entry); } /* Part2 error messages generated by SAPI as part of offloading the error * checking. */ static void tpm2_rc_entry_layer_part2_from_all (void **state) { (void) state; LOOKUP_EXPECTED_SUCCESS (TSS2_SYS_PART2_ERROR_LEVEL | ~(0xff << TSS2_RC_LEVEL_SHIFT), TSS2_SYS_PART2_ERROR_LEVEL, tpm2_get_layer_entry); } /* Lookup layer to identify errors from the TPM */ static void tpm2_rc_entry_layer_tpm (void **state) { (void) state; LOOKUP_EXPECTED_SUCCESS (TSS2_TPM_ERROR_LEVEL | ~(0xff << TSS2_RC_LEVEL_SHIFT), TSS2_TPM_ERROR_LEVEL, tpm2_get_layer_entry); } /* Lookup non-existant error level */ static void tpm2_rc_entry_layer_bad (void **state) { (void) state; LOOKUP_FAILURE (~(0x1 << TSS2_RC_LEVEL_SHIFT), tpm2_get_layer_entry); } /* Lookup structures holding data about format0 / VER1 error codes. */ static void tpm2_rc_entry_fmt0_failure (void **state) { (void) state; LOOKUP_SUCCESS (TPM_RC_FAILURE, tpm2_get_fmt0_entry); } static void tpm2_rc_entry_fmt0_pcr_changed (void **state) { (void) state; LOOKUP_SUCCESS (TPM_RC_PCR_CHANGED, tpm2_get_fmt0_entry); } /* Check for no match on invalid fmt0 / ver1 error code */ static void tpm2_rc_entry_fmt0_bad (void **state) { (void) state; LOOKUP_FAILURE (0x023, tpm2_get_fmt0_entry); } /* Lookup structures holding data about format1 / FMT1 error codes. */ static void tpm2_rc_entry_fmt1_hierarchy (void **state) { (void) state; LOOKUP_SUCCESS (TPM_RC_HIERARCHY, tpm2_get_fmt1_entry); } static void tpm2_rc_entry_fmt1_expired (void **state) { (void) state; LOOKUP_SUCCESS (TPM_RC_EXPIRED, tpm2_get_fmt1_entry); } static void tpm2_rc_entry_fmt1_bad (void **state) { (void) state; LOOKUP_FAILURE (0x30, tpm2_get_fmt1_entry); } /* Lookup structures holding data about fmt1 warning error codes. */ static void tpm2_rc_entry_warn_memory (void **state) { (void) state; LOOKUP_SUCCESS (TPM_RC_MEMORY, tpm2_get_warn_entry); } static void tpm2_rc_entry_warn_reference_s5 (void **state) { (void) state; LOOKUP_SUCCESS (TPM_RC_REFERENCE_S5, tpm2_get_warn_entry); } static void tpm2_rc_entry_warn_bad (void **state) { (void) state; LOOKUP_FAILURE (0x17, tpm2_get_warn_entry); } int main (int argc, char *argv[]) { (void)argc; (void)argv; const struct CMUnitTest tests[] = { cmocka_unit_test (tpm2_rc_entry_tss_base_rc_general), cmocka_unit_test (tpm2_rc_entry_tss_base_rc_insufficient_buffer), cmocka_unit_test (tpm2_rc_entry_tss_base_rc_bad_min), cmocka_unit_test (tpm2_rc_entry_tss_base_rc_bad_max), cmocka_unit_test (tpm2_rc_entry_tss_tcti_rc_general), cmocka_unit_test (tpm2_rc_entry_tss_sapi_rc_bad_value), cmocka_unit_test (tpm2_rc_entry_parameter_1), cmocka_unit_test (tpm2_rc_entry_parameter_a), cmocka_unit_test (tpm2_rc_entry_handle_3), cmocka_unit_test (tpm2_rc_entry_handle_7), cmocka_unit_test (tpm2_rc_entry_session_2), cmocka_unit_test (tpm2_rc_entry_session_5), cmocka_unit_test (tpm2_rc_entry_layer_tcti_from_general_failure), cmocka_unit_test (tpm2_rc_entry_layer_tcti_from_not_permitted), cmocka_unit_test (tpm2_rc_entry_layer_sapi_from_no_encrypt_param), cmocka_unit_test (tpm2_rc_entry_layer_sapi_from_bad_tcti_structure), cmocka_unit_test (tpm2_rc_entry_layer_part2_from_all), cmocka_unit_test (tpm2_rc_entry_layer_tpm), cmocka_unit_test (tpm2_rc_entry_layer_bad), cmocka_unit_test (tpm2_rc_entry_fmt0_failure), cmocka_unit_test (tpm2_rc_entry_fmt0_pcr_changed), cmocka_unit_test (tpm2_rc_entry_fmt0_bad), cmocka_unit_test (tpm2_rc_entry_fmt1_hierarchy), cmocka_unit_test (tpm2_rc_entry_fmt1_expired), cmocka_unit_test (tpm2_rc_entry_fmt1_bad), cmocka_unit_test (tpm2_rc_entry_warn_memory), cmocka_unit_test (tpm2_rc_entry_warn_reference_s5), cmocka_unit_test (tpm2_rc_entry_warn_bad), }; return cmocka_run_group_tests(tests, NULL, NULL); } tpm2-tools-2.1.0/tools/000077500000000000000000000000001313543155100146735ustar00rootroot00000000000000tpm2-tools-2.1.0/tools/main.c000066400000000000000000000061241313543155100157660ustar00rootroot00000000000000/* * Copyright (c) 2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include #include "context-util.h" #include "log.h" #include "main.h" #include "options.h" /* * This program is a template for TPM2 tools that use the SAPI. It does * nothing more than parsing command line options that allow the caller to * specify which TCTI to use for the test. */ int main (int argc, char *argv[], char *envp[]) { extern int opterr, optind; int ret; TSS2_SYS_CONTEXT *sapi_context; common_opts_t opts = COMMON_OPTS_INITIALIZER; /* * Get common options and reset getopt global variables. This allows the * tools to use getopt as they normally would. */ get_common_opts (&argc, &argv, &opts); opterr = 0; optind = 1; switch (sanity_check_common (&opts)) { case 1: execute_man (argv[0], envp); fprintf (stderr, "failed to load manpage, check your environment / PATH\n"); /* no break */ case 2: exit (1); } if (opts.version) { showVersion (argv[0]); exit (0); } if (opts.verbose) log_set_level(log_level_verbose); sapi_context = sapi_init_from_options (&opts); if (sapi_context == NULL) exit (1); /* * Call the specific tool, all tools implement this function instead of * 'main'. */ ret = execute_tool (argc, argv, envp, &opts, sapi_context) ? 1 : 0; /* * Cleanup contexts & memory allocated for the modified argument vector * passed to execute_tool. */ sapi_teardown_full (sapi_context); free (argv); exit (ret); } tpm2-tools-2.1.0/tools/main.h000066400000000000000000000035231313543155100157730ustar00rootroot00000000000000/* * Copyright (c) 2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef MAIN_H #define MAIN_H #include #include "options.h" int execute_tool (int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context); #endif /* MAIN_H */ tpm2-tools-2.1.0/tools/tpm2_activatecredential.c000066400000000000000000000301141313543155100216330ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include #include #include "files.h" #include "log.h" #include "main.h" #include "options.h" #include "password_util.h" #include "string-bytes.h" #include "tpm_session.h" typedef struct tpm_activatecred_ctx tpm_activatecred_ctx; struct tpm_activatecred_ctx { struct { TPMI_DH_OBJECT activate; TPMI_DH_OBJECT key; } handle; TPM2B_ID_OBJECT credentialBlob; TPM2B_ENCRYPTED_SECRET secret; bool hexPasswd; TPMS_AUTH_COMMAND password; TPMS_AUTH_COMMAND endorse_password; struct { char output[PATH_MAX]; char *context; char *key_context; } file ; }; static bool read_cert_secret(const char *path, TPM2B_ID_OBJECT *credentialBlob, TPM2B_ENCRYPTED_SECRET *secret) { bool result = false; FILE *fp = fopen(path, "rb"); if (!fp) { LOG_ERR("Could not open file \"%s\" error: \"%s\"", path, strerror(errno)); return false; } size_t items = fread(credentialBlob, sizeof(TPM2B_ID_OBJECT), 1, fp); if (items != 1) { const char *fmt_msg = "Reading credential from file \"%s\" failed, error: \"%s\""; const char *err_msg = "Unknown error"; if (ferror(fp)) { err_msg = strerror(errno); } else if (feof(fp)) { err_msg = "end of file"; } LOG_ERR(fmt_msg, path, err_msg); goto out; } items = fread(secret, sizeof(TPM2B_ENCRYPTED_SECRET), 1, fp); if (items != 1) { const char *fmt_msg = "Reading secret from file \"%s\" failed, error: \"%s\""; const char *err_msg = "Unknown error"; if (ferror(fp)) { err_msg = strerror(errno); } else if (feof(fp)) { err_msg = "end of file"; } LOG_ERR(fmt_msg, path, err_msg); goto out; } result = true; out: fclose(fp); return result; } static bool output_and_save(TPM2B_DIGEST *digest, const char *path) { printf("\nCertInfoData :\n"); unsigned k; for (k = 0; k < digest->t.size; k++) { printf("0x%.2x ", digest->t.buffer[k]); } printf("\n\n"); return files_save_bytes_to_file(path, digest->t.buffer, digest->t.size); } static bool activate_credential_and_output(TSS2_SYS_CONTEXT *sapi_context, tpm_activatecred_ctx *ctx) { TPM2B_DIGEST certInfoData = TPM2B_TYPE_INIT(TPM2B_DIGEST, buffer); TPMS_AUTH_COMMAND tmp_auth; ctx->password.sessionHandle = TPM_RS_PW; ctx->endorse_password.sessionHandle = TPM_RS_PW; *((UINT8 *) ((void *) &ctx->password.sessionAttributes)) = 0; *((UINT8 *) ((void *) &ctx->endorse_password.sessionAttributes)) = 0; *((UINT8 *) ((void *) &tmp_auth.sessionAttributes)) = 0; TPMS_AUTH_COMMAND *cmd_session_array_password[2] = { &ctx->password, &tmp_auth }; TSS2_SYS_CMD_AUTHS cmd_auth_array_password = { 2, &cmd_session_array_password[0] }; TPMS_AUTH_COMMAND *cmd_session_array_endorse[1] = { &ctx->endorse_password }; TSS2_SYS_CMD_AUTHS cmd_auth_array_endorse = { 1, &cmd_session_array_endorse[0] }; TPM2B_ENCRYPTED_SECRET encryptedSalt = { { 0, } }; TPM2B_NONCE nonceCaller = { { 0, } }; TPMT_SYM_DEF symmetric = { .algorithm = TPM_ALG_NULL }; bool result = password_util_to_auth(&ctx->password.hmac, ctx->hexPasswd, "handlePasswd", &ctx->password.hmac); if (!result) { return false; } result = password_util_to_auth(&ctx->endorse_password.hmac, ctx->hexPasswd, "endorsePasswd", &ctx->endorse_password.hmac); if (!result) { return false; } SESSION *session = NULL; UINT32 rval = tpm_session_start_auth_with_params(sapi_context, &session, TPM_RH_NULL, 0, TPM_RH_NULL, 0, &nonceCaller, &encryptedSalt, TPM_SE_POLICY, &symmetric, TPM_ALG_SHA256); if (rval != TPM_RC_SUCCESS) { LOG_ERR("tpm_session_start_auth_with_params Error. TPM Error:0x%x", rval); return false; } rval = Tss2_Sys_PolicySecret(sapi_context, TPM_RH_ENDORSEMENT, session->sessionHandle, &cmd_auth_array_endorse, 0, 0, 0, 0, 0, 0, 0); if (rval != TPM_RC_SUCCESS) { LOG_ERR("Tss2_Sys_PolicySecret Error. TPM Error:0x%x", rval); return false; } tmp_auth.sessionHandle = session->sessionHandle; tmp_auth.sessionAttributes.continueSession = 1; tmp_auth.hmac.t.size = 0; rval = Tss2_Sys_ActivateCredential(sapi_context, ctx->handle.activate, ctx->handle.key, &cmd_auth_array_password, &ctx->credentialBlob, &ctx->secret, &certInfoData, 0); if (rval != TPM_RC_SUCCESS) { LOG_ERR("ActivateCredential failed. TPM Error:0x%x", rval); return false; } // Need to flush the session here. rval = Tss2_Sys_FlushContext(sapi_context, session->sessionHandle); if (rval != TPM_RC_SUCCESS) { LOG_ERR("TPM2_Sys_FlushContext Error. TPM Error:0x%x", rval); return false; } // And remove the session from sessions table. rval = tpm_session_auth_end(session); if (rval != TPM_RC_SUCCESS) { LOG_ERR("EndAuthSession Error. TPM Error:0x%x", rval); return false; } return output_and_save(&certInfoData, ctx->file.output); } static bool init(int argc, char *argv[], tpm_activatecred_ctx *ctx) { static const char *optstring = "H:c:k:C:P:e:f:o:X"; static const struct option long_options[] = { {"handle", required_argument, NULL, 'H'}, {"context", required_argument, NULL, 'c'}, {"keyHandle", required_argument, NULL, 'k'}, {"keyContext", required_argument, NULL, 'C'}, {"Password", required_argument, NULL, 'P'}, {"endorsePasswd", required_argument, NULL, 'e'}, {"inFile", required_argument, NULL, 'f'}, {"outFile", required_argument, NULL, 'o'}, {"passwdInHex", no_argument, NULL, 'X'}, {NULL, no_argument, NULL, '\0'}, }; if (argc == 1) { showArgMismatch(argv[0]); return false; } int H_flag = 0, c_flag = 0, k_flag = 0, C_flag = 0, f_flag = 0, o_flag = 0; int opt; int rc; bool result; while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) { switch (opt) { case 'H': result = string_bytes_get_uint32(optarg, &ctx->handle.activate); if (!result) { LOG_ERR("Could not convert -H argument to a number, " "got \"%s\"!", optarg); return false; } H_flag = 1; break; case 'c': ctx->file.context = strdup(optarg); if (!ctx->file.context) { LOG_ERR("oom"); return false; } c_flag = 1; break; case 'k': result = string_bytes_get_uint32(optarg, &ctx->handle.key); if (!result) { return false; } k_flag = 1; break; case 'C': ctx->file.key_context = strdup(optarg); if (!ctx->file.key_context) { LOG_ERR("oom"); return false; } C_flag = 1; break; case 'P': ctx->password.hmac.t.size = sizeof(ctx->password.hmac.t) - 2; rc = str2ByteStructure(optarg, &ctx->password.hmac.t.size, ctx->password.hmac.t.buffer); if (rc) { LOG_ERR("Could not convert password \"%s\" into byte array", optarg); return false; } //P_flag = 1; break; case 'e': ctx->endorse_password.hmac.t.size = sizeof(ctx->endorse_password.hmac.t) - 2; rc = str2ByteStructure(optarg, &ctx->endorse_password.hmac.t.size, ctx->endorse_password.hmac.t.buffer); if (rc) { LOG_ERR( "Could not convert endorsePassword \"%s\" into byte array", optarg); return false; } break; case 'f': /* logs errors */ result = read_cert_secret(optarg, &ctx->credentialBlob, &ctx->secret); if (!result) { return false; } f_flag = 1; break; case 'o': snprintf(ctx->file.output, sizeof(ctx->file.output), "%s", optarg); o_flag = 1; break; case 'X': ctx->hexPasswd = true; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } }; if ((!H_flag && !c_flag ) && (!k_flag || !C_flag) && !f_flag && !o_flag) { showArgMismatch(argv[0]); return false; } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { /* opts is unused, avoid compiler warning */ (void) opts; (void) envp; /* static an easy way to get zero memory, these don't need thread safety */ static tpm_activatecred_ctx ctx; int rc = 1; bool result = init(argc, argv, &ctx); if (!result) { LOG_ERR("Initialization failed\n"); goto out; } if (ctx.file.context) { bool res = file_load_tpm_context_from_file(sapi_context, &ctx.handle.activate, ctx.file.context); if (!res) { goto out; } } if (ctx.file.key_context) { bool res = file_load_tpm_context_from_file(sapi_context, &ctx.handle.key, ctx.file.key_context) != true; if (!res) { goto out; } } result = activate_credential_and_output(sapi_context, &ctx); if (!result) { goto out; } rc = 0; out: free(ctx.file.key_context); free(ctx.file.context); return rc; } tpm2-tools-2.1.0/tools/tpm2_akparse.c000066400000000000000000000161421313543155100174330ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include #include "files.h" #include "log.h" #include "main.h" #include "options.h" #include "string-bytes.h" typedef struct tpm_akparse_ctx tpm_akparse_ctx; struct tpm_akparse_ctx { char ak_data_file_path[PATH_MAX]; char ak_key_file_path[PATH_MAX]; }; static bool is_big_endian() { uint32_t test_word; uint8_t *test_byte; test_word = 0xFF000000; test_byte = (uint8_t *) (&test_word); return test_byte[0] == 0xFF; } static bool write_be_convert(FILE *file, UINT16 data) { bool is_big_endian_arch = is_big_endian(); if (!is_big_endian_arch) { BYTE *from = (BYTE *) &data; UINT16 tmp; BYTE *to = (BYTE *) &tmp; to[1] = from[0]; to[0] = from[1]; data = tmp; } size_t size = fwrite(&data, 1, sizeof(UINT16), file); if (size != sizeof(UINT16)) { LOG_ERR("Short write, expected %zu, got: %zu", sizeof(UINT16), size); return false; } return true; } static bool save_alg_and_key_to_file(const char *key_file, UINT16 alg_type, TPM2B **key_data, size_t key_data_len) { FILE *f = fopen(key_file, "wb+"); if (!f) { LOG_ERR("Could not open file \"%s\" due to error: \"%s\".", key_file, strerror(errno)); return false; } bool res = write_be_convert(f, alg_type); if (!res) { /* write_be_convert prints error */ goto out; } /* * For each TPM2B buffer in the list, save its size in be format, write it * to the output file and output it to stdout. */ unsigned i; for (i=0; i < key_data_len; i++) { TPM2B *tmp = key_data[i]; res = write_be_convert(f, tmp->size); if (!res) { /* write_be_convert prints error */ goto out; } size_t count = fwrite(tmp->buffer, sizeof(BYTE), tmp->size, f); if (count != tmp->size) { if (ferror(f)) { LOG_ERR("Error writing to file \"%s\", error: \"%s\"", key_file, strerror(errno)); } else { LOG_ERR("Did not write all bytes to file, got %zu expected %u", count, tmp->size); } goto out; } string_bytes_print_tpm2b(tmp); } out: fclose(f); return true; } static bool parse_and_save_ak_public(tpm_akparse_ctx *ctx) { TPM2B_PUBLIC outPublic; UINT16 size = sizeof(outPublic); bool result = files_load_bytes_from_file(ctx->ak_data_file_path, (UINT8 *)&outPublic, &size); if (!result) { /* loadDataFromFile prints error */ return false; } size_t key_data_len = 1; TPM2B *key_data[2]; switch (outPublic.t.publicArea.type) { case TPM_ALG_RSA: key_data[0] = &outPublic.t.publicArea.unique.rsa.b; break; case TPM_ALG_KEYEDHASH: key_data[0] = &outPublic.t.publicArea.unique.keyedHash.b; break; case TPM_ALG_SYMCIPHER: key_data[0] = &outPublic.t.publicArea.unique.sym.b; break; case TPM_ALG_ECC: key_data_len = 2; key_data[0] = &outPublic.t.publicArea.unique.ecc.x.b; key_data[1] = &outPublic.t.publicArea.unique.ecc.y.b; break; default: LOG_ERR("The algorithm type(0x%4.4x) is not supported", outPublic.t.publicArea.type); return false; } return save_alg_and_key_to_file(ctx->ak_key_file_path, outPublic.t.publicArea.type, key_data, key_data_len); } static bool init(int argc, char *argv[], tpm_akparse_ctx *ctx) { struct option options[] = { { "file", required_argument, NULL, 'f' }, { "keyFile", required_argument, NULL, 'k' }, { NULL, no_argument, NULL, '\0' } }; if (argc <=1 || argc > (int) (2 * sizeof(options) / sizeof(struct option))) { showArgMismatch(argv[0]); return false; } int opt; while ((opt = getopt_long(argc, argv, "f:k:hv", options, NULL)) != -1) { switch (opt) { case 'f': if (!optarg) { LOG_ERR("Please input the file that used to be parsed."); return false; } snprintf(ctx->ak_data_file_path, sizeof(ctx->ak_data_file_path), "%s", optarg); break; case 'k': if (!optarg) { LOG_ERR("Please input the file that used to save ak key."); return false; } snprintf(ctx->ak_key_file_path, sizeof(ctx->ak_key_file_path), "%s", optarg); break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { /* opts is unused, avoid compiler warning */ (void)opts; (void)sapi_context; (void)envp; struct tpm_akparse_ctx ctx; bool result = init(argc, argv, &ctx); if (!result) { return 1; } /* 0 on success 1 on error */ return parse_and_save_ak_public(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_certify.c000066400000000000000000000306731313543155100174570ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include "log.h" #include "files.h" #include "main.h" #include "options.h" #include "password_util.h" #include "string-bytes.h" typedef struct tpm_certify_ctx tpm_certify_ctx; struct tpm_certify_ctx { TPMS_AUTH_COMMAND cmd_auth[2]; TPMI_ALG_HASH halg; struct { TPMI_DH_OBJECT key; TPMI_DH_OBJECT obj; } handle; struct { char attest[PATH_MAX]; char sig[PATH_MAX]; } file_path; TSS2_SYS_CONTEXT *sapi_context; }; #define ARRAY_LEN(x) (sizeof(x)/sizeof(x[0])) static bool get_key_type(TSS2_SYS_CONTEXT *sapi_context, TPMI_DH_OBJECT object_handle, TPMI_ALG_PUBLIC *type) { TPMS_AUTH_RESPONSE session_data_out; TPMS_AUTH_RESPONSE *session_data_out_array[] = { &session_data_out }; TSS2_SYS_RSP_AUTHS sessions_data_out = { .rspAuthsCount = ARRAY_LEN(session_data_out_array), .rspAuths = session_data_out_array }; TPM2B_PUBLIC out_public = { { 0, } }; TPM2B_NAME name = TPM2B_TYPE_INIT(TPM2B_NAME, name); TPM2B_NAME qualified_name = TPM2B_TYPE_INIT(TPM2B_NAME, name); TPM_RC rval = Tss2_Sys_ReadPublic(sapi_context, object_handle, 0, &out_public, &name, &qualified_name, &sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("TPM2_ReadPublic failed. Error Code: 0x%x", rval); return false; } *type = out_public.t.publicArea.type; return true; } static bool set_scheme(TSS2_SYS_CONTEXT *sapi_context, TPMI_DH_OBJECT key_handle, TPMI_ALG_HASH halg, TPMT_SIG_SCHEME *scheme) { TPM_ALG_ID type; bool result = get_key_type(sapi_context, key_handle, &type); if (!result) { return false; } switch (type) { case TPM_ALG_RSA : scheme->scheme = TPM_ALG_RSASSA; scheme->details.rsassa.hashAlg = halg; break; case TPM_ALG_KEYEDHASH : scheme->scheme = TPM_ALG_HMAC; scheme->details.hmac.hashAlg = halg; break; case TPM_ALG_ECC : scheme->scheme = TPM_ALG_ECDSA; scheme->details.ecdsa.hashAlg = halg; break; case TPM_ALG_SYMCIPHER : default: LOG_ERR("Unknown key type, got: 0x%x", type); return false; } return true; } static bool certify_and_save_data(tpm_certify_ctx *ctx) { TPMS_AUTH_COMMAND *cmd_session_array[ARRAY_LEN(ctx->cmd_auth)] = { &ctx->cmd_auth[0], &ctx->cmd_auth[1] }; TSS2_SYS_CMD_AUTHS cmd_auth_array = { .cmdAuthsCount = ARRAY_LEN(cmd_session_array), .cmdAuths = cmd_session_array }; TPMS_AUTH_RESPONSE session_data_out[ARRAY_LEN(ctx->cmd_auth)]; TPMS_AUTH_RESPONSE *session_data_array[] = { &session_data_out[0], &session_data_out[1] }; TSS2_SYS_RSP_AUTHS sessions_data_out = { .rspAuthsCount = ARRAY_LEN(session_data_array), .rspAuths = session_data_array }; TPM2B_DATA qualifying_data = { .t = { .size = 4, .buffer = { 0x00, 0xff, 0x55,0xaa } } }; TPMT_SIG_SCHEME scheme; bool result = set_scheme(ctx->sapi_context, ctx->handle.key, ctx->halg, &scheme); if (!result) { LOG_ERR("No suitable signing scheme!\n"); return false; } TPM2B_ATTEST certify_info = { .t = { .size = sizeof(certify_info)-2 } }; TPMT_SIGNATURE signature; TPM_RC rval = Tss2_Sys_Certify(ctx->sapi_context, ctx->handle.obj, ctx->handle.key, &cmd_auth_array, &qualifying_data, &scheme, &certify_info, &signature, &sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("TPM2_Certify failed. Error Code: 0x%x", rval); return false; } /* serialization is safe here, since it's just a byte array */ result = files_save_bytes_to_file(ctx->file_path.attest, (UINT8 *) certify_info.t.attestationData, certify_info.t.size); if (!result) { return false; } /* TODO serialization is not safe here */ return files_save_bytes_to_file(ctx->file_path.sig, (UINT8 *) &signature, sizeof(signature)); } static bool check_and_set_file(const char *path, char *dest, size_t dest_size) { bool result = files_does_file_exist(path); if (result) { return false; } snprintf(dest, dest_size, "%s", path); return true; } static bool init(int argc, char *argv[], tpm_certify_ctx *ctx) { bool result = false; bool is_hex_password = false; char *context_file = NULL; char *context_key_file = NULL; const char *optstring = "H:k:P:K:g:a:s:C:c:X"; static struct option long_options[] = { {"objectHandle", required_argument, NULL, 'H'}, {"keyHandle", required_argument, NULL, 'k'}, {"pwdo", required_argument, NULL, 'P'}, {"pwdk", required_argument, NULL, 'K'}, {"halg", required_argument, NULL, 'g'}, {"attestFile", required_argument, NULL, 'a'}, {"sigFile", required_argument, NULL, 's'}, {"objContext", required_argument, NULL, 'C'}, {"keyContext", required_argument, NULL, 'c'}, {"passwdInHex", no_argument, NULL, 'X'}, {NULL, no_argument, NULL, '\0'} }; struct { UINT16 H : 1; UINT16 k : 1; UINT16 P : 1; UINT16 K : 1; UINT16 g : 1; UINT16 a : 1; UINT16 s : 1; UINT16 C : 1; UINT16 c : 1; UINT16 unused : 7; } flags = { 0 }; if (argc == 1) { showArgMismatch(argv[0]); return false; } int opt = -1; while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) { switch (opt) { case 'H': result = string_bytes_get_uint32(optarg, &ctx->handle.obj); if (!result) { LOG_ERR("Could not format object handle to number, got: \"%s\"", optarg); goto out; } flags.H = 1; break; case 'k': result = string_bytes_get_uint32(optarg, &ctx->handle.key); if (!result) { LOG_ERR("Could not format key handle to number, got: \"%s\"", optarg); goto out; } flags.k = 1; break; case 'P': result = password_util_copy_password(optarg, "object handle", &ctx->cmd_auth[0].hmac); if (!result) { goto out; } flags.P = 1; break; case 'K': result = password_util_copy_password(optarg, "key handle", &ctx->cmd_auth[1].hmac); if (!result) { goto out; } flags.K = 1; break; case 'g': result = string_bytes_get_uint16(optarg, &ctx->halg); if (!result) { LOG_ERR("Could not format algorithm to number, got: \"%s\"", optarg); goto out; } flags.g = 1; break; case 'a': result = check_and_set_file(optarg, ctx->file_path.attest, sizeof(ctx->file_path.attest)); if (!result) { goto out; } flags.a = 1; break; case 's': result = check_and_set_file(optarg, ctx->file_path.sig, sizeof(ctx->file_path.sig)); if (!result) { goto out; } flags.s = 1; break; case 'c': if (context_key_file) { LOG_ERR("Multiple specifications of -c"); goto out; } context_key_file = strdup(optarg); if (!context_key_file) { LOG_ERR("oom"); goto out; } flags.c = 1; break; case 'C': if (context_file) { LOG_ERR("Multiple specifications of -C"); goto out; } context_file = strdup(optarg); if (!context_file) { LOG_ERR("oom"); goto out; } flags.C = 1; break; case 'X': is_hex_password = true; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); result = false; goto out; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); result = false; goto out; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); result = false; goto out; } }; if (!(flags.H || flags.C) && (flags.k || flags.c) && (flags.g) && (flags.a) && (flags.s)) { result = false; goto out; } /* convert a hex passwords if needed */ result = password_util_to_auth(&ctx->cmd_auth[0].hmac, is_hex_password, "object handle", &ctx->cmd_auth[0].hmac); if (!result) { goto out; } result = password_util_to_auth(&ctx->cmd_auth[1].hmac, is_hex_password, "key handle", &ctx->cmd_auth[1].hmac); if (!result) { goto out; } /* Finish initialize the cmd_auth array */ ctx->cmd_auth[0].sessionHandle = TPM_RS_PW; ctx->cmd_auth[1].sessionHandle = TPM_RS_PW; *((UINT8 *) ((void *) &ctx->cmd_auth[0].sessionAttributes)) = 0; *((UINT8 *) ((void *) &ctx->cmd_auth[0].sessionAttributes)) = 0; /* Load input files */ if (flags.C) { result = file_load_tpm_context_from_file(ctx->sapi_context, &ctx->handle.obj, context_file); if (!result) { goto out; } } if (flags.c) { result = file_load_tpm_context_from_file(ctx->sapi_context, &ctx->handle.key, context_key_file); if (!result) { goto out; } } result = true; out: free(context_file); free(context_key_file); return result; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void)opts; (void)envp; tpm_certify_ctx ctx = { .cmd_auth = { { .sessionHandle = TPM_RS_PW, .sessionAttributes = { .val = 0 } }, // [0] { .sessionHandle = TPM_RS_PW, .sessionAttributes = { .val = 0 } } // [1] }, .file_path = { .attest = { 0 }, .sig = { 0 } }, .sapi_context = sapi_context }; bool result = init(argc, argv, &ctx); if (!result) { return false; } return certify_and_save_data(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_create.c000066400000000000000000000357401313543155100172550ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include #include #include "files.h" #include "main.h" #include "options.h" #include "string-bytes.h" TSS2_SYS_CONTEXT *sysContext; TPMS_AUTH_COMMAND sessionData; bool hexPasswd = false; int setAlg(TPMI_ALG_PUBLIC type,TPMI_ALG_HASH nameAlg,TPM2B_PUBLIC *inPublic, int I_flag) { switch(nameAlg) { case TPM_ALG_SHA1: case TPM_ALG_SHA256: case TPM_ALG_SHA384: case TPM_ALG_SHA512: case TPM_ALG_SM3_256: case TPM_ALG_NULL: inPublic->t.publicArea.nameAlg = nameAlg; break; default: printf("nameAlg algrithm: 0x%0x not support !\n", nameAlg); return -1; } // First clear attributes bit field. *(UINT32 *)&(inPublic->t.publicArea.objectAttributes) = 0; inPublic->t.publicArea.objectAttributes.restricted = 0; inPublic->t.publicArea.objectAttributes.userWithAuth = 1; inPublic->t.publicArea.objectAttributes.decrypt = 1; inPublic->t.publicArea.objectAttributes.sign = 1; inPublic->t.publicArea.objectAttributes.fixedTPM = 1; inPublic->t.publicArea.objectAttributes.fixedParent = 1; inPublic->t.publicArea.objectAttributes.sensitiveDataOrigin = 1; inPublic->t.publicArea.type = type; switch(type) { case TPM_ALG_RSA: inPublic->t.publicArea.parameters.rsaDetail.symmetric.algorithm = TPM_ALG_NULL; inPublic->t.publicArea.parameters.rsaDetail.scheme.scheme = TPM_ALG_NULL; inPublic->t.publicArea.parameters.rsaDetail.keyBits = 2048; inPublic->t.publicArea.parameters.rsaDetail.exponent = 0; inPublic->t.publicArea.unique.rsa.t.size = 0; break; case TPM_ALG_KEYEDHASH: inPublic->t.publicArea.unique.keyedHash.t.size = 0; inPublic->t.publicArea.objectAttributes.decrypt = 0; if (I_flag) { // sealing inPublic->t.publicArea.objectAttributes.sign = 0; inPublic->t.publicArea.objectAttributes.sensitiveDataOrigin = 0; inPublic->t.publicArea.parameters.keyedHashDetail.scheme.scheme = TPM_ALG_NULL; } else { // hmac inPublic->t.publicArea.objectAttributes.sign = 1; inPublic->t.publicArea.parameters.keyedHashDetail.scheme.scheme = TPM_ALG_HMAC; inPublic->t.publicArea.parameters.keyedHashDetail.scheme.details.hmac.hashAlg = nameAlg; //for tpm2_hmac multi alg } break; case TPM_ALG_ECC: inPublic->t.publicArea.parameters.eccDetail.symmetric.algorithm = TPM_ALG_NULL; inPublic->t.publicArea.parameters.eccDetail.scheme.scheme = TPM_ALG_NULL; inPublic->t.publicArea.parameters.eccDetail.curveID = TPM_ECC_NIST_P256; inPublic->t.publicArea.parameters.eccDetail.kdf.scheme = TPM_ALG_NULL; inPublic->t.publicArea.unique.ecc.x.t.size = 0; inPublic->t.publicArea.unique.ecc.y.t.size = 0; break; case TPM_ALG_SYMCIPHER: inPublic->t.publicArea.parameters.symDetail.sym.algorithm = TPM_ALG_AES; inPublic->t.publicArea.parameters.symDetail.sym.keyBits.sym = 128; inPublic->t.publicArea.parameters.symDetail.sym.mode.sym = TPM_ALG_CFB; inPublic->t.publicArea.unique.sym.t.size = 0; break; default: printf("type algrithm: 0x%0x not support !\n",type); return -2; } return 0; } int create(TPMI_DH_OBJECT parentHandle, TPM2B_PUBLIC *inPublic, TPM2B_SENSITIVE_CREATE *inSensitive, TPMI_ALG_PUBLIC type, TPMI_ALG_HASH nameAlg, const char *opuFilePath, const char *oprFilePath, int o_flag, int O_flag, int I_flag, int A_flag, UINT32 objectAttributes) { TPM_RC rval; TPMS_AUTH_RESPONSE sessionDataOut; TSS2_SYS_CMD_AUTHS sessionsData; TSS2_SYS_RSP_AUTHS sessionsDataOut; TPMS_AUTH_COMMAND *sessionDataArray[1]; TPMS_AUTH_RESPONSE *sessionDataOutArray[1]; TPM2B_DATA outsideInfo = { { 0, } }; TPML_PCR_SELECTION creationPCR; TPM2B_PUBLIC outPublic = { { 0, } }; TPM2B_PRIVATE outPrivate = TPM2B_TYPE_INIT(TPM2B_PRIVATE, buffer); TPM2B_CREATION_DATA creationData = { { 0, } }; TPM2B_DIGEST creationHash = TPM2B_TYPE_INIT(TPM2B_DIGEST, buffer); TPMT_TK_CREATION creationTicket = { 0, }; sessionDataArray[0] = &sessionData; sessionDataOutArray[0] = &sessionDataOut; sessionsDataOut.rspAuths = &sessionDataOutArray[0]; sessionsData.cmdAuths = &sessionDataArray[0]; sessionsDataOut.rspAuthsCount = 1; sessionData.sessionHandle = TPM_RS_PW; sessionData.nonce.t.size = 0; sessionsData.cmdAuthsCount = 1; sessionsData.cmdAuths[0] = &sessionData; if (sessionData.hmac.t.size > 0 && hexPasswd) { sessionData.hmac.t.size = sizeof(sessionData.hmac) - 2; if (hex2ByteStructure((char *)sessionData.hmac.t.buffer, &sessionData.hmac.t.size, sessionData.hmac.t.buffer) != 0) { printf( "Failed to convert Hex format password for parent Passwd.\n"); return -1; } } if (inSensitive->t.sensitive.userAuth.t.size > 0 && hexPasswd) { inSensitive->t.sensitive.userAuth.t.size = sizeof(inSensitive->t.sensitive.userAuth) - 2; if (hex2ByteStructure((char *)inSensitive->t.sensitive.userAuth.t.buffer, &inSensitive->t.sensitive.userAuth.t.size, inSensitive->t.sensitive.userAuth.t.buffer) != 0) { printf( "Failed to convert Hex format password for object Passwd.\n"); return -1; } } inSensitive->t.size = inSensitive->t.sensitive.userAuth.b.size + 2; if(setAlg(type, nameAlg, inPublic, I_flag)) return -1; if(A_flag == 1) inPublic->t.publicArea.objectAttributes.val = objectAttributes; printf("ObjectAttribute: 0x%08X\n",inPublic->t.publicArea.objectAttributes.val); creationPCR.count = 0; rval = Tss2_Sys_Create(sysContext, parentHandle, &sessionsData, inSensitive, inPublic, &outsideInfo, &creationPCR, &outPrivate,&outPublic,&creationData, &creationHash, &creationTicket, &sessionsDataOut); if(rval != TPM_RC_SUCCESS) { printf("\nCreate Object Failed ! ErrorCode: 0x%0x\n\n",rval); return -2; } printf("\nCreate Object Succeed !\n"); /* * TODO These public and private serializations are not safe since its outputting size as well. */ if(o_flag == 1) { if(!files_save_bytes_to_file(opuFilePath, (UINT8 *)&outPublic, sizeof(outPublic))) return -3; } if(O_flag == 1) { if(!files_save_bytes_to_file(oprFilePath, (UINT8 *)&outPrivate, sizeof(outPrivate))) return -4; } return 0; } int execute_tool (int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void)envp; (void)opts; sysContext = sapi_context; TPM2B_SENSITIVE_CREATE inSensitive; inSensitive.t.sensitive.data.t.size = 0; TPM2B_PUBLIC inPublic; TPMI_ALG_PUBLIC type; TPMI_ALG_HASH nameAlg; TPMI_DH_OBJECT parentHandle; UINT32 objectAttributes = 0; char opuFilePath[PATH_MAX] = {0}; char oprFilePath[PATH_MAX] = {0}; char *contextParentFilePath = NULL; setbuf(stdout, NULL); setvbuf (stdout, NULL, _IONBF, BUFSIZ); int opt = -1; const char *optstring = "H:P:K:g:G:A:I:L:o:O:c:X"; static struct option long_options[] = { {"parent",1,NULL,'H'}, {"pwdp",1,NULL,'P'}, {"pwdk",1,NULL,'K'}, {"halg",1,NULL,'g'}, {"kalg",1,NULL,'G'}, {"objectAttributes",1,NULL,'A'}, {"inFile",1,NULL,'I'}, {"policyFile",1,NULL,'L'}, {"opu",1,NULL,'o'}, {"opr",1,NULL,'O'}, {"contextParent",1,NULL,'c'}, {"passwdInHex",0,NULL,'X'}, {0,0,0,0} }; int returnVal = 0; int flagCnt = 0; int H_flag = 0, P_flag = 0, K_flag = 0, g_flag = 0, G_flag = 0, A_flag = 0, I_flag = 0, L_flag = 0, o_flag = 0, c_flag = 0, O_flag = 0/*, f_flag = 0*/; while((opt = getopt_long(argc,argv,optstring,long_options,NULL)) != -1) { switch(opt) { case 'H': if(!string_bytes_get_uint32(optarg,&parentHandle)) { showArgError(optarg, argv[0]); returnVal = -1; break; } H_flag = 1; break; case 'P': sessionData.hmac.t.size = sizeof(sessionData.hmac.t) - 2; if(str2ByteStructure(optarg,&sessionData.hmac.t.size,sessionData.hmac.t.buffer) != 0) { returnVal = -2; break; } P_flag = 1; break; case 'K': inSensitive.t.sensitive.userAuth.t.size = sizeof(inSensitive.t.sensitive.userAuth.t) - 2; if(str2ByteStructure(optarg,&inSensitive.t.sensitive.userAuth.t.size, inSensitive.t.sensitive.userAuth.t.buffer) != 0) { returnVal = -3; break; } K_flag = 1; break; case 'g': if(!string_bytes_get_uint16(optarg,&nameAlg)) { showArgError(optarg, argv[0]); returnVal = -4; break; } printf("nameAlg = 0x%4.4x\n", nameAlg); g_flag = 1; break; case 'G': if(!string_bytes_get_uint16(optarg,&type)) { showArgError(optarg, argv[0]); returnVal = -5; break; } printf("type = 0x%4.4x\n", type); G_flag = 1; break; case 'A': if(!string_bytes_get_uint32(optarg,&objectAttributes)) { showArgError(optarg, argv[0]); returnVal = -6; break; } A_flag = 1;//H_flag = 1; break; case 'I': inSensitive.t.sensitive.data.t.size = sizeof(inSensitive.t.sensitive.data) - 2; if(!files_load_bytes_from_file(optarg, inSensitive.t.sensitive.data.t.buffer, &inSensitive.t.sensitive.data.t.size)) { returnVal = -7; break; } I_flag = 1; printf("inSensitive.t.sensitive.data.t.size = %d\n",inSensitive.t.sensitive.data.t.size); break; case 'L': inPublic.t.publicArea.authPolicy.t.size = sizeof(inPublic.t.publicArea.authPolicy) - 2; if(!files_load_bytes_from_file(optarg, inPublic.t.publicArea.authPolicy.t.buffer, &inPublic.t.publicArea.authPolicy.t.size)) { returnVal = -8; break; } L_flag = 1; break; case 'o': snprintf(opuFilePath, sizeof(opuFilePath), "%s", optarg); if(files_does_file_exist(opuFilePath) != 0) { returnVal = -9; break; } o_flag = 1; break; case 'O': snprintf(oprFilePath, sizeof(oprFilePath), "%s", optarg); if(files_does_file_exist(oprFilePath) != 0) { returnVal = -10; break; } O_flag = 1; break; case 'c': contextParentFilePath = optarg; if(contextParentFilePath == NULL || contextParentFilePath[0] == '\0') { returnVal = -11; break; } printf("contextParentFile = %s\n", contextParentFilePath); c_flag = 1; break; case 'X': hexPasswd = true; break; case ':': // printf("Argument %c needs a value!\n",optopt); returnVal = -14; break; case '?': // printf("Unknown Argument: %c\n",optopt); returnVal = -15; break; //default: // break; } if(returnVal) break; }; if(returnVal != 0) return returnVal; if(P_flag == 0) sessionData.hmac.t.size = 0; if(I_flag == 0) inSensitive.t.sensitive.data.t.size = 0; if(K_flag == 0) inSensitive.t.sensitive.userAuth.t.size = 0; if(L_flag == 0) inPublic.t.publicArea.authPolicy.t.size = 0; *((UINT8 *)((void *)&sessionData.sessionAttributes)) = 0; flagCnt = H_flag + g_flag + G_flag + c_flag ; if(flagCnt == 1) { showArgMismatch(argv[0]); return -16; } else if(flagCnt == 3 && (H_flag == 1 || c_flag == 1) && g_flag == 1 && G_flag == 1) { if(c_flag) returnVal = file_load_tpm_context_from_file(sysContext, &parentHandle, contextParentFilePath) != true; if(returnVal == 0) returnVal = create(parentHandle, &inPublic, &inSensitive, type, nameAlg, opuFilePath, oprFilePath, o_flag, O_flag, I_flag, A_flag, objectAttributes); if(returnVal) return -17; } else { showArgMismatch(argv[0]); return -18; } return 0; } tpm2-tools-2.1.0/tools/tpm2_createprimary.c000066400000000000000000000302251313543155100206520ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include #include #include #include "files.h" #include "main.h" #include "options.h" #include "string-bytes.h" TPMS_AUTH_COMMAND sessionData; bool hexPasswd = false; TPM_HANDLE handle2048rsa; int setAlg(TPMI_ALG_PUBLIC type,TPMI_ALG_HASH nameAlg,TPM2B_PUBLIC *inPublic) { switch(nameAlg) { case TPM_ALG_SHA1: case TPM_ALG_SHA256: case TPM_ALG_SHA384: case TPM_ALG_SHA512: case TPM_ALG_SM3_256: case TPM_ALG_NULL: inPublic->t.publicArea.nameAlg = nameAlg; break; default: printf("nameAlg algrithm: 0x%0x not support !\n", nameAlg); return -1; } // First clear attributes bit field. *(UINT32 *)&(inPublic->t.publicArea.objectAttributes) = 0; inPublic->t.publicArea.objectAttributes.restricted = 1; inPublic->t.publicArea.objectAttributes.userWithAuth = 1; inPublic->t.publicArea.objectAttributes.decrypt = 1; inPublic->t.publicArea.objectAttributes.fixedTPM = 1; inPublic->t.publicArea.objectAttributes.fixedParent = 1; inPublic->t.publicArea.objectAttributes.sensitiveDataOrigin = 1; inPublic->t.publicArea.authPolicy.t.size = 0; inPublic->t.publicArea.type = type; switch(type) { case TPM_ALG_RSA: inPublic->t.publicArea.parameters.rsaDetail.symmetric.algorithm = TPM_ALG_AES; inPublic->t.publicArea.parameters.rsaDetail.symmetric.keyBits.aes = 128; inPublic->t.publicArea.parameters.rsaDetail.symmetric.mode.aes = TPM_ALG_CFB; inPublic->t.publicArea.parameters.rsaDetail.scheme.scheme = TPM_ALG_NULL; inPublic->t.publicArea.parameters.rsaDetail.keyBits = 2048; inPublic->t.publicArea.parameters.rsaDetail.exponent = 0; inPublic->t.publicArea.unique.rsa.t.size = 0; break; case TPM_ALG_KEYEDHASH: inPublic->t.publicArea.parameters.keyedHashDetail.scheme.scheme = TPM_ALG_XOR; inPublic->t.publicArea.parameters.keyedHashDetail.scheme.details.exclusiveOr.hashAlg = TPM_ALG_SHA256; inPublic->t.publicArea.parameters.keyedHashDetail.scheme.details.exclusiveOr.kdf = TPM_ALG_KDF1_SP800_108; inPublic->t.publicArea.unique.keyedHash.t.size = 0; break; case TPM_ALG_ECC: inPublic->t.publicArea.parameters.eccDetail.symmetric.algorithm = TPM_ALG_AES; inPublic->t.publicArea.parameters.eccDetail.symmetric.keyBits.aes = 128; inPublic->t.publicArea.parameters.eccDetail.symmetric.mode.sym = TPM_ALG_CFB; inPublic->t.publicArea.parameters.eccDetail.scheme.scheme = TPM_ALG_NULL; inPublic->t.publicArea.parameters.eccDetail.curveID = TPM_ECC_NIST_P256; inPublic->t.publicArea.parameters.eccDetail.kdf.scheme = TPM_ALG_NULL; inPublic->t.publicArea.unique.ecc.x.t.size = 0; inPublic->t.publicArea.unique.ecc.y.t.size = 0; break; case TPM_ALG_SYMCIPHER: inPublic->t.publicArea.parameters.symDetail.sym.algorithm = TPM_ALG_AES; inPublic->t.publicArea.parameters.symDetail.sym.keyBits.sym = 128; inPublic->t.publicArea.parameters.symDetail.sym.mode.sym = TPM_ALG_CFB; inPublic->t.publicArea.unique.sym.t.size = 0; break; default: printf("type algrithm: 0x%0x not support !\n",type); return -2; } return 0; } int createPrimary(TSS2_SYS_CONTEXT *sysContext, TPMI_RH_HIERARCHY hierarchy, TPM2B_PUBLIC *inPublic, TPM2B_SENSITIVE_CREATE *inSensitive, TPMI_ALG_PUBLIC type, TPMI_ALG_HASH nameAlg, int P_flag, int K_flag) { UINT32 rval; TPMS_AUTH_RESPONSE sessionDataOut; TSS2_SYS_CMD_AUTHS sessionsData; TSS2_SYS_RSP_AUTHS sessionsDataOut; TPMS_AUTH_COMMAND *sessionDataArray[1]; TPMS_AUTH_RESPONSE *sessionDataOutArray[1]; TPM2B_DATA outsideInfo = { { 0, } }; TPML_PCR_SELECTION creationPCR; TPM2B_NAME name = TPM2B_TYPE_INIT(TPM2B_NAME, name); TPM2B_PUBLIC outPublic = { { 0, } }; TPM2B_CREATION_DATA creationData = { { 0, } }; TPM2B_DIGEST creationHash = TPM2B_TYPE_INIT(TPM2B_DIGEST, buffer); TPMT_TK_CREATION creationTicket = { 0, }; sessionDataArray[0] = &sessionData; sessionDataOutArray[0] = &sessionDataOut; sessionsDataOut.rspAuths = &sessionDataOutArray[0]; sessionsData.cmdAuths = &sessionDataArray[0]; sessionsData.cmdAuthsCount = 1; sessionsDataOut.rspAuthsCount = 1; sessionData.sessionHandle = TPM_RS_PW; sessionData.nonce.t.size = 0; if(P_flag == 0) sessionData.hmac.t.size = 0; *((UINT8 *)((void *)&sessionData.sessionAttributes)) = 0; if (sessionData.hmac.t.size > 0 && hexPasswd) { sessionData.hmac.t.size = sizeof(sessionData.hmac) - 2; if (hex2ByteStructure((char *)sessionData.hmac.t.buffer, &sessionData.hmac.t.size, sessionData.hmac.t.buffer) != 0) { printf( "Failed to convert Hex format password for hierarchy Passwd.\n"); return -1; } } if(K_flag == 0) inSensitive->t.sensitive.userAuth.t.size = 0; if (inSensitive->t.sensitive.userAuth.t.size > 0 && hexPasswd) { inSensitive->t.sensitive.userAuth.t.size = sizeof(inSensitive->t.sensitive.userAuth) - 2; if (hex2ByteStructure((char *)inSensitive->t.sensitive.userAuth.t.buffer, &inSensitive->t.sensitive.userAuth.t.size, inSensitive->t.sensitive.userAuth.t.buffer) != 0) { printf( "Failed to convert Hex format password for primary Passwd.\n"); return -1; } } inSensitive->t.sensitive.data.t.size = 0; inSensitive->t.size = inSensitive->t.sensitive.userAuth.b.size + 2; if(setAlg(type, nameAlg, inPublic)) return -1; creationPCR.count = 0; rval = Tss2_Sys_CreatePrimary(sysContext, hierarchy, &sessionsData, inSensitive, inPublic, &outsideInfo, &creationPCR, &handle2048rsa, &outPublic, &creationData, &creationHash, &creationTicket, &name, &sessionsDataOut); if(rval != TPM_RC_SUCCESS) { printf("\nCreatePrimary Failed ! ErrorCode: 0x%0x\n\n",rval); return -2; } printf("\nCreatePrimary Succeed ! Handle: 0x%8.8x\n\n",handle2048rsa); return 0; } int execute_tool (int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void) envp; (void) opts; TPM2B_SENSITIVE_CREATE inSensitive; TPM2B_PUBLIC inPublic; TPMI_ALG_PUBLIC type; TPMI_ALG_HASH nameAlg; TPMI_RH_HIERARCHY hierarchy = TPM_RH_NULL; setbuf(stdout, NULL); setvbuf (stdout, NULL, _IONBF, BUFSIZ); int opt = -1; const char *optstring = "A:P:K:g:G:C:X"; static struct option long_options[] = { {"auth",1,NULL,'A'}, {"pwdp",1,NULL,'P'}, {"pwdk",1,NULL,'K'}, {"halg",1,NULL,'g'}, {"kalg",1,NULL,'G'}, {"context",1,NULL,'C'}, {"passwdInHex",0,NULL,'X'}, {0,0,0,0} }; int returnVal = 0; int A_flag = 0, P_flag = 0, K_flag = 0, g_flag = 0, G_flag = 0, C_flag = 0; char *contextFile = NULL; while((opt = getopt_long(argc,argv,optstring,long_options,NULL)) != -1) { switch(opt) { case 'A': if(strcmp(optarg,"o") == 0 || strcmp(optarg,"O") == 0) hierarchy = TPM_RH_OWNER; else if(strcmp(optarg,"p") == 0 || strcmp(optarg,"P") == 0) hierarchy = TPM_RH_PLATFORM; else if(strcmp(optarg,"e") == 0 || strcmp(optarg,"E") == 0) hierarchy = TPM_RH_ENDORSEMENT; else if(strcmp(optarg,"n") == 0 || strcmp(optarg,"N") == 0) hierarchy = TPM_RH_NULL; else { returnVal = -1; break; } A_flag = 1; break; case 'P': sessionData.hmac.t.size = sizeof(sessionData.hmac.t) - 2; if(str2ByteStructure(optarg,&sessionData.hmac.t.size,sessionData.hmac.t.buffer) != 0) { returnVal = -2; break; } P_flag = 1; break; case 'K': inSensitive.t.sensitive.userAuth.t.size = sizeof(inSensitive.t.sensitive.userAuth.t) - 2; if(str2ByteStructure(optarg,&inSensitive.t.sensitive.userAuth.t.size, inSensitive.t.sensitive.userAuth.t.buffer) != 0) { returnVal = -3; break; } K_flag = 1; break; case 'g': if(!string_bytes_get_uint16(optarg,&nameAlg)) { showArgError(optarg, argv[0]); returnVal = -4; break; } printf("nameAlg = 0x%4.4x\n", nameAlg); g_flag = 1; break; case 'G': if(!string_bytes_get_uint16(optarg,&type)) { showArgError(optarg, argv[0]); returnVal = -5; break; } printf("type = 0x%4.4x\n", type); G_flag = 1; break; case 'C': contextFile = optarg; if(contextFile == NULL || contextFile[0] == '\0') { returnVal = -8; break; } printf("contextFile = %s\n", contextFile); C_flag = 1; break; case 'X': hexPasswd = true; break; case ':': // printf("Argument %c needs a value!\n",optopt); returnVal = -9; break; case '?': // printf("Unknown Argument: %c\n",optopt); returnVal = -10; break; //default: // break; } if(returnVal) break; }; if(returnVal != 0) return returnVal; if(A_flag == 1 && g_flag == 1 && G_flag == 1) { returnVal = createPrimary(sapi_context, hierarchy, &inPublic, &inSensitive, type, nameAlg, P_flag, K_flag); if (returnVal == 0 && C_flag) returnVal = files_save_tpm_context_to_file(sapi_context, handle2048rsa, contextFile) != true; if(returnVal) return -12; } else { showArgMismatch(argv[0]); return -13; } return 0; } tpm2-tools-2.1.0/tools/tpm2_dump_capability.c000066400000000000000000000564621313543155100211640ustar00rootroot00000000000000/* * Copyright (c) 2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include "main.h" /* convenience macro to convert flags into "set" / "clear" strings */ #define prop_str(val) val ? "set" : "clear" /* number of eleents in the capability_map array */ #define CAPABILITY_MAP_COUNT \ (sizeof (capability_map) / sizeof (capability_map_entry_t)) /* Structure to map a string to the appropriate TPM_CAP / TPM_PT pair */ typedef struct capability_map_entry { char *capability_string; TPM_CAP capability; UINT32 property; UINT32 count; } capability_map_entry_t; /* * Array of structurs for use as a lookup table to map string representation * of a capability to the proper TPM_CAP / TPM_PT pair. */ capability_map_entry_t capability_map[] = { { .capability_string = "properties-fixed", .capability = TPM_CAP_TPM_PROPERTIES, .property = PT_FIXED, .count = MAX_TPM_PROPERTIES, }, { .capability_string = "properties-variable", .capability = TPM_CAP_TPM_PROPERTIES, .property = PT_VAR, .count = MAX_TPM_PROPERTIES, }, { .capability_string = "algorithms", .capability = TPM_CAP_ALGS, .property = TPM_ALG_FIRST, .count = MAX_ALG_LIST_SIZE, }, { .capability_string = "commands", .capability = TPM_CAP_COMMANDS, .property = TPM_CC_FIRST, .count = MAX_CAP_CC, }, }; /* * Structure to hold options for this tool. */ typedef struct capability_opts { char *capability_string; TPM_CAP capability; UINT32 property; UINT32 count; } capability_opts_t; /* * This function takes a capability_opts_t structure as a parameter. It * uses the 'param' field in this structure to locate the same string in * the capability_map array and then populates the 'capability' and * 'property' fields of the capability_opts_t structure with the appropriate * values from the capability_map. * Return values: * 0 - the function executed normally. * 1 - the parameter 'param' in the capability_opts_t structure is NULL. * 2 - no matching entry found in capability_map. */ int sanity_check_capability_opts (capability_opts_t *capability_opts) { if (capability_opts->capability_string == NULL) { fprintf (stderr, "missing capability string, see --help\n"); return 2; } size_t i; for (i = 0; i < CAPABILITY_MAP_COUNT; ++i) { int cmp = strncmp (capability_map [i].capability_string, capability_opts->capability_string, strlen (capability_map [i].capability_string)); if (cmp == 0) { capability_opts->capability = capability_map [i].capability; capability_opts->property = capability_map [i].property; capability_opts->count = capability_map [i].count; return 0; } } fprintf (stderr, "invalid capability string: %s, see --help\n", capability_opts->capability_string); return 2; } /* * There are a number of fixed TPM properties (tagged properties) that are * characters (8bit chars) packed into 32bit integers. */ void get_uint32_as_chars (UINT32 value, char *buf) { sprintf (buf, "%c%c%c%c", ((UINT8*)&value)[3], ((UINT8*)&value)[2], ((UINT8*)&value)[1], ((UINT8*)&value)[0]); } /* * Print string representations of the TPMA_MODES. */ void printf_tpma_modes (TPMA_MODES modes) { printf ("TPM_PT_MODES: 0x%08x\n", modes.val); if (modes.FIPS_140_2) printf (" TPMA_MODES_FIPS_140_2\n"); if (modes.reserved1) printf (" TPMA_MODES_RESERVED1 (these bits shouldn't be set)\n"); } /* * Print string representation of the TPMA_PERMANENT attributes. */ void dump_permanent_attrs (TPMA_PERMANENT attrs) { printf ("TPM_PT_PERSISTENT:\n"); printf (" ownerAuthSet: %s\n", prop_str (attrs.ownerAuthSet)); printf (" endorsementAuthSet: %s\n", prop_str (attrs.endorsementAuthSet)); printf (" lockoutAuthSet: %s\n", prop_str (attrs.lockoutAuthSet)); printf (" reserved1: %s\n", prop_str (attrs.reserved1)); printf (" disableClear: %s\n", prop_str (attrs.disableClear)); printf (" inLockout: %s\n", prop_str (attrs.inLockout)); printf (" tpmGeneratedEPS: %s\n", prop_str (attrs.tpmGeneratedEPS)); printf (" reserved2: %s\n", prop_str (attrs.reserved2)); } /* * Print string representations of the TPMA_STARTUP_CLEAR attributes. */ void dump_startup_clear_attrs (TPMA_STARTUP_CLEAR attrs) { printf ("TPM_PT_STARTUP_CLEAR:\n"); printf (" phEnable: %s\n", prop_str (attrs.phEnable)); printf (" shEnable: %s\n", prop_str (attrs.shEnable)); printf (" ehEnable: %s\n", prop_str (attrs.ehEnable)); printf (" phEnableNV: %s\n", prop_str (attrs.phEnableNV)); printf (" reserved1: %s\n", prop_str (attrs.reserved1)); printf (" orderly: %s\n", prop_str (attrs.orderly)); } /* * Iterate over all fixed properties, call the unique print function for each. */ void dump_tpm_properties_fixed (TPMS_TAGGED_PROPERTY properties[], size_t count) { size_t i; char buf[5] = { 0, }; for (i = 0; i < count; ++i) { TPM_PT property = properties[i].property; UINT32 value = properties[i].value; switch (property) { case TPM_PT_FAMILY_INDICATOR: get_uint32_as_chars (value, buf); printf ("TPM_PT_FAMILY_INDICATOR:\n" " as UINT32: 0x08%x\n" " as string: \"%s\"\n", value, buf); break; case TPM_PT_LEVEL: printf ("TPM_PT_LEVEL: %d\n", value); break; case TPM_PT_REVISION: printf ("TPM_PT_REVISION: %.2f\n", (float)(value / 100)); break; case TPM_PT_DAY_OF_YEAR: printf ("TPM_PT_DAY_OF_YEAR: 0x%08x\n", value); break; case TPM_PT_YEAR: printf ("TPM_PT_YEAR: 0x%08x\n", value); break; case TPM_PT_MANUFACTURER: printf ("TPM_PT_MANUFACTURER: 0x%08x\n", value); break; case TPM_PT_VENDOR_STRING_1: get_uint32_as_chars (value, buf); printf ("TPM_PT_VENDOR_STRING_1:\n" " as UINT32: 0x%08x\n" " as string: \"%s\"\n", value, buf); break; case TPM_PT_VENDOR_STRING_2: get_uint32_as_chars (value, buf); printf ("TPM_PT_VENDOR_STRING_2:\n" " as UINT32: 0x%08x\n" " as string: \"%s\"\n", value, buf); break; case TPM_PT_VENDOR_STRING_3: get_uint32_as_chars (value, buf); printf ("TPM_PT_VENDOR_STRING_3:\n" " as UINT32: 0x%08x\n" " as string: \"%s\"\n", value, buf); break; case TPM_PT_VENDOR_STRING_4: get_uint32_as_chars (value, buf); printf ("TPM_PT_VENDOR_STRING_4:\n" " as UINT32: 0x%08x\n" " as string: \"%s\"\n", value, buf); break; case TPM_PT_VENDOR_TPM_TYPE: printf ("TPM_PT_VENDOR_TPM_TYPE: 0x%08x\n", value); break; case TPM_PT_FIRMWARE_VERSION_1: printf ("TPM_PT_FIRMWARE_VERSION_1: 0x%08x\n", value); break; case TPM_PT_FIRMWARE_VERSION_2: printf ("TPM_PT_FIRMWARE_VERSION_2: 0x%08x\n", value); break; case TPM_PT_INPUT_BUFFER: printf ("TPM_PT_INPUT_BUFFER: 0x%08x\n", value); break; case TPM_PT_HR_TRANSIENT_MIN: printf ("TPM_PT_HR_TRANSIENT_MIN: 0x%08x\n", value); break; case TPM_PT_HR_PERSISTENT_MIN: printf ("TPM_PT_HR_PERSISTENT_MIN: 0x%08x\n", value); break; case TPM_PT_HR_LOADED_MIN: printf ("TPM_PT_HR_LOADED_MIN: 0x%08x\n", value); break; case TPM_PT_ACTIVE_SESSIONS_MAX: printf ("TPM_PT_ACTIVE_SESSIONS_MAX: 0x%08x\n", value); break; case TPM_PT_PCR_COUNT: printf ("TPM_PT_PCR_COUNT: 0x%08x\n", value); break; case TPM_PT_PCR_SELECT_MIN: printf ("TPM_PT_PCR_SELECT_MIN: 0x%08x\n", value); break; case TPM_PT_CONTEXT_GAP_MAX: printf ("TPM_PT_CONTEXT_GAP_MAX: 0x%08x\n", value); break; case TPM_PT_NV_COUNTERS_MAX: printf ("TPM_PT_NV_COUNTERS_MAX: 0x%08x\n", value); break; case TPM_PT_NV_INDEX_MAX: printf ("TPM_PT_NV_INDEX_MAX: 0x%08x\n", value); break; case TPM_PT_MEMORY: printf ("TPM_PT_MEMORY: 0x%08x\n", value); break; case TPM_PT_CLOCK_UPDATE: printf ("TPM_PT_CLOCK_UPDATE: 0x%08x\n", value); break; case TPM_PT_CONTEXT_HASH: /* this may be a TPM_ALG_ID type */ printf ("TPM_PT_CONTEXT_HASH: 0x%08x\n", value); break; case TPM_PT_CONTEXT_SYM: /* this is a TPM_ALG_ID type */ printf ("TPM_PT_CONTEXT_SYM: 0x%08x\n", value); break; case TPM_PT_CONTEXT_SYM_SIZE: printf ("TPM_PT_CONTEXT_SYM_SIZE: 0x%08x\n", value); break; case TPM_PT_ORDERLY_COUNT: printf ("TPM_PT_ORDERLY_COUNT: 0x%08x\n", value); break; case TPM_PT_MAX_COMMAND_SIZE: printf ("TPM_PT_MAX_COMMAND_SIZE: 0x%08x\n", value); break; case TPM_PT_MAX_RESPONSE_SIZE: printf ("TPM_PT_MAX_RESPONSE_SIZE: 0x%08x\n", value); break; case TPM_PT_MAX_DIGEST: printf ("TPM_PT_MAX_DIGEST: 0x%08x\n", value); break; case TPM_PT_MAX_OBJECT_CONTEXT: printf ("TPM_PT_MAX_OBJECT_CONTEXT: 0x%08x\n", value); break; case TPM_PT_MAX_SESSION_CONTEXT: printf ("TPM_PT_MAX_SESSION_CONTEXT: 0x%08x\n", value); break; case TPM_PT_PS_FAMILY_INDICATOR: printf ("TPM_PT_PS_FAMILY_INDICATOR: 0x%08x\n", value); break; case TPM_PT_PS_LEVEL: printf ("TPM_PT_PS_LEVEL: 0x%08x\n", value); break; case TPM_PT_PS_REVISION: printf ("TPM_PT_PS_REVISION: 0x%08x\n", value); break; case TPM_PT_PS_DAY_OF_YEAR: printf ("TPM_PT_PS_DAY_OF_YEAR: 0x%08x\n", value); break; case TPM_PT_PS_YEAR: printf ("TPM_PT_PS_YEAR: 0x%08x\n", value); break; case TPM_PT_SPLIT_MAX: printf ("TPM_PT_SPLIT_MAX: 0x%08x\n", value); break; case TPM_PT_TOTAL_COMMANDS: printf ("TPM_PT_TOTAL_COMMANDS: 0x%08x\n", value); break; case TPM_PT_LIBRARY_COMMANDS: printf ("TPM_PT_LIBRARY_COMMANDS: 0x%08x\n", value); break; case TPM_PT_VENDOR_COMMANDS: printf ("TPM_PT_VENDOR_COMMANDS: 0x%08x\n", value); break; case TPM_PT_NV_BUFFER_MAX: printf ("TPM_PT_NV_BUFFER_MAX: 0x%08x\n", value); break; case TPM_PT_MODES: printf_tpma_modes ((TPMA_MODES)value); break; } } } /* * Iterate over all variable properties, call the unique print function for each. */ void dump_tpm_properties_var (TPMS_TAGGED_PROPERTY properties[], size_t count) { size_t i; for (i = 0; i < count; ++i) { TPM_PT property = properties[i].property; UINT32 value = properties[i].value; switch (property) { case TPM_PT_PERMANENT: dump_permanent_attrs ((TPMA_PERMANENT)value); break; case TPM_PT_STARTUP_CLEAR: dump_startup_clear_attrs ((TPMA_STARTUP_CLEAR)value); break; case TPM_PT_HR_NV_INDEX: printf ("TPM_PT_HR_NV_INDEX: 0x%08x\n", value); break; case TPM_PT_HR_LOADED: printf ("TPM_PT_HR_LOADED: 0x%08x\n", value); break; case TPM_PT_HR_LOADED_AVAIL: printf ("TPM_PT_HR_LOADED_AVAIL: 0x%08x\n", value); break; case TPM_PT_HR_ACTIVE: printf ("TPM_PT_HR_ACTIVE: 0x%08x\n", value); break; case TPM_PT_HR_ACTIVE_AVAIL: printf ("TPM_PT_HR_ACTIVE_AVAIL: 0x%08x\n", value); break; case TPM_PT_HR_TRANSIENT_AVAIL: printf ("TPM_PT_HR_TRANSIENT_AVAIL: 0x%08x\n", value); break; case TPM_PT_HR_PERSISTENT: printf ("TPM_PT_HR_PERSISTENT: 0x%08x\n", value); break; case TPM_PT_HR_PERSISTENT_AVAIL: printf ("TPM_PT_HR_PERSISTENT_AVAIL: 0x%08x\n", value); break; case TPM_PT_NV_COUNTERS: printf ("TPM_PT_NV_COUNTERS: 0x%08x\n", value); break; case TPM_PT_NV_COUNTERS_AVAIL: printf ("TPM_PT_NV_COUNTERS_AVAIL: 0x%08x\n", value); break; case TPM_PT_ALGORITHM_SET: printf ("TPM_PT_ALGORITHM_SET: 0x%08x\n", value); break; case TPM_PT_LOADED_CURVES: printf ("TPM_PT_LOADED_CURVES: 0x%08x\n", value); break; case TPM_PT_LOCKOUT_COUNTER: printf ("TPM_PT_LOCKOUT_COUNTER: 0x%08x\n", value); break; case TPM_PT_MAX_AUTH_FAIL: printf ("TPM_PT_MAX_AUTH_FAIL: 0x%08x\n", value); break; case TPM_PT_LOCKOUT_INTERVAL: printf ("TPM_PT_LOCKOUT_INTERVAL: 0x%08x\n", value); break; case TPM_PT_LOCKOUT_RECOVERY: printf ("TPM_PT_LOCKOUT_RECOVERY: 0x%08x\n", value); break; case TPM_PT_NV_WRITE_RECOVERY: printf ("TPM_PT_NV_WRITE_RECOVERY: 0x%08x\n", value); break; case TPM_PT_AUDIT_COUNTER_0: printf ("TPM_PT_AUDIT_COUNTER_0: 0x%08x\n", value); break; case TPM_PT_AUDIT_COUNTER_1: printf ("TPM_PT_AUDIT_COUNTER_1: 0x%08x\n", value); break; default: fprintf (stderr, "Unknown property: 0x%08x\n", properties[i].property); break; } } } /* * Print data about TPM_ALG_ID in human readable form. */ void dump_algorithm_properties (TPM_ALG_ID id, TPMA_ALGORITHM alg_attrs) { printf ("TPMA_ALGORITHM for ALG_ID: 0x%x\n", id); printf (" asymmetric: %s\n", prop_str (alg_attrs.asymmetric)); printf (" symmetric: %s\n", prop_str (alg_attrs.symmetric)); printf (" hash: %s\n", prop_str (alg_attrs.hash)); printf (" object: %s\n", prop_str (alg_attrs.object)); printf (" reserved: 0x%x\n", alg_attrs.reserved1); printf (" signing: %s\n", prop_str (alg_attrs.signing)); printf (" encrypting: %s\n", prop_str (alg_attrs.encrypting)); printf (" method: %s\n", prop_str (alg_attrs.method)); } /* * Iterate over the count TPMS_ALG_PROPERTY entries and dump the * TPMA_ALGORITHM attributes for each. */ void dump_algorithms (TPMS_ALG_PROPERTY alg_properties[], size_t count) { size_t i; for (i = 0; i < count; ++i) dump_algorithm_properties (alg_properties[i].alg, alg_properties[i].algProperties); } /* * Pretty print the bit fields from the TPMA_CC (UINT32) */ void dump_command_attrs (TPMA_CC tpma_cc) { printf ("TPMA_CC: 0x%08x\n", tpma_cc.val); printf (" commandIndex: 0x%x\n", tpma_cc.commandIndex); printf (" reserved1: 0x%x\n", tpma_cc.reserved1); printf (" nv: %s\n", prop_str (tpma_cc.nv)); printf (" extensive: %s\n", prop_str (tpma_cc.extensive)); printf (" flushed: %s\n", prop_str (tpma_cc.flushed)); printf (" cHandles: 0x%x\n", tpma_cc.cHandles); printf (" rHandle: %s\n", prop_str (tpma_cc.rHandle)); printf (" V: %s\n", prop_str (tpma_cc.V)); printf (" Res: 0x%x\n", tpma_cc.Res); } /* * Iterate over an array of TPMA_CCs and dump out a human readable * representation of each array member. */ void dump_command_attr_array (TPMA_CC command_attributes[], UINT32 count) { size_t i; for (i = 0; i < count; ++i) dump_command_attrs (command_attributes [i]); } /* * Query the TPM for TPM capabilities. */ TSS2_RC get_tpm_capability_all (TSS2_SYS_CONTEXT *sapi_ctx, TPMS_CAPABILITY_DATA *capability_data, TPM_CAP capability, UINT32 property, UINT32 count) { TSS2_RC rc; TPMI_YES_NO more_data; rc = Tss2_Sys_GetCapability (sapi_ctx, NULL, capability, property, count, &more_data, capability_data, NULL); if (rc != TSS2_RC_SUCCESS) fprintf (stderr, "Failed to GetCapability: capability: 0x%x, property: 0x%x, " "TSS2_RC: 0x%x\n", capability, property, rc); return rc; } /* * Get options required by / for this tool. * Returns: * 0 if we get all of the options we expect. * 1 if we encounter an error. */ void get_capability_opts (int argc, char *argv[], capability_opts_t *capability_opts) { int c = 0, option_index = 0; char *arg_str = "c:"; static struct option long_options [] = { { .name = "capability", .has_arg = required_argument, .flag = NULL, .val = 'c', }, { NULL, }, }; while ((c = getopt_long (argc, argv, arg_str, long_options, &option_index)) != -1) { switch (c) { case 'c': capability_opts->capability_string = optarg; break; } } } /* * This function is a glorified switch statement. It uses the 'capability' * and 'property' parameters to find the right print function for the * capabilities in the 'capabilities' parameter. * On success it will return 0, if it failes (is unable to find an * appropriate print function for the provided 'capability' / 'property' * pair) then it will return 1. */ static int dump_tpm_capability (TPMU_CAPABILITIES *capabilities, TPM_CAP capability, UINT32 property) { switch (capability) { case TPM_CAP_TPM_PROPERTIES: switch (property) { case PT_FIXED: dump_tpm_properties_fixed (capabilities->tpmProperties.tpmProperty, capabilities->tpmProperties.count); break; case PT_VAR: dump_tpm_properties_var (capabilities->tpmProperties.tpmProperty, capabilities->tpmProperties.count); break; default: return 1; } break; case TPM_CAP_ALGS: dump_algorithms (capabilities->algorithms.algProperties, capabilities->algorithms.count); break; case TPM_CAP_COMMANDS: dump_command_attr_array (capabilities->command.commandAttributes, capabilities->command.count); /* no break */ default: return 1; } return 0; } int execute_tool (int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void) opts; (void) envp; TSS2_RC rc; TPMS_CAPABILITY_DATA capability_data = { 0, }; int ret; capability_opts_t options = { .capability_string = NULL, .capability = 0, .property = 0, }; get_capability_opts (argc, argv, &options); ret = sanity_check_capability_opts (&options); if (ret == 1) { fprintf (stderr, "Missing capability string. See --help.\n"); return 1; } else if (ret == 2) { fprintf (stderr, "Invalid capability string. See --help.\n"); return 1; } /* get requested capability from TPM, dump it to stdout */ rc = get_tpm_capability_all (sapi_context, &capability_data, options.capability, options.property, options.count); if (rc != TSS2_RC_SUCCESS) return 1; dump_tpm_capability (&capability_data.data, options.capability, options.property); return 0; } tpm2-tools-2.1.0/tools/tpm2_encryptdecrypt.c000066400000000000000000000174021313543155100210640ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include #include "files.h" #include "log.h" #include "main.h" #include "options.h" #include "password_util.h" #include "string-bytes.h" typedef struct tpm_encrypt_decrypt_ctx tpm_encrypt_decrypt_ctx; struct tpm_encrypt_decrypt_ctx { TPMS_AUTH_COMMAND session_data; TPMI_YES_NO is_decrypt; TPMI_DH_OBJECT key_handle; TPM2B_MAX_BUFFER data; char out_file_path[PATH_MAX]; TSS2_SYS_CONTEXT *sapi_context; }; static bool encryptDecrypt(tpm_encrypt_decrypt_ctx *ctx) { TPM2B_MAX_BUFFER out_data = TPM2B_TYPE_INIT(TPM2B_MAX_BUFFER, buffer); TPM2B_IV iv_out = TPM2B_TYPE_INIT(TPM2B_IV, buffer); TSS2_SYS_CMD_AUTHS sessions_data; TPMS_AUTH_RESPONSE session_data_out; TSS2_SYS_RSP_AUTHS sessions_data_out; TPMS_AUTH_COMMAND *session_data_array[1]; TPMS_AUTH_RESPONSE *session_data_out_array[1]; session_data_array[0] = &ctx->session_data; sessions_data.cmdAuths = &session_data_array[0]; session_data_out_array[0] = &session_data_out; sessions_data_out.rspAuths = &session_data_out_array[0]; sessions_data_out.rspAuthsCount = 1; sessions_data.cmdAuthsCount = 1; sessions_data.cmdAuths[0] = &ctx->session_data; TPM2B_IV iv_in = { .t = { .size = MAX_SYM_BLOCK_SIZE, .buffer = { 0 } }, }; TPM_RC rval = Tss2_Sys_EncryptDecrypt(ctx->sapi_context, ctx->key_handle, &sessions_data, ctx->is_decrypt, TPM_ALG_NULL, &iv_in, &ctx->data, &out_data, &iv_out, &sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("EncryptDecrypt failed, error code: 0x%x\n", rval); return false; } return files_save_bytes_to_file(ctx->out_file_path, (UINT8 *) out_data.t.buffer, out_data.t.size); } static bool init(int argc, char *argv[], tpm_encrypt_decrypt_ctx *ctx) { bool result = false; bool is_hex_passwd = false; int opt = -1; const char *optstring = "k:P:D:I:o:c:X"; static struct option long_options[] = { {"keyHandle", required_argument, NULL, 'k'}, {"pwdk", required_argument, NULL, 'P'}, {"decrypt", required_argument, NULL, 'D'}, {"inFile", required_argument, NULL, 'I'}, {"outFile", required_argument, NULL, 'o'}, {"keyContext", required_argument, NULL, 'c'}, {"passwdInHex", no_argument, NULL, 'X'}, {NULL, no_argument, NULL, '\0'} }; struct { UINT8 k : 1; UINT8 P : 1; UINT8 D : 1; UINT8 I : 1; UINT8 o : 1; UINT8 c : 1; UINT8 X : 1; UINT8 unused : 1; } flags = { 0 }; char *contextKeyFile = NULL; if (argc == 1) { showArgMismatch(argv[0]); return false; } while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) { switch (opt) { case 'k': result = string_bytes_get_uint32(optarg, &ctx->key_handle); if (!result) { LOG_ERR("Could not convert keyhandle to number, got: \"%s\"", optarg); goto out; } flags.k = 1; break; case 'P': result = password_util_copy_password(optarg, "key", &ctx->session_data.hmac); if (!result) { goto out; } flags.P = 1; break; case 'D': if (!strcasecmp("YES", optarg)) { ctx->is_decrypt = YES; } else if (!strcasecmp("NO", optarg)) { ctx->is_decrypt = NO; } else { showArgError(optarg, argv[0]); goto out; } break; case 'I': ctx->data.t.size = sizeof(ctx->data) - 2; result = files_load_bytes_from_file(optarg, ctx->data.t.buffer, &ctx->data.t.size); if (!result) { goto out; } flags.I = 1; break; case 'o': result = files_does_file_exist(optarg); if (result) { goto out; } snprintf(ctx->out_file_path, sizeof(ctx->out_file_path), "%s", optarg); flags.o = 1; break; case 'c': if (contextKeyFile) { LOG_ERR("Multiple specifications of -c"); goto out; } contextKeyFile = strdup(optarg); if (!contextKeyFile) { LOG_ERR("OOM"); goto out; } flags.c = 1; break; case 'X': is_hex_passwd = true; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); goto out; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); goto out; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); goto out; } } if (!((flags.k || flags.c) && flags.I && flags.o)) { LOG_ERR("Invalid arguments"); goto out; } if (flags.c) { result = file_load_tpm_context_from_file(ctx->sapi_context, &ctx->key_handle, contextKeyFile); if (!result) { goto out; } } result = password_util_to_auth(&ctx->session_data.hmac, is_hex_passwd, "key", &ctx->session_data.hmac); out: free(contextKeyFile); return result; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { /* opts and envp are unused, avoid compiler warning */ (void) opts; (void) envp; tpm_encrypt_decrypt_ctx ctx = { .session_data = { 0 }, .is_decrypt = NO, .data = {{ 0 }}, .sapi_context = sapi_context }; ctx.session_data.sessionHandle = TPM_RS_PW; bool result = init(argc, argv, &ctx); if (!result) { return false; } return encryptDecrypt(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_evictcontrol.c000066400000000000000000000161661313543155100205260ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include #include "files.h" #include "log.h" #include "main.h" #include "options.h" #include "password_util.h" #include "string-bytes.h" typedef struct tpm_evictcontrol_ctx tpm_evictcontrol_ctx; struct tpm_evictcontrol_ctx { TPMS_AUTH_COMMAND session_data; TPMI_RH_PROVISION auth; struct { TPMI_DH_OBJECT object; TPMI_DH_OBJECT persist; } handle; TSS2_SYS_CONTEXT *sapi_context; }; static int evict_control(tpm_evictcontrol_ctx *ctx) { TPMS_AUTH_RESPONSE session_data_out; TSS2_SYS_CMD_AUTHS sessions_data; TSS2_SYS_RSP_AUTHS sessions_data_out; TPMS_AUTH_COMMAND *session_data_array[1]; TPMS_AUTH_RESPONSE *session_ata_out_array[1]; session_data_array[0] = &ctx->session_data; session_ata_out_array[0] = &session_data_out; sessions_data_out.rspAuths = &session_ata_out_array[0]; sessions_data.cmdAuths = &session_data_array[0]; sessions_data_out.rspAuthsCount = 1; sessions_data.cmdAuthsCount = 1; TPM_RC rval = Tss2_Sys_EvictControl(ctx->sapi_context, ctx->auth, ctx->handle.object, &sessions_data, ctx->handle.persist,&sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("EvictControl failed, error code: 0x%x\n", rval); return false; } return true; } static bool init(int argc, char *argv[], tpm_evictcontrol_ctx *ctx) { const char *optstring = "A:H:S:P:c:X"; static struct option long_options[] = { {"auth", required_argument, NULL, 'A'}, {"handle", required_argument, NULL, 'H'}, {"persistent", required_argument, NULL, 'S'}, {"pwda", required_argument, NULL, 'P'}, {"context", required_argument, NULL, 'c'}, {"passwdInHex", no_argument, NULL, 'X'}, {NULL, no_argument, NULL, '\0'} }; struct { UINT8 A : 1; UINT8 H : 1; UINT8 S : 1; UINT8 c : 1; UINT8 P : 1; } flags = { 0 }; char contextFile[PATH_MAX]; bool is_hex_passwd = false; if (argc == 1) { showArgMismatch(argv[0]); return false; } int opt; while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) { switch (opt) { case 'A': if (!strcasecmp(optarg, "o")) { ctx->auth = TPM_RH_OWNER; } else if (!strcasecmp(optarg, "p")) { ctx->auth = TPM_RH_PLATFORM; } else { LOG_ERR("Incorrect auth value, got: \"%s\", expected [o|O|p|P!", optarg); return false; } flags.A = 1; break; case 'H': { bool result = string_bytes_get_uint32(optarg, &ctx->handle.object); if (!result) { LOG_ERR( "Could not convert object handle to a number, got: \"%s\"", optarg); return false; } flags.H = 1; } break; case 'S': { bool result = string_bytes_get_uint32(optarg, &ctx->handle.persist); if (!result) { LOG_ERR( "Could not convert persistent handle to a number, got: \"%s\"", optarg); return false; } flags.S = 1; } break; case 'P': { bool result = password_util_copy_password(optarg, "authenticating", &ctx->session_data.hmac); if (!result) { return false; } flags.P = 1; } break; case 'c': snprintf(contextFile, sizeof(contextFile), "%s", optarg); flags.c = 1; break; case 'X': is_hex_passwd = true; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } } if (!(flags.A && (flags.H || flags.c) && flags.S)) { LOG_ERR("Invalid arguments"); return false; } bool result = password_util_to_auth(&ctx->session_data.hmac, is_hex_passwd, "authenticating", &ctx->session_data.hmac); if (!result) { return false; } if (flags.c) { result = file_load_tpm_context_from_file(ctx->sapi_context, &ctx->handle.object, contextFile); if (!result) { return false; } } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { /* opts and envp are unused, avoid compiler warning */ (void) opts; (void) envp; tpm_evictcontrol_ctx ctx = { .auth = 0, .handle = { 0 }, .session_data = { 0 }, .sapi_context = sapi_context }; ctx.session_data.sessionHandle = TPM_RS_PW; bool result = init(argc, argv, &ctx); if (!result) { return 1; } /* FIXME required output for testing scripts */ printf("persistentHandle: 0x%x\n", ctx.handle.persist); return evict_control(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_getmanufec.c000066400000000000000000000526431313543155100201310ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "log.h" #include "files.h" #include "main.h" #include "options.h" #include "string-bytes.h" #include "tpm_hash.h" char outputFile[PATH_MAX]; char ownerPasswd[sizeof(TPMU_HA)]; char endorsePasswd[sizeof(TPMU_HA)]; char ekPasswd[sizeof(TPMU_HA)]; bool hexPasswd = false; TPM_HANDLE persistentHandle; UINT32 algorithmType = TPM_ALG_RSA; char ECcertFile[PATH_MAX]; char *EKserverAddr = NULL; unsigned int nonPersistentRead = 0; unsigned int SSL_NO_VERIFY = 0; unsigned int OfflineProv = 0; BYTE authPolicy[] = {0x83, 0x71, 0x97, 0x67, 0x44, 0x84, 0xB3, 0xF8, 0x1A, 0x90, 0xCC, 0x8D, 0x46, 0xA5, 0xD7, 0x24, 0xFD, 0x52, 0xD7, 0x6E, 0x06, 0x52, 0x0B, 0x64, 0xF2, 0xA1, 0xDA, 0x1B, 0x33, 0x14, 0x69, 0xAA}; int setKeyAlgorithm(UINT16 algorithm, TPM2B_PUBLIC *inPublic) { inPublic->t.publicArea.nameAlg = TPM_ALG_SHA256; // First clear attributes bit field. *(UINT32 *)&(inPublic->t.publicArea.objectAttributes) = 0; inPublic->t.publicArea.objectAttributes.restricted = 1; inPublic->t.publicArea.objectAttributes.userWithAuth = 0; inPublic->t.publicArea.objectAttributes.adminWithPolicy = 1; inPublic->t.publicArea.objectAttributes.sign = 0; inPublic->t.publicArea.objectAttributes.decrypt = 1; inPublic->t.publicArea.objectAttributes.fixedTPM = 1; inPublic->t.publicArea.objectAttributes.fixedParent = 1; inPublic->t.publicArea.objectAttributes.sensitiveDataOrigin = 1; inPublic->t.publicArea.authPolicy.t.size = 32; memcpy(inPublic->t.publicArea.authPolicy.t.buffer, authPolicy, 32); inPublic->t.publicArea.type = algorithm; switch (algorithm) { case TPM_ALG_RSA: inPublic->t.publicArea.parameters.rsaDetail.symmetric.algorithm = TPM_ALG_AES; inPublic->t.publicArea.parameters.rsaDetail.symmetric.keyBits.aes = 128; inPublic->t.publicArea.parameters.rsaDetail.symmetric.mode.aes = TPM_ALG_CFB; inPublic->t.publicArea.parameters.rsaDetail.scheme.scheme = TPM_ALG_NULL; inPublic->t.publicArea.parameters.rsaDetail.keyBits = 2048; inPublic->t.publicArea.parameters.rsaDetail.exponent = 0x0; inPublic->t.publicArea.unique.rsa.t.size = 256; break; case TPM_ALG_KEYEDHASH: inPublic->t.publicArea.parameters.keyedHashDetail.scheme.scheme = TPM_ALG_XOR; inPublic->t.publicArea.parameters.keyedHashDetail.scheme.details.exclusiveOr.hashAlg = TPM_ALG_SHA256; inPublic->t.publicArea.parameters.keyedHashDetail.scheme.details.exclusiveOr.kdf = TPM_ALG_KDF1_SP800_108; inPublic->t.publicArea.unique.keyedHash.t.size = 0; break; case TPM_ALG_ECC: inPublic->t.publicArea.parameters.eccDetail.symmetric.algorithm = TPM_ALG_AES; inPublic->t.publicArea.parameters.eccDetail.symmetric.keyBits.aes = 128; inPublic->t.publicArea.parameters.eccDetail.symmetric.mode.sym = TPM_ALG_CFB; inPublic->t.publicArea.parameters.eccDetail.scheme.scheme = TPM_ALG_NULL; inPublic->t.publicArea.parameters.eccDetail.curveID = TPM_ECC_NIST_P256; inPublic->t.publicArea.parameters.eccDetail.kdf.scheme = TPM_ALG_NULL; inPublic->t.publicArea.unique.ecc.x.t.size = 32; inPublic->t.publicArea.unique.ecc.y.t.size = 32; break; case TPM_ALG_SYMCIPHER: inPublic->t.publicArea.parameters.symDetail.sym.algorithm = TPM_ALG_AES; inPublic->t.publicArea.parameters.symDetail.sym.keyBits.aes = 128; inPublic->t.publicArea.parameters.symDetail.sym.mode.sym = TPM_ALG_CFB; inPublic->t.publicArea.unique.sym.t.size = 0; break; default: printf("\nThe algorithm type input(%4.4x) is not supported!\n", algorithm); return -1; } return 0; } int createEKHandle(TSS2_SYS_CONTEXT *sapi_context) { UINT32 rval; TPMS_AUTH_COMMAND sessionData; TPMS_AUTH_RESPONSE sessionDataOut; TSS2_SYS_CMD_AUTHS sessionsData; TSS2_SYS_RSP_AUTHS sessionsDataOut; TPMS_AUTH_COMMAND *sessionDataArray[1]; TPMS_AUTH_RESPONSE *sessionDataOutArray[1]; TPM2B_SENSITIVE_CREATE inSensitive = TPM2B_TYPE_INIT(TPM2B_SENSITIVE_CREATE, sensitive); TPM2B_PUBLIC inPublic = TPM2B_TYPE_INIT(TPM2B_PUBLIC, publicArea); TPM2B_DATA outsideInfo = { { 0, } }; TPML_PCR_SELECTION creationPCR; TPM2B_NAME name = TPM2B_TYPE_INIT(TPM2B_NAME, name); TPM2B_PUBLIC outPublic = { { 0, } }; TPM2B_CREATION_DATA creationData = { { 0, } }; TPM2B_DIGEST creationHash = TPM2B_TYPE_INIT(TPM2B_DIGEST, buffer); TPMT_TK_CREATION creationTicket = { 0, }; TPM_HANDLE handle2048ek; sessionDataArray[0] = &sessionData; sessionDataOutArray[0] = &sessionDataOut; sessionsDataOut.rspAuths = &sessionDataOutArray[0]; sessionsData.cmdAuths = &sessionDataArray[0]; sessionsDataOut.rspAuthsCount = 1; sessionsData.cmdAuthsCount = 1; sessionData.sessionHandle = TPM_RS_PW; sessionData.nonce.t.size = 0; sessionData.hmac.t.size = 0; *((UINT8 *)((void *)&sessionData.sessionAttributes)) = 0; /* * use enAuth in Tss2_Sys_CreatePrimary */ if (strlen(endorsePasswd) > 0 && !hexPasswd) { sessionData.hmac.t.size = strlen(endorsePasswd); memcpy( &sessionData.hmac.t.buffer[0], endorsePasswd, sessionData.hmac.t.size ); } else { if (strlen(endorsePasswd) > 0 && hexPasswd) { sessionData.hmac.t.size = sizeof(sessionData.hmac) - 2; if (hex2ByteStructure(endorsePasswd, &sessionData.hmac.t.size, sessionData.hmac.t.buffer) != 0) { printf( "Failed to convert Hex format password for endorsePasswd.\n"); return -1; } } } if (strlen(ekPasswd) > 0 && !hexPasswd) { inSensitive.t.sensitive.userAuth.t.size = strlen(ekPasswd); memcpy( &inSensitive.t.sensitive.userAuth.t.buffer[0], ekPasswd, inSensitive.t.sensitive.userAuth.t.size ); } else { if (strlen(ekPasswd) > 0 && hexPasswd) { inSensitive.t.sensitive.userAuth.t.size = sizeof(inSensitive.t.sensitive.userAuth) - 2; if (hex2ByteStructure(ekPasswd, &inSensitive.t.sensitive.userAuth.t.size, inSensitive.t.sensitive.userAuth.t.buffer) != 0) { printf( "Failed to convert Hex format password for ekPasswd.\n"); return -1; } } } inSensitive.t.sensitive.data.t.size = 0; inSensitive.t.size = inSensitive.t.sensitive.userAuth.b.size + 2; if (setKeyAlgorithm(algorithmType, &inPublic) ) return -1; creationPCR.count = 0; rval = Tss2_Sys_CreatePrimary(sapi_context, TPM_RH_ENDORSEMENT, &sessionsData, &inSensitive, &inPublic, &outsideInfo, &creationPCR, &handle2048ek, &outPublic, &creationData, &creationHash, &creationTicket, &name, &sessionsDataOut); if (rval != TPM_RC_SUCCESS ) { printf("\nTPM2_CreatePrimary Error. TPM Error:0x%x\n", rval); return -2; } printf("\nEK create succ.. Handle: 0x%8.8x\n", handle2048ek); if (!nonPersistentRead) { /* * To make EK persistent, use own auth */ sessionData.hmac.t.size = 0; if (strlen(ownerPasswd) > 0 && !hexPasswd) { sessionData.hmac.t.size = strlen(ownerPasswd); memcpy( &sessionData.hmac.t.buffer[0], ownerPasswd, sessionData.hmac.t.size ); } else { if (strlen(ownerPasswd) > 0 && hexPasswd) { sessionData.hmac.t.size = sizeof(sessionData.hmac) - 2; if (hex2ByteStructure(ownerPasswd, &sessionData.hmac.t.size, sessionData.hmac.t.buffer) != 0) { printf( "Failed to convert Hex format password for ownerPasswd.\n"); return -1; } } } rval = Tss2_Sys_EvictControl(sapi_context, TPM_RH_OWNER, handle2048ek, &sessionsData, persistentHandle, &sessionsDataOut); if (rval != TPM_RC_SUCCESS ) { printf("\nEvictControl:Make EK persistent Error. TPM Error:0x%x\n", rval); return -3; } printf("EvictControl EK persistent succ.\n"); } rval = Tss2_Sys_FlushContext(sapi_context, handle2048ek); if (rval != TPM_RC_SUCCESS ) { printf("\nFlush transient EK failed. TPM Error:0x%x\n", rval); return -4; } printf("Flush transient EK succ.\n"); /* TODO this serialization is not correct */ if (!files_save_bytes_to_file(outputFile, (UINT8 *)&outPublic, sizeof(outPublic))) { printf("\nFailed to save EK pub key into file(%s)\n", outputFile); return -5; } return 0; } unsigned char *HashEKPublicKey(void) { unsigned char *hash = NULL; FILE *fp = NULL; unsigned char EKpubKey[259]; printf("Calculating the SHA256 hash of the Endorsement Public Key\n"); fp = fopen(outputFile, "rb"); if (!fp) { LOG_ERR("Could not open file: \"%s\"", outputFile); return NULL; } int rc = fseek(fp, 0x66, 0); if (rc < 0) { LOG_ERR("Could not perform fseek: %s\n", strerror(errno)); goto out; } size_t read = fread(EKpubKey, 1, 256, fp); if (read != 256) { LOG_ERR ("Could not read whole file."); goto out; } hash = (unsigned char*)malloc(SHA256_DIGEST_LENGTH); if (hash == NULL) { LOG_ERR ("OOM"); goto out; } EKpubKey[256] = 0x01; EKpubKey[257] = 0x00; EKpubKey[258] = 0x01; //Exponent SHA256_CTX sha256; int is_success = SHA256_Init(&sha256); if (!is_success) { LOG_ERR ("SHA256_Init failed"); goto hash_out; } is_success = SHA256_Update(&sha256, EKpubKey, sizeof(EKpubKey)); if (!is_success) { LOG_ERR ("SHA256_Update failed"); goto hash_out; } is_success = SHA256_Final(hash, &sha256); if (!is_success) { LOG_ERR ("SHA256_Final failed"); goto hash_out; } unsigned i; for (i = 0; i < SHA256_DIGEST_LENGTH; i++) { printf("%02X", hash[i]); } printf("\n"); goto out; hash_out: free(hash); hash = NULL; out: fclose(fp); return hash; } char *Base64Encode(const unsigned char* buffer) { BIO *bio, *b64; BUF_MEM *bufferPtr; printf("Calculating the Base64Encode of the hash of the Endorsement Public Key:\n"); if (buffer == NULL) { LOG_ERR("HashEKPublicKey returned null"); return NULL; } b64 = BIO_new(BIO_f_base64()); bio = BIO_new(BIO_s_mem()); bio = BIO_push(b64, bio); BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); BIO_write(bio, buffer, SHA256_DIGEST_LENGTH); BIO_flush(bio); BIO_get_mem_ptr(bio, &bufferPtr); BIO_set_close(bio, BIO_NOCLOSE); /* these are not NULL terminated */ char *b64text = bufferPtr->data; size_t len = bufferPtr->length; size_t i; for (i = 0; i < len; i++) { if (b64text[i] == '+') { b64text[i] = '-'; } if (b64text[i] == '/') { b64text[i] = '_'; } } char *final_string = NULL; CURL *curl = curl_easy_init(); if (curl) { char *output = curl_easy_escape(curl, b64text, len); if (output) { final_string = strdup(output); curl_free(output); } } curl_easy_cleanup(curl); curl_global_cleanup(); BIO_free_all(bio); /* format to a proper NULL terminated string */ return final_string; } int RetrieveEndorsementCredentials(char *b64h) { int ret = -1; size_t len = 1 + strlen(b64h) + strlen(EKserverAddr); char *weblink = (char *)malloc(len); if (!weblink) { LOG_ERR("Could not open file for writing: \"%s\"", ECcertFile); return ret; } snprintf(weblink, len, "%s%s", EKserverAddr, b64h); FILE * respfile = fopen(ECcertFile, "wb"); if (!respfile) { LOG_ERR("Could not open file for writing: \"%s\"", ECcertFile); goto out_memory; } CURLcode rc = curl_global_init(CURL_GLOBAL_DEFAULT); if (rc != CURLE_OK) { LOG_ERR("curl_global_init failed: %s", curl_easy_strerror(rc)); goto out_file_close; } CURL *curl = curl_easy_init(); if (!curl) { LOG_ERR("curl_easy_init failed"); goto out_global_cleanup; } /* * should not be used - Used only on platforms with older CA certificates. */ if (SSL_NO_VERIFY) { rc = curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); if (rc != CURLE_OK) { LOG_ERR("curl_easy_setopt for CURLOPT_SSL_VERIFYPEER failed: %s", curl_easy_strerror(rc)); goto out_easy_cleanup; } } rc = curl_easy_setopt(curl, CURLOPT_URL, weblink); if (rc != CURLE_OK) { LOG_ERR("curl_easy_setopt for CURLOPT_URL failed: %s", curl_easy_strerror(rc)); goto out_easy_cleanup; } rc = curl_easy_setopt(curl, CURLOPT_VERBOSE, respfile); if (rc != CURLE_OK) { LOG_ERR("curl_easy_setopt for CURLOPT_VERBOSE failed: %s", curl_easy_strerror(rc)); goto out_easy_cleanup; } rc = curl_easy_setopt(curl, CURLOPT_WRITEDATA, respfile); if (rc != CURLE_OK) { LOG_ERR("curl_easy_setopt for CURLOPT_WRITEDATA failed: %s", curl_easy_strerror(rc)); goto out_easy_cleanup; } rc = curl_easy_perform(curl); if (rc != CURLE_OK) { LOG_ERR("curl_easy_perform() failed: %s\n", curl_easy_strerror(rc)); goto out_easy_cleanup; } ret = 0; out_easy_cleanup: curl_easy_cleanup(curl); out_global_cleanup: curl_global_cleanup(); out_file_close: fclose(respfile); out_memory: free(weblink); return ret; } int TPMinitialProvisioning(void) { if (EKserverAddr == NULL) { printf("TPM Manufacturer Endorsement Credential Server Address cannot be NULL\n"); return -99; } char *b64 = Base64Encode(HashEKPublicKey()); if (!b64) { LOG_ERR("Base64Encode returned null"); return -1; } printf("%s\n", b64); int rc = RetrieveEndorsementCredentials(b64); free(b64); return rc; } int execute_tool (int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void) opts; (void) envp; int return_val = 1; static const char *optstring = "e:o:H:P:g:f:X:N:O:E:S:U"; static struct option long_options[] = { { "endorsePasswd", 1, NULL, 'e' }, { "ownerPasswd" , 1, NULL, 'o' }, { "handle" , 1, NULL, 'H' }, { "ekPasswd" , 1, NULL, 'P' }, { "alg" , 1, NULL, 'g' }, { "file" , 1, NULL, 'f' }, { "passwdInHex" , 0, NULL, 'X' }, { "NonPersistent", 0, NULL, 'N' }, { "OfflineProv" , 0, NULL, 'O' }, { "ECcertFile" , 1, NULL, 'E' }, { "EKserverAddr" , 1, NULL, 'S' }, { "SSL_NO_VERIFY", 0, NULL, 'U' }, { NULL , 0, NULL, 0 }, }; if (argc > (int)(2 * sizeof(long_options) / sizeof(struct option)) ) { showArgMismatch(argv[0]); return -1; } int opt; while ( ( opt = getopt_long( argc, argv, optstring, long_options, NULL ) ) != -1 ) { switch ( opt ) { case 'H': if (!string_bytes_get_uint32(optarg, &persistentHandle)) { printf("\nPlease input the handle used to make EK persistent(hex) in correct format.\n"); goto out; } break; case 'e': if (optarg == NULL || (strlen(optarg) >= sizeof(TPMU_HA)) ) { printf("\nPlease input the endorsement password(optional,no more than %d characters).\n", (int)sizeof(TPMU_HA) - 1); goto out; } snprintf(endorsePasswd, sizeof(endorsePasswd), "%s", optarg); break; case 'o': if (optarg == NULL || (strlen(optarg) >= sizeof(TPMU_HA)) ) { printf("\nPlease input the owner password(optional,no more than %d characters).\n", (int)sizeof(TPMU_HA) - 1); goto out; } snprintf(ownerPasswd, sizeof(ownerPasswd), "%s", optarg); break; case 'P': if (optarg == NULL || (strlen(optarg) >= sizeof(TPMU_HA)) ) { printf("\nPlease input the EK password(optional,no more than %d characters).\n", (int)sizeof(TPMU_HA) - 1); goto out; } snprintf(ekPasswd, sizeof(ekPasswd), "%s", optarg); break; case 'g': if (!string_bytes_get_uint32(optarg, &algorithmType)) { printf("\nPlease input the algorithm type in correct format.\n"); goto out; } break; case 'f': if (optarg == NULL ) { printf("\nPlease input the file used to save the pub ek.\n"); goto out; } snprintf(outputFile, sizeof(outputFile), "%s", optarg); break; case 'X': hexPasswd = true; break; case 'E': if (optarg == NULL ) { printf("\nPlease input the file used to save the EC Certificate retrieved from server\n"); goto out; } snprintf(ECcertFile, sizeof(ECcertFile), "%s", optarg); break; case 'N': nonPersistentRead = 1; printf("Tss2_Sys_CreatePrimary called with Endorsement Handle without making it persistent\n"); break; case 'O': OfflineProv = 1; printf("Setting up for offline provisioning - reading the retrieved EK specified by the file \n"); break; case 'U': SSL_NO_VERIFY = 1; printf("CAUTION: TLS communication with the said TPM manufacturer server setup with SSL_NO_VERIFY!\n"); break; case 'S': if (EKserverAddr) { printf("Multiple specifications of -S\n"); goto out; } EKserverAddr = strdup(optarg); if (EKserverAddr == NULL) { LOG_ERR ("Memory allocation failed."); goto out; } printf("TPM Manufacturer EK provisioning address -- %s\n", EKserverAddr); break; } } int provisioning_return_val = 0; if (argc < 2) { showArgMismatch(argv[0]); return -1; } else { if (!OfflineProv) { return_val = createEKHandle(sapi_context); } provisioning_return_val = TPMinitialProvisioning(); } if (return_val && provisioning_return_val) { goto out; } return_val = 0; out: free(EKserverAddr); return return_val; } tpm2-tools-2.1.0/tools/tpm2_getpubak.c000066400000000000000000000452751313543155100176200ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include #include "files.h" #include "log.h" #include "main.h" #include "options.h" #include "password_util.h" #include "string-bytes.h" #include "tpm_session.h" typedef struct getpubak_context getpubak_context; struct getpubak_context { struct { TPM_HANDLE ek; TPM_HANDLE ak; } persistent_handle; struct { TPM2B_AUTH endorse; TPM2B_AUTH ak; TPM2B_AUTH owner; } passwords; bool hexPasswd; char outputFile[PATH_MAX]; char aknameFile[PATH_MAX]; UINT32 algorithmType; UINT32 digestAlg; UINT32 signAlg; TSS2_SYS_CONTEXT *sapi_context; }; /* * TODO: All these set_xxx_signing_algorithm() routines could likely somehow be refactored into one. */ static bool set_rsa_signing_algorithm(UINT32 sign_alg, UINT32 digest_alg, TPM2B_PUBLIC *in_public) { if (sign_alg == TPM_ALG_NULL) { sign_alg = TPM_ALG_RSASSA; } in_public->t.publicArea.parameters.rsaDetail.scheme.scheme = sign_alg; switch (sign_alg) { case TPM_ALG_RSASSA : case TPM_ALG_RSAPSS : in_public->t.publicArea.parameters.rsaDetail.scheme.details.anySig.hashAlg = digest_alg; break; default: LOG_ERR("The RSA signing algorithm type input(%4.4x) is not supported!", sign_alg); return false; } return true; } static bool set_ecc_signing_algorithm(UINT32 sign_alg, UINT32 digest_alg, TPM2B_PUBLIC *in_public) { if (sign_alg == TPM_ALG_NULL) { sign_alg = TPM_ALG_ECDSA; } in_public->t.publicArea.parameters.eccDetail.scheme.scheme = sign_alg; switch (sign_alg) { case TPM_ALG_ECDSA : case TPM_ALG_SM2 : case TPM_ALG_ECSCHNORR : case TPM_ALG_ECDAA : in_public->t.publicArea.parameters.eccDetail.scheme.details.anySig.hashAlg = digest_alg; break; default: LOG_ERR("The ECC signing algorithm type input(%4.4x) is not supported!", sign_alg); return false; } return true; } static bool set_keyed_hash_signing_algorithm(UINT32 sign_alg, UINT32 digest_alg, TPM2B_PUBLIC *in_public) { if (sign_alg == TPM_ALG_NULL) { sign_alg = TPM_ALG_HMAC; } in_public->t.publicArea.parameters.keyedHashDetail.scheme.scheme = sign_alg; switch (sign_alg) { case TPM_ALG_HMAC : in_public->t.publicArea.parameters.keyedHashDetail.scheme.details.hmac.hashAlg = digest_alg; break; default: LOG_ERR( "The Keyedhash signing algorithm type input(%4.4x) is not supported!", sign_alg); return false; } return true; } static bool set_key_algorithm(getpubak_context *ctx, TPM2B_PUBLIC *in_public) { in_public->t.publicArea.nameAlg = TPM_ALG_SHA256; // First clear attributes bit field. *(UINT32 *)&(in_public->t.publicArea.objectAttributes) = 0; in_public->t.publicArea.objectAttributes.restricted = 1; in_public->t.publicArea.objectAttributes.userWithAuth = 1; in_public->t.publicArea.objectAttributes.sign = 1; in_public->t.publicArea.objectAttributes.decrypt = 0; in_public->t.publicArea.objectAttributes.fixedTPM = 1; in_public->t.publicArea.objectAttributes.fixedParent = 1; in_public->t.publicArea.objectAttributes.sensitiveDataOrigin = 1; in_public->t.publicArea.authPolicy.t.size = 0; in_public->t.publicArea.type = ctx->algorithmType; switch(ctx->algorithmType) { case TPM_ALG_RSA: in_public->t.publicArea.parameters.rsaDetail.symmetric.algorithm = TPM_ALG_NULL; in_public->t.publicArea.parameters.rsaDetail.symmetric.keyBits.aes = 0; in_public->t.publicArea.parameters.rsaDetail.symmetric.mode.aes = TPM_ALG_NULL; in_public->t.publicArea.parameters.rsaDetail.keyBits = 2048; in_public->t.publicArea.parameters.rsaDetail.exponent = 0; in_public->t.publicArea.unique.rsa.t.size = 0; return set_rsa_signing_algorithm(ctx->signAlg, ctx->digestAlg, in_public); case TPM_ALG_ECC: in_public->t.publicArea.parameters.eccDetail.symmetric.algorithm = TPM_ALG_NULL; in_public->t.publicArea.parameters.eccDetail.symmetric.mode.sym = TPM_ALG_NULL; in_public->t.publicArea.parameters.eccDetail.symmetric.keyBits.sym = 0; in_public->t.publicArea.parameters.eccDetail.curveID = TPM_ECC_NIST_P256; in_public->t.publicArea.parameters.eccDetail.kdf.scheme = TPM_ALG_NULL; in_public->t.publicArea.unique.ecc.x.t.size = 0; in_public->t.publicArea.unique.ecc.y.t.size = 0; return set_ecc_signing_algorithm(ctx->signAlg, ctx->digestAlg, in_public); case TPM_ALG_KEYEDHASH: in_public->t.publicArea.unique.keyedHash.t.size = 0; return set_keyed_hash_signing_algorithm(ctx->signAlg, ctx->digestAlg, in_public); case TPM_ALG_SYMCIPHER: default: LOG_ERR("The algorithm type input(%4.4x) is not supported!", ctx->algorithmType); return false; } return true; } static bool create_ak(getpubak_context *ctx) { TPML_PCR_SELECTION creation_pcr; TPMS_AUTH_COMMAND session_data; TPMS_AUTH_RESPONSE session_data_out; TSS2_SYS_CMD_AUTHS sessions_data; TSS2_SYS_RSP_AUTHS sessions_data_out; TPMS_AUTH_COMMAND *session_data_array[1]; TPMS_AUTH_RESPONSE *session_data_out_array[1]; TPM2B_DATA outsideInfo = { { 0, } }; TPM2B_PUBLIC out_public = {{ 0, } }; TPM2B_NONCE nonce_caller = { { 0, } }; TPMT_TK_CREATION creation_ticket = { 0, }; TPM2B_CREATION_DATA creation_data = { { 0, } }; TPM2B_ENCRYPTED_SECRET encrypted_salt = { { 0, } }; TPMT_SYM_DEF symmetric = { .algorithm = TPM_ALG_NULL, }; TPM2B_SENSITIVE_CREATE inSensitive = TPM2B_TYPE_INIT(TPM2B_SENSITIVE_CREATE, sensitive); TPM2B_PUBLIC inPublic = TPM2B_TYPE_INIT(TPM2B_PUBLIC, publicArea); TPM2B_NAME name = TPM2B_TYPE_INIT(TPM2B_NAME, name); TPM2B_PRIVATE out_private = TPM2B_TYPE_INIT(TPM2B_PRIVATE, buffer); TPM2B_DIGEST creation_hash = TPM2B_TYPE_INIT(TPM2B_DIGEST, buffer); TPM_HANDLE handle_2048_rsa = ctx->persistent_handle.ek; session_data_array[0] = &session_data; session_data_out_array[0] = &session_data_out; sessions_data_out.rspAuths = &session_data_out_array[0]; sessions_data.cmdAuths = &session_data_array[0]; session_data.sessionHandle = TPM_RS_PW; session_data.nonce.t.size = 0; session_data.hmac.t.size = 0; *((UINT8 *) ((void *) &session_data.sessionAttributes)) = 0; sessions_data.cmdAuthsCount = 1; sessions_data_out.rspAuthsCount = 1; inSensitive.t.sensitive.data.t.size = 0; inSensitive.t.size = inSensitive.t.sensitive.userAuth.b.size + 2; creation_pcr.count = 0; bool result = password_util_to_auth(&ctx->passwords.ak, ctx->hexPasswd, "AK", &inSensitive.t.sensitive.userAuth); if (!result) { return false; } result = set_key_algorithm(ctx, &inPublic); if (!result) { return false; } result = password_util_to_auth(&ctx->passwords.endorse, ctx->hexPasswd, "endorse", &session_data.hmac); if (!result) { return false; } SESSION *session = NULL; UINT32 rval = tpm_session_start_auth_with_params(ctx->sapi_context, &session, TPM_RH_NULL, 0, TPM_RH_NULL, 0, &nonce_caller, &encrypted_salt, TPM_SE_POLICY, &symmetric, TPM_ALG_SHA256); if (rval != TPM_RC_SUCCESS) { LOG_ERR("tpm_session_start_auth_with_params Error. TPM Error:0x%x", rval); return false; } LOG_INFO("tpm_session_start_auth_with_params succ"); rval = Tss2_Sys_PolicySecret(ctx->sapi_context, TPM_RH_ENDORSEMENT, session->sessionHandle, &sessions_data, 0, 0, 0, 0, 0, 0, 0); if (rval != TPM_RC_SUCCESS) { LOG_ERR("Tss2_Sys_PolicySecret Error. TPM Error:0x%x", rval); return false; } LOG_INFO("Tss2_Sys_PolicySecret succ"); session_data.sessionHandle = session->sessionHandle; session_data.sessionAttributes.continueSession = 1; session_data.hmac.t.size = 0; rval = Tss2_Sys_Create(ctx->sapi_context, handle_2048_rsa, &sessions_data, &inSensitive, &inPublic, &outsideInfo, &creation_pcr, &out_private, &out_public, &creation_data, &creation_hash, &creation_ticket, &sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("TPM2_Create Error. TPM Error:0x%x", rval); return false; } LOG_INFO("TPM2_Create succ"); // Need to flush the session here. rval = Tss2_Sys_FlushContext(ctx->sapi_context, session->sessionHandle); if (rval != TPM_RC_SUCCESS) { LOG_INFO("TPM2_Sys_FlushContext Error. TPM Error:0x%x", rval); return false; } // And remove the session from sessions table. rval = tpm_session_auth_end(session); if (rval != TPM_RC_SUCCESS) { LOG_ERR("tpm_session_auth_end Error. TPM Error:0x%x", rval); return false; } session_data.sessionHandle = TPM_RS_PW; session_data.sessionAttributes.continueSession = 0; session_data.hmac.t.size = 0; result = password_util_to_auth(&ctx->passwords.endorse, ctx->hexPasswd, "endorse", &session_data.hmac); if (!result) { return false; } rval = tpm_session_start_auth_with_params(ctx->sapi_context, &session, TPM_RH_NULL, 0, TPM_RH_NULL, 0, &nonce_caller, &encrypted_salt, TPM_SE_POLICY, &symmetric, TPM_ALG_SHA256); if (rval != TPM_RC_SUCCESS) { LOG_ERR("tpm_session_start_auth_with_params Error. TPM Error:0x%x", rval); return false; } LOG_INFO("tpm_session_start_auth_with_params succ"); rval = Tss2_Sys_PolicySecret(ctx->sapi_context, TPM_RH_ENDORSEMENT, session->sessionHandle, &sessions_data, 0, 0, 0, 0, 0, 0, 0); if (rval != TPM_RC_SUCCESS) { LOG_ERR("Tss2_Sys_PolicySecret Error. TPM Error:0x%x", rval); return false; } LOG_INFO("Tss2_Sys_PolicySecret succ"); session_data.sessionHandle = session->sessionHandle; session_data.sessionAttributes.continueSession = 1; session_data.hmac.t.size = 0; TPM_HANDLE loaded_sha1_key_handle; rval = Tss2_Sys_Load(ctx->sapi_context, handle_2048_rsa, &sessions_data, &out_private, &out_public, &loaded_sha1_key_handle, &name, &sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("TPM2_Load Error. TPM Error:0x%x", rval); return false; } /* required output of testing scripts */ printf("Name of loaded key: "); string_bytes_print_tpm2b(&name.b); printf("\n"); printf("Loaded key handle: %8.8x\n", loaded_sha1_key_handle); // write name to ak.name file result = files_save_bytes_to_file(ctx->aknameFile, &name.t.name[0], name.t.size); if (!result) { LOG_ERR("Failed to save AK name into file \"%s\"", ctx->aknameFile); return false; } // Need to flush the session here. rval = Tss2_Sys_FlushContext(ctx->sapi_context, session->sessionHandle); if (rval != TPM_RC_SUCCESS) { LOG_ERR("TPM2_Sys_FlushContext Error. TPM Error:0x%x", rval); return false; } // And remove the session from sessions table. rval = tpm_session_auth_end(session); if (rval != TPM_RC_SUCCESS) { LOG_ERR("tpm_session_auth_end Error. TPM Error:0x%x", rval); return false; } session_data.sessionHandle = TPM_RS_PW; session_data.sessionAttributes.continueSession = 0; session_data.hmac.t.size = 0; // use the owner auth here. result = password_util_to_auth(&ctx->passwords.owner, ctx->hexPasswd, "owner", &session_data.hmac); if (!result) { return false; } rval = Tss2_Sys_EvictControl(ctx->sapi_context, TPM_RH_OWNER, loaded_sha1_key_handle, &sessions_data, ctx->persistent_handle.ak, &sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("\n......TPM2_EvictControl Error. TPM Error:0x%x......\n", rval); return false; } LOG_INFO("EvictControl: Make AK persistent succ."); rval = Tss2_Sys_FlushContext(ctx->sapi_context, loaded_sha1_key_handle); if (rval != TPM_RC_SUCCESS) { LOG_ERR("Flush transient AK error. TPM Error:0x%x", rval); return false; } LOG_INFO("Flush transient AK succ."); /* TODO fix this serialization */ result = files_save_bytes_to_file(ctx->outputFile, (UINT8 *) &out_public, sizeof(out_public)); if (!result) { LOG_ERR("Failed to save AK pub key into file \"%s\"", ctx->outputFile); return false; } return true; } static bool init(int argc, char *argv[], getpubak_context *ctx) { struct option opts[] = { { "ownerPasswd", required_argument, NULL, 'o' }, { "endorsePasswd", required_argument, NULL, 'e' }, { "ekHandle" , required_argument, NULL, 'E' }, { "akHandle" , required_argument, NULL, 'k' }, { "alg" , required_argument, NULL, 'g' }, { "digestAlg" , required_argument, NULL, 'D' }, { "signAlg" , required_argument, NULL, 's' }, { "akPasswd" , required_argument, NULL, 'P' }, { "file" , required_argument, NULL, 'f' }, { "akName" , required_argument, NULL, 'n' }, { "passwdInHex", no_argument, NULL, 'X' }, { NULL , no_argument, NULL, 0 }, }; if (argc == 1 || argc > (int) (2 * sizeof(opts) / sizeof(opts[0]))) { showArgMismatch(argv[0]); return false; } int opt; bool result; while ((opt = getopt_long(argc, argv, "o:E:e:k:g:D:s:P:f:n:Xp:", opts, NULL)) != -1) { switch (opt) { case 'E': result = string_bytes_get_uint32(optarg, &ctx->persistent_handle.ek); if (!result) { LOG_ERR("Could not convert persistent EK handle."); return false; } break; case 'k': result = string_bytes_get_uint32(optarg, &ctx->persistent_handle.ak); if (!result) { LOG_ERR("Could not convert persistent AK handle."); return false; } break; case 'g': result = string_bytes_get_uint32(optarg, &ctx->algorithmType); if (!result) { LOG_ERR("Could not convert algorithm."); return false; } break; case 'D': result = string_bytes_get_uint32(optarg, &ctx->digestAlg); if (!result) { LOG_ERR("Could not convert digest algorithm."); return false; } break; case 's': result = string_bytes_get_uint32(optarg, &ctx->signAlg); if (!result) { LOG_ERR("Could not convert signing algorithm."); return false; } break; case 'o': result = password_util_copy_password(optarg, "owner", &ctx->passwords.owner); if (!result) { return false; } break; case 'e': result = password_util_copy_password(optarg, "endorse", &ctx->passwords.endorse); if (!result) { return false; } break; case 'P': result = password_util_copy_password(optarg, "AK", &ctx->passwords.ak); if (!result) { return false; } break; case 'f': if (!optarg) { LOG_ERR( "Please specify the output file used to save the pub ek."); return false; } snprintf(ctx->outputFile, sizeof(ctx->outputFile), "%s", optarg); break; case 'n': if (!optarg) { LOG_ERR( "Please specify the output file used to save the ak name."); return false; } snprintf(ctx->aknameFile, sizeof(ctx->aknameFile), "%s", optarg); break; case 'X': ctx->hexPasswd = true; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { /* opts is unused, avoid compiler warning */ (void)opts; (void)envp; getpubak_context ctx = { .hexPasswd = false, .algorithmType = TPM_ALG_RSA, .digestAlg = TPM_ALG_SHA256, .signAlg = TPM_ALG_NULL, .sapi_context = sapi_context }; bool result = init(argc, argv, &ctx); if (!result) { return 1; } return !create_ak(&ctx); } tpm2-tools-2.1.0/tools/tpm2_getpubek.c000066400000000000000000000311711313543155100176120ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include "files.h" #include "log.h" #include "main.h" #include "password_util.h" #include "string-bytes.h" typedef struct getpubek_context getpubek_context; struct getpubek_context { struct { bool is_hex; TPM2B_AUTH owner; TPM2B_AUTH endorse; TPM2B_AUTH ek; } passwords; char out_file_path[PATH_MAX]; TPM_HANDLE persistent_handle; UINT32 algorithm; TSS2_SYS_CONTEXT *sapi_context; }; static bool set_key_algorithm(UINT16 algorithm, TPM2B_PUBLIC *inPublic) { static BYTE auth_policy[] = { 0x83, 0x71, 0x97, 0x67, 0x44, 0x84, 0xB3, 0xF8, 0x1A, 0x90, 0xCC, 0x8D, 0x46, 0xA5, 0xD7, 0x24, 0xFD, 0x52, 0xD7, 0x6E, 0x06, 0x52, 0x0B, 0x64, 0xF2, 0xA1, 0xDA, 0x1B, 0x33, 0x14, 0x69, 0xAA }; inPublic->t.publicArea.nameAlg = TPM_ALG_SHA256; // First clear attributes bit field. *(UINT32 *) &(inPublic->t.publicArea.objectAttributes) = 0; inPublic->t.publicArea.objectAttributes.restricted = 1; inPublic->t.publicArea.objectAttributes.userWithAuth = 0; inPublic->t.publicArea.objectAttributes.adminWithPolicy = 1; inPublic->t.publicArea.objectAttributes.sign = 0; inPublic->t.publicArea.objectAttributes.decrypt = 1; inPublic->t.publicArea.objectAttributes.fixedTPM = 1; inPublic->t.publicArea.objectAttributes.fixedParent = 1; inPublic->t.publicArea.objectAttributes.sensitiveDataOrigin = 1; inPublic->t.publicArea.authPolicy.t.size = 32; memcpy(inPublic->t.publicArea.authPolicy.t.buffer, auth_policy, 32); inPublic->t.publicArea.type = algorithm; switch (algorithm) { case TPM_ALG_RSA : inPublic->t.publicArea.parameters.rsaDetail.symmetric.algorithm = TPM_ALG_AES; inPublic->t.publicArea.parameters.rsaDetail.symmetric.keyBits.aes = 128; inPublic->t.publicArea.parameters.rsaDetail.symmetric.mode.aes = TPM_ALG_CFB; inPublic->t.publicArea.parameters.rsaDetail.scheme.scheme = TPM_ALG_NULL; inPublic->t.publicArea.parameters.rsaDetail.keyBits = 2048; inPublic->t.publicArea.parameters.rsaDetail.exponent = 0; inPublic->t.publicArea.unique.rsa.t.size = 256; break; case TPM_ALG_KEYEDHASH : inPublic->t.publicArea.parameters.keyedHashDetail.scheme.scheme = TPM_ALG_XOR; inPublic->t.publicArea.parameters.keyedHashDetail.scheme.details.exclusiveOr.hashAlg = TPM_ALG_SHA256; inPublic->t.publicArea.parameters.keyedHashDetail.scheme.details.exclusiveOr.kdf = TPM_ALG_KDF1_SP800_108; inPublic->t.publicArea.unique.keyedHash.t.size = 0; break; case TPM_ALG_ECC : inPublic->t.publicArea.parameters.eccDetail.symmetric.algorithm = TPM_ALG_AES; inPublic->t.publicArea.parameters.eccDetail.symmetric.keyBits.aes = 128; inPublic->t.publicArea.parameters.eccDetail.symmetric.mode.sym = TPM_ALG_CFB; inPublic->t.publicArea.parameters.eccDetail.scheme.scheme = TPM_ALG_NULL; inPublic->t.publicArea.parameters.eccDetail.curveID = TPM_ECC_NIST_P256; inPublic->t.publicArea.parameters.eccDetail.kdf.scheme = TPM_ALG_NULL; inPublic->t.publicArea.unique.ecc.x.t.size = 32; inPublic->t.publicArea.unique.ecc.y.t.size = 32; break; case TPM_ALG_SYMCIPHER : inPublic->t.publicArea.parameters.symDetail.sym.algorithm = TPM_ALG_AES; inPublic->t.publicArea.parameters.symDetail.sym.keyBits.aes = 128; inPublic->t.publicArea.parameters.symDetail.sym.mode.sym = TPM_ALG_CFB; inPublic->t.publicArea.unique.sym.t.size = 0; break; default: LOG_ERR("The algorithm type input(%4.4x) is not supported!", algorithm); return false; } return true; } static bool create_ek_handle(getpubek_context *ctx) { TPMS_AUTH_COMMAND sessionData; TPMS_AUTH_RESPONSE sessionDataOut; TSS2_SYS_CMD_AUTHS sessionsData; TSS2_SYS_RSP_AUTHS sessionsDataOut; TPMS_AUTH_COMMAND *sessionDataArray[1]; TPMS_AUTH_RESPONSE *sessionDataOutArray[1]; TPML_PCR_SELECTION creationPCR; TPM2B_SENSITIVE_CREATE inSensitive = TPM2B_TYPE_INIT(TPM2B_SENSITIVE_CREATE, sensitive); TPM2B_PUBLIC inPublic = TPM2B_TYPE_INIT(TPM2B_PUBLIC, publicArea); TPM2B_DATA outsideInfo = { { 0, } }; TPM2B_NAME name = TPM2B_TYPE_INIT(TPM2B_NAME, name); TPM2B_PUBLIC outPublic = { { 0, } }; TPM2B_CREATION_DATA creationData = { { 0, } }; TPM2B_DIGEST creationHash = TPM2B_TYPE_INIT(TPM2B_DIGEST, buffer); TPMT_TK_CREATION creationTicket = { 0, }; sessionDataArray[0] = &sessionData; sessionDataOutArray[0] = &sessionDataOut; sessionsDataOut.rspAuths = &sessionDataOutArray[0]; sessionsData.cmdAuths = &sessionDataArray[0]; sessionsDataOut.rspAuthsCount = 1; sessionsData.cmdAuthsCount = 1; sessionData.sessionHandle = TPM_RS_PW; sessionData.nonce.t.size = 0; sessionData.hmac.t.size = 0; *((UINT8 *) ((void *) &sessionData.sessionAttributes)) = 0; bool result = password_util_to_auth(&ctx->passwords.endorse, ctx->passwords.is_hex, "endorse", &sessionData.hmac); if (!result) { return false; } result = password_util_to_auth(&ctx->passwords.ek, ctx->passwords.is_hex, "ek", &inSensitive.t.sensitive.userAuth); if (!result) { return false; } inSensitive.t.sensitive.data.t.size = 0; inSensitive.t.size = inSensitive.t.sensitive.userAuth.b.size + 2; result = set_key_algorithm(ctx->algorithm, &inPublic); if (!result) { return false; } creationPCR.count = 0; /* Create EK and get a handle to the key */ TPM_HANDLE handle2048ek; UINT32 rval = Tss2_Sys_CreatePrimary(ctx->sapi_context, TPM_RH_ENDORSEMENT, &sessionsData, &inSensitive, &inPublic, &outsideInfo, &creationPCR, &handle2048ek, &outPublic, &creationData, &creationHash, &creationTicket, &name, &sessionsDataOut); if (rval != TPM_RC_SUCCESS) { LOG_ERR("TPM2_CreatePrimary Error. TPM Error:0x%x", rval); return false; } LOG_INFO("EK create success. Got handle: 0x%8.8x", handle2048ek); // To make EK persistent, use own auth sessionData.hmac.t.size = 0; result = password_util_to_auth(&ctx->passwords.owner, ctx->passwords.is_hex, "owner", &sessionData.hmac); if (!result) { return false; } rval = Tss2_Sys_EvictControl(ctx->sapi_context, TPM_RH_OWNER, handle2048ek, &sessionsData, ctx->persistent_handle, &sessionsDataOut); if (rval != TPM_RC_SUCCESS) { LOG_ERR("EvictControl failed. Could not make EK persistent." "TPM Error:0x%x", rval); return false; } LOG_INFO("EvictControl EK persistent success."); rval = Tss2_Sys_FlushContext(ctx->sapi_context, handle2048ek); if (rval != TPM_RC_SUCCESS) { LOG_ERR("Flush transient EK failed. TPM Error:0x%x", rval); return false; } LOG_INFO("Flush transient EK success."); /* TODO fix this serialization */ if (!files_save_bytes_to_file(ctx->out_file_path, (UINT8 *) &outPublic, sizeof(outPublic))) { LOG_ERR("Failed to save EK pub key into file \"%s\"", ctx->out_file_path); return false; } return true; } static bool init(int argc, char *argv[], char *envp[], getpubek_context *ctx) { struct option options[] = { { "endorsePasswd", required_argument, NULL, 'e' }, { "ownerPasswd" , required_argument, NULL, 'o' }, { "handle" , required_argument, NULL, 'H' }, { "ekPasswd" , required_argument, NULL, 'P' }, { "alg" , required_argument, NULL, 'g' }, { "file" , required_argument, NULL, 'f' }, { "passwdInHex" , no_argument, NULL, 'X' }, { "dbg" , required_argument, NULL, 'd' }, { "help" , no_argument, NULL, 'h' }, { NULL , no_argument, NULL, '\0' }, }; if (argc == 1) { execute_man(argv[0], envp); return 1; } if (argc > (int) (2 * sizeof(options) / sizeof(struct option))) { showArgMismatch(argv[0]); return -1; } int opt; while ((opt = getopt_long(argc, argv, "e:o:H:P:g:f:Xp:d:hv", options, NULL)) != -1) { bool result; switch (opt) { case 'H': result = string_bytes_get_uint32(optarg, &ctx->persistent_handle); if (!result) { LOG_ERR("Could not convert EK persistent from hex format.\n"); return false; } break; case 'e': result = password_util_copy_password(optarg, "endorsement password", &ctx->passwords.endorse); if (!result) { return false; } break; case 'o': result = password_util_copy_password(optarg, "owner password", &ctx->passwords.owner); if (!result) { return false; } break; case 'P': result = password_util_copy_password(optarg, "EK password", &ctx->passwords.ek); if (!result) { return false; } break; case 'g': result = string_bytes_get_uint32(optarg, &ctx->algorithm); if (!result) { LOG_ERR("Could not convert algorithm to value, got: %s", optarg); return false; } break; case 'f': if (!optarg) { LOG_ERR("Please specify an output file to save the pub ek to."); return false; } snprintf(ctx->out_file_path, sizeof(ctx->out_file_path), "%s", optarg); break; case 'X': ctx->passwords.is_hex = true; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); } } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { /* common options are not used, avoid compiler warning */ (void) opts; getpubek_context ctx = { .passwords = { 0 }, .algorithm = TPM_ALG_RSA, .sapi_context = sapi_context }; bool result = init(argc, argv, envp, &ctx); if (!result) { return false; } /* normalize 0 success 1 failure */ return create_ek_handle(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_getrandom.c000066400000000000000000000113071313543155100177630ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include "log.h" #include "files.h" #include "main.h" #include "options.h" #include "password_util.h" #include "string-bytes.h" typedef struct tpm_random_ctx tpm_random_ctx; struct tpm_random_ctx { bool output_file_specified; char output_file[PATH_MAX]; UINT16 num_of_bytes; TSS2_SYS_CONTEXT *sapi_context; }; static bool get_random_and_save(tpm_random_ctx *ctx) { TPM2B_DIGEST random_bytes = TPM2B_TYPE_INIT(TPM2B_DIGEST, buffer); TPM_RC rval = Tss2_Sys_GetRandom(ctx->sapi_context, NULL, ctx->num_of_bytes, &random_bytes, NULL); if (rval != TSS2_RC_SUCCESS) { LOG_ERR("TPM2_GetRandom Error. TPM Error:0x%x", rval); return false; } if (!ctx->output_file_specified) { UINT16 i; for (i = 0; i < random_bytes.t.size; i++) { printf("%s0x%2.2X", i ? " " : "", random_bytes.t.buffer[i]); } printf("\n"); return true; } return files_save_bytes_to_file(ctx->output_file, (UINT8 *) random_bytes.t.buffer, random_bytes.t.size); } #define ARG_CNT (2 * (sizeof(long_options)/sizeof(long_options[0]) - 1)) static bool init(int argc, char *argv[], tpm_random_ctx *ctx) { static const char *short_options = "o:"; static const struct option long_options[] = { { "output", required_argument, NULL, 'o' }, { NULL, no_argument, NULL, '\0' }, }; if (argc !=2 && argc != 4) { showArgMismatch(argv[0]); return false; } int opt; optind = 0; /* force reset of getopt() since we used gnu extensionsin main, sic */ while ((opt = getopt_long(argc, argv, short_options, long_options, NULL)) != -1) { switch (opt) { case 'o': ctx->output_file_specified = true; snprintf(ctx->output_file, sizeof(ctx->output_file), "%s", optarg); break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } } bool result = string_bytes_get_uint16(argv[optind], &ctx->num_of_bytes); if (!result) { LOG_ERR("Error converting size to a number, got: \"%s\".", argv[optind]); return false; } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void)opts; (void)envp; tpm_random_ctx ctx = { .output_file_specified = false, .num_of_bytes = 0, .output_file = { 0 }, .sapi_context = sapi_context }; bool result = init(argc, argv, &ctx); if (!result) { return 1; } return get_random_and_save(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_hash.c000066400000000000000000000162151313543155100167310ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include "files.h" #include "log.h" #include "main.h" #include "options.h" #include "string-bytes.h" typedef struct tpm_hash_ctx tpm_hash_ctx; struct tpm_hash_ctx { TPMI_RH_HIERARCHY hierarchyValue; TPM2B_MAX_BUFFER data; TPMI_ALG_HASH halg; char outHashFilePath[PATH_MAX]; char outTicketFilePath[PATH_MAX]; TSS2_SYS_CONTEXT *sapi_context; }; static bool get_hierarchy_value(const char *hiearchy_code, TPMI_RH_HIERARCHY *hierarchy_value) { size_t len = strlen(hiearchy_code); if (len != 1) { LOG_ERR("Hierarchy Values are single characters, got: %s\n", hiearchy_code); return false; } switch (hiearchy_code[0]) { case 'e': *hierarchy_value = TPM_RH_ENDORSEMENT; break; case 'o': *hierarchy_value = TPM_RH_OWNER; break; case 'p': *hierarchy_value = TPM_RH_PLATFORM; break; case 'n': *hierarchy_value = TPM_RH_NULL; break; default: LOG_ERR("Unknown hierarchy value: %s\n", hiearchy_code); return false; } return true; } static bool hash_and_save(tpm_hash_ctx *ctx) { TPM2B_DIGEST outHash = TPM2B_TYPE_INIT(TPM2B_DIGEST, buffer); TPMT_TK_HASHCHECK validation; UINT32 rval = Tss2_Sys_Hash(ctx->sapi_context, 0, &ctx->data, ctx->halg, ctx->hierarchyValue, &outHash, &validation, 0); if (rval != TPM_RC_SUCCESS) { LOG_ERR("TPM2_Sys_Hash Error. TPM Error:0x%x", rval); return false; } printf("\nhash value(hex type): "); UINT16 i; for (i = 0; i < outHash.t.size; i++) printf("%02x ", outHash.t.buffer[i]); printf("\n"); printf("\nvalidation value(hex type): "); for (i = 0; i < validation.digest.t.size; i++) printf("%02x ", validation.digest.t.buffer[i]); printf("\n"); /* TODO fix serialization */ bool result = files_save_bytes_to_file(ctx->outHashFilePath, (UINT8 *) &outHash, sizeof(outHash)); if (!result) { return false; } /* TODO fix serialization */ return files_save_bytes_to_file(ctx->outTicketFilePath, (UINT8 *) &validation, sizeof(validation)); } static bool init(int argc, char *argv[], tpm_hash_ctx *ctx) { static struct option long_options[] = { {"Hierachy", required_argument, NULL, 'H'}, {"halg", required_argument, NULL, 'g'}, {"infile", required_argument, NULL, 'I'}, {"outfile", required_argument, NULL, 'o'}, {"ticket", required_argument, NULL, 't'}, {NULL, no_argument, NULL, '\0'} }; if (argc == 1) { showArgMismatch(argv[0]); return false; } int opt; bool res; long fileSize; unsigned flags = 0; while ((opt = getopt_long(argc, argv, "H:g:I:o:t:", long_options, NULL)) != -1) { switch (opt) { case 'H': flags++; res = get_hierarchy_value(optarg, &ctx->hierarchyValue); if (!res) { return false; } break; case 'g': flags++; res = string_bytes_get_uint16(optarg, &ctx->halg); if (!res) { showArgError(optarg, argv[0]); return false; } break; case 'I': flags++; res = files_get_file_size(optarg, &fileSize); if (!res) { return false; } if (fileSize > MAX_DIGEST_BUFFER) { LOG_ERR( "Input data too long: %ld, should be less than %d bytes\n", fileSize, MAX_DIGEST_BUFFER); return false; } ctx->data.t.size = fileSize; res = files_load_bytes_from_file(optarg, ctx->data.t.buffer, &ctx->data.t.size); if (!res) { return false; } break; case 'o': flags++; snprintf(ctx->outHashFilePath, sizeof(ctx->outHashFilePath), "%s", optarg); res = files_does_file_exist(ctx->outHashFilePath); if (res) { return false; } break; case 't': flags++; snprintf(ctx->outTicketFilePath, sizeof(ctx->outTicketFilePath), "%s", optarg); res = files_does_file_exist(ctx->outTicketFilePath); if (res) { return false; } break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } } /* all flags must be specified */ if (flags != 5) { showArgMismatch(argv[0]); return false; } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { /* opts is unused, avoid compiler warning */ (void)opts; (void)envp; tpm_hash_ctx ctx = { .sapi_context = sapi_context, }; bool res = init(argc, argv, &ctx); if (!res) { return 1; } return hash_and_save(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_hmac.c000066400000000000000000000202651313543155100167160ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include "log.h" #include "files.h" #include "main.h" #include "options.h" #include "password_util.h" #include "string-bytes.h" typedef struct tpm_hmac_ctx tpm_hmac_ctx; struct tpm_hmac_ctx { TPMS_AUTH_COMMAND session_data; TPMI_DH_OBJECT key_handle; TPMI_ALG_HASH algorithm; char hmac_output_file_path[PATH_MAX]; TPM2B_MAX_BUFFER data; TSS2_SYS_CONTEXT *sapi_context; }; static bool do_hmac_and_output(tpm_hmac_ctx *ctx) { TPMS_AUTH_RESPONSE session_data_out; TSS2_SYS_CMD_AUTHS sessions_data; TSS2_SYS_RSP_AUTHS sessions_data_out; TPMS_AUTH_COMMAND *session_data_array[1]; TPMS_AUTH_RESPONSE *session_data_out_array[1]; TPM2B_DIGEST hmac_out = TPM2B_TYPE_INIT(TPM2B_DIGEST, buffer); session_data_array[0] = &ctx->session_data; session_data_out_array[0] = &session_data_out; sessions_data_out.rspAuths = &session_data_out_array[0]; sessions_data.cmdAuths = &session_data_array[0]; sessions_data_out.rspAuthsCount = 1; sessions_data.cmdAuthsCount = 1; ctx->session_data.sessionHandle = TPM_RS_PW; TPM_RC rval = Tss2_Sys_HMAC(ctx->sapi_context, ctx->key_handle, &sessions_data, &ctx->data, ctx->algorithm, &hmac_out, &sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("TPM2_HMAC Error. TPM Error:0x%x", rval); return -1; } printf("\nhmac value(hex type): "); UINT16 i; for (i = 0; i < hmac_out.t.size; i++) printf("%02x ", hmac_out.t.buffer[i]); printf("\n"); /* TODO fix serialization */ return files_save_bytes_to_file(ctx->hmac_output_file_path, (UINT8 *) &hmac_out, sizeof(hmac_out)); } #define ARG_CNT(optional) ((int)(2 * (sizeof(long_options)/sizeof(long_options[0]) - optional - 1))) static bool init(int argc, char *argv[], tpm_hmac_ctx *ctx) { bool result = false; bool is_hex_passwd = false; char *contextKeyFile = NULL; const char *optstring = "k:P:g:I:o:c:X"; static struct option long_options[] = { {"keyHandle", required_argument, NULL, 'k'}, {"keyContext", required_argument, NULL, 'c'}, {"pwdk", required_argument, NULL, 'P'}, {"algorithm", required_argument, NULL, 'g'}, {"infile", required_argument, NULL, 'I'}, {"outfile", required_argument, NULL, 'o'}, {"passwdInHex", no_argument, NULL, 'X'}, {NULL, no_argument, NULL, '\0'} }; struct { UINT8 k : 1; UINT8 P : 1; UINT8 g : 1; UINT8 I : 1; UINT8 o : 1; UINT8 c : 1; UINT8 unused : 2; } flags = { 0 }; /* * argc should be bound by the maximum and minimum option count. * subtract 1 from argc to disregard argv[0] */ if ((argc - 1) < 1 || (argc - 1) > ARG_CNT(0)) { showArgMismatch(argv[0]); return false; } int opt = -1; while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) { switch (opt) { case 'k': result = string_bytes_get_uint32(optarg, &ctx->key_handle); if (!result) { LOG_ERR("Could not convert key handle to number, got \"%s\"", optarg); goto out; } flags.k = 1; break; case 'P': result = password_util_copy_password(optarg, "key handle", &ctx->session_data.hmac); if (!result) { goto out; } flags.P = 1; break; case 'g': result = string_bytes_get_uint16(optarg, &ctx->algorithm); if (!result) { LOG_ERR("Could not convert algorithm to number, got \"%s\"", optarg); goto out; } flags.g = 1; break; case 'I': ctx->data.t.size = sizeof(ctx->data) - 2; result = files_load_bytes_from_file(optarg, ctx->data.t.buffer, &ctx->data.t.size); if (!result) { goto out; } flags.I = 1; break; case 'o': result = files_does_file_exist(optarg); if (result) { goto out; } snprintf(ctx->hmac_output_file_path, sizeof(ctx->hmac_output_file_path), "%s", optarg); flags.o = 1; break; case 'c': if (contextKeyFile) { LOG_ERR("Multiple specifications of -c"); goto out; } contextKeyFile = strdup(optarg); if (!contextKeyFile) { LOG_ERR("OOM"); goto out; } flags.c = 1; break; case 'X': is_hex_passwd = true; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); goto out; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); goto out; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); goto out; } } /* * Options g, i, o must be specified and k or c must be specified. */ if (!((flags.k || flags.c) && flags.I && flags.o && flags.g)) { LOG_ERR("Must specify options g, i, o and k or c"); goto out; } if (flags.c) { result = file_load_tpm_context_from_file(ctx->sapi_context, &ctx->key_handle, contextKeyFile); if (!result) { LOG_ERR("Loading tpm context from file \"%s\" failed.", contextKeyFile); goto out; } } /* convert a hex password if needed */ result = password_util_to_auth(&ctx->session_data.hmac, is_hex_passwd, "key handle", &ctx->session_data.hmac); if (!result) { goto out; } result = true; out: free(contextKeyFile); return result; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void)opts; (void)envp; tpm_hmac_ctx ctx = { .session_data = { 0 }, .key_handle = 0, .sapi_context = sapi_context }; bool result = init(argc, argv, &ctx); if (!result) { return 1; } return do_hmac_and_output(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_listpcrs.c000066400000000000000000000314201313543155100176440ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include "log.h" #include "main.h" #include "options.h" #include "pcr.h" #include "string-bytes.h" typedef struct tpm2_algorithm tpm2_algorithm; struct tpm2_algorithm { int count; TPMI_ALG_HASH alg[8]; //XXX Why 8? }; typedef struct tpm2_pcrs tpm2_pcrs; struct tpm2_pcrs { size_t count; TPML_DIGEST pcr_values[24]; //XXX Why 24? }; typedef struct listpcr_context listpcr_context; struct listpcr_context { TSS2_SYS_CONTEXT *sapi_context; FILE *output_file; tpm2_algorithm algs; tpm2_pcrs pcrs; TPML_PCR_SELECTION pcr_selections; }; static inline void set_pcr_select_bit(TPMS_PCR_SELECTION *pcr_selection, UINT32 pcr) { pcr_selection->pcrSelect[((pcr) / 8)] |= (1 << ((pcr) % 8)); } static inline void clear_pcr_select_bits(TPMS_PCR_SELECTION *pcr_selection) { /* XXX Why only the first 3? */ pcr_selection->pcrSelect[0] = 0; pcr_selection->pcrSelect[1] = 0; pcr_selection->pcrSelect[2] = 0; } static inline void set_pcr_select_size(TPMS_PCR_SELECTION *pcr_selection, UINT8 size) { pcr_selection->sizeofSelect = size; } static bool is_pcr_select_bit_set(TPMS_PCR_SELECTION *pcr_selection, UINT32 pcr) { return (pcr_selection->pcrSelect[((pcr) / 8)] & (1 << ((pcr) % 8))); } static const char *get_algorithm_name(TPMI_ALG_HASH alg_id) { static const struct { TPMI_ALG_HASH alg; const char *desc; } g_algs[] = { { TPM_ALG_SHA1, "TPM_ALG_SHA1" }, { TPM_ALG_SHA256, "TPM_ALG_SHA256" }, { TPM_ALG_SHA384, "TPM_ALG_SHA384" }, { TPM_ALG_SHA512, "TPM_ALG_SHA512" }, { TPM_ALG_SM3_256, "TPM_ALG_SM3_256" }, { TPM_ALG_NULL, "TPM_ALG_UNKOWN" } }; unsigned i; for (i = 0; g_algs[i].alg != TPM_ALG_NULL ; i++) { if (g_algs[i].alg == alg_id) { break; } } return g_algs[i].desc; } static void update_pcr_selections(TPML_PCR_SELECTION *s1, TPML_PCR_SELECTION *s2) { UINT32 i1, i2, j; for (i2 = 0; i2 < s2->count; i2++) { for (i1 = 0; i1 < s1->count; i1++) { if (s2->pcrSelections[i2].hash != s1->pcrSelections[i1].hash) continue; for (j = 0; j < s1->pcrSelections[i1].sizeofSelect; j++) s1->pcrSelections[i1].pcrSelect[j] &= ~s2->pcrSelections[i2].pcrSelect[j]; } } } static bool unset_pcr_sections(TPML_PCR_SELECTION *s) { UINT32 i, j; for (i = 0; i < s->count; i++) { for (j = 0; j < s->pcrSelections[i].sizeofSelect; j++) { if (s->pcrSelections[i].pcrSelect[j]) { return false; } } } return true; } static bool read_pcr_values(listpcr_context *context) { TPML_PCR_SELECTION pcr_selection_tmp; TPML_PCR_SELECTION pcr_selection_out; UINT32 pcr_update_counter; //1. prepare pcrSelectionIn with g_pcrSelections memcpy(&pcr_selection_tmp, &context->pcr_selections, sizeof(pcr_selection_tmp)); //2. call pcr_read context->pcrs.count = 0; do { UINT32 rval = Tss2_Sys_PCR_Read(context->sapi_context, 0, &pcr_selection_tmp, &pcr_update_counter, &pcr_selection_out, &context->pcrs.pcr_values[context->pcrs.count], 0); if (rval != TPM_RC_SUCCESS) { LOG_ERR("read pcr failed. tpm error 0x%0x", rval); return -1; } //3. unmask pcrSelectionOut bits from pcrSelectionIn update_pcr_selections(&pcr_selection_tmp, &pcr_selection_out); //4. goto step 2 if pcrSelctionIn still has bits set } while (++context->pcrs.count < 24 && !unset_pcr_sections(&pcr_selection_tmp)); if (context->pcrs.count >= 24 && !unset_pcr_sections(&pcr_selection_tmp)) { LOG_ERR("too much pcrs to get! try to split into multiple calls..."); return false; } return true; } static void init_pcr_selection_from_algorithm(TPMI_ALG_HASH alg_id, TPML_PCR_SELECTION *pcr_selections) { pcr_selections->count = 1; pcr_selections->pcrSelections[0].hash = alg_id; set_pcr_select_size(&pcr_selections->pcrSelections[0], 3); clear_pcr_select_bits(&pcr_selections->pcrSelections[0]); UINT32 pcr_id; for (pcr_id = 0; pcr_id < 24; pcr_id++) { set_pcr_select_bit(&pcr_selections->pcrSelections[0], pcr_id); } } /* XXX Could this internally call init_pcr_selection_from_algorithm to reduce duplicate code? */ static void init_pcr_selection_all(tpm2_algorithm *algorithm, TPML_PCR_SELECTION *pcr_selections) { pcr_selections->count = 0; int i; for (i = 0; i < algorithm->count; i++) { pcr_selections->pcrSelections[i].hash = algorithm->alg[i]; set_pcr_select_size(&pcr_selections->pcrSelections[i], 3); clear_pcr_select_bits(&pcr_selections->pcrSelections[i]); UINT32 pcr_id; for (pcr_id = 0; pcr_id < 24; pcr_id++) { set_pcr_select_bit(&pcr_selections->pcrSelections[i], pcr_id); } pcr_selections->count++; } } // show all PCR banks according to g_pcrSelection & g_pcrs-> static bool show_pcr_values(listpcr_context *context) { UINT32 vi = 0, di = 0, i; for (i = 0; i < context->pcr_selections.count; i++) { const char *alg_name = get_algorithm_name( context->pcr_selections.pcrSelections[i].hash); printf("\nBank/Algorithm: %s(0x%04x)\n", alg_name, context->pcr_selections.pcrSelections[i].hash); UINT32 pcr_id; for (pcr_id = 0; pcr_id < 24; pcr_id++) { if (!is_pcr_select_bit_set(&context->pcr_selections.pcrSelections[i], pcr_id)) { continue; } if (vi >= context->pcrs.count || di >= context->pcrs.pcr_values[vi].count) { LOG_ERR("Something wrong, trying to print but nothing more\n"); return false; } printf("PCR_%02d:", pcr_id); int k; for (k = 0; k < context->pcrs.pcr_values[vi].digests[di].t.size; k++) printf(" %02x", context->pcrs.pcr_values[vi].digests[di].t.buffer[k]); printf("\n"); if (context->output_file != NULL && fwrite(context->pcrs.pcr_values[vi].digests[di].t.buffer, context->pcrs.pcr_values[vi].digests[di].t.size, 1, context->output_file) != 1) { LOG_ERR("write to output file failed: %s", strerror(errno)); return false; } if (++di < context->pcrs.pcr_values[vi].count) { continue; } di = 0; if (++vi < context->pcrs.count) { continue; } } } return true; } static bool show_selected_pcr_values(listpcr_context *context) { if (!read_pcr_values(context)) return false; if (!show_pcr_values(context)) return false; return true; } static bool show_all_pcr_values(listpcr_context *context) { init_pcr_selection_all(&context->algs, &context->pcr_selections); return show_selected_pcr_values(context); } static bool show_alg_pcr_values(listpcr_context *context, TPMI_ALG_HASH alg_id) { init_pcr_selection_from_algorithm(alg_id, &context->pcr_selections); return show_selected_pcr_values(context); } static bool get_banks(listpcr_context *context) { TPMI_YES_NO more_data; TPMS_CAPABILITY_DATA capability_data; UINT32 rval; rval = Tss2_Sys_GetCapability(context->sapi_context, 0, TPM_CAP_PCRS, 0, 1, &more_data, &capability_data, 0); if (rval != TPM_RC_SUCCESS) { LOG_ERR( "GetCapability: Get PCR allocation status Error. TPM Error:0x%x......\n", rval); return false; } unsigned i; for (i = 0; i < capability_data.data.assignedPCR.count; i++) { context->algs.alg[i] = capability_data.data.assignedPCR.pcrSelections[i].hash; } context->algs.count = capability_data.data.assignedPCR.count; return true; } static void show_banks(tpm2_algorithm *g_banks) { printf("Supported Bank/Algorithm:"); int i; for (i = 0; i < g_banks->count; i++) { const char *alg_name = get_algorithm_name(g_banks->alg[i]); printf(" %s(0x%04x)", alg_name, g_banks->alg[i]); } printf("\n"); } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { listpcr_context context = { .algs = { .count = 3, .alg = { TPM_ALG_SHA1, TPM_ALG_SHA256, TPM_ALG_SHA384 } }, .output_file = NULL, .pcr_selections = { 0 }, .pcrs = { 0 }, .sapi_context = sapi_context }; bool success = false; TPMI_ALG_HASH selected_algorithm; unsigned L_flag = 0, s_flag = 0, g_flag = 0; static struct option long_options[] = { { "algorithm", 1, NULL, 'g' }, { "output", 1, NULL, 'o' }, { "algs", 0, NULL, 's' }, { "selList", 1, NULL, 'L' }, { NULL, 0, NULL, '\0' } }; /* mark these as unused to prevent compiler warnings/errors */ (void) opts; (void) envp; int opt; while ((opt = getopt_long(argc, argv, "g:o:L:s", long_options, NULL)) != -1) { switch (opt) { case 'g': if (!string_bytes_get_uint16(optarg, &selected_algorithm)) { showArgError(optarg, argv[0]); goto error; } g_flag = 1; break; case 'o': context.output_file = fopen(optarg, "wb+"); if (!context.output_file) { LOG_ERR("Could not open output file \"%s\" error: \"%s\"", optarg, strerror(errno)); goto error; } /* XXX Should o option only print to output file and nothing to stdout? */ break; case 'L': if (pcr_parse_selections(optarg, &context.pcr_selections) != 0) { showArgError(optarg, argv[0]); goto error; } L_flag = 1; break; case 's': s_flag = 1; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); goto error; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); goto error; } } int flagCnt = g_flag + L_flag + s_flag; if (flagCnt > 1) { showArgMismatch(argv[0]); goto error; } success = get_banks(&context); if (!success) { goto error; } if (s_flag) { show_banks(&context.algs); } else if (g_flag) { success = show_alg_pcr_values(&context, selected_algorithm); } else if (L_flag) { success = show_selected_pcr_values(&context); } else { success = show_all_pcr_values(&context); } error: if (context.output_file) { fclose(context.output_file); } /* 0 on success 1 otherwise */ return !success; } tpm2-tools-2.1.0/tools/tpm2_listpersistent.c000066400000000000000000000102701313543155100210750ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2016, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include #include "files.h" #include "main.h" #include "options.h" #include "string-bytes.h" int debugLevel = 0; int readPublic(TSS2_SYS_CONTEXT *sapi_context, TPMI_DH_OBJECT objectHandle) { UINT32 rval; TPMS_AUTH_RESPONSE sessionDataOut; TSS2_SYS_RSP_AUTHS sessionsDataOut; TPMS_AUTH_RESPONSE *sessionDataOutArray[1]; TPM2B_PUBLIC outPublic = { { 0, } }; TPM2B_NAME name = TPM2B_TYPE_INIT(TPM2B_NAME, name); TPM2B_NAME qualifiedName = TPM2B_TYPE_INIT(TPM2B_NAME, name); sessionDataOutArray[0] = &sessionDataOut; sessionsDataOut.rspAuths = &sessionDataOutArray[0]; sessionsDataOut.rspAuthsCount = 1; rval = Tss2_Sys_ReadPublic(sapi_context, objectHandle, 0, &outPublic, &name, &qualifiedName, &sessionsDataOut); if(rval != TPM_RC_SUCCESS) { printf("\nTPM2_ReadPublic error: rval = 0x%0x\n\n",rval); return -1; } printf(" {\n"); printf("\tType: 0x%x\n ", outPublic.t.publicArea.type); printf("\tHash algorithm(nameAlg): 0x%x\n ", outPublic.t.publicArea.nameAlg); printf("\tAttributes: 0x%x\n", outPublic.t.publicArea.objectAttributes.val); printf(" }\n"); return 0; } int execute_tool (int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void) opts; (void) envp; (void) argc; (void) argv; TPMI_YES_NO moreData; TPMS_CAPABILITY_DATA capabilityData; UINT32 rval; UINT32 property = string_bytes_endian_convert_32(TPM_HT_PERSISTENT); rval = Tss2_Sys_GetCapability( sapi_context, 0, TPM_CAP_HANDLES, property, TPM_PT_HR_PERSISTENT, &moreData, &capabilityData, 0 ); if(rval != TPM_RC_SUCCESS) { printf("\n......GetCapability: Get persistent object list Error." " TPM Error:0x%x......\n", rval); return 1; } printf( "%d persistent objects defined.\n", capabilityData.data.handles.count); UINT32 i; for( i=0; i < capabilityData.data.handles.count; i++ ) { printf("\n %d. Persistent handle: 0x%x\n", i, capabilityData.data.handles.handle[i]); if(readPublic(sapi_context, capabilityData.data.handles.handle[i])) return 2; } printf("\n"); return 0; } tpm2-tools-2.1.0/tools/tpm2_load.c000066400000000000000000000214631313543155100167260ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include #include #include "files.h" #include "main.h" #include "options.h" #include "string-bytes.h" TPM_HANDLE handle2048rsa; TPMS_AUTH_COMMAND sessionData; bool hexPasswd = false; int load (TSS2_SYS_CONTEXT *sapi_context, TPMI_DH_OBJECT parentHandle, TPM2B_PUBLIC *inPublic, TPM2B_PRIVATE *inPrivate, const char *outFileName, int P_flag) { UINT32 rval; TPMS_AUTH_RESPONSE sessionDataOut; TSS2_SYS_CMD_AUTHS sessionsData; TSS2_SYS_RSP_AUTHS sessionsDataOut; TPMS_AUTH_COMMAND *sessionDataArray[1]; TPMS_AUTH_RESPONSE *sessionDataOutArray[1]; TPM2B_NAME nameExt = TPM2B_TYPE_INIT(TPM2B_NAME, name); sessionDataArray[0] = &sessionData; sessionDataOutArray[0] = &sessionDataOut; sessionsDataOut.rspAuths = &sessionDataOutArray[0]; sessionsData.cmdAuths = &sessionDataArray[0]; sessionsDataOut.rspAuthsCount = 1; sessionsData.cmdAuthsCount = 1; sessionData.sessionHandle = TPM_RS_PW; sessionData.nonce.t.size = 0; if(P_flag == 0) sessionData.hmac.t.size = 0; *((UINT8 *)((void *)&sessionData.sessionAttributes)) = 0; if (sessionData.hmac.t.size > 0 && hexPasswd) { sessionData.hmac.t.size = sizeof(sessionData.hmac) - 2; if (hex2ByteStructure((char *)sessionData.hmac.t.buffer, &sessionData.hmac.t.size, sessionData.hmac.t.buffer) != 0) { printf( "Failed to convert Hex format password for parent Passwd.\n"); return -1; } } rval = Tss2_Sys_Load (sapi_context, parentHandle, &sessionsData, inPrivate, inPublic, &handle2048rsa, &nameExt, &sessionsDataOut); if(rval != TPM_RC_SUCCESS) { printf("\nLoad Object Failed ! ErrorCode: 0x%0x\n\n",rval); return -1; } printf("\nLoad succ.\nLoadedHandle: 0x%08x\n\n",handle2048rsa); /* TODO fix serialization */ if(!files_save_bytes_to_file(outFileName, (UINT8 *)&nameExt, sizeof(nameExt))) return -2; return 0; } int execute_tool (int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void) envp; (void) opts; TPMI_DH_OBJECT parentHandle; TPM2B_PUBLIC inPublic; TPM2B_PRIVATE inPrivate; UINT16 size; char outFilePath[PATH_MAX] = {0}; char *contextFile = NULL; char *contextParentFilePath = NULL; memset(&inPublic,0,sizeof(TPM2B_PUBLIC)); memset(&inPrivate,0,sizeof(TPM2B_SENSITIVE)); setbuf(stdout, NULL); setvbuf (stdout, NULL, _IONBF, BUFSIZ); int opt = -1; const char *optstring = "H:P:u:r:n:C:c:X"; static struct option long_options[] = { {"parent",1,NULL,'H'}, {"pwdp",1,NULL,'P'}, {"pubfile",1,NULL,'u'}, {"privfile",1,NULL,'r'}, {"name",1,NULL,'n'}, {"context",1,NULL,'C'}, {"contextParent",1,NULL,'c'}, {"passwdInHex",0,NULL,'X'}, {0,0,0,0} }; int returnVal = 0; int flagCnt = 0; int H_flag = 0, P_flag = 0, u_flag = 0, r_flag = 0, c_flag = 0, C_flag = 0, n_flag = 0; while((opt = getopt_long(argc,argv,optstring,long_options,NULL)) != -1) { switch(opt) { case 'H': if (!string_bytes_get_uint32(optarg, &parentHandle)) { returnVal = -1; break; } printf("\nparentHandle: 0x%x\n\n",parentHandle); H_flag = 1; break; case 'P': sessionData.hmac.t.size = sizeof(sessionData.hmac.t) - 2; if(str2ByteStructure(optarg,&sessionData.hmac.t.size,sessionData.hmac.t.buffer) != 0) { returnVal = -2; break; } P_flag = 1; break; case 'u': size = sizeof(inPublic); if(!files_load_bytes_from_file(optarg, (UINT8 *)&inPublic, &size)) { returnVal = -3; break; } u_flag = 1; break; case 'r': size = sizeof(inPrivate); if(!files_load_bytes_from_file(optarg, (UINT8 *)&inPrivate, &size)) { returnVal = -4; break; } r_flag = 1; break; case 'n': snprintf(outFilePath, sizeof(outFilePath), "%s", optarg); if(files_does_file_exist(outFilePath)) { returnVal = -5; break; } n_flag = 1; break; case 'c': contextParentFilePath = optarg; if(contextParentFilePath == NULL || contextParentFilePath[0] == '\0') { returnVal = -8; break; } printf("contextParentFile = %s\n", contextParentFilePath); c_flag = 1; break; case 'C': contextFile = optarg; if(contextFile == NULL || contextFile[0] == '\0') { returnVal = -9; break; } printf("contextFile = %s\n", contextFile); C_flag = 1; break; case 'X': hexPasswd = true; break; case ':': // printf("Argument %c needs a value!\n",optopt); returnVal = -10; break; case '?': // printf("Unknown Argument: %c\n",optopt); returnVal = -11; break; //default: // break; } if(returnVal) break; }; if(returnVal != 0) return returnVal; flagCnt = H_flag + u_flag +r_flag + n_flag + c_flag; if(flagCnt == 4 && (H_flag == 1 || c_flag == 1) && u_flag == 1 && r_flag == 1 && n_flag == 1) { if(c_flag) { returnVal = file_load_tpm_context_from_file (sapi_context, &parentHandle, contextParentFilePath) != true; } if (returnVal == 0) { returnVal = load (sapi_context, parentHandle, &inPublic, &inPrivate, outFilePath, P_flag); } if (returnVal == 0 && C_flag) { returnVal = files_save_tpm_context_to_file (sapi_context, handle2048rsa, contextFile) != true; } if(returnVal) return -13; } else { showArgMismatch(argv[0]); return -14; } return 0; } tpm2-tools-2.1.0/tools/tpm2_loadexternal.c000066400000000000000000000150321313543155100204640ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include "files.h" #include "log.h" #include "main.h" #include "options.h" #include "string-bytes.h" typedef struct tpm_loadexternal_ctx tpm_loadexternal_ctx; struct tpm_loadexternal_ctx { char context_file_path[PATH_MAX]; TPMI_RH_HIERARCHY hierarchy_value; TPM_HANDLE rsa2048_handle; TPM2B_PUBLIC public_key; TPM2B_SENSITIVE private_key; bool has_private_key; bool save_to_context_file; TSS2_SYS_CONTEXT *sapi_context; }; static bool get_hierarchy_value(const char *argument_opt, TPMI_RH_HIERARCHY *hierarchy_value) { if (strlen(argument_opt) != 1) { LOG_ERR("Wrong Hierarchy Value, got: \"%s\", expected one of e,o,p,n", argument_opt); return false; } switch (argument_opt[0]) { case 'e': *hierarchy_value = TPM_RH_ENDORSEMENT; break; case 'o': *hierarchy_value = TPM_RH_OWNER; break; case 'p': *hierarchy_value = TPM_RH_PLATFORM; break; case 'n': *hierarchy_value = TPM_RH_NULL; break; default: LOG_ERR("Wrong Hierarchy Value, got: \"%s\", expected one of e,o,p,n", argument_opt); return false; } return true; } static bool load_external(tpm_loadexternal_ctx *ctx) { TSS2_SYS_RSP_AUTHS sessionsDataOut; TPMS_AUTH_RESPONSE *sessionDataOutArray[1]; TPM2B_NAME nameExt = TPM2B_TYPE_INIT(TPM2B_NAME, name); sessionsDataOut.rspAuths = &sessionDataOutArray[0]; sessionsDataOut.rspAuthsCount = 1; TPM_RC rval = Tss2_Sys_LoadExternal(ctx->sapi_context, 0, ctx->has_private_key ? &ctx->private_key : NULL, &ctx->public_key, ctx->hierarchy_value, &ctx->rsa2048_handle, &nameExt, &sessionsDataOut); if (rval != TPM_RC_SUCCESS) { LOG_ERR("LoadExternal Failed ! ErrorCode: 0x%0x", rval); return false; } return true; } static bool init(int argc, char *argv[], tpm_loadexternal_ctx *ctx) { const char *optstring = "H:u:r:C:"; static struct option long_options[] = { { "Hierachy", required_argument, NULL, 'H'}, { "pubfile", required_argument, NULL, 'u'}, { "privfile", required_argument, NULL, 'r'}, { "context", required_argument, NULL, 'C'}, { NULL, no_argument, NULL, '\0' } }; struct { UINT8 H : 1; UINT8 u : 1; UINT8 unused : 6; } flags = { 0 }; if(argc == 1) { showArgMismatch(argv[0]); return false; } int opt = -1; while((opt = getopt_long(argc,argv,optstring,long_options,NULL)) != -1) { switch(opt) { case 'H': { bool result = get_hierarchy_value(optarg, &ctx->hierarchy_value); if (!result) { return false; } } flags.H = 1; break; case 'u': { UINT16 size = sizeof(ctx->public_key); bool result = files_load_bytes_from_file(optarg, (UINT8 *)&ctx->public_key, &size); if (!result) { return false; } flags.u = 1; } break; case 'r': { UINT16 size = sizeof(ctx->private_key); bool result = files_load_bytes_from_file(optarg, (UINT8 *)&ctx->private_key, &size); if (!result) { return false; } ctx->has_private_key = true; } break; case 'C': snprintf(ctx->context_file_path, sizeof(ctx->context_file_path), "%s", optarg); ctx->save_to_context_file = true; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } } if (!(flags.H && flags.u)) { LOG_ERR("Expected H and u options"); return false; } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { /* opts and envp are unused, avoid compiler warning */ (void)opts; (void) envp; tpm_loadexternal_ctx ctx = { .has_private_key = false, .save_to_context_file = false, .sapi_context = sapi_context }; bool result = init(argc, argv, &ctx); if(!result) { return 1; } result = load_external(&ctx); if (!result) { return false; } if(ctx.save_to_context_file) { return files_save_tpm_context_to_file(ctx.sapi_context, ctx.rsa2048_handle, ctx.context_file_path) != true; } return 0; } tpm2-tools-2.1.0/tools/tpm2_makecredential.c000066400000000000000000000157561313543155100207670ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include #include "log.h" #include "files.h" #include "main.h" #include "options.h" #include "string-bytes.h" typedef struct tpm_makecred_ctx tpm_makecred_ctx; struct tpm_makecred_ctx { TPM_HANDLE rsa2048_handle; TPM2B_NAME object_name; char out_file_path[PATH_MAX]; TPM2B_PUBLIC public; TPM2B_DIGEST credential; }; static bool write_cred_and_secret(const char *path, TPM2B_ID_OBJECT *cred, TPM2B_ENCRYPTED_SECRET *secret) { bool result = false; FILE *fp = fopen(path, "w+"); if (!fp) { LOG_ERR("Could not open file \"%s\" error: \"%s\"", path, strerror(errno)); return false; } size_t items = fwrite(cred, sizeof(TPM2B_ID_OBJECT), 1, fp); if (items != 1) { LOG_ERR("writing credential to file \"%s\" failed, error: \"%s\"", path, strerror(errno)); goto out; } items = fwrite(secret, sizeof(TPM2B_ENCRYPTED_SECRET), 1, fp); if (items != 1) { LOG_ERR("writing secret to file \"%s\" failed, error: \"%s\"", path, strerror(errno)); goto out; } result = true; out: fclose(fp); return result; } static bool make_credential_and_save(TSS2_SYS_CONTEXT *sapi_context, tpm_makecred_ctx *ctx) { TPMS_AUTH_RESPONSE session_data_out; TSS2_SYS_RSP_AUTHS sessions_data_out; TPMS_AUTH_RESPONSE *session_data_out_array[1]; TPM2B_NAME name_ext = TPM2B_TYPE_INIT(TPM2B_NAME, name); TPM2B_ID_OBJECT cred_blob = TPM2B_TYPE_INIT(TPM2B_ID_OBJECT, credential); TPM2B_ENCRYPTED_SECRET secret = TPM2B_TYPE_INIT(TPM2B_ENCRYPTED_SECRET, secret); session_data_out_array[0] = &session_data_out; sessions_data_out.rspAuths = &session_data_out_array[0]; sessions_data_out.rspAuthsCount = 1; UINT32 rval = Tss2_Sys_LoadExternal(sapi_context, 0, NULL, &ctx->public, TPM_RH_NULL, &ctx->rsa2048_handle, &name_ext, &sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("LoadExternal failed. TPM Error:0x%x", rval); return false; } rval = Tss2_Sys_MakeCredential(sapi_context, ctx->rsa2048_handle, 0, &ctx->credential, &ctx->object_name, &cred_blob, &secret, &sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("MakeCredential failed. TPM Error:0x%x", rval); return false; } rval = Tss2_Sys_FlushContext(sapi_context, ctx->rsa2048_handle); if (rval != TPM_RC_SUCCESS) { LOG_ERR("Flush loaded key failed. TPM Error:0x%x", rval); return false; } return write_cred_and_secret(ctx->out_file_path, &cred_blob, &secret); } static bool init(int argc, char *argv[], tpm_makecred_ctx *ctx) { static const char *optstring = "e:s:n:o:"; static const struct option long_options[] = { {"encKey" ,required_argument, NULL, 'e'}, {"sec" ,required_argument, NULL, 's'}, {"name" ,required_argument, NULL, 'n'}, {"outFile" ,required_argument, NULL, 'o'}, {NULL ,no_argument , NULL, '\0'} }; if (argc == 1) { showArgMismatch(argv[0]); return false; } UINT16 size; int flagCnt = 0; int opt = -1; while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) { switch (opt) { case 'e': size = sizeof(ctx->public); if (!files_load_bytes_from_file(optarg, (UINT8 *) &ctx->public, &size)) { return false; } flagCnt++; break; case 's': ctx->credential.t.size = sizeof(ctx->credential) - 2; if (!files_load_bytes_from_file(optarg, ctx->credential.t.buffer, &ctx->credential.t.size)) { return false; } flagCnt++; break; case 'n': ctx->object_name.t.size = sizeof(ctx->object_name) - 2; if (hex2ByteStructure(optarg, &ctx->object_name.t.size, ctx->object_name.t.name) != 0) { return false; } flagCnt++; break; case 'o': snprintf(ctx->out_file_path, sizeof(ctx->out_file_path), "%s", optarg); if (files_does_file_exist(ctx->out_file_path)) { return false; } flagCnt++; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } } if (flagCnt != 4) { showArgMismatch(argv[0]); return false; } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { /* opts is unused, avoid compiler warning */ (void) opts; (void) envp; tpm_makecred_ctx ctx = { 0 }; bool result = init(argc, argv, &ctx); if (!result) { LOG_ERR("Initialization failed"); return 1; } return make_credential_and_save(sapi_context, &ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_nvdefine.c000066400000000000000000000176451313543155100176140ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include "log.h" #include "main.h" #include "options.h" #include "password_util.h" #include "string-bytes.h" typedef struct tpm_nvdefine_ctx tpm_nvdefine_ctx; struct tpm_nvdefine_ctx { UINT32 nvIndex; UINT32 authHandle; UINT32 size; UINT32 nvAttribute; TPM2B_AUTH handlePasswd; TPM2B_AUTH indexPasswd; bool hexPasswd; TSS2_SYS_CONTEXT *sapi_context; }; static int nv_space_define(tpm_nvdefine_ctx *ctx) { TPM2B_NV_PUBLIC public_info; TPMS_AUTH_COMMAND session_data; TPMS_AUTH_RESPONSE session_data_out; TSS2_SYS_CMD_AUTHS sessions_data; TSS2_SYS_RSP_AUTHS sessions_data_out; TPMS_AUTH_COMMAND *session_data_array[1] = { &session_data }; TPMS_AUTH_RESPONSE *session_data_out_array[1] = { &session_data_out }; sessions_data_out.rspAuths = &session_data_out_array[0]; sessions_data.cmdAuths = &session_data_array[0]; sessions_data_out.rspAuthsCount = 1; sessions_data.cmdAuthsCount = 1; session_data.sessionHandle = TPM_RS_PW; session_data.nonce.t.size = 0; session_data.hmac.t.size = 0; *((UINT8 *) ((void *) &session_data.sessionAttributes)) = 0; bool result = password_util_to_auth(&ctx->handlePasswd, ctx->hexPasswd, "handle password", &session_data.hmac); if (!result) { return false; } public_info.t.size = sizeof(TPMI_RH_NV_INDEX) + sizeof(TPMI_ALG_HASH) + sizeof(TPMA_NV) + sizeof(UINT16) + sizeof(UINT16); public_info.t.nvPublic.nvIndex = ctx->nvIndex; public_info.t.nvPublic.nameAlg = TPM_ALG_SHA256; // Now set the attributes. public_info.t.nvPublic.attributes.val = ctx->nvAttribute; public_info.t.nvPublic.authPolicy.t.size = 0; public_info.t.nvPublic.dataSize = ctx->size; TPM2B_AUTH nvAuth; result = password_util_to_auth(&ctx->indexPasswd, ctx->hexPasswd, "index password", &nvAuth); if (!result) { return false; } TPM_RC rval = Tss2_Sys_NV_DefineSpace(ctx->sapi_context, ctx->authHandle, &sessions_data, &nvAuth, &public_info, &sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("Failed to define NV area at index 0x%x (%d).Error:0x%x", ctx->nvIndex, ctx->nvIndex, rval); return false; } LOG_INFO("Success to define NV area at index 0x%x (%d).", ctx->nvIndex, ctx->nvIndex); return true; } #define MAX_ARG_CNT ((int)(2 * (sizeof(long_options)/sizeof(long_options[0]) - 1))) static bool init(int argc, char* argv[], tpm_nvdefine_ctx *ctx) { struct option long_options[] = { { "index" , required_argument, NULL, 'x' }, { "authHandle" , required_argument, NULL, 'a' }, { "size" , required_argument, NULL, 's' }, { "attribute" , required_argument, NULL, 't' }, { "handlePasswd", required_argument, NULL, 'P' }, { "indexPasswd" , required_argument, NULL, 'I' }, { "passwdInHex" , no_argument, NULL, 'X' }, { NULL , no_argument, NULL, 0 }, }; if (argc <= 1 || argc > MAX_ARG_CNT) { showArgMismatch(argv[0]); return false; } int opt; bool result; while ((opt = getopt_long(argc, argv, "x:a:s:t:P:I:X", long_options, NULL)) != -1) { switch (opt) { case 'x': result = string_bytes_get_uint32(optarg, &ctx->nvIndex); if (!result) { LOG_ERR("Could not convert NV index to number, got: \"%s\"", optarg); return false; } if (ctx->nvIndex == 0) { LOG_ERR("NV Index cannot be 0"); return false; } break; case 'a': result = string_bytes_get_uint32(optarg, &ctx->authHandle); if (!result) { LOG_ERR("Could not convert auth handle to number, got: \"%s\"", optarg); return false; } if (ctx->authHandle == 0) { LOG_ERR("Auth handle cannot be 0"); return false; } break; case 'P': result = password_util_copy_password(optarg, "handle password", &ctx->handlePasswd); if (!result) { return false; } break; case 's': result = string_bytes_get_uint32(optarg, &ctx->size); if (!result) { LOG_ERR("Could not convert size to number, got: \"%s\"", optarg); return false; } break; case 't': result = string_bytes_get_uint32(optarg, &ctx->nvAttribute); if (!result) { LOG_ERR("Could not convert NV attribute to number, got: \"%s\"", optarg); return false; } break; case 'I': result = password_util_copy_password(optarg, "index password", &ctx->indexPasswd); if (!result) { return false; } break; case 'X': ctx->hexPasswd = true; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void)opts; (void)envp; tpm_nvdefine_ctx ctx = { .nvIndex = 0, .authHandle = TPM_RH_PLATFORM, .size = 0, .nvAttribute = 0, .handlePasswd = {{ 0 }}, .indexPasswd = {{ 0 }}, .hexPasswd = false, .sapi_context = sapi_context }; bool result = init(argc, argv, &ctx); if (!result) { return 1; } return nv_space_define(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_nvlist.c000066400000000000000000000074641313543155100173330ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include "string-bytes.h" #include "log.h" #include "main.h" #include "options.h" #include "string-bytes.h" static bool nv_read_public(TSS2_SYS_CONTEXT *sapi_context, TPMI_RH_NV_INDEX nv_index) { TPM2B_NAME nv_name = TPM2B_TYPE_INIT(TPM2B_NAME, name); TPM2B_NV_PUBLIC nv_public = { { 0, } }; TPM_RC rval = Tss2_Sys_NV_ReadPublic(sapi_context, nv_index, 0, &nv_public, &nv_name, 0); if (rval != TPM_RC_SUCCESS) { LOG_ERR("NVReadPublic Failed ! ErrorCode: 0x%0x\n", rval); return false; } printf(" {\n"); printf("\tHash algorithm(nameAlg):%d\n ", nv_public.t.nvPublic.nameAlg); printf("\tThe Index attributes(attributes):0x%x\n ", nv_public.t.nvPublic.attributes.val); printf("\tThe size of the data area(dataSize):%d\n ", nv_public.t.nvPublic.dataSize); printf(" }\n"); return true; } static bool nv_list(TSS2_SYS_CONTEXT *sapi_context) { TPMI_YES_NO moreData; TPMS_CAPABILITY_DATA capabilityData; UINT32 property = string_bytes_endian_convert_32(TPM_HT_NV_INDEX); TPM_RC rval = Tss2_Sys_GetCapability(sapi_context, 0, TPM_CAP_HANDLES, property, TPM_PT_NV_INDEX_MAX, &moreData, &capabilityData, 0); if (rval != TPM_RC_SUCCESS) { LOG_ERR("GetCapability:Get NV Index list Error. TPM Error:0x%x", rval); return false; } printf("%d NV indexes defined.\n", capabilityData.data.handles.count); UINT32 i; for (i = 0; i < capabilityData.data.handles.count; i++) { printf("\n %d. NV Index: 0x%x\n", i, capabilityData.data.handles.handle[i]); bool result = nv_read_public(sapi_context, capabilityData.data.handles.handle[i]); if (!result) { return false; } } printf("\n"); return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void) argc; (void) argv; (void) envp; (void) opts; return nv_list(sapi_context) != 0; } tpm2-tools-2.1.0/tools/tpm2_nvread.c000066400000000000000000000162141313543155100172640ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include "log.h" #include "main.h" #include "options.h" #include "password_util.h" #include "string-bytes.h" typedef struct tpm_nvread_ctx tpm_nvread_ctx; struct tpm_nvread_ctx { UINT32 nv_index; UINT32 auth_handle; UINT32 size_to_read; UINT32 offset; TPM2B_AUTH handle_passwd; bool is_hex_password; TSS2_SYS_CONTEXT *sapi_context; }; static bool nv_read(tpm_nvread_ctx *ctx) { TPMS_AUTH_COMMAND session_data = { 0 }; TPMS_AUTH_RESPONSE session_data_out; TSS2_SYS_CMD_AUTHS sessions_data; TSS2_SYS_RSP_AUTHS sessions_data_out; TPM2B_MAX_NV_BUFFER nv_data = TPM2B_TYPE_INIT(TPM2B_MAX_NV_BUFFER, buffer); TPMS_AUTH_COMMAND *session_data_array[1]; TPMS_AUTH_RESPONSE *session_data_out_array[1]; session_data_array[0] = &session_data; session_data_out_array[0] = &session_data_out; sessions_data_out.rspAuths = &session_data_out_array[0]; sessions_data.cmdAuths = &session_data_array[0]; sessions_data_out.rspAuthsCount = 1; sessions_data.cmdAuthsCount = 1; session_data.sessionHandle = TPM_RS_PW; bool result = password_util_to_auth(&ctx->handle_passwd, ctx->is_hex_password, "handle password", &session_data.hmac); if (!result) { return false; } TPM_RC rval = Tss2_Sys_NV_Read(ctx->sapi_context, ctx->auth_handle, ctx->nv_index, &sessions_data, ctx->size_to_read, ctx->offset, &nv_data, &sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("Failed to read NVRAM area at index 0x%x (%d). Error:0x%x", ctx->nv_index, ctx->nv_index, rval); return false; } printf("\nThe size of data:%d\n", nv_data.t.size); int i; for (i = 0; i < nv_data.t.size; i++) printf(" %2.2x ", nv_data.t.buffer[i]); printf("\n"); return true; } /* -3 for NULL entry and P nor X are required */ #define ARG_CNT(optional) ((int)(2 * (sizeof(long_options)/sizeof(long_options[0]) - optional - 1))) static bool init(int argc, char *argv[], tpm_nvread_ctx *ctx) { struct option long_options[] = { { "index" , required_argument, NULL, 'x' }, { "authHandle" , required_argument, NULL, 'a' }, { "size" , required_argument, NULL, 's' }, { "offset" , required_argument, NULL, 'o' }, { "handlePasswd", required_argument, NULL, 'P' }, { "passwdInHex" , no_argument, NULL, 'X' }, { NULL , no_argument, NULL, 0 }, }; /* subtract 1 from argc to disregard argv[0] */ if ((argc - 1) < ARG_CNT(2) || (argc - 1) > ARG_CNT(0)) { showArgMismatch(argv[0]); return false; } int opt; bool result; while ((opt = getopt_long(argc, argv, "x:a:s:o:P:X", long_options, NULL)) != -1) { switch (opt) { case 'x': result = string_bytes_get_uint32(optarg, &ctx->nv_index); if (!result) { LOG_ERR("Could not convert NV index to number, got: \"%s\"", optarg); return false; } if (ctx->nv_index == 0) { LOG_ERR("NV Index cannot be 0"); return false; } break; case 'a': result = string_bytes_get_uint32(optarg, &ctx->auth_handle); if (!result) { LOG_ERR("Could not convert auth handle to number, got: \"%s\"", optarg); return false; } if (ctx->auth_handle == 0) { LOG_ERR("Auth handle cannot be 0"); return false; } break; case 'P': result = password_util_copy_password(optarg, "handle password", &ctx->handle_passwd); if (!result) { return false; } break; case 's': result = string_bytes_get_uint32(optarg, &ctx->size_to_read); if (!result) { LOG_ERR("Could not convert size to number, got: \"%s\"", optarg); return false; } break; case 'o': result = string_bytes_get_uint32(optarg, &ctx->offset); if (!result) { LOG_ERR("Could not convert offset to number, got: \"%s\"", optarg); return false; } break; case 'X': ctx->is_hex_password = true; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void)opts; (void)envp; tpm_nvread_ctx ctx = { .nv_index = 0, .auth_handle = TPM_RH_PLATFORM, .size_to_read = 0, .offset = 0, .handle_passwd = {{ 0 }}, .is_hex_password = false, .sapi_context = sapi_context }; bool result = init(argc, argv, &ctx); if (!result) { return 1; } return nv_read(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_nvreadlock.c000066400000000000000000000145011313543155100201320ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // Copyright (c) 2016, Atom Software Studios // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include "log.h" #include "main.h" #include "options.h" #include "password_util.h" #include "string-bytes.h" typedef struct tpm_nvreadlock_ctx tpm_nvreadlock_ctx; struct tpm_nvreadlock_ctx { UINT32 nv_index; UINT32 auth_handle; UINT32 size_to_read; UINT32 offset; TPM2B_AUTH handle_passwd; bool is_hex_passwd; TSS2_SYS_CONTEXT *sapi_context; }; static bool nv_readlock(tpm_nvreadlock_ctx *ctx) { TPMS_AUTH_COMMAND session_data; TPMS_AUTH_RESPONSE session_data_out; TSS2_SYS_CMD_AUTHS sessions_data; TSS2_SYS_RSP_AUTHS sessions_data_out; TPMS_AUTH_COMMAND *session_data_array[1]; TPMS_AUTH_RESPONSE *sessionDataOutArray[1]; session_data_array[0] = &session_data; sessionDataOutArray[0] = &session_data_out; sessions_data_out.rspAuths = &sessionDataOutArray[0]; sessions_data.cmdAuths = &session_data_array[0]; sessions_data_out.rspAuthsCount = 1; sessions_data.cmdAuthsCount = 1; session_data.sessionHandle = TPM_RS_PW; session_data.nonce.t.size = 0; session_data.hmac.t.size = 0; *((UINT8 *) ((void *) &session_data.sessionAttributes)) = 0; bool result = password_util_to_auth(&ctx->handle_passwd, ctx->is_hex_passwd, "handle password", &session_data.hmac); if (!result) { return false; } TPM_RC rval = Tss2_Sys_NV_ReadLock(ctx->sapi_context, ctx->auth_handle, ctx->nv_index, &sessions_data, &sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("Failed to lock NVRAM area at index 0x%x (%d).Error:0x%x", ctx->nv_index, ctx->nv_index, rval); return false; } return true; } #define ARG_CNT(optional) ((int)(2 * (sizeof(long_options)/sizeof(long_options[0]) - optional - 1))) static bool init(int argc, char *argv[], tpm_nvreadlock_ctx *ctx) { struct option long_options[] = { { "index" , required_argument, NULL, 'x' }, { "authHandle" , required_argument, NULL, 'a' }, { "handlePasswd", required_argument, NULL, 'P' }, { "passwdInHex" , no_argument, NULL, 'X' }, { NULL , no_argument, NULL, 0 }, }; /* subtract 1 from argc to disregard argv[0] */ if ((argc - 1) < ARG_CNT(1) || (argc - 1) > ARG_CNT(0)) { showArgMismatch(argv[0]); return false; } int opt; bool result; while ((opt = getopt_long(argc, argv, "x:a:P:Xp:d:hv", long_options, NULL)) != -1) { switch (opt) { case 'x': result = string_bytes_get_uint32(optarg, &ctx->nv_index); if (!result) { LOG_ERR("Could not convert NV index to number, got: \"%s\"", optarg); return false; } if (ctx->nv_index == 0) { LOG_ERR("NV Index cannot be 0"); return false; } break; case 'a': result = string_bytes_get_uint32(optarg, &ctx->auth_handle); if (!result) { LOG_ERR("Could not convert auth handle to number, got: \"%s\"", optarg); return false; } if (ctx->auth_handle == 0) { LOG_ERR("Auth handle cannot be 0"); return false; } break; case 'P': result = password_util_copy_password(optarg, "handle password", &ctx->handle_passwd); if (!result) { return false; } break; case 'X': ctx->is_hex_passwd = true; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void)opts; (void)envp; tpm_nvreadlock_ctx ctx = { .nv_index = 0, .auth_handle = TPM_RH_PLATFORM, .size_to_read = 0, .offset = 0, .handle_passwd = {{ 0 }}, .is_hex_passwd = false, .sapi_context = sapi_context }; bool result = init(argc, argv, &ctx); if (!result) { return 1; } return nv_readlock(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_nvrelease.c000066400000000000000000000137151313543155100177740ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include "log.h" #include "main.h" #include "options.h" #include "password_util.h" #include "string-bytes.h" typedef struct tpm_nvrelease_ctx tpm_nvrelease_ctx; struct tpm_nvrelease_ctx { UINT32 nv_index; UINT32 auth_handle; bool is_hex_password; TPM2B_AUTH handle_passwd; TSS2_SYS_CONTEXT *sapi_context; }; static bool nv_space_release(tpm_nvrelease_ctx *ctx) { TPMS_AUTH_COMMAND session_data; TSS2_SYS_CMD_AUTHS sessions_data; TPMS_AUTH_COMMAND *session_data_array[1]; session_data_array[0] = &session_data; sessions_data.cmdAuths = &session_data_array[0]; sessions_data.cmdAuthsCount = 1; session_data.sessionHandle = TPM_RS_PW; session_data.nonce.t.size = 0; session_data.hmac.t.size = 0; *((UINT8 *) ((void *) &session_data.sessionAttributes)) = 0; bool result = password_util_to_auth(&ctx->handle_passwd, ctx->is_hex_password, "handle password", &session_data.hmac); if (!result) { return false; } TPM_RC rval = Tss2_Sys_NV_UndefineSpace(ctx->sapi_context, ctx->auth_handle, ctx->nv_index, &sessions_data, 0); if (rval != TPM_RC_SUCCESS) { LOG_ERR("Failed to release NV area at index 0x%x (%d).Error:0x%x", ctx->nv_index, ctx->nv_index, rval); return false; } LOG_INFO("Success to release NV area at index 0x%x (%d).\n", ctx->nv_index, ctx->nv_index); return true; } #define ARG_CNT(optional) ((int)(2 * (sizeof(long_options)/sizeof(long_options[0]) - optional - 1))) static bool init(int argc, char* argv[], tpm_nvrelease_ctx *ctx) { struct option long_options[] = { { "index" , required_argument, NULL, 'x' }, { "authHandle" , required_argument, NULL, 'a' }, { "handlePasswd", required_argument, NULL, 'P' }, { "passwdInHex" , no_argument, NULL, 'X' }, { NULL , no_argument, NULL, 0 }, }; /* subtract 1 from argc to disregard argv[0] */ if ((argc - 1) < ARG_CNT(2) || (argc - 1) > ARG_CNT(0)) { showArgMismatch(argv[0]); return false; } int opt; bool result; while ((opt = getopt_long(argc, argv, "x:a:s:o:P:X", long_options, NULL)) != -1) { switch (opt) { case 'x': result = string_bytes_get_uint32(optarg, &ctx->nv_index); if (!result) { LOG_ERR("Could not convert NV index to number, got: \"%s\"", optarg); return false; } if (ctx->nv_index == 0) { LOG_ERR("NV Index cannot be 0"); return false; } break; case 'a': result = string_bytes_get_uint32(optarg, &ctx->auth_handle); if (!result) { LOG_ERR("Could not convert auth handle to number, got: \"%s\"", optarg); return false; } if (ctx->auth_handle == 0) { LOG_ERR("Auth handle cannot be 0"); return false; } break; case 'P': result = password_util_copy_password(optarg, "handle password", &ctx->handle_passwd); if (!result) { return false; } break; case 'X': ctx->is_hex_password = true; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void)opts; (void)envp; tpm_nvrelease_ctx ctx = { .auth_handle = 0, .nv_index = 0, .is_hex_password = false, .sapi_context = sapi_context }; bool result = init(argc, argv, &ctx); if (!result) { return 1; } return nv_space_release(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_nvwrite.c000066400000000000000000000167741313543155100175160ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include "log.h" #include "files.h" #include "main.h" #include "options.h" #include "password_util.h" #include "string-bytes.h" typedef struct tpm_nvwrite_ctx tpm_nvwrite_ctx; struct tpm_nvwrite_ctx { UINT32 nv_index; UINT32 auth_handle; UINT16 data_size; UINT8 nv_buffer[MAX_NV_INDEX_SIZE]; TPM2B_AUTH handle_passwd; bool hex_passwd; char input_file[PATH_MAX]; TSS2_SYS_CONTEXT *sapi_context; }; static int nv_write(tpm_nvwrite_ctx *ctx) { TPMS_AUTH_COMMAND session_data; TPMS_AUTH_RESPONSE session_data_out; TSS2_SYS_CMD_AUTHS sessions_data; TSS2_SYS_RSP_AUTHS sessions_data_out; TPM2B_MAX_NV_BUFFER nv_write_data; TPMS_AUTH_COMMAND *session_data_array[1] = { &session_data }; TPMS_AUTH_RESPONSE *session_data_out_array[1] = { &session_data_out }; sessions_data_out.rspAuths = &session_data_out_array[0]; sessions_data.cmdAuths = &session_data_array[0]; sessions_data_out.rspAuthsCount = 1; sessions_data.cmdAuthsCount = 1; session_data.sessionHandle = TPM_RS_PW; session_data.nonce.t.size = 0; session_data.hmac.t.size = 0; *((UINT8 *) ((void *) &session_data.sessionAttributes)) = 0; bool result = password_util_to_auth(&ctx->handle_passwd, ctx->hex_passwd, "handle password", &session_data.hmac); if (!result) { return false; } while (ctx->data_size > 0) { nv_write_data.t.size = ctx->data_size > MAX_NV_BUFFER_SIZE ? MAX_NV_BUFFER_SIZE : ctx->data_size; LOG_INFO("The data(size=%d) to be written:\n", nv_write_data.t.size); UINT16 i; UINT16 offset = 0; for (i = 0; i < nv_write_data.t.size; i++) { nv_write_data.t.buffer[i] = ctx->nv_buffer[offset + i]; printf("%02x ", ctx->nv_buffer[offset + i]); } printf("\n\n"); TPM_RC rval = Tss2_Sys_NV_Write(ctx->sapi_context, ctx->auth_handle, ctx->nv_index, &sessions_data, &nv_write_data, offset, &sessions_data_out); if (rval != TSS2_RC_SUCCESS) { LOG_ERR( "Failed to write NV area at index 0x%x (%d) offset 0x%x. Error:0x%x", ctx->nv_index, ctx->nv_index, offset, rval); return false; } LOG_INFO("Success to write NV area at index 0x%x (%d) offset 0x%x.", ctx->nv_index, ctx->nv_index, offset); ctx->data_size -= nv_write_data.t.size; offset += nv_write_data.t.size; } return true; } #define ARG_CNT(optional) ((int)(2 * (sizeof(long_options)/sizeof(long_options[0]) - optional - 1))) static bool init(int argc, char *argv[], tpm_nvwrite_ctx *ctx) { struct option long_options[] = { { "index" , required_argument, NULL, 'x' }, { "authHandle" , required_argument, NULL, 'a' }, { "file" , required_argument, NULL, 'f' }, { "handlePasswd", required_argument, NULL, 'P' }, { "passwdInHex" , no_argument, NULL, 'X' }, { NULL , no_argument, NULL, 0 }, }; /* subtract 1 from argc to disregard argv[0] */ if ((argc - 1) < ARG_CNT(2) || (argc - 1) > ARG_CNT(0)) { showArgMismatch(argv[0]); return false; } int opt; bool result; while ((opt = getopt_long(argc, argv, "x:a:f:P:X", long_options, NULL)) != -1) { switch (opt) { case 'x': result = string_bytes_get_uint32(optarg, &ctx->nv_index); if (!result) { LOG_ERR("Could not convert NV index to number, got: \"%s\"", optarg); return false; } if (ctx->nv_index == 0) { LOG_ERR("NV Index cannot be 0"); return false; } break; case 'a': result = string_bytes_get_uint32(optarg, &ctx->auth_handle); if (!result) { LOG_ERR("Could not convert auth handle to number, got: \"%s\"", optarg); return false; } if (ctx->auth_handle == 0) { LOG_ERR("Auth handle cannot be 0"); return false; } break; case 'f': snprintf(ctx->input_file, sizeof(ctx->input_file), "%s", optarg); break; case 'P': result = password_util_copy_password(optarg, "handle password", &ctx->handle_passwd); if (!result) { return false; } break; case 'X': ctx->hex_passwd = true; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } } ctx->data_size = MAX_NV_INDEX_SIZE; result = files_load_bytes_from_file(ctx->input_file, ctx->nv_buffer, &ctx->data_size); if (!result) { LOG_ERR("Failed to read data from %s\n", ctx->input_file); return -false; } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void)opts; (void)envp; tpm_nvwrite_ctx ctx = { .nv_index = 0, .auth_handle = TPM_RH_PLATFORM, .data_size = 0, .handle_passwd = {{ 0 }}, .hex_passwd = false, .sapi_context = sapi_context }; bool result = init(argc, argv, &ctx); if (!result) { return 1; } return nv_write(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_quote.c000066400000000000000000000367711313543155100171540ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include #include #include #include "files.h" #include "log.h" #include "main.h" #include "pcr.h" #include "string-bytes.h" typedef struct { int size; UINT32 id[24]; } PCR_LIST; TPMS_AUTH_COMMAND sessionData; bool hexPasswd = false; char outFilePath[PATH_MAX]; TPM2B_DATA qualifyingData = {{0,}}; TPML_PCR_SELECTION pcrSelections; void PrintBuffer( UINT8 *buffer, UINT32 size ) { UINT32 i; for( i = 0; i < size; i++ ) { printf( "%2.2x", buffer[i] ); } printf( "\n" ); } #if 0 void PrintTPM2B_ATTEST( TPM2B_ATTEST *attest ) { TPMS_ATTEST *s_att = (TPMS_ATTEST *)&attest->t.attestationData[0]; printf( "ATTEST_2B:\n" ); printf( "\tsize = 0x%4.4x\n", attest->t.size ); //already little endian printf( "\tattestationData(TPMS_ATTEST):\n" ); printf( "\t\tmagic = 0x%8.8x\n", ntohl(s_att->magic) );//big endian printf( "\t\ttype = 0x%4.4x\n", ntohs(s_att->type) ); printf( "\t\tqualifiedSigner(NAME_2B):\n" ); printf( "\t\t\tsize = 0x%4.4x\n", ntohs(s_att->qualifiedSigner.t.size) ); printf( "\t\t\tname = " ); PrintBuffer( s_att->qualifiedSigner.b.buffer, ntohs(s_att->qualifiedSigner.b.size) ); s_att = (TPMS_ATTEST *)(((BYTE *)s_att) - sizeof(s_att->qualifiedSigner.t) + ntohs(s_att->qualifiedSigner.t.size) + 2); printf( "\t\textraData(DATA_2B):\n" ); printf( "\t\t\tsize = 0x%4.4x\n", ntohs(s_att->extraData.t.size) ); printf( "\t\t\tbuffer = " ); PrintBuffer( s_att->extraData.b.buffer, ntohs(s_att->extraData.b.size) ); s_att = (TPMS_ATTEST *)(((BYTE *)s_att) - sizeof(s_att->extraData.t) + ntohs(s_att->extraData.t.size) + 2); printf( "\t\tclockInfo(TPMS_CLOCK_INFO):\n" ); printf( "\t\t\tclock = 0x%16.16lx\n", s_att->clockInfo.clock ); printf( "\t\t\tresetCount = 0x%8.8x\n", ntohl(s_att->clockInfo.resetCount) ); printf( "\t\t\trestartCount = 0x%8.8x\n", ntohl(s_att->clockInfo.restartCount) ); printf( "\t\t\tsafe = 0x%2.2x\n", s_att->clockInfo.safe ); s_att = (TPMS_ATTEST *)(((BYTE *)s_att) - 7); printf( "\t\tfirmwareVersion = 0x%16.16lx\n", s_att->firmwareVersion ); printf( "\t\tattested(TPMS_QUOTE_INFO):\n" ); printf( "\t\t\tpcrSelect(TPML_PCR_SELECTION):\n" ); printf( "\t\t\t\tcount = 0x%8.8x\n", ntohl(s_att->attested.quote.pcrSelect.count) ); for ( UINT32 i = 0; i < ntohl(s_att->attested.quote.pcrSelect.count); i++ ) { TPMS_PCR_SELECTION *s = &s_att->attested.quote.pcrSelect.pcrSelections[i]; printf( "\t\t\t\tpcrSelections[%d](TPMS_PCR_SELECTION):\n", i ); printf( "\t\t\t\t\thash = 0x%4.4x\n", ntohs(s->hash) ); printf( "\t\t\t\t\tsizeofSelect = 0x%2.2x\n", s->sizeofSelect ); printf( "\t\t\t\t\tpcrSelect = " ); PrintBuffer( s->pcrSelect, s->sizeofSelect ); } s_att = (TPMS_ATTEST *)(((BYTE *)s_att) - sizeof(s_att->attested.quote.pcrSelect) + ntohl(s_att->attested.quote.pcrSelect.count) * sizeof(TPMS_PCR_SELECTION) + 4 ); printf( "\t\t\tpcrDigest(DIGEST_2B):\n" ); printf( "\t\t\t\tsize = 0x%4.4x\n", ntohs(s_att->attested.quote.pcrDigest.t.size) ); printf( "\t\t\t\tbuffer = " ); PrintBuffer( s_att->attested.quote.pcrDigest.b.buffer, ntohs(s_att->attested.quote.pcrDigest.b.size) ); } void PrintTPMT_SIGNATURE( TPMT_SIGNATURE *sig ) { printf( "TPMT_SIGNATURE:\n" ); printf( "\tsigAlg = 0x%4.4x\n", sig->sigAlg ); printf( "\tsignature(TPMU_SIGNATURE):\n" ); switch ( sig->sigAlg ) { case TPM_ALG_RSASSA: case TPM_ALG_RSAPSS: printf( "\t\tTPMS_SIGNATURE_RSA:\n" ); printf( "\t\t\thash = 0x%4.4x\n", sig->signature.rsassa.hash ); printf( "\t\t\tsig(PUBLIC_KEY_RSA_2B):\n" ); printf( "\t\t\t\tsize = 0x%4.4x\n", sig->signature.rsassa.sig.t.size ); printf( "\t\t\t\tbuffer = " ); PrintSizedBuffer( &sig->signature.rsassa.sig.b ); break; case TPM_ALG_ECDSA: case TPM_ALG_ECDAA: case TPM_ALG_SM2: case TPM_ALG_ECSCHNORR: printf( "\t\tTPMS_SIGNATURE_ECC:\n" ); printf( "\t\t\thash = 0x%4.4x\n", sig->signature.ecdsa.hash); printf( "\t\t\tsignatureR(TPM2B_ECC_PARAMETER):\n" ); printf( "\t\t\t\tsize = 0x%4.4x\n", sig->signature.ecdsa.signatureR.t.size ); printf( "\t\t\t\tbuffer = " ); PrintSizedBuffer( &sig->signature.ecdsa.signatureR.b ); printf( "\t\t\tsignatureS(TPM2B_ECC_PARAMETER):\n" ); printf( "\t\t\t\tsize = 0x%4.4x\n", sig->signature.ecdsa.signatureS.t.size ); printf( "\t\t\t\tbuffer = " ); PrintSizedBuffer( &sig->signature.ecdsa.signatureS.b ); break; case TPM_ALG_HMAC: printf( "\t\tTPMS_HA:\n" ); printf( "\t\t\thashAlg = 0x%4.4x\n", sig->signature.hmac.hashAlg); printf( "\t\t\tdigest = " ); UINT16 size = 0; switch ( sig->signature.hmac.hashAlg ) { case TPM_ALG_SHA1: size = SHA1_DIGEST_SIZE; break; case TPM_ALG_SHA256: size = SHA256_DIGEST_SIZE; break; case TPM_ALG_SHA384: size = SHA384_DIGEST_SIZE; break; case TPM_ALG_SHA512: size = SHA512_DIGEST_SIZE; break; case TPM_ALG_SM3_256: size = SM3_256_DIGEST_SIZE; break; } PrintBuffer( (BYTE *)&sig->signature.hmac.digest, size ); break; } } #endif UINT16 calcSizeofTPM2B_ATTEST( TPM2B_ATTEST *attest ) { return 2 + attest->b.size; } UINT16 calcSizeofTPMT_SIGNATURE( TPMT_SIGNATURE *sig ) { UINT16 size = 2; switch ( sig->sigAlg ) { case TPM_ALG_RSASSA: case TPM_ALG_RSAPSS: size += 2 + 2 + sig->signature.rsassa.sig.t.size; break; case TPM_ALG_ECDSA: case TPM_ALG_ECDAA: case TPM_ALG_SM2: case TPM_ALG_ECSCHNORR: size += 2 + 2*sizeof(TPM2B_ECC_PARAMETER); break; case TPM_ALG_HMAC: size += 2; switch ( sig->signature.hmac.hashAlg ) { case TPM_ALG_SHA1: size += SHA1_DIGEST_SIZE; break; case TPM_ALG_SHA256: size += SHA256_DIGEST_SIZE; break; case TPM_ALG_SHA384: size += SHA384_DIGEST_SIZE; break; case TPM_ALG_SHA512: size += SHA512_DIGEST_SIZE; break; case TPM_ALG_SM3_256: size += SM3_256_DIGEST_SIZE; break; default: size = 0; break; } break; default: size = 0; break; } return size > sizeof(*sig) ? sizeof(*sig) : size; } int quote(TSS2_SYS_CONTEXT *sapi_context, TPM_HANDLE akHandle, TPML_PCR_SELECTION *pcrSelection) { UINT32 rval; TPMT_SIG_SCHEME inScheme; TPMS_AUTH_RESPONSE sessionDataOut; TSS2_SYS_CMD_AUTHS sessionsData; TSS2_SYS_RSP_AUTHS sessionsDataOut; TPM2B_ATTEST quoted = TPM2B_TYPE_INIT(TPM2B_ATTEST, attestationData); TPMT_SIGNATURE signature; TPMS_AUTH_COMMAND *sessionDataArray[1]; TPMS_AUTH_RESPONSE *sessionDataOutArray[1]; sessionDataArray[0] = &sessionData; sessionDataOutArray[0] = &sessionDataOut; sessionsDataOut.rspAuths = &sessionDataOutArray[0]; sessionsData.cmdAuths = &sessionDataArray[0]; sessionsDataOut.rspAuthsCount = 1; sessionsData.cmdAuthsCount = 1; sessionData.sessionHandle = TPM_RS_PW; sessionData.nonce.t.size = 0; *( (UINT8 *)((void *)&sessionData.sessionAttributes ) ) = 0; if (sessionData.hmac.t.size > 0 && hexPasswd) { sessionData.hmac.t.size = sizeof(sessionData.hmac) - 2; if (hex2ByteStructure((char *)sessionData.hmac.t.buffer, &sessionData.hmac.t.size, sessionData.hmac.t.buffer) != 0) { printf( "Failed to convert Hex format password for AK Passwd.\n"); return -1; } } inScheme.scheme = TPM_ALG_NULL; memset( (void *)&signature, 0, sizeof(signature) ); rval = Tss2_Sys_Quote(sapi_context, akHandle, &sessionsData, &qualifyingData, &inScheme, pcrSelection, "ed, &signature, &sessionsDataOut ); if(rval != TPM_RC_SUCCESS) { printf("\nQuote Failed ! ErrorCode: 0x%0x\n\n", rval); return -1; } printf( "\nquoted:\n " ); string_bytes_print_tpm2b( (TPM2B *)"ed ); //PrintTPM2B_ATTEST("ed); printf( "\nsignature:\n " ); PrintBuffer( (UINT8 *)&signature, sizeof(signature) ); //PrintTPMT_SIGNATURE(&signature); FILE *fp = fopen(outFilePath,"w+"); if(NULL == fp) { printf("OutFile: %s Can Not Be Created !\n",outFilePath); return -2; } if(fwrite("ed, calcSizeofTPM2B_ATTEST("ed), 1 ,fp) != 1) { fclose(fp); printf("OutFile: %s Write quoted Data In Error!\n",outFilePath); return -3; } if(fwrite(&signature, calcSizeofTPMT_SIGNATURE(&signature), 1, fp) != 1) { fclose(fp); printf("OutFile: %s Write signature Data In Error!\n",outFilePath); return -4; } fclose(fp); return 0; } int execute_tool (int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void) envp; (void) opts; int opt = -1; const char *optstring = "hvk:c:P:l:g:L:o:Xq:"; static struct option long_options[] = { {"help",0,NULL,'h'}, {"version",0,NULL,'v'}, {"akHandle",1,NULL,'k'}, {"akContext",1,NULL,'c'}, {"akPassword",1,NULL,'P'}, //add ak auth {"idList",1,NULL,'l'}, {"algorithm",1,NULL,'g'}, {"selList",1,NULL,'L'}, {"outFile",1,NULL,'o'}, {"passwdInHex",0,NULL,'X'}, {"qualifyData",1,NULL,'q'}, {0,0,0,0} }; char *contextFilePath = NULL; TPM_HANDLE akHandle; int returnVal = 0; int flagCnt = 0; int k_flag = 0, c_flag = 0, P_flag = 0, l_flag = 0, g_flag = 0, L_flag = 0, o_flag = 0; if(argc == 1) { LOG_ERR("Invalid usage, try --help for help!"); return 0; } while((opt = getopt_long(argc,argv,optstring,long_options,NULL)) != -1) { switch(opt) { case 'k': if(!string_bytes_get_uint32(optarg,&akHandle)) { showArgError(optarg, argv[0]); returnVal = -1; break; } k_flag = 1; break; case 'c': contextFilePath = optarg; if(contextFilePath == NULL || contextFilePath[0] == '\0') { showArgError(optarg, argv[0]); returnVal = -2; break; } printf("contextFile = %s\n", contextFilePath); c_flag = 1; break; case 'P': sessionData.hmac.t.size = sizeof(sessionData.hmac.t) - 2; if(str2ByteStructure(optarg,&sessionData.hmac.t.size,sessionData.hmac.t.buffer) != 0) { showArgError(optarg, argv[0]); returnVal = -3; break; } P_flag = 1; break; case 'l': if(pcr_parse_list(optarg, strlen(optarg), &pcrSelections.pcrSelections[0]) != 0) { showArgError(optarg, argv[0]); returnVal = -4; break; } l_flag = 1; break; case 'g': if(!string_bytes_get_uint16(optarg,&pcrSelections.pcrSelections[0].hash)) { showArgError(optarg, argv[0]); returnVal = -5; break; } pcrSelections.count = 1; g_flag = 1; break; case 'L': if(pcr_parse_selections(optarg, &pcrSelections) != 0) { showArgError(optarg, argv[0]); returnVal = -15; break; } L_flag = 1; break; case 'o': snprintf(outFilePath, sizeof(outFilePath), "%s", optarg); if(files_does_file_exist(outFilePath)) { showArgError(optarg, argv[0]); returnVal = -6; break; } o_flag = 1; break; case 'X': hexPasswd = true; break; case 'q': qualifyingData.t.size = sizeof(qualifyingData) - 2; if(hex2ByteStructure(optarg,&qualifyingData.t.size,qualifyingData.t.buffer) != 0) { showArgError(optarg, argv[0]); returnVal = -14; break; } break; case ':': // printf("Argument %c needs a value!\n",optopt); returnVal = -9; break; case '?': // printf("Unknown Argument: %c\n",optopt); returnVal = -10; break; //default: // break; } if(returnVal) break; }; if(returnVal != 0) return returnVal; flagCnt = k_flag + c_flag + l_flag + g_flag + L_flag + o_flag; if(((flagCnt == 3 && L_flag) || (flagCnt == 4 && (g_flag && l_flag))) && (k_flag || c_flag) && o_flag) { if(P_flag == 0) sessionData.hmac.t.size = 0; if(c_flag) returnVal = file_load_tpm_context_from_file(sapi_context, &akHandle, contextFilePath) != true; if(returnVal == TPM_RC_SUCCESS) returnVal = quote(sapi_context, akHandle, &pcrSelections); if(returnVal) return -12; } else { showArgMismatch(argv[0]); return -13; } return 0; } tpm2-tools-2.1.0/tools/tpm2_rc_decode.c000066400000000000000000000211261313543155100177120ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2016, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include "options.h" #include "log.h" #include "rc-decode.h" #define TPM_RC_MAX 0xffffffff TPM_RC str_to_tpm_rc (const char *rc_str) { uintmax_t rc_read = 0; char *end_ptr = NULL; rc_read = strtoumax (rc_str, &end_ptr, 0); if (rc_read > TPM_RC_MAX) { LOG_ERR("invalid TPM_RC"); exit (1); } /* apply the TPM_RC_MAX mask to the possibly larger uintmax_t */ return rc_read & TPM_RC_MAX; } int process_cmdline (int argc, char *argv[], char *envp[]) { int opt = -1; const char *optstring = "hv"; static struct option long_options[] = { { "help", 0 , NULL, 'h' }, { "version", 0, NULL, 'v' }, { 0 } }; while ((opt = getopt_long (argc, argv, optstring, long_options, NULL)) != -1) { switch (opt) { case 'h': execute_man (argv[0], envp); exit (0); case 'v': showVersion (argv[0]); exit (0); case '?': exit (1); } } return optind; } /* Dump the hex, identifier and description for the format zero / VER1 error * provided in TPM_RC parameter. */ int print_tpm_rc_format_zero (TPM_RC rc) { TPM_RC rc_tmp; tpm2_rc_entry_t *entry; rc_tmp = tpm2_rc_get_code_7bit (rc); if (tpm2_rc_is_vendor_defined (rc)) { LOG_ERR("vendor defined TPM_RCs are not supported"); return -1; } else if (tpm2_rc_is_warning_code (rc)) { entry = tpm2_get_warn_entry (rc_tmp); if (entry) printf ("format 0 warning code\n hex: 0x%02x\n name: %s\n " "description: %s\n", rc_tmp, entry->name, entry->description); else printf ("failed to decode TPM_RC warning: 0x%x\n", rc_tmp); } else if (tpm2_rc_is_error_code (rc)) { entry = tpm2_get_fmt0_entry (rc_tmp); if (entry) printf ("format 0 error code\n hex: 0x%02x\n name: %s\n " "description: %s\n", rc_tmp, entry->name, entry->description); else printf ("failed to decode TPM_RC error: 0x%02x\n", rc_tmp); } else if (tpm2_rc_is_tpm12 (rc_tmp)) { LOG_ERR("version 1.2 TPM_RCs are not supported"); return -1; } else { LOG_ERR("Unknown TPM_RC format"); return -1; } /* decode warning / error code */ return 0; } /* Dump the hex, identifier and description for the format one / FMT1 error * as well as the parameter, handle or session data. */ int print_tpm_rc_format_one (TPM_RC rc) { TPM_RC rc_tmp; tpm2_rc_entry_t *entry; printf ("format 1 error code\n"); rc_tmp = tpm2_rc_get_code_6bit (rc); printf (" hex: 0x%02x\n", rc_tmp); /* decode error message */ entry = tpm2_get_fmt1_entry (rc_tmp); if (!entry) { printf ("Unknown TPM_RC\n"); return -1; } printf (" identifier: %s\n description: %s\n", entry->name, entry->description); /* decode parameter / handle / session number */ if (tpm2_rc_is_error_code_with_parameter (rc)) { rc_tmp = tpm2_rc_get_parameter_number (rc); entry = tpm2_get_parameter_entry (rc_tmp); if (!entry) { printf ("Unknown TPM_RC parameter number: 0x%03x\n", rc_tmp); return -1; } printf ("parameter\n hex: 0x%03x\n identifier: %s\n " "description: %s\n", rc_tmp, entry->name, entry->description); } else if (tpm2_rc_is_error_code_with_handle (rc)) { rc_tmp = tpm2_rc_get_handle_number (rc); entry = tpm2_get_handle_entry (rc_tmp); if (!entry) { printf ("Unkonwn TPM_RC handle number: 0x%03x\n", rc_tmp); return -1; } printf ("handle\n hex:0x%03x\n identifier: %s\n " "description: %s\n", rc_tmp, entry->name, entry->description); } else if (tpm2_rc_is_error_code_with_session (rc)) { rc_tmp = tpm2_rc_get_session_number (rc); entry = tpm2_get_session_entry (rc_tmp); if (!entry) { printf ("Unknown TPM_RC session number: 0x%03x\n", rc_tmp); return -1; } printf ("session\n hex: 0x%03x\n identifier: %s\n " "description: %s\n", rc_tmp, entry->name, entry->description); } return 0; } /* Dump the hex, identifier and description for the TSS defined layer * indicator in the provided TPM_RC. */ int print_tpm_rc_tss_layer (TPM_RC rc) { TPM_RC rc_tmp; tpm2_rc_entry_t *entry; int ret; rc_tmp = tpm2_rc_get_layer (rc); /* Currently no entry for 0x0 layer, assume it's directly from the TPM? */ printf ("error layer\n hex: 0x%x\n", rc_tmp); entry = tpm2_get_layer_entry (rc_tmp); if (entry) { printf (" identifier: %s\n description: %s\n", entry->name, entry->description); ret = 0; } else { printf ("failed to decode TPM_RC layer: 0x%x\n", rc_tmp); ret = -1; } return ret; } /* Dump the hex, identifier string and description for the TSS defined * base error code in the provided TPM_RC. */ int print_tpm_rc_tss_error_code (TPM_RC rc) { TPM_RC rc_tmp; tpm2_rc_entry_t *entry; int ret; entry = tpm2_get_tss_base_rc_entry (rc); if (entry) { printf ("base error code\n identifier: %s\n description: %s\n", entry->name, entry->description); ret = 0; } else { rc_tmp = tpm2_rc_get_tss_err_code (rc); printf ("failed to decode TPM_RC error code: 0x%x\n", rc_tmp); ret = -1; } return ret; } /* Top level function to dump human readable data about TPM_RCs as defined * in the TPM2 Part 2: Structures, Table 17.. */ int print_tpm_rc_tpm_error_code (TPM_RC rc) { if (tpm2_rc_is_format_zero (rc)) print_tpm_rc_format_zero (rc); else if (tpm2_rc_is_format_one (rc)) print_tpm_rc_format_one (rc); else { LOG_ERR("Unknown TPM_RC format"); return -1; } return 0; } /* Top level function to dump human readable data about TPM_RCs. */ int print_tpm_rc (TPM_RC rc) { int ret; TPM_RC rc_tmp; /* Determine which layer in the stack produced the error */ rc_tmp = tpm2_rc_get_layer (rc); ret = print_tpm_rc_tss_layer (rc); switch (rc_tmp) { case TSS2_SYS_ERROR_LEVEL: case TSS2_TCTI_ERROR_LEVEL: ret = print_tpm_rc_tss_error_code (rc); break; case TSS2_SYS_PART2_ERROR_LEVEL: case TSS2_TPM_ERROR_LEVEL: ret = print_tpm_rc_tpm_error_code (rc); break; default: break; } return ret; } int main (int argc, char *argv[], char *envp[]) { TPM_RC rc = 0; int pos_ind = -1, ret = -1; pos_ind = process_cmdline (argc, argv, envp); if (pos_ind + 1 != argc) { LOG_ERR ("No error code provided, try --help"); exit (1); } rc = str_to_tpm_rc (argv[pos_ind]); ret = print_tpm_rc (rc); exit (ret); } tpm2-tools-2.1.0/tools/tpm2_readpublic.c000066400000000000000000000131021313543155100201100ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include "files.h" #include "log.h" #include "main.h" #include "options.h" #include "password_util.h" #include "string-bytes.h" typedef struct tpm_readpub_ctx tpm_readpub_ctx; struct tpm_readpub_ctx { TPMI_DH_OBJECT objectHandle; char outFilePath[PATH_MAX]; TSS2_SYS_CONTEXT *sapi_context; }; #define ARRAY_LEN(x) (sizeof(x)/sizeof(x[0])) static int read_public_and_save(tpm_readpub_ctx *ctx) { TPMS_AUTH_RESPONSE session_out_data; TSS2_SYS_RSP_AUTHS sessions_out_data; TPMS_AUTH_RESPONSE *session_out_data_array[1]; TPM2B_PUBLIC public = { { 0, } }; TPM2B_NAME name = TPM2B_TYPE_INIT(TPM2B_NAME, name); TPM2B_NAME qualified_name = TPM2B_TYPE_INIT(TPM2B_NAME, name); session_out_data_array[0] = &session_out_data; sessions_out_data.rspAuths = &session_out_data_array[0]; sessions_out_data.rspAuthsCount = ARRAY_LEN(session_out_data_array); TPM_RC rval = Tss2_Sys_ReadPublic(ctx->sapi_context, ctx->objectHandle, 0, &public, &name, &qualified_name, &sessions_out_data); if (rval != TPM_RC_SUCCESS) { LOG_ERR("TPM2_ReadPublic error: rval = 0x%0x", rval); return false; } printf("\nTPM2_ReadPublic OutPut: \n"); printf("name: \n"); UINT16 i; for (i = 0; i < name.t.size; i++) printf("%02x ", name.t.name[i]); printf("\n"); printf("qualified_name: \n"); for (i = 0; i < qualified_name.t.size; i++) printf("%02x ", qualified_name.t.name[i]); printf("\n"); /* TODO fix serialization */ return files_save_bytes_to_file(ctx->outFilePath, (UINT8 *) &public, sizeof(public)); } static bool init(int argc, char *argv[], tpm_readpub_ctx * ctx) { const char *short_options = "H:o:c:"; static struct option long_options[] = { {"object", required_argument, NULL,'H'}, {"opu", required_argument, NULL,'o'}, {"contextObject", required_argument, NULL,'c'}, {NULL, no_argument, NULL, '\0'} }; struct { UINT8 H : 1; UINT8 o : 1; UINT8 c : 1; UINT8 unused : 5; } flags = { 0 }; if (argc == 1) { showArgMismatch(argv[0]); return 0; } int opt = -1; bool result; char context_file[PATH_MAX] = {0}; while ((opt = getopt_long(argc, argv, short_options, long_options, NULL)) != -1) { switch (opt) { case 'H': result = string_bytes_get_uint32(optarg, &ctx->objectHandle); if (!result) { return false; } flags.H = 1; break; case 'o': result = files_does_file_exist(optarg); if (result) { return false; } snprintf(ctx->outFilePath, sizeof(ctx->outFilePath), "%s", optarg); flags.o = 1; break; case 'c': snprintf(context_file, sizeof(context_file), "%s", optarg); flags.c = 1; break; } }; if (!((flags.H || flags.c) && flags.o)) { showArgMismatch(argv[0]); return false; } if (flags.c) { result = file_load_tpm_context_from_file(ctx->sapi_context, &ctx->objectHandle, context_file); if (!result) { return false; } } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void)opts; (void)envp; tpm_readpub_ctx ctx = { .objectHandle = 0, .outFilePath = { 0 }, .sapi_context = sapi_context }; bool result = init(argc, argv, &ctx); if (!result) { return 1; } return read_public_and_save(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_rsadecrypt.c000066400000000000000000000162141313543155100201650ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include "files.h" #include "log.h" #include "main.h" #include "options.h" #include "password_util.h" #include "string-bytes.h" typedef struct tpm_rsadecrypt_ctx tpm_rsadecrypt_ctx; struct tpm_rsadecrypt_ctx { TPMI_DH_OBJECT key_handle; TPMS_AUTH_COMMAND session_data; TPM2B_PUBLIC_KEY_RSA cipher_text; char output_file_path[PATH_MAX]; TSS2_SYS_CONTEXT *sapi_context; }; static bool rsa_decrypt_and_save(tpm_rsadecrypt_ctx *ctx) { TPMT_RSA_DECRYPT inScheme; TPM2B_DATA label; TPM2B_PUBLIC_KEY_RSA message = TPM2B_TYPE_INIT(TPM2B_PUBLIC_KEY_RSA, buffer); TSS2_SYS_CMD_AUTHS sessions_data; TPMS_AUTH_RESPONSE session_data_out; TSS2_SYS_RSP_AUTHS sessions_data_out; TPMS_AUTH_COMMAND *session_data_array[1]; TPMS_AUTH_RESPONSE *session_data_out_array[1]; session_data_array[0] = &ctx->session_data; sessions_data.cmdAuths = &session_data_array[0]; session_data_out_array[0] = &session_data_out; sessions_data_out.rspAuths = &session_data_out_array[0]; sessions_data_out.rspAuthsCount = 1; sessions_data.cmdAuthsCount = 1; inScheme.scheme = TPM_ALG_RSAES; label.t.size = 0; TPM_RC rval = Tss2_Sys_RSA_Decrypt(ctx->sapi_context, ctx->key_handle, &sessions_data, &ctx->cipher_text, &inScheme, &label, &message, &sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("rsaDecrypt failed, error code: 0x%x", rval); return false; } return files_save_bytes_to_file(ctx->output_file_path, message.t.buffer, message.t.size); } static bool init(int argc, char *argv[], tpm_rsadecrypt_ctx *ctx) { const char *optstring = "k:P:I:o:c:X"; static struct option long_options[] = { { "keyHandle", required_argument, NULL, 'k'}, { "pwdk", required_argument, NULL, 'P'}, { "inFile", required_argument, NULL, 'I'}, { "outFile", required_argument, NULL, 'o'}, { "keyContext", required_argument, NULL, 'c'}, { "passwdInHex", no_argument, NULL, 'X'}, { NULL, no_argument, NULL, '\0'} }; struct { UINT8 k : 1; UINT8 P : 1; UINT8 I : 1; UINT8 c : 1; UINT8 o : 1; UINT8 unused : 3; } flags = { 0 }; if (argc == 1) { showArgMismatch(argv[0]); return false; } int opt; bool is_hex_passwd = false; char context_key_file[PATH_MAX]; while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) { switch (opt) { case 'k': { bool result = string_bytes_get_uint32(optarg, &ctx->key_handle); if (!result) { LOG_ERR("Could not convert key handle to number, got: \"%s\"", optarg); return false; } flags.k = 1; } break; case 'P': { bool result = password_util_copy_password(optarg, "key", &ctx->session_data.hmac); if (!result) { return false; } flags.P = 1; } break; case 'I': { ctx->cipher_text.t.size = sizeof(ctx->cipher_text) - 2; bool result = files_load_bytes_from_file(optarg, ctx->cipher_text.t.buffer, &ctx->cipher_text.t.size); if (!result) { return false; } flags.I = 1; } break; case 'o': { bool result = files_does_file_exist(optarg); if (result) { return false; } snprintf(ctx->output_file_path, sizeof(ctx->output_file_path), "%s", optarg); flags.o = 1; } break; case 'c': snprintf(context_key_file, sizeof(context_key_file), "%s", optarg); flags.c = 1; break; case 'X': is_hex_passwd = true; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } } if (!((flags.k || flags.c) && flags.I && flags.o)) { LOG_ERR("Expected arguments I and o and (k or c)"); return false; } if (flags.c) { bool result = file_load_tpm_context_from_file(ctx->sapi_context, &ctx->key_handle, context_key_file); if (!result) { return false; } } return password_util_to_auth(&ctx->session_data.hmac, is_hex_passwd, "key", &ctx->session_data.hmac); } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { /* opts and envp are unused, avoid compiler warning */ (void)opts; (void) envp; tpm_rsadecrypt_ctx ctx = { .key_handle = 0, .cipher_text = {{ 0 }}, .output_file_path = { 0 }, .session_data = { 0 }, .sapi_context = sapi_context }; ctx.session_data.sessionHandle = TPM_RS_PW; bool result = init(argc, argv, &ctx); if (!result) { return 1; } return rsa_decrypt_and_save(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_rsaencrypt.c000066400000000000000000000142661313543155100202040ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include "files.h" #include "log.h" #include "main.h" #include "options.h" #include "string-bytes.h" typedef struct tpm_rsaencrypt_ctx tpm_rsaencrypt_ctx; struct tpm_rsaencrypt_ctx { TPMI_DH_OBJECT key_handle; TPM2B_PUBLIC_KEY_RSA message; char output_file_path[PATH_MAX]; TSS2_SYS_CONTEXT *sapi_context; }; static bool rsa_encrypt_and_save(tpm_rsaencrypt_ctx *ctx) { // Inputs TPMT_RSA_DECRYPT scheme; TPM2B_DATA label; // Outputs TPM2B_PUBLIC_KEY_RSA out_data = TPM2B_TYPE_INIT(TPM2B_PUBLIC_KEY_RSA, buffer); TPMS_AUTH_RESPONSE out_session_data; TSS2_SYS_RSP_AUTHS out_sessions_data; TPMS_AUTH_RESPONSE *out_session_data_array[1]; out_session_data_array[0] = &out_session_data; out_sessions_data.rspAuths = &out_session_data_array[0]; out_sessions_data.rspAuthsCount = 1; scheme.scheme = TPM_ALG_RSAES; label.t.size = 0; TPM_RC rval = Tss2_Sys_RSA_Encrypt(ctx->sapi_context, ctx->key_handle, NULL, &ctx->message, &scheme, &label, &out_data, &out_sessions_data); if (rval != TPM_RC_SUCCESS) { LOG_ERR("RSA_Encrypt failed, error code: 0x%x", rval); return false; } return files_save_bytes_to_file(ctx->output_file_path, out_data.t.buffer, out_data.t.size); } static bool init(int argc, char *argv[], tpm_rsaencrypt_ctx *ctx) { const char *optstring = "k:I:o:c:"; static struct option long_options[] = { {"keyHandle", required_argument, NULL, 'k'}, {"inFile", required_argument, NULL, 'I'}, {"outFile", required_argument, NULL, 'o'}, {"keyContext", required_argument, NULL, 'c'}, { NULL, no_argument, NULL, '\0'} }; if(argc == 1) { showArgMismatch(argv[0]); return false; } struct { UINT8 k : 1; UINT8 I : 1; UINT8 o : 1; UINT8 c : 1; UINT8 unused : 4; } flags = { 0 }; int opt; char context_key_file[PATH_MAX]; while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) { switch (opt) { case 'k': { bool result = string_bytes_get_uint32(optarg, &ctx->key_handle); if (!result) { LOG_ERR("Could not convert key handle to number, got: \"%s\"", optarg); return false; } flags.k = 1; } break; case 'I': { ctx->message.t.size = sizeof(ctx->message) - 2; bool result = files_load_bytes_from_file(optarg, ctx->message.t.buffer, &ctx->message.t.size); if (!result) { return false; } flags.I = 1; } break; case 'o': { bool result = files_does_file_exist(optarg); if (result) { return false; } snprintf(ctx->output_file_path, sizeof(ctx->output_file_path), "%s", optarg); flags.o = 1; } break; case 'c': snprintf(context_key_file, sizeof(context_key_file), "%s", optarg); flags.c = 1; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } }; if (!((flags.k || flags.c) && flags.I && flags.o)) { LOG_ERR("Expected options I and o and (k or c)"); return false; } if (flags.c) { bool result = file_load_tpm_context_from_file(ctx->sapi_context, &ctx->key_handle, context_key_file); if (!result) { return false; } } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { /* opts and envp are unused, avoid compiler warning */ (void)opts; (void) envp; tpm_rsaencrypt_ctx ctx = { .key_handle = 0, .message = {{ 0 }}, .output_file_path = { 0 }, .sapi_context = sapi_context }; bool result = init(argc, argv, &ctx); if (!result) { return 1; } return rsa_encrypt_and_save(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_send_command.c000066400000000000000000000153621313543155100204370ustar00rootroot00000000000000/* * Copyright (c) 2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include "main.h" #include "tpm2-header.h" #include "log.h" #define MAX_BUF 4096 #define COMMAND_HEADER_SIZE (sizeof (TPMI_ST_COMMAND_TAG) + sizeof (UINT32) + sizeof (TPM_CC)) #define RESPONSE_HEADER_SIZE (sizeof (TPM_ST) + sizeof (UINT32) + sizeof (TPM_RC)) /* * Read a TPM command buffer from a 'file_stream'. Store this buffer in * 'buf'. On success we return the size of the command, error returns 0. */ UINT32 read_command_from_file (FILE *file_stream, uint8_t *buf, size_t const buf_size) { size_t ret; UINT32 command_size; LOG_INFO ("read_command_from_file"); ret = fread (buf, COMMAND_HEADER_SIZE, 1, file_stream); /* I'm not sure if fread will actually set errno from the docs */ if (ret != 1 && ferror (file_stream)) { LOG_ERR ("Failed to read command header: %s", strerror (errno)); return 0; } LOG_INFO ("read %zd command header of size: %zd", ret, COMMAND_HEADER_SIZE); command_size = get_command_size (buf); if (command_size > buf_size) { LOG_ERR("buf_size is insufficient: %u > %zd", command_size, buf_size); return 0; } LOG_INFO ("command tag: 0x%04x", get_command_tag (buf)); LOG_INFO ("command size: 0x%08x", get_command_size (buf)); LOG_INFO ("command code: 0x%08x", get_command_code (buf)); ret = fread (buf + COMMAND_HEADER_SIZE, command_size - COMMAND_HEADER_SIZE, 1, file_stream); if (ret != 1 && ferror (file_stream)) { LOG_ERR ("Failed to read command body: %s", strerror (errno)); return 0; } LOG_INFO ("read command body successfully"); return command_size; } /* * Write a TPM response buffer to a 'file_stream'. On error this function * returns 0, on success it returns the size of the response buffer. */ UINT32 write_response_to_file (FILE *file_stream, uint8_t *buf, size_t const buf_size) { size_t num_write; UINT32 response_size; LOG_INFO ("write_response_to_file"); num_write = fwrite (buf, RESPONSE_HEADER_SIZE, 1, file_stream); if (num_write != 1 && ferror (stdout)) { LOG_ERR ("failed to write to stdout"); return 0; } LOG_INFO ("wrote response header: %zd members of size %zd", num_write, RESPONSE_HEADER_SIZE); response_size = get_command_size (buf); if (response_size > buf_size) { LOG_ERR ("buf_size is insufficient: %u > %zd", response_size, buf_size); return 0; } LOG_INFO ("response tag: 0x%04x", get_response_tag (buf)); LOG_INFO ("response size: 0x%08x", get_response_size (buf)); LOG_INFO ("response code: 0x%08x", get_response_code (buf)); num_write = fwrite (buf + RESPONSE_HEADER_SIZE, response_size - RESPONSE_HEADER_SIZE, 1, file_stream); if (num_write != 1 && ferror (file_stream)) { LOG_ERR ("Failed to write response to file: %s", strerror (errno)); return 0; } LOG_INFO ("wrote response body: %zd members of size 0x%x", num_write, response_size); return response_size; } /* * This program reads a TPM command buffer from stdin then dumps it out * to a tabd TCTI. It then reads the response from the TCTI and writes it * to stdout. Like the TCTI, we expect the input TPM command buffer to be * in network byte order (big-endian). We output the response in the same * form. */ int execute_tool (int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void)envp; (void)opts; (void)argc; (void)argv; TSS2_TCTI_CONTEXT *tcti_context = NULL; size_t response_size = MAX_BUF; uint8_t buf [MAX_BUF]; UINT32 written_size, command_size; TSS2_RC rc; command_size = read_command_from_file (stdin, buf, MAX_BUF); if (command_size == 0) { LOG_ERR ("failed to read TPM2 command buffer from stdin"); return 1; } rc = Tss2_Sys_GetTctiContext (sapi_context, &tcti_context); if (rc != TSS2_RC_SUCCESS) { LOG_ERR ("Failed to get TCTI context from SAPI context: 0x%x", rc); return 1; } rc = tss2_tcti_transmit (tcti_context, command_size, buf); if (rc != TSS2_RC_SUCCESS) { LOG_ERR ("tss2_tcti_transmit failed: 0x%x", rc); return 1; } rc = tss2_tcti_receive (tcti_context, &response_size, buf, TSS2_TCTI_TIMEOUT_BLOCK); if (rc != TSS2_RC_SUCCESS) { LOG_ERR ("tss2_tcti_receive failed: 0x%x", rc); return 1; } written_size = write_response_to_file (stdout, buf, response_size); if (written_size < response_size) { LOG_ERR ("write_command_to_file failed"); return 1; } return 0; } tpm2-tools-2.1.0/tools/tpm2_sign.c000066400000000000000000000253231313543155100167460ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include "files.h" #include "log.h" #include "main.h" #include "options.h" #include "password_util.h" #include "string-bytes.h" #include "tpm_hash.h" typedef struct tpm_sign_ctx tpm_sign_ctx; struct tpm_sign_ctx { TPMT_TK_HASHCHECK validation; TPMS_AUTH_COMMAND sessionData; TPMI_DH_OBJECT keyHandle; TPMI_ALG_HASH halg; char outFilePath[PATH_MAX]; BYTE *msg; UINT16 length; TSS2_SYS_CONTEXT *sapi_context; }; static bool get_key_type(TSS2_SYS_CONTEXT *sapi_context, TPMI_DH_OBJECT objectHandle, TPMI_ALG_PUBLIC *type) { TPMS_AUTH_RESPONSE session_data_out; TPMS_AUTH_RESPONSE *session_data_out_array[1] = { &session_data_out }; TSS2_SYS_RSP_AUTHS sessions_data_out = { 1, &session_data_out_array[0] }; TPM2B_PUBLIC out_public = { { 0, } }; TPM2B_NAME name = TPM2B_TYPE_INIT(TPM2B_NAME, name); TPM2B_NAME qaulified_name = TPM2B_TYPE_INIT(TPM2B_NAME, name); TPM_RC rval = Tss2_Sys_ReadPublic(sapi_context, objectHandle, 0, &out_public, &name, &qaulified_name, &sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("Sys_ReadPublic failed, error code: 0x%x", rval); return false; } *type = out_public.t.publicArea.type; return true; } static bool set_scheme(TSS2_SYS_CONTEXT *sapi_context, TPMI_DH_OBJECT keyHandle, TPMI_ALG_HASH halg, TPMT_SIG_SCHEME *inScheme) { TPM_ALG_ID type; bool result = get_key_type(sapi_context, keyHandle, &type); if (!result) { return false; } switch (type) { case TPM_ALG_RSA : inScheme->scheme = TPM_ALG_RSASSA; inScheme->details.rsassa.hashAlg = halg; break; case TPM_ALG_KEYEDHASH : inScheme->scheme = TPM_ALG_HMAC; inScheme->details.hmac.hashAlg = halg; break; case TPM_ALG_ECC : inScheme->scheme = TPM_ALG_ECDSA; inScheme->details.ecdsa.hashAlg = halg; break; case TPM_ALG_SYMCIPHER : default: LOG_ERR("Unknown key type, got: 0x%x", type); return false; } return true; } static bool sign_and_save(tpm_sign_ctx *ctx) { TPM2B_DIGEST digest = TPM2B_TYPE_INIT(TPM2B_DIGEST, buffer); TPMT_SIG_SCHEME in_scheme; TPMT_SIGNATURE signature; TSS2_SYS_CMD_AUTHS sessions_data; TPMS_AUTH_RESPONSE session_data_out; TSS2_SYS_RSP_AUTHS sessions_data_out; TPMS_AUTH_COMMAND *session_data_array[1]; TPMS_AUTH_RESPONSE *session_data_out_array[1]; session_data_array[0] = &ctx->sessionData; sessions_data.cmdAuths = &session_data_array[0]; session_data_out_array[0] = &session_data_out; sessions_data_out.rspAuths = &session_data_out_array[0]; sessions_data_out.rspAuthsCount = 1; sessions_data.cmdAuthsCount = 1; int rc = tpm_hash_compute_data(ctx->sapi_context, ctx->msg, ctx->length, ctx->halg, &digest); if (rc) { LOG_ERR("Compute message hash failed!"); return false; } // printf("\ndigest(hex type):\n "); // UINT16 i; // for (i = 0; i < digest.t.size; i++) // printf("%02x ", digest.t.buffer[i]); // printf("\n"); bool result = set_scheme(ctx->sapi_context, ctx->keyHandle, ctx->halg, &in_scheme); if (!result) { return false; } TPM_RC rval = Tss2_Sys_Sign(ctx->sapi_context, ctx->keyHandle, &sessions_data, &digest, &in_scheme, &ctx->validation, &signature, &sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("Sys_Sign failed, error code: 0x%x", rval); return false; } /* TODO fix serialization */ return files_save_bytes_to_file(ctx->outFilePath, (UINT8 *) &signature, sizeof(signature)); } static bool init(int argc, char *argv[], tpm_sign_ctx *ctx) { static const char *optstring = "k:P:g:m:t:s:c:X"; static const struct option long_options[] = { {"keyHandle",1,NULL,'k'}, {"pwdk",1,NULL,'P'}, {"halg",1,NULL,'g'}, {"msg",1,NULL,'m'}, {"sig",1,NULL,'s'}, {"ticket",1,NULL,'t'}, {"keyContext",1,NULL,'c'}, {"passwdInHex",0,NULL,'X'}, {0,0,0,0} }; if(argc == 1) { showArgMismatch(argv[0]); return false; } struct { UINT8 k : 1; UINT8 P : 1; UINT8 g : 1; UINT8 m : 1; UINT8 t : 1; UINT8 s : 1; UINT8 c : 1; UINT8 unused : 1; } flags = { 0 }; int opt; bool hexPasswd = false; char contextKeyFile[PATH_MAX]; char inMsgFileName[PATH_MAX]; while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) { switch (opt) { case 'k': { bool result = string_bytes_get_uint32(optarg, &ctx->keyHandle); if (!result) { LOG_ERR("Could not format key handle to number, got: \"%s\"", optarg); return false; } flags.k = 1; } break; case 'P': { bool result = password_util_copy_password(optarg, "key", &ctx->sessionData.hmac); if (!result) { return false; } flags.P = 1; } break; case 'g': { bool result = string_bytes_get_uint16(optarg, &ctx->halg); if (!result) { LOG_ERR("Could not format algorithm to number, got: \"%s\"", optarg); return false; } flags.g = 1; } break; case 'm': snprintf(inMsgFileName, sizeof(inMsgFileName), "%s", optarg); flags.m = 1; break; case 't': { UINT16 size = sizeof(ctx->validation); bool result = files_load_bytes_from_file(optarg, (UINT8 *) &ctx->validation, &size); if (!result) { return false; } flags.t = 1; } break; case 's': { bool result = files_does_file_exist(optarg); if (result) { return false; } snprintf(ctx->outFilePath, sizeof(ctx->outFilePath), "%s", optarg); flags.s = 1; } break; case 'c': snprintf(contextKeyFile, sizeof(contextKeyFile), "%s", optarg); flags.c = 1; break; case 'X': hexPasswd = true; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } } if (!((flags.k || flags.c) && flags.g && flags.m && flags.s)) { LOG_ERR("Expected options (k or c) and g and m and s"); return false; } if (!flags.t) { ctx->validation.tag = TPM_ST_HASHCHECK; ctx->validation.hierarchy = TPM_RH_NULL; } bool result = password_util_to_auth(&ctx->sessionData.hmac, hexPasswd, "key", &ctx->sessionData.hmac); if (!result) { return false; } /* * load tpm context from a file if -c is provided */ if (flags.c) { result = file_load_tpm_context_from_file(ctx->sapi_context, &ctx->keyHandle, contextKeyFile); if (!result) { return false; } } /* * Process the msg file */ long file_size; result = files_get_file_size(inMsgFileName, &file_size); if (!result) { return false; } if (file_size == 0) { LOG_ERR("The message file \"%s\" is empty!", inMsgFileName); return false; } if (file_size > 0xffff) { LOG_ERR( "The message file was longer than a 16 bit length, got: %ld, expected less than: %d!", file_size, 0x10000); return false; } ctx->msg = (BYTE*) calloc(1, file_size); if (!ctx->msg) { LOG_ERR("oom"); return false; } ctx->length = file_size; result = files_load_bytes_from_file(inMsgFileName, ctx->msg, &ctx->length); if (!result) { free(ctx->msg); return false; } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { /* opts and envp are unused, avoid compiler warning */ (void)opts; (void) envp; tpm_sign_ctx ctx = { .msg = NULL, .sessionData = { 0 }, .halg = 0, .keyHandle = 0, .validation = { 0 }, .sapi_context = sapi_context }; ctx.sessionData.sessionHandle = TPM_RS_PW; bool result = init(argc, argv, &ctx); if (!result) { return 1; } result = sign_and_save(&ctx); free(ctx.msg); return result != true; } tpm2-tools-2.1.0/tools/tpm2_startup.c000066400000000000000000000116451313543155100175120ustar00rootroot00000000000000/* * Copyright (c) 2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include "main.h" #include "log.h" /* * Both the Microsoft and IBM TPM2 simulators require some specific setup * before they can be used by the SAPI. This setup is specific to the * simulators and is something that the low-level hardware / firmware does * for a discrete TPM. * NOTE: In the code that interacts with a TPM this can be a very ugly * abstraction leak. */ typedef struct startup_opts { bool clear; bool state; } startup_opts_t; /* * Parse the command line options specific to the 'startup' command. * Populate the provided startup_opts_t structure with this data. */ void get_startup_opts (int argc, char *argv[], startup_opts_t *startup_opts) { int c = 0, option_index = 0; char *arg_str = "cs"; static struct option long_options [] = { { .name = "clear", .has_arg = no_argument, .flag = NULL, .val = 'c', }, { .name = "state", .has_arg = no_argument, .flag = NULL, .val = 's', }, { NULL, }, }; while ((c = getopt_long (argc, argv, arg_str, long_options, &option_index)) != -1) { switch (c) { case 'c': startup_opts->clear = true; break; case 's': startup_opts->state = true; break; } } } /* * Sanity check the options that were passed. This is simply being sure * we have either the 'clear' or 'state' flags set but not both. */ int sanity_check_startup_opts (startup_opts_t *startup_opts) { /* * Detect when both clear and state are 'true' or 'false'. If this * condition fails, then the know that either clear or state are set but * not which (but we don't care). */ if (startup_opts->clear == startup_opts->state) { LOG_ERR ("Select either '--clear' or '--state'. Try --help."); return 1; } return 0; } /* * Create a connection to the simulator using the provided parameters: * hostname / IP address and port. Then issue the commands necessary to bring * the simulator up to a point where it can be used by the SAPI. */ int execute_tool (int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void) opts; (void) envp; TSS2_RC rc; TPM_SU startup_type; startup_opts_t startup_opts = { .clear = false, .state = false, }; get_startup_opts (argc, argv, &startup_opts); if (sanity_check_startup_opts (&startup_opts)) return 1; /* cheat here a bit and use the 'clear' flag to determine the SU type */ if (startup_opts.clear) startup_type = TPM_SU_CLEAR; else startup_type = TPM_SU_STATE; LOG_INFO ("Sending TPM_Startup command with type: %s", startup_opts.clear ? "TPM_SU_CLEAR" : "TPM_SU_STATE"); rc = Tss2_Sys_Startup (sapi_context, startup_type); if (rc != TSS2_RC_SUCCESS && rc != TPM_RC_INITIALIZE) { LOG_ERR ("Tss2_Sys_Startup failed: 0x%x", rc); return 1; } LOG_INFO ("Success. TSS2_RC: 0x%x", rc); return 0; } tpm2-tools-2.1.0/tools/tpm2_takeownership.c000066400000000000000000000217651313543155100206770ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include #include #include "log.h" #include "options.h" #include "main.h" #include "password_util.h" #include "string-bytes.h" typedef struct password password; struct password { TPM2B_AUTH old; TPM2B_AUTH new; }; typedef struct takeownership_ctx takeownership_ctx; struct takeownership_ctx { struct { password owner; password endorse; password lockout; } passwords; bool is_hex_passwords; TSS2_SYS_CONTEXT *sapi_context; }; bool clear_hierarchy_auth(takeownership_ctx *ctx) { TPMS_AUTH_COMMAND sessionData; TSS2_SYS_CMD_AUTHS sessionsData; TPMS_AUTH_COMMAND *sessionDataArray[1]; sessionDataArray[0] = &sessionData; sessionsData.cmdAuths = &sessionDataArray[0]; sessionsData.cmdAuthsCount = 1; sessionData.sessionHandle = TPM_RS_PW; sessionData.nonce.t.size = 0; sessionData.hmac.t.size = 0; *((UINT8 *) ((void *) &sessionData.sessionAttributes)) = 0; bool result = password_util_to_auth(&ctx->passwords.lockout.old, ctx->is_hex_passwords, "old lockout", &sessionData.hmac); if (!result) { return false; } UINT32 rval = Tss2_Sys_Clear(ctx->sapi_context, TPM_RH_LOCKOUT, &sessionsData, 0); if (rval != TPM_RC_SUCCESS) { LOG_ERR("Clearing Failed! TPM error code: 0x%0x", rval); return false; } return true; } #define ARRAY_LEN(x) (sizeof(x)/sizeof(*x)) static bool change_hierarchy_auth(takeownership_ctx *ctx) { TPM2B_AUTH newAuth; TPMS_AUTH_COMMAND sessionData; TSS2_SYS_CMD_AUTHS sessionsData; TPMS_AUTH_COMMAND *sessionDataArray[1]; sessionDataArray[0] = &sessionData; sessionsData.cmdAuths = &sessionDataArray[0]; sessionsData.cmdAuthsCount = 1; sessionData.sessionHandle = TPM_RS_PW; sessionData.nonce.t.size = 0; sessionData.hmac.t.size = 0; *((UINT8 *) ((void *) &sessionData.sessionAttributes)) = 0; struct { TPM2B_AUTH *new_passwd; TPM2B_AUTH *old_passwd; TPMI_RH_HIERARCHY_AUTH auth_handle; char *desc; } sources[] = { { .new_passwd = &ctx->passwords.owner.new, .old_passwd = &ctx->passwords.owner.old, .auth_handle = TPM_RH_OWNER, .desc = "Owner" }, { .new_passwd = &ctx->passwords.endorse.new, .old_passwd = &ctx->passwords.endorse.old, .auth_handle = TPM_RH_ENDORSEMENT, .desc = "Endorsement" }, { .new_passwd = &ctx->passwords.lockout.new, .old_passwd = &ctx->passwords.lockout.old, .auth_handle = TPM_RH_LOCKOUT, .desc = "Lockout" } }; unsigned i; for (i = 0; i < ARRAY_LEN(sources); i++) { unsigned j; for (j = 0; j < 2; j++) { TPM2B_AUTH *passwd = j == 0 ? sources[i].new_passwd : sources[i].old_passwd; TPM2B_AUTH *auth_dest = j == 0 ? &newAuth : &sessionData.hmac; char desc[256]; snprintf(desc, sizeof(desc), "%s %s", j == 0 ? "new" : "old", sources[i].desc); bool result = password_util_to_auth(passwd, ctx->is_hex_passwords, desc, auth_dest); if (!result) { return false; } } UINT32 rval = Tss2_Sys_HierarchyChangeAuth(ctx->sapi_context, sources[i].auth_handle, &sessionsData, &newAuth, 0); if (rval != TPM_RC_SUCCESS) { LOG_ERR("Could not change hierarchy for %s. TPM Error:0x%x", sources[i].desc, rval); return false; } LOG_INFO("Successfully changed hierarchy for %s", sources[i].desc); } return true; } static bool init(int argc, char *argv[], char *envp[], takeownership_ctx *ctx, bool *clear_auth) { struct option sOpts[] = { { "ownerPasswd", required_argument, NULL, 'o' }, {"endorsePasswd", required_argument, NULL, 'e' }, { "lockPasswd", required_argument, NULL, 'l' }, { "oldOwnerPasswd", required_argument, NULL, 'O' }, { "oldEndorsePasswd", required_argument, NULL, 'E' }, { "oldLockPasswd", required_argument, NULL, 'L' }, { "passwdInHex", no_argument, NULL, 'X' }, { "clear", no_argument, NULL, 'c' }, { NULL, no_argument, NULL, '\0' }, }; if (argc == 1) { execute_man(argv[0], envp); return false; } if (argc > (int) (2 * sizeof(sOpts) / sizeof(struct option))) { showArgMismatch(argv[0]); return false; } *clear_auth = false; int opt; bool result; while ((opt = getopt_long(argc, argv, "o:e:l:O:E:L:Xc", sOpts, NULL)) != -1) { switch (opt) { case 'c': *clear_auth = true; break; case 'o': result = password_util_copy_password(optarg, "new owner password", &ctx->passwords.owner.new); if (!result) { return false; } break; case 'e': result = password_util_copy_password(optarg, "new endorse password", &ctx->passwords.endorse.new); if (!result) { return false; } break; case 'l': result = password_util_copy_password(optarg, "new lockout password", &ctx->passwords.lockout.new); if (!result) { return false; } break; case 'O': result = password_util_copy_password(optarg, "current owner password", &ctx->passwords.owner.old); if (!result) { return false; } break; case 'E': result = password_util_copy_password(optarg, "current endorse password", &ctx->passwords.endorse.old); if (!result) { return false; } break; case 'L': result = password_util_copy_password(optarg, "current lockout password", &ctx->passwords.lockout.old); if (!result) { return false; } break; case 'X': ctx->is_hex_passwords = true; break; case '?': default: showArgMismatch(argv[0]); return false; } } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { /* opts is unused */ (void) opts; takeownership_ctx ctx = { .sapi_context = sapi_context, .is_hex_passwords = false }; bool clear_auth = false; bool result = init(argc, argv, envp, &ctx, &clear_auth); if (!result) { return 1; } int rc = (clear_auth ? clear_hierarchy_auth(&ctx) : change_hierarchy_auth(&ctx)); /* true is success, coerce to 0 for program success */ return rc == false; } tpm2-tools-2.1.0/tools/tpm2_unseal.c000066400000000000000000000144361313543155100173000ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include "files.h" #include "log.h" #include "main.h" #include "options.h" #include "password_util.h" #include "string-bytes.h" typedef struct tpm_unseal_ctx tpm_unseal_ctx; struct tpm_unseal_ctx { TPMS_AUTH_COMMAND sessionData; TPMI_DH_OBJECT itemHandle; char outFilePath[PATH_MAX]; TSS2_SYS_CONTEXT *sapi_context; }; bool unseal_and_save(tpm_unseal_ctx *ctx) { TPMS_AUTH_RESPONSE session_data_out; TSS2_SYS_CMD_AUTHS sessions_data; TSS2_SYS_RSP_AUTHS sessions_data_out; TPMS_AUTH_COMMAND *session_data_array[1]; TPMS_AUTH_RESPONSE *session_data_out_array[1]; TPM2B_SENSITIVE_DATA outData = TPM2B_TYPE_INIT(TPM2B_SENSITIVE_DATA, buffer); session_data_array[0] = &ctx->sessionData; session_data_out_array[0] = &session_data_out; sessions_data_out.rspAuths = &session_data_out_array[0]; sessions_data.cmdAuths = &session_data_array[0]; sessions_data_out.rspAuthsCount = 1; sessions_data.cmdAuthsCount = 1; TPM_RC rval = Tss2_Sys_Unseal(ctx->sapi_context, ctx->itemHandle, &sessions_data, &outData, &sessions_data_out); if (rval != TPM_RC_SUCCESS) { LOG_ERR("Sys_Unseal failed. Error Code: 0x%x", rval); return false; } /* TODO fix serialization */ return files_save_bytes_to_file(ctx->outFilePath, (UINT8 *) &outData, sizeof(outData)); } static bool init(int argc, char *argv[], tpm_unseal_ctx *ctx) { static const char *optstring = "H:P:o:c:X"; static const struct option long_options[] = { {"item",1,NULL,'H'}, {"pwdi",1,NULL,'P'}, {"outfile",1,NULL,'o'}, {"itemContext",1,NULL,'c'}, {"passwdInHex",0,NULL,'X'}, {0,0,0,0} }; if (argc == 1) { showArgMismatch(argv[0]); return false; } struct { UINT8 H : 1; UINT8 o : 1; UINT8 c : 1; UINT8 P : 1; } flags = { 0 }; int opt; bool hexPasswd = false; char contextItemFile[PATH_MAX]; while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) { switch (opt) { case 'H': { bool result = string_bytes_get_uint32(optarg, &ctx->itemHandle); if (!result) { LOG_ERR("Could not cobvert item handle to number, got: \"%s\"", optarg); return false; } flags.H = 1; } break; case 'P': { bool result = password_util_copy_password(optarg, "key", &ctx->sessionData.hmac); if (!result) { return false; } flags.P = 1; } break; case 'o': { bool result = files_does_file_exist(optarg); if (result) { return false; } snprintf(ctx->outFilePath, sizeof(ctx->outFilePath), "%s", optarg); flags.o = 1; } break; case 'c': snprintf(contextItemFile, sizeof(contextItemFile), "%s", optarg); flags.c = 1; break; case 'X': hexPasswd = true; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); return false; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); return false; default: LOG_ERR("?? getopt returned character code 0%o ??\n", opt); return false; } } if (!((flags.H || flags.c) && flags.o)) { LOG_ERR("Expected options (H or c) and o"); return false; } if (flags.P) { bool result = password_util_to_auth(&ctx->sessionData.hmac, hexPasswd, "key", &ctx->sessionData.hmac); if (!result) { return false; } } if (flags.c) { bool result = file_load_tpm_context_from_file(ctx->sapi_context, &ctx->itemHandle, contextItemFile); if (!result) { return false; } } return true; } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { /* opts and envp are unused, avoid compiler warning */ (void)opts; (void) envp; tpm_unseal_ctx ctx = { .sessionData = { 0 }, .sapi_context = sapi_context }; ctx.sessionData.sessionHandle = TPM_RS_PW; bool result = init(argc, argv, &ctx); if (!result) { return 1; } return unseal_and_save(&ctx) != true; } tpm2-tools-2.1.0/tools/tpm2_verifysignature.c000066400000000000000000000255241313543155100212370ustar00rootroot00000000000000//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. //**********************************************************************; #include #include #include #include #include #include #include #include #include "files.h" #include "log.h" #include "main.h" #include "options.h" #include "string-bytes.h" #include "tpm_hash.h" typedef struct tpm2_verifysig_ctx tpm2_verifysig_ctx; struct tpm2_verifysig_ctx { struct { uint8_t key_handle :1; uint8_t digest :1; uint8_t halg :1; uint8_t msg :1; uint8_t raw :1; uint8_t sig :1; uint8_t ticket :1; uint8_t key_context :1; } flags; TPMI_ALG_HASH halg; TPM2B_DIGEST msgHash; TPMI_DH_OBJECT keyHandle; TPMT_SIGNATURE signature; char *msg_file_path; char *sig_file_path; char *out_file_path; char *context_key_file_path; TSS2_SYS_CONTEXT *sapi_context; }; static bool verify_signature(tpm2_verifysig_ctx *ctx) { UINT32 rval; TPMT_TK_VERIFIED validation; TPMS_AUTH_RESPONSE sessionDataOut; TSS2_SYS_RSP_AUTHS sessionsDataOut; TPMS_AUTH_RESPONSE *sessionDataOutArray[1]; sessionDataOutArray[0] = &sessionDataOut; sessionsDataOut.rspAuths = &sessionDataOutArray[0]; sessionsDataOut.rspAuthsCount = 1; UINT16 i; for (i = 0; i < ctx->msgHash.t.size; i++) printf("%02x ", ctx->msgHash.t.buffer[i]); printf("\n"); rval = Tss2_Sys_VerifySignature(ctx->sapi_context, ctx->keyHandle, NULL, &ctx->msgHash, &ctx->signature, &validation, &sessionsDataOut); if (rval != TPM_RC_SUCCESS) { LOG_ERR("Tss2_Sys_VerifySignature failed, error code: 0x%x\n", rval); return false; } /* TODO fix serialization */ return files_save_bytes_to_file(ctx->out_file_path, (UINT8 *) &validation, sizeof(validation)); } static TPM2B *message_from_file(const char *msg_file_path) { long size; bool result = files_get_file_size(msg_file_path, &size); if (!result) { return NULL; } if (!size) { LOG_ERR("The msg file \"%s\" is empty", msg_file_path); return NULL; } TPM2B *msg = (TPM2B *) calloc(1, sizeof(TPM2B) + size); if (!msg) { LOG_ERR("OOM"); return NULL; } UINT16 tmp = msg->size = size; if (!files_load_bytes_from_file(msg_file_path, msg->buffer, &tmp)) { free(msg); return NULL; } return msg; } static bool generate_signature(tpm2_verifysig_ctx *ctx) { UINT16 size; UINT8 *buffer; if (ctx->flags.raw) { ctx->signature.sigAlg = TPM_ALG_RSASSA; ctx->signature.signature.rsassa.hash = ctx->halg; ctx->signature.signature.rsassa.sig.t.size = sizeof(ctx->signature.signature.rsassa.sig) - 2; buffer = ctx->signature.signature.rsassa.sig.t.buffer; size = ctx->signature.signature.rsassa.sig.t.size; } else { size = sizeof(ctx->signature); buffer = (UINT8 *) &ctx->signature; } bool result = files_load_bytes_from_file(ctx->sig_file_path, buffer, &size); if (!result) { LOG_ERR("Could not create %s signature from file: \"%s\"", ctx->flags.raw ? "raw" : "\0", ctx->sig_file_path); } return result; } static bool string_dup(char **new, char *old) { *new = strdup(old); if (!*new) { LOG_ERR("OOM while duplicating \"%s\"", old); return false; } return true; } static bool init(tpm2_verifysig_ctx *ctx) { TPM2B *msg = NULL; bool return_value = false; if (ctx->flags.msg) { msg = message_from_file(ctx->msg_file_path); if (!msg) { /* message_from_file() logs specific error no need to here */ return false; } } if (ctx->flags.sig) { bool res = generate_signature(ctx); if (!res) { goto err; } } if (ctx->flags.key_context) { bool result = file_load_tpm_context_from_file(ctx->sapi_context, &ctx->keyHandle, ctx->context_key_file_path); if (!result) { goto err; } } /* If no digest is specified, compute it */ if (!ctx->flags.digest) { if (!ctx->flags.msg) { /* * This is a redundant check since main() checks this case, but we'll add it here to silence any * complainers. */ LOG_ERR("No digest set and no message file to compute from, cannot compute message hash!"); goto err; } int rc = tpm_hash_compute_data(ctx->sapi_context, msg->buffer, msg->size, ctx->halg, &ctx->msgHash); if (rc) { LOG_ERR("Compute message hash failed!\n"); goto err; } } return_value = true; err: free(msg); return return_value; } static bool handle_options_and_init(int argc, char *argv[], tpm2_verifysig_ctx *ctx) { const char *optstring = "k:g:m:D:rs:t:c:"; const struct option long_options[] = { { "keyHandle", 1, NULL, 'k' }, { "digest", 1, NULL, 'D' }, { "halg", 1, NULL, 'g' }, { "msg", 1, NULL, 'm' }, { "raw", 0, NULL, 'r' }, { "sig", 1, NULL, 's' }, { "ticket", 1, NULL, 't' }, { "keyContext", 1, NULL, 'c' }, { NULL, 0, NULL, '\0' } }; if (argc == 1) { LOG_ERR("Invalid usage. Try --help for help."); return false; } int opt; while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) { switch (opt) { case 'k': { bool res = string_bytes_get_uint32(optarg, &ctx->keyHandle); if (!res) { LOG_ERR("Unable to convert key handle, got: \"%s\"", optarg); return false; } ctx->flags.key_handle = 1; } break; case 'g': { bool result = string_bytes_get_uint16(optarg, &ctx->halg); if (!result) { LOG_ERR("Unable to convert algorithm, got: \"%s\"", optarg); return false; } ctx->flags.halg = 1; } break; case 'm': { bool res = string_dup(&ctx->msg_file_path, optarg); if (!res) { return false; } ctx->flags.msg = 1; } break; case 'D': { UINT16 size = sizeof(ctx->msgHash); if (!files_load_bytes_from_file(optarg, (UINT8 *) &ctx->msgHash, &size)) { LOG_ERR("Could not load digest from file!"); return false; } ctx->flags.digest = 1; } break; case 'r': ctx->flags.raw = 1; break; case 's': if (!string_dup(&ctx->sig_file_path, optarg)) { return false; } ctx->flags.sig = 1; break; case 't': if (!string_dup(&ctx->out_file_path, optarg)) { return false; } if (files_does_file_exist(ctx->out_file_path)) { return false; } ctx->flags.ticket = 1; break; case 'c': if (!string_dup(&ctx->context_key_file_path, optarg)) { return false; } ctx->flags.key_context = 1; break; case ':': LOG_ERR("Argument %c needs a value!\n", optopt); break; case '?': LOG_ERR("Unknown Argument: %c\n", optopt); break; /* no default */ } }; /* check flags for mismatches */ if (ctx->flags.digest && (ctx->flags.msg || ctx->flags.halg)) { LOG_ERR( "Cannot specify --digest (-D) and ( --msg (-m) or --halg (-g) )"); return false; } if (!((ctx->flags.key_handle || ctx->flags.key_context) && ctx->flags.sig && ctx->flags.ticket)) { LOG_ERR( "--keyHandle (-k) or --keyContext (-c) and --sig (-s) and --ticket (-t) must be specified"); return false; } /* initialize and process */ return init(ctx); } static void tpm_verifysig_ctx_dealloc(tpm2_verifysig_ctx *ctx) { free(ctx->sig_file_path); free(ctx->out_file_path); free(ctx->msg_file_path); free(ctx->context_key_file_path); } int execute_tool(int argc, char *argv[], char *envp[], common_opts_t *opts, TSS2_SYS_CONTEXT *sapi_context) { (void) opts; (void) envp; int normalized_return_code = 1; tpm2_verifysig_ctx ctx = { .flags = { 0 }, .halg = TPM_ALG_SHA256, .msgHash = TPM2B_TYPE_INIT(TPM2B_DIGEST, buffer), .sig_file_path = NULL, .msg_file_path = NULL, .out_file_path = NULL, .context_key_file_path = NULL, .sapi_context = sapi_context }; bool res = handle_options_and_init(argc, argv, &ctx); if (!res) { goto err; } res = verify_signature(&ctx); if (!res) { LOG_ERR("Verify signature failed!"); goto err; } normalized_return_code = 0; err: tpm_verifysig_ctx_dealloc(&ctx); return normalized_return_code; }