pax_global_header00006660000000000000000000000064142071753600014517gustar00rootroot0000000000000052 comment=b3682d9c5a1686f4833e8882f3ca88e2a52de1be sscg-sscg-3.0.2/000077500000000000000000000000001420717536000134155ustar00rootroot00000000000000sscg-sscg-3.0.2/.clang-format000066400000000000000000000030531420717536000157710ustar00rootroot00000000000000--- # C format Language: Cpp BasedOnStyle: WebKit AlignAfterOpenBracket: Align AlignConsecutiveAssignments: false AlignConsecutiveDeclarations: false AlignEscapedNewlinesLeft: false AlignOperands: true AlignTrailingComments: false AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: true AllowShortFunctionsOnASingleLine: None AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AlwaysBreakAfterReturnType: All AlwaysBreakBeforeMultilineStrings: true BinPackArguments: false BinPackParameters: false BreakBeforeBinaryOperators: None BreakBeforeBraces: GNU BreakBeforeTernaryOperators: false ColumnLimit: 79 CommentPragmas: '^ IWYU pragma:' ContinuationIndentWidth: 2 DerivePointerAlignment: false DisableFormat: false ExperimentalAutoDetectBinPacking: false IndentCaseLabels: false IndentWidth: 2 IndentWrappedFunctionNames: false KeepEmptyLinesAtTheStartOfBlocks: false MacroBlockBegin: '' MacroBlockEnd: '' MaxEmptyLinesToKeep: 2 PenaltyBreakBeforeFirstCallParameter: 19 PenaltyBreakComment: 300 PenaltyBreakFirstLessLess: 120 PenaltyBreakString: 1000 PenaltyExcessCharacter: 1000000 PointerAlignment: Right ReflowComments: false SortIncludes: false SpaceAfterCStyleCast: false SpaceBeforeAssignmentOperators: true SpaceBeforeParens: Always SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 1 SpacesInContainerLiterals: true SpacesInCStyleCastParentheses: false SpacesInParentheses: false SpacesInSquareBrackets: false Standard: Cpp11 TabWidth: 4 UseTab: Never ... sscg-sscg-3.0.2/COPYING000066400000000000000000001060121420717536000144500ustar00rootroot00000000000000 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 . 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. sscg-sscg-3.0.2/Changelog.md000066400000000000000000000010171420717536000156250ustar00rootroot00000000000000# Changes for sscg 3.0 ## New features * Support for OpenSSL 3.0 * Support for outputting named Diffie-Hellman parameter groups * Support for CentOS Stream 9 ## Major version notes * SSCG now requires OpenSSL 1.1.0 or later. * sscg will now always output DH parameters to a PEM file. It will default to using the `ffdhe4096` group. * Generated certificate lifetime now defaults to 398 days, rather than ten years to conform to [modern browser expectations](https://chromium-review.googlesource.com/c/chromium/src/+/2258372). sscg-sscg-3.0.2/README.md000066400000000000000000000213271420717536000147010ustar00rootroot00000000000000# SSCG - Simple Signed Certificate Generator Coverity Scan Build Status ## Why? x509 Certificates are complicated to get right. SSCG makes it easy to generate usable, _signed_ certificates quickly without needing to understand complex `openssl`, `certtool` or `certutil` commands. ## Quick Usage - Certificates Signed by a Private CA ``` /usr/bin/sscg ```` This will produce a `ca.crt` and a pair of `service.pem` and `service-key.pem` files in the current directory, the latter of which is signed by the private key of the `ca.crt`. The CA's private key will be destroyed by default after these files are created, so nothing further can be signed by it. (See [this blog post](https://sgallagh.wordpress.com/2016/05/02/self-signed-ssltls-certificates-why-they-are-terrible-and-a-better-alternative/) for details on why this is desirable.) Certificates generated by SSCG will be valid by default for securing the current machine's hostname and no others. To add further names (such as for a multi-homed system), look at the `--subject-alt-name` argument below. ## Full Usage Usage of sscg: ``` Usage: sscg [OPTION...] -q, --quiet Display no output unless there is an error. -v, --verbose Display progress messages. -d, --debug Enable logging of debug messages. Implies verbose. Warning! This will print private key information to the screen! -V, --version Display the version number and exit. -f, --force Overwrite any pre-existing files in the requested locations --lifetime=1-3650 Certificate lifetime (days). (default: 398) --country=US, CZ, etc. Certificate DN: Country (C). (default: "US") --state=Massachusetts, British Columbia, etc. Certificate DN: State or Province (ST). --locality=Westford, Paris, etc. Certificate DN: Locality (L). --organization=My Company Certificate DN: Organization (O). (default: "Unspecified") --organizational-unit=Engineering, etc. Certificate DN: Organizational Unit (OU). --email=myname@example.com Certificate DN: Email Address (Email). --hostname=server.example.com The valid hostname of the certificate. Must be an FQDN. (default: current system FQDN) --subject-alt-name alt.example.com Optional additional valid hostnames for the certificate. In addition to hostnames, this option also accepts explicit values supported by RFC 5280 such as IP:xxx.xxx.xxx.xxx/yyy.yyy.yyy.yyy May be specified multiple times. --package=STRING Unused. Retained for compatibility with earlier versions of sscg. --key-strength=2048 or larger Strength of the certificate private keys in bits. (default: 2048) --hash-alg={sha256,sha384,sha512} Hashing algorithm to use for signing. (default: "sha256") --cipher-alg={des-ede3-cbc,aes-256-cbc} Cipher to use for encrypting key files. (default: "aes-256-cbc") --ca-file=STRING Path where the public CA certificate will be stored. (default: "./ca.crt") --ca-mode=0644 File mode of the created CA certificate. --ca-key-file=STRING Path where the CA's private key will be stored. If unspecified, the key will be destroyed rather than written to the disk. --ca-key-mode=0600 File mode of the created CA key. --ca-key-password=STRING Provide a password for the CA key file. Note that this will be visible in the process table for all users, so it should be used for testing purposes only. Use --ca-keypassfile or --ca-key-password-prompt for secure password entry. --ca-key-passfile=STRING A file containing the password to encrypt the CA key file. -C, --ca-key-password-prompt Prompt to enter a password for the CA key file. --crl-file=STRING Path where an (empty) Certificate Revocation List file will be created, for applications that expect such a file to exist. If unspecified, no such file will be created. --crl-mode=0644 File mode of the created Certificate Revocation List. --cert-file=STRING Path where the public service certificate will be stored. (default "./service.pem") --cert-mode=0644 File mode of the created certificate. --cert-key-file=STRING Path where the service's private key will be stored. (default "service-key.pem") --cert-key-mode=0600 File mode of the created certificate key. -p, --cert-key-password=STRING Provide a password for the service key file. Note that this will be visible in the process table for all users, so this flag should be used for testing purposes only. Use --cert-keypassfile or --cert-key-password-prompt for secure password entry. --cert-key-passfile=STRING A file containing the password to encrypt the service key file. -P, --cert-key-password-prompt Prompt to enter a password for the service key file. --client-file=STRING Path where a client authentication certificate will be stored. --client-mode=0644 File mode of the created certificate. --client-key-file=STRING Path where the client's private key will be stored. (default is the client-file) --client-key-mode=0600 File mode of the created certificate key. --client-key-password=STRING Provide a password for the client key file. Note that this will be visible in the process table for all users, so this flag should be used for testing purposes only. Use --client-keypassfile or --client-key-password-prompt for secure password entry. --client-key-passfile=STRING A file containing the password to encrypt the client key file. --client-key-password-prompt Prompt to enter a password for the client key file. --dhparams-file=STRING A file to contain a set of Diffie-Hellman parameters. (Default: "./dhparams.pem") --dhparams-named-group=STRING Output well-known DH parameters. The available named groups are: ffdhe2048, ffdhe3072, ffdhe4096, ffdhe6144, ffdhe8192, modp_2048, modp_3072, modp_4096, modp_6144, modp_8192, modp_1536, dh_1024_160, dh_2048_224, dh_2048_256. (Default: "ffdhe4096") --dhparams-prime-len=INT The length of the prime number to generate for dhparams, in bits. If set to non-zero, the parameters will be generated rather than using a well-known group. (default: 0) --dhparams-generator={2,3,5} The generator value for dhparams. (default: 2) Help options: -?, --help Show this help message --usage Display brief usage message ``` For developers, you can run with the environment variable `SSCG_TALLOC_REPORT=true` to get a memory leak report. sscg-sscg-3.0.2/include/000077500000000000000000000000001420717536000150405ustar00rootroot00000000000000sscg-sscg-3.0.2/include/authority.h000066400000000000000000000020171420717536000172410ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ #include "sscg.h" #include "x509.h" #ifndef _AUTHORITY_H #define _AUTHORITY_H int create_private_CA (TALLOC_CTX *mem_ctx, const struct sscg_options *options, struct sscg_x509_cert **_cacert, struct sscg_evp_pkey **_cakey); #endif /* _AUTHORITY_H */ sscg-sscg-3.0.2/include/bignum.h000066400000000000000000000024201420717536000164700ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ #ifndef _SSCG_BIGNUM_H #define _SSCG_BIGNUM_H #include #include "sscg.h" /* Add definitions for some helper values added in OpenSSL 1.1.0 when building against OpenSSL 1.0.2 */ #ifndef BN_RAND_TOP_ANY #define BN_RAND_TOP_ANY -1 #endif #ifndef BN_RAND_BOTTOM_ANY #define BN_RAND_BOTTOM_ANY 0 #endif struct sscg_bignum { BIGNUM *bn; }; int sscg_bignum_destructor (TALLOC_CTX *mem_ctx); int sscg_init_bignum (TALLOC_CTX *mem_ctx, unsigned long num, struct sscg_bignum **bn); #endif /* _SSCG_BIGNUM_H */ sscg-sscg-3.0.2/include/cert.h000066400000000000000000000022131420717536000161440ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ #include "sscg.h" #include "x509.h" #include "key.h" #ifndef _SSCG_CERT_H #define _SSCG_CERT_H int create_cert (TALLOC_CTX *mem_ctx, const struct sscg_options *options, struct sscg_x509_cert *ca_cert, struct sscg_evp_pkey *ca_key, enum sscg_cert_type type, struct sscg_x509_cert **_svc_cert, struct sscg_evp_pkey **_svc_key); #endif /* _SSCG_CERT_H */ sscg-sscg-3.0.2/include/dhparams.h000066400000000000000000000024301420717536000170070ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2019 by Stephen Gallagher */ #ifndef _SSCG_DHPARAMS_H #define _SSCG_DHPARAMS_H #include #include #include "include/sscg.h" extern const char *dh_fips_groups[]; extern const char *dh_nonfips_groups[]; int create_dhparams (enum sscg_verbosity verbosity, int prime_len, int generator, EVP_PKEY **dhparams); bool is_valid_named_group (const char *group_name); char * valid_dh_group_names (TALLOC_CTX *mem_ctx); int get_params_by_named_group (const char *group_name, EVP_PKEY **dhparams); #endif /* _SSCG_DHPARAMS_H */ sscg-sscg-3.0.2/include/io_utils.h000066400000000000000000000073551420717536000170520ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2019 by Stephen Gallagher */ #ifndef _SSCG_IO_UTILS_H #define _SSCG_IO_UTILS_H #include #include #include #include "include/key.h" #include "include/sscg.h" struct sscg_stream { BIO *bio; char *path; int mode; int filetypes; bool pass_prompt; char *passphrase; }; int sscg_normalize_path (TALLOC_CTX *mem_ctx, const char *path, char **_normalized_path); struct sscg_stream * sscg_io_utils_get_stream_by_path (struct sscg_stream **streams, const char *normalized_path); struct sscg_stream * sscg_io_utils_get_stream_by_type (struct sscg_stream **streams, enum sscg_file_type filetype); BIO * sscg_io_utils_get_bio_by_type (struct sscg_stream **streams, enum sscg_file_type filetype); const char * sscg_io_utils_get_path_by_type (struct sscg_stream **streams, enum sscg_file_type filetype); /** * sscg_io_utils_add_output_file: * @streams: The array of streams from the sscg_options * @filetype: * @path: The path to the file on disk. * @mode: The filesystem mode this file should have when written to disk. * See chmod(1) for the possible values. * * Prepares all output filenames to be opened. Files are not created until * sscg_io_utils_open_output_files() is called. */ int sscg_io_utils_add_output_file (struct sscg_stream **streams, enum sscg_file_type filetype, const char *path, int mode); /** * sscg_io_utils_add_output_key: * @streams: The array of streams from the sscg_options * @filetype: * @path: The path to the file on disk. * @mode: The filesystem mode this file should have when written to disk. * See chmod(1) for the possible values. * @pass_prompt: Whether the user should be prompted to enter a passphrase * interactively. * @passphrase: The passphrase supplied at the command line. * @passfile: The path to a file containing the passphrase. * * Prepares all output filenames to be opened. Files are not created until * sscg_io_utils_open_output_files() is called. */ int sscg_io_utils_add_output_key (struct sscg_stream **streams, enum sscg_file_type filetype, const char *path, int mode, bool pass_prompt, char *passphrase, char *passfile); int sscg_io_utils_open_output_files (struct sscg_stream **streams, bool overwrite); int sscg_io_utils_write_privatekey (struct sscg_stream **streams, enum sscg_file_type filetype, struct sscg_evp_pkey *key, struct sscg_options *options); /* If this function fails, some of the output files may be left as 0400 */ int sscg_io_utils_finalize_output_files (struct sscg_stream **streams); #endif /* _SSCG_IO_UTILS_H */ sscg-sscg-3.0.2/include/key.h000066400000000000000000000021271420717536000160030ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ #ifndef _SSCG_KEY_H #define _SSCG_KEY_H #include #include #include #include "include/sscg.h" #include "include/bignum.h" struct sscg_evp_pkey { EVP_PKEY *evp_pkey; }; int sscg_generate_rsa_key (TALLOC_CTX *mem_ctx, int bits, struct sscg_evp_pkey **_key); #endif /* _SSCG_KEY_H */ sscg-sscg-3.0.2/include/sscg.h000066400000000000000000000266021420717536000161560ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ /* This is a master header file that should be included by all sscg source files. */ #ifndef _SSCG_H #define _SSCG_H #include #include #include #include #include #include #include #include /* TODO: implement internationalization */ #ifndef _ #ifdef HAVE_GETTEXT #define _(STRING) gettext (STRING) #else #define _(STRING) STRING #endif /* HAVE_GETTEXT */ #endif /* _ */ #ifndef EOK #define EOK 0 #endif #ifndef discard_const #define discard_const(ptr) ((void *)((uintptr_t) (ptr))) #endif #ifndef talloc_zfree #define talloc_zfree(ptr) \ do \ { \ talloc_free (discard_const (ptr)); \ ptr = NULL; \ } \ while (0) #endif #define CHECK_MEM(ptr) \ do \ { \ if (!ptr) \ { \ ret = ENOMEM; \ goto done; \ } \ } \ while (0) #define CHECK_OK(_ret) \ do \ { \ if (_ret != EOK) \ { \ goto done; \ } \ } \ while (0) /* The function changed in 1.1, but the library and reason names did not */ #ifndef UI_F_UI_SET_RESULT_EX #define UI_F_UI_SET_RESULT_EX UI_F_UI_SET_RESULT #endif #define CHECK_SSL(_sslret, _fn) \ do \ { \ if (_sslret != 1) \ { \ /* Get information about error from OpenSSL */ \ unsigned long _ssl_error = ERR_get_error (); \ if ((ERR_GET_LIB (_ssl_error) == ERR_LIB_UI) && \ ((ERR_GET_REASON (_ssl_error) == UI_R_RESULT_TOO_LARGE) || \ (ERR_GET_REASON (_ssl_error) == UI_R_RESULT_TOO_SMALL))) \ { \ fprintf ( \ stderr, \ "Passphrases must be between %d and %d characters. \n", \ SSCG_MIN_KEY_PASS_LEN, \ SSCG_MAX_KEY_PASS_LEN); \ ret = EINVAL; \ goto done; \ } \ fprintf (stderr, \ "Error occurred in " #_fn ": [%s].\n", \ ERR_error_string (_ssl_error, NULL)); \ ret = EIO; \ goto done; \ } \ } \ while (0) #define CHECK_BIO(ptr, file) \ do \ { \ if (!ptr) \ { \ ret = errno; \ fprintf (stderr, \ "Could not write to %s. Check directory permissions.\n", \ file); \ goto done; \ } \ } \ while (0) #define SSCG_CERT_DEFAULT_MODE 0644 #define SSCG_CERT_DEFAULT_MODE_HELP _ ("0644") #define SSCG_KEY_DEFAULT_MODE 0600 #define SSCG_KEY_DEFAULT_MODE_HELP _ ("0600") enum sscg_verbosity { SSCG_QUIET = -1, SSCG_DEFAULT, SSCG_VERBOSE, SSCG_DEBUG }; extern int verbosity; const char *sscg_get_verbosity_name (enum sscg_verbosity); #define SSCG_LOG(_level, _format, ...) \ do \ { \ if (verbosity >= _level) \ { \ printf ("%s", sscg_get_verbosity_name (_level)); \ printf (_format, ##__VA_ARGS__); \ } \ } \ while (0) #define SSCG_ERROR(_format, ...) \ do \ { \ if (verbosity > SSCG_QUIET) \ { \ fprintf (stderr, "ERROR: "); \ fprintf (stderr, _format, ##__VA_ARGS__); \ } \ } \ while (0) enum sscg_file_type { SSCG_FILE_TYPE_UNKNOWN = -1, SSCG_FILE_TYPE_CA, SSCG_FILE_TYPE_CA_KEY, SSCG_FILE_TYPE_SVC, SSCG_FILE_TYPE_SVC_KEY, SSCG_FILE_TYPE_CLIENT, SSCG_FILE_TYPE_CLIENT_KEY, SSCG_FILE_TYPE_CRL, SSCG_FILE_TYPE_DHPARAMS, SSCG_NUM_FILE_TYPES }; #define SSCG_FILE_TYPE_KEYS \ ((1 << SSCG_FILE_TYPE_CA_KEY) | (1 << SSCG_FILE_TYPE_SVC_KEY) | \ (1 << SSCG_FILE_TYPE_CLIENT_KEY)) #define SSCG_FILE_TYPE_SVC_TYPES \ ((1 << SSCG_FILE_TYPE_SVC) | (1 << SSCG_FILE_TYPE_SVC_KEY)) #define SSCG_FILE_TYPE_CLIENT_TYPES \ ((1 << SSCG_FILE_TYPE_CLIENT) | (1 << SSCG_FILE_TYPE_CLIENT_KEY)) #define SSCG_FILE_TYPE_CA_TYPES \ ((1 << SSCG_FILE_TYPE_CA) | (1 << SSCG_FILE_TYPE_CA_KEY)) const char * sscg_get_file_type_name (enum sscg_file_type _type); #define GET_BIO(_type) sscg_io_utils_get_bio_by_type (options->streams, _type) #define GET_PATH(_type) \ sscg_io_utils_get_path_by_type (options->streams, _type) #define ANNOUNCE_WRITE(_type) \ SSCG_LOG (SSCG_DEFAULT, \ "Wrote %s to %s\n", \ sscg_get_file_type_name (_type), \ GET_PATH (_type)); struct sscg_options { /* How noisy to be when printing information */ enum sscg_verbosity verbosity; /* Whether to print the version and exit */ bool print_version; /* How long should certificates be valid (in days) */ int lifetime; /* Subject information */ const char *country; const char *state; const char *locality; const char *org; const char *org_unit; const char *email; const char *hostname; char **subject_alt_names; /* Encryption requirements */ int key_strength; int minimum_key_strength; char *hash_alg; char *cipher_alg; const EVP_CIPHER *cipher; const EVP_MD *hash_fn; int ca_key_pass_prompt; int cert_key_pass_prompt; int client_key_pass_prompt; /* Output Files */ struct sscg_stream **streams; char *ca_file; char *ca_key_file; int ca_mode; int ca_key_mode; char *ca_key_password; char *ca_key_passfile; char *cert_file; char *cert_key_file; int cert_mode; int cert_key_mode; char *cert_key_password; char *cert_key_passfile; char *client_file; char *client_key_file; int client_mode; int client_key_mode; char *client_key_password; char *client_key_passfile; char *crl_file; int crl_mode; char *dhparams_file; int dhparams_mode; /* Diffie-Hellman Parameters */ char *dhparams_group; int dhparams_prime_len; int dhparams_generator; /* Overwrite the output files */ bool overwrite; }; enum sscg_cert_type { SSCG_CERT_TYPE_UNKNOWN = -1, SSCG_CERT_TYPE_SERVER, SSCG_CERT_TYPE_CLIENT, SSCG_NUM_CERT_TYPES }; #define SSCG_MIN_KEY_PASS_LEN 4 #define SSCG_MAX_KEY_PASS_LEN 1023 int sscg_handle_arguments (TALLOC_CTX *mem_ctx, int argc, const char **argv, struct sscg_options **config); #endif /* _SSCG_H */ sscg-sscg-3.0.2/include/x509.h000066400000000000000000000060761420717536000157270ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ #ifndef _SSCG_X509_H #define _SSCG_X509_H #include #include #include "include/sscg.h" #include "include/bignum.h" #include "include/key.h" struct sscg_cert_info { /* === Input Data === */ struct sscg_bignum *serial; const EVP_MD *hash_fn; /* Subject information */ const char *country; const char *state; const char *locality; const char *org; const char *org_unit; const char *cn; const char *email; char **subject_alt_names; /* X509v3 Extensions */ STACK_OF (X509_EXTENSION) * extensions; }; /* Initialize a certificate */ struct sscg_cert_info * sscg_cert_info_new (TALLOC_CTX *mem_ctx, const EVP_MD *hash_fn); struct sscg_x509_req { X509_REQ *x509_req; }; struct sscg_x509_cert { X509 *certificate; }; /* Generate a random serial number The generated serial number will be the size of sizeof(unsigned long) in bits. This is to ensure that it can be returned by BN_get_word(). */ int sscg_generate_serial (TALLOC_CTX *mem_ctx, struct sscg_bignum **serial); /* Create a Certificate Signing Request If this function succeeds, it returns 0 and _csr is allocated and populated. If it fails, it will return an errno code and _csr is undefined. */ int sscg_x509v3_csr_new (TALLOC_CTX *mem_ctx, struct sscg_cert_info *certinfo, struct sscg_evp_pkey *pkey, struct sscg_x509_req **_csr); /* Finish creation of the CSR by adding extensions and self-signing the request. */ int sscg_x509v3_csr_finalize (struct sscg_cert_info *certinfo, struct sscg_evp_pkey *spkey, struct sscg_x509_req *csr); /* Sign a CSR with a private key * Returns a signed X509 certificate through the _cert parameter if ret == 0, * allocated on mem_ctx. */ int sscg_sign_x509_csr (TALLOC_CTX *mem_ctx, struct sscg_x509_req *scsr, struct sscg_bignum *serial, size_t days, struct sscg_x509_cert *issuer, struct sscg_evp_pkey *signing_key, const EVP_MD *hash_fn, struct sscg_x509_cert **_cert); /* Allocate an sscg_x509_cert and set a destructor to clean up the * OpenSSL certificate. */ struct sscg_x509_cert * sscg_x509_cert_new (TALLOC_CTX *mem_ctx); #endif /* _SSCG_X509_H */ sscg-sscg-3.0.2/meson.build000066400000000000000000000130051420717536000155560ustar00rootroot00000000000000project('sscg', 'c', version : '3.0.2', default_options : [ 'buildtype=debugoptimized', 'c_std=gnu99', 'warning_level=1', 'b_asneeded=true', ], license : 'MIT', meson_version : '>=0.44.0') cc = meson.get_compiler('c') test_cflags = [ '-Wpointer-arith', '-Wmissing-declarations', '-Wmissing-prototypes', '-Wstrict-prototypes', '-Wuninitialized', '-Werror=implicit', '-Werror=init-self', '-Werror=main', '-Werror=missing-braces', '-Werror=return-type', '-Werror=array-bounds', '-Werror=write-strings', '-DG_LOG_USE_STRUCTURED', ] foreach cflag: test_cflags if cc.has_argument(cflag) add_project_arguments(cflag, language : 'c') endif endforeach pkg = import('pkgconfig') crypto = dependency('libcrypto11', version: '>= 1.1.0', required: false) if crypto.found() else crypto = dependency('libcrypto', version: '>= 1.1.0') endif ssl = dependency('libssl11', version: '>= 1.1.0', required: false) if ssl.found() else ssl = dependency('libssl', version: '>= 1.1.0') endif path_utils = dependency('path_utils') talloc = dependency('talloc') popt = dependency( 'popt', version : '>=1.14', required : true) has_evp_rsa_gen = cc.has_header_symbol( 'openssl/rsa.h', 'EVP_RSA_gen', dependencies: [ crypto ]) has_ossl_param = cc.has_header_symbol( 'openssl/core.h', 'OSSL_PARAM') sscg_bin_srcs = [ 'src/arguments.c', 'src/sscg.c', ] sscg_lib_srcs = [ 'src/authority.c', 'src/bignum.c', 'src/cert.c', 'src/dhparams.c', 'src/io_utils.c', 'src/key.c', 'src/x509.c', ] sscg_lib_hdrs = [ 'include/authority.h', 'include/bignum.h', 'include/cert.h', 'include/dhparams.h', 'include/io_utils.h', 'include/key.h', 'include/sscg.h', 'include/x509.h', ] sscg_lib = static_library( 'sscg', sources : sscg_lib_srcs, dependencies : [ crypto, ssl, talloc, ], install : false, pic : true, ) sscg = executable( 'sscg', sscg_bin_srcs, link_with : sscg_lib, dependencies : [ crypto, path_utils, popt, ssl, talloc, ], include_directories : include_directories('.'), install : true, ) # Fake test to ensure that all sources and headers are formatted properly test_clang_format = find_program('clang-format', required: false) if not test_clang_format.found() test_clang_format = disabler() endif clang_args = [ '-i' ] test('test_clang_format', test_clang_format, args : clang_args + files(sscg_lib_srcs + sscg_lib_hdrs + sscg_bin_srcs)) create_ca_test = executable( 'create_ca_test', 'test/create_ca_test.c', link_with : sscg_lib, dependencies: [ crypto ], install:false, ) test('create_ca_test', create_ca_test, timeout: 120) create_csr_test = executable( 'create_csr_test', 'test/create_csr_test.c', link_with : sscg_lib, dependencies: [ crypto ], install:false, ) test('create_csr_test', create_csr_test) generate_rsa_key_test = executable( 'generate_rsa_key_test', 'test/generate_rsa_key_test.c', link_with : sscg_lib, dependencies: [ crypto ], install:false, ) test('generate_rsa_key_test', generate_rsa_key_test, timeout: 120) generate_serial_test = executable( 'generate_serial_test', 'test/generate_serial_test.c', link_with : sscg_lib, dependencies: [ crypto ], install:false, ) test('generate_serial_test', generate_serial_test) init_bignum_test = executable( 'init_bignum_test', 'test/init_bignum_test.c', link_with : sscg_lib, dependencies: [ crypto ], install : false, ) test('init_bignum_test', init_bignum_test) # Test generating 512-bit, 1024-bit and 2048-bit and 4096 DH params with # multiple generators. 2048-bit and larger takes a long time, so they are # excluded from the test suite by default. prime_lengths = [ 512, 1024 ] dhparam_timeout = 240 if get_option('run_slow_tests') prime_lengths = prime_lengths + [ 2048, 4096 ] dhparam_timeout = 900 endif generators = [ 2, 5 ] dhparams_test = executable( 'dhparams_test', 'test/dhparams_test.c', link_with : sscg_lib, dependencies: [ crypto ], install : false ) foreach prime_len : prime_lengths foreach g : generators test('dhparams_test_' + prime_len.to_string() + '_' + g.to_string(), dhparams_test, args: [ prime_len.to_string(), g.to_string() ], timeout: dhparam_timeout) endforeach endforeach named_dhparams_test = executable( 'named_dhparams_test', 'test/named_dhparams_test.c', link_with : sscg_lib, dependencies: [ crypto ], install : false, ) # takes *very* long on some architectures like Debian armel test('named_dhparams_test', named_dhparams_test, timeout : 2700) cdata = configuration_data() cdata.set_quoted('PACKAGE_VERSION', meson.project_version()) cdata.set('HAVE_SSL_EVP_RSA_GEN', has_evp_rsa_gen) cdata.set('HAVE_OSSL_PARAM', has_ossl_param) configure_file( output : 'config.h', configuration : cdata) # Generate a manpage from the POPT documentation help2man = find_program('help2man') manpage = custom_target('manpage', output : 'sscg.8', capture : true, command : [ help2man, '-s', '8', '-n', 'Tool for generating x.509 certificates', '-N', sscg, ], install : true, build_by_default : true, install_dir : join_paths( get_option('prefix'), get_option('mandir'), 'man8'), ) sscg-sscg-3.0.2/meson_options.txt000066400000000000000000000020211420717536000170450ustar00rootroot00000000000000# This file is part of sscg. # # sscg 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. # # sscg 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 sscg. If not, see . # # Copyright 2019 by Stephen Gallagher # Generating 4096-bit Diffie-Hellman parameters can take over ten minutes on a # fast system. We skip testing it by default. # Some tests take a long time (dozens of seconds or even minutes) # For general development, we will skip them and run them only in the CI # environment. option('run_slow_tests', type : 'boolean', value : false) sscg-sscg-3.0.2/packaging/000077500000000000000000000000001420717536000153415ustar00rootroot00000000000000sscg-sscg-3.0.2/packaging/debian/000077500000000000000000000000001420717536000165635ustar00rootroot00000000000000sscg-sscg-3.0.2/packaging/debian/changelog000066400000000000000000000002271420717536000204360ustar00rootroot00000000000000sscg (0-1) unstable; urgency=low * Initial release. (Closes: #986830) -- Stephen Gallagher Wed, 07 Apr 2021 09:39:20 +0200 sscg-sscg-3.0.2/packaging/debian/control000066400000000000000000000017511420717536000201720ustar00rootroot00000000000000Source: sscg Section: utils Priority: optional Build-Depends: debhelper-compat (= 12), meson, help2man, libpath-utils-dev, libpopt-dev, libssl-dev, libtalloc-dev, pkgconf, Maintainer: Stephen Gallagher Uploaders: Martin Pitt Homepage: https://github.com/sgallagher/sscg/ Vcs-Git: https://salsa.debian.org/debian/sscg.git Vcs-Browser: https://salsa.debian.org/debian/sscg Standards-Version: 4.6.0 Rules-Requires-Root: no Package: sscg Architecture: any Depends: ${shlibs:Depends}, ${misc:Depends} Description: simple SSL certificate generator sscg is a utility to aid in the creation of more secure "self-signed" certificates. The certificates created by this tool are generated in a way so as to create a CA certificate that can be safely imported into a client machine to trust the service certificate without needing to set up a full PKI environment and without exposing the machine to a risk of false signatures from the service certificate. sscg-sscg-3.0.2/packaging/debian/copyright000066400000000000000000000053701420717536000205230ustar00rootroot00000000000000Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: sscg Upstream-Contact: Stephen Gallagher Source: https://github.com/sgallagher/sscg/ Files: * Copyright: 2017 - 2019 by Stephen Gallagher License: GPL-3+ with OpenSSL exception 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. . 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. . The full text of the GPL is distributed as in /usr/share/common-licenses/GPL-3 on Debian systems. Files: subprojects/popt/* Copyright: (C) 1998-2002 Red Hat, Inc. (c) 2010-2011 Elia Pinto (c) 1998 by Addison Wesley Longman, Inc. License: X11 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: . The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. . THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. . Except as contained in this notice, the name of the X Consortium shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from the X Consortium. sscg-sscg-3.0.2/packaging/debian/rules000077500000000000000000000001211420717536000176350ustar00rootroot00000000000000#!/usr/bin/make -f export DEB_BUILD_MAINT_OPTIONS = hardening=+all %: dh "$@" sscg-sscg-3.0.2/packaging/debian/source/000077500000000000000000000000001420717536000200635ustar00rootroot00000000000000sscg-sscg-3.0.2/packaging/debian/source/format000066400000000000000000000000141420717536000212710ustar00rootroot000000000000003.0 (quilt) sscg-sscg-3.0.2/packaging/debian/watch000066400000000000000000000001251420717536000176120ustar00rootroot00000000000000version=4 https://github.com/sgallagher/sscg/releases/ .*/sscg-([\d\.]+)\.tar\.[gx]z sscg-sscg-3.0.2/packaging/fedora/000077500000000000000000000000001420717536000166015ustar00rootroot00000000000000sscg-sscg-3.0.2/packaging/fedora/sscg.spec000066400000000000000000000030171420717536000204150ustar00rootroot00000000000000%global provider github %global provider_tld com %global project sgallagher %global repo sscg # https://github.com/sgallagher/sscg %global provider_prefix %{provider}.%{provider_tld}/%{project}/%{repo} %global import_path %{provider_prefix} %{!?meson_test: %global meson_test %{__meson} test -C %{_vpath_builddir} --num-processes %{_smp_build_ncpus} --print-errorlogs} Name: sscg Version: 3.0.2 Release: %autorelease Summary: Simple SSL certificate generator License: GPLv3+ with exceptions URL: https://%{provider_prefix} Source0: https://%{provider_prefix}/archive/refs/tags/%{repo}-%{version}.tar.gz BuildRequires: gcc BuildRequires: libtalloc-devel BuildRequires: openssl-devel BuildRequires: popt-devel BuildRequires: libpath_utils-devel BuildRequires: meson BuildRequires: ninja-build BuildRequires: help2man %description A utility to aid in the creation of more secure "self-signed" certificates. The certificates created by this tool are generated in a way so as to create a CA certificate that can be safely imported into a client machine to trust the service certificate without needing to set up a full PKI environment and without exposing the machine to a risk of false signatures from the service certificate. %prep %autosetup -p1 -n %{name}-%{name}-%{version} %build %meson %meson_build %install %meson_install %check %meson_test -t 10 %files %license COPYING %doc README.md %{_bindir}/%{name} %{_mandir}/man8/%{name}.8* %changelog %autochangelog sscg-sscg-3.0.2/src/000077500000000000000000000000001420717536000142045ustar00rootroot00000000000000sscg-sscg-3.0.2/src/arguments.c000066400000000000000000000504571420717536000163700ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2021 by Stephen Gallagher */ #include #include #include #include #include #include #include #include "include/sscg.h" #include "include/dhparams.h" #include "config.h" #define _GNU_SOURCE void print_options (struct sscg_options *opts); static int get_security_level (void) { SSL_CTX *ssl_ctx = SSL_CTX_new (TLS_method ()); int security_level = SSL_CTX_get_security_level (ssl_ctx); SSL_CTX_free (ssl_ctx); ssl_ctx = NULL; return security_level; } static int set_default_options (struct sscg_options *opts) { int security_level = get_security_level (); opts->ca_mode = SSCG_CERT_DEFAULT_MODE; opts->ca_key_mode = SSCG_KEY_DEFAULT_MODE; opts->cert_mode = SSCG_CERT_DEFAULT_MODE; opts->cert_key_mode = SSCG_KEY_DEFAULT_MODE; opts->client_mode = SSCG_CERT_DEFAULT_MODE; opts->client_key_mode = SSCG_KEY_DEFAULT_MODE; opts->crl_mode = SSCG_CERT_DEFAULT_MODE; opts->dhparams_mode = SSCG_CERT_DEFAULT_MODE; opts->lifetime = 398; opts->dhparams_file = talloc_strdup (opts, "dhparams.pem"); opts->dhparams_group = talloc_strdup (opts, "ffdhe4096"); opts->dhparams_generator = 2; /* Select the default key strength based on the system security level * See: * https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_get_security_level.html * for the specification of the minimums. */ switch (security_level) { case 0: case 1: case 2: /* Security level 2 and below permits lower key-strengths, but SSCG * will set a minimum of 2048 bits and the sha256 hash algorithm. */ opts->hash_alg = talloc_strdup (opts, "sha256"); opts->key_strength = 2048; break; case 3: opts->hash_alg = talloc_strdup (opts, "sha256"); opts->key_strength = 3072; break; case 4: opts->hash_alg = talloc_strdup (opts, "sha384"); opts->key_strength = 7680; break; default: /* Unknown security level. Default to the highest we know about */ fprintf (stderr, "Unknown system security level %d. Defaulting to highest-known " "level.\n", security_level); /* Fall through */ case 5: opts->hash_alg = talloc_strdup (opts, "sha512"); opts->key_strength = 15360; break; } opts->minimum_key_strength = opts->key_strength; opts->cipher_alg = talloc_strdup (opts, "aes-256-cbc"); return 0; } int sscg_handle_arguments (TALLOC_CTX *mem_ctx, int argc, const char **argv, struct sscg_options **config) { int ret, sret, opt; poptContext pc; char *minimum_key_strength_help = NULL; char *named_groups_help = NULL; char *country = NULL; char *state = NULL; char *locality = NULL; char *organization = NULL; char *organizational_unit = NULL; char *email = NULL; char *hostname = NULL; char *packagename; char **alternative_names = NULL; TALLOC_CTX *tmp_ctx = talloc_new (NULL); CHECK_MEM (tmp_ctx); struct sscg_options *options = talloc_zero (tmp_ctx, struct sscg_options); CHECK_MEM (options); options->streams = talloc_zero_array (options, struct sscg_stream *, SSCG_NUM_FILE_TYPES); ret = set_default_options (options); if (ret != EOK) goto done; minimum_key_strength_help = talloc_asprintf (tmp_ctx, "%d or larger", options->minimum_key_strength); named_groups_help = talloc_asprintf (tmp_ctx, "Output well-known DH parameters. The available named " "groups are: %s. (Default: \"ffdhe4096\")", valid_dh_group_names (tmp_ctx)); options->verbosity = SSCG_DEFAULT; // clang-format off struct poptOption long_options[] = { POPT_AUTOHELP { "quiet", 'q', POPT_ARG_VAL, &options->verbosity, SSCG_QUIET, ("Display no output unless there is an error."), NULL }, { "verbose", 'v', POPT_ARG_VAL, &options->verbosity, SSCG_VERBOSE, _ ("Display progress messages."), NULL }, { "debug", 'd', POPT_ARG_VAL, &options->verbosity, SSCG_DEBUG, _ ("Enable logging of debug messages. Implies verbose. Warning! " "This will print private key information to the screen!"), NULL }, { "version", 'V', POPT_ARG_NONE, &options->print_version, 0, _ ("Display the version number and exit."), NULL }, { "force", 'f', POPT_ARG_NONE, &options->overwrite, 0, _ ("Overwrite any pre-existing files in the requested locations"), NULL }, { "lifetime", '\0', POPT_ARG_INT | POPT_ARGFLAG_SHOW_DEFAULT, &options->lifetime, 0, _ ("Certificate lifetime (days)."), _ ("1-3650") }, { "country", '\0', POPT_ARG_STRING, &country, 0, _ ("Certificate DN: Country (C). (default: \"US\")"), _ ("US, CZ, etc.") }, { "state", '\0', POPT_ARG_STRING, &state, 0, _ ("Certificate DN: State or Province (ST)."), _ ("Massachusetts, British Columbia, etc.") }, { "locality", '\0', POPT_ARG_STRING, &locality, 0, _ ("Certificate DN: Locality (L)."), _ ("Westford, Paris, etc.") }, { "organization", '\0', POPT_ARG_STRING, &organization, 0, _ ("Certificate DN: Organization (O). (default: \"Unspecified\")"), _ ("My Company") }, { "organizational-unit", '\0', POPT_ARG_STRING, &organizational_unit, 0, _ ("Certificate DN: Organizational Unit (OU)."), _ ("Engineering, etc.") }, { "email", '\0', POPT_ARG_STRING, &email, 0, _ ("Certificate DN: Email Address (Email)."), _ ("myname@example.com") }, { "hostname", '\0', POPT_ARG_STRING, &hostname, 0, _ ("The valid hostname of the certificate. Must be an FQDN. (default: " "current system FQDN)"), _ ("server.example.com") }, { "subject-alt-name", '\0', POPT_ARG_ARGV, &alternative_names, 0, _ ("Optional additional valid hostnames for the certificate. " "In addition to hostnames, this option also accepts explicit values " "supported by RFC 5280 such as " "IP:xxx.xxx.xxx.xxx/yyy.yyy.yyy.yyy " "May be specified multiple times."), _ ("alt.example.com") }, { "package", '\0', POPT_ARG_STRING, &packagename, 0, _ ("Unused. Retained for compatibility with earlier versions of sscg."), NULL, }, { "key-strength", '\0', POPT_ARG_INT | POPT_ARGFLAG_SHOW_DEFAULT, &options->key_strength, 0, _ ("Strength of the certificate private keys in bits."), minimum_key_strength_help }, { "hash-alg", '\0', POPT_ARG_STRING | POPT_ARGFLAG_SHOW_DEFAULT, &options->hash_alg, 0, _ ("Hashing algorithm to use for signing."), _ ("{sha256,sha384,sha512}"), }, { "cipher-alg", '\0', POPT_ARG_STRING | POPT_ARGFLAG_SHOW_DEFAULT, &options->cipher_alg, 0, _ ("Cipher to use for encrypting key files."), _ ("{des-ede3-cbc,aes-256-cbc}"), }, { "ca-file", '\0', POPT_ARG_STRING, &options->ca_file, 0, _ ("Path where the public CA certificate will be stored. (default: " "\"./ca.crt\")"), NULL, }, { "ca-mode", '\0', POPT_ARG_INT, &options->ca_mode, 0, _ ("File mode of the created CA certificate."), SSCG_CERT_DEFAULT_MODE_HELP, }, { "ca-key-file", '\0', POPT_ARG_STRING, &options->ca_key_file, 0, _ ("Path where the CA's private key will be stored. If unspecified, " "the key will be destroyed rather than written to the disk."), NULL, }, { "ca-key-mode", '\0', POPT_ARG_INT, &options->ca_key_mode, 0, _ ("File mode of the created CA key."), SSCG_KEY_DEFAULT_MODE_HELP, }, { "ca-key-password", '\0', POPT_ARG_STRING, &options->ca_key_password, 0, _ ("Provide a password for the CA key file. Note that this will be " "visible in the process table for all users, so it should be used " "for testing purposes only. Use --ca-keypassfile or " "--ca-key-password-prompt for secure password entry."), NULL }, { "ca-key-passfile", '\0', POPT_ARG_STRING, &options->ca_key_passfile, 0, _ ("A file containing the password to encrypt the CA key file."), NULL }, { "ca-key-password-prompt", 'C', POPT_ARG_NONE, &options->ca_key_pass_prompt, 0, _ ("Prompt to enter a password for the CA key file."), NULL }, { "crl-file", '\0', POPT_ARG_STRING, &options->crl_file, 0, _ ("Path where an (empty) Certificate Revocation List file will be " "created, for applications that expect such a file to exist. If " "unspecified, no such file will be created."), NULL }, { "crl-mode", '\0', POPT_ARG_INT, &options->crl_mode, 0, _ ("File mode of the created Certificate Revocation List."), SSCG_CERT_DEFAULT_MODE_HELP, }, { "cert-file", '\0', POPT_ARG_STRING, &options->cert_file, 0, _ ("Path where the public service certificate will be stored. " "(default \"./service.pem\")"), NULL, }, { "cert-mode", '\0', POPT_ARG_INT, &options->cert_mode, 0, _ ("File mode of the created certificate."), SSCG_CERT_DEFAULT_MODE_HELP, }, { "cert-key-file", '\0', POPT_ARG_STRING, &options->cert_key_file, 0, _ ("Path where the service's private key will be stored. " "(default \"service-key.pem\")"), NULL, }, { "cert-key-mode", '\0', POPT_ARG_INT, &options->cert_key_mode, 0, _ ("File mode of the created certificate key."), SSCG_KEY_DEFAULT_MODE_HELP, }, { "cert-key-password", 'p', POPT_ARG_STRING, &options->cert_key_password, 0, _ ("Provide a password for the service key file. Note that this will be " "visible in the process table for all users, so this flag should be " "used for testing purposes only. Use --cert-keypassfile or " "--cert-key-password-prompt for secure password entry."), NULL }, { "cert-key-passfile", '\0', POPT_ARG_STRING, &options->cert_key_passfile, 0, _ ("A file containing the password to encrypt the service key file."), NULL }, { "cert-key-password-prompt", 'P', POPT_ARG_NONE, &options->cert_key_pass_prompt, 0, _ ("Prompt to enter a password for the service key file."), NULL }, { "client-file", '\0', POPT_ARG_STRING, &options->client_file, 0, _ ("Path where a client authentication certificate will be stored."), NULL }, { "client-mode", '\0', POPT_ARG_INT, &options->client_mode, 0, _ ("File mode of the created certificate."), SSCG_CERT_DEFAULT_MODE_HELP, }, { "client-key-file", '\0', POPT_ARG_STRING, &options->client_key_file, 0, _ ("Path where the client's private key will be stored. " "(default is the client-file)"), NULL, }, { "client-key-mode", '\0', POPT_ARG_INT, &options->client_key_mode, 0, _ ("File mode of the created certificate key."), SSCG_KEY_DEFAULT_MODE_HELP, }, { "client-key-password", '\0', POPT_ARG_STRING, &options->client_key_password, 0, _ ("Provide a password for the client key file. Note that this will be " "visible in the process table for all users, so this flag should be " "used for testing purposes only. Use --client-keypassfile or " "--client-key-password-prompt for secure password entry."), NULL }, { "client-key-passfile", '\0', POPT_ARG_STRING, &options->client_key_passfile, 0, _ ("A file containing the password to encrypt the client key file."), NULL }, { "client-key-password-prompt", '\0', POPT_ARG_NONE, &options->client_key_pass_prompt, 0, _ ("Prompt to enter a password for the client key file."), NULL }, { "dhparams-file", '\0', POPT_ARG_STRING, &options->dhparams_file, 0, _("A file to contain a set of Diffie-Hellman parameters. " "(Default: \"./dhparams.pem\")"), NULL }, { "dhparams-named-group", '\0', POPT_ARG_STRING, &options->dhparams_group, 0, _(named_groups_help), NULL }, { "dhparams-prime-len", '\0', POPT_ARG_INT | POPT_ARGFLAG_SHOW_DEFAULT, &options->dhparams_prime_len, 0, _ ("The length of the prime number to generate for dhparams, in bits. " "If set to non-zero, the parameters will be generated rather than " "using a well-known group."), NULL }, { "dhparams-generator", '\0', POPT_ARG_INT | POPT_ARGFLAG_SHOW_DEFAULT, &options->dhparams_generator, 0, _ ("The generator value for dhparams."), _("{2,3,5}") }, POPT_TABLEEND }; // clang-format on pc = poptGetContext (argv[0], argc, argv, long_options, 0); while ((opt = poptGetNextOpt (pc)) != -1) { switch (opt) { default: fprintf (stderr, "\nInvalid option %s: %s\n\n", poptBadOption (pc, 0), poptStrerror (opt)); poptPrintUsage (pc, stderr, 0); ret = EINVAL; goto done; } } if (options->print_version) { /* Print the version number and exit */ printf ("%s\n", PACKAGE_VERSION); exit (0); } verbosity = options->verbosity; /* Process the Subject information */ if (country) { if (strlen (country) != 2) { fprintf (stderr, "Country codes must be exactly two letters.\n"); ret = EINVAL; goto done; } options->country = talloc_strdup (options, country); } else { /* Country name is mandatory. 1.0 (in Golang) defaulted to "US", so we'll keep it the same to avoid breaking existing usages. */ options->country = talloc_strdup (options, "US"); } CHECK_MEM (options->country); if (state) { options->state = talloc_strdup (options, state); } else { options->state = talloc_strdup (options, ""); } CHECK_MEM (options->state); if (locality) { options->locality = talloc_strdup (options, locality); } else { options->locality = talloc_strdup (options, ""); } CHECK_MEM (options->locality); if (organization) { options->org = talloc_strdup (options, organization); } else { /* In 1.0 (Golang), organization defaulted to "Unspecified". Keep it the same here to avoid breaking existing usages. */ options->org = talloc_strdup (options, "Unspecified"); } CHECK_MEM (options->org); if (organizational_unit) { options->org_unit = talloc_strdup (options, organizational_unit); } else { options->org_unit = talloc_strdup (options, ""); } CHECK_MEM (options->org_unit); if (email) { options->email = talloc_strdup (options, email); } else { options->email = talloc_strdup (options, ""); } CHECK_MEM (options->email); if (hostname) { options->hostname = talloc_strdup (options, hostname); } else { /* Get hostname from the system */ hostname = talloc_zero_array (options, char, HOST_NAME_MAX + 1); CHECK_MEM (hostname); sret = gethostname (hostname, HOST_NAME_MAX); if (sret != 0) { ret = errno; goto done; } options->hostname = hostname; } CHECK_MEM (options->hostname); if (strnlen (options->hostname, MAXHOSTNAMELEN + 1) > MAXHOSTNAMELEN) { fprintf ( stderr, "Hostnames may not exceed %d characters\n", MAXHOSTNAMELEN); ret = EINVAL; goto done; } /* Use a realloc loop to copy the names from popt into the options struct. It's not the most efficient approach, but it's only done one time, so there is no sense in optimizing it. */ if (alternative_names) { size_t i = 0; while (alternative_names[i] != NULL) { options->subject_alt_names = talloc_realloc ( options, options->subject_alt_names, char *, i + 2); CHECK_MEM (options->subject_alt_names); options->subject_alt_names[i] = talloc_strdup (options->subject_alt_names, alternative_names[i]); CHECK_MEM (options->subject_alt_names[i]); /* Add a NULL terminator to the end */ options->subject_alt_names[i + 1] = NULL; i++; } } if (options->key_strength < options->minimum_key_strength) { fprintf (stderr, "Key strength must be at least %d bits.\n", options->minimum_key_strength); ret = EINVAL; goto done; } /* Make sure we have a valid cipher */ options->cipher = EVP_get_cipherbyname (options->cipher_alg); if (!options->cipher) { fprintf (stderr, "Invalid cipher specified: %s\n", options->cipher_alg); ret = EINVAL; goto done; } /* TODO: restrict this to approved hashes. * For now, we'll only list SHA[256|384|512] in the help */ options->hash_fn = EVP_get_digestbyname (options->hash_alg); if (!is_valid_named_group (options->dhparams_group)) { fprintf (stderr, "Unknown Diffie Hellman finite field group.\n"); fprintf ( stderr, "Valid groups are: %s.\n", valid_dh_group_names (tmp_ctx)); ret = EINVAL; goto done; } if (!options->hash_fn) { fprintf (stderr, "Unsupported hashing algorithm."); ret = EINVAL; goto done; } /* On verbose logging, display all of the selected options. */ if (options->verbosity >= SSCG_VERBOSE) print_options (options); poptFreeContext (pc); *config = talloc_steal (mem_ctx, options); ret = EOK; done: talloc_free (tmp_ctx); return ret; } void print_options (struct sscg_options *opts) { size_t i = 0; fprintf (stdout, "==== Options ====\n"); fprintf (stdout, "Certificate lifetime: %d\n", opts->lifetime); fprintf (stdout, "Country: \"%s\"\n", opts->country); fprintf (stdout, "State or Principality: \"%s\"\n", opts->state); fprintf (stdout, "Locality: \"%s\"\n", opts->locality); fprintf (stdout, "Organization: \"%s\"\n", opts->org); fprintf (stdout, "Organizational Unit: \"%s\"\n", opts->org_unit); fprintf (stdout, "Email Address: \"%s\"\n", opts->email); fprintf (stdout, "Hostname: \"%s\"\n", opts->hostname); if (opts->subject_alt_names) { for (i = 0; opts->subject_alt_names[i]; i++) { fprintf (stdout, "Subject Alternative Name: \"%s\"\n", opts->subject_alt_names[i]); } } fprintf (stdout, "=================\n"); } sscg-sscg-3.0.2/src/authority.c000066400000000000000000000144551420717536000164110ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ #include #include "include/sscg.h" #include "include/authority.h" #include "include/x509.h" #include "include/key.h" int create_private_CA (TALLOC_CTX *mem_ctx, const struct sscg_options *options, struct sscg_x509_cert **_cacert, struct sscg_evp_pkey **_cakey) { int ret; int bits; size_t i; TALLOC_CTX *tmp_ctx = NULL; struct sscg_bignum *serial; struct sscg_cert_info *ca_certinfo; struct sscg_x509_req *csr; struct sscg_evp_pkey *pkey; struct sscg_x509_cert *cert; X509_EXTENSION *ex = NULL; X509V3_CTX xctx; char *name_constraint; char *san; char *tmp; tmp_ctx = talloc_new (NULL); CHECK_MEM (tmp_ctx); /* create a serial number for this certificate */ ret = sscg_generate_serial (tmp_ctx, &serial); CHECK_OK (ret); ca_certinfo = sscg_cert_info_new (tmp_ctx, options->hash_fn); CHECK_MEM (ca_certinfo); /* Populate cert_info from options */ ca_certinfo->country = talloc_strdup (ca_certinfo, options->country); CHECK_MEM (ca_certinfo->country); ca_certinfo->state = talloc_strdup (ca_certinfo, options->state); CHECK_MEM (ca_certinfo->state); ca_certinfo->locality = talloc_strdup (ca_certinfo, options->locality); CHECK_MEM (ca_certinfo->locality); ca_certinfo->org = talloc_strdup (ca_certinfo, options->org); CHECK_MEM (ca_certinfo->org); ca_certinfo->org_unit = talloc_asprintf (ca_certinfo, "ca-%lu", BN_get_word (serial->bn)); ca_certinfo->email = talloc_strdup (ca_certinfo, options->email); CHECK_MEM (ca_certinfo->email); ca_certinfo->cn = talloc_strdup (ca_certinfo, options->hostname); CHECK_MEM (ca_certinfo->cn); /* Make this a CA certificate */ /* Add key extensions */ ex = X509V3_EXT_conf_nid ( NULL, NULL, NID_key_usage, "critical,digitalSignature,keyEncipherment,keyCertSign"); CHECK_MEM (ex); sk_X509_EXTENSION_push (ca_certinfo->extensions, ex); /* Mark it as a CA */ ex = X509V3_EXT_conf_nid (NULL, NULL, NID_basic_constraints, "CA:TRUE"); CHECK_MEM (ex); sk_X509_EXTENSION_push (ca_certinfo->extensions, ex); /* Restrict signing to the hostname and subjectAltNames of the service certificate */ name_constraint = talloc_asprintf (tmp_ctx, "permitted;DNS:%s", options->hostname); CHECK_MEM (name_constraint); if (options->subject_alt_names) { for (i = 0; options->subject_alt_names[i]; i++) { if (!strchr (options->subject_alt_names[i], ':')) { san = talloc_asprintf ( tmp_ctx, "DNS:%s", options->subject_alt_names[i]); } else { san = talloc_strdup (tmp_ctx, options->subject_alt_names[i]); } CHECK_MEM (san); tmp = talloc_asprintf ( tmp_ctx, "%s, permitted;%s", name_constraint, san); talloc_zfree (san); CHECK_MEM (tmp); talloc_free (name_constraint); name_constraint = tmp; } } ex = X509V3_EXT_conf_nid (NULL, NULL, NID_name_constraints, name_constraint); if (!ex) { ret = EINVAL; fprintf (stderr, "Invalid name constraint: %s\n", name_constraint); goto done; } sk_X509_EXTENSION_push (ca_certinfo->extensions, ex); talloc_free (name_constraint); /* For the private CA, we always use 4096 bits and an exponent value of RSA F4 aka 0x10001 (65537) */ bits = 4096; /* Generate an RSA keypair for this CA */ if (options->verbosity >= SSCG_VERBOSE) { fprintf (stdout, "Generating RSA key for private CA.\n"); } /* TODO: support DSA keys as well */ ret = sscg_generate_rsa_key (tmp_ctx, bits, &pkey); CHECK_OK (ret); /* Create a certificate signing request for the private CA */ if (options->verbosity >= SSCG_VERBOSE) { fprintf (stdout, "Generating CSR for private CA.\n"); } ret = sscg_x509v3_csr_new (tmp_ctx, ca_certinfo, pkey, &csr); CHECK_OK (ret); X509V3_set_ctx_nodb (&xctx); X509V3_set_ctx (&xctx, NULL, NULL, csr->x509_req, NULL, 0); /* Set the Subject Key Identifier extension */ if (options->verbosity >= SSCG_DEBUG) { fprintf (stderr, "DEBUG: Creating SubjectKeyIdentifier\n"); } ex = X509V3_EXT_conf_nid (NULL, &xctx, NID_subject_key_identifier, "hash"); if (!ex) { /* Get information about error from OpenSSL */ fprintf (stderr, "Error occurred in " "X509V3_EXT_conf_nid(SubjectKeyIdentifier): [%s].\n", ERR_error_string (ERR_get_error (), NULL)); ret = EIO; goto done; } sk_X509_EXTENSION_push (ca_certinfo->extensions, ex); /* Finalize the CSR */ ret = sscg_x509v3_csr_finalize (ca_certinfo, pkey, csr); CHECK_OK (ret); if (options->verbosity >= SSCG_DEBUG) { fprintf (stderr, "DEBUG: Writing CA CSR to ./debug-ca.csr\n"); BIO *ca_csr_out = BIO_new_file ("./debug-ca.csr", "w"); int sslret = PEM_write_bio_X509_REQ (ca_csr_out, csr->x509_req); CHECK_SSL (sslret, PEM_write_bio_X509_REQ); } /* Self-sign the private CA */ if (options->verbosity >= SSCG_VERBOSE) { fprintf (stdout, "Signing CSR for private CA.\n"); } ret = sscg_sign_x509_csr (tmp_ctx, csr, serial, options->lifetime, NULL, pkey, options->hash_fn, &cert); CHECK_OK (ret); *_cacert = talloc_steal (mem_ctx, cert); *_cakey = talloc_steal (mem_ctx, pkey); ret = EOK; done: talloc_zfree (tmp_ctx); return ret; } sscg-sscg-3.0.2/src/bignum.c000066400000000000000000000033751420717536000156410ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ #include #include "include/sscg.h" #include "include/bignum.h" static int _sscg_bignum_destructor (TALLOC_CTX *mem_ctx) { struct sscg_bignum *bn = talloc_get_type_abort (mem_ctx, struct sscg_bignum); BN_free (bn->bn); return 0; } int sscg_init_bignum (TALLOC_CTX *mem_ctx, unsigned long num, struct sscg_bignum **bn) { int ret = EOK; int sslret; struct sscg_bignum *bignum; TALLOC_CTX *tmp_ctx = talloc_new (NULL); if (!tmp_ctx) { return ENOMEM; } bignum = talloc_zero (tmp_ctx, struct sscg_bignum); if (!bignum) { ret = ENOMEM; goto done; } BIGNUM *sslbn = BN_new (); if (!sslbn) { ret = ENOMEM; goto done; } bignum->bn = sslbn; talloc_set_destructor ((TALLOC_CTX *)bignum, _sscg_bignum_destructor); sslret = BN_set_word (bignum->bn, num); CHECK_SSL (sslret, BN_set_word); ret = EOK; done: if (ret == EOK) { *bn = talloc_steal (mem_ctx, bignum); } talloc_zfree (tmp_ctx); return ret; } sscg-sscg-3.0.2/src/cert.c000066400000000000000000000130301420717536000153020ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ #include "include/sscg.h" #include "include/cert.h" #include "include/x509.h" #include "include/key.h" int create_cert (TALLOC_CTX *mem_ctx, const struct sscg_options *options, struct sscg_x509_cert *ca_cert, struct sscg_evp_pkey *ca_key, enum sscg_cert_type type, struct sscg_x509_cert **_cert, struct sscg_evp_pkey **_key) { int ret; size_t i; struct sscg_bignum *serial; struct sscg_cert_info *certinfo; struct sscg_x509_req *csr; struct sscg_evp_pkey *pkey; struct sscg_x509_cert *cert; X509_EXTENSION *ex = NULL; EXTENDED_KEY_USAGE *extended; TALLOC_CTX *tmp_ctx = NULL; tmp_ctx = talloc_new (NULL); CHECK_MEM (tmp_ctx); /* create a serial number for this certificate */ ret = sscg_generate_serial (tmp_ctx, &serial); CHECK_OK (ret); certinfo = sscg_cert_info_new (tmp_ctx, options->hash_fn); CHECK_MEM (certinfo); /* Populate cert_info from options */ certinfo->country = talloc_strdup (certinfo, options->country); CHECK_MEM (certinfo->country); certinfo->state = talloc_strdup (certinfo, options->state); CHECK_MEM (certinfo->state); certinfo->locality = talloc_strdup (certinfo, options->locality); CHECK_MEM (certinfo->locality); certinfo->org = talloc_strdup (certinfo, options->org); CHECK_MEM (certinfo->org); certinfo->org_unit = talloc_strdup (certinfo, options->org_unit); CHECK_MEM (certinfo->org_unit); certinfo->email = talloc_strdup (certinfo, options->email); CHECK_MEM (certinfo->email); certinfo->cn = talloc_strdup (certinfo, options->hostname); CHECK_MEM (certinfo->cn); if (options->subject_alt_names) { for (i = 0; options->subject_alt_names[i]; i++) { certinfo->subject_alt_names = talloc_realloc ( certinfo, certinfo->subject_alt_names, char *, i + 2); CHECK_MEM (certinfo->subject_alt_names); certinfo->subject_alt_names[i] = talloc_strdup ( certinfo->subject_alt_names, options->subject_alt_names[i]); CHECK_MEM (certinfo->subject_alt_names[i]); /* Add a NULL terminator to the end */ certinfo->subject_alt_names[i + 1] = NULL; } } /* Ensure that this certificate may not sign other certificates */ /* Add key extensions */ ex = X509V3_EXT_conf_nid ( NULL, NULL, NID_key_usage, "critical,digitalSignature,keyEncipherment"); CHECK_MEM (ex); sk_X509_EXTENSION_push (certinfo->extensions, ex); extended = sk_ASN1_OBJECT_new_null (); switch (type) { case SSCG_CERT_TYPE_SERVER: sk_ASN1_OBJECT_push (extended, OBJ_nid2obj (NID_server_auth)); break; case SSCG_CERT_TYPE_CLIENT: sk_ASN1_OBJECT_push (extended, OBJ_nid2obj (NID_client_auth)); break; default: fprintf (stdout, "Unknown certificate type!"); ret = EINVAL; goto done; } ex = X509V3_EXT_i2d (NID_ext_key_usage, 0, extended); sk_ASN1_OBJECT_pop_free (extended, ASN1_OBJECT_free); sk_X509_EXTENSION_push (certinfo->extensions, ex); /* Mark it as not a CA */ ex = X509V3_EXT_conf_nid (NULL, NULL, NID_basic_constraints, "CA:FALSE"); CHECK_MEM (ex); sk_X509_EXTENSION_push (certinfo->extensions, ex); /* Generate an RSA keypair for this CA */ if (options->verbosity >= SSCG_VERBOSE) { fprintf (stdout, "Generating RSA key for certificate.\n"); } /* TODO: support DSA keys as well */ ret = sscg_generate_rsa_key (tmp_ctx, options->key_strength, &pkey); CHECK_OK (ret); /* Create a certificate signing request for the private CA */ if (options->verbosity >= SSCG_VERBOSE) { fprintf (stdout, "Generating CSR for certificate.\n"); } ret = sscg_x509v3_csr_new (tmp_ctx, certinfo, pkey, &csr); CHECK_OK (ret); /* Finalize the CSR */ ret = sscg_x509v3_csr_finalize (certinfo, pkey, csr); CHECK_OK (ret); if (options->verbosity >= SSCG_DEBUG) { const char *tempcert = SSCG_CERT_TYPE_SERVER ? "./debug-service.csr" : "debug-client.csr"; fprintf (stderr, "DEBUG: Writing certificate CSR to %s\n", tempcert); BIO *csr_out = BIO_new_file (tempcert, "w"); int sslret = PEM_write_bio_X509_REQ (csr_out, csr->x509_req); CHECK_SSL (sslret, PEM_write_bio_X509_REQ); } /* Sign the certificate */ if (options->verbosity >= SSCG_VERBOSE) { fprintf (stdout, "Signing CSR for certificate. \n"); } ret = sscg_sign_x509_csr (tmp_ctx, csr, serial, options->lifetime, ca_cert, ca_key, options->hash_fn, &cert); CHECK_OK (ret); *_cert = talloc_steal (mem_ctx, cert); *_key = talloc_steal (mem_ctx, pkey); ret = EOK; done: talloc_free (tmp_ctx); return ret; } sscg-sscg-3.0.2/src/dhparams.c000066400000000000000000000170471420717536000161600ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2019 by Stephen Gallagher */ #include #include #include #include "config.h" #include "include/sscg.h" #include "include/dhparams.h" // clang-format off #if OPENSSL_VERSION_NUMBER < 0x30000000L const char *dh_fips_groups[] = { "ffdhe2048", "ffdhe3072", "ffdhe4096", "ffdhe6144", "ffdhe8192", NULL, }; const char *dh_nonfips_groups[] = { NULL }; #else //OPENSSL_VERSION_NUMBER const char *dh_fips_groups[] = { "ffdhe2048", "ffdhe3072", "ffdhe4096", "ffdhe6144", "ffdhe8192", "modp_2048", "modp_3072", "modp_4096", "modp_6144", "modp_8192", NULL, }; const char *dh_nonfips_groups[] = { "modp_1536", "dh_1024_160", "dh_2048_224", "dh_2048_256", NULL }; #endif //OPENSSL_VERSION_NUMBER // clang-format on char * valid_dh_group_names (TALLOC_CTX *mem_ctx) { size_t i; char *names = NULL; TALLOC_CTX *tmp_ctx = talloc_new (NULL); i = 0; while (dh_fips_groups[i]) { names = talloc_asprintf_append (names, "%s, ", dh_fips_groups[i]); if (!names) goto done; i++; } i = 0; while (dh_nonfips_groups[i]) { names = talloc_asprintf_append (names, "%s, ", dh_nonfips_groups[i]); if (!names) goto done; i++; } /* Truncate the last ", " */ names = talloc_strndup (names, names, strlen (names) - 2); if (!names) goto done; talloc_steal (mem_ctx, names); done: talloc_free (tmp_ctx); return names; } static int evp_cb (EVP_PKEY_CTX *ctx); int create_dhparams (enum sscg_verbosity verbosity, int prime_len, int generator, EVP_PKEY **dhparams) { int ret; EVP_PKEY_CTX *pctx = NULL; EVP_PKEY *params = NULL; /* First validate the input */ assert (dhparams && !*dhparams); if (prime_len <= 0) { fprintf (stderr, "Prime length must be a positive integer"); ret = ERANGE; goto done; } if (generator <= 0) { fprintf (stderr, "Generator must be a positive integer"); ret = ERANGE; goto done; } if (verbosity >= SSCG_DEFAULT) { fprintf (stdout, "Generating DH parameters of length %d and generator %d. " "This will take a long time.\n", prime_len, generator); } /* Create the context for generating the parameters */ if (!(pctx = EVP_PKEY_CTX_new_id (EVP_PKEY_DH, NULL))) { ERR_print_errors_fp (stderr); ret = ENOMEM; goto done; } if (!EVP_PKEY_paramgen_init (pctx)) { ERR_print_errors_fp (stderr); ret = EIO; goto done; } /* Set up a callback to display progress */ EVP_PKEY_CTX_set_cb (pctx, evp_cb); /* Set the parameter values */ if (!EVP_PKEY_CTX_set_dh_paramgen_prime_len (pctx, prime_len)) { ERR_print_errors_fp (stderr); ret = EIO; goto done; } if (!EVP_PKEY_CTX_set_dh_paramgen_generator (pctx, generator)) { ERR_print_errors_fp (stderr); ret = EIO; goto done; } /* Generate parameters */ if (!EVP_PKEY_paramgen (pctx, ¶ms)) { ERR_print_errors_fp (stderr); ret = EIO; goto done; } ret = EOK; *dhparams = params; params = NULL; done: EVP_PKEY_free (params); EVP_PKEY_CTX_free (pctx); return ret; } static int evp_cb (EVP_PKEY_CTX *ctx) { char c = '*'; int p = EVP_PKEY_CTX_get_keygen_info (ctx, 0); // clang-format off if (p == 0) c = '.'; if (p == 1) c = '+'; if (p == 2) c = '*'; if (p == 3) c = '\n'; // clang-format on fprintf (stdout, "%c", c); return 1; } bool is_valid_named_group (const char *group_name) { size_t i = 0; /* Check FIPS groups */ while (dh_fips_groups[i]) { if (strcmp (dh_fips_groups[i], group_name) == 0) return true; i++; } /* Check non-FIPS groups */ #if OPENSSL_VERSION_NUMBER < 0x30000000L if (!FIPS_mode ()) #else if (!EVP_default_properties_is_fips_enabled (NULL)) #endif { i = 0; while (dh_nonfips_groups[i]) { if (strcmp (dh_nonfips_groups[i], group_name) == 0) return true; i++; } } return false; } #ifdef HAVE_OSSL_PARAM int get_params_by_named_group (const char *group_name, EVP_PKEY **dhparams) { int ret; EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name (NULL, "DH", NULL); OSSL_PARAM ossl_params[2]; EVP_PKEY *params = NULL; char *name = NULL; TALLOC_CTX *tmp_ctx = talloc_new (NULL); if (!is_valid_named_group (group_name)) { fprintf (stderr, "Unknown Diffie Hellman finite field group.\n"); fprintf ( stderr, "Valid groups are: %s.\n", valid_dh_group_names (tmp_ctx)); ret = EINVAL; goto done; } name = talloc_strdup (NULL, group_name); ossl_params[0] = OSSL_PARAM_construct_utf8_string ("group", name, 0); ossl_params[1] = OSSL_PARAM_construct_end (); if (!EVP_PKEY_keygen_init (pctx)) { ERR_print_errors_fp (stderr); ret = EIO; goto done; } if (!EVP_PKEY_CTX_set_params (pctx, ossl_params)) { ERR_print_errors_fp (stderr); ret = EIO; goto done; } if (!EVP_PKEY_generate (pctx, ¶ms)) { ERR_print_errors_fp (stderr); ret = EIO; goto done; } *dhparams = params; params = NULL; ret = EOK; done: EVP_PKEY_free (params); EVP_PKEY_CTX_free (pctx); talloc_free (tmp_ctx); return ret; } #else //HAVE_OSSL_PARAM static int get_group_nid (const char *group_name) { if (strcmp ("ffdhe2048", group_name) == 0) { return NID_ffdhe2048; } else if (strcmp ("ffdhe3072", group_name) == 0) { return NID_ffdhe3072; } else if (strcmp ("ffdhe4096", group_name) == 0) { return NID_ffdhe4096; } else if (strcmp ("ffdhe6144", group_name) == 0) { return NID_ffdhe6144; } else if (strcmp ("ffdhe8192", group_name) == 0) { return NID_ffdhe8192; } return NID_undef; } int get_params_by_named_group (const char *group_name, EVP_PKEY **dhparams) { int ret, sslret; DH *dh = NULL; EVP_PKEY *pkey = NULL; TALLOC_CTX *tmp_ctx = talloc_new (NULL); if (!is_valid_named_group (group_name)) { fprintf (stderr, "Unknown Diffie Hellman finite field group.\n"); fprintf ( stderr, "Valid groups are: %s.\n", valid_dh_group_names (tmp_ctx)); ret = EINVAL; goto done; } dh = DH_new_by_nid (get_group_nid (group_name)); if (!dh) { fprintf ( stderr, "Unknown Diffie Hellman finite field group %s.\n", group_name); ret = EINVAL; goto done; } pkey = EVP_PKEY_new (); sslret = EVP_PKEY_assign_DH (pkey, dh); CHECK_SSL (sslret, "EVP_PKEY_ASSIGN_DH"); /* The dhparams are owned by the pkey now */ dh = NULL; *dhparams = pkey; pkey = NULL; ret = EOK; done: DH_free (dh); EVP_PKEY_free (pkey); talloc_free (tmp_ctx); return ret; } #endif //HAVE_OSSL_PARAM sscg-sscg-3.0.2/src/io_utils.c000066400000000000000000000367211420717536000162100ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2019 by Stephen Gallagher */ #include #include #include #include #include "include/io_utils.h" #include "include/key.h" #include "include/sscg.h" /* Same as OpenSSL CLI */ #define MAX_PW_LEN 1024 int sscg_normalize_path (TALLOC_CTX *mem_ctx, const char *path, char **_normalized_path) { int ret; char *normalized_path = NULL; TALLOC_CTX *tmp_ctx = talloc_new (NULL); CHECK_MEM (tmp_ctx); normalized_path = talloc_zero_array (tmp_ctx, char, PATH_MAX); CHECK_MEM (normalized_path); ret = make_normalized_absolute_path (normalized_path, PATH_MAX, path); CHECK_OK (ret); *_normalized_path = talloc_strdup (mem_ctx, normalized_path); CHECK_MEM (*_normalized_path); ret = EOK; done: talloc_free (normalized_path); talloc_free (tmp_ctx); return ret; } static int sscg_stream_destructor (TALLOC_CTX *ptr) { struct sscg_stream *stream = talloc_get_type_abort (ptr, struct sscg_stream); BIO_free (stream->bio); /* Zero out the memory before freeing it so we don't leak passwords */ if (stream->passphrase) { memset (stream->passphrase, 0, strnlen (stream->passphrase, MAX_PW_LEN)); } return 0; } struct sscg_stream * sscg_io_utils_get_stream_by_path (struct sscg_stream **streams, const char *normalized_path) { struct sscg_stream *stream = NULL; /* First see if this path already exists in the list */ for (int i = 0; (stream = streams[i]) && i < SSCG_NUM_FILE_TYPES; i++) { if (strcmp (normalized_path, stream->path) == 0) break; } return stream; } struct sscg_stream * sscg_io_utils_get_stream_by_type (struct sscg_stream **streams, enum sscg_file_type filetype) { struct sscg_stream *stream = NULL; /* First see if this path already exists in the list */ for (int i = 0; (stream = streams[i]) && i < SSCG_NUM_FILE_TYPES; i++) { SSCG_LOG (SSCG_DEBUG, "Checking for 0x%.4x in 0x%.4x\n", (1 << filetype), stream->filetypes); if (stream->filetypes & (1 << filetype)) { SSCG_LOG (SSCG_DEBUG, "Found file type %s in %s\n", sscg_get_file_type_name (filetype), stream->path); break; } } if (!stream) SSCG_LOG (SSCG_DEBUG, "Could not locate file type: %s. Skipping.\n", sscg_get_file_type_name (filetype)); return stream; } BIO * sscg_io_utils_get_bio_by_type (struct sscg_stream **streams, enum sscg_file_type filetype) { struct sscg_stream *_tmp_stream = sscg_io_utils_get_stream_by_type (streams, filetype); if (_tmp_stream) { return _tmp_stream->bio; } return NULL; } const char * sscg_io_utils_get_path_by_type (struct sscg_stream **streams, enum sscg_file_type filetype) { struct sscg_stream *_tmp_stream = sscg_io_utils_get_stream_by_type (streams, filetype); if (_tmp_stream) { return _tmp_stream->path; } return NULL; } /* This function takes a copy of a string into a talloc hierarchy and memsets * the original string to zeroes to avoid leaking it when that memory is freed. */ static char * sscg_secure_string_steal (TALLOC_CTX *mem_ctx, char *src) { char *dest = talloc_strdup (mem_ctx, src); memset ((void *)src, 0, strlen (src)); return dest; } static int validate_passphrase (struct sscg_stream *stream) { /* Ignore non-key types */ if (!(stream->filetypes & SSCG_FILE_TYPE_KEYS)) return EOK; /* Ignore unset passwords; these will be prompted for when writing out the * key file */ if (!stream->passphrase) return EOK; size_t pass_len = strnlen (stream->passphrase, SSCG_MAX_KEY_PASS_LEN + 1); if ((pass_len < SSCG_MIN_KEY_PASS_LEN) || (pass_len > SSCG_MAX_KEY_PASS_LEN)) { SSCG_ERROR ("Passphrases must be between %d and %d characters. \n", SSCG_MIN_KEY_PASS_LEN, SSCG_MAX_KEY_PASS_LEN); return EINVAL; } return EOK; } static char * sscg_read_pw_file (TALLOC_CTX *mem_ctx, char *path) { int i; BIO *pwdbio = NULL; char tpass[MAX_PW_LEN + 1]; int offset = 0; char *tmp = NULL; char *password = NULL; pwdbio = BIO_new_file (path, "r"); if (pwdbio == NULL) { fprintf (stderr, "Can't open file %s\n", path); return NULL; } /* Read up to one more character than the MAX_PW_LEN */ for (offset = 0; (i = BIO_read (pwdbio, tpass + offset, MAX_PW_LEN + 1 - offset)) > 0 && offset < (MAX_PW_LEN + 1); offset += i) ; tpass[MAX_PW_LEN] = '\0'; BIO_free_all (pwdbio); pwdbio = NULL; if (i < 0) { fprintf (stderr, "Error reading password from BIO\n"); return NULL; } tmp = strchr (tpass, '\n'); if (tmp != NULL) *tmp = 0; password = talloc_strdup (mem_ctx, tpass); memset (tpass, 0, MAX_PW_LEN + 1); return password; } int sscg_io_utils_add_output_key (struct sscg_stream **streams, enum sscg_file_type filetype, const char *path, int mode, bool pass_prompt, char *passphrase, char *passfile) { int ret, i; TALLOC_CTX *tmp_ctx = NULL; struct sscg_stream *stream = NULL; char *normalized_path = NULL; /* If we haven't been passed a path, just return; it's probably an optional * output file */ if (path == NULL) { if (pass_prompt) { SSCG_ERROR ( "Passphrase prompt requested for %s, but no file path provided.\n", sscg_get_file_type_name (filetype)); return EINVAL; } if (passphrase) { SSCG_ERROR ( "Passphrase provided for %s, but no file path provided.\n", sscg_get_file_type_name (filetype)); return EINVAL; } SSCG_LOG (SSCG_DEBUG, "Got a NULL path with filetype: %s\n", sscg_get_file_type_name (filetype)); return EOK; } tmp_ctx = talloc_new (NULL); CHECK_MEM (tmp_ctx); /* Get the normalized version of the path */ ret = sscg_normalize_path (tmp_ctx, path, &normalized_path); CHECK_OK (ret); SSCG_LOG (SSCG_DEBUG, "%s file path: %s\n", sscg_get_file_type_name (filetype), normalized_path); /* First see if this path already exists in the list */ stream = sscg_io_utils_get_stream_by_path (streams, normalized_path); if (stream == NULL) { /* The path wasn't found, so open it and create it */ /* First advance the index to the end */ for (i = 0; streams[i]; i++) ; /* This should never happen. The streams array should always be * sized to the maximum number of known types. If we are asked to add * more entries to the array than we have known file types, it must be * due to a bug. */ assert (i < SSCG_NUM_FILE_TYPES); stream = talloc_zero (tmp_ctx, struct sscg_stream); CHECK_MEM (stream); talloc_set_destructor ((TALLOC_CTX *)stream, sscg_stream_destructor); stream->path = talloc_steal (stream, normalized_path); CHECK_MEM (stream->path); streams[i] = talloc_steal (streams, stream); } /* Always set the mode to the most-restrictive one requested */ SSCG_LOG (SSCG_DEBUG, "Requested mode: %o\n", mode); if (stream->mode) stream->mode &= mode; else stream->mode = mode; SSCG_LOG (SSCG_DEBUG, "Actual mode: %o\n", stream->mode); /* Add the file type */ stream->filetypes |= (1 << filetype); /* Set the password options */ stream->pass_prompt = pass_prompt; if (passphrase) { stream->passphrase = sscg_secure_string_steal (stream, passphrase); ret = validate_passphrase (stream); if (ret != EOK) goto done; } else if (passfile) { stream->passphrase = sscg_read_pw_file (stream, passfile); if (!stream->passphrase) { fprintf (stderr, "Failed to read passphrase from %s", passfile); ret = EIO; goto done; } } ret = validate_passphrase (stream); if (ret != EOK) goto done; ret = EOK; done: talloc_free (tmp_ctx); return ret; } int sscg_io_utils_add_output_file (struct sscg_stream **streams, enum sscg_file_type filetype, const char *path, int mode) { return sscg_io_utils_add_output_key ( streams, filetype, path, mode, false, NULL, NULL); } enum io_utils_errors { IO_UTILS_OK = 0, IO_UTILS_TOOMANYKEYS, IO_UTILS_DHPARAMS_NON_EXCLUSIVE, IO_UTILS_CRL_NON_EXCLUSIVE, IO_UTILS_SVC_UNMATCHED, IO_UTILS_CLIENT_UNMATCHED, IO_UTILS_CA_UNMATCHED }; static enum io_utils_errors io_utils_validate (struct sscg_stream **streams) { enum io_utils_errors ret; struct sscg_stream *stream = NULL; int keybits; int allbits = 0; for (int i = 0; (stream = streams[i]) && i < SSCG_NUM_FILE_TYPES; i++) { SSCG_LOG (SSCG_DEBUG, "filetypes: 0x%.4x\n", stream->filetypes); allbits |= stream->filetypes; /* No file may contain two different private keys */ /* First check if any private keys are in this file */ if ((keybits = stream->filetypes & SSCG_FILE_TYPE_KEYS)) { /* Next check if there is exactly one private key in the remainder. * The following bitwise magic checks whether the value is exactly a * power of two (meaning only one bit is set). If the result is * nonzero, more than one bit was set and we have been asked to * include multiple keys into the same file. */ if (keybits & (keybits - 1)) { ret = IO_UTILS_TOOMANYKEYS; goto done; } } /* The dhparams file may only contain dhparams */ if ((stream->filetypes & (1 << SSCG_FILE_TYPE_DHPARAMS)) && (stream->filetypes ^ (1 << SSCG_FILE_TYPE_DHPARAMS))) { ret = IO_UTILS_DHPARAMS_NON_EXCLUSIVE; goto done; } /* The CRL file may only contain certificate revocations */ if ((stream->filetypes & (1 << SSCG_FILE_TYPE_CRL)) && (stream->filetypes ^ (1 << SSCG_FILE_TYPE_CRL))) { ret = IO_UTILS_CRL_NON_EXCLUSIVE; goto done; } } SSCG_LOG (SSCG_DEBUG, "allbits: 0x%.4x\n", allbits); /* If the public or private key is present for the service cert, the other * must be present also */ if ((allbits & SSCG_FILE_TYPE_SVC_TYPES) && ((allbits & SSCG_FILE_TYPE_SVC_TYPES) != SSCG_FILE_TYPE_SVC_TYPES)) { ret = IO_UTILS_SVC_UNMATCHED; goto done; } /* If the public or private key is present for the client cert, the other * must be present also */ if ((allbits & SSCG_FILE_TYPE_CLIENT_TYPES) && ((allbits & SSCG_FILE_TYPE_CLIENT_TYPES) != SSCG_FILE_TYPE_CLIENT_TYPES)) { ret = IO_UTILS_CLIENT_UNMATCHED; goto done; } /* If the private key is present for the CA cert, the public key must be * present also */ if ((allbits & (1 << SSCG_FILE_TYPE_CA_KEY)) && !(allbits & (1 << SSCG_FILE_TYPE_CA))) { ret = IO_UTILS_CA_UNMATCHED; goto done; } ret = IO_UTILS_OK; done: return ret; } int sscg_io_utils_open_output_files (struct sscg_stream **streams, bool overwrite) { int ret; TALLOC_CTX *tmp_ctx = NULL; enum io_utils_errors validation_result; char *create_mode = NULL; struct sscg_stream *stream = NULL; validation_result = io_utils_validate (streams); switch (validation_result) { case IO_UTILS_TOOMANYKEYS: SSCG_ERROR ("Attempted to output multiple keys to the same file.\n"); ret = EINVAL; goto done; case IO_UTILS_CRL_NON_EXCLUSIVE: SSCG_ERROR ("The CRL file may not include other content.\n"); ret = EINVAL; goto done; case IO_UTILS_DHPARAMS_NON_EXCLUSIVE: SSCG_ERROR ("The dhparams file may not include other content.\n"); ret = EINVAL; goto done; case IO_UTILS_SVC_UNMATCHED: SSCG_ERROR ( "The service certificate must have both public and private key " "locations specified.\n"); ret = EINVAL; goto done; case IO_UTILS_CLIENT_UNMATCHED: SSCG_ERROR ( "The client certificate must have the public key location " "specified.\n"); ret = EINVAL; goto done; case IO_UTILS_CA_UNMATCHED: SSCG_ERROR ( "The CA certificate must have a public key location specified.\n"); ret = EINVAL; goto done; case IO_UTILS_OK: break; } tmp_ctx = talloc_new (NULL); CHECK_MEM (tmp_ctx); if (overwrite) create_mode = talloc_strdup (tmp_ctx, "w"); else create_mode = talloc_strdup (tmp_ctx, "wx"); CHECK_MEM (create_mode); for (int i = 0; (stream = streams[i]) && i < SSCG_NUM_FILE_TYPES; i++) { SSCG_LOG (SSCG_DEBUG, "Opening %s\n", stream->path); stream->bio = BIO_new_file (stream->path, create_mode); CHECK_BIO (stream->bio, stream->path); } ret = EOK; done: talloc_free (tmp_ctx); return ret; } int sscg_io_utils_write_privatekey (struct sscg_stream **streams, enum sscg_file_type filetype, struct sscg_evp_pkey *key, struct sscg_options *options) { int ret, sret; struct sscg_stream *stream = sscg_io_utils_get_stream_by_type (streams, filetype); if (stream) { /* This function has a default mechanism for prompting for the * password if it is passed a cipher and gets a NULL password. * * Only pass the cipher if we have a password or were instructed * to prompt for one. */ sret = PEM_write_bio_PKCS8PrivateKey ( stream->bio, key->evp_pkey, stream->pass_prompt || stream->passphrase ? options->cipher : NULL, stream->passphrase, stream->passphrase ? strlen (stream->passphrase) : 0, NULL, NULL); CHECK_SSL (sret, PEM_write_bio_PKCS8PrivateKey); ANNOUNCE_WRITE (filetype); } ret = EOK; done: return ret; } int sscg_io_utils_finalize_output_files (struct sscg_stream **streams) { struct sscg_stream *stream = NULL; FILE *fp; for (int i = 0; (stream = streams[i]) && i < SSCG_NUM_FILE_TYPES; i++) { /* Set the final permissions mode */ SSCG_LOG (SSCG_DEBUG, "Setting %s file permissions to %o\n", stream->path, stream->mode); BIO_get_fp (stream->bio, &fp); errno = 0; if (fchmod (fileno (fp), stream->mode) != 0) return errno; } return EOK; } sscg-sscg-3.0.2/src/key.c000066400000000000000000000047221420717536000151450ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ #include #include "config.h" #include "include/sscg.h" #include "include/key.h" static int _sscg_evp_pkey_destructor (TALLOC_CTX *mem_ctx) { struct sscg_evp_pkey *pkey = talloc_get_type_abort (mem_ctx, struct sscg_evp_pkey); EVP_PKEY_free (pkey->evp_pkey); return 0; } int sscg_generate_rsa_key (TALLOC_CTX *mem_ctx, int bits, struct sscg_evp_pkey **_key) { int ret; EVP_PKEY *pkey = NULL; TALLOC_CTX *tmp_ctx = NULL; #ifdef HAVE_SSL_EVP_RSA_GEN pkey = EVP_RSA_gen (bits); CHECK_MEM (pkey); #else // HAVE_SSL_EVP_RSA_GEN int sslret; RSA *rsa = NULL; struct sscg_bignum *e; tmp_ctx = talloc_new (NULL); /* Create memory for the actual key */ rsa = RSA_new (); CHECK_MEM (rsa); /* Use an exponent value of RSA F4 aka 0x10001 (65537) */ ret = sscg_init_bignum (tmp_ctx, RSA_F4, &e); CHECK_OK (ret); /* Generate a random RSA keypair */ sslret = RSA_generate_key_ex (rsa, bits, e->bn, NULL); CHECK_SSL (sslret, RSA_generate_key_ex); pkey = EVP_PKEY_new (); CHECK_MEM (pkey); sslret = EVP_PKEY_assign_RSA (pkey, rsa); CHECK_SSL (sslret, EVP_PKEY_assign_RSA); /* The memory for the RSA key is now maintained by the EVP_PKEY. Mark this variable as NULL so we don't free() it below */ rsa = NULL; #endif // HAVE_SSL_EVP_RSA_GEN /* Create the talloc container to hold the memory */ (*_key) = talloc_zero (mem_ctx, struct sscg_evp_pkey); if (!(*_key)) { ret = ENOMEM; goto done; } (*_key)->evp_pkey = pkey; talloc_set_destructor ((TALLOC_CTX *)(*_key), _sscg_evp_pkey_destructor); ret = EOK; done: #ifndef HAVE_SSL_EVP_RSA_GEN RSA_free (rsa); #endif //HAVE_SSL_EVP_RSA_GEN talloc_free (tmp_ctx); return ret; } sscg-sscg-3.0.2/src/sscg.c000066400000000000000000000220151420717536000153070ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include "config.h" #include "include/sscg.h" #include "include/authority.h" #include "include/cert.h" #include "include/dhparams.h" #include "include/io_utils.h" int verbosity; const char * sscg_get_verbosity_name (enum sscg_verbosity type) { switch (type) { case SSCG_DEFAULT: case SSCG_VERBOSE: return ""; case SSCG_DEBUG: return "DEBUG: "; default: break; } /* If it wasn't one of these, we have a bug */ return "Unknown Verbosity (bug):"; } const char * sscg_get_file_type_name (enum sscg_file_type type) { switch (type) { case SSCG_FILE_TYPE_CA: return "CA certificate"; case SSCG_FILE_TYPE_CA_KEY: return "CA certificate key"; case SSCG_FILE_TYPE_SVC: return "service certificate"; case SSCG_FILE_TYPE_SVC_KEY: return "service certificate key"; case SSCG_FILE_TYPE_CLIENT: return "client auth certificate"; case SSCG_FILE_TYPE_CLIENT_KEY: return "client auth certificate key"; case SSCG_FILE_TYPE_CRL: return "certificate revocation list"; case SSCG_FILE_TYPE_DHPARAMS: return "Diffie-Hellman parameters"; default: break; } /* If it wasn't one of these, we have a bug */ return "Unknown (bug)"; } int main (int argc, const char **argv) { int ret, sret; struct sscg_options *options; bool build_client_cert = false; struct sscg_x509_cert *cacert; struct sscg_evp_pkey *cakey; struct sscg_x509_cert *svc_cert; struct sscg_evp_pkey *svc_key; struct sscg_x509_cert *client_cert = NULL; struct sscg_evp_pkey *client_key = NULL; BIO *bp; EVP_PKEY *dhparams = NULL; struct sscg_stream *stream = NULL; /* Always use umask 0577 for generating certificates and keys This means that it's opened as write-only by the effective user. */ umask (0577); if (getenv ("SSCG_TALLOC_REPORT")) talloc_enable_null_tracking (); TALLOC_CTX *main_ctx = talloc_new (NULL); if (!main_ctx) { fprintf (stderr, "Could not allocate memory."); return ENOMEM; } ret = sscg_handle_arguments (main_ctx, argc, argv, &options); CHECK_OK (ret); /* Prepare the output files */ ret = sscg_io_utils_add_output_file (options->streams, SSCG_FILE_TYPE_CA, options->ca_file ? options->ca_file : "./ca.crt", options->ca_mode); CHECK_OK (ret); ret = sscg_io_utils_add_output_key (options->streams, SSCG_FILE_TYPE_CA_KEY, options->ca_key_file, options->ca_key_mode, options->ca_key_pass_prompt, options->ca_key_password, options->ca_key_passfile); CHECK_OK (ret); ret = sscg_io_utils_add_output_file ( options->streams, SSCG_FILE_TYPE_SVC, options->cert_file ? options->cert_file : "./service.pem", options->cert_mode); CHECK_OK (ret); ret = sscg_io_utils_add_output_key ( options->streams, SSCG_FILE_TYPE_SVC_KEY, options->cert_key_file ? options->cert_key_file : "./service-key.pem", options->cert_key_mode, options->cert_key_pass_prompt, options->cert_key_password, options->cert_key_passfile); CHECK_OK (ret); ret = sscg_io_utils_add_output_file (options->streams, SSCG_FILE_TYPE_CLIENT, options->client_file, options->client_mode); CHECK_OK (ret); ret = sscg_io_utils_add_output_key ( options->streams, SSCG_FILE_TYPE_CLIENT_KEY, options->client_key_file ? options->client_key_file : options->client_file, options->client_key_mode, options->client_key_pass_prompt, options->client_key_password, options->client_key_passfile); CHECK_OK (ret); ret = sscg_io_utils_add_output_file (options->streams, SSCG_FILE_TYPE_CRL, options->crl_file, options->crl_mode); CHECK_OK (ret); ret = sscg_io_utils_add_output_file (options->streams, SSCG_FILE_TYPE_DHPARAMS, options->dhparams_file, options->dhparams_mode); CHECK_OK (ret); /* Validate and open the file paths */ ret = sscg_io_utils_open_output_files (options->streams, options->overwrite); CHECK_OK (ret); /* Generate the private CA for the certificate */ ret = create_private_CA (main_ctx, options, &cacert, &cakey); CHECK_OK (ret); /* Generate the service certificate and sign it with the private CA */ ret = create_cert (main_ctx, options, cacert, cakey, SSCG_CERT_TYPE_SERVER, &svc_cert, &svc_key); CHECK_OK (ret); /* If requested, generate the client auth certificate and sign it with the * private CA. */ build_client_cert = !!(GET_BIO (SSCG_FILE_TYPE_CLIENT)); if (build_client_cert) { ret = create_cert (main_ctx, options, cacert, cakey, SSCG_CERT_TYPE_CLIENT, &client_cert, &client_key); CHECK_OK (ret); } /* ==== Output the final files ==== */ /* Write private keys first */ ret = sscg_io_utils_write_privatekey ( options->streams, SSCG_FILE_TYPE_CLIENT_KEY, client_key, options); CHECK_OK (ret); ret = sscg_io_utils_write_privatekey ( options->streams, SSCG_FILE_TYPE_SVC_KEY, svc_key, options); CHECK_OK (ret); ret = sscg_io_utils_write_privatekey ( options->streams, SSCG_FILE_TYPE_CA_KEY, cakey, options); CHECK_OK (ret); /* Public keys come next, in chain order */ /* Start with the client certificate */ if (build_client_cert) { sret = PEM_write_bio_X509 (GET_BIO (SSCG_FILE_TYPE_CLIENT), client_cert->certificate); CHECK_SSL (sret, PEM_write_bio_X509 (client)); ANNOUNCE_WRITE (SSCG_FILE_TYPE_CLIENT); } /* Create service public certificate */ sret = PEM_write_bio_X509 (GET_BIO (SSCG_FILE_TYPE_SVC), svc_cert->certificate); CHECK_SSL (sret, PEM_write_bio_X509 (svc)); ANNOUNCE_WRITE (SSCG_FILE_TYPE_SVC); /* Create CA public certificate */ stream = sscg_io_utils_get_stream_by_type (options->streams, SSCG_FILE_TYPE_CA); sret = PEM_write_bio_X509 (stream->bio, cacert->certificate); CHECK_SSL (sret, PEM_write_bio_X509 (CA)); ANNOUNCE_WRITE (SSCG_FILE_TYPE_CA); /* Then write any non-certificate files */ /* Create CRL file */ if (GET_BIO (SSCG_FILE_TYPE_CRL)) { /* The CRL file is left intentionally blank, so do nothing here. The * file was created as empty, so it will just be closed and have its * permissions set later. */ ANNOUNCE_WRITE (SSCG_FILE_TYPE_CRL); } /* Create DH parameters file */ bp = GET_BIO (SSCG_FILE_TYPE_DHPARAMS); if (options->dhparams_prime_len > 0) { ret = create_dhparams (options->verbosity, options->dhparams_prime_len, options->dhparams_generator, &dhparams); CHECK_OK (ret); } else { ret = get_params_by_named_group (options->dhparams_group, &dhparams); CHECK_OK (ret); } /* Export the DH parameters to the file */ sret = PEM_write_bio_Parameters (bp, dhparams); CHECK_SSL (sret, PEM_write_bio_Parameters ()); ANNOUNCE_WRITE (SSCG_FILE_TYPE_DHPARAMS); EVP_PKEY_free (dhparams); /* Set the final file permissions */ sscg_io_utils_finalize_output_files (options->streams); ret = EOK; done: talloc_zfree (main_ctx); if (ret != EOK) { SSCG_ERROR ("%s\n", strerror (ret)); } if (getenv ("SSCG_TALLOC_REPORT")) talloc_report_full (NULL, stderr); return ret; } sscg-sscg-3.0.2/src/x509.c000066400000000000000000000330711420717536000150610ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ #include #include #include #include #include "include/sscg.h" #include "include/key.h" #include "include/x509.h" #include "include/bignum.h" int sscg_generate_serial (TALLOC_CTX *mem_ctx, struct sscg_bignum **serial) { int ret = EOK; int bnret; struct sscg_bignum *bn; TALLOC_CTX *tmp_ctx = talloc_new (NULL); if (!tmp_ctx) { return ENOMEM; } ret = sscg_init_bignum (tmp_ctx, 0, &bn); CHECK_OK (ret); /* We'll create a random number of sizeof(unsigned long) - 1 bits to use as the serial. We use unsigned long to ensure that it could be printed by BN_get_word() later. We omit the last bit in order to ensure that we can't randomly get 0xffffffffL, which is reserved by BN_get_word() to mean "too large to represent". */ bnret = BN_rand (bn->bn, (sizeof (unsigned long) * CHAR_BIT) - 1, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY); CHECK_SSL (bnret, BN_rand); ret = EOK; done: if (ret == EOK) { *serial = talloc_steal (mem_ctx, bn); } talloc_zfree (tmp_ctx); return ret; } static int _sscg_certinfo_destructor (TALLOC_CTX *ctx) { struct sscg_cert_info *certinfo = talloc_get_type_abort (ctx, struct sscg_cert_info); sk_X509_EXTENSION_pop_free (certinfo->extensions, X509_EXTENSION_free); return 0; } struct sscg_cert_info * sscg_cert_info_new (TALLOC_CTX *mem_ctx, const EVP_MD *hash_fn) { int ret; struct sscg_cert_info *certinfo; certinfo = talloc_zero (mem_ctx, struct sscg_cert_info); CHECK_MEM (certinfo); if (hash_fn) { certinfo->hash_fn = hash_fn; } else { certinfo->hash_fn = EVP_sha256 (); } /* Allocate space for the stack of extensions */ certinfo->extensions = sk_X509_EXTENSION_new_null (); CHECK_MEM (certinfo->extensions); talloc_set_destructor ((TALLOC_CTX *)certinfo, _sscg_certinfo_destructor); ret = EOK; done: if (ret != EOK) { talloc_free (certinfo); return NULL; } return certinfo; } static int _sscg_csr_destructor (TALLOC_CTX *ctx) { struct sscg_x509_req *csr = talloc_get_type_abort (ctx, struct sscg_x509_req); X509_REQ_free (csr->x509_req); return 0; } int sscg_x509v3_csr_new (TALLOC_CTX *mem_ctx, struct sscg_cert_info *certinfo, struct sscg_evp_pkey *spkey, struct sscg_x509_req **_csr) { int ret, sslret; size_t i; X509_NAME *subject; char *alt_name = NULL; char *tmp = NULL; char *san = NULL; TALLOC_CTX *tmp_ctx; X509_EXTENSION *ex = NULL; struct sscg_x509_req *csr; /* Make sure we have a key available */ if (!talloc_get_type (spkey, struct sscg_evp_pkey)) { return EINVAL; } tmp_ctx = talloc_new (NULL); CHECK_MEM (tmp_ctx); csr = talloc_zero (tmp_ctx, struct sscg_x509_req); CHECK_MEM (csr); csr->x509_req = X509_REQ_new (); CHECK_MEM (csr->x509_req); talloc_set_destructor ((TALLOC_CTX *)csr, _sscg_csr_destructor); /* We will generate only x509v3 certificates */ sslret = X509_REQ_set_version (csr->x509_req, 2); CHECK_SSL (sslret, X509_REQ_set_version); subject = X509_REQ_get_subject_name (csr->x509_req); /* Country */ sslret = X509_NAME_add_entry_by_NID (subject, NID_countryName, MBSTRING_UTF8, (const unsigned char *)certinfo->country, -1, -1, 0); CHECK_SSL (sslret, X509_NAME_add_entry_by_NID (C)); /* State or Principality */ if (certinfo->state && certinfo->state[0]) { sslret = X509_NAME_add_entry_by_NID (subject, NID_stateOrProvinceName, MBSTRING_UTF8, (const unsigned char *)certinfo->state, -1, -1, 0); CHECK_SSL (sslret, X509_NAME_add_entry_by_NID (ST)); } /* Locality */ if (certinfo->locality && certinfo->locality[0]) { sslret = X509_NAME_add_entry_by_NID (subject, NID_localityName, MBSTRING_UTF8, (const unsigned char *)certinfo->locality, -1, -1, 0); CHECK_SSL (sslret, X509_NAME_add_entry_by_NID (L)); } /* Organization */ if (certinfo->org && certinfo->org[0]) { sslret = X509_NAME_add_entry_by_NID (subject, NID_organizationName, MBSTRING_UTF8, (const unsigned char *)certinfo->org, -1, -1, 0); CHECK_SSL (sslret, X509_NAME_add_entry_by_NID (O)); } /* Organizational Unit */ if (certinfo->org_unit && certinfo->org_unit[0]) { sslret = X509_NAME_add_entry_by_NID (subject, NID_organizationalUnitName, MBSTRING_UTF8, (const unsigned char *)certinfo->org_unit, -1, -1, 0); CHECK_SSL (sslret, X509_NAME_add_entry_by_NID (OU)); } /* Common Name */ sslret = X509_NAME_add_entry_by_NID (subject, NID_commonName, MBSTRING_UTF8, (const unsigned char *)certinfo->cn, -1, -1, 0); CHECK_SSL (sslret, X509_NAME_add_entry_by_NID (CN)); /* Email Address */ if (certinfo->email && certinfo->email[0]) { sslret = X509_NAME_add_entry_by_NID (subject, NID_pkcs9_emailAddress, MBSTRING_UTF8, (const unsigned char *)certinfo->email, -1, -1, 0); CHECK_SSL (sslret, X509_NAME_add_entry_by_NID (Email)); } /* SubjectAltNames */ alt_name = talloc_asprintf (tmp_ctx, "DNS:%s", certinfo->cn); CHECK_MEM (alt_name); if (certinfo->subject_alt_names) { for (i = 0; certinfo->subject_alt_names[i]; i++) { if (!strchr (certinfo->subject_alt_names[i], ':')) { san = talloc_asprintf ( tmp_ctx, "DNS:%s", certinfo->subject_alt_names[i]); } else { san = talloc_strdup (tmp_ctx, certinfo->subject_alt_names[i]); } CHECK_MEM (san); if (strnlen (san, MAXHOSTNAMELEN + 5) > MAXHOSTNAMELEN + 4) { fprintf (stderr, "Hostnames may not exceed %d characters in Subject " "Alternative Names\n", MAXHOSTNAMELEN); ret = EINVAL; goto done; } tmp = talloc_asprintf (tmp_ctx, "%s, %s", alt_name, san); talloc_zfree (san); CHECK_MEM (tmp); talloc_free (alt_name); alt_name = tmp; } } ex = X509V3_EXT_conf_nid (NULL, NULL, NID_subject_alt_name, alt_name); CHECK_MEM (ex); sk_X509_EXTENSION_push (certinfo->extensions, ex); /* Set the public key for the certificate */ sslret = X509_REQ_set_pubkey (csr->x509_req, spkey->evp_pkey); CHECK_SSL (sslret, X509_REQ_set_pubkey (OU)); *_csr = talloc_steal (mem_ctx, csr); ret = EOK; done: talloc_free (tmp_ctx); return ret; } int sscg_x509v3_csr_finalize (struct sscg_cert_info *certinfo, struct sscg_evp_pkey *spkey, struct sscg_x509_req *csr) { int ret, sslret; /* Add extensions */ sslret = X509_REQ_add_extensions (csr->x509_req, certinfo->extensions); CHECK_SSL (sslret, X509_REQ_add_extensions); /* Set the private key */ sslret = X509_REQ_sign (csr->x509_req, spkey->evp_pkey, certinfo->hash_fn); if (sslret <= 0) { /* Get information about error from OpenSSL */ fprintf (stderr, "Error occurred in X509_REQ_sign: [%s].\n", ERR_error_string (ERR_get_error (), NULL)); ret = EIO; goto done; } ret = EOK; done: return ret; } static int _sscg_cert_destructor (TALLOC_CTX *ctx) { struct sscg_x509_cert *cert = talloc_get_type_abort (ctx, struct sscg_x509_cert); X509_free (cert->certificate); return 0; } struct sscg_x509_cert * sscg_x509_cert_new (TALLOC_CTX *mem_ctx) { int ret, sslret; struct sscg_x509_cert *cert = talloc_zero (NULL, struct sscg_x509_cert); CHECK_MEM (cert); cert->certificate = X509_new (); CHECK_MEM (cert->certificate); talloc_set_destructor ((TALLOC_CTX *)cert, _sscg_cert_destructor); // set version to X509 v3 certificate sslret = X509_set_version (cert->certificate, 2); CHECK_SSL (sslret, X509_set_version); ret = EOK; done: if (ret != EOK) { talloc_free (cert); return NULL; } return talloc_steal (mem_ctx, cert); } int sscg_sign_x509_csr (TALLOC_CTX *mem_ctx, struct sscg_x509_req *scsr, struct sscg_bignum *serial, size_t days, struct sscg_x509_cert *issuer, struct sscg_evp_pkey *signing_key, const EVP_MD *hash_fn, struct sscg_x509_cert **_cert) { int ret, sslret; size_t i; struct sscg_x509_cert *scert = NULL; X509 *cert; X509_REQ *csr = NULL; X509_NAME *subject = NULL; EVP_PKEY *pktmp; STACK_OF (X509_EXTENSION) *extensions = NULL; X509_EXTENSION *ext; X509V3_CTX x509v3_ctx; TALLOC_CTX *tmp_ctx = talloc_new (NULL); CHECK_MEM (tmp_ctx); X509V3_set_ctx_nodb (&x509v3_ctx); scert = sscg_x509_cert_new (tmp_ctx); CHECK_MEM (scert); /* Easier shorthand */ cert = scert->certificate; csr = scsr->x509_req; /* Set the serial number for the new certificate */ BN_to_ASN1_INTEGER (serial->bn, X509_get_serialNumber (cert)); /* set the issuer name */ if (issuer) { X509_set_issuer_name (cert, X509_get_subject_name (issuer->certificate)); } else { /* If unspecified, it's self-signing */ X509_set_issuer_name (cert, X509_REQ_get_subject_name (csr)); } /* set time */ X509_gmtime_adj (X509_get_notBefore (cert), 0); X509_gmtime_adj (X509_get_notAfter (cert), days * 24 * 60 * 60); /* set subject */ subject = X509_NAME_dup (X509_REQ_get_subject_name (csr)); sslret = X509_set_subject_name (cert, subject); CHECK_SSL (sslret, X509_set_subject_name); /* Copy the extensions from the CSR */ extensions = X509_REQ_get_extensions (csr); for (i = 0; i < sk_X509_EXTENSION_num (extensions); i++) { ext = sk_X509_EXTENSION_value (extensions, i); sslret = X509_add_ext (cert, ext, -1); CHECK_SSL (sslret, X509_add_ext); } sk_X509_EXTENSION_pop_free (extensions, X509_EXTENSION_free); /* set pubkey from req */ pktmp = X509_REQ_get_pubkey (csr); sslret = X509_set_pubkey (cert, pktmp); EVP_PKEY_free (pktmp); CHECK_SSL (sslret, X509_set_pubkey); if (issuer) { X509V3_set_ctx (&x509v3_ctx, issuer->certificate, cert, NULL, NULL, 0); /* Set the Authority Key Identifier extension */ ext = X509V3_EXT_conf_nid (NULL, &x509v3_ctx, NID_authority_key_identifier, "keyid:always,issuer"); if (!ext) { /* Get information about error from OpenSSL */ fprintf (stderr, "Error occurred in " "X509V3_EXT_conf_nid(AuthorityKeyIdentifier): [%s].\n", ERR_error_string (ERR_get_error (), NULL)); ret = EIO; goto done; } sslret = X509_add_ext (cert, ext, -1); CHECK_SSL (sslret, X509_add_ext); X509_EXTENSION_free (ext); } /* Sign the new certificate */ sslret = X509_sign (cert, signing_key->evp_pkey, hash_fn); if (sslret <= 0) { /* Get information about error from OpenSSL */ fprintf (stderr, "Error occurred in X509_sign: [%s].\n", ERR_error_string (ERR_get_error (), NULL)); ret = EIO; goto done; } ret = EOK; done: if (ret == EOK) { *_cert = talloc_steal (mem_ctx, scert); } X509_NAME_free (subject); talloc_free (tmp_ctx); return ret; } sscg-sscg-3.0.2/test/000077500000000000000000000000001420717536000143745ustar00rootroot00000000000000sscg-sscg-3.0.2/test/create_ca_test.c000066400000000000000000000053171420717536000175130ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ #include #include #include #include #include "include/sscg.h" #include "include/x509.h" int main (int argc, char **argv) { int ret, bits; struct sscg_cert_info *certinfo; struct sscg_bignum *serial; struct sscg_x509_req *csr = NULL; struct sscg_evp_pkey *pkey = NULL; struct sscg_x509_cert *cert = NULL; TALLOC_CTX *tmp_ctx = talloc_new (NULL); if (!tmp_ctx) { return ENOMEM; } certinfo = sscg_cert_info_new (tmp_ctx, EVP_sha256 ()); if (!certinfo) { ret = ENOMEM; goto done; } ret = sscg_generate_serial (tmp_ctx, &certinfo->serial); if (ret != EOK) { printf ("FAILED.\n"); goto done; } /* Create a subject matching the defaults in sscg.c Keep this in sync if defaults change. */ certinfo->country = talloc_strdup (certinfo, "US"); CHECK_MEM (certinfo->country); certinfo->state = talloc_strdup (certinfo, ""); CHECK_MEM (certinfo->state); certinfo->locality = talloc_strdup (certinfo, ""); CHECK_MEM (certinfo->locality); certinfo->org = talloc_strdup (certinfo, "Unspecified"); CHECK_MEM (certinfo->org); certinfo->org_unit = talloc_strdup (certinfo, ""); CHECK_MEM (certinfo->org_unit); certinfo->cn = talloc_strdup (certinfo, "server.example.com"); CHECK_MEM (certinfo->cn); /* TODO: include subject alt names */ /* Generate an RSA keypair */ bits = 4096; ret = sscg_generate_rsa_key (certinfo, bits, &pkey); CHECK_OK (ret); /* Create the CSR */ ret = sscg_x509v3_csr_new (tmp_ctx, certinfo, pkey, &csr); CHECK_OK (ret); ret = sscg_x509v3_csr_finalize (certinfo, pkey, csr); CHECK_OK (ret); /* Sign the CSR */ ret = sscg_generate_serial (tmp_ctx, &serial); CHECK_OK (ret); ret = sscg_sign_x509_csr ( tmp_ctx, csr, serial, 3650, NULL, pkey, EVP_sha512 (), &cert); CHECK_OK (ret); ret = EOK; done: if (ret != EOK) { fprintf (stderr, "FAILURE: %s\n", strerror (ret)); } talloc_free (tmp_ctx); return ret; } sscg-sscg-3.0.2/test/create_csr_test.c000066400000000000000000000047431420717536000177210ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ #include #include #include #include #include #include int main (int argc, char **argv) { int ret, bits; struct sscg_cert_info *certinfo; struct sscg_x509_req *csr = NULL; struct sscg_evp_pkey *pkey = NULL; TALLOC_CTX *tmp_ctx = talloc_new (NULL); if (!tmp_ctx) { return ENOMEM; } certinfo = sscg_cert_info_new (tmp_ctx, EVP_sha256 ()); if (!certinfo) { ret = ENOMEM; goto done; } ret = sscg_generate_serial (tmp_ctx, &certinfo->serial); if (ret != EOK) { printf ("FAILED.\n"); goto done; } /* Create a subject matching the defaults in sscg.c Keep this in sync if defaults change. */ certinfo->country = talloc_strdup (certinfo, "US"); CHECK_MEM (certinfo->country); certinfo->state = talloc_strdup (certinfo, ""); CHECK_MEM (certinfo->state); certinfo->locality = talloc_strdup (certinfo, ""); CHECK_MEM (certinfo->locality); certinfo->org = talloc_strdup (certinfo, "Unspecified"); CHECK_MEM (certinfo->org); certinfo->org_unit = talloc_strdup (certinfo, ""); CHECK_MEM (certinfo->org_unit); certinfo->cn = talloc_strdup (certinfo, "server.example.com"); CHECK_MEM (certinfo->cn); /* TODO: include subject alt names */ /* Generate an RSA keypair */ bits = 4096; ret = sscg_generate_rsa_key (certinfo, bits, &pkey); CHECK_OK (ret); /* Create the CSR */ ret = sscg_x509v3_csr_new (tmp_ctx, certinfo, pkey, &csr); CHECK_OK (ret); ret = sscg_x509v3_csr_finalize (certinfo, pkey, csr); CHECK_OK (ret); /* TODO: compare subject values */ ret = EOK; done: if (ret != EOK) { fprintf (stderr, "FAILURE: %s", strerror (ret)); } talloc_free (tmp_ctx); return ret; } sscg-sscg-3.0.2/test/dhparams_test.c000066400000000000000000000037331420717536000174040ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2019 by Stephen Gallagher */ #include #include #include #include #include #include #include "include/dhparams.h" int main (int argc, char **argv) { int ret, prime_len, generator; EVP_PKEY *params = NULL; EVP_PKEY_CTX *pctx = NULL; TALLOC_CTX *main_ctx = NULL; if (getenv ("SSCG_SKIP_DHPARAMS")) { /* Skip this test */ return 77; } errno = 0; prime_len = strtol (argv[1], NULL, 0); if (errno) { fprintf (stderr, "Prime length was not a valid integer."); ret = errno; goto done; } errno = 0; generator = strtol (argv[2], NULL, 0); if (errno) { fprintf (stderr, "Generator was not a valid integer."); ret = errno; goto done; } main_ctx = talloc_new (NULL); ret = create_dhparams (SSCG_DEBUG, prime_len, generator, ¶ms); if (ret != EOK) { fprintf (stderr, "Could not generate DH parameters: [%s]", ERR_error_string (ERR_get_error (), NULL)); goto done; } pctx = EVP_PKEY_CTX_new (params, NULL); if (!EVP_PKEY_param_check (pctx)) { ERR_print_errors_fp (stderr); ret = EIO; goto done; } ret = EOK; done: talloc_free (main_ctx); return ret; } sscg-sscg-3.0.2/test/generate_rsa_key_test.c000066400000000000000000000033531420717536000211120ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ #include #include #include #include #include "include/bignum.h" #include "include/key.h" int main (int argc, char **argv) { int ret; struct sscg_evp_pkey *pkey; size_t j; int bits[] = { 512, 1024, 2048, 4096, 0 }; TALLOC_CTX *tmp_ctx = talloc_new (NULL); if (!tmp_ctx) { return ENOMEM; } j = 0; while (bits[j] != 0) { printf ("\tGenerating %d-bit key. ", bits[j]); ret = sscg_generate_rsa_key (tmp_ctx, bits[j], &pkey); if (ret != EOK) { printf ("FAILED.\n"); fprintf (stderr, "Error generating key: [%s].\n", strerror (ret)); goto done; } printf ("SUCCESS.\n"); /* Inspect the created key for validity */ if (EVP_PKEY_RSA != EVP_PKEY_base_id (pkey->evp_pkey)) { fprintf (stderr, "Generated key was not an RSA key.\n"); ret = EINVAL; goto done; } j++; } ret = EOK; done: talloc_free (tmp_ctx); return ret; } sscg-sscg-3.0.2/test/generate_serial_test.c000066400000000000000000000030741420717536000207340ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ #include #include #include "include/x509.h" int main (int argc, char **argv) { int ret; unsigned long val; struct sscg_bignum *serial; TALLOC_CTX *tmp_ctx = talloc_new (NULL); if (!tmp_ctx) { return ENOMEM; } printf ("Testing sscg_generate_serial. "); ret = sscg_generate_serial (tmp_ctx, &serial); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); printf ("Verifying serial initialized to nonzero. "); val = BN_get_word (serial->bn); if (val == 0 || val == 0xffffffffL) { /* If val is zero or out of range for unsigned long, generation failed somewhere. */ printf ("FAILED.\n"); ret = EINVAL; goto done; } printf ("SUCCESS. Value is [%lu]\n", val); ret = EOK; done: talloc_free (tmp_ctx); return ret; }sscg-sscg-3.0.2/test/init_bignum_test.c000066400000000000000000000027171420717536000201120ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2017 by Stephen Gallagher */ #include #include #include "include/bignum.h" int main (int argc, char **argv) { int ret; unsigned long val; struct sscg_bignum *bn; TALLOC_CTX *tmp_ctx = talloc_new (NULL); if (!tmp_ctx) { return ENOMEM; } printf ("Testing sscg_init_bignum. "); ret = sscg_init_bignum (tmp_ctx, 0, &bn); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); printf ("Verifying bignum initialized to zero. "); val = BN_get_word (bn->bn); if (val != 0) { /* Bignum should always be initialized to 0 */ printf ("FAILED.\n"); ret = EINVAL; goto done; } printf ("SUCCESS.\n"); ret = EOK; done: talloc_free (tmp_ctx); return ret; }sscg-sscg-3.0.2/test/named_dhparams_test.c000066400000000000000000000074431420717536000205520ustar00rootroot00000000000000/* This file is part of sscg. sscg 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. sscg 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 sscg. If not, see . Copyright 2019 by Stephen Gallagher */ #include #include #include #include #include #include #include "include/sscg.h" #include "include/dhparams.h" static int test_group_name_list (void) { int ret; TALLOC_CTX *tmp_ctx = talloc_new (NULL); char *names = valid_dh_group_names (tmp_ctx); if (!names) { ret = EINVAL; goto done; } #if OPENSSL_VERSION_NUMBER < 0x30000000L if (strcmp (names, "ffdhe2048, ffdhe3072, ffdhe4096, ffdhe6144, ffdhe8192") != 0) { ret = EINVAL; goto done; } #else if (strcmp (names, "ffdhe2048, ffdhe3072, ffdhe4096, ffdhe6144, ffdhe8192, " "modp_2048, modp_3072, modp_4096, modp_6144, modp_8192, " "modp_1536, dh_1024_160, dh_2048_224, dh_2048_256") != 0) { ret = EINVAL; goto done; } #endif ret = EOK; done: talloc_free (tmp_ctx); return ret; } static int test_valid_named_groups (void) { int ret; size_t i = 0; EVP_PKEY *dhparams = NULL; EVP_PKEY_CTX *pctx = NULL; if (getenv ("SSCG_SKIP_DHPARAMS")) { /* Skip this test */ return 77; } while (dh_fips_groups[i]) { printf ("Testing %s\n", dh_fips_groups[i]); ret = get_params_by_named_group (dh_fips_groups[i], &dhparams); if (ret != EOK) { fprintf (stderr, "Could not retrieve named DH parameters."); goto done; } pctx = EVP_PKEY_CTX_new (dhparams, NULL); if (!EVP_PKEY_param_check (pctx)) { ERR_print_errors_fp (stderr); ret = EIO; goto done; } i++; EVP_PKEY_CTX_free (pctx); pctx = NULL; EVP_PKEY_free (dhparams); dhparams = NULL; } ret = EOK; done: EVP_PKEY_free (dhparams); EVP_PKEY_CTX_free (pctx); return ret; } static int test_invalid_named_groups (void) { int ret; EVP_PKEY *dhparams = NULL; TALLOC_CTX *tmp_ctx = NULL; char *name = NULL; if (getenv ("SSCG_SKIP_DHPARAMS")) { /* Skip this test */ return 77; } tmp_ctx = talloc_new (NULL); printf ("Testing empty string\n"); ret = get_params_by_named_group ("", &dhparams); if (ret != EINVAL) { fprintf (stderr, "Received [%s] return code.", strerror (ret)); ret = EINVAL; goto done; } printf ("Testing long, unterminated string\n"); name = talloc_array (tmp_ctx, char, 10 * 1024 * 1024 + 1); memset (name, 'a', 10 * 1024 * 1024); ret = get_params_by_named_group (name, &dhparams); if (ret != EINVAL) { fprintf (stderr, "Received [%s] return code.", strerror (ret)); ret = EINVAL; goto done; } talloc_zfree (name); EVP_PKEY_free (dhparams); dhparams = NULL; ret = EOK; done: EVP_PKEY_free (dhparams); return ret; } int main (int argc, char **argv) { int ret = EOK; ret = test_valid_named_groups (); if (ret != EOK) goto done; ret = test_invalid_named_groups (); if (ret != EOK) goto done; ret = test_group_name_list (); if (ret != EOK) goto done; ret = EOK; done: return ret; }