pax_global_header00006660000000000000000000000064134015673230014516gustar00rootroot0000000000000052 comment=fe89b08e35f61a8f9c84b9078ca35b8a079cd5e0 osslsigncode-2.0/000077500000000000000000000000001340156732300140535ustar00rootroot00000000000000osslsigncode-2.0/.gitignore000066400000000000000000000005021340156732300160400ustar00rootroot00000000000000.deps Makefile Makefile.in aclocal.m4 autom4te.cache/ compile config.h config.h.in config.h.in~ config.log config.status configure depcomp install-sh missing osslsigncode osslsigncode.o stamp-h1 .#*# .*.bak .*.orig .*.rej .*~ #*# *.bak *.d *.def *.dll *.exe *.la *.lib *.lo *.orig *.pdb *.rej *.u *.rc *.pc *~ *.gz *.bz2 osslsigncode-2.0/CHANGELOG.md000066400000000000000000000061261340156732300156710ustar00rootroot00000000000000### 2.0 (2018-12-04) - orphaned project adopted by Michał Trojnara - ported to OpenSSL 1.1.x - ported to SoftHSM2 - add support for pkcs11-based hardware tokens (Patch from Leif Johansson) - improved error reporting of timestamping errors (Patch from Carlo Teubner) ### 1.7.1 (2014-07-11) - MSI: added -add-msi-dse option (Patch from Mikkel Krautz) - MSI: fix build when GSF_CAN_READ_MSI_METADATA defined (Patch from Mikkel Krautz) ### 1.7 (2014-07-10) - add support for nested signatures (Patch from Mikkel Krautz) - fix compilation problem with OpenSSL < 1.0.0 - added OpenSSL linkage exception to license ### 1.6 (2014-01-21) - add support for reading password from file - add support for asking for password (on systems that provide support for it) - add support for compiling and running on Windows (Patch from Heiko Hund) - fix compilation without curl (Fix from Heiko Hund) - added support for giving multiple timestamp servers as arguments (first one that succeeds will be used) - signatures on hierarchical MSI files were broken (Fix from Mikkel Krautz) - MSI: Add support for MsiDigitalSignatureEx signature (Patch from Mikkel Krautz) - add support for adding additional/cross certificates through -ac option (Thanks to Lars Munch for idea + testing) - MSI: Add support for signature extract/remove/verify (Patches from Mikkel Krautz) - PE/MSI: Implement -require-leaf-hash for verify. (Patch from Mikkel Krautz) ### 1.5.2 (2013-03-13) - added support for signing with SHA-384 and SHA-512 - added support for page hashing (-ph option) ### 1.5.1 (2013-03-12) - forgot to bump version number... ### 1.5 (2013-03-12) - added support for signing MSI files (patch from Marc-André Lureau) - calculate correct PE checksum instead of setting it to 0 (patch from Roland Schwingel) - added support for RFC3161 timestamping (-ts option) - added support for extracting/removing/verifying signature on PE files - fixed problem with not being able to decode timestamps with no newlines - added stricter checks for PE file validity - added support for reading keys from PVK files (requires OpenSSL 1.0.0 or later) - added support for reading certificates from PEM files - renamed program option: -spc to -certs (old option name still valid) ### 1.4 (2011-08-12) - improved build system (patch from Alon Bar-Lev) - support reading cert+key from PKCS12 file (patch from Alon Bar-Lev) - support reading key from PEM file - added support for sha1/sha256 - default hash is now sha1 - added flag for commercial signing (default is individual) ### 1.3.1 (2009-08-07) - support signing of 64-bit executables (fix from Paul Kendall) ### 1.3 (2008-01-31) - fixed padding problem (fix from Ryan Rubley) - allow signing of already signed files (fix from Ryan Rubley) - added Ryan Rubley's PVK-to-DER guide into the README ### 1.2 (2005-01-21) - autoconf:ed (Thanks to Roy Keene) - added documentation - don't override PKCS7_get_signed_attribute, it wasn't actually needed, it was me being confused. - compiles without curl, which means no timestamping - version number output ### 1.1 (2005-01-19) - Initial release osslsigncode-2.0/COPYING.txt000066400000000000000000001045131340156732300157300ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. 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 them 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 prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. 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. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey 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; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU 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 that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. 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. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 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. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 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 state 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 3 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, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program 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, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU 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. But first, please read . osslsigncode-2.0/LICENSE.txt000066400000000000000000000027421340156732300157030ustar00rootroot00000000000000OpenSSL based Authenticode signing for PE/MSI/Java CAB files. Copyright (C) 2005-2014 Per Allansson Copyright (C) 2018 Michał Trojnara 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 3 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, see . In addition, as a special exception, the copyright holders give permission to link the code of portions of this program with the OpenSSL library under certain conditions as described in each individual source file, and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than OpenSSL. If you modify file(s) with this exception, you may extend this exception to your version of the file(s), but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. If you delete this exception statement from all source files in the program, then also delete it here. osslsigncode-2.0/Makefile.am000066400000000000000000000011061340156732300161050ustar00rootroot00000000000000AUTOMAKE_OPTIONS = foreign 1.10 MAINTAINERCLEANFILES = \ config.log config.status \ $(srcdir)/Makefile.in \ $(srcdir)/config.h.in $(srcdir)/config.h.in~ $(srcdir)/configure \ $(srcdir)/install-sh $(srcdir)/ltmain.sh $(srcdir)/missing \ $(srcdir)/depcomp $(srcdir)/aclocal.m4 $(srcdir)/ylwrap \ $(srcdir)/config.guess $(srcdir)/config.sub EXTRA_DIST = .gitignore AM_CFLAGS = $(GSF_CFLAGS) $(OPENSSL_CFLAGS) $(OPTIONAL_LIBCURL_CFLAGS) bin_PROGRAMS = osslsigncode osslsigncode_SOURCES = osslsigncode.c osslsigncode_LDADD = $(GSF_LIBS) $(OPENSSL_LIBS) $(OPTIONAL_LIBCURL_LIBS) osslsigncode-2.0/README.md000066400000000000000000000115211340156732300153320ustar00rootroot00000000000000osslsigncode ============ ## WHAT IS IT? osslsigncode is a small tool that implements part of the functionality of the Microsoft tool signtool.exe - more exactly the Authenticode signing and timestamping. But osslsigncode is based on OpenSSL and cURL, and thus should be able to compile on most platforms where these exist. ## WHY? Why not use signtool.exe? Because I don't want to go to a Windows machine every time I need to sign a binary - I can compile and build the binaries using Wine on my Linux machine, but I can't sign them since the signtool.exe makes good use of the CryptoAPI in Windows, and these APIs aren't (yet?) fully implemented in Wine, so the signtool.exe tool would fail. And, so, osslsigncode was born. ## WHAT CAN IT DO? It can sign and timestamp PE (EXE/SYS/DLL/etc), CAB and MSI files. It supports the equivalent of signtool.exe's "-j javasign.dll -jp low", i.e. add a valid signature for a CAB file containing Java files. It supports getting the timestamp through a proxy as well. It also supports signature verification, removal and extraction. ## INSTALLATION The usual way: ``` ./configure make make install ``` ## USAGE Before you can sign a file you need a Software Publishing Certificate (spc) and a corresponding private key. This article provides a good starting point as to how to do the signing with the Microsoft signtool.exe: http://www.matthew-jones.com/articles/codesigning.html To sign with osslsigncode you need the certificate file mentioned in the article above, in SPC or PEM format, and you will also need the private key which must be a key file in DER or PEM format, or if osslsigncode was compiled against OpenSSL 1.0.0 or later, in PVK format. To sign a PE or MSI file you can now do: ``` osslsigncode sign -certs -key \ -n "Your Application" -i http://www.yourwebsite.com/ \ -in yourapp.exe -out yourapp-signed.exe ``` or if you are using a PEM or PVK key file with a password together with a PEM certificate: ``` osslsigncode sign -certs \ -key -pass \ -n "Your Application" -i http://www.yourwebsite.com/ \ -in yourapp.exe -out yourapp-signed.exe ``` or if you want to add a timestamp as well: ``` osslsigncode sign -certs -key \ -n "Your Application" -i http://www.yourwebsite.com/ \ -t http://timestamp.verisign.com/scripts/timstamp.dll \ -in yourapp.exe -out yourapp-signed.exe ``` You can use a certificate and key stored in a PKCS#12 container: ``` osslsigncode sign -pkcs12 -pass \ -n "Your Application" -i http://www.yourwebsite.com/ \ -in yourapp.exe -out yourapp-signed.exe ``` To sign a CAB file containing java class files: ``` osslsigncode sign -certs -key \ -n "Your Application" -i http://www.yourwebsite.com/ \ -jp low \ -in yourapp.cab -out yourapp-signed.cab ``` Only the 'low' parameter is currently supported. You can check that the signed file is correct by right-clicking on it in Windows and choose Properties --> Digital Signatures, and then choose the signature from the list, and click on Details. You should then be presented with a dialog that says amongst other things that "This digital signature is OK". ## CONVERTING FROM PVK TO DER (This guide was written by Ryan Rubley) If you've managed to finally find osslsigncode from some searches, you're most likely going to have a heck of a time getting your SPC and PVK files into the formats osslsigncode wants. On the computer where you originally purchased your certificate, you probably had to use IE to get it. Run IE and select Tools/Internet Options from the menu, then under the Content tab, click the Certificates button. Under the Personal tab, select your certificate and click the Export button. On the second page of the wizard, select the PKCS #7 Certificate (.P7B) format. This file you export as a *.p7b is what you use instead of your *.spc file. It's the same basic thing, in a different format. For your PVK file, you will need to download a little utility called PVK.EXE. This can currently be downloaded at http://support.globalsign.net/en/objectsign/PVK.zip Run: ``` pvk -in foo.pvk -nocrypt -out foo.pem ``` This will convert your PVK file to a PEM file. From there, you can copy the PEM file to a Linux box, and run: ``` openssl rsa -outform der -in foo.pem -out foo.der ``` This will convert your PEM file to a DER file. You need the *.p7b and *.der files to use osslsigncode, instead of your *.spc and *.pvk files. ## BUGS, QUESTIONS etc. Send an email to pallansson@gmail.com BUT, if you have questions related to generating spc files, converting between different formats and so on, *please* spend a few minutes searching on google for your particular problem since many people probably already have had your problem and solved it as well. osslsigncode-2.0/README.unauthblob.md000066400000000000000000000054441340156732300175030ustar00rootroot00000000000000# This is NOT the official repo for osslsigncode This project was copied from osslsigncode 1.7.1 to apply some patches for compiling with cygwin and being able to add unauthenticated blobs. The official source for the project is at: http://sourceforge.net/projects/osslsigncode/ ## Features added Adds the argument "-addUnauthenticatedBlob" to add a 1024 byte unauthenticated blob of data to the signature in the same area as the timestamp. This can be used while signing, while timestamping (new `add` command added to allow just time-stamping, after a file has been code signed, or by itself. Examples: ``` # Example 1. Sign and add blob to unsigned file osslsigncode sign -addUnauthenticatedBlob -pkcs12 yourcert.pfx -pass your_password -n "Your Company" -i https://YourSite.com/ -in srepp.msi -out srepp_added.msi ``` ``` # Example 2. Timestamp and add blob to signed file osslsigncode.exe add -addUnauthenticatedBlob -t http://timestamp.verisign.com/scripts/timstamp.dll -in your_signed_file.exe -out out.exe ``` ``` # Example 3. Add blob to signed and time-stamped file osslsigncode.exe add -addUnauthenticatedBlob -in your_signed_file.exe -out out.exe ``` ``` # Example 4. Sign, timestamp, and add blob # Technically you can do this, but this would mean your signing certificate # is on a computer that is connected the Internet, # which means you are doing something wrong, # so I'm not going to show how to do that. ``` This technique (but not this project) is used by Dropbox, GoToMeeting, and Summit Route. You can read more about this technique here: - https://tech.dropbox.com/2014/08/tech-behind-dropboxs-new-user-experience-for-mobile/ - http://blogs.msdn.com/b/ieinternals/archive/2014/09/04/personalizing-installers-using-unauthenticated-data-inside-authenticode-signed-binaries.aspx ## WARNING The capability this adds can allow you to do dumb things. Be very careful with what you put in the unauthenticated blob, as an attacker could modify this. Do NOT under any circumstances put a URL here that you will use to download an additional file. If you do do that, you would need to check the newly downloaded file is code signed AND that it has been signed with your cert AND that it is the version you expect. You should consider using asymmetrical encryption for the data you put in the blob, such that the executable contains the public key to decrypt the data. Basically, be VERY careful. ## Compiling under cygwin - Ensure you install the development libraries for openssl, libgfs, and curl. - Install pkg-config - Run ``` export SHELLOPTS set -o igncr ./configure make ``` ## Download - Compiled binary for cygwin: https://summitroute.com/downloads/osslsigncode.exe - Compiled binary plus all the required DLL's (self-extracting exe): https://summitroute.com/downloads/osslsigncode-cygwin_files.exe osslsigncode-2.0/TODO.md000066400000000000000000000003731340156732300151450ustar00rootroot00000000000000- signature extraction/removal/verificaton on MSI/CAB files - improved signature verification on PE files - clean up / untangle code - separate timestamping - man page - remove mmap usage to increase portability - tests - fix other stuff marked 'XXX' osslsigncode-2.0/autogen.sh000077500000000000000000001344321340156732300160630ustar00rootroot00000000000000#!/bin/sh # a u t o g e n . s h # # Copyright (c) 2005-2009 United States Government as represented by # the U.S. Army Research Laboratory. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # 3. The name of the author may not be used to endorse or promote # products derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ### # # Script for automatically preparing the sources for compilation by # performing the myriad of necessary steps. The script attempts to # detect proper version support, and outputs warnings about particular # systems that have autotool peculiarities. # # Basically, if everything is set up and installed correctly, the # script will validate that minimum versions of the GNU Build System # tools are installed, account for several common configuration # issues, and then simply run autoreconf for you. # # If autoreconf fails, which can happen for many valid configurations, # this script proceeds to run manual preparation steps effectively # providing a POSIX shell script (mostly complete) reimplementation of # autoreconf. # # The AUTORECONF, AUTOCONF, AUTOMAKE, LIBTOOLIZE, ACLOCAL, AUTOHEADER # environment variables and corresponding _OPTIONS variables (e.g. # AUTORECONF_OPTIONS) may be used to override the default automatic # detection behaviors. Similarly the _VERSION variables will override # the minimum required version numbers. # # Examples: # # To obtain help on usage: # ./autogen.sh --help # # To obtain verbose output: # ./autogen.sh --verbose # # To skip autoreconf and prepare manually: # AUTORECONF=false ./autogen.sh # # To verbosely try running with an older (unsupported) autoconf: # AUTOCONF_VERSION=2.50 ./autogen.sh --verbose # # Author: # Christopher Sean Morrison # # Patches: # Sebastian Pipping # ###################################################################### # set to minimum acceptable version of autoconf if [ "x$AUTOCONF_VERSION" = "x" ] ; then AUTOCONF_VERSION=2.52 fi # set to minimum acceptable version of automake if [ "x$AUTOMAKE_VERSION" = "x" ] ; then AUTOMAKE_VERSION=1.6.0 fi # set to minimum acceptable version of libtool if [ "x$LIBTOOL_VERSION" = "x" ] ; then LIBTOOL_VERSION=1.4.2 fi ################## # ident function # ################## ident ( ) { # extract copyright from header __copyright="`grep Copyright $AUTOGEN_SH | head -${HEAD_N}1 | awk '{print $4}'`" if [ "x$__copyright" = "x" ] ; then __copyright="`date +%Y`" fi # extract version from CVS Id string __id="$Id: autogen.sh 33925 2009-03-01 23:27:06Z brlcad $" __version="`echo $__id | sed 's/.*\([0-9][0-9][0-9][0-9]\)[-\/]\([0-9][0-9]\)[-\/]\([0-9][0-9]\).*/\1\2\3/'`" if [ "x$__version" = "x" ] ; then __version="" fi echo "autogen.sh build preparation script by Christopher Sean Morrison" echo " + config.guess download patch by Sebastian Pipping (2008-12-03)" echo "revised 3-clause BSD-style license, copyright (c) $__copyright" echo "script version $__version, ISO/IEC 9945 POSIX shell script" } ################## # USAGE FUNCTION # ################## usage ( ) { echo "Usage: $AUTOGEN_SH [-h|--help] [-v|--verbose] [-q|--quiet] [-d|--download] [--version]" echo " --help Help on $NAME_OF_AUTOGEN usage" echo " --verbose Verbose progress output" echo " --quiet Quiet suppressed progress output" echo " --download Download the latest config.guess from gnulib" echo " --version Only perform GNU Build System version checks" echo echo "Description: This script will validate that minimum versions of the" echo "GNU Build System tools are installed and then run autoreconf for you." echo "Should autoreconf fail, manual preparation steps will be run" echo "potentially accounting for several common preparation issues. The" echo "AUTORECONF, AUTOCONF, AUTOMAKE, LIBTOOLIZE, ACLOCAL, AUTOHEADER," echo "PROJECT, & CONFIGURE environment variables and corresponding _OPTIONS" echo "variables (e.g. AUTORECONF_OPTIONS) may be used to override the" echo "default automatic detection behavior." echo ident return 0 } ########################## # VERSION_ERROR FUNCTION # ########################## version_error ( ) { if [ "x$1" = "x" ] ; then echo "INTERNAL ERROR: version_error was not provided a version" exit 1 fi if [ "x$2" = "x" ] ; then echo "INTERNAL ERROR: version_error was not provided an application name" exit 1 fi $ECHO $ECHO "ERROR: To prepare the ${PROJECT} build system from scratch," $ECHO " at least version $1 of $2 must be installed." $ECHO $ECHO "$NAME_OF_AUTOGEN does not need to be run on the same machine that will" $ECHO "run configure or make. Either the GNU Autotools will need to be installed" $ECHO "or upgraded on this system, or $NAME_OF_AUTOGEN must be run on the source" $ECHO "code on another system and then transferred to here. -- Cheers!" $ECHO } ########################## # VERSION_CHECK FUNCTION # ########################## version_check ( ) { if [ "x$1" = "x" ] ; then echo "INTERNAL ERROR: version_check was not provided a minimum version" exit 1 fi _min="$1" if [ "x$2" = "x" ] ; then echo "INTERNAL ERROR: version check was not provided a comparison version" exit 1 fi _cur="$2" # needed to handle versions like 1.10 and 1.4-p6 _min="`echo ${_min}. | sed 's/[^0-9]/./g' | sed 's/\.\././g'`" _cur="`echo ${_cur}. | sed 's/[^0-9]/./g' | sed 's/\.\././g'`" _min_major="`echo $_min | cut -d. -f1`" _min_minor="`echo $_min | cut -d. -f2`" _min_patch="`echo $_min | cut -d. -f3`" _cur_major="`echo $_cur | cut -d. -f1`" _cur_minor="`echo $_cur | cut -d. -f2`" _cur_patch="`echo $_cur | cut -d. -f3`" if [ "x$_min_major" = "x" ] ; then _min_major=0 fi if [ "x$_min_minor" = "x" ] ; then _min_minor=0 fi if [ "x$_min_patch" = "x" ] ; then _min_patch=0 fi if [ "x$_cur_minor" = "x" ] ; then _cur_major=0 fi if [ "x$_cur_minor" = "x" ] ; then _cur_minor=0 fi if [ "x$_cur_patch" = "x" ] ; then _cur_patch=0 fi $VERBOSE_ECHO "Checking if ${_cur_major}.${_cur_minor}.${_cur_patch} is greater than ${_min_major}.${_min_minor}.${_min_patch}" if [ $_min_major -lt $_cur_major ] ; then return 0 elif [ $_min_major -eq $_cur_major ] ; then if [ $_min_minor -lt $_cur_minor ] ; then return 0 elif [ $_min_minor -eq $_cur_minor ] ; then if [ $_min_patch -lt $_cur_patch ] ; then return 0 elif [ $_min_patch -eq $_cur_patch ] ; then return 0 fi fi fi return 1 } ###################################### # LOCATE_CONFIGURE_TEMPLATE FUNCTION # ###################################### locate_configure_template ( ) { _pwd="`pwd`" if test -f "./configure.ac" ; then echo "./configure.ac" elif test -f "./configure.in" ; then echo "./configure.in" elif test -f "$_pwd/configure.ac" ; then echo "$_pwd/configure.ac" elif test -f "$_pwd/configure.in" ; then echo "$_pwd/configure.in" elif test -f "$PATH_TO_AUTOGEN/configure.ac" ; then echo "$PATH_TO_AUTOGEN/configure.ac" elif test -f "$PATH_TO_AUTOGEN/configure.in" ; then echo "$PATH_TO_AUTOGEN/configure.in" fi } ################## # argument check # ################## ARGS="$*" PATH_TO_AUTOGEN="`dirname $0`" NAME_OF_AUTOGEN="`basename $0`" AUTOGEN_SH="$PATH_TO_AUTOGEN/$NAME_OF_AUTOGEN" LIBTOOL_M4="${PATH_TO_AUTOGEN}/misc/libtool.m4" if [ "x$HELP" = "x" ] ; then HELP=no fi if [ "x$QUIET" = "x" ] ; then QUIET=no fi if [ "x$VERBOSE" = "x" ] ; then VERBOSE=no fi if [ "x$VERSION_ONLY" = "x" ] ; then VERSION_ONLY=no fi if [ "x$DOWNLOAD" = "x" ] ; then DOWNLOAD=no fi if [ "x$AUTORECONF_OPTIONS" = "x" ] ; then AUTORECONF_OPTIONS="-i -f" fi if [ "x$AUTOCONF_OPTIONS" = "x" ] ; then AUTOCONF_OPTIONS="-f" fi if [ "x$AUTOMAKE_OPTIONS" = "x" ] ; then AUTOMAKE_OPTIONS="-a -c -f" fi ALT_AUTOMAKE_OPTIONS="-a -c" if [ "x$LIBTOOLIZE_OPTIONS" = "x" ] ; then LIBTOOLIZE_OPTIONS="--automake -c -f" fi ALT_LIBTOOLIZE_OPTIONS="--automake --copy --force" if [ "x$ACLOCAL_OPTIONS" = "x" ] ; then ACLOCAL_OPTIONS="" fi if [ "x$AUTOHEADER_OPTIONS" = "x" ] ; then AUTOHEADER_OPTIONS="" fi if [ "x$CONFIG_GUESS_URL" = "x" ] ; then CONFIG_GUESS_URL="http://git.savannah.gnu.org/gitweb/?p=gnulib.git;a=blob_plain;f=build-aux/config.guess;hb=HEAD" fi for arg in $ARGS ; do case "x$arg" in x--help) HELP=yes ;; x-[hH]) HELP=yes ;; x--quiet) QUIET=yes ;; x-[qQ]) QUIET=yes ;; x--verbose) VERBOSE=yes ;; x-[dD]) DOWNLOAD=yes ;; x--download) DOWNLOAD=yes ;; x-[vV]) VERBOSE=yes ;; x--version) VERSION_ONLY=yes ;; *) echo "Unknown option: $arg" echo usage exit 1 ;; esac done ##################### # environment check # ##################### # sanity check before recursions potentially begin if [ ! -f "$AUTOGEN_SH" ] ; then echo "INTERNAL ERROR: $AUTOGEN_SH does not exist" if [ ! "x$0" = "x$AUTOGEN_SH" ] ; then echo "INTERNAL ERROR: dirname/basename inconsistency: $0 != $AUTOGEN_SH" fi exit 1 fi # force locale setting to C so things like date output as expected LC_ALL=C # commands that this script expects for __cmd in echo head tail pwd ; do echo "test" | $__cmd > /dev/null 2>&1 if [ $? != 0 ] ; then echo "INTERNAL ERROR: '${__cmd}' command is required" exit 2 fi done echo "test" | grep "test" > /dev/null 2>&1 if test ! x$? = x0 ; then echo "INTERNAL ERROR: grep command is required" exit 1 fi echo "test" | sed "s/test/test/" > /dev/null 2>&1 if test ! x$? = x0 ; then echo "INTERNAL ERROR: sed command is required" exit 1 fi # determine the behavior of echo case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in *c*,-n*) ECHO_N= ECHO_C=' ' ECHO_T=' ' ;; *c*,* ) ECHO_N=-n ECHO_C= ECHO_T= ;; *) ECHO_N= ECHO_C='\c' ECHO_T= ;; esac # determine the behavior of head case "x`echo 'head' | head -n 1 2>&1`" in *xhead*) HEAD_N="n " ;; *) HEAD_N="" ;; esac # determine the behavior of tail case "x`echo 'tail' | tail -n 1 2>&1`" in *xtail*) TAIL_N="n " ;; *) TAIL_N="" ;; esac VERBOSE_ECHO=: ECHO=: if [ "x$QUIET" = "xyes" ] ; then if [ "x$VERBOSE" = "xyes" ] ; then echo "Verbose output quelled by quiet option. Further output disabled." fi else ECHO=echo if [ "x$VERBOSE" = "xyes" ] ; then echo "Verbose output enabled" VERBOSE_ECHO=echo fi fi # allow a recursive run to disable further recursions if [ "x$RUN_RECURSIVE" = "x" ] ; then RUN_RECURSIVE=yes fi ################################################ # check for help arg and bypass version checks # ################################################ if [ "x`echo $ARGS | sed 's/.*[hH][eE][lL][pP].*/help/'`" = "xhelp" ] ; then HELP=yes fi if [ "x$HELP" = "xyes" ] ; then usage $ECHO "---" $ECHO "Help was requested. No preparation or configuration will be performed." exit 0 fi ####################### # set up signal traps # ####################### untrap_abnormal ( ) { for sig in 1 2 13 15; do trap - $sig done } # do this cleanup whenever we exit. trap ' # start from the root if test -d "$START_PATH" ; then cd "$START_PATH" fi # restore/delete backup files if test "x$PFC_INIT" = "x1" ; then recursive_restore fi ' 0 # trap SIGHUP (1), SIGINT (2), SIGPIPE (13), SIGTERM (15) for sig in 1 2 13 15; do trap ' $ECHO "" $ECHO "Aborting $NAME_OF_AUTOGEN: caught signal '$sig'" # start from the root if test -d "$START_PATH" ; then cd "$START_PATH" fi # clean up on abnormal exit $VERBOSE_ECHO "rm -rf autom4te.cache" rm -rf autom4te.cache if test -f "acinclude.m4.$$.backup" ; then $VERBOSE_ECHO "cat acinclude.m4.$$.backup > acinclude.m4" chmod u+w acinclude.m4 cat acinclude.m4.$$.backup > acinclude.m4 $VERBOSE_ECHO "rm -f acinclude.m4.$$.backup" rm -f acinclude.m4.$$.backup fi { (exit 1); exit 1; } ' $sig done ############################# # look for a configure file # ############################# if [ "x$CONFIGURE" = "x" ] ; then CONFIGURE="`locate_configure_template`" if [ ! "x$CONFIGURE" = "x" ] ; then $VERBOSE_ECHO "Found a configure template: $CONFIGURE" fi else $ECHO "Using CONFIGURE environment variable override: $CONFIGURE" fi if [ "x$CONFIGURE" = "x" ] ; then if [ "x$VERSION_ONLY" = "xyes" ] ; then CONFIGURE=/dev/null else $ECHO $ECHO "A configure.ac or configure.in file could not be located implying" $ECHO "that the GNU Build System is at least not used in this directory. In" $ECHO "any case, there is nothing to do here without one of those files." $ECHO $ECHO "ERROR: No configure.in or configure.ac file found in `pwd`" exit 1 fi fi #################### # get project name # #################### if [ "x$PROJECT" = "x" ] ; then PROJECT="`grep AC_INIT $CONFIGURE | grep -v '.*#.*AC_INIT' | tail -${TAIL_N}1 | sed 's/^[ ]*AC_INIT(\([^,)]*\).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`" if [ "x$PROJECT" = "xAC_INIT" ] ; then # projects might be using the older/deprecated arg-less AC_INIT .. look for AM_INIT_AUTOMAKE instead PROJECT="`grep AM_INIT_AUTOMAKE $CONFIGURE | grep -v '.*#.*AM_INIT_AUTOMAKE' | tail -${TAIL_N}1 | sed 's/^[ ]*AM_INIT_AUTOMAKE(\([^,)]*\).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`" fi if [ "x$PROJECT" = "xAM_INIT_AUTOMAKE" ] ; then PROJECT="project" fi if [ "x$PROJECT" = "x" ] ; then PROJECT="project" fi else $ECHO "Using PROJECT environment variable override: $PROJECT" fi $ECHO "Preparing the $PROJECT build system...please wait" $ECHO ######################## # check for autoreconf # ######################## HAVE_AUTORECONF=no if [ "x$AUTORECONF" = "x" ] ; then for AUTORECONF in autoreconf ; do $VERBOSE_ECHO "Checking autoreconf version: $AUTORECONF --version" $AUTORECONF --version > /dev/null 2>&1 if [ $? = 0 ] ; then HAVE_AUTORECONF=yes break fi done else HAVE_AUTORECONF=yes $ECHO "Using AUTORECONF environment variable override: $AUTORECONF" fi ########################## # autoconf version check # ########################## _acfound=no if [ "x$AUTOCONF" = "x" ] ; then for AUTOCONF in autoconf ; do $VERBOSE_ECHO "Checking autoconf version: $AUTOCONF --version" $AUTOCONF --version > /dev/null 2>&1 if [ $? = 0 ] ; then _acfound=yes break fi done else _acfound=yes $ECHO "Using AUTOCONF environment variable override: $AUTOCONF" fi _report_error=no if [ ! "x$_acfound" = "xyes" ] ; then $ECHO "ERROR: Unable to locate GNU Autoconf." _report_error=yes else _version="`$AUTOCONF --version | head -${HEAD_N}1 | sed 's/[^0-9]*\([0-9\.][0-9\.]*\)/\1/'`" if [ "x$_version" = "x" ] ; then _version="0.0.0" fi $ECHO "Found GNU Autoconf version $_version" version_check "$AUTOCONF_VERSION" "$_version" if [ $? -ne 0 ] ; then _report_error=yes fi fi if [ "x$_report_error" = "xyes" ] ; then version_error "$AUTOCONF_VERSION" "GNU Autoconf" exit 1 fi ########################## # automake version check # ########################## _amfound=no if [ "x$AUTOMAKE" = "x" ] ; then for AUTOMAKE in automake ; do $VERBOSE_ECHO "Checking automake version: $AUTOMAKE --version" $AUTOMAKE --version > /dev/null 2>&1 if [ $? = 0 ] ; then _amfound=yes break fi done else _amfound=yes $ECHO "Using AUTOMAKE environment variable override: $AUTOMAKE" fi _report_error=no if [ ! "x$_amfound" = "xyes" ] ; then $ECHO $ECHO "ERROR: Unable to locate GNU Automake." _report_error=yes else _version="`$AUTOMAKE --version | head -${HEAD_N}1 | sed 's/[^0-9]*\([0-9\.][0-9\.]*\)/\1/'`" if [ "x$_version" = "x" ] ; then _version="0.0.0" fi $ECHO "Found GNU Automake version $_version" version_check "$AUTOMAKE_VERSION" "$_version" if [ $? -ne 0 ] ; then _report_error=yes fi fi if [ "x$_report_error" = "xyes" ] ; then version_error "$AUTOMAKE_VERSION" "GNU Automake" exit 1 fi ######################## # check for libtoolize # ######################## HAVE_LIBTOOLIZE=yes HAVE_ALT_LIBTOOLIZE=no _ltfound=no if [ "x$LIBTOOLIZE" = "x" ] ; then LIBTOOLIZE=libtoolize $VERBOSE_ECHO "Checking libtoolize version: $LIBTOOLIZE --version" $LIBTOOLIZE --version > /dev/null 2>&1 if [ ! $? = 0 ] ; then HAVE_LIBTOOLIZE=no $ECHO if [ "x$HAVE_AUTORECONF" = "xno" ] ; then $ECHO "Warning: libtoolize does not appear to be available." else $ECHO "Warning: libtoolize does not appear to be available. This means that" $ECHO "the automatic build preparation via autoreconf will probably not work." $ECHO "Preparing the build by running each step individually, however, should" $ECHO "work and will be done automatically for you if autoreconf fails." fi # look for some alternates for tool in glibtoolize libtoolize15 libtoolize14 libtoolize13 ; do $VERBOSE_ECHO "Checking libtoolize alternate: $tool --version" _glibtoolize="`$tool --version > /dev/null 2>&1`" if [ $? = 0 ] ; then $VERBOSE_ECHO "Found $tool --version" _glti="`which $tool`" if [ "x$_glti" = "x" ] ; then $VERBOSE_ECHO "Cannot find $tool with which" continue; fi if test ! -f "$_glti" ; then $VERBOSE_ECHO "Cannot use $tool, $_glti is not a file" continue; fi _gltidir="`dirname $_glti`" if [ "x$_gltidir" = "x" ] ; then $VERBOSE_ECHO "Cannot find $tool path with dirname of $_glti" continue; fi if test ! -d "$_gltidir" ; then $VERBOSE_ECHO "Cannot use $tool, $_gltidir is not a directory" continue; fi HAVE_ALT_LIBTOOLIZE=yes LIBTOOLIZE="$tool" $ECHO $ECHO "Fortunately, $tool was found which means that your system may simply" $ECHO "have a non-standard or incomplete GNU Autotools install. If you have" $ECHO "sufficient system access, it may be possible to quell this warning by" $ECHO "running:" $ECHO sudo -V > /dev/null 2>&1 if [ $? = 0 ] ; then $ECHO " sudo ln -s $_glti $_gltidir/libtoolize" $ECHO else $ECHO " ln -s $_glti $_gltidir/libtoolize" $ECHO $ECHO "Run that as root or with proper permissions to the $_gltidir directory" $ECHO fi _ltfound=yes break fi done else _ltfound=yes fi else _ltfound=yes $ECHO "Using LIBTOOLIZE environment variable override: $LIBTOOLIZE" fi ############################ # libtoolize version check # ############################ _report_error=no if [ ! "x$_ltfound" = "xyes" ] ; then $ECHO $ECHO "ERROR: Unable to locate GNU Libtool." _report_error=yes else _version="`$LIBTOOLIZE --version | head -${HEAD_N}1 | sed 's/[^0-9]*\([0-9\.][0-9\.]*\)/\1/'`" if [ "x$_version" = "x" ] ; then _version="0.0.0" fi $ECHO "Found GNU Libtool version $_version" version_check "$LIBTOOL_VERSION" "$_version" if [ $? -ne 0 ] ; then _report_error=yes fi fi if [ "x$_report_error" = "xyes" ] ; then version_error "$LIBTOOL_VERSION" "GNU Libtool" exit 1 fi ##################### # check for aclocal # ##################### if [ "x$ACLOCAL" = "x" ] ; then for ACLOCAL in aclocal ; do $VERBOSE_ECHO "Checking aclocal version: $ACLOCAL --version" $ACLOCAL --version > /dev/null 2>&1 if [ $? = 0 ] ; then break fi done else $ECHO "Using ACLOCAL environment variable override: $ACLOCAL" fi ######################## # check for autoheader # ######################## if [ "x$AUTOHEADER" = "x" ] ; then for AUTOHEADER in autoheader ; do $VERBOSE_ECHO "Checking autoheader version: $AUTOHEADER --version" $AUTOHEADER --version > /dev/null 2>&1 if [ $? = 0 ] ; then break fi done else $ECHO "Using AUTOHEADER environment variable override: $AUTOHEADER" fi ######################### # check if version only # ######################### $VERBOSE_ECHO "Checking whether to only output version information" if [ "x$VERSION_ONLY" = "xyes" ] ; then $ECHO ident $ECHO "---" $ECHO "Version requested. No preparation or configuration will be performed." exit 0 fi ################################# # PROTECT_FROM_CLOBBER FUNCTION # ################################# protect_from_clobber ( ) { PFC_INIT=1 # protect COPYING & INSTALL from overwrite by automake. the # automake force option will (inappropriately) ignore the existing # contents of a COPYING and/or INSTALL files (depending on the # version) instead of just forcing *missing* files like it does # for AUTHORS, NEWS, and README. this is broken but extremely # prevalent behavior, so we protect against it by keeping a backup # of the file that can later be restored. for file in COPYING INSTALL ; do if test -f ${file} ; then if test -f ${file}.$$.protect_from_automake.backup ; then $VERBOSE_ECHO "Already backed up ${file} in `pwd`" else $VERBOSE_ECHO "Backing up ${file} in `pwd`" $VERBOSE_ECHO "cp -p ${file} ${file}.$$.protect_from_automake.backup" cp -p ${file} ${file}.$$.protect_from_automake.backup fi fi done } ############################## # RECURSIVE_PROTECT FUNCTION # ############################## recursive_protect ( ) { # for projects using recursive configure, run the build # preparation steps for the subdirectories. this function assumes # START_PATH was set to pwd before recursion begins so that # relative paths work. # git 'r done, protect COPYING and INSTALL from being clobbered protect_from_clobber if test -d autom4te.cache ; then $VERBOSE_ECHO "Found an autom4te.cache directory, deleting it" $VERBOSE_ECHO "rm -rf autom4te.cache" rm -rf autom4te.cache fi # find configure template _configure="`locate_configure_template`" if [ "x$_configure" = "x" ] ; then return fi # $VERBOSE_ECHO "Looking for configure template found `pwd`/$_configure" # look for subdirs # $VERBOSE_ECHO "Looking for subdirs in `pwd`" _det_config_subdirs="`grep AC_CONFIG_SUBDIRS $_configure | grep -v '.*#.*AC_CONFIG_SUBDIRS' | sed 's/^[ ]*AC_CONFIG_SUBDIRS(\(.*\)).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`" CHECK_DIRS="" for dir in $_det_config_subdirs ; do if test -d "`pwd`/$dir" ; then CHECK_DIRS="$CHECK_DIRS \"`pwd`/$dir\"" fi done # process subdirs if [ ! "x$CHECK_DIRS" = "x" ] ; then $VERBOSE_ECHO "Recursively scanning the following directories:" $VERBOSE_ECHO " $CHECK_DIRS" for dir in $CHECK_DIRS ; do $VERBOSE_ECHO "Protecting files from automake in $dir" cd "$START_PATH" eval "cd $dir" # recursively git 'r done recursive_protect done fi } # end of recursive_protect ############################# # RESTORE_CLOBBERED FUNCION # ############################# restore_clobbered ( ) { # The automake (and autoreconf by extension) -f/--force-missing # option may overwrite COPYING and INSTALL even if they do exist. # Here we restore the files if necessary. spacer=no for file in COPYING INSTALL ; do if test -f ${file}.$$.protect_from_automake.backup ; then if test -f ${file} ; then # compare entire content, restore if needed if test "x`cat ${file}`" != "x`cat ${file}.$$.protect_from_automake.backup`" ; then if test "x$spacer" = "xno" ; then $VERBOSE_ECHO spacer=yes fi # restore the backup $VERBOSE_ECHO "Restoring ${file} from backup (automake -f likely clobbered it)" $VERBOSE_ECHO "rm -f ${file}" rm -f ${file} $VERBOSE_ECHO "mv ${file}.$$.protect_from_automake.backup ${file}" mv ${file}.$$.protect_from_automake.backup ${file} fi # check contents elif test -f ${file}.$$.protect_from_automake.backup ; then $VERBOSE_ECHO "mv ${file}.$$.protect_from_automake.backup ${file}" mv ${file}.$$.protect_from_automake.backup ${file} fi # -f ${file} # just in case $VERBOSE_ECHO "rm -f ${file}.$$.protect_from_automake.backup" rm -f ${file}.$$.protect_from_automake.backup fi # -f ${file}.$$.protect_from_automake.backup done CONFIGURE="`locate_configure_template`" if [ "x$CONFIGURE" = "x" ] ; then return fi _aux_dir="`grep AC_CONFIG_AUX_DIR $CONFIGURE | grep -v '.*#.*AC_CONFIG_AUX_DIR' | tail -${TAIL_N}1 | sed 's/^[ ]*AC_CONFIG_AUX_DIR(\(.*\)).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`" if test ! -d "$_aux_dir" ; then _aux_dir=. fi for file in config.guess config.sub ltmain.sh ; do if test -f "${_aux_dir}/${file}" ; then $VERBOSE_ECHO "rm -f \"${_aux_dir}/${file}.backup\"" rm -f "${_aux_dir}/${file}.backup" fi done } # end of restore_clobbered ############################## # RECURSIVE_RESTORE FUNCTION # ############################## recursive_restore ( ) { # restore COPYING and INSTALL from backup if they were clobbered # for each directory recursively. # git 'r undone restore_clobbered # find configure template _configure="`locate_configure_template`" if [ "x$_configure" = "x" ] ; then return fi # look for subdirs _det_config_subdirs="`grep AC_CONFIG_SUBDIRS $_configure | grep -v '.*#.*AC_CONFIG_SUBDIRS' | sed 's/^[ ]*AC_CONFIG_SUBDIRS(\(.*\)).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`" CHECK_DIRS="" for dir in $_det_config_subdirs ; do if test -d "`pwd`/$dir" ; then CHECK_DIRS="$CHECK_DIRS \"`pwd`/$dir\"" fi done # process subdirs if [ ! "x$CHECK_DIRS" = "x" ] ; then $VERBOSE_ECHO "Recursively scanning the following directories:" $VERBOSE_ECHO " $CHECK_DIRS" for dir in $CHECK_DIRS ; do $VERBOSE_ECHO "Checking files for automake damage in $dir" cd "$START_PATH" eval "cd $dir" # recursively git 'r undone recursive_restore done fi } # end of recursive_restore ####################### # INITIALIZE FUNCTION # ####################### initialize ( ) { # this routine performs a variety of directory-specific # initializations. some are sanity checks, some are preventive, # and some are necessary setup detection. # # this function sets: # CONFIGURE # SEARCH_DIRS # CONFIG_SUBDIRS ################################## # check for a configure template # ################################## CONFIGURE="`locate_configure_template`" if [ "x$CONFIGURE" = "x" ] ; then $ECHO $ECHO "A configure.ac or configure.in file could not be located implying" $ECHO "that the GNU Build System is at least not used in this directory. In" $ECHO "any case, there is nothing to do here without one of those files." $ECHO $ECHO "ERROR: No configure.in or configure.ac file found in `pwd`" exit 1 fi ##################### # detect an aux dir # ##################### _aux_dir="`grep AC_CONFIG_AUX_DIR $CONFIGURE | grep -v '.*#.*AC_CONFIG_AUX_DIR' | tail -${TAIL_N}1 | sed 's/^[ ]*AC_CONFIG_AUX_DIR(\(.*\)).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`" if test ! -d "$_aux_dir" ; then _aux_dir=. else $VERBOSE_ECHO "Detected auxillary directory: $_aux_dir" fi ################################ # detect a recursive configure # ################################ CONFIG_SUBDIRS="" _det_config_subdirs="`grep AC_CONFIG_SUBDIRS $CONFIGURE | grep -v '.*#.*AC_CONFIG_SUBDIRS' | sed 's/^[ ]*AC_CONFIG_SUBDIRS(\(.*\)).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`" for dir in $_det_config_subdirs ; do if test -d "`pwd`/$dir" ; then $VERBOSE_ECHO "Detected recursive configure directory: `pwd`/$dir" CONFIG_SUBDIRS="$CONFIG_SUBDIRS `pwd`/$dir" fi done ########################################################### # make sure certain required files exist for GNU projects # ########################################################### _marker_found="" _marker_found_message_intro='Detected non-GNU marker "' _marker_found_message_mid='" in ' for marker in foreign cygnus ; do _marker_found_message=${_marker_found_message_intro}${marker}${_marker_found_message_mid} _marker_found="`grep 'AM_INIT_AUTOMAKE.*'${marker} $CONFIGURE`" if [ ! "x$_marker_found" = "x" ] ; then $VERBOSE_ECHO "${_marker_found_message}`basename \"$CONFIGURE\"`" break fi if test -f "`dirname \"$CONFIGURE\"/Makefile.am`" ; then _marker_found="`grep 'AUTOMAKE_OPTIONS.*'${marker} Makefile.am`" if [ ! "x$_marker_found" = "x" ] ; then $VERBOSE_ECHO "${_marker_found_message}Makefile.am" break fi fi done if [ "x${_marker_found}" = "x" ] ; then _suggest_foreign=no for file in AUTHORS COPYING ChangeLog INSTALL NEWS README ; do if [ ! -f $file ] ; then $VERBOSE_ECHO "Touching ${file} since it does not exist" _suggest_foreign=yes touch $file fi done if [ "x${_suggest_foreign}" = "xyes" ] ; then $ECHO $ECHO "Warning: Several files expected of projects that conform to the GNU" $ECHO "coding standards were not found. The files were automatically added" $ECHO "for you since you do not have a 'foreign' declaration specified." $ECHO $ECHO "Considered adding 'foreign' to AM_INIT_AUTOMAKE in `basename \"$CONFIGURE\"`" if test -f "`dirname \"$CONFIGURE\"/Makefile.am`" ; then $ECHO "or to AUTOMAKE_OPTIONS in your top-level Makefile.am file." fi $ECHO fi fi ################################################## # make sure certain generated files do not exist # ################################################## for file in config.guess config.sub ltmain.sh ; do if test -f "${_aux_dir}/${file}" ; then $VERBOSE_ECHO "mv -f \"${_aux_dir}/${file}\" \"${_aux_dir}/${file}.backup\"" mv -f "${_aux_dir}/${file}" "${_aux_dir}/${file}.backup" fi done ############################ # search alternate m4 dirs # ############################ SEARCH_DIRS="" for dir in m4 ; do if [ -d $dir ] ; then $VERBOSE_ECHO "Found extra aclocal search directory: $dir" SEARCH_DIRS="$SEARCH_DIRS -I $dir" fi done ###################################### # remove any previous build products # ###################################### if test -d autom4te.cache ; then $VERBOSE_ECHO "Found an autom4te.cache directory, deleting it" $VERBOSE_ECHO "rm -rf autom4te.cache" rm -rf autom4te.cache fi # tcl/tk (and probably others) have a customized aclocal.m4, so can't delete it # if test -f aclocal.m4 ; then # $VERBOSE_ECHO "Found an aclocal.m4 file, deleting it" # $VERBOSE_ECHO "rm -f aclocal.m4" # rm -f aclocal.m4 # fi } # end of initialize() ############## # initialize # ############## # stash path START_PATH="`pwd`" # Before running autoreconf or manual steps, some prep detection work # is necessary or useful. Only needs to occur once per directory, but # does need to traverse the entire subconfigure hierarchy to protect # files from being clobbered even by autoreconf. recursive_protect # start from where we started cd "$START_PATH" # get ready to process initialize ######################################### # DOWNLOAD_GNULIB_CONFIG_GUESS FUNCTION # ######################################### # TODO - should make sure wget/curl exist and/or work before trying to # use them. download_gnulib_config_guess () { # abuse gitweb to download gnulib's latest config.guess via HTTP config_guess_temp="config.guess.$$.download" ret=1 for __cmd in wget curl fetch ; do $VERBOSE_ECHO "Checking for command ${__cmd}" ${__cmd} --version > /dev/null 2>&1 ret=$? if [ ! $ret = 0 ] ; then continue fi __cmd_version=`${__cmd} --version | head -n 1 | sed -e 's/^[^0-9]\+//' -e 's/ .*//'` $VERBOSE_ECHO "Found ${__cmd} ${__cmd_version}" opts="" case ${__cmd} in wget) opts="-O" ;; curl) opts="-o" ;; fetch) opts="-t 5 -f" ;; esac $VERBOSE_ECHO "Running $__cmd \"${CONFIG_GUESS_URL}\" $opts \"${config_guess_temp}\"" eval "$__cmd \"${CONFIG_GUESS_URL}\" $opts \"${config_guess_temp}\"" > /dev/null 2>&1 if [ $? = 0 ] ; then mv -f "${config_guess_temp}" ${_aux_dir}/config.guess ret=0 break fi done if [ ! $ret = 0 ] ; then $ECHO "Warning: config.guess download failed from: $CONFIG_GUESS_URL" rm -f "${config_guess_temp}" fi } ############################## # LIBTOOLIZE_NEEDED FUNCTION # ############################## libtoolize_needed () { ret=1 # means no, don't need libtoolize for feature in AC_PROG_LIBTOOL AM_PROG_LIBTOOL LT_INIT ; do $VERBOSE_ECHO "Searching for $feature in $CONFIGURE" found="`grep \"^$feature.*\" $CONFIGURE`" if [ ! "x$found" = "x" ] ; then ret=0 # means yes, need to run libtoolize break fi done return ${ret} } ############################################ # prepare build via autoreconf or manually # ############################################ reconfigure_manually=no if [ "x$HAVE_AUTORECONF" = "xyes" ] ; then $ECHO $ECHO $ECHO_N "Automatically preparing build ... $ECHO_C" $VERBOSE_ECHO "$AUTORECONF $SEARCH_DIRS $AUTORECONF_OPTIONS" autoreconf_output="`$AUTORECONF $SEARCH_DIRS $AUTORECONF_OPTIONS 2>&1`" ret=$? $VERBOSE_ECHO "$autoreconf_output" if [ ! $ret = 0 ] ; then if [ "x$HAVE_ALT_LIBTOOLIZE" = "xyes" ] ; then if [ ! "x`echo \"$autoreconf_output\" | grep libtoolize | grep \"No such file or directory\"`" = "x" ] ; then $ECHO $ECHO "Warning: autoreconf failed but due to what is usually a common libtool" $ECHO "misconfiguration issue. This problem is encountered on systems that" $ECHO "have installed libtoolize under a different name without providing a" $ECHO "symbolic link or without setting the LIBTOOLIZE environment variable." $ECHO $ECHO "Restarting the preparation steps with LIBTOOLIZE set to $LIBTOOLIZE" export LIBTOOLIZE RUN_RECURSIVE=no export RUN_RECURSIVE untrap_abnormal $VERBOSE_ECHO sh $AUTOGEN_SH "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9" sh "$AUTOGEN_SH" "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9" exit $? fi fi $ECHO "Warning: $AUTORECONF failed" if test -f ltmain.sh ; then $ECHO "libtoolize being run by autoreconf is not creating ltmain.sh in the auxillary directory like it should" fi $ECHO "Attempting to run the preparation steps individually" reconfigure_manually=yes else if [ "x$DOWNLOAD" = "xyes" ] ; then if libtoolize_needed ; then download_gnulib_config_guess fi fi fi else reconfigure_manually=yes fi ############################ # LIBTOOL_FAILURE FUNCTION # ############################ libtool_failure ( ) { # libtool is rather error-prone in comparison to the other # autotools and this routine attempts to compensate for some # common failures. the output after a libtoolize failure is # parsed for an error related to AC_PROG_LIBTOOL and if found, we # attempt to inject a project-provided libtool.m4 file. _autoconf_output="$1" if [ "x$RUN_RECURSIVE" = "xno" ] ; then # we already tried the libtool.m4, don't try again return 1 fi if test -f "$LIBTOOL_M4" ; then found_libtool="`$ECHO $_autoconf_output | grep AC_PROG_LIBTOOL`" if test ! "x$found_libtool" = "x" ; then if test -f acinclude.m4 ; then rm -f acinclude.m4.$$.backup $VERBOSE_ECHO "cat acinclude.m4 > acinclude.m4.$$.backup" cat acinclude.m4 > acinclude.m4.$$.backup fi $VERBOSE_ECHO "cat \"$LIBTOOL_M4\" >> acinclude.m4" chmod u+w acinclude.m4 cat "$LIBTOOL_M4" >> acinclude.m4 # don't keep doing this RUN_RECURSIVE=no export RUN_RECURSIVE untrap_abnormal $ECHO $ECHO "Restarting the preparation steps with libtool macros in acinclude.m4" $VERBOSE_ECHO sh $AUTOGEN_SH "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9" sh "$AUTOGEN_SH" "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9" exit $? fi fi } ########################### # MANUAL_AUTOGEN FUNCTION # ########################### manual_autogen ( ) { ################################################## # Manual preparation steps taken are as follows: # # aclocal [-I m4] # # libtoolize --automake -c -f # # aclocal [-I m4] # # autoconf -f # # autoheader # # automake -a -c -f # ################################################## ########### # aclocal # ########### $VERBOSE_ECHO "$ACLOCAL $SEARCH_DIRS $ACLOCAL_OPTIONS" aclocal_output="`$ACLOCAL $SEARCH_DIRS $ACLOCAL_OPTIONS 2>&1`" ret=$? $VERBOSE_ECHO "$aclocal_output" if [ ! $ret = 0 ] ; then $ECHO "ERROR: $ACLOCAL failed" && exit 2 ; fi ############## # libtoolize # ############## if libtoolize_needed ; then if [ "x$HAVE_LIBTOOLIZE" = "xyes" ] ; then $VERBOSE_ECHO "$LIBTOOLIZE $LIBTOOLIZE_OPTIONS" libtoolize_output="`$LIBTOOLIZE $LIBTOOLIZE_OPTIONS 2>&1`" ret=$? $VERBOSE_ECHO "$libtoolize_output" if [ ! $ret = 0 ] ; then $ECHO "ERROR: $LIBTOOLIZE failed" && exit 2 ; fi else if [ "x$HAVE_ALT_LIBTOOLIZE" = "xyes" ] ; then $VERBOSE_ECHO "$LIBTOOLIZE $ALT_LIBTOOLIZE_OPTIONS" libtoolize_output="`$LIBTOOLIZE $ALT_LIBTOOLIZE_OPTIONS 2>&1`" ret=$? $VERBOSE_ECHO "$libtoolize_output" if [ ! $ret = 0 ] ; then $ECHO "ERROR: $LIBTOOLIZE failed" && exit 2 ; fi fi fi ########### # aclocal # ########### # re-run again as instructed by libtoolize $VERBOSE_ECHO "$ACLOCAL $SEARCH_DIRS $ACLOCAL_OPTIONS" aclocal_output="`$ACLOCAL $SEARCH_DIRS $ACLOCAL_OPTIONS 2>&1`" ret=$? $VERBOSE_ECHO "$aclocal_output" # libtoolize might put ltmain.sh in the wrong place if test -f ltmain.sh ; then if test ! -f "${_aux_dir}/ltmain.sh" ; then $ECHO $ECHO "Warning: $LIBTOOLIZE is creating ltmain.sh in the wrong directory" $ECHO $ECHO "Fortunately, the problem can be worked around by simply copying the" $ECHO "file to the appropriate location (${_aux_dir}/). This has been done for you." $ECHO $VERBOSE_ECHO "cp -p ltmain.sh \"${_aux_dir}/ltmain.sh\"" cp -p ltmain.sh "${_aux_dir}/ltmain.sh" $ECHO $ECHO_N "Continuing build preparation ... $ECHO_C" fi fi # ltmain.sh if [ "x$DOWNLOAD" = "xyes" ] ; then download_gnulib_config_guess fi fi # libtoolize_needed ############ # autoconf # ############ $VERBOSE_ECHO $VERBOSE_ECHO "$AUTOCONF $AUTOCONF_OPTIONS" autoconf_output="`$AUTOCONF $AUTOCONF_OPTIONS 2>&1`" ret=$? $VERBOSE_ECHO "$autoconf_output" if [ ! $ret = 0 ] ; then # retry without the -f and check for usage of macros that are too new ac2_59_macros="AC_C_RESTRICT AC_INCLUDES_DEFAULT AC_LANG_ASSERT AC_LANG_WERROR AS_SET_CATFILE" ac2_55_macros="AC_COMPILER_IFELSE AC_FUNC_MBRTOWC AC_HEADER_STDBOOL AC_LANG_CONFTEST AC_LANG_SOURCE AC_LANG_PROGRAM AC_LANG_CALL AC_LANG_FUNC_TRY_LINK AC_MSG_FAILURE AC_PREPROC_IFELSE" ac2_54_macros="AC_C_BACKSLASH_A AC_CONFIG_LIBOBJ_DIR AC_GNU_SOURCE AC_PROG_EGREP AC_PROG_FGREP AC_REPLACE_FNMATCH AC_FUNC_FNMATCH_GNU AC_FUNC_REALLOC AC_TYPE_MBSTATE_T" macros_to_search="" ac_major="`echo ${AUTOCONF_VERSION}. | cut -d. -f1 | sed 's/[^0-9]//g'`" ac_minor="`echo ${AUTOCONF_VERSION}. | cut -d. -f2 | sed 's/[^0-9]//g'`" if [ $ac_major -lt 2 ] ; then macros_to_search="$ac2_59_macros $ac2_55_macros $ac2_54_macros" else if [ $ac_minor -lt 54 ] ; then macros_to_search="$ac2_59_macros $ac2_55_macros $ac2_54_macros" elif [ $ac_minor -lt 55 ] ; then macros_to_search="$ac2_59_macros $ac2_55_macros" elif [ $ac_minor -lt 59 ] ; then macros_to_search="$ac2_59_macros" fi fi configure_ac_macros=__none__ for feature in $macros_to_search ; do $VERBOSE_ECHO "Searching for $feature in $CONFIGURE" found="`grep \"^$feature.*\" $CONFIGURE`" if [ ! "x$found" = "x" ] ; then if [ "x$configure_ac_macros" = "x__none__" ] ; then configure_ac_macros="$feature" else configure_ac_macros="$feature $configure_ac_macros" fi fi done if [ ! "x$configure_ac_macros" = "x__none__" ] ; then $ECHO $ECHO "Warning: Unsupported macros were found in $CONFIGURE" $ECHO $ECHO "The `basename \"$CONFIGURE\"` file was scanned in order to determine if any" $ECHO "unsupported macros are used that exceed the minimum version" $ECHO "settings specified within this file. As such, the following macros" $ECHO "should be removed from configure.ac or the version numbers in this" $ECHO "file should be increased:" $ECHO $ECHO "$configure_ac_macros" $ECHO $ECHO $ECHO_N "Ignorantly continuing build preparation ... $ECHO_C" fi ################### # autoconf, retry # ################### $VERBOSE_ECHO $VERBOSE_ECHO "$AUTOCONF" autoconf_output="`$AUTOCONF 2>&1`" ret=$? $VERBOSE_ECHO "$autoconf_output" if [ ! $ret = 0 ] ; then # test if libtool is busted libtool_failure "$autoconf_output" # let the user know what went wrong cat <@])], , [enable_strict="no"] ) AC_ARG_ENABLE( [pedantic], [AS_HELP_STRING([--enable-pedantic],[enable pedantic compile mode @<:@disabled@:>@])], , [enable_pedantic="no"] ) AC_ARG_WITH( [curl], [AS_HELP_STRING([--with-curl],[enable curl @<:@enabled@:>@])], , [with_curl="yes"] ) if test "${enable_pedantic}" = "yes"; then enable_strict="yes"; CFLAGS="${CFLAGS} -pedantic" fi if test "${enable_strict}" = "yes"; then CFLAGS="${CFLAGS} -Wall -Wextra" fi PKG_PROG_PKG_CONFIG AC_PROG_CPP AC_PROG_INSTALL AC_PROG_LN_S AC_PROG_MKDIR_P AC_PROG_SED AC_PROG_MAKE_SET AC_C_CONST AC_HEADER_STDC AC_HEADER_TIME AC_CHECK_HEADERS( [sys/mman.h], [AC_CHECK_FUNC( [mmap], [AC_DEFINE(HAVE_MMAP, [1], [Define to 1 if you have mmap])], [AC_MSG_ERROR([Need mmap to build.])] )], [have_mmap=no] ) AC_CHECK_HEADERS( [windows.h], [], [have_MapViewOfFile=no] ) AS_IF([test "x$have_mmap$have_MapViewOfFile" = "xnono"], [AC_MSG_ERROR([Need file mapping function to buid.])]) AC_CHECK_LIB( [dl], [dlopen], [DL_LIBS="-ldl"] ) AC_CHECK_HEADERS([termios.h]) AC_CHECK_FUNCS(getpass) AC_ARG_WITH([gsf], AS_HELP_STRING([--without-gsf], [Ignore presence of libgsf and disable it]) ) AS_IF([test "x$with_gsf" != "xno"], [PKG_CHECK_MODULES([GSF], [libgsf-1], [have_gsf=yes], [have_gsf=no])], [have_gsf=no] ) AS_IF([test "x$have_gsf" = "xyes"], [AC_DEFINE([WITH_GSF], 1, [Have libgsf?])], [AS_IF([test "x$with_gsf" = "xyes"], [AC_MSG_ERROR([libgsf requested but not found])])] ) PKG_CHECK_MODULES( [OPENSSL], [libcrypto >= 1.1.0], , [PKG_CHECK_MODULES( [OPENSSL], [openssl >= 1.1.0], , [AC_CHECK_LIB( [crypto], [RSA_verify], [OPENSSL_LIBS="-lcrypto ${SOCKETS_LIBS} ${DL_LIBS}"], [AC_MSG_ERROR([OpenSSL 1.1.0 or later is required. http://www.openssl.org/])], [${DL_LIBS}] )] )] ) PKG_CHECK_MODULES( [LIBCURL], [libcurl >= 7.12.0], , [AC_CHECK_LIB( [curl], [curl_easy_strerror], [LIBCURL_LIBS="-lcurl"], , [${DL_LIBS}] )] ) if test "${with_curl}" = "yes"; then test -z "${LIBCURL_LIBS}" && AC_MSG_ERROR([Curl 7.12.0 or later is required for timestamping support. http://curl.haxx.se/]) OPTIONAL_LIBCURL_CFLAGS="${LIBCURL_CFLAGS}" OPTIONAL_LIBCURL_LIBS="${LIBCURL_LIBS}" AC_DEFINE([ENABLE_CURL], [1], [libcurl is enabled]) fi AC_SUBST([OPTIONAL_LIBCURL_CFLAGS]) AC_SUBST([OPTIONAL_LIBCURL_LIBS]) AC_CONFIG_FILES([Makefile]) AC_OUTPUT osslsigncode-2.0/misc/000077500000000000000000000000001340156732300150065ustar00rootroot00000000000000osslsigncode-2.0/misc/pagehash.py000066400000000000000000000061541340156732300171460ustar00rootroot00000000000000#!/usr/bin/python import struct import sys import hashlib from pyasn1.type import univ from pyasn1.codec.ber import encoder, decoder f = open(sys.argv[1], 'rb') filehdr = f.read(1024) if filehdr[0:2] != 'MZ': print "Not a DOS file." sys.exit(0) pepos = struct.unpack('config.py < Copyright (C) 2018 Michał Trojnara 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 3 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, see . In addition, as a special exception, the copyright holders give permission to link the code of portions of this program with the OpenSSL library under certain conditions as described in each individual source file, and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than OpenSSL. If you modify file(s) with this exception, you may extend this exception to your version of the file(s), but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. If you delete this exception statement from all source files in the program, then also delete it here. */ /* Implemented with good help from: * Peter Gutmann's analysis of Authenticode: http://www.cs.auckland.ac.nz/~pgut001/pubs/authenticode.txt * MS CAB SDK documentation http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncabsdk/html/cabdl.asp * MS PE/COFF documentation http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx * MS Windows Authenticode PE Signature Format http://msdn.microsoft.com/en-US/windows/hardware/gg463183 (Although the part of how the actual checksumming is done is not how it is done inside Windows. The end result is however the same on all "normal" PE files.) * tail -c, tcpdump, mimencode & openssl asn1parse :) */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef HAVE_WINDOWS_H #define NOCRYPT #define WIN32_LEAN_AND_MEAN #include typedef unsigned char u_char; #endif #include #include #ifndef _WIN32 #include #endif #include #include #include #include #include #include #ifndef _WIN32 #ifdef HAVE_SYS_MMAN_H #include #endif #ifdef HAVE_TERMIOS_H #include #endif #endif #ifdef WITH_GSF #include #include #include #include #include #include #include #endif #include #include #include #include #include #include #include #include #include #ifndef OPENSSL_NO_ENGINE #include #endif #ifdef ENABLE_CURL #ifdef __CYGWIN__ #ifndef SOCKET #define SOCKET UINT_PTR #endif #endif #include #define MAX_TS_SERVERS 256 #endif #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif #if defined (HAVE_TERMIOS_H) || defined (HAVE_GETPASS) #define PROVIDE_ASKPASS 1 #endif /* MS Authenticode object ids */ #define SPC_INDIRECT_DATA_OBJID "1.3.6.1.4.1.311.2.1.4" #define SPC_STATEMENT_TYPE_OBJID "1.3.6.1.4.1.311.2.1.11" #define SPC_SP_OPUS_INFO_OBJID "1.3.6.1.4.1.311.2.1.12" #define SPC_INDIVIDUAL_SP_KEY_PURPOSE_OBJID "1.3.6.1.4.1.311.2.1.21" #define SPC_COMMERCIAL_SP_KEY_PURPOSE_OBJID "1.3.6.1.4.1.311.2.1.22" #define SPC_MS_JAVA_SOMETHING "1.3.6.1.4.1.311.15.1" #define SPC_PE_IMAGE_DATA_OBJID "1.3.6.1.4.1.311.2.1.15" #define SPC_CAB_DATA_OBJID "1.3.6.1.4.1.311.2.1.25" #define SPC_TIME_STAMP_REQUEST_OBJID "1.3.6.1.4.1.311.3.2.1" #define SPC_SIPINFO_OBJID "1.3.6.1.4.1.311.2.1.30" #define SPC_PE_IMAGE_PAGE_HASHES_V1 "1.3.6.1.4.1.311.2.3.1" /* Page hash using SHA1 */ #define SPC_PE_IMAGE_PAGE_HASHES_V2 "1.3.6.1.4.1.311.2.3.2" /* Page hash using SHA256 */ #define SPC_NESTED_SIGNATURE_OBJID "1.3.6.1.4.1.311.2.4.1" #define SPC_RFC3161_OBJID "1.3.6.1.4.1.311.3.3.1" /* 1.3.6.1.4.1.311.4... MS Crypto 2.0 stuff... */ #define WIN_CERT_REVISION_2 0x0200 #define WIN_CERT_TYPE_PKCS_SIGNED_DATA 0x0002 /* ASN.1 definitions (more or less from official MS Authenticode docs) */ typedef struct { int type; union { ASN1_BMPSTRING *unicode; ASN1_IA5STRING *ascii; } value; } SpcString; DECLARE_ASN1_FUNCTIONS(SpcString) ASN1_CHOICE(SpcString) = { ASN1_IMP_OPT(SpcString, value.unicode, ASN1_BMPSTRING , 0), ASN1_IMP_OPT(SpcString, value.ascii, ASN1_IA5STRING, 1) } ASN1_CHOICE_END(SpcString) IMPLEMENT_ASN1_FUNCTIONS(SpcString) typedef struct { ASN1_OCTET_STRING *classId; ASN1_OCTET_STRING *serializedData; } SpcSerializedObject; DECLARE_ASN1_FUNCTIONS(SpcSerializedObject) ASN1_SEQUENCE(SpcSerializedObject) = { ASN1_SIMPLE(SpcSerializedObject, classId, ASN1_OCTET_STRING), ASN1_SIMPLE(SpcSerializedObject, serializedData, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(SpcSerializedObject) IMPLEMENT_ASN1_FUNCTIONS(SpcSerializedObject) typedef struct { int type; union { ASN1_IA5STRING *url; SpcSerializedObject *moniker; SpcString *file; } value; } SpcLink; DECLARE_ASN1_FUNCTIONS(SpcLink) ASN1_CHOICE(SpcLink) = { ASN1_IMP_OPT(SpcLink, value.url, ASN1_IA5STRING, 0), ASN1_IMP_OPT(SpcLink, value.moniker, SpcSerializedObject, 1), ASN1_EXP_OPT(SpcLink, value.file, SpcString, 2) } ASN1_CHOICE_END(SpcLink) IMPLEMENT_ASN1_FUNCTIONS(SpcLink) typedef struct { SpcString *programName; SpcLink *moreInfo; } SpcSpOpusInfo; DECLARE_ASN1_FUNCTIONS(SpcSpOpusInfo) ASN1_SEQUENCE(SpcSpOpusInfo) = { ASN1_EXP_OPT(SpcSpOpusInfo, programName, SpcString, 0), ASN1_EXP_OPT(SpcSpOpusInfo, moreInfo, SpcLink, 1) } ASN1_SEQUENCE_END(SpcSpOpusInfo) IMPLEMENT_ASN1_FUNCTIONS(SpcSpOpusInfo) typedef struct { ASN1_OBJECT *type; ASN1_TYPE *value; } SpcAttributeTypeAndOptionalValue; DECLARE_ASN1_FUNCTIONS(SpcAttributeTypeAndOptionalValue) ASN1_SEQUENCE(SpcAttributeTypeAndOptionalValue) = { ASN1_SIMPLE(SpcAttributeTypeAndOptionalValue, type, ASN1_OBJECT), ASN1_OPT(SpcAttributeTypeAndOptionalValue, value, ASN1_ANY) } ASN1_SEQUENCE_END(SpcAttributeTypeAndOptionalValue) IMPLEMENT_ASN1_FUNCTIONS(SpcAttributeTypeAndOptionalValue) typedef struct { ASN1_OBJECT *algorithm; ASN1_TYPE *parameters; } AlgorithmIdentifier; DECLARE_ASN1_FUNCTIONS(AlgorithmIdentifier) ASN1_SEQUENCE(AlgorithmIdentifier) = { ASN1_SIMPLE(AlgorithmIdentifier, algorithm, ASN1_OBJECT), ASN1_OPT(AlgorithmIdentifier, parameters, ASN1_ANY) } ASN1_SEQUENCE_END(AlgorithmIdentifier) IMPLEMENT_ASN1_FUNCTIONS(AlgorithmIdentifier) typedef struct { AlgorithmIdentifier *digestAlgorithm; ASN1_OCTET_STRING *digest; } DigestInfo; DECLARE_ASN1_FUNCTIONS(DigestInfo) ASN1_SEQUENCE(DigestInfo) = { ASN1_SIMPLE(DigestInfo, digestAlgorithm, AlgorithmIdentifier), ASN1_SIMPLE(DigestInfo, digest, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(DigestInfo) IMPLEMENT_ASN1_FUNCTIONS(DigestInfo) typedef struct { SpcAttributeTypeAndOptionalValue *data; DigestInfo *messageDigest; } SpcIndirectDataContent; DECLARE_ASN1_FUNCTIONS(SpcIndirectDataContent) ASN1_SEQUENCE(SpcIndirectDataContent) = { ASN1_SIMPLE(SpcIndirectDataContent, data, SpcAttributeTypeAndOptionalValue), ASN1_SIMPLE(SpcIndirectDataContent, messageDigest, DigestInfo) } ASN1_SEQUENCE_END(SpcIndirectDataContent) IMPLEMENT_ASN1_FUNCTIONS(SpcIndirectDataContent) typedef struct { ASN1_BIT_STRING* flags; SpcLink *file; } SpcPeImageData; DECLARE_ASN1_FUNCTIONS(SpcPeImageData) ASN1_SEQUENCE(SpcPeImageData) = { ASN1_SIMPLE(SpcPeImageData, flags, ASN1_BIT_STRING), ASN1_EXP_OPT(SpcPeImageData, file, SpcLink, 0) } ASN1_SEQUENCE_END(SpcPeImageData) IMPLEMENT_ASN1_FUNCTIONS(SpcPeImageData) typedef struct { ASN1_INTEGER *a; ASN1_OCTET_STRING *string; ASN1_INTEGER *b; ASN1_INTEGER *c; ASN1_INTEGER *d; ASN1_INTEGER *e; ASN1_INTEGER *f; } SpcSipInfo; DECLARE_ASN1_FUNCTIONS(SpcSipInfo) ASN1_SEQUENCE(SpcSipInfo) = { ASN1_SIMPLE(SpcSipInfo, a, ASN1_INTEGER), ASN1_SIMPLE(SpcSipInfo, string, ASN1_OCTET_STRING), ASN1_SIMPLE(SpcSipInfo, b, ASN1_INTEGER), ASN1_SIMPLE(SpcSipInfo, c, ASN1_INTEGER), ASN1_SIMPLE(SpcSipInfo, d, ASN1_INTEGER), ASN1_SIMPLE(SpcSipInfo, e, ASN1_INTEGER), ASN1_SIMPLE(SpcSipInfo, f, ASN1_INTEGER), } ASN1_SEQUENCE_END(SpcSipInfo) IMPLEMENT_ASN1_FUNCTIONS(SpcSipInfo) #ifdef ENABLE_CURL typedef struct { ASN1_OBJECT *type; ASN1_OCTET_STRING *signature; } TimeStampRequestBlob; DECLARE_ASN1_FUNCTIONS(TimeStampRequestBlob) ASN1_SEQUENCE(TimeStampRequestBlob) = { ASN1_SIMPLE(TimeStampRequestBlob, type, ASN1_OBJECT), ASN1_EXP_OPT(TimeStampRequestBlob, signature, ASN1_OCTET_STRING, 0) } ASN1_SEQUENCE_END(TimeStampRequestBlob) IMPLEMENT_ASN1_FUNCTIONS(TimeStampRequestBlob) typedef struct { ASN1_OBJECT *type; TimeStampRequestBlob *blob; } TimeStampRequest; DECLARE_ASN1_FUNCTIONS(TimeStampRequest) ASN1_SEQUENCE(TimeStampRequest) = { ASN1_SIMPLE(TimeStampRequest, type, ASN1_OBJECT), ASN1_SIMPLE(TimeStampRequest, blob, TimeStampRequestBlob) } ASN1_SEQUENCE_END(TimeStampRequest) IMPLEMENT_ASN1_FUNCTIONS(TimeStampRequest) /* RFC3161 Time stamping */ typedef struct { ASN1_INTEGER *status; STACK_OF(ASN1_UTF8STRING) *statusString; ASN1_BIT_STRING *failInfo; } PKIStatusInfo; DECLARE_ASN1_FUNCTIONS(PKIStatusInfo) ASN1_SEQUENCE(PKIStatusInfo) = { ASN1_SIMPLE(PKIStatusInfo, status, ASN1_INTEGER), ASN1_SEQUENCE_OF_OPT(PKIStatusInfo, statusString, ASN1_UTF8STRING), ASN1_OPT(PKIStatusInfo, failInfo, ASN1_BIT_STRING) } ASN1_SEQUENCE_END(PKIStatusInfo) IMPLEMENT_ASN1_FUNCTIONS(PKIStatusInfo) typedef struct { PKIStatusInfo *status; PKCS7 *token; } TimeStampResp; DECLARE_ASN1_FUNCTIONS(TimeStampResp) ASN1_SEQUENCE(TimeStampResp) = { ASN1_SIMPLE(TimeStampResp, status, PKIStatusInfo), ASN1_OPT(TimeStampResp, token, PKCS7) } ASN1_SEQUENCE_END(TimeStampResp) IMPLEMENT_ASN1_FUNCTIONS(TimeStampResp) typedef struct { AlgorithmIdentifier *digestAlgorithm; ASN1_OCTET_STRING *digest; } MessageImprint; DECLARE_ASN1_FUNCTIONS(MessageImprint) ASN1_SEQUENCE(MessageImprint) = { ASN1_SIMPLE(MessageImprint, digestAlgorithm, AlgorithmIdentifier), ASN1_SIMPLE(MessageImprint, digest, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(MessageImprint) IMPLEMENT_ASN1_FUNCTIONS(MessageImprint) typedef struct { ASN1_INTEGER *version; MessageImprint *messageImprint; ASN1_OBJECT *reqPolicy; ASN1_INTEGER *nonce; ASN1_BOOLEAN *certReq; STACK_OF(X509_EXTENSION) *extensions; } TimeStampReq; DECLARE_ASN1_FUNCTIONS(TimeStampReq) ASN1_SEQUENCE(TimeStampReq) = { ASN1_SIMPLE(TimeStampReq, version, ASN1_INTEGER), ASN1_SIMPLE(TimeStampReq, messageImprint, MessageImprint), ASN1_OPT (TimeStampReq, reqPolicy, ASN1_OBJECT), ASN1_OPT (TimeStampReq, nonce, ASN1_INTEGER), ASN1_SIMPLE(TimeStampReq, certReq, ASN1_BOOLEAN), ASN1_IMP_SEQUENCE_OF_OPT(TimeStampReq, extensions, X509_EXTENSION, 0) } ASN1_SEQUENCE_END(TimeStampReq) IMPLEMENT_ASN1_FUNCTIONS(TimeStampReq) #endif /* ENABLE_CURL */ static SpcSpOpusInfo* createOpus(const char *desc, const char *url) { SpcSpOpusInfo *info = SpcSpOpusInfo_new(); if (desc) { info->programName = SpcString_new(); info->programName->type = 1; info->programName->value.ascii = ASN1_IA5STRING_new(); ASN1_STRING_set((ASN1_STRING *)info->programName->value.ascii, (const unsigned char*)desc, strlen(desc)); } if (url) { info->moreInfo = SpcLink_new(); info->moreInfo->type = 0; info->moreInfo->value.url = ASN1_IA5STRING_new(); ASN1_STRING_set((ASN1_STRING *)info->moreInfo->value.url, (const unsigned char*)url, strlen(url)); } return info; } static unsigned int asn1_simple_hdr_len(const unsigned char *p, unsigned int len) { if (len <= 2 || p[0] > 0x31) return 0; return (p[1]&0x80) ? (2 + (p[1]&0x7f)) : 2; } static void tohex(const unsigned char *v, unsigned char *b, int len) { int i; for(i=0; id.sign->signer_info, 0); p = OPENSSL_malloc(len); memset(p, 0, len); memcpy(p, prefix, sizeof(prefix)); memcpy(p+len-sizeof(postfix), postfix, sizeof(postfix)); ASN1_STRING *astr = ASN1_STRING_new(); ASN1_STRING_set(astr, p, len); int nid = OBJ_create("1.3.6.1.4.1.42921.1.2.1", "unauthenticatedData", "unauthenticatedData"); PKCS7_add_attribute (si, nid, V_ASN1_SEQUENCE, astr); OPENSSL_free(p); return 0; } static int g_verbose = 0; #ifdef ENABLE_CURL static int blob_has_nl = 0; static size_t curl_write( void *ptr, size_t sz, size_t nmemb, void *stream) { if (sz*nmemb > 0 && !blob_has_nl) { if (memchr(ptr, '\n', sz*nmemb)) blob_has_nl = 1; } return BIO_write((BIO*)stream, ptr, sz*nmemb); } static void print_timestamp_error(const char *url, long http_code) { if (http_code != -1) { fprintf(stderr, "Failed to convert timestamp reply from %s; " "HTTP status %ld\n", url, http_code); } else { fprintf(stderr, "Failed to convert timestamp reply from %s; " "no HTTP status available", url); } ERR_print_errors_fp(stderr); } /* A timestamp request looks like this: POST HTTP/1.1 Content-Type: application/octet-stream Content-Length: ... Accept: application/octet-stream User-Agent: Transport Host: ... Cache-Control: no-cache .. and the blob has the following ASN1 structure: 0:d=0 hl=4 l= 291 cons: SEQUENCE 4:d=1 hl=2 l= 10 prim: OBJECT :1.3.6.1.4.1.311.3.2.1 16:d=1 hl=4 l= 275 cons: SEQUENCE 20:d=2 hl=2 l= 9 prim: OBJECT :pkcs7-data 31:d=2 hl=4 l= 260 cons: cont [ 0 ] 35:d=3 hl=4 l= 256 prim: OCTET STRING .. and it returns a base64 encoded PKCS#7 structure. */ static int add_timestamp(PKCS7 *sig, char *url, char *proxy, int rfc3161, const EVP_MD *md, int verbose, int noverifypeer) { CURL *curl; struct curl_slist *slist = NULL; CURLcode c; BIO *bout, *bin, *b64; u_char *p = NULL; int len = 0; PKCS7_SIGNER_INFO *si = sk_PKCS7_SIGNER_INFO_value (sig->d.sign->signer_info, 0); if (!url) return -1; curl = curl_easy_init(); if (proxy) { curl_easy_setopt(curl, CURLOPT_PROXY, proxy); if (!strncmp("http:", proxy, 5)) curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); if (!strncmp("socks:", proxy, 6)) curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); } curl_easy_setopt(curl, CURLOPT_URL, url); /* curl_easy_setopt(curl, CURLOPT_VERBOSE, 42); */ if (noverifypeer) curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, FALSE); if (rfc3161) { slist = curl_slist_append(slist, "Content-Type: application/timestamp-query"); slist = curl_slist_append(slist, "Accept: application/timestamp-reply"); } else { slist = curl_slist_append(slist, "Content-Type: application/octet-stream"); slist = curl_slist_append(slist, "Accept: application/octet-stream"); } slist = curl_slist_append(slist, "User-Agent: Transport"); slist = curl_slist_append(slist, "Cache-Control: no-cache"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist); if (rfc3161) { unsigned char mdbuf[EVP_MAX_MD_SIZE]; EVP_MD_CTX *mdctx; mdctx = EVP_MD_CTX_new(); EVP_DigestInit(mdctx, md); EVP_DigestUpdate(mdctx, si->enc_digest->data, si->enc_digest->length); EVP_DigestFinal(mdctx, mdbuf, NULL); EVP_MD_CTX_free(mdctx); TimeStampReq *req = TimeStampReq_new(); ASN1_INTEGER_set(req->version, 1); req->messageImprint->digestAlgorithm->algorithm = OBJ_nid2obj(EVP_MD_nid(md)); req->messageImprint->digestAlgorithm->parameters = ASN1_TYPE_new(); req->messageImprint->digestAlgorithm->parameters->type = V_ASN1_NULL; ASN1_OCTET_STRING_set(req->messageImprint->digest, mdbuf, EVP_MD_size(md)); req->certReq = (void*)0x1; len = i2d_TimeStampReq(req, NULL); p = OPENSSL_malloc(len); len = i2d_TimeStampReq(req, &p); p -= len; TimeStampReq_free(req); } else { TimeStampRequest *req = TimeStampRequest_new(); req->type = OBJ_txt2obj(SPC_TIME_STAMP_REQUEST_OBJID, 1); req->blob->type = OBJ_nid2obj(NID_pkcs7_data); req->blob->signature = si->enc_digest; len = i2d_TimeStampRequest(req, NULL); p = OPENSSL_malloc(len); len = i2d_TimeStampRequest(req, &p); p -= len; req->blob->signature = NULL; TimeStampRequest_free(req); } bout = BIO_new(BIO_s_mem()); if (!rfc3161) { b64 = BIO_new(BIO_f_base64()); bout = BIO_push(b64, bout); } BIO_write(bout, p, len); (void)BIO_flush(bout); OPENSSL_free(p); p = NULL; len = BIO_get_mem_data(bout, &p); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, len); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, (char*)p); bin = BIO_new(BIO_s_mem()); BIO_set_mem_eof_return(bin, 0); curl_easy_setopt(curl, CURLOPT_POST, 1); curl_easy_setopt(curl, CURLOPT_WRITEDATA, bin); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write); c = curl_easy_perform(curl); curl_slist_free_all(slist); BIO_free_all(bout); if (c) { BIO_free_all(bin); if (verbose) fprintf(stderr, "CURL failure: %s\n", curl_easy_strerror(c)); } else { (void)BIO_flush(bin); long http_code = -1; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); /* * At this point we could also look at the response body (and perhaps * log it if we fail to decode the response): * * char *resp_body = NULL; * long resp_body_len = BIO_get_mem_data(bin, &resp_body); */ if (rfc3161) { TimeStampResp *reply; (void)BIO_flush(bin); reply = ASN1_item_d2i_bio(ASN1_ITEM_rptr(TimeStampResp), bin, NULL); BIO_free_all(bin); if (!reply) { if (verbose) print_timestamp_error(url, http_code); return -1; } if (ASN1_INTEGER_get(reply->status->status) != 0) { if (verbose) fprintf(stderr, "Timestamping failed: %ld\n", ASN1_INTEGER_get(reply->status->status)); TimeStampResp_free(reply); return -1; } if (((len = i2d_PKCS7(reply->token, NULL)) <= 0) || (p = OPENSSL_malloc(len)) == NULL) { if (verbose) { fprintf(stderr, "Failed to convert pkcs7: %d\n", len); ERR_print_errors_fp(stderr); } TimeStampResp_free(reply); return -1; } len = i2d_PKCS7(reply->token, &p); p -= len; TimeStampResp_free(reply); STACK_OF(X509_ATTRIBUTE) *attrs = sk_X509_ATTRIBUTE_new_null(); attrs = X509at_add1_attr_by_txt (&attrs, SPC_RFC3161_OBJID, V_ASN1_SET, p, len); OPENSSL_free(p); PKCS7_set_attributes(si, attrs); sk_X509_ATTRIBUTE_pop_free(attrs, X509_ATTRIBUTE_free); } else { int i; PKCS7 *p7; PKCS7_SIGNER_INFO *info; ASN1_STRING *astr; BIO* b64_bin; b64 = BIO_new(BIO_f_base64()); if (!blob_has_nl) BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); b64_bin = BIO_push(b64, bin); p7 = d2i_PKCS7_bio(b64_bin, NULL); if (p7 == NULL) { BIO_free_all(b64_bin); if (verbose) print_timestamp_error(url, http_code); return -1; } BIO_free_all(b64_bin); for(i = sk_X509_num(p7->d.sign->cert)-1; i>=0; i--) PKCS7_add_certificate(sig, sk_X509_value(p7->d.sign->cert, i)); info = sk_PKCS7_SIGNER_INFO_value(p7->d.sign->signer_info, 0); if (((len = i2d_PKCS7_SIGNER_INFO(info, NULL)) <= 0) || (p = OPENSSL_malloc(len)) == NULL) { if (verbose) { fprintf(stderr, "Failed to convert signer info: %d\n", len); ERR_print_errors_fp(stderr); } PKCS7_free(p7); return -1; } len = i2d_PKCS7_SIGNER_INFO(info, &p); p -= len; astr = ASN1_STRING_new(); ASN1_STRING_set(astr, p, len); OPENSSL_free(p); PKCS7_add_attribute (si, NID_pkcs9_countersignature, V_ASN1_SEQUENCE, astr); PKCS7_free(p7); } } curl_easy_cleanup(curl); curl_global_cleanup(); return (int)c; } static int add_timestamp_authenticode(PKCS7 *sig, char **url, int nurls, char *proxy, int noverifypeer) { int i; for (i=0; i -key | -pkcs12 |\n" "\t\t -pkcs11engine -pkcs11module -certs -key )\n" "\t\t[ -pass ] " #ifdef PROVIDE_ASKPASS "[ -askpass ]" #endif "[ -readpass ]\n" "\t\t[ -ac ]\n" "\t\t[ -h {md5,sha1,sha2(56),sha384,sha512} ]\n" "\t\t[ -n ] [ -i ] [ -jp ] [ -comm ]\n" "\t\t[ -ph ]\n" #ifdef ENABLE_CURL "\t\t[ -t [ -t ... ] [ -p ] [ -noverifypeer ] ]\n" "\t\t[ -ts [ -ts ... ] [ -p ] [ -noverifypeer ] ]\n" #endif "\t\t[ -addUnauthenticatedBlob ]\n\n" "\t\t[ -nest ]\n\n" "\t\t[ -verbose ]\n\n" "\t\tMSI specific:\n" "\t\t[ -add-msi-dse ]\n\n" "\t\t[ -in ] [-out ] \n\n" "\textract-signature [ -pem ] [ -in ] [ -out ] \n\n" "\tremove-signature [ -in ] [ -out ] \n\n" "\tattach-signature [ -sigin ] [ -in ] [ -out ] \n\n" "\tverify [ -in ] \n" "\t\t[ -require-leaf-hash {md5,sha1,sha2(56),sha384,sha512}:XXXXXXXXXXXX... ]\n\n" "\tadd [-addUnauthenticatedBlob] [ -in ] [ -out ] \n" #ifdef ENABLE_CURL "\t\t[ -t [ -t ... ] [ -p ] [ -noverifypeer ] ]\n" "\t\t[ -ts [ -ts ... ] [ -p ] [ -noverifypeer ] ]\n" #endif "\n" "", argv0); cleanup_lib_state(); exit(-1); } #define DO_EXIT_0(x) { fputs(x, stderr); goto err_cleanup; } #define DO_EXIT_1(x, y) { fprintf(stderr, x, y); goto err_cleanup; } #define DO_EXIT_2(x, y, z) { fprintf(stderr, x, y, z); goto err_cleanup; } #define GET_UINT16_LE(p) (((u_char*)(p))[0] | (((u_char*)(p))[1]<<8)) #define GET_UINT32_LE(p) (((u_char*)(p))[0] | (((u_char*)(p))[1]<<8) | \ (((u_char*)(p))[2]<<16) | (((u_char*)(p))[3]<<24)) #define PUT_UINT16_LE(i,p) \ ((u_char*)(p))[0] = (i) & 0xff; \ ((u_char*)(p))[1] = ((i)>>8) & 0xff #define PUT_UINT32_LE(i,p) \ ((u_char*)(p))[0] = (i) & 0xff; \ ((u_char*)(p))[1] = ((i)>>8) & 0xff; \ ((u_char*)(p))[2] = ((i)>>16) & 0xff; \ ((u_char*)(p))[3] = ((i)>>24) & 0xff typedef enum { FILE_TYPE_CAB, FILE_TYPE_PE, FILE_TYPE_MSI, } file_type_t; typedef enum { CMD_SIGN, CMD_EXTRACT, CMD_REMOVE, CMD_VERIFY, CMD_ADD, CMD_ATTACH, } cmd_type_t; static SpcLink *get_obsolete_link(void) { static const unsigned char obsolete[] = { 0x00, 0x3c, 0x00, 0x3c, 0x00, 0x3c, 0x00, 0x4f, 0x00, 0x62, 0x00, 0x73, 0x00, 0x6f, 0x00, 0x6c, 0x00, 0x65, 0x00, 0x74, 0x00, 0x65, 0x00, 0x3e, 0x00, 0x3e, 0x00, 0x3e }; SpcLink *link = SpcLink_new(); link->type = 2; link->value.file = SpcString_new(); link->value.file->type = 0; link->value.file->value.unicode = ASN1_BMPSTRING_new(); ASN1_STRING_set(link->value.file->value.unicode, obsolete, sizeof(obsolete)); return link; } static const unsigned char classid_page_hash[] = { 0xA6, 0xB5, 0x86, 0xD5, 0xB4, 0xA1, 0x24, 0x66, 0xAE, 0x05, 0xA2, 0x17, 0xDA, 0x8E, 0x60, 0xD6 }; static unsigned char *calc_page_hash(char *indata, unsigned int peheader, int pe32plus, unsigned int sigpos, int phtype, unsigned int *phlen); DEFINE_STACK_OF(ASN1_OCTET_STRING) DEFINE_STACK_OF(SpcAttributeTypeAndOptionalValue) static SpcLink *get_page_hash_link(int phtype, char *indata, unsigned int peheader, int pe32plus, unsigned int sigpos) { unsigned int phlen; unsigned char *ph = calc_page_hash(indata, peheader, pe32plus, sigpos, phtype, &phlen); if (!ph) { fprintf(stderr, "Failed to calculate page hash\n"); exit(-1); } ASN1_OCTET_STRING *ostr = ASN1_OCTET_STRING_new(); ASN1_OCTET_STRING_set(ostr, ph, phlen); free(ph); STACK_OF(ASN1_OCTET_STRING) *oset = sk_ASN1_OCTET_STRING_new_null(); sk_ASN1_OCTET_STRING_push(oset, ostr); unsigned char *p, *tmp; unsigned int l; l = i2d_ASN1_SET_ANY((ASN1_SEQUENCE_ANY *)oset, NULL); tmp = p = OPENSSL_malloc(l); i2d_ASN1_SET_ANY((ASN1_SEQUENCE_ANY *)oset, &tmp); ASN1_OCTET_STRING_free(ostr); sk_ASN1_OCTET_STRING_free(oset); SpcAttributeTypeAndOptionalValue *aval = SpcAttributeTypeAndOptionalValue_new(); aval->type = OBJ_txt2obj((phtype == NID_sha1) ? SPC_PE_IMAGE_PAGE_HASHES_V1 : SPC_PE_IMAGE_PAGE_HASHES_V2, 1); aval->value = ASN1_TYPE_new(); aval->value->type = V_ASN1_SET; aval->value->value.set = ASN1_STRING_new(); ASN1_STRING_set(aval->value->value.set, p, l); OPENSSL_free(p); STACK_OF(SpcAttributeTypeAndOptionalValue) *aset = sk_SpcAttributeTypeAndOptionalValue_new_null(); sk_SpcAttributeTypeAndOptionalValue_push(aset, aval); l = i2d_ASN1_SET_ANY((ASN1_SEQUENCE_ANY *)aset, NULL); tmp = p = OPENSSL_malloc(l); l = i2d_ASN1_SET_ANY((ASN1_SEQUENCE_ANY *)aset, &tmp); sk_SpcAttributeTypeAndOptionalValue_free(aset); SpcAttributeTypeAndOptionalValue_free(aval); SpcSerializedObject *so = SpcSerializedObject_new(); ASN1_OCTET_STRING_set(so->classId, classid_page_hash, sizeof(classid_page_hash)); ASN1_OCTET_STRING_set(so->serializedData, p, l); OPENSSL_free(p); SpcLink *link = SpcLink_new(); link->type = 1; link->value.moniker = so; return link; } static void get_indirect_data_blob(u_char **blob, int *len, const EVP_MD *md, file_type_t type, int pagehash, char *indata, unsigned int peheader, int pe32plus, unsigned int sigpos) { static const unsigned char msistr[] = { 0xf1, 0x10, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 }; u_char *p; int hashlen, l; void *hash; ASN1_OBJECT *dtype; SpcIndirectDataContent *idc = SpcIndirectDataContent_new(); idc->data->value = ASN1_TYPE_new(); idc->data->value->type = V_ASN1_SEQUENCE; idc->data->value->value.sequence = ASN1_STRING_new(); if (type == FILE_TYPE_CAB) { SpcLink *link = get_obsolete_link(); l = i2d_SpcLink(link, NULL); p = OPENSSL_malloc(l); i2d_SpcLink(link, &p); p -= l; dtype = OBJ_txt2obj(SPC_CAB_DATA_OBJID, 1); SpcLink_free(link); } else if (type == FILE_TYPE_PE) { SpcPeImageData *pid = SpcPeImageData_new(); ASN1_BIT_STRING_set(pid->flags, (unsigned char*)"0", 0); if (pagehash) { int phtype = NID_sha1; if (EVP_MD_size(md) > EVP_MD_size(EVP_sha1())) phtype = NID_sha256; pid->file = get_page_hash_link(phtype, indata, peheader, pe32plus, sigpos); } else { pid->file = get_obsolete_link(); } l = i2d_SpcPeImageData(pid, NULL); p = OPENSSL_malloc(l); i2d_SpcPeImageData(pid, &p); p -= l; dtype = OBJ_txt2obj(SPC_PE_IMAGE_DATA_OBJID, 1); SpcPeImageData_free(pid); } else if (type == FILE_TYPE_MSI) { SpcSipInfo *si = SpcSipInfo_new(); ASN1_INTEGER_set(si->a, 1); ASN1_INTEGER_set(si->b, 0); ASN1_INTEGER_set(si->c, 0); ASN1_INTEGER_set(si->d, 0); ASN1_INTEGER_set(si->e, 0); ASN1_INTEGER_set(si->f, 0); ASN1_OCTET_STRING_set(si->string, msistr, sizeof(msistr)); l = i2d_SpcSipInfo(si, NULL); p = OPENSSL_malloc(l); i2d_SpcSipInfo(si, &p); p -= l; dtype = OBJ_txt2obj(SPC_SIPINFO_OBJID, 1); SpcSipInfo_free(si); } else { fprintf(stderr, "Unexpected file type: %d\n", type); exit(1); } idc->data->type = dtype; idc->data->value->value.sequence->data = p; idc->data->value->value.sequence->length = l; idc->messageDigest->digestAlgorithm->algorithm = OBJ_nid2obj(EVP_MD_nid(md)); idc->messageDigest->digestAlgorithm->parameters = ASN1_TYPE_new(); idc->messageDigest->digestAlgorithm->parameters->type = V_ASN1_NULL; hashlen = EVP_MD_size(md); hash = OPENSSL_malloc(hashlen); memset(hash, 0, hashlen); ASN1_OCTET_STRING_set(idc->messageDigest->digest, hash, hashlen); OPENSSL_free(hash); *len = i2d_SpcIndirectDataContent(idc, NULL); *blob = OPENSSL_malloc(*len); p = *blob; i2d_SpcIndirectDataContent(idc, &p); SpcIndirectDataContent_free(idc); } static unsigned int calc_pe_checksum(BIO *bio, unsigned int peheader) { unsigned int checkSum = 0; unsigned short val; unsigned int size = 0; unsigned short *buf; int nread; /* recalc checksum. */ buf = (unsigned short*)malloc(sizeof(unsigned short)*32768); (void)BIO_seek(bio, 0); while ((nread = BIO_read(bio, buf, sizeof(unsigned short)*32768)) > 0) { int i; for (i = 0; i < nread / 2; i++) { val = buf[i]; if (size == peheader + 88 || size == peheader + 90) val = 0; checkSum += val; checkSum = 0xffff & (checkSum + (checkSum >> 0x10)); size += 2; } } free(buf); checkSum = 0xffff & (checkSum + (checkSum >> 0x10)); checkSum += size; return checkSum; } static void recalc_pe_checksum(BIO *bio, unsigned int peheader) { unsigned int checkSum = calc_pe_checksum(bio, peheader); char buf[4]; /* write back checksum. */ (void)BIO_seek(bio, peheader + 88); PUT_UINT32_LE(checkSum, buf); BIO_write(bio, buf, 4); } static unsigned char nib2val(unsigned char c) { if (c >= '0' && c <= '9') { return c - '0'; } else if (c >= 'a' && c <= 'f') { return c - 'a' + 10; } else if (c >= 'A' && c <= 'F') { return c - 'A' + 10; } printf("Illegal hex value: '%x'\n", c); return 0; } static int verify_leaf_hash(X509 *leaf, const char *leafhash) { char *lhdup = NULL; char *orig = NULL; char *mdid = NULL; char *hash = NULL; int ret = 0; lhdup = strdup(leafhash); orig = lhdup; mdid = lhdup; while (lhdup != NULL && *lhdup != '\0') { if (*lhdup == ':') { *lhdup = '\0'; ++lhdup; hash = lhdup; break; } ++lhdup; } lhdup = orig; if (hash == NULL) { printf("Unable to parse -require-leaf-hash parameter: %s\n\n", orig); ret = 1; goto out; } const EVP_MD *md = EVP_get_digestbyname(mdid); if (md == NULL) { printf("Unable to lookup digest by name '%s'\n", mdid); ret = 1; goto out; } unsigned long sz = EVP_MD_size(md); unsigned long actual = strlen(hash); if (actual%2 != 0) { printf("Hash length mismatch: length is uneven.\n"); ret = 1; goto out; } actual /= 2; if (actual != sz) { printf("Hash length mismatch: '%s' digest must be %lu bytes long (got %lu bytes)\n", mdid, sz, actual); ret = 1; goto out; } unsigned char mdbuf[EVP_MAX_MD_SIZE]; unsigned char cmdbuf[EVP_MAX_MD_SIZE]; int i = 0, j = 0; while (i < sz*2) { unsigned char x; x = nib2val(hash[i+1]); x |= nib2val(hash[i]) << 4; mdbuf[j] = x; i += 2; j += 1; } unsigned long certlen = i2d_X509(leaf, NULL); unsigned char *certbuf = malloc(certlen); unsigned char *tmp = certbuf; i2d_X509(leaf, &tmp); EVP_MD_CTX *ctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(ctx, md, NULL); EVP_DigestUpdate(ctx, certbuf, certlen); EVP_DigestFinal_ex(ctx, cmdbuf, NULL); EVP_MD_CTX_destroy(ctx); free(certbuf); if (memcmp(mdbuf, cmdbuf, EVP_MD_size(md))) { ret = 1; goto out; } out: free(lhdup); return ret; } // pkcs7_get_nested_signature exctracts a nested signature from p7. // The caller is responsible for freeing the returned object. // // If has_sig is provided, it will be set to either 1 if there is a // SPC_NESTED_SIGNATURE attribute in p7 at all or 0 if not. // This allows has_sig to be used to distinguish two possible scenarios // when the functon returns NULL: if has_sig is 1, it means d2i_PKCS7 // failed to decode the nested signature. However, if has_sig is 0, it // simply means the given p7 does not have a nested signature. static PKCS7 *pkcs7_get_nested_signature(PKCS7 *p7, int *has_sig) { PKCS7 *ret = NULL; PKCS7_SIGNER_INFO *si = sk_PKCS7_SIGNER_INFO_value(p7->d.sign->signer_info, 0); ASN1_TYPE *nestedSignature = PKCS7_get_attribute(si, OBJ_txt2nid(SPC_NESTED_SIGNATURE_OBJID)); if (nestedSignature) { ASN1_STRING *astr = nestedSignature->value.sequence; const unsigned char *p = astr->data; ret = d2i_PKCS7(NULL, &p, astr->length); } if (has_sig) *has_sig = (nestedSignature != NULL); return ret; } // pkcs7_set_nested_signature adds the p7nest signature to p7 // as a nested signature (SPC_NESTED_SIGNATURE). static int pkcs7_set_nested_signature(PKCS7 *p7, PKCS7 *p7nest) { u_char *p = NULL; int len = 0; if (((len = i2d_PKCS7(p7nest, NULL)) <= 0) || (p = OPENSSL_malloc(len)) == NULL) return 0; i2d_PKCS7(p7nest, &p); p -= len; ASN1_STRING *astr = ASN1_STRING_new(); ASN1_STRING_set(astr, p, len); OPENSSL_free(p); PKCS7_SIGNER_INFO *si = sk_PKCS7_SIGNER_INFO_value(p7->d.sign->signer_info, 0); if (PKCS7_add_attribute(si, OBJ_txt2nid(SPC_NESTED_SIGNATURE_OBJID), V_ASN1_SEQUENCE, astr) == 0) return 0; return 1; } #ifdef WITH_GSF static gint msi_base64_decode(gint x) { if (x < 10) return x + '0'; if (x < (10 + 26)) return x - 10 + 'A'; if (x < (10 + 26 + 26)) return x - 10 - 26 + 'a'; if (x == (10 + 26 + 26)) return '.'; return 1; } static void msi_decode(const guint8 *in, gchar *out) { guint count = 0; guint8 *q = (guint8 *)out; /* utf-8 encoding of 0x4840 */ if (in[0] == 0xe4 && in[1] == 0xa1 && in[2] == 0x80) in += 3; while (*in) { guint8 ch = *in; if ((ch == 0xe3 && in[1] >= 0xa0) || (ch == 0xe4 && in[1] < 0xa0)) { *q++ = msi_base64_decode(in[2] & 0x7f); *q++ = msi_base64_decode(in[1] ^ 0xa0); in += 3; count += 2; continue; } if (ch == 0xe4 && in[1] == 0xa0) { *q++ = msi_base64_decode(in[2] & 0x7f); in += 3; count++; continue; } *q++ = *in++; if (ch >= 0xc1) *q++ = *in++; if (ch >= 0xe0) *q++ = *in++; if (ch >= 0xf0) *q++ = *in++; count++; } *q = 0; } /* * Sorry if this code looks a bit silly, but that seems * to be the best solution so far... */ static gint msi_cmp(gpointer a, gpointer b) { glong anc = 0, bnc = 0; gchar *pa = (gchar*)g_utf8_to_utf16(a, -1, NULL, &anc, NULL); gchar *pb = (gchar*)g_utf8_to_utf16(b, -1, NULL, &bnc, NULL); gint diff; diff = memcmp(pa, pb, MIN(2*anc, 2*bnc)); /* apparently the longer wins */ if (diff == 0) return 2*anc > 2*bnc ? 1 : -1; g_free(pa); g_free(pb); return diff; } /* * msi_sorted_infile_children returns a sorted list of all * of the children of the given infile. The children are * sorted according to the msi_cmp. * * The returned list must be freed with g_slist_free. */ static GSList *msi_sorted_infile_children(GsfInfile *infile) { GSList *sorted = NULL; gchar decoded[0x40]; int i; for (i = 0; i < gsf_infile_num_children(infile); i++) { GsfInput *child = gsf_infile_child_by_index(infile, i); const guint8 *name = (const guint8*)gsf_input_name(child); msi_decode(name, decoded); if (!g_strcmp0(decoded, "\05DigitalSignature")) continue; if (!g_strcmp0(decoded, "\05MsiDigitalSignatureEx")) continue; sorted = g_slist_insert_sorted(sorted, (gpointer)name, (GCompareFunc)msi_cmp); } return sorted; } /* * msi_prehash_utf16_name converts an UTF-8 representation of * an MSI filename to its on-disk UTF-16 representation and * writes it to the hash BIO. It is used when calculating the * pre-hash used for MsiDigitalSignatureEx signatures in MSI files. */ static gboolean msi_prehash_utf16_name(gchar *name, BIO *hash) { glong chars_written = 0; gchar *u16name = (gchar*)g_utf8_to_utf16(name, -1, NULL, &chars_written, NULL); if (u16name == NULL) { return FALSE; } BIO_write(hash, u16name, 2*chars_written); g_free(u16name); return TRUE; } /* * msi_prehash calculates the pre-hash used for 'MsiDigitalSignatureEx' * signatures in MSI files. The pre-hash hashes only metadata (file names, * file sizes, creation times and modification times), whereas the basic * 'DigitalSignature' MSI signature only hashes file content. * * The hash is written to the hash BIO. */ static gboolean msi_prehash(GsfInfile *infile, gchar *dirname, BIO *hash) { GSList *sorted = NULL; guint8 classid[16]; guint8 zeroes[8]; memset(&zeroes, 0, sizeof(zeroes)); gsf_infile_msole_get_class_id(GSF_INFILE_MSOLE(infile), classid); if (dirname != NULL) { if (!msi_prehash_utf16_name(dirname, hash)) return FALSE; } BIO_write(hash, classid, sizeof(classid)); BIO_write(hash, zeroes, 4); if (dirname != NULL) { /* * Creation time and modification time for the root directory. * These are always zero. The ctime and mtime of the actual * file itself takes precedence. */ BIO_write(hash, zeroes, 8); // ctime as Windows FILETIME. BIO_write(hash, zeroes, 8); // mtime as Windows FILETIME. } sorted = msi_sorted_infile_children(infile); for (; sorted; sorted = sorted->next) { gchar *name = (gchar*)sorted->data; GsfInput *child = gsf_infile_child_by_name(infile, name); if (child == NULL) continue; gboolean is_dir = GSF_IS_INFILE(child) && gsf_infile_num_children(GSF_INFILE(child)) > 0; if (is_dir) { if (!msi_prehash(GSF_INFILE(child), name, hash)) return FALSE; } else { if (!msi_prehash_utf16_name(name, hash)) return FALSE; /* * File size. */ gsf_off_t size = gsf_input_remaining(child); guint32 sizebuf = GUINT32_TO_LE((guint32)size); BIO_write(hash, &sizebuf, sizeof(sizebuf)); /* * Reserved - must be 0. Corresponds to * offset 0x7c..0x7f in the CDFv2 file. */ BIO_write(hash, zeroes, 4); /* * Creation time and modification time * as Windows FILETIMEs. We keep them * zeroed, because libgsf doesn't seem * to support outputting them. */ BIO_write(hash, zeroes, 8); // ctime as a Windows FILETIME BIO_write(hash, zeroes, 8); // mtime as a Windows FILETIME } } g_slist_free(sorted); return TRUE; } /** * msi_handle_dir performs a direct copy of the input MSI file in infile to a new * output file in outfile. While copying, it also writes all file content to the * hash BIO in order to calculate a 'basic' hash that can be used for an MSI * 'DigitalSignature' hash. * * msi_handle_dir is hierarchy aware: if any subdirectories are found, they will be * visited, copied and hashed as well. */ static gboolean msi_handle_dir(GsfInfile *infile, GsfOutfile *outole, BIO *hash) { guint8 classid[16]; GSList *sorted = NULL; gsf_infile_msole_get_class_id(GSF_INFILE_MSOLE(infile), classid); if (outole != NULL) gsf_outfile_msole_set_class_id(GSF_OUTFILE_MSOLE(outole), classid); sorted = msi_sorted_infile_children(infile); for (; sorted; sorted = sorted->next) { gchar *name = (gchar*)sorted->data; GsfInput *child = gsf_infile_child_by_name(infile, name); if (child == NULL) continue; gboolean is_dir = GSF_IS_INFILE(child) && gsf_infile_num_children(GSF_INFILE(child)) > 0; GsfOutput *outchild = NULL; if (outole != NULL) outchild = gsf_outfile_new_child(outole, name, is_dir); if (is_dir) { if (!msi_handle_dir(GSF_INFILE(child), GSF_OUTFILE(outchild), hash)) { return FALSE; } } else { while (gsf_input_remaining(child) > 0) { gsf_off_t size = MIN(gsf_input_remaining(child), 4096); guint8 const *data = gsf_input_read(child, size, NULL); BIO_write(hash, data, size); if (outchild != NULL && !gsf_output_write(outchild, size, data)) { return FALSE; } } } if (outchild != NULL) { gsf_output_close(outchild); g_object_unref(outchild); } } BIO_write(hash, classid, sizeof(classid)); g_slist_free(sorted); return TRUE; } /* * msi_verify_pkcs7 is a helper function for msi_verify_file. * It exists to make it easier to implement verification of nested signatures. */ static int msi_verify_pkcs7(PKCS7 *p7, GsfInfile *infile, unsigned char *exdata, unsigned int exlen, char *leafhash, int allownest) { int i = 0; int ret = 0; X509_STORE *store = NULL; int mdtype = -1; unsigned char mdbuf[EVP_MAX_MD_SIZE]; unsigned char cmdbuf[EVP_MAX_MD_SIZE]; #ifdef GSF_CAN_READ_MSI_METADATA unsigned char cexmdbuf[EVP_MAX_MD_SIZE]; #endif unsigned char hexbuf[EVP_MAX_MD_SIZE*2+1]; BIO *bio = NULL; ASN1_OBJECT *indir_objid = OBJ_txt2obj(SPC_INDIRECT_DATA_OBJID, 1); if (p7 && PKCS7_type_is_signed(p7) && !OBJ_cmp(p7->d.sign->contents->type, indir_objid) && p7->d.sign->contents->d.other->type == V_ASN1_SEQUENCE) { ASN1_STRING *astr = p7->d.sign->contents->d.other->value.sequence; const unsigned char *p = astr->data; SpcIndirectDataContent *idc = d2i_SpcIndirectDataContent(NULL, &p, astr->length); if (idc) { if (idc->messageDigest && idc->messageDigest->digest && idc->messageDigest->digestAlgorithm) { mdtype = OBJ_obj2nid(idc->messageDigest->digestAlgorithm->algorithm); memcpy(mdbuf, idc->messageDigest->digest->data, idc->messageDigest->digest->length); } SpcIndirectDataContent_free(idc); } ASN1_OBJECT_free(indir_objid); } if (mdtype == -1) { printf("Failed to extract current message digest\n\n"); ret = 1; goto out; } if (p7 == NULL) { printf("Failed to read PKCS7 signature from DigitalSignature section\n\n"); ret = 1; goto out; } printf("Message digest algorithm : %s\n", OBJ_nid2sn(mdtype)); const EVP_MD *md = EVP_get_digestbynid(mdtype); BIO *hash = BIO_new(BIO_f_md()); BIO_set_md(hash, md); BIO_push(hash, BIO_new(BIO_s_null())); if (exdata) { /* * Until libgsf can read more MSI metadata, we can't * really verify them by plowing through the file. * Verifying files signed by osslsigncode itself works, * though! * * For now, the compromise is to use the hash given * by the file, which is equivalent to verifying a * non-MsiDigitalSignatureEx signature from a security * pespective, because we'll only be calculating the * file content hashes ourselves. */ #ifdef GSF_CAN_READ_MSI_METADATA BIO *prehash = BIO_new(BIO_f_md()); BIO_set_md(prehash, md); BIO_push(prehash, BIO_new(BIO_s_null())); if (!msi_prehash(infile, NULL, prehash)) { ret = 1; goto out; } BIO_gets(prehash, (char*)cexmdbuf, EVP_MAX_MD_SIZE); BIO_write(hash, (char*)cexmdbuf, EVP_MD_size(md)); #else BIO_write(hash, (char *)exdata, EVP_MD_size(md)); #endif } if (!msi_handle_dir(infile, NULL, hash)) { ret = 1; goto out; } BIO_gets(hash, (char*)cmdbuf, EVP_MAX_MD_SIZE); tohex(cmdbuf, hexbuf, EVP_MD_size(md)); int mdok = !memcmp(mdbuf, cmdbuf, EVP_MD_size(md)); if (!mdok) ret = 1; printf("Calculated DigitalSignature : %s", hexbuf); if (mdok) { printf("\n"); } else { tohex(mdbuf, hexbuf, EVP_MD_size(md)); printf(" MISMATCH!!! FILE HAS %s\n", hexbuf); } #ifdef GSF_CAN_READ_MSI_METADATA if (exdata) { tohex(cexmdbuf, hexbuf, EVP_MD_size(md)); int exok = !memcmp(exdata, cexmdbuf, MIN(EVP_MD_size(md), exlen)); if (!exok) ret = 1; printf("Calculated MsiDigitalSignatureEx : %s", hexbuf); if (exok) { printf("\n"); } else { tohex(exdata, hexbuf, EVP_MD_size(md)); printf(" MISMATCH!!! FILE HAS %s\n", hexbuf); } } #endif printf("\n"); int seqhdrlen = asn1_simple_hdr_len(p7->d.sign->contents->d.other->value.sequence->data, p7->d.sign->contents->d.other->value.sequence->length); bio = BIO_new_mem_buf(p7->d.sign->contents->d.other->value.sequence->data + seqhdrlen, p7->d.sign->contents->d.other->value.sequence->length - seqhdrlen); store = X509_STORE_new(); int verok = PKCS7_verify(p7, p7->d.sign->cert, store, bio, NULL, PKCS7_NOVERIFY); BIO_free(bio); /* XXX: add more checks here (attributes, timestamp, etc) */ printf("Signature verification: %s\n\n", verok ? "ok" : "failed"); if (!verok) { ERR_print_errors_fp(stdout); ret = 1; } int leafok = 0; STACK_OF(X509) *signers = PKCS7_get0_signers(p7, NULL, 0); printf("Number of signers: %d\n", sk_X509_num(signers)); for (i=0; id.sign->cert)); for (i=0; id.sign->cert); i++) { X509 *cert = sk_X509_value(p7->d.sign->cert, i); char *subject = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0); char *issuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0); printf("\tCert #%d:\n\t\tSubject : %s\n\t\tIssuer : %s\n", i, subject, issuer); OPENSSL_free(subject); OPENSSL_free(issuer); } printf("\n"); if (leafhash != NULL) { printf("Leaf hash match: %s\n\n", leafok ? "ok" : "failed"); if (!leafok) ret = 1; } if (allownest) { int has_sig = 0; PKCS7 *p7nest = pkcs7_get_nested_signature(p7, &has_sig); if (p7nest) { printf("\n"); int nest_ret = msi_verify_pkcs7(p7nest, infile, exdata, exlen, leafhash, 0); if (ret == 0) ret = nest_ret; PKCS7_free(p7nest); } else if (!p7nest && has_sig) { printf("\nFailed to decode nested signature!\n"); ret = 1; } else printf("\n"); } else printf("\n"); out: if (store) X509_STORE_free(store); return ret; } /* * msi_verify_file checks whether or not the signature of infile is valid. */ static int msi_verify_file(GsfInfile *infile, char *leafhash) { GsfInput *sig = NULL; GsfInput *exsig = NULL; unsigned char *exdata = NULL; unsigned char *indata = NULL; gchar decoded[0x40]; int i, ret = 0; PKCS7 *p7 = NULL; for (i = 0; i < gsf_infile_num_children(infile); i++) { GsfInput *child = gsf_infile_child_by_index(infile, i); const guint8 *name = (const guint8*)gsf_input_name(child); msi_decode(name, decoded); if (!g_strcmp0(decoded, "\05DigitalSignature")) sig = child; if (!g_strcmp0(decoded, "\05MsiDigitalSignatureEx")) exsig = child; } if (sig == NULL) { printf("MSI file has no signature\n\n"); ret = 1; goto out; } unsigned long inlen = (unsigned long) gsf_input_remaining(sig); indata = malloc(inlen); if (gsf_input_read(sig, inlen, indata) == NULL) { ret = 1; goto out; } unsigned long exlen = 0; if (exsig != NULL) { exlen = (unsigned long) gsf_input_remaining(exsig); exdata = malloc(exlen); if (gsf_input_read(exsig, exlen, exdata) == NULL) { ret = 1; goto out; } } const unsigned char *blob = (unsigned char *)indata; p7 = d2i_PKCS7(NULL, &blob, inlen); ret = msi_verify_pkcs7(p7, infile, exdata, exlen, leafhash, 1); out: free(indata); free(exdata); if (p7) PKCS7_free(p7); return ret; } static int msi_extract_dse(GsfInfile *infile, unsigned char **dsebuf, unsigned long *dselen, int *has_dse) { GsfInput *exsig = NULL; gchar decoded[0x40]; u_char *buf = NULL; gsf_off_t size = 0; int i, ret = 0; for (i = 0; i < gsf_infile_num_children(infile); i++) { GsfInput *child = gsf_infile_child_by_index(infile, i); const guint8 *name = (const guint8*)gsf_input_name(child); msi_decode(name, decoded); if (!g_strcmp0(decoded, "\05MsiDigitalSignatureEx")) exsig = child; } if (exsig == NULL) { ret = 1; goto out; } if (has_dse != NULL) { *has_dse = 1; } size = gsf_input_remaining(exsig); if (dselen != NULL) { *dselen = (unsigned long) size; } if (dsebuf != NULL) { buf = malloc(size); if (gsf_input_read(exsig, size, buf) == NULL) { ret = 1; goto out; } *dsebuf = (unsigned char *) buf; } out: return ret; } /* * msi_extract_signature_to_file extracts the MSI DigitalSignaure from infile * to a file at the path given by outfile. */ static int msi_extract_signature_to_file(GsfInfile *infile, char *outfile) { unsigned char hexbuf[EVP_MAX_MD_SIZE*2+1]; GsfInput *sig = NULL; GsfInput *exsig = NULL; unsigned char *exdata = NULL; unsigned long exlen = 0; BIO *outdata = NULL; gchar decoded[0x40]; int i, ret = 0; for (i = 0; i < gsf_infile_num_children(infile); i++) { GsfInput *child = gsf_infile_child_by_index(infile, i); const guint8 *name = (const guint8*)gsf_input_name(child); msi_decode(name, decoded); if (!g_strcmp0(decoded, "\05DigitalSignature")) sig = child; if (!g_strcmp0(decoded, "\05MsiDigitalSignatureEx")) exsig = child; } if (sig == NULL) { printf("MSI file has no signature\n\n"); ret = 1; goto out; } /* Create outdata file */ outdata = BIO_new_file(outfile, "w+b"); if (outdata == NULL) { printf("Unable to open %s\n\n", outfile); ret = 1; goto out; } while (gsf_input_remaining(sig) > 0) { gsf_off_t size = MIN(gsf_input_remaining(sig), 4096); guint8 const *data = gsf_input_read(sig, size, NULL); BIO_write(outdata, data, size); } if (exsig != NULL) { exlen = (unsigned long) gsf_input_remaining(exsig); if (exlen > EVP_MAX_MD_SIZE) { printf("MsiDigitalSignatureEx is larger than EVP_MAX_MD_SIZE. Aborting...\n\n"); ret = 1; goto out; } exdata = malloc(exlen); if (gsf_input_read(exsig, exlen, exdata) == NULL) { printf("Unable to read MsiDigitalSignatureEx\n\n"); ret = 1; goto out; } tohex(exdata, hexbuf, exlen); printf("Note: MSI includes a MsiDigitalSignatureEx section.\n"); printf("MsiDigitalSignatureEx pre-hash: %s\n\n", hexbuf); } out: free(exdata); if (outdata) BIO_free_all(outdata); return ret; } static PKCS7 *msi_extract_signature_to_pkcs7(GsfInfile *infile) { GsfInput *sig = NULL; gchar decoded[0x40]; PKCS7 *p7 = NULL; u_char *buf = NULL; gsf_off_t size = 0; int i = 0; for (i = 0; i < gsf_infile_num_children(infile); i++) { GsfInput *child = gsf_infile_child_by_index(infile, i); const guint8 *name = (const guint8*)gsf_input_name(child); msi_decode(name, decoded); if (!g_strcmp0(decoded, "\05DigitalSignature")) sig = child; } if (sig == NULL) { goto out; } size = gsf_input_remaining(sig); buf = malloc(size); if (gsf_input_read(sig, size, buf) == NULL) { goto out; } const unsigned char *p7buf = buf; p7 = d2i_PKCS7(NULL, &p7buf, size); out: free(buf); return p7; } #endif static void calc_pe_digest(BIO *bio, const EVP_MD *md, unsigned char *mdbuf, unsigned int peheader, int pe32plus, unsigned int fileend) { static unsigned char bfb[16*1024*1024]; EVP_MD_CTX *mdctx; mdctx = EVP_MD_CTX_new(); EVP_DigestInit(mdctx, md); memset(mdbuf, 0, EVP_MAX_MD_SIZE); (void)BIO_seek(bio, 0); BIO_read(bio, bfb, peheader + 88); EVP_DigestUpdate(mdctx, bfb, peheader + 88); BIO_read(bio, bfb, 4); BIO_read(bio, bfb, 60+pe32plus*16); EVP_DigestUpdate(mdctx, bfb, 60+pe32plus*16); BIO_read(bio, bfb, 8); unsigned int n = peheader + 88 + 4 + 60+pe32plus*16 + 8; while (n < fileend) { int want = fileend - n; if (want > sizeof(bfb)) want = sizeof(bfb); int l = BIO_read(bio, bfb, want); if (l <= 0) break; EVP_DigestUpdate(mdctx, bfb, l); n += l; } EVP_DigestFinal(mdctx, mdbuf, NULL); EVP_MD_CTX_free(mdctx); } static void extract_page_hash (SpcAttributeTypeAndOptionalValue *obj, unsigned char **ph, unsigned int *phlen, int *phtype) { *phlen = 0; const unsigned char *blob = obj->value->value.sequence->data; SpcPeImageData *id = d2i_SpcPeImageData(NULL, &blob, obj->value->value.sequence->length); if (id == NULL) return; if (id->file->type != 1) { SpcPeImageData_free(id); return; } SpcSerializedObject *so = id->file->value.moniker; if (so->classId->length != sizeof(classid_page_hash) || memcmp(so->classId->data, classid_page_hash, sizeof (classid_page_hash))) { SpcPeImageData_free(id); return; } /* skip ASN.1 SET hdr */ unsigned int l = asn1_simple_hdr_len(so->serializedData->data, so->serializedData->length); blob = so->serializedData->data + l; obj = d2i_SpcAttributeTypeAndOptionalValue(NULL, &blob, so->serializedData->length - l); SpcPeImageData_free(id); if (!obj) return; char buf[128]; *phtype = 0; buf[0] = 0x00; OBJ_obj2txt(buf, sizeof(buf), obj->type, 1); if (!strcmp(buf, SPC_PE_IMAGE_PAGE_HASHES_V1)) { *phtype = NID_sha1; } else if (!strcmp(buf, SPC_PE_IMAGE_PAGE_HASHES_V2)) { *phtype = NID_sha256; } else { SpcAttributeTypeAndOptionalValue_free(obj); return; } /* Skip ASN.1 SET hdr */ unsigned int l2 = asn1_simple_hdr_len(obj->value->value.sequence->data, obj->value->value.sequence->length); /* Skip ASN.1 OCTET STRING hdr */ l = asn1_simple_hdr_len(obj->value->value.sequence->data + l2, obj->value->value.sequence->length - l2); l += l2; *phlen = obj->value->value.sequence->length - l; *ph = malloc(*phlen); memcpy(*ph, obj->value->value.sequence->data + l, *phlen); SpcAttributeTypeAndOptionalValue_free(obj); } static unsigned char *calc_page_hash(char *indata, unsigned int peheader, int pe32plus, unsigned int sigpos, int phtype, unsigned int *rphlen) { unsigned short nsections = GET_UINT16_LE(indata + peheader + 6); unsigned int pagesize = GET_UINT32_LE(indata + peheader + 56); unsigned int hdrsize = GET_UINT32_LE(indata + peheader + 84); const EVP_MD *md = EVP_get_digestbynid(phtype); int pphlen = 4 + EVP_MD_size(md); int phlen = pphlen * (3 + nsections + sigpos / pagesize); unsigned char *res = malloc(phlen); unsigned char *zeroes = calloc(pagesize, 1); EVP_MD_CTX *mdctx; mdctx = EVP_MD_CTX_new(); EVP_DigestInit(mdctx, md); EVP_DigestUpdate(mdctx, indata, peheader + 88); EVP_DigestUpdate(mdctx, indata + peheader + 92, 60 + pe32plus*16); EVP_DigestUpdate(mdctx, indata + peheader + 160 + pe32plus*16, hdrsize - (peheader + 160 + pe32plus*16)); EVP_DigestUpdate(mdctx, zeroes, pagesize - hdrsize); memset(res, 0, 4); EVP_DigestFinal(mdctx, res + 4, NULL); unsigned short sizeofopthdr = GET_UINT16_LE(indata + peheader + 20); char *sections = indata + peheader + 24 + sizeofopthdr; int i, pi = 1; unsigned int lastpos = 0; for (i=0; id.sign->contents->type, indir_objid) && p7->d.sign->contents->d.other->type == V_ASN1_SEQUENCE) { ASN1_STRING *astr = p7->d.sign->contents->d.other->value.sequence; const unsigned char *p = astr->data; SpcIndirectDataContent *idc = d2i_SpcIndirectDataContent(NULL, &p, astr->length); if (idc) { extract_page_hash (idc->data, &ph, &phlen, &phtype); if (idc->messageDigest && idc->messageDigest->digest && idc->messageDigest->digestAlgorithm) { mdtype = OBJ_obj2nid(idc->messageDigest->digestAlgorithm->algorithm); memcpy(mdbuf, idc->messageDigest->digest->data, idc->messageDigest->digest->length); } SpcIndirectDataContent_free(idc); } } ASN1_OBJECT_free(indir_objid); if (mdtype == -1) { printf("Failed to extract current message digest\n\n"); return -1; } printf("Message digest algorithm : %s\n", OBJ_nid2sn(mdtype)); const EVP_MD *md = EVP_get_digestbynid(mdtype); tohex(mdbuf, hexbuf, EVP_MD_size(md)); printf("Current message digest : %s\n", hexbuf); bio = BIO_new_mem_buf(indata, sigpos + siglen); calc_pe_digest(bio, md, cmdbuf, peheader, pe32plus, sigpos); BIO_free(bio); tohex(cmdbuf, hexbuf, EVP_MD_size(md)); int mdok = !memcmp(mdbuf, cmdbuf, EVP_MD_size(md)); if (!mdok) ret = 1; printf("Calculated message digest : %s%s\n\n", hexbuf, mdok?"":" MISMATCH!!!"); if (phlen > 0) { printf("Page hash algorithm : %s\n", OBJ_nid2sn(phtype)); tohex(ph, hexbuf, (phlen < 32) ? phlen : 32); printf("Page hash : %s ...\n", hexbuf); unsigned int cphlen = 0; unsigned char *cph = calc_page_hash(indata, peheader, pe32plus, sigpos, phtype, &cphlen); tohex(cph, hexbuf, (cphlen < 32) ? cphlen : 32); printf("Calculated page hash : %s ...%s\n\n", hexbuf, ((phlen != cphlen) || memcmp(ph, cph, phlen)) ? " MISMATCH!!!":""); free(ph); free(cph); } int seqhdrlen = asn1_simple_hdr_len(p7->d.sign->contents->d.other->value.sequence->data, p7->d.sign->contents->d.other->value.sequence->length); bio = BIO_new_mem_buf(p7->d.sign->contents->d.other->value.sequence->data + seqhdrlen, p7->d.sign->contents->d.other->value.sequence->length - seqhdrlen); X509_STORE *store = X509_STORE_new(); int verok = PKCS7_verify(p7, p7->d.sign->cert, store, bio, NULL, PKCS7_NOVERIFY); BIO_free(bio); /* XXX: add more checks here (attributes, timestamp, etc) */ printf("Signature verification: %s\n\n", verok ? "ok" : "failed"); if (!verok) { ERR_print_errors_fp(stdout); ret = 1; } int i; int leafok = 0; STACK_OF(X509) *signers = PKCS7_get0_signers(p7, NULL, 0); printf("Number of signers: %d\n", sk_X509_num(signers)); for (i=0; i 0) printf("\t------------------\n"); printf("\tSigner #%d:\n\t\tSubject: %s\n\t\tIssuer : %s\n\t\tSerial : %s\n", i, subject, issuer, serial); OPENSSL_free(subject); OPENSSL_free(issuer); OPENSSL_free(serial); BN_free(serialbn); if (leafhash != NULL && leafok == 0) { leafok = verify_leaf_hash(cert, leafhash) == 0; } } sk_X509_free(signers); printf("\nNumber of certificates: %d\n", sk_X509_num(p7->d.sign->cert)); for (i=0; id.sign->cert); i++) { X509 *cert = sk_X509_value(p7->d.sign->cert, i); char *subject = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0); char *issuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0); BIGNUM *serialbn = ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), NULL); char *serial = BN_bn2hex(serialbn); if (i > 0) printf("\t------------------\n"); printf("\tCert #%d:\n\t\tSubject: %s\n\t\tIssuer : %s\n\t\tSerial : %s\n", i, subject, issuer, serial); OPENSSL_free(subject); OPENSSL_free(issuer); OPENSSL_free(serial); BN_free(serialbn); } if (leafhash != NULL) { printf("\nLeaf hash match: %s\n", leafok ? "ok" : "failed"); if (!leafok) ret = 1; } if (allownest) { int has_sig = 0; PKCS7 *p7nest = pkcs7_get_nested_signature(p7, &has_sig); if (p7nest) { printf("\n"); int nest_ret = verify_pe_pkcs7(p7nest, indata, peheader, pe32plus, sigpos, siglen, leafhash, 0); if (ret == 0) ret = nest_ret; PKCS7_free(p7nest); } else if (!p7nest && has_sig) { printf("\nFailed to decode nested signature!\n"); ret = 1; } else printf("\n"); } else printf("\n"); X509_STORE_free(store); return ret; } static int verify_pe_file(char *indata, unsigned int peheader, int pe32plus, unsigned int sigpos, unsigned int siglen, char *leafhash) { int ret = 0; unsigned int pe_checksum = GET_UINT32_LE(indata + peheader + 88); printf("Current PE checksum : %08X\n", pe_checksum); BIO *bio = BIO_new_mem_buf(indata, sigpos + siglen); unsigned int real_pe_checksum = calc_pe_checksum(bio, peheader); BIO_free(bio); if (pe_checksum && pe_checksum != real_pe_checksum) ret = 1; printf("Calculated PE checksum: %08X%s\n\n", real_pe_checksum, ret ? " MISMATCH!!!!" : ""); if (siglen == 0) { printf("No signature found.\n\n"); return ret; } unsigned int pos = 0; PKCS7 *p7 = NULL; while (pos < siglen) { unsigned int l = GET_UINT32_LE(indata + sigpos + pos); unsigned short certrev = GET_UINT16_LE(indata + sigpos + pos + 4); unsigned short certtype = GET_UINT16_LE(indata + sigpos + pos + 6); if (certrev == WIN_CERT_REVISION_2 && certtype == WIN_CERT_TYPE_PKCS_SIGNED_DATA) { const unsigned char *blob = (unsigned char*)indata + sigpos + pos + 8; p7 = d2i_PKCS7(NULL, &blob, l - 8); } if (l%8) l += (8 - l%8); pos += l; } if (p7 == NULL) { printf("Failed to extract PKCS7 data\n\n"); return -1; } ret = verify_pe_pkcs7(p7, indata, peheader, pe32plus, sigpos, siglen, leafhash, 1); PKCS7_free(p7); return ret; } // extract_existing_pe_pkcs7 retreives a decoded PKCS7 struct corresponding to the // existing signature of the PE file. static PKCS7 *extract_existing_pe_pkcs7(char *indata, unsigned int peheader, int pe32plus, unsigned int sigpos, unsigned int siglen) { unsigned int pos = 0; PKCS7 *p7 = NULL; while (pos < siglen) { unsigned int l = GET_UINT32_LE(indata + sigpos + pos); unsigned short certrev = GET_UINT16_LE(indata + sigpos + pos + 4); unsigned short certtype = GET_UINT16_LE(indata + sigpos + pos + 6); if (certrev == WIN_CERT_REVISION_2 && certtype == WIN_CERT_TYPE_PKCS_SIGNED_DATA) { const unsigned char *blob = (unsigned char*)indata + sigpos + pos + 8; p7 = d2i_PKCS7(NULL, &blob, l - 8); } if (l%8) l += (8 - l%8); pos += l; } return p7; } static STACK_OF(X509) *PEM_read_certs_with_pass(BIO *bin, char *certpass) { STACK_OF(X509) *certs = sk_X509_new_null(); X509 *x509; (void)BIO_seek(bin, 0); while((x509 = PEM_read_bio_X509(bin, NULL, NULL, certpass))) sk_X509_push(certs, x509); if (!sk_X509_num(certs)) { sk_X509_free(certs); return NULL; } return certs; } static STACK_OF(X509) *PEM_read_certs(BIO *bin, char *certpass) { STACK_OF(X509) *certs = PEM_read_certs_with_pass(bin, certpass); if (!certs) certs = PEM_read_certs_with_pass(bin, NULL); return certs; } static off_t get_file_size(const char *infile) { int ret; #ifdef _WIN32 struct _stat st; ret = _stat(infile, &st); #else struct stat st; ret = stat(infile, &st); #endif if (ret) { fprintf(stderr, "Failed to open file: %s\n", infile); return 0; } if (st.st_size < 4) { fprintf(stderr, "Unrecognized file type - file is too short: %s\n", infile); return 0; } return st.st_size; } static char* map_file(const char *infile, const off_t size) { char *indata = NULL; #ifdef WIN32 HANDLE fh, fm; fh = CreateFile(infile, GENERIC_READ, FILE_SHARE_READ , NULL, OPEN_EXISTING, 0, NULL); if (fh == INVALID_HANDLE_VALUE) return NULL; fm = CreateFileMapping(fh, NULL, PAGE_READONLY, 0, 0, NULL); if (fm == NULL) return NULL; indata = MapViewOfFile(fm, FILE_MAP_READ, 0, 0, 0); #else int fd = open(infile, O_RDONLY); if (fd < 0) return NULL; indata = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0); if (indata == MAP_FAILED) return NULL; #endif return indata; } #ifdef PROVIDE_ASKPASS char *getpassword(const char *prompt) { #ifdef HAVE_TERMIOS_H struct termios ofl, nfl; char *p, passbuf[1024]; fputs(prompt, stdout); tcgetattr(fileno(stdin), &ofl); nfl = ofl; nfl.c_lflag &= ~ECHO; nfl.c_lflag |= ECHONL; if (tcsetattr(fileno(stdin), TCSANOW, &nfl) != 0) { fprintf(stderr, "Failed to set terminal attributes\n"); return NULL; } p = fgets(passbuf, sizeof(passbuf), stdin); if (tcsetattr(fileno(stdin), TCSANOW, &ofl) != 0) fprintf(stderr, "Failed to restore terminal attributes\n"); if (!p) { fprintf(stderr, "Failed to read password\n"); return NULL; } passbuf[strlen(passbuf)-1] = 0x00; char *pass = strdup(passbuf); memset(passbuf, 0, sizeof(passbuf)); return pass; #else return getpass(prompt); #endif } #endif int main(int argc, char **argv) { BIO *btmp, *sigbio, *hash, *outdata; PKCS12 *p12; PKCS7 *p7 = NULL, *cursig = NULL, *outsig = NULL, *sig, *p7x = NULL; X509 *cert = NULL; STACK_OF(X509) *certs = NULL, *xcerts = NULL; EVP_PKEY *pkey = NULL; PKCS7_SIGNER_INFO *si; ASN1_STRING *astr; const EVP_MD *md; const char *argv0 = argv[0]; static char buf[64*1024]; char *xcertfile, *certfile, *keyfile, *pvkfile, *pkcs12file, *infile, *outfile, *sigfile, *desc, *url, *indata, *insigdata, *outdataverify; char *p11engine, *p11module; char *pass = NULL, *readpass = NULL; int output_pkcs7 = 0; int askpass = 0; char *leafhash = NULL; #ifdef ENABLE_CURL char *turl[MAX_TS_SERVERS], *proxy = NULL, *tsurl[MAX_TS_SERVERS]; int noverifypeer = 0; #endif int nest = 0; int add_msi_dse = 0; int nturl = 0, ntsurl = 0; int addBlob = 0; u_char *p = NULL; int ret = 0, i, len = 0, jp = -1, pe32plus = 0, comm = 0, pagehash = 0; unsigned int tmp, peheader = 0, padlen = 0; off_t filesize, fileend, sigfilesize, sigfileend, outdatasize; file_type_t type; cmd_type_t cmd = CMD_SIGN; char *failarg = NULL; static u_char purpose_ind[] = { 0x30, 0x0c, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x01, 0x15 }; static u_char purpose_comm[] = { 0x30, 0x0c, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x01, 0x16 }; static u_char msi_signature[] = { 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1 }; #ifdef WITH_GSF GsfOutfile *outole = NULL; GsfOutput *sink = NULL; u_char *p_msiex = NULL; int len_msiex = 0; #endif xcertfile = certfile = keyfile = pvkfile = pkcs12file = p11module = p11engine = infile = outfile = sigfile = desc = url = NULL; hash = outdata = NULL; /* Set up OpenSSL */ ERR_load_crypto_strings(); OPENSSL_add_all_algorithms_conf(); /* create some MS Authenticode OIDS we need later on */ if (!OBJ_create(SPC_STATEMENT_TYPE_OBJID, NULL, NULL) || !OBJ_create(SPC_MS_JAVA_SOMETHING, NULL, NULL) || !OBJ_create(SPC_SP_OPUS_INFO_OBJID, NULL, NULL) || !OBJ_create(SPC_NESTED_SIGNATURE_OBJID, NULL, NULL)) DO_EXIT_0("Failed to add objects\n"); md = EVP_sha1(); if (argc > 1) { if (!strcmp(argv[1], "sign")) { cmd = CMD_SIGN; argv++; argc--; } else if (!strcmp(argv[1], "extract-signature")) { cmd = CMD_EXTRACT; argv++; argc--; } else if (!strcmp(argv[1], "attach-signature")) { cmd = CMD_ATTACH; argv++; argc--; } else if (!strcmp(argv[1], "remove-signature")) { cmd = CMD_REMOVE; argv++; argc--; } else if (!strcmp(argv[1], "verify")) { cmd = CMD_VERIFY; argv++; argc--; } else if (!strcmp(argv[1], "add")) { cmd = CMD_ADD; argv++; argc--; } } for (argc--,argv++; argc >= 1; argc--,argv++) { if (!strcmp(*argv, "-in")) { if (--argc < 1) usage(argv0); infile = *(++argv); } else if (!strcmp(*argv, "-out")) { if (--argc < 1) usage(argv0); outfile = *(++argv); } else if (!strcmp(*argv, "-sigin")) { if (--argc < 1) usage(argv0); sigfile = *(++argv); } else if ((cmd == CMD_SIGN) && (!strcmp(*argv, "-spc") || !strcmp(*argv, "-certs"))) { if (--argc < 1) usage(argv0); certfile = *(++argv); } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-ac")) { if (--argc < 1) usage(argv0); xcertfile = *(++argv); } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-key")) { if (--argc < 1) usage(argv0); keyfile = *(++argv); } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-pkcs12")) { if (--argc < 1) usage(argv0); pkcs12file = *(++argv); } else if ((cmd == CMD_EXTRACT) && !strcmp(*argv, "-pem")) { output_pkcs7 = 1; } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-pkcs11engine")) { if (--argc < 1) usage(argv0); p11engine = *(++argv); } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-pkcs11module")) { if (--argc < 1) usage(argv0); p11module = *(++argv); } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-pass")) { if (askpass || readpass) usage(argv0); if (--argc < 1) usage(argv0); pass = strdup(*(++argv)); memset(*argv, 0, strlen(*argv)); #ifdef PROVIDE_ASKPASS } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-askpass")) { if (pass || readpass) usage(argv0); askpass = 1; #endif } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-readpass")) { if (askpass || pass) usage(argv0); if (--argc < 1) usage(argv0); readpass = *(++argv); } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-comm")) { comm = 1; } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-ph")) { pagehash = 1; } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-n")) { if (--argc < 1) usage(argv0); desc = *(++argv); } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-h")) { if (--argc < 1) usage(argv0); ++argv; if (!strcmp(*argv, "md5")) { md = EVP_md5(); } else if (!strcmp(*argv, "sha1")) { md = EVP_sha1(); } else if (!strcmp(*argv, "sha2") || !strcmp(*argv, "sha256")) { md = EVP_sha256(); } else if (!strcmp(*argv, "sha384")) { md = EVP_sha384(); } else if (!strcmp(*argv, "sha512")) { md = EVP_sha512(); } else { usage(argv0); } } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-i")) { if (--argc < 1) usage(argv0); url = *(++argv); #ifdef ENABLE_CURL } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-t")) { if (--argc < 1) usage(argv0); turl[nturl++] = *(++argv); } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-ts")) { if (--argc < 1) usage(argv0); tsurl[ntsurl++] = *(++argv); } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-p")) { if (--argc < 1) usage(argv0); proxy = *(++argv); } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-noverifypeer")) { noverifypeer = 1; #endif } else if ((cmd == CMD_SIGN || cmd == CMD_ADD) && !strcmp(*argv, "-addUnauthenticatedBlob")) { addBlob = 1; } else if ((cmd == CMD_SIGN || cmd == CMD_ATTACH) && !strcmp(*argv, "-nest")) { nest = 1; } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-verbose")) { g_verbose = 1; } else if ((cmd == CMD_SIGN) && !strcmp(*argv, "-add-msi-dse")) { add_msi_dse = 1; } else if ((cmd == CMD_VERIFY) && !strcmp(*argv, "-require-leaf-hash")) { if (--argc < 1) usage(argv0); leafhash = (*++argv); } else if (!strcmp(*argv, "-v") || !strcmp(*argv, "--version")) { printf(PACKAGE_STRING ", using:\n\t%s\n\t%s\n", SSLeay_version(SSLEAY_VERSION), #ifdef ENABLE_CURL curl_version() #else "no libcurl available" #endif ); printf( #ifdef WITH_GSF "\tlibgsf %d.%d.%d\n", libgsf_major_version, libgsf_minor_version, libgsf_micro_version #else "\tno libgsf available\n" #endif ); printf("\nPlease send bug-reports to " PACKAGE_BUGREPORT "\n\n"); } else if (!strcmp(*argv, "-jp")) { char *ap; if (--argc < 1) usage(argv0); ap = *(++argv); for (i=0; ap[i]; i++) ap[i] = tolower((int)ap[i]); if (!strcmp(ap, "low")) { jp = 0; } else if (!strcmp(ap, "medium")) { jp = 1; } else if (!strcmp(ap, "high")) { jp = 2; } if (jp != 0) usage(argv0); /* XXX */ } else { failarg = *argv; break; } } if (!infile && argc > 0) { infile = *(argv++); argc--; } if (cmd != CMD_VERIFY && (!outfile && argc > 0)) { if (!strcmp(*argv, "-out")) { argv++; argc--; } if (argc > 0) { outfile = *(argv++); argc--; } } if (argc > 0 || (nturl && ntsurl) || !infile || (cmd != CMD_VERIFY && !outfile) || (cmd == CMD_SIGN && !((certfile && keyfile) || pkcs12file || (p11engine && p11module)))) { if (failarg) fprintf(stderr, "Unknown option: %s\n", failarg); usage(argv0); } if (readpass) { char passbuf[4096]; int passfd = open(readpass, O_RDONLY); if (passfd < 0) DO_EXIT_1("Failed to open password file: %s\n", readpass); int passlen = read(passfd, passbuf, sizeof(passbuf)-1); close(passfd); if (passlen <= 0) DO_EXIT_1("Failed to read password from file: %s\n", readpass); passbuf[passlen] = 0x00; pass = strdup(passbuf); memset(passbuf, 0, sizeof(passbuf)); #ifdef PROVIDE_ASKPASS } else if (askpass) { pass = getpassword("Password: "); #endif } if (cmd == CMD_SIGN) { /* Read certificate and key */ if (keyfile && !p11engine && (btmp = BIO_new_file(keyfile, "rb")) != NULL) { unsigned char magic[4]; unsigned char pvkhdr[4] = { 0x1e, 0xf1, 0xb5, 0xb0 }; magic[0] = 0x00; BIO_read(btmp, magic, 4); if (!memcmp(magic, pvkhdr, 4)) { pvkfile = keyfile; keyfile = NULL; } BIO_free(btmp); } if (pkcs12file != NULL) { if ((btmp = BIO_new_file(pkcs12file, "rb")) == NULL || (p12 = d2i_PKCS12_bio(btmp, NULL)) == NULL) DO_EXIT_1("Failed to read PKCS#12 file: %s\n", pkcs12file); BIO_free(btmp); if (!PKCS12_parse(p12, pass ? pass : "", &pkey, &cert, &certs)) DO_EXIT_1("Failed to parse PKCS#12 file: %s (Wrong password?)\n", pkcs12file); PKCS12_free(p12); } else if (pvkfile != NULL) { if ((btmp = BIO_new_file(certfile, "rb")) == NULL || ((p7 = d2i_PKCS7_bio(btmp, NULL)) == NULL && (certs = PEM_read_certs(btmp, "")) == NULL)) DO_EXIT_1("Failed to read certificate file: %s\n", certfile); BIO_free(btmp); if ((btmp = BIO_new_file(pvkfile, "rb")) == NULL || ( (pkey = b2i_PVK_bio(btmp, NULL, pass ? pass : "")) == NULL && (BIO_seek(btmp, 0) == 0) && (pkey = b2i_PVK_bio(btmp, NULL, NULL)) == NULL)) DO_EXIT_1("Failed to read PVK file: %s\n", pvkfile); BIO_free(btmp); } else if (p11engine != NULL && p11module != NULL) { const int CMD_MANDATORY = 0; ENGINE_load_dynamic(); ENGINE * dyn = ENGINE_by_id( "dynamic" ); if ( ! dyn ) DO_EXIT_0( "Failed to load 'dynamic' engine"); if ( 1 != ENGINE_ctrl_cmd_string( dyn, "SO_PATH", p11engine, CMD_MANDATORY ) ) DO_EXIT_1( "Failed to set dyn SO_PATH to '%s'", p11engine); if ( 1 != ENGINE_ctrl_cmd_string( dyn, "ID", "pkcs11", CMD_MANDATORY ) ) DO_EXIT_0( "Failed to set dyn ID to 'pkcs11'" ); if ( 1 != ENGINE_ctrl_cmd( dyn, "LIST_ADD", 1, NULL, NULL, CMD_MANDATORY ) ) DO_EXIT_0( "Failed to set dyn LIST_ADD to '1'" ); if ( 1 != ENGINE_ctrl_cmd( dyn, "LOAD", 1, NULL, NULL, CMD_MANDATORY ) ) DO_EXIT_0( "Failed to set dyn LOAD to '1'" ); ENGINE * pkcs11 = ENGINE_by_id( "pkcs11" ); if ( ! pkcs11 ) DO_EXIT_0( "Failed to find and load pkcs11 engine" ); if ( 1 != ENGINE_ctrl_cmd_string( pkcs11, "MODULE_PATH", p11module, CMD_MANDATORY ) ) DO_EXIT_1( "Failed to set pkcs11 engine MODULE_PATH to '%s'", p11module ); if (pass != NULL) { if ( 1 != ENGINE_ctrl_cmd_string( pkcs11, "PIN", pass, CMD_MANDATORY ) ) DO_EXIT_0( "Failed to set pkcs11 PIN" ); } if ( 1 != ENGINE_init( pkcs11 ) ) DO_EXIT_0( "Failed to initialized pkcs11 engine" ); pkey = ENGINE_load_private_key( pkcs11, keyfile, NULL, NULL ); if (pkey == NULL) DO_EXIT_1("Failed to load private key %s", keyfile); if ((btmp = BIO_new_file(certfile, "rb")) == NULL || ((p7 = d2i_PKCS7_bio(btmp, NULL)) == NULL && (certs = PEM_read_certs(btmp, "")) == NULL)) DO_EXIT_1("Failed to read certificate file: %s\n", certfile); BIO_free(btmp); } else { if ((btmp = BIO_new_file(certfile, "rb")) == NULL || ((p7 = d2i_PKCS7_bio(btmp, NULL)) == NULL && (certs = PEM_read_certs(btmp, "")) == NULL)) DO_EXIT_1("Failed to read certificate file: %s\n", certfile); BIO_free(btmp); if ((btmp = BIO_new_file(keyfile, "rb")) == NULL || ( (pkey = d2i_PrivateKey_bio(btmp, NULL)) == NULL && (BIO_seek(btmp, 0) == 0) && (pkey = PEM_read_bio_PrivateKey(btmp, NULL, NULL, pass ? pass : "")) == NULL && (BIO_seek(btmp, 0) == 0) && (pkey = PEM_read_bio_PrivateKey(btmp, NULL, NULL, NULL)) == NULL)) DO_EXIT_1("Failed to read private key file: %s (Wrong password?)\n", keyfile); BIO_free(btmp); } if (xcertfile) { if ((btmp = BIO_new_file(xcertfile, "rb")) == NULL || ((p7x = d2i_PKCS7_bio(btmp, NULL)) == NULL && (xcerts = PEM_read_certs(btmp, "")) == NULL)) DO_EXIT_1("Failed to read cross certificate file: %s\n", xcertfile); BIO_free(btmp); } if (pass) { memset (pass, 0, strlen(pass)); pass = NULL; } } if (certs == NULL && p7 != NULL) certs = p7->d.sign->cert; /* Check if indata is cab or pe */ filesize = get_file_size(infile); if (filesize == 0) goto err_cleanup; indata = map_file(infile, filesize); if (indata == NULL) DO_EXIT_1("Failed to open file: %s\n", infile); fileend = filesize; if (!memcmp(indata, "MSCF", 4)) { type = FILE_TYPE_CAB; } else if (!memcmp(indata, "MZ", 2)) { type = FILE_TYPE_PE; } else if (!memcmp(indata, msi_signature, sizeof(msi_signature))) { type = FILE_TYPE_MSI; #ifdef WITH_GSF gsf_init(); gsf_initialized = 1; #endif } else { DO_EXIT_1("Unrecognized file type: %s\n", infile); } if (cmd != CMD_SIGN && !(type == FILE_TYPE_PE || type == FILE_TYPE_MSI)) DO_EXIT_1("Command is not supported for non-PE/non-MSI files: %s\n", infile); hash = BIO_new(BIO_f_md()); BIO_set_md(hash, md); if (type == FILE_TYPE_CAB) { if (filesize < 44) DO_EXIT_1("Corrupt cab file - too short: %s\n", infile); if (indata[0x1e] != 0x00 || indata[0x1f] != 0x00) DO_EXIT_0("Cannot sign cab files with flag bits set!\n"); /* XXX */ } else if (type == FILE_TYPE_PE) { if (filesize < 64) DO_EXIT_1("Corrupt DOS file - too short: %s\n", infile); peheader = GET_UINT32_LE(indata+60); if (filesize < peheader + 160) DO_EXIT_1("Corrupt PE file - too short: %s\n", infile); if (memcmp(indata+peheader, "PE\0\0", 4)) DO_EXIT_1("Unrecognized DOS file type: %s\n", infile); } else if (type == FILE_TYPE_MSI) { #ifdef WITH_GSF GsfInput *src; GsfInfile *ole; BIO_push(hash, BIO_new(BIO_s_null())); src = gsf_input_stdio_new(infile, NULL); if (!src) DO_EXIT_1("Error opening file %s", infile); ole = gsf_infile_msole_new(src, NULL); if (cmd == CMD_EXTRACT) { if(output_pkcs7) { sig = msi_extract_signature_to_pkcs7(ole); if (!sig) DO_EXIT_0("Unable to extract existing signature."); outdata = BIO_new_file(outfile, "w+b"); if (outdata == NULL) DO_EXIT_1("Unable to open %s\n\n", outfile); ret = !PEM_write_bio_PKCS7(outdata, sig); BIO_free_all(outdata); } else ret = msi_extract_signature_to_file(ole, outfile); goto skip_signing; } else if (cmd == CMD_VERIFY) { ret = msi_verify_file(ole, leafhash); goto skip_signing; } else if (cmd == CMD_SIGN || cmd == CMD_ADD || cmd == CMD_ATTACH) { if (nest || cmd == CMD_ADD) { // Perform a sanity check for the MsiDigitalSignatureEx section. // If the file we're attempting to sign has an MsiDigitalSignatureEx // section, we can't add a nested signature of a different MD type // without breaking the initial signature. { unsigned long dselen = 0; int has_dse = 0; if (msi_extract_dse(ole, NULL, &dselen, &has_dse) != 0 && has_dse) { DO_EXIT_0("Unable to extract MsiDigitalSigantureEx section.\n"); } if (has_dse) { int mdlen = EVP_MD_size(md); if (dselen != (unsigned long)mdlen) { DO_EXIT_0("Unable to add nested signature with a different MD type (-h parameter) " "than what exists in the MSI file already. This is due to the presence of " "MsiDigitalSigantureEx (-add-msi-dse parameter).\n"); } } } cursig = msi_extract_signature_to_pkcs7(ole); if (cursig == NULL) { DO_EXIT_0("Unable to extract existing signature in -nest mode"); } if (cmd == CMD_ADD) { sig = cursig; } } } sink = gsf_output_stdio_new(outfile, NULL); if (!sink) DO_EXIT_1("Error opening output file %s", outfile); outole = gsf_outfile_msole_new(sink); /* * MsiDigitalSignatureEx is an enhanced signature type that * can be used when signing MSI files. In addition to * file content, it also hashes some file metadata, specifically * file names, file sizes, creation times and modification times. * * The file content hashing part stays the same, so the * msi_handle_dir() function can be used across both variants. * * When an MsiDigitalSigntaureEx section is present in an MSI file, * the meaning of the DigitalSignature section changes: Instead * of being merely a file content hash (as what is output by the * msi_handle_dir() function), it is now hashes both content * and metadata. * * Here is how it works: * * First, a "pre-hash" is calculated. This is the "metadata" hash. * It iterates over the files in the MSI in the same order as the * file content hashing method would - but it only processes the * metadata. * * Once the pre-hash is calculated, a new hash is created for * calculating the hash of the file content. The output of the * pre-hash is added as the first element of the file content hash. * * After the pre-hash is written, what follows is the "regular" * stream of data that would normally be written when performing * file content hashing. * * The output of this hash, which combines both metadata and file * content, is what will be output in signed form to the * DigitalSignature section when in 'MsiDigitalSignatureEx' mode. * * As mentioned previously, this new mode of operation is signalled * by the presence of a 'MsiDigitalSignatureEx' section in the MSI * file. This section must come after the 'DigitalSignature' * section, and its content must be the output of the pre-hash * ("metadata") hash. */ if (add_msi_dse) { BIO *prehash = BIO_new(BIO_f_md()); BIO_set_md(prehash, md); BIO_push(prehash, BIO_new(BIO_s_null())); if (!msi_prehash(ole, NULL, prehash)) DO_EXIT_0("unable to calculate MSI pre-hash ('metadata') hash.\n"); p_msiex = malloc(EVP_MAX_MD_SIZE); len_msiex = BIO_gets(prehash, (char*)p_msiex, EVP_MAX_MD_SIZE); BIO_write(hash, p_msiex, len_msiex); } if (!msi_handle_dir(ole, outole, hash)) { DO_EXIT_0("unable to msi_handle_dir()\n"); } if (cmd == CMD_REMOVE) { gsf_output_close(GSF_OUTPUT(outole)); g_object_unref(sink); } #else DO_EXIT_1("libgsf is not available, msi support is disabled: %s\n", infile); #endif } if (type == FILE_TYPE_CAB || type == FILE_TYPE_PE) { if (cmd != CMD_VERIFY) { /* Create outdata file */ outdata = BIO_new_file(outfile, "w+b"); if (outdata == NULL) DO_EXIT_1("Failed to create file: %s\n", outfile); BIO_push(hash, outdata); } } if (type == FILE_TYPE_CAB) { unsigned short nfolders; u_char cabsigned[] = { 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0xde, 0xad, 0xbe, 0xef, /* size of cab file */ 0xde, 0xad, 0xbe, 0xef, /* size of asn1 blob */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; BIO_write(hash, indata, 4); BIO_write(outdata, indata+4, 4); tmp = GET_UINT32_LE(indata+8) + 24; PUT_UINT32_LE(tmp, buf); BIO_write(hash, buf, 4); BIO_write(hash, indata+12, 4); tmp = GET_UINT32_LE(indata+16) + 24; PUT_UINT32_LE(tmp, buf+4); BIO_write(hash, buf+4, 4); memcpy(buf+4, indata+20, 14); buf[4+10] = 0x04; /* RESERVE_PRESENT */ BIO_write(hash, buf+4, 14); BIO_write(outdata, indata+34, 2); memcpy(cabsigned+8, buf, 4); BIO_write(outdata, cabsigned, 20); BIO_write(hash, cabsigned+20, 4); /* ??? or possibly the previous 4 bytes instead? */ nfolders = indata[26] | (indata[27] << 8); for (i = 36; nfolders; nfolders--, i+=8) { tmp = GET_UINT32_LE(indata+i); tmp += 24; PUT_UINT32_LE(tmp, buf); BIO_write(hash, buf, 4); BIO_write(hash, indata+i+4, 4); } /* Write what's left */ BIO_write(hash, indata+i, filesize-i); } else if (type == FILE_TYPE_PE) { unsigned int sigpos, siglen, nrvas; unsigned short magic; if (jp >= 0) fprintf(stderr, "Warning: -jp option is only valid " "for CAB files.\n"); magic = GET_UINT16_LE(indata + peheader + 24); if (magic == 0x20b) { pe32plus = 1; } else if (magic == 0x10b) { pe32plus = 0; } else { DO_EXIT_2("Corrupt PE file - found unknown magic %x: %s\n", magic, infile); } nrvas = GET_UINT32_LE(indata + peheader + 116 + pe32plus*16); if (nrvas < 5) DO_EXIT_1("Can not handle PE files without certificate table resource: %s\n", infile); sigpos = GET_UINT32_LE(indata + peheader + 152 + pe32plus*16); siglen = GET_UINT32_LE(indata + peheader + 152 + pe32plus*16 + 4); /* Since fix for MS Bulletin MS12-024 we can really assume that signature should be last part of file */ if (sigpos > 0 && sigpos + siglen != filesize) DO_EXIT_1("Corrupt PE file - current signature not at end of file: %s\n", infile); if ((cmd == CMD_REMOVE || cmd == CMD_EXTRACT) && sigpos == 0) DO_EXIT_1("PE file does not have any signature: %s\n", infile); if (cmd == CMD_EXTRACT) { /* A lil' bit of ugliness. Reset stream, write signature and skip forward */ (void)BIO_reset(outdata); if(output_pkcs7) { sig = extract_existing_pe_pkcs7(indata, peheader, pe32plus, sigpos ? sigpos : fileend, siglen); if (!sig) DO_EXIT_0("Unable to extract existing signature."); PEM_write_bio_PKCS7(outdata, sig); } else BIO_write(outdata, indata + sigpos, siglen); goto skip_signing; } if ((cmd == CMD_SIGN && nest) || (cmd == CMD_ATTACH && nest) || cmd == CMD_ADD) { cursig = extract_existing_pe_pkcs7(indata, peheader, pe32plus, sigpos ? sigpos : fileend, siglen); if (cursig == NULL) { DO_EXIT_0("Unable to extract existing signature in -nest mode"); } if (cmd == CMD_ADD) { sig = cursig; } } if (cmd == CMD_VERIFY) { ret = verify_pe_file(indata, peheader, pe32plus, sigpos ? sigpos : fileend, siglen, leafhash); goto skip_signing; } if (sigpos > 0) { /* Strip current signature */ fileend = sigpos; } BIO_write(hash, indata, peheader + 88); i = peheader + 88; memset(buf, 0, 4); BIO_write(outdata, buf, 4); /* zero out checksum */ i += 4; BIO_write(hash, indata + i, 60+pe32plus*16); i += 60+pe32plus*16; memset(buf, 0, 8); BIO_write(outdata, buf, 8); /* zero out sigtable offset + pos */ i += 8; BIO_write(hash, indata + i, fileend - i); /* pad (with 0's) pe file to 8 byte boundary */ len = 8 - fileend % 8; if (len > 0 && len != 8) { memset(buf, 0, len); BIO_write(hash, buf, len); fileend += len; } } if (cmd == CMD_ADD) goto add_only; if(cmd == CMD_ATTACH) { const char pemhdr[] = "-----BEGIN PKCS7-----"; sigfilesize = get_file_size(sigfile); if(!sigfilesize) goto err_cleanup; insigdata = map_file(sigfile, sigfilesize); if (insigdata == NULL) DO_EXIT_1("Failed to open file: %s\n", infile); if (sigfilesize >= sizeof(pemhdr) && !memcmp(insigdata, pemhdr, sizeof(pemhdr)-1)) { sigbio = BIO_new_mem_buf(insigdata, sigfilesize); sig = PEM_read_bio_PKCS7(sigbio, NULL, NULL, NULL); BIO_free_all(sigbio); } else { if (type == FILE_TYPE_PE) { sig = extract_existing_pe_pkcs7(insigdata, peheader, pe32plus, 0, sigfilesize); } else if (type == FILE_TYPE_MSI) { #ifdef WITH_GSF const unsigned char *p = (unsigned char*)insigdata; sig = d2i_PKCS7(NULL, &p, sigfilesize); #else DO_EXIT_1("libgsf is not available, msi support is disabled: %s\n", infile); #endif } } if (!sig) DO_EXIT_0("No valid signature found."); goto add_only; } if (cmd != CMD_SIGN) goto skip_signing; sig = PKCS7_new(); PKCS7_set_type(sig, NID_pkcs7_signed); si = NULL; if (cert != NULL) si = PKCS7_add_signature(sig, cert, pkey, md); if (si == NULL) { for (i=0; i= 0) { const u_char *attrs = NULL; static const u_char java_attrs_low[] = { 0x30, 0x06, 0x03, 0x02, 0x00, 0x01, 0x30, 0x00 }; switch (jp) { case 0: attrs = java_attrs_low; len = sizeof(java_attrs_low); break; case 1: /* XXX */ case 2: /* XXX */ default: break; } if (attrs) { astr = ASN1_STRING_new(); ASN1_STRING_set(astr, attrs, len); PKCS7_add_signed_attribute (si, OBJ_txt2nid(SPC_MS_JAVA_SOMETHING), V_ASN1_SEQUENCE, astr); } } astr = ASN1_STRING_new(); if (comm) { ASN1_STRING_set(astr, purpose_comm, sizeof(purpose_comm)); } else { ASN1_STRING_set(astr, purpose_ind, sizeof(purpose_ind)); } PKCS7_add_signed_attribute(si, OBJ_txt2nid(SPC_STATEMENT_TYPE_OBJID), V_ASN1_SEQUENCE, astr); if (desc || url) { SpcSpOpusInfo *opus = createOpus(desc, url); if ((len = i2d_SpcSpOpusInfo(opus, NULL)) <= 0 || (p = OPENSSL_malloc(len)) == NULL) DO_EXIT_0("Couldn't allocate memory for opus info\n"); i2d_SpcSpOpusInfo(opus, &p); p -= len; astr = ASN1_STRING_new(); ASN1_STRING_set(astr, p, len); OPENSSL_free(p); PKCS7_add_signed_attribute(si, OBJ_txt2nid(SPC_SP_OPUS_INFO_OBJID), V_ASN1_SEQUENCE, astr); SpcSpOpusInfo_free(opus); } PKCS7_content_new(sig, NID_pkcs7_data); if (cert != NULL) { PKCS7_add_certificate(sig, cert); X509_free(cert); cert = NULL; } if (xcerts) { for(i = sk_X509_num(xcerts)-1; i>=0; i--) PKCS7_add_certificate(sig, sk_X509_value(xcerts, i)); } for(i = sk_X509_num(certs)-1; i>=0; i--) PKCS7_add_certificate(sig, sk_X509_value(certs, i)); if (p7 == NULL || certs != p7->d.sign->cert) { sk_X509_free(certs); certs = NULL; } if (p7) { PKCS7_free(p7); p7 = NULL; } if (xcerts) { sk_X509_free(xcerts); xcerts = NULL; } if (p7x) { PKCS7_free(p7x); p7x = NULL; } get_indirect_data_blob(&p, &len, md, type, pagehash, indata, peheader, pe32plus, fileend); len -= EVP_MD_size(md); memcpy(buf, p, len); OPENSSL_free(p); unsigned char mdbuf[EVP_MAX_MD_SIZE]; int mdlen = BIO_gets(hash, (char*)mdbuf, EVP_MAX_MD_SIZE); memcpy(buf+len, mdbuf, mdlen); int seqhdrlen = asn1_simple_hdr_len((unsigned char*)buf, len); if ((sigbio = PKCS7_dataInit(sig, NULL)) == NULL) DO_EXIT_0("Signing failed(PKCS7_dataInit)\n"); BIO_write(sigbio, buf+seqhdrlen, len-seqhdrlen+mdlen); (void)BIO_flush(sigbio); if (!PKCS7_dataFinal(sig, sigbio)) DO_EXIT_0("Signing failed(PKCS7_dataFinal)\n"); BIO_free_all(sigbio); /* replace the data part with the MS Authenticode spcIndirectDataContext blob */ PKCS7 *td7 = PKCS7_new(); td7->type = OBJ_txt2obj(SPC_INDIRECT_DATA_OBJID, 1); td7->d.other = ASN1_TYPE_new(); td7->d.other->type = V_ASN1_SEQUENCE; td7->d.other->value.sequence = ASN1_STRING_new(); ASN1_STRING_set(td7->d.other->value.sequence, buf, len+mdlen); PKCS7_set_content(sig, td7); add_only: #ifdef ENABLE_CURL /* add counter-signature/timestamp */ if (nturl && add_timestamp_authenticode(sig, turl, nturl, proxy, noverifypeer)) DO_EXIT_0("authenticode timestamping failed\n"); if (ntsurl && add_timestamp_rfc3161(sig, tsurl, ntsurl, proxy, md, noverifypeer)) DO_EXIT_0("RFC 3161 timestamping failed\n"); #endif if (addBlob && add_unauthenticated_blob(sig)) DO_EXIT_0("Adding unauthenticated blob failed\n"); #if 0 if (!PEM_write_PKCS7(stdout, sig)) DO_EXIT_0("PKCS7 output failed\n"); #endif if (nest) { if (cursig == NULL) { DO_EXIT_0("no 'cursig' was extracted. this points to a bug in the code. aborting...\n") } if (pkcs7_set_nested_signature(cursig, sig) == 0) DO_EXIT_0("unable to append the nested signature to the current signature\n"); outsig = cursig; } else { outsig = sig; } /* Append signature to outfile */ if (((len = i2d_PKCS7(outsig, NULL)) <= 0) || (p = OPENSSL_malloc(len)) == NULL) DO_EXIT_1("i2d_PKCS - memory allocation failed: %d\n", len); i2d_PKCS7(outsig, &p); p -= len; padlen = (8 - len%8) % 8; if (type == FILE_TYPE_PE) { PUT_UINT32_LE(len+8+padlen, buf); PUT_UINT16_LE(WIN_CERT_REVISION_2, buf + 4); PUT_UINT16_LE(WIN_CERT_TYPE_PKCS_SIGNED_DATA, buf + 6); BIO_write(outdata, buf, 8); } if (type == FILE_TYPE_PE || type == FILE_TYPE_CAB) { BIO_write(outdata, p, len); /* pad (with 0's) asn1 blob to 8 byte boundary */ if (padlen > 0) { memset(p, 0, padlen); BIO_write(outdata, p, padlen); } #ifdef WITH_GSF } else if (type == FILE_TYPE_MSI) { /* Only output signatures if we're signing. */ if (cmd == CMD_SIGN || cmd == CMD_ADD || cmd == CMD_ATTACH) { GsfOutput *child = gsf_outfile_new_child(outole, "\05DigitalSignature", FALSE); if (!gsf_output_write(child, len, p)) DO_EXIT_1("Failed to write MSI 'DigitalSignature' signature to %s", infile); gsf_output_close(child); if (p_msiex != NULL) { child = gsf_outfile_new_child(outole, "\05MsiDigitalSignatureEx", FALSE); if (!gsf_output_write(child, len_msiex, p_msiex)) { DO_EXIT_1("Failed to write MSI 'MsiDigitalSignatureEx' signature to %s", infile); } gsf_output_close(child); } gsf_output_close(GSF_OUTPUT(outole)); g_object_unref(sink); } #endif } PKCS7_free(sig); OPENSSL_free(p); skip_signing: if (type == FILE_TYPE_PE) { if (cmd == CMD_SIGN || cmd == CMD_ADD || cmd == CMD_ATTACH) { /* Update signature position and size */ (void)BIO_seek(outdata, peheader+152+pe32plus*16); PUT_UINT32_LE(fileend, buf); /* Previous file end = signature table start */ BIO_write(outdata, buf, 4); PUT_UINT32_LE(len+8+padlen, buf); BIO_write(outdata, buf, 4); } if (cmd == CMD_SIGN || cmd == CMD_REMOVE || cmd == CMD_ADD || cmd == CMD_ATTACH) recalc_pe_checksum(outdata, peheader); } else if (type == FILE_TYPE_CAB) { (void)BIO_seek(outdata, 0x30); PUT_UINT32_LE(len+padlen, buf); BIO_write(outdata, buf, 4); } BIO_free_all(hash); hash = outdata = NULL; if (cmd == CMD_ATTACH) { if (type == FILE_TYPE_PE) { outdatasize = get_file_size(outfile); if (!outdatasize) DO_EXIT_0("Error verifying result.\n"); outdataverify = map_file(outfile, outdatasize); if (!outdataverify) DO_EXIT_0("Error verifying result.\n"); int sigpos = GET_UINT32_LE(outdataverify + peheader + 152 + pe32plus*16); int siglen = GET_UINT32_LE(outdataverify + peheader + 152 + pe32plus*16 + 4); ret = verify_pe_file(outdataverify, peheader, pe32plus, sigpos, siglen, leafhash); if (ret) { DO_EXIT_0("Signature mismatch.\n"); } } else if (type == FILE_TYPE_MSI) { #ifdef WITH_GSF GsfInput *src; GsfInfile *ole; src = gsf_input_stdio_new(outfile, NULL); if (!src) DO_EXIT_1("Error opening file %s", outfile); ole = gsf_infile_msole_new(src, NULL); g_object_unref(src); ret = msi_verify_file(ole, leafhash); g_object_unref(ole); if (ret) { DO_EXIT_0("Signature mismatch.\n"); } #else DO_EXIT_1("libgsf is not available, msi support is disabled: %s\n", infile); #endif } else { DO_EXIT_1("Unknown input type for file: %s\n", infile); } printf("Signature successfully attached.\n"); } else printf(ret ? "Failed\n" : "Succeeded\n"); cleanup_lib_state(); return ret; err_cleanup: if (pass) { memset (pass, 0, strlen(pass)); pass = NULL; } ERR_print_errors_fp(stderr); if (certs && (p7 == NULL || certs != p7->d.sign->cert)) sk_X509_free(certs); if (p7) PKCS7_free(p7); if (p7x) PKCS7_free(p7x); if (xcerts) sk_X509_free(xcerts); if (cert) X509_free(cert); if (pkey) EVP_PKEY_free(pkey); if (hash) BIO_free_all(hash); if (outfile) unlink(outfile); fprintf(stderr, "\nFailed\n"); cleanup_lib_state(); return -1; } /* Local Variables: c-basic-offset: 4 tab-width: 4 indent-tabs-mode: t End: vim: set ts=4 : */ osslsigncode-2.0/tests/000077500000000000000000000000001340156732300152155ustar00rootroot00000000000000osslsigncode-2.0/tests/testsign.sh000077500000000000000000000044271340156732300174230ustar00rootroot00000000000000#!/bin/sh rm -f putty*.exe PUTTY_URL="http://the.earth.li/~sgtatham/putty/0.64/x86/putty.exe" [ -f putty.exe ] || wget -q -O putty.exe $PUTTY_URL [ -f putty.exe ] || curl -o putty.exe $PUTTY_URL if [ ! -f putty.exe ]; then echo "FAIL: Couldn't download putty.exe" exit 1 fi rm -f cert.pem cert.spc key.der key.p12 key.pem key.pvk keyp.pem keytool -genkey \ -alias selfsigned -keysize 2048 -keyalg RSA -keypass passme -storepass passme -keystore key.ks << EOF John Doe ACME In ACME Springfield LaLaLand SE yes EOF echo "Converting key/cert to PKCS12 container" keytool -importkeystore \ -srckeystore key.ks -srcstoretype JKS -srckeypass passme -srcstorepass passme -srcalias selfsigned \ -destkeystore key.p12 -deststoretype PKCS12 -destkeypass passme -deststorepass passme rm -f key.ks echo "Converting key to PEM format" openssl pkcs12 -in key.p12 -passin pass:passme -nocerts -nodes -out key.pem echo "Converting key to PEM format (with password)" openssl rsa -in key.pem -out keyp.pem -passout pass:passme echo "Converting key to DER format" openssl rsa -in key.pem -outform DER -out key.der -passout pass:passme echo "Converting key to PVK format" openssl rsa -in key.pem -outform PVK -pvk-strong -out key.pvk -passout pass:passme echo "Converting cert to PEM format" openssl pkcs12 -in key.p12 -passin pass:passme -nokeys -out cert.pem echo "Converting cert to SPC format" openssl crl2pkcs7 -nocrl -certfile cert.pem -outform DER -out cert.spc ../osslsigncode sign -spc cert.spc -key key.pem putty.exe putty1.exe ../osslsigncode sign -certs cert.spc -key keyp.pem -pass passme putty.exe putty2.exe ../osslsigncode sign -certs cert.pem -key keyp.pem -pass passme putty.exe putty3.exe ../osslsigncode sign -certs cert.spc -key key.der putty.exe putty4.exe ../osslsigncode sign -pkcs12 key.p12 -pass passme putty.exe putty5.exe ../osslsigncode sign -certs cert.spc -key key.pvk -pass passme putty.exe putty6.exe rm -f cert.pem cert.spc key.der key.p12 key.pem key.pvk keyp.pem echo "" echo "" check=`sha1sum putty[1-9]*.exe | cut -d' ' -f1 | uniq | wc -l` cmp putty1.exe putty2.exe && \ cmp putty2.exe putty3.exe && \ cmp putty3.exe putty4.exe && \ cmp putty4.exe putty5.exe && \ cmp putty5.exe putty6.exe if [ $? -ne 0 ]; then echo "Failure is not an option." else echo "Yes, it works." fi