pax_global_header00006660000000000000000000000064135321466770014530gustar00rootroot0000000000000052 comment=70703ce5574a54c5b593abb75f365fd26723aded tpm2-initramfs-tool-0.2.1/000077500000000000000000000000001353214667700153575ustar00rootroot00000000000000tpm2-initramfs-tool-0.2.1/.clang-format000066400000000000000000000351361353214667700177420ustar00rootroot00000000000000# SPDX-License-Identifier: GPL-2.0 # # clang-format configuration file. Intended for clang-format >= 4. # # For more information, see: # # Documentation/process/clang-format.rst # https://clang.llvm.org/docs/ClangFormat.html # https://clang.llvm.org/docs/ClangFormatStyleOptions.html # --- AccessModifierOffset: -4 AlignAfterOpenBracket: Align AlignConsecutiveAssignments: false AlignConsecutiveDeclarations: false #AlignEscapedNewlines: Left # Unknown to clang-format-4.0 AlignOperands: true AlignTrailingComments: false AllowAllParametersOfDeclarationOnNextLine: false AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: None AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: false BinPackArguments: true BinPackParameters: true BraceWrapping: AfterClass: false AfterControlStatement: false AfterEnum: false AfterFunction: true AfterNamespace: true AfterObjCDeclaration: false AfterStruct: false AfterUnion: false #AfterExternBlock: false # Unknown to clang-format-5.0 BeforeCatch: false BeforeElse: false IndentBraces: false #SplitEmptyFunction: true # Unknown to clang-format-4.0 #SplitEmptyRecord: true # Unknown to clang-format-4.0 #SplitEmptyNamespace: true # Unknown to clang-format-4.0 BreakBeforeBinaryOperators: None BreakBeforeBraces: Custom #BreakBeforeInheritanceComma: false # Unknown to clang-format-4.0 BreakBeforeTernaryOperators: false BreakConstructorInitializersBeforeComma: false #BreakConstructorInitializers: BeforeComma # Unknown to clang-format-4.0 BreakAfterJavaFieldAnnotations: false BreakStringLiterals: false ColumnLimit: 80 CommentPragmas: '^ IWYU pragma:' #CompactNamespaces: false # Unknown to clang-format-4.0 ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 8 ContinuationIndentWidth: 8 Cpp11BracedListStyle: false DerivePointerAlignment: false DisableFormat: false ExperimentalAutoDetectBinPacking: false #FixNamespaceComments: false # Unknown to clang-format-4.0 # Taken from: # git grep -h '^#define [^[:space:]]*for_each[^[:space:]]*(' include/ \ # | sed "s,^#define \([^[:space:]]*for_each[^[:space:]]*\)(.*$, - '\1'," \ # | sort | uniq ForEachMacros: - 'apei_estatus_for_each_section' - 'ata_for_each_dev' - 'ata_for_each_link' - '__ata_qc_for_each' - 'ata_qc_for_each' - 'ata_qc_for_each_raw' - 'ata_qc_for_each_with_internal' - 'ax25_for_each' - 'ax25_uid_for_each' - '__bio_for_each_bvec' - 'bio_for_each_bvec' - 'bio_for_each_integrity_vec' - '__bio_for_each_segment' - 'bio_for_each_segment' - 'bio_for_each_segment_all' - 'bio_list_for_each' - 'bip_for_each_vec' - 'blkg_for_each_descendant_post' - 'blkg_for_each_descendant_pre' - 'blk_queue_for_each_rl' - 'bond_for_each_slave' - 'bond_for_each_slave_rcu' - 'bpf_for_each_spilled_reg' - 'btree_for_each_safe128' - 'btree_for_each_safe32' - 'btree_for_each_safe64' - 'btree_for_each_safel' - 'card_for_each_dev' - 'cgroup_taskset_for_each' - 'cgroup_taskset_for_each_leader' - 'cpufreq_for_each_entry' - 'cpufreq_for_each_entry_idx' - 'cpufreq_for_each_valid_entry' - 'cpufreq_for_each_valid_entry_idx' - 'css_for_each_child' - 'css_for_each_descendant_post' - 'css_for_each_descendant_pre' - 'device_for_each_child_node' - 'drm_atomic_crtc_for_each_plane' - 'drm_atomic_crtc_state_for_each_plane' - 'drm_atomic_crtc_state_for_each_plane_state' - 'drm_atomic_for_each_plane_damage' - 'drm_connector_for_each_possible_encoder' - 'drm_for_each_connector_iter' - 'drm_for_each_crtc' - 'drm_for_each_encoder' - 'drm_for_each_encoder_mask' - 'drm_for_each_fb' - 'drm_for_each_legacy_plane' - 'drm_for_each_plane' - 'drm_for_each_plane_mask' - 'drm_for_each_privobj' - 'drm_mm_for_each_hole' - 'drm_mm_for_each_node' - 'drm_mm_for_each_node_in_range' - 'drm_mm_for_each_node_safe' - 'flow_action_for_each' - 'for_each_active_drhd_unit' - 'for_each_active_iommu' - 'for_each_available_child_of_node' - 'for_each_bio' - 'for_each_board_func_rsrc' - 'for_each_bvec' - 'for_each_card_components' - 'for_each_card_links' - 'for_each_card_links_safe' - 'for_each_card_prelinks' - 'for_each_card_rtds' - 'for_each_card_rtds_safe' - 'for_each_cgroup_storage_type' - 'for_each_child_of_node' - 'for_each_clear_bit' - 'for_each_clear_bit_from' - 'for_each_cmsghdr' - 'for_each_compatible_node' - 'for_each_component_dais' - 'for_each_component_dais_safe' - 'for_each_comp_order' - 'for_each_console' - 'for_each_cpu' - 'for_each_cpu_and' - 'for_each_cpu_not' - 'for_each_cpu_wrap' - 'for_each_dev_addr' - 'for_each_dma_cap_mask' - 'for_each_dpcm_be' - 'for_each_dpcm_be_rollback' - 'for_each_dpcm_be_safe' - 'for_each_dpcm_fe' - 'for_each_drhd_unit' - 'for_each_dss_dev' - 'for_each_efi_memory_desc' - 'for_each_efi_memory_desc_in_map' - 'for_each_element' - 'for_each_element_extid' - 'for_each_element_id' - 'for_each_endpoint_of_node' - 'for_each_evictable_lru' - 'for_each_fib6_node_rt_rcu' - 'for_each_fib6_walker_rt' - 'for_each_free_mem_range' - 'for_each_free_mem_range_reverse' - 'for_each_func_rsrc' - 'for_each_hstate' - 'for_each_if' - 'for_each_iommu' - 'for_each_ip_tunnel_rcu' - 'for_each_irq_nr' - 'for_each_link_codecs' - 'for_each_lru' - 'for_each_matching_node' - 'for_each_matching_node_and_match' - 'for_each_memblock' - 'for_each_memblock_type' - 'for_each_memcg_cache_index' - 'for_each_mem_pfn_range' - 'for_each_mem_range' - 'for_each_mem_range_rev' - 'for_each_migratetype_order' - 'for_each_msi_entry' - 'for_each_msi_entry_safe' - 'for_each_net' - 'for_each_netdev' - 'for_each_netdev_continue' - 'for_each_netdev_continue_rcu' - 'for_each_netdev_feature' - 'for_each_netdev_in_bond_rcu' - 'for_each_netdev_rcu' - 'for_each_netdev_reverse' - 'for_each_netdev_safe' - 'for_each_net_rcu' - 'for_each_new_connector_in_state' - 'for_each_new_crtc_in_state' - 'for_each_new_mst_mgr_in_state' - 'for_each_new_plane_in_state' - 'for_each_new_private_obj_in_state' - 'for_each_node' - 'for_each_node_by_name' - 'for_each_node_by_type' - 'for_each_node_mask' - 'for_each_node_state' - 'for_each_node_with_cpus' - 'for_each_node_with_property' - 'for_each_of_allnodes' - 'for_each_of_allnodes_from' - 'for_each_of_cpu_node' - 'for_each_of_pci_range' - 'for_each_old_connector_in_state' - 'for_each_old_crtc_in_state' - 'for_each_old_mst_mgr_in_state' - 'for_each_oldnew_connector_in_state' - 'for_each_oldnew_crtc_in_state' - 'for_each_oldnew_mst_mgr_in_state' - 'for_each_oldnew_plane_in_state' - 'for_each_oldnew_plane_in_state_reverse' - 'for_each_oldnew_private_obj_in_state' - 'for_each_old_plane_in_state' - 'for_each_old_private_obj_in_state' - 'for_each_online_cpu' - 'for_each_online_node' - 'for_each_online_pgdat' - 'for_each_pci_bridge' - 'for_each_pci_dev' - 'for_each_pci_msi_entry' - 'for_each_populated_zone' - 'for_each_possible_cpu' - 'for_each_present_cpu' - 'for_each_prime_number' - 'for_each_prime_number_from' - 'for_each_process' - 'for_each_process_thread' - 'for_each_property_of_node' - 'for_each_registered_fb' - 'for_each_reserved_mem_region' - 'for_each_rtd_codec_dai' - 'for_each_rtd_codec_dai_rollback' - 'for_each_rtdcom' - 'for_each_rtdcom_safe' - 'for_each_set_bit' - 'for_each_set_bit_from' - 'for_each_sg' - 'for_each_sg_dma_page' - 'for_each_sg_page' - 'for_each_sibling_event' - 'for_each_subelement' - 'for_each_subelement_extid' - 'for_each_subelement_id' - '__for_each_thread' - 'for_each_thread' - 'for_each_zone' - 'for_each_zone_zonelist' - 'for_each_zone_zonelist_nodemask' - 'fwnode_for_each_available_child_node' - 'fwnode_for_each_child_node' - 'fwnode_graph_for_each_endpoint' - 'gadget_for_each_ep' - 'genradix_for_each' - 'genradix_for_each_from' - 'hash_for_each' - 'hash_for_each_possible' - 'hash_for_each_possible_rcu' - 'hash_for_each_possible_rcu_notrace' - 'hash_for_each_possible_safe' - 'hash_for_each_rcu' - 'hash_for_each_safe' - 'hctx_for_each_ctx' - 'hlist_bl_for_each_entry' - 'hlist_bl_for_each_entry_rcu' - 'hlist_bl_for_each_entry_safe' - 'hlist_for_each' - 'hlist_for_each_entry' - 'hlist_for_each_entry_continue' - 'hlist_for_each_entry_continue_rcu' - 'hlist_for_each_entry_continue_rcu_bh' - 'hlist_for_each_entry_from' - 'hlist_for_each_entry_from_rcu' - 'hlist_for_each_entry_rcu' - 'hlist_for_each_entry_rcu_bh' - 'hlist_for_each_entry_rcu_notrace' - 'hlist_for_each_entry_safe' - '__hlist_for_each_rcu' - 'hlist_for_each_safe' - 'hlist_nulls_for_each_entry' - 'hlist_nulls_for_each_entry_from' - 'hlist_nulls_for_each_entry_rcu' - 'hlist_nulls_for_each_entry_safe' - 'i3c_bus_for_each_i2cdev' - 'i3c_bus_for_each_i3cdev' - 'ide_host_for_each_port' - 'ide_port_for_each_dev' - 'ide_port_for_each_present_dev' - 'idr_for_each_entry' - 'idr_for_each_entry_continue' - 'idr_for_each_entry_ul' - 'inet_bind_bucket_for_each' - 'inet_lhash2_for_each_icsk_rcu' - 'key_for_each' - 'key_for_each_safe' - 'klp_for_each_func' - 'klp_for_each_func_safe' - 'klp_for_each_func_static' - 'klp_for_each_object' - 'klp_for_each_object_safe' - 'klp_for_each_object_static' - 'kvm_for_each_memslot' - 'kvm_for_each_vcpu' - 'list_for_each' - 'list_for_each_codec' - 'list_for_each_codec_safe' - 'list_for_each_entry' - 'list_for_each_entry_continue' - 'list_for_each_entry_continue_rcu' - 'list_for_each_entry_continue_reverse' - 'list_for_each_entry_from' - 'list_for_each_entry_from_rcu' - 'list_for_each_entry_from_reverse' - 'list_for_each_entry_lockless' - 'list_for_each_entry_rcu' - 'list_for_each_entry_reverse' - 'list_for_each_entry_safe' - 'list_for_each_entry_safe_continue' - 'list_for_each_entry_safe_from' - 'list_for_each_entry_safe_reverse' - 'list_for_each_prev' - 'list_for_each_prev_safe' - 'list_for_each_safe' - 'llist_for_each' - 'llist_for_each_entry' - 'llist_for_each_entry_safe' - 'llist_for_each_safe' - 'media_device_for_each_entity' - 'media_device_for_each_intf' - 'media_device_for_each_link' - 'media_device_for_each_pad' - 'mp_bvec_for_each_page' - 'mp_bvec_for_each_segment' - 'nanddev_io_for_each_page' - 'netdev_for_each_lower_dev' - 'netdev_for_each_lower_private' - 'netdev_for_each_lower_private_rcu' - 'netdev_for_each_mc_addr' - 'netdev_for_each_uc_addr' - 'netdev_for_each_upper_dev_rcu' - 'netdev_hw_addr_list_for_each' - 'nft_rule_for_each_expr' - 'nla_for_each_attr' - 'nla_for_each_nested' - 'nlmsg_for_each_attr' - 'nlmsg_for_each_msg' - 'nr_neigh_for_each' - 'nr_neigh_for_each_safe' - 'nr_node_for_each' - 'nr_node_for_each_safe' - 'of_for_each_phandle' - 'of_property_for_each_string' - 'of_property_for_each_u32' - 'pci_bus_for_each_resource' - 'ping_portaddr_for_each_entry' - 'plist_for_each' - 'plist_for_each_continue' - 'plist_for_each_entry' - 'plist_for_each_entry_continue' - 'plist_for_each_entry_safe' - 'plist_for_each_safe' - 'pnp_for_each_card' - 'pnp_for_each_dev' - 'protocol_for_each_card' - 'protocol_for_each_dev' - 'queue_for_each_hw_ctx' - 'radix_tree_for_each_slot' - 'radix_tree_for_each_tagged' - 'rbtree_postorder_for_each_entry_safe' - 'rdma_for_each_port' - 'resource_list_for_each_entry' - 'resource_list_for_each_entry_safe' - 'rhl_for_each_entry_rcu' - 'rhl_for_each_rcu' - 'rht_for_each' - 'rht_for_each_from' - 'rht_for_each_entry' - 'rht_for_each_entry_from' - 'rht_for_each_entry_rcu' - 'rht_for_each_entry_rcu_from' - 'rht_for_each_entry_safe' - 'rht_for_each_rcu' - 'rht_for_each_rcu_from' - '__rq_for_each_bio' - 'rq_for_each_bvec' - 'rq_for_each_segment' - 'scsi_for_each_prot_sg' - 'scsi_for_each_sg' - 'sctp_for_each_hentry' - 'sctp_skb_for_each' - 'shdma_for_each_chan' - '__shost_for_each_device' - 'shost_for_each_device' - 'sk_for_each' - 'sk_for_each_bound' - 'sk_for_each_entry_offset_rcu' - 'sk_for_each_from' - 'sk_for_each_rcu' - 'sk_for_each_safe' - 'sk_nulls_for_each' - 'sk_nulls_for_each_from' - 'sk_nulls_for_each_rcu' - 'snd_array_for_each' - 'snd_pcm_group_for_each_entry' - 'snd_soc_dapm_widget_for_each_path' - 'snd_soc_dapm_widget_for_each_path_safe' - 'snd_soc_dapm_widget_for_each_sink_path' - 'snd_soc_dapm_widget_for_each_source_path' - 'tb_property_for_each' - 'tcf_exts_for_each_action' - 'udp_portaddr_for_each_entry' - 'udp_portaddr_for_each_entry_rcu' - 'usb_hub_for_each_child' - 'v4l2_device_for_each_subdev' - 'v4l2_m2m_for_each_dst_buf' - 'v4l2_m2m_for_each_dst_buf_safe' - 'v4l2_m2m_for_each_src_buf' - 'v4l2_m2m_for_each_src_buf_safe' - 'virtio_device_for_each_vq' - 'xa_for_each' - 'xa_for_each_marked' - 'xa_for_each_start' - 'xas_for_each' - 'xas_for_each_conflict' - 'xas_for_each_marked' - 'zorro_for_each_dev' #IncludeBlocks: Preserve # Unknown to clang-format-5.0 IncludeCategories: - Regex: '.*' Priority: 1 IncludeIsMainRegex: '(Test)?$' IndentCaseLabels: false #IndentPPDirectives: None # Unknown to clang-format-5.0 IndentWidth: 4 IndentWrappedFunctionNames: false JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: false MacroBlockBegin: '' MacroBlockEnd: '' MaxEmptyLinesToKeep: 1 NamespaceIndentation: Inner #ObjCBinPackProtocolList: Auto # Unknown to clang-format-5.0 ObjCBlockIndentWidth: 8 ObjCSpaceAfterProperty: true ObjCSpaceBeforeProtocolList: true # Taken from git's rules #PenaltyBreakAssignment: 10 # Unknown to clang-format-4.0 PenaltyBreakBeforeFirstCallParameter: 30 PenaltyBreakComment: 10 PenaltyBreakFirstLessLess: 0 PenaltyBreakString: 10 PenaltyExcessCharacter: 100 PenaltyReturnTypeOnItsOwnLine: 60 PointerAlignment: Right ReflowComments: false SortIncludes: false #SortUsingDeclarations: false # Unknown to clang-format-4.0 SpaceAfterCStyleCast: false SpaceAfterTemplateKeyword: true SpaceBeforeAssignmentOperators: true #SpaceBeforeCtorInitializerColon: true # Unknown to clang-format-5.0 #SpaceBeforeInheritanceColon: true # Unknown to clang-format-5.0 SpaceBeforeParens: ControlStatements #SpaceBeforeRangeBasedForLoopColon: true # Unknown to clang-format-5.0 SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 1 SpacesInAngles: false SpacesInContainerLiterals: false SpacesInCStyleCastParentheses: false SpacesInParentheses: false SpacesInSquareBrackets: false Standard: Cpp03 TabWidth: 8 UseTab: Never ... tpm2-initramfs-tool-0.2.1/CHANGELOG.md000066400000000000000000000015071353214667700171730ustar00rootroot00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [0.2.1] - 2019-08-30 ### Added - To compat with debian release convention Remove debian/ in git master, built release tarball on github and use quilt instead of native format. ## [0.2.0] - 2019-08-19 ### Added - Large refactor and add tests/code coverage Large refactor, add tests and add functionality to seal provided data and persistent object address. ## [0.1.0] - 2019-05-09 ### Added - Initial release of the tool to be used in the initramfs to generate/seal/unseal the key based on PCR policy using ESAPI from the TCG's TPM Software Stack compliant tpm2-tss libraries tpm2-initramfs-tool-0.2.1/LICENSE000066400000000000000000000432541353214667700163740ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. tpm2-initramfs-tool-0.2.1/Makefile.am000066400000000000000000000042621353214667700174170ustar00rootroot00000000000000# SPDX-License-Identifier: GPL-2.0-or-later # Copyright (c) 2018 Fraunhofer SIT # Copyright (c) 2019 Canonical Ltd. # All rights reserved. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 or 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . INCLUDE_DIRS = -I$(srcdir)/include ACLOCAL_AMFLAGS = -I m4 --install AM_CFLAGS = $(INCLUDE_DIRS) $(EXTRA_CFLAGS) $(TSS2_ESYS_CFLAGS) $(CODE_COVERAGE_CFLAGS) AM_LDFLAGS = $(EXTRA_LDFLAGS) $(CODE_COVERAGE_LDFLAGS) AM_LDADD = $(TSS2_ESYS_LIBS) -ldl ### Add ax_* rules ### # ax_code_coverage if AUTOCONF_CODE_COVERAGE_2019_01_06 include $(top_srcdir)/aminclude_static.am clean-local: code-coverage-clean distclean-local: code-coverage-dist-clean else @CODE_COVERAGE_RULES@ endif noinst_LIBRARIES = libtpm2-initramfs-tool.a noinst_HEADERS = include/tpm2-initramfs-tool.h libtpm2_initramfs_tool_a_SOURCES = src/libtpm2-initramfs-tool.c pkgconfig_DATA = dist/tpm2-initramfs-tool.pc bin_PROGRAMS = tpm2-initramfs-tool tpm2_initramfs_tool_SOURCES = src/tpm2-initramfs-tool.c tpm2_initramfs_tool_LDADD = libtpm2-initramfs-tool.a $(AM_LDADD) tpm2_initramfs_tool_LDFLAGS = $(AM_LDFLAGS) ### Tests ### TESTS = TESTS += $(TESTS_SHELL) TESTS_SHELL = test/test-tpm2-initramfs-tool.sh EXTRA_DIST = $(TESTS_SHELL) TEST_EXTENSIONS = .sh check_PROGRAMS = test-tpm2-initramfs-tool-base32enc test_tpm2_initramfs_tool_base32enc_SOURCES = test/test-tpm2-initramfs-tool-base32enc.c test_tpm2_initramfs_tool_base32enc_LDADD = libtpm2-initramfs-tool.a $(AM_LDADD) TESTS += $(check_PROGRAMS) EXTRA_DIST += \ CHANGELOG.md \ LICENSE \ README.md AUTHORS: $(AM_V_GEN)git log --format='%aN <%aE>' | \ grep -v 'users.noreply.github.com' | sort -u > $@ EXTRA_DIST += AUTHORS CLEANFILES = AUTHORS tpm2-initramfs-tool-0.2.1/README.md000066400000000000000000000037661353214667700166520ustar00rootroot00000000000000% tpm2-initramfs-tool(1) tpm2-initramfs-tool | General Commands Manual % % MAY 2019 # Overview This tool using the [tpm2-tss](https://github.com/tpm2-software/tpm2-tss) software stack. Its purpose is to generate/seal/unseal the FDE encrypytion key into the TPM persistent object using TPM2 ESAPI. The code include functions, macros and structures based from the following projects: * tpm2-tss https://github.com/tpm2-software/tpm2-tss * tpm2-totp https://github.com/tpm2-software/tpm2-totp * tpm2-tools https://github.com/tpm2-software/tpm2-tools # Name **tpm2-initramfs-tool**(1) - Tool used in initramfs to seal/unseal FDE key to the TPM. # Build and install instructions Standard installation using ``` $ ./bootstrap $ ./configure $ make $ sudo make install ``` # Usage ``` $ ./tpm2-initramfs-tool seal -T device:/dev/tpm0 Generate and seal the key to TPM with the default policy on PCR7 in SHA256 bank. $ ./tpm2-initramfs-tool unseal -T device:/dev/tpm0 Unseal the key to TPM with the default policy on PCR7 in SHA256 bank. $ ./tpm2-initramfs-tool seal --pcrs 0,2,4,7 --banks SHA1,SHA256 -T device:/dev/tpmrm0 Generate and seal the key to TPM with the policy on PCR0,PCR2,PCR4,PCR7 in both SHA1 and SHA256 bank. $ ./tpm2-initramfs-tool unseal --pcrs 0,2,4,7 --banks SHA1,SHA256 -T device:/dev/tpmrm0 Unseal the key to TPM with the policy on PCR0,PCR2,PCR4,PCR7 in both SHA1 and SHA256 bank. $ ./tpm2-initramfs-tool seal --data "DATA SEALED" -P 0x81000004 -T device:/dev/tpmrm0 Seal the string "DATA SEALED" to the persistent object address 0x81000004 with the default policy on PCR7 in SHA256 bank. ``` # Tests and Code Coverage Install lcov and configure with --enable-code-coverage. You will need to install TPM 2.0 simulator for integration tests, see https://github.com/tpm2-software/tpm2-tools/wiki/Getting-Started#installing-the-tpm20-simulator ``` $ ./configure --enable-code-coverage $ make check-code-coverage ``` # Notice Everytime you re-seal the new key it will overwrite the old persistent object. tpm2-initramfs-tool-0.2.1/bootstrap000077500000000000000000000000601353214667700173160ustar00rootroot00000000000000#!/bin/bash set -e autoreconf --install --sym tpm2-initramfs-tool-0.2.1/configure.ac000066400000000000000000000060151353214667700176470ustar00rootroot00000000000000# SPDX-License-Identifier: GPL-2.0-or-later # Copyright (c) 2018 Fraunhofer SIT # Copyright (c) 2019 Canonical Ltd. # All rights reserved. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 or 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . AC_PREREQ([2.68]) AC_INIT([tpm2-initramfs-tool], [0.2.1], [https://github.com/timchen119/tpm2-initramfs-tools/issues], [], [https://github.com/timchen119/tpm2-initramfs-tools]) dnl Avoid setting CFLAGS to anything by default; we use AC_CFLAGS below for this. : ${CFLAGS=""} dnl Let's be FHS-conform by default. if test "$prefix" = '/usr'; then test "$sysconfdir" = '${prefix}/etc' && sysconfdir="/etc" test "$sharedstatedir" = '${prefix}/com' && sharedstatedir="/var" test "$localstatedir" = '${prefix}/var' && localstatedir="/var" fi AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_SRCDIR([src/tpm2-initramfs-tool.c]) AC_CONFIG_AUX_DIR([build-aux]) AC_USE_SYSTEM_EXTENSIONS # propagate configure arguments to distcheck AC_SUBST([DISTCHECK_CONFIGURE_FLAGS],[$ac_configure_args]) AC_CANONICAL_SYSTEM AM_INIT_AUTOMAKE([foreign subdir-objects -Wall -Wno-portability]) #Backward compatible setting of "silent-rules" m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])]) AM_MAINTAINER_MODE([enable]) AC_PROG_CC AC_PROG_CC_C99 AM_PROG_CC_C_O # Use static libary AC_PROG_RANLIB AC_GNU_SOURCE PKG_INSTALLDIR() AC_CONFIG_FILES([Makefile dist/tpm2-initramfs-tool.pc]) AX_ADD_COMPILER_FLAG([-std=c99]) AX_ADD_COMPILER_FLAG([-Wall]) AX_ADD_COMPILER_FLAG([-Wextra]) AX_ADD_COMPILER_FLAG([-Wformat-security]) AX_ADD_COMPILER_FLAG([-Werror]) AX_ADD_COMPILER_FLAG([-fstack-protector-all]) AX_ADD_COMPILER_FLAG([-fpic]) AX_ADD_COMPILER_FLAG([-fPIC]) # work around GCC bug #53119 # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119 AX_ADD_COMPILER_FLAG([-Wno-missing-braces]) AX_ADD_LINK_FLAG([-Wl,--no-undefined]) AX_ADD_LINK_FLAG([-Wl,-z,noexecstack]) AX_ADD_LINK_FLAG([-Wl,-z,now]) AX_ADD_LINK_FLAG([-Wl,-z,relro]) AX_CODE_COVERAGE m4_ifdef([_AX_CODE_COVERAGE_RULES], [AM_CONDITIONAL(AUTOCONF_CODE_COVERAGE_2019_01_06, [true])], [AM_CONDITIONAL(AUTOCONF_CODE_COVERAGE_2019_01_06, [false])]) AX_ADD_AM_MACRO_STATIC([]) AC_ARG_ENABLE([debug], [AS_HELP_STRING([--enable-debug], [build with debug output])],, [enable_debug=no]) AS_IF([test "x$enable_debug" != "xno"], AC_DEFINE_UNQUOTED([DEBUG], [1], ["Debug output enabled"])) PKG_PROG_PKG_CONFIG([0.25]) PKG_CHECK_MODULES([TSS2_ESYS],[tss2-esys]) AC_OUTPUT AC_MSG_RESULT([ $PACKAGE_NAME $VERSION ]) tpm2-initramfs-tool-0.2.1/dist/000077500000000000000000000000001353214667700163225ustar00rootroot00000000000000tpm2-initramfs-tool-0.2.1/dist/tpm2-initramfs-tool.pc.in000066400000000000000000000005311353214667700231010ustar00rootroot00000000000000prefix=/usr/local exec_prefix=${prefix} Name: tpm2-initramfs-tool Description: a single binary to be used in the initramfs to seal and unseal the key based on PCR policy using ESAPI from the TCG's TPM Software Stack compliant tpm2-tss libraries URL: https://github.com/timchen119/tpm2-initramfs-tool Version: 0.2.1 Requires.private: tss2-esys tpm2-initramfs-tool-0.2.1/include/000077500000000000000000000000001353214667700170025ustar00rootroot00000000000000tpm2-initramfs-tool-0.2.1/include/tpm2-initramfs-tool.h000066400000000000000000000156121353214667700230070ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright 2018, Fraunhofer SIT * Copyright 2018, Jonas Witschel * Copyright © 2019 Canonical Ltd. * All rights reserved. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 or 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authored by: Tim Chen * */ #include #include #include #include #include #include #include #include #include #define SECRETLEN 128 #define STR_HELPER(x) #x #define STR(x) STR_HELPER(x) #define SECRETLEN_STR STR(SECRETLEN) /* Trusted Platform Module Library Part 2: Structures, * Revision 01.38, Section 10.6.1. * Default PCRs list for pcrSelect: PCR 7 */ #define DEFAULT_PCRS (0b000000000000000010000000) /* Default bank hash algorithm: TPM2_ALG_SHA256 */ #define DEFAULT_BANKS (0b10) #define TPM2_BANK_SHA1 (1 << 0) #define TPM2_BANK_SHA256 (1 << 1) #define TPM2_BANK_SHA384 (1 << 2) /* TODO: document templates, algorithms and object attributes */ #define TPM2B_PUBLIC_PRIMARY_TEMPLATE \ { \ .size = 0, .publicArea = { \ .type = TPM2_ALG_ECC, \ .nameAlg = TPM2_ALG_SHA256, \ .objectAttributes = \ (TPMA_OBJECT_USERWITHAUTH | TPMA_OBJECT_RESTRICTED | \ TPMA_OBJECT_DECRYPT | TPMA_OBJECT_NODA | \ TPMA_OBJECT_FIXEDTPM | TPMA_OBJECT_FIXEDPARENT | \ TPMA_OBJECT_SENSITIVEDATAORIGIN), \ .authPolicy = \ { \ .size = 0, \ }, \ .parameters.eccDetail = \ { \ .symmetric = \ { \ .algorithm = TPM2_ALG_AES, \ .keyBits.aes = 128, \ .mode.aes = TPM2_ALG_CFB, \ }, \ .scheme = {.scheme = TPM2_ALG_NULL, .details = {}}, \ .curveID = TPM2_ECC_NIST_P256, \ .kdf = {.scheme = TPM2_ALG_NULL, .details = {}}, \ }, \ .unique.ecc = {.x.size = 0, .y.size = 0} \ } \ } #define TPM2B_PUBLIC_KEY_TEMPLATE_UNSEAL \ { \ .size = 0, .publicArea = { \ .type = TPM2_ALG_KEYEDHASH, \ .nameAlg = TPM2_ALG_SHA256, \ .objectAttributes = \ (TPMA_OBJECT_FIXEDTPM | \ TPMA_OBJECT_FIXEDPARENT | TPMA_OBJECT_NODA), \ .authPolicy = {.size = 0, .buffer = {0}}, \ .parameters.keyedHashDetail \ .scheme = {.scheme = TPM2_ALG_NULL, \ .details = {.hmac = {.hashAlg = TPM2_ALG_SHA256}}}, \ .unique.keyedHash = \ { \ .size = 0, \ .buffer = {0}, \ }, \ } \ } #define TPM2B_SENSITIVE_CREATE_TEMPLATE \ { .size = 0, \ .sensitive = { \ .userAuth = { .size = 0, .buffer = { 0 } }, \ .data = { .size = 0, .buffer = { 0 } }, \ } }; #define VERB(...) \ if (opt.verbose) \ fprintf(stderr, __VA_ARGS__) #define ERR(...) fprintf(stderr, __VA_ARGS__) #define chkrc(rc, cmd) \ if (rc != TSS2_RC_SUCCESS) { \ ERR("ERROR in %s (%s:%i): 0x%08x\n", __func__, __FILE__, __LINE__, \ rc); \ cmd; \ } #define TPM2_INITRAMFS_TOOL_ENV_TCTI "TPM2_INITRAMFS_TOOL_TCTI" #define TSS2_TCTI_SO_FORMAT "libtss2-tcti-%s.so.0" extern TPM2B_PUBLIC primaryPublic; extern TPM2B_SENSITIVE_CREATE primarySensitive; extern TPM2B_DATA allOutsideInfo; extern TPML_PCR_SELECTION allCreationPCR; extern const char *help; extern const char *optstr; extern const struct option long_options[]; struct { enum { CMD_NONE, CMD_SEAL, CMD_UNSEAL } cmd; char *data; uint32_t persistent; int banks; int pcrs; char *tcti; int verbose; } opt; struct { void *dlhandle; TSS2_TCTI_CONTEXT *context; } tcti; void tcti_finalize(); int tcti_init(char *str, TSS2_TCTI_CONTEXT **context); int pcr_unseal(uint32_t pcrs, uint32_t banks, uint32_t persistent, TSS2_TCTI_CONTEXT *tcti_context); int pcr_seal(const char *data, uint32_t pcrs, uint32_t banks, uint32_t persistent, TSS2_TCTI_CONTEXT *tcti_context); int parse_opts(int argc, char **argv); char *base32enc(const uint8_t *in, size_t in_size); tpm2-initramfs-tool-0.2.1/m4/000077500000000000000000000000001353214667700156775ustar00rootroot00000000000000tpm2-initramfs-tool-0.2.1/m4/flags.m4000066400000000000000000000044201353214667700172350ustar00rootroot00000000000000dnl AX_ADD_COMPILER_FLAG: dnl A macro to add a CFLAG to the EXTRA_CFLAGS variable. This macro will dnl check to be sure the compiler supports the flag. Flags can be made dnl mandatory (configure will fail). dnl $1: C compiler flag to add to EXTRA_CFLAGS. dnl $2: Set to "required" to cause configure failure if flag not supported. AC_DEFUN([AX_ADD_COMPILER_FLAG],[ AX_CHECK_COMPILE_FLAG([$1],[ EXTRA_CFLAGS="$EXTRA_CFLAGS $1" AC_SUBST([EXTRA_CFLAGS])],[ AS_IF([test x$2 != xrequired],[ AC_MSG_WARN([Optional CFLAG "$1" not supported by your compiler, continuing.])],[ AC_MSG_ERROR([Required CFLAG "$1" not supported by your compiler, aborting.])] )],[ -Wall -Werror] )] ) dnl AX_ADD_PREPROC_FLAG: dnl Add the provided preprocessor flag to the EXTRA_CFLAGS variable. This dnl macro will check to be sure the preprocessor supports the flag. dnl The flag can be made mandatory by providing the string 'required' as dnl the second parameter. dnl $1: Preprocessor flag to add to EXTRA_CFLAGS. dnl $2: Set to "required" t ocause configure failure if preprocesor flag dnl is not supported. AC_DEFUN([AX_ADD_PREPROC_FLAG],[ AX_CHECK_PREPROC_FLAG([$1],[ EXTRA_CFLAGS="$EXTRA_CFLAGS $1" AC_SUBST([EXTRA_CFLAGS])],[ AS_IF([test x$2 != xrequired],[ AC_MSG_WARN([Optional preprocessor flag "$1" not supported by your compiler, continuing.])],[ AC_MSG_ERROR([Required preprocessor flag "$1" not supported by your compiler, aborting.])] )],[ -Wall -Werror] )] ) dnl AX_ADD_LINK_FLAG: dnl A macro to add a LDLAG to the EXTRA_LDFLAGS variable. This macro will dnl check to be sure the linker supports the flag. Flags can be made dnl mandatory (configure will fail). dnl $1: linker flag to add to EXTRA_LDFLAGS. dnl $2: Set to "required" to cause configure failure if flag not supported. AC_DEFUN([AX_ADD_LINK_FLAG],[ AX_CHECK_LINK_FLAG([$1],[ EXTRA_LDFLAGS="$EXTRA_LDFLAGS $1" AC_SUBST([EXTRA_LDFLAGS])],[ AS_IF([test x$2 != xrequired],[ AC_MSG_WARN([Optional LDFLAG "$1" not supported by your linker, continuing.])],[ AC_MSG_ERROR([Required LDFLAG "$1" not supported by your linker, aborting.])] )] )] ) tpm2-initramfs-tool-0.2.1/src/000077500000000000000000000000001353214667700161465ustar00rootroot00000000000000tpm2-initramfs-tool-0.2.1/src/libtpm2-initramfs-tool.c000066400000000000000000000520711353214667700226350ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright 2018, Fraunhofer SIT * Copyright 2018, Jonas Witschel * Copyright © 2019 Canonical Ltd. * All rights reserved. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 or 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authored by: Tim Chen * */ #include "tpm2-initramfs-tool.h" TPM2B_PUBLIC primaryPublic = TPM2B_PUBLIC_PRIMARY_TEMPLATE; TPM2B_SENSITIVE_CREATE primarySensitive = TPM2B_SENSITIVE_CREATE_TEMPLATE; TPM2B_DATA allOutsideInfo = { .size = 0, }; TPML_PCR_SELECTION allCreationPCR = { .count = 0 }; /* TODO: add -o for output file, -i for input file */ const char *help = "Usage: [options] {seal|unseal}\n" "Version: " PACKAGE_VERSION "\n" "Options:\n" " -h, --help print help\n" " -D --data Seal provided data in the persistent object (max chars:" SECRETLEN_STR ")\n" " -P --persistent Persistent object address (default: TPM2_PERSISTENT_FIRST)\n" " -b, --banks Selected PCR banks (default: SHA256, comma for separated list)\n" " -p, --pcrs Selected PCR registers (default: 7, comma for separated list)\n" " -T, --tcti TCTI to use (e.g. device:/dev/tpm0)\n" " -v, --verbose print verbose messages\n" "\n"; const char *optstr = "hD:P:b:p:T:v"; const struct option long_options[] = { { "help", no_argument, 0, 'h' }, { "data", required_argument, 0, 'D' }, { "persistent", required_argument, 0, 'P' }, { "banks", required_argument, 0, 'b' }, { "pcrs", required_argument, 0, 'p' }, { "tcti", required_argument, 0, 'T' }, { "verbose", no_argument, 0, 'v' }, { 0, 0, 0, 0 } }; /** Function to generate base32 encoding string. * * This function generates the base32 encoding for input data. * @param[in] in the character array pointer to be encoded. * @param[in] in_size the size of the input data. * @retval the pointer of base32 encoding chracters array. */ char *base32enc(const uint8_t *in, size_t in_size) { static unsigned char base32[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; size_t i = 0, j = 0; size_t out_size = ((in_size + 4) / 5) * 8; unsigned char *r = malloc(out_size + 1); if (!r) return NULL; while (1) { r[i++] = in[j] >> 3 & 0x1F; r[i++] = in[j] << 2 & 0x1F; if (++j >= in_size) break; else i--; r[i++] |= in[j] >> 6 & 0x1F; r[i++] = in[j] >> 1 & 0x1F; r[i++] = in[j] << 4 & 0x1F; if (++j >= in_size) break; else i--; r[i++] |= in[j] >> 4 & 0x1F; r[i++] = in[j] << 1 & 0x1F; if (++j >= in_size) break; else i--; r[i++] |= in[j] >> 7 & 0x1F; r[i++] = in[j] >> 2 & 0x1F; r[i++] = in[j] << 3 & 0x1F; if (++j >= in_size) break; else i--; r[i++] |= in[j] >> 5 & 0x1F; r[i++] = in[j] & 0x1F; if (++j >= in_size) break; } for (j = 0; j < i; j++) { r[j] = base32[r[j]]; } while (i < out_size) { r[i++] = '='; } r[i] = 0; return (char *)r; } /** Function to setup pcrSelections. * * This function setup PCRs selection list and bank hash algorithm. * @param[in] pcrs PCRs the key should be sealed against. * @param[in] banks PCR banks the key should be sealed against. * @param[in,out] pcrsel PCRs selection list. */ static void setup_pcr_selections(uint32_t *pcrs, uint32_t *banks, TPML_PCR_SELECTION *pcrsel) { if (*pcrs == 0) *pcrs = DEFAULT_PCRS; if (*banks == 0) *banks = DEFAULT_BANKS; if ((*banks & TPM2_BANK_SHA1)) { pcrsel->pcrSelections[pcrsel->count].hash = TPM2_ALG_SHA1; pcrsel->count++; } if ((*banks & TPM2_BANK_SHA256)) { pcrsel->pcrSelections[pcrsel->count].hash = TPM2_ALG_SHA256; pcrsel->count++; } if ((*banks & TPM2_BANK_SHA384)) { pcrsel->pcrSelections[pcrsel->count].hash = TPM2_ALG_SHA384; pcrsel->count++; } for (size_t i = 0; i < pcrsel->count; i++) { pcrsel->pcrSelections[i].sizeofSelect = 3; pcrsel->pcrSelections[i].pcrSelect[0] = *pcrs & 0xff; pcrsel->pcrSelections[i].pcrSelect[1] = *pcrs >> 8 & 0xff; pcrsel->pcrSelections[i].pcrSelect[2] = *pcrs >> 16 & 0xff; } } /** Generate a key and seal as a persistent object with policy of PCRs. * * This function generate the key and seal it as a persistent object. * It output the key in base32 encoding to stdout. * @param[in] pcrs PCRs the key should be sealed against. * @param[in] banks PCR banks the key should be sealed against. * @param[in] persistent Persistent object address. * @param[in] tcti_context Optional TCTI context to select TPM to use. * @retval 0 on success. * @retval -1 on undefined/general failure. */ int pcr_seal(const char *data, uint32_t pcrs, uint32_t banks, uint32_t persistent, TSS2_TCTI_CONTEXT *tcti_context) { char *base32key = NULL; size_t base32keySize = 0; uint8_t *secret = NULL; size_t secretSize = 0; TPM2B_DIGEST *t = NULL, *policyDigest = NULL; ESYS_CONTEXT *ctx = NULL; ESYS_TR primary = ESYS_TR_NONE, session = ESYS_TR_NONE, key = ESYS_TR_NONE; TSS2_RC rc = -1; TPMT_SYM_DEF sym = { .algorithm = TPM2_ALG_AES, .keyBits = { .aes = 128 }, .mode = { .aes = TPM2_ALG_CFB } }; TPM2B_PUBLIC keyInPublicSeal = TPM2B_PUBLIC_KEY_TEMPLATE_UNSEAL; TPM2B_SENSITIVE_CREATE keySensitive = TPM2B_SENSITIVE_CREATE_TEMPLATE; TPM2B_PUBLIC *keyPublicHmac = NULL; TPM2B_PRIVATE *keyPrivateHmac = NULL; TPML_PCR_SELECTION pcrsel = { .count = 0 }; TPM2_HANDLE permanentHandle = persistent ? persistent : (uint32_t)TPM2_PERSISTENT_FIRST; ESYS_TR persistentHandle1 = ESYS_TR_NONE; TPMI_YES_NO moreData; TPMS_CAPABILITY_DATA *fetchedData = NULL; int count; setup_pcr_selections(&pcrs, &banks, &pcrsel); secret = malloc(SECRETLEN + 1); if (!secret) { return -1; } memset(secret, 0, SECRETLEN + 1); rc = Esys_Initialize(&ctx, tcti_context, NULL); chkrc(rc, goto error); /* Check if we already seal the persistent object */ rc = Esys_GetCapability( ctx, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, TPM2_CAP_HANDLES, persistent ? persistent : (uint32_t)TPM2_PERSISTENT_FIRST, TPM2_MAX_CAP_HANDLES, &moreData, &fetchedData); chkrc(rc, goto error); count = fetchedData->data.handles.count; /* If persistent handle exists, try to remove the handle we plan to use */ if (count > 0) { ESYS_TR outHandle; rc = Esys_TR_FromTPMPublic( ctx, persistent ? persistent : (uint32_t)TPM2_PERSISTENT_FIRST, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, &outHandle); if (rc == TSS2_RC_SUCCESS) { VERB("Remove the persistent handle on 0x%x\n", persistent); rc = Esys_EvictControl(ctx, ESYS_TR_RH_OWNER, outHandle, ESYS_TR_PASSWORD, ESYS_TR_NONE, ESYS_TR_NONE, permanentHandle, &persistentHandle1); chkrc(rc, Esys_FlushContext(ctx, outHandle); goto error); } } /* To seal the provided data */ if (data) { if (strlen(data) > SECRETLEN) VERB("truncating provided data to " STR(SECRETLEN) " bytes \n"); secretSize = strnlen(data, SECRETLEN); memcpy(&(secret)[0], &(data)[0], secretSize); } else { /* Generate the random string from TPM if no data provided */ while (secretSize < SECRETLEN) { VERB("Calling Esys_GetRandom for %zu bytes\n", SECRETLEN - secretSize); rc = Esys_GetRandom(ctx, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, SECRETLEN - secretSize, &t); chkrc(rc, goto error); base32key = base32enc(t->buffer, t->size); if (!base32key) goto error; base32keySize = strnlen(base32key, SECRETLEN - secretSize); memcpy(&(secret)[secretSize], &(base32key)[0], base32keySize); secretSize += base32keySize; } } /* Create Primary Object under the TPM_RH_OWNER hierarchy */ rc = Esys_CreatePrimary(ctx, ESYS_TR_RH_OWNER, ESYS_TR_PASSWORD, ESYS_TR_NONE, ESYS_TR_NONE, &primarySensitive, &primaryPublic, &allOutsideInfo, &allCreationPCR, &primary, NULL, NULL, NULL, NULL); chkrc(rc, Esys_FlushContext(ctx, primary); goto error); /* Check PCRs */ rc = Esys_GetCapability(ctx, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, TPM2_CAP_PCRS, 0, TPM2_MAX_TPM_PROPERTIES, &moreData, &fetchedData); chkrc(rc, goto error); count = fetchedData->data.assignedPCR.count; if (count == 0) { ERR("No active banks selected"); return -1; } /* Setup PCR policy * 1. Start Trial Session * 2. Send appropriate TPM 2.0 session commands to update the digest * 3. Get final policy digest */ rc = Esys_StartAuthSession(ctx, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, NULL, TPM2_SE_POLICY, &sym, TPM2_ALG_SHA256, &session); chkrc(rc, goto error); rc = Esys_PolicyPCR(ctx, session, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, NULL, &pcrsel); chkrc(rc, goto error); rc = Esys_PolicyGetDigest(ctx, session, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, &policyDigest); chkrc(rc, goto error); keyInPublicSeal.publicArea.authPolicy = *policyDigest; keySensitive.sensitive.data.size = secretSize; memcpy(&keySensitive.sensitive.data.buffer[0], &(secret)[0], secretSize); /* Create an object that can be loaded into TPM */ rc = Esys_Create(ctx, primary, ESYS_TR_PASSWORD, ESYS_TR_NONE, ESYS_TR_NONE, &keySensitive, &keyInPublicSeal, &allOutsideInfo, &allCreationPCR, &keyPrivateHmac, &keyPublicHmac, NULL, NULL, NULL); chkrc(rc, goto error); rc = Esys_Load(ctx, primary, ESYS_TR_PASSWORD, ESYS_TR_NONE, ESYS_TR_NONE, keyPrivateHmac, keyPublicHmac, &key); chkrc(rc, goto error); /* Save the object as persistent object */ rc = Esys_EvictControl(ctx, ESYS_TR_RH_OWNER, key, ESYS_TR_PASSWORD, ESYS_TR_NONE, ESYS_TR_NONE, permanentHandle, &persistentHandle1); chkrc(rc, goto error); printf("%s", secret); rc = 0; /* clean up */ error: if (base32key) free(base32key); if (secret) free(secret); if (t) free(t); if (policyDigest) free(policyDigest); if (primary != ESYS_TR_NONE) Esys_FlushContext(ctx, primary); if (session != ESYS_TR_NONE) Esys_FlushContext(ctx, session); if (key != ESYS_TR_NONE) Esys_FlushContext(ctx, key); if (ctx) Esys_Finalize(&ctx); if (keyPublicHmac) free(keyPublicHmac); if (keyPrivateHmac) free(keyPrivateHmac); if (fetchedData) free(fetchedData); return (int)rc; } /** Unseal a key with PCRs. * * This function will unseal the persistent object based on the PCRs. * It output the key in base32 encoding to stdout. * @param[in] pcrs PCRs the key should be sealed against. * @param[in] banks PCR banks the key should be sealed against. * @param[in] persistent Persistent object address. * @param[in] tcti_context Optional TCTI context to select TPM to use. * @retval 0 on success. * @retval -1 on undefined/general failure. */ int pcr_unseal(uint32_t pcrs, uint32_t banks, uint32_t persistent, TSS2_TCTI_CONTEXT *tcti_context) { ESYS_CONTEXT *ctx = NULL; ESYS_TR primary, session = ESYS_TR_NONE; TSS2_RC rc = -1; TPM2B_SENSITIVE_DATA *secret2b = NULL; TPMT_SYM_DEF sym = { .algorithm = TPM2_ALG_AES, .keyBits = { .aes = 128 }, .mode = { .aes = TPM2_ALG_CFB } }; TPML_PCR_SELECTION pcrsel = { .count = 0 }; setup_pcr_selections(&pcrs, &banks, &pcrsel); rc = Esys_Initialize(&ctx, tcti_context, NULL); chkrc(rc, goto error); rc = Esys_TR_FromTPMPublic( ctx, persistent ? persistent : (uint32_t)TPM2_PERSISTENT_FIRST, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, &primary); chkrc(rc, goto error); rc = Esys_StartAuthSession(ctx, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, NULL, TPM2_SE_POLICY, &sym, TPM2_ALG_SHA256, &session); chkrc(rc, goto error); rc = Esys_PolicyPCR(ctx, session, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, NULL, &pcrsel); chkrc(rc, goto error); rc = Esys_Unseal(ctx, primary, session, ESYS_TR_NONE, ESYS_TR_NONE, &secret2b); chkrc(rc, goto error); printf("%s", secret2b->buffer); rc = 0; /* clean up */ error: if (secret2b) free(secret2b); if (session != ESYS_TR_NONE) Esys_FlushContext(ctx, session); if (ctx) Esys_Finalize(&ctx); return (int)rc; } /** Parse TCTI options string. * * This function parse TCTI options string. * @param[in] str The TCTI options string. * @param[out] path the TCTI module library path. * @param[out] conf the TCTI configuration string. */ static void tcti_parse_string(char *str, char **path, char **conf) { *path = str; char *split = strchr(str, ':'); if (split == NULL) { *conf = NULL; } else { split[0] = '\0'; *conf = &split[1]; } } /** Load TCTI dynamic library. * * This function use dlopen to load TCTI library dynamicly. * @param[in] path the TCTI module library path. */ static void *tcti_dlopen(const char *path) { void *dlhandle; dlhandle = dlopen(path, RTLD_LAZY); if (dlhandle) { return dlhandle; } else { /* Expand to libtss2-tcti-.so.0 */ char *dlname; int size = snprintf(NULL, 0, TSS2_TCTI_SO_FORMAT, path); if (size <= 0) { ERR("Could not open TCTI %s.\n", path); return NULL; } dlname = malloc(size + 1); if (!dlname) { ERR("oom"); return NULL; } snprintf(dlname, size + 1, TSS2_TCTI_SO_FORMAT, path); dlhandle = dlopen(dlname, RTLD_LAZY); free(dlname); return dlhandle; } } /** Initial TCTI context. * * This function will unseal the persistent object based on the PCRs. * @param[in] str The TCTI options string. * @param[out] context TCTI context to select TPM to use. * @retval 0 on success. * @retval 1 on undefined/general failure. */ int tcti_init(char *str, TSS2_TCTI_CONTEXT **context) { *context = tcti.context = NULL; /* If no option is given, load from environment or use default TCTI */ if (!str) { str = getenv(TPM2_INITRAMFS_TOOL_ENV_TCTI); if (!str) { return 0; } } char *path; char *conf; tcti_parse_string(str, &path, &conf); if (path[0] == '\0') { ERR("No TCTI given.\n"); return 1; } tcti.dlhandle = tcti_dlopen(path); if (!tcti.dlhandle) { ERR("Could not open TCTI '%s'.\n", path); return 1; } TSS2_TCTI_INFO_FUNC infofn = (TSS2_TCTI_INFO_FUNC)dlsym(tcti.dlhandle, TSS2_TCTI_INFO_SYMBOL); if (!infofn) { dlclose(tcti.dlhandle); ERR("Symbol '%s' not found in library '%s'.\n", TSS2_TCTI_INFO_SYMBOL, path); return 1; } const TSS2_TCTI_INFO *info = infofn(); const TSS2_TCTI_INIT_FUNC init = info->init; size_t context_size; if (init(NULL, &context_size, conf) != TPM2_RC_SUCCESS) { ERR("TCTI init routine failed.\n"); goto err; } tcti.context = (TSS2_TCTI_CONTEXT *)malloc(context_size); if (!tcti.context) { ERR("oom"); goto err; } if (init(tcti.context, &context_size, conf) != TPM2_RC_SUCCESS) { ERR("TCTI context creation failed.\n"); goto err; } *context = tcti.context; return 0; err: free(tcti.context); tcti.context = NULL; dlclose(tcti.dlhandle); tcti.dlhandle = NULL; return 1; } /* Finalize TCTI context */ void tcti_finalize() { if (tcti.context) { Tss2_Tcti_Finalize(tcti.context); free(tcti.context); dlclose(tcti.dlhandle); } } /** Parse Banks argument. * * @param[in,out] str The argument string pointer to be parsed. * @param[in,out] banks Construct banks from the string arguments. * @retval 0 on success * @retval -1 on failure */ static int parse_banks(char *str, int *banks) { char *token; char *saveptr; *banks = 0; token = strtok_r(str, ",", &saveptr); if (!token) { return -1; } while (token) { if (strcmp(token, "SHA1") == 0) { *banks |= TPM2_BANK_SHA1; } else if (strcmp(token, "SHA256") == 0) { *banks |= TPM2_BANK_SHA256; } else if (strcmp(token, "SHA384") == 0) { *banks |= TPM2_BANK_SHA384; } else { return -1; } token = strtok_r(NULL, ",", &saveptr); } return 0; } /** Parse PCRs argument. * * @param[in,out] str The argument string pointer to be parsed. * @param[in,out] pcrs Construct pcrs from the string arguments. * @retval 0 on success * @retval -1 on failure */ static int parse_pcrs(char *str, int *pcrs) { char *token; char *saveptr; char *endptr; long pcr; *pcrs = 0; token = strtok_r(str, ",", &saveptr); if (!token) { return -1; } while (token) { errno = 0; pcr = strtoul(token, &endptr, 0); if (errno || endptr == token || *endptr != '\0') { return -1; } else { *pcrs |= 1 << pcr; } token = strtok_r(NULL, ",", &saveptr); } return 0; } /** Parse and set command line options. * * This function parses the command line options and sets the appropriate values * in the opt struct. * @param argc The argument count. * @param argv The arguments. * @retval 0 on success * @retval -1 on failure */ int parse_opts(int argc, char **argv) { /* set the default values */ opt.cmd = CMD_NONE; opt.data = NULL; opt.banks = 0; opt.pcrs = 0; opt.persistent = TPM2_PERSISTENT_FIRST; opt.verbose = 0; /* parse the options */ int c; int opt_idx = 0; while (-1 != (c = getopt_long(argc, argv, optstr, long_options, &opt_idx))) { switch (c) { case 'h': printf("%s", help); exit(0); case 'D': opt.data = optarg; break; case 'P': if (sscanf(optarg, "0x%x", &opt.persistent) != 1 && sscanf(optarg, "%i", &opt.persistent) != 1) { opt.persistent = TPM2_PERSISTENT_FIRST; } if (opt.persistent < (uint32_t)TPM2_PERSISTENT_FIRST || opt.persistent > (uint32_t)TPM2_PERSISTENT_LAST) { ERR("Error parsing persistent object address.\n"); } break; case 'b': if (parse_banks(optarg, &opt.banks) != 0) { ERR("Error parsing banks.\n"); return -1; } break; case 'p': if (parse_pcrs(optarg, &opt.pcrs) != 0) { ERR("Error parsing pcrs.\n"); return -1; } break; case 'T': opt.tcti = optarg; break; case 'v': opt.verbose = 1; break; default: ERR("Unknown option at index %i.\n\n", opt_idx); ERR("%s", help); return -1; } } /* parse the non-option arguments */ if (optind >= argc) { ERR("Missing command: seal, unseal.\n\n"); ERR("%s", help); return -1; } if (!strcmp(argv[optind], "seal")) { opt.cmd = CMD_SEAL; } else if (!strcmp(argv[optind], "unseal")) { opt.cmd = CMD_UNSEAL; } else { ERR("Unknown command: seal, unseal.\n\n"); ERR("%s", help); return -1; } optind++; if (optind < argc) { ERR("Unknown argument provided.\n\n"); ERR("%s", help); return -1; } return 0; } tpm2-initramfs-tool-0.2.1/src/tpm2-initramfs-tool.c000066400000000000000000000033141353214667700221420ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright 2018, Fraunhofer SIT * Copyright 2018, Jonas Witschel * Copyright © 2019 Canonical Ltd. * All rights reserved. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 or 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authored by: Tim Chen * */ #include "include/tpm2-initramfs-tool.h" /** Main function * * @param argc The argument count. * @param argv The arguments. * @retval 0 on success * @retval 1 on failure */ int main(int argc, char **argv) { if (parse_opts(argc, argv) != 0) { goto err; } int rc; TSS2_TCTI_CONTEXT *tcti_context; if (tcti_init(opt.tcti, &tcti_context) != 0) { goto err; } switch (opt.cmd) { case CMD_SEAL: rc = pcr_seal(opt.data, opt.pcrs, opt.banks, opt.persistent, tcti_context); if (rc != 0) { goto err; } break; case CMD_UNSEAL: rc = pcr_unseal(opt.pcrs, opt.banks, opt.persistent, tcti_context); if (rc != 0) { goto err; } break; default: goto err; } tcti_finalize(); return 0; err: tcti_finalize(); return 1; } tpm2-initramfs-tool-0.2.1/test/000077500000000000000000000000001353214667700163365ustar00rootroot00000000000000tpm2-initramfs-tool-0.2.1/test/test-tpm2-initramfs-tool-base32enc.c000066400000000000000000000020111353214667700250430ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright © 2019 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 or 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authored by: Tim Chen * */ #include "tpm2-initramfs-tool.h" #include int main() { char *base32key = NULL; const unsigned char teststring[] = {0xfe, 0x58, 0x12, 0x53, 0x75, 0x69}; base32key = base32enc(teststring, 6); assert(strcmp(base32key,"7ZMBEU3VNE======") == 0); free(base32key); } tpm2-initramfs-tool-0.2.1/test/test-tpm2-initramfs-tool.sh000077500000000000000000000052211353214667700235010ustar00rootroot00000000000000#!/bin/sh # # Tests for tpm2-initramfs-tool # # SPDX-License-Identifier: GPL-2.0-or-later # Copyright (c) 2019 Canonical Ltd. # All rights reserved. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 or 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . set -eufx ./tpm2-initramfs-tool --help ./tpm2-initramfs-tool -h ./tpm2-initramfs-tool 2>&1 | grep "Missing command" ./tpm2-initramfs-tool nothisarg 2>&1 | grep "Unknown command" ./tpm2-initramfs-tool --nothisoption 2>&1 | grep "Unknown option" ./tpm2-initramfs-tool seal nothisarg 2>&1 | grep "Unknown argument provided" ./tpm2-initramfs-tool seal --tcti nothistcti 2>&1 | grep "Could not open TCTI" ./tpm2-initramfs-tool seal --banks SHA999 2>&1 | grep "Error parsing banks" ./tpm2-initramfs-tool seal --pcrs 0,2,4,kk 2>&1 | grep "Error parsing pcrs" # if no tpm_server (TPM simulator) or tpm2_startup (from tpm2-tools) found, skip the integration tests command -v tpm_server >/dev/null 2>&1 || exit 77 command -v tpm2_startup >/dev/null 2>&1 || exit 77 tpm_server_port="$(shuf --input-range 1024-65534 --head-count 1)" echo "Starting simulator on port $tpm_server_port" tpm_server -port "$tpm_server_port" & tpm_server_pid="$!" cleanup() { echo "clean up tpm_server" kill "$tpm_server_pid" } trap cleanup INT TERM EXIT sleep 1 tpm2_startup --clear -T mssim:host=localhost,port=$tpm_server_port # seal the "DATA SEALED" string as a persitent object in TPM simulator, using current PCRs 0,2,4,7 with bank SHA1 and SHA256 ./tpm2-initramfs-tool seal --pcrs 0,2,4,7 --banks SHA1,SHA256 --data "DATA SEALED" -T mssim:host=localhost,port=$tpm_server_port # unseal the data from TPM simulator and check if it works ./tpm2-initramfs-tool unseal --pcrs 0,2,4,7 --banks SHA1,SHA256 -T mssim:host=localhost,port=$tpm_server_port | grep "DATA SEALED" # seal a TPM random string to address 0x81000004 as a persitant object in TPM simulator, with default PCR 7 on bank SHA384 SEAL_DATA=$(./tpm2-initramfs-tool seal -v -P 0x81000004 --banks SHA384 -T mssim:host=localhost,port=$tpm_server_port) # unseal from TPM and make sure the data sealed is correct ./tpm2-initramfs-tool unseal -P 0x81000004 --banks SHA384 -v -T mssim:host=localhost,port=$tpm_server_port | grep "$SEAL_DATA" tpm2-initramfs-tool-0.2.1/tpm2-initramfs-tool.1000066400000000000000000000033471353214667700212770ustar00rootroot00000000000000.TH "tpm2-initramfs-tool" "1" " tpm2-initramfs-tool | General Commands Manual" "%" "MAY 2019" .nh .ad l .SH Overview .PP This tool using the tpm2\-tss \[la]https://github.com/tpm2-software/tpm2-tss\[ra] software stack. Its purpose is to generate/seal/unseal the FDE encrypytion key into the TPM persistent object using TPM2 ESAPI. .SH Name .PP \fBtpm2\-initramfs\-tool\fP(1) \- Tool used in initramfs to seal/unseal FDE key to the TPM. .SH Build and install instructions .PP Standard installation using .PP .RS .nf $ ./bootstrap $ ./configure $ make $ sudo make install .fi .RE .SH Usage .PP .RS .nf $ ./tpm2\-initramfs\-tool seal \-T device:/dev/tpm0 Generate and seal the key to TPM with the default policy on PCR7 in SHA256 bank. $ ./tpm2\-initramfs\-tool unseal \-T device:/dev/tpm0 Unseal the key to TPM with the default policy on PCR7 in SHA256 bank. $ ./tpm2\-initramfs\-tool seal \-\-pcrs 0,2,4,7 \-\-banks SHA1,SHA256 \-T device:/dev/tpmrm0 Generate and seal the key to TPM with the policy on PCR0,PCR2,PCR4,PCR7 in both SHA1 and SHA256 bank. $ ./tpm2\-initramfs\-tool unseal \-\-pcrs 0,2,4,7 \-\-banks SHA1,SHA256 \-T device:/dev/tpmrm0 Unseal the key to TPM with the policy on PCR0,PCR2,PCR4,PCR7 in both SHA1 and SHA256 bank. $ ./tpm2\-initramfs\-tool seal \-\-data "DATA SEALED" \-P 0x81000004 \-T device:/dev/tpmrm0 Seal the string "DATA SEALED" to the persistent object address 0x81000004 with the default policy on PCR7 in SHA256 bank. .fi .RE .SH Tests and Code Coverage .PP Install lcov and configure with \-\-enable\-code\-coverage .PP .RS .nf $ ./configure \-\-enable\-code\-coverage $ make check\-code\-coverage .fi .RE .SH Notice .PP Everytime you re\-seal the new key it will overwrite the old persistent object.