./0000755000000000000000000000000013200730623007705 5ustar rootroot./LICENSE0000644000000000000000000006364213200730623010725 0ustar rootroot GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 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. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, 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 library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete 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 distribute a copy of this License along with the Library. 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 Library or any portion of it, thus forming a work based on the Library, 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) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, 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 Library, 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 Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you 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. If distribution of 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 satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be 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. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library 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. 9. 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 Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library 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 with this License. 11. 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 Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library 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 Library. 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. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library 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. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library 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 Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, 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 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. 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 LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; 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. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! ./README.md0000644000000000000000000000200113200730623011155 0ustar rootrootTPM2 PK11 ========== TPM2 PK11 provide a PKCS#11 backend for a TPM 2.0 chip. This can be used to secure your SSH keys. NOTICE: Currently only the OpenSSH client is supported ## SSH Usage 1. Create key's ``` mkdir ~/.tpm2 && cd ~/.tpm2 tpm2_createprimary -A e -g 0x000b -G 0x0001 -C po.ctx tpm2_create -c po.ctx -g 0x000b -G 0x0001 -o key.pub -O key.priv tpm2_load -c po.ctx -u key.pub -r key.priv -n key.name -C obj.ctx tpm2_evictcontrol -A o -c obj.ctx -S 0x81010010 rm key.name *.ctx ``` 2. Create configuration file and change it for your setup ``` cp config.sample ~/.tpm2/config ``` 3. Extract public key ``` ssh-keygen -D libtpm2-pk11.so ``` 4. Use your TPM key ``` ssh -I libtpm2-pk11.so ssh.example.com ``` or add the PKCS#11 module to your ssh config in `~/.ssh/config`: ``` Host * PKCS11Provider libtpm2-pk11.so ``` ## Contribute 1. Fork us 2. Write code 3. Send Pull Requests ## Copyright and license Copyright 2017 Iwan Timmer. Distributed under the GNU LGPL v2.1. For full terms see the LICENSE file ./CMakeLists.txt0000644000000000000000000000247513200730623012455 0ustar rootrootcmake_minimum_required(VERSION 3.1) project(TPM2_PK11 LANGUAGES C) include(${CMAKE_ROOT}/Modules/GNUInstallDirs.cmake) find_package(PkgConfig REQUIRED) pkg_check_modules(P11_KIT REQUIRED p11-kit-1) pkg_check_modules(SAPI REQUIRED sapi) pkg_check_modules(TCTI_SOCKET tcti-socket) pkg_check_modules(TCTI_DEVICE tcti-device) pkg_check_modules(TCTI_TABRMD tcti-tabrmd) if(NOT TCTI_SOCKET_FOUND AND NOT TCTI_DEVICE_FOUND AND NOT TCTI_TABRMD_FOUND) message(FATAL_ERROR "At least one connection type must be enabled") endif() aux_source_directory(./src SRC_LIST) add_library(tpm2-pk11 SHARED ${SRC_LIST}) set_property(TARGET tpm2-pk11 PROPERTY C_STANDARD 11) target_include_directories(tpm2-pk11 PRIVATE ${P11_KIT_INCLUDE_DIRS} ${SAPI_INCLUDE_DIRS} ${TCTI_SOCKET_INCLUDE_DIRS} ${TCTI_DEVICE_INCLUDE_DIRS} ${TCTI_TABRMD_INCLUDE_DIRS}) target_link_libraries(tpm2-pk11 ${P11_KIT_LIBRARIES} ${SAPI_LIBRARIES} ${TCTI_SOCKET_LIBRARIES} ${TCTI_DEVICE_LIBRARIES} ${TCTI_TABRMD_LIBRARIES}) if(TCTI_SOCKET_FOUND) target_compile_definitions(tpm2-pk11 PUBLIC TCTI_SOCKET_ENABLED=1) endif() if(TCTI_DEVICE_FOUND) target_compile_definitions(tpm2-pk11 PUBLIC TCTI_DEVICE_ENABLED=1) endif() if(TCTI_TABRMD_FOUND) target_compile_definitions(tpm2-pk11 PUBLIC TCTI_TABRMD_ENABLED=1) endif() install(TARGETS tpm2-pk11 DESTINATION ${CMAKE_INSTALL_LIBDIR}) ./config.sample0000644000000000000000000000066413200730623012363 0ustar rootroot# Type can be device/socket/tabrmd type device # Hostname to connect when using socket hostname localhost # Port number of TPM socket to connect to port 2321 # Device to use as TPM device /dev/tpm0 # Sign using encrypt in case TPM doesn't support hash format # For example SSH use SHA512 which isn't supported by all TPM's # Enabling this option requires key's to be encryption keys instead of signing only keys sign-using-encrypt true ./src/0000755000000000000000000000000013200730623010474 5ustar rootroot./src/certificate.h0000644000000000000000000000161013200730623013125 0ustar rootroot/* * This file is part of tpm2-pk11. * Copyright (C) 2017 Iwan Timmer * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "object.h" pObject certificate_read(const char* pathname); ./src/utils.c0000644000000000000000000000346713200730623012012 0ustar rootroot/* * This file is part of tpm2-pk11. * Copyright (C) 2017 Iwan Timmer * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include #include #include #include #include void strncpy_pad(char *dest, const char *src, size_t n) { size_t len = strlen(src); memcpy(dest, src, len < n ? len : n); if (len < n) memset(dest + len, ' ', n - len); } void retmem(void* dest, size_t* size, const void* src, size_t n) { if (n <= *size) memcpy(dest, src, n); *size = n; } void* read_file(const char* filename, size_t* length) { int fd = open(filename, O_RDONLY); if (fd < 0) { *length = 0; return NULL; } struct stat s; char* buffer = NULL; int ret = fstat(fd, &s); if (ret < 0) { *length = 0; goto cleanup; } size_t pre_length = *length; *length = s.st_size; buffer = malloc(*length + pre_length); printf("Is %d, %x, %x\n", pre_length, buffer, buffer + pre_length); if (buffer == NULL || read(fd, buffer + pre_length, *length) != *length) *length = 0; cleanup: close(fd); return buffer; } ./src/object.c0000644000000000000000000000276413200730623012117 0ustar rootroot/* * This file is part of tpm2-pk11. * Copyright (C) 2017 Iwan Timmer * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "object.h" void* attr_get(pObject object, CK_ATTRIBUTE_TYPE type, size_t *size) { for (int i = 0; i < object->num_entries; i++) { pAttrIndexEntry entries = &object->entries[i]; for (int j = 0; j < entries->num_attrs; j++) { if (type == entries->indexes[j].type) { pAttrIndex index = &entries->indexes[j]; if (index->size_offset == 0) { if (size) *size = index->size; return entries->object + index->offset; } else { if (size) *size = *((size_t*) (entries->object + index->size_offset)); return *((void**) (entries->object + index->offset)); } } } } return NULL; } ./src/pk11.c0000644000000000000000000004535013200730623011423 0ustar rootroot/* * This file is part of tpm2-pk11. * Copyright (C) 2017 Iwan Timmer * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "pk11.h" #include "config.h" #include "sessions.h" #include "utils.h" #include "tpm.h" #include "object.h" #include #include #include #define SLOT_ID 0x1234 #define get_session(x) ((struct session*) x) static struct config pk11_config = {0}; CK_RV C_GetInfo(CK_INFO_PTR pInfo) { pInfo->cryptokiVersion.major = CRYPTOKI_VERSION_MAJOR; pInfo->cryptokiVersion.minor = CRYPTOKI_VERSION_MINOR; strncpy_pad(pInfo->manufacturerID, TPM2_PK11_MANUFACTURER, sizeof(pInfo->manufacturerID)); strncpy_pad(pInfo->libraryDescription, TPM2_PK11_LIBRARY_DESCRIPTION, sizeof(pInfo->libraryDescription)); pInfo->flags = 0; return CKR_OK; } CK_RV C_GetSlotList(CK_BBOOL tokenPresent, CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pusCount) { if (*pusCount && pSlotList) *pSlotList = SLOT_ID; *pusCount = 1; return CKR_OK; } CK_RV C_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags, CK_VOID_PTR pApplication, CK_RV (*Notify) (CK_SESSION_HANDLE hSession, CK_NOTIFICATION event, CK_VOID_PTR pApplication), CK_SESSION_HANDLE_PTR phSession) { *phSession = (unsigned long) malloc(sizeof(struct session)); if ((void*) *phSession == NULL) return CKR_GENERAL_ERROR; int ret = session_init((struct session*) *phSession, &pk11_config); return ret != 0 ? CKR_GENERAL_ERROR : CKR_OK; } CK_RV C_CloseSession(CK_SESSION_HANDLE hSession) { session_close(get_session(hSession)); free(get_session(hSession)); return CKR_OK; } CK_RV C_GetSessionInfo(CK_SESSION_HANDLE hSession, CK_SESSION_INFO_PTR pInfo) { pInfo->slotID = 0; pInfo->state = CKS_RO_USER_FUNCTIONS; pInfo->flags = CKF_SERIAL_SESSION; pInfo->ulDeviceError = 0; return CKR_OK; } CK_RV C_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { strncpy_pad(pInfo->manufacturerID, TPM2_PK11_MANUFACTURER, sizeof(pInfo->manufacturerID)); strncpy_pad(pInfo->slotDescription, TPM2_PK11_SLOT_DESCRIPTION, sizeof(pInfo->slotDescription)); pInfo->flags = CKF_TOKEN_PRESENT | CKF_HW_SLOT; pInfo->hardwareVersion.major = 0; pInfo->hardwareVersion.minor = 0; pInfo->firmwareVersion.major = 0; pInfo->firmwareVersion.minor = 0; return CKR_OK; } CK_RV C_GetTokenInfo(CK_SLOT_ID slotID, CK_TOKEN_INFO_PTR pInfo) { strncpy_pad(pInfo->label, TPM2_PK11_LABEL, sizeof(pInfo->label)); strncpy_pad(pInfo->manufacturerID, TPM2_PK11_MANUFACTURER, sizeof(pInfo->manufacturerID)); strncpy_pad(pInfo->model, TPM2_PK11_MODEL, sizeof(pInfo->label)); strncpy_pad(pInfo->serialNumber, TPM2_PK11_SERIAL, sizeof(pInfo->serialNumber)); strncpy_pad(pInfo->utcTime, "", sizeof(pInfo->utcTime)); pInfo->flags = CKF_TOKEN_INITIALIZED; pInfo->ulMaxSessionCount = 1; pInfo->ulSessionCount = 0; pInfo->ulMaxRwSessionCount = 1; pInfo->ulRwSessionCount = 0; pInfo->ulMaxPinLen = 64; pInfo->ulMinPinLen = 8; pInfo->ulTotalPublicMemory = 8; pInfo->ulFreePublicMemory = 8; pInfo->ulTotalPrivateMemory = 8; pInfo->ulFreePrivateMemory = 8; pInfo->hardwareVersion.major = 0; pInfo->hardwareVersion.minor = 0; pInfo->firmwareVersion.major = 0; pInfo->firmwareVersion.minor = 0; return CKR_OK; } CK_RV C_Finalize(CK_VOID_PTR pReserved) { return CKR_OK; } CK_RV C_FindObjectsInit(CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR filters, CK_ULONG nfilters) { struct session *session = get_session(hSession); session->find_cursor = session->objects; session->filters = filters; session->num_filters = nfilters; return CKR_OK; } CK_RV C_FindObjects(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE_PTR phObject, CK_ULONG usMaxObjectCount, CK_ULONG_PTR nfound) { TPMS_CAPABILITY_DATA persistent; tpm_list(get_session(hSession)->context, &persistent); struct session* session = get_session(hSession); *nfound = 0; while (session->find_cursor != NULL && *nfound < usMaxObjectCount) { pObject object = session->find_cursor->object; bool filtered = false; for (int j = 0; j < session->num_filters; j++) { size_t size = 0; void* value = attr_get(object, session->filters[j].type, &size); if (session->filters[j].ulValueLen != size || memcmp(session->filters[j].pValue, value, size) != 0) { filtered = true; break; } } if (!filtered) { phObject[*nfound] = (CK_OBJECT_HANDLE) session->find_cursor->object; (*nfound)++; } session->find_cursor = session->find_cursor->next; } return CKR_OK; } CK_RV C_FindObjectsFinal(CK_SESSION_HANDLE hSession) { return CKR_OK; } CK_RV C_GetAttributeValue(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG usCount) { pObject object = (pObject) hObject; for (int i = 0; i < usCount; i++) { for (int j = 0; j < object->num_entries; j++) { void *obj = object->entries[j].object; pAttrIndex index = object->entries[j].indexes; for (int k = 0; k < object->entries[j].num_attrs; k++) { if (pTemplate[i].type == index[k].type) { if (index[k].size_offset == 0) retmem(pTemplate[i].pValue, &pTemplate[i].ulValueLen, obj + index[k].offset, index[k].size); else retmem(pTemplate[i].pValue, &pTemplate[i].ulValueLen, *((void**) (obj + index[k].offset)), *((size_t*) (obj + index[k].size_offset))); } } } } return CKR_OK; } CK_RV C_SignInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { pObject object = (pObject) hKey; get_session(hSession)->keyHandle = object->tpm_handle; get_session(hSession)->current_object = object; return CKR_OK; } CK_RV C_Sign(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG usDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pusSignatureLen) { struct session* session = get_session(hSession); TPM_RC ret; if (pk11_config.sign_using_encrypt) { TPM2B_PUBLIC_KEY_RSA message = { .t.size = MAX_RSA_KEY_BYTES }; pObject object = session->current_object->opposite; CK_ULONG_PTR key_size = (CK_ULONG_PTR) attr_get(object, CKA_MODULUS_BITS, NULL); ret = tpm_sign_encrypt(session->context, session->keyHandle, *key_size / 8, pData, usDataLen, &message); retmem(pSignature, pusSignatureLen, message.t.buffer, message.t.size); } else { TPMT_SIGNATURE signature = {0}; ret = tpm_sign(session->context, session->keyHandle, pData, usDataLen, &signature); retmem(pSignature, pusSignatureLen, signature.signature.rsassa.sig.t.buffer, signature.signature.rsassa.sig.t.size); } return ret == TPM_RC_SUCCESS ? CKR_OK : CKR_GENERAL_ERROR; } CK_RV C_DecryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { pObject object = (pObject) hKey; get_session(hSession)->keyHandle = object->tpm_handle; return CKR_OK; } CK_RV C_Decrypt(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) { TPM2B_PUBLIC_KEY_RSA message = { .t.size = MAX_RSA_KEY_BYTES }; struct session* session = get_session(hSession); TPM_RC ret = tpm_decrypt(session->context, session->keyHandle, pEncryptedData, ulEncryptedDataLen, &message); retmem(pData, pulDataLen, message.t.buffer, message.t.size); return ret == TPM_RC_SUCCESS ? CKR_OK : CKR_GENERAL_ERROR; } CK_RV C_Initialize(CK_VOID_PTR pInitArgs) { char configfile_path[256]; snprintf(configfile_path, sizeof(configfile_path), "%s/" TPM2_PK11_CONFIG_DIR "/" TPM2_PK11_CONFIG_FILE, getenv("HOME")); if (config_load(configfile_path, &pk11_config) < 0) return CKR_GENERAL_ERROR; return CKR_OK; } /* Stubs for not yet supported functions*/ CK_RV C_GetMechanismList(CK_SLOT_ID slotID, CK_MECHANISM_TYPE_PTR pMechanismList, CK_ULONG_PTR pulCount) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_GetMechanismInfo (CK_SLOT_ID slotID, CK_MECHANISM_TYPE type, CK_MECHANISM_INFO_PTR pInfo) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_InitToken (CK_SLOT_ID slotID, CK_CHAR_PTR pPin, CK_ULONG usPinLen, CK_CHAR_PTR pLabel) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_InitPIN (CK_SESSION_HANDLE hSession, CK_CHAR_PTR pPin, CK_ULONG usPinLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_SetPIN (CK_SESSION_HANDLE hSession, CK_CHAR_PTR pOldPin, CK_ULONG usOldLen, CK_CHAR_PTR pNewPin, CK_ULONG usNewLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_CloseAllSessions (CK_SLOT_ID slotID) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_GetOperationState(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pOperationState, CK_ULONG_PTR pulOperationStateLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_SetOperationState(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pOperationState, CK_ULONG ulOperationStateLen, CK_OBJECT_HANDLE hEncryptionKey, CK_OBJECT_HANDLE hAuthenticationKey) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, CK_UTF8CHAR_PTR pPin, CK_ULONG ulPinLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_Logout(CK_SESSION_HANDLE hSession) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_CreateObject(CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phObject) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_CopyObject(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phNewObject) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_DestroyObject(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_GetObjectSize(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_SetAttributeValue(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_EncryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hObject) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_Encrypt(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_EncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_EncryptFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_DecryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, CK_ULONG_PTR pDataLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_DecryptFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG_PTR pDataLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_DigestInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_Digest(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pDigest, CK_ULONG_PTR pulDigestLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_DigestUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_DigestKey(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_DigestFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pDigest, CK_ULONG_PTR pulDigestLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_SignUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_SignFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_SignRecoverInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_SignRecover(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_VerifyInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_Verify(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_VerifyUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_VerifyFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_VerifyRecoverInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_VerifyRecover(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen, CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_DigestEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, CK_ULONG_PTR pulEncryptedPartLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_DecryptDigestUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen, CK_BYTE_PTR pDecryptedPart, CK_ULONG_PTR pulDecryptedPartLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_SignEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, CK_ULONG_PTR pulEncryptedPartLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_DecryptVerifyUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedPart, CK_ULONG ulEncryptedPartLen, CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_GenerateKey(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_GenerateKeyPair(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pPublicKeyTemplate, CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, CK_OBJECT_HANDLE_PTR phPrivateKey) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_WrapKey(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hWrappingKey, CK_OBJECT_HANDLE hKey, CK_BYTE_PTR pWrappedKey, CK_ULONG_PTR pulWrappedKeyLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_UnwrapKey(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hUnwrappingKey, CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_DeriveKey(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_SeedRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSeed, CK_ULONG ulSeedLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_GenerateRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pRandomData, CK_ULONG ulRandomLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_GetFunctionStatus(CK_SESSION_HANDLE hSession) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_CancelFunction(CK_SESSION_HANDLE hSession) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_RV C_WaitForSlotEvent(CK_FLAGS flags, CK_SLOT_ID_PTR pSlot, CK_VOID_PTR pReserved) { return CKR_FUNCTION_NOT_SUPPORTED; } static CK_FUNCTION_LIST function_list = { { CRYPTOKI_VERSION_MAJOR, CRYPTOKI_VERSION_MINOR }, .C_Initialize = C_Initialize, .C_Finalize = C_Finalize, .C_GetInfo = C_GetInfo, .C_GetSlotList = C_GetSlotList, .C_GetSlotInfo = C_GetSlotInfo, .C_GetTokenInfo = C_GetTokenInfo, .C_GetMechanismList = C_GetMechanismList, .C_GetMechanismInfo = C_GetMechanismInfo, .C_InitToken = C_InitToken, .C_InitPIN = C_InitPIN, .C_SetPIN = C_SetPIN, .C_OpenSession = C_OpenSession, .C_CloseSession = C_CloseSession, .C_CloseAllSessions = C_CloseAllSessions, .C_GetSessionInfo = C_GetSessionInfo, .C_CloseAllSessions = C_CloseAllSessions, .C_GetOperationState = C_GetOperationState, .C_SetOperationState = C_SetOperationState, .C_Login = C_Login, .C_Logout = C_Logout, .C_CreateObject = C_CreateObject, .C_CopyObject = C_CopyObject, .C_DestroyObject = C_DestroyObject, .C_GetObjectSize = C_GetObjectSize, .C_GetAttributeValue = C_GetAttributeValue, .C_SetAttributeValue = C_SetAttributeValue, .C_FindObjectsInit = C_FindObjectsInit, .C_FindObjects = C_FindObjects, .C_FindObjectsFinal = C_FindObjectsFinal, .C_EncryptInit = C_EncryptInit, .C_Encrypt = C_Encrypt, .C_EncryptUpdate = C_EncryptUpdate, .C_EncryptFinal = C_EncryptFinal, .C_DecryptInit = C_DecryptInit, .C_Decrypt = C_Decrypt, .C_DecryptUpdate = C_DecryptUpdate, .C_DecryptFinal = C_DecryptFinal, .C_DigestInit = C_DigestInit, .C_Digest = C_Digest, .C_DigestUpdate = C_DigestUpdate, .C_DigestKey = C_DigestKey, .C_DigestFinal = C_DigestFinal, .C_SignInit = C_SignInit, .C_Sign = C_Sign, .C_SignUpdate = C_SignUpdate, .C_SignFinal = C_SignFinal, .C_SignRecoverInit = C_SignRecoverInit, .C_SignRecover = C_SignRecover, .C_VerifyInit = C_VerifyInit, .C_Verify = C_Verify, .C_VerifyUpdate = C_VerifyUpdate, .C_VerifyFinal = C_VerifyFinal, .C_VerifyRecoverInit = C_VerifyRecoverInit, .C_VerifyRecover = C_VerifyRecover, .C_DigestEncryptUpdate = C_DigestEncryptUpdate, .C_DecryptDigestUpdate = C_DecryptDigestUpdate, .C_SignEncryptUpdate = C_SignEncryptUpdate, .C_DecryptVerifyUpdate = C_DecryptVerifyUpdate, .C_GenerateKey = C_GenerateKey, .C_GenerateKeyPair = C_GenerateKeyPair, .C_WrapKey = C_WrapKey, .C_UnwrapKey = C_UnwrapKey, .C_DeriveKey = C_DeriveKey, .C_SeedRandom = C_SeedRandom, .C_GenerateRandom = C_GenerateRandom, .C_GetFunctionStatus = C_GetFunctionStatus, .C_CancelFunction = C_CancelFunction, .C_WaitForSlotEvent = C_WaitForSlotEvent, }; CK_RV C_GetFunctionList(CK_FUNCTION_LIST_PTR_PTR ppFunctionList) { if (ppFunctionList == NULL_PTR) return CKR_ARGUMENTS_BAD; *ppFunctionList = &function_list; return CKR_OK; } ./src/pk11.h0000644000000000000000000000322113200730623011417 0ustar rootroot/* * This file is part of tpm2-pk11. * Copyright (C) 2017 Iwan Timmer * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include #include #define TPM2_PK11_CONFIG_DIR ".tpm2" #define TPM2_PK11_CONFIG_FILE "config" #define TPM2_PK11_LABEL "" #define TPM2_PK11_SLOT_DESCRIPTION "TPM2 PKCS11 slot" #define TPM2_PK11_MANUFACTURER "Iwan Timmer" #define TPM2_PK11_LIBRARY_DESCRIPTION "TPM2 PKCS11 Library" #define TPM2_PK11_MODEL "TPM2" #define TPM2_PK11_SERIAL "123456789" typedef struct pkcs_object_t { void* id; size_t id_size; CK_OBJECT_CLASS class; } PkcsObject, *pPkcsObject; typedef struct pkcs_key_t { CK_BBOOL sign; CK_BBOOL decrypt; CK_KEY_TYPE key_type; } PkcsKey, *pPkcsKey; typedef struct pkcs_public_key_t { void* modulus; size_t modulus_size; CK_ULONG bits; uint32_t exponent; } PkcsPublicKey, *pPkcsPublicKey; typedef struct pkcs_x509_t { char* value; size_t value_size; } PkcsX509, *pPkcsX509; ./src/tpm.h0000644000000000000000000000274613200730623011456 0ustar rootroot/* * This file is part of tpm2-pk11. * Copyright (C) 2017 Iwan Timmer * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include TPM_RC tpm_readpublic(TSS2_SYS_CONTEXT *context, TPMI_DH_OBJECT handle, TPM2B_PUBLIC *public, TPM2B_NAME *name); TPM_RC tpm_sign(TSS2_SYS_CONTEXT *context, TPMI_DH_OBJECT handle, unsigned char *hash, unsigned long hashLength, TPMT_SIGNATURE *signature); TPM_RC tpm_decrypt(TSS2_SYS_CONTEXT *context, TPMI_DH_OBJECT handle, unsigned char *cipherText, unsigned long cipherLength, TPM2B_PUBLIC_KEY_RSA *message); TPM_RC tpm_sign_encrypt(TSS2_SYS_CONTEXT *context, TPMI_DH_OBJECT handle, size_t key_size, unsigned char *message, size_t message_length, TPM2B_PUBLIC_KEY_RSA *signature); TPM_RC tpm_list(TSS2_SYS_CONTEXT *context, TPMS_CAPABILITY_DATA* capabilityData); ./src/sessions.h0000644000000000000000000000234413200730623012516 0ustar rootroot/* * This file is part of tpm2-pk11. * Copyright (C) 2017 Iwan Timmer * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "objects.h" #include #include #include struct session { TSS2_SYS_CONTEXT *context; pObjectList objects; TPMI_DH_OBJECT keyHandle; pObjectList find_cursor; CK_ATTRIBUTE_PTR filters; size_t num_filters; pObject current_object; }; int session_init(struct session* session, struct config *config); void session_close(struct session* session); ./src/utils.h0000644000000000000000000000177413200730623012016 0ustar rootroot/* * This file is part of tpm2-pk11. * Copyright (C) 2017 Iwan Timmer * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include void strncpy_pad(char *dest, const char *src, size_t n); void retmem(void* dest, size_t* size, const void* src, size_t n); void* read_file(const char* filename, size_t* length); ./src/certificate.c0000644000000000000000000000501313200730623013121 0ustar rootroot/* * This file is part of tpm2-pk11. * Copyright (C) 2017 Iwan Timmer * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define _GNU_SOURCE #include "object.h" #include "objects.h" #include "pk11.h" #include "utils.h" #include #include #define MAX_ID_BITS 512 typedef struct userdata_certificate_t { char id[MAX_ID_BITS / 4]; PkcsObject object; PkcsX509 certificate; } UserdataCertificate, *pUserdataCertificate; static AttrIndex OBJECT_INDEX[] = { attr_dynamic_index_of(CKA_ID, PkcsObject, id, id_size), attr_index_of(CKA_CLASS, PkcsObject, class) }; static AttrIndex CERTIFICATE_INDEX[] = { attr_dynamic_index_of(CKA_VALUE, PkcsX509, value, value_size), }; pObject certificate_read(const char* pathname) { pObject object = malloc(sizeof(Object)); if (!object) return NULL; size_t size = sizeof(UserdataCertificate); pUserdataCertificate userdata = (pUserdataCertificate) read_file(pathname, &size); if (!userdata) { free(object); return NULL; } userdata->object.class = CKO_CERTIFICATE; userdata->object.id = userdata->id; userdata->object.id_size = 0; char* filename = basename(pathname); while (userdata->object.id_size < sizeof(userdata->id)) { if (sscanf(filename + (userdata->object.id_size * 2), "%2hhx", userdata->id + userdata->object.id_size) != 1) break; else userdata->object.id_size++; } userdata->certificate.value_size = size; userdata->certificate.value = ((char*) userdata) + sizeof(UserdataCertificate); object->userdata = userdata; object->num_entries = 2; object->entries = calloc(object->num_entries, sizeof(AttrIndexEntry)); object->entries[0] = (AttrIndexEntry) attr_index_entry(&userdata->object, OBJECT_INDEX); object->entries[1] = (AttrIndexEntry) attr_index_entry(&userdata->certificate, CERTIFICATE_INDEX); return object; } ./src/objects.c0000644000000000000000000001332613200730623012276 0ustar rootroot/* * This file is part of tpm2-pk11. * Copyright (C) 2017 Iwan Timmer * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define _GNU_SOURCE #include "objects.h" #include "certificate.h" #include "tpm.h" #include "pk11.h" #include #include #include #include typedef struct userdata_tpm_t { TPM2B_PUBLIC tpm_key; TPM2B_NAME name; PkcsObject public_object, private_object; PkcsKey key; PkcsPublicKey public_key; } UserdataTpm, *pUserdataTpm; static AttrIndex OBJECT_INDEX[] = { attr_dynamic_index_of(CKA_ID, PkcsObject, id, id_size), attr_index_of(CKA_CLASS, PkcsObject, class) }; static AttrIndex KEY_INDEX[] = { attr_index_of(CKA_SIGN, PkcsKey, sign), attr_index_of(CKA_DECRYPT, PkcsKey, decrypt), attr_index_of(CKA_KEY_TYPE, PkcsKey, key_type) }; static AttrIndex PUBLIC_KEY_INDEX[] = { attr_dynamic_index_of(CKA_MODULUS, PkcsPublicKey, modulus, modulus_size), attr_index_of(CKA_MODULUS_BITS, PkcsPublicKey, bits), attr_index_of(CKA_PUBLIC_EXPONENT, PkcsPublicKey, exponent) }; pObject object_get(pObjectList list, int id) { while (list != NULL) { if (list->object != NULL && list->object->id == id) return list->object; list = list->next; } return NULL; } void object_add(pObjectList list, pObject object) { if (list->object == NULL) list->object = object; else { pObjectList next = list->next; list->next = malloc(sizeof(ObjectList)); list->next->object = object; list->next->next = next; } } void object_free(pObjectList list) { while (list != NULL) { pObjectList next = list->next; if (list->object != NULL) { pObject object = list->object; if (object->userdata != NULL) free(object->userdata); free(object->entries); free(object); } free(list); list = next; } } pObjectList object_load(TSS2_SYS_CONTEXT *ctx, struct config *config) { pObjectList list = malloc(sizeof(ObjectList)); list->object = NULL; list->next = NULL; if (list == NULL) goto error; TPMS_CAPABILITY_DATA persistent; TPM_RC rc = tpm_list(ctx, &persistent); if (rc != TPM_RC_SUCCESS) goto error; for (int i = 0; i < persistent.data.handles.count; i++) { pUserdataTpm userdata = malloc(sizeof(UserdataTpm)); if (userdata == NULL) goto error; memset(userdata, 0, sizeof(UserdataTpm)); userdata->name.t.size = sizeof(TPMU_NAME); rc = tpm_readpublic(ctx, persistent.data.handles.handle[i], &userdata->tpm_key, &userdata->name); if (rc != TPM_RC_SUCCESS) { free(userdata); goto error; } TPM2B_PUBLIC_KEY_RSA *rsa_key = &userdata->tpm_key.t.publicArea.unique.rsa; TPMS_RSA_PARMS *rsa_key_parms = &userdata->tpm_key.t.publicArea.parameters.rsaDetail; userdata->public_object.id = userdata->name.t.name; userdata->public_object.id_size = userdata->name.t.size; userdata->public_object.class = CKO_PUBLIC_KEY; userdata->private_object.id = userdata->name.t.name; userdata->private_object.id_size = userdata->name.t.size; userdata->private_object.class = CKO_PRIVATE_KEY; userdata->key.sign = CK_TRUE; userdata->key.decrypt = CK_TRUE; userdata->key.key_type = CKK_RSA; userdata->public_key.modulus = rsa_key->b.buffer; userdata->public_key.modulus_size = rsa_key_parms->keyBits / 8; userdata->public_key.bits = rsa_key_parms->keyBits; userdata->public_key.exponent = htobe32(rsa_key_parms->exponent == 0 ? 65537 : rsa_key_parms->exponent); pObject object = malloc(sizeof(Object)); if (object == NULL) { free(userdata); goto error; } object->tpm_handle = NULL; object->userdata = userdata; object->num_entries = 3; object->entries = calloc(object->num_entries, sizeof(AttrIndexEntry)); object->entries[0] = (AttrIndexEntry) attr_index_entry(&userdata->public_object, OBJECT_INDEX); object->entries[1] = (AttrIndexEntry) attr_index_entry(&userdata->key, KEY_INDEX); object->entries[2] = (AttrIndexEntry) attr_index_entry(&userdata->public_key, PUBLIC_KEY_INDEX); object_add(list, object); pObject public_object = object; object = malloc(sizeof(Object)); if (object == NULL) goto error; object->tpm_handle = persistent.data.handles.handle[i]; object->userdata = NULL; object->num_entries = 2; object->entries = calloc(object->num_entries, sizeof(AttrIndexEntry)); object->entries[0] = (AttrIndexEntry) attr_index_entry(&userdata->private_object, OBJECT_INDEX); object->entries[1] = (AttrIndexEntry) attr_index_entry(&userdata->key, KEY_INDEX); object_add(list, object); public_object->opposite = object; object->opposite = public_object; } glob_t results; char search_path[PATH_MAX]; snprintf(search_path, PATH_MAX, "%s/*.der", config->certificates); if (glob(search_path, GLOB_TILDE, NULL, &results) == 0) { for (int i = 0; i < results.gl_pathc; i++) { pObject object = certificate_read(results.gl_pathv[i]); if (object) object_add(list, object); } } return list; error: object_free(list); return NULL; } ./src/objects.h0000644000000000000000000000227613200730623012305 0ustar rootroot/* * This file is part of tpm2-pk11. * Copyright (C) 2017 Iwan Timmer * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "config.h" #include "object.h" #include typedef struct object_list_t { pObject object; struct object_list_t* next; } ObjectList, *pObjectList; pObject object_get(pObjectList list, int id); void object_add(pObjectList list, pObject object); void object_free(pObjectList list); pObjectList object_load(TSS2_SYS_CONTEXT *ctx, struct config *config); ./src/config.h0000644000000000000000000000215013200730623012110 0ustar rootroot/* * This file is part of tpm2-pk11. * Copyright (C) 2017 Iwan Timmer * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include #define TPM_TYPE_DEVICE 0 #define TPM_TYPE_SOCKET 1 #define TPM_TYPE_TABRMD 2 struct config { int type; char* device; char* hostname; char* certificates; unsigned int port; bool sign_using_encrypt; }; int config_load(char* filename, struct config *config); ./src/sessions.c0000644000000000000000000000741113200730623012511 0ustar rootroot/* * This file is part of tpm2-pk11. * Copyright (C) 2017 Iwan Timmer * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "sessions.h" #include #ifdef TCTI_SOCKET_ENABLED #include #endif // TCTI_SOCKET_ENABLED #ifdef TCTI_DEVICE_ENABLED #include #endif // TCTI_DEVICE_ENABLED #ifdef TCTI_TABRMD_ENABLED #include #endif // TCTI_TABRMD_ENABLED #define DEFAULT_DEVICE "/dev/tpm0" #define DEFAULT_HOSTNAME "127.0.0.1" #define DEFAULT_PORT 2323 int session_init(struct session* session, struct config *config) { session->context = NULL; size_t size = 0; TSS2_TCTI_CONTEXT *tcti_ctx = NULL; TSS2_RC rc; TCTI_SOCKET_CONF socket_conf = { .hostname = config->hostname != NULL ? config->hostname : DEFAULT_HOSTNAME, .port = config->port > 0 ? config->port : DEFAULT_PORT, .logCallback = NULL, .logBufferCallback = NULL, .logData = NULL, }; switch(config->type) { #ifdef TCTI_SOCKET_ENABLED case TPM_TYPE_SOCKET: rc = InitSocketTcti(NULL, &size, &socket_conf, 0); break; #endif // TCTI_SOCKET_ENABLED #ifdef TCTI_DEVICE_ENABLED case TPM_TYPE_DEVICE: rc = InitDeviceTcti(NULL, &size, 0); break; #endif // TCTI_DEVICE_ENABLED #ifdef TCTI_TABRMD_ENABLED case TPM_TYPE_TABRMD: rc = tss2_tcti_tabrmd_init(NULL, &size); break; #endif // TCTI_TABRMD_ENABLED default: rc = TSS2_TCTI_RC_NOT_IMPLEMENTED; break; } if (rc != TSS2_RC_SUCCESS) goto cleanup; tcti_ctx = (TSS2_TCTI_CONTEXT*) calloc(1, size); if (tcti_ctx == NULL) goto cleanup; switch(config->type) { #ifdef TCTI_SOCKET_ENABLED case TPM_TYPE_SOCKET: rc = InitSocketTcti(tcti_ctx, &size, &socket_conf, 0); break; #endif // TCTI_SOCKET_ENABLED #ifdef TCTI_DEVICE_ENABLED case TPM_TYPE_DEVICE: { TCTI_DEVICE_CONF conf = { .device_path = config->device != NULL ? config->device : DEFAULT_DEVICE, .logCallback = NULL, .logData = NULL, }; rc = InitDeviceTcti(tcti_ctx, &size, &conf); break; } #endif // TCTI_DEVICE_ENABLED #ifdef TCTI_TABRMD_ENABLED case TPM_TYPE_TABRMD: rc = tss2_tcti_tabrmd_init(tcti_ctx, &size); break; #endif // TCTI_TABRMD_ENABLED default: rc = TSS2_TCTI_RC_NOT_IMPLEMENTED; break; } if (rc != TSS2_RC_SUCCESS) goto cleanup; size = Tss2_Sys_GetContextSize(0); session->context = (TSS2_SYS_CONTEXT*) calloc(1, size); if (session->context == NULL) goto cleanup; TSS2_ABI_VERSION abi_version = { .tssCreator = TSSWG_INTEROP, .tssFamily = TSS_SAPI_FIRST_FAMILY, .tssLevel = TSS_SAPI_FIRST_LEVEL, .tssVersion = TSS_SAPI_FIRST_VERSION, }; rc = Tss2_Sys_Initialize(session->context, size, tcti_ctx, &abi_version); session->objects = object_load(session->context, config); return 0; cleanup: if (tcti_ctx != NULL) free(tcti_ctx); if (session->context != NULL) free(session->context); return -1; } void session_close(struct session* session) { object_free(session->objects); Tss2_Sys_Finalize(session->context); } ./src/tpm.c0000644000000000000000000001207713200730623011447 0ustar rootroot/* * This file is part of tpm2-pk11. * Copyright (C) 2017 Iwan Timmer * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tpm.h" #include const unsigned char oid_sha1[] = {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14}; const unsigned char oid_sha256[] = {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20}; TPM_RC tpm_readpublic(TSS2_SYS_CONTEXT *context, TPMI_DH_OBJECT handle, TPM2B_PUBLIC *public, TPM2B_NAME *name) { TPMS_AUTH_RESPONSE sessionDataOut; TPMS_AUTH_RESPONSE *sessionDataOutArray[1] = {&sessionDataOut}; TSS2_SYS_RSP_AUTHS sessionsDataOut; sessionsDataOut.rspAuths = &sessionDataOutArray[0]; sessionsDataOut.rspAuthsCount = 1; TPM2B_NAME qualifiedName = { .t.size = sizeof(TPMU_NAME) }; return Tss2_Sys_ReadPublic(context, handle, 0, public, name, &qualifiedName, &sessionsDataOut); } TPM_RC tpm_sign(TSS2_SYS_CONTEXT *context, TPMI_DH_OBJECT handle, unsigned char *hash, unsigned long hashLength, TPMT_SIGNATURE *signature) { TPMS_AUTH_COMMAND sessionData = {0}; sessionData.sessionHandle = TPM_RS_PW; TPMS_AUTH_RESPONSE sessionDataOut; TPMS_AUTH_COMMAND *sessionDataArray[1] = {&sessionData}; TPMS_AUTH_RESPONSE *sessionDataOutArray[1] = {&sessionDataOut}; TSS2_SYS_CMD_AUTHS sessionsData; sessionsData.cmdAuths = &sessionDataArray[0]; sessionsData.cmdAuthsCount = 1; TSS2_SYS_RSP_AUTHS sessionsDataOut; sessionsDataOut.rspAuths = &sessionDataOutArray[0]; sessionsDataOut.rspAuthsCount = 1; TPMT_TK_HASHCHECK validation = {0}; validation.tag = TPM_ST_HASHCHECK; validation.hierarchy = TPM_RH_NULL; TPMT_SIG_SCHEME scheme; scheme.scheme = TPM_ALG_RSASSA; int digestSize; if (memcmp(hash, oid_sha1, sizeof(oid_sha1)) == 0) { scheme.details.rsassa.hashAlg = TPM_ALG_SHA1; digestSize = SHA1_DIGEST_SIZE; } else if (memcmp(hash, oid_sha256, sizeof(oid_sha256)) == 0) { scheme.details.rsassa.hashAlg = TPM_ALG_SHA256; digestSize = SHA256_DIGEST_SIZE; } else return TPM_RC_FAILURE; TPM2B_DIGEST digest = { .t.size = digestSize }; // Remove OID from hash if provided memcpy(digest.t.buffer, hash - digestSize + hashLength, hashLength); return Tss2_Sys_Sign(context, handle, &sessionsData, &digest, &scheme, &validation, signature, &sessionsDataOut); } TPM_RC tpm_decrypt(TSS2_SYS_CONTEXT *context, TPMI_DH_OBJECT handle, unsigned char *cipherText, unsigned long cipherLength, TPM2B_PUBLIC_KEY_RSA *message) { TPMS_AUTH_COMMAND sessionData = {0}; sessionData.sessionHandle = TPM_RS_PW; TPMS_AUTH_RESPONSE sessionDataOut; TPMS_AUTH_COMMAND *sessionDataArray[1] = {&sessionData}; TPMS_AUTH_RESPONSE *sessionDataOutArray[1] = {&sessionDataOut}; TSS2_SYS_CMD_AUTHS sessionsData; sessionsData.cmdAuths = &sessionDataArray[0]; sessionsData.cmdAuthsCount = 1; TSS2_SYS_RSP_AUTHS sessionsDataOut; sessionsDataOut.rspAuths = &sessionDataOutArray[0]; sessionsDataOut.rspAuthsCount = 1; TPM2B_DATA label = {0}; TPMT_RSA_DECRYPT scheme; scheme.scheme = TPM_ALG_RSAES; TPM2B_PUBLIC_KEY_RSA cipher = { .t.size = cipherLength }; memcpy(cipher.t.buffer, cipherText, cipherLength); return Tss2_Sys_RSA_Decrypt(context, handle, &sessionsData, &cipher, &scheme, &label, message, &sessionsDataOut); } TPM_RC tpm_sign_encrypt(TSS2_SYS_CONTEXT *context, TPMI_DH_OBJECT handle, size_t key_size, unsigned char *hash, size_t hash_length, TPM2B_PUBLIC_KEY_RSA *signature) { TPMS_AUTH_COMMAND sessionData = {0}; sessionData.sessionHandle = TPM_RS_PW; TPMS_AUTH_COMMAND *sessionDataArray[1] = {&sessionData}; TSS2_SYS_CMD_AUTHS sessionsData; sessionsData.cmdAuths = &sessionDataArray[0]; sessionsData.cmdAuthsCount = 1; TPM2B_PUBLIC_KEY_RSA message = { .t.size = key_size }; unsigned char *p = message.t.buffer; *p++ = 0; *p++ = 1; size_t nb_pad = key_size - hash_length - 3; memset(p, 0xFF, nb_pad); p += nb_pad; *p++ = 0; memcpy(p, hash, hash_length); TPM2B_DATA label = {0}; TPMT_RSA_DECRYPT scheme = { .scheme = TPM_ALG_NULL }; return Tss2_Sys_RSA_Decrypt(context, handle, &sessionsData, &message, &scheme, &label, signature, NULL); } TPM_RC tpm_list(TSS2_SYS_CONTEXT *context, TPMS_CAPABILITY_DATA* capabilityData) { TPMI_YES_NO moreData; return Tss2_Sys_GetCapability(context, 0, TPM_CAP_HANDLES, htobe32(TPM_HT_PERSISTENT), TPM_PT_HR_PERSISTENT, &moreData, capabilityData, 0); } ./src/config.c0000644000000000000000000000446113200730623012112 0ustar rootroot/* * This file is part of tpm2-pk11. * Copyright (C) 2017 Iwan Timmer * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #define _POSIX_C_SOURCE 200809L #include #include #include #include #include #include #include #include #include int config_load(char* filename, struct config *config) { FILE* fd = fopen(filename, "r"); if (fd == NULL) return -ENOENT; char *line = NULL; size_t len = 0; while (getline(&line, &len, fd) != -1) { char *key = NULL, *value = NULL; if (sscanf(line, "%ms %m[^\n]", &key, &value) == 2) { if (strcmp(key, "hostname") == 0) { config->hostname = value; value = NULL; } else if (strcmp(key, "device") == 0) { config->device = value; value = NULL; } else if (strcmp(key, "certificates") == 0) { config->certificates = value; value = NULL; } else if (strcmp(key, "port") == 0) config->port = atoi(value); else if (strcmp(key, "sign-using-encrypt") == 0) config->sign_using_encrypt = strcasecmp(value, "true") == 0; else if (strcmp(key, "type") == 0) { if (strcmp(value, "socket") == 0) config->type = TPM_TYPE_SOCKET; else if (strcmp(value, "device") == 0) config->type = TPM_TYPE_DEVICE; else if (strcmp(value, "tabrmd") == 0) config->type = TPM_TYPE_TABRMD; } } if (key != NULL) free(key); if (value != NULL) free(value); } if (line != NULL) free(line); fclose(fd); return 0; } ./src/object.h0000644000000000000000000000363713200730623012124 0ustar rootroot/* * This file is part of tpm2-pk11. * Copyright (C) 2017 Iwan Timmer * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include #include #include #define NELEMS(x) (sizeof(x) / sizeof((x)[0])) #define attr_index_of(type, struct, attribute) {type, offsetof(struct, attribute), sizeof(((struct*)0)->attribute), 0} #define attr_dynamic_index_of(type, struct, attribute, size_attribute) {type, offsetof(struct, attribute), 0, offsetof(struct, size_attribute)} #define attr_index_entry(object, index) {object, index, NELEMS(index)} typedef struct attr_index_t { CK_ATTRIBUTE_TYPE type; size_t offset; size_t size; size_t size_offset; } AttrIndex, *pAttrIndex; typedef struct attr_index_entry_t { void* object; pAttrIndex indexes; size_t num_attrs; } AttrIndexEntry, *pAttrIndexEntry; typedef struct attr_map_t { CK_ATTRIBUTE_TYPE type; unsigned int len; void* value; struct attr_map_t* next; } AttrMap, *pAttrMap; typedef struct object_t { int id; void* userdata; pAttrIndexEntry entries; size_t num_entries; TPMI_DH_OBJECT tpm_handle; struct object_t *opposite; } Object, *pObject; void* attr_get(pObject object, CK_ATTRIBUTE_TYPE type, size_t *size);