pax_global_header00006660000000000000000000000064150402441010014501gustar00rootroot0000000000000052 comment=d95bb14960dbcb9913aac7aa65677d0827e37ce7 sscg-sscg-3.0.8/000077500000000000000000000000001504024410100134055ustar00rootroot00000000000000sscg-sscg-3.0.8/.clang-format000066400000000000000000000057111504024410100157640ustar00rootroot00000000000000--- # 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 . # # 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. # # Copyright 2017-2023 by Stephen Gallagher # 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.8/COPYING000066400000000000000000001060121504024410100144400ustar00rootroot00000000000000 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.8/README.md000066400000000000000000000362771504024410100147030ustar00rootroot00000000000000# 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. ## License 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, along with an exception permitting the code to link against the OpenSSL library. ## 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") --no-dhparams-file Do not create the dhparams file --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 ``` ## Development Setup and Contribution Guide ### Building from Source #### Dependencies **Build dependencies:** ```bash # Fedora/RHEL/CentOS dnf install meson ninja-build gcc pkgconf-pkg-config dnf install openssl-devel talloc-devel popt-devel path_utils-devel dnf install gettext-devel help2man clang-format # Debian/Ubuntu apt-get install meson ninja-build gcc pkg-config apt-get install libssl-dev libtalloc-dev libpopt-dev libpath-utils-dev apt-get install gettext help2man clang-format ``` **Runtime dependencies:** - OpenSSL 1.1.0+ (libssl, libcrypto) - talloc - popt - path_utils #### Build Process 1. **Clone the repository:** ```bash git clone https://github.com/sgallagher/sscg.git cd sscg ``` 2. **Configure the build:** ```bash meson setup build ``` 3. **Build the project:** ```bash ninja -C build ``` 4. **Run tests:** ```bash ninja -C build test ``` 5. **Install (optional):** ```bash ninja -C build install ``` #### Development Build Options **Debug build with additional checks:** ```bash meson setup build --buildtype=debug ninja -C build ``` **Release build:** ```bash meson setup build --buildtype=release ninja -C build ``` **Run slow tests (including DH parameter generation):** ```bash meson setup build -Drun_slow_tests=true ninja -C build test ``` ### Development Workflow #### Code Style and Formatting SSCG uses `clang-format` for consistent code formatting: **Auto-format code:** ```bash clang-format -i src/*.c include/*.h test/*.c ``` #### Running Tests **Basic test suite:** ```bash ninja -C build test ``` **Individual tests:** ```bash # Run specific test ./build/create_cert_test ./build/create_ca_test ./build/init_bignum_test ``` **Memory leak detection:** ```bash SSCG_TALLOC_REPORT=true ./build/sscg ``` #### Code Architecture **Key components:** - `src/sscg.c` - Main application entry point - `src/arguments.c` - Command-line argument parsing - `src/authority.c` - Certificate Authority management - `src/cert.c` - Certificate creation and signing - `src/x509.c` - X.509 certificate operations - `src/key.c` - Key generation and management - `src/io_utils.c` - File I/O operations - `src/dhparams.c` - Diffie-Hellman parameter generation **Memory management:** - All dynamic memory uses [talloc](https://talloc.samba.org/talloc/doc/html/index.html) - Use `TALLOC_CTX` for hierarchical cleanup - Follow talloc parent-child relationships - Never use `malloc()`/`free()` directly **Error handling:** - Use `CHECK_OK()` macro for error propagation - Return appropriate errno values - Clean up resources on error paths - Provide meaningful error messages to users ### Contributing #### Before Submitting 1. **Code quality checks:** ```bash ninja -C build test ``` 2. **Test on multiple platforms** if possible (Fedora, Ubuntu, etc.) 3. **Update translations** if you added user-facing strings: ```bash ninja -C build sscg-pot ninja -C build sscg-update-po ``` #### Submitting Changes 1. **Create descriptive commit messages:** ``` Add support for ECDSA key generation - Implement ECDSA key creation in key.c - Add curve selection via --key-curve option - Update tests for ECDSA functionality - Update documentation ``` 2. **Submit pull request** with: - Clear description of changes - Rationale for the change - Test results - Any breaking changes noted #### Bug Reports When reporting bugs, include: - SSCG version (`sscg --version`) - Operating system and version - OpenSSL version - Complete command line used - Expected vs. actual behavior - Any error messages #### Security Issues For security-related issues, please contact the [maintainer](mailto:sgallagh@redhat.com) directly rather than filing a public issue. ### Debugging #### Common Development Tools **GDB debugging:** ```bash gdb --args ./build/sscg --debug ``` **Valgrind for memory checking:** ```bash valgrind --leak-check=full --show-leak-kinds=all ./build/sscg ``` #### Troubleshooting Build Issues **Meson configuration issues:** ```bash # Clean and reconfigure rm -rf build meson setup build ``` **Missing dependencies:** ```bash # Check what's missing meson setup build 2>&1 | grep -i "not found\|missing" ``` **Test failures:** ```bash # Run tests with verbose output meson test -C build -v ``` ## Internationalization (i18n) and Translations SSCG supports internationalization and can display messages in multiple languages. ### For Users To use SSCG in your preferred language, set the `LANG` environment variable: ```bash LANG=es_ES.UTF-8 sscg --help # Spanish LANG=fr_FR.UTF-8 sscg --help # French LANG=de_DE.UTF-8 sscg --help # German ``` If a translation is not available for your language, SSCG will fall back to English. ### For Translators To create or update translations: 1. **Install required tools:** ```bash # Fedora/RHEL/CentOS dnf install gettext-devel meson ninja-build # Debian/Ubuntu apt-get install gettext meson ninja-build ``` 2. **Set up the build environment:** ```bash meson setup build cd build ``` 3. **Generate/update the translation template:** ```bash ninja sscg-pot ``` 4. **Create a new translation (replace `LANG` with your language code):** ```bash msginit -l LANG -i po/sscg.pot -o po/LANG.po ``` 5. **Update an existing translation:** ```bash msgmerge -U po/LANG.po po/sscg.pot ``` 6. **Edit the translation file:** ```bash # Use your preferred editor or a specialized tool like poedit vim po/LANG.po ``` 7. **Test your translation:** ```bash ninja LANG=LANG.UTF-8 ./sscg --help ``` 8. **Submit your translation:** Create a pull request with your `.po` file. ### For Developers When adding new user-facing strings to the code: 1. **Mark strings for translation** by wrapping them with `_()`: ```c fprintf(stderr, _("Error: Could not open file\n")); ``` 2. **Update the translation template** after adding new strings: ```bash ninja sscg-pot ``` 3. **Update existing translations:** ```bash ninja sscg-update-po ``` 4. **Test with different locales** to ensure proper functionality. **Important:** Do not internationalize: - Debug messages (use `fprintf(stderr, "DEBUG: ...")` without `_()`) - Technical error codes or OpenSSL error strings - Test files and test output ### Supported Languages Current translations are maintained in the `po/` directory. To see available languages: ```bash ls po/*.po ``` ### Translation Status To check the completion status of translations: ```bash msgfmt --statistics po/LANG.po ``` sscg-sscg-3.0.8/include/000077500000000000000000000000001504024410100150305ustar00rootroot00000000000000sscg-sscg-3.0.8/include/authority.h000066400000000000000000000035251504024410100172360ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 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.8/include/bignum.h000066400000000000000000000041261504024410100164650ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 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.8/include/cert.h000066400000000000000000000037211504024410100161410ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 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.8/include/dhparams.h000066400000000000000000000041361504024410100170040ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2019-2025 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.8/include/io_utils.h000066400000000000000000000110631504024410100170310ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2019-2025 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.8/include/key.h000066400000000000000000000036351504024410100160000ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 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.8/include/sscg.h000066400000000000000000000304141504024410100161420ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 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 #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; int skip_dhparams; /* 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 /* RFC 1035, section 2.3.4 (Size Limits) */ #define MAX_HOST_LEN 63 #define MAX_FQDN_LEN 255 int sscg_handle_arguments (TALLOC_CTX *mem_ctx, int argc, const char **argv, struct sscg_options **config); #endif /* _SSCG_H */ sscg-sscg-3.0.8/include/x509.h000066400000000000000000000076041504024410100157150ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 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.8/meson.build000066400000000000000000000242011504024410100155460ustar00rootroot00000000000000# SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception # 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 . # # 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. # # Copyright 2019-2025 by Stephen Gallagher project( 'sscg', 'c', version : files('sscg.version'), default_options : ['buildtype=debugoptimized', 'c_std=gnu99', 'warning_level=1', 'b_asneeded=true'], license : 'GPL-3.0-or-later WITH OpenSSL-exception', meson_version : '>=0.59.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 # Import required modules pkg = import('pkgconfig') i18n = import('i18n') # Dependencies gettext = dependency('intl', required: false) 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, gettext, 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, timeout: 120) create_cert_test = executable( 'create_cert_test', 'test/create_cert_test.c', link_with : sscg_lib, dependencies: [ crypto ], install:false, ) test('create_cert_test', create_cert_test, timeout: 300) 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) test_env = environment() test_env.set('LC_ALL', 'C') test_env.set ('MESON_SOURCE_ROOT', meson.current_source_dir()) test_env.set ('MESON_BUILD_ROOT', meson.current_build_dir()) test_cert_validity = find_program( 'test/test_cert_validity.sh', required: true, ) hash_algs = [ 'sha256', 'sha384', 'sha512', ] bad_algs = [ 'md2', 'nonexistent', ] cipher_algs = [ 'des-ede3-cbc', 'aes-256-cbc', ] key_strengths = [ 2048, 4096, ] if get_option('run_slow_tests') key_strengths = key_strengths + [ 7680, 8192, 15360 ] endif bad_strengths = [ 512, 1024, ] foreach hash_alg : hash_algs foreach cipher_alg : cipher_algs foreach key_strength : key_strengths test( 'test_cert_validity_' + hash_alg + '_' + cipher_alg + '_' + key_strength.to_string(), test_cert_validity, args: [ '--hash-alg', hash_alg, '--cipher-alg', cipher_alg, '--key-strength', key_strength.to_string(), ], env: test_env, depends: sscg, timeout: key_strength / 32, ) endforeach endforeach endforeach foreach hash_alg : bad_algs foreach cipher_alg : cipher_algs foreach key_strength : key_strengths test( 'test_cert_invalidity_bad_alg_' + hash_alg + '_' + cipher_alg + '_' + key_strength.to_string(), test_cert_validity, args: [ '--hash-alg', hash_alg, '--cipher-alg', cipher_alg, '--key-strength', key_strength.to_string(), ], env: test_env, depends: sscg, timeout: key_strength / 32, should_fail: true, ) endforeach endforeach endforeach foreach hash_alg : hash_algs foreach cipher_alg : cipher_algs foreach key_strength : bad_strengths test( 'test_cert_invalidity_bad_strength_' + hash_alg + '_' + cipher_alg + '_' + key_strength.to_string(), test_cert_validity, args: [ '--hash-alg', hash_alg, '--cipher-alg', cipher_alg, '--key-strength', key_strength.to_string(), ], env: test_env, depends: sscg, timeout: key_strength / 32, should_fail: true, ) endforeach endforeach endforeach cdata = configuration_data() cdata.set_quoted('PACKAGE_VERSION', meson.project_version()) cdata.set_quoted('PACKAGE_NAME', meson.project_name()) cdata.set_quoted('LOCALEDIR', join_paths(get_option('prefix'), get_option('datadir'), 'locale')) cdata.set('HAVE_SSL_EVP_RSA_GEN', has_evp_rsa_gen) cdata.set('HAVE_OSSL_PARAM', has_ossl_param) cdata.set('HAVE_GETTEXT', gettext.found()) 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'), ) # Internationalization support if gettext.found() subdir('po') endif sscg-sscg-3.0.8/meson_options.txt000066400000000000000000000021441504024410100170430ustar00rootroot00000000000000# SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception # 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-2025 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.8/packaging/000077500000000000000000000000001504024410100153315ustar00rootroot00000000000000sscg-sscg-3.0.8/packaging/debian/000077500000000000000000000000001504024410100165535ustar00rootroot00000000000000sscg-sscg-3.0.8/packaging/debian/changelog000066400000000000000000000002271504024410100204260ustar00rootroot00000000000000sscg (0-1) unstable; urgency=low * Initial release. (Closes: #986830) -- Stephen Gallagher Wed, 07 Apr 2021 09:39:20 +0200 sscg-sscg-3.0.8/packaging/debian/control000066400000000000000000000017511504024410100201620ustar00rootroot00000000000000Source: 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.1 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.8/packaging/debian/copyright000066400000000000000000000025401504024410100205070ustar00rootroot00000000000000Format: 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 - 2023 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. sscg-sscg-3.0.8/packaging/debian/rules000077500000000000000000000003301504024410100176270ustar00rootroot00000000000000#!/usr/bin/make -f ifeq ($(CC),clang) export DEB_BUILD_MAINT_OPTIONS=hardening=+all optimize=-lto export DEB_CFLAGS_MAINT_APPEND=-gdwarf-4 else export DEB_BUILD_MAINT_OPTIONS=hardening=+all endif %: dh "$@" sscg-sscg-3.0.8/packaging/debian/source/000077500000000000000000000000001504024410100200535ustar00rootroot00000000000000sscg-sscg-3.0.8/packaging/debian/source/format000066400000000000000000000000141504024410100212610ustar00rootroot000000000000003.0 (quilt) sscg-sscg-3.0.8/packaging/debian/watch000066400000000000000000000001251504024410100176020ustar00rootroot00000000000000version=4 https://github.com/sgallagher/sscg/releases/ .*/sscg-([\d\.]+)\.tar\.[gx]z sscg-sscg-3.0.8/po/000077500000000000000000000000001504024410100140235ustar00rootroot00000000000000sscg-sscg-3.0.8/po/LINGUAS000066400000000000000000000001721504024410100150500ustar00rootroot00000000000000# List of available translations # Add language codes here as translations become available # For example: # es # fr # de sscg-sscg-3.0.8/po/POTFILES.in000066400000000000000000000001741504024410100156020ustar00rootroot00000000000000# List of source files containing translatable strings src/arguments.c src/authority.c src/io_utils.c src/sscg.c src/x509.c sscg-sscg-3.0.8/po/meson.build000066400000000000000000000033131504024410100161650ustar00rootroot00000000000000# SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception # 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 . # # 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. # # Copyright 2025 by Stephen Gallagher # i18n.gettext() handles the setup of .pot/.po/.mo files # and installation of translated message catalogs i18n.gettext( 'sscg', preset: 'glib', args: [ '--keyword=_', '--keyword=N_', '--from-code=UTF-8', ] ) sscg-sscg-3.0.8/po/sscg.pot000066400000000000000000000234221504024410100155110ustar00rootroot00000000000000# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the sscg package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: sscg\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-07-18 15:33-0400\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: 8bit\n" #: src/arguments.c:121 #, c-format msgid "Unknown system security level %d. Defaulting to highest-known level.\n" msgstr "" #: src/arguments.c:174 #, c-format msgid "%d or larger" msgstr "" #: src/arguments.c:178 #, c-format msgid "" "Output well-known DH parameters. The available named groups are: %s. " "(Default: \"ffdhe4096\")" msgstr "" #: src/arguments.c:193 msgid "Display no output unless there is an error." msgstr "" #: src/arguments.c:203 msgid "Display progress messages." msgstr "" #: src/arguments.c:213 msgid "" "Enable logging of debug messages. Implies verbose. Warning! This will print " "private key information to the screen!" msgstr "" #: src/arguments.c:224 msgid "Display the version number and exit." msgstr "" #: src/arguments.c:234 msgid "Overwrite any pre-existing files in the requested locations" msgstr "" #: src/arguments.c:244 msgid "Certificate lifetime (days)." msgstr "" #: src/arguments.c:245 msgid "1-3650" msgstr "" #: src/arguments.c:254 msgid "Certificate DN: Country (C). (default: \"US\")" msgstr "" #: src/arguments.c:255 msgid "US, CZ, etc." msgstr "" #: src/arguments.c:264 msgid "Certificate DN: State or Province (ST)." msgstr "" #: src/arguments.c:265 msgid "Massachusetts, British Columbia, etc." msgstr "" #: src/arguments.c:274 msgid "Certificate DN: Locality (L)." msgstr "" #: src/arguments.c:275 msgid "Westford, Paris, etc." msgstr "" #: src/arguments.c:284 msgid "Certificate DN: Organization (O). (default: \"Unspecified\")" msgstr "" #: src/arguments.c:285 msgid "My Company" msgstr "" #: src/arguments.c:294 msgid "Certificate DN: Organizational Unit (OU)." msgstr "" #: src/arguments.c:295 msgid "Engineering, etc." msgstr "" #: src/arguments.c:304 msgid "Certificate DN: Email Address (Email)." msgstr "" #: src/arguments.c:305 msgid "myname@example.com" msgstr "" #: src/arguments.c:314 msgid "" "The valid hostname of the certificate. Must be an FQDN. (default: current " "system FQDN)" msgstr "" #: src/arguments.c:316 msgid "server.example.com" msgstr "" #: src/arguments.c:325 msgid "" "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." msgstr "" #: src/arguments.c:330 msgid "alt.example.com" msgstr "" #: src/arguments.c:339 msgid "Unused. Retained for compatibility with earlier versions of sscg." msgstr "" #: src/arguments.c:349 msgid "Strength of the certificate private keys in bits." msgstr "" #: src/arguments.c:357 msgid "Hashing algorithm to use for signing." msgstr "" #: src/arguments.c:358 msgid "{sha256,sha384,sha512}" msgstr "" #: src/arguments.c:367 msgid "Cipher to use for encrypting key files." msgstr "" #: src/arguments.c:368 msgid "{des-ede3-cbc,aes-256-cbc}" msgstr "" #: src/arguments.c:377 msgid "" "Path where the public CA certificate will be stored. (default: \"./ca.crt\")" msgstr "" #: src/arguments.c:388 msgid "File mode of the created CA certificate." msgstr "" #: src/arguments.c:398 msgid "" "Path where the CA's private key will be stored. If unspecified, the key will " "be destroyed rather than written to the disk." msgstr "" #: src/arguments.c:409 msgid "File mode of the created CA key." msgstr "" #: src/arguments.c:419 msgid "" "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." msgstr "" #: src/arguments.c:432 msgid "A file containing the password to encrypt the CA key file." msgstr "" #: src/arguments.c:442 msgid "Prompt to enter a password for the CA key file." msgstr "" #: src/arguments.c:452 msgid "" "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." msgstr "" #: src/arguments.c:464 msgid "File mode of the created Certificate Revocation List." msgstr "" #: src/arguments.c:474 msgid "" "Path where the public service certificate will be stored. (default \"./" "service.pem\")" msgstr "" #: src/arguments.c:485 src/arguments.c:558 msgid "File mode of the created certificate." msgstr "" #: src/arguments.c:495 msgid "" "Path where the service's private key will be stored. (default \"service-" "key.pem\")" msgstr "" #: src/arguments.c:506 src/arguments.c:579 msgid "File mode of the created certificate key." msgstr "" #: src/arguments.c:516 msgid "" "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." msgstr "" #: src/arguments.c:529 msgid "A file containing the password to encrypt the service key file." msgstr "" #: src/arguments.c:539 msgid "Prompt to enter a password for the service key file." msgstr "" #: src/arguments.c:549 msgid "Path where a client authentication certificate will be stored." msgstr "" #: src/arguments.c:568 msgid "" "Path where the client's private key will be stored. (default is the client-" "file)" msgstr "" #: src/arguments.c:589 msgid "" "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." msgstr "" #: src/arguments.c:602 msgid "A file containing the password to encrypt the client key file." msgstr "" #: src/arguments.c:612 msgid "Prompt to enter a password for the client key file." msgstr "" #: src/arguments.c:622 msgid "" "A file to contain a set of Diffie-Hellman parameters. (Default: \"./" "dhparams.pem\")" msgstr "" #: src/arguments.c:633 msgid "Do not create the dhparams file" msgstr "" #: src/arguments.c:653 msgid "" "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." msgstr "" #: src/arguments.c:665 msgid "The generator value for dhparams." msgstr "" #: src/arguments.c:666 msgid "{2,3,5}" msgstr "" #: src/arguments.c:680 #, c-format msgid "" "\n" "Invalid option %s: %s\n" "\n" msgstr "" #: src/arguments.c:704 #, c-format msgid "Country codes must be exactly two letters.\n" msgstr "" #: src/arguments.c:795 #, c-format msgid "FQDNs may not exceed %d characters\n" msgstr "" #: src/arguments.c:803 #, c-format msgid "Hostnames may not exceed %d characters in Subject Alternative Names\n" msgstr "" #: src/arguments.c:846 #, c-format msgid "Key strength must be at least %d bits.\n" msgstr "" #: src/arguments.c:857 #, c-format msgid "Invalid cipher specified: %s\n" msgstr "" #: src/arguments.c:868 #, c-format msgid "Unknown Diffie Hellman finite field group.\n" msgstr "" #: src/arguments.c:870 #, c-format msgid "Valid groups are: %s.\n" msgstr "" #: src/arguments.c:877 #, c-format msgid "Unsupported hashing algorithm." msgstr "" #: src/arguments.c:902 #, c-format msgid "==== Options ====\n" msgstr "" #: src/arguments.c:903 #, c-format msgid "Certificate lifetime: %d\n" msgstr "" #: src/arguments.c:904 #, c-format msgid "Country: \"%s\"\n" msgstr "" #: src/arguments.c:905 #, c-format msgid "State or Principality: \"%s\"\n" msgstr "" #: src/arguments.c:906 #, c-format msgid "Locality: \"%s\"\n" msgstr "" #: src/arguments.c:907 #, c-format msgid "Organization: \"%s\"\n" msgstr "" #: src/arguments.c:908 #, c-format msgid "Organizational Unit: \"%s\"\n" msgstr "" #: src/arguments.c:909 #, c-format msgid "Email Address: \"%s\"\n" msgstr "" #: src/arguments.c:910 #, c-format msgid "Hostname: \"%s\"\n" msgstr "" #: src/arguments.c:916 #, c-format msgid "Subject Alternative Name: \"%s\"\n" msgstr "" #: src/arguments.c:920 #, c-format msgid "=================\n" msgstr "" #: src/authority.c:170 #, c-format msgid "Invalid name constraint: %s\n" msgstr "" #: src/authority.c:183 #, c-format msgid "Generating RSA key for private CA.\n" msgstr "" #: src/authority.c:192 #, c-format msgid "Generating CSR for private CA.\n" msgstr "" #: src/authority.c:210 #, c-format msgid "Error occurred in X509V3_EXT_conf_nid(SubjectKeyIdentifier): [%s].\n" msgstr "" #: src/authority.c:233 #, c-format msgid "Signing CSR for private CA.\n" msgstr "" #: src/io_utils.c:240 #, c-format msgid "Can't open file %s\n" msgstr "" #: src/io_utils.c:258 #, c-format msgid "Error reading password from BIO\n" msgstr "" #: src/io_utils.c:388 #, c-format msgid "Failed to read passphrase from %s" msgstr "" #: src/sscg.c:145 #, c-format msgid "Could not allocate memory." msgstr "" #: src/sscg.c:347 #, c-format msgid "Could not write to %s: " msgstr "" #: src/x509.c:303 #, c-format msgid "FQDNs may not exceed %d characters in Subject Alternative Names\n" msgstr "" #: src/x509.c:322 #, c-format msgid "Invalid subjectAlternativeName: %s\n" msgstr "" #: src/x509.c:357 #, c-format msgid "Error occurred in X509_REQ_sign: [%s].\n" msgstr "" #: src/x509.c:489 #, c-format msgid "Error occurred in X509V3_EXT_conf_nid(AuthorityKeyIdentifier): [%s].\n" msgstr "" #: src/x509.c:507 #, c-format msgid "Error occurred in X509_sign: [%s].\n" msgstr "" sscg-sscg-3.0.8/src/000077500000000000000000000000001504024410100141745ustar00rootroot00000000000000sscg-sscg-3.0.8/src/arguments.c000066400000000000000000000544071504024410100163570ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2021-2025 by Stephen Gallagher */ #include #include #include #include #include #include #include "include/sscg.h" #include "include/dhparams.h" #include "config.h" #ifdef HAVE_GETTEXT #include #endif #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_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 " "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 }, { "no-dhparams-file", '\0', POPT_ARG_NONE, &options->skip_dhparams, 0, _ ("Do not create the dhparams file"), 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, MAX_FQDN_LEN + 1) > MAX_FQDN_LEN) { fprintf ( stderr, _ ("FQDNs may not exceed %d characters\n"), MAX_FQDN_LEN); ret = EINVAL; goto done; } if ((strchr (options->hostname, '.') - options->hostname) > MAX_HOST_LEN + 4) { fprintf (stderr, _ ("Hostnames may not exceed %d characters in Subject " "Alternative Names\n"), MAX_HOST_LEN); 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. */ size_t i = 0; if (alternative_names) { while (alternative_names[i] != NULL) { options->subject_alt_names = talloc_realloc ( options, options->subject_alt_names, char *, i + 1); 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]); i++; } } /* The hostname must always be listed in SubjectAlternativeNames as well. Note that the realloc also adds an extra entry for the NULL terminator */ 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, options->hostname); CHECK_MEM (options->subject_alt_names[i]); /* Add a NULL terminator to the end */ options->subject_alt_names[i + 1] = NULL; 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; } options->hash_fn = EVP_get_digestbyname (options->hash_alg); if (!options->hash_fn || EVP_MD_is_a (options->hash_fn, options->hash_alg) != 1) { /* This check ensures that the passed hash algorithm is both a real * algorithm and that it is permitted by the current system policy. */ fprintf (stderr, _ ("Unsupported hashing algorithm.")); ret = EINVAL; goto done; } 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.8/src/authority.c000066400000000000000000000257511504024410100164020ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 by Stephen Gallagher */ #include #include "config.h" #ifdef HAVE_GETTEXT #include #endif #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; char *dot; 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); /* Truncate the CN at the first dot */ if ((dot = strchr (ca_certinfo->cn, '.'))) *dot = '\0'; if (options->subject_alt_names) { for (i = 0; options->subject_alt_names[i]; i++) { ca_certinfo->subject_alt_names = talloc_realloc ( ca_certinfo, ca_certinfo->subject_alt_names, char *, i + 2); CHECK_MEM (ca_certinfo->subject_alt_names); ca_certinfo->subject_alt_names[i] = talloc_strdup ( ca_certinfo->subject_alt_names, options->subject_alt_names[i]); CHECK_MEM (ca_certinfo->subject_alt_names[i]); /* Add a NULL terminator to the end */ ca_certinfo->subject_alt_names[i + 1] = NULL; } } /* 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, "critical,CA:TRUE"); CHECK_MEM (ex); sk_X509_EXTENSION_push (ca_certinfo->extensions, ex); /* Restrict signing to the CN and subjectAltNames of the service certificate */ name_constraint = talloc_asprintf (tmp_ctx, "permitted;DNS:%s", ca_certinfo->cn); 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 if (strncmp (options->subject_alt_names[i], "IP:", 3) == 0) { char *ip_addr = options->subject_alt_names[i] + 3; char *slash = strchr (ip_addr, '/'); char *clean_ip = ip_addr; const char *netmask_str = NULL; if (slash) { /* Extract IP and netmask parts */ clean_ip = talloc_strndup (tmp_ctx, ip_addr, slash - ip_addr); char *cidr_str = slash + 1; int cidr_bits = atoi (cidr_str); /* Convert CIDR to appropriate netmask format */ if (strchr (clean_ip, ':')) { /* IPv6 - convert CIDR to hex netmask */ if (cidr_bits == 128) { netmask_str = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"; } else if (cidr_bits == 64) { netmask_str = "FFFF:FFFF:FFFF:FFFF:0:0:0:0"; } else { /* For other values, default to /128 */ netmask_str = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"; } } else { /* IPv4 - convert CIDR to dotted decimal */ if (cidr_bits == 32) { netmask_str = "255.255.255.255"; } else if (cidr_bits == 24) { netmask_str = "255.255.255.0"; } else if (cidr_bits == 16) { netmask_str = "255.255.0.0"; } else if (cidr_bits == 8) { netmask_str = "255.0.0.0"; } else { /* For other values, default to /32 */ netmask_str = "255.255.255.255"; } } } else { /* No netmask provided - add single host netmask */ if (strchr (clean_ip, ':')) { /* IPv6 - use /128 netmask */ netmask_str = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"; } else { /* IPv4 - use /32 netmask */ netmask_str = "255.255.255.255"; } } san = talloc_asprintf (tmp_ctx, "IP:%s/%s", clean_ip, netmask_str); if (slash && clean_ip != ip_addr) { talloc_free (clean_ip); } } 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")); } 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 /tmp/debug-ca.csr\n"); BIO *ca_csr_out = BIO_new_file ("/tmp/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.8/src/bignum.c000066400000000000000000000051031504024410100156200ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 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.8/src/cert.c000066400000000000000000000147621504024410100153070ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 by Stephen Gallagher */ #include #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; char *dot; 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); /* Truncate the CN at the first dot */ if ((dot = strchr (certinfo->cn, '.'))) *dot = '\0'; 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"); } 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 ? "/tmp/debug-service.csr" : "/tmp/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.8/src/dhparams.c000066400000000000000000000214031504024410100161370ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2019-2025 by Stephen Gallagher */ #include #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; TALLOC_CTX *tmp_ctx = talloc_new (NULL); char *names = NULL; bool first = true; i = 0; while (dh_fips_groups[i]) { if (first) { names = talloc_strdup (tmp_ctx, dh_fips_groups[i]); first = false; } else { names = talloc_asprintf_append (names, ", %s", dh_fips_groups[i]); } if (!names) goto done; i++; } i = 0; while (dh_nonfips_groups[i]) { if (first) { /* This should never be reached, since dh_fips_groups should always * have at least one entry, but for safety we will include it. */ names = talloc_strdup (tmp_ctx, dh_nonfips_groups[i]); first = false; } else { names = talloc_asprintf_append (names, ", %s", dh_nonfips_groups[i]); } if (!names) goto done; i++; } 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.8/src/io_utils.c000066400000000000000000000414451504024410100161770ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2019-2025 by Stephen Gallagher */ #include #include #include #include #include #include "config.h" #ifdef HAVE_GETTEXT #include #endif #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; if (filetype < 0 || filetype > SSCG_NUM_FILE_TYPES) { SSCG_LOG (SSCG_DEFAULT, "Unknown filetype for stream"); return 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 (filetype < 0 || filetype > SSCG_NUM_FILE_TYPES) { SSCG_ERROR ("Unknown filetype for stream"); return EINVAL; } /* 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 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); if (!stream->bio) { /* The dhparams file is special, it will be handled later */ if (stream->filetypes == 1 << SSCG_FILE_TYPE_DHPARAMS) { continue; } } 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++) { if (!stream->bio) { /* This filetype exists but was not opened successfully * (It's probably dhparams) */ continue; } /* 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.8/src/key.c000066400000000000000000000064301504024410100151330ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 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.8/src/sscg.c000066400000000000000000000253401504024410100153030ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 by Stephen Gallagher */ #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include "config.h" #ifdef HAVE_GETTEXT #include #endif #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; char *dhparams_file = NULL; 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); #ifdef HAVE_GETTEXT /* Initialize internationalization */ setlocale (LC_ALL, ""); bindtextdomain (PACKAGE_NAME, LOCALEDIR); textdomain (PACKAGE_NAME); #endif 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); if (!options->skip_dhparams) { if (options->dhparams_file) { dhparams_file = talloc_strdup (main_ctx, options->dhparams_file); } else { dhparams_file = talloc_strdup (main_ctx, "./dhparams.pem"); } CHECK_MEM (dhparams_file); ret = sscg_io_utils_add_output_file (options->streams, SSCG_FILE_TYPE_DHPARAMS, 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 */ if ((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); } else if (options->dhparams_file) { /* A filename was explicitly passed, but it couldn't be created */ ret = EPERM; fprintf (stderr, _ ("Could not write to %s: "), options->dhparams_file); goto done; } /* 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.8/src/x509.c000066400000000000000000000356431504024410100150600ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 by Stephen Gallagher */ #include #include #include #include #include "config.h" #ifdef HAVE_GETTEXT #include #endif #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; char *slash = 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); /* All CSRs are v1 */ sslret = X509_REQ_set_version (csr->x509_req, 0); 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]); /* SAN IP addresses cannot include the subnet mask */ /* Only strip slashes from IP addresses, not from URIs or other types */ if (strncmp (san, "IP:", 3) == 0 && (slash = strchr (san, '/'))) { /* Truncate at the slash */ *slash = '\0'; } } CHECK_MEM (san); if (strnlen (san, MAX_FQDN_LEN + 5) > MAX_FQDN_LEN + 4) { fprintf (stderr, _ ("FQDNs may not exceed %d characters in Subject " "Alternative Names\n"), MAX_FQDN_LEN); 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); if (!ex) { ret = EINVAL; fprintf (stderr, _ ("Invalid subjectAlternativeName: %s\n"), alt_name); goto done; } 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.8/sscg.version000066400000000000000000000000051504024410100157460ustar00rootroot000000000000003.0.8sscg-sscg-3.0.8/test/000077500000000000000000000000001504024410100143645ustar00rootroot00000000000000sscg-sscg-3.0.8/test/create_ca_test.c000066400000000000000000001130051504024410100174750ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 by Stephen Gallagher */ #include #include #include #include #include #include #include #include "include/sscg.h" #include "include/x509.h" #include "include/authority.h" static int verify_subject_alt_names (struct sscg_x509_cert *cert) { X509 *x509 = cert->certificate; STACK_OF (GENERAL_NAME) *san_names = NULL; GENERAL_NAME *name = NULL; ASN1_STRING *san_str = NULL; int san_count = 0; int found_primary_cn = 0; int found_alt1 = 0; int found_alt2 = 0; int found_ip4_1 = 0; int found_ip4_2 = 0; int found_ip6 = 0; int found_ip4_netmask = 0; int found_ip6_netmask = 0; int found_email = 0; int found_uri = 0; int found_wildcard = 0; int found_subdomain = 0; int found_international = 0; char *name_str = NULL; /* Get the Subject Alternative Name extension */ san_names = X509_get_ext_d2i (x509, NID_subject_alt_name, NULL, NULL); if (!san_names) { printf ("Certificate missing Subject Alternative Name extension.\n"); return EINVAL; } san_count = sk_GENERAL_NAME_num (san_names); printf ("\n Processing %d Subject Alternative Names:\n", san_count); /* Check each SAN entry */ for (int i = 0; i < san_count; i++) { name = sk_GENERAL_NAME_value (san_names, i); switch (name->type) { case GEN_DNS: san_str = name->d.dNSName; name_str = (char *)ASN1_STRING_get0_data (san_str); printf (" DNS: %s\n", name_str); if (strcmp (name_str, "server.example.com") == 0) found_primary_cn = 1; else if (strcmp (name_str, "alt1.example.com") == 0) found_alt1 = 1; else if (strcmp (name_str, "alt2.example.com") == 0) found_alt2 = 1; else if (strcmp (name_str, "*.wildcard.example.com") == 0) found_wildcard = 1; else if (strcmp (name_str, "subdomain.alt1.example.com") == 0) found_subdomain = 1; else if (strcmp (name_str, "xn--nxasmq6b.example.com") == 0) found_international = 1; break; case GEN_IPADD: san_str = name->d.iPAddress; /* IP addresses are stored as binary data */ if (ASN1_STRING_length (san_str) == 4) /* IPv4 */ { const unsigned char *ip_data = ASN1_STRING_get0_data (san_str); printf (" IP (IPv4): %d.%d.%d.%d\n", ip_data[0], ip_data[1], ip_data[2], ip_data[3]); if (ip_data[0] == 192 && ip_data[1] == 168 && ip_data[2] == 1 && ip_data[3] == 100) found_ip4_1 = 1; else if (ip_data[0] == 10 && ip_data[1] == 0 && ip_data[2] == 0 && ip_data[3] == 1) found_ip4_2 = 1; else if (ip_data[0] == 203 && ip_data[1] == 0 && ip_data[2] == 113 && ip_data[3] == 0) found_ip4_netmask = 1; } else if (ASN1_STRING_length (san_str) == 16) /* IPv6 */ { const unsigned char *ip_data = ASN1_STRING_get0_data (san_str); printf (" IP (IPv6): "); for (int j = 0; j < 16; j += 2) { printf ("%02x%02x", ip_data[j], ip_data[j + 1]); if (j < 14) printf (":"); } printf ("\n"); /* Check for 2001:db8::1 */ if (ip_data[0] == 0x20 && ip_data[1] == 0x01 && ip_data[2] == 0x0d && ip_data[3] == 0xb8 && ip_data[4] == 0x00 && ip_data[5] == 0x00 && ip_data[6] == 0x00 && ip_data[7] == 0x00 && ip_data[8] == 0x00 && ip_data[9] == 0x00 && ip_data[10] == 0x00 && ip_data[11] == 0x00 && ip_data[12] == 0x00 && ip_data[13] == 0x00 && ip_data[14] == 0x00 && ip_data[15] == 0x01) found_ip6 = 1; /* Check for 2001:db8:85a3:: (netmask stripped) */ else if (ip_data[0] == 0x20 && ip_data[1] == 0x01 && ip_data[2] == 0x0d && ip_data[3] == 0xb8 && ip_data[4] == 0x85 && ip_data[5] == 0xa3 && ip_data[6] == 0x00 && ip_data[7] == 0x00 && ip_data[8] == 0x00 && ip_data[9] == 0x00 && ip_data[10] == 0x00 && ip_data[11] == 0x00 && ip_data[12] == 0x00 && ip_data[13] == 0x00 && ip_data[14] == 0x00 && ip_data[15] == 0x00) found_ip6_netmask = 1; } break; case GEN_EMAIL: san_str = name->d.rfc822Name; name_str = (char *)ASN1_STRING_get0_data (san_str); printf (" Email: %s\n", name_str); if (strcmp (name_str, "admin@example.com") == 0) found_email = 1; break; case GEN_URI: san_str = name->d.uniformResourceIdentifier; name_str = (char *)ASN1_STRING_get0_data (san_str); printf (" URI: %s\n", name_str); if (strcmp (name_str, "https://www.example.com/service") == 0) found_uri = 1; break; default: printf (" Other type: %d\n", name->type); break; } } GENERAL_NAMES_free (san_names); /* Verify all expected SANs were found */ int missing_count = 0; if (!found_primary_cn) { printf ( " MISSING: Primary CN not found in Subject Alternative Names.\n"); missing_count++; } if (!found_alt1) { printf ( " MISSING: alt1.example.com not found in Subject Alternative " "Names.\n"); missing_count++; } if (!found_alt2) { printf ( " MISSING: alt2.example.com not found in Subject Alternative " "Names.\n"); missing_count++; } if (!found_ip4_1) { printf ( " MISSING: IPv4 192.168.1.100 not found in Subject Alternative " "Names.\n"); missing_count++; } if (!found_ip4_2) { printf ( " MISSING: IPv4 10.0.0.1 not found in Subject Alternative " "Names.\n"); missing_count++; } if (!found_ip6) { printf ( " MISSING: IPv6 2001:db8::1 not found in Subject Alternative " "Names.\n"); missing_count++; } if (!found_ip4_netmask) { printf ( " MISSING: IPv4 203.0.113.0 (from 203.0.113.0/24, netmask " "stripped) not found in Subject Alternative Names.\n"); missing_count++; } if (!found_ip6_netmask) { printf ( " MISSING: IPv6 2001:db8:85a3:: (from 2001:db8:85a3::/64, netmask " "stripped) not found in Subject Alternative Names.\n"); missing_count++; } if (!found_email) { printf ( " MISSING: Email admin@example.com not found in Subject " "Alternative Names.\n"); missing_count++; } if (!found_uri) { printf ( " MISSING: URI https://www.example.com/service not found in " "Subject Alternative Names.\n"); missing_count++; } if (!found_wildcard) { printf ( " MISSING: Wildcard *.wildcard.example.com not found in Subject " "Alternative Names.\n"); missing_count++; } if (!found_subdomain) { printf ( " MISSING: Subdomain subdomain.alt1.example.com not found in " "Subject Alternative Names.\n"); missing_count++; } if (!found_international) { printf ( " MISSING: International domain xn--nxasmq6b.example.com not found " "in Subject Alternative Names.\n"); missing_count++; } if (missing_count > 0) { printf (" %d expected SAN entries were missing.\n", missing_count); return EINVAL; } printf (" All expected SAN entries found successfully.\n"); return EOK; } static int test_san_edge_cases (struct sscg_x509_cert *cert) { X509 *x509 = cert->certificate; STACK_OF (GENERAL_NAME) *san_names = NULL; GENERAL_NAME *name = NULL; ASN1_STRING *san_str = NULL; int san_count = 0; int dns_count = 0; int ip_count = 0; int email_count = 0; int uri_count = 0; char *name_str = NULL; /* Get the Subject Alternative Name extension */ san_names = X509_get_ext_d2i (x509, NID_subject_alt_name, NULL, NULL); if (!san_names) { printf ("Certificate missing Subject Alternative Name extension.\n"); return EINVAL; } san_count = sk_GENERAL_NAME_num (san_names); printf ("\n Performing comprehensive SAN validation:\n"); /* Count and validate all SAN types */ for (int i = 0; i < san_count; i++) { name = sk_GENERAL_NAME_value (san_names, i); switch (name->type) { case GEN_DNS: dns_count++; san_str = name->d.dNSName; name_str = (char *)ASN1_STRING_get0_data (san_str); /* Validate DNS name format */ if (strlen (name_str) == 0) { printf (" ERROR: Empty DNS name found in SANs.\n"); GENERAL_NAMES_free (san_names); return EINVAL; } /* Allow wildcards and validate domain format */ if (name_str[0] != '*' && !strchr (name_str, '.')) { printf (" ERROR: DNS name '%s' missing domain part.\n", name_str); GENERAL_NAMES_free (san_names); return EINVAL; } /* Validate wildcard format */ if (name_str[0] == '*' && name_str[1] != '.') { printf (" ERROR: Invalid wildcard DNS name '%s'.\n", name_str); GENERAL_NAMES_free (san_names); return EINVAL; } break; case GEN_IPADD: ip_count++; san_str = name->d.iPAddress; /* Validate IP address length */ int ip_len = ASN1_STRING_length (san_str); if (ip_len != 4 && ip_len != 16) /* IPv4 or IPv6 */ { printf (" ERROR: Invalid IP address length: %d bytes.\n", ip_len); GENERAL_NAMES_free (san_names); return EINVAL; } break; case GEN_EMAIL: email_count++; san_str = name->d.rfc822Name; name_str = (char *)ASN1_STRING_get0_data (san_str); /* Validate email format */ if (!strchr (name_str, '@')) { printf (" ERROR: Invalid email address '%s' - missing @.\n", name_str); GENERAL_NAMES_free (san_names); return EINVAL; } break; case GEN_URI: uri_count++; san_str = name->d.uniformResourceIdentifier; name_str = (char *)ASN1_STRING_get0_data (san_str); /* Validate URI format - must have scheme */ if (!strstr (name_str, "://")) { printf (" ERROR: Invalid URI '%s' - missing scheme.\n", name_str); GENERAL_NAMES_free (san_names); return EINVAL; } break; default: /* Other SAN types are acceptable but not validated here */ break; } } printf (" Found %d total SANs: %d DNS, %d IP, %d Email, %d URI.\n", san_count, dns_count, ip_count, email_count, uri_count); /* Validate expected counts for comprehensive test */ int expected_dns = 6; /* CN + alt1 + alt2 + wildcard + subdomain + international */ int expected_ip = 5; /* IPv4 x2 + IPv6 x1 + IPv4 netmask + IPv6 netmask */ int expected_email = 1; int expected_uri = 1; if (dns_count < expected_dns) { printf (" ERROR: Expected at least %d DNS names, found %d.\n", expected_dns, dns_count); GENERAL_NAMES_free (san_names); return EINVAL; } if (ip_count < expected_ip) { printf (" ERROR: Expected at least %d IP addresses, found %d.\n", expected_ip, ip_count); GENERAL_NAMES_free (san_names); return EINVAL; } if (email_count < expected_email) { printf (" ERROR: Expected at least %d email addresses, found %d.\n", expected_email, email_count); GENERAL_NAMES_free (san_names); return EINVAL; } if (uri_count < expected_uri) { printf (" ERROR: Expected at least %d URIs, found %d.\n", expected_uri, uri_count); GENERAL_NAMES_free (san_names); return EINVAL; } printf (" All SAN format validations passed successfully.\n"); GENERAL_NAMES_free (san_names); return EOK; } static int test_ip_netmask_handling (struct sscg_x509_cert *cert) { X509 *x509 = cert->certificate; STACK_OF (GENERAL_NAME) *san_names = NULL; GENERAL_NAME *name = NULL; ASN1_STRING *san_str = NULL; int san_count = 0; int found_netmask_ipv4 = 0; int found_netmask_ipv6 = 0; /* Get the Subject Alternative Name extension */ san_names = X509_get_ext_d2i (x509, NID_subject_alt_name, NULL, NULL); if (!san_names) { printf ("Certificate missing Subject Alternative Name extension.\n"); return EINVAL; } san_count = sk_GENERAL_NAME_num (san_names); printf ("\n Testing IP address netmask stripping:\n"); /* Look specifically for IP addresses that had netmasks stripped */ for (int i = 0; i < san_count; i++) { name = sk_GENERAL_NAME_value (san_names, i); if (name->type == GEN_IPADD) { san_str = name->d.iPAddress; if (ASN1_STRING_length (san_str) == 4) /* IPv4 */ { const unsigned char *ip_data = ASN1_STRING_get0_data (san_str); /* Check for 203.0.113.0 (from original 203.0.113.0/24) */ if (ip_data[0] == 203 && ip_data[1] == 0 && ip_data[2] == 113 && ip_data[3] == 0) { printf ( " ✓ IPv4 netmask stripped: 203.0.113.0/24 → " "203.0.113.0\n"); found_netmask_ipv4 = 1; } } else if (ASN1_STRING_length (san_str) == 16) /* IPv6 */ { const unsigned char *ip_data = ASN1_STRING_get0_data (san_str); /* Check for 2001:db8:85a3:: (from original 2001:db8:85a3::/64) */ if (ip_data[0] == 0x20 && ip_data[1] == 0x01 && ip_data[2] == 0x0d && ip_data[3] == 0xb8 && ip_data[4] == 0x85 && ip_data[5] == 0xa3 && ip_data[6] == 0x00 && ip_data[7] == 0x00 && ip_data[8] == 0x00 && ip_data[9] == 0x00 && ip_data[10] == 0x00 && ip_data[11] == 0x00 && ip_data[12] == 0x00 && ip_data[13] == 0x00 && ip_data[14] == 0x00 && ip_data[15] == 0x00) { printf ( " ✓ IPv6 netmask stripped: 2001:db8:85a3::/64 → " "2001:db8:85a3::\n"); found_netmask_ipv6 = 1; } } } } GENERAL_NAMES_free (san_names); /* Verify that netmask stripping worked correctly */ if (!found_netmask_ipv4) { printf (" ERROR: IPv4 netmask stripping test failed.\n"); return EINVAL; } if (!found_netmask_ipv6) { printf (" ERROR: IPv6 netmask stripping test failed.\n"); return EINVAL; } printf (" All IP address netmask tests passed successfully.\n"); return EOK; } static int verify_name_constraints (struct sscg_x509_cert *ca_cert, char **expected_san_list) { X509 *x509 = ca_cert->certificate; X509_EXTENSION *name_constraints_ext = NULL; ASN1_OCTET_STRING *ext_data = NULL; BIO *bio = NULL; char *ext_str = NULL; char *line = NULL; char *saveptr = NULL; size_t ext_str_len = 0; int found_constraints[20] = { 0 }; /* Track which expected constraints we found */ int missing_count = 0; int j; printf ("\n Verifying name constraints in CA certificate:\n"); /* Find the name constraints extension */ int ext_idx = X509_get_ext_by_NID (x509, NID_name_constraints, -1); if (ext_idx < 0) { printf ( " ERROR: CA certificate missing Name Constraints extension.\n"); return EINVAL; } name_constraints_ext = X509_get_ext (x509, ext_idx); if (!name_constraints_ext) { printf (" ERROR: Failed to get Name Constraints extension.\n"); return EINVAL; } /* Get the extension data */ ext_data = X509_EXTENSION_get_data (name_constraints_ext); if (!ext_data) { printf (" ERROR: Failed to get Name Constraints extension data.\n"); return EINVAL; } /* Convert the extension to a readable string using BIO */ bio = BIO_new (BIO_s_mem ()); if (!bio) { printf (" ERROR: Failed to create BIO for extension parsing.\n"); return EINVAL; } /* Print the extension to the BIO */ if (!X509V3_EXT_print (bio, name_constraints_ext, 0, 0)) { printf (" ERROR: Failed to print Name Constraints extension.\n"); BIO_free (bio); return EINVAL; } /* Get the string representation */ ext_str_len = BIO_get_mem_data (bio, &ext_str); if (ext_str_len <= 0 || !ext_str) { printf (" ERROR: Failed to get extension string data.\n"); BIO_free (bio); return EINVAL; } /* Null-terminate the string for parsing */ char *ext_str_copy = malloc (ext_str_len + 1); if (!ext_str_copy) { printf ( " ERROR: Failed to allocate memory for extension parsing.\n"); BIO_free (bio); return ENOMEM; } memcpy (ext_str_copy, ext_str, ext_str_len); ext_str_copy[ext_str_len] = '\0'; printf (" Name Constraints content:\n%s\n", ext_str_copy); /* Parse the extension string to find constraints */ line = strtok_r (ext_str_copy, "\n", &saveptr); while (line) { /* Look for "Permitted:" sections and DNS/IP entries */ if (strstr (line, "DNS:")) { char *dns_start = strstr (line, "DNS:"); if (dns_start) { dns_start += 4; /* Skip "DNS:" */ /* Trim whitespace */ while (*dns_start == ' ' || *dns_start == '\t') dns_start++; printf (" Found DNS constraint: %s\n", dns_start); /* Check if this matches our expected CN (truncated) */ if (strstr (dns_start, "server")) { found_constraints[0] = 1; } /* Check against our expected SAN list */ if (expected_san_list) { for (j = 0; expected_san_list[j]; j++) { char *expected_dns = NULL; if (!strchr (expected_san_list[j], ':')) { expected_dns = expected_san_list[j]; } else if (strncmp (expected_san_list[j], "DNS:", 4) == 0) { expected_dns = expected_san_list[j] + 4; } if (expected_dns && strstr (dns_start, expected_dns)) { found_constraints[j + 1] = 1; } } } } } else if (strstr (line, "IP:")) { char *ip_start = strstr (line, "IP:"); if (ip_start) { ip_start += 3; /* Skip "IP:" */ while (*ip_start == ' ' || *ip_start == '\t') ip_start++; printf (" Found IP constraint: %s\n", ip_start); /* Check against expected IP SANs */ if (expected_san_list) { for (j = 0; expected_san_list[j]; j++) { if (strncmp (expected_san_list[j], "IP:", 3) == 0) { char *expected_ip = expected_san_list[j] + 3; char *slash = strchr (expected_ip, '/'); char expected_constraint[128]; char clean_ip[64]; /* Extract IP and netmask parts */ if (slash) { int ip_len = slash - expected_ip; strncpy (clean_ip, expected_ip, ip_len); clean_ip[ip_len] = '\0'; /* Parse the CIDR netmask */ char *cidr_str = slash + 1; int cidr_bits = atoi (cidr_str); /* Convert to constraint format with proper netmask */ if (strchr (clean_ip, ':')) { /* IPv6 - convert CIDR to hex netmask */ const char *netmask; if (cidr_bits == 128) netmask = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:" "FFFF"; else if (cidr_bits == 64) netmask = "FFFF:FFFF:FFFF:FFFF:0:0:0:0"; else netmask = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:" "FFFF"; /* default to /128 */ /* Handle compressed IPv6 forms */ if (strstr (clean_ip, "2001:db8::1")) { snprintf (expected_constraint, sizeof (expected_constraint), "IP:2001:DB8:0:0:0:0:0:1/%s", netmask); } else if (strstr (clean_ip, "2001:db8:85a3::")) { snprintf ( expected_constraint, sizeof (expected_constraint), "IP:2001:DB8:85A3:0:0:0:0:0/%s", netmask); } else { snprintf (expected_constraint, sizeof (expected_constraint), "IP:%s/%s", clean_ip, netmask); } } else { /* IPv4 - convert CIDR to dotted decimal */ const char *netmask; if (cidr_bits == 32) netmask = "255.255.255.255"; else if (cidr_bits == 24) netmask = "255.255.255.0"; else if (cidr_bits == 16) netmask = "255.255.0.0"; else if (cidr_bits == 8) netmask = "255.0.0.0"; else netmask = "255.255.255.255"; /* default to /32 */ snprintf (expected_constraint, sizeof (expected_constraint), "IP:%s/%s", clean_ip, netmask); } } else { /* No netmask - add single host netmask */ strncpy (clean_ip, expected_ip, 64); clean_ip[63] = '\0'; if (strchr (clean_ip, ':')) { /* IPv6 with /128 netmask */ if (strstr (clean_ip, "2001:db8::1")) { snprintf (expected_constraint, sizeof (expected_constraint), "IP:2001:DB8:0:0:0:0:0:1/" "FFFF:FFFF:FFFF:FFFF:FFFF:" "FFFF:FFFF:FFFF"); } else if (strstr (clean_ip, "2001:db8:85a3::")) { snprintf (expected_constraint, sizeof (expected_constraint), "IP:2001:DB8:85A3:0:0:0:0:0/" "FFFF:FFFF:FFFF:FFFF:FFFF:" "FFFF:FFFF:FFFF"); } else { snprintf (expected_constraint, sizeof (expected_constraint), "IP:%s/" "FFFF:FFFF:FFFF:FFFF:FFFF:" "FFFF:FFFF:FFFF", clean_ip); } } else { /* IPv4 with /32 netmask */ snprintf (expected_constraint, sizeof (expected_constraint), "IP:%s/255.255.255.255", clean_ip); } } /* Check if this expected constraint matches what we found */ /* Skip the "IP:" prefix for comparison since ip_start doesn't include it */ char *constraint_without_prefix = expected_constraint + 3; /* Skip "IP:" */ if (strcmp (ip_start, constraint_without_prefix) == 0) { found_constraints[j + 1] = 1; } } } } } } line = strtok_r (NULL, "\n", &saveptr); } free (ext_str_copy); BIO_free (bio); /* Verify that we found all expected constraints */ if (!found_constraints[0]) { printf (" MISSING: CN constraint 'server' not found.\n"); missing_count++; } if (expected_san_list) { for (j = 0; expected_san_list[j]; j++) { if (!found_constraints[j + 1]) { /* Only report missing DNS and IP constraints, skip email/URI */ if (!strchr (expected_san_list[j], ':') || strncmp (expected_san_list[j], "DNS:", 4) == 0 || strncmp (expected_san_list[j], "IP:", 3) == 0) { printf (" MISSING: Constraint for '%s' not found.\n", expected_san_list[j]); missing_count++; } } } } if (missing_count > 0) { printf (" %d expected name constraints were missing.\n", missing_count); return EINVAL; } printf (" All expected name constraints found successfully.\n"); return EOK; } 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; /* Variables for CA testing */ struct sscg_x509_cert *ca_cert = NULL; struct sscg_evp_pkey *ca_key = NULL; struct sscg_options ca_options; 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); /* Set up comprehensive subject alternative names covering all supported formats * * SSCG SAN Format Support Summary: * - DNS names: Supported (both implicit and explicit "DNS:" prefix) * - IPv4/IPv6 addresses: Supported (with "IP:" prefix) * - Email addresses: Supported (with "email:" prefix) * - URIs: Partial support (limitation: slashes get truncated due to IP subnet mask handling) * - Wildcards: Supported in DNS names * - Internationalized domains: Limited (needs ACE encoding) * * Known limitations: * 1. URI paths with slashes get truncated (affects https://example.com/path) * 2. Only basic SAN formats supported (no otherName, directoryName, etc.) * * IP Address Netmask Handling: * - SSCG automatically strips netmask suffixes (e.g., /24, /64) from IP addresses * - This is intentional behavior to ensure clean IP address encoding in certificates */ certinfo->subject_alt_names = talloc_zero_array (certinfo, char *, 13); CHECK_MEM (certinfo->subject_alt_names); /* DNS names (both implicit and explicit) */ certinfo->subject_alt_names[0] = talloc_strdup (certinfo->subject_alt_names, "alt1.example.com"); CHECK_MEM (certinfo->subject_alt_names[0]); certinfo->subject_alt_names[1] = talloc_strdup (certinfo->subject_alt_names, "DNS:alt2.example.com"); CHECK_MEM (certinfo->subject_alt_names[1]); /* IPv4 addresses */ certinfo->subject_alt_names[2] = talloc_strdup (certinfo->subject_alt_names, "IP:192.168.1.100"); CHECK_MEM (certinfo->subject_alt_names[2]); certinfo->subject_alt_names[3] = talloc_strdup (certinfo->subject_alt_names, "IP:10.0.0.1"); CHECK_MEM (certinfo->subject_alt_names[3]); /* IPv6 address */ certinfo->subject_alt_names[4] = talloc_strdup (certinfo->subject_alt_names, "IP:2001:db8::1"); CHECK_MEM (certinfo->subject_alt_names[4]); /* IPv4 address with netmask (SSCG will strip the /24 part) */ certinfo->subject_alt_names[5] = talloc_strdup (certinfo->subject_alt_names, "IP:203.0.113.0/24"); CHECK_MEM (certinfo->subject_alt_names[5]); /* IPv6 address with netmask (SSCG will strip the /64 part) */ certinfo->subject_alt_names[6] = talloc_strdup (certinfo->subject_alt_names, "IP:2001:db8:85a3::/64"); CHECK_MEM (certinfo->subject_alt_names[6]); /* Email addresses */ certinfo->subject_alt_names[7] = talloc_strdup (certinfo->subject_alt_names, "email:admin@example.com"); CHECK_MEM (certinfo->subject_alt_names[7]); /* URI (proper format - let's see what SSCG actually does with it) */ certinfo->subject_alt_names[8] = talloc_strdup ( certinfo->subject_alt_names, "URI:https://www.example.com/service"); CHECK_MEM (certinfo->subject_alt_names[8]); /* Wildcard DNS name */ certinfo->subject_alt_names[9] = talloc_strdup (certinfo->subject_alt_names, "*.wildcard.example.com"); CHECK_MEM (certinfo->subject_alt_names[9]); /* Subdomain */ certinfo->subject_alt_names[10] = talloc_strdup (certinfo->subject_alt_names, "subdomain.alt1.example.com"); CHECK_MEM (certinfo->subject_alt_names[10]); /* International domain (ACE encoded) */ certinfo->subject_alt_names[11] = talloc_strdup (certinfo->subject_alt_names, "xn--nxasmq6b.example.com"); CHECK_MEM (certinfo->subject_alt_names[11]); /* NULL terminator */ certinfo->subject_alt_names[12] = NULL; /* 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); /* ============= SERVICE CERTIFICATE TESTS ============= */ /* Verify that subject alternative names were properly included */ printf ("Verifying subject alternative names in service certificate. "); ret = verify_subject_alt_names (cert); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); /* Test additional SAN verification scenarios */ printf ("Testing SAN edge cases and validation. "); ret = test_san_edge_cases (cert); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); /* Test IP address netmask handling */ printf ("Testing IP address netmask stripping functionality. "); ret = test_ip_netmask_handling (cert); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); /* ============= CA CERTIFICATE TESTS ============= */ printf ("\n=== CA CERTIFICATE TESTS ===\n"); /* Set up options for CA creation */ memset (&ca_options, 0, sizeof (ca_options)); ca_options.country = "US"; ca_options.state = ""; ca_options.locality = ""; ca_options.org = "Unspecified"; ca_options.email = ""; ca_options.hostname = "server.example.com"; ca_options.hash_fn = EVP_sha256 (); ca_options.lifetime = 3650; ca_options.verbosity = SSCG_QUIET; /* Set up the same subject alternative names for the CA */ ca_options.subject_alt_names = certinfo->subject_alt_names; /* Create the private CA */ printf ("Creating private CA certificate. "); ret = create_private_CA (tmp_ctx, &ca_options, &ca_cert, &ca_key); if (ret != EOK) { printf ("FAILED.\n"); goto done; } else { printf ("SUCCESS.\n"); } /* If create_private_CA returns EOK, ca_cert must be non-NULL */ if (ca_cert == NULL) { printf ("FAILED: ca_cert is NULL.\n"); ret = EINVAL; goto done; } /* Verify name constraints in the CA certificate */ printf ("Verifying name constraints in CA certificate. "); ret = verify_name_constraints (ca_cert, certinfo->subject_alt_names); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); done: if (ret != EOK) { fprintf (stderr, "FAILURE: %s\n", strerror (ret)); } talloc_free (tmp_ctx); return ret; } sscg-sscg-3.0.8/test/create_cert_test.c000066400000000000000000000427551504024410100200640ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2025 by Stephen Gallagher */ #include #include #include #include #include #include #include "include/sscg.h" #include "include/cert.h" #include "include/authority.h" #include "include/x509.h" static int setup_test_options (TALLOC_CTX *mem_ctx, struct sscg_options **_options) { struct sscg_options *options; options = talloc_zero (mem_ctx, struct sscg_options); if (!options) { return ENOMEM; } /* Set up basic test values manually (avoiding internal function) */ options->lifetime = 365; /* 1 year */ options->verbosity = SSCG_QUIET; /* Keep tests quiet */ options->hash_fn = EVP_sha256 (); options->key_strength = 2048; /* Reasonable default */ /* Set up test-specific values */ options->country = talloc_strdup (options, "US"); if (!options->country) return ENOMEM; options->state = talloc_strdup (options, "TestState"); if (!options->state) return ENOMEM; options->locality = talloc_strdup (options, "TestCity"); if (!options->locality) return ENOMEM; options->org = talloc_strdup (options, "Test Organization"); if (!options->org) return ENOMEM; options->org_unit = talloc_strdup (options, "Test Unit"); if (!options->org_unit) return ENOMEM; options->email = talloc_strdup (options, "test@example.com"); if (!options->email) return ENOMEM; options->hostname = talloc_strdup (options, "test.example.com"); if (!options->hostname) return ENOMEM; options->lifetime = 365; /* 1 year */ options->verbosity = SSCG_QUIET; /* Keep tests quiet */ options->hash_fn = EVP_sha256 (); /* Initialize streams array to avoid segfaults */ options->streams = talloc_zero_array (options, struct sscg_stream *, SSCG_NUM_FILE_TYPES); if (!options->streams) return ENOMEM; *_options = options; return EOK; } /* Test data structures for comprehensive testing */ struct hash_test_case { const char *name; const EVP_MD *(*hash_func) (void); }; struct key_strength_test_case { const char *name; int bits; }; /* Hash functions to test - only including modern, supported algorithms */ static struct hash_test_case hash_test_cases[] = { { "SHA-256", EVP_sha256 }, /* Most common, widely supported */ { "SHA-384", EVP_sha384 }, /* High security */ { "SHA-512", EVP_sha512 }, /* Highest security */ { NULL, NULL } /* Terminator */ }; /* Key strengths to test */ static struct key_strength_test_case key_strength_test_cases[] = { { "512-bit", 512 }, /* Weak, but requested for testing */ { "1024-bit", 1024 }, /* Deprecated but still used */ { "2048-bit", 2048 }, /* Current standard */ { "4096-bit", 4096 }, /* High security */ { NULL, 0 } /* Terminator */ }; static int create_cert_with_params (TALLOC_CTX *mem_ctx, const char *hash_name, const EVP_MD *hash_func, int key_strength, struct sscg_x509_cert *ca_cert, struct sscg_evp_pkey *ca_key, enum sscg_cert_type cert_type, struct sscg_x509_cert **_cert, struct sscg_evp_pkey **_key) { int ret; struct sscg_options *options; /* Set up test options for this specific test */ ret = setup_test_options (mem_ctx, &options); if (ret != EOK) { return ret; } /* Override with test-specific parameters */ options->hash_fn = hash_func; options->key_strength = key_strength; /* Allow weak keys for testing purposes */ options->minimum_key_strength = 512; /* Create certificate with specified parameters */ ret = create_cert (mem_ctx, options, ca_cert, ca_key, cert_type, _cert, _key); return ret; } static int verify_certificate_basic_properties (struct sscg_x509_cert *cert, struct sscg_evp_pkey *key, struct sscg_x509_cert *ca_cert) { X509 *x509 = cert->certificate; EVP_PKEY *pkey = key->evp_pkey; X509 *ca_x509 = ca_cert->certificate; /* Verify certificate has a serial number */ ASN1_INTEGER *serial = X509_get_serialNumber (x509); if (!serial) { printf ("Certificate missing serial number.\n"); return EINVAL; } /* Verify certificate has valid dates */ ASN1_TIME *not_before = X509_get_notBefore (x509); ASN1_TIME *not_after = X509_get_notAfter (x509); if (!not_before || !not_after) { printf ("Certificate missing validity dates.\n"); return EINVAL; } /* Verify the certificate was signed by the CA */ EVP_PKEY *ca_pubkey = X509_get_pubkey (ca_x509); if (!ca_pubkey) { printf ("Could not extract CA public key.\n"); return EINVAL; } int verify_result = X509_verify (x509, ca_pubkey); EVP_PKEY_free (ca_pubkey); if (verify_result != 1) { printf ("Certificate verification against CA failed.\n"); return EINVAL; } /* Verify the private key matches the certificate */ if (X509_check_private_key (x509, pkey) != 1) { printf ("Private key does not match certificate.\n"); return EINVAL; } return EOK; } static int verify_server_certificate_extensions (struct sscg_x509_cert *cert) { X509 *x509 = cert->certificate; /* Check for Key Usage extension */ int key_usage = X509_get_key_usage (x509); if (!(key_usage & X509v3_KU_DIGITAL_SIGNATURE) || !(key_usage & X509v3_KU_KEY_ENCIPHERMENT)) { printf ("Server certificate missing required key usage extensions.\n"); return EINVAL; } return EOK; } int main (int argc, char **argv) { int ret; size_t initial_blocks, final_blocks; struct sscg_options *options = NULL; struct sscg_x509_cert *ca_cert = NULL; struct sscg_evp_pkey *ca_key = NULL; struct sscg_x509_cert *server_cert = NULL; struct sscg_evp_pkey *server_key = NULL; struct sscg_x509_cert *client_cert = NULL; struct sscg_evp_pkey *client_key = NULL; /* Enable talloc leak reporting for memory leak detection */ talloc_enable_leak_report_full (); /* Record initial memory state for leak detection */ initial_blocks = talloc_total_blocks (NULL); TALLOC_CTX *tmp_ctx = talloc_new (NULL); if (!tmp_ctx) { return ENOMEM; } printf ("=== SSCG Create Cert Test with Talloc Leak Detection ===\n"); printf ("Initial talloc blocks: %zu\n", initial_blocks); /* Test 1: Set up test options */ printf ("Setting up test options. "); ret = setup_test_options (tmp_ctx, &options); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); /* Test 2: Create a private CA for testing */ printf ("Creating private CA for testing. "); ret = create_private_CA (tmp_ctx, options, &ca_cert, &ca_key); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); /* Test 3: Create a server certificate */ printf ("Creating server certificate. "); ret = create_cert (tmp_ctx, options, ca_cert, ca_key, SSCG_CERT_TYPE_SERVER, &server_cert, &server_key); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); /* Test 4: Verify server certificate properties */ printf ("Verifying server certificate properties. "); ret = verify_certificate_basic_properties (server_cert, server_key, ca_cert); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); /* Test 5: Verify server certificate extensions */ printf ("Verifying server certificate extensions. "); ret = verify_server_certificate_extensions (server_cert); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); /* Test 6: Create a client certificate */ printf ("Creating client certificate. "); ret = create_cert (tmp_ctx, options, ca_cert, ca_key, SSCG_CERT_TYPE_CLIENT, &client_cert, &client_key); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); /* Test 7: Verify client certificate properties */ printf ("Verifying client certificate properties. "); ret = verify_certificate_basic_properties (client_cert, client_key, ca_cert); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); /* Test 8: Verify certificates are different */ printf ("Verifying server and client certificates are different. "); if (X509_cmp (server_cert->certificate, client_cert->certificate) == 0) { printf ("FAILED. Server and client certificates are identical.\n"); ret = EINVAL; goto done; } printf ("SUCCESS.\n"); /* Test 9: Test error handling with invalid certificate type */ printf ("Testing error handling with invalid certificate type. "); struct sscg_x509_cert *invalid_cert = NULL; struct sscg_evp_pkey *invalid_key = NULL; ret = create_cert (tmp_ctx, options, ca_cert, ca_key, SSCG_CERT_TYPE_UNKNOWN, &invalid_cert, &invalid_key); if (ret == EOK) { printf ("FAILED. Expected error but got success.\n"); ret = EINVAL; goto done; } printf ("SUCCESS. Correctly failed with invalid certificate type.\n"); /* Test 10: Test memory management with isolated context */ printf ("Testing memory management with isolated context. "); TALLOC_CTX *isolated_ctx = talloc_new (NULL); if (!isolated_ctx) { printf ("FAILED. Could not create isolated context.\n"); ret = ENOMEM; goto done; } struct sscg_x509_cert *isolated_cert = NULL; struct sscg_evp_pkey *isolated_key = NULL; ret = create_cert (isolated_ctx, options, ca_cert, ca_key, SSCG_CERT_TYPE_SERVER, &isolated_cert, &isolated_key); if (ret != EOK) { printf ("FAILED. Could not create certificate in isolated context.\n"); talloc_free (isolated_ctx); goto done; } /* Verify the certificate in isolated context */ ret = verify_certificate_basic_properties (isolated_cert, isolated_key, ca_cert); if (ret != EOK) { printf ("FAILED. Isolated certificate verification failed.\n"); talloc_free (isolated_ctx); goto done; } /* Clean up isolated context */ talloc_free (isolated_ctx); printf ("SUCCESS.\n"); /* Test 11: Comprehensive hash function testing */ printf ("\n=== Comprehensive Hash Function Testing ===\n"); for (int h = 0; hash_test_cases[h].name != NULL; h++) { printf ("Testing %s hash function. ", hash_test_cases[h].name); struct sscg_x509_cert *hash_test_cert = NULL; struct sscg_evp_pkey *hash_test_key = NULL; ret = create_cert_with_params ( tmp_ctx, hash_test_cases[h].name, hash_test_cases[h].hash_func (), 2048, /* Use standard key size for hash tests */ ca_cert, ca_key, SSCG_CERT_TYPE_SERVER, &hash_test_cert, &hash_test_key); if (ret != EOK) { printf ("FAILED.\n"); goto done; } ret = verify_certificate_basic_properties ( hash_test_cert, hash_test_key, ca_cert); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); } /* Test 12: Comprehensive key strength testing */ printf ("\n=== Comprehensive Key Strength Testing ===\n"); for (int k = 0; key_strength_test_cases[k].name != NULL; k++) { printf ("Testing %s key strength. ", key_strength_test_cases[k].name); struct sscg_x509_cert *key_test_cert = NULL; struct sscg_evp_pkey *key_test_key = NULL; ret = create_cert_with_params (tmp_ctx, "SHA-256", EVP_sha256 (), key_strength_test_cases[k].bits, ca_cert, ca_key, SSCG_CERT_TYPE_SERVER, &key_test_cert, &key_test_key); if (ret != EOK) { printf ("FAILED.\n"); goto done; } ret = verify_certificate_basic_properties ( key_test_cert, key_test_key, ca_cert); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); } /* Test 13: Matrix testing - critical combinations */ printf ("\n=== Matrix Testing - Critical Combinations ===\n"); /* Test a representative subset to avoid excessive test time */ struct { const char *hash_name; const EVP_MD *(*hash_func) (void); const char *key_name; int key_bits; } matrix_tests[] = { { "SHA-256", EVP_sha256, "1024-bit", 1024 }, { "SHA-256", EVP_sha256, "4096-bit", 4096 }, { "SHA-384", EVP_sha384, "2048-bit", 2048 }, { "SHA-512", EVP_sha512, "2048-bit", 2048 }, { "SHA-512", EVP_sha512, "4096-bit", 4096 }, { NULL, NULL, NULL, 0 } }; for (int m = 0; matrix_tests[m].hash_name != NULL; m++) { printf ("Testing %s with %s. ", matrix_tests[m].hash_name, matrix_tests[m].key_name); struct sscg_x509_cert *matrix_cert = NULL; struct sscg_evp_pkey *matrix_key = NULL; ret = create_cert_with_params ( tmp_ctx, matrix_tests[m].hash_name, matrix_tests[m].hash_func (), matrix_tests[m].key_bits, ca_cert, ca_key, SSCG_CERT_TYPE_CLIENT, /* Use client for variety */ &matrix_cert, &matrix_key); if (ret != EOK) { printf ("FAILED.\n"); goto done; } ret = verify_certificate_basic_properties (matrix_cert, matrix_key, ca_cert); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); } /* Test 14: Performance test with high-security parameters */ printf ("\n=== High-Security Parameters Test ===\n"); printf ("Testing SHA-512 with 4096-bit key (high-security). "); struct sscg_x509_cert *high_sec_cert = NULL; struct sscg_evp_pkey *high_sec_key = NULL; ret = create_cert_with_params (tmp_ctx, "SHA-512", EVP_sha512 (), 4096, ca_cert, ca_key, SSCG_CERT_TYPE_SERVER, &high_sec_cert, &high_sec_key); if (ret != EOK) { printf ("FAILED.\n"); goto done; } ret = verify_certificate_basic_properties (high_sec_cert, high_sec_key, ca_cert); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); printf ("\n=== Comprehensive Testing Complete ===\n"); ret = EOK; done: /* Clean up main test context */ talloc_free (tmp_ctx); /* Check for memory leaks */ final_blocks = talloc_total_blocks (NULL); printf ("\n=== Talloc Leak Detection Report ===\n"); printf ("Initial talloc blocks: %zu\n", initial_blocks); printf ("Final talloc blocks: %zu\n", final_blocks); if (final_blocks > initial_blocks) { printf ("FAILED: Memory leak detected! %zu blocks leaked.\n", final_blocks - initial_blocks); printf ("Detailed leak report:\n"); talloc_report_full (NULL, stderr); /* Fail the test when leaks are detected */ ret = ENOMEM; } else { printf ("SUCCESS: No memory leaks detected.\n"); } printf ("=== Test Complete ===\n"); return ret; } sscg-sscg-3.0.8/test/create_csr_test.c000066400000000000000000000064351504024410100177110ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 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); /* Subject alternative names are covered in create_ca_test.c */ /* 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); ret = EOK; done: if (ret != EOK) { fprintf (stderr, "FAILURE: %s", strerror (ret)); } talloc_free (tmp_ctx); return ret; } sscg-sscg-3.0.8/test/dhparams_test.c000066400000000000000000000054411504024410100173720ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2019-2025 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.8/test/generate_rsa_key_test.c000066400000000000000000000050611504024410100211000ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 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.8/test/generate_serial_test.c000066400000000000000000000046021504024410100207220ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 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.8/test/init_bignum_test.c000066400000000000000000000160241504024410100200760ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2017-2025 by Stephen Gallagher */ #include #include #include #include "include/bignum.h" int main (int argc, char **argv) { int ret; unsigned long val; struct sscg_bignum *bn; size_t initial_blocks, final_blocks; /* Enable talloc leak reporting for memory leak detection */ talloc_enable_leak_report_full (); TALLOC_CTX *tmp_ctx = talloc_new (NULL); if (!tmp_ctx) { return ENOMEM; } /* Record initial memory state for leak detection */ initial_blocks = talloc_total_blocks (NULL); printf ("=== SSCG Init Bignum Test with Talloc Leak Detection ===\n"); printf ("Initial talloc blocks: %zu\n", initial_blocks); /* Test 1: Initialize bignum with zero */ printf ("Testing sscg_init_bignum with zero. "); 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"); /* Test 2: Initialize bignum with a non-zero value */ printf ("Testing sscg_init_bignum with value 12345. "); ret = sscg_init_bignum (tmp_ctx, 12345, &bn); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); printf ("Verifying bignum initialized to 12345. "); val = BN_get_word (bn->bn); if (val != 12345) { printf ("FAILED. Expected 12345, got %lu.\n", val); ret = EINVAL; goto done; } printf ("SUCCESS.\n"); /* Test 3: Initialize bignum with maximum unsigned long value */ printf ("Testing sscg_init_bignum with ULONG_MAX. "); ret = sscg_init_bignum (tmp_ctx, ULONG_MAX, &bn); if (ret != EOK) { printf ("FAILED.\n"); goto done; } printf ("SUCCESS.\n"); printf ("Verifying bignum initialized to ULONG_MAX. "); val = BN_get_word (bn->bn); if (val != ULONG_MAX && val != 0xffffffffL) { /* BN_get_word returns 0xffffffffL if the value is too large to fit */ printf ( "FAILED. Expected %lu or 0xffffffffL, got %lu.\n", ULONG_MAX, val); ret = EINVAL; goto done; } printf ("SUCCESS.\n"); /* Test 4: Verify memory management by creating and destroying multiple bignums */ printf ("Testing memory management with multiple bignums. "); struct sscg_bignum *bn1, *bn2, *bn3; ret = sscg_init_bignum (tmp_ctx, 100, &bn1); if (ret != EOK) goto memory_test_failed; ret = sscg_init_bignum (tmp_ctx, 200, &bn2); if (ret != EOK) goto memory_test_failed; ret = sscg_init_bignum (tmp_ctx, 300, &bn3); if (ret != EOK) goto memory_test_failed; /* Verify values are correct */ if (BN_get_word (bn1->bn) != 100 || BN_get_word (bn2->bn) != 200 || BN_get_word (bn3->bn) != 300) { goto memory_test_failed; } printf ("SUCCESS.\n"); /* Test 5: Test with different value ranges */ printf ("Testing various value ranges. "); struct sscg_bignum *bn_small, *bn_medium, *bn_large; ret = sscg_init_bignum (tmp_ctx, 1, &bn_small); if (ret != EOK) goto range_test_failed; ret = sscg_init_bignum (tmp_ctx, 65536, &bn_medium); if (ret != EOK) goto range_test_failed; ret = sscg_init_bignum (tmp_ctx, 4294967295UL, &bn_large); if (ret != EOK) goto range_test_failed; /* Verify values are correct */ if (BN_get_word (bn_small->bn) != 1 || BN_get_word (bn_medium->bn) != 65536 || (BN_get_word (bn_large->bn) != 4294967295UL && BN_get_word (bn_large->bn) != 0xffffffffL)) { goto range_test_failed; } printf ("SUCCESS.\n"); /* Test 6: Test talloc leak detection by creating isolated context */ printf ("Testing talloc leak detection with isolated context. "); TALLOC_CTX *leak_test_ctx = talloc_new (NULL); if (!leak_test_ctx) { printf ("FAILED. Could not create leak test context.\n"); ret = ENOMEM; goto done; } struct sscg_bignum *leak_test_bn; ret = sscg_init_bignum (leak_test_ctx, 999, &leak_test_bn); if (ret != EOK) { printf ("FAILED. Could not create bignum in leak test context.\n"); talloc_free (leak_test_ctx); goto done; } /* Verify the value and then properly clean up */ if (BN_get_word (leak_test_bn->bn) != 999) { printf ("FAILED. Leak test bignum has wrong value.\n"); talloc_free (leak_test_ctx); ret = EINVAL; goto done; } /* Clean up the isolated context - this should free all associated memory */ talloc_free (leak_test_ctx); printf ("SUCCESS.\n"); ret = EOK; goto done; memory_test_failed: printf ("FAILED.\n"); ret = EINVAL; goto done; range_test_failed: printf ("FAILED.\n"); ret = EINVAL; done: /* Clean up main test context */ talloc_free (tmp_ctx); /* Check for memory leaks */ final_blocks = talloc_total_blocks (NULL); printf ("\n=== Talloc Leak Detection Report ===\n"); printf ("Initial talloc blocks: %zu\n", initial_blocks); printf ("Final talloc blocks: %zu\n", final_blocks); if (final_blocks > initial_blocks) { printf ("FAILED: Memory leak detected! %zu blocks leaked.\n", final_blocks - initial_blocks); printf ("Detailed leak report:\n"); talloc_report_full (NULL, stderr); /* Fail the test when leaks are detected */ ret = ENOMEM; } else { printf ("SUCCESS: No memory leaks detected.\n"); } printf ("=== Test Complete ===\n"); return ret; } sscg-sscg-3.0.8/test/named_dhparams_test.c000066400000000000000000000113771504024410100205430ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception */ /* 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 . 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. Copyright 2019-2025 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); char *expected = NULL; if (!names) { ret = EINVAL; goto done; } #if OPENSSL_VERSION_NUMBER < 0x30000000L expected = talloc_strdup ( tmp_ctx, "ffdhe2048, ffdhe3072, ffdhe4096, ffdhe6144, ffdhe8192"); #else expected = talloc_strdup (tmp_ctx, "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"); #endif if (strcmp (names, expected) != 0) { fprintf (stderr, "Expected: [%s]\n", expected); fprintf (stderr, "Recieved: [%s]\n", names); ret = EINVAL; goto done; } 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; } sscg-sscg-3.0.8/test/test_cert_validity.sh000077500000000000000000000166221504024410100206330ustar00rootroot00000000000000#!/bin/bash # SPDX-License-Identifier: GPL-3.0-or-later WITH cryptsetup-OpenSSL-exception # 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 . # # 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. # # Copyright 2022-2025 by Stephen Gallagher # ARG_OPTIONAL_SINGLE([hash-alg],[],[Certificate hashing algorithm],[sha256]) # ARG_OPTIONAL_SINGLE([cipher-alg],[],[Key password cipher algorithm],[aes-256-cbc]) # ARG_OPTIONAL_SINGLE([key-strength],[],[Certificate key strength],[2048]) # ARG_HELP([Test for validity of created certificates]) # ARGBASH_GO() # needed because of Argbash --> m4_ignore([ ### START OF CODE GENERATED BY Argbash v2.9.0 one line above ### # Argbash is a bash code generator used to get arguments parsing right. # Argbash is FREE SOFTWARE, see https://argbash.io for more info # Generated online by https://argbash.io/generate # # When called, the process ends. # Args: # $1: The exit message (print to stderr) # $2: The exit code (default is 1) # if env var _PRINT_HELP is set to 'yes', the usage is print to stderr (prior to $1) # Example: # test -f "$_arg_infile" || _PRINT_HELP=yes die "Can't continue, have to supply file as an argument, got '$_arg_infile'" 4 die() { local _ret="${2:-1}" test "${_PRINT_HELP:-no}" = yes && print_help >&2 echo "$1" >&2 exit "${_ret}" } # Function that evaluates whether a value passed to it begins by a character # that is a short option of an argument the script knows about. # This is required in order to support getopts-like short options grouping. begins_with_short_option() { local first_option all_short_options='h' first_option="${1:0:1}" test "$all_short_options" = "${all_short_options/$first_option/}" && return 1 || return 0 } # THE DEFAULTS INITIALIZATION - OPTIONALS _arg_hash_alg="sha256" _arg_cipher_alg="aes-256-cbc" _arg_key_strength="2048" # Function that prints general usage of the script. # This is useful if users asks for it, or if there is an argument parsing error (unexpected / spurious arguments) # and it makes sense to remind the user how the script is supposed to be called. print_help() { printf '%s\n' "Test for validity of created certificates" printf 'Usage: %s [--hash-alg ] [--cipher-alg ] [--key-strength ] [-h|--help]\n' "$0" printf '\t%s\n' "--hash-alg: Certificate hashing algorithm (default: 'sha256')" printf '\t%s\n' "--cipher-alg: Key password cipher algorithm (default: 'aes-256-cbc')" printf '\t%s\n' "--key-strength: Certificate key strength (default: '2048')" printf '\t%s\n' "-h, --help: Prints help" } # The parsing of the command-line parse_commandline() { while test $# -gt 0 do _key="$1" case "$_key" in # We support whitespace as a delimiter between option argument and its value. # Therefore, we expect the --hash-alg value, so we watch for --hash-alg. # Since we know that we got the long option, # we just reach out for the next argument to get the value. --hash-alg) test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 _arg_hash_alg="$2" shift ;; # We support the = as a delimiter between option argument and its value. # Therefore, we expect --hash-alg=value, so we watch for --hash-alg=* # For whatever we get, we strip '--hash-alg=' using the ${var##--hash-alg=} notation # to get the argument value --hash-alg=*) _arg_hash_alg="${_key##--hash-alg=}" ;; # See the comment of option '--hash-alg' to see what's going on here - principle is the same. --cipher-alg) test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 _arg_cipher_alg="$2" shift ;; # See the comment of option '--hash-alg=' to see what's going on here - principle is the same. --cipher-alg=*) _arg_cipher_alg="${_key##--cipher-alg=}" ;; # See the comment of option '--hash-alg' to see what's going on here - principle is the same. --key-strength) test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 _arg_key_strength="$2" shift ;; # See the comment of option '--hash-alg=' to see what's going on here - principle is the same. --key-strength=*) _arg_key_strength="${_key##--key-strength=}" ;; # The help argurment doesn't accept a value, # we expect the --help or -h, so we watch for them. -h|--help) print_help exit 0 ;; # We support getopts-style short arguments clustering, # so as -h doesn't accept value, other short options may be appended to it, so we watch for -h*. # After stripping the leading -h from the argument, we have to make sure # that the first character that follows coresponds to a short option. -h*) print_help exit 0 ;; *) _PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1'" 1 ;; esac shift done } # Now call all the functions defined above that are needed to get the job done parse_commandline "$@" # OTHER STUFF GENERATED BY Argbash ### END OF CODE GENERATED BY Argbash (sortof) ### ]) # [ <-- needed because of Argbash TMPDIR=$(mktemp --directory --tmpdir sscg_XXXXXX) function common_finalize { exitcode=$? rm -Rf "$TMPDIR" return $exitcode } trap common_finalize EXIT # Fail the test if any command returns non-zero set -ex pushd "$TMPDIR" "${MESON_BUILD_ROOT}"/sscg --hash-alg "$_arg_hash_alg" \ --cipher-alg "$_arg_cipher_alg" \ --key-strength "$_arg_key_strength" \ --cert-key-password mypassword \ --dhparams-file "dhparams.pem" # Verify that the expected files were created test -e dhparams.pem test -e ca.crt test -e service.pem test -e service-key.pem # Verify that they have the correct file format openssl dhparam -noout -in dhparams.pem openssl x509 -noout -in ca.crt openssl x509 -noout -in service.pem grep "ENCRYPTED PRIVATE KEY" service-key.pem openssl pkey -noout -in service-key.pem -passin pass:mypassword # Verify the key strength key_strength=$(openssl pkey -text -noout -in service-key.pem -passin pass:mypassword|head -n1 |sed 's/.*Private-Key: (\([0-9]\{1,\}\).*/\1/') test "$key_strength" -eq "$_arg_key_strength" # Validate the certificates openssl verify -x509_strict -CAfile ca.crt service.pem popd # $TMPDIR # ] <-- needed because of Argbash