diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 05:31:45 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 05:31:45 +0000 |
commit | 74aa0bc6779af38018a03fd2cf4419fe85917904 (patch) | |
tree | 9cb0681aac9a94a49c153d5823e7a55d1513d91f /src/sss_client | |
parent | Initial commit. (diff) | |
download | sssd-74aa0bc6779af38018a03fd2cf4419fe85917904.tar.xz sssd-74aa0bc6779af38018a03fd2cf4419fe85917904.zip |
Adding upstream version 2.9.4.upstream/2.9.4
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/sss_client')
58 files changed, 20529 insertions, 0 deletions
diff --git a/src/sss_client/COPYING b/src/sss_client/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/src/sss_client/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + 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. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + 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 <http://www.gnu.org/licenses/>. + +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: + + <program> Copyright (C) <year> <name of author> + 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 +<http://www.gnu.org/licenses/>. + + 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 +<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/src/sss_client/COPYING.LESSER b/src/sss_client/COPYING.LESSER new file mode 100644 index 0000000..755013b --- /dev/null +++ b/src/sss_client/COPYING.LESSER @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/src/sss_client/autofs/autofs_test_client.c b/src/sss_client/autofs/autofs_test_client.c new file mode 100644 index 0000000..f5cbf36 --- /dev/null +++ b/src/sss_client/autofs/autofs_test_client.c @@ -0,0 +1,148 @@ +/* + Authors: + Jakub Hrozek <jhrozek@redhat.com> + + Copyright (C) 2012 Red Hat + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 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 Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdio.h> +#include <stdlib.h> +#include <dlfcn.h> +#include <errno.h> +#include <popt.h> + +#include "util/util.h" +#include "sss_client/autofs/sss_autofs_private.h" + +struct automtent { + const char *mapname; + size_t cursor; +}; + +int main(int argc, const char *argv[]) +{ + void *ctx; + errno_t ret; + const char *mapname; + char *key = NULL; + char *value = NULL; + char *pc_key = NULL; + int pc_setent = 0; + int pc_protocol = 1; + unsigned int protocol; + unsigned int requested_protocol = 1; + struct poptOption long_options[] = { + POPT_AUTOHELP + { "by-name", 'n', POPT_ARG_STRING, &pc_key, 0, "Request map by name", NULL }, + { "only-setent", 's', POPT_ARG_VAL, &pc_setent, 1, "Run only setent, do not enumerate", NULL }, + { "protocol", 'p', POPT_ARG_INT, &pc_protocol, 0, "Protocol version", NULL }, + POPT_TABLEEND + }; + poptContext pc = NULL; + + pc = poptGetContext(NULL, argc, argv, long_options, 0); + poptSetOtherOptionHelp(pc, "MAPNAME"); + + while (poptGetNextOpt(pc) > 0) + ; + + mapname = poptGetArg(pc); + if (mapname == NULL) { + poptPrintUsage(pc, stderr, 0); + fprintf(stderr, "Please specify the automounter map name\n"); + poptFreeContext(pc); + exit(EXIT_FAILURE); + } + + poptFreeContext(pc); + + requested_protocol = pc_protocol; + protocol = _sss_auto_protocol_version(requested_protocol); + if (protocol != requested_protocol) { + fprintf(stderr, "Unsupported protocol version: %u -> %u\n", + requested_protocol, protocol); + exit(EXIT_FAILURE); + } + + ret = _sss_setautomntent(mapname, &ctx); + if (ret) { + fprintf(stderr, "setautomntent failed [%d]: %s\n", + ret, strerror(ret)); + exit(EXIT_FAILURE); + } + printf("setautomntent done for %s\n", mapname); + + if (pc_setent) { + goto end; + } + + if (!pc_key) { + do { + ret = _sss_getautomntent_r(&key, &value, ctx); + if (ret == 0) { + if (!key || !value) { + fprintf(stderr, + "getautomntent returned success but no data?\n"); + goto end; + } + + printf("key: %s\t\tvalue: %s\n", key, value); + free(key); + key = NULL; + free(value); + value = NULL; + } + } while(ret == 0); + + if (ret != 0 && ret != ENOENT) { + fprintf(stderr, "getautomntent_r failed [%d]: %s\n", + ret, strerror(ret)); + goto end; + } + } else { + ret = _sss_getautomntbyname_r(pc_key, &value, ctx); + if (ret == ENOENT) { + fprintf(stderr, "no such entry in map\n"); + } else if (ret != 0) { + fprintf(stderr, "getautomntbyname_r failed [%d]: %s\n", + ret, strerror(ret)); + goto end; + } else { + if (!value) { + fprintf(stderr, "_sss_getautomntbyname_r " + "returned success but no data?\n"); + goto end; + } + + printf("key: %s\t\tvalue: %s\n", pc_key, value); + free(value); + } + } + +end: + ret = _sss_endautomntent(&ctx); + if (ret) { + fprintf(stderr, "endautomntent failed [%d]: %s\n", + ret, strerror(ret)); + exit(EXIT_FAILURE); + } + printf("endautomntent done for %s\n", mapname); + return 0; +} diff --git a/src/sss_client/autofs/sss_autofs.c b/src/sss_client/autofs/sss_autofs.c new file mode 100644 index 0000000..ef27cf8 --- /dev/null +++ b/src/sss_client/autofs/sss_autofs.c @@ -0,0 +1,505 @@ +/* + Authors: + Jakub Hrozek <jhrozek@redhat.com> + + Copyright (C) 2012 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include <errno.h> +#include <stdlib.h> +#include <stdatomic.h> + +#include "sss_client/autofs/sss_autofs_private.h" +#include "sss_client/sss_cli.h" + +/* Historically, autofs map names were just file names. Direct key names + * may be full directory paths + */ +#define MAX_AUTOMNTMAPNAME_LEN NAME_MAX +#define MAX_AUTOMNTKEYNAME_LEN PATH_MAX + +/* How many entries shall _sss_getautomntent_r retrieve at once */ +#define GETAUTOMNTENT_MAX_ENTRIES 512 + +static atomic_uint _protocol = 0; + +unsigned int _sss_auto_protocol_version(unsigned int requested) +{ + switch (requested) { + case 0: + /* EHOSTDOWN will be translated to ENOENT */ + _protocol = 0; + return 0; + default: + /* There is no other protocol version at this point. */ + _protocol = 1; + return 1; + } +} + +/* Returns correct errno based on autofs version expectations. */ +static errno_t errnop_to_errno(int errnop) +{ + if (errnop == EHOSTDOWN && _protocol == 0) { + return ENOENT; + } + + return errnop; +} + +struct automtent { + char *mapname; + size_t cursor; +}; + +static struct sss_getautomntent_data { + char *mapname; + size_t len; + size_t ptr; + uint8_t *data; +} sss_getautomntent_data; + +static void +sss_getautomntent_data_clean(void) +{ + free(sss_getautomntent_data.data); + free(sss_getautomntent_data.mapname); + memset(&sss_getautomntent_data, 0, sizeof(struct sss_getautomntent_data)); +} + +errno_t +_sss_setautomntent(const char *mapname, void **context) +{ + errno_t ret; + int errnop; + struct automtent *ctx; + char *name; + size_t name_len; + struct sss_cli_req_data rd; + uint8_t *repbuf = NULL; + size_t replen; + uint32_t num_results = 0; + + if (!mapname) return EINVAL; + + sss_nss_lock(); + + /* Make sure there are no leftovers from previous runs */ + sss_getautomntent_data_clean(); + + ret = sss_strnlen(mapname, MAX_AUTOMNTMAPNAME_LEN, &name_len); + if (ret != 0) { + ret = EINVAL; + goto out; + } + + name = malloc(sizeof(char)*name_len + 1); + if (name == NULL) { + ret = ENOMEM; + goto out; + } + strncpy(name, mapname, name_len + 1); + + rd.data = name; + rd.len = name_len + 1; + + ret = sss_autofs_make_request(SSS_AUTOFS_SETAUTOMNTENT, &rd, + &repbuf, &replen, &errnop); + if (ret != SSS_STATUS_SUCCESS) { + free(name); + ret = errnop_to_errno(errnop); + goto out; + } + + /* Get number of results from repbuf. */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* no results if not found */ + if (num_results == 0) { + free(name); + free(repbuf); + ret = ENOENT; + goto out; + } + free(repbuf); + + ctx = malloc(sizeof(struct automtent)); + if (!ctx) { + free(name); + ret = ENOMEM; + goto out; + } + + ctx->mapname = strdup(name); + if (!ctx->mapname) { + free(name); + free(ctx); + ret = ENOMEM; + goto out; + } + ctx->cursor = 0; + free(name); + + *context = ctx; + ret = 0; +out: + sss_nss_unlock(); + return ret; +} + +static errno_t +sss_getautomntent_data_return(const char *mapname, char **_key, char **_value) +{ + size_t dp; + uint32_t len = 0; + char *key = NULL; + uint32_t keylen; + char *value = NULL; + uint32_t vallen; + errno_t ret; + + if (sss_getautomntent_data.mapname == NULL || + sss_getautomntent_data.data == NULL || + sss_getautomntent_data.ptr >= sss_getautomntent_data.len) { + /* We're done with this buffer */ + ret = ENOENT; + goto done; + } + + ret = strcmp(mapname, sss_getautomntent_data.mapname); + if (ret != EOK) { + /* The map we're looking for is not cached. Let responder + * do an implicit setautomntent */ + ret = ENOENT; + goto done; + } + + dp = sss_getautomntent_data.ptr; + + SAFEALIGN_COPY_UINT32(&len, sss_getautomntent_data.data+dp, &dp); + if (len + sss_getautomntent_data.ptr > sss_getautomntent_data.len) { + /* len is bigger than the buffer */ + ret = EIO; + goto done; + } + + if (len == 0) { + /* There are no more records. */ + *_key = NULL; + *_value = NULL; + ret = ENOENT; + goto done; + } + + SAFEALIGN_COPY_UINT32(&keylen, sss_getautomntent_data.data+dp, &dp); + if (keylen + dp > sss_getautomntent_data.len) { + ret = EIO; + goto done; + } + + key = malloc(keylen); + if (!key) { + ret = ENOMEM; + goto done; + } + + safealign_memcpy(key, sss_getautomntent_data.data+dp, keylen, &dp); + + SAFEALIGN_COPY_UINT32(&vallen, sss_getautomntent_data.data+dp, &dp); + if (vallen + dp > sss_getautomntent_data.len) { + ret = EIO; + goto done; + } + + value = malloc(vallen); + if (!value) { + ret = ENOMEM; + goto done; + } + + safealign_memcpy(value, sss_getautomntent_data.data+dp, vallen, &dp); + + sss_getautomntent_data.ptr = dp; + *_key = key; + *_value = value; + return EOK; + +done: + free(key); + free(value); + sss_getautomntent_data_clean(); + return ret; +} + +/* The repbuf is owned by the sss_getautomntent_data once this + * function is called */ +static errno_t +sss_getautomntent_data_save(const char *mapname, uint8_t **repbuf, size_t replen) +{ + size_t rp; + uint32_t num; + + rp = 0; + SAFEALIGN_COPY_UINT32(&num, *repbuf+rp, &rp); + if (num == 0) { + free(*repbuf); + return ENOENT; + } + + sss_getautomntent_data.mapname = strdup(mapname); + if (sss_getautomntent_data.mapname == NULL) { + free(*repbuf); + return ENOENT; + } + + sss_getautomntent_data.data = *repbuf; + sss_getautomntent_data.len = replen; + sss_getautomntent_data.ptr = rp; + *repbuf = NULL; + return EOK; +} + +errno_t +_sss_getautomntent_r(char **key, char **value, void *context) +{ + int errnop; + errno_t ret; + size_t name_len; + struct sss_cli_req_data rd; + uint8_t *repbuf = NULL; + size_t replen; + struct automtent *ctx; + size_t ctr = 0; + size_t data_len = 0; + uint8_t *data; + + sss_nss_lock(); + + ctx = (struct automtent *) context; + if (!ctx) { + ret = EINVAL; + goto out; + } + + /* Be paranoid in case someone tries to smuggle in a huge map name */ + ret = sss_strnlen(ctx->mapname, MAX_AUTOMNTMAPNAME_LEN, &name_len); + if (ret != 0) { + ret = EINVAL; + goto out; + } + + ret = sss_getautomntent_data_return(ctx->mapname, key, value); + if (ret == EOK) { + /* The results are available from cache. Just advance the + * cursor and return. */ + ctx->cursor++; + ret = 0; + goto out; + } + /* Don't try to handle any error codes, just go to the responder again */ + + data_len = sizeof(uint32_t) + /* mapname len */ + name_len + 1 + /* mapname\0 */ + sizeof(uint32_t) + /* index into the map */ + sizeof(uint32_t); /* num entries to retrieve */ + + data = malloc(data_len); + if (!data) { + ret = ENOMEM; + goto out; + } + + SAFEALIGN_SET_UINT32(data, name_len, &ctr); + + safealign_memcpy(data+ctr, ctx->mapname, name_len + 1, &ctr); + + SAFEALIGN_SET_UINT32(data+ctr, ctx->cursor, &ctr); + + SAFEALIGN_SET_UINT32(data+ctr, GETAUTOMNTENT_MAX_ENTRIES, &ctr); + + rd.data = data; + rd.len = data_len; + + ret = sss_autofs_make_request(SSS_AUTOFS_GETAUTOMNTENT, &rd, + &repbuf, &replen, &errnop); + free(data); + if (ret != SSS_STATUS_SUCCESS) { + ret = errnop_to_errno(errnop); + goto out; + } + + /* Got reply, let's save it and return from "cache" */ + ret = sss_getautomntent_data_save(ctx->mapname, &repbuf, replen); + if (ret == ENOENT) { + /* No results */ + *key = NULL; + *value = NULL; + goto out; + } else if (ret != EOK) { + /* Unexpected error */ + goto out; + } + + ret = sss_getautomntent_data_return(ctx->mapname, key, value); + if (ret != EOK) { + goto out; + } + + /* Advance the cursor so that we'll fetch the next map + * next time getautomntent is called */ + ctx->cursor++; + ret = 0; +out: + sss_nss_unlock(); + return ret; +} + +errno_t +_sss_getautomntbyname_r(const char *key, char **value, void *context) +{ + int errnop; + errno_t ret; + struct automtent *ctx; + size_t key_len; + size_t name_len; + size_t data_len = 0; + uint8_t *data; + size_t ctr = 0; + struct sss_cli_req_data rd; + uint8_t *repbuf = NULL; + size_t replen; + + char *buf; + uint32_t len; + uint32_t vallen; + size_t rp; + + sss_nss_lock(); + + ctx = (struct automtent *) context; + if (!ctx || !key) { + ret = EINVAL; + goto out; + } + + /* Be paranoid in case someone tries to smuggle in a huge map name */ + ret = sss_strnlen(ctx->mapname, MAX_AUTOMNTMAPNAME_LEN, &name_len); + if (ret != 0) { + ret = EINVAL; + goto out; + } + + ret = sss_strnlen(key, MAX_AUTOMNTKEYNAME_LEN, &key_len); + if (ret != 0) { + ret = EINVAL; + goto out; + } + + + data_len = sizeof(uint32_t) + /* mapname len */ + name_len + 1 + /* mapname\0 */ + sizeof(uint32_t) + /* keyname len */ + key_len + 1; /* keyname\0 */ + + data = malloc(data_len); + if (!data) { + ret = ENOMEM; + goto out; + } + + SAFEALIGN_SET_UINT32(data, name_len, &ctr); + + safealign_memcpy(data+ctr, ctx->mapname, name_len + 1, &ctr); + + SAFEALIGN_SET_UINT32(data+ctr, key_len, &ctr); + + safealign_memcpy(data+ctr, key, key_len + 1, &ctr); + + rd.data = data; + rd.len = data_len; + + ret = sss_autofs_make_request(SSS_AUTOFS_GETAUTOMNTBYNAME, &rd, + &repbuf, &replen, &errnop); + free(data); + if (ret != SSS_STATUS_SUCCESS) { + ret = errnop_to_errno(errnop); + goto out; + } + + /* Got reply, let's parse it */ + rp = 0; + SAFEALIGN_COPY_UINT32(&len, repbuf+rp, &rp); + if (len == 0) { + /* No data */ + *value = NULL; + ret = ENOENT; + goto out; + } + + SAFEALIGN_COPY_UINT32(&vallen, repbuf+rp, &rp); + if (vallen > len-rp) { + ret = EIO; + goto out; + } + + buf = malloc(vallen); + if (!buf) { + ret = ENOMEM; + goto out; + } + + safealign_memcpy(buf, repbuf+rp, vallen, &rp); + *value = buf; + + ret = 0; +out: + free(repbuf); + sss_nss_unlock(); + return ret; +} + +errno_t +_sss_endautomntent(void **context) +{ + struct automtent *fctx; + errno_t ret; + int errnop; + + if (!context) return 0; + + sss_nss_lock(); + + sss_getautomntent_data_clean(); + + fctx = (struct automtent *) *context; + + if (fctx != NULL) { + free(fctx->mapname); + free(fctx); + } + + ret = sss_autofs_make_request(SSS_AUTOFS_ENDAUTOMNTENT, + NULL, NULL, NULL, &errnop); + if (ret != SSS_STATUS_SUCCESS) { + ret = errnop_to_errno(errnop); + goto out; + } + + ret = 0; +out: + sss_nss_unlock(); + return ret; +} diff --git a/src/sss_client/autofs/sss_autofs.exports b/src/sss_client/autofs/sss_autofs.exports new file mode 100644 index 0000000..ec61f71 --- /dev/null +++ b/src/sss_client/autofs/sss_autofs.exports @@ -0,0 +1,15 @@ +EXPORTED { + + # public functions + global: + _sss_auto_protocol_version; + _sss_setautomntent; + _sss_getautomntent_r; + _sss_getautomntbyname_r; + _sss_endautomntent; + + # everything else is local + local: + *; +}; + diff --git a/src/sss_client/autofs/sss_autofs_private.h b/src/sss_client/autofs/sss_autofs_private.h new file mode 100644 index 0000000..7fd49db --- /dev/null +++ b/src/sss_client/autofs/sss_autofs_private.h @@ -0,0 +1,50 @@ +/* + Authors: + Jakub Hrozek <jhrozek@redhat.com> + + Copyright (C) 2012 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include <errno.h> +#include "util/util.h" + +/** + * Choose an autofs protocol version to be used between autofs and sss_autofs. + */ +unsigned int _sss_auto_protocol_version(unsigned int requested); + +/** + * Selects a map for processing. + */ +errno_t _sss_setautomntent(const char *mapname, void **context); + +/** + * Iterates through key/value pairs in the selected map. The key is usually + * the mount point, the value is mount information (server:/export) + */ +errno_t _sss_getautomntent_r(char **key, char **value, void *context); + +/** + * Returns value for a specific key + */ +errno_t +_sss_getautomntbyname_r(const char *key, char **value, void *context); + +/** + * Deselect a map, end the processing + */ +errno_t _sss_endautomntent(void **context); + diff --git a/src/sss_client/common.c b/src/sss_client/common.c new file mode 100644 index 0000000..702d059 --- /dev/null +++ b/src/sss_client/common.c @@ -0,0 +1,1445 @@ +/* + * System Security Services Daemon. NSS client interface + * + * Copyright (C) Simo Sorce 2007 + * + * Winbind derived code: + * Copyright (C) Tim Potter 2000 + * Copyright (C) Andrew Tridgell 2000 + * Copyright (C) Andrew Bartlett 2002 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "config.h" + +#include <nss.h> +#include <security/pam_modules.h> +#include <errno.h> +#include <stdatomic.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <sys/un.h> +#include <sys/stat.h> +#include <unistd.h> +#include <stdlib.h> +#include <stdbool.h> +#include <stdint.h> +#include <string.h> +#include <fcntl.h> +#include <poll.h> +#include <time.h> + +#include <libintl.h> +#define _(STRING) dgettext (PACKAGE, STRING) +#include "sss_cli.h" +#include "common_private.h" +#include "util/util_errors.h" + +/* +* Note we set MSG_NOSIGNAL to avoid +* having to fiddle with signal masks +* but also do not want to die in case +* SIGPIPE gets raised and the application +* does not handle it. +*/ +#ifdef MSG_NOSIGNAL +#define SSS_DEFAULT_WRITE_FLAGS MSG_NOSIGNAL +#else +#define SSS_DEFAULT_WRITE_FLAGS 0 +#endif + +/* common functions */ + +static int sss_cli_sd_get(void); +static void sss_cli_sd_set(int sd); +static const struct stat *sss_cli_sb_get(void); +static int sss_cli_sb_set_by_sd(int sd); + +#ifdef HAVE_PTHREAD_EXT +static pthread_key_t sss_sd_key; +static pthread_once_t sss_sd_key_init = PTHREAD_ONCE_INIT; +static atomic_bool sss_sd_key_initialized = false; +struct sss_socket_descriptor_t { + int sd; + struct stat sb; +}; +#else +static int _sss_cli_sd = -1; /* the sss client socket descriptor */ +static struct stat _sss_cli_sb; /* the sss client stat buffer */ +#endif + +void sss_cli_close_socket(void) +{ + int sd = sss_cli_sd_get(); + + if (sd != -1) { + close(sd); + sss_cli_sd_set(-1); + } +} + +#ifdef HAVE_PTHREAD_EXT +static void sss_at_thread_exit(void *v) +{ + sss_cli_close_socket(); + free(v); + pthread_setspecific(sss_sd_key, NULL); +} + +static void init_sd_key(void) +{ + if (pthread_key_create(&sss_sd_key, sss_at_thread_exit) == 0) { + sss_sd_key_initialized = true; + } +} +#endif + +#if HAVE_FUNCTION_ATTRIBUTE_DESTRUCTOR +__attribute__((destructor)) void sss_at_lib_unload(void) +{ + sss_cli_close_socket(); +#ifdef HAVE_PTHREAD_EXT + if (sss_sd_key_initialized) { + sss_sd_key_initialized = false; + free(pthread_getspecific(sss_sd_key)); + pthread_setspecific(sss_sd_key, NULL); + pthread_key_delete(sss_sd_key); + } +#endif +} +#endif + + +/* Requests: + * + * byte 0-3: 32bit unsigned with length (the complete packet length: 0 to X) + * byte 4-7: 32bit unsigned with command code + * byte 8-11: 32bit unsigned (reserved) + * byte 12-15: 32bit unsigned (reserved) + * byte 16-X: (optional) request structure associated to the command code used + */ +static enum sss_status sss_cli_send_req(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + int timeout, + int *errnop) +{ + uint32_t header[4]; + size_t datasent; + + header[0] = SSS_NSS_HEADER_SIZE + (rd?rd->len:0); + header[1] = cmd; + header[2] = 0; + header[3] = 0; + + datasent = 0; + + while (datasent < header[0]) { + struct pollfd pfd; + int rdsent; + int res, error; + + *errnop = 0; + pfd.fd = sss_cli_sd_get(); + pfd.events = POLLOUT; + + do { + errno = 0; + res = poll(&pfd, 1, timeout); + error = errno; + + /* If error is EINTR here, we'll try again + * If it's any other error, we'll catch it + * below. + */ + } while (error == EINTR); + + switch (res) { + case -1: + *errnop = error; + break; + case 0: + *errnop = ETIME; + break; + case 1: + if (pfd.revents & (POLLERR | POLLHUP)) { + *errnop = EPIPE; + } else if (pfd.revents & POLLNVAL) { + /* Invalid request: fd is not opened */ + sss_cli_sd_set(-1); + *errnop = EPIPE; + } else if (!(pfd.revents & POLLOUT)) { + *errnop = EBUSY; + } + break; + default: /* more than one available!? */ + *errnop = EBADF; + break; + } + if (*errnop) { + sss_cli_close_socket(); + return SSS_STATUS_UNAVAIL; + } + + errno = 0; + if (datasent < SSS_NSS_HEADER_SIZE) { + res = send(sss_cli_sd_get(), + (char *)header + datasent, + SSS_NSS_HEADER_SIZE - datasent, + SSS_DEFAULT_WRITE_FLAGS); + } else { + rdsent = datasent - SSS_NSS_HEADER_SIZE; + res = send(sss_cli_sd_get(), + (const char *)rd->data + rdsent, + rd->len - rdsent, + SSS_DEFAULT_WRITE_FLAGS); + } + error = errno; + + if ((res == -1) || (res == 0)) { + if ((error == EINTR) || error == EAGAIN) { + /* If the write was interrupted, go back through + * the loop and try again + */ + continue; + } + + /* Write failed */ + sss_cli_close_socket(); + *errnop = error; + return SSS_STATUS_UNAVAIL; + } + + datasent += res; + } + + return SSS_STATUS_SUCCESS; +} + +/* Replies: + * + * byte 0-3: 32bit unsigned with length (the complete packet length: 0 to X) + * byte 4-7: 32bit unsigned with command code + * byte 8-11: 32bit unsigned with the request status (server errno) + * byte 12-15: 32bit unsigned (reserved) + * byte 16-X: (optional) reply structure associated to the command code used + */ + +static enum sss_status sss_cli_recv_rep(enum sss_cli_command cmd, + int timeout, + uint8_t **_buf, int *_len, + int *errnop) +{ + uint32_t header[4]; + size_t datarecv; + uint8_t *buf = NULL; + bool pollhup = false; + int len; + int ret; + + header[0] = SSS_NSS_HEADER_SIZE; /* until we know the real length */ + header[1] = 0; + header[2] = 0; + header[3] = 0; + + datarecv = 0; + buf = NULL; + len = 0; + *errnop = 0; + + while (datarecv < header[0]) { + struct pollfd pfd; + int bufrecv; + int res, error; + + pfd.fd = sss_cli_sd_get(); + pfd.events = POLLIN; + + do { + errno = 0; + res = poll(&pfd, 1, timeout); + error = errno; + + /* If error is EINTR here, we'll try again + * If it's any other error, we'll catch it + * below. + */ + } while (error == EINTR); + + switch (res) { + case -1: + *errnop = error; + break; + case 0: + *errnop = ETIME; + break; + case 1: + if (pfd.revents & (POLLHUP)) { + pollhup = true; + } + if (pfd.revents & POLLERR) { + *errnop = EPIPE; + } else if (pfd.revents & POLLNVAL) { + /* Invalid request: fd is not opened */ + sss_cli_sd_set(-1); + *errnop = EPIPE; + } else if (!(pfd.revents & POLLIN)) { + *errnop = EBUSY; + } + break; + default: /* more than one available!? */ + *errnop = EBADF; + break; + } + if (*errnop) { + sss_cli_close_socket(); + ret = SSS_STATUS_UNAVAIL; + goto failed; + } + + errno = 0; + if (datarecv < SSS_NSS_HEADER_SIZE) { + res = read(sss_cli_sd_get(), + (char *)header + datarecv, + SSS_NSS_HEADER_SIZE - datarecv); + } else { + bufrecv = datarecv - SSS_NSS_HEADER_SIZE; + res = read(sss_cli_sd_get(), + (char *) buf + bufrecv, + header[0] - datarecv); + } + error = errno; + + if ((res == -1) || (res == 0)) { + if ((error == EINTR) || error == EAGAIN) { + /* If the read was interrupted, go back through + * the loop and try again + */ + continue; + } + + /* Read failed. I think the only useful thing + * we can do here is just return -1 and fail + * since the transaction has failed half way + * through. */ + + sss_cli_close_socket(); + *errnop = error; + ret = SSS_STATUS_UNAVAIL; + goto failed; + } + + datarecv += res; + + if (datarecv == SSS_NSS_HEADER_SIZE && len == 0) { + /* at this point recv buf is not yet + * allocated and the header has just + * been read, do checks and proceed */ + if (header[2] != 0) { + /* server side error */ + sss_cli_close_socket(); + *errnop = header[2]; + if (*errnop == EAGAIN) { + ret = SSS_STATUS_TRYAGAIN; + goto failed; + } else { + ret = SSS_STATUS_UNAVAIL; + goto failed; + } + } + if (header[1] != cmd) { + /* wrong command id */ + sss_cli_close_socket(); + *errnop = EBADMSG; + ret = SSS_STATUS_UNAVAIL; + goto failed; + } + if (header[0] > SSS_NSS_HEADER_SIZE) { + len = header[0] - SSS_NSS_HEADER_SIZE; + buf = malloc(len); + if (!buf) { + sss_cli_close_socket(); + *errnop = ENOMEM; + ret = SSS_STATUS_UNAVAIL; + goto failed; + } + } + } + } + + if (pollhup) { + sss_cli_close_socket(); + } + + *_len = len; + *_buf = buf; + + return SSS_STATUS_SUCCESS; + +failed: + free(buf); + return ret; +} + +/* this function will check command codes match and returned length is ok */ +/* repbuf and replen report only the data section not the header */ +static enum sss_status sss_cli_make_request_nochecks( + enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + int timeout, + uint8_t **repbuf, size_t *replen, + int *errnop) +{ + enum sss_status ret; + uint8_t *buf = NULL; + int len = 0; + + /* send data */ + ret = sss_cli_send_req(cmd, rd, timeout, errnop); + if (ret != SSS_STATUS_SUCCESS) { + return ret; + } + + /* data sent, now get reply */ + ret = sss_cli_recv_rep(cmd, timeout, &buf, &len, errnop); + if (ret != SSS_STATUS_SUCCESS) { + return ret; + } + + /* we got through, now we have the custom data in buf if any, + * return it if requested */ + if (repbuf && buf) { + *repbuf = buf; + if (replen) { + *replen = len; + } + } else { + free(buf); + if (replen) { + *replen = 0; + } + } + + return SSS_STATUS_SUCCESS; +} + +/* GET_VERSION Reply: + * 0-3: 32bit unsigned version number + */ + +static bool sss_cli_check_version(const char *socket_name, int timeout) +{ + uint8_t *repbuf = NULL; + size_t replen; + enum sss_status nret; + int errnop; + uint32_t expected_version; + uint32_t obtained_version; + struct sss_cli_req_data req; + + if (strcmp(socket_name, SSS_NSS_SOCKET_NAME) == 0) { + expected_version = SSS_NSS_PROTOCOL_VERSION; + } else if (strcmp(socket_name, SSS_PAM_SOCKET_NAME) == 0 || + strcmp(socket_name, SSS_PAM_PRIV_SOCKET_NAME) == 0) { + expected_version = SSS_PAM_PROTOCOL_VERSION; + } else if (strcmp(socket_name, SSS_SUDO_SOCKET_NAME) == 0) { + expected_version = SSS_SUDO_PROTOCOL_VERSION; + } else if (strcmp(socket_name, SSS_AUTOFS_SOCKET_NAME) == 0) { + expected_version = SSS_AUTOFS_PROTOCOL_VERSION; + } else if (strcmp(socket_name, SSS_SSH_SOCKET_NAME) == 0) { + expected_version = SSS_SSH_PROTOCOL_VERSION; + } else if (strcmp(socket_name, SSS_PAC_SOCKET_NAME) == 0) { + expected_version = SSS_PAC_PROTOCOL_VERSION; + } else { + return false; + } + + req.len = sizeof(expected_version); + req.data = &expected_version; + + nret = sss_cli_make_request_nochecks(SSS_GET_VERSION, &req, timeout, + &repbuf, &replen, &errnop); + if (nret != SSS_STATUS_SUCCESS) { + return false; + } + + if (!repbuf) { + return false; + } + + SAFEALIGN_COPY_UINT32(&obtained_version, repbuf, NULL); + free(repbuf); + + return (obtained_version == expected_version); +} + +/* this 2 functions are adapted from samba3 winbind's wb_common.c */ + +/* Make sure socket handle isn't stdin (0), stdout(1) or stderr(2) by setting + * the limit to 3 */ +#define RECURSION_LIMIT 3 + +static int make_nonstd_fd_internals(int fd, int limit) +{ + int new_fd; + if (fd >= 0 && fd <= 2) { +#ifdef F_DUPFD + if ((new_fd = fcntl(fd, F_DUPFD, 3)) == -1) { + return -1; + } + /* Paranoia */ + if (new_fd < 3) { + close(new_fd); + return -1; + } + close(fd); + return new_fd; +#else + if (limit <= 0) + return -1; + + new_fd = dup(fd); + if (new_fd == -1) + return -1; + + /* use the program stack to hold our list of FDs to close */ + new_fd = make_nonstd_fd_internals(new_fd, limit - 1); + close(fd); + return new_fd; +#endif + } + return fd; +} + +/**************************************************************************** + Ensures fd isn't std[in/out/err] (duplicates it if needed) and + set it into nonblocking mode. Uses POSIX O_NONBLOCK if available, + else + if SYSV use O_NDELAY + if BSD use FNDELAY + Set close on exec also. +****************************************************************************/ + +static int make_safe_fd(int fd) +{ + int result, flags; + int new_fd = make_nonstd_fd_internals(fd, RECURSION_LIMIT); + if (new_fd == -1) { + close(fd); + return -1; + } + + /* Socket should be nonblocking. */ +#ifdef O_NONBLOCK +#define FLAG_TO_SET O_NONBLOCK +#else +#ifdef SYSV +#define FLAG_TO_SET O_NDELAY +#else /* BSD */ +#define FLAG_TO_SET FNDELAY +#endif +#endif + + if ((flags = fcntl(new_fd, F_GETFL)) == -1) { + close(new_fd); + return -1; + } + + flags |= FLAG_TO_SET; + if (fcntl(new_fd, F_SETFL, flags) == -1) { + close(new_fd); + return -1; + } + +#undef FLAG_TO_SET + + /* Socket should be closed on exec() */ +#ifdef FD_CLOEXEC + result = flags = fcntl(new_fd, F_GETFD, 0); + if (flags >= 0) { + flags |= FD_CLOEXEC; + result = fcntl( new_fd, F_SETFD, flags ); + } + if (result < 0) { + close(new_fd); + return -1; + } +#endif + return new_fd; +} + +static int sss_cli_open_socket(int *errnop, const char *socket_name, int timeout) +{ + struct sockaddr_un nssaddr; + bool inprogress = true; + bool connected = false; + unsigned int wait_time; + unsigned int sleep_time; + time_t start_time = time(NULL); + int ret; + int sd; + + if (sizeof(nssaddr.sun_path) < strlen(socket_name) + 1) { + *errnop = EINVAL; + return -1; + } + + memset(&nssaddr, 0, sizeof(struct sockaddr_un)); + nssaddr.sun_family = AF_UNIX; + strcpy(nssaddr.sun_path, socket_name); /* safe due to above check */ + + sd = socket(AF_UNIX, SOCK_STREAM, 0); + if (sd == -1) { + *errnop = errno; + return -1; + } + + /* set as non-blocking, close on exec, and make sure standard + * descriptors are not used */ + sd = make_safe_fd(sd); + if (sd == -1) { + *errnop = errno; + return -1; + } + + /* this piece is adapted from winbind client code */ + wait_time = 0; + sleep_time = 0; + while (inprogress) { + int connect_errno = 0; + socklen_t errnosize; + struct pollfd pfd; + + wait_time += sleep_time * 1000; + + ret = connect(sd, (struct sockaddr *)&nssaddr, + sizeof(nssaddr)); + if (ret == 0) { + connected = true; + break; + } + + switch(errno) { + case EINPROGRESS: + pfd.fd = sd; + pfd.events = POLLOUT; + + ret = poll(&pfd, 1, timeout - wait_time); + + if (ret > 0) { + errnosize = sizeof(connect_errno); + ret = getsockopt(sd, SOL_SOCKET, SO_ERROR, + &connect_errno, &errnosize); + if (ret >= 0 && connect_errno == 0) { + connected = true; + break; + } + } + wait_time = time(NULL) - start_time; + break; + case EAGAIN: + if (wait_time < timeout) { + sleep_time = 1; + sleep(sleep_time); + } + break; + default: + *errnop = errno; + inprogress = false; + break; + } + + if (wait_time >= timeout) { + inprogress = false; + } + + if (connected) { + inprogress = false; + } + } + + if (!connected) { + close(sd); + return -1; + } + + ret = sss_cli_sb_set_by_sd(sd); + if (ret != 0) { + close(sd); + return -1; + } + + return sd; +} + +static enum sss_status sss_cli_check_socket(int *errnop, + const char *socket_name, + int timeout) +{ + static pid_t mypid_s; + static ino_t myself_ino; + struct stat mypid_sb, myself_sb; + const struct stat *sss_cli_sb = NULL; + pid_t mypid_d; + int mysd; + int ret; +#ifdef HAVE_PTHREAD_EXT + struct sss_socket_descriptor_t *descriptor = NULL; + + ret = pthread_once(&sss_sd_key_init, init_sd_key); /* once for all threads */ + if (ret != 0) { + *errnop = EFAULT; + return SSS_STATUS_UNAVAIL; + } + if (!sss_sd_key_initialized) { + /* pthread_once::init_sd_key::pthread_key_create failed -- game over? */ + *errnop = EFAULT; + return SSS_STATUS_UNAVAIL; + } + + if (pthread_getspecific(sss_sd_key) == NULL) { /* for every thread */ + descriptor = (struct sss_socket_descriptor_t *) + calloc(1, sizeof(struct sss_socket_descriptor_t)); + if (descriptor == NULL) { + *errnop = ENOMEM; + return SSS_STATUS_UNAVAIL; + } + descriptor->sd = -1; + ret = pthread_setspecific(sss_sd_key, descriptor); + if (ret != 0) { + free(descriptor); + *errnop = ENOMEM; + return SSS_STATUS_UNAVAIL; + } + } +#endif + sss_cli_sb = sss_cli_sb_get(); + if (sss_cli_sb == NULL) { + *errnop = EFAULT; + return SSS_STATUS_UNAVAIL; + } + + ret = lstat("/proc/self/", &myself_sb); + mypid_d = getpid(); + if (mypid_d != mypid_s || (ret == 0 && myself_sb.st_ino != myself_ino)) { + ret = fstat(sss_cli_sd_get(), &mypid_sb); + if (ret == 0) { + if (S_ISSOCK(mypid_sb.st_mode) && + mypid_sb.st_dev == sss_cli_sb->st_dev && + mypid_sb.st_ino == sss_cli_sb->st_ino) { + sss_cli_close_socket(); + } + } + sss_cli_sd_set(-1); + mypid_s = mypid_d; + myself_ino = myself_sb.st_ino; + } + + /* check if the socket has been hijacked */ + if (sss_cli_sd_get() != -1) { + ret = fstat(sss_cli_sd_get(), &mypid_sb); + if ((ret != 0) || (!S_ISSOCK(mypid_sb.st_mode)) + || (mypid_sb.st_dev != sss_cli_sb->st_dev) + || (mypid_sb.st_ino != sss_cli_sb->st_ino)) { + sss_cli_sd_set(-1); /* don't ruin app even if it's misbehaving */ + } + } + + /* check if the socket has been closed on the other side */ + if (sss_cli_sd_get() != -1) { + struct pollfd pfd; + int res, error; + + *errnop = 0; + pfd.fd = sss_cli_sd_get(); + pfd.events = POLLIN | POLLOUT; + + do { + errno = 0; + res = poll(&pfd, 1, timeout); + error = errno; + + /* If error is EINTR here, we'll try again + * If it's any other error, we'll catch it + * below. + */ + } while (error == EINTR); + + switch (res) { + case -1: + *errnop = error; + break; + case 0: + *errnop = ETIME; + break; + case 1: + if (pfd.revents & (POLLERR | POLLHUP)) { + *errnop = EPIPE; + } else if (pfd.revents & POLLNVAL) { + /* Invalid request: fd is not opened */ + sss_cli_sd_set(-1); + *errnop = EPIPE; + } else if (!(pfd.revents & (POLLIN | POLLOUT))) { + *errnop = EBUSY; + } + break; + default: /* more than one available!? */ + *errnop = EBADF; + break; + } + if (*errnop == 0) { + return SSS_STATUS_SUCCESS; + } + + sss_cli_close_socket(); + } + + mysd = sss_cli_open_socket(errnop, socket_name, timeout); + if (mysd == -1) { + return SSS_STATUS_UNAVAIL; + } + + sss_cli_sd_set(mysd); + + if (sss_cli_check_version(socket_name, timeout)) { + return SSS_STATUS_SUCCESS; + } + + sss_cli_close_socket(); + *errnop = EFAULT; + return SSS_STATUS_UNAVAIL; +} + +/* this function will check command codes match and returned length is ok */ +/* repbuf and replen report only the data section not the header */ +enum nss_status sss_nss_make_request_timeout(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + int timeout, + uint8_t **repbuf, size_t *replen, + int *errnop) +{ + enum sss_status ret; + char *envval; + + /* avoid looping in the nss daemon */ + envval = getenv("_SSS_LOOPS"); + if (envval && strcmp(envval, "NO") == 0) { + return NSS_STATUS_NOTFOUND; + } + + ret = sss_cli_check_socket(errnop, SSS_NSS_SOCKET_NAME, timeout); + if (ret != SSS_STATUS_SUCCESS) { +#ifdef NONSTANDARD_SSS_NSS_BEHAVIOUR + *errnop = 0; + errno = 0; + return NSS_STATUS_NOTFOUND; +#else + return NSS_STATUS_UNAVAIL; +#endif + } + + ret = sss_cli_make_request_nochecks(cmd, rd, timeout, repbuf, replen, + errnop); + if (ret == SSS_STATUS_UNAVAIL && *errnop == EPIPE) { + /* try reopen socket */ + ret = sss_cli_check_socket(errnop, SSS_NSS_SOCKET_NAME, timeout); + if (ret != SSS_STATUS_SUCCESS) { +#ifdef NONSTANDARD_SSS_NSS_BEHAVIOUR + *errnop = 0; + errno = 0; + return NSS_STATUS_NOTFOUND; +#else + return NSS_STATUS_UNAVAIL; +#endif + } + + /* and make request one more time */ + ret = sss_cli_make_request_nochecks(cmd, rd, timeout, repbuf, replen, + errnop); + } + switch (ret) { + case SSS_STATUS_TRYAGAIN: + return NSS_STATUS_TRYAGAIN; + case SSS_STATUS_SUCCESS: + return NSS_STATUS_SUCCESS; + case SSS_STATUS_UNAVAIL: + default: +#ifdef NONSTANDARD_SSS_NSS_BEHAVIOUR + *errnop = 0; + errno = 0; + return NSS_STATUS_NOTFOUND; +#else + return NSS_STATUS_UNAVAIL; +#endif + } +} + +enum nss_status sss_nss_make_request(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + uint8_t **repbuf, size_t *replen, + int *errnop) +{ + return sss_nss_make_request_timeout(cmd, rd, SSS_CLI_SOCKET_TIMEOUT, + repbuf, replen, errnop); +} + +int sss_pac_check_and_open(void) +{ + enum sss_status ret; + int errnop; + + ret = sss_cli_check_socket(&errnop, SSS_PAC_SOCKET_NAME, + SSS_CLI_SOCKET_TIMEOUT); + if (ret != SSS_STATUS_SUCCESS) { + return EIO; + } + + return EOK; +} + +int sss_pac_make_request(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + uint8_t **repbuf, size_t *replen, + int *errnop) +{ + enum sss_status ret; + char *envval; + int timeout = SSS_CLI_SOCKET_TIMEOUT; + + /* avoid looping in the nss daemon */ + envval = getenv("_SSS_LOOPS"); + if (envval && strcmp(envval, "NO") == 0) { + return NSS_STATUS_NOTFOUND; + } + + ret = sss_cli_check_socket(errnop, SSS_PAC_SOCKET_NAME, timeout); + if (ret != SSS_STATUS_SUCCESS) { + return NSS_STATUS_UNAVAIL; + } + + ret = sss_cli_make_request_nochecks(cmd, rd, timeout, repbuf, replen, + errnop); + if (ret == SSS_STATUS_UNAVAIL && *errnop == EPIPE) { + /* try reopen socket */ + ret = sss_cli_check_socket(errnop, SSS_PAC_SOCKET_NAME, timeout); + if (ret != SSS_STATUS_SUCCESS) { + return NSS_STATUS_UNAVAIL; + } + + /* and make request one more time */ + ret = sss_cli_make_request_nochecks(cmd, rd, timeout, repbuf, replen, + errnop); + } + switch (ret) { + case SSS_STATUS_TRYAGAIN: + return NSS_STATUS_TRYAGAIN; + case SSS_STATUS_SUCCESS: + return NSS_STATUS_SUCCESS; + case SSS_STATUS_UNAVAIL: + default: + return NSS_STATUS_UNAVAIL; + } +} + +int sss_pac_make_request_with_lock(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + uint8_t **repbuf, size_t *replen, + int *errnop) +{ + int ret; + + sss_pac_lock(); + + ret = sss_pac_make_request(cmd, rd, repbuf, replen, errnop); + + sss_pac_unlock(); + + return ret; +} + +errno_t check_server_cred(int sockfd) +{ +#ifdef HAVE_UCRED + int ret; + struct ucred server_cred; + socklen_t server_cred_len = sizeof(server_cred); + + ret = getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &server_cred, + &server_cred_len); + if (ret != 0) { + return errno; + } + + if (server_cred_len != sizeof(struct ucred)) { + return ESSS_BAD_CRED_MSG; + } + + if (server_cred.uid != 0 || server_cred.gid != 0) { + return ESSS_SERVER_NOT_TRUSTED; + } +#endif + return 0; +} + +int sss_pam_make_request(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + uint8_t **repbuf, size_t *replen, + int *errnop) +{ + int ret, statret; + errno_t error; + enum sss_status status; + char *envval; + struct stat stat_buf; + const char *socket_name; + int timeout = SSS_CLI_SOCKET_TIMEOUT; + + sss_pam_lock(); + + /* avoid looping in the pam daemon */ + envval = getenv("_SSS_LOOPS"); + if (envval && strcmp(envval, "NO") == 0) { + ret = PAM_SERVICE_ERR; + goto out; + } + + /* only UID 0 shall use the privileged pipe */ + if (getuid() == 0) { + socket_name = SSS_PAM_PRIV_SOCKET_NAME; + errno = 0; + statret = stat(socket_name, &stat_buf); + if (statret != 0) { + if (errno == ENOENT) { + *errnop = ESSS_NO_SOCKET; + } else { + *errnop = ESSS_SOCKET_STAT_ERROR; + } + ret = PAM_SERVICE_ERR; + goto out; + } + if ( ! (stat_buf.st_uid == 0 && + stat_buf.st_gid == 0 && + S_ISSOCK(stat_buf.st_mode) && + (stat_buf.st_mode & ~S_IFMT) == 0600 )) { + *errnop = ESSS_BAD_PRIV_SOCKET; + ret = PAM_SERVICE_ERR; + goto out; + } + } else { + socket_name = SSS_PAM_SOCKET_NAME; + errno = 0; + statret = stat(socket_name, &stat_buf); + if (statret != 0) { + if (errno == ENOENT) { + *errnop = ESSS_NO_SOCKET; + } else { + *errnop = ESSS_SOCKET_STAT_ERROR; + } + ret = PAM_SERVICE_ERR; + goto out; + } + if ( ! (stat_buf.st_uid == 0 && + stat_buf.st_gid == 0 && + S_ISSOCK(stat_buf.st_mode) && + (stat_buf.st_mode & ~S_IFMT) == 0666 )) { + *errnop = ESSS_BAD_PUB_SOCKET; + ret = PAM_SERVICE_ERR; + goto out; + } + } + + status = sss_cli_check_socket(errnop, socket_name, timeout); + if (status != SSS_STATUS_SUCCESS) { + ret = PAM_SERVICE_ERR; + goto out; + } + + error = check_server_cred(sss_cli_sd_get()); + if (error != 0) { + sss_cli_close_socket(); + *errnop = error; + ret = PAM_SERVICE_ERR; + goto out; + } + + status = sss_cli_make_request_nochecks(cmd, rd, timeout, repbuf, replen, + errnop); + if (status == SSS_STATUS_UNAVAIL && *errnop == EPIPE) { + /* try reopen socket */ + status = sss_cli_check_socket(errnop, socket_name, timeout); + if (status != SSS_STATUS_SUCCESS) { + ret = PAM_SERVICE_ERR; + goto out; + } + + /* and make request one more time */ + status = sss_cli_make_request_nochecks(cmd, rd, timeout, repbuf, replen, + errnop); + } + + if (status == SSS_STATUS_SUCCESS) { + ret = PAM_SUCCESS; + } else { + ret = PAM_SERVICE_ERR; + } + +out: + sss_pam_unlock(); + return ret; +} + +enum sss_status +sss_cli_make_request_with_checks(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + int timeout, + uint8_t **repbuf, size_t *replen, + int *errnop, + const char *socket_name) +{ + enum sss_status ret = SSS_STATUS_UNAVAIL; + + ret = sss_cli_check_socket(errnop, socket_name, timeout); + if (ret != SSS_STATUS_SUCCESS) { + return SSS_STATUS_UNAVAIL; + } + + ret = sss_cli_make_request_nochecks(cmd, rd, timeout, repbuf, replen, + errnop); + if (ret == SSS_STATUS_UNAVAIL && *errnop == EPIPE) { + /* try reopen socket */ + ret = sss_cli_check_socket(errnop, socket_name, timeout); + if (ret != SSS_STATUS_SUCCESS) { + return SSS_STATUS_UNAVAIL; + } + + /* and make request one more time */ + ret = sss_cli_make_request_nochecks(cmd, rd, timeout, repbuf, replen, + errnop); + } + + return ret; +} + +int sss_sudo_make_request(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + uint8_t **repbuf, size_t *replen, + int *errnop) +{ + return sss_cli_make_request_with_checks(cmd, rd, SSS_CLI_SOCKET_TIMEOUT, + repbuf, replen, errnop, + SSS_SUDO_SOCKET_NAME); +} + +int sss_autofs_make_request(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + uint8_t **repbuf, size_t *replen, + int *errnop) +{ + enum sss_status status; + + status = sss_cli_make_request_with_checks(cmd, rd, SSS_CLI_SOCKET_TIMEOUT, + repbuf, replen, errnop, + SSS_AUTOFS_SOCKET_NAME); + + if (*errnop == ERR_OFFLINE) { + *errnop = EHOSTDOWN; + } + + return status; +} + +int sss_ssh_make_request(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + uint8_t **repbuf, size_t *replen, + int *errnop) +{ + return sss_cli_make_request_with_checks(cmd, rd, SSS_CLI_SOCKET_TIMEOUT, + repbuf, replen, errnop, + SSS_SSH_SOCKET_NAME); +} + + +const char *ssscli_err2string(int err) +{ + const char *m; + + switch(err) { + case ESSS_BAD_PRIV_SOCKET: + return _("Privileged socket has wrong ownership or permissions."); + break; + case ESSS_BAD_PUB_SOCKET: + return _("Public socket has wrong ownership or permissions."); + break; + case ESSS_BAD_CRED_MSG: + return _("Unexpected format of the server credential message."); + break; + case ESSS_SERVER_NOT_TRUSTED: + return _("SSSD is not run by root."); + break; + case ESSS_NO_SOCKET: + return _("SSSD socket does not exist."); + break; + case ESSS_SOCKET_STAT_ERROR: + return _("Cannot get stat of SSSD socket."); + break; + default: + m = strerror(err); + if (m == NULL) { + return _("An error occurred, but no description can be found."); + } + return m; + break; + } + + return _("Unexpected error while looking for an error description"); +} + +/* Return strlen(str) or maxlen, whichever is shorter + * Returns EINVAL if str is NULL, EFBIG if str is longer than maxlen + * _len will return the result + * + * This function is useful for preventing buffer overflow attacks. + */ +errno_t sss_strnlen(const char *str, size_t maxlen, size_t *len) +{ + if (!str) { + return EINVAL; + } + +#if defined __USE_GNU + *len = strnlen(str, maxlen); +#else + *len = 0; + while (*len < maxlen) { + if (str[*len] == '\0') break; + (*len)++; + } +#endif + + if (*len == maxlen && str[*len] != '\0') { + return EFBIG; + } + + return 0; +} + +#if HAVE_PTHREAD + +#ifdef HAVE_PTHREAD_EXT +static bool sss_lock_free = true; +static pthread_once_t sss_lock_mode_initialized = PTHREAD_ONCE_INIT; + +static void init_lock_mode(void) +{ + const char *env = getenv("SSS_LOCKFREE"); + + if ((env != NULL) && (strcasecmp(env, "NO") == 0)) { + sss_lock_free = false; + } +} + +bool sss_is_lockfree_mode(void) +{ + pthread_once(&sss_lock_mode_initialized, init_lock_mode); + return sss_lock_free; +} +#endif + +struct sss_mutex sss_nss_mtx = { .mtx = PTHREAD_MUTEX_INITIALIZER }; +static struct sss_mutex sss_pam_mtx = { .mtx = PTHREAD_MUTEX_INITIALIZER }; +static struct sss_mutex sss_pac_mtx = { .mtx = PTHREAD_MUTEX_INITIALIZER }; + +static void sss_mt_lock(struct sss_mutex *m) +{ +#ifdef HAVE_PTHREAD_EXT + if (sss_is_lockfree_mode()) { + return; + } +#endif + + pthread_mutex_lock(&m->mtx); + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &m->old_cancel_state); +} + +static void sss_mt_unlock(struct sss_mutex *m) +{ +#ifdef HAVE_PTHREAD_EXT + if (sss_is_lockfree_mode()) { + return; + } +#endif + + pthread_setcancelstate(m->old_cancel_state, NULL); + pthread_mutex_unlock(&m->mtx); +} + +/* NSS mutex wrappers */ +void sss_nss_lock(void) +{ + sss_mt_lock(&sss_nss_mtx); +} +void sss_nss_unlock(void) +{ + sss_mt_unlock(&sss_nss_mtx); +} + +/* PAM mutex wrappers */ +void sss_pam_lock(void) +{ + sss_mt_lock(&sss_pam_mtx); +} +void sss_pam_unlock(void) +{ + sss_mt_unlock(&sss_pam_mtx); +} + +/* PAC mutex wrappers */ +void sss_pac_lock(void) +{ + sss_mt_lock(&sss_pac_mtx); +} +void sss_pac_unlock(void) +{ + sss_mt_unlock(&sss_pac_mtx); +} + +#else + +/* sorry no mutexes available */ +void sss_nss_lock(void) { return; } +void sss_nss_unlock(void) { return; } +void sss_pam_lock(void) { return; } +void sss_pam_unlock(void) { return; } +void sss_nss_mc_lock(void) { return; } +void sss_nss_mc_unlock(void) { return; } +void sss_pac_lock(void) { return; } +void sss_pac_unlock(void) { return; } +#endif + + +errno_t sss_readrep_copy_string(const char *in, + size_t *offset, + size_t *slen, + size_t *dlen, + char **out, + size_t *size) +{ + size_t i = 0; + while (*slen > *offset && *dlen > 0) { + (*out)[i] = in[*offset]; + if ((*out)[i] == '\0') break; + i++; + (*offset)++; + (*dlen)--; + } + if (*slen <= *offset) { /* premature end of buf */ + return EBADMSG; + } + if (*dlen == 0) { /* not enough memory */ + return ERANGE; /* not ENOMEM, ERANGE is what glibc looks for */ + } + (*offset)++; + (*dlen)--; + if (size) { + *size = i; + } + + return EOK; +} + +#ifdef HAVE_PTHREAD_EXT + +static int sss_cli_sd_get(void) +{ + if (!sss_sd_key_initialized) { + return -1; + } + + struct sss_socket_descriptor_t *descriptor = pthread_getspecific(sss_sd_key); + + if (descriptor == NULL) { /* sanity check */ + return -1; + } + + return descriptor->sd; +} + +static void sss_cli_sd_set(int sd) +{ + if (!sss_sd_key_initialized) { + return; + } + + struct sss_socket_descriptor_t *descriptor = pthread_getspecific(sss_sd_key); + + if (descriptor == NULL) { /* sanity check */ + return; + } + + descriptor->sd = sd; +} + +static const struct stat *sss_cli_sb_get(void) +{ + if (!sss_sd_key_initialized) { + return NULL; + } + + struct sss_socket_descriptor_t *descriptor = pthread_getspecific(sss_sd_key); + + if (descriptor == NULL) { /* sanity check */ + return NULL; + } + + return &descriptor->sb; +} + +static int sss_cli_sb_set_by_sd(int sd) +{ + if (!sss_sd_key_initialized) { + return -1; + } + + struct sss_socket_descriptor_t *descriptor = pthread_getspecific(sss_sd_key); + + if (descriptor == NULL) { /* sanity check */ + return -1; + } + + return fstat(sd, &descriptor->sb); +} + +#else + +static int sss_cli_sd_get(void) +{ + return _sss_cli_sd; +} + +static void sss_cli_sd_set(int sd) +{ + _sss_cli_sd = sd; +} + +static const struct stat *sss_cli_sb_get(void) +{ + return &_sss_cli_sb; +} + +static int sss_cli_sb_set_by_sd(int sd) +{ + return fstat(sd, &_sss_cli_sb); +} + +#endif diff --git a/src/sss_client/common_private.h b/src/sss_client/common_private.h new file mode 100644 index 0000000..a98d2c0 --- /dev/null +++ b/src/sss_client/common_private.h @@ -0,0 +1,41 @@ +/* + SSSD + + SSS client - private calls + + Authors: + Sumit Bose <sbose@redhat.com> + + Copyright (C) 2017 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#ifndef COMMON_PRIVATE_H_ +#define COMMON_PRIVATE_H_ + +#include "config.h" + +#if HAVE_PTHREAD +#include <pthread.h> + +struct sss_mutex { + pthread_mutex_t mtx; + + int old_cancel_state; +}; + +#endif /* HAVE_PTHREAD */ + +#endif /* COMMON_PRIVATE_H_ */ diff --git a/src/sss_client/idmap/common_ex.c b/src/sss_client/idmap/common_ex.c new file mode 100644 index 0000000..8c4894f --- /dev/null +++ b/src/sss_client/idmap/common_ex.c @@ -0,0 +1,118 @@ +/* + Authors: + Sumit Bose <sbose@redhat.com> + + Copyright (C) 2017 Red Hat + + SSSD's enhanced NSS API + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include <time.h> +#include <errno.h> +#include <stdbool.h> + +#include "sss_cli.h" +#include "common_private.h" + +extern struct sss_mutex sss_nss_mtx; +#ifdef HAVE_PTHREAD_EXT +bool sss_is_lockfree_mode(void); +#endif + +#define SEC_FROM_MSEC(ms) ((ms) / 1000) +#define NSEC_FROM_MSEC(ms) (((ms) % 1000) * 1000 * 1000) + +/* adopted from timersub() defined in /usr/include/sys/time.h */ +#define TIMESPECSUB(a, b, result) \ + do { \ + (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ + (result)->tv_nsec = (a)->tv_nsec - (b)->tv_nsec; \ + if ((result)->tv_nsec < 0) { \ + --(result)->tv_sec; \ + (result)->tv_nsec += 1000000000; \ + } \ + } while (0) + +#define TIMESPEC_TO_MS(ts) ( ((ts)->tv_sec * 1000) \ + + ((ts)->tv_nsec) / (1000 * 1000) ) + +static int sss_mt_timedlock(struct sss_mutex *m, const struct timespec *endtime) +{ + int ret; + +#ifdef HAVE_PTHREAD_EXT + if (sss_is_lockfree_mode()) { + return 0; + } +#endif + + ret = pthread_mutex_timedlock(&m->mtx, endtime); + if (ret != 0) { + return ret; + } + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &m->old_cancel_state); + + return 0; +} + +int sss_nss_timedlock(unsigned int timeout_ms, int *time_left_ms) +{ + int ret; + int left; + struct timespec starttime; + struct timespec endtime; + struct timespec diff; + + /* make sure there is no overrun when calculating the time left */ + if (timeout_ms > INT_MAX) { + timeout_ms = INT_MAX; + } + + ret = clock_gettime(CLOCK_REALTIME, &starttime); + if (ret != 0) { + return errno; + } + endtime.tv_sec = starttime.tv_sec + SEC_FROM_MSEC(timeout_ms); + endtime.tv_nsec = starttime.tv_nsec + NSEC_FROM_MSEC(timeout_ms); + + ret = sss_mt_timedlock(&sss_nss_mtx, &endtime); + + if (ret == 0) { + ret = clock_gettime(CLOCK_REALTIME, &endtime); + if (ret != 0) { + ret = errno; + sss_nss_unlock(); + return ret; + } + + if (timeout_ms == 0) { + *time_left_ms = 0; + } else { + TIMESPECSUB(&endtime, &starttime, &diff); + left = timeout_ms - TIMESPEC_TO_MS(&diff); + if (left <= 0) { + sss_nss_unlock(); + return EIO; + } else if (left > SSS_CLI_SOCKET_TIMEOUT) { + *time_left_ms = SSS_CLI_SOCKET_TIMEOUT; + } else { + *time_left_ms = left; + } + } + } + + return ret; +} diff --git a/src/sss_client/idmap/sss_nss_ex.c b/src/sss_client/idmap/sss_nss_ex.c new file mode 100644 index 0000000..24e2a6b --- /dev/null +++ b/src/sss_client/idmap/sss_nss_ex.c @@ -0,0 +1,533 @@ +/* + SSSD + + Extended NSS Responder Interface + + Authors: + Sumit Bose <sbose@redhat.com> + + Copyright (C) 2017 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ +#include <stdlib.h> +#include <errno.h> + +#include <sys/param.h> /* for MIN() */ + +#include "sss_client/sss_cli.h" +#include "sss_client/nss_mc.h" +#include "sss_client/nss_common.h" +#include "sss_client/idmap/sss_nss_idmap.h" +#include "sss_client/idmap/sss_nss_idmap_private.h" + +#ifndef discard_const +#define discard_const(ptr) ((void *)((uintptr_t)(ptr))) +#endif + +struct sss_nss_initgr_rep { + gid_t *groups; + long int *ngroups; + long int *start; +}; + +struct nss_input { + union { + const char *name; + uid_t uid; + gid_t gid; + } input; + struct sss_cli_req_data rd; + enum sss_cli_command cmd; + union { + struct sss_nss_pw_rep pwrep; + struct sss_nss_gr_rep grrep; + struct sss_nss_initgr_rep initgrrep; + } result; +}; + +static errno_t sss_nss_mc_get(struct nss_input *inp) +{ + switch(inp->cmd) { + case SSS_NSS_GETPWNAM: + case SSS_NSS_GETPWNAM_EX: + return sss_nss_mc_getpwnam(inp->input.name, strlen(inp->input.name), + inp->result.pwrep.result, + inp->result.pwrep.buffer, + inp->result.pwrep.buflen); + break; + case SSS_NSS_GETPWUID: + case SSS_NSS_GETPWUID_EX: + return sss_nss_mc_getpwuid(inp->input.uid, + inp->result.pwrep.result, + inp->result.pwrep.buffer, + inp->result.pwrep.buflen); + break; + case SSS_NSS_GETGRNAM: + case SSS_NSS_GETGRNAM_EX: + return sss_nss_mc_getgrnam(inp->input.name, strlen(inp->input.name), + inp->result.grrep.result, + inp->result.grrep.buffer, + inp->result.grrep.buflen); + break; + case SSS_NSS_GETGRGID: + case SSS_NSS_GETGRGID_EX: + return sss_nss_mc_getgrgid(inp->input.gid, + inp->result.grrep.result, + inp->result.grrep.buffer, + inp->result.grrep.buflen); + break; + case SSS_NSS_INITGR: + case SSS_NSS_INITGR_EX: + return sss_nss_mc_initgroups_dyn(inp->input.name, + strlen(inp->input.name), + -1 /* currently ignored */, + inp->result.initgrrep.start, + inp->result.initgrrep.ngroups, + &(inp->result.initgrrep.groups), + /* no limit so that needed size can + * be returned properly */ + -1); + break; + default: + return EINVAL; + } +} + +static int check_flags(struct nss_input *inp, uint32_t flags, + bool *skip_mc, bool *skip_data) +{ + bool no_data = false; + + /* SSS_NSS_EX_FLAG_NO_CACHE and SSS_NSS_EX_FLAG_INVALIDATE_CACHE are + * mutually exclusive */ + if ((flags & SSS_NSS_EX_FLAG_NO_CACHE) != 0 + && (flags & SSS_NSS_EX_FLAG_INVALIDATE_CACHE) != 0) { + return EINVAL; + } + + *skip_mc = false; + if ((flags & SSS_NSS_EX_FLAG_NO_CACHE) != 0 + || (flags & SSS_NSS_EX_FLAG_INVALIDATE_CACHE) != 0) { + *skip_mc = true; + } + + switch(inp->cmd) { + case SSS_NSS_GETPWNAM: + case SSS_NSS_GETPWNAM_EX: + case SSS_NSS_GETPWUID: + case SSS_NSS_GETPWUID_EX: + if (inp->result.pwrep.buffer == NULL + || inp->result.pwrep.buflen == 0) { + no_data = true; + } + break; + case SSS_NSS_GETGRNAM: + case SSS_NSS_GETGRNAM_EX: + case SSS_NSS_GETGRGID: + case SSS_NSS_GETGRGID_EX: + if (inp->result.grrep.buffer == NULL + || inp->result.grrep.buflen == 0) { + no_data = true; + } + break; + case SSS_NSS_INITGR: + case SSS_NSS_INITGR_EX: + if (inp->result.initgrrep.ngroups == 0 + || inp->result.initgrrep.groups == NULL) { + return EINVAL; + } + break; + default: + return EINVAL; + } + + *skip_data = false; + /* Allow empty buffer with SSS_NSS_EX_FLAG_INVALIDATE_CACHE */ + if (no_data) { + if ((flags & SSS_NSS_EX_FLAG_INVALIDATE_CACHE) != 0) { + *skip_data = true; + } else { + return ERANGE; + } + } + + return 0; +} + +static int sss_get_ex(struct nss_input *inp, uint32_t flags, + unsigned int timeout) +{ + uint8_t *repbuf = NULL; + size_t replen; + size_t len; + uint32_t num_results; + int ret; + int time_left; + int errnop; + size_t c; + gid_t *new_groups; + size_t idx; + bool skip_mc = false; + bool skip_data = false; + + ret = check_flags(inp, flags, &skip_mc, &skip_data); + if (ret != 0) { + return ret; + } + + if (!skip_mc && !skip_data) { + ret = sss_nss_mc_get(inp); + switch (ret) { + case 0: + return 0; + case ERANGE: + return ERANGE; + case ENOENT: + /* fall through, we need to actively ask the parent + * if no entry is found */ + break; + default: + /* if using the mmapped cache failed, + * fall back to socket based comms */ + break; + } + } + + ret = sss_nss_timedlock(timeout, &time_left); + if (ret != 0) { + return ret; + } + + if (!skip_mc && !skip_data) { + /* previous thread might already initialize entry in mmap cache */ + ret = sss_nss_mc_get(inp); + switch (ret) { + case 0: + ret = 0; + goto out; + case ERANGE: + ret = ERANGE; + goto out; + case ENOENT: + /* fall through, we need to actively ask the parent + * if no entry is found */ + break; + default: + /* if using the mmapped cache failed, + * fall back to socket based comms */ + break; + } + } + + ret = sss_nss_make_request_timeout(inp->cmd, &inp->rd, time_left, + &repbuf, &replen, &errnop); + if (ret != NSS_STATUS_SUCCESS) { + ret = errnop != 0 ? errnop : EIO; + goto out; + } + + /* Get number of results from repbuf. */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* no results if not found, INITGR requests are handled separately */ + if (num_results == 0 && inp->cmd != SSS_NSS_INITGR + && inp->cmd != SSS_NSS_INITGR_EX) { + ret = ENOENT; + goto out; + } + + if (skip_data) { + /* No data requested, just return the return code */ + ret = 0; + goto out; + } + + if (inp->cmd == SSS_NSS_INITGR || inp->cmd == SSS_NSS_INITGR_EX) { + if ((*(inp->result.initgrrep.ngroups) - *(inp->result.initgrrep.start)) + < num_results) { + new_groups = realloc(inp->result.initgrrep.groups, + (num_results + *(inp->result.initgrrep.start)) + * sizeof(gid_t)); + if (new_groups == NULL) { + ret = ENOMEM; + goto out; + } + + inp->result.initgrrep.groups = new_groups; + } + *(inp->result.initgrrep.ngroups) = num_results + + *(inp->result.initgrrep.start); + + idx = 2 * sizeof(uint32_t); + for (c = 0; c < num_results; c++) { + SAFEALIGN_COPY_UINT32( + &(inp->result.initgrrep.groups[*(inp->result.initgrrep.start)]), + repbuf + idx, &idx); + *(inp->result.initgrrep.start) += 1; + } + + ret = 0; + goto out; + } + + /* only 1 result is accepted for this function */ + if (num_results != 1) { + ret = EBADMSG; + goto out; + } + + len = replen - 8; + + switch(inp->cmd) { + case SSS_NSS_GETPWNAM: + case SSS_NSS_GETPWUID: + case SSS_NSS_GETPWNAM_EX: + case SSS_NSS_GETPWUID_EX: + ret = sss_nss_getpw_readrep(&(inp->result.pwrep), repbuf+8, &len); + break; + case SSS_NSS_GETGRNAM: + case SSS_NSS_GETGRGID: + case SSS_NSS_GETGRNAM_EX: + case SSS_NSS_GETGRGID_EX: + ret = sss_nss_getgr_readrep(&(inp->result.grrep), repbuf+8, &len); + break; + default: + ret = EINVAL; + } + if (ret != 0) { + goto out; + } + + if (len == 0) { + /* no extra data */ + ret = 0; + goto out; + } + +out: + free(repbuf); + + sss_nss_unlock(); + return ret; +} + +static int make_name_flag_req_data(const char *name, uint32_t flags, + struct sss_cli_req_data *rd) +{ + size_t len; + size_t name_len; + uint8_t *data; + int ret; + + if (name == NULL) { + return EINVAL; + } + + ret = sss_strnlen(name, SSS_NAME_MAX, &name_len); + if (ret != 0) { + return ret; + } + name_len++; + + len = name_len + sizeof(uint32_t); + data = malloc(len); + if (data == NULL) { + return ENOMEM; + } + + memcpy(data, name, name_len); + SAFEALIGN_COPY_UINT32(data + name_len, &flags, NULL); + + rd->len = len; + rd->data = data; + + return 0; +} + +int sss_nss_getpwnam_timeout(const char *name, struct passwd *pwd, + char *buffer, size_t buflen, + struct passwd **result, + uint32_t flags, unsigned int timeout) +{ + int ret; + struct nss_input inp = { + .input.name = name, + .cmd = SSS_NSS_GETPWNAM_EX, + .result.pwrep.result = pwd, + .result.pwrep.buffer = buffer, + .result.pwrep.buflen = buflen}; + + ret = make_name_flag_req_data(name, flags, &inp.rd); + if (ret != 0) { + return ret; + } + + ret = sss_get_ex(&inp, flags, timeout); + free(discard_const(inp.rd.data)); + + if (result != NULL) { + if (ret == 0) { + *result = inp.result.pwrep.result; + } else { + *result = NULL; + } + } + + return ret; +} + +int sss_nss_getpwuid_timeout(uid_t uid, struct passwd *pwd, + char *buffer, size_t buflen, + struct passwd **result, + uint32_t flags, unsigned int timeout) +{ + int ret; + uint32_t req_data[2]; + struct nss_input inp = { + .input.uid = uid, + .cmd = SSS_NSS_GETPWUID_EX, + .rd.len = 2 * sizeof(uint32_t), + .rd.data = &req_data, + .result.pwrep.result = pwd, + .result.pwrep.buffer = buffer, + .result.pwrep.buflen = buflen}; + + SAFEALIGN_COPY_UINT32(&req_data[0], &uid, NULL); + SAFEALIGN_COPY_UINT32(&req_data[1], &flags, NULL); + + ret = sss_get_ex(&inp, flags, timeout); + + if (result != NULL) { + if (ret == 0) { + *result = inp.result.pwrep.result; + } else { + *result = NULL; + } + } + + return ret; +} + +int sss_nss_getgrnam_timeout(const char *name, struct group *grp, + char *buffer, size_t buflen, struct group **result, + uint32_t flags, unsigned int timeout) +{ + int ret; + struct nss_input inp = { + .input.name = name, + .cmd = SSS_NSS_GETGRNAM_EX, + .result.grrep.result = grp, + .result.grrep.buffer = buffer, + .result.grrep.buflen = buflen}; + + ret = make_name_flag_req_data(name, flags, &inp.rd); + if (ret != 0) { + return ret; + } + + ret = sss_get_ex(&inp, flags, timeout); + free(discard_const(inp.rd.data)); + + if (result != NULL) { + if (ret == 0) { + *result = inp.result.grrep.result; + } else { + *result = NULL; + } + } + + return ret; +} + +int sss_nss_getgrgid_timeout(gid_t gid, struct group *grp, + char *buffer, size_t buflen, struct group **result, + uint32_t flags, unsigned int timeout) +{ + int ret; + uint32_t req_data[2]; + struct nss_input inp = { + .input.gid = gid, + .cmd = SSS_NSS_GETGRGID_EX, + .rd.len = 2 * sizeof(uint32_t), + .rd.data = &req_data, + .result.grrep.result = grp, + .result.grrep.buffer = buffer, + .result.grrep.buflen = buflen}; + + SAFEALIGN_COPY_UINT32(&req_data[0], &gid, NULL); + SAFEALIGN_COPY_UINT32(&req_data[1], &flags, NULL); + + ret = sss_get_ex(&inp, flags, timeout); + + if (result != NULL) { + if (ret == 0) { + *result = inp.result.grrep.result; + } else { + *result = NULL; + } + } + + return ret; +} + +int sss_nss_getgrouplist_timeout(const char *name, gid_t group, + gid_t *groups, int *ngroups, + uint32_t flags, unsigned int timeout) +{ + int ret; + long int new_ngroups; + long int start = 1; + struct nss_input inp = { + .input.name = name, + .cmd = SSS_NSS_INITGR_EX}; + + ret = make_name_flag_req_data(name, flags, &inp.rd); + if (ret != 0) { + return ret; + } + + new_ngroups = MAX(1, *ngroups); + inp.result.initgrrep.groups = malloc(new_ngroups * sizeof(gid_t)); + if (inp.result.initgrrep.groups == NULL) { + free(discard_const(inp.rd.data)); + return ENOMEM; + } + inp.result.initgrrep.groups[0] = group; + + inp.result.initgrrep.ngroups = &new_ngroups; + inp.result.initgrrep.start = &start; + + /* inp.result.initgrrep.groups, inp.result.initgrrep.ngroups and + * inp.result.initgrrep.start might be modified by sss_get_ex() */ + ret = sss_get_ex(&inp, flags, timeout); + free(discard_const(inp.rd.data)); + if (ret != 0) { + free(inp.result.initgrrep.groups); + return ret; + } + + memcpy(groups, inp.result.initgrrep.groups, + MIN(*ngroups, start) * sizeof(gid_t)); + free(inp.result.initgrrep.groups); + + if (start > *ngroups) { + ret = ERANGE; + } else { + ret = 0; + } + *ngroups = start; + + return ret; +} diff --git a/src/sss_client/idmap/sss_nss_idmap.c b/src/sss_client/idmap/sss_nss_idmap.c new file mode 100644 index 0000000..575d030 --- /dev/null +++ b/src/sss_client/idmap/sss_nss_idmap.c @@ -0,0 +1,742 @@ +/* + SSSD + + NSS Responder Interface for ID-SID mappings + + Authors: + Sumit Bose <sbose@redhat.com> + + Copyright (C) 2013 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include <stdlib.h> +#include <errno.h> +#include <nss.h> + +#include "sss_client/sss_cli.h" +#include "sss_client/nss_mc.h" +#include "sss_client/idmap/sss_nss_idmap.h" +#include "sss_client/idmap/sss_nss_idmap_private.h" +#include "util/strtonum.h" + +#define DATA_START (3 * sizeof(uint32_t)) +#define LIST_START (2 * sizeof(uint32_t)) +#define NO_TIMEOUT ((unsigned int) -1) + +union input { + const char *str; + uint32_t id; +}; + +struct output { + enum sss_id_type type; + enum sss_id_type *types; + union { + char *str; + uint32_t id; + struct sss_nss_kv *kv_list; + char **names; + } d; +}; + +static int sss_nss_status_to_errno(enum nss_status nret) { + switch (nret) { + case NSS_STATUS_TRYAGAIN: + return EAGAIN; + case NSS_STATUS_SUCCESS: + return EOK; + case NSS_STATUS_UNAVAIL: + default: + return ENOENT; + } + + return EINVAL; +} + +void sss_nss_free_kv(struct sss_nss_kv *kv_list) +{ + size_t c; + + if (kv_list != NULL) { + for (c = 0; kv_list[c].key != NULL; c++) { + free(kv_list[c].key); + free(kv_list[c].value); + } + free(kv_list); + } +} + +void sss_nss_free_list(char **l) +{ + size_t c; + + if (l != NULL) { + for (c = 0; l[c] != NULL; c++) { + free(l[c]); + } + free(l); + } +} + +static int buf_to_name_type_list(uint8_t *buf, size_t buf_len, uint32_t num, + char ***names, enum sss_id_type **types) +{ + int ret; + size_t c; + char **n = NULL; + enum sss_id_type *t = NULL; + size_t rp = 0; + + n = calloc(num + 1, sizeof(char *)); + if (n == NULL) { + ret = ENOMEM; + goto done; + } + + t = calloc(num + 1, sizeof(enum sss_id_type)); + if (t == NULL) { + ret = ENOMEM; + goto done; + } + + for (c = 0; c < num; c++) { + SAFEALIGN_COPY_UINT32(&(t[c]), buf + rp, &rp); + n[c] = strdup((char *) buf + rp); + if (n[c] == NULL) { + ret = ENOMEM; + goto done; + } + rp += strlen(n[c]) + 1; + } + + ret = EOK; + +done: + if (ret != EOK) { + sss_nss_free_list(n); + free(t); + } else { + *names = n; + *types = t; + } + + return ret; +} + +static int buf_to_kv_list(uint8_t *buf, size_t buf_len, + struct sss_nss_kv **kv_list) +{ + size_t c; + size_t count = 0; + struct sss_nss_kv *list; + uint8_t *p; + int ret; + + for (c = 0; c < buf_len; c++) { + if (buf[c] == '\0') { + count++; + } + } + + if ((count % 2) != 0) { + return EINVAL; + } + count /= 2; + + list = calloc((count + 1), sizeof(struct sss_nss_kv)); + if (list == NULL) { + return ENOMEM; + } + + p = buf; + for (c = 0; c < count; c++) { + list[c].key = strdup((char *) p); + if (list[c].key == NULL) { + ret = ENOMEM; + goto done; + } + + p = memchr(p, '\0', buf_len - (p - buf)); + if (p == NULL) { + ret = EINVAL; + goto done; + } + p++; + + list[c].value = strdup((char *) p); + if (list[c].value == NULL) { + ret = ENOMEM; + goto done; + } + + p = memchr(p, '\0', buf_len - (p - buf)); + if (p == NULL) { + ret = EINVAL; + goto done; + } + p++; + } + + *kv_list = list; + + ret = EOK; + +done: + if (ret != EOK) { + sss_nss_free_kv(list); + } + + return ret; +} + +static errno_t sss_nss_mc_get(union input inp, enum sss_cli_command cmd, + struct output *out) +{ + switch (cmd) { + case SSS_NSS_GETSIDBYID: + return sss_nss_mc_get_sid_by_id(inp.id, &out->d.str, &out->type); + + case SSS_NSS_GETSIDBYUID: + return sss_nss_mc_get_sid_by_uid(inp.id, &out->d.str, &out->type); + + case SSS_NSS_GETSIDBYGID: + return sss_nss_mc_get_sid_by_gid(inp.id, &out->d.str, &out->type); + + case SSS_NSS_GETIDBYSID: + return sss_nss_mc_get_id_by_sid(inp.str, &out->d.id, &out->type); + + default: + return ENOENT; + } +} + +static int sss_nss_getyyybyxxx(union input inp, enum sss_cli_command cmd, + unsigned int timeout, struct output *out) +{ + int ret; + size_t inp_len; + struct sss_cli_req_data rd; + uint8_t *repbuf = NULL; + size_t replen; + int errnop; + enum nss_status nret; + uint32_t num_results; + char *str = NULL; + size_t data_len; + uint32_t c; + struct sss_nss_kv *kv_list; + char **names; + enum sss_id_type *types; + int time_left = SSS_CLI_SOCKET_TIMEOUT; + + ret = sss_nss_mc_get(inp, cmd, out); + if (ret == EOK) { + return 0; + } + + switch (cmd) { + case SSS_NSS_GETSIDBYNAME: + case SSS_NSS_GETSIDBYUSERNAME: + case SSS_NSS_GETSIDBYGROUPNAME: + case SSS_NSS_GETNAMEBYSID: + case SSS_NSS_GETIDBYSID: + case SSS_NSS_GETORIGBYNAME: + case SSS_NSS_GETORIGBYUSERNAME: + case SSS_NSS_GETORIGBYGROUPNAME: + ret = sss_strnlen(inp.str, 2048, &inp_len); + if (ret != EOK) { + return EINVAL; + } + + rd.len = inp_len + 1; + rd.data = inp.str; + + break; + case SSS_NSS_GETNAMEBYCERT: + case SSS_NSS_GETLISTBYCERT: + ret = sss_strnlen(inp.str, 10 * 1024 , &inp_len); + if (ret != EOK) { + return EINVAL; + } + + rd.len = inp_len + 1; + rd.data = inp.str; + + break; + case SSS_NSS_GETSIDBYID: + case SSS_NSS_GETSIDBYUID: + case SSS_NSS_GETSIDBYGID: + rd.len = sizeof(uint32_t); + rd.data = &inp.id; + + break; + default: + return EINVAL; + } + + if (timeout == NO_TIMEOUT) { + sss_nss_lock(); + } else { + ret = sss_nss_timedlock(timeout, &time_left); + if (ret != 0) { + return ret; + } + } + + /* previous thread might already initialize entry in mmap cache */ + ret = sss_nss_mc_get(inp, cmd, out); + if (ret == EOK) { + sss_nss_unlock(); + return 0; + } + + nret = sss_nss_make_request_timeout(cmd, &rd, time_left, &repbuf, &replen, + &errnop); + if (nret != NSS_STATUS_SUCCESS) { + ret = sss_nss_status_to_errno(nret); + goto done; + } + + if (replen < 8) { + ret = EBADMSG; + goto done; + } + + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + if (num_results == 0) { + ret = ENOENT; + goto done; + } else if (num_results > 1 && cmd != SSS_NSS_GETLISTBYCERT) { + ret = EBADMSG; + goto done; + } + + /* Skip first two 32 bit values (number of results and + * reserved padding) */ + SAFEALIGN_COPY_UINT32(&out->type, repbuf + 2 * sizeof(uint32_t), NULL); + + data_len = replen - DATA_START; + + switch(cmd) { + case SSS_NSS_GETSIDBYID: + case SSS_NSS_GETSIDBYUID: + case SSS_NSS_GETSIDBYGID: + case SSS_NSS_GETSIDBYNAME: + case SSS_NSS_GETSIDBYUSERNAME: + case SSS_NSS_GETSIDBYGROUPNAME: + case SSS_NSS_GETNAMEBYSID: + case SSS_NSS_GETNAMEBYCERT: + if (data_len <= 1 || repbuf[replen - 1] != '\0') { + ret = EBADMSG; + goto done; + } + + str = malloc(sizeof(char) * data_len); + if (str == NULL) { + ret = ENOMEM; + goto done; + } + + strncpy(str, (char *) repbuf + DATA_START, data_len-1); + str[data_len-1] = '\0'; + + out->d.str = str; + + break; + case SSS_NSS_GETIDBYSID: + if (data_len != sizeof(uint32_t)) { + ret = EBADMSG; + goto done; + } + + SAFEALIGN_COPY_UINT32(&c, repbuf + DATA_START, NULL); + out->d.id = c; + + break; + case SSS_NSS_GETLISTBYCERT: + ret = buf_to_name_type_list(repbuf + LIST_START, replen - LIST_START, + num_results, + &names, &types); + if (ret != EOK) { + goto done; + } + + out->types = types; + out->d.names = names; + + break; + case SSS_NSS_GETORIGBYNAME: + case SSS_NSS_GETORIGBYUSERNAME: + case SSS_NSS_GETORIGBYGROUPNAME: + ret = buf_to_kv_list(repbuf + DATA_START, data_len, &kv_list); + if (ret != EOK) { + goto done; + } + + out->d.kv_list = kv_list; + + break; + default: + ret = EINVAL; + goto done; + } + + ret = EOK; + +done: + sss_nss_unlock(); + free(repbuf); + if (ret != EOK) { + free(str); + } + + return ret; +} + +static int _sss_nss_getsidbyxxxname_timeout(enum sss_cli_command cmd, + const char *fq_name, + unsigned int timeout, + char **sid, + enum sss_id_type *type) +{ + int ret; + union input inp; + struct output out; + + if (sid == NULL || fq_name == NULL || *fq_name == '\0') { + return EINVAL; + } + + inp.str = fq_name; + + ret = sss_nss_getyyybyxxx(inp, cmd, timeout, &out); + if (ret == EOK) { + *sid = out.d.str; + *type = out.type; + } + + return ret; +} + +int sss_nss_getsidbyname_timeout(const char *fq_name, unsigned int timeout, + char **sid, enum sss_id_type *type) +{ + return _sss_nss_getsidbyxxxname_timeout(SSS_NSS_GETSIDBYNAME, fq_name, + timeout, sid, type); +} + +int sss_nss_getsidbyname(const char *fq_name, char **sid, + enum sss_id_type *type) +{ + return _sss_nss_getsidbyxxxname_timeout(SSS_NSS_GETSIDBYNAME, fq_name, + NO_TIMEOUT, sid, type); +} + +int sss_nss_getsidbyusername_timeout(const char *fq_name, + unsigned int timeout, + char **sid, + enum sss_id_type *type) +{ + return _sss_nss_getsidbyxxxname_timeout(SSS_NSS_GETSIDBYUSERNAME, fq_name, + timeout, sid, type); +} + +int sss_nss_getsidbyusername(const char *fq_name, + char **sid, + enum sss_id_type *type) +{ + return _sss_nss_getsidbyxxxname_timeout(SSS_NSS_GETSIDBYUSERNAME, fq_name, + NO_TIMEOUT, sid, type); +} + +int sss_nss_getsidbygroupname_timeout(const char *fq_name, + unsigned int timeout, + char **sid, + enum sss_id_type *type) +{ + return _sss_nss_getsidbyxxxname_timeout(SSS_NSS_GETSIDBYGROUPNAME, fq_name, + timeout, sid, type); +} + +int sss_nss_getsidbygroupname(const char *fq_name, + char **sid, + enum sss_id_type *type) +{ + return _sss_nss_getsidbyxxxname_timeout(SSS_NSS_GETSIDBYGROUPNAME, fq_name, + NO_TIMEOUT, sid, type); +} + +int sss_nss_getsidbyid_timeout(uint32_t id, unsigned int timeout, + char **sid, enum sss_id_type *type) +{ + int ret; + union input inp; + struct output out; + + if (sid == NULL) { + return EINVAL; + } + + inp.id = id; + + ret = sss_nss_getyyybyxxx(inp, SSS_NSS_GETSIDBYID, timeout, &out); + if (ret == EOK) { + *sid = out.d.str; + *type = out.type; + } + + return ret; +} + +int sss_nss_getsidbyid(uint32_t id, char **sid, enum sss_id_type *type) +{ + return sss_nss_getsidbyid_timeout(id, NO_TIMEOUT, sid, type); +} + +int sss_nss_getsidbyuid_timeout(uint32_t uid, unsigned int timeout, + char **sid, enum sss_id_type *type) +{ + int ret; + union input inp; + struct output out; + + if (sid == NULL) { + return EINVAL; + } + + inp.id = uid; + + ret = sss_nss_getyyybyxxx(inp, SSS_NSS_GETSIDBYUID, timeout, &out); + if (ret == EOK) { + *sid = out.d.str; + *type = out.type; + } + + return ret; +} + +int sss_nss_getsidbyuid(uint32_t uid, char **sid, enum sss_id_type *type) +{ + return sss_nss_getsidbyuid_timeout(uid, NO_TIMEOUT, sid, type); +} + +int sss_nss_getsidbygid_timeout(uint32_t gid, unsigned int timeout, + char **sid, enum sss_id_type *type) +{ + int ret; + union input inp; + struct output out; + + if (sid == NULL) { + return EINVAL; + } + + inp.id = gid; + + ret = sss_nss_getyyybyxxx(inp, SSS_NSS_GETSIDBYGID, timeout, &out); + if (ret == EOK) { + *sid = out.d.str; + *type = out.type; + } + + return ret; +} + +int sss_nss_getsidbygid(uint32_t gid, char **sid, enum sss_id_type *type) +{ + return sss_nss_getsidbygid_timeout(gid, NO_TIMEOUT, sid, type); +} + +int sss_nss_getnamebysid_timeout(const char *sid, unsigned int timeout, + char **fq_name, enum sss_id_type *type) +{ + int ret; + union input inp; + struct output out; + + if (fq_name == NULL || sid == NULL || *sid == '\0') { + return EINVAL; + } + + inp.str = sid; + + ret = sss_nss_getyyybyxxx(inp, SSS_NSS_GETNAMEBYSID, timeout, &out); + if (ret == EOK) { + *fq_name = out.d.str; + *type = out.type; + } + + return ret; +} + +int sss_nss_getnamebysid(const char *sid, char **fq_name, + enum sss_id_type *type) +{ + return sss_nss_getnamebysid_timeout(sid, NO_TIMEOUT, fq_name, type); +} + +int sss_nss_getidbysid_timeout(const char *sid, unsigned int timeout, + uint32_t *id, enum sss_id_type *id_type) +{ + int ret; + union input inp; + struct output out; + + if (id == NULL || id_type == NULL || sid == NULL || *sid == '\0') { + return EINVAL; + } + + inp.str = sid; + + ret = sss_nss_getyyybyxxx(inp, SSS_NSS_GETIDBYSID, timeout, &out); + if (ret == EOK) { + *id = out.d.id; + *id_type = out.type; + } + + return ret; +} + +int sss_nss_getidbysid(const char *sid, uint32_t *id, enum sss_id_type *id_type) +{ + return sss_nss_getidbysid_timeout(sid, NO_TIMEOUT, id, id_type); +} + +int sss_nss_getorigbyname_timeout_common(const char *fq_name, + unsigned int timeout, + enum sss_cli_command cmd, + struct sss_nss_kv **kv_list, + enum sss_id_type *type) +{ + int ret; + union input inp; + struct output out; + + if (kv_list == NULL || fq_name == NULL || *fq_name == '\0') { + return EINVAL; + } + + inp.str = fq_name; + + ret = sss_nss_getyyybyxxx(inp, cmd, timeout, &out); + if (ret == EOK) { + *kv_list = out.d.kv_list; + *type = out.type; + } + + return ret; +} + +int sss_nss_getorigbyname_timeout(const char *fq_name, unsigned int timeout, + struct sss_nss_kv **kv_list, + enum sss_id_type *type) +{ + return sss_nss_getorigbyname_timeout_common(fq_name, timeout, + SSS_NSS_GETORIGBYNAME, kv_list, + type); +} + +int sss_nss_getorigbyname(const char *fq_name, struct sss_nss_kv **kv_list, + enum sss_id_type *type) +{ + return sss_nss_getorigbyname_timeout(fq_name, NO_TIMEOUT, kv_list, type); +} + +int sss_nss_getorigbyusername_timeout(const char *fq_name, unsigned int timeout, + struct sss_nss_kv **kv_list, + enum sss_id_type *type) +{ + return sss_nss_getorigbyname_timeout_common(fq_name, timeout, + SSS_NSS_GETORIGBYUSERNAME, + kv_list, type); +} + +int sss_nss_getorigbyusername(const char *fq_name, struct sss_nss_kv **kv_list, + enum sss_id_type *type) +{ + return sss_nss_getorigbyusername_timeout(fq_name, NO_TIMEOUT, kv_list, type); +} + +int sss_nss_getorigbygroupname_timeout(const char *fq_name, unsigned int timeout, + struct sss_nss_kv **kv_list, + enum sss_id_type *type) +{ + return sss_nss_getorigbyname_timeout_common(fq_name, timeout, + SSS_NSS_GETORIGBYGROUPNAME, + kv_list, type); +} + +int sss_nss_getorigbygroupname(const char *fq_name, struct sss_nss_kv **kv_list, + enum sss_id_type *type) +{ + return sss_nss_getorigbygroupname_timeout(fq_name, NO_TIMEOUT, kv_list, type); +} + +int sss_nss_getnamebycert_timeout(const char *cert, unsigned int timeout, + char **fq_name, enum sss_id_type *type) +{ + int ret; + union input inp; + struct output out; + + if (fq_name == NULL || cert == NULL || *cert == '\0') { + return EINVAL; + } + + inp.str = cert; + + ret = sss_nss_getyyybyxxx(inp, SSS_NSS_GETNAMEBYCERT, timeout, &out); + if (ret == EOK) { + *fq_name = out.d.str; + *type = out.type; + } + + return ret; +} + +int sss_nss_getnamebycert(const char *cert, char **fq_name, + enum sss_id_type *type) +{ + return sss_nss_getnamebycert_timeout(cert, NO_TIMEOUT, fq_name, type); +} + +int sss_nss_getlistbycert_timeout(const char *cert, unsigned int timeout, + char ***fq_name, enum sss_id_type **type) +{ + int ret; + union input inp; + struct output out; + + if (fq_name == NULL || cert == NULL || *cert == '\0') { + return EINVAL; + } + + inp.str = cert; + + ret = sss_nss_getyyybyxxx(inp, SSS_NSS_GETLISTBYCERT, timeout, &out); + if (ret == EOK) { + *fq_name = out.d.names; + *type = out.types; + } + + return ret; +} + +int sss_nss_getlistbycert(const char *cert, char ***fq_name, + enum sss_id_type **type) +{ + return sss_nss_getlistbycert_timeout(cert, NO_TIMEOUT, fq_name, type); +} diff --git a/src/sss_client/idmap/sss_nss_idmap.doxy.in b/src/sss_client/idmap/sss_nss_idmap.doxy.in new file mode 100644 index 0000000..f6c18ba --- /dev/null +++ b/src/sss_client/idmap/sss_nss_idmap.doxy.in @@ -0,0 +1,1539 @@ +# Doxyfile 1.6.1 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# http://www.gnu.org/software/libiconv for the list of possible encodings. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = sss_nss_idmap + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = @PACKAGE_VERSION@ + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = nss_idmap_doc + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, +# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English +# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, +# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak, +# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = "The $name class" \ + "The $name widget" \ + "The $name file" \ + is \ + provides \ + specifies \ + contains \ + represents \ + a \ + an \ + the + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = YES + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful is your file systems +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like regular Qt-style comments +# (thus requiring an explicit @brief command for a brief description.) + +JAVADOC_AUTOBRIEF = YES + +# If the QT_AUTOBRIEF tag is set to YES then Doxygen will +# interpret the first line (until the first dot) of a Qt-style +# comment as the brief description. If set to NO, the comments +# will behave just like regular Qt-style comments (thus requiring +# an explicit \brief command for a brief description.) + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 8 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = YES + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for +# Java. For instance, namespaces will be presented as packages, qualified +# scopes will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources only. Doxygen will then generate output that is more tailored for +# Fortran. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for +# VHDL. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it parses. +# With this tag you can assign which parser to use for a given extension. +# Doxygen has a built-in mapping, but you can override or extend it using this tag. +# The format is ext=language, where ext is a file extension, and language is one of +# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP, +# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat +# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran), +# use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. +# Doxygen will parse them like normal C++ but will assume all classes use public +# instead of private inheritance when no explicit protection keyword is present. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate getter +# and setter methods for a property. Setting this option to YES (the default) +# will make doxygen to replace the get and set methods by a property in the +# documentation. This will only work if the methods are indeed getting or +# setting a simple type. If this is not the case, or you want to show the +# methods anyway, you should set this option to NO. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum +# is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically +# be useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. + +TYPEDEF_HIDES_STRUCT = NO + +# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to +# determine which symbols to keep in memory and which to flush to disk. +# When the cache is full, less often used symbols will be written to disk. +# For small to medium size projects (<1000 input files) the default value is +# probably good enough. For larger projects a too small cache size can cause +# doxygen to be busy swapping symbols to and from disk most of the time +# causing a significant performance penality. +# If the system has enough physical memory increasing the cache will improve the +# performance by keeping more symbols in memory. Note that the value works on +# a logarithmic scale so increasing the size by one will rougly double the +# memory usage. The cache size is given by this formula: +# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, +# corresponding to a cache size of 2^16 = 65536 symbols + +SYMBOL_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = NO + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base +# name of the file that contains the anonymous namespace. By default +# anonymous namespace are hidden. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = YES + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = YES + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = YES + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the +# hierarchy of group names into alphabetical order. If set to NO (the default) +# the group names will appear in their defined order. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or define consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and defines in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# If the sources in your project are distributed over multiple directories +# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy +# in the documentation. The default is NO. + +SHOW_DIRECTORIES = NO + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. +# This will remove the Files entry from the Quick Index and from the +# Folder Tree View (if specified). The default is YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the +# Namespaces page. +# This will remove the Namespaces entry from the Quick Index +# and from the Folder Tree View (if specified). The default is YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command <command> <input-file>, where <command> is the value of +# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by +# doxygen. The layout file controls the global structure of the generated output files +# in an output format independent way. The create the layout file that represents +# doxygen's defaults, run doxygen with the -l option. You can optionally specify a +# file name after the option, if omitted DoxygenLayout.xml will be used as the name +# of the layout file. + +LAYOUT_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be abled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = @abs_top_srcdir@/src/sss_client/idmap/sss_nss_idmap.h + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is +# also the default input encoding. Doxygen uses libiconv (or the iconv built +# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for +# the list of possible encodings. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx +# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90 + +FILE_PATTERNS = *.cpp \ + *.cc \ + *.c \ + *.h \ + *.hh \ + *.hpp \ + *.dox + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a UNIX filesystem feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = */.git/* \ + */.svn/* \ + */cmake/* \ + */build/* + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command <filter> <input-file>, where <filter> +# is the value of the INPUT_FILTER tag, and <input-file> is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. +# If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. +# Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. +# The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER +# is applied to all files. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. +# Otherwise they will link to the documentation. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = NO + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated +# HTML page will contain the date and time when the page was generated. Setting +# this to NO can help when comparing the output of multiple runs. + +HTML_TIMESTAMP = NO + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = + +# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, +# files or namespaces will be aligned in HTML using tables. If set to +# NO a bullet list will be used. + +HTML_ALIGN_MEMBERS = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. For this to work a browser that supports +# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox +# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). + +HTML_DYNAMIC_SECTIONS = NO + +# If the GENERATE_DOCSET tag is set to YES, additional index files +# will be generated that can be used as input for Apple's Xcode 3 +# integrated development environment, introduced with OSX 10.5 (Leopard). +# To create a documentation set, doxygen will generate a Makefile in the +# HTML output directory. Running make will produce the docset in that +# directory and running "make install" will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find +# it at startup. +# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information. + +GENERATE_DOCSET = NO + +# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the +# feed. A documentation feed provides an umbrella under which multiple +# documentation sets from a single provider (such as a company or product suite) +# can be grouped. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that +# should uniquely identify the documentation set bundle. This should be a +# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen +# will append .docset to the name. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING +# is used to encode HtmlHelp index (hhk), content (hhc) and project file +# content. + +CHM_INDEX_ENCODING = + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER +# are set, an additional index file will be generated that can be used as input for +# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated +# HTML documentation. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can +# be used to specify the file name of the resulting .qch file. +# The path specified is relative to the HTML output folder. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#namespace + +QHP_NAMESPACE = + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#virtual-folders + +QHP_VIRTUAL_FOLDER = doc + +# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add. +# For more information please see +# http://doc.trolltech.com/qthelpproject.html#custom-filters + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see +# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">Qt Help Project / Custom Filters</a>. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's +# filter section matches. +# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">Qt Help Project / Filter Attributes</a>. + +QHP_SECT_FILTER_ATTRS = + +# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can +# be used to specify the location of Qt's qhelpgenerator. +# If non-empty doxygen will try to run qhelpgenerator on the generated +# .qhp file. + +QHG_LOCATION = + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# This tag can be used to set the number of enum values (range [1..20]) +# that doxygen will group on one line in the generated HTML documentation. + +ENUM_VALUES_PER_LINE = 4 + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. +# If the tag value is set to YES, a side panel will be generated +# containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). +# Windows users are probably better off using the HTML help feature. + +GENERATE_TREEVIEW = NONE + +# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, +# and Class Hierarchy pages using a tree view instead of an ordered list. + +USE_INLINE_TREES = NO + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +# Use this tag to change the font size of Latex formulas included +# as images in the HTML documentation. The default is 10. Note that +# when you change the font size after a successful doxygen run you need +# to manually remove any form_*.png images from the HTML output directory +# to force them to be regenerated. + +FORMULA_FONTSIZE = 10 + +# When the SEARCHENGINE tag is enable doxygen will generate a search box for the HTML output. The underlying search engine uses javascript +# and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP) or Qt help (GENERATE_QHP) +# there is already a search function so this one should typically +# be disabled. + +SEARCHENGINE = NO + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = NO + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, a4wide, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = YES + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = YES + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +# If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER. + +LATEX_SOURCE_CODE = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. +# This is useful +# if you want to understand what is going on. +# On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = NO + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = NO + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# in the INCLUDE_PATH (see below) will be search if a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = DOXYGEN + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all function-like macros that are alone +# on a line, have an all uppercase name, and do not end with a semicolon. Such +# function macros are typically used for boiler-plate code, and will confuse +# the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option is superseded by the HAVE_DOT option below. This is only a +# fallback. It is recommended to install and use dot, since it yields more +# powerful graphs. + +CLASS_DIAGRAMS = YES + +# You can define message sequence charts within doxygen comments using the \msc +# command. Doxygen will then run the mscgen tool (see +# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the +# documentation. The MSCGEN_PATH tag allows you to specify the directory where +# the mscgen tool resides. If left empty the tool is assumed to be found in the +# default search path. + +MSCGEN_PATH = + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = NO + +# By default doxygen will write a font called FreeSans.ttf to the output +# directory and reference it in all dot files that doxygen generates. This +# font does not include all possible unicode characters however, so when you need +# these (or just want a differently looking font) you can specify the font name +# using DOT_FONTNAME. You need need to make sure dot is able to find the font, +# which can be done by putting it in a standard location or by setting the +# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory +# containing the font. + +DOT_FONTNAME = FreeSans + +# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. +# The default size is 10pt. + +DOT_FONTSIZE = 10 + +# By default doxygen will tell dot to use the output directory to look for the +# FreeSans.ttf font (which doxygen will put there itself). If you specify a +# different font using DOT_FONTNAME you can set the path where dot +# can find it using this tag. + +DOT_FONTPATH = + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT options are set to YES then +# doxygen will generate a call dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable call graphs +# for selected functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then +# doxygen will generate a caller dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable caller +# graphs for selected functions only using the \callergraph command. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are png, jpg, or gif +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of +# nodes that will be shown in the graph. If the number of nodes in a graph +# becomes larger than this value, doxygen will truncate the graph, which is +# visualized by representing a node as a red box. Note that doxygen if the +# number of direct children of the root node in a graph is already larger than +# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note +# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. + +DOT_GRAPH_MAX_NODES = 50 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that the size of a graph can be further restricted by +# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, because dot on Windows does not +# seem to support this out of the box. Warning: Depending on the platform used, +# enabling this option may lead to badly anti-aliased labels on the edges of +# a graph (i.e. they become hard to read). + +DOT_TRANSPARENT = YES + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES diff --git a/src/sss_client/idmap/sss_nss_idmap.exports b/src/sss_client/idmap/sss_nss_idmap.exports new file mode 100644 index 0000000..d905bf2 --- /dev/null +++ b/src/sss_client/idmap/sss_nss_idmap.exports @@ -0,0 +1,77 @@ +SSS_NSS_IDMAP_0.0.1 { + + # public functions + global: + + sss_nss_getsidbyname; + sss_nss_getsidbyid; + sss_nss_getnamebysid; + sss_nss_getidbysid; + + # everything else is local + local: + *; +}; + +SSS_NSS_IDMAP_0.1.0 { + # public functions + global: + sss_nss_getorigbyname; + sss_nss_free_kv; +} SSS_NSS_IDMAP_0.0.1; + +SSS_NSS_IDMAP_0.2.0 { + # public functions + global: + sss_nss_getnamebycert; +} SSS_NSS_IDMAP_0.1.0; + +SSS_NSS_IDMAP_0.3.0 { + # public functions + global: + sss_nss_getlistbycert; +} SSS_NSS_IDMAP_0.2.0; + +SSS_NSS_IDMAP_0.4.0 { + # public functions + global: + sss_nss_getpwnam_timeout; + sss_nss_getpwuid_timeout; + sss_nss_getgrnam_timeout; + sss_nss_getgrgid_timeout; + sss_nss_getgrouplist_timeout; + sss_nss_getsidbyname_timeout; + sss_nss_getsidbyid_timeout; + sss_nss_getnamebysid_timeout; + sss_nss_getidbysid_timeout; + sss_nss_getorigbyname_timeout; + sss_nss_getnamebycert_timeout; + sss_nss_getlistbycert_timeout; +} SSS_NSS_IDMAP_0.3.0; + +SSS_NSS_IDMAP_0.5.0 { + # public functions + global: + sss_nss_getsidbyuid; + sss_nss_getsidbyuid_timeout; + sss_nss_getsidbygid; + sss_nss_getsidbygid_timeout; +} SSS_NSS_IDMAP_0.4.0; + +SSS_NSS_IDMAP_0.6.0 { + # public functions + global: + sss_nss_getorigbyusername; + sss_nss_getorigbyusername_timeout; + sss_nss_getorigbygroupname; + sss_nss_getorigbygroupname_timeout; +} SSS_NSS_IDMAP_0.5.0; + +SSS_NSS_IDMAP_0.7.0 { + # public functions + global: + sss_nss_getsidbyusername; + sss_nss_getsidbyusername_timeout; + sss_nss_getsidbygroupname; + sss_nss_getsidbygroupname_timeout; +} SSS_NSS_IDMAP_0.6.0; diff --git a/src/sss_client/idmap/sss_nss_idmap.h b/src/sss_client/idmap/sss_nss_idmap.h new file mode 100644 index 0000000..02e8bdb --- /dev/null +++ b/src/sss_client/idmap/sss_nss_idmap.h @@ -0,0 +1,644 @@ +/* + SSSD + + NSS Responder ID-mapping interface + + Authors: + Sumit Bose <sbose@redhat.com> + + Copyright (C) 2013 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#ifndef SSS_NSS_IDMAP_H_ +#define SSS_NSS_IDMAP_H_ + +#include <stdint.h> +#include <sys/types.h> +#include <pwd.h> +#include <grp.h> + +/** + * Object types + */ +enum sss_id_type { + SSS_ID_TYPE_NOT_SPECIFIED = 0, + SSS_ID_TYPE_UID, + SSS_ID_TYPE_GID, + SSS_ID_TYPE_BOTH /* used for user or magic private groups */ +}; + +struct sss_nss_kv { + char *key; + char *value; +}; + +/** + * @brief Find SID by fully qualified name + * + * @param[in] fq_name Fully qualified name of a user or a group + * @param[out] sid String representation of the SID of the requested user + * or group, must be freed by the caller + * @param[out] type Type of the object related to the given name + * + * @return + * - 0 (EOK): success, sid contains the requested SID + * - ENOENT: requested object was not found in the domain extracted from the given name + * - ENETUNREACH: SSSD does not know how to handle the domain extracted from the given name + * - ENOSYS: this call is not supported by the configured provider + * - EINVAL: input cannot be parsed + * - EIO: remote servers cannot be reached + * - EFAULT: any other error + */ +int sss_nss_getsidbyname(const char *fq_name, char **sid, + enum sss_id_type *type); + +/** + * @brief Find SID by fully qualified user name + * + * @param[in] fq_name Fully qualified name of a user + * @param[out] sid String representation of the SID of the requested user, + * must be freed by the caller + * @param[out] type Type of the object related to the given name + * + * @return + * - see #sss_nss_getsidbyname + */ +int sss_nss_getsidbyusername(const char *fq_name, + char **sid, + enum sss_id_type *type); + +/** + * @brief Find SID by fully qualified group name + * + * @param[in] fq_name Fully qualified name of a group + * @param[out] sid String representation of the SID of the requested group, + * must be freed by the caller + * @param[out] type Type of the object related to the given name + * + * @return + * - see #sss_nss_getsidbyname + */ +int sss_nss_getsidbygroupname(const char *fq_name, + char **sid, + enum sss_id_type *type); + +/** + * @brief Find SID by a POSIX UID or GID + * + * @param[in] id POSIX UID or GID + * @param[out] sid String representation of the SID of the requested user + * or group, must be freed by the caller + * @param[out] type Type of the object related to the given ID + * + * @return + * - see #sss_nss_getsidbyname + */ +int sss_nss_getsidbyid(uint32_t id, char **sid, enum sss_id_type *type); + +/** + * @brief Find SID by a POSIX UID + * + * @param[in] uid POSIX UID + * @param[out] sid String representation of the SID of the requested user, + * must be freed by the caller + * @param[out] type Type of the object related to the given ID + * + * @return + * - see #sss_nss_getsidbyname + */ +int sss_nss_getsidbyuid(uint32_t uid, char **sid, enum sss_id_type *type); + +/** + * @brief Find SID by a POSIX GID + * + * @param[in] gid POSIX GID + * @param[out] sid String representation of the SID of the requested group, + * must be freed by the caller + * @param[out] type Type of the object related to the given ID + * + * @return + * - see #sss_nss_getsidbyname + */ +int sss_nss_getsidbygid(uint32_t id, char **sid, enum sss_id_type *type); + +/** + * @brief Return the fully qualified name for the given SID + * + * @param[in] sid String representation of the SID + * @param[out] fq_name Fully qualified name of a user or a group, + * must be freed by the caller + * @param[out] type Type of the object related to the SID + * + * @return + * - see #sss_nss_getsidbyname + */ +int sss_nss_getnamebysid(const char *sid, char **fq_name, + enum sss_id_type *type); + +/** + * @brief Return the POSIX ID for the given SID + * + * @param[in] sid String representation of the SID + * @param[out] id POSIX ID related to the SID + * @param[out] id_type Type of the object related to the SID + * + * @return + * - see #sss_nss_getsidbyname + */ +int sss_nss_getidbysid(const char *sid, uint32_t *id, + enum sss_id_type *id_type); + +/** + * @brief Find original data by fully qualified name + * + * @param[in] fq_name Fully qualified name of a user or a group + * @param[out] kv_list A NULL terminate list of key-value pairs where the key + * is the attribute name in the cache of SSSD, + * must be freed by the caller with sss_nss_free_kv() + * @param[out] type Type of the object related to the given name + * + * @return + * - 0 (EOK): success, sid contains the requested SID + * - ENOENT: requested object was not found in the domain extracted from the given name + * - ENETUNREACH: SSSD does not know how to handle the domain extracted from the given name + * - ENOSYS: this call is not supported by the configured provider + * - EINVAL: input cannot be parsed + * - EIO: remote servers cannot be reached + * - EFAULT: any other error + */ +int sss_nss_getorigbyname(const char *fq_name, struct sss_nss_kv **kv_list, + enum sss_id_type *type); + +/** + * @brief Find original data by fully qualified user name + * + * @param[in] fq_name Fully qualified name of a user + * @param[out] kv_list A NULL terminate list of key-value pairs where the key + * is the attribute name in the cache of SSSD, + * must be freed by the caller with sss_nss_free_kv() + * @param[out] type Type of the object related to the given name + * + * @return + * - 0 (EOK): success + * - ENOENT: requested user was not found in the domain extracted from the given name + * - ENETUNREACH: SSSD does not know how to handle the domain extracted from the given name + * - ENOSYS: this call is not supported by the configured provider + * - EINVAL: input cannot be parsed + * - EIO: remote servers cannot be reached + * - EFAULT: any other error + */ +int sss_nss_getorigbyusername(const char *fq_name, struct sss_nss_kv **kv_list, + enum sss_id_type *type); + +/** + * @brief Find original data by fully qualified group name + * + * @param[in] fq_name Fully qualified name of a group + * @param[out] kv_list A NULL terminate list of key-value pairs where the key + * is the attribute name in the cache of SSSD, + * must be freed by the caller with sss_nss_free_kv() + * @param[out] type Type of the object related to the given name + * + * @return + * - 0 (EOK): success + * - ENOENT: requested group was not found in the domain extracted from the given name + * - ENETUNREACH: SSSD does not know how to handle the domain extracted from the given name + * - ENOSYS: this call is not supported by the configured provider + * - EINVAL: input cannot be parsed + * - EIO: remote servers cannot be reached + * - EFAULT: any other error + */ +int sss_nss_getorigbygroupname(const char *fq_name, struct sss_nss_kv **kv_list, + enum sss_id_type *type); + +/** + * @brief Return the fully qualified name for the given base64 encoded + * X.509 certificate in DER format + * + * @param[in] cert base64 encoded certificate + * @param[out] fq_name Fully qualified name of a user or a group, + * must be freed by the caller + * @param[out] type Type of the object related to the cert + * + * @return + * - see #sss_nss_getsidbyname + */ +int sss_nss_getnamebycert(const char *cert, char **fq_name, + enum sss_id_type *type); + +/** + * @brief Return a list of fully qualified names for the given base64 encoded + * X.509 certificate in DER format + * + * @param[in] cert base64 encoded certificate + * @param[out] fq_name List of fully qualified name of users or groups, + * must be freed by the caller + * @param[out] type List of types of the objects related to the cert + * + * @return + * - see #sss_nss_getsidbyname + */ +int sss_nss_getlistbycert(const char *cert, char ***fq_name, + enum sss_id_type **type); + +/** + * @brief Free key-value list returned by sss_nss_getorigbyXYZ() + * + * @param[in] kv_list Key-value list returned by sss_nss_getorigbyname() and + * similar calls. + */ +void sss_nss_free_kv(struct sss_nss_kv *kv_list); + +/** + * Flags to control the behavior and the results for sss_*_ex() calls + */ + +#define SSS_NSS_EX_FLAG_NO_FLAGS 0 + +/** Always request data from the server side, client must be privileged to do + * so, see nss_trusted_users option in man sssd.conf for details. + * This flag cannot be used together with SSS_NSS_EX_FLAG_INVALIDATE_CACHE */ +#define SSS_NSS_EX_FLAG_NO_CACHE (1 << 0) + +/** Invalidate the data in the caches, client must be privileged to do + * so, see nss_trusted_users option in man sssd.conf for details. + * This flag cannot be used together with SSS_NSS_EX_FLAG_NO_CACHE */ +#define SSS_NSS_EX_FLAG_INVALIDATE_CACHE (1 << 1) + +#ifdef IPA_389DS_PLUGIN_HELPER_CALLS + +/** + * @brief Return user information based on the user name + * + * @param[in] name same as for getpwnam_r(3) + * @param[in] pwd same as for getpwnam_r(3) + * @param[in] buffer same as for getpwnam_r(3) + * @param[in] buflen same as for getpwnam_r(3) + * @param[out] result same as for getpwnam_r(3) + * @param[in] flags flags to control the behavior and the results of the + * call + * @param[in] timeout timeout in milliseconds + * + * @return + * - 0: + * - ENOENT: no user with the given name found + * - ERANGE: Insufficient buffer space supplied + * - ETIME: request timed out but was send to SSSD + * - ETIMEDOUT: request timed out but was not send to SSSD + */ +int sss_nss_getpwnam_timeout(const char *name, struct passwd *pwd, + char *buffer, size_t buflen, + struct passwd **result, + uint32_t flags, unsigned int timeout); + +/** + * @brief Return user information based on the user uid + * + * @param[in] uid same as for getpwuid_r(3) + * @param[in] pwd same as for getpwuid_r(3) + * @param[in] buffer same as for getpwuid_r(3) + * @param[in] buflen same as for getpwuid_r(3) + * @param[out] result same as for getpwuid_r(3) + * @param[in] flags flags to control the behavior and the results of the + * call + * @param[in] timeout timeout in milliseconds + * + * @return + * - 0: + * - ENOENT: no user with the given uid found + * - ERANGE: Insufficient buffer space supplied + * - ETIME: request timed out but was send to SSSD + * - ETIMEDOUT: request timed out but was not send to SSSD + */ +int sss_nss_getpwuid_timeout(uid_t uid, struct passwd *pwd, + char *buffer, size_t buflen, + struct passwd **result, + uint32_t flags, unsigned int timeout); + +/** + * @brief Return group information based on the group name + * + * @param[in] name same as for getgrnam_r(3) + * @param[in] pwd same as for getgrnam_r(3) + * @param[in] buffer same as for getgrnam_r(3) + * @param[in] buflen same as for getgrnam_r(3) + * @param[out] result same as for getgrnam_r(3) + * @param[in] flags flags to control the behavior and the results of the + * call + * @param[in] timeout timeout in milliseconds + * + * @return + * - 0: + * - ENOENT: no group with the given name found + * - ERANGE: Insufficient buffer space supplied + * - ETIME: request timed out but was send to SSSD + * - ETIMEDOUT: request timed out but was not send to SSSD + */ +int sss_nss_getgrnam_timeout(const char *name, struct group *grp, + char *buffer, size_t buflen, struct group **result, + uint32_t flags, unsigned int timeout); + +/** + * @brief Return group information based on the group gid + * + * @param[in] gid same as for getgrgid_r(3) + * @param[in] pwd same as for getgrgid_r(3) + * @param[in] buffer same as for getgrgid_r(3) + * @param[in] buflen same as for getgrgid_r(3) + * @param[out] result same as for getgrgid_r(3) + * @param[in] flags flags to control the behavior and the results of the + * call + * @param[in] timeout timeout in milliseconds + * + * @return + * - 0: + * - ENOENT: no group with the given gid found + * - ERANGE: Insufficient buffer space supplied + * - ETIME: request timed out but was send to SSSD + * - ETIMEDOUT: request timed out but was not send to SSSD + */ +int sss_nss_getgrgid_timeout(gid_t gid, struct group *grp, + char *buffer, size_t buflen, struct group **result, + uint32_t flags, unsigned int timeout); + +/** + * @brief Return a list of groups to which a user belongs + * + * @param[in] name name of the user + * @param[in] group same as second argument of getgrouplist(3) + * @param[in] groups array of gid_t of size ngroups, will be filled + * with GIDs of groups the user belongs to + * @param[in,out] ngroups size of the groups array on input. On output it + * will contain the actual number of groups the + * user belongs to. With a return value of 0 the + * groups array was large enough to hold all group. + * With a return valu of ERANGE the array was not + * large enough and ngroups will have the needed + * size. + * @param[in] flags flags to control the behavior and the results of + * the call + * @param[in] timeout timeout in milliseconds + * + * @return + * - 0: success + * - ENOENT: no user with the given name found + * - ERANGE: Insufficient buffer space supplied + * - ETIME: request timed out but was send to SSSD + * - ETIMEDOUT: request timed out but was not send to SSSD + */ +int sss_nss_getgrouplist_timeout(const char *name, gid_t group, + gid_t *groups, int *ngroups, + uint32_t flags, unsigned int timeout); +/** + * @brief Find SID by fully qualified name with timeout + * + * @param[in] fq_name Fully qualified name of a user or a group + * @param[in] timeout timeout in milliseconds + * @param[out] sid String representation of the SID of the requested user + * or group, must be freed by the caller + * @param[out] type Type of the object related to the given name + * + * @return + * - 0 (EOK): success, sid contains the requested SID + * - ENOENT: requested object was not found in the domain extracted from the given name + * - ENETUNREACH: SSSD does not know how to handle the domain extracted from the given name + * - ENOSYS: this call is not supported by the configured provider + * - EINVAL: input cannot be parsed + * - EIO: remote servers cannot be reached + * - EFAULT: any other error + * - ETIME: request timed out but was send to SSSD + * - ETIMEDOUT: request timed out but was not send to SSSD + */ +int sss_nss_getsidbyname_timeout(const char *fq_name, unsigned int timeout, + char **sid, enum sss_id_type *type); + +/** + * @brief Find SID by fully qualified user name with timeout + * + * @param[in] fq_name Fully qualified name of a user + * @param[in] timeout timeout in milliseconds + * @param[out] sid String representation of the SID of the requested user, + * must be freed by the caller + * @param[out] type Type of the object related to the given name + * + * @return + * - see #sss_nss_getsidbyname_timeout + */ +int sss_nss_getsidbyusername_timeout(const char *fq_name, + unsigned int timeout, + char **sid, + enum sss_id_type *type); + +/** + * @brief Find SID by fully qualified group name with timeout + * + * @param[in] fq_name Fully qualified name of a group + * @param[in] timeout timeout in milliseconds + * @param[out] sid String representation of the SID of the requested group, + * must be freed by the caller + * @param[out] type Type of the object related to the given name + * + * @return + * - see #sss_nss_getsidbyname_timeout + */ +int sss_nss_getsidbygroupname_timeout(const char *fq_name, + unsigned int timeout, + char **sid, + enum sss_id_type *type); + +/** + * @brief Find SID by a POSIX UID or GID with timeout + * + * @param[in] id POSIX UID or GID + * @param[in] timeout timeout in milliseconds + * @param[out] sid String representation of the SID of the requested user + * or group, must be freed by the caller + * @param[out] type Type of the object related to the given ID + * + * @return + * - see #sss_nss_getsidbyname_timeout + */ +int sss_nss_getsidbyid_timeout(uint32_t id, unsigned int timeout, + char **sid, enum sss_id_type *type); +/** + * @brief Find SID by a POSIX UID with timeout + * + * @param[in] uid POSIX UID + * @param[in] timeout timeout in milliseconds + * @param[out] sid String representation of the SID of the requested user, + * must be freed by the caller + * @param[out] type Type of the object related to the given ID + * + * @return + * - see #sss_nss_getsidbyname_timeout + */ +int sss_nss_getsidbyuid_timeout(uint32_t uid, unsigned int timeout, + char **sid, enum sss_id_type *type); + +/** + * @brief Find SID by a POSIX GID with timeout + * + * @param[in] gid POSIX GID + * @param[in] timeout timeout in milliseconds + * @param[out] sid String representation of the SID of the requested group, + * must be freed by the caller + * @param[out] type Type of the object related to the given ID + * + * @return + * - see #sss_nss_getsidbyname_timeout + */ +int sss_nss_getsidbygid_timeout(uint32_t gid, unsigned int timeout, + char **sid, enum sss_id_type *type); + + +/** + * @brief Return the fully qualified name for the given SID with timeout + * + * @param[in] sid String representation of the SID + * @param[in] timeout timeout in milliseconds + * @param[out] fq_name Fully qualified name of a user or a group, + * must be freed by the caller + * @param[out] type Type of the object related to the SID + * + * @return + * - see #sss_nss_getsidbyname_timeout + */ +int sss_nss_getnamebysid_timeout(const char *sid, unsigned int timeout, + char **fq_name, enum sss_id_type *type); + +/** + * @brief Return the POSIX ID for the given SID with timeout + * + * @param[in] sid String representation of the SID + * @param[in] timeout timeout in milliseconds + * @param[out] id POSIX ID related to the SID + * @param[out] id_type Type of the object related to the SID + * + * @return + * - see #sss_nss_getsidbyname_timeout + */ +int sss_nss_getidbysid_timeout(const char *sid, unsigned int timeout, + uint32_t *id, enum sss_id_type *id_type); + +/** + * @brief Find original data by fully qualified name with timeout + * + * @param[in] fq_name Fully qualified name of a user or a group + * @param[in] timeout timeout in milliseconds + * @param[out] kv_list A NULL terminate list of key-value pairs where the key + * is the attribute name in the cache of SSSD, + * must be freed by the caller with sss_nss_free_kv() + * @param[out] type Type of the object related to the given name + * + * @return + * - 0 (EOK): success, sid contains the requested SID + * - ENOENT: requested object was not found in the domain extracted from the given name + * - ENETUNREACH: SSSD does not know how to handle the domain extracted from the given name + * - ENOSYS: this call is not supported by the configured provider + * - EINVAL: input cannot be parsed + * - EIO: remote servers cannot be reached + * - EFAULT: any other error + * - ETIME: request timed out but was send to SSSD + * - ETIMEDOUT: request timed out but was not send to SSSD + */ +int sss_nss_getorigbyname_timeout(const char *fq_name, unsigned int timeout, + struct sss_nss_kv **kv_list, + enum sss_id_type *type); + +/** + * @brief Find original data by fully qualified user name with timeout + * + * @param[in] fq_name Fully qualified name of a user + * @param[in] timeout timeout in milliseconds + * @param[out] kv_list A NULL terminate list of key-value pairs where the key + * is the attribute name in the cache of SSSD, + * must be freed by the caller with sss_nss_free_kv() + * @param[out] type Type of the object related to the given name + * + * @return + * - 0 (EOK): success + * - ENOENT: requested user was not found in the domain extracted from the given name + * - ENETUNREACH: SSSD does not know how to handle the domain extracted from the given name + * - ENOSYS: this call is not supported by the configured provider + * - EINVAL: input cannot be parsed + * - EIO: remote servers cannot be reached + * - EFAULT: any other error + * - ETIME: request timed out but was send to SSSD + * - ETIMEDOUT: request timed out but was not send to SSSD + */ +int sss_nss_getorigbyusername_timeout(const char *fq_name, unsigned int timeout, + struct sss_nss_kv **kv_list, + enum sss_id_type *type); + +/** + * @brief Find original data by fully qualified group name with timeout + * + * @param[in] fq_name Fully qualified name of a group + * @param[in] timeout timeout in milliseconds + * @param[out] kv_list A NULL terminate list of key-value pairs where the key + * is the attribute name in the cache of SSSD, + * must be freed by the caller with sss_nss_free_kv() + * @param[out] type Type of the object related to the given name + * + * @return + * - 0 (EOK): success + * - ENOENT: requested group was not found in the domain extracted from the given name + * - ENETUNREACH: SSSD does not know how to handle the domain extracted from the given name + * - ENOSYS: this call is not supported by the configured provider + * - EINVAL: input cannot be parsed + * - EIO: remote servers cannot be reached + * - EFAULT: any other error + * - ETIME: request timed out but was send to SSSD + * - ETIMEDOUT: request timed out but was not send to SSSD + */ +int sss_nss_getorigbygroupname_timeout(const char *fq_name, unsigned int timeout, + struct sss_nss_kv **kv_list, + enum sss_id_type *type); + +/** + * @brief Return the fully qualified name for the given base64 encoded + * X.509 certificate in DER format with timeout + * + * @param[in] cert base64 encoded certificate + * @param[in] timeout timeout in milliseconds + * @param[out] fq_name Fully qualified name of a user or a group, + * must be freed by the caller + * @param[out] type Type of the object related to the cert + * + * @return + * - see #sss_nss_getsidbyname_timeout + */ +int sss_nss_getnamebycert_timeout(const char *cert, unsigned int timeout, + char **fq_name, enum sss_id_type *type); + +/** + * @brief Return a list of fully qualified names for the given base64 encoded + * X.509 certificate in DER format with timeout + * + * @param[in] cert base64 encoded certificate + * @param[in] timeout timeout in milliseconds + * @param[out] fq_name List of fully qualified name of users or groups, + * must be freed by the caller + * @param[out] type List of types of the objects related to the cert + * + * @return + * - see #sss_nss_getsidbyname_timeout + */ +int sss_nss_getlistbycert_timeout(const char *cert, unsigned int timeout, + char ***fq_name, enum sss_id_type **type); + +#endif /* IPA_389DS_PLUGIN_HELPER_CALLS */ +#endif /* SSS_NSS_IDMAP_H_ */ diff --git a/src/sss_client/idmap/sss_nss_idmap.pc.in b/src/sss_client/idmap/sss_nss_idmap.pc.in new file mode 100644 index 0000000..8676882 --- /dev/null +++ b/src/sss_client/idmap/sss_nss_idmap.pc.in @@ -0,0 +1,11 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: sss_nss_idmap +Description: NSS Responder ID-SID mapping interface +Version: @VERSION@ +Libs: -L${libdir} -lsss_nss_idmap +Cflags: +URL: https://github.com/SSSD/sssd/ diff --git a/src/sss_client/idmap/sss_nss_idmap_private.h b/src/sss_client/idmap/sss_nss_idmap_private.h new file mode 100644 index 0000000..afcd8e3 --- /dev/null +++ b/src/sss_client/idmap/sss_nss_idmap_private.h @@ -0,0 +1,30 @@ +/* + SSSD + + NSS Responder ID-mapping interface - private calls + + Authors: + Sumit Bose <sbose@redhat.com> + + Copyright (C) 2017 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#ifndef SSS_NSS_IDMAP_PRIVATE_H_ +#define SSS_NSS_IDMAP_PRIVATE_H_ + +int sss_nss_timedlock(unsigned int timeout_ms, int *time_left_ms); + +#endif /* SSS_NSS_IDMAP_PRIVATE_H_ */ diff --git a/src/sss_client/krb5_authdata_int.h b/src/sss_client/krb5_authdata_int.h new file mode 100644 index 0000000..bafff71 --- /dev/null +++ b/src/sss_client/krb5_authdata_int.h @@ -0,0 +1,185 @@ +/* + SSSD - MIT Kerberos authdata plugin + + This file contains definitions and declarations to build authdata plugins + for MIT Kerberos outside of the MIT Kerberos source tree. +*/ + +#ifndef _KRB5_AUTHDATA_INT_H +#define _KRB5_AUTHDATA_INT_H + +krb5_error_code KRB5_CALLCONV +krb5_ser_pack_int32(krb5_int32, krb5_octet **, size_t *); + +krb5_error_code KRB5_CALLCONV +krb5_ser_unpack_int32(krb5_int32 *, krb5_octet **, size_t *); + +krb5_error_code KRB5_CALLCONV +krb5_ser_pack_bytes(krb5_octet *, size_t, krb5_octet **, size_t *); + +#define AD_USAGE_AS_REQ 0x01 +#define AD_USAGE_TGS_REQ 0x02 +#define AD_USAGE_AP_REQ 0x04 +#define AD_USAGE_KDC_ISSUED 0x08 +#define AD_USAGE_MASK 0x0F +#define AD_INFORMATIONAL 0x10 + +struct _krb5_authdata_context; +typedef struct _krb5_authdata_context *krb5_authdata_context; + +typedef void +(*authdata_client_plugin_flags_proc)(krb5_context kcontext, + void *plugin_context, + krb5_authdatatype ad_type, + krb5_flags *flags); + +typedef krb5_error_code +(*authdata_client_plugin_init_proc)(krb5_context context, + void **plugin_context); +typedef void +(*authdata_client_plugin_fini_proc)(krb5_context kcontext, + void *plugin_context); + +typedef krb5_error_code +(*authdata_client_request_init_proc)(krb5_context kcontext, + struct _krb5_authdata_context *context, + void *plugin_context, + void **request_context); + +typedef void +(*authdata_client_request_fini_proc)(krb5_context kcontext, + struct _krb5_authdata_context *context, + void *plugin_context, + void *request_context); + +typedef krb5_error_code +(*authdata_client_import_authdata_proc)(krb5_context kcontext, + struct _krb5_authdata_context *context, + void *plugin_context, + void *request_context, + krb5_authdata **authdata, + krb5_boolean kdc_issued_flag, + krb5_const_principal issuer); + +typedef krb5_error_code +(*authdata_client_export_authdata_proc)(krb5_context kcontext, + struct _krb5_authdata_context *context, + void *plugin_context, + void *request_context, + krb5_flags usage, + krb5_authdata ***authdata); + +typedef krb5_error_code +(*authdata_client_get_attribute_types_proc)(krb5_context kcontext, + struct _krb5_authdata_context *context, + void *plugin_context, + void *request_context, + krb5_data **attrs); + +typedef krb5_error_code +(*authdata_client_get_attribute_proc)(krb5_context kcontext, + struct _krb5_authdata_context *context, + void *plugin_context, + void *request_context, + const krb5_data *attribute, + krb5_boolean *authenticated, + krb5_boolean *complete, + krb5_data *value, + krb5_data *display_value, + int *more); + +typedef krb5_error_code +(*authdata_client_set_attribute_proc)(krb5_context kcontext, + struct _krb5_authdata_context *context, + void *plugin_context, + void *request_context, + krb5_boolean complete, + const krb5_data *attribute, + const krb5_data *value); + +typedef krb5_error_code +(*authdata_client_delete_attribute_proc)(krb5_context kcontext, + struct _krb5_authdata_context *context, + void *plugin_context, + void *request_context, + const krb5_data *attribute); + +typedef krb5_error_code +(*authdata_client_export_internal_proc)(krb5_context kcontext, + struct _krb5_authdata_context *context, + void *plugin_context, + void *request_context, + krb5_boolean restrict_authenticated, + void **ptr); + +typedef void +(*authdata_client_free_internal_proc)(krb5_context kcontext, + struct _krb5_authdata_context *context, + void *plugin_context, + void *request_context, + void *ptr); + +typedef krb5_error_code +(*authdata_client_verify_proc)(krb5_context kcontext, + struct _krb5_authdata_context *context, + void *plugin_context, + void *request_context, + const krb5_auth_context *auth_context, + const krb5_keyblock *key, + const krb5_ap_req *req); + +typedef krb5_error_code +(*authdata_client_size_proc)(krb5_context kcontext, + struct _krb5_authdata_context *context, + void *plugin_context, + void *request_context, + size_t *sizep); + +typedef krb5_error_code +(*authdata_client_externalize_proc)(krb5_context kcontext, + struct _krb5_authdata_context *context, + void *plugin_context, + void *request_context, + krb5_octet **buffer, + size_t *lenremain); + +typedef krb5_error_code +(*authdata_client_internalize_proc)(krb5_context kcontext, + struct _krb5_authdata_context *context, + void *plugin_context, + void *request_context, + krb5_octet **buffer, + size_t *lenremain); + +typedef krb5_error_code +(*authdata_client_copy_proc)(krb5_context kcontext, + struct _krb5_authdata_context *context, + void *plugin_context, + void *request_context, + void *dst_plugin_context, + void *dst_request_context); + +typedef struct krb5plugin_authdata_client_ftable_v0 { + const char *name; + krb5_authdatatype *ad_type_list; + authdata_client_plugin_init_proc init; + authdata_client_plugin_fini_proc fini; + authdata_client_plugin_flags_proc flags; + authdata_client_request_init_proc request_init; + authdata_client_request_fini_proc request_fini; + authdata_client_get_attribute_types_proc get_attribute_types; + authdata_client_get_attribute_proc get_attribute; + authdata_client_set_attribute_proc set_attribute; + authdata_client_delete_attribute_proc delete_attribute; + authdata_client_export_authdata_proc export_authdata; + authdata_client_import_authdata_proc import_authdata; + authdata_client_export_internal_proc export_internal; + authdata_client_free_internal_proc free_internal; + authdata_client_verify_proc verify; + authdata_client_size_proc size; + authdata_client_externalize_proc externalize; + authdata_client_internalize_proc internalize; + authdata_client_copy_proc copy; /* optional */ +} krb5plugin_authdata_client_ftable_v0; + +#endif /* _KRB5_AUTHDATA_INT_H */ diff --git a/src/sss_client/nfs/nfsidmap_internal.h b/src/sss_client/nfs/nfsidmap_internal.h new file mode 100644 index 0000000..07547f8 --- /dev/null +++ b/src/sss_client/nfs/nfsidmap_internal.h @@ -0,0 +1,78 @@ +/* + * nfsidmap_internal.h + * + * nfs idmapping library, primarily for nfs4 client/server kernel idmapping + * and for userland nfs4 idmapping by acl libraries. + * + * Copyright (c) 2004 The Regents of the University of Michigan. + * All rights reserved. + * + * Andy Adamson <andros@umich.edu> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +char *get_default_domain(void); +struct conf_list *get_local_realms(void); + +typedef struct trans_func * (*libnfsidmap_plugin_init_t)(void); + +struct trans_func { + char *name; + int (*init)(void); + int (*princ_to_ids)(char *secname, char *princ, uid_t *uid, gid_t *gid, + extra_mapping_params **ex); + int (*name_to_uid)(char *name, uid_t *uid); + int (*name_to_gid)(char *name, gid_t *gid); + int (*uid_to_name)(uid_t uid, char *domain, char *name, size_t len); + int (*gid_to_name)(gid_t gid, char *domain, char *name, size_t len); + int (*gss_princ_to_grouplist)(char *secname, char *princ, gid_t *groups, + int *ngroups, extra_mapping_params **ex); +}; + +struct mapping_plugin { + void *dl_handle; + struct trans_func *trans; +}; + +typedef enum { + IDTYPE_USER = 1, + IDTYPE_GROUP = 2 +} idtypes; + +extern int idmap_verbosity; +extern nfs4_idmap_log_function_t idmap_log_func; +/* Level zero always prints, others print depending on verbosity level */ +#define IDMAP_LOG(LVL, MSG) \ + do { if (LVL <= idmap_verbosity) (*idmap_log_func)MSG; } while (0) + + +/* + * from libnfsidmap's cfg.h (same license as above) + * Copyright (c) 1998, 1999, 2001 Niklas Hallqvist. All rights reserved. + * Copyright (c) 2000, 2003 H�kan Olsson. All rights reserved. + */ +extern const char *conf_get_str(const char *, const char *); diff --git a/src/sss_client/nfs/sss_nfs_client.c b/src/sss_client/nfs/sss_nfs_client.c new file mode 100644 index 0000000..571256a --- /dev/null +++ b/src/sss_client/nfs/sss_nfs_client.c @@ -0,0 +1,589 @@ +/* + SSSD + + NFS Client + + Copyright (C) Noam Meltzer <noam@primarydata.com> 2013-2014 + Copyright (C) Noam Meltzer <tsnoam@gmail.com> 2014- + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include "config.h" + +#include <stddef.h> +#include <stdlib.h> +#include <sys/types.h> +#include <errno.h> +#include <string.h> + +#include <nfsidmap.h> + +#ifdef HAVE_NFSIDMAP_PLUGIN_H +#include <nfsidmap_plugin.h> +#else /* fallback to internal header file with older version of libnfsidmap */ +#include "nfsidmap_internal.h" +#define nfsidmap_config_get conf_get_str +#endif + +#include "sss_client/sss_cli.h" +#include "sss_client/nss_mc.h" + + +/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ +#define PLUGIN_NAME "sss_nfs" +#define CONF_SECTION "sss_nfs" +#define CONF_USE_MC "memcache" +#define REPLY_ID_OFFSET (8) +#define REPLY_NAME_OFFSET (REPLY_ID_OFFSET + 8) +#define BUF_LEN (4096) +#define USE_MC_DEFAULT true + + +/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ +static char sss_nfs_plugin_name[] = PLUGIN_NAME; +static char nfs_conf_sect[] = CONF_SECTION; +static char nfs_conf_use_mc[] = CONF_USE_MC; + +static bool nfs_use_mc = USE_MC_DEFAULT; + + +/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ +/* Forward declarations */ +static int send_recv(uint8_t **repp, size_t *rep_lenp, enum sss_cli_command cmd, + const void *req, size_t req_len); +static int reply_to_id(id_t *idp, uint8_t *rep, size_t rep_len); +static int reply_to_name(char *name, size_t len, uint8_t *rep, size_t rep_len); + + +/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ +/* get from memcache functions */ +static int get_uid_from_mc(id_t *uid, const char *name) +{ + int rc = 0; + struct passwd pwd; + char *buf = NULL; + char *p = NULL; + size_t buflen = 0; + size_t len = 0; + + if (!nfs_use_mc) { + return -1; + } + + rc = sss_strnlen(name, SSS_NAME_MAX, &len); + if (rc != 0) { + IDMAP_LOG(0, ("%s: no-strnlen; rc=%i", __func__, rc)); + return rc; + } + + do { + buflen += BUF_LEN; + if ((p = realloc(buf, buflen)) == NULL) { + rc = ENOMEM; + goto done; + } + buf = p; + rc = sss_nss_mc_getpwnam(name, len, &pwd, buf, buflen); + } while (rc == ERANGE); + + if (rc == 0) { + IDMAP_LOG(1, ("found user %s in memcache", name)); + *uid = pwd.pw_uid; + } else { + IDMAP_LOG(1, ("user %s not in memcache", name)); + } + +done: + free(buf); + return rc; +} + +static int get_gid_from_mc(id_t *gid, const char *name) +{ + int rc = 0; + struct group grp; + char *buf = NULL; + char *p = NULL; + size_t buflen = 0; + size_t len; + + if (!nfs_use_mc) { + return -1; + } + + rc = sss_strnlen(name, SSS_NAME_MAX, &len); + if (rc != 0) { + IDMAP_LOG(0, ("%s: no-strnlen; rc=%i", __func__, rc)); + return rc; + } + + do { + buflen += BUF_LEN; + if ((p = realloc(buf, buflen)) == NULL) { + rc = ENOMEM; + goto done; + } + buf = p; + rc = sss_nss_mc_getgrnam(name, len, &grp, buf, buflen); + } while (rc == ERANGE); + + if (rc == 0) { + IDMAP_LOG(1, ("found group %s in memcache", name)); + *gid = grp.gr_gid; + } else { + IDMAP_LOG(1, ("group %s not in memcache", name)); + } + +done: + free(buf); + return rc; +} + +static int get_user_from_mc(char *name, size_t len, uid_t uid) +{ + int rc; + struct passwd pwd; + char *buf = NULL; + char *p = NULL; + size_t buflen = 0; + size_t pw_name_len; + + if (!nfs_use_mc) { + return -1; + } + + do { + buflen += BUF_LEN; + if ((p = realloc(buf, buflen)) == NULL) { + rc = ENOMEM; + goto done; + } + buf = p; + rc = sss_nss_mc_getpwuid(uid, &pwd, buf, buflen); + } while (rc == ERANGE); + + if (rc == 0) { + pw_name_len = strlen(pwd.pw_name) + 1; + if (pw_name_len > len) { + IDMAP_LOG(0, ("%s: reply too long; pw_name_len=%lu, len=%lu", + __func__, pw_name_len, len)); + rc = ENOBUFS; + } + IDMAP_LOG(1, ("found uid %i in memcache", uid)); + memcpy(name, pwd.pw_name, pw_name_len); + } else { + IDMAP_LOG(1, ("uid %i not in memcache", uid)); + } + +done: + free(buf); + return rc; +} + +static int get_group_from_mc(char *name, size_t len, id_t gid) +{ + int rc; + struct group grp; + char *buf = NULL; + char *p = NULL; + size_t buflen = 0; + size_t gr_name_len; + + if (!nfs_use_mc) { + return -1; + } + + do { + buflen += BUF_LEN; + if ((p = realloc(buf, buflen)) == NULL) { + rc = ENOMEM; + goto done; + } + buf = p; + rc = sss_nss_mc_getgrgid(gid, &grp, buf, buflen); + } while (rc == ERANGE); + + if (rc == 0) { + gr_name_len = strlen(grp.gr_name) + 1; + if (gr_name_len > len) { + IDMAP_LOG(0, ("%s: reply too long; gr_name_len=%lu, len=%lu", + __func__, gr_name_len, len)); + rc = ENOBUFS; + } + IDMAP_LOG(1, ("found gid %i in memcache", gid)); + memcpy(name, grp.gr_name, gr_name_len); + } else { + IDMAP_LOG(1, ("gid %i not in memcache", gid)); + } + +done: + free(buf); + return rc; +} + +/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ +static int name_to_id(const char *name, id_t *id, enum sss_cli_command cmd) +{ + int rc; + uint8_t *rep = NULL; + size_t rep_len = 0; + size_t name_len; + + rc = sss_strnlen(name, SSS_NAME_MAX, &name_len); + if (rc != 0) { + IDMAP_LOG(0, ("%s: no-strnlen; rc=%i", __func__, rc)); + return rc; + } + + rc = send_recv(&rep, &rep_len, cmd, name, name_len + 1); + if (rc == 0) { + rc = reply_to_id(id, rep, rep_len); + } + + free(rep); + + return rc; +} + +static int id_to_name(char *name, size_t len, id_t id, + enum sss_cli_command cmd) +{ + int rc; + size_t rep_len = 0; + size_t req_len = sizeof(id_t); + uint8_t *rep = NULL; + uint8_t req[req_len]; + + memcpy(req, &id, req_len); + rc = send_recv(&rep, &rep_len, cmd, &req, req_len); + if (rc == 0) { + rc = reply_to_name(name, len, rep, rep_len); + } + + free(rep); + + return rc; +} + +/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ +static int send_recv(uint8_t **rep, size_t *rep_len, enum sss_cli_command cmd, + const void *req, size_t req_len) +{ + int err = 0; + enum nss_status req_rc; + struct sss_cli_req_data rd; + + rd.data = req; + rd.len = req_len; + + sss_nss_lock(); + req_rc = sss_nss_make_request(cmd, &rd, rep, rep_len, &err); + sss_nss_unlock(); + + if (req_rc == NSS_STATUS_NOTFOUND) { + return ENOENT; + } + if (req_rc != NSS_STATUS_SUCCESS) { + IDMAP_LOG(0, ("no-make-request; err=%i", err)); + return EPIPE; + } + + return 0; +} + +static int reply_to_id(id_t *idp, uint8_t *rep, size_t rep_len) +{ + int rc = 0; + id_t id; + uint32_t num_results = 0; + + if (rep_len < sizeof(uint32_t)) { + IDMAP_LOG(0, ("%s: reply too small; rep_len=%lu", __func__, rep_len)); + rc = EBADMSG; + goto done; + } + + SAFEALIGN_COPY_UINT32(&num_results, rep, NULL); + if (num_results > 1) { + IDMAP_LOG(0, ("%s: too many results (%lu)", __func__, num_results)); + rc = EBADMSG; + goto done; + } + if (num_results == 0) { + rc = ENOENT; + goto done; + } + if (rep_len < sizeof(uint32_t) + REPLY_ID_OFFSET) { + IDMAP_LOG(0, ("%s: reply too small(2); rep_len=%lu", __func__, + rep_len)); + rc = EBADMSG; + goto done; + } + + SAFEALIGN_COPY_UINT32(&id, rep + REPLY_ID_OFFSET, NULL); + *idp = id; + +done: + return rc; +} + +static int reply_to_name(char *name, size_t len, uint8_t *rep, size_t rep_len) +{ + int rc = 0; + uint32_t num_results = 0; + const char *buf; + size_t buf_len; + size_t offset; + + if (rep_len < sizeof(uint32_t)) { + IDMAP_LOG(0, ("%s: reply too small; rep_len=%lu", __func__, rep_len)); + rc = EBADMSG; + goto done; + } + + SAFEALIGN_COPY_UINT32(&num_results, rep, NULL); + if (num_results > 1) { + IDMAP_LOG(0, ("%s: too many results (%lu)", __func__, num_results)); + rc = EBADMSG; + goto done; + } + if (num_results == 0) { + rc = ENOENT; + goto done; + } + if (rep_len < sizeof(uint32_t) + REPLY_NAME_OFFSET) { + IDMAP_LOG(0, ("%s: reply too small(2); rep_len=%lu", __func__, + rep_len)); + rc = EBADMSG; + goto done; + } + + buf = (const char *)(rep + REPLY_NAME_OFFSET); + buf_len = rep_len - REPLY_NAME_OFFSET; + offset = 0; + rc = sss_readrep_copy_string(buf, &offset, &buf_len, &len, &name, NULL); + if (rc != 0) { + rc = -rc; + } + +done: + return rc; +} + +/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ +/* configuration parsing aids */ +static bool str_equal(const char *s1, const char *s2) +{ + bool res = false; + size_t len1; + size_t len2; + + len1 = strlen(s1); + len2 = strlen(s2); + + if (len1 == len2) { + res = (strncasecmp(s1, s2, len1) == 0); + } + + return res; +} + +static int nfs_conf_get_bool(const char *sect, const char *attr, int def) +{ + int res; + const char *val; + + res = def; + val = nfsidmap_config_get(sect, attr); + if (val) { + res = (str_equal("1", val) || + str_equal("yes", val) || + str_equal("true", val) || + str_equal("on", val)); + } + + return res; +} + + +/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ +/* libnfsidmap return-code aids */ + +/* + * we only want to return 0 or ENOENT; otherwise libnfsidmap will stop + * translation instead of proceeding to the next translation plugin + */ +int normalise_rc(int rc) { + int res; + + res = rc; + if (res != 0 && res != ENOENT) { + res = ENOENT; + } + + return res; +} + +/* log the actual rc from our code (to be used before normalising the rc) */ +void log_actual_rc(const char *trans_name, int rc) { + char tmp[80]; + IDMAP_LOG(1, ("%s: rc=%i msg=%s", trans_name, rc, + strerror_r(rc, tmp, sizeof(tmp)))); +} + + +/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ +/* The external interface */ +static int sss_nfs_init(void) +{ + nfs_use_mc = nfs_conf_get_bool(nfs_conf_sect, nfs_conf_use_mc, + USE_MC_DEFAULT); + IDMAP_LOG(1, ("%s: use memcache: %i", __func__, nfs_use_mc)); + + return 0; +} + +static int sss_nfs_princ_to_ids(char *secname, char *princ, uid_t *uid, + gid_t *gid, extra_mapping_params **ex) +{ + IDMAP_LOG(0, ("%s: not implemented", __func__)); + return -ENOENT; +} + +static int sss_nfs_name_to_uid(char *name, uid_t *uid) +{ + int rc; + size_t name_len = 0; + + if (name == NULL) { + IDMAP_LOG(0, ("%s: name is null", __func__)); + return -EINVAL; + } + if (uid == NULL) { + IDMAP_LOG(0, ("%s: uid is null", __func__)); + return -EINVAL; + } + + rc = sss_strnlen(name, SSS_NAME_MAX, &name_len); + if (rc != 0) { + IDMAP_LOG(0, ("%s: no-strnlen; rc=%i", __func__, rc)); + return -rc; + } + + rc = get_uid_from_mc(uid, name); + if (rc != 0) { + rc = name_to_id(name, uid, SSS_NSS_GETPWNAM); + } + + log_actual_rc(__func__, rc); + rc = normalise_rc(rc); + + return -rc; +} + +static int sss_nfs_name_to_gid(char *name, gid_t *gid) +{ + int rc; + size_t name_len = 0; + + if (name == NULL) { + IDMAP_LOG(0, ("%s: name is null", __func__)); + return -EINVAL; + } + if (gid == NULL) { + IDMAP_LOG(0, ("%s: gid is null", __func__)); + return -EINVAL; + } + + rc = sss_strnlen(name, SSS_NAME_MAX, &name_len); + if (rc != 0) { + IDMAP_LOG(0, ("%s: no-strnlen; rc=%i", __func__, rc)); + return -rc; + } + + rc = get_gid_from_mc(gid, name); + if (rc != 0) { + rc = name_to_id(name, gid, SSS_NSS_GETGRNAM); + } + + log_actual_rc(__func__, rc); + rc = normalise_rc(rc); + + return -rc; +} + +static int sss_nfs_uid_to_name(uid_t uid, char *domain, char *name, size_t len) +{ + int rc; + + if (name == NULL) { + IDMAP_LOG(0, ("%s: name is null", __func__)); + return -EINVAL; + } + + rc = get_user_from_mc(name, len, uid); + if (rc != 0) { + rc = id_to_name(name, len, uid, SSS_NSS_GETPWUID); + } + + log_actual_rc(__func__, rc); + rc = normalise_rc(rc); + + return -rc; +} + +static int sss_nfs_gid_to_name(gid_t gid, char *domain, char *name, size_t len) +{ + int rc; + + if (name == NULL) { + IDMAP_LOG(0, ("%s: name is null", __func__)); + return -EINVAL; + } + + rc = get_group_from_mc(name, len, gid); + if (rc != 0) { + rc = id_to_name(name, len, gid, SSS_NSS_GETGRGID); + } + + log_actual_rc(__func__, rc); + rc = normalise_rc(rc); + + return -rc; +} + +static int sss_nfs_gss_princ_to_grouplist( + char *secname, char *princ, gid_t *groups, int *ngroups, + extra_mapping_params **ex) +{ + IDMAP_LOG(0, ("%s: not implemented", __func__)); + return -ENOENT; +} + +static struct trans_func s_sss_nfs_trans = { + .name = sss_nfs_plugin_name, + .init = sss_nfs_init, + .princ_to_ids = sss_nfs_princ_to_ids, + .name_to_uid = sss_nfs_name_to_uid, + .name_to_gid = sss_nfs_name_to_gid, + .uid_to_name = sss_nfs_uid_to_name, + .gid_to_name = sss_nfs_gid_to_name, + .gss_princ_to_grouplist = sss_nfs_gss_princ_to_grouplist, +}; + +struct trans_func *libnfsidmap_plugin_init(void) +{ + return (&s_sss_nfs_trans); +} diff --git a/src/sss_client/nss_common.h b/src/sss_client/nss_common.h new file mode 100644 index 0000000..e83b4f9 --- /dev/null +++ b/src/sss_client/nss_common.h @@ -0,0 +1,43 @@ +/* + SSSD + + Common routines for classical and enhanced NSS interface + + Authors: + Sumit Bose <sbose@redhat.com> + + Copyright (C) Red Hat, Inc 2007 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 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 Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + + + +struct sss_nss_pw_rep { + struct passwd *result; + char *buffer; + size_t buflen; +}; + +int sss_nss_getpw_readrep(struct sss_nss_pw_rep *pr, + uint8_t *buf, size_t *len); + +struct sss_nss_gr_rep { + struct group *result; + char *buffer; + size_t buflen; +}; + +int sss_nss_getgr_readrep(struct sss_nss_gr_rep *pr, + uint8_t *buf, size_t *len); diff --git a/src/sss_client/nss_compat.h b/src/sss_client/nss_compat.h new file mode 100644 index 0000000..97fbfeb --- /dev/null +++ b/src/sss_client/nss_compat.h @@ -0,0 +1,67 @@ +/* + SSSD + + nss_compat.h + + Authors: + Stephen Gallagher <sgallagh@redhat.com> + + Copyright (C) 2010 Red Hat + + 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 <http://www.gnu.org/licenses/>. + + Portions of this source file were copied from nss-pam-ldapd version + 0.7.8, licensed under LGPLv2.1+ +*/ + +#ifndef NSS_COMPAT_H_ +#define NSS_COMPAT_H_ + +/* We also define struct __netgrent because it's definition is + not publically available. This is taken from inet/netgroup.h + of the glibc (2.3.6) source tarball. + The first part of the struct is the only part that is modified + by our getnetgrent() function, all the other fields are not + touched at all. */ +struct __netgrent +{ + enum { triple_val, group_val } type; + union + { + struct + { + const char *host; + const char *user; + const char *domain; + } triple; + const char *group; + } val; + /* the following stuff is used by some NSS services + but not by ours (it's not completely clear how these + are shared between different services) or is used + by our caller */ + char *data; + size_t data_size; + union + { + char *cursor; + unsigned long int position; + } idx; /* added name to union to avoid warning */ + int first; + struct name_list *known_groups; + struct name_list *needed_groups; + void *nip; /* changed from `service_user *nip' */ +}; + +#endif /* NSS_COMPAT_H_ */ diff --git a/src/sss_client/nss_group.c b/src/sss_client/nss_group.c new file mode 100644 index 0000000..fcabf8c --- /dev/null +++ b/src/sss_client/nss_group.c @@ -0,0 +1,769 @@ +/* + * System Security Services Daemon. NSS client interface + * + * Copyright (C) Simo Sorce 2007 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/* GROUP database NSS interface */ + +#include "config.h" + +#include <nss.h> +#include <errno.h> +#include <sys/types.h> +#include <unistd.h> +#include <stdlib.h> +#include <stdint.h> +#include <string.h> +#include <stdbool.h> +#include "sss_cli.h" +#include "nss_mc.h" +#include "nss_common.h" + +static +#ifdef HAVE_PTHREAD_EXT +__thread +#endif +struct sss_nss_getgrent_data { + size_t len; + size_t ptr; + uint8_t *data; +} sss_nss_getgrent_data; + +static void sss_nss_getgrent_data_clean(void) +{ + if (sss_nss_getgrent_data.data != NULL) { + free(sss_nss_getgrent_data.data); + sss_nss_getgrent_data.data = NULL; + } + sss_nss_getgrent_data.len = 0; + sss_nss_getgrent_data.ptr = 0; +} + +enum sss_nss_gr_type { + GETGR_NONE, + GETGR_NAME, + GETGR_GID +}; + +static +#ifdef HAVE_PTHREAD_EXT +__thread +#endif +struct sss_nss_getgr_data { + enum sss_nss_gr_type type; + union { + char *grname; + gid_t gid; + } id; + + uint8_t *repbuf; + size_t replen; +} sss_nss_getgr_data; + +static void sss_nss_getgr_data_clean(bool freebuf) +{ + if (sss_nss_getgr_data.type == GETGR_NAME) { + free(sss_nss_getgr_data.id.grname); + } + if (freebuf) { + free(sss_nss_getgr_data.repbuf); + } + memset(&sss_nss_getgr_data, 0, sizeof(struct sss_nss_getgr_data)); +} + +static enum nss_status sss_nss_get_getgr_cache(const char *name, gid_t gid, + enum sss_nss_gr_type type, + uint8_t **repbuf, + size_t *replen, + int *errnop) +{ + bool freebuf = true; + enum nss_status status; + int ret = 0; + + if (sss_nss_getgr_data.type != type) { + status = NSS_STATUS_NOTFOUND; + goto done; + } + + switch (type) { + case GETGR_NAME: + if (name != NULL) { + ret = strcmp(name, sss_nss_getgr_data.id.grname); + } else { + ret = -1; + } + if (ret != 0) { + status = NSS_STATUS_NOTFOUND; + goto done; + } + break; + case GETGR_GID: + if (sss_nss_getgr_data.id.gid != gid) { + status = NSS_STATUS_NOTFOUND; + goto done; + } + break; + default: + status = NSS_STATUS_TRYAGAIN; + ret = EINVAL; + goto done; + } + + /* ok we have it, remove from cache and pass back to the caller */ + *repbuf = sss_nss_getgr_data.repbuf; + *replen = sss_nss_getgr_data.replen; + + /* prevent _clean() from freeing the buffer */ + freebuf = false; + status = NSS_STATUS_SUCCESS; + +done: + sss_nss_getgr_data_clean(freebuf); + *errnop = ret; + return status; +} + +/* this function always takes ownership of repbuf and NULLs it before + * returning */ +static void sss_nss_save_getgr_cache(const char *name, gid_t gid, + enum sss_nss_gr_type type, + uint8_t **repbuf, size_t replen) +{ + int ret = 0; + + sss_nss_getgr_data.type = type; + sss_nss_getgr_data.repbuf = *repbuf; + sss_nss_getgr_data.replen = replen; + + switch (type) { + case GETGR_NAME: + if (name == NULL) { + ret = EINVAL; + goto done; + } + sss_nss_getgr_data.id.grname = strdup(name); + if (!sss_nss_getgr_data.id.grname) { + ret = ENOMEM; + goto done; + } + break; + case GETGR_GID: + if (gid == 0) { + ret = EINVAL; + goto done; + } + sss_nss_getgr_data.id.gid = gid; + break; + default: + ret = EINVAL; + goto done; + } + +done: + if (ret) { + sss_nss_getgr_data_clean(true); + } + *repbuf = NULL; +} + +/* GETGRNAM Request: + * + * 0-X: string with name + * + * GERTGRGID Request: + * + * 0-7: 32bit number with gid + * + * INITGROUPS Request: + * + * 0-3: 32bit number with gid + * 4-7: 32bit unsigned with max num of entries + * + * Replies: + * + * 0-3: 32bit unsigned number of results + * 4-7: 32bit unsigned (reserved/padding) + * For each result (64bit padded?): + * 0-3: 32bit number gid + * 4-7: 32bit unsigned number of members + * 8-X: sequence of 0 terminated strings (name, passwd, mem..) + * + * FIXME: do we need to pad so that each result is 32 bit aligned? + */ + +int sss_nss_getgr_readrep(struct sss_nss_gr_rep *pr, + uint8_t *buf, size_t *len) +{ + errno_t ret; + size_t i, l, slen, ptmem, pad, dlen, glen; + char *sbuf; + uint32_t mem_num; + uint32_t c; + + if (*len < 11) { /* not enough space for data, bad packet */ + return EBADMSG; + } + + SAFEALIGN_COPY_UINT32(&c, buf, NULL); + pr->result->gr_gid = c; + SAFEALIGN_COPY_UINT32(&mem_num, buf+sizeof(uint32_t), NULL); + + sbuf = (char *)&buf[8]; + slen = *len - 8; + dlen = pr->buflen; + + pr->result->gr_name = &(pr->buffer[0]); + i = 0; + + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &pr->result->gr_name, + NULL); + if (ret != EOK) return ret; + + pr->result->gr_passwd = &(pr->buffer[i]); + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &pr->result->gr_passwd, + NULL); + if (ret != EOK) return ret; + + /* Make sure pr->buffer[i+pad] is aligned to sizeof(char *) */ + pad = PADDING_SIZE(i, char *); + + /* now members */ + pr->result->gr_mem = DISCARD_ALIGN(&(pr->buffer[i+pad]), char **); + + ptmem = (sizeof(char *) * (mem_num + 1)) + pad; + if (ptmem > dlen) { + return ERANGE; /* not ENOMEM, ERANGE is what glibc looks for */ + } + dlen -= ptmem; + ptmem += i; + pr->result->gr_mem[mem_num] = NULL; /* terminate array */ + + for (l = 0; l < mem_num; l++) { + pr->result->gr_mem[l] = &(pr->buffer[ptmem]); + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &pr->result->gr_mem[l], + &glen); + if (ret != EOK) return ret; + + ptmem += glen + 1; + } + + *len = slen -i; + return 0; +} + +/* INITGROUP Reply: + * + * 0-3: 32bit unsigned number of results + * 4-7: 32bit unsigned (reserved/padding) + * For each result: + * 0-4: 32bit number with gid + */ + + +enum nss_status _nss_sss_initgroups_dyn(const char *user, gid_t group, + long int *start, long int *size, + gid_t **groups, long int limit, + int *errnop) +{ + struct sss_cli_req_data rd; + uint8_t *repbuf; + size_t replen; + enum nss_status nret; + size_t buf_index = 0; + size_t user_len; + uint32_t num_ret; + long int l, max_ret; + int ret; + + ret = sss_strnlen(user, SSS_NAME_MAX, &user_len); + if (ret != 0) { + *errnop = EINVAL; + return NSS_STATUS_NOTFOUND; + } + + ret = sss_nss_mc_initgroups_dyn(user, user_len, group, start, size, + groups, limit); + switch (ret) { + case 0: + *errnop = 0; + return NSS_STATUS_SUCCESS; + case ERANGE: + *errnop = ERANGE; + return NSS_STATUS_TRYAGAIN; + case ENOENT: + /* fall through, we need to actively ask the parent + * if no entry is found */ + break; + default: + /* if using the mmapped cache failed, + * fall back to socket based comms */ + break; + } + + rd.len = user_len + 1; + rd.data = user; + + sss_nss_lock(); + + /* previous thread might already initialize entry in mmap cache */ + ret = sss_nss_mc_initgroups_dyn(user, user_len, group, start, size, + groups, limit); + switch (ret) { + case 0: + *errnop = 0; + nret = NSS_STATUS_SUCCESS; + goto out; + case ERANGE: + *errnop = ERANGE; + nret = NSS_STATUS_TRYAGAIN; + goto out; + case ENOENT: + /* fall through, we need to actively ask the parent + * if no entry is found */ + break; + default: + /* if using the mmapped cache failed, + * fall back to socket based comms */ + break; + } + + nret = sss_nss_make_request(SSS_NSS_INITGR, &rd, + &repbuf, &replen, errnop); + if (nret != NSS_STATUS_SUCCESS) { + goto out; + } + + /* no results if not found */ + SAFEALIGN_COPY_UINT32(&num_ret, repbuf, NULL); + if (num_ret == 0) { + free(repbuf); + nret = NSS_STATUS_NOTFOUND; + goto out; + } + max_ret = num_ret; + + /* check we have enough space in the buffer */ + if ((*size - *start) < num_ret) { + long int newsize; + gid_t *newgroups; + + newsize = *size + num_ret; + if ((limit > 0) && (newsize > limit)) { + newsize = limit; + max_ret = newsize - *start; + } + + newgroups = (gid_t *)realloc((*groups), newsize * sizeof(**groups)); + if (!newgroups) { + *errnop = ENOMEM; + free(repbuf); + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + *groups = newgroups; + *size = newsize; + } + + /* Skip first two 32 bit values (number of results and + * reserved padding) */ + buf_index = 2 * sizeof(uint32_t); + + for (l = 0; l < max_ret; l++) { + SAFEALIGN_COPY_UINT32(&(*groups)[*start], repbuf + buf_index, + &buf_index); + *start += 1; + } + + free(repbuf); + nret = NSS_STATUS_SUCCESS; + +out: + sss_nss_unlock(); + return nret; +} + + +enum nss_status _nss_sss_getgrnam_r(const char *name, struct group *result, + char *buffer, size_t buflen, int *errnop) +{ + struct sss_cli_req_data rd; + struct sss_nss_gr_rep grrep; + uint8_t *repbuf; + size_t replen, len, name_len; + uint32_t num_results; + enum nss_status nret; + int ret; + + /* Caught once glibc passing in buffer == 0x0 */ + if (!buffer || !buflen) { + *errnop = ERANGE; + return NSS_STATUS_TRYAGAIN; + } + + ret = sss_strnlen(name, SSS_NAME_MAX, &name_len); + if (ret != 0) { + *errnop = EINVAL; + return NSS_STATUS_NOTFOUND; + } + + ret = sss_nss_mc_getgrnam(name, name_len, result, buffer, buflen); + switch (ret) { + case 0: + *errnop = 0; + return NSS_STATUS_SUCCESS; + case ERANGE: + *errnop = ERANGE; + return NSS_STATUS_TRYAGAIN; + case ENOENT: + /* fall through, we need to actively ask the parent + * if no entry is found */ + break; + default: + /* if using the mmapped cache failed, + * fall back to socket based comms */ + break; + } + + rd.len = name_len + 1; + rd.data = name; + + sss_nss_lock(); + + /* previous thread might already initialize entry in mmap cache */ + ret = sss_nss_mc_getgrnam(name, name_len, result, buffer, buflen); + switch (ret) { + case 0: + *errnop = 0; + nret = NSS_STATUS_SUCCESS; + goto out; + case ERANGE: + *errnop = ERANGE; + nret = NSS_STATUS_TRYAGAIN; + goto out; + case ENOENT: + /* fall through, we need to actively ask the parent + * if no entry is found */ + break; + default: + /* if using the mmapped cache failed, + * fall back to socket based comms */ + break; + } + + nret = sss_nss_get_getgr_cache(name, 0, GETGR_NAME, + &repbuf, &replen, errnop); + if (nret == NSS_STATUS_NOTFOUND) { + nret = sss_nss_make_request(SSS_NSS_GETGRNAM, &rd, + &repbuf, &replen, errnop); + } + if (nret != NSS_STATUS_SUCCESS) { + goto out; + } + + grrep.result = result; + grrep.buffer = buffer; + grrep.buflen = buflen; + + /* Get number of results from repbuf. */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* no results if not found */ + if (num_results == 0) { + free(repbuf); + nret = NSS_STATUS_NOTFOUND; + goto out; + } + + /* only 1 result is accepted for this function */ + if (num_results != 1) { + *errnop = EBADMSG; + free(repbuf); + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + len = replen - 8; + ret = sss_nss_getgr_readrep(&grrep, repbuf+8, &len); + if (ret == ERANGE) { + sss_nss_save_getgr_cache(name, 0, GETGR_NAME, &repbuf, replen); + } else { + free(repbuf); + } + if (ret) { + *errnop = ret; + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + nret = NSS_STATUS_SUCCESS; + +out: + sss_nss_unlock(); + return nret; +} + +enum nss_status _nss_sss_getgrgid_r(gid_t gid, struct group *result, + char *buffer, size_t buflen, int *errnop) +{ + struct sss_cli_req_data rd; + struct sss_nss_gr_rep grrep; + uint8_t *repbuf; + size_t replen, len; + uint32_t num_results; + enum nss_status nret; + uint32_t group_gid; + int ret; + + /* Caught once glibc passing in buffer == 0x0 */ + if (!buffer || !buflen) { + *errnop = ERANGE; + return NSS_STATUS_TRYAGAIN; + } + + ret = sss_nss_mc_getgrgid(gid, result, buffer, buflen); + switch (ret) { + case 0: + *errnop = 0; + return NSS_STATUS_SUCCESS; + case ERANGE: + *errnop = ERANGE; + return NSS_STATUS_TRYAGAIN; + case ENOENT: + /* fall through, we need to actively ask the parent + * if no entry is found */ + break; + default: + /* if using the mmapped cache failed, + * fall back to socket based comms */ + break; + } + + group_gid = gid; + rd.len = sizeof(uint32_t); + rd.data = &group_gid; + + sss_nss_lock(); + + /* previous thread might already initialize entry in mmap cache */ + ret = sss_nss_mc_getgrgid(gid, result, buffer, buflen); + switch (ret) { + case 0: + *errnop = 0; + nret = NSS_STATUS_SUCCESS; + goto out; + case ERANGE: + *errnop = ERANGE; + nret = NSS_STATUS_TRYAGAIN; + goto out; + case ENOENT: + /* fall through, we need to actively ask the parent + * if no entry is found */ + break; + default: + /* if using the mmapped cache failed, + * fall back to socket based comms */ + break; + } + + nret = sss_nss_get_getgr_cache(NULL, gid, GETGR_GID, + &repbuf, &replen, errnop); + if (nret == NSS_STATUS_NOTFOUND) { + nret = sss_nss_make_request(SSS_NSS_GETGRGID, &rd, + &repbuf, &replen, errnop); + } + if (nret != NSS_STATUS_SUCCESS) { + goto out; + } + + grrep.result = result; + grrep.buffer = buffer; + grrep.buflen = buflen; + + /* Get number of results from repbuf. */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* no results if not found */ + if (num_results == 0) { + free(repbuf); + nret = NSS_STATUS_NOTFOUND; + goto out; + } + + /* only 1 result is accepted for this function */ + if (num_results != 1) { + *errnop = EBADMSG; + free(repbuf); + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + len = replen - 8; + ret = sss_nss_getgr_readrep(&grrep, repbuf+8, &len); + if (ret == ERANGE) { + sss_nss_save_getgr_cache(NULL, gid, GETGR_GID, &repbuf, replen); + } else { + free(repbuf); + } + if (ret) { + *errnop = ret; + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + nret = NSS_STATUS_SUCCESS; + +out: + sss_nss_unlock(); + return nret; +} + +enum nss_status _nss_sss_setgrent(void) +{ + enum nss_status nret; + int errnop; + + sss_nss_lock(); + + /* make sure we do not have leftovers, and release memory */ + sss_nss_getgrent_data_clean(); + + nret = sss_nss_make_request(SSS_NSS_SETGRENT, + NULL, NULL, NULL, &errnop); + if (nret != NSS_STATUS_SUCCESS) { + errno = errnop; + } + + sss_nss_unlock(); + return nret; +} + +static enum nss_status internal_getgrent_r(struct group *result, + char *buffer, size_t buflen, + int *errnop) +{ + struct sss_cli_req_data rd; + struct sss_nss_gr_rep grrep; + uint8_t *repbuf; + size_t replen; + uint32_t num_results; + enum nss_status nret; + uint32_t num_entries; + int ret; + + /* Caught once glibc passing in buffer == 0x0 */ + if (!buffer || !buflen) { + *errnop = ERANGE; + return NSS_STATUS_TRYAGAIN; + } + + /* if there are leftovers return the next one */ + if (sss_nss_getgrent_data.data != NULL && + sss_nss_getgrent_data.ptr < sss_nss_getgrent_data.len) { + + repbuf = (uint8_t *)sss_nss_getgrent_data.data + + sss_nss_getgrent_data.ptr; + replen = sss_nss_getgrent_data.len - + sss_nss_getgrent_data.ptr; + + grrep.result = result; + grrep.buffer = buffer; + grrep.buflen = buflen; + + ret = sss_nss_getgr_readrep(&grrep, repbuf, &replen); + if (ret) { + *errnop = ret; + return NSS_STATUS_TRYAGAIN; + } + + /* advance buffer pointer */ + sss_nss_getgrent_data.ptr = sss_nss_getgrent_data.len - replen; + + return NSS_STATUS_SUCCESS; + } + + /* release memory if any */ + sss_nss_getgrent_data_clean(); + + /* retrieve no more than SSS_NSS_MAX_ENTRIES at a time */ + num_entries = SSS_NSS_MAX_ENTRIES; + rd.len = sizeof(uint32_t); + rd.data = &num_entries; + + nret = sss_nss_make_request(SSS_NSS_GETGRENT, &rd, + &repbuf, &replen, errnop); + if (nret != NSS_STATUS_SUCCESS) { + return nret; + } + + /* Get number of results from repbuf. */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* no results if not found */ + if ((num_results == 0) || (replen - 8 == 0)) { + free(repbuf); + return NSS_STATUS_NOTFOUND; + } + + sss_nss_getgrent_data.data = repbuf; + sss_nss_getgrent_data.len = replen; + sss_nss_getgrent_data.ptr = 8; /* skip metadata fields */ + + /* call again ourselves, this will return the first result */ + return internal_getgrent_r(result, buffer, buflen, errnop); +} + +enum nss_status _nss_sss_getgrent_r(struct group *result, + char *buffer, size_t buflen, int *errnop) +{ + enum nss_status nret; + + sss_nss_lock(); + nret = internal_getgrent_r(result, buffer, buflen, errnop); + sss_nss_unlock(); + + return nret; +} + +enum nss_status _nss_sss_endgrent(void) +{ + enum nss_status nret; + int errnop; + int saved_errno = errno; + + sss_nss_lock(); + + /* make sure we do not have leftovers, and release memory */ + sss_nss_getgrent_data_clean(); + + nret = sss_nss_make_request(SSS_NSS_ENDGRENT, + NULL, NULL, NULL, &errnop); + if (nret != NSS_STATUS_SUCCESS) { + errno = errnop; + } else { + errno = saved_errno; + } + + sss_nss_unlock(); + return nret; +} diff --git a/src/sss_client/nss_hosts.c b/src/sss_client/nss_hosts.c new file mode 100644 index 0000000..81017bc --- /dev/null +++ b/src/sss_client/nss_hosts.c @@ -0,0 +1,591 @@ +/* + SSSD + + Authors: + Samuel Cabrero <scabrero@suse.com> + + Copyright (C) 2019 SUSE LINUX GmbH, Nuernberg, Germany. + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include "config.h" + +#include <nss.h> +#include <netdb.h> +#include <resolv.h> +#include <arpa/inet.h> +#include <errno.h> +#include <sys/types.h> +#include <unistd.h> +#include <stdlib.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> +#include "sss_cli.h" + +static +#ifdef HAVE_PTHREAD_EXT +__thread +#endif +struct sss_nss_gethostent_data { + size_t len; + size_t ptr; + uint8_t *data; +} sss_nss_gethostent_data; + +static void +sss_nss_gethostent_data_clean(void) +{ + if (sss_nss_gethostent_data.data != NULL) { + free(sss_nss_gethostent_data.data); + sss_nss_gethostent_data.data = NULL; + } + sss_nss_gethostent_data.len = 0; + sss_nss_gethostent_data.ptr = 0; +} + +/* GETHOSTBYNAME2 Request + * + * 0-X: One zero-terminated string (name) + * + * GETHOSTBYADDR Request: + * 0-3: 32-bit unsigned address family + * 4-7: 32-bit unsigned address length + * 8-X: binary address + * + * Replies: + * 0-3: 32-bit unsigned number of results + * 4-7: 32-bit unsigned (reserved/padding) + * 7-X: Result data (blocks equal to number of results) + * + * Result data: + * 0-3: 32-bit unsigned number of aliases + * 4-7: 32-bit unsigned number of addresses + * 8-X: sequence of zero-terminated strings + * (name, zero or more aliases, zero or more addresses) + */ + +struct sss_nss_host_rep { + struct hostent *result; + char *buffer; + size_t buflen; +}; + +#define HOST_METADATA_COUNT 8 + +static errno_t +sss_nss_gethost_readrep(struct sss_nss_host_rep *sr, + uint8_t *buf, size_t *len, int af) +{ + errno_t ret; + uint32_t num_aliases; + uint32_t num_addresses; + const char *sbuf; + size_t i, a, l, slen, dlen, pad, ptmem, alen; + + if (af != AF_INET && af != AF_INET6) { + return EBADMSG; + } + + /* Buffer must contain two 32-bit integers, + * at least one character and null-terminator + * for the name, at least a null-terminator for + * the aliases and a null-terminator for the + * addresses. + */ + if (*len < 12) { + /* not enough data, bad packet */ + return EBADMSG; + } + + /* Get the number of aliases */ + SAFEALIGN_COPY_UINT32(&num_aliases, buf, NULL); + + /* Get the number of addresses */ + SAFEALIGN_COPY_UINT32(&num_addresses, buf + sizeof(uint32_t), NULL); + + sbuf = (char *)&buf[2 * sizeof(uint32_t)]; + slen = *len - (2 * sizeof(uint32_t)); + dlen = sr->buflen; + + i = 0; + sr->result->h_name = &(sr->buffer[i]); + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &sr->result->h_name, + NULL); + if (ret != EOK) { + return ret; + } + + /* Copy the aliases */ + pad = PADDING_SIZE(i, char *); + sr->result->h_aliases = DISCARD_ALIGN(&(sr->buffer[i+pad]), char **); + + ptmem = (sizeof(char *) * (num_aliases + 1)) + pad; + if (ptmem > dlen) { + /* Not ENOMEM, ERANGE is what glibc looks for */ + return ERANGE; + } + + dlen -= ptmem; + ptmem += i; + + /* Terminate array */ + sr->result->h_aliases[num_aliases] = NULL; + + for (l = 0; l < num_aliases; l++) { + sr->result->h_aliases[l] = &(sr->buffer[ptmem]); + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &sr->result->h_aliases[l], + &alen); + if (ret != EOK) { + return ret; + } + + ptmem += alen + 1; + } + + /* Copy the addresses */ + pad = PADDING_SIZE(ptmem, char *); + sr->result->h_addr_list = + DISCARD_ALIGN(&(sr->buffer[ptmem + pad]), char **); + + ptmem += (sizeof(char *) * (num_addresses + 1)) + pad; + if (ptmem > dlen) { + /* Not ENOMEM, ERANGE is what glibc looks for */ + return ERANGE; + } + + dlen -= (sizeof(char *) * (num_addresses + 1)) + pad; + + /* Initialize array, can return less address than num_addresses depending + * on requested address family */ + for (a = 0; a < num_addresses + 1; a++) { + sr->result->h_addr_list[a] = NULL; + } + + for (a = 0, l = 0; l < num_addresses; l++) { + /* Can be optimized, but ensure we can fit an IPv6 for now */ + if (dlen < IN6ADDRSZ) { + return ERANGE; + } + + sr->result->h_addr_list[a] = &(sr->buffer[ptmem]); + + if (af == AF_INET && + inet_pton(AF_INET, &sbuf[i], &(sr->buffer[ptmem]))) { + sr->result->h_addrtype = AF_INET; + sr->result->h_length = INADDRSZ; + dlen -= INADDRSZ; + ptmem += INADDRSZ; + a++; + } else if (af == AF_INET6 && + inet_pton(AF_INET6, &sbuf[i], &(sr->buffer[ptmem]))) { + sr->result->h_addrtype = AF_INET6; + sr->result->h_length = IN6ADDRSZ; + dlen -= IN6ADDRSZ; + ptmem += IN6ADDRSZ; + a++; + } else { + /* Skip illegal address */ + sr->result->h_addr_list[a] = NULL; + } + + i += strlen(&sbuf[i]) + 1; + } + + *len = slen - i; + + return EOK; +} + +static enum nss_status +internal_gethostbyname2_r(const char *name, int af, + struct hostent *result, + char *buffer, size_t buflen, + int *errnop, int *h_errnop) +{ + struct sss_cli_req_data rd; + struct sss_nss_host_rep hostrep; + size_t name_len; + uint8_t *repbuf; + size_t replen, len; + uint32_t num_results; + enum nss_status nret; + int ret; + + if (af != AF_INET && af != AF_INET6) { + *errnop = EAFNOSUPPORT; + *h_errnop = NETDB_INTERNAL; + return NSS_STATUS_UNAVAIL; + } + + /* Caught once glibc passing in buffer == 0x0 */ + if (buffer == NULL || buflen == 0) { + *errnop = ERANGE; + *h_errnop = NETDB_INTERNAL; + return NSS_STATUS_TRYAGAIN; + } + + ret = sss_strnlen(name, SSS_NAME_MAX, &name_len); + if (ret != 0) { + *errnop = EINVAL; + *h_errnop = NETDB_INTERNAL; + return NSS_STATUS_UNAVAIL; + } + + rd.len = name_len + 1; + rd.data = name; + + sss_nss_lock(); + + nret = sss_nss_make_request(SSS_NSS_GETHOSTBYNAME2, &rd, + &repbuf, &replen, errnop); + if (nret != NSS_STATUS_SUCCESS) { + *h_errnop = NO_RECOVERY; + goto out; + } + + hostrep.result = result; + hostrep.buffer = buffer; + hostrep.buflen = buflen; + + /* Get number of results from repbuf. */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* No results if not found */ + if (num_results == 0) { + free(repbuf); + nret = NSS_STATUS_NOTFOUND; + *h_errnop = HOST_NOT_FOUND; + goto out; + } + + /* Only 1 result is accepted for this function */ + if (num_results != 1) { + free(repbuf); + *errnop = EBADMSG; + *h_errnop = NETDB_INTERNAL; + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + len = replen - HOST_METADATA_COUNT; + ret = sss_nss_gethost_readrep(&hostrep, repbuf + HOST_METADATA_COUNT, + &len, af); + free(repbuf); + if (ret) { + *errnop = ret; + nret = NSS_STATUS_TRYAGAIN; + *h_errnop = NETDB_INTERNAL; + goto out; + } + + /* If host name is valid but does not have an IP address of the requested + * address family return the correct error. */ + if (result->h_addr_list[0] == NULL) { + *h_errnop = NO_DATA; + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + nret = NSS_STATUS_SUCCESS; + +out: + sss_nss_unlock(); + + return nret; +} + +enum nss_status +_nss_sss_gethostbyname2_r(const char *name, int af, + struct hostent *result, + char *buffer, size_t buflen, + int *errnop, int *h_errnop) +{ + return internal_gethostbyname2_r(name, af, result, buffer, buflen, + errnop, h_errnop); +} + +enum nss_status +_nss_sss_gethostbyname_r(const char *name, + struct hostent *result, + char *buffer, size_t buflen, + int *errnop, int *h_errnop) +{ + return internal_gethostbyname2_r(name, AF_INET, result, buffer, buflen, + errnop, h_errnop); +} + +enum nss_status +_nss_sss_gethostbyaddr_r(const void *addr, socklen_t addrlen, + int af, struct hostent *result, + char *buffer, size_t buflen, + int *errnop, int *h_errnop) +{ + struct sss_cli_req_data rd; + struct sss_nss_host_rep hostrep; + uint8_t *repbuf; + uint8_t *data; + size_t replen, len; + uint32_t num_results; + enum nss_status nret; + int ret; + size_t data_len = 0; + size_t ctr = 0; + + if (af != AF_INET && af != AF_INET6) { + *errnop = EAFNOSUPPORT; + *h_errnop = NETDB_INTERNAL; + return NSS_STATUS_UNAVAIL; + } + + /* Caught once glibc passing in buffer == 0x0 */ + if (buffer == NULL || buflen == 0) { + *errnop = ERANGE; + *h_errnop = NETDB_INTERNAL; + return NSS_STATUS_TRYAGAIN; + } + + data_len = sizeof(uint32_t) + sizeof(socklen_t) + addrlen; + data = malloc(data_len); + if (data == NULL) { + *h_errnop = NETDB_INTERNAL; + return NSS_STATUS_TRYAGAIN; + } + + /* Push AF */ + SAFEALIGN_SETMEM_VALUE(data, af, uint32_t, &ctr); + + /* Push LEN */ + SAFEALIGN_SETMEM_VALUE(data + ctr, addrlen, socklen_t, &ctr); + + /* Push ADDR */ + SAFEALIGN_SETMEM_STRING(data + ctr, addr, addrlen, &ctr); + + rd.data = data; + rd.len = data_len; + + sss_nss_lock(); + + nret = sss_nss_make_request(SSS_NSS_GETHOSTBYADDR, &rd, + &repbuf, &replen, errnop); + free(data); + if (nret != NSS_STATUS_SUCCESS) { + *h_errnop = NO_RECOVERY; + goto out; + } + + hostrep.result = result; + hostrep.buffer = buffer; + hostrep.buflen = buflen; + + /* Get number of results from repbuf. */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* No results if not found */ + if (num_results == 0) { + free(repbuf); + nret = NSS_STATUS_NOTFOUND; + *h_errnop = HOST_NOT_FOUND; + goto out; + } + + /* Only 1 result is accepted for this function */ + if (num_results != 1) { + free(repbuf); + *errnop = EBADMSG; + *h_errnop = NETDB_INTERNAL; + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + len = replen - HOST_METADATA_COUNT; + ret = sss_nss_gethost_readrep(&hostrep, repbuf + HOST_METADATA_COUNT, + &len, af); + free(repbuf); + if (ret) { + *errnop = ret; + nret = NSS_STATUS_TRYAGAIN; + *h_errnop = NETDB_INTERNAL; + goto out; + } + + /* If host name is valid but does not have an IP address of the requested + * address family return the correct error. */ + if (result->h_addr_list[0] == NULL) { + *h_errnop = NO_DATA; + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + nret = NSS_STATUS_SUCCESS; + +out: + sss_nss_unlock(); + + return nret; +} + +static enum nss_status +internal_gethostent_r(struct hostent *result, + char *buffer, size_t buflen, + int *errnop, int *h_errnop) +{ + struct sss_cli_req_data rd; + struct sss_nss_host_rep pwrep; + uint8_t *repbuf; + size_t replen; + uint32_t num_results; + enum nss_status nret; + uint32_t num_entries; + int retval; + + /* Caught once glibc passing in buffer == 0x0 */ + if (buffer == NULL || buflen == 0) { + *errnop = ERANGE; + *h_errnop = NETDB_INTERNAL; + return NSS_STATUS_TRYAGAIN; + } + + /* if there are leftovers return the next one */ + if (sss_nss_gethostent_data.data != NULL && + sss_nss_gethostent_data.ptr < sss_nss_gethostent_data.len) { + + repbuf = sss_nss_gethostent_data.data + sss_nss_gethostent_data.ptr; + replen = sss_nss_gethostent_data.len - sss_nss_gethostent_data.ptr; + + pwrep.result = result; + pwrep.buffer = buffer; + pwrep.buflen = buflen; + + retval = sss_nss_gethost_readrep(&pwrep, repbuf, &replen, AF_INET); + if (retval) { + *errnop = retval; + *h_errnop = NETDB_INTERNAL; + return NSS_STATUS_TRYAGAIN; + } + + /* advance buffer pointer */ + sss_nss_gethostent_data.ptr = sss_nss_gethostent_data.len - replen; + + /* If host name is valid but does not have an IP address of the + * requested address family return the correct error. */ + if (result->h_addr_list[0] == NULL) { + *h_errnop = NO_DATA; + return NSS_STATUS_TRYAGAIN; + } + + *h_errnop = 0; + + return NSS_STATUS_SUCCESS; + } + + /* release memory if any */ + sss_nss_gethostent_data_clean(); + + /* retrieve no more than SSS_NSS_MAX_ENTRIES at a time */ + num_entries = SSS_NSS_MAX_ENTRIES; + rd.len = sizeof(uint32_t); + rd.data = &num_entries; + + nret = sss_nss_make_request(SSS_NSS_GETHOSTENT, &rd, + &repbuf, &replen, errnop); + if (nret != NSS_STATUS_SUCCESS) { + *h_errnop = NO_RECOVERY; + return nret; + } + + /* Get number of results from repbuf */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* no results if not found */ + if ((num_results == 0) || (replen - HOST_METADATA_COUNT == 0)) { + free(repbuf); + *h_errnop = HOST_NOT_FOUND; + return NSS_STATUS_NOTFOUND; + } + + sss_nss_gethostent_data.data = repbuf; + sss_nss_gethostent_data.len = replen; + + /* skip metadata fields */ + sss_nss_gethostent_data.ptr = HOST_METADATA_COUNT; + + /* call again ourselves, this will return the first result */ + return internal_gethostent_r(result, buffer, buflen, errnop, h_errnop); +} + +enum nss_status +_nss_sss_sethostent(void) +{ + enum nss_status nret; + int errnop; + + sss_nss_lock(); + + /* make sure we do not have leftovers, and release memory */ + sss_nss_gethostent_data_clean(); + + nret = sss_nss_make_request(SSS_NSS_SETHOSTENT, + NULL, NULL, NULL, &errnop); + if (nret != NSS_STATUS_SUCCESS) { + errno = errnop; + } + + sss_nss_unlock(); + + return nret; +} + +enum nss_status +_nss_sss_gethostent_r(struct hostent *result, + char *buffer, size_t buflen, + int *errnop, int *h_errnop) +{ + enum nss_status nret; + + sss_nss_lock(); + nret = internal_gethostent_r(result, buffer, buflen, errnop, h_errnop); + sss_nss_unlock(); + + return nret; +} + +enum nss_status +_nss_sss_endhostent(void) +{ + enum nss_status nret; + int errnop; + int saved_errno = errno; + + sss_nss_lock(); + + /* make sure we do not have leftovers, and release memory */ + sss_nss_gethostent_data_clean(); + + nret = sss_nss_make_request(SSS_NSS_ENDHOSTENT, + NULL, NULL, NULL, &errnop); + if (nret != NSS_STATUS_SUCCESS) { + errno = errnop; + } else { + errno = saved_errno; + } + + sss_nss_unlock(); + return nret; +} diff --git a/src/sss_client/nss_ipnetworks.c b/src/sss_client/nss_ipnetworks.c new file mode 100644 index 0000000..85d9cc7 --- /dev/null +++ b/src/sss_client/nss_ipnetworks.c @@ -0,0 +1,550 @@ +/* + SSSD + + Authors: + Samuel Cabrero <scabrero@suse.com> + + Copyright (C) 2020 SUSE LINUX GmbH, Nuernberg, Germany. + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include "config.h" + +#include <nss.h> +#include <netdb.h> +#include <resolv.h> +#include <arpa/inet.h> +#include <errno.h> +#include <sys/types.h> +#include <unistd.h> +#include <stdlib.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> +#include "sss_cli.h" + +static +#ifdef HAVE_PTHREAD_EXT +__thread +#endif +struct sss_nss_getnetent_data { + size_t len; + size_t ptr; + uint8_t *data; +} sss_nss_getnetent_data; + +static void +sss_nss_getnetent_data_clean(void) +{ + if (sss_nss_getnetent_data.data != NULL) { + free(sss_nss_getnetent_data.data); + sss_nss_getnetent_data.data = NULL; + } + sss_nss_getnetent_data.len = 0; + sss_nss_getnetent_data.ptr = 0; +} + +/* GETNETBYNAME Request + * + * 0-X: One zero-terminated string (name) + * + * GETNETBYADDR Request: + * 0-3: 32-bit unsigned address family + * 4-7: 32-bit unsigned address length + * 8-X: binary address + * + * Replies: + * 0-3: 32-bit unsigned number of results + * 4-7: 32-bit unsigned (reserved/padding) + * 7-X: Result data (blocks equal to number of results) + * + * Result data: + * 0-3: 32-bit unsigned number of aliases + * 4-X: sequence of zero-terminated strings + * (name, address, zero or more aliases) + */ + +struct sss_nss_net_rep { + struct netent *result; + char *buffer; + size_t buflen; +}; + +#define IP_NETWORK_METADATA_COUNT 8 + +static errno_t +sss_nss_net_readrep(struct sss_nss_net_rep *sr, + uint8_t *buf, size_t *len, int type) +{ + errno_t ret; + char *net_addrstr; + uint32_t net_addr; + uint32_t num_aliases; + const char *sbuf; + size_t i, l, slen, dlen, pad, ptmem, alen; + + /* Only AF_INET is supported */ + if (type != AF_INET) { + return EBADMSG; + } + + /* Buffer must contain one 32-bit integer, + * at least one character and null terminator + * for the name, at least one character and a + * null terminator for the address and a null + * terminator for the aliases. + */ + if (*len < 9) { + /* not enough data, bad packet */ + return EBADMSG; + } + + /* Get the number of aliases */ + SAFEALIGN_COPY_UINT32(&num_aliases, buf, NULL); + + sbuf = (char *)&buf[sizeof(uint32_t)]; + slen = *len - (sizeof(uint32_t)); + dlen = sr->buflen; + i = 0; + + /* Copy the name */ + sr->result->n_name = &(sr->buffer[i]); + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &sr->result->n_name, + NULL); + if (ret != EOK) { + return ret; + } + + /* Copy the address */ + net_addrstr = &(sr->buffer[i]); + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &net_addrstr, + NULL); + if (ret != EOK) { + return ret; + } + + if (inet_pton(AF_INET, net_addrstr, &net_addr)) { + sr->result->n_addrtype = AF_INET; + } else { + /* Skip illegal address */ + return EAFNOSUPPORT; + } + + /* result->n_net must be represented in host byte order */ + sr->result->n_net = ntohl(net_addr); + + /* Copy the aliases */ + pad = PADDING_SIZE(i, char *); + sr->result->n_aliases = DISCARD_ALIGN(&(sr->buffer[i+pad]), char **); + + ptmem = (sizeof(char *) * (num_aliases + 1)) + pad; + if (ptmem > dlen) { + /* Not ENOMEM, ERANGE is what glibc looks for */ + return ERANGE; + } + + dlen -= ptmem; + ptmem += i; + + /* Terminate array */ + sr->result->n_aliases[num_aliases] = NULL; + + for (l = 0; l < num_aliases; l++) { + sr->result->n_aliases[l] = &(sr->buffer[ptmem]); + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &sr->result->n_aliases[l], + &alen); + if (ret != EOK) { + return ret; + } + + ptmem += alen + 1; + } + + *len = slen - i; + + return EOK; +} + +enum nss_status +_nss_sss_getnetbyname_r(const char *name, + struct netent *result, + char *buffer, size_t buflen, + int *errnop, int *h_errnop) +{ + struct sss_cli_req_data rd; + struct sss_nss_net_rep netrep; + size_t name_len; + uint8_t *repbuf; + size_t replen, len; + uint32_t num_results; + enum nss_status nret; + int ret; + + /* Caught once glibc passing in buffer == 0x0 */ + if (buffer == NULL || buflen == 0) { + *errnop = ERANGE; + *h_errnop = NETDB_INTERNAL; + return NSS_STATUS_TRYAGAIN; + } + + ret = sss_strnlen(name, SSS_NAME_MAX, &name_len); + if (ret != 0) { + *errnop = EINVAL; + *h_errnop = NETDB_INTERNAL; + return NSS_STATUS_UNAVAIL; + } + + rd.len = name_len + 1; + rd.data = name; + + sss_nss_lock(); + + nret = sss_nss_make_request(SSS_NSS_GETNETBYNAME, &rd, + &repbuf, &replen, errnop); + if (nret != NSS_STATUS_SUCCESS) { + *h_errnop = NETDB_INTERNAL; + goto out; + } + + netrep.result = result; + netrep.buffer = buffer; + netrep.buflen = buflen; + + /* Get number of results from repbuf. */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* No results if not found */ + if (num_results == 0) { + free(repbuf); + nret = NSS_STATUS_NOTFOUND; + *h_errnop = HOST_NOT_FOUND; + goto out; + } + + /* Only 1 result is accepted for this function */ + if (num_results != 1) { + free(repbuf); + *errnop = EBADMSG; + *h_errnop = NETDB_INTERNAL; + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + len = replen - IP_NETWORK_METADATA_COUNT; + ret = sss_nss_net_readrep(&netrep, repbuf + IP_NETWORK_METADATA_COUNT, + &len, AF_INET); + free(repbuf); + + /* If network name is valid but does not have an IP address of the + * requested address family return the correct error + */ + if (ret == EAFNOSUPPORT) { + *h_errnop = NO_DATA; + nret = NSS_STATUS_TRYAGAIN; + goto out; + } else if (ret) { + *errnop = ret; + nret = NSS_STATUS_TRYAGAIN; + *h_errnop = NETDB_INTERNAL; + goto out; + } + + nret = NSS_STATUS_SUCCESS; + +out: + sss_nss_unlock(); + + return nret; +} + +enum nss_status +_nss_sss_getnetbyaddr_r(uint32_t addr, int type, + struct netent *result, + char *buffer, size_t buflen, + int *errnop, int *h_errnop) +{ + struct sss_cli_req_data rd; + struct sss_nss_net_rep netrep; + uint8_t *repbuf; + uint8_t *data; + size_t replen, len; + uint32_t num_results; + enum nss_status nret; + int ret; + size_t data_len = 0; + size_t ctr = 0; + socklen_t addrlen; + + /* addr is in host byte order, but nss_protocol_parse_addr and inet_ntop + * expects the buffer in network byte order */ + addr = htonl(addr); + + if (type == AF_UNSPEC) { + char addrbuf[INET_ADDRSTRLEN]; + + /* Try to parse to IPv4 */ + if (inet_ntop(AF_INET, &addr, addrbuf, INET_ADDRSTRLEN)) { + type = AF_INET; + } + } + + if (type != AF_INET) { + *errnop = EAFNOSUPPORT; + *h_errnop = NETDB_INTERNAL; + return NSS_STATUS_UNAVAIL; + } + + /* Caught once glibc passing in buffer == 0x0 */ + if (buffer == NULL || buflen == 0) { + *errnop = ERANGE; + *h_errnop = NETDB_INTERNAL; + return NSS_STATUS_TRYAGAIN; + } + + addrlen = INADDRSZ; + + data_len = sizeof(uint32_t) + sizeof(socklen_t) + addrlen; + data = malloc(data_len); + if (data == NULL) { + *h_errnop = NETDB_INTERNAL; + return NSS_STATUS_TRYAGAIN; + } + + /* Push type */ + SAFEALIGN_SETMEM_VALUE(data, type, int, &ctr); + + /* Push LEN */ + SAFEALIGN_SETMEM_VALUE(data + ctr, addrlen, socklen_t, &ctr); + + /* Push ADDR */ + SAFEALIGN_SETMEM_STRING(data + ctr, &addr, addrlen, &ctr); + + rd.data = data; + rd.len = data_len; + + sss_nss_lock(); + + nret = sss_nss_make_request(SSS_NSS_GETNETBYADDR, &rd, + &repbuf, &replen, errnop); + free(data); + if (nret != NSS_STATUS_SUCCESS) { + *h_errnop = NETDB_INTERNAL; + goto out; + } + + netrep.result = result; + netrep.buffer = buffer; + netrep.buflen = buflen; + + /* Get number of results from repbuf. */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* No results if not found */ + if (num_results == 0) { + free(repbuf); + nret = NSS_STATUS_NOTFOUND; + *h_errnop = HOST_NOT_FOUND; + goto out; + } + + /* Only 1 result is accepted for this function */ + if (num_results != 1) { + free(repbuf); + *errnop = EBADMSG; + *h_errnop = NETDB_INTERNAL; + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + len = replen - IP_NETWORK_METADATA_COUNT; + ret = sss_nss_net_readrep(&netrep, repbuf + IP_NETWORK_METADATA_COUNT, + &len, type); + free(repbuf); + + /* If network name is valid but does not have an IP address of the + * requested address family return the correct error + */ + if (ret == EAFNOSUPPORT) { + *h_errnop = NO_DATA; + nret = NSS_STATUS_TRYAGAIN; + goto out; + } else if (ret) { + *errnop = ret; + nret = NSS_STATUS_TRYAGAIN; + *h_errnop = NETDB_INTERNAL; + goto out; + } + + nret = NSS_STATUS_SUCCESS; + +out: + sss_nss_unlock(); + + return nret; +} + +static enum nss_status +internal_getnetent_r(struct netent *result, + char *buffer, size_t buflen, + int *errnop, int *h_errnop) +{ + struct sss_cli_req_data rd; + struct sss_nss_net_rep netrep; + uint8_t *repbuf; + size_t replen; + uint32_t num_results; + enum nss_status nret; + uint32_t num_entries; + int retval; + + /* Caught once glibc passing in buffer == 0x0 */ + if (buffer == NULL || buflen == 0) { + *errnop = ERANGE; + *h_errnop = NETDB_INTERNAL; + return NSS_STATUS_TRYAGAIN; + } + + /* if there are leftovers return the next one */ + if (sss_nss_getnetent_data.data != NULL && + sss_nss_getnetent_data.ptr < sss_nss_getnetent_data.len) { + + repbuf = sss_nss_getnetent_data.data + sss_nss_getnetent_data.ptr; + replen = sss_nss_getnetent_data.len - sss_nss_getnetent_data.ptr; + + netrep.result = result; + netrep.buffer = buffer; + netrep.buflen = buflen; + + retval = sss_nss_net_readrep(&netrep, repbuf, &replen, AF_INET); + /* If net name is valid but does not have an IP address of the + * requested address family return the correct error. */ + if (retval == EAFNOSUPPORT) { + *h_errnop = NO_DATA; + return NSS_STATUS_TRYAGAIN; + } else if (retval) { + *errnop = retval; + *h_errnop = NETDB_INTERNAL; + return NSS_STATUS_TRYAGAIN; + } + + /* advance buffer pointer */ + sss_nss_getnetent_data.ptr = sss_nss_getnetent_data.len - replen; + + *h_errnop = 0; + + return NSS_STATUS_SUCCESS; + } + + /* release memory if any */ + sss_nss_getnetent_data_clean(); + + /* retrieve no more than SSS_NSS_MAX_ENTRIES at a time */ + num_entries = SSS_NSS_MAX_ENTRIES; + rd.len = sizeof(uint32_t); + rd.data = &num_entries; + + nret = sss_nss_make_request(SSS_NSS_GETNETENT, &rd, + &repbuf, &replen, errnop); + if (nret != NSS_STATUS_SUCCESS) { + *h_errnop = NETDB_INTERNAL; + return nret; + } + + /* Get number of results from repbuf */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* no results if not found */ + if ((num_results == 0) || (replen - IP_NETWORK_METADATA_COUNT == 0)) { + free(repbuf); + *h_errnop = HOST_NOT_FOUND; + return NSS_STATUS_NOTFOUND; + } + + sss_nss_getnetent_data.data = repbuf; + sss_nss_getnetent_data.len = replen; + + /* skip metadata fields */ + sss_nss_getnetent_data.ptr = IP_NETWORK_METADATA_COUNT; + + /* call again ourselves, this will return the first result */ + return internal_getnetent_r(result, buffer, buflen, errnop, h_errnop); +} + +enum nss_status +_nss_sss_setnetent(void) +{ + enum nss_status nret; + int errnop; + + sss_nss_lock(); + + /* make sure we do not have leftovers, and release memory */ + sss_nss_getnetent_data_clean(); + + nret = sss_nss_make_request(SSS_NSS_SETNETENT, + NULL, NULL, NULL, &errnop); + if (nret != NSS_STATUS_SUCCESS) { + errno = errnop; + } + + sss_nss_unlock(); + + return nret; +} + +enum nss_status +_nss_sss_getnetent_r(struct netent *result, + char *buffer, size_t buflen, + int *errnop, int *h_errnop) +{ + enum nss_status nret; + + sss_nss_lock(); + nret = internal_getnetent_r(result, buffer, buflen, errnop, h_errnop); + sss_nss_unlock(); + + return nret; +} + +enum nss_status +_nss_sss_endnetent(void) +{ + enum nss_status nret; + int errnop; + int saved_errno = errno; + + sss_nss_lock(); + + /* make sure we do not have leftovers, and release memory */ + sss_nss_getnetent_data_clean(); + + nret = sss_nss_make_request(SSS_NSS_ENDNETENT, + NULL, NULL, NULL, &errnop); + if (nret != NSS_STATUS_SUCCESS) { + errno = errnop; + } else { + errno = saved_errno; + } + + sss_nss_unlock(); + return nret; +} + diff --git a/src/sss_client/nss_mc.h b/src/sss_client/nss_mc.h new file mode 100644 index 0000000..646861b --- /dev/null +++ b/src/sss_client/nss_mc.h @@ -0,0 +1,117 @@ +/* + * System Security Services Daemon. NSS client interface + * + * Copyright (C) Simo Sorce 2011 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/* NSS interfaces to mmap cache */ + +#ifndef _NSS_MC_H_ +#define _NSS_MC_H_ + +#include <stdint.h> +#include <stdbool.h> +#include <pwd.h> +#include <grp.h> + +#include "config.h" +#if HAVE_PTHREAD +#include <pthread.h> +#endif +#include "util/mmap_cache.h" + +#ifndef HAVE_ERRNO_T +#define HAVE_ERRNO_T +typedef int errno_t; +#endif + +enum sss_mc_state { + UNINITIALIZED = 0, + INITIALIZED, + RECYCLED, +}; + +/* In the case this structure is extended, don't forget to update + * `SSS_CLI_MC_CTX_INITIALIZER` and `sss_nss_mc_destroy_ctx()`. + */ +struct sss_cli_mc_ctx { + enum sss_mc_state initialized; +#if HAVE_PTHREAD + pthread_mutex_t *mutex; +#endif + int fd; + ino_t fd_inode; + dev_t fd_device; + + uint32_t seed; /* seed from the tables header */ + + void *mmap_base; /* base address of mmap */ + size_t mmap_size; /* total size of mmap */ + + uint8_t *data_table; /* data table address (in mmap) */ + uint32_t dt_size; /* size of data table */ + + uint32_t *hash_table; /* hash table address (in mmap) */ + uint32_t ht_size; /* size of hash table */ + + uint32_t active_threads; /* count of threads which use memory cache */ +}; + +#if HAVE_PTHREAD +#define SSS_CLI_MC_CTX_INITIALIZER(mtx) {UNINITIALIZED, (mtx), -1, 0, 0, 0, NULL, 0, NULL, 0, NULL, 0, 0} +#else +#define SSS_CLI_MC_CTX_INITIALIZER {UNINITIALIZED, -1, 0, 0, 0, NULL, 0, NULL, 0, NULL, 0, 0} +#endif + +errno_t sss_nss_mc_get_ctx(const char *name, struct sss_cli_mc_ctx *ctx); +errno_t sss_nss_check_header(struct sss_cli_mc_ctx *ctx); +uint32_t sss_nss_mc_hash(struct sss_cli_mc_ctx *ctx, + const char *key, size_t len); +errno_t sss_nss_mc_get_record(struct sss_cli_mc_ctx *ctx, + uint32_t slot, struct sss_mc_rec **_rec); +errno_t sss_nss_str_ptr_from_buffer(char **str, void **cookie, + char *buf, size_t len); +uint32_t sss_nss_mc_next_slot_with_hash(struct sss_mc_rec *rec, + uint32_t hash); + +/* passwd db */ +errno_t sss_nss_mc_getpwnam(const char *name, size_t name_len, + struct passwd *result, + char *buffer, size_t buflen); +errno_t sss_nss_mc_getpwuid(uid_t uid, + struct passwd *result, + char *buffer, size_t buflen); + +/* group db */ +errno_t sss_nss_mc_getgrnam(const char *name, size_t name_len, + struct group *result, + char *buffer, size_t buflen); +errno_t sss_nss_mc_getgrgid(gid_t gid, + struct group *result, + char *buffer, size_t buflen); + +/* initgroups db */ +errno_t sss_nss_mc_initgroups_dyn(const char *name, size_t name_len, + gid_t group, long int *start, long int *size, + gid_t **groups, long int limit); + +/* SID db */ +errno_t sss_nss_mc_get_sid_by_id(uint32_t id, char **sid, uint32_t *type); +errno_t sss_nss_mc_get_sid_by_uid(uint32_t id, char **sid, uint32_t *type); +errno_t sss_nss_mc_get_sid_by_gid(uint32_t id, char **sid, uint32_t *type); +errno_t sss_nss_mc_get_id_by_sid(const char *sid, uint32_t *id, uint32_t *type); + +#endif /* _NSS_MC_H_ */ diff --git a/src/sss_client/nss_mc_common.c b/src/sss_client/nss_mc_common.c new file mode 100644 index 0000000..17683ac --- /dev/null +++ b/src/sss_client/nss_mc_common.c @@ -0,0 +1,434 @@ +/* + * System Security Services Daemon. NSS client interface + * + * Copyright (C) Simo Sorce 2011 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/* NSS interfaces to mmap cache */ + +#include "config.h" + +#include <stdio.h> +#include <errno.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <unistd.h> +#include <sys/mman.h> +#include <string.h> +#include <stdlib.h> +#include "nss_mc.h" +#include "sss_cli.h" +#include "shared/io.h" + +/* FIXME: hook up to library destructor to avoid leaks */ +/* FIXME: temporarily open passwd file on our own, later we will probably + * use socket passing from the main process */ +/* FIXME: handle name upper/lower casing? Maybe a flag passed down by + * SSSD or a flag in sss_mc_header? per domain? */ + +#define MEMCPY_WITH_BARRIERS(res, dest, src, len) \ +do { \ + uint32_t _b1; \ + res = false; \ + _b1 = (src)->b1; \ + if (MC_VALID_BARRIER(_b1)) { \ + __sync_synchronize(); \ + memcpy(dest, src, len); \ + __sync_synchronize(); \ + if ((src)->b2 == _b1) { \ + res = true; \ + } \ + } \ +} while(0) + +static void sss_mt_lock(struct sss_cli_mc_ctx *ctx) +{ +#if HAVE_PTHREAD + pthread_mutex_lock(ctx->mutex); +#endif +} + +static void sss_mt_unlock(struct sss_cli_mc_ctx *ctx) +{ +#if HAVE_PTHREAD + pthread_mutex_unlock(ctx->mutex); +#endif +} + +static errno_t sss_nss_mc_validate(struct sss_cli_mc_ctx *ctx) +{ + struct stat fdstat; + + /* No mc ctx initialized?*/ + if (ctx == NULL || ctx->fd < 0) { + return EINVAL; + } + + if (fstat(ctx->fd, &fdstat) == -1) { + return EINVAL; + } + + /* Memcache was removed. */ + if (fdstat.st_nlink == 0) { + return EINVAL; + } + + /* FD was hijacked */ + if ((fdstat.st_dev != ctx->fd_device) || (fdstat.st_ino != ctx->fd_inode)) { + ctx->fd = -1; /* don't ruin app even if it's misbehaving */ + return EINVAL; + } + + /* Invalid size. */ + if (fdstat.st_size != ctx->mmap_size) { + return EINVAL; + } + + return EOK; +} + +errno_t sss_nss_check_header(struct sss_cli_mc_ctx *ctx) +{ + struct sss_mc_header h; + bool copy_ok; + int count; + int ret; + + ret = sss_nss_mc_validate(ctx); + if (ret != EOK) { + return ret; + } + + /* retry barrier protected reading max 5 times then give up */ + for (count = 5; count > 0; count--) { + MEMCPY_WITH_BARRIERS(copy_ok, &h, + (struct sss_mc_header *)ctx->mmap_base, + sizeof(struct sss_mc_header)); + if (copy_ok) { + /* record is consistent so we can proceed */ + break; + } + } + if (count == 0) { + /* couldn't successfully read header we have to give up */ + return EIO; + } + + if (h.major_vno != SSS_MC_MAJOR_VNO || + h.minor_vno != SSS_MC_MINOR_VNO || + h.status == SSS_MC_HEADER_RECYCLED) { + return EINVAL; + } + + /* first time we check the header, let's fill our own struct */ + if (ctx->data_table == NULL) { + ctx->seed = h.seed; + ctx->data_table = MC_PTR_ADD(ctx->mmap_base, h.data_table); + ctx->hash_table = MC_PTR_ADD(ctx->mmap_base, h.hash_table); + ctx->dt_size = h.dt_size; + ctx->ht_size = h.ht_size; + } else { + if (ctx->seed != h.seed || + ctx->data_table != MC_PTR_ADD(ctx->mmap_base, h.data_table) || + ctx->hash_table != MC_PTR_ADD(ctx->mmap_base, h.hash_table) || + ctx->dt_size != h.dt_size || + ctx->ht_size != h.ht_size) { + return EINVAL; + } + } + + return 0; +} + +static void sss_nss_mc_destroy_ctx(struct sss_cli_mc_ctx *ctx) +{ + + if ((ctx->mmap_base != NULL) && (ctx->mmap_size != 0)) { + munmap(ctx->mmap_base, ctx->mmap_size); + } + ctx->mmap_base = NULL; + ctx->mmap_size = 0; + + if (ctx->fd != -1) { + close(ctx->fd); + } + ctx->fd = -1; + ctx->fd_inode = 0; + ctx->fd_device = 0; + + ctx->seed = 0; + ctx->data_table = NULL; + ctx->dt_size = 0; + ctx->hash_table = NULL; + ctx->ht_size = 0; + ctx->initialized = UNINITIALIZED; + /* `mutex` and `active_threads` should be left intact */ +} + +static errno_t sss_nss_mc_init_ctx(const char *name, + struct sss_cli_mc_ctx *ctx) +{ + struct stat fdstat; + char *file = NULL; + int ret; + + sss_mt_lock(ctx); + /* check if ctx is initialised by previous thread. */ + if (ctx->initialized != UNINITIALIZED) { + ret = sss_nss_check_header(ctx); + goto done; + } + + ret = asprintf(&file, "%s/%s", SSS_NSS_MCACHE_DIR, name); + if (ret == -1) { + ret = ENOMEM; + goto done; + } + + ctx->fd = sss_open_cloexec(file, O_RDONLY, &ret); + if (ctx->fd == -1) { + ret = EIO; + goto done; + } + + ret = fstat(ctx->fd, &fdstat); + if (ret == -1) { + ret = EIO; + goto done; + } + ctx->fd_inode = fdstat.st_ino; + ctx->fd_device = fdstat.st_dev; + + if (fdstat.st_size < MC_HEADER_SIZE) { + ret = ENOMEM; + goto done; + } + ctx->mmap_size = fdstat.st_size; + + ctx->mmap_base = mmap(NULL, ctx->mmap_size, + PROT_READ, MAP_SHARED, ctx->fd, 0); + if (ctx->mmap_base == MAP_FAILED) { + ret = ENOMEM; + goto done; + } + + ret = sss_nss_check_header(ctx); + if (ret != 0) { + goto done; + } + + ctx->initialized = INITIALIZED; + + ret = 0; + +done: + if (ret) { + sss_nss_mc_destroy_ctx(ctx); + } + free(file); + sss_mt_unlock(ctx); + + return ret; +} + +errno_t sss_nss_mc_get_ctx(const char *name, struct sss_cli_mc_ctx *ctx) +{ + char *envval; + int ret; + bool need_decrement = false; + + envval = getenv("SSS_NSS_USE_MEMCACHE"); + if (envval && strcasecmp(envval, "NO") == 0) { + return EPERM; + } + + switch (ctx->initialized) { + case UNINITIALIZED: + __sync_add_and_fetch(&ctx->active_threads, 1); + ret = sss_nss_mc_init_ctx(name, ctx); + if (ret) { + need_decrement = true; + } + break; + case INITIALIZED: + __sync_add_and_fetch(&ctx->active_threads, 1); + ret = sss_nss_check_header(ctx); + if (ret) { + need_decrement = true; + } + break; + case RECYCLED: + /* we need to safely destroy memory cache */ + ret = EAGAIN; + break; + default: + ret = EFAULT; + } + + if (ret) { + if (ctx->initialized == INITIALIZED) { + ctx->initialized = RECYCLED; + } + if (ctx->initialized == RECYCLED && ctx->active_threads == 0) { + /* just one thread should call munmap */ + sss_mt_lock(ctx); + if (ctx->initialized == RECYCLED) { + sss_nss_mc_destroy_ctx(ctx); + } + sss_mt_unlock(ctx); + } + if (need_decrement) { + /* In case of error, we will not touch mmapped area => decrement */ + __sync_sub_and_fetch(&ctx->active_threads, 1); + } + } + return ret; +} + +uint32_t sss_nss_mc_hash(struct sss_cli_mc_ctx *ctx, + const char *key, size_t len) +{ + return murmurhash3(key, len, ctx->seed) % MC_HT_ELEMS(ctx->ht_size); +} + +errno_t sss_nss_mc_get_record(struct sss_cli_mc_ctx *ctx, + uint32_t slot, struct sss_mc_rec **_rec) +{ + struct sss_mc_rec *rec; + struct sss_mc_rec *copy_rec = NULL; + size_t buf_size = 0; + size_t rec_len; + uint32_t b1; + uint32_t b2; + bool copy_ok; + int count; + int ret; + + /* try max 5 times */ + for (count = 5; count > 0; count--) { + rec = MC_SLOT_TO_PTR(ctx->data_table, slot, struct sss_mc_rec); + + /* fetch record length */ + b1 = rec->b1; + __sync_synchronize(); + rec_len = rec->len; + __sync_synchronize(); + b2 = rec->b2; + if (!MC_VALID_BARRIER(b1) || b1 != b2) { + /* record is inconsistent, retry */ + continue; + } + + if (!MC_CHECK_RECORD_LENGTH(ctx, rec)) { + /* record has invalid length */ + free(copy_rec); + return EINVAL; + } + + if (rec_len > buf_size) { + free(copy_rec); + copy_rec = malloc(rec_len); + if (!copy_rec) { + ret = ENOMEM; + goto done; + } + buf_size = rec_len; + } + /* we cannot access data directly, we must copy data and then + * access the copy */ + MEMCPY_WITH_BARRIERS(copy_ok, copy_rec, rec, rec_len); + + /* we must check data is consistent again after the copy */ + if (copy_ok && b1 == copy_rec->b2) { + /* record is consistent, use it */ + break; + } + } + if (count == 0) { + /* couldn't successfully read header we have to give up */ + ret = EIO; + goto done; + } + + *_rec = copy_rec; + ret = 0; + +done: + if (ret) { + free(copy_rec); + *_rec = NULL; + } + return ret; +} + +/* + * returns strings from a buffer. + * + * Call first time with *cookie set to null, then call again + * with the returned cookie. + * On the last string the cookie will be reset to null and + * all strings will have been returned. + * In case the last string is not zero terminated EINVAL is returned. + */ +errno_t sss_nss_str_ptr_from_buffer(char **str, void **cookie, + char *buf, size_t len) +{ + char *max = buf + len; + char *ret; + char *p; + + if (*cookie == NULL) { + p = buf; + } else { + p = *((char **)cookie); + } + + ret = p; + + while (p < max) { + if (*p == '\0') { + break; + } + p++; + } + if (p >= max) { + return EINVAL; + } + p++; + if (p == max) { + *cookie = NULL; + } else { + *cookie = p; + } + + *str = ret; + return 0; +} + +uint32_t sss_nss_mc_next_slot_with_hash(struct sss_mc_rec *rec, + uint32_t hash) +{ + if (rec->hash1 == hash) { + return rec->next1; + } else if (rec->hash2 == hash) { + return rec->next2; + } else { + /* it should never happen. */ + return MC_INVALID_VAL; + } + +} diff --git a/src/sss_client/nss_mc_group.c b/src/sss_client/nss_mc_group.c new file mode 100644 index 0000000..d4f2a82 --- /dev/null +++ b/src/sss_client/nss_mc_group.c @@ -0,0 +1,254 @@ +/* + * System Security Services Daemon. NSS client interface + * + * Copyright (C) Simo Sorce 2011 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/* GROUP database NSS interface using mmap cache */ + +#include <errno.h> +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <stddef.h> +#include <sys/mman.h> +#include <time.h> +#include "nss_mc.h" +#include "shared/safealign.h" + +#if HAVE_PTHREAD +static pthread_mutex_t gr_mc_ctx_mutex = PTHREAD_MUTEX_INITIALIZER; +static struct sss_cli_mc_ctx gr_mc_ctx = SSS_CLI_MC_CTX_INITIALIZER(&gr_mc_ctx_mutex); +#else +static struct sss_cli_mc_ctx gr_mc_ctx = SSS_CLI_MC_CTX_INITIALIZER; +#endif + +static errno_t sss_nss_mc_parse_result(struct sss_mc_rec *rec, + struct group *result, + char *buffer, size_t buflen) +{ + struct sss_mc_grp_data *data; + time_t expire; + void *cookie; + char *membuf; + size_t memsize; + int ret; + int i; + + /* additional checks before filling result*/ + expire = rec->expire; + if (expire < time(NULL)) { + /* entry is now invalid */ + return EINVAL; + } + + data = (struct sss_mc_grp_data *)rec->data; + + memsize = (data->members + 1) * sizeof(char *); + if (data->strs_len + memsize > buflen) { + return ERANGE; + } + + /* fill in glibc provided structs */ + + /* copy in buffer */ + membuf = buffer + memsize; + memcpy(membuf, data->strs, data->strs_len); + + /* fill in group */ + result->gr_gid = data->gid; + + /* The address &buffer[0] must be aligned to sizeof(char *) */ + if (!IS_ALIGNED(buffer, char *)) { + /* The buffer is not properly aligned. */ + return EFAULT; + } + + result->gr_mem = DISCARD_ALIGN(buffer, char **); + result->gr_mem[data->members] = NULL; + + cookie = NULL; + ret = sss_nss_str_ptr_from_buffer(&result->gr_name, &cookie, + membuf, data->strs_len); + if (ret) { + return ret; + } + ret = sss_nss_str_ptr_from_buffer(&result->gr_passwd, &cookie, + membuf, data->strs_len); + if (ret) { + return ret; + } + + for (i = 0; i < data->members; i++) { + ret = sss_nss_str_ptr_from_buffer(&result->gr_mem[i], &cookie, + membuf, data->strs_len); + if (ret) { + return ret; + } + } + if (cookie != NULL) { + return EINVAL; + } + + return 0; +} + +errno_t sss_nss_mc_getgrnam(const char *name, size_t name_len, + struct group *result, + char *buffer, size_t buflen) +{ + struct sss_mc_rec *rec = NULL; + struct sss_mc_grp_data *data; + char *rec_name; + uint32_t hash; + uint32_t slot; + int ret; + const size_t strs_offset = offsetof(struct sss_mc_grp_data, strs); + size_t data_size; + + ret = sss_nss_mc_get_ctx("group", &gr_mc_ctx); + if (ret) { + return ret; + } + + /* Get max size of data table. */ + data_size = gr_mc_ctx.dt_size; + + /* hashes are calculated including the NULL terminator */ + hash = sss_nss_mc_hash(&gr_mc_ctx, name, name_len + 1); + slot = gr_mc_ctx.hash_table[hash]; + + /* If slot is not within the bounds of mmapped region and + * it's value is not MC_INVALID_VAL, then the cache is + * probably corrupted. */ + while (MC_SLOT_WITHIN_BOUNDS(slot, data_size)) { + /* free record from previous iteration */ + free(rec); + rec = NULL; + + ret = sss_nss_mc_get_record(&gr_mc_ctx, slot, &rec); + if (ret) { + goto done; + } + + /* check record matches what we are searching for */ + if (hash != rec->hash1) { + /* if name hash does not match we can skip this immediately */ + slot = sss_nss_mc_next_slot_with_hash(rec, hash); + continue; + } + + data = (struct sss_mc_grp_data *)rec->data; + rec_name = (char *)data + data->name; + /* Integrity check + * - data->name cannot point outside strings + * - all strings must be within copy of record + * - rec_name is a zero-terminated string */ + if (data->name < strs_offset + || data->name >= strs_offset + data->strs_len + || data->strs_len > rec->len) { + ret = ENOENT; + goto done; + } + + if (strcmp(name, rec_name) == 0) { + break; + } + + slot = sss_nss_mc_next_slot_with_hash(rec, hash); + } + + if (!MC_SLOT_WITHIN_BOUNDS(slot, data_size)) { + ret = ENOENT; + goto done; + } + + ret = sss_nss_mc_parse_result(rec, result, buffer, buflen); + +done: + free(rec); + __sync_sub_and_fetch(&gr_mc_ctx.active_threads, 1); + return ret; +} + +errno_t sss_nss_mc_getgrgid(gid_t gid, + struct group *result, + char *buffer, size_t buflen) +{ + struct sss_mc_rec *rec = NULL; + struct sss_mc_grp_data *data; + char gidstr[11]; + uint32_t hash; + uint32_t slot; + int len; + int ret; + + ret = sss_nss_mc_get_ctx("group", &gr_mc_ctx); + if (ret) { + return ret; + } + + len = snprintf(gidstr, 11, "%ld", (long)gid); + if (len > 10) { + ret = EINVAL; + goto done; + } + + /* hashes are calculated including the NULL terminator */ + hash = sss_nss_mc_hash(&gr_mc_ctx, gidstr, len+1); + slot = gr_mc_ctx.hash_table[hash]; + + /* If slot is not within the bounds of mmapped region and + * it's value is not MC_INVALID_VAL, then the cache is + * probably corrupted. */ + while (MC_SLOT_WITHIN_BOUNDS(slot, gr_mc_ctx.dt_size)) { + /* free record from previous iteration */ + free(rec); + rec = NULL; + + ret = sss_nss_mc_get_record(&gr_mc_ctx, slot, &rec); + if (ret) { + goto done; + } + + /* check record matches what we are searching for */ + if (hash != rec->hash2) { + /* if uid hash does not match we can skip this immediately */ + slot = sss_nss_mc_next_slot_with_hash(rec, hash); + continue; + } + + data = (struct sss_mc_grp_data *)rec->data; + if (gid == data->gid) { + break; + } + + slot = sss_nss_mc_next_slot_with_hash(rec, hash); + } + + if (!MC_SLOT_WITHIN_BOUNDS(slot, gr_mc_ctx.dt_size)) { + ret = ENOENT; + goto done; + } + + ret = sss_nss_mc_parse_result(rec, result, buffer, buflen); + +done: + free(rec); + __sync_sub_and_fetch(&gr_mc_ctx.active_threads, 1); + return ret; +} + diff --git a/src/sss_client/nss_mc_initgr.c b/src/sss_client/nss_mc_initgr.c new file mode 100644 index 0000000..bd72829 --- /dev/null +++ b/src/sss_client/nss_mc_initgr.c @@ -0,0 +1,168 @@ +/* + * System Security Services Daemon. NSS client interface + * + * Authors: + * Lukas Slebodnik <lslebodn@redhat.com> + * + * Copyright (C) 2015 Red Hat + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/* INITGROUPs database NSS interface using mmap cache */ + +#include <errno.h> +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <stddef.h> +#include <sys/mman.h> +#include <time.h> +#include "nss_mc.h" +#include "shared/safealign.h" + +#if HAVE_PTHREAD +static pthread_mutex_t initgr_mc_ctx_mutex = PTHREAD_MUTEX_INITIALIZER; +static struct sss_cli_mc_ctx initgr_mc_ctx = SSS_CLI_MC_CTX_INITIALIZER(&initgr_mc_ctx_mutex); +#else +static struct sss_cli_mc_ctx initgr_mc_ctx = SSS_CLI_MC_CTX_INITIALIZER; +#endif + +static errno_t sss_nss_mc_parse_result(struct sss_mc_rec *rec, + long int *start, long int *size, + gid_t **groups, long int limit) +{ + struct sss_mc_initgr_data *data; + time_t expire; + long int i; + uint32_t num_groups; + long int max_ret; + + /* additional checks before filling result*/ + expire = rec->expire; + if (expire < time(NULL)) { + /* entry is now invalid */ + return EINVAL; + } + + data = (struct sss_mc_initgr_data *)rec->data; + num_groups = data->num_groups; + max_ret = num_groups; + + /* check we have enough space in the buffer */ + if ((*size - *start) < num_groups) { + long int newsize; + gid_t *newgroups; + + newsize = *size + num_groups; + if ((limit > 0) && (newsize > limit)) { + newsize = limit; + max_ret = newsize - *start; + } + + newgroups = (gid_t *)realloc((*groups), newsize * sizeof(**groups)); + if (!newgroups) { + return ENOMEM; + } + *groups = newgroups; + *size = newsize; + } + + for (i = 0; i < max_ret; i++) { + SAFEALIGN_COPY_UINT32(&(*groups)[*start], data->gids + i, NULL); + *start += 1; + } + + return 0; +} + +errno_t sss_nss_mc_initgroups_dyn(const char *name, size_t name_len, + gid_t group, long int *start, long int *size, + gid_t **groups, long int limit) +{ + struct sss_mc_rec *rec = NULL; + struct sss_mc_initgr_data *data; + char *rec_name; + uint32_t hash; + uint32_t slot; + int ret; + const size_t data_offset = offsetof(struct sss_mc_initgr_data, gids); + size_t data_size; + + ret = sss_nss_mc_get_ctx("initgroups", &initgr_mc_ctx); + if (ret) { + return ret; + } + + /* Get max size of data table. */ + data_size = initgr_mc_ctx.dt_size; + + /* hashes are calculated including the NULL terminator */ + hash = sss_nss_mc_hash(&initgr_mc_ctx, name, name_len + 1); + slot = initgr_mc_ctx.hash_table[hash]; + + /* If slot is not within the bounds of mmapped region and + * it's value is not MC_INVALID_VAL, then the cache is + * probably corrupted. */ + while (MC_SLOT_WITHIN_BOUNDS(slot, data_size)) { + /* free record from previous iteration */ + free(rec); + rec = NULL; + + ret = sss_nss_mc_get_record(&initgr_mc_ctx, slot, &rec); + if (ret) { + goto done; + } + + /* check record matches what we are searching for */ + if (hash != rec->hash1) { + /* if name hash does not match we can skip this immediately */ + slot = sss_nss_mc_next_slot_with_hash(rec, hash); + continue; + } + + data = (struct sss_mc_initgr_data *)rec->data; + rec_name = (char *)data + data->name; + /* Integrity check + * - data->name cannot point outside all strings or data + * - all data must be within copy of record + * - data->strs cannot point outside strings + * - rec_name is a zero-terminated string */ + if (data->name < data_offset + || data->name >= data_offset + data->data_len + || data->strs_len > data->data_len + || data->data_len > rec->len) { + ret = ENOENT; + goto done; + } + + if (strcmp(name, rec_name) == 0) { + break; + } + + slot = sss_nss_mc_next_slot_with_hash(rec, hash); + } + + if (!MC_SLOT_WITHIN_BOUNDS(slot, data_size)) { + ret = ENOENT; + goto done; + } + + ret = sss_nss_mc_parse_result(rec, start, size, groups, limit); + +done: + free(rec); + __sync_sub_and_fetch(&initgr_mc_ctx.active_threads, 1); + return ret; +} diff --git a/src/sss_client/nss_mc_passwd.c b/src/sss_client/nss_mc_passwd.c new file mode 100644 index 0000000..256d484 --- /dev/null +++ b/src/sss_client/nss_mc_passwd.c @@ -0,0 +1,247 @@ +/* + * System Security Services Daemon. NSS client interface + * + * Copyright (C) Simo Sorce 2011 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/* PASSWD database NSS interface using mmap cache */ + +#include <errno.h> +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <stddef.h> +#include <sys/mman.h> +#include <time.h> +#include "nss_mc.h" + +#if HAVE_PTHREAD +static pthread_mutex_t pw_mc_ctx_mutex = PTHREAD_MUTEX_INITIALIZER; +static struct sss_cli_mc_ctx pw_mc_ctx = SSS_CLI_MC_CTX_INITIALIZER(&pw_mc_ctx_mutex); +#else +static struct sss_cli_mc_ctx pw_mc_ctx = SSS_CLI_MC_CTX_INITIALIZER; +#endif + +static errno_t sss_nss_mc_parse_result(struct sss_mc_rec *rec, + struct passwd *result, + char *buffer, size_t buflen) +{ + struct sss_mc_pwd_data *data; + time_t expire; + void *cookie; + int ret; + + /* additional checks before filling result*/ + expire = rec->expire; + if (expire < time(NULL)) { + /* entry is now invalid */ + return EINVAL; + } + + data = (struct sss_mc_pwd_data *)rec->data; + + if (data->strs_len > buflen) { + return ERANGE; + } + + /* fill in glibc provided structs */ + + /* copy in buffer */ + memcpy(buffer, data->strs, data->strs_len); + + /* fill in passwd */ + result->pw_uid = data->uid; + result->pw_gid = data->gid; + + cookie = NULL; + ret = sss_nss_str_ptr_from_buffer(&result->pw_name, &cookie, + buffer, data->strs_len); + if (ret) { + return ret; + } + ret = sss_nss_str_ptr_from_buffer(&result->pw_passwd, &cookie, + buffer, data->strs_len); + if (ret) { + return ret; + } + ret = sss_nss_str_ptr_from_buffer(&result->pw_gecos, &cookie, + buffer, data->strs_len); + if (ret) { + return ret; + } + ret = sss_nss_str_ptr_from_buffer(&result->pw_dir, &cookie, + buffer, data->strs_len); + if (ret) { + return ret; + } + ret = sss_nss_str_ptr_from_buffer(&result->pw_shell, &cookie, + buffer, data->strs_len); + if (ret) { + return ret; + } + if (cookie != NULL) { + return EINVAL; + } + + return 0; +} + +errno_t sss_nss_mc_getpwnam(const char *name, size_t name_len, + struct passwd *result, + char *buffer, size_t buflen) +{ + struct sss_mc_rec *rec = NULL; + struct sss_mc_pwd_data *data; + char *rec_name; + uint32_t hash; + uint32_t slot; + int ret; + const size_t strs_offset = offsetof(struct sss_mc_pwd_data, strs); + size_t data_size; + + ret = sss_nss_mc_get_ctx("passwd", &pw_mc_ctx); + if (ret) { + return ret; + } + + /* Get max size of data table. */ + data_size = pw_mc_ctx.dt_size; + + /* hashes are calculated including the NULL terminator */ + hash = sss_nss_mc_hash(&pw_mc_ctx, name, name_len + 1); + slot = pw_mc_ctx.hash_table[hash]; + + /* If slot is not within the bounds of mmapped region and + * it's value is not MC_INVALID_VAL, then the cache is + * probably corrupted. */ + while (MC_SLOT_WITHIN_BOUNDS(slot, data_size)) { + /* free record from previous iteration */ + free(rec); + rec = NULL; + + ret = sss_nss_mc_get_record(&pw_mc_ctx, slot, &rec); + if (ret) { + goto done; + } + + /* check record matches what we are searching for */ + if (hash != rec->hash1) { + /* if name hash does not match we can skip this immediately */ + slot = sss_nss_mc_next_slot_with_hash(rec, hash); + continue; + } + + data = (struct sss_mc_pwd_data *)rec->data; + rec_name = (char *)data + data->name; + /* Integrity check + * - data->name cannot point outside strings + * - all strings must be within copy of record + * - rec_name is a zero-terminated string */ + if (data->name < strs_offset + || data->name >= strs_offset + data->strs_len + || data->strs_len > rec->len) { + ret = ENOENT; + goto done; + } + + if (strcmp(name, rec_name) == 0) { + break; + } + + slot = sss_nss_mc_next_slot_with_hash(rec, hash); + } + + if (!MC_SLOT_WITHIN_BOUNDS(slot, data_size)) { + ret = ENOENT; + goto done; + } + + ret = sss_nss_mc_parse_result(rec, result, buffer, buflen); + +done: + free(rec); + __sync_sub_and_fetch(&pw_mc_ctx.active_threads, 1); + return ret; +} + +errno_t sss_nss_mc_getpwuid(uid_t uid, + struct passwd *result, + char *buffer, size_t buflen) +{ + struct sss_mc_rec *rec = NULL; + struct sss_mc_pwd_data *data; + char uidstr[11]; + uint32_t hash; + uint32_t slot; + int len; + int ret; + + ret = sss_nss_mc_get_ctx("passwd", &pw_mc_ctx); + if (ret) { + return ret; + } + + len = snprintf(uidstr, 11, "%ld", (long)uid); + if (len > 10) { + ret = EINVAL; + goto done; + } + + /* hashes are calculated including the NULL terminator */ + hash = sss_nss_mc_hash(&pw_mc_ctx, uidstr, len+1); + slot = pw_mc_ctx.hash_table[hash]; + + /* If slot is not within the bounds of mmapped region and + * it's value is not MC_INVALID_VAL, then the cache is + * probably corrupted. */ + while (MC_SLOT_WITHIN_BOUNDS(slot, pw_mc_ctx.dt_size)) { + /* free record from previous iteration */ + free(rec); + rec = NULL; + + ret = sss_nss_mc_get_record(&pw_mc_ctx, slot, &rec); + if (ret) { + goto done; + } + + /* check record matches what we are searching for */ + if (hash != rec->hash2) { + /* if uid hash does not match we can skip this immediately */ + slot = sss_nss_mc_next_slot_with_hash(rec, hash); + continue; + } + + data = (struct sss_mc_pwd_data *)rec->data; + if (uid == data->uid) { + break; + } + + slot = sss_nss_mc_next_slot_with_hash(rec, hash); + } + + if (!MC_SLOT_WITHIN_BOUNDS(slot, pw_mc_ctx.dt_size)) { + ret = ENOENT; + goto done; + } + + ret = sss_nss_mc_parse_result(rec, result, buffer, buflen); + +done: + free(rec); + __sync_sub_and_fetch(&pw_mc_ctx.active_threads, 1); + return ret; +} + diff --git a/src/sss_client/nss_mc_sid.c b/src/sss_client/nss_mc_sid.c new file mode 100644 index 0000000..52e684d --- /dev/null +++ b/src/sss_client/nss_mc_sid.c @@ -0,0 +1,198 @@ +/* + * System Security Services Daemon. NSS client interface + * + * Copyright (C) 2022 Red Hat + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/* SID database NSS interface using mmap cache */ + +#include <stddef.h> +#include <errno.h> +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <time.h> + +#include "nss_mc.h" +#include "util/mmap_cache.h" +#include "idmap/sss_nss_idmap.h" + +#if HAVE_PTHREAD +static pthread_mutex_t sid_mc_ctx_mutex = PTHREAD_MUTEX_INITIALIZER; +static struct sss_cli_mc_ctx sid_mc_ctx = SSS_CLI_MC_CTX_INITIALIZER(&sid_mc_ctx_mutex); +#else +static struct sss_cli_mc_ctx sid_mc_ctx = SSS_CLI_MC_CTX_INITIALIZER; +#endif + +static errno_t mc_get_sid_by_typed_id(uint32_t id, enum sss_id_type object_type, + char **sid, uint32_t *type, + uint32_t *populated_by) +{ + int ret; + char key[16]; + int key_len; + uint32_t hash; + uint32_t slot; + struct sss_mc_rec *rec = NULL; + const struct sss_mc_sid_data *data = NULL; + + key_len = snprintf(key, sizeof(key), "%d-%ld", object_type, (long)id); + if (key_len > (sizeof(key) - 1)) { + return EINVAL; + } + + ret = sss_nss_mc_get_ctx("sid", &sid_mc_ctx); + if (ret) { + return ret; + } + + hash = sss_nss_mc_hash(&sid_mc_ctx, key, key_len + 1); + slot = sid_mc_ctx.hash_table[hash]; + + while (MC_SLOT_WITHIN_BOUNDS(slot, sid_mc_ctx.dt_size)) { + free(rec); /* free record from previous iteration */ + rec = NULL; + + ret = sss_nss_mc_get_record(&sid_mc_ctx, slot, &rec); + if (ret) { + goto done; + } + if (hash != rec->hash2) { + ret = EINVAL; + goto done; + } + + data = (struct sss_mc_sid_data *)rec->data; + if (id == data->id) { + if (rec->expire < time(NULL)) { + ret = EINVAL; + goto done; + } + *type = data->type; + if (populated_by) { + *populated_by = data->populated_by; + } + *sid = strdup(data->sid); + if (!*sid) { + ret = ENOMEM; + } + goto done; + } + + slot = sss_nss_mc_next_slot_with_hash(rec, hash); + } + + ret = ENOENT; + +done: + free(rec); + __sync_sub_and_fetch(&sid_mc_ctx.active_threads, 1); + return ret; +} + +errno_t sss_nss_mc_get_sid_by_uid(uint32_t id, char **sid, uint32_t *type) +{ + return mc_get_sid_by_typed_id(id, SSS_ID_TYPE_UID, sid, type, NULL); +} + +errno_t sss_nss_mc_get_sid_by_gid(uint32_t id, char **sid, uint32_t *type) +{ + return mc_get_sid_by_typed_id(id, SSS_ID_TYPE_GID, sid, type, NULL); +} + +errno_t sss_nss_mc_get_sid_by_id(uint32_t id, char **sid, uint32_t *type) +{ + errno_t ret; + uint32_t populated_by; + + /* MC should behave the same way sssd_nss does. + * If user object exists sssd_nss would always return this user object. + */ + ret = sss_nss_mc_get_sid_by_uid(id, sid, type); + if (ret != ENOENT) { + return ret; /* found or fatal error */ + } + + /* This is where things get tricky. + * Consider a case of manually created user private group: + * since MC could be primed via explicit by-gid() lookup, + * missing user object doesn't mean sssd_nss wouldn't return + * it, hence only return group object if cache was primed via + * by-id() lookup. + */ + ret = mc_get_sid_by_typed_id(id, SSS_ID_TYPE_GID, sid, type, &populated_by); + if ((ret == 0) && (populated_by == 1)) { + /* Cache was primed via explicit by-gid() lookup - request should go to sssd_nss */ + free(*sid); + ret = ENOENT; + } + + return ret; +} + +errno_t sss_nss_mc_get_id_by_sid(const char *sid, uint32_t *id, uint32_t *type) +{ + int ret; + int key_len; + uint32_t hash; + uint32_t slot; + struct sss_mc_rec *rec = NULL; + const struct sss_mc_sid_data *data = NULL; + + key_len = strlen(sid) + 1; + + ret = sss_nss_mc_get_ctx("sid", &sid_mc_ctx); + if (ret) { + return ret; + } + + hash = sss_nss_mc_hash(&sid_mc_ctx, sid, key_len); + slot = sid_mc_ctx.hash_table[hash]; + + while (MC_SLOT_WITHIN_BOUNDS(slot, sid_mc_ctx.dt_size)) { + free(rec); /* free record from previous iteration */ + rec = NULL; + + ret = sss_nss_mc_get_record(&sid_mc_ctx, slot, &rec); + if (ret) { + goto done; + } + if (hash != rec->hash1) { + ret = EINVAL; + goto done; + } + + data = (struct sss_mc_sid_data *)rec->data; + if (strcmp(sid, data->sid) == 0) { + if (rec->expire < time(NULL)) { + ret = EINVAL; + goto done; + } + *type = data->type; + *id = data->id; + goto done; /* ret == 0 */ + } + + slot = sss_nss_mc_next_slot_with_hash(rec, hash); + } + + ret = ENOENT; + +done: + free(rec); + __sync_sub_and_fetch(&sid_mc_ctx.active_threads, 1); + return ret; +} diff --git a/src/sss_client/nss_netgroup.c b/src/sss_client/nss_netgroup.c new file mode 100644 index 0000000..dab7404 --- /dev/null +++ b/src/sss_client/nss_netgroup.c @@ -0,0 +1,286 @@ +/* + SSSD + + nss_netgroup.c + + Authors: + Stephen Gallagher <sgallagh@redhat.com> + + Copyright (C) 2010 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include <nss.h> +#include <errno.h> +#include <sys/types.h> +#include <unistd.h> +#include <stdlib.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> +#include "sss_cli.h" +#include "nss_compat.h" + +#define CLEAR_NETGRENT_DATA(netgrent) do { \ + free(netgrent->data); \ + netgrent->data = NULL; \ + netgrent->idx.position = 0; \ + netgrent->data_size = 0; \ +} while (0); + +/* + * Replies: + * + * 0-3: 32bit unsigned number of results N + * 4-7: 32bit unsigned (reserved/padding) + * For each result: + * 8-11: 32bit unsigned type of result + * 12-X: \0 terminated string representing a tuple + * (host, user, domain) + * or a netgroup, depending on the type indicator + * ... repeated N times + */ +#define NETGR_METADATA_COUNT 2 * sizeof(uint32_t) +struct sss_nss_netgr_rep { + struct __netgrent *result; + char *buffer; + size_t buflen; +}; + +static int sss_nss_getnetgr_readrep(struct sss_nss_netgr_rep *pr, + uint8_t *buf, size_t *len) +{ + errno_t ret; + char *sbuf; + char *temp; + size_t i, slen, dlen, size; + uint32_t type; + + if (*len < 6) { + /* Not enough space for data, bad packet */ + return EBADMSG; + } + + sbuf = (char *)(buf + sizeof(uint32_t)); + slen = *len - sizeof(uint32_t); + dlen = pr->buflen; + + i = 0; + + SAFEALIGN_COPY_UINT32(&type, buf, NULL); + switch (type) { + case SSS_NETGR_REP_TRIPLE: + pr->result->type = triple_val; + + /* Host value */ + temp = &(pr->buffer[i]); + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &temp, + &size); + if (ret != EOK) return ret; + + /* libc expects NULL instead of empty string */ + if (size == 0) { + pr->result->val.triple.host = NULL; + } else { + pr->result->val.triple.host = temp; + } + + /* User value */ + temp = &(pr->buffer[i]); + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &temp, + &size); + if (ret != EOK) return ret; + + /* libc expects NULL instead of empty string */ + if (size == 0) { + pr->result->val.triple.user = NULL; + } else { + pr->result->val.triple.user = temp; + } + + /* Domain value */ + temp = &(pr->buffer[i]); + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &temp, + &size); + if (ret != EOK) return ret; + + /* libc expects NULL instead of empty string */ + if (size == 0) { + pr->result->val.triple.domain = NULL; + } else { + pr->result->val.triple.domain = temp; + } + + break; + + case SSS_NETGR_REP_GROUP: + pr->result->type = group_val; + + temp = &(pr->buffer[i]); + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &temp, + NULL); + if (ret != EOK) return ret; + + pr->result->val.group = temp; + + break; + + default: + return EBADMSG; + } + + + *len = slen -i; + + return 0; +} + +enum nss_status _nss_sss_setnetgrent(const char *netgroup, + struct __netgrent *result) +{ + uint8_t *repbuf = NULL; + size_t replen; + uint32_t num_results; + enum nss_status nret; + struct sss_cli_req_data rd; + int errnop; + char *name; + size_t name_len; + errno_t ret; + + if (!netgroup) return NSS_STATUS_NOTFOUND; + + sss_nss_lock(); + + /* make sure we do not have leftovers, and release memory */ + CLEAR_NETGRENT_DATA(result); + + ret = sss_strnlen(netgroup, SSS_NAME_MAX, &name_len); + if (ret != 0) { + nret = NSS_STATUS_NOTFOUND; + goto out; + } + + name = malloc(sizeof(char)*name_len + 1); + if (name == NULL) { + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + strncpy(name, netgroup, name_len + 1); + + rd.data = name; + rd.len = name_len + 1; + + nret = sss_nss_make_request(SSS_NSS_SETNETGRENT, &rd, + &repbuf, &replen, &errnop); + free(name); + if (nret != NSS_STATUS_SUCCESS) { + errno = errnop; + goto out; + } + + /* Get number of results from repbuf */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* no results if not found */ + if ((num_results == 0) || (replen < NETGR_METADATA_COUNT)) { + free(repbuf); + nret = NSS_STATUS_NOTFOUND; + goto out; + } + + result->data = (char *) repbuf; + result->data_size = replen; + /* skip metadata fields */ + result->idx.position = NETGR_METADATA_COUNT; + + nret = NSS_STATUS_SUCCESS; + +out: + sss_nss_unlock(); + return nret; +} + +static enum nss_status internal_getnetgrent_r(struct __netgrent *result, + char *buffer, size_t buflen, + int *errnop) +{ + struct sss_nss_netgr_rep netgrrep; + uint8_t *repbuf; + size_t replen; + int ret; + + /* Caught once glibc passing in buffer == 0x0 */ + if (!buffer || !buflen) { + *errnop = ERANGE; + return NSS_STATUS_TRYAGAIN; + } + + /* If we're already processing result data, continue to + * return it. + */ + if (result->data != NULL && + result->idx.position < result->data_size) { + + repbuf = (uint8_t *) result->data + result->idx.position; + replen = result->data_size - result->idx.position; + + netgrrep.result = result; + netgrrep.buffer = buffer; + netgrrep.buflen = buflen; + + ret = sss_nss_getnetgr_readrep(&netgrrep, repbuf, &replen); + if (ret != 0) { + *errnop = ret; + return NSS_STATUS_TRYAGAIN; + } + + result->idx.position = result->data_size - replen; + + return NSS_STATUS_SUCCESS; + } + + return NSS_STATUS_RETURN; +} + +enum nss_status _nss_sss_getnetgrent_r(struct __netgrent *result, + char *buffer, size_t buflen, + int *errnop) +{ + enum nss_status nret; + + /* no lock needed because results are already stored in result */ + nret = internal_getnetgrent_r(result, buffer, buflen, errnop); + + return nret; +} + +enum nss_status _nss_sss_endnetgrent(struct __netgrent *result) +{ + /* no lock needed because resources in the responder are already + * released */ + /* make sure we do not have leftovers, and release memory */ + CLEAR_NETGRENT_DATA(result); + + return NSS_STATUS_SUCCESS; +} diff --git a/src/sss_client/nss_passwd.c b/src/sss_client/nss_passwd.c new file mode 100644 index 0000000..ec19908 --- /dev/null +++ b/src/sss_client/nss_passwd.c @@ -0,0 +1,481 @@ +/* + * System Security Services Daemon. NSS client interface + * + * Copyright (C) Simo Sorce 2007 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/* PASSWD database NSS interface */ + +#include "config.h" + +#include <nss.h> +#include <errno.h> +#include <sys/types.h> +#include <unistd.h> +#include <stdlib.h> +#include <stdint.h> +#include <string.h> +#include "sss_cli.h" +#include "nss_mc.h" +#include "nss_common.h" + +static +#ifdef HAVE_PTHREAD_EXT +__thread +#endif +struct sss_nss_getpwent_data { + size_t len; + size_t ptr; + uint8_t *data; +} sss_nss_getpwent_data; + +static void sss_nss_getpwent_data_clean(void) { + + if (sss_nss_getpwent_data.data != NULL) { + free(sss_nss_getpwent_data.data); + sss_nss_getpwent_data.data = NULL; + } + sss_nss_getpwent_data.len = 0; + sss_nss_getpwent_data.ptr = 0; +} + +/* GETPWNAM Request: + * + * 0-X: string with name + * + * GERTPWUID Request: + * + * 0-3: 32bit number with uid + * + * Replies: + * + * 0-3: 32bit unsigned number of results + * 4-7: 32bit unsigned (reserved/padding) + * For each result: + * 0-3: 32bit number uid + * 4-7: 32bit number gid + * 8-X: sequence of 5, 0 terminated, strings (name, passwd, gecos, dir, shell) + */ + +int sss_nss_getpw_readrep(struct sss_nss_pw_rep *pr, + uint8_t *buf, size_t *len) +{ + errno_t ret; + size_t i, slen, dlen; + char *sbuf; + uint32_t c; + + if (*len < 13) { /* not enough space for data, bad packet */ + return EBADMSG; + } + + SAFEALIGN_COPY_UINT32(&c, buf, NULL); + pr->result->pw_uid = c; + SAFEALIGN_COPY_UINT32(&c, buf+sizeof(uint32_t), NULL); + pr->result->pw_gid = c; + + sbuf = (char *)&buf[8]; + slen = *len - 8; + dlen = pr->buflen; + + i = 0; + pr->result->pw_name = &(pr->buffer[i]); + + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &pr->result->pw_name, + NULL); + if (ret != EOK) return ret; + + pr->result->pw_passwd = &(pr->buffer[i]); + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &pr->result->pw_passwd, + NULL); + if (ret != EOK) return ret; + + pr->result->pw_gecos = &(pr->buffer[i]); + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &pr->result->pw_gecos, + NULL); + if (ret != EOK) return ret; + + + pr->result->pw_dir = &(pr->buffer[i]); + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &pr->result->pw_dir, + NULL); + if (ret != EOK) return ret; + + pr->result->pw_shell = &(pr->buffer[i]); + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &pr->result->pw_shell, + NULL); + if (ret != EOK) return ret; + *len = slen - i; + + return 0; +} + +enum nss_status _nss_sss_getpwnam_r(const char *name, struct passwd *result, + char *buffer, size_t buflen, int *errnop) +{ + struct sss_cli_req_data rd; + struct sss_nss_pw_rep pwrep; + uint8_t *repbuf; + size_t replen, len, name_len; + uint32_t num_results; + enum nss_status nret; + int ret; + + /* Caught once glibc passing in buffer == 0x0 */ + if (!buffer || !buflen) { + *errnop = ERANGE; + return NSS_STATUS_TRYAGAIN; + } + + ret = sss_strnlen(name, SSS_NAME_MAX, &name_len); + if (ret != 0) { + *errnop = EINVAL; + return NSS_STATUS_NOTFOUND; + } + + ret = sss_nss_mc_getpwnam(name, name_len, result, buffer, buflen); + switch (ret) { + case 0: + *errnop = 0; + return NSS_STATUS_SUCCESS; + case ERANGE: + *errnop = ERANGE; + return NSS_STATUS_TRYAGAIN; + case ENOENT: + /* fall through, we need to actively ask the parent + * if no entry is found */ + break; + default: + /* if using the mmapped cache failed, + * fall back to socket based comms */ + break; + } + + rd.len = name_len + 1; + rd.data = name; + + sss_nss_lock(); + + /* previous thread might already initialize entry in mmap cache */ + ret = sss_nss_mc_getpwnam(name, name_len, result, buffer, buflen); + switch (ret) { + case 0: + *errnop = 0; + nret = NSS_STATUS_SUCCESS; + goto out; + case ERANGE: + *errnop = ERANGE; + nret = NSS_STATUS_TRYAGAIN; + goto out; + case ENOENT: + /* fall through, we need to actively ask the parent + * if no entry is found */ + break; + default: + /* if using the mmapped cache failed, + * fall back to socket based comms */ + break; + } + + nret = sss_nss_make_request(SSS_NSS_GETPWNAM, &rd, + &repbuf, &replen, errnop); + if (nret != NSS_STATUS_SUCCESS) { + goto out; + } + + pwrep.result = result; + pwrep.buffer = buffer; + pwrep.buflen = buflen; + + /* Get number of results from repbuf. */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* no results if not found */ + if (num_results == 0) { + free(repbuf); + nret = NSS_STATUS_NOTFOUND; + goto out; + } + + /* only 1 result is accepted for this function */ + if (num_results != 1) { + *errnop = EBADMSG; + free(repbuf); + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + len = replen - 8; + ret = sss_nss_getpw_readrep(&pwrep, repbuf+8, &len); + free(repbuf); + if (ret) { + *errnop = ret; + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + nret = NSS_STATUS_SUCCESS; + +out: + sss_nss_unlock(); + return nret; +} + +enum nss_status _nss_sss_getpwuid_r(uid_t uid, struct passwd *result, + char *buffer, size_t buflen, int *errnop) +{ + struct sss_cli_req_data rd; + struct sss_nss_pw_rep pwrep; + uint8_t *repbuf; + size_t replen, len; + uint32_t num_results; + enum nss_status nret; + uint32_t user_uid; + int ret; + + /* Caught once glibc passing in buffer == 0x0 */ + if (!buffer || !buflen) { + *errnop = ERANGE; + return NSS_STATUS_TRYAGAIN; + } + + ret = sss_nss_mc_getpwuid(uid, result, buffer, buflen); + switch (ret) { + case 0: + *errnop = 0; + return NSS_STATUS_SUCCESS; + case ERANGE: + *errnop = ERANGE; + return NSS_STATUS_TRYAGAIN; + case ENOENT: + /* fall through, we need to actively ask the parent + * if no entry is found */ + break; + default: + /* if using the mmapped cache failed, + * fall back to socket based comms */ + break; + } + + user_uid = uid; + rd.len = sizeof(uint32_t); + rd.data = &user_uid; + + sss_nss_lock(); + + /* previous thread might already initialize entry in mmap cache */ + ret = sss_nss_mc_getpwuid(uid, result, buffer, buflen); + switch (ret) { + case 0: + *errnop = 0; + nret = NSS_STATUS_SUCCESS; + goto out; + case ERANGE: + *errnop = ERANGE; + nret = NSS_STATUS_TRYAGAIN; + goto out; + case ENOENT: + /* fall through, we need to actively ask the parent + * if no entry is found */ + break; + default: + /* if using the mmapped cache failed, + * fall back to socket based comms */ + break; + } + + nret = sss_nss_make_request(SSS_NSS_GETPWUID, &rd, + &repbuf, &replen, errnop); + if (nret != NSS_STATUS_SUCCESS) { + goto out; + } + + pwrep.result = result; + pwrep.buffer = buffer; + pwrep.buflen = buflen; + + /* Get number of results from repbuf. */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* no results if not found */ + if (num_results == 0) { + free(repbuf); + nret = NSS_STATUS_NOTFOUND; + goto out; + } + + /* only 1 result is accepted for this function */ + if (num_results != 1) { + *errnop = EBADMSG; + free(repbuf); + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + len = replen - 8; + ret = sss_nss_getpw_readrep(&pwrep, repbuf+8, &len); + free(repbuf); + if (ret) { + *errnop = ret; + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + nret = NSS_STATUS_SUCCESS; + +out: + sss_nss_unlock(); + return nret; +} + +enum nss_status _nss_sss_setpwent(void) +{ + enum nss_status nret; + int errnop; + + sss_nss_lock(); + + /* make sure we do not have leftovers, and release memory */ + sss_nss_getpwent_data_clean(); + + nret = sss_nss_make_request(SSS_NSS_SETPWENT, + NULL, NULL, NULL, &errnop); + if (nret != NSS_STATUS_SUCCESS) { + errno = errnop; + } + + sss_nss_unlock(); + return nret; +} + +static enum nss_status internal_getpwent_r(struct passwd *result, + char *buffer, size_t buflen, + int *errnop) +{ + struct sss_cli_req_data rd; + struct sss_nss_pw_rep pwrep; + uint8_t *repbuf; + size_t replen; + uint32_t num_results; + enum nss_status nret; + uint32_t num_entries; + int ret; + + /* Caught once glibc passing in buffer == 0x0 */ + if (!buffer || !buflen) { + *errnop = ERANGE; + return NSS_STATUS_TRYAGAIN; + } + + /* if there are leftovers return the next one */ + if (sss_nss_getpwent_data.data != NULL && + sss_nss_getpwent_data.ptr < sss_nss_getpwent_data.len) { + + repbuf = sss_nss_getpwent_data.data + sss_nss_getpwent_data.ptr; + replen = sss_nss_getpwent_data.len - sss_nss_getpwent_data.ptr; + + pwrep.result = result; + pwrep.buffer = buffer; + pwrep.buflen = buflen; + + ret = sss_nss_getpw_readrep(&pwrep, repbuf, &replen); + if (ret) { + *errnop = ret; + return NSS_STATUS_TRYAGAIN; + } + + /* advance buffer pointer */ + sss_nss_getpwent_data.ptr = sss_nss_getpwent_data.len - replen; + + return NSS_STATUS_SUCCESS; + } + + /* release memory if any */ + sss_nss_getpwent_data_clean(); + + /* retrieve no more than SSS_NSS_MAX_ENTRIES at a time */ + num_entries = SSS_NSS_MAX_ENTRIES; + rd.len = sizeof(uint32_t); + rd.data = &num_entries; + + nret = sss_nss_make_request(SSS_NSS_GETPWENT, &rd, + &repbuf, &replen, errnop); + if (nret != NSS_STATUS_SUCCESS) { + return nret; + } + + /* Get number of results from repbuf. */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* no results if not found */ + if ((num_results == 0) || (replen - 8 == 0)) { + free(repbuf); + return NSS_STATUS_NOTFOUND; + } + + sss_nss_getpwent_data.data = repbuf; + sss_nss_getpwent_data.len = replen; + sss_nss_getpwent_data.ptr = 8; /* skip metadata fields */ + + /* call again ourselves, this will return the first result */ + return internal_getpwent_r(result, buffer, buflen, errnop); +} + +enum nss_status _nss_sss_getpwent_r(struct passwd *result, + char *buffer, size_t buflen, + int *errnop) +{ + enum nss_status nret; + + sss_nss_lock(); + nret = internal_getpwent_r(result, buffer, buflen, errnop); + sss_nss_unlock(); + + return nret; +} + +enum nss_status _nss_sss_endpwent(void) +{ + enum nss_status nret; + int errnop; + int saved_errno = errno; + + sss_nss_lock(); + + /* make sure we do not have leftovers, and release memory */ + sss_nss_getpwent_data_clean(); + + nret = sss_nss_make_request(SSS_NSS_ENDPWENT, + NULL, NULL, NULL, &errnop); + if (nret != NSS_STATUS_SUCCESS) { + errno = errnop; + } else { + errno = saved_errno; + } + + sss_nss_unlock(); + return nret; +} diff --git a/src/sss_client/nss_services.c b/src/sss_client/nss_services.c new file mode 100644 index 0000000..4f44cb2 --- /dev/null +++ b/src/sss_client/nss_services.c @@ -0,0 +1,510 @@ +/* + SSSD + + Authors: + Stephen Gallagher <sgallagh@redhat.com> + + Copyright (C) 2012 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include "config.h" + +#include <nss.h> +#include <netdb.h> +#include <errno.h> +#include <sys/types.h> +#include <unistd.h> +#include <stdlib.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> +#include "sss_cli.h" + +static +#ifdef HAVE_PTHREAD_EXT +__thread +#endif +struct sss_nss_getservent_data { + size_t len; + size_t ptr; + uint8_t *data; +} sss_nss_getservent_data; + +static void sss_nss_getservent_data_clean(void) { + + if (sss_nss_getservent_data.data != NULL) { + free(sss_nss_getservent_data.data); + sss_nss_getservent_data.data = NULL; + } + sss_nss_getservent_data.len = 0; + sss_nss_getservent_data.ptr = 0; +} + +/* GETSERVBYNAME Request + * + * 0-X: Sequence of two, zero-terminated strings (name, protocol). + * Protocol may be zero-length to imply "any" + * + * GETSERVBYPORT Request: + * 0-3: 16-bit port number in network byte order + * 4-15: Reserved/padding + * 16-X: Zero-terminated string (protocol) + * Protocol may be zero-length to imply "any" + * + * Replies: + * 0-3: 32-bit unsigned number of results + * 4-7: 32-bit unsigned (reserved/padding) + * 7-X: Result data (blocks equal to number of results) + * + * Result data: + * 0-3: 32-bit unsigned port number in network byte order + * 4-7: 32-bit unsigned number of aliases + * 8-X: sequence of zero-terminated strings + * (name, protocol, zero or more aliases) + */ +struct sss_nss_svc_rep { + struct servent *result; + char *buffer; + size_t buflen; +}; + +#define SVC_METADATA_COUNT 8 + +static errno_t +sss_nss_getsvc_readrep(struct sss_nss_svc_rep *sr, + uint8_t *buf, size_t *len) +{ + errno_t ret; + uint32_t c; + uint32_t num_aliases; + size_t i, l, slen, dlen, pad, ptaliases, alen; + char *sbuf; + + /* Buffer must contain two 32-bit integers, + * at least one character and null-terminator + * for the name, and at least a null- + * terminator for the protocol. + */ + if (*len < 11) { + /* not enough space for data, bad packet */ + return EBADMSG; + } + + /* Get the port */ + SAFEALIGN_COPY_UINT32(&c, buf, NULL); + sr->result->s_port = (uint16_t)c; + + /* Get the number of aliases */ + SAFEALIGN_COPY_UINT32(&num_aliases, buf + sizeof(uint32_t), NULL); + + sbuf = (char *)&buf[2 * sizeof(uint32_t)]; + slen = *len - (2 * sizeof(uint32_t)); + dlen = sr->buflen; + + /* Copy in the name */ + i = 0; + sr->result->s_name = &(sr->buffer[i]); + + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &sr->result->s_name, + NULL); + if (ret != EOK) return ret; + + /* Copy in the protocol */ + sr->result->s_proto = &(sr->buffer[i]); + + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &sr->result->s_proto, + NULL); + if (ret != EOK) return ret; + + /* Make sure sr->buffer[i+pad] is aligned to sizeof(char *) */ + pad = PADDING_SIZE(i, char *); + + /* Copy in the aliases */ + sr->result->s_aliases = DISCARD_ALIGN(&(sr->buffer[i+pad]), char **); + + ptaliases = (sizeof(char *) * (num_aliases + 1)) + pad; + if (ptaliases > dlen) { + return ERANGE; /* not ENOMEM, ERANGE is what glibc looks for */ + } + + dlen -= ptaliases; + ptaliases += i; + sr->result->s_aliases[num_aliases] = NULL; /* terminate array */ + + for (l = 0; l < num_aliases; l++) { + sr->result->s_aliases[l] = &(sr->buffer[ptaliases]); + ret = sss_readrep_copy_string(sbuf, &i, + &slen, &dlen, + &sr->result->s_aliases[l], + &alen); + if (ret != EOK) return ret; + + ptaliases += alen + 1; + } + + *len = slen - i; + + return EOK; +} + +enum nss_status +_nss_sss_getservbyname_r(const char *name, + const char *protocol, + struct servent *result, + char *buffer, size_t buflen, + int *errnop) +{ + struct sss_cli_req_data rd; + struct sss_nss_svc_rep svcrep; + size_t name_len; + size_t proto_len = 0; + uint8_t *repbuf; + uint8_t *data; + size_t replen, len; + uint32_t num_results; + enum nss_status nret; + int ret; + + /* Caught once glibc passing in buffer == 0x0 */ + if (!buffer || !buflen) { + *errnop = ERANGE; + return NSS_STATUS_TRYAGAIN; + } + + ret = sss_strnlen(name, SSS_NAME_MAX, &name_len); + if (ret != 0) { + *errnop = EINVAL; + return NSS_STATUS_NOTFOUND; + } + + if (protocol) { + ret = sss_strnlen(protocol, SSS_NAME_MAX, &proto_len); + if (ret != 0) { + *errnop = EINVAL; + return NSS_STATUS_NOTFOUND; + } + } + + rd.len = name_len + proto_len + 2; + data = malloc(sizeof(uint8_t)*rd.len); + if (data == NULL) { + *errnop = ENOMEM; + return NSS_STATUS_TRYAGAIN; + } + + memcpy(data, name, name_len + 1); + + if (protocol) { + memcpy(data + name_len + 1, protocol, proto_len + 1); + } else { + /* No protocol specified, pass empty string */ + data[name_len + 1] = '\0'; + } + rd.data = data; + + sss_nss_lock(); + + nret = sss_nss_make_request(SSS_NSS_GETSERVBYNAME, &rd, + &repbuf, &replen, errnop); + free(data); + if (nret != NSS_STATUS_SUCCESS) { + goto out; + } + + svcrep.result = result; + svcrep.buffer = buffer; + svcrep.buflen = buflen; + + /* Get number of results from repbuf. */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* no results if not found */ + if (num_results == 0) { + free(repbuf); + nret = NSS_STATUS_NOTFOUND; + goto out; + } + + /* only 1 result is accepted for this function */ + if (num_results != 1) { + *errnop = EBADMSG; + free(repbuf); + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + len = replen - SVC_METADATA_COUNT; + ret = sss_nss_getsvc_readrep(&svcrep, + repbuf + SVC_METADATA_COUNT, + &len); + free(repbuf); + if (ret) { + *errnop = ret; + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + nret = NSS_STATUS_SUCCESS; + +out: + sss_nss_unlock(); + return nret; +} + + +enum nss_status +_nss_sss_getservbyport_r(int port, const char *protocol, + struct servent *result, + char *buffer, size_t buflen, + int *errnop) +{ + struct sss_cli_req_data rd; + struct sss_nss_svc_rep svcrep; + size_t proto_len = 0; + uint8_t *repbuf; + uint8_t *data; + size_t p = 0; + size_t replen, len; + uint32_t num_results; + enum nss_status nret; + int ret; + + /* Caught once glibc passing in buffer == 0x0 */ + if (!buffer || !buflen) { + *errnop = ERANGE; + return NSS_STATUS_TRYAGAIN; + } + + if (protocol) { + ret = sss_strnlen(protocol, SSS_NAME_MAX, &proto_len); + if (ret != 0) { + *errnop = EINVAL; + return NSS_STATUS_NOTFOUND; + } + } + + rd.len = sizeof(uint32_t)*2 + proto_len + 1; + data = malloc(sizeof(uint8_t)*rd.len); + if (data == NULL) { + *errnop = ENOMEM; + return NSS_STATUS_TRYAGAIN; + } + + SAFEALIGN_SET_UINT16(data, port, &p); + + /* Padding */ + SAFEALIGN_SET_UINT16(data + p, 0, &p); + SAFEALIGN_SET_UINT32(data + p, 0, &p); + + if (protocol) { + memcpy(data + p, protocol, proto_len + 1); + } else { + /* No protocol specified, pass empty string */ + data[p] = '\0'; + } + rd.data = data; + + sss_nss_lock(); + + nret = sss_nss_make_request(SSS_NSS_GETSERVBYPORT, &rd, + &repbuf, &replen, errnop); + free(data); + if (nret != NSS_STATUS_SUCCESS) { + goto out; + } + + svcrep.result = result; + svcrep.buffer = buffer; + svcrep.buflen = buflen; + + /* Get number of results from repbuf. */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* no results if not found */ + if (num_results == 0) { + free(repbuf); + nret = NSS_STATUS_NOTFOUND; + goto out; + } + + /* only 1 result is accepted for this function */ + if (num_results != 1) { + *errnop = EBADMSG; + free(repbuf); + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + len = replen - SVC_METADATA_COUNT; + ret = sss_nss_getsvc_readrep(&svcrep, + repbuf + SVC_METADATA_COUNT, + &len); + free(repbuf); + if (ret) { + *errnop = ret; + nret = NSS_STATUS_TRYAGAIN; + goto out; + } + + nret = NSS_STATUS_SUCCESS; + +out: + sss_nss_unlock(); + return nret; +} + + +enum nss_status +_nss_sss_setservent(void) +{ + enum nss_status nret; + int errnop; + sss_nss_lock(); + + /* make sure we do not have leftovers, and release memory */ + sss_nss_getservent_data_clean(); + + nret = sss_nss_make_request(SSS_NSS_SETSERVENT, + NULL, NULL, NULL, &errnop); + if (nret != NSS_STATUS_SUCCESS) { + errno = errnop; + } + + sss_nss_unlock(); + return nret; +} + +static enum nss_status internal_getservent_r(struct servent *result, + char *buffer, size_t buflen, + int *errnop); + +enum nss_status +_nss_sss_getservent_r(struct servent *result, + char *buffer, size_t buflen, + int *errnop) +{ + enum nss_status nret; + + sss_nss_lock(); + nret = internal_getservent_r(result, buffer, buflen, errnop); + sss_nss_unlock(); + + return nret; +} + +static enum nss_status internal_getservent_r(struct servent *result, + char *buffer, size_t buflen, + int *errnop) +{ + struct sss_cli_req_data rd; + struct sss_nss_svc_rep pwrep; + uint8_t *repbuf; + size_t replen; + uint32_t num_results; + enum nss_status nret; + uint32_t num_entries; + int ret; + + /* Caught once glibc passing in buffer == 0x0 */ + if (!buffer || !buflen) { + *errnop = ERANGE; + return NSS_STATUS_TRYAGAIN; + } + + /* if there are leftovers return the next one */ + if (sss_nss_getservent_data.data != NULL && + sss_nss_getservent_data.ptr < sss_nss_getservent_data.len) { + + repbuf = sss_nss_getservent_data.data + sss_nss_getservent_data.ptr; + replen = sss_nss_getservent_data.len - sss_nss_getservent_data.ptr; + + pwrep.result = result; + pwrep.buffer = buffer; + pwrep.buflen = buflen; + + ret = sss_nss_getsvc_readrep(&pwrep, repbuf, &replen); + if (ret) { + *errnop = ret; + return NSS_STATUS_TRYAGAIN; + } + + /* advance buffer pointer */ + sss_nss_getservent_data.ptr = sss_nss_getservent_data.len - replen; + + return NSS_STATUS_SUCCESS; + } + + /* release memory if any */ + sss_nss_getservent_data_clean(); + + /* retrieve no more than SSS_NSS_MAX_ENTRIES at a time */ + num_entries = SSS_NSS_MAX_ENTRIES; + rd.len = sizeof(uint32_t); + rd.data = &num_entries; + + nret = sss_nss_make_request(SSS_NSS_GETSERVENT, &rd, + &repbuf, &replen, errnop); + if (nret != NSS_STATUS_SUCCESS) { + return nret; + } + + /* Get number of results from repbuf */ + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + + /* no results if not found */ + if ((num_results == 0) || (replen - SVC_METADATA_COUNT == 0)) { + free(repbuf); + return NSS_STATUS_NOTFOUND; + } + + sss_nss_getservent_data.data = repbuf; + sss_nss_getservent_data.len = replen; + + /* skip metadata fields */ + sss_nss_getservent_data.ptr = SVC_METADATA_COUNT; + + /* call again ourselves, this will return the first result */ + return internal_getservent_r(result, buffer, buflen, errnop); +} + + +enum nss_status +_nss_sss_endservent(void) +{ + enum nss_status nret; + int errnop; + int saved_errno = errno; + + sss_nss_lock(); + + /* make sure we do not have leftovers, and release memory */ + sss_nss_getservent_data_clean(); + + nret = sss_nss_make_request(SSS_NSS_ENDSERVENT, + NULL, NULL, NULL, &errnop); + if (nret != NSS_STATUS_SUCCESS) { + errno = errnop; + } else { + errno = saved_errno; + } + + sss_nss_unlock(); + return nret; +} diff --git a/src/sss_client/pam_message.c b/src/sss_client/pam_message.c new file mode 100644 index 0000000..e3a09f5 --- /dev/null +++ b/src/sss_client/pam_message.c @@ -0,0 +1,194 @@ +/* + Authors: + Sumit Bose <sbose@redhat.com> + + PAM client - create message blob + + Copyright (C) 2015 Red Hat + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 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 Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include <stdlib.h> +#include <security/pam_modules.h> + +#include "sss_pam_compat.h" +#include "sss_pam_macros.h" + +#include "pam_message.h" + +#include "sss_cli.h" + +static size_t add_authtok_item(enum pam_item_type type, + enum sss_authtok_type authtok_type, + const char *tok, const size_t size, + uint8_t *buf) +{ + size_t rp = 0; + uint32_t c; + + if (tok == NULL) return 0; + + c = type; + memcpy(&buf[rp], &c, sizeof(uint32_t)); + rp += sizeof(uint32_t); + + c = size + sizeof(uint32_t); + memcpy(&buf[rp], &c, sizeof(uint32_t)); + rp += sizeof(uint32_t); + + c = authtok_type; + memcpy(&buf[rp], &c, sizeof(uint32_t)); + rp += sizeof(uint32_t); + + memcpy(&buf[rp], tok, size); + rp += size; + + return rp; +} + +static size_t add_uint32_t_item(enum pam_item_type type, const uint32_t val, + uint8_t *buf) +{ + size_t rp = 0; + uint32_t c; + + c = type; + memcpy(&buf[rp], &c, sizeof(uint32_t)); + rp += sizeof(uint32_t); + + c = sizeof(uint32_t); + memcpy(&buf[rp], &c, sizeof(uint32_t)); + rp += sizeof(uint32_t); + + c = val; + memcpy(&buf[rp], &c, sizeof(uint32_t)); + rp += sizeof(uint32_t); + + return rp; +} + +static size_t add_string_item(enum pam_item_type type, const char *str, + const size_t size, uint8_t *buf) +{ + size_t rp = 0; + uint32_t c; + + if (str == NULL || *str == '\0') return 0; + + c = type; + memcpy(&buf[rp], &c, sizeof(uint32_t)); + rp += sizeof(uint32_t); + + c = size; + memcpy(&buf[rp], &c, sizeof(uint32_t)); + rp += sizeof(uint32_t); + + memcpy(&buf[rp], str, size); + rp += size; + + return rp; +} + +int pack_message_v3(struct pam_items *pi, size_t *size, uint8_t **buffer) +{ + int len; + uint8_t *buf; + size_t rp; + + len = sizeof(uint32_t) + sizeof(uint32_t); + + len += *pi->pam_user != '\0' ? + 2*sizeof(uint32_t) + pi->pam_user_size : 0; + len += *pi->pam_service != '\0' ? + 2*sizeof(uint32_t) + pi->pam_service_size : 0; + len += *pi->pam_tty != '\0' ? + 2*sizeof(uint32_t) + pi->pam_tty_size : 0; + len += *pi->pam_ruser != '\0' ? + 2*sizeof(uint32_t) + pi->pam_ruser_size : 0; + len += *pi->pam_rhost != '\0' ? + 2*sizeof(uint32_t) + pi->pam_rhost_size : 0; + len += pi->pam_authtok != NULL ? + 3*sizeof(uint32_t) + pi->pam_authtok_size : 0; + len += pi->pam_newauthtok != NULL ? + 3*sizeof(uint32_t) + pi->pam_newauthtok_size : 0; + len += 3*sizeof(uint32_t); /* cli_pid */ + + len += *pi->requested_domains != '\0' ? + 2*sizeof(uint32_t) + pi->requested_domains_size : 0; + len += 3*sizeof(uint32_t); /* flags */ + + /* optional child_pid */ + if(pi->child_pid > 0) { + len += 3*sizeof(uint32_t); + } + + buf = malloc(len); + if (buf == NULL) { + D(("malloc failed.")); + return PAM_BUF_ERR; + } + + rp = 0; + SAFEALIGN_SETMEM_UINT32(buf, SSS_START_OF_PAM_REQUEST, &rp); + + rp += add_string_item(SSS_PAM_ITEM_USER, pi->pam_user, pi->pam_user_size, + &buf[rp]); + + rp += add_string_item(SSS_PAM_ITEM_SERVICE, pi->pam_service, + pi->pam_service_size, &buf[rp]); + + rp += add_string_item(SSS_PAM_ITEM_TTY, pi->pam_tty, pi->pam_tty_size, + &buf[rp]); + + rp += add_string_item(SSS_PAM_ITEM_RUSER, pi->pam_ruser, pi->pam_ruser_size, + &buf[rp]); + + rp += add_string_item(SSS_PAM_ITEM_RHOST, pi->pam_rhost, pi->pam_rhost_size, + &buf[rp]); + + rp += add_string_item(SSS_PAM_ITEM_REQUESTED_DOMAINS, pi->requested_domains, pi->requested_domains_size, + &buf[rp]); + + rp += add_uint32_t_item(SSS_PAM_ITEM_CLI_PID, (uint32_t) pi->cli_pid, + &buf[rp]); + + if (pi->child_pid > 0) { + rp += add_uint32_t_item(SSS_PAM_ITEM_CHILD_PID, + (uint32_t) pi->child_pid, &buf[rp]); + } + + rp += add_authtok_item(SSS_PAM_ITEM_AUTHTOK, pi->pam_authtok_type, + pi->pam_authtok, pi->pam_authtok_size, &buf[rp]); + + rp += add_authtok_item(SSS_PAM_ITEM_NEWAUTHTOK, pi->pam_newauthtok_type, + pi->pam_newauthtok, pi->pam_newauthtok_size, + &buf[rp]); + + rp += add_uint32_t_item(SSS_PAM_ITEM_FLAGS, (uint32_t) pi->flags, + &buf[rp]); + + SAFEALIGN_SETMEM_UINT32(buf + rp, SSS_END_OF_PAM_REQUEST, &rp); + + if (rp != len) { + D(("error during packet creation.")); + free(buf); + return PAM_BUF_ERR; + } + + *size = len; + *buffer = buf; + + return 0; +} diff --git a/src/sss_client/pam_message.h b/src/sss_client/pam_message.h new file mode 100644 index 0000000..d6fb254 --- /dev/null +++ b/src/sss_client/pam_message.h @@ -0,0 +1,80 @@ +/* + Authors: + Sumit Bose <sbose@redhat.com> + + Copyright (C) 2015 Red Hat + + PAM client - create message blob + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 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 Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef _PAM_MESSAGE_H_ +#define _PAM_MESSAGE_H_ + +#include <unistd.h> +#include <stdint.h> +#include <stdbool.h> + +#include "sss_client/sss_cli.h" + +struct cert_auth_info; + +struct pam_items { + const char *pam_service; + const char *pam_user; + const char *pam_tty; + const char *pam_ruser; + const char *pam_rhost; + char *pam_authtok; + char *pam_newauthtok; + const char *pamstack_authtok; + const char *pamstack_oldauthtok; + size_t pam_service_size; + size_t pam_user_size; + size_t pam_tty_size; + size_t pam_ruser_size; + size_t pam_rhost_size; + enum sss_authtok_type pam_authtok_type; + size_t pam_authtok_size; + enum sss_authtok_type pam_newauthtok_type; + size_t pam_newauthtok_size; + pid_t cli_pid; + pid_t child_pid; + uint32_t flags; + const char *login_name; + char *domain_name; + const char *requested_domains; + size_t requested_domains_size; + char *otp_vendor; + char *otp_token_id; + char *otp_challenge; + char *oauth2_url; + char *oauth2_url_complete; + char *oauth2_pin; + char *first_factor; + char *passkey_key; + char *passkey_prompt_pin; + bool password_prompting; + + bool user_name_hint; + struct cert_auth_info *cert_list; + struct cert_auth_info *selected_cert; + + struct prompt_config **pc; +}; + +int pack_message_v3(struct pam_items *pi, size_t *size, uint8_t **buffer); + +#endif /* _PAM_MESSAGE_H_ */ diff --git a/src/sss_client/pam_sss.c b/src/sss_client/pam_sss.c new file mode 100644 index 0000000..a1c3536 --- /dev/null +++ b/src/sss_client/pam_sss.c @@ -0,0 +1,3220 @@ +/* + Authors: + Sumit Bose <sbose@redhat.com> + + Copyright (C) 2009 Red Hat + Copyright (C) 2010, rhafer@suse.de, Novell Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 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 Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "config.h" +#include <sys/types.h> +#include <unistd.h> +#include <stdlib.h> +#include <stdint.h> +#include <stdio.h> +#include <syslog.h> +#include <time.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <errno.h> +#include <locale.h> +#include <stdbool.h> +#include <ctype.h> + +#include <security/pam_modules.h> +#include <security/pam_appl.h> + +#ifdef HAVE_GDM_PAM_EXTENSIONS +#include <gdm/gdm-pam-extensions.h> +#endif + +#include "sss_pam_compat.h" +#include "sss_pam_macros.h" + +#include "sss_cli.h" +#include "pam_message.h" +#include "util/atomic_io.h" +#include "util/authtok-utils.h" +#include "util/dlinklist.h" + +#include <libintl.h> +#define _(STRING) dgettext (PACKAGE, STRING) +#define _n(SINGULAR, PLURAL, VALUE) dngettext(PACKAGE, SINGULAR, PLURAL, VALUE) + +#define PWEXP_FLAG "pam_sss:password_expired_flag" +#define FD_DESTRUCTOR "pam_sss:fd_destructor" +#define PAM_SSS_AUTHOK_TYPE "pam_sss:authtok_type" +#define PAM_SSS_AUTHOK_SIZE "pam_sss:authtok_size" +#define PAM_SSS_AUTHOK_DATA "pam_sss:authtok_data" + +#define PW_RESET_MSG_FILENAME_TEMPLATE SSSD_CONF_DIR"/customize/%s/pam_sss_pw_reset_message.%s" +#define PW_RESET_MSG_MAX_SIZE 4096 + +#define OPT_RETRY_KEY "retry=" +#define OPT_DOMAINS_KEY "domains=" + +#define EXP_ACC_MSG _("Permission denied. ") +#define SRV_MSG _("Server message: ") +#define PASSKEY_LOCAL_AUTH_MSG _("Kerberos TGT will not be granted upon login, user experience will be affected.") +#define PASSKEY_DEFAULT_PIN_MSG _("Enter PIN:") + +#define DEBUG_MGS_LEN 1024 +#define MAX_AUTHTOK_SIZE (1024*1024) +#define CHECK_AND_RETURN_PI_STRING(s) ((s != NULL && *s != '\0')? s : "(not available)") +#define SERVICE_IS_GDM_SMARTCARD(pitem) (strcmp((pitem)->pam_service, \ + "gdm-smartcard") == 0) + +static void logger(pam_handle_t *pamh, int level, const char *fmt, ...) { + va_list ap; + + va_start(ap, fmt); + +#ifdef DEBUG + va_list apd; + char debug_msg[DEBUG_MGS_LEN]; + int ret; + va_copy(apd, ap); + + ret = vsnprintf(debug_msg, DEBUG_MGS_LEN, fmt, apd); + if (ret >= DEBUG_MGS_LEN) { + D(("the following message is truncated: %s", debug_msg)); + } else if (ret < 0) { + D(("vsnprintf failed to format debug message!")); + } else { + D((debug_msg)); + } + + va_end(apd); +#endif + + pam_vsyslog(pamh, LOG_AUTHPRIV|level, fmt, ap); + + va_end(ap); +} + +static void free_exp_data(pam_handle_t *pamh, void *ptr, int err) +{ + free(ptr); +} + +static void close_fd(pam_handle_t *pamh, void *ptr, int err) +{ +#ifdef PAM_DATA_REPLACE + if (err & PAM_DATA_REPLACE) { + /* Nothing to do */ + return; + } +#endif /* PAM_DATA_REPLACE */ + + D(("Closing the fd")); + + sss_pam_lock(); + sss_cli_close_socket(); + sss_pam_unlock(); +} + +struct cert_auth_info { + char *cert_user; + char *cert; + char *token_name; + char *module_name; + char *key_id; + char *label; + char *prompt_str; + char *pam_cert_user; + char *choice_list_id; + struct cert_auth_info *prev; + struct cert_auth_info *next; +}; + +static void free_cai(struct cert_auth_info *cai) +{ + if (cai != NULL) { + free(cai->cert_user); + free(cai->cert); + free(cai->token_name); + free(cai->module_name); + free(cai->key_id); + free(cai->label); + free(cai->prompt_str); + free(cai->choice_list_id); + free(cai); + } +} + +static void free_cert_list(struct cert_auth_info *list) +{ + struct cert_auth_info *cai; + struct cert_auth_info *cai_next; + + if (list != NULL) { + DLIST_FOR_EACH_SAFE(cai, cai_next, list) { + DLIST_REMOVE(list, cai); + free_cai(cai); + } + } +} + +static void overwrite_and_free_authtoks(struct pam_items *pi) +{ + if (pi->pam_authtok != NULL) { + _pam_overwrite_n((void *)pi->pam_authtok, pi->pam_authtok_size); + free((void *)pi->pam_authtok); + pi->pam_authtok = NULL; + } + + if (pi->pam_newauthtok != NULL) { + _pam_overwrite_n((void *)pi->pam_newauthtok, pi->pam_newauthtok_size); + free((void *)pi->pam_newauthtok); + pi->pam_newauthtok = NULL; + } + + if (pi->first_factor != NULL) { + _pam_overwrite_n((void *)pi->first_factor, strlen(pi->first_factor)); + free((void *)pi->first_factor); + pi->first_factor = NULL; + } + + pi->pamstack_authtok = NULL; + pi->pamstack_oldauthtok = NULL; +} + +static void overwrite_and_free_pam_items(struct pam_items *pi) +{ + overwrite_and_free_authtoks(pi); + + free(pi->domain_name); + pi->domain_name = NULL; + + free(pi->otp_vendor); + pi->otp_vendor = NULL; + + free(pi->otp_token_id); + pi->otp_token_id = NULL; + + free(pi->otp_challenge); + pi->otp_challenge = NULL; + + free(pi->passkey_key); + pi->passkey_key = NULL; + + free(pi->passkey_prompt_pin); + pi->passkey_prompt_pin = NULL; + + free_cert_list(pi->cert_list); + pi->cert_list = NULL; + pi->selected_cert = NULL; + + pc_list_free(pi->pc); + pi->pc = NULL; +} + +static int null_strcmp(const char *s1, const char *s2) { + if (s1 == NULL && s2 == NULL) return 0; + if (s1 == NULL && s2 != NULL) return -1; + if (s1 != NULL && s2 == NULL) return 1; + return strcmp(s1, s2); +} + +enum { + SSS_PAM_CONV_DONE = 0, + SSS_PAM_CONV_STD, + SSS_PAM_CONV_REENTER, +}; + +static int do_pam_conversation(pam_handle_t *pamh, const int msg_style, + const char *msg, + const char *reenter_msg, + char **_answer) +{ + int ret; + int state = SSS_PAM_CONV_STD; + const struct pam_conv *conv; + const struct pam_message *mesg[1]; + struct pam_message *pam_msg; + struct pam_response *resp=NULL; + char *answer = NULL; + + if ((msg_style == PAM_TEXT_INFO || msg_style == PAM_ERROR_MSG) && + msg == NULL) return PAM_SYSTEM_ERR; + + if ((msg_style == PAM_PROMPT_ECHO_OFF || + msg_style == PAM_PROMPT_ECHO_ON) && + (msg == NULL || _answer == NULL)) return PAM_SYSTEM_ERR; + + if (msg_style == PAM_TEXT_INFO || msg_style == PAM_ERROR_MSG) { + logger(pamh, LOG_INFO, "User %s message: %s", + msg_style == PAM_TEXT_INFO ? "info" : "error", + msg); + } + + ret=pam_get_item(pamh, PAM_CONV, (const void **) &conv); + if (ret != PAM_SUCCESS) return ret; + if (conv == NULL || conv->conv == NULL) { + logger(pamh, LOG_ERR, "No conversation function"); + return PAM_SYSTEM_ERR; + } + + do { + pam_msg = malloc(sizeof(struct pam_message)); + if (pam_msg == NULL) { + D(("Malloc failed.")); + ret = PAM_SYSTEM_ERR; + goto failed; + } + + pam_msg->msg_style = msg_style; + if (state == SSS_PAM_CONV_REENTER) { + pam_msg->msg = reenter_msg; + } else { + pam_msg->msg = msg; + } + + mesg[0] = (const struct pam_message *) pam_msg; + + ret=conv->conv(1, mesg, &resp, + conv->appdata_ptr); + free(pam_msg); + if (ret != PAM_SUCCESS) { + D(("Conversation failure: %s.", pam_strerror(pamh,ret))); + goto failed; + } + + if (msg_style == PAM_PROMPT_ECHO_OFF || + msg_style == PAM_PROMPT_ECHO_ON) { + if (resp == NULL) { + D(("response expected, but resp==NULL")); + ret = PAM_SYSTEM_ERR; + goto failed; + } + + if (state == SSS_PAM_CONV_REENTER) { + if (null_strcmp(answer, resp[0].resp) != 0) { + logger(pamh, LOG_NOTICE, "Passwords do not match."); + _pam_overwrite((void *)resp[0].resp); + free(resp[0].resp); + if (answer != NULL) { + _pam_overwrite((void *) answer); + free(answer); + answer = NULL; + } + ret = do_pam_conversation(pamh, PAM_ERROR_MSG, + _("Passwords do not match"), + NULL, NULL); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + ret = PAM_SYSTEM_ERR; + goto failed; + } + ret = PAM_CRED_ERR; + goto failed; + } + _pam_overwrite((void *)resp[0].resp); + free(resp[0].resp); + } else { + if (resp[0].resp == NULL) { + D(("Empty password")); + answer = NULL; + } else { + answer = strndup(resp[0].resp, MAX_AUTHTOK_SIZE); + _pam_overwrite((void *)resp[0].resp); + free(resp[0].resp); + if(answer == NULL) { + D(("strndup failed")); + ret = PAM_BUF_ERR; + goto failed; + } + } + } + free(resp); + resp = NULL; + } + + if (reenter_msg != NULL && state == SSS_PAM_CONV_STD) { + state = SSS_PAM_CONV_REENTER; + } else { + state = SSS_PAM_CONV_DONE; + } + } while (state != SSS_PAM_CONV_DONE); + + if (_answer) *_answer = answer; + return PAM_SUCCESS; + +failed: + free(answer); + return ret; + +} + +static errno_t display_pw_reset_message(pam_handle_t *pamh, + const char *domain_name, + const char *suffix) +{ + int ret; + struct stat stat_buf; + char *msg_buf = NULL; + int fd = -1; + size_t size; + size_t total_len; + char *filename = NULL; + + if (strchr(suffix, '/') != NULL || strchr(domain_name, '/') != NULL) { + D(("Suffix [%s] or domain name [%s] contain illegal character.", suffix, + domain_name)); + return EINVAL; + } + + size = sizeof(PW_RESET_MSG_FILENAME_TEMPLATE) + strlen(domain_name) + + strlen(suffix); + filename = malloc(size); + if (filename == NULL) { + D(("malloc failed.")); + ret = ENOMEM; + goto done; + } + ret = snprintf(filename, size, PW_RESET_MSG_FILENAME_TEMPLATE, domain_name, + suffix); + if (ret < 0 || ret >= size) { + D(("snprintf failed.")); + ret = EFAULT; + goto done; + } + + fd = open(filename, O_RDONLY); + if (fd == -1) { + ret = errno; + D(("open failed [%d][%s].\n", ret, strerror(ret))); + goto done; + } + + ret = fstat(fd, &stat_buf); + if (ret == -1) { + ret = errno; + D(("fstat failed [%d][%s].", ret, strerror(ret))); + goto done; + } + + if (!S_ISREG(stat_buf.st_mode)) { + logger(pamh, LOG_ERR, + "Password reset message file is not a regular file."); + ret = EINVAL; + goto done; + } + + if (stat_buf.st_uid != 0 || stat_buf.st_gid != 0 || + (stat_buf.st_mode & ~S_IFMT) != 0644) { + logger(pamh, LOG_ERR,"Permission error, " + "file [%s] must be owned by root with permissions 0644.", + filename); + ret = EPERM; + goto done; + } + + if (stat_buf.st_size > PW_RESET_MSG_MAX_SIZE) { + logger(pamh, LOG_ERR, "Password reset message file is too large."); + ret = EFBIG; + goto done; + } + + msg_buf = malloc(stat_buf.st_size + 1); + if (msg_buf == NULL) { + D(("malloc failed.")); + ret = ENOMEM; + goto done; + } + + errno = 0; + total_len = sss_atomic_read_s(fd, msg_buf, stat_buf.st_size); + if (total_len == -1) { + ret = errno; + D(("read failed [%d][%s].", ret, strerror(ret))); + goto done; + } + + ret = close(fd); + fd = -1; + if (ret == -1) { + ret = errno; + D(("close failed [%d][%s].", ret, strerror(ret))); + } + + if (total_len != stat_buf.st_size) { + D(("read fewer bytes [%d] than expected [%d].", total_len, + stat_buf.st_size)); + ret = EIO; + goto done; + } + + msg_buf[stat_buf.st_size] = '\0'; + + ret = do_pam_conversation(pamh, PAM_TEXT_INFO, msg_buf, NULL, NULL); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + } + +done: + if (fd != -1) { + close(fd); + } + free(msg_buf); + free(filename); + + return ret; +} + +static errno_t select_pw_reset_message(pam_handle_t *pamh, struct pam_items *pi) +{ + int ret; + char *locale; + const char *domain_name; + + domain_name = pi->domain_name; + if (domain_name == NULL || *domain_name == '\0') { + D(("Domain name is unknown.")); + return EINVAL; + } + + locale = setlocale(LC_MESSAGES, NULL); + + ret = -1; + if (locale != NULL) { + ret = display_pw_reset_message(pamh, domain_name, locale); + } + + if (ret != 0) { + ret = display_pw_reset_message(pamh, domain_name, "txt"); + } + + if (ret != 0) { + ret = do_pam_conversation(pamh, PAM_TEXT_INFO, + _("Password reset by root is not supported."), + NULL, NULL); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + } + } + + return ret; +} + +static int user_info_offline_auth(pam_handle_t *pamh, size_t buflen, + uint8_t *buf) +{ + int ret; + int64_t expire_date; + struct tm tm; + char expire_str[128]; + char user_msg[256]; + + expire_str[0] = '\0'; + + if (buflen != sizeof(uint32_t) + sizeof(int64_t)) { + D(("User info response data has the wrong size")); + return PAM_BUF_ERR; + } + + memcpy(&expire_date, buf + sizeof(uint32_t), sizeof(int64_t)); + + if (expire_date > 0) { + if (localtime_r((time_t *) &expire_date, &tm) != NULL) { + ret = strftime(expire_str, sizeof(expire_str), "%c", &tm); + if (ret == 0) { + D(("strftime failed.")); + expire_str[0] = '\0'; + } + } else { + D(("localtime_r failed")); + } + } + + ret = snprintf(user_msg, sizeof(user_msg), "%s%s%s.", + _("Authenticated with cached credentials"), + expire_str[0] ? _(", your cached password will expire at: ") : "", + expire_str[0] ? expire_str : ""); + if (ret < 0 || ret >= sizeof(user_msg)) { + D(("snprintf failed.")); + return PAM_SYSTEM_ERR; + } + + ret = do_pam_conversation(pamh, PAM_TEXT_INFO, user_msg, NULL, NULL); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + return PAM_SYSTEM_ERR; + } + + return PAM_SUCCESS; +} + +static int user_info_grace_login(pam_handle_t *pamh, + size_t buflen, + uint8_t *buf) +{ + int ret; + uint32_t grace; + char user_msg[256]; + + if (buflen != 2* sizeof(uint32_t)) { + D(("User info response data has the wrong size")); + return PAM_BUF_ERR; + } + memcpy(&grace, buf + sizeof(uint32_t), sizeof(uint32_t)); + ret = snprintf(user_msg, sizeof(user_msg), + _("Your password has expired. " + "You have %1$d grace login(s) remaining."), + grace); + if (ret < 0 || ret >= sizeof(user_msg)) { + D(("snprintf failed.")); + return PAM_SYSTEM_ERR; + } + ret = do_pam_conversation(pamh, PAM_TEXT_INFO, user_msg, NULL, NULL); + + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + return PAM_SYSTEM_ERR; + } + + return PAM_SUCCESS; +} + +#define MINSEC 60 +#define HOURSEC (60*MINSEC) +#define DAYSEC (24*HOURSEC) +static int user_info_expire_warn(pam_handle_t *pamh, + size_t buflen, + uint8_t *buf) +{ + int ret; + uint32_t expire; + char user_msg[256]; + const char* unit; + + if (buflen != 2* sizeof(uint32_t)) { + D(("User info response data has the wrong size")); + return PAM_BUF_ERR; + } + memcpy(&expire, buf + sizeof(uint32_t), sizeof(uint32_t)); + /* expire == 0 indicates the password expired */ + if (expire != 0) { + if (expire >= DAYSEC) { + expire /= DAYSEC; + unit = _n("day", "days", expire); + } else if (expire >= HOURSEC) { + expire /= HOURSEC; + unit = _n("hour", "hours", expire); + } else if (expire >= MINSEC) { + expire /= MINSEC; + unit = _n("minute", "minutes", expire); + } else { + unit = _n("second", "seconds", expire); + } + + ret = snprintf(user_msg, sizeof(user_msg), + _("Your password will expire in %1$d %2$s."), expire, unit); + } else { + ret = snprintf(user_msg, sizeof(user_msg), + _("Your password has expired.")); + } + + if (ret < 0 || ret >= sizeof(user_msg)) { + D(("snprintf failed.")); + return PAM_SYSTEM_ERR; + } + ret = do_pam_conversation(pamh, PAM_TEXT_INFO, user_msg, NULL, NULL); + + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + return PAM_SYSTEM_ERR; + } + + return PAM_SUCCESS; +} + +static int user_info_offline_auth_delayed(pam_handle_t *pamh, size_t buflen, + uint8_t *buf) +{ + int ret; + int64_t delayed_until; + struct tm tm; + char delay_str[128]; + char user_msg[256]; + + delay_str[0] = '\0'; + + if (buflen != sizeof(uint32_t) + sizeof(int64_t)) { + D(("User info response data has the wrong size")); + return PAM_BUF_ERR; + } + + memcpy(&delayed_until, buf + sizeof(uint32_t), sizeof(int64_t)); + + if (delayed_until <= 0) { + D(("User info response data has an invalid value")); + return PAM_BUF_ERR; + } + + if (localtime_r((time_t *) &delayed_until, &tm) != NULL) { + ret = strftime(delay_str, sizeof(delay_str), "%c", &tm); + if (ret == 0) { + D(("strftime failed.")); + delay_str[0] = '\0'; + } + } else { + D(("localtime_r failed")); + } + + ret = snprintf(user_msg, sizeof(user_msg), "%s%s.", + _("Authentication is denied until: "), + delay_str); + if (ret < 0 || ret >= sizeof(user_msg)) { + D(("snprintf failed.")); + return PAM_SYSTEM_ERR; + } + + ret = do_pam_conversation(pamh, PAM_TEXT_INFO, user_msg, NULL, NULL); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + return PAM_SYSTEM_ERR; + } + + return PAM_SUCCESS; +} + +static int user_info_offline_chpass(pam_handle_t *pamh) +{ + int ret; + + ret = do_pam_conversation(pamh, PAM_TEXT_INFO, + _("System is offline, password change not possible"), + NULL, NULL); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + return PAM_SYSTEM_ERR; + } + + return PAM_SUCCESS; +} + +static int user_info_otp_chpass(pam_handle_t *pamh) +{ + int ret; + + ret = do_pam_conversation(pamh, PAM_TEXT_INFO, + _("After changing the OTP password, you need to " + "log out and back in order to acquire a ticket"), + NULL, NULL); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + return PAM_SYSTEM_ERR; + } + + return PAM_SUCCESS; +} + +static int user_info_pin_locked(pam_handle_t *pamh) +{ + int ret; + + ret = do_pam_conversation(pamh, PAM_TEXT_INFO, _("PIN locked"), + NULL, NULL); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + return PAM_SYSTEM_ERR; + } + + return PAM_SUCCESS; +} + +static int user_info_no_krb_tgt(pam_handle_t *pamh) +{ + int ret; + + ret = do_pam_conversation(pamh, PAM_TEXT_INFO, + _("No Kerberos TGT granted as " + "the server does not support this method. " + "Your single-sign on(SSO) experience will " + "be affected."), + NULL, NULL); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + return PAM_SYSTEM_ERR; + } + + return PAM_SUCCESS; +} + +static int user_info_account_expired(pam_handle_t *pamh, size_t buflen, + uint8_t *buf) +{ + int ret; + uint32_t msg_len; + char *user_msg; + size_t bufsize = 0; + + /* resp_type and length of message are expected to be in buf */ + if (buflen < 2* sizeof(uint32_t)) { + D(("User info response data is too short")); + return PAM_BUF_ERR; + } + + /* msg_len = legth of message */ + memcpy(&msg_len, buf + sizeof(uint32_t), sizeof(uint32_t)); + + if (buflen != 2* sizeof(uint32_t) + msg_len) { + D(("User info response data has the wrong size")); + return PAM_BUF_ERR; + } + + bufsize = strlen(EXP_ACC_MSG) + 1; + + if (msg_len > 0) { + bufsize += strlen(SRV_MSG) + msg_len; + } + + user_msg = (char *)malloc(sizeof(char) * bufsize); + if (!user_msg) { + D(("Out of memory.")); + return PAM_SYSTEM_ERR; + } + + ret = snprintf(user_msg, bufsize, "%s%s%.*s", + EXP_ACC_MSG, + msg_len > 0 ? SRV_MSG : "", + (int)msg_len, + msg_len > 0 ? (char *)(buf + 2 * sizeof(uint32_t)) : "" ); + if (ret < 0 || ret > bufsize) { + D(("snprintf failed.")); + + free(user_msg); + return PAM_SYSTEM_ERR; + } + + ret = do_pam_conversation(pamh, PAM_TEXT_INFO, user_msg, NULL, NULL); + free(user_msg); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + + return PAM_SYSTEM_ERR; + } + + return PAM_SUCCESS; +} + +static int user_info_chpass_error(pam_handle_t *pamh, size_t buflen, + uint8_t *buf) +{ + int ret; + uint32_t msg_len; + char *user_msg; + size_t bufsize = 0; + + if (buflen < 2* sizeof(uint32_t)) { + D(("User info response data is too short")); + return PAM_BUF_ERR; + } + + memcpy(&msg_len, buf + sizeof(uint32_t), sizeof(uint32_t)); + + if (buflen != 2* sizeof(uint32_t) + msg_len) { + D(("User info response data has the wrong size")); + return PAM_BUF_ERR; + } + + bufsize = strlen(_("Password change failed. ")) + 1; + + if (msg_len > 0) { + bufsize += strlen(_("Server message: ")) + msg_len; + } + + user_msg = (char *)malloc(sizeof(char) * bufsize); + if (!user_msg) { + D(("Out of memory.")); + return PAM_SYSTEM_ERR; + } + + ret = snprintf(user_msg, bufsize, "%s%s%.*s", + _("Password change failed. "), + msg_len > 0 ? _("Server message: ") : "", + (int)msg_len, + msg_len > 0 ? (char *)(buf + 2 * sizeof(uint32_t)) : "" ); + if (ret < 0 || ret > bufsize) { + D(("snprintf failed.")); + + free(user_msg); + return PAM_SYSTEM_ERR; + } + + ret = do_pam_conversation(pamh, PAM_TEXT_INFO, user_msg, NULL, NULL); + free(user_msg); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + + return PAM_SYSTEM_ERR; + } + + return PAM_SUCCESS; +} + +static int eval_user_info_response(pam_handle_t *pamh, size_t buflen, + uint8_t *buf) +{ + int ret; + uint32_t type; + + if (buflen < sizeof(uint32_t)) { + D(("User info response data is too short")); + return PAM_BUF_ERR; + } + + memcpy(&type, buf, sizeof(uint32_t)); + + switch(type) { + case SSS_PAM_USER_INFO_OFFLINE_AUTH: + ret = user_info_offline_auth(pamh, buflen, buf); + break; + case SSS_PAM_USER_INFO_GRACE_LOGIN: + ret = user_info_grace_login(pamh, buflen, buf); + break; + case SSS_PAM_USER_INFO_EXPIRE_WARN: + ret = user_info_expire_warn(pamh, buflen, buf); + break; + case SSS_PAM_USER_INFO_OFFLINE_AUTH_DELAYED: + ret = user_info_offline_auth_delayed(pamh, buflen, buf); + break; + case SSS_PAM_USER_INFO_OFFLINE_CHPASS: + ret = user_info_offline_chpass(pamh); + break; + case SSS_PAM_USER_INFO_OTP_CHPASS: + ret = user_info_otp_chpass(pamh); + break; + case SSS_PAM_USER_INFO_CHPASS_ERROR: + ret = user_info_chpass_error(pamh, buflen, buf); + break; + case SSS_PAM_USER_INFO_PIN_LOCKED: + ret = user_info_pin_locked(pamh); + break; + case SSS_PAM_USER_INFO_ACCOUNT_EXPIRED: + ret = user_info_account_expired(pamh, buflen, buf); + break; + case SSS_PAM_USER_INFO_NO_KRB_TGT: + ret = user_info_no_krb_tgt(pamh); + break; + default: + D(("Unknown user info type [%d]", type)); + ret = PAM_SYSTEM_ERR; + } + + return ret; +} + +static int parse_cert_info(struct pam_items *pi, uint8_t *buf, size_t len, + size_t *p, const char **cert_user, + const char **pam_cert_user) +{ + struct cert_auth_info *cai = NULL; + size_t offset; + int ret; + + if (buf[*p + (len - 1)] != '\0') { + D(("cert info does not end with \\0.")); + return EINVAL; + } + + cai = calloc(1, sizeof(struct cert_auth_info)); + if (cai == NULL) { + return ENOMEM; + } + + cai->cert_user = strdup((char *) &buf[*p]); + if (cai->cert_user == NULL) { + D(("strdup failed")); + ret = ENOMEM; + goto done; + } + if (cert_user != NULL) { + *cert_user = cai->cert_user; + } + + offset = strlen(cai->cert_user) + 1; + if (offset >= len) { + D(("Cert message size mismatch")); + ret = EINVAL; + goto done; + } + + cai->token_name = strdup((char *) &buf[*p + offset]); + if (cai->token_name == NULL) { + D(("strdup failed")); + ret = ENOMEM; + goto done; + } + + offset += strlen(cai->token_name) + 1; + if (offset >= len) { + D(("Cert message size mismatch")); + ret = EINVAL; + goto done; + } + + cai->module_name = strdup((char *) &buf[*p + offset]); + if (cai->module_name == NULL) { + D(("strdup failed")); + ret = ENOMEM; + goto done; + } + + offset += strlen(cai->module_name) + 1; + if (offset >= len) { + D(("Cert message size mismatch")); + ret = EINVAL; + goto done; + } + + cai->key_id = strdup((char *) &buf[*p + offset]); + if (cai->key_id == NULL) { + D(("strdup failed")); + ret = ENOMEM; + goto done; + } + + offset += strlen(cai->key_id) + 1; + if (offset >= len) { + D(("Cert message size mismatch")); + ret = EINVAL; + goto done; + } + + cai->label = strdup((char *) &buf[*p + offset]); + if (cai->label == NULL) { + D(("strdup failed")); + ret = ENOMEM; + goto done; + } + + offset += strlen(cai->label) + 1; + if (offset >= len) { + D(("Cert message size mismatch")); + ret = EINVAL; + goto done; + } + + cai->prompt_str = strdup((char *) &buf[*p + offset]); + if (cai->prompt_str == NULL) { + D(("strdup failed")); + ret = ENOMEM; + goto done; + } + + offset += strlen(cai->prompt_str) + 1; + if (offset >= len) { + D(("Cert message size mismatch")); + ret = EINVAL; + goto done; + } + + cai->pam_cert_user = strdup((char *) &buf[*p + offset]); + if (cai->pam_cert_user == NULL) { + D(("strdup failed")); + ret = ENOMEM; + goto done; + } + if (pam_cert_user != NULL) { + *pam_cert_user = cai->pam_cert_user; + } + + D(("cert user: [%s] token name: [%s] module: [%s] key id: [%s] " + "prompt: [%s] pam cert user: [%s]", + cai->cert_user, cai->token_name, cai->module_name, + cai->key_id, cai->prompt_str, cai->pam_cert_user)); + + DLIST_ADD(pi->cert_list, cai); + ret = 0; + +done: + if (ret != 0) { + free_cai(cai); + } + + return ret; +} + +static int eval_response(pam_handle_t *pamh, size_t buflen, uint8_t *buf, + struct pam_items *pi) +{ + int ret; + size_t p=0; + char *env_item; + int32_t c; + int32_t type; + int32_t len; + int32_t pam_status; + size_t offset; + const char *cert_user; + const char *pam_cert_user; + + if (buflen < (2*sizeof(int32_t))) { + D(("response buffer is too small")); + return PAM_BUF_ERR; + } + + memcpy(&pam_status, buf+p, sizeof(int32_t)); + p += sizeof(int32_t); + + + memcpy(&c, buf+p, sizeof(int32_t)); + p += sizeof(int32_t); + + while(c>0) { + if (buflen < (p+2*sizeof(int32_t))) { + D(("response buffer is too small")); + return PAM_BUF_ERR; + } + + memcpy(&type, buf+p, sizeof(int32_t)); + p += sizeof(int32_t); + + memcpy(&len, buf+p, sizeof(int32_t)); + p += sizeof(int32_t); + + if (buflen < (p + len)) { + D(("response buffer is too small")); + return PAM_BUF_ERR; + } + + switch(type) { + case SSS_PAM_SYSTEM_INFO: + if (buf[p + (len -1)] != '\0') { + D(("system info does not end with \\0.")); + break; + } + logger(pamh, LOG_INFO, "system info: [%s]", &buf[p]); + break; + case SSS_PAM_DOMAIN_NAME: + if (buf[p + (len -1)] != '\0') { + D(("domain name does not end with \\0.")); + break; + } + D(("domain name: [%s]", &buf[p])); + free(pi->domain_name); + pi->domain_name = strdup((char *) &buf[p]); + if (pi->domain_name == NULL) { + D(("strdup failed")); + } + break; + case SSS_ENV_ITEM: + case SSS_PAM_ENV_ITEM: + case SSS_ALL_ENV_ITEM: + if (buf[p + (len -1)] != '\0') { + D(("env item does not end with \\0.")); + break; + } + + D(("env item: [%s]", &buf[p])); + if (type == SSS_PAM_ENV_ITEM || type == SSS_ALL_ENV_ITEM) { + ret = pam_putenv(pamh, (char *)&buf[p]); + if (ret != PAM_SUCCESS) { + D(("pam_putenv failed.")); + break; + } + } + + if (type == SSS_ENV_ITEM || type == SSS_ALL_ENV_ITEM) { + env_item = strdup((char *)&buf[p]); + if (env_item == NULL) { + D(("strdup failed")); + break; + } + ret = putenv(env_item); + if (ret == -1) { + D(("putenv failed.")); + break; + } + } + break; + case SSS_PAM_USER_INFO: + ret = eval_user_info_response(pamh, len, &buf[p]); + if (ret != PAM_SUCCESS) { + D(("eval_user_info_response failed")); + } + break; + case SSS_PAM_TEXT_MSG: + if (buf[p + (len -1)] != '\0') { + D(("system info does not end with \\0.")); + break; + } + + ret = do_pam_conversation(pamh, PAM_TEXT_INFO, (char *) &buf[p], + NULL, NULL); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + } + break; + case SSS_OTP: + D(("OTP was used, removing authtokens.")); + overwrite_and_free_authtoks(pi); + ret = pam_set_item(pamh, PAM_AUTHTOK, NULL); + if (ret != PAM_SUCCESS) { + D(("Failed to remove PAM_AUTHTOK after using otp [%s]", + pam_strerror(pamh,ret))); + } + break; + case SSS_PAM_OTP_INFO: + if (buf[p + (len - 1)] != '\0') { + D(("otp info does not end with \\0.")); + break; + } + + free(pi->otp_vendor); + pi->otp_vendor = strdup((char *) &buf[p]); + if (pi->otp_vendor == NULL) { + D(("strdup failed")); + break; + } + + offset = strlen(pi->otp_vendor) + 1; + if (offset >= len) { + D(("OTP message size mismatch")); + free(pi->otp_vendor); + pi->otp_vendor = NULL; + break; + } + free(pi->otp_token_id); + pi->otp_token_id = strdup((char *) &buf[p + offset]); + if (pi->otp_token_id == NULL) { + D(("strdup failed")); + break; + } + + offset += strlen(pi->otp_token_id) + 1; + if (offset >= len) { + D(("OTP message size mismatch")); + free(pi->otp_token_id); + pi->otp_token_id = NULL; + break; + } + free(pi->otp_challenge); + pi->otp_challenge = strdup((char *) &buf[p + offset]); + if (pi->otp_challenge == NULL) { + D(("strdup failed")); + break; + } + + break; + case SSS_PAM_CERT_INFO: + case SSS_PAM_CERT_INFO_WITH_HINT: + if (buf[p + (len - 1)] != '\0') { + D(("cert info does not end with \\0.")); + break; + } + + if (type == SSS_PAM_CERT_INFO_WITH_HINT) { + pi->user_name_hint = true; + } else { + pi->user_name_hint = false; + } + + ret = parse_cert_info(pi, buf, len, &p, &cert_user, + &pam_cert_user); + if (ret != 0) { + D(("Failed to parse cert info")); + break; + } + + if ((pi->pam_user == NULL || *(pi->pam_user) == '\0') + && *cert_user != '\0' && *pam_cert_user != '\0') { + ret = pam_set_item(pamh, PAM_USER, pam_cert_user); + if (ret != PAM_SUCCESS) { + D(("Failed to set PAM_USER during " + "Smartcard authentication [%s]", + pam_strerror(pamh, ret))); + break; + } + + pi->pam_user = cert_user; + pi->pam_user_size = strlen(pi->pam_user) + 1; + } + break; + case SSS_PASSWORD_PROMPTING: + D(("Password prompting available.")); + pi->password_prompting = true; + break; + case SSS_PAM_PROMPT_CONFIG: + if (pi->pc == NULL) { + ret = pc_list_from_response(len, &buf[p], &pi->pc); + if (ret != EOK) { + D(("Failed to parse prompting data, using defaults")); + pc_list_free(pi->pc); + pi->pc = NULL; + } + } + break; + case SSS_CHILD_KEEP_ALIVE: + memcpy(&pi->child_pid, &buf[p], len); + break; + case SSS_PAM_OAUTH2_INFO: + if (buf[p + (len - 1)] != '\0') { + D(("oauth2 info does not end with \\0.")); + break; + } + + free(pi->oauth2_url); + pi->oauth2_url = strdup((char *) &buf[p]); + if (pi->oauth2_url == NULL) { + D(("strdup failed")); + break; + } + + offset = strlen(pi->oauth2_url) + 1; + if (offset >= len) { + D(("OAuth2 message size mismatch")); + free(pi->oauth2_url); + pi->oauth2_url = NULL; + break; + } + + free(pi->oauth2_url_complete); + pi->oauth2_url_complete = strdup((char *) &buf[p + offset]); + if (pi->oauth2_url_complete == NULL) { + D(("strdup failed")); + break; + } + + offset = offset + strlen(pi->oauth2_url_complete) + 1; + if (offset >= len) { + D(("OAuth2 message size mismatch")); + free(pi->oauth2_url_complete); + pi->oauth2_url_complete = NULL; + break; + } + + /* This field is optional. */ + if (pi->oauth2_url_complete[0] == '\0') { + free(pi->oauth2_url_complete); + pi->oauth2_url_complete = NULL; + } + + free(pi->oauth2_pin); + pi->oauth2_pin = strdup((char *) &buf[p + offset]); + if (pi->oauth2_pin == NULL) { + D(("strdup failed")); + break; + } + + break; + case SSS_PAM_PASSKEY_KRB_INFO: + free(pi->passkey_prompt_pin); + pi->passkey_prompt_pin = strdup((char *) &buf[p]); + if (pi->passkey_prompt_pin == NULL) { + D(("strdup failed")); + break; + } + + offset = strlen(pi->passkey_prompt_pin) + 1; + if (offset >= len) { + D(("Passkey message size mismatch")); + free(pi->passkey_prompt_pin); + pi->passkey_prompt_pin = NULL; + break; + } + + free(pi->passkey_key); + pi->passkey_key = strdup((char *) &buf[p + offset]); + if (pi->passkey_key == NULL) { + D(("strdup failed")); + break; + } + break; + case SSS_PAM_PASSKEY_INFO: + if (buf[p + (len - 1)] != '\0') { + D(("passkey info does not end with \\0.")); + break; + } + + free(pi->passkey_prompt_pin); + pi->passkey_prompt_pin = strdup((char *) &buf[p]); + if (pi->passkey_prompt_pin == NULL) { + D(("strdup failed")); + break; + } + break; + default: + D(("Unknown response type [%d]", type)); + } + p += len; + + --c; + } + + return PAM_SUCCESS; +} + +bool is_string_empty_or_whitespace(const char *str) +{ + int i; + + if (str == NULL) { + return true; + } + + for (i = 0; str[i] != '\0'; i++) { + if (!isspace(str[i])) { + return false; + } + } + + return true; +} + +static int get_pam_items(pam_handle_t *pamh, uint32_t flags, + struct pam_items *pi) +{ + int ret; + + pi->pam_authtok_type = SSS_AUTHTOK_TYPE_EMPTY; + pi->pam_authtok = NULL; + pi->pam_authtok_size = 0; + pi->pam_newauthtok_type = SSS_AUTHTOK_TYPE_EMPTY; + pi->pam_newauthtok = NULL; + pi->pam_newauthtok_size = 0; + pi->first_factor = NULL; + + ret = pam_get_item(pamh, PAM_SERVICE, (const void **) &(pi->pam_service)); + if (ret != PAM_SUCCESS) return ret; + if (pi->pam_service == NULL) pi->pam_service=""; + pi->pam_service_size=strlen(pi->pam_service)+1; + + ret = pam_get_item(pamh, PAM_USER, (const void **) &(pi->pam_user)); + if (ret == PAM_PERM_DENIED && (flags & PAM_CLI_FLAGS_ALLOW_MISSING_NAME)) { + pi->pam_user = ""; + ret = PAM_SUCCESS; + } + if (ret != PAM_SUCCESS) return ret; + if (flags & PAM_CLI_FLAGS_ALLOW_MISSING_NAME) { + if (is_string_empty_or_whitespace(pi->pam_user)) { + pi->pam_user = ""; + } + } + if (pi->pam_user == NULL) { + D(("No user found, aborting.")); + return PAM_BAD_ITEM; + } + if (strcmp(pi->pam_user, "root") == 0) { + D(("pam_sss will not handle root.")); + return PAM_USER_UNKNOWN; + } + pi->pam_user_size=strlen(pi->pam_user)+1; + + + ret = pam_get_item(pamh, PAM_TTY, (const void **) &(pi->pam_tty)); + if (ret != PAM_SUCCESS) return ret; + if (pi->pam_tty == NULL) pi->pam_tty=""; + pi->pam_tty_size=strlen(pi->pam_tty)+1; + + ret = pam_get_item(pamh, PAM_RUSER, (const void **) &(pi->pam_ruser)); + if (ret != PAM_SUCCESS) return ret; + if (pi->pam_ruser == NULL) pi->pam_ruser=""; + pi->pam_ruser_size=strlen(pi->pam_ruser)+1; + + ret = pam_get_item(pamh, PAM_RHOST, (const void **) &(pi->pam_rhost)); + if (ret != PAM_SUCCESS) return ret; + if (pi->pam_rhost == NULL) pi->pam_rhost=""; + pi->pam_rhost_size=strlen(pi->pam_rhost)+1; + + ret = pam_get_item(pamh, PAM_AUTHTOK, + (const void **) &(pi->pamstack_authtok)); + if (ret != PAM_SUCCESS) return ret; + if (pi->pamstack_authtok == NULL) pi->pamstack_authtok=""; + + ret = pam_get_item(pamh, PAM_OLDAUTHTOK, + (const void **) &(pi->pamstack_oldauthtok)); + if (ret != PAM_SUCCESS) return ret; + if (pi->pamstack_oldauthtok == NULL) pi->pamstack_oldauthtok=""; + + pi->cli_pid = getpid(); + + pi->login_name = pam_modutil_getlogin(pamh); + if (pi->login_name == NULL) pi->login_name=""; + + pi->domain_name = NULL; + + if (pi->requested_domains == NULL) pi->requested_domains = ""; + pi->requested_domains_size = strlen(pi->requested_domains) + 1; + + pi->otp_vendor = NULL; + pi->otp_token_id = NULL; + pi->otp_challenge = NULL; + pi->password_prompting = false; + + pi->cert_list = NULL; + pi->selected_cert = NULL; + + pi->pc = NULL; + + pi->flags = flags; + + return PAM_SUCCESS; +} + +static void print_pam_items(struct pam_items *pi) +{ + if (pi == NULL) return; + + D(("Service: %s", CHECK_AND_RETURN_PI_STRING(pi->pam_service))); + D(("User: %s", CHECK_AND_RETURN_PI_STRING(pi->pam_user))); + D(("Tty: %s", CHECK_AND_RETURN_PI_STRING(pi->pam_tty))); + D(("Ruser: %s", CHECK_AND_RETURN_PI_STRING(pi->pam_ruser))); + D(("Rhost: %s", CHECK_AND_RETURN_PI_STRING(pi->pam_rhost))); + D(("Pamstack_Authtok: %s", + CHECK_AND_RETURN_PI_STRING(pi->pamstack_authtok))); + D(("Pamstack_Oldauthtok: %s", + CHECK_AND_RETURN_PI_STRING(pi->pamstack_oldauthtok))); + D(("Authtok: %s", CHECK_AND_RETURN_PI_STRING(pi->pam_authtok))); + D(("Newauthtok: %s", CHECK_AND_RETURN_PI_STRING(pi->pam_newauthtok))); + D(("Cli_PID: %d", pi->cli_pid)); + D(("Child_PID: %d", pi->child_pid)); + D(("Requested domains: %s", pi->requested_domains)); + D(("Flags: %d", pi->flags)); +} + +static int send_and_receive(pam_handle_t *pamh, struct pam_items *pi, + enum sss_cli_command task, bool quiet_mode) +{ + int ret; + int sret; + int errnop; + struct sss_cli_req_data rd; + uint8_t *buf = NULL; + uint8_t *repbuf = NULL; + size_t replen; + int pam_status = PAM_SYSTEM_ERR; + + print_pam_items(pi); + + ret = pack_message_v3(pi, &rd.len, &buf); + if (ret != 0) { + D(("pack_message failed.")); + pam_status = PAM_SYSTEM_ERR; + goto done; + } + rd.data = buf; + + errnop = 0; + ret = sss_pam_make_request(task, &rd, &repbuf, &replen, &errnop); + + sret = pam_set_data(pamh, FD_DESTRUCTOR, NULL, close_fd); + if (sret != PAM_SUCCESS) { + D(("pam_set_data failed, client might leaks fds")); + } + + if (ret != PAM_SUCCESS) { + /* If there is no PAM responder socket during the access control step + * we assume this is on purpose, i.e. PAM responder is not configured. + * PAM_USER_UNKNOWN is returned to the PAM stack to avoid unexpected + * denials. */ + if (errnop == ESSS_NO_SOCKET && task == SSS_PAM_ACCT_MGMT) { + pam_status = PAM_USER_UNKNOWN; + } else { + if (errnop != 0 && errnop != ESSS_NO_SOCKET) { + logger(pamh, LOG_ERR, "Request to sssd failed. %s", + ssscli_err2string(errnop)); + } + + pam_status = PAM_AUTHINFO_UNAVAIL; + } + goto done; + } + +/* FIXME: add an end signature */ + if (replen < (2*sizeof(int32_t))) { + D(("response not in expected format.")); + pam_status = PAM_SYSTEM_ERR; + goto done; + } + + SAFEALIGN_COPY_UINT32(&pam_status, repbuf, NULL); + ret = eval_response(pamh, replen, repbuf, pi); + if (ret != PAM_SUCCESS) { + D(("eval_response failed.")); + pam_status = ret; + goto done; + } + + switch (task) { + case SSS_PAM_AUTHENTICATE: + logger(pamh, (pam_status == PAM_SUCCESS ? LOG_INFO : LOG_NOTICE), + "authentication %s; logname=%s uid=%lu euid=%d tty=%s " + "ruser=%s rhost=%s user=%s", + pam_status == PAM_SUCCESS ? "success" : "failure", + pi->login_name, getuid(), (unsigned long) geteuid(), + pi->pam_tty, pi->pam_ruser, pi->pam_rhost, pi->pam_user); + if (pam_status != PAM_SUCCESS) { + /* don't log if quiet_mode is on and pam_status is + * User not known to the underlying authentication module + */ + if (!quiet_mode || pam_status != 10) { + logger(pamh, LOG_NOTICE, "received for user %s: %d (%s)", + pi->pam_user, pam_status, + pam_strerror(pamh,pam_status)); + } + } + break; + case SSS_PAM_CHAUTHTOK_PRELIM: + if (pam_status != PAM_SUCCESS) { + /* don't log if quiet_mode is on and pam_status is + * User not known to the underlying authentication module + */ + if (!quiet_mode || pam_status != 10) { + logger(pamh, LOG_NOTICE, + "Authentication failed for user %s: %d (%s)", + pi->pam_user, pam_status, + pam_strerror(pamh,pam_status)); + } + } + break; + case SSS_PAM_CHAUTHTOK: + if (pam_status != PAM_SUCCESS) { + logger(pamh, LOG_NOTICE, + "Password change failed for user %s: %d (%s)", + pi->pam_user, pam_status, + pam_strerror(pamh,pam_status)); + } + break; + case SSS_PAM_ACCT_MGMT: + if (pam_status != PAM_SUCCESS) { + /* don't log if quiet_mode is on and pam_status is + * User not known to the underlying authentication module + */ + if (!quiet_mode || pam_status != 10) { + logger(pamh, LOG_NOTICE, + "Access denied for user %s: %d (%s)", + pi->pam_user, pam_status, + pam_strerror(pamh,pam_status)); + } + } + break; + case SSS_PAM_OPEN_SESSION: + case SSS_PAM_SETCRED: + case SSS_PAM_CLOSE_SESSION: + case SSS_PAM_PREAUTH: + break; + default: + D(("Illegal task [%#x]", task)); + return PAM_SYSTEM_ERR; + } + +done: + if (buf != NULL ) { + _pam_overwrite_n((void *)buf, rd.len); + free(buf); + } + free(repbuf); + + return pam_status; +} + +static int prompt_password(pam_handle_t *pamh, struct pam_items *pi, + const char *prompt) +{ + int ret; + char *answer = NULL; + + ret = do_pam_conversation(pamh, PAM_PROMPT_ECHO_OFF, prompt, NULL, &answer); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + return ret; + } + + if (answer == NULL) { + pi->pam_authtok = NULL; + pi->pam_authtok_type = SSS_AUTHTOK_TYPE_EMPTY; + pi->pam_authtok_size=0; + } else { + pi->pam_authtok = strdup(answer); + _pam_overwrite((void *)answer); + free(answer); + answer=NULL; + if (pi->pam_authtok == NULL) { + return PAM_BUF_ERR; + } + pi->pam_authtok_type = SSS_AUTHTOK_TYPE_PASSWORD; + pi->pam_authtok_size=strlen(pi->pam_authtok); + } + + return PAM_SUCCESS; +} + +static int prompt_2fa(pam_handle_t *pamh, struct pam_items *pi, + const char *prompt_fa1, const char *prompt_fa2) +{ + int ret; + const struct pam_conv *conv; + const struct pam_message *mesg[2] = { NULL, NULL }; + struct pam_message m[2] = { {0}, {0} }; + struct pam_response *resp = NULL; + size_t needed_size; + + ret = pam_get_item(pamh, PAM_CONV, (const void **) &conv); + if (ret != PAM_SUCCESS) { + return ret; + } + if (conv == NULL || conv->conv == NULL) { + logger(pamh, LOG_ERR, "No conversation function"); + return PAM_SYSTEM_ERR; + } + + m[0].msg_style = PAM_PROMPT_ECHO_OFF; + m[0].msg = prompt_fa1; + m[1].msg_style = PAM_PROMPT_ECHO_OFF; + m[1].msg = prompt_fa2; + + mesg[0] = (const struct pam_message *) m; + /* The following assignment might look a bit odd but is recommended in the + * pam_conv man page to make sure that the second argument of the PAM + * conversation function can be interpreted in two different ways. + * Basically it is important that both the actual struct pam_message and + * the pointers to the struct pam_message are arrays. Since the assignment + * makes clear that mesg[] and (*mesg)[] are arrays it should be kept this + * way and not be replaced by other equivalent assignments. */ + mesg[1] = & (( *mesg )[1]); + + ret = conv->conv(2, mesg, &resp, conv->appdata_ptr); + if (ret != PAM_SUCCESS) { + D(("Conversation failure: %s.", pam_strerror(pamh, ret))); + return ret; + } + + if (resp == NULL) { + D(("response expected, but resp==NULL")); + return PAM_SYSTEM_ERR; + } + + if (resp[0].resp == NULL || *(resp[0].resp) == '\0') { + D(("Missing factor.")); + ret = PAM_CRED_INSUFFICIENT; + goto done; + } + + if (resp[1].resp == NULL || *(resp[1].resp) == '\0' + || (pi->pam_service != NULL && strcmp(pi->pam_service, "sshd") == 0 + && strcmp(resp[0].resp, resp[1].resp) == 0)) { + /* Missing second factor, assume first factor contains combined 2FA + * credentials. + * Special handling for SSH with password authentication. Combined + * 2FA credentials are used but SSH puts them in both responses. */ + + pi->pam_authtok = strndup(resp[0].resp, MAX_AUTHTOK_SIZE); + if (pi->pam_authtok == NULL) { + D(("strndup failed.")); + ret = PAM_BUF_ERR; + goto done; + } + pi->pam_authtok_size = strlen(pi->pam_authtok) + 1; + pi->pam_authtok_type = SSS_AUTHTOK_TYPE_PASSWORD; + } else { + + ret = sss_auth_pack_2fa_blob(resp[0].resp, 0, resp[1].resp, 0, NULL, 0, + &needed_size); + if (ret != EAGAIN) { + D(("sss_auth_pack_2fa_blob failed.")); + ret = PAM_BUF_ERR; + goto done; + } + + pi->pam_authtok = malloc(needed_size); + if (pi->pam_authtok == NULL) { + D(("malloc failed.")); + ret = PAM_BUF_ERR; + goto done; + } + + ret = sss_auth_pack_2fa_blob(resp[0].resp, 0, resp[1].resp, 0, + (uint8_t *) pi->pam_authtok, needed_size, + &needed_size); + if (ret != EOK) { + D(("sss_auth_pack_2fa_blob failed.")); + ret = PAM_BUF_ERR; + goto done; + } + + pi->pam_authtok_size = needed_size; + pi->pam_authtok_type = SSS_AUTHTOK_TYPE_2FA; + pi->first_factor = strndup(resp[0].resp, MAX_AUTHTOK_SIZE); + if (pi->first_factor == NULL) { + D(("strndup failed.")); + ret = PAM_BUF_ERR; + goto done; + } + } + + ret = PAM_SUCCESS; + +done: + if (resp != NULL) { + if (resp[0].resp != NULL) { + _pam_overwrite((void *)resp[0].resp); + free(resp[0].resp); + } + if (resp[1].resp != NULL) { + _pam_overwrite((void *)resp[1].resp); + free(resp[1].resp); + } + + free(resp); + resp = NULL; + } + + return ret; +} + +static int prompt_2fa_single(pam_handle_t *pamh, struct pam_items *pi, + const char *prompt) +{ + int ret; + char *answer = NULL; + + ret = do_pam_conversation(pamh, PAM_PROMPT_ECHO_OFF, prompt, NULL, &answer); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + return ret; + } + + if (answer == NULL) { + pi->pam_authtok = NULL; + pi->pam_authtok_type = SSS_AUTHTOK_TYPE_EMPTY; + pi->pam_authtok_size=0; + } else { + pi->pam_authtok = strdup(answer); + _pam_overwrite((void *)answer); + free(answer); + answer=NULL; + if (pi->pam_authtok == NULL) { + return PAM_BUF_ERR; + } + pi->pam_authtok_type = SSS_AUTHTOK_TYPE_2FA_SINGLE; + pi->pam_authtok_size=strlen(pi->pam_authtok); + } + + return PAM_SUCCESS; +} + +static int prompt_oauth2(pam_handle_t *pamh, struct pam_items *pi) +{ + char *answer = NULL; + char *msg; + int ret; + + if (pi->oauth2_url_complete != NULL) { + ret = asprintf(&msg, _("Authenticate at %1$s and press ENTER."), + pi->oauth2_url_complete); + } else { + ret = asprintf(&msg, _("Authenticate with PIN %1$s at %2$s and press " + "ENTER."), pi->oauth2_pin, pi->oauth2_url); + } + if (ret == -1) { + return PAM_SYSTEM_ERR; + } + + ret = do_pam_conversation(pamh, PAM_PROMPT_ECHO_OFF, msg, NULL, &answer); + free(msg); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + return ret; + } + + /* We don't care about answer here. We just need to notify that the + * authentication has finished. */ + free(answer); + + pi->pam_authtok = strdup(pi->oauth2_pin); + pi->pam_authtok_type = SSS_AUTHTOK_TYPE_OAUTH2; + pi->pam_authtok_size=strlen(pi->oauth2_pin); + + return PAM_SUCCESS; +} + +static int prompt_passkey(pam_handle_t *pamh, struct pam_items *pi, + const char *prompt_interactive, const char *prompt_touch) +{ + int ret; + const struct pam_conv *conv; + const struct pam_message *mesg[4] = { NULL, NULL, NULL, NULL }; + struct pam_message m[4] = { {0}, {0}, {0}, {0} }; + struct pam_response *resp = NULL; + bool kerberos_preauth; + bool prompt_pin; + int pin_idx = 0; + int msg_idx = 0; + size_t needed_size; + + ret = pam_get_item(pamh, PAM_CONV, (const void **) &conv); + if (ret != PAM_SUCCESS) { + return ret; + } + if (conv == NULL || conv->conv == NULL) { + logger(pamh, LOG_ERR, "No conversation function"); + return PAM_SYSTEM_ERR; + } + + kerberos_preauth = pi->passkey_key != NULL ? true : false; + if (!kerberos_preauth) { + m[msg_idx].msg_style = PAM_TEXT_INFO; + m[msg_idx].msg = PASSKEY_LOCAL_AUTH_MSG; + msg_idx++; + } + + if ((strcasecmp(pi->passkey_prompt_pin, "false")) == 0) { + prompt_pin = false; + } else { + prompt_pin = true; + } + + /* Interactive, prompt a message and wait before continuing */ + if (prompt_interactive != NULL && prompt_interactive[0] != '\0') { + m[msg_idx].msg_style = PAM_PROMPT_ECHO_OFF; + m[msg_idx].msg = prompt_interactive; + msg_idx++; + } + + /* Prompt for PIN + * + * If prompt_pin is false but a PIN is set on the device + * we still prompt for PIN */ + if (prompt_pin) { + m[msg_idx].msg_style = PAM_PROMPT_ECHO_OFF; + m[msg_idx].msg = PASSKEY_DEFAULT_PIN_MSG; + pin_idx = msg_idx; + msg_idx++; + } + + /* Prompt to remind the user to touch the device */ + if (prompt_touch != NULL && prompt_touch[0] != '\0') { + m[msg_idx].msg_style = PAM_PROMPT_ECHO_OFF; + m[msg_idx].msg = prompt_touch; + msg_idx++; + } + + mesg[0] = (const struct pam_message *) m; + /* The following assignment might look a bit odd but is recommended in the + * pam_conv man page to make sure that the second argument of the PAM + * conversation function can be interpreted in two different ways. + * Basically it is important that both the actual struct pam_message and + * the pointers to the struct pam_message are arrays. Since the assignment + * makes clear that mesg[] and (*mesg)[] are arrays it should be kept this + * way and not be replaced by other equivalent assignments. */ + for (int i = 1; i < msg_idx; i++) { + mesg[i] = & (( *mesg )[i]); + } + + ret = conv->conv(msg_idx, mesg, &resp, conv->appdata_ptr); + if (ret != PAM_SUCCESS) { + D(("Conversation failure: %s.", pam_strerror(pamh, ret))); + return ret; + } + + if (kerberos_preauth) { + if (!prompt_pin) { + resp[pin_idx].resp = NULL; + } + + pi->pam_authtok_type = SSS_AUTHTOK_TYPE_PASSKEY_KRB; + sss_auth_passkey_calc_size(pi->passkey_prompt_pin, + pi->passkey_key, + resp[pin_idx].resp, + &needed_size); + + pi->pam_authtok = malloc(needed_size); + if (pi->pam_authtok == NULL) { + D(("malloc failed.")); + ret = PAM_BUF_ERR; + goto done; + } + + sss_auth_pack_passkey_blob((uint8_t *)pi->pam_authtok, + pi->passkey_prompt_pin, pi->passkey_key, + resp[pin_idx].resp); + + } else { + if (!prompt_pin) { + /* user verification = false, SSS_AUTHTOK_TYPE_PASSKEY will be reset to + * SSS_AUTHTOK_TYPE_NULL in PAM responder + */ + pi->pam_authtok_type = SSS_AUTHTOK_TYPE_PASSKEY; + pi->pam_authtok = NULL; + pi->pam_authtok_size = 0; + ret = PAM_SUCCESS; + goto done; + } else { + pi->pam_authtok_type = SSS_AUTHTOK_TYPE_PASSKEY; + pi->pam_authtok = strdup(resp[pin_idx].resp); + needed_size = strlen(pi->pam_authtok); + } + } + + pi->pam_authtok_size = needed_size; + + /* Fallback to password auth if no PIN was entered */ + if (prompt_pin) { + if (resp[pin_idx].resp == NULL || resp[pin_idx].resp[0] == '\0') { + ret = EIO; + goto done; + } + } + + ret = PAM_SUCCESS; + +done: + if (resp != NULL) { + if (resp[pin_idx].resp != NULL) { + _pam_overwrite((void *)resp[pin_idx].resp); + free(resp[pin_idx].resp); + } + + free(resp); + resp = NULL; + } + + return ret; +} + +#define SC_PROMPT_FMT "PIN for %s: " + +#ifndef discard_const +#define discard_const(ptr) ((void *)((uintptr_t)(ptr))) +#endif + +#define CERT_SEL_PROMPT_FMT "%s" +#define SEL_TITLE discard_const("Please select a certificate") + +static int prompt_multi_cert_gdm(pam_handle_t *pamh, struct pam_items *pi) +{ +#ifdef HAVE_GDM_PAM_EXTENSIONS + int ret; + size_t cert_count = 0; + size_t c; + const struct pam_conv *conv; + struct cert_auth_info *cai; + GdmPamExtensionChoiceListRequest *request = NULL; + GdmPamExtensionChoiceListResponse *response = NULL; + struct pam_message prompt_message; + const struct pam_message *prompt_messages[1]; + struct pam_response *reply = NULL; + char *prompt; + + if (!GDM_PAM_EXTENSION_SUPPORTED(GDM_PAM_EXTENSION_CHOICE_LIST)) { + return ENOTSUP; + } + + if (pi->cert_list == NULL) { + return EINVAL; + } + + DLIST_FOR_EACH(cai, pi->cert_list) { + cert_count++; + } + + ret = pam_get_item(pamh, PAM_CONV, (const void **)&conv); + if (ret != PAM_SUCCESS) { + ret = EIO; + return ret; + } + + request = calloc(1, GDM_PAM_EXTENSION_CHOICE_LIST_REQUEST_SIZE(cert_count)); + if (request == NULL) { + ret = ENOMEM; + goto done; + } + GDM_PAM_EXTENSION_CHOICE_LIST_REQUEST_INIT(request, SEL_TITLE, cert_count); + + c = 0; + DLIST_FOR_EACH(cai, pi->cert_list) { + ret = asprintf(&prompt, CERT_SEL_PROMPT_FMT, cai->prompt_str); + if (ret == -1) { + ret = ENOMEM; + goto done; + } + free(cai->choice_list_id); + ret = asprintf(&cai->choice_list_id, "%zu", c); + if (ret == -1) { + cai->choice_list_id = NULL; + free(prompt); + ret = ENOMEM; + goto done; + } + + request->list.items[c].key = cai->choice_list_id; + request->list.items[c++].text = prompt; + } + + GDM_PAM_EXTENSION_MESSAGE_TO_BINARY_PROMPT_MESSAGE(request, + &prompt_message); + prompt_messages[0] = &prompt_message; + + ret = conv->conv(1, prompt_messages, &reply, conv->appdata_ptr); + if (ret != PAM_SUCCESS) { + ret = EIO; + goto done; + } + + ret = EIO; + response = GDM_PAM_EXTENSION_REPLY_TO_CHOICE_LIST_RESPONSE(reply); + if (response->key == NULL) { + goto done; + } + + DLIST_FOR_EACH(cai, pi->cert_list) { + if (strcmp(response->key, cai->choice_list_id) == 0) { + pam_info(pamh, "Certificate ‘%s’ selected", cai->key_id); + pi->selected_cert = cai; + ret = 0; + break; + } + } + +done: + if (request != NULL) { + for (c = 0; c < cert_count; c++) { + free(discard_const(request->list.items[c++].text)); + } + free(request); + } + free(response); + + return ret; +#else + return ENOTSUP; +#endif +} + +#define TEXT_CERT_SEL_PROMPT_FMT "%s\n[%zu]:\n%s\n" +#define TEXT_SEL_TITLE discard_const("Please select a certificate by typing " \ + "the corresponding number\n") + +static int prompt_multi_cert(pam_handle_t *pamh, struct pam_items *pi) +{ + int ret; + size_t cert_count = 0; + size_t tries = 0; + long int resp = -1; + struct cert_auth_info *cai; + char *prompt; + char *tmp; + char *answer; + char *ep; + + /* First check if gdm extension is supported */ + ret = prompt_multi_cert_gdm(pamh, pi); + if (ret != ENOTSUP) { + return ret; + } + + if (pi->cert_list == NULL) { + return EINVAL; + } + + prompt = strdup(TEXT_SEL_TITLE); + if (prompt == NULL) { + return ENOMEM; + } + + DLIST_FOR_EACH(cai, pi->cert_list) { + cert_count++; + ret = asprintf(&tmp, TEXT_CERT_SEL_PROMPT_FMT, prompt, cert_count, + cai->prompt_str); + free(prompt); + if (ret == -1) { + return ENOMEM; + } + + prompt = tmp; + } + + do { + ret = do_pam_conversation(pamh, PAM_PROMPT_ECHO_ON, prompt, NULL, + &answer); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + break; + } + + errno = 0; + resp = strtol(answer, &ep, 10); + if (errno == 0 && *ep == '\0' && resp > 0 && resp <= cert_count) { + /* do not free answer ealier because ep is pointing to it */ + free(answer); + break; + } + free(answer); + resp = -1; + } while (++tries < 5); + free(prompt); + + pi->selected_cert = NULL; + ret = ENOENT; + if (resp > 0 && resp <= cert_count) { + cert_count = 0; + DLIST_FOR_EACH(cai, pi->cert_list) { + cert_count++; + if (resp == cert_count) { + pam_info(pamh, "Certificate ‘%s’ selected", cai->key_id); + pi->selected_cert = cai; + ret = 0; + break; + } + } + } + + return ret; +} + +#define SC_INSERT_PROMPT _("Please (re)insert (different) Smartcard") + +static int prompt_sc_pin(pam_handle_t *pamh, struct pam_items *pi) +{ + int ret; + char *answer = NULL; + char *prompt = NULL; + size_t needed_size; + const struct pam_conv *conv; + const struct pam_message *mesg[2] = { NULL, NULL }; + struct pam_message m[2] = { { 0 }, { 0 } }; + struct pam_response *resp = NULL; + struct cert_auth_info *cai = pi->selected_cert; + + if (cai == NULL && (SERVICE_IS_GDM_SMARTCARD(pi) + || (pi->flags & PAM_CLI_FLAGS_REQUIRE_CERT_AUTH))) { + ret = asprintf(&prompt, SC_INSERT_PROMPT); + } else if (cai == NULL || cai->token_name == NULL + || *cai->token_name == '\0') { + return PAM_SYSTEM_ERR; + } else { + ret = asprintf(&prompt, SC_PROMPT_FMT, cai->token_name); + } + + if (ret == -1) { + D(("asprintf failed.")); + return PAM_SYSTEM_ERR; + } + + if (cai == NULL) { + ret = do_pam_conversation(pamh, PAM_TEXT_INFO, prompt, NULL, NULL); + if (ret != PAM_SUCCESS) { + D(("Conversation failure: %s, ignored", pam_strerror(pamh, ret))); + } + } + + if (pi->user_name_hint) { + ret = pam_get_item(pamh, PAM_CONV, (const void **)&conv); + if (ret != PAM_SUCCESS) { + free(prompt); + return ret; + } + if (conv == NULL || conv->conv == NULL) { + logger(pamh, LOG_ERR, "No conversation function"); + free(prompt); + return PAM_SYSTEM_ERR; + } + + m[0].msg_style = PAM_PROMPT_ECHO_OFF; + m[0].msg = prompt; + m[1].msg_style = PAM_PROMPT_ECHO_ON; + m[1].msg = "User name hint: "; + + mesg[0] = (const struct pam_message *)m; + /* The following assignment might look a bit odd but is recommended in the + * pam_conv man page to make sure that the second argument of the PAM + * conversation function can be interpreted in two different ways. + * Basically it is important that both the actual struct pam_message and + * the pointers to the struct pam_message are arrays. Since the assignment + * makes clear that mesg[] and (*mesg)[] are arrays it should be kept this + * way and not be replaced by other equivalent assignments. */ + mesg[1] = &((*mesg)[1]); + + ret = conv->conv(2, mesg, &resp, conv->appdata_ptr); + free(prompt); + if (ret != PAM_SUCCESS) { + D(("Conversation failure: %s.", pam_strerror(pamh, ret))); + return ret; + } + + if (resp == NULL) { + D(("response expected, but resp==NULL")); + return PAM_SYSTEM_ERR; + } + + if (resp[0].resp == NULL || *(resp[0].resp) == '\0') { + D(("Missing PIN.")); + ret = PAM_CRED_INSUFFICIENT; + goto done; + } + + answer = strndup(resp[0].resp, MAX_AUTHTOK_SIZE); + _pam_overwrite((void *)resp[0].resp); + free(resp[0].resp); + resp[0].resp = NULL; + if (answer == NULL) { + D(("strndup failed")); + ret = PAM_BUF_ERR; + goto done; + } + + if (resp[1].resp != NULL && *(resp[1].resp) != '\0') { + ret = pam_set_item(pamh, PAM_USER, resp[1].resp); + free(resp[1].resp); + resp[1].resp = NULL; + if (ret != PAM_SUCCESS) { + D(("Failed to set PAM_USER with user name hint [%s]", + pam_strerror(pamh, ret))); + goto done; + } + + ret = pam_get_item(pamh, PAM_USER, (const void **)&(pi->pam_user)); + if (ret != PAM_SUCCESS) { + D(("Failed to get PAM_USER with user name hint [%s]", + pam_strerror(pamh, ret))); + goto done; + } + + pi->pam_user_size = strlen(pi->pam_user) + 1; + } + } else { + ret = do_pam_conversation(pamh, PAM_PROMPT_ECHO_OFF, prompt, NULL, + &answer); + free(prompt); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + return ret; + } + } + + if (cai == NULL) { + /* it is expected that the user just replaces the Smartcard which + * would trigger gdm to restart the PAM module, so it is not + * expected that this part of the code is reached. */ + ret = PAM_AUTHINFO_UNAVAIL; + goto done; + } + + if (answer == NULL || *answer == '\0') { + D(("Missing PIN.")); + ret = PAM_CRED_INSUFFICIENT; + goto done; + } else { + + ret = sss_auth_pack_sc_blob(answer, 0, cai->token_name, 0, + cai->module_name, 0, + cai->key_id, 0, + cai->label, 0, + NULL, 0, &needed_size); + if (ret != EAGAIN) { + D(("sss_auth_pack_sc_blob failed.")); + ret = PAM_BUF_ERR; + goto done; + } + + pi->pam_authtok = malloc(needed_size); + if (pi->pam_authtok == NULL) { + D(("malloc failed.")); + ret = PAM_BUF_ERR; + goto done; + } + + ret = sss_auth_pack_sc_blob(answer, 0, cai->token_name, 0, + cai->module_name, 0, + cai->key_id, 0, + cai->label, 0, + (uint8_t *) pi->pam_authtok, needed_size, + &needed_size); + if (ret != EOK) { + D(("sss_auth_pack_sc_blob failed.")); + free((void *)pi->pam_authtok); + ret = PAM_BUF_ERR; + goto done; + } + + pi->pam_authtok_type = SSS_AUTHTOK_TYPE_SC_PIN; + pi->pam_authtok_size = needed_size; + } + + ret = PAM_SUCCESS; + +done: + _pam_overwrite((void *)answer); + free(answer); + answer=NULL; + + if (resp != NULL) { + if (resp[0].resp != NULL) { + _pam_overwrite((void *)resp[0].resp); + free(resp[0].resp); + } + if (resp[1].resp != NULL) { + _pam_overwrite((void *)resp[1].resp); + free(resp[1].resp); + } + + free(resp); + resp = NULL; + } + + return ret; +} + +static int prompt_new_password(pam_handle_t *pamh, struct pam_items *pi) +{ + int ret; + char *answer = NULL; + + ret = do_pam_conversation(pamh, PAM_PROMPT_ECHO_OFF, + _("New Password: "), + _("Reenter new Password: "), + &answer); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + return ret; + } + if (answer == NULL) { + pi->pam_newauthtok = NULL; + pi->pam_newauthtok_type = SSS_AUTHTOK_TYPE_EMPTY; + pi->pam_newauthtok_size=0; + } else { + pi->pam_newauthtok = strdup(answer); + _pam_overwrite((void *)answer); + free(answer); + answer=NULL; + if (pi->pam_newauthtok == NULL) { + return PAM_BUF_ERR; + } + pi->pam_newauthtok_type = SSS_AUTHTOK_TYPE_PASSWORD; + pi->pam_newauthtok_size=strlen(pi->pam_newauthtok); + } + + return PAM_SUCCESS; +} + +static void eval_argv(pam_handle_t *pamh, int argc, const char **argv, + uint32_t *flags, int *retries, bool *quiet_mode, + const char **domains) +{ + char *ep; + + *quiet_mode = false; + + for (; argc-- > 0; ++argv) { + if (strcmp(*argv, "forward_pass") == 0) { + *flags |= PAM_CLI_FLAGS_FORWARD_PASS; + } else if (strcmp(*argv, "use_first_pass") == 0) { + *flags |= PAM_CLI_FLAGS_USE_FIRST_PASS; + } else if (strcmp(*argv, "use_authtok") == 0) { + *flags |= PAM_CLI_FLAGS_USE_AUTHTOK; + } else if (strncmp(*argv, OPT_DOMAINS_KEY, strlen(OPT_DOMAINS_KEY)) == 0) { + if (*(*argv+strlen(OPT_DOMAINS_KEY)) == '\0') { + logger(pamh, LOG_ERR, "Missing argument to option domains."); + *domains = ""; + } else { + *domains = *argv+strlen(OPT_DOMAINS_KEY); + } + + } else if (strncmp(*argv, OPT_RETRY_KEY, strlen(OPT_RETRY_KEY)) == 0) { + if (*(*argv+6) == '\0') { + logger(pamh, LOG_ERR, "Missing argument to option retry."); + *retries = 0; + } else { + errno = 0; + *retries = strtol(*argv+6, &ep, 10); + if (errno != 0) { + D(("strtol failed [%d][%s]", errno, strerror(errno))); + *retries = 0; + } + if (*ep != '\0') { + logger(pamh, LOG_ERR, "Argument to option retry contains " + "extra characters."); + *retries = 0; + } + if (*retries < 0) { + logger(pamh, LOG_ERR, "Argument to option retry must not " + "be negative."); + *retries = 0; + } + } + } else if (strcmp(*argv, "quiet") == 0) { + *quiet_mode = true; + } else if (strcmp(*argv, "ignore_unknown_user") == 0) { + *flags |= PAM_CLI_FLAGS_IGNORE_UNKNOWN_USER; + } else if (strcmp(*argv, "ignore_authinfo_unavail") == 0) { + *flags |= PAM_CLI_FLAGS_IGNORE_AUTHINFO_UNAVAIL; + } else if (strcmp(*argv, "use_2fa") == 0) { + *flags |= PAM_CLI_FLAGS_USE_2FA; + } else if (strcmp(*argv, "allow_missing_name") == 0) { + *flags |= PAM_CLI_FLAGS_ALLOW_MISSING_NAME; + } else if (strcmp(*argv, "prompt_always") == 0) { + *flags |= PAM_CLI_FLAGS_PROMPT_ALWAYS; + } else if (strcmp(*argv, "try_cert_auth") == 0) { + *flags |= PAM_CLI_FLAGS_TRY_CERT_AUTH; + } else if (strcmp(*argv, "require_cert_auth") == 0) { + *flags |= PAM_CLI_FLAGS_REQUIRE_CERT_AUTH; + } else { + logger(pamh, LOG_WARNING, "unknown option: %s", *argv); + } + } + + return; +} + +static int prompt_by_config(pam_handle_t *pamh, struct pam_items *pi) +{ + size_t c; + int ret = PAM_SUCCESS; + + if (pi->pc == NULL || *pi->pc == NULL) { + return PAM_SYSTEM_ERR; + } + + for (c = 0; pi->pc[c] != NULL; c++) { + switch (pc_get_type(pi->pc[c])) { + case PC_TYPE_PASSWORD: + ret = prompt_password(pamh, pi, pc_get_password_prompt(pi->pc[c])); + break; + case PC_TYPE_2FA: + ret = prompt_2fa(pamh, pi, pc_get_2fa_1st_prompt(pi->pc[c]), + pc_get_2fa_2nd_prompt(pi->pc[c])); + break; + case PC_TYPE_2FA_SINGLE: + ret = prompt_2fa_single(pamh, pi, + pc_get_2fa_single_prompt(pi->pc[c])); + break; + case PC_TYPE_PASSKEY: + ret = prompt_passkey(pamh, pi, + pc_get_passkey_inter_prompt(pi->pc[c]), + pc_get_passkey_touch_prompt(pi->pc[c])); + break; + case PC_TYPE_SC_PIN: + ret = prompt_sc_pin(pamh, pi); + /* Todo: add extra string option */ + break; + default: + ret = PAM_SYSTEM_ERR; + } + + /* If not credential where given try the next type otherwise we are + * done. */ + if (ret == PAM_SUCCESS && pi->pam_authtok_size == 0) { + continue; + } + + break; + } + + return ret; +} + +static int get_authtok_for_authentication(pam_handle_t *pamh, + struct pam_items *pi, + uint32_t flags) +{ + int ret; + const char *pin = NULL; + + if ((flags & PAM_CLI_FLAGS_USE_FIRST_PASS) + || ( pi->pamstack_authtok != NULL + && *(pi->pamstack_authtok) != '\0' + && !(flags & PAM_CLI_FLAGS_PROMPT_ALWAYS))) { + pi->pam_authtok_type = SSS_AUTHTOK_TYPE_PASSWORD; + pi->pam_authtok = strdup(pi->pamstack_authtok); + if (pi->pam_authtok == NULL) { + D(("option use_first_pass set, but no password found")); + return PAM_BUF_ERR; + } + pi->pam_authtok_size = strlen(pi->pam_authtok); + } else { + if (pi->oauth2_url != NULL) { + /* Prompt config is not supported for OAuth2. */ + ret = prompt_oauth2(pamh, pi); + } else if (pi->pc != NULL) { + ret = prompt_by_config(pamh, pi); + } else { + if (flags & PAM_CLI_FLAGS_USE_2FA + || (pi->otp_vendor != NULL && pi->otp_token_id != NULL + && pi->otp_challenge != NULL)) { + if (pi->password_prompting) { + ret = prompt_2fa(pamh, pi, _("First Factor: "), + _("Second Factor (optional): ")); + } else { + ret = prompt_2fa(pamh, pi, _("First Factor: "), + _("Second Factor: ")); + } + } else if (pi->cert_list != NULL) { + if (pi->cert_list->next == NULL) { + /* Only one certificate */ + pi->selected_cert = pi->cert_list; + } else { + ret = prompt_multi_cert(pamh, pi); + if (ret != 0) { + D(("Failed to select certificate")); + return PAM_AUTHTOK_ERR; + } + } + ret = prompt_sc_pin(pamh, pi); + } else if (SERVICE_IS_GDM_SMARTCARD(pi) + || (pi->flags & PAM_CLI_FLAGS_REQUIRE_CERT_AUTH)) { + /* Use pin prompt as fallback for gdm-smartcard */ + ret = prompt_sc_pin(pamh, pi); + } else if (pi->passkey_prompt_pin) { + ret = prompt_passkey(pamh, pi, + _("Insert your passkey device, then press ENTER."), + ""); + /* Fallback to password auth if no PIN was entered */ + if (ret == EIO) { + ret = prompt_password(pamh, pi, _("Password: ")); + if (pi->pam_authtok_size == 0) { + D(("Empty password failure")); + pi->passkey_prompt_pin = NULL; + return PAM_AUTHTOK_ERR; + } + } + } else { + ret = prompt_password(pamh, pi, _("Password: ")); + } + } + if (ret != PAM_SUCCESS) { + D(("failed to get password from user")); + return ret; + } + + if (flags & PAM_CLI_FLAGS_FORWARD_PASS) { + if (pi->pam_authtok_type == SSS_AUTHTOK_TYPE_PASSWORD) { + ret = pam_set_item(pamh, PAM_AUTHTOK, pi->pam_authtok); + } else if (pi->pam_authtok_type == SSS_AUTHTOK_TYPE_SC_PIN) { + pin = sss_auth_get_pin_from_sc_blob((uint8_t *) pi->pam_authtok, + pi->pam_authtok_size); + if (pin != NULL) { + ret = pam_set_item(pamh, PAM_AUTHTOK, pin); + } else { + ret = PAM_SYSTEM_ERR; + } + } else if (pi->pam_authtok_type == SSS_AUTHTOK_TYPE_2FA + && pi->first_factor != NULL) { + ret = pam_set_item(pamh, PAM_AUTHTOK, pi->first_factor); + } else { + ret = PAM_SYSTEM_ERR; + } + if (ret != PAM_SUCCESS) { + D(("Failed to set PAM_AUTHTOK [%s], " + "authtok may not be available for other modules", + pam_strerror(pamh,ret))); + } + } + } + + return PAM_SUCCESS; +} + +static int check_authtok_data(pam_handle_t *pamh, struct pam_items *pi) +{ + int pam_status; + int *authtok_type; + size_t *authtok_size; + char *authtok_data; + + pam_status = pam_get_data(pamh, PAM_SSS_AUTHOK_TYPE, + (const void **) &authtok_type); + if (pam_status != PAM_SUCCESS) { + D(("pam_get_data failed.")); + return EIO; + } + + pam_status = pam_get_data(pamh, PAM_SSS_AUTHOK_SIZE, + (const void **) &authtok_size); + if (pam_status != PAM_SUCCESS) { + D(("pam_get_data failed.")); + return EIO; + } + + pam_status = pam_get_data(pamh, PAM_SSS_AUTHOK_DATA, + (const void **) &authtok_data); + if (pam_status != PAM_SUCCESS) { + D(("pam_get_data failed.")); + return EIO; + } + + pi->pam_authtok = malloc(*authtok_size); + if (pi->pam_authtok == NULL) { + D(("malloc failed.")); + return ENOMEM; + } + memcpy(pi->pam_authtok, authtok_data, *authtok_size); + + pi->pam_authtok_type = *authtok_type; + pi->pam_authtok_size = *authtok_size; + + return 0; +} + +static int keep_authtok_data(pam_handle_t *pamh, struct pam_items *pi) +{ + int pam_status; + int *authtok_type; + size_t *authtok_size; + char *authtok_data; + + authtok_type = malloc(sizeof(int)); + if (authtok_type == NULL) { + D(("malloc failed.")); + return ENOMEM; + } + *authtok_type = pi->pam_authtok_type; + + pam_status = pam_set_data(pamh, PAM_SSS_AUTHOK_TYPE, authtok_type, + free_exp_data); + if (pam_status != PAM_SUCCESS) { + free(authtok_type); + D(("pam_set_data failed.")); + return EIO; + } + + authtok_size = malloc(sizeof(size_t)); + if (authtok_size == NULL) { + D(("malloc failed.")); + return ENOMEM; + } + *authtok_size = pi->pam_authtok_size; + + pam_status = pam_set_data(pamh, PAM_SSS_AUTHOK_SIZE, authtok_size, + free_exp_data); + if (pam_status != PAM_SUCCESS) { + free(authtok_size); + D(("pam_set_data failed.")); + return EIO; + } + + authtok_data = malloc(pi->pam_authtok_size); + if (authtok_data == NULL) { + D(("malloc failed.")); + return ENOMEM; + } + memcpy(authtok_data, pi->pam_authtok, pi->pam_authtok_size); + + pam_status = pam_set_data(pamh, PAM_SSS_AUTHOK_DATA, authtok_data, + free_exp_data); + if (pam_status != PAM_SUCCESS) { + free(authtok_data); + D(("pam_set_data failed.")); + return EIO; + } + + return 0; +} + +static int get_authtok_for_password_change(pam_handle_t *pamh, + struct pam_items *pi, + uint32_t flags, + int pam_flags) +{ + int ret; + const int *exp_data = NULL; + ret = pam_get_data(pamh, PWEXP_FLAG, (const void **) &exp_data); + if (ret != PAM_SUCCESS) { + exp_data = NULL; + } + + /* we query for the old password during PAM_PRELIM_CHECK to make + * pam_sss work e.g. with pam_cracklib */ + if (pam_flags & PAM_PRELIM_CHECK) { + if ( (getuid() != 0 || exp_data ) && !(flags & PAM_CLI_FLAGS_USE_FIRST_PASS)) { + if (flags & PAM_CLI_FLAGS_USE_2FA + || (pi->otp_vendor != NULL && pi->otp_token_id != NULL + && pi->otp_challenge != NULL)) { + if (pi->password_prompting) { + ret = prompt_2fa(pamh, pi, _("First Factor (Current Password): "), + _("Second Factor (optional): ")); + } else { + ret = prompt_2fa(pamh, pi, _("First Factor (Current Password): "), + _("Second Factor: ")); + } + } else { + ret = prompt_password(pamh, pi, _("Current Password: ")); + } + if (ret != PAM_SUCCESS) { + D(("failed to get credentials from user")); + return ret; + } + + ret = pam_set_item(pamh, PAM_OLDAUTHTOK, pi->pam_authtok); + if (ret != PAM_SUCCESS) { + D(("Failed to set PAM_OLDAUTHTOK [%s], " + "oldauthtok may not be available", + pam_strerror(pamh,ret))); + return ret; + } + + if (pi->pam_authtok_type == SSS_AUTHTOK_TYPE_2FA) { + ret = keep_authtok_data(pamh, pi); + if (ret != 0) { + D(("Failed to store authtok data to pam handle. Password " + "change might fail.")); + } + } + } + + return PAM_SUCCESS; + } + + if (check_authtok_data(pamh, pi) != 0) { + if (pi->pamstack_oldauthtok == NULL) { + if (getuid() != 0) { + D(("no password found for chauthtok")); + return PAM_BUF_ERR; + } else { + pi->pam_authtok_type = SSS_AUTHTOK_TYPE_EMPTY; + pi->pam_authtok = NULL; + pi->pam_authtok_size = 0; + } + } else { + pi->pam_authtok = strdup(pi->pamstack_oldauthtok); + if (pi->pam_authtok == NULL) { + D(("strdup failed")); + return PAM_BUF_ERR; + } + pi->pam_authtok_type = SSS_AUTHTOK_TYPE_PASSWORD; + pi->pam_authtok_size = strlen(pi->pam_authtok); + } + } + + if (flags & PAM_CLI_FLAGS_USE_AUTHTOK) { + pi->pam_newauthtok_type = SSS_AUTHTOK_TYPE_PASSWORD; + pi->pam_newauthtok = strdup(pi->pamstack_authtok); + if (pi->pam_newauthtok == NULL) { + D(("option use_authtok set, but no new password found")); + return PAM_BUF_ERR; + } + pi->pam_newauthtok_size = strlen(pi->pam_newauthtok); + } else { + ret = prompt_new_password(pamh, pi); + if (ret != PAM_SUCCESS) { + D(("failed to get new password from user")); + return ret; + } + + if (flags & PAM_CLI_FLAGS_FORWARD_PASS) { + ret = pam_set_item(pamh, PAM_AUTHTOK, pi->pam_newauthtok); + if (ret != PAM_SUCCESS) { + D(("Failed to set PAM_AUTHTOK [%s], " + "oldauthtok may not be available", + pam_strerror(pamh,ret))); + } + } + } + + return PAM_SUCCESS; +} + +#define SC_ENTER_LABEL_FMT "Please insert smart card labeled\n %s" +#define SC_ENTER_FMT "Please insert smart card" + +static int check_login_token_name(pam_handle_t *pamh, struct pam_items *pi, + int retries, bool quiet_mode) +{ + int ret; + int pam_status; + char *login_token_name; + char *prompt = NULL; + uint32_t orig_flags = pi->flags; + + login_token_name = getenv("PKCS11_LOGIN_TOKEN_NAME"); + if (login_token_name == NULL + && !(pi->flags & PAM_CLI_FLAGS_REQUIRE_CERT_AUTH)) { + return PAM_SUCCESS; + } + + if (login_token_name == NULL) { + ret = asprintf(&prompt, SC_ENTER_FMT); + } else { + ret = asprintf(&prompt, SC_ENTER_LABEL_FMT, login_token_name); + } + if (ret == -1) { + return ENOMEM; + } + + pi->flags |= PAM_CLI_FLAGS_REQUIRE_CERT_AUTH; + + /* TODO: check multiple cert case */ + while (pi->cert_list == NULL || pi->cert_list->token_name == NULL + || (login_token_name != NULL + && strcmp(login_token_name, + pi->cert_list->token_name) != 0)) { + + free_cert_list(pi->cert_list); + pi->cert_list = NULL; + if (retries < 0) { + ret = PAM_AUTHINFO_UNAVAIL; + goto done; + } + retries--; + + ret = do_pam_conversation(pamh, PAM_TEXT_INFO, prompt, NULL, NULL); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + goto done; + } + + pam_status = send_and_receive(pamh, pi, SSS_PAM_PREAUTH, quiet_mode); + if (pam_status != PAM_SUCCESS) { + D(("send_and_receive returned [%d] during pre-auth", pam_status)); + /* + * Since we are waiting for the right Smartcard to be inserted errors + * can be ignored here. + */ + } + } + + ret = PAM_SUCCESS; + +done: + + pi->flags = orig_flags; + free(prompt); + + return ret; +} + +static int pam_sss(enum sss_cli_command task, pam_handle_t *pamh, + int pam_flags, int argc, const char **argv) +{ + int ret; + int pam_status; + struct pam_items pi = { 0 }; + uint32_t flags = 0; + const int *exp_data; + int *pw_exp_data; + bool retry = false; + bool quiet_mode = false; + int retries = 0; + const char *domains = NULL; + + bindtextdomain(PACKAGE, LOCALEDIR); + + D(("Hello pam_sssd: %#x", task)); + + eval_argv(pamh, argc, argv, &flags, &retries, &quiet_mode, &domains); + + /* Fail all authentication on misconfigured domains= parameter. The admin + * probably wanted to restrict authentication, so it's safer to fail */ + if (domains && strcmp(domains, "") == 0) { + return PAM_SYSTEM_ERR; + } + + pi.requested_domains = domains; + + ret = get_pam_items(pamh, flags, &pi); + if (ret != PAM_SUCCESS) { + D(("get items returned error: %s", pam_strerror(pamh,ret))); + if ((flags & PAM_CLI_FLAGS_TRY_CERT_AUTH) + || (flags & PAM_CLI_FLAGS_REQUIRE_CERT_AUTH) ) { + return PAM_AUTHINFO_UNAVAIL; + } + if (flags & PAM_CLI_FLAGS_IGNORE_UNKNOWN_USER && ret == PAM_USER_UNKNOWN) { + ret = PAM_IGNORE; + } + if (flags & PAM_CLI_FLAGS_IGNORE_AUTHINFO_UNAVAIL + && ret == PAM_AUTHINFO_UNAVAIL) { + ret = PAM_IGNORE; + } + return ret; + } + + do { + retry = false; + + switch(task) { + case SSS_PAM_AUTHENTICATE: + /* + * Only do preauth if + * - PAM_CLI_FLAGS_USE_FIRST_PASS is not set + * - no password is on the stack or PAM_CLI_FLAGS_PROMPT_ALWAYS is set + * - preauth indicator file exists. + */ + if ( !(flags & PAM_CLI_FLAGS_USE_FIRST_PASS) + && (pi.pam_authtok == NULL + || (flags & PAM_CLI_FLAGS_PROMPT_ALWAYS)) + && access(PAM_PREAUTH_INDICATOR, F_OK) == 0) { + + if (flags & PAM_CLI_FLAGS_REQUIRE_CERT_AUTH) { + /* Do not use PAM_CLI_FLAGS_REQUIRE_CERT_AUTH in the first + * SSS_PAM_PREAUTH run. In case a card is already inserted + * we do not have to prompt to insert a card. */ + pi.flags &= ~PAM_CLI_FLAGS_REQUIRE_CERT_AUTH; + pi.flags |= PAM_CLI_FLAGS_TRY_CERT_AUTH; + } + + pam_status = send_and_receive(pamh, &pi, SSS_PAM_PREAUTH, + quiet_mode); + + pi.flags = flags; + if (pam_status != PAM_SUCCESS) { + D(("send_and_receive returned [%d] during pre-auth", + pam_status)); + /* + * Since we are only interested in the result message + * and will always use password authentication + * as a fallback (except for gdm-smartcard), + * errors can be ignored here. + */ + } + } + + if (flags & PAM_CLI_FLAGS_TRY_CERT_AUTH + && pi.cert_list == NULL) { + D(("No certificates for authentication available.")); + overwrite_and_free_pam_items(&pi); + return PAM_AUTHINFO_UNAVAIL; + } + + if (SERVICE_IS_GDM_SMARTCARD(&pi) + || (flags & PAM_CLI_FLAGS_REQUIRE_CERT_AUTH)) { + ret = check_login_token_name(pamh, &pi, retries, + quiet_mode); + if (ret != PAM_SUCCESS) { + D(("check_login_token_name failed.\n")); + } + } + + ret = get_authtok_for_authentication(pamh, &pi, flags); + if (ret != PAM_SUCCESS) { + D(("failed to get authentication token: %s", + pam_strerror(pamh, ret))); + return ret; + } + break; + case SSS_PAM_CHAUTHTOK: + /* + * Even if we only want to change the (long term) password + * there are cases where more than the password is needed to + * get the needed privileges in a backend to change the + * password. + * + * E.g. with mandatory 2-factor authentication we have to ask + * not only for the current password but for the second + * factor, e.g. the one-time token value, as well. + * + * The means the preauth step has to be done here as well but + * only if + * - PAM_PRELIM_CHECK is set + * - PAM_CLI_FLAGS_USE_FIRST_PASS is not set + * - no password is on the stack or PAM_CLI_FLAGS_PROMPT_ALWAYS is set + * - preauth indicator file exists. + */ + if ( (pam_flags & PAM_PRELIM_CHECK) + && !(flags & PAM_CLI_FLAGS_USE_FIRST_PASS) + && (pi.pam_authtok == NULL + || (flags & PAM_CLI_FLAGS_PROMPT_ALWAYS)) + && access(PAM_PREAUTH_INDICATOR, F_OK) == 0) { + pam_status = send_and_receive(pamh, &pi, SSS_PAM_PREAUTH, + quiet_mode); + if (pam_status != PAM_SUCCESS) { + D(("send_and_receive returned [%d] during pre-auth", + pam_status)); + /* + * Since we are only interested in the result message + * and will always use password authentication + * as a fallback, errors can be ignored here. + */ + } + } + + ret = get_authtok_for_password_change(pamh, &pi, flags, pam_flags); + if (ret != PAM_SUCCESS) { + D(("failed to get tokens for password change: %s", + pam_strerror(pamh, ret))); + overwrite_and_free_pam_items(&pi); + return ret; + } + + if (pam_flags & PAM_PRELIM_CHECK) { + if (pi.pam_authtok_type == SSS_AUTHTOK_TYPE_2FA) { + /* We cannot validate the credentials with an OTP + * token value during PAM_PRELIM_CHECK because it + * would be invalid for the actual password change. So + * we are done. */ + + return PAM_SUCCESS; + } + task = SSS_PAM_CHAUTHTOK_PRELIM; + } + break; + case SSS_PAM_ACCT_MGMT: + case SSS_PAM_SETCRED: + case SSS_PAM_OPEN_SESSION: + case SSS_PAM_CLOSE_SESSION: + break; + default: + D(("Illegal task [%#x]", task)); + return PAM_SYSTEM_ERR; + } + + pam_status = send_and_receive(pamh, &pi, task, quiet_mode); + + if (flags & PAM_CLI_FLAGS_IGNORE_UNKNOWN_USER + && pam_status == PAM_USER_UNKNOWN) { + pam_status = PAM_IGNORE; + } + if (flags & PAM_CLI_FLAGS_IGNORE_AUTHINFO_UNAVAIL + && pam_status == PAM_AUTHINFO_UNAVAIL) { + pam_status = PAM_IGNORE; + } + + switch (task) { + case SSS_PAM_AUTHENTICATE: + /* We allow sssd to send the return code PAM_NEW_AUTHTOK_REQD during + * authentication, see sss_cli.h for details */ + if (pam_status == PAM_NEW_AUTHTOK_REQD) { + D(("Authtoken expired, trying to change it")); + + pw_exp_data = malloc(sizeof(int)); + if (pw_exp_data == NULL) { + D(("malloc failed.")); + pam_status = PAM_BUF_ERR; + break; + } + *pw_exp_data = 1; + + pam_status = pam_set_data(pamh, PWEXP_FLAG, pw_exp_data, + free_exp_data); + if (pam_status != PAM_SUCCESS) { + D(("pam_set_data failed.")); + } + } + break; + case SSS_PAM_ACCT_MGMT: + if (pam_status == PAM_SUCCESS && + pam_get_data(pamh, PWEXP_FLAG, (const void **) &exp_data) == + PAM_SUCCESS) { + ret = do_pam_conversation(pamh, PAM_TEXT_INFO, + _("Password expired. Change your password now."), + NULL, NULL); + if (ret != PAM_SUCCESS) { + D(("do_pam_conversation failed.")); + } + pam_status = PAM_NEW_AUTHTOK_REQD; + } + break; + case SSS_PAM_CHAUTHTOK: + if (pam_status != PAM_SUCCESS && pam_status != PAM_USER_UNKNOWN) { + ret = pam_set_item(pamh, PAM_AUTHTOK, NULL); + if (ret != PAM_SUCCESS) { + D(("Failed to unset PAM_AUTHTOK [%s]", + pam_strerror(pamh,ret))); + } + ret = pam_set_item(pamh, PAM_OLDAUTHTOK, NULL); + if (ret != PAM_SUCCESS) { + D(("Failed to unset PAM_OLDAUTHTOK [%s]", + pam_strerror(pamh,ret))); + } + } + break; + case SSS_PAM_CHAUTHTOK_PRELIM: + if (pam_status == PAM_PERM_DENIED && pi.pam_authtok_size == 0 && + getuid() == 0 && + pam_get_data(pamh, PWEXP_FLAG, (const void **) &exp_data) != + PAM_SUCCESS) { + + ret = select_pw_reset_message(pamh, &pi); + if (ret != 0) { + D(("select_pw_reset_message failed.\n")); + } + } + default: + /* nothing to do */ + break; + } + + overwrite_and_free_pam_items(&pi); + + D(("retries [%d].", retries)); + + if (pam_status != PAM_SUCCESS && + (task == SSS_PAM_AUTHENTICATE || task == SSS_PAM_CHAUTHTOK_PRELIM) && + retries > 0) { + retry = true; + retries--; + + flags &= ~PAM_CLI_FLAGS_USE_FIRST_PASS; + ret = pam_set_item(pamh, PAM_AUTHTOK, NULL); + if (ret != PAM_SUCCESS) { + D(("Failed to unset PAM_AUTHTOK [%s]", + pam_strerror(pamh,ret))); + } + ret = pam_set_item(pamh, PAM_OLDAUTHTOK, NULL); + if (ret != PAM_SUCCESS) { + D(("Failed to unset PAM_OLDAUTHTOK [%s]", + pam_strerror(pamh,ret))); + } + } + } while(retry); + + return pam_status; +} + +PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, + const char **argv ) +{ + return pam_sss(SSS_PAM_AUTHENTICATE, pamh, flags, argc, argv); +} + + +PAM_EXTERN int pam_sm_setcred(pam_handle_t *pamh, int flags, int argc, + const char **argv ) +{ + return pam_sss(SSS_PAM_SETCRED, pamh, flags, argc, argv); +} + +PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags, int argc, + const char **argv ) +{ + return pam_sss(SSS_PAM_ACCT_MGMT, pamh, flags, argc, argv); +} + +PAM_EXTERN int pam_sm_chauthtok(pam_handle_t *pamh, int flags, int argc, + const char **argv ) +{ + return pam_sss(SSS_PAM_CHAUTHTOK, pamh, flags, argc, argv); +} + +PAM_EXTERN int pam_sm_open_session(pam_handle_t *pamh, int flags, int argc, + const char **argv ) +{ + return pam_sss(SSS_PAM_OPEN_SESSION, pamh, flags, argc, argv); +} + +PAM_EXTERN int pam_sm_close_session(pam_handle_t *pamh, int flags, int argc, + const char **argv ) +{ + return pam_sss(SSS_PAM_CLOSE_SESSION, pamh, flags, argc, argv); +} + + +#ifdef PAM_STATIC + +/* static module data */ + +struct pam_module _pam_sssd_modstruct ={ + "pam_sssd", + pam_sm_authenticate, + pam_sm_setcred, + pam_sm_acct_mgmt, + pam_sm_open_session, + pam_sm_close_session, + pam_sm_chauthtok +}; + +#endif diff --git a/src/sss_client/pam_sss_gss.c b/src/sss_client/pam_sss_gss.c new file mode 100644 index 0000000..dd578ae --- /dev/null +++ b/src/sss_client/pam_sss_gss.c @@ -0,0 +1,625 @@ +/* + Authors: + Pavel Březina <pbrezina@redhat.com> + + Copyright (C) 2020 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include <stdlib.h> +#include <stddef.h> +#include <stdbool.h> +#include <security/pam_modules.h> +#include <security/pam_ext.h> +#include <gssapi.h> +#include <gssapi/gssapi_ext.h> +#include <gssapi/gssapi_generic.h> +#include <errno.h> +#include <sys/types.h> +#include <sys/syslog.h> +#include <unistd.h> +#include <string.h> + +#include "util/sss_format.h" +#include "sss_client/sss_cli.h" + +bool debug_enabled; + +#define TRACE(pamh, fmt, ...) do { \ + if (debug_enabled) { \ + pam_info(pamh, "pam_sss_gss: " fmt, ## __VA_ARGS__); \ + } \ +} while (0) + +#define ERROR(pamh, fmt, ...) do { \ + if (debug_enabled) { \ + pam_error(pamh, "pam_sss_gss: " fmt, ## __VA_ARGS__); \ + pam_syslog(pamh, LOG_ERR, fmt, ## __VA_ARGS__); \ + } \ +} while (0) + +static bool switch_euid(pam_handle_t *pamh, uid_t current, uid_t desired) +{ + int ret; + + TRACE(pamh, "Switching euid from %" SPRIuid " to %" SPRIuid, current, + desired); + + if (current == desired) { + return true; + } + + ret = seteuid(desired); + if (ret != 0) { + ERROR(pamh, "Unable to set euid to %" SPRIuid, desired); + return false; + } + + return true; +} + +static const char *get_item_as_string(pam_handle_t *pamh, int item) +{ + const char *str; + int ret; + + ret = pam_get_item(pamh, item, (void *)&str); + if (ret != PAM_SUCCESS || str == NULL || str[0] == '\0') { + return NULL; + } + + return str; +} + +static errno_t string_to_gss_name(pam_handle_t *pamh, + const char *target, + gss_OID type, + gss_name_t *_name) +{ + gss_buffer_desc name_buf; + OM_uint32 major; + OM_uint32 minor; + + name_buf.value = (void *)(uintptr_t)target; + name_buf.length = strlen(target); + major = gss_import_name(&minor, &name_buf, type, _name); + if (GSS_ERROR(major)) { + ERROR(pamh, "Could not convert target to GSS name"); + return EIO; + } + + return EOK; +} + +static void gssapi_log_status(pam_handle_t *pamh, + int type, + OM_uint32 status_code) +{ + gss_buffer_desc buf; + OM_uint32 message_context; + OM_uint32 minor; + + message_context = 0; + do { + gss_display_status(&minor, status_code, type, GSS_C_NO_OID, + &message_context, &buf); + ERROR(pamh, "GSSAPI: %.*s", (int)buf.length, (char *)buf.value); + gss_release_buffer(&minor, &buf); + } while (message_context != 0); +} + +static void gssapi_log_error(pam_handle_t *pamh, + OM_uint32 major, + OM_uint32 minor) +{ + gssapi_log_status(pamh, GSS_C_GSS_CODE, major); + gssapi_log_status(pamh, GSS_C_MECH_CODE, minor); +} + +static errno_t gssapi_get_creds(pam_handle_t *pamh, + const char *ccache, + const char *target, + const char *upn, + gss_cred_id_t *_creds) +{ + gss_key_value_set_desc cstore = {0, NULL}; + gss_key_value_element_desc el; + gss_name_t name = GSS_C_NO_NAME; + OM_uint32 major; + OM_uint32 minor; + errno_t ret; + + if (upn != NULL && upn[0] != '\0') { + TRACE(pamh, "Acquiring credentials for principal [%s]", upn); + ret = string_to_gss_name(pamh, upn, GSS_C_NT_USER_NAME, &name); + if (ret != EOK) { + goto done; + } + } else { + TRACE(pamh, "Acquiring credentials, principal name will be derived"); + } + + if (ccache != NULL) { + el.key = "ccache"; + el.value = ccache; + cstore.count = 1; + cstore.elements = ⪙ + } + + major = gss_acquire_cred_from(&minor, name, GSS_C_INDEFINITE, + GSS_C_NO_OID_SET, GSS_C_INITIATE, + &cstore, _creds, NULL, NULL); + if (GSS_ERROR(major)) { + /* TODO: Do not hardcode the error code. */ + if (minor == 2529639053 && name != GSS_C_NO_NAME) { + /* Hint principal was not found. Try again and let GSSAPI choose. */ + TRACE(pamh, "Principal [%s] was not found in ccache", upn); + ret = gssapi_get_creds(pamh, ccache, target, NULL, _creds); + goto done; + } else { + ERROR(pamh, "Unable to read credentials from [%s] " + "[maj:0x%x, min:0x%x]", ccache == NULL ? "default" : ccache, + major, minor); + + gssapi_log_error(pamh, major, minor); + ret = EIO; + goto done; + } + } + + ret = EOK; + +done: + gss_release_name(&minor, &name); + + return ret; +} + +static errno_t sssd_gssapi_init_send(pam_handle_t *pamh, + const char *pam_service, + const char *pam_user, + uint8_t **_reply, + size_t *_reply_len) +{ + struct sss_cli_req_data req_data; + size_t service_len; + size_t user_len; + size_t reply_len; + uint8_t *reply = NULL; + uint8_t *data; + errno_t ret; + int ret_errno; + + if (pam_service == NULL || pam_user == NULL) { + return EINVAL; + } + + service_len = strlen(pam_service) + 1; + user_len = strlen(pam_user) + 1; + + req_data.len = (service_len + user_len) * sizeof(char); + data = (uint8_t*)malloc(req_data.len); + if (data == NULL) { + return ENOMEM; + } + + memcpy(data, pam_service, service_len); + memcpy(data + service_len, pam_user, user_len); + + req_data.data = data; + + ret = sss_pam_make_request(SSS_GSSAPI_INIT, &req_data, &reply, &reply_len, + &ret_errno); + free(data); + if (ret != PAM_SUCCESS) { + if (ret_errno == ENOTSUP) { + TRACE(pamh, "GSSAPI authentication is not supported for user %s " + "and service %s", pam_user, pam_service); + return ret_errno; + } + + ERROR(pamh, "Communication error [%d, %d]: %s; %s", ret, ret_errno, + pam_strerror(pamh, ret), strerror(ret_errno)); + + return (ret_errno != EOK) ? ret_errno : EIO; + } + + if (ret_errno == EOK) { + *_reply = reply; + *_reply_len = reply_len; + } else { + /* We got PAM_SUCCESS therefore the communication with SSSD was + * successful and we have received a reply buffer. We just don't care + * about it, we are only interested in the error code. */ + free(reply); + } + + return ret_errno; +} + +static errno_t sssd_gssapi_init_recv(uint8_t *reply, + size_t reply_len, + char **_username, + char **_domain, + char **_target, + char **_upn) +{ + char *username = NULL; + char *domain = NULL; + char *target = NULL; + char *upn = NULL; + const char *buf; + size_t pctr = 0; + size_t dlen; + errno_t ret; + + username = malloc(reply_len * sizeof(char)); + domain = malloc(reply_len * sizeof(char)); + target = malloc(reply_len * sizeof(char)); + upn = malloc(reply_len * sizeof(char)); + if (username == NULL || domain == NULL || target == NULL || upn == NULL) { + ret = ENOMEM; + goto done; + } + + buf = (const char*)reply; + + dlen = reply_len; + ret = sss_readrep_copy_string(buf, &pctr, &reply_len, &dlen, &username, + NULL); + if (ret != EOK) { + goto done; + } + + dlen = reply_len; + ret = sss_readrep_copy_string(buf, &pctr, &reply_len, &dlen, &domain, NULL); + if (ret != EOK) { + goto done; + } + + dlen = reply_len; + ret = sss_readrep_copy_string(buf, &pctr, &reply_len, &dlen, &target, NULL); + if (ret != EOK) { + goto done; + } + + dlen = reply_len; + ret = sss_readrep_copy_string(buf, &pctr, &reply_len, &dlen, &upn, NULL); + if (ret != EOK) { + goto done; + } + + *_username = username; + *_domain = domain; + *_target = target; + *_upn = upn; + +done: + if (ret != EOK) { + free(username); + free(domain); + free(target); + free(upn); + } + + return ret; +} + +static errno_t sssd_gssapi_init(pam_handle_t *pamh, + const char *pam_service, + const char *pam_user, + char **_username, + char **_domain, + char **_target, + char **_upn) +{ + size_t reply_len = 0; + uint8_t *reply = NULL; + errno_t ret; + + ret = sssd_gssapi_init_send(pamh, pam_service, pam_user, &reply, + &reply_len); + if (ret != EOK) { + return ret; + } + + ret = sssd_gssapi_init_recv(reply, reply_len, _username, _domain, _target, + _upn); + free(reply); + + return ret; +} + +static errno_t sssd_establish_sec_ctx_send(pam_handle_t *pamh, + const char *pam_service, + const char *username, + const char *domain, + const void *gss_data, + size_t gss_data_len, + void **_reply, + size_t *_reply_len) +{ + struct sss_cli_req_data req_data; + size_t username_len; + size_t service_len; + size_t domain_len; + uint8_t *data; + int ret_errno; + int ret; + + service_len = strlen(pam_service) + 1; + username_len = strlen(username) + 1; + domain_len = strlen(domain) + 1; + + req_data.len = (service_len + username_len + domain_len) * sizeof(char) + + gss_data_len; + data = malloc(req_data.len); + if (data == NULL) { + return ENOMEM; + } + + memcpy(data, pam_service, service_len); + memcpy(data + service_len, username, username_len); + memcpy(data + service_len + username_len, domain, domain_len); + memcpy(data + service_len + username_len + domain_len, gss_data, + gss_data_len); + + req_data.data = data; + ret = sss_pam_make_request(SSS_GSSAPI_SEC_CTX, &req_data, (uint8_t**)_reply, + _reply_len, &ret_errno); + free(data); + if (ret != PAM_SUCCESS) { + /* ENOTSUP should not happend here so let's keep it as generic error. */ + ERROR(pamh, "Communication error [%d, %d]: %s; %s", ret, ret_errno, + pam_strerror(pamh, ret), strerror(ret_errno)); + + return (ret_errno != EOK) ? ret_errno : EIO; + } + + return ret_errno; +} + +static int sssd_establish_sec_ctx(pam_handle_t *pamh, + const char *ccache, + const char *pam_service, + const char *username, + const char *domain, + const char *target, + const char *upn) +{ + gss_ctx_id_t ctx = GSS_C_NO_CONTEXT; + gss_buffer_desc input = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output = GSS_C_EMPTY_BUFFER; + OM_uint32 flags = GSS_C_MUTUAL_FLAG; + gss_name_t gss_name; + gss_cred_id_t creds; + OM_uint32 ret_flags; + OM_uint32 major; + OM_uint32 minor; + int ret; + + ret = gssapi_get_creds(pamh, ccache, target, upn, &creds); + if (ret != EOK) { + return ret; + } + + ret = string_to_gss_name(pamh, target, GSS_C_NT_HOSTBASED_SERVICE, &gss_name); + if (ret != 0) { + return ret; + } + + do { + major = gss_init_sec_context(&minor, creds, &ctx, + gss_name, GSS_C_NO_OID, flags, 0, NULL, + &input, NULL, &output, + &ret_flags, NULL); + + free(input.value); + memset(&input, 0, sizeof(gss_buffer_desc)); + + if (GSS_ERROR(major)) { + ERROR(pamh, "Unable to establish GSS context [maj:0x%x, min:0x%x]", + major, minor); + gssapi_log_error(pamh, major, minor); + ret = EIO; + goto done; + } else if (major == GSS_S_CONTINUE_NEEDED || output.length > 0) { + ret = sssd_establish_sec_ctx_send(pamh, pam_service, + username, domain, + output.value, output.length, + &input.value, &input.length); + gss_release_buffer(NULL, &output); + if (ret != EOK) { + goto done; + } + } + } while (major != GSS_S_COMPLETE); + + if ((ret_flags & flags) != flags) { + ERROR(pamh, "Negotiated context does not support requested flags\n"); + ret = EIO; + goto done; + } + + ret = EOK; + +done: + gss_delete_sec_context(&minor, &ctx, NULL); + gss_release_name(&minor, &gss_name); + + return ret; +} + +static int errno_to_pam(pam_handle_t *pamh, errno_t ret) +{ + switch (ret) { + case EOK: + TRACE(pamh, "Authentication successful"); + return PAM_SUCCESS; + case ENOENT: + TRACE(pamh, "User not found"); + return PAM_USER_UNKNOWN; + case ENOTSUP: + TRACE(pamh, "GSSAPI authentication is not enabled " + "for given user and service"); + return PAM_USER_UNKNOWN; + case ESSS_NO_SOCKET: + TRACE(pamh, "SSSD socket does not exist"); + return PAM_AUTHINFO_UNAVAIL; + case EPERM: + TRACE(pamh, "Authentication failed"); + return PAM_AUTH_ERR; + default: + TRACE(pamh, "System error [%d]: %s", + ret, strerror(ret)); + return PAM_SYSTEM_ERR; + } +} + +static errno_t sss_cli_getenv(const char *variable_name, char **_value) +{ + char *value = getenv(variable_name); + if (value == NULL) { + *_value = NULL; + return EOK; + } + + *_value = strdup(value); + if (*_value == NULL) { + return ENOMEM; + } + + return EOK; +} + +int pam_sm_authenticate(pam_handle_t *pamh, + int flags, + int argc, + const char **argv) +{ + const char *pam_service = NULL; + const char *pam_user = NULL; + char *ccache = NULL; + char *username = NULL; + char *domain = NULL; + char *target = NULL; + char *upn = NULL; + uid_t uid; + uid_t euid; + errno_t ret; + + debug_enabled = false; + for (int i = 0; i < argc; i++) { + if (strcmp(argv[i], "debug") == 0) { + debug_enabled = true; + break; + } + } + + /* Get non-default ccache if specified, may be NULL. */ + ret = sss_cli_getenv("KRB5CCNAME", &ccache); + if (ret != EOK) { + ERROR(pamh, "sss_cli_getenv() call failed [%d]: %s", ret, strerror(ret)); + goto done; + } + + uid = getuid(); + euid = geteuid(); + + /* Read PAM data. */ + pam_service = get_item_as_string(pamh, PAM_SERVICE); + pam_user = get_item_as_string(pamh, PAM_USER); + if (pam_service == NULL || pam_user == NULL) { + ERROR(pamh, "Unable to get PAM data!"); + ret = EINVAL; + goto done; + } + + /* Initialize GSSAPI authentication with SSSD. Get user domain + * and target GSS service name. */ + TRACE(pamh, "Initializing GSSAPI authentication with SSSD"); + ret = sssd_gssapi_init(pamh, pam_service, pam_user, &username, &domain, + &target, &upn); + if (ret != EOK) { + goto done; + } + + /* PAM is often called from set-user-id applications (sudo, su). we want to + * make sure that we access credentials of the caller (real uid). */ + if (!switch_euid(pamh, euid, uid)) { + ret = EFAULT; + goto done; + } + + /* Authenticate the user by estabilishing security context. Authorization is + * expected to be done by other modules through pam_access. */ + TRACE(pamh, "Trying to establish security context"); + TRACE(pamh, "SSSD User name: %s", username); + TRACE(pamh, "User domain: %s", domain); + TRACE(pamh, "User principal: %s", upn); + TRACE(pamh, "Target name: %s", target); + TRACE(pamh, "Using ccache: %s", ccache == NULL ? "default" : ccache); + ret = sssd_establish_sec_ctx(pamh, ccache, pam_service, + username, domain, target, upn); + + /* Restore original euid. */ + if (!switch_euid(pamh, uid, euid)) { + ret = EFAULT; + goto done; + } + +done: + sss_pam_lock(); + sss_cli_close_socket(); + sss_pam_unlock(); + free(username); + free(domain); + free(target); + free(upn); + free(ccache); + + return errno_to_pam(pamh, ret); +} + +int pam_sm_setcred(pam_handle_t *pamh, int flags, int argc, const char **argv) +{ + return PAM_IGNORE; +} + +int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags, int argc, const char **argv) +{ + return PAM_IGNORE; +} + +int pam_sm_open_session(pam_handle_t *pamh, + int flags, + int argc, + const char **argv) +{ + return PAM_IGNORE; +} + +int pam_sm_close_session(pam_handle_t *pamh, + int flags, + int argc, + const char **argv) +{ + return PAM_IGNORE; +} + +int pam_sm_chauthtok(pam_handle_t *pamh, int flags, int argc, const char **argv) +{ + return PAM_IGNORE; +} diff --git a/src/sss_client/pam_sss_gss.exports b/src/sss_client/pam_sss_gss.exports new file mode 100644 index 0000000..9afa106 --- /dev/null +++ b/src/sss_client/pam_sss_gss.exports @@ -0,0 +1,4 @@ +{ + global: + *; +}; diff --git a/src/sss_client/pam_sss_prompt_config.c b/src/sss_client/pam_sss_prompt_config.c new file mode 100644 index 0000000..f336054 --- /dev/null +++ b/src/sss_client/pam_sss_prompt_config.c @@ -0,0 +1,701 @@ +/* + Authors: + Sumit Bose <sbose@redhat.com> + + Copyright (C) 2019 Red Hat + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 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 Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "config.h" +#include <stdlib.h> +#include <errno.h> + +#include "sss_cli.h" + +#include <libintl.h> +#define _(STRING) dgettext (PACKAGE, STRING) + +struct prompt_config_password { + char *prompt; +}; + +struct prompt_config_2fa { + char *prompt_1st; + char *prompt_2nd; +}; + +struct prompt_config_2fa_single { + char *prompt; +}; + +struct prompt_config_passkey { + char *prompt_inter; + char *prompt_touch; +}; + +struct prompt_config_sc_pin { + char *prompt; /* Currently not used */ +}; + +struct prompt_config { + enum prompt_config_type type; + union { + struct prompt_config_password password; + struct prompt_config_2fa two_fa; + struct prompt_config_2fa_single two_fa_single; + struct prompt_config_passkey passkey; + struct prompt_config_sc_pin sc_pin; + } data; +}; + +enum prompt_config_type pc_get_type(struct prompt_config *pc) +{ + if (pc != NULL && pc->type > PC_TYPE_INVALID && pc->type < PC_TYPE_LAST) { + return pc->type; + } + return PC_TYPE_INVALID; +} + +const char *pc_get_password_prompt(struct prompt_config *pc) +{ + if (pc != NULL && pc_get_type(pc) == PC_TYPE_PASSWORD) { + return pc->data.password.prompt; + } + return NULL; +} + +const char *pc_get_2fa_1st_prompt(struct prompt_config *pc) +{ + if (pc != NULL && pc_get_type(pc) == PC_TYPE_2FA) { + return pc->data.two_fa.prompt_1st; + } + return NULL; +} + +const char *pc_get_2fa_2nd_prompt(struct prompt_config *pc) +{ + if (pc != NULL && pc_get_type(pc) == PC_TYPE_2FA) { + return pc->data.two_fa.prompt_2nd; + } + return NULL; +} + +const char *pc_get_2fa_single_prompt(struct prompt_config *pc) +{ + if (pc != NULL && pc_get_type(pc) == PC_TYPE_2FA_SINGLE) { + return pc->data.two_fa_single.prompt; + } + return NULL; +} + +const char *pc_get_passkey_touch_prompt(struct prompt_config *pc) +{ + if (pc != NULL && (pc_get_type(pc) == PC_TYPE_PASSKEY)) { + return pc->data.passkey.prompt_touch; + } + return NULL; +} + +const char *pc_get_passkey_inter_prompt(struct prompt_config *pc) +{ + if (pc != NULL && (pc_get_type(pc) == PC_TYPE_PASSKEY)) { + return pc->data.passkey.prompt_inter; + } + return NULL; +} + +static void pc_free_passkey(struct prompt_config *pc) +{ + if (pc != NULL && pc_get_type(pc) == PC_TYPE_PASSKEY) { + free(pc->data.passkey.prompt_inter); + pc->data.passkey.prompt_inter = NULL; + free(pc->data.passkey.prompt_touch); + pc->data.passkey.prompt_touch = NULL; + } + return; +} + +static void pc_free_password(struct prompt_config *pc) +{ + if (pc != NULL && pc_get_type(pc) == PC_TYPE_PASSWORD) { + free(pc->data.password.prompt); + pc->data.password.prompt = NULL; + } + return; +} + +static void pc_free_2fa(struct prompt_config *pc) +{ + if (pc != NULL && pc_get_type(pc) == PC_TYPE_2FA) { + free(pc->data.two_fa.prompt_1st); + pc->data.two_fa.prompt_1st = NULL; + free(pc->data.two_fa.prompt_2nd); + pc->data.two_fa.prompt_2nd = NULL; + } + return; +} + +static void pc_free_2fa_single(struct prompt_config *pc) +{ + if (pc != NULL && pc_get_type(pc) == PC_TYPE_2FA_SINGLE) { + free(pc->data.two_fa_single.prompt); + pc->data.two_fa_single.prompt = NULL; + } + return; +} + +static void pc_free_sc_pin(struct prompt_config *pc) +{ + if (pc != NULL && pc_get_type(pc) == PC_TYPE_SC_PIN) { + free(pc->data.sc_pin.prompt); + pc->data.sc_pin.prompt = NULL; + } + return; +} + + +void pc_list_free(struct prompt_config **pc_list) +{ + size_t c; + + if (pc_list == NULL) { + return; + } + + for (c = 0; pc_list[c] != NULL; c++) { + switch (pc_list[c]->type) { + case PC_TYPE_PASSWORD: + pc_free_password(pc_list[c]); + break; + case PC_TYPE_2FA: + pc_free_2fa(pc_list[c]); + break; + case PC_TYPE_2FA_SINGLE: + pc_free_2fa_single(pc_list[c]); + break; + case PC_TYPE_SC_PIN: + pc_free_sc_pin(pc_list[c]); + break; + case PC_TYPE_PASSKEY: + pc_free_passkey(pc_list[c]); + break; + default: + return; + } + free(pc_list[c]); + pc_list[c] = NULL; + } + free(pc_list); +} + +static errno_t pc_list_add_pc(struct prompt_config ***pc_list, + struct prompt_config *pc) +{ + size_t c = 0; + struct prompt_config **pcl; + + for (c = 0; *pc_list != NULL && (*pc_list)[c] != NULL; c++); /* just counting */ + + pcl = realloc(*pc_list, (c + 2) * sizeof(struct prompt_config *)); + if (pcl == NULL) { + return ENOMEM; + } + pcl[c] = pc; + pcl[c + 1] = NULL; + + *pc_list = pcl; + + return EOK; +} + +#define DEFAULT_PASSWORD_PROMPT _("Password: ") +#define DEFAULT_2FA_SINGLE_PROMPT _("Password + Token value: ") +#define DEFAULT_2FA_PROMPT_1ST _("First Factor: ") +#define DEFAULT_2FA_PROMPT_2ND _("Second Factor: ") + +errno_t pc_list_add_password(struct prompt_config ***pc_list, + const char *prompt) +{ + struct prompt_config *pc; + int ret; + + if (pc_list == NULL) { + return EINVAL; + } + + pc = calloc(1, sizeof(struct prompt_config)); + if (pc == NULL) { + return ENOMEM; + } + + pc->type = PC_TYPE_PASSWORD; + pc->data.password.prompt = strdup(prompt != NULL ? prompt + : DEFAULT_PASSWORD_PROMPT); + if (pc->data.password.prompt == NULL) { + ret = ENOMEM; + goto done; + } + + ret = pc_list_add_pc(pc_list, pc); + if (ret != EOK) { + goto done; + } + + ret = EOK; + +done: + if (ret != EOK) { + free(pc->data.password.prompt); + free(pc); + } + + return ret; +} + +errno_t pc_list_add_2fa(struct prompt_config ***pc_list, + const char *prompt_1st, const char *prompt_2nd) +{ + struct prompt_config *pc; + int ret; + + if (pc_list == NULL) { + return EINVAL; + } + + pc = calloc(1, sizeof(struct prompt_config)); + if (pc == NULL) { + return ENOMEM; + } + + pc->type = PC_TYPE_2FA; + pc->data.two_fa.prompt_1st = strdup(prompt_1st != NULL ? prompt_1st + : DEFAULT_2FA_PROMPT_1ST); + if (pc->data.two_fa.prompt_1st == NULL) { + ret = ENOMEM; + goto done; + } + pc->data.two_fa.prompt_2nd = strdup(prompt_2nd != NULL ? prompt_2nd + : DEFAULT_2FA_PROMPT_2ND); + if (pc->data.two_fa.prompt_2nd == NULL) { + ret = ENOMEM; + goto done; + } + + ret = pc_list_add_pc(pc_list, pc); + if (ret != EOK) { + goto done; + } + + ret = EOK; + +done: + if (ret != EOK) { + free(pc->data.two_fa.prompt_1st); + free(pc->data.two_fa.prompt_2nd); + free(pc); + } + + return ret; +} + +errno_t pc_list_add_2fa_single(struct prompt_config ***pc_list, + const char *prompt) +{ + struct prompt_config *pc; + int ret; + + if (pc_list == NULL) { + return EINVAL; + } + + pc = calloc(1, sizeof(struct prompt_config)); + if (pc == NULL) { + return ENOMEM; + } + + pc->type = PC_TYPE_2FA_SINGLE; + pc->data.two_fa_single.prompt = strdup(prompt != NULL ? prompt + : DEFAULT_2FA_SINGLE_PROMPT); + if (pc->data.two_fa_single.prompt == NULL) { + ret = ENOMEM; + goto done; + } + + ret = pc_list_add_pc(pc_list, pc); + if (ret != EOK) { + goto done; + } + + ret = EOK; + +done: + if (ret != EOK) { + free(pc->data.two_fa_single.prompt); + free(pc); + } + + return ret; +} + +errno_t pc_list_add_passkey(struct prompt_config ***pc_list, + const char *prompt_inter, const char *prompt_touch) +{ + struct prompt_config *pc; + int ret; + + if (pc_list == NULL) { + return EINVAL; + } + + pc = calloc(1, sizeof(struct prompt_config)); + if (pc == NULL) { + return ENOMEM; + } + + pc->type = PC_TYPE_PASSKEY; + + pc->data.passkey.prompt_inter = strdup(prompt_inter != NULL ? prompt_inter + : ""); + if (pc->data.passkey.prompt_inter == NULL) { + ret = ENOMEM; + goto done; + } + pc->data.passkey.prompt_touch = strdup(prompt_touch != NULL ? prompt_touch + : ""); + if (pc->data.passkey.prompt_touch == NULL) { + ret = ENOMEM; + goto done; + } + + ret = pc_list_add_pc(pc_list, pc); + if (ret != EOK) { + goto done; + } + + ret = EOK; + +done: + if (ret != EOK) { + free(pc->data.passkey.prompt_inter); + free(pc->data.passkey.prompt_touch); + free(pc); + } + + return ret; +} + +errno_t pam_get_response_prompt_config(struct prompt_config **pc_list, int *len, + uint8_t **data) +{ + size_t c; + size_t l = 0; + uint8_t *d = NULL; + uint32_t uint32_val; + size_t rp; + + if (pc_list == NULL || *pc_list == NULL) { + return ENOENT; + } + + l += sizeof(uint32_t); + for (c = 0; pc_list[c] != NULL; c++) { + l += sizeof(uint32_t); + switch (pc_list[c]->type) { + case PC_TYPE_PASSWORD: + l += sizeof(uint32_t); + l += strlen(pc_list[c]->data.password.prompt); + break; + case PC_TYPE_2FA: + l += sizeof(uint32_t); + l += strlen(pc_list[c]->data.two_fa.prompt_1st); + l += sizeof(uint32_t); + l += strlen(pc_list[c]->data.two_fa.prompt_2nd); + break; + case PC_TYPE_2FA_SINGLE: + l += sizeof(uint32_t); + l += strlen(pc_list[c]->data.two_fa_single.prompt); + break; + case PC_TYPE_PASSKEY: + l += sizeof(uint32_t); + l += strlen(pc_list[c]->data.passkey.prompt_inter); + l += sizeof(uint32_t); + l += strlen(pc_list[c]->data.passkey.prompt_touch); + break; + case PC_TYPE_SC_PIN: + break; + default: + return EINVAL; + } + } + + d = malloc(l * sizeof(uint8_t)); + if (d == NULL) { + return ENOMEM; + } + + rp = 0; + uint32_val = c; + SAFEALIGN_COPY_UINT32(&d[rp], &uint32_val, &rp); + + for (c = 0; pc_list[c] != NULL; c++) { + uint32_val = pc_list[c]->type; + SAFEALIGN_COPY_UINT32(&d[rp], &uint32_val, &rp); + + switch (pc_list[c]->type) { + case PC_TYPE_PASSWORD: + SAFEALIGN_SET_UINT32(&d[rp], + strlen(pc_list[c]->data.password.prompt), &rp); + safealign_memcpy(&d[rp], pc_list[c]->data.password.prompt, + strlen(pc_list[c]->data.password.prompt), &rp); + break; + case PC_TYPE_2FA: + SAFEALIGN_SET_UINT32(&d[rp], + strlen(pc_list[c]->data.two_fa.prompt_1st), + &rp); + safealign_memcpy(&d[rp], pc_list[c]->data.two_fa.prompt_1st, + strlen(pc_list[c]->data.two_fa.prompt_1st), &rp); + SAFEALIGN_SET_UINT32(&d[rp], + strlen(pc_list[c]->data.two_fa.prompt_2nd), + &rp); + safealign_memcpy(&d[rp], pc_list[c]->data.two_fa.prompt_2nd, + strlen(pc_list[c]->data.two_fa.prompt_2nd), &rp); + break; + case PC_TYPE_2FA_SINGLE: + SAFEALIGN_SET_UINT32(&d[rp], + strlen(pc_list[c]->data.two_fa_single.prompt), + &rp); + safealign_memcpy(&d[rp], pc_list[c]->data.two_fa_single.prompt, + strlen(pc_list[c]->data.two_fa_single.prompt), + &rp); + break; + case PC_TYPE_PASSKEY: + SAFEALIGN_SET_UINT32(&d[rp], + strlen(pc_list[c]->data.passkey.prompt_inter), + &rp); + safealign_memcpy(&d[rp], pc_list[c]->data.passkey.prompt_inter, + strlen(pc_list[c]->data.passkey.prompt_inter), &rp); + SAFEALIGN_SET_UINT32(&d[rp], + strlen(pc_list[c]->data.passkey.prompt_touch), + &rp); + safealign_memcpy(&d[rp], pc_list[c]->data.passkey.prompt_touch, + strlen(pc_list[c]->data.passkey.prompt_touch), &rp); + break; + case PC_TYPE_SC_PIN: + break; + default: + free(d); + return EINVAL; + } + } + + if (rp != l) { + free(d); + return EFAULT; + } + + *data = d; + *len = l; + + return EOK; +} + +errno_t pc_list_from_response(int size, uint8_t *buf, + struct prompt_config ***pc_list) +{ + int ret; + uint32_t count; + uint32_t type; + uint32_t l; + size_t rp; + size_t c; + struct prompt_config **pl = NULL; + char *str; + char *str2; + + if (buf == NULL || size < 3 * sizeof(uint32_t)) { + return EINVAL; + } + + rp = 0; + SAFEALIGN_COPY_UINT32_CHECK(&count, buf + rp, size, &rp); + + for (c = 0; c < count; c++) { + /* Since we already know size < 3 * sizeof(uint32_t) this check should + * be safe and without over- or underflow. */ + if (rp > size - sizeof(uint32_t)) { + ret = EINVAL; + goto done; + } + SAFEALIGN_COPY_UINT32(&type, buf + rp, &rp); + + switch (type) { + case PC_TYPE_PASSWORD: + if (rp > size - sizeof(uint32_t)) { + ret = EINVAL; + goto done; + } + SAFEALIGN_COPY_UINT32(&l, buf + rp, &rp); + + if (l > size || rp > size - l) { + ret = EINVAL; + goto done; + } + str = strndup((char *) buf + rp, l); + if (str == NULL) { + ret = ENOMEM; + goto done; + } + rp += l; + + ret = pc_list_add_password(&pl, str); + free(str); + if (ret != EOK) { + goto done; + } + break; + case PC_TYPE_2FA: + if (rp > size - sizeof(uint32_t)) { + ret = EINVAL; + goto done; + } + SAFEALIGN_COPY_UINT32(&l, buf + rp, &rp); + + if (l > size || rp > size - l) { + ret = EINVAL; + goto done; + } + str = strndup((char *) buf + rp, l); + if (str == NULL) { + ret = ENOMEM; + goto done; + } + rp += l; + + if (rp > size - sizeof(uint32_t)) { + free(str); + ret = EINVAL; + goto done; + } + SAFEALIGN_COPY_UINT32(&l, buf + rp, &rp); + + if (l > size || rp > size - l) { + free(str); + ret = EINVAL; + goto done; + } + str2 = strndup((char *) buf + rp, l); + if (str2 == NULL) { + free(str); + ret = ENOMEM; + goto done; + } + rp += l; + + ret = pc_list_add_2fa(&pl, str, str2); + free(str); + free(str2); + if (ret != EOK) { + goto done; + } + break; + case PC_TYPE_PASSKEY: + if (rp > size - sizeof(uint32_t)) { + ret = EINVAL; + goto done; + } + SAFEALIGN_COPY_UINT32(&l, buf + rp, &rp); + + if (l > size || rp > size - l) { + ret = EINVAL; + goto done; + } + str = strndup((char *) buf + rp, l); + if (str == NULL) { + ret = ENOMEM; + goto done; + } + rp += l; + + if (rp > size - sizeof(uint32_t)) { + free(str); + ret = EINVAL; + goto done; + } + SAFEALIGN_COPY_UINT32(&l, buf + rp, &rp); + + if (l > size || rp > size - l) { + free(str); + ret = EINVAL; + goto done; + } + str2 = strndup((char *) buf + rp, l); + if (str2 == NULL) { + free(str); + ret = ENOMEM; + goto done; + } + rp += l; + + ret = pc_list_add_passkey(&pl, str, str2); + free(str); + free(str2); + if (ret != EOK) { + goto done; + } + break; + case PC_TYPE_2FA_SINGLE: + if (rp > size - sizeof(uint32_t)) { + ret = EINVAL; + goto done; + } + SAFEALIGN_COPY_UINT32(&l, buf + rp, &rp); + + if (l > size || rp > size - l) { + ret = EINVAL; + goto done; + } + str = strndup((char *) buf + rp, l); + if (str == NULL) { + ret = ENOMEM; + goto done; + } + rp += l; + + ret = pc_list_add_2fa_single(&pl, str); + free(str); + if (ret != EOK) { + goto done; + } + break; + case PC_TYPE_SC_PIN: + break; + default: + ret = EINVAL; + goto done; + } + } + + *pc_list = pl; + + ret = EOK; + +done: + if (ret != EOK) { + pc_list_free(pl); + pl = NULL; + } + + return ret; +} diff --git a/src/sss_client/ssh/sss_ssh_authorizedkeys.c b/src/sss_client/ssh/sss_ssh_authorizedkeys.c new file mode 100644 index 0000000..324e5e3 --- /dev/null +++ b/src/sss_client/ssh/sss_ssh_authorizedkeys.c @@ -0,0 +1,126 @@ +/* + Authors: + Jan Cholasta <jcholast@redhat.com> + + Copyright (C) 2012 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include <stdio.h> +#include <talloc.h> +#include <popt.h> +#include <signal.h> + +#include "util/util.h" +#include "util/crypto/sss_crypto.h" +#include "util/sss_ssh.h" +#include "sss_client/sss_cli.h" +#include "sss_client/ssh/sss_ssh_client.h" + +int main(int argc, const char **argv) +{ + TALLOC_CTX *mem_ctx = NULL; + int pc_debug = SSSDBG_TOOLS_DEFAULT; + const char *pc_domain = NULL; + const char *pc_user = NULL; + struct poptOption long_options[] = { + POPT_AUTOHELP + { "debug", '\0', POPT_ARG_INT | POPT_ARGFLAG_DOC_HIDDEN, &pc_debug, 0, + _("The debug level to run with"), NULL }, + { "domain", 'd', POPT_ARG_STRING, &pc_domain, 0, + _("The SSSD domain to use"), NULL }, + POPT_TABLEEND + }; + poptContext pc = NULL; + struct sss_ssh_ent *ent; + size_t i; + int ret; + + debug_prg_name = argv[0]; + + ret = set_locale(); + if (ret != EOK) { + DEBUG(SSSDBG_CRIT_FAILURE, + "set_locale() failed (%d): %s\n", ret, strerror(ret)); + ERROR("Error setting the locale\n"); + ret = EXIT_FAILURE; + goto fini; + } + + mem_ctx = talloc_new(NULL); + if (!mem_ctx) { + ERROR("Not enough memory\n"); + ret = EXIT_FAILURE; + goto fini; + } + + /* parse parameters */ + pc = poptGetContext(NULL, argc, argv, long_options, 0); + poptSetOtherOptionHelp(pc, "USER"); + while ((ret = poptGetNextOpt(pc)) > 0) + ; + + DEBUG_CLI_INIT(pc_debug); + + if (ret != -1) { + BAD_POPT_PARAMS(pc, poptStrerror(ret), ret, fini); + } + + pc_user = poptGetArg(pc); + if (pc_user == NULL) { + BAD_POPT_PARAMS(pc, _("User not specified\n"), ret, fini); + } + + /* look up public keys */ + ret = sss_ssh_get_ent(mem_ctx, SSS_SSH_GET_USER_PUBKEYS, + pc_user, pc_domain, NULL, &ent); + if (ret == ERR_NON_SSSD_USER) { + DEBUG(SSSDBG_MINOR_FAILURE, + "The user %s is valid, but not handled by sssd\n", pc_user); + ret = EXIT_SUCCESS; + goto fini; + } else if (ret != EOK) { + DEBUG(SSSDBG_CRIT_FAILURE, + "sss_ssh_get_ent() failed (%d): %s\n", ret, strerror(ret)); + ERROR("Error looking up public keys\n"); + ret = EXIT_FAILURE; + goto fini; + } + + /* if sshd closes its end of the pipe, we don't want sss_ssh_authorizedkeys + * to exit abruptly, but to finish gracefully instead because the valid + * key can be present in the data already written + */ + signal(SIGPIPE, SIG_IGN); + + /* print results */ + for (i = 0; i < ent->num_pubkeys; i++) { + ret = sss_ssh_print_pubkey(&ent->pubkeys[i]); + if (ret != EOK && ret != EINVAL) { + DEBUG(SSSDBG_CRIT_FAILURE, + "ssh_ssh_print_pubkey() failed (%d): %s\n", + ret, strerror(ret)); + goto fini; + } + } + + ret = EXIT_SUCCESS; + +fini: + poptFreeContext(pc); + talloc_free(mem_ctx); + + return ret; +} diff --git a/src/sss_client/ssh/sss_ssh_client.c b/src/sss_client/ssh/sss_ssh_client.c new file mode 100644 index 0000000..a198039 --- /dev/null +++ b/src/sss_client/ssh/sss_ssh_client.c @@ -0,0 +1,265 @@ +/* + Authors: + Jan Cholasta <jcholast@redhat.com> + + Copyright (C) 2012 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include "config.h" + +#include <errno.h> +#include <stdlib.h> +#include <stdio.h> +#include <talloc.h> + +#include <popt.h> +#include <locale.h> +#include <libintl.h> +#include <string.h> + +#include "util/util.h" +#include "util/crypto/sss_crypto.h" +#include "util/sss_ssh.h" +#include "sss_client/sss_cli.h" +#include "sss_client/ssh/sss_ssh_client.h" + +/* FIXME - split from tools_util to create a common function */ +void usage(poptContext pc, const char *error) +{ + poptPrintUsage(pc, stderr, 0); + if (error) fprintf(stderr, "%s", error); +} + +/* FIXME - split from tools_util to create a common function */ +int set_locale(void) +{ + char *c; + + c = setlocale(LC_ALL, ""); + if (c == NULL) { + /* If setlocale fails, continue with the default + * locale. */ + DEBUG(SSSDBG_MINOR_FAILURE, "Unable to set locale\n"); + } + + errno = 0; + c = bindtextdomain(PACKAGE, LOCALEDIR); + if (c == NULL) { + return errno; + } + + errno = 0; + c = textdomain(PACKAGE); + if (c == NULL) { + return errno; + } + + return EOK; +} + +/* SSH public key request: + * + * header: + * 0..3: flags (unsigned int, must be combination of SSS_SSH_REQ_* flags) + * 4..7: name length (unsigned int) + * 8..X: name (null-terminated UTF-8 string) + * alias (only included if flags & SSS_SSH_REQ_ALIAS): + * 0..3: alias length (unsigned int) + * 4..X: alias (null-terminated UTF-8 string) + * domain (ony included if flags & SSS_SSH_REQ_DOMAIN): + * 0..3: domain length (unsigned int, 0 means default domain) + * 4..X: domain (null-terminated UTF-8 string) + * + * SSH public key reply: + * + * header: + * 0..3: number of results (unsigned int) + * 4..7: reserved (unsigned int, must be 0) + * results (repeated for each result): + * 0..3: flags (unsigned int, must be 0) + * 4..7: name length (unsigned int) + * 8..(X-1): name (null-terminated UTF-8 string) + * X..(X+3): key length (unsigned int) + * (X+4)..Y: key (public key data) + */ +errno_t +sss_ssh_get_ent(TALLOC_CTX *mem_ctx, + enum sss_cli_command command, + const char *name, + const char *domain, + const char *alias, + struct sss_ssh_ent **result) +{ + TALLOC_CTX *tmp_ctx; + struct sss_ssh_ent *res = NULL; + errno_t ret; + uint32_t flags; + uint32_t name_len; + uint32_t alias_len = 0; + uint32_t domain_len; + size_t req_len; + uint8_t *req = NULL; + size_t c = 0; + struct sss_cli_req_data rd; + int req_ret, req_errno; + uint8_t *rep = NULL; + size_t rep_len; + uint32_t count, reserved, len, i; + + tmp_ctx = talloc_new(NULL); + if (!tmp_ctx) { + return ENOMEM; + } + + /* build request */ + flags = 0; + name_len = strlen(name)+1; + req_len = 2*sizeof(uint32_t) + name_len; + + if (alias) { + flags |= SSS_SSH_REQ_ALIAS; + alias_len = strlen(alias)+1; + req_len += sizeof(uint32_t) + alias_len; + } + + flags |= SSS_SSH_REQ_DOMAIN; + domain_len = domain ? (strlen(domain)+1) : 0; + req_len += sizeof(uint32_t) + domain_len; + + req = talloc_array(tmp_ctx, uint8_t, req_len); + if (!req) { + ret = ENOMEM; + goto done; + } + + SAFEALIGN_SET_UINT32(req+c, flags, &c); + SAFEALIGN_SET_UINT32(req+c, name_len, &c); + safealign_memcpy(req+c, name, name_len, &c); + if (alias) { + SAFEALIGN_SET_UINT32(req+c, alias_len, &c); + safealign_memcpy(req+c, alias, alias_len, &c); + } + SAFEALIGN_SET_UINT32(req+c, domain_len, &c); + if (domain_len > 0) { + safealign_memcpy(req+c, domain, domain_len, &c); + } + + /* send request */ + rd.data = req; + rd.len = req_len; + + req_ret = sss_ssh_make_request(command, &rd, &rep, &rep_len, &req_errno); + if (req_errno != EOK) { + ret = req_errno; + goto done; + } + if (req_ret != SSS_STATUS_SUCCESS) { + ret = EFAULT; + goto done; + } + + /* parse reply */ + c = 0; + if (rep_len < c + 2*sizeof(uint32_t)) { + ret = EINVAL; + goto done; + } + + SAFEALIGN_COPY_UINT32(&count, rep+c, &c); + + SAFEALIGN_COPY_UINT32(&reserved, rep+c, &c); + if (reserved != 0) { + ret = EINVAL; + goto done; + } + + res = talloc_zero(tmp_ctx, struct sss_ssh_ent); + if (!res) { + ret = ENOMEM; + goto done; + } + + if (count > 0) { + res->pubkeys = talloc_zero_array(res, struct sss_ssh_pubkey, count); + if (!res->pubkeys) { + ret = ENOMEM; + goto done; + } + + res->num_pubkeys = count; + } + + for (i = 0; i < count; i++) { + if (rep_len-c < 2*sizeof(uint32_t)) { + ret = EINVAL; + goto done; + } + + SAFEALIGN_COPY_UINT32(&flags, rep+c, &c); + if (flags != 0) { + ret = EINVAL; + goto done; + } + + SAFEALIGN_COPY_UINT32(&len, rep+c, &c); + + if (len > rep_len - c - sizeof(uint32_t)) { + ret = EINVAL; + goto done; + } + + if (!res->name) { + res->name = talloc_array(res, char, len); + if (!res->name) { + ret = ENOMEM; + goto done; + } + + safealign_memcpy(res->name, rep+c, len, &c); + if (strnlen(res->name, len) != len-1) { + ret = EINVAL; + goto done; + } + } else { + c += len; + } + + SAFEALIGN_COPY_UINT32(&len, rep+c, &c); + + if (len > rep_len - c) { + ret = EINVAL; + goto done; + } + + res->pubkeys[i].data = talloc_array(res, uint8_t, len); + if (!res->pubkeys[i].data) { + ret = ENOMEM; + goto done; + } + + safealign_memcpy(res->pubkeys[i].data, rep+c, len, &c); + res->pubkeys[i].data_len = len; + } + + *result = talloc_steal(mem_ctx, res); + ret = EOK; + +done: + talloc_free(tmp_ctx); + free(rep); + + return ret; +} diff --git a/src/sss_client/ssh/sss_ssh_client.h b/src/sss_client/ssh/sss_ssh_client.h new file mode 100644 index 0000000..5ad0643 --- /dev/null +++ b/src/sss_client/ssh/sss_ssh_client.h @@ -0,0 +1,41 @@ +/* + Authors: + Jan Cholasta <jcholast@redhat.com> + + Copyright (C) 2012 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#ifndef _SSS_SSH_CLIENT_H_ +#define _SSS_SSH_CLIENT_H_ + +void usage(poptContext pc, const char *error); +int set_locale(void); + +#define BAD_POPT_PARAMS(pc, msg, val, label) do { \ + usage(pc, msg); \ + val = EXIT_FAILURE; \ + goto label; \ +} while(0) + +errno_t +sss_ssh_get_ent(TALLOC_CTX *mem_ctx, + enum sss_cli_command command, + const char *name, + const char *domain, + const char *alias, + struct sss_ssh_ent **result); + +#endif /* _SSS_SSH_CLIENT_H_ */ diff --git a/src/sss_client/ssh/sss_ssh_knownhostsproxy.c b/src/sss_client/ssh/sss_ssh_knownhostsproxy.c new file mode 100644 index 0000000..170ba30 --- /dev/null +++ b/src/sss_client/ssh/sss_ssh_knownhostsproxy.c @@ -0,0 +1,347 @@ +/* + Authors: + Jan Cholasta <jcholast@redhat.com> + + Copyright (C) 2012 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include <stdio.h> +#include <talloc.h> +#include <unistd.h> +#include <fcntl.h> +#include <poll.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <netinet/tcp.h> +#include <netdb.h> +#include <popt.h> + +#include "util/util.h" +#include "util/crypto/sss_crypto.h" +#include "util/sss_ssh.h" +#include "sss_client/sss_cli.h" +#include "sss_client/ssh/sss_ssh_client.h" + +#define BUFFER_SIZE 8192 + +/* connect to server using socket */ +static int +connect_socket(int family, struct sockaddr *addr, size_t addr_len, int *sd) +{ + int sock = -1; + int ret; + + /* create socket */ + sock = socket(family, SOCK_STREAM, IPPROTO_TCP); + if (sock == -1) { + ret = errno; + DEBUG(SSSDBG_OP_FAILURE, "socket() failed (%d): %s\n", + ret, strerror(ret)); + goto done; + } + + /* connect to the server */ + ret = connect(sock, addr, addr_len); + if (ret == -1) { + ret = errno; + DEBUG(SSSDBG_OP_FAILURE, "connect() failed (%d): %s\n", + ret, strerror(ret)); + goto done; + } + +done: + if (ret != 0) { + if (sock >= 0) { + close(sock); + } + } else { + *sd = sock; + } + return ret; +} + +static int proxy_data(int sock) +{ + struct pollfd fds[2]; + char buffer[BUFFER_SIZE]; + int i; + ssize_t res; + int ret; + + /* set O_NONBLOCK on standard input */ + ret = sss_fd_nonblocking(0); + if (ret != EOK) { + DEBUG(SSSDBG_OP_FAILURE, "Failed to make fd=0 nonblocking\n"); + goto done; + } + + /* set O_NONBLOCK on the socket */ + ret = sss_fd_nonblocking(sock); + if (ret != EOK) { + DEBUG(SSSDBG_OP_FAILURE, "Failed to make socket nonblocking\n"); + goto done; + } + + fds[0].fd = 0; + fds[0].events = POLLIN; + fds[1].fd = sock; + fds[1].events = POLLIN; + + while (1) { + ret = poll(fds, 2, -1); + if (ret == -1) { + ret = errno; + if (ret == EINTR || ret == EAGAIN) { + continue; + } + DEBUG(SSSDBG_OP_FAILURE, + "poll() failed (%d): %s\n", ret, strerror(ret)); + goto done; + } + + /* read from standard input & write to socket */ + /* read from socket & write to standard output */ + for (i = 0; i < 2; i++) { + if (fds[i].revents & POLLIN) { + res = read(fds[i].fd, buffer, BUFFER_SIZE); + if (res == -1) { + ret = errno; + if (ret == EAGAIN || ret == EINTR || ret == EWOULDBLOCK) { + continue; + } + DEBUG(SSSDBG_OP_FAILURE, + "read() failed (%d): %s\n", ret, strerror(ret)); + goto done; + } else if (res == 0) { + ret = EOK; + goto done; + } + + errno = 0; + res = sss_atomic_write_s(i == 0 ? sock : 1, buffer, res); + ret = errno; + if (res == -1) { + DEBUG(SSSDBG_OP_FAILURE, + "sss_atomic_write_s() failed (%d): %s\n", + ret, strerror(ret)); + goto done; + } else if (ret == EPIPE) { + ret = EOK; + goto done; + } + } + if (fds[i].revents & POLLHUP) { + ret = EOK; + goto done; + } + } + } + +done: + close(sock); + return ret; +} + +/* connect to server using proxy command */ +static int +connect_proxy_command(char **args) +{ + int ret; + + execv(args[0], (char * const *)args); + + ret = errno; + DEBUG(SSSDBG_OP_FAILURE, "execv() failed (%d): %s\n", + ret, strerror(ret)); + + return ret; +} + +int main(int argc, const char **argv) +{ + TALLOC_CTX *mem_ctx = NULL; + int pc_debug = SSSDBG_TOOLS_DEFAULT; + int pc_port = 22; + const char *pc_domain = NULL; + const char *pc_host = NULL; + const char **pc_args = NULL; + int pc_pubkeys = 0; + struct poptOption long_options[] = { + POPT_AUTOHELP + { "debug", '\0', POPT_ARG_INT | POPT_ARGFLAG_DOC_HIDDEN, &pc_debug, 0, + _("The debug level to run with"), NULL }, + { "port", 'p', POPT_ARG_INT, &pc_port, 0, + _("The port to use to connect to the host"), NULL }, + { "domain", 'd', POPT_ARG_STRING, &pc_domain, 0, + _("The SSSD domain to use"), NULL }, + { "pubkey", 'k', POPT_ARG_NONE, &pc_pubkeys, 0, + _("Print the host ssh public keys"), NULL }, + POPT_TABLEEND + }; + poptContext pc = NULL; + char strport[6]; + struct addrinfo ai_hint; + struct addrinfo *ai = NULL; + char canonhost[NI_MAXHOST]; + const char *host = NULL; + struct sss_ssh_ent *ent = NULL; + int ret; + + debug_prg_name = argv[0]; + + ret = set_locale(); + if (ret != EOK) { + DEBUG(SSSDBG_CRIT_FAILURE, + "set_locale() failed (%d): %s\n", ret, strerror(ret)); + ret = EXIT_FAILURE; + goto fini; + } + + mem_ctx = talloc_new(NULL); + if (!mem_ctx) { + DEBUG(SSSDBG_CRIT_FAILURE, "Not enough memory\n"); + ret = EXIT_FAILURE; + goto fini; + } + + /* parse parameters */ + pc = poptGetContext(NULL, argc, argv, long_options, 0); + poptSetOtherOptionHelp(pc, "HOST [PROXY_COMMAND]"); + while ((ret = poptGetNextOpt(pc)) > 0) + ; + + DEBUG_CLI_INIT(pc_debug); + + if (ret != -1) { + BAD_POPT_PARAMS(pc, poptStrerror(ret), ret, fini); + } + + if (pc_port < 1 || pc_port > 65535) { + BAD_POPT_PARAMS(pc, _("Invalid port\n"), ret, fini); + } + + pc_host = poptGetArg(pc); + if (pc_host == NULL) { + BAD_POPT_PARAMS(pc, _("Host not specified\n"), ret, fini); + } + + pc_args = poptGetArgs(pc); + if (pc_args && pc_args[0] && pc_args[0][0] != '/') { + BAD_POPT_PARAMS(pc, + _("The path to the proxy command must be absolute\n"), + ret, fini); + } + + /* canonicalize hostname */ + snprintf(strport, 6, "%d", pc_port); + + memset(&ai_hint, 0, sizeof(struct addrinfo)); + ai_hint.ai_family = AF_UNSPEC; + ai_hint.ai_socktype = SOCK_STREAM; + ai_hint.ai_protocol = IPPROTO_TCP; + ai_hint.ai_flags = AI_ADDRCONFIG | AI_NUMERICHOST | AI_NUMERICSERV; + + ret = getaddrinfo(pc_host, strport, &ai_hint, &ai); + if (ret) { + ai_hint.ai_flags = AI_ADDRCONFIG | AI_CANONNAME | AI_NUMERICSERV; + + ret = getaddrinfo(pc_host, strport, &ai_hint, &ai); + if (ret) { + DEBUG(SSSDBG_OP_FAILURE, + "getaddrinfo() failed (%d): %s\n", ret, gai_strerror(ret)); + } else { + host = ai->ai_canonname; + } + } else { + ret = getnameinfo(ai->ai_addr, ai->ai_addrlen, + canonhost, NI_MAXHOST, NULL, 0, NI_NAMEREQD); + if (ret) { + DEBUG(SSSDBG_OP_FAILURE, + "getnameinfo() failed (%d): %s\n", ret, gai_strerror(ret)); + } else { + host = canonhost; + } + } + + if (host) { + /* look up public keys */ + ret = sss_ssh_get_ent(mem_ctx, SSS_SSH_GET_HOST_PUBKEYS, + host, pc_domain, pc_host, &ent); + if (ret != EOK) { + DEBUG(SSSDBG_OP_FAILURE, + "sss_ssh_get_ent() failed (%d): %s\n", ret, strerror(ret)); + } + } + + if (pc_pubkeys) { + /* print results */ + if (ent != NULL) { + for (size_t i = 0; i < ent->num_pubkeys; i++) { + ret = sss_ssh_print_pubkey(&ent->pubkeys[i]); + if (ret != EOK && ret != EINVAL) { + DEBUG(SSSDBG_CRIT_FAILURE, + "ssh_ssh_print_pubkey() failed (%d): %s\n", + ret, strerror(ret)); + ret = EXIT_FAILURE; + goto fini; + } + } + } + + ret = EXIT_SUCCESS; + goto fini; + } + + /* connect to server */ + if (pc_args) { + ret = connect_proxy_command(discard_const(pc_args)); + } else if (ai) { + /* Try all IP addresses before giving up */ + int socket_descriptor = -1; + for (struct addrinfo *ti = ai; ti != NULL; ti = ti->ai_next) { + ret = connect_socket(ti->ai_family, ti->ai_addr, ti->ai_addrlen, + &socket_descriptor); + if (ret == EOK) { + break; + } + } + + if (ret == EOK) { + ret = proxy_data(socket_descriptor); + if (ret != EOK) { + ERROR("sss_ssh_knownhostsproxy: unable to proxy data: " + "%s\n", strerror(ret)); + } + } else { + ERROR("sss_ssh_knownhostsproxy: connect to host %s port %d: " + "%s\n", pc_host, pc_port, strerror(ret)); + } + } else { + ERROR("sss_ssh_knownhostsproxy: Could not resolve hostname %s\n", + pc_host); + ret = EFAULT; + } + + ret = (ret == EOK) ? EXIT_SUCCESS : EXIT_FAILURE; + +fini: + poptFreeContext(pc); + if (ai) freeaddrinfo(ai); + talloc_free(mem_ctx); + + return ret; +} diff --git a/src/sss_client/sss_cli.h b/src/sss_client/sss_cli.h new file mode 100644 index 0000000..4614612 --- /dev/null +++ b/src/sss_client/sss_cli.h @@ -0,0 +1,816 @@ +/* + SSSD + + Client Interface for NSS and PAM. + + Authors: + Simo Sorce <ssorce@redhat.com> + + Copyright (C) Red Hat, Inc 2007 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 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 Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef _SSSCLI_H +#define _SSSCLI_H + +#include <nss.h> +#include <pwd.h> +#include <grp.h> +#include <string.h> +#include <stdint.h> +#include <limits.h> + +#include "shared/safealign.h" + +#ifndef HAVE_ERRNO_T +#define HAVE_ERRNO_T +typedef int errno_t; +#endif + + +#ifndef EOK +#define EOK 0 +#endif + +#define SSS_NSS_PROTOCOL_VERSION 1 +#define SSS_PAM_PROTOCOL_VERSION 3 +#define SSS_SUDO_PROTOCOL_VERSION 1 +#define SSS_AUTOFS_PROTOCOL_VERSION 1 +#define SSS_SSH_PROTOCOL_VERSION 0 +#define SSS_PAC_PROTOCOL_VERSION 1 + +#ifdef LOGIN_NAME_MAX +#define SSS_NAME_MAX LOGIN_NAME_MAX +#else +#define SSS_NAME_MAX 256 +#endif + +/** + * @defgroup sss_cli_command SSS client commands + * @{ + */ + +/** The allowed commands an SSS client can send to the SSSD */ + +enum sss_cli_command { +/* null */ + SSS_CLI_NULL = 0x0000, + +/* version */ + SSS_GET_VERSION = 0x0001, + +/* passwd */ + + SSS_NSS_GETPWNAM = 0x0011, + SSS_NSS_GETPWUID = 0x0012, + SSS_NSS_SETPWENT = 0x0013, + SSS_NSS_GETPWENT = 0x0014, + SSS_NSS_ENDPWENT = 0x0015, + + SSS_NSS_GETPWNAM_EX = 0x0019, + SSS_NSS_GETPWUID_EX = 0x001A, + +/* group */ + + SSS_NSS_GETGRNAM = 0x0021, + SSS_NSS_GETGRGID = 0x0022, + SSS_NSS_SETGRENT = 0x0023, + SSS_NSS_GETGRENT = 0x0024, + SSS_NSS_ENDGRENT = 0x0025, + SSS_NSS_INITGR = 0x0026, + + SSS_NSS_GETGRNAM_EX = 0x0029, + SSS_NSS_GETGRGID_EX = 0x002A, + SSS_NSS_INITGR_EX = 0x002E, + +#if 0 +/* aliases */ + + SSS_NSS_GETALIASBYNAME = 0x0031, + SSS_NSS_GETALIASBYPORT = 0x0032, + SSS_NSS_SETALIASENT = 0x0033, + SSS_NSS_GETALIASENT = 0x0034, + SSS_NSS_ENDALIASENT = 0x0035, + +/* ethers */ + + SSS_NSS_GETHOSTTON = 0x0041, + SSS_NSS_GETNTOHOST = 0x0042, + SSS_NSS_SETETHERENT = 0x0043, + SSS_NSS_GETETHERENT = 0x0044, + SSS_NSS_ENDETHERENT = 0x0045, +#endif + +/* hosts */ + + SSS_NSS_GETHOSTBYNAME = 0x0051, + SSS_NSS_GETHOSTBYNAME2 = 0x0052, + SSS_NSS_GETHOSTBYADDR = 0x0053, + SSS_NSS_SETHOSTENT = 0x0054, + SSS_NSS_GETHOSTENT = 0x0055, + SSS_NSS_ENDHOSTENT = 0x0056, + +/* netgroup */ + + SSS_NSS_SETNETGRENT = 0x0061, + SSS_NSS_GETNETGRENT = 0x0062, + SSS_NSS_ENDNETGRENT = 0x0063, + +/* networks */ + + SSS_NSS_GETNETBYNAME = 0x0071, + SSS_NSS_GETNETBYADDR = 0x0072, + SSS_NSS_SETNETENT = 0x0073, + SSS_NSS_GETNETENT = 0x0074, + SSS_NSS_ENDNETENT = 0x0075, + +#if 0 +/* protocols */ + + SSS_NSS_GETPROTOBYNAME = 0x0081, + SSS_NSS_GETPROTOBYNUM = 0x0082, + SSS_NSS_SETPROTOENT = 0x0083, + SSS_NSS_GETPROTOENT = 0x0084, + SSS_NSS_ENDPROTOENT = 0x0085, + +/* rpc */ + + SSS_NSS_GETRPCBYNAME = 0x0091, + SSS_NSS_GETRPCBYNUM = 0x0092, + SSS_NSS_SETRPCENT = 0x0093, + SSS_NSS_GETRPCENT = 0x0094, + SSS_NSS_ENDRPCENT = 0x0095, +#endif + +/* services */ + + SSS_NSS_GETSERVBYNAME = 0x00A1, + SSS_NSS_GETSERVBYPORT = 0x00A2, + SSS_NSS_SETSERVENT = 0x00A3, + SSS_NSS_GETSERVENT = 0x00A4, + SSS_NSS_ENDSERVENT = 0x00A5, + +#if 0 +/* shadow */ + + SSS_NSS_GETSPNAM = 0x00B1, + SSS_NSS_GETSPUID = 0x00B2, + SSS_NSS_SETSPENT = 0x00B3, + SSS_NSS_GETSPENT = 0x00B4, + SSS_NSS_ENDSPENT = 0x00B5, +#endif + +/* SUDO */ + SSS_SUDO_GET_SUDORULES = 0x00C1, + SSS_SUDO_GET_DEFAULTS = 0x00C2, + +/* autofs */ + SSS_AUTOFS_SETAUTOMNTENT = 0x00D1, + SSS_AUTOFS_GETAUTOMNTENT = 0x00D2, + SSS_AUTOFS_GETAUTOMNTBYNAME = 0x00D3, + SSS_AUTOFS_ENDAUTOMNTENT = 0x00D4, + +/* SSH */ + SSS_SSH_GET_USER_PUBKEYS = 0x00E1, + SSS_SSH_GET_HOST_PUBKEYS = 0x00E2, + +/* PAM related calls */ + SSS_PAM_AUTHENTICATE = 0x00F1, /**< see pam_sm_authenticate(3) for + * details. + * + * Additionally we allow sssd to send + * the return code PAM_NEW_AUTHTOK_REQD + * during authentication if the + * authentication was successful but + * the authentication token is expired. + * To meet the standards of libpam we + * return PAM_SUCCESS for + * authentication and set a flag so + * that the account management module + * can return PAM_NEW_AUTHTOK_REQD if + * sssd return success for account + * management. We do this to reduce the + * communication with external servers, + * because there are cases, e.g. + * Kerberos authentication, where the + * information that the password is + * expired is already available during + * authentication. */ + SSS_PAM_SETCRED = 0x00F2, /**< see pam_sm_setcred(3) for + * details */ + SSS_PAM_ACCT_MGMT = 0x00F3, /**< see pam_sm_acct_mgmt(3) for + * details */ + SSS_PAM_OPEN_SESSION = 0x00F4, /**< see pam_sm_open_session(3) for + * details */ + SSS_PAM_CLOSE_SESSION = 0x00F5, /**< see pam_sm_close_session(3) for + *details */ + SSS_PAM_CHAUTHTOK = 0x00F6, /**< second run of the password change + * operation where the PAM_UPDATE_AUTHTOK + * flag is set and the real change may + * happen, see pam_sm_chauthtok(3) for + * details */ + SSS_PAM_CHAUTHTOK_PRELIM = 0x00F7, /**< first run of the password change + * operation where the PAM_PRELIM_CHECK + * flag is set, see pam_sm_chauthtok(3) + * for details */ + SSS_CMD_RENEW = 0x00F8, /**< Renew a credential with a limited + * lifetime, e.g. a Kerberos Ticket + * Granting Ticket (TGT) */ + SSS_PAM_PREAUTH = 0x00F9, /**< Request which can be run before + * an authentication request to find + * out which authentication methods + * are available for the given user. */ + SSS_GSSAPI_INIT = 0x00FA, /**< Initialize GSSAPI authentication. */ + SSS_GSSAPI_SEC_CTX = 0x00FB, /**< Establish GSSAPI security ctx. */ + +/* PAC responder calls */ + SSS_PAC_ADD_PAC_USER = 0x0101, + +/* ID-SID mapping calls */ +SSS_NSS_GETSIDBYNAME = 0x0111, /**< Takes a zero terminated fully qualified + name and returns the zero terminated + string representation of the SID of the + object with the given name. */ +SSS_NSS_GETSIDBYID = 0x0112, /**< Takes an unsigned 32bit integer (POSIX ID) + and returns the zero terminated string + representation of the SID of the object + with the given ID. */ +SSS_NSS_GETNAMEBYSID = 0x0113, /**< Takes the zero terminated string + representation of a SID and returns the + zero terminated fully qualified name of + the related object. */ +SSS_NSS_GETIDBYSID = 0x0114, /**< Takes the zero terminated string + representation of a SID and returns and + returns the POSIX ID of the related object + as unsigned 32bit integer value and + another unsigned 32bit integer value + indicating the type (unknown, user, group, + both) of the object. */ +SSS_NSS_GETORIGBYNAME = 0x0115, /**< Takes a zero terminated fully qualified + name and returns a list of zero + terminated strings with key-value pairs + where the first string is the key and + second the value. Hence the list should + have an even number of strings, if not + the whole list is invalid. */ +SSS_NSS_GETNAMEBYCERT = 0x0116, /**< Takes the zero terminated string + of the base64 encoded DER representation + of a X509 certificate and returns the zero + terminated fully qualified name of the + related object. */ +SSS_NSS_GETLISTBYCERT = 0x0117, /**< Takes the zero terminated string + of the base64 encoded DER representation + of a X509 certificate and returns a list + of zero terminated fully qualified names + of the related objects. */ +SSS_NSS_GETSIDBYUID = 0x0118, /**< Takes an unsigned 32bit integer (POSIX UID) + and return the zero terminated string + representation of the SID of the object + with the given UID. */ +SSS_NSS_GETSIDBYGID = 0x0119, /**< Takes an unsigned 32bit integer (POSIX GID) + and return the zero terminated string + representation of the SID of the object + with the given UID. */ +SSS_NSS_GETORIGBYUSERNAME = 0x011A, /**< Takes a zero terminated fully qualified + user name and returns a list of zero + terminated strings with key-value pairs + where the first string is the key and + second the value. Hence the list should + have an even number of strings, if not + the whole list is invalid. */ +SSS_NSS_GETORIGBYGROUPNAME = 0x011B, /**< Takes a zero terminated fully qualified + group name and returns a list of zero + terminated strings with key-value pairs + where the first string is the key and + second the value. Hence the list should + have an even number of strings, if not + the whole list is invalid. */ +SSS_NSS_GETSIDBYUSERNAME = 0x011C, /**< Takes a zero terminated fully qualified + name and returns the zero terminated + string representation of the SID of the + user with the given name. */ +SSS_NSS_GETSIDBYGROUPNAME = 0x011D, /**< Takes a zero terminated fully qualified + name and returns the zero terminated + string representation of the SID of the + group with the given name. */ + + +/* subid */ + SSS_NSS_GET_SUBID_RANGES = 0x0130, /**< Requests both subuid and subgid ranges + defined for a user. */ +}; + +/** + * @} + */ /* end of group sss_cli_command */ + + +/** + * @defgroup sss_pam SSSD and PAM + * + * SSSD offers authentication and authorization via PAM + * + * The SSSD provides a PAM client modules pam_sss which can be called from the + * PAM stack of the operation system. pam_sss will collect all the data about + * the user from the PAM stack and sends them via a socket to the PAM + * responder of the SSSD. The PAM responder selects the appropriate backend + * and forwards the data via D-BUS to the backend. The backend preforms the + * requested operation and sends the result expressed by a PAM return value + * and optional additional information back to the PAM responder. Finally the + * PAM responder forwards the response back to the client. + * + * @{ + */ + +/** + * @} + */ /* end of group sss_pam */ + +/** + * @defgroup sss_authtok_type Authentication Tokens + * @ingroup sss_pam + * + * To indicate to the components of the SSSD how to handle the authentication + * token the client sends the type of the authentication token to the SSSD. + * + * @{ + */ + +/** The different types of authentication tokens */ + +enum sss_authtok_type { + SSS_AUTHTOK_TYPE_EMPTY = 0x0000, /**< No authentication token + * available */ + SSS_AUTHTOK_TYPE_PASSWORD = 0x0001, /**< Authentication token is a + * password, it may or may no contain + * a trailing \\0 */ + SSS_AUTHTOK_TYPE_CCFILE = 0x0002, /**< Authentication token is a path to + * a Kerberos credential cache file, + * it may or may no contain + * a trailing \\0 */ + SSS_AUTHTOK_TYPE_2FA = 0x0003, /**< Authentication token has two + * factors, they may or may no contain + * a trailing \\0 */ + SSS_AUTHTOK_TYPE_SC_PIN = 0x0004, /**< Authentication token is a Smart + * Card PIN, it may or may no contain + * a trailing \\0 */ + SSS_AUTHTOK_TYPE_SC_KEYPAD = 0x0005, /**< Authentication token indicates + * Smart Card authentication is used + * and that the PIN will be entered + * at the card reader. */ + SSS_AUTHTOK_TYPE_2FA_SINGLE = 0x0006, /**< Authentication token has two + * factors in a single string, it may + * or may no contain a trailing \\0 */ + SSS_AUTHTOK_TYPE_OAUTH2 = 0x0007, /**< Authentication token is a + * oauth2 token for presented + * challenge that is acquired from + * Kerberos. It may or may no + * contain a trailing \\0 */ + SSS_AUTHTOK_TYPE_PASSKEY = 0x0008, /**< Authentication token is a Passkey + * PIN, it may or may not contain + * a trailing \\0 */ + SSS_AUTHTOK_TYPE_PASSKEY_KRB = 0x0009, /**< Authentication token contains + * Passkey data used for Kerberos + * pre-authentication */ + SSS_AUTHTOK_TYPE_PASSKEY_REPLY = 0x0010, /**< Authentication token contains + * Passkey reply data presented as + * a kerberos challenge answer */ +}; + +/** + * @} + */ /* end of group sss_authtok_type */ + +#define SSS_START_OF_PAM_REQUEST 0x4d415049 +#define SSS_END_OF_PAM_REQUEST 0x4950414d + +#define PAM_PREAUTH_INDICATOR PUBCONF_PATH"/pam_preauth_available" + +enum pam_item_type { + SSS_PAM_ITEM_EMPTY = 0x0000, + SSS_PAM_ITEM_USER, + SSS_PAM_ITEM_SERVICE, + SSS_PAM_ITEM_TTY, + SSS_PAM_ITEM_RUSER, + SSS_PAM_ITEM_RHOST, + SSS_PAM_ITEM_AUTHTOK, + SSS_PAM_ITEM_NEWAUTHTOK, + SSS_PAM_ITEM_CLI_LOCALE, + SSS_PAM_ITEM_CLI_PID, + SSS_PAM_ITEM_CHILD_PID, + SSS_PAM_ITEM_REQUESTED_DOMAINS, + SSS_PAM_ITEM_FLAGS, +}; + +#define PAM_CLI_FLAGS_USE_FIRST_PASS (1 << 0) +#define PAM_CLI_FLAGS_FORWARD_PASS (1 << 1) +#define PAM_CLI_FLAGS_USE_AUTHTOK (1 << 2) +#define PAM_CLI_FLAGS_IGNORE_UNKNOWN_USER (1 << 3) +#define PAM_CLI_FLAGS_IGNORE_AUTHINFO_UNAVAIL (1 << 4) +#define PAM_CLI_FLAGS_USE_2FA (1 << 5) +#define PAM_CLI_FLAGS_ALLOW_MISSING_NAME (1 << 6) +#define PAM_CLI_FLAGS_PROMPT_ALWAYS (1 << 7) +#define PAM_CLI_FLAGS_TRY_CERT_AUTH (1 << 8) +#define PAM_CLI_FLAGS_REQUIRE_CERT_AUTH (1 << 9) + +#define SSS_NSS_MAX_ENTRIES 256 +#define SSS_NSS_HEADER_SIZE (sizeof(uint32_t) * 4) +struct sss_cli_req_data { + size_t len; + const void *data; +}; + +/* this is in milliseconds, wait up to 300 seconds */ +#define SSS_CLI_SOCKET_TIMEOUT 300000 + +enum sss_status { + SSS_STATUS_TRYAGAIN, + SSS_STATUS_UNAVAIL, + SSS_STATUS_SUCCESS +}; + +/** + * @defgroup sss_pam_cli Responses to the PAM client + * @ingroup sss_pam + * @{ + */ + +/** + * @defgroup response_type Messages from the server + * @ingroup sss_pam_cli + * + * SSSD can send different kind of information back to the client. + * A response from the SSSD can contain 0 or more messages. Each message + * contains a type tag and the size of the message data, both are unsigned + * 32-bit integer values, followed be the message specific data. + * + * If the message is generated by a backend it is send back to the PAM + * responder via a D-BUS message in an array of D-BUS structs. The struct + * consists of a DBUS_TYPE_UINT32 for the tag and a DBUS_TYPE_ARRAY to hold + * the message. + * + * Examples: + * - #SSS_PAM_ENV_ITEM, + uint32_t | uint32_t | uint8_t[4] + ----------|----------|------------ + 0x03 | 0x04 | a=b\\0 + * @{ + */ + +/** Types of different messages */ + +enum response_type { + SSS_PAM_SYSTEM_INFO = 0x01, /**< Message for the system log. + * @param String, zero terminated. */ + SSS_PAM_DOMAIN_NAME, /**< Name of the domain the user belongs too. + * This messages is generated by the PAM responder. + * @param String, zero terminated, with the domain + * name. */ + SSS_PAM_ENV_ITEM, /**< Set and environment variable with pam_putenv(3). + * @param String, zero terminated, of the form + * name=value. See pam_putenv(3) for details. */ + SSS_ENV_ITEM, /**< Set and environment variable with putenv(3). + * @param String, zero terminated, of the form + * name=value. See putenv(3) for details. */ + SSS_ALL_ENV_ITEM, /**< Set and environment variable with putenv(3) and + * pam_putenv(3). + * @param String, zero terminated, of the form + * name=value. See putenv(3) and pam_putenv(3) for + * details. */ + SSS_PAM_USER_INFO, /**< A message which should be displayed to the user. + * @param User info message, see #user_info_type + * for details. */ + SSS_PAM_TEXT_MSG, /**< A plain text message which should be displayed to + * the user. This should only be used in the case where + * it is not possible to use SSS_PAM_USER_INFO. + * @param A zero terminated string. */ + SSS_PAM_OTP_INFO, /**< A message which optionally may contain the name + * of the vendor, the ID of an OTP token and a + * challenge. + * @param Three zero terminated strings, if one of the + * strings is missing the message will contain only + * an empty string (\0) for that component. */ + SSS_PAM_CERT_INFO, /**< A message indicating that Smartcard/certificate + * based authentication is available and contains + * details about the found Smartcard. + * @param user name, zero terminated + * @param token name, zero terminated + * @param PKCS#11 module name, zero terminated + * @param key id, zero terminated */ + SSS_OTP, /**< Indicates that the authtok was a OTP, so don't + * cache it. There is no message. + * @param None. */ + SSS_PASSWORD_PROMPTING, /**< Indicates that password prompting is possible. + * This might be used together with + * SSS_PAM_OTP_INFO to determine the type of + * prompting. There is no message. + * @param None. */ + SSS_CERT_AUTH_PROMPTING, /**< Indicates that on the server side + * Smartcard/certificate based authentication is + * available for the selected account. This might + * be used together with other prompting options + * to determine the type of prompting. + * @param None. */ + SSS_PAM_CERT_INFO_WITH_HINT, /**< Same as SSS_PAM_CERT_INFO but user name + * might be missing and should be prompted + * for. */ + SSS_PAM_PROMPT_CONFIG, /**< Contains data which controls which credentials + * are expected and how the user is prompted for + * them. */ + SSS_CHILD_KEEP_ALIVE, /**< Indicates that the child process is kept alived + * and further communication must be done with the + * same child. The message is the pid of the child + * process. */ + SSS_PAM_OAUTH2_INFO, /**< A message which contains the oauth2 + * parameters for the user. + * @param Three zero terminated strings: + * - verification_uri + * - verification_uri_complete + * - user_code + */ + SSS_PAM_PASSKEY_INFO, /**< Indicates that passkey authentication is available. + * including a parameter string which dictates whether + * prompting for PIN is needed. + * @param + * - prompt_pin + */ + SSS_PAM_PASSKEY_KRB_INFO, /**< A message containing the passkey parameters + * for the user. The key is the cryptographic challenge + * used as the key to the passkey hash table entry. + * @param + * - user verification (string) + * - key (string) + */ +}; + +/** + * @defgroup user_info_type User info messages + * @ingroup response_type + * + * To achieve a consistent user experience and to facilitate + * internationalization all messages show to the user are generate by the PAM + * client and not by the SSSD server components. To indicate what message the + * client should display to the user SSSD can send a #SSS_PAM_USER_INFO message + * where the data part contains one of the following tags as an unsigned + * 32-bit integer value and optional data. + * + * Examples: + * - #SSS_PAM_USER_INFO_OFFLINE_CHPASS + * uint32_t | uint32_t | uint32_t + * ----------|----------|---------- + * 0x06 | 0x04 | 0x03 + * + * - #SSS_PAM_USER_INFO_CHPASS_ERROR + * uint32_t | uint32_t | uint32_t | uint32_t | uint8_t[3] + * ----------|----------|----------|----------|------------ + * 0x06 | 0x0B | 0x04 | 0x03 | abc + * @{ + */ + +/** Different types of user messages */ + +enum user_info_type { + SSS_PAM_USER_INFO_OFFLINE_AUTH = 0x01, /**< Inform the user that the + * authentication happened offline. + * This message is generated by the + * PAM responder. + * @param Time when the cached + * password will expire in seconds + * since the UNIX Epoch as returned + * by time(2) as int64_t. A value + * of zero indicates that the + * cached password will never + * expire. */ + SSS_PAM_USER_INFO_OFFLINE_AUTH_DELAYED, /**< Tell the user how low a new + * authentication is delayed. This + * message is generated by the PAM + * responder. + * @param Time when an + * authentication is allowed again + * in seconds since the UNIX Epoch + * as returned by time(2) as + * int64_t. */ + SSS_PAM_USER_INFO_OFFLINE_CHPASS, /**< * Tell the user that it is not + * possible to change the password while + * the system is offline. This message + * is generated by the PAM responder. */ + SSS_PAM_USER_INFO_OTP_CHPASS, /**< Tell the user that he needs to kinit + * or login and logout to get a TGT after + * an OTP password change */ + SSS_PAM_USER_INFO_CHPASS_ERROR, /**< Tell the user that a password change + * failed and optionally give a reason. + * @param Size of the message as unsigned + * 32-bit integer value. A value of 0 + * indicates that no message is following. + * @param String with the specified + * length. */ + + SSS_PAM_USER_INFO_GRACE_LOGIN, /**< Warn the user that the password is + * expired and inform about the remaining + * number of grace logins. + * @param The number of remaining grace + * logins as uint32_t */ + SSS_PAM_USER_INFO_EXPIRE_WARN, /**< Warn the user that the password will + * expire soon. + * @param Number of seconds before the + * user's password will expire. */ + + SSS_PAM_USER_INFO_ACCOUNT_EXPIRED, /**< Tell the user that the account + * has expired and optionally give + * a reason. + * @param Size of the message as + * unsigned 32-bit integer value. A + * value of 0 indicates that no message + * is following. @param String with the + * specified length. */ + + SSS_PAM_USER_INFO_PIN_LOCKED, /**< Tell the user that the PIN is locked */ + SSS_PAM_USER_INFO_NO_KRB_TGT, /**< Tell the user that Kerberos local/offline + auth was performed, therefore no TGT + is granted */ +}; +/** + * @} + */ /* end of group user_info_type */ + +/** + * @} + */ /* end of group response_type */ + +/** + * @} + */ /* end of group sss_pam_cli */ + + +enum prompt_config_type { + PC_TYPE_INVALID = 0, + PC_TYPE_PASSWORD, + PC_TYPE_2FA, + PC_TYPE_2FA_SINGLE, + PC_TYPE_PASSKEY, + PC_TYPE_SC_PIN, + PC_TYPE_LAST +}; + +struct prompt_config; + +enum prompt_config_type pc_get_type(struct prompt_config *pc); +const char *pc_get_password_prompt(struct prompt_config *pc); +const char *pc_get_2fa_1st_prompt(struct prompt_config *pc); +const char *pc_get_2fa_2nd_prompt(struct prompt_config *pc); +const char *pc_get_2fa_single_prompt(struct prompt_config *pc); +const char *pc_get_passkey_inter_prompt(struct prompt_config *pc); +const char *pc_get_passkey_touch_prompt(struct prompt_config *pc); +errno_t pc_list_add_passkey(struct prompt_config ***pc_list, + const char *inter_prompt, + const char *touch_prompt); +void pc_list_free(struct prompt_config **pc_list); +errno_t pc_list_add_password(struct prompt_config ***pc_list, + const char *prompt); +errno_t pc_list_add_2fa(struct prompt_config ***pc_list, + const char *prompt_1st, const char *prompt_2nd); +errno_t pc_list_add_2fa_single(struct prompt_config ***pc_list, + const char *prompt); +errno_t pam_get_response_prompt_config(struct prompt_config **pc_list, int *len, + uint8_t **data); +errno_t pc_list_from_response(int size, uint8_t *buf, + struct prompt_config ***pc_list); + +enum sss_netgr_rep_type { + SSS_NETGR_REP_TRIPLE = 1, + SSS_NETGR_REP_GROUP +}; + +enum sss_cli_error_codes { + ESSS_SSS_CLI_ERROR_START = 0x1000, + ESSS_BAD_PRIV_SOCKET, + ESSS_BAD_PUB_SOCKET, + ESSS_BAD_CRED_MSG, + ESSS_SERVER_NOT_TRUSTED, + ESSS_NO_SOCKET, + ESSS_SOCKET_STAT_ERROR, + + ESS_SSS_CLI_ERROR_MAX +}; + +const char *ssscli_err2string(int err); + +enum sss_status sss_cli_make_request_with_checks(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + int timeout, + uint8_t **repbuf, size_t *replen, + int *errnop, + const char *socket_name); + +enum nss_status sss_nss_make_request(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + uint8_t **repbuf, size_t *replen, + int *errnop); + +enum nss_status sss_nss_make_request_timeout(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + int timeout, + uint8_t **repbuf, size_t *replen, + int *errnop); + +int sss_pam_make_request(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + uint8_t **repbuf, size_t *replen, + int *errnop); + +void sss_cli_close_socket(void); + +/* Checks access to the PAC responder and opens the socket, if available. + * Required for processes like krb5_child that need to open the socket + * before dropping privs. + */ +int sss_pac_check_and_open(void); + +int sss_pac_make_request(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + uint8_t **repbuf, size_t *replen, + int *errnop); + +int sss_pac_make_request_with_lock(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + uint8_t **repbuf, size_t *replen, + int *errnop); + +int sss_sudo_make_request(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + uint8_t **repbuf, size_t *replen, + int *errnop); + +int sss_autofs_make_request(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + uint8_t **repbuf, size_t *replen, + int *errnop); + +int sss_ssh_make_request(enum sss_cli_command cmd, + struct sss_cli_req_data *rd, + uint8_t **repbuf, size_t *replen, + int *errnop); + +#if 0 + +/* GETSPNAM Request: + * + * 0-X: string with name + * + * Replies: + * + * 0-3: 32bit unsigned number of results + * 4-7: 32bit unsigned (reserved/padding) + * For each result: + * 0-7: 64bit unsigned with Date of last change + * 8-15: 64bit unsigned with Min #days between changes + * 16-23: 64bit unsigned with Max #days between changes + * 24-31: 64bit unsigned with #days before pwd expires + * 32-39: 64bit unsigned with #days after pwd expires until account is disabled + * 40-47: 64bit unsigned with expiration date in days since 1970-01-01 + * 48-55: 64bit unsigned (flags/reserved) + * 56-X: sequence of 2, 0 terminated, strings (name, pwd) 64bit padded + */ +#endif + +/* Return strlen(str) or maxlen, whichever is shorter + * Returns EINVAL if str is NULL, EFBIG if str is longer than maxlen + * _len will return the result + */ +errno_t sss_strnlen(const char *str, size_t maxlen, size_t *len); + +void sss_nss_lock(void); +void sss_nss_unlock(void); +void sss_pam_lock(void); +void sss_pam_unlock(void); +void sss_nss_mc_lock(void); +void sss_nss_mc_unlock(void); +void sss_pac_lock(void); +void sss_pac_unlock(void); + +errno_t sss_readrep_copy_string(const char *in, + size_t *offset, + size_t *slen, + size_t *dlen, + char **out, + size_t *size); + +enum pam_gssapi_cmd { + PAM_GSSAPI_GET_NAME, + PAM_GSSAPI_INIT, + PAM_GSSAPI_SENTINEL +}; + +#endif /* _SSSCLI_H */ diff --git a/src/sss_client/sss_nss.exports b/src/sss_client/sss_nss.exports new file mode 100644 index 0000000..d833ddf --- /dev/null +++ b/src/sss_client/sss_nss.exports @@ -0,0 +1,73 @@ +EXPORTED { + + # public functions + global: + + _nss_sss_getpwnam_r; + _nss_sss_getpwuid_r; + _nss_sss_setpwent; + _nss_sss_getpwent_r; + _nss_sss_endpwent; + + _nss_sss_getgrnam_r; + _nss_sss_getgrgid_r; + _nss_sss_setgrent; + _nss_sss_getgrent_r; + _nss_sss_endgrent; + _nss_sss_initgroups_dyn; + + #_nss_sss_getaliasbyname_r; + #_nss_sss_setaliasent; + #_nss_sss_getaliasent_r; + #_nss_sss_endaliasent; + + #_nss_sss_gethostton_r; + #_nss_sss_getntohost_r; + #_nss_sss_setetherent; + #_nss_sss_getetherent_r; + #_nss_sss_endetherent; + + _nss_sss_gethostbyname_r; + _nss_sss_gethostbyname2_r; + _nss_sss_gethostbyaddr_r; + _nss_sss_sethostent; + _nss_sss_gethostent_r; + _nss_sss_endhostent; + + _nss_sss_setnetgrent; + _nss_sss_getnetgrent_r; + _nss_sss_endnetgrent; + + _nss_sss_getnetbyname_r; + _nss_sss_getnetbyaddr_r; + _nss_sss_setnetent; + _nss_sss_getnetent_r; + _nss_sss_endnetent; + + #_nss_sss_getprotobyname_r; + #_nss_sss_getprotobynumber_r; + #_nss_sss_setprotoent; + #_nss_sss_getprotoent_r; + #_nss_sss_endprotoent; + + #_nss_sss_getrpcbyname_r; + #_nss_sss_getrpcbynumber_r; + #_nss_sss_setrpcent; + #_nss_sss_getrpcent_r; + #_nss_sss_endrpcent; + + _nss_sss_getservbyname_r; + _nss_sss_getservbyport_r; + _nss_sss_setservent; + _nss_sss_getservent_r; + _nss_sss_endservent; + + #_nss_sss_getspnam_r; + #_nss_sss_setspent; + #_nss_sss_getspent_r; + #_nss_sss_endspent; + + # everything else is local + local: + *; +}; diff --git a/src/sss_client/sss_pac_responder_client.c b/src/sss_client/sss_pac_responder_client.c new file mode 100644 index 0000000..ee0ec0e --- /dev/null +++ b/src/sss_client/sss_pac_responder_client.c @@ -0,0 +1,153 @@ +/* + Copyright (C) 2016 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + + +#include <stdio.h> +#include <stdbool.h> +#include <pthread.h> +#include <pwd.h> +#include <unistd.h> +#include <sys/types.h> +#include <errno.h> + +#include <sys/syscall.h> + +#include "sss_client/sss_cli.h" +#include "util/util.h" + +const uint8_t pac[] = { +0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x10, +0x02, 0x00, 0x00, 0x58, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, +0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x68, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x0c, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x78, 0x02, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0xb8, +0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x10, 0x00, +0x00, 0x00, 0xc8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x10, 0x08, +0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x02, 0x00, 0x30, 0xe3, 0xd6, 0x9e, 0x99, 0x2b, 0xd3, 0x01, 0xff, +0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +0xff, 0x7f, 0xe2, 0xf7, 0x8a, 0xaf, 0x00, 0x0f, 0xd0, 0x01, 0xe2, 0xb7, 0xf4, +0xd9, 0xc9, 0x0f, 0xd0, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, +0x06, 0x00, 0x06, 0x00, 0x04, 0x00, 0x02, 0x00, 0x06, 0x00, 0x06, 0x00, 0x08, +0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x02, 0x00, 0x00, 0x00, +0x00, 0x00, 0x10, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x02, +0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x02, 0x00, 0x45, 0x02, 0x00, 0x00, +0x50, 0x04, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x1c, +0x00, 0x02, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x14, +0x00, 0x20, 0x00, 0x02, 0x00, 0x04, 0x00, 0x06, 0x00, 0x24, 0x00, 0x02, 0x00, +0x28, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, +0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x02, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x74, 0x00, +0x75, 0x00, 0x31, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x03, 0x00, 0x00, 0x00, 0x74, 0x00, 0x20, 0x00, 0x75, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, +0xfd, 0xa2, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00, 0x07, +0x00, 0x00, 0x00, 0x5c, 0x04, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x56, 0x04, +0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x89, 0xa6, 0x00, 0x00, 0x07, 0x00, 0x00, +0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, +0x41, 0x00, 0x44, 0x00, 0x2d, 0x00, 0x53, 0x00, 0x45, 0x00, 0x52, 0x00, 0x56, +0x00, 0x45, 0x00, 0x52, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x41, 0x00, 0x44, 0x00, 0x04, 0x00, 0x00, +0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x15, 0x00, 0x00, 0x00, +0xf8, 0x12, 0x13, 0xdc, 0x47, 0xf3, 0x1c, 0x76, 0x47, 0x2f, 0x2e, 0xd7, 0x02, +0x00, 0x00, 0x00, 0x30, 0x00, 0x02, 0x00, 0x07, 0x00, 0x00, 0x00, 0x34, 0x00, +0x02, 0x00, 0x07, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x05, 0x00, +0x00, 0x00, 0x00, 0x00, 0x05, 0x15, 0x00, 0x00, 0x00, 0x29, 0xc9, 0x4f, 0xd9, +0xc2, 0x3c, 0xc3, 0x78, 0x36, 0x55, 0x87, 0xf8, 0x54, 0x04, 0x00, 0x00, 0x05, +0x00, 0x00, 0x00, 0x01, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x15, 0x00, +0x00, 0x00, 0x25, 0xe1, 0xff, 0x1c, 0xf7, 0x87, 0x6b, 0x2c, 0x25, 0xd2, 0x0c, +0xe3, 0xf2, 0x03, 0x00, 0x00, 0x00, 0x2c, 0x29, 0x89, 0x65, 0x2d, 0xd3, 0x01, +0x06, 0x00, 0x74, 0x00, 0x75, 0x00, 0x31, 0x00, 0x20, 0x00, 0x10, 0x00, 0x10, +0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x00, +0x75, 0x00, 0x31, 0x00, 0x74, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x40, +0x00, 0x61, 0x00, 0x64, 0x00, 0x2e, 0x00, 0x64, 0x00, 0x65, 0x00, 0x76, 0x00, +0x65, 0x00, 0x6c, 0x00, 0x41, 0x00, 0x44, 0x00, 0x2e, 0x00, 0x44, 0x00, 0x45, +0x00, 0x56, 0x00, 0x45, 0x00, 0x4c, 0x00, 0x10, 0x00, 0x00, 0x00, 0x76, 0x8e, +0x25, 0x32, 0x7c, 0x85, 0x00, 0x32, 0xac, 0x8f, 0x02, 0x2c, 0x10, 0x00, 0x00, +0x00, 0x6b, 0xe8, 0x51, 0x03, 0x30, 0xed, 0xca, 0x7d, 0xe2, 0x12, 0xa5, 0xde}; + +enum nss_status _nss_sss_getpwuid_r(uid_t uid, struct passwd *result, + char *buffer, size_t buflen, int *errnop); +static void *pac_client(void *arg) +{ + struct sss_cli_req_data sss_data = { sizeof(pac), pac }; + int errnop = -1; + int ret; + size_t c; + + fprintf(stderr, "[%"SPRItime"][%d][%ld][%s] started\n", + time(NULL), getpid(), syscall(SYS_gettid), (char *) arg); + for (c = 0; c < 1000; c++) { + /* sss_pac_make_request() does not protect the client's file + * descriptor to the PAC responder. With this one thread will miss a + * reply for an SSS_GET_VERSION request and will wait until + * SSS_CLI_SOCKET_TIMEOUT is passed. + + ret = sss_pac_make_request(SSS_PAC_ADD_PAC_USER, &sss_data, + NULL, NULL, &errnop); + */ + ret = sss_pac_make_request_with_lock(SSS_PAC_ADD_PAC_USER, &sss_data, + NULL, NULL, &errnop); + if (ret != NSS_STATUS_SUCCESS + && !(ret == NSS_STATUS_UNAVAIL && errnop != ECONNREFUSED)) { + /* NSS_STATUS_UNAVAIL is returned if the PAC responder rejects + * the request which is ok because the client is waiting for a + * response here as well. Only errnop == ECONNREFUSED should + * be treated as error because this means that the PAC + * responder is not running. */ + fprintf(stderr, "pac: [%s][%d][%d]\n", (char *)arg, ret, errnop); + return ((void *)((uintptr_t)("X"))); + } + } + + fprintf(stderr, "[%"SPRItime"][%s] done\n", time(NULL),(char *) arg); + return NULL; +} + +int main(void) +{ + pthread_t thread1; + pthread_t thread2; + int ret; + void *t_ret; + + pthread_create(&thread1, NULL, pac_client, + ((void *)((uintptr_t)("Thread 1")))); + pthread_create(&thread2, NULL, pac_client, + ((void *)((uintptr_t)("Thread 2")))); + + ret = pthread_join(thread1, &t_ret); + if (ret != 0 || t_ret != NULL) { + fprintf(stderr, "Thread 1 failed.\n"); + return EIO; + } + + ret = pthread_join(thread2, &t_ret); + if (ret != 0 || t_ret != NULL) { + fprintf(stderr, "Thread 1 failed.\n"); + return EIO; + } + + return 0; +} diff --git a/src/sss_client/sss_pam.exports b/src/sss_client/sss_pam.exports new file mode 100644 index 0000000..9afa106 --- /dev/null +++ b/src/sss_client/sss_pam.exports @@ -0,0 +1,4 @@ +{ + global: + *; +}; diff --git a/src/sss_client/sss_pam_compat.h b/src/sss_client/sss_pam_compat.h new file mode 100644 index 0000000..d131cea --- /dev/null +++ b/src/sss_client/sss_pam_compat.h @@ -0,0 +1,45 @@ +/* + SSSD + + Compat declarations for PAM. + + Authors: + Lukas Slebodnik <lslebodn@redhat.com> + + Copyright (C) Red Hat, Inc 2014 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 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 Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef _SSS_PAM_COMPAT_H +#define _SSS_PAM_COMPAT_H + +#ifdef HAVE_SECURITY_PAM_MODUTIL_H +# include <security/pam_modutil.h> +#endif /* HAVE_SECURITY_PAM_MODUTIL_H */ + +#ifdef HAVE_SECURITY_PAM_EXT_H +# include <security/pam_ext.h> +#endif /* HAVE_SECURITY_PAM_EXT_H */ + +#ifndef HAVE_PAM_VSYSLOG +#define pam_vsyslog(pamh, priority, fmt, vargs) \ + vsyslog((priority), (fmt), (vargs)) +#endif /* HAVE_PAM_VSYSLOG */ + +#ifndef PAM_BAD_ITEM +# define PAM_BAD_ITEM PAM_USER_UNKNOWN +#endif /* PAM_BAD_ITEM */ + +#endif /* _SSS_PAM_COMPAT_H */ diff --git a/src/sss_client/sss_pam_macros.h b/src/sss_client/sss_pam_macros.h new file mode 100644 index 0000000..0a7e266 --- /dev/null +++ b/src/sss_client/sss_pam_macros.h @@ -0,0 +1,61 @@ +/* + SSSD + + Client Interface for NSS and PAM. + + Authors: + Stephen Gallagher <sgallagh@redhat.com> + + Copyright (C) Red Hat, Inc 2009 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 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 Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef _SSS_PAM_MACROS_H +#define _SSS_PAM_MACROS_H + +/* Older versions of the pam development headers do not include the + * _pam_overwrite_n(n,x) macro. This implementation is copied from + * the Fedora 11 _pam_macros.h. + */ +#ifdef HAVE_SECURITY__PAM_MACROS_H +# include <security/_pam_macros.h> +#endif /* HAVE_SECURITY__PAM_MACROS_H */ + +#ifndef _pam_overwrite +#define _pam_overwrite(x) \ +do { \ + register char *__xx__; \ + if ((__xx__=(x))) \ + while (*__xx__) \ + *__xx__++ = '\0'; \ +} while (0) +#endif /* _pam_overwrite */ + +#ifndef _pam_overwrite_n +#define _pam_overwrite_n(x,n) \ +do { \ + register char *__xx__; \ + register unsigned int __i__ = 0; \ + if ((__xx__=(x))) \ + for (;__i__<n; __i__++) \ + __xx__[__i__] = 0; \ +} while (0) +#endif /* _pam_overwrite_n */ + +#ifndef D +#define D(x) do { } while (0) +#endif /* D */ + +#endif /* _SSS_PAM_MACROS_H */ diff --git a/src/sss_client/sss_sudo.exports b/src/sss_client/sss_sudo.exports new file mode 100644 index 0000000..644e012 --- /dev/null +++ b/src/sss_client/sss_sudo.exports @@ -0,0 +1,16 @@ +EXPORTED { + + # public functions + global: + + sss_sudo_send_recv; + sss_sudo_send_recv_defaults; + sss_sudo_free_result; + sss_sudo_get_values; + sss_sudo_free_values; + + # everything else is local + local: + *; +}; + diff --git a/src/sss_client/sssd_pac.c b/src/sss_client/sssd_pac.c new file mode 100644 index 0000000..523b5c4 --- /dev/null +++ b/src/sss_client/sssd_pac.c @@ -0,0 +1,325 @@ +/* + Authors: + Sumit Bose <sbose@redhat.com> + + Copyright (C) 2011, 2012, 2013 Red Hat + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 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 Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/* A short documentation about authdata plugins can be found in + * http://http://k5wiki.kerberos.org/wiki/Projects/VerifyAuthData */ + +#include <krb5/krb5.h> +#include <errno.h> + +#include "krb5_authdata_int.h" +#include "sss_cli.h" + + +struct sssd_context { + krb5_data data; +}; + +static krb5_error_code +sssdpac_init(krb5_context kcontext, void **plugin_context) +{ + *plugin_context = NULL; + return 0; +} + +static void +sssdpac_flags(krb5_context kcontext, + void *plugin_context, + krb5_authdatatype ad_type, + krb5_flags *flags) +{ + *flags = AD_USAGE_KDC_ISSUED | AD_USAGE_TGS_REQ; +} + +static void +sssdpac_fini(krb5_context kcontext, void *plugin_context) +{ + return; +} + +static krb5_error_code +sssdpac_request_init(krb5_context kcontext, + krb5_authdata_context context, + void *plugin_context, + void **request_context) +{ + struct sssd_context *sssdctx; + + sssdctx = (struct sssd_context *)calloc(1, sizeof(*sssdctx)); + if (sssdctx == NULL) { + return ENOMEM; + } + + *request_context = sssdctx; + + return 0; +} + +static krb5_error_code +sssdpac_import_authdata(krb5_context kcontext, + krb5_authdata_context context, + void *plugin_context, + void *request_context, + krb5_authdata **authdata, + krb5_boolean kdc_issued, + krb5_const_principal kdc_issuer) +{ + char *data = NULL; + struct sssd_context *sssdctx = (struct sssd_context *)request_context; + + if (authdata[0] == NULL) { + return EINVAL; + } + + if (authdata[0]->length > 0) { + data = malloc(sizeof(char) * authdata[0]->length); + if (data == NULL) { + return ENOMEM; + } + memcpy(data, authdata[0]->contents, authdata[0]->length); + } + + if (sssdctx->data.data != NULL) { + krb5_free_data_contents(kcontext, &sssdctx->data); + } + + sssdctx->data.length = authdata[0]->length; + sssdctx->data.data = data; + return 0; +} + +static void +sssdpac_request_fini(krb5_context kcontext, + krb5_authdata_context context, + void *plugin_context, + void *request_context) +{ + struct sssd_context *sssdctx = (struct sssd_context *)request_context; + + if (sssdctx != NULL) { + if (sssdctx->data.data != NULL) { + krb5_free_data_contents(kcontext, &sssdctx->data); + } + + free(sssdctx); + } +} + +static krb5_error_code sssdpac_verify(krb5_context kcontext, + krb5_authdata_context context, + void *plugin_context, + void *request_context, + const krb5_auth_context *auth_context, + const krb5_keyblock *key, + const krb5_ap_req *req) +{ + krb5_error_code kerr; + int ret; + krb5_pac pac; + struct sssd_context *sssdctx = (struct sssd_context *)request_context; + struct sss_cli_req_data sss_data; + int errnop; + + if (sssdctx == NULL || sssdctx->data.data == NULL) { + return EINVAL; + } + + kerr = krb5_pac_parse(kcontext, sssdctx->data.data, + sssdctx->data.length, &pac); + if (kerr != 0) { + return EINVAL; + } + + kerr = krb5_pac_verify(kcontext, pac, + req->ticket->enc_part2->times.authtime, + req->ticket->enc_part2->client, key, NULL); + /* deallocate pac */ + krb5_pac_free(kcontext, pac); + pac = NULL; + if (kerr != 0) { + /* The krb5 documentation says: + * A checksum mismatch can occur if the PAC was copied from a + * cross-realm TGT by an ignorant KDC; also Apple Mac OS X Server + * Open Directory (as of 10.6) generates PACs with no server checksum + * at all. One should consider not failing the whole authentication + * because of this reason, but, instead, treating the ticket as + * if it did not contain a PAC or marking the PAC information as + * non-verified. + */ + return 0; + } + + sss_data.len = sssdctx->data.length; + sss_data.data = sssdctx->data.data; + + ret = sss_pac_make_request_with_lock(SSS_PAC_ADD_PAC_USER, &sss_data, + NULL, NULL, &errnop); + if (ret != 0) { + /* Ignore the error */ + } + + return 0; +} + +static krb5_error_code +sssdpac_size(krb5_context kcontext, + krb5_authdata_context context, + void *plugin_context, + void *request_context, + size_t *sizep) +{ + struct sssd_context *sssdctx = (struct sssd_context *)request_context; + + *sizep += sizeof(krb5_int32); + + *sizep += sssdctx->data.length; + + *sizep += sizeof(krb5_int32); + + return 0; +} + +static krb5_error_code +sssdpac_externalize(krb5_context kcontext, + krb5_authdata_context context, + void *plugin_context, + void *request_context, + krb5_octet **buffer, + size_t *lenremain) +{ + krb5_error_code code = 0; + struct sssd_context *sssdctx = (struct sssd_context *)request_context; + size_t required = 0; + krb5_octet *bp; + size_t remain; + + bp = *buffer; + remain = *lenremain; + + if (sssdctx->data.data != NULL) { + sssdpac_size(kcontext, context, plugin_context, + request_context, &required); + + if (required <= remain) { + krb5_ser_pack_int32((krb5_int32)sssdctx->data.length, + &bp, &remain); + krb5_ser_pack_bytes((krb5_octet *)sssdctx->data.data, + (size_t)sssdctx->data.length, + &bp, &remain); + krb5_ser_pack_int32(0, + &bp, &remain); + } else { + code = ENOMEM; + } + } else { + krb5_ser_pack_int32(0, &bp, &remain); /* length */ + krb5_ser_pack_int32(0, &bp, &remain); /* verified */ + } + + *buffer = bp; + *lenremain = remain; + + return code; +} + +static krb5_error_code +sssdpac_internalize(krb5_context kcontext, + krb5_authdata_context context, + void *plugin_context, + void *request_context, + krb5_octet **buffer, + size_t *lenremain) +{ + struct sssd_context *sssdctx = (struct sssd_context *)request_context; + krb5_error_code code; + krb5_int32 ibuf; + krb5_octet *bp; + size_t remain; + krb5_data data; + + bp = *buffer; + remain = *lenremain; + + /* length */ + code = krb5_ser_unpack_int32(&ibuf, &bp, &remain); + if (code != 0) { + return code; + } + + if (ibuf != 0) { + + data.length = ibuf; + data.data = malloc(sizeof(char) * ibuf); + if (data.data == NULL) { + return ENOMEM; + } + memcpy(data.data, bp, ibuf); + + bp += ibuf; + remain -= ibuf; + } else { + data.length = 0; + data.data = NULL; + } + + /* verified */ + code = krb5_ser_unpack_int32(&ibuf, &bp, &remain); + if (code != 0) { + free(data.data); + return code; + } + + if (sssdctx->data.data != NULL) { + krb5_free_data_contents(kcontext, &sssdctx->data); + } + + sssdctx->data.length = data.length; + sssdctx->data.data = data.data; + + *buffer = bp; + *lenremain = remain; + + return 0; +} + +static krb5_authdatatype sssdpac_ad_types[] = { KRB5_AUTHDATA_WIN2K_PAC, 0 }; + +krb5plugin_authdata_client_ftable_v0 authdata_client_0 = { + "sssd_sssdpac", + sssdpac_ad_types, + sssdpac_init, + sssdpac_fini, + sssdpac_flags, + sssdpac_request_init, + sssdpac_request_fini, + NULL, + NULL, + NULL, + NULL, + NULL, + sssdpac_import_authdata, + NULL, + NULL, + sssdpac_verify, + sssdpac_size, + sssdpac_externalize, + sssdpac_internalize, + NULL +}; diff --git a/src/sss_client/subid/sss_subid.c b/src/sss_client/subid/sss_subid.c new file mode 100644 index 0000000..f1fbe34 --- /dev/null +++ b/src/sss_client/subid/sss_subid.c @@ -0,0 +1,222 @@ +/* + Copyright (C) 2021 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include <stdlib.h> +#include <string.h> +#include <shadow/subid.h> +#include "sss_cli.h" + +/* This shadow-utils plugin contains partial SSSD implementation + * of `subid_nss_ops` API as described in + * https://github.com/shadow-maint/shadow/blob/d4b6d1549b2af48ce3cb6ff78d9892095fb8fdd9/lib/prototypes.h#L271 + */ + +/* Find all subid ranges delegated to a user. + * + * Usage in shadow-utils: + * libsubid: get_sub?id_ranges() -> list_owner_ranges() + * + * SUBID_RANGES Reply: + * + * 0-3: 32bit unsigned number of UID results + * 4-7: 32bit unsigned number of GID results + * For each result (sub-uid ranges first): + * 0-3: 32bit number with "start" id + * 4-7: 32bit number with "count" (range size) + */ +enum subid_status shadow_subid_list_owner_ranges(const char *user, + enum subid_type id_type, + struct subid_range **ranges, + int *count) +{ + size_t user_len; + enum sss_status ret; + uint8_t *repbuf = NULL; + size_t index = 0; + size_t replen; + int errnop; + struct sss_cli_req_data rd; + uint32_t num_results = 0; + uint32_t val; + + if ( !user || !ranges || !count || + ((id_type != ID_TYPE_UID) && (id_type != ID_TYPE_GID)) ) { + return SUBID_STATUS_ERROR; + } + + ret = sss_strnlen(user, SSS_NAME_MAX, &user_len); + if (ret != 0) { + return SUBID_STATUS_UNKNOWN_USER; + } + rd.len = user_len + 1; + rd.data = user; + + sss_nss_lock(); + /* Anticipated workflow will always request both + * sub-uid and sub-gid ranges anyway. + * So don't bother with dedicated commands - + * just request everything in one shot. + * The second request will get data from the cache. + */ + ret = sss_cli_make_request_with_checks(SSS_NSS_GET_SUBID_RANGES, &rd, + SSS_CLI_SOCKET_TIMEOUT, + &repbuf, &replen, &errnop, + SSS_NSS_SOCKET_NAME); + sss_nss_unlock(); + + if ( (ret != SSS_STATUS_SUCCESS) || (errnop != EOK) + /* response must contain at least the "payload header" */ + || (replen < 2*sizeof(uint32_t)) + /* and even number of 'uint32_t' */ + || (replen % (2*sizeof(uint32_t)) != 0) ) { + free(repbuf); + if (ret == SSS_STATUS_UNAVAIL) { + return SUBID_STATUS_ERROR_CONN; + } + return SUBID_STATUS_ERROR; + } + + SAFEALIGN_COPY_UINT32(&num_results, repbuf, NULL); + if (num_results > (replen/sizeof(uint32_t) - 2)/2) { + free(repbuf); + return SUBID_STATUS_ERROR; + } + + if (id_type == ID_TYPE_UID) { + index = 2 * sizeof(uint32_t); + } else { + index = (2 + 2*num_results) * sizeof(uint32_t); + SAFEALIGN_COPY_UINT32(&num_results, repbuf + sizeof(uint32_t), NULL); + if (num_results > ((replen - index)/sizeof(uint32_t)/2)) { + free(repbuf); + return SUBID_STATUS_ERROR; + } + } + if (num_results == 0) { + /* TODO: how to distinguish "user not found" vs "user doesn't have ranges defined" here? + * Options: + * - special "fake" entry in the cache + * - provide 'nss_protocol_done_fn' to 'nss_getby_name' to avoid "ENOENT -> "empty packet" logic + * - add custom error code for this case and handle in generic 'nss_protocol_done' + * + * Note: at the moment this is not important, since shadow-utils doesn't use return code internally + * and returns -1 from libsubid on any error anyway. + */ + free(repbuf); + return SUBID_STATUS_UNKNOWN_USER; + } + + *count = num_results; + if (*count < 0) { + free(repbuf); + return SUBID_STATUS_ERROR; + } + + *ranges = malloc(num_results * sizeof(struct subid_range)); + if (!*ranges) { + free(repbuf); + return SUBID_STATUS_ERROR; + } + + for (uint32_t c = 0; c < num_results; ++c) { + SAFEALIGN_COPY_UINT32(&val, repbuf + index, &index); + (*ranges)[c].start = val; + SAFEALIGN_COPY_UINT32(&val, repbuf + index, &index); + (*ranges)[c].count = val; + } + free(repbuf); + + return SUBID_STATUS_SUCCESS; +} + +/* Does a user own a given subid range? + * + * Usage in shadow-utils: + * newuidmap/user busy : have_sub_uids() -> has_range() + */ +enum subid_status shadow_subid_has_range(const char *owner, + unsigned long start, + unsigned long count, + enum subid_type id_type, + bool *result) +{ + enum subid_status ret; + struct subid_range *range; + int amount; + unsigned long end = start + count; + + if (!result || (end < start)) { + return SUBID_STATUS_ERROR; + } + + if (count == 0) { + *result = true; + return SUBID_STATUS_SUCCESS; + } + + /* Anticipated workflow is the following: + * + * 1) Podman figures out ranges available for a user: + * libsubid::get_subid_ranges() -> ... -> list_owner_ranges() + * + * 2) Podman maps available ranges: + * newuidmap -> have_sub_uids() -> has_range() + * At this point all ranges are available in a cache from step (1) + * so it doesn't make sense to try "smart" LDAP searches (even if possible) + * Let's just reuse list_owner_ranges() and do a check. + * + * It might have some sense to do a check at responder's side (i.e. without + * fetching all ranges), but range is just a couple of numbers (and FreeIPA + * only supports a single range per user anyway), so this optimization + * wouldn't save much traffic anyway, but would introduce new + * `sss_cli_command`/responder handler. + */ + + ret = shadow_subid_list_owner_ranges(owner, id_type, &range, &amount); + if (ret != SUBID_STATUS_SUCCESS) { + return ret; + } + + *result = false; + + for (int i = 0; i < amount; ++i) { + if ((range[i].start <= start) && + (range[i].start + range[i].count >= end)) { + *result = true; + } + /* TODO: handle coverage via multiple ranges (once IPA supports this) */ + } + + free(range); + return ret; +} + +/* Find uids who own a given subid. + * + * Usage in shadow-utils: + * libsubid: get_sub?id_owners() -> find_subid_owners() + */ +enum subid_status shadow_subid_find_subid_owners(unsigned long subid, + enum subid_type id_type, + uid_t **uids, + int *count) +{ + /* Not yet implemented. + * Currently there are no users of this function. + */ + return SUBID_STATUS_ERROR; +} diff --git a/src/sss_client/subid/sss_subid.exports b/src/sss_client/subid/sss_subid.exports new file mode 100644 index 0000000..87c073b --- /dev/null +++ b/src/sss_client/subid/sss_subid.exports @@ -0,0 +1,12 @@ +EXPORTED { + + # public functions + global: + shadow_subid_has_range; + shadow_subid_list_owner_ranges; + shadow_subid_find_subid_owners; + + # everything else is local + local: + *; +}; diff --git a/src/sss_client/sudo/sss_sudo.c b/src/sss_client/sudo/sss_sudo.c new file mode 100644 index 0000000..6c86b8f --- /dev/null +++ b/src/sss_client/sudo/sss_sudo.c @@ -0,0 +1,251 @@ +/* + Authors: + Pavel Březina <pbrezina@redhat.com> + + Copyright (C) 2011 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include "config.h" + +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <errno.h> + +#include "util/util.h" +#include "sss_client/sss_cli.h" +#include "sss_client/sudo/sss_sudo.h" +#include "sss_client/sudo/sss_sudo_private.h" + +static int sss_sudo_create_query(uid_t uid, + const char *username, + uint8_t **_query, + size_t *_query_len); + +static void sss_sudo_free_rules(unsigned int num_rules, + struct sss_sudo_rule *rules); + +static void sss_sudo_free_attrs(unsigned int num_attrs, + struct sss_sudo_attr *attrs); + +static int sss_sudo_send_recv_generic(enum sss_cli_command command, + uid_t uid, + const char *username, + uint32_t *_error, + char **_domainname, + struct sss_sudo_result **_result) +{ + struct sss_cli_req_data request; + uint8_t *query_buf = NULL; + size_t query_len = 0; + uint8_t *reply_buf = NULL; + size_t reply_len = 0; + int errnop = 0; + int ret = 0; + + /* create query */ + + ret = sss_sudo_create_query(uid, username, &query_buf, &query_len); + if (ret != EOK) { + goto done; + } + + request.len = query_len; + request.data = (const void*)query_buf; + + /* send query and receive response */ + + errnop = 0; + ret = sss_sudo_make_request(command, &request, + &reply_buf, &reply_len, &errnop); + if (ret != SSS_STATUS_SUCCESS) { + ret = errnop; + goto done; + } + + /* parse structure */ + + ret = sss_sudo_parse_response((const char*)reply_buf, reply_len, + _domainname, _result, _error); + +done: + free(query_buf); + free(reply_buf); + return ret; +} + +int sss_sudo_send_recv(uid_t uid, + const char *username, + const char *domainname, + uint32_t *_error, + struct sss_sudo_result **_result) +{ + int ret; + + if (username == NULL || strlen(username) == 0) { + return EINVAL; + } + + /* send query and receive response */ + + ret = sss_sudo_send_recv_generic(SSS_SUDO_GET_SUDORULES, uid, username, + _error, NULL, _result); + return ret; +} + +int sss_sudo_send_recv_defaults(uid_t uid, + const char *username, + uint32_t *_error, + char **_domainname, + struct sss_sudo_result **_result) +{ + if (username == NULL || strlen(username) == 0) { + return EINVAL; + } + + return sss_sudo_send_recv_generic(SSS_SUDO_GET_DEFAULTS, uid, username, + _error, _domainname, _result); +} + +static int sss_sudo_create_query(uid_t uid, const char *username, + uint8_t **_query, size_t *_query_len) +{ + uint8_t *data = NULL; + size_t username_len = strlen(username) * sizeof(char) + 1; + size_t data_len = sizeof(uid_t) + username_len; + size_t offset = 0; + + data = (uint8_t*)malloc(data_len * sizeof(uint8_t)); + if (data == NULL) { + return ENOMEM; + } + + SAFEALIGN_SET_VALUE(data, uid, uid_t, &offset); + memcpy(data + offset, username, username_len); + + *_query = data; + *_query_len = data_len; + + return EOK; +} + +int sss_sudo_get_values(struct sss_sudo_rule *e, + const char *attrname, char ***_values) +{ + struct sss_sudo_attr *attr = NULL; + char **values = NULL; + int i, j; + + for (i = 0; i < e->num_attrs; i++) { + attr = e->attrs + i; + if (strcasecmp(attr->name, attrname) == 0) { + values = calloc(attr->num_values + 1, sizeof(char*)); + if (values == NULL) { + return ENOMEM; + } + + for (j = 0; j < attr->num_values; j++) { + values[j] = strdup(attr->values[j]); + if (values[j] == NULL) { + sss_sudo_free_values(values); + return ENOMEM; + } + } + + values[attr->num_values] = NULL; + + break; + } + } + + if (values == NULL) { + return ENOENT; + } + + *_values = values; + + return EOK; +} + +void sss_sudo_free_values(char **values) +{ + char **value = NULL; + + if (values == NULL) { + return; + } + + for (value = values; *value != NULL; value++) { + free(*value); + } + + free(values); +} + +void sss_sudo_free_result(struct sss_sudo_result *result) +{ + if (result == NULL) { + return; + } + + sss_sudo_free_rules(result->num_rules, result->rules); + free(result); +} + +void sss_sudo_free_rules(unsigned int num_rules, struct sss_sudo_rule *rules) +{ + struct sss_sudo_rule *rule = NULL; + int i; + + if (rules == NULL) { + return; + } + + for (i = 0; i < num_rules; i++) { + rule = rules + i; + + sss_sudo_free_attrs(rule->num_attrs, rule->attrs); + rule->attrs = NULL; + } + + free(rules); +} + +void sss_sudo_free_attrs(unsigned int num_attrs, struct sss_sudo_attr *attrs) +{ + struct sss_sudo_attr *attr = NULL; + int i, j; + + if (attrs == NULL) { + return; + } + + for (i = 0; i < num_attrs; i++) { + attr = attrs + i; + + free(attr->name); + attr->name = NULL; + + for (j = 0; j < attr->num_values; j++) { + free(attr->values[j]); + attr->values[j] = NULL; + } + + free(attr->values); + } + + free(attrs); +} diff --git a/src/sss_client/sudo/sss_sudo.h b/src/sss_client/sudo/sss_sudo.h new file mode 100644 index 0000000..dc41d9f --- /dev/null +++ b/src/sss_client/sudo/sss_sudo.h @@ -0,0 +1,195 @@ +/* + Authors: + Pavel Březina <pbrezina@redhat.com> + + Copyright (C) 2011 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#ifndef SSS_SUDO_H_ +#define SSS_SUDO_H_ + +/** + * @defgroup libsss_sudo A library for communication between SUDO and SSSD + * libsss_sudo provides a mechanism to for a SUDO plugin + * to communicate with the sudo responder of SSSD. + * + * @{ + */ + +#include <stdint.h> +#include <sys/types.h> + +/** The value returned when the communication with SUDO is successful and + * the user was found in one of the domains + */ +#define SSS_SUDO_ERROR_OK 0 + +/** + * Component of an sss_rule structure. The component + * has exactly one name and one or more values. + * + */ +struct sss_sudo_attr { + /** The attribute name */ + char *name; + /** A string array that contains all the attribute values */ + char **values; + + /** The number of values the attribute contains. + * + * Attributes are multivalued in general. + */ + unsigned int num_values; +}; + +/** + * One sudo rule. The rule consists of one or more + * attributes of sss_attr type + */ +struct sss_sudo_rule { + /** The number of attributes in the rule */ + unsigned int num_attrs; + + /** List of rule attributes */ + struct sss_sudo_attr *attrs; +}; + +/** + * A result object returned from SSSD. + * + * The result consists of zero or more sss_rule elements. + */ +struct sss_sudo_result { + /** + * The number of rules for the user + * + * In case the user exists in one of SSSD domains + * but no rules match for him, the num_rules element + * is 0. + */ + unsigned int num_rules; + + /** List of rules found */ + struct sss_sudo_rule *rules; +}; + +/** + * @brief Send a request to SSSD to retrieve all SUDO rules for a given + * user. + * + * @param[in] uid The uid of the user to retrieve the rules for. + * @param[in] username The username to retrieve the rules for + * @param[in] domainname The domain name the user is a member of. + * @param[out] _error The result of the search in SSSD's domains. If the + * user was present in the domain, the _error code is + * SSS_SUDO_ERROR_OK and the _result structure is + * returned even if it was empty (in other words + * _result->num_rules == 0). Other problems are returned + * as errno codes. Most prominently these are ENOENT + * (the user was not found with SSSD), EIO (SSSD + * encountered an internal problem) and EINVAL + * (malformed query). + * @param[out] _result Newly allocated structure sss_result that contains + * the rules for the user. If no rules were found but + * the user was valid, this structure is "empty", which + * means that the num_rules member is 0. + * + * @return 0 on success and other errno values on failure. The return value + * denotes whether communication with SSSD was successful. It does not + * tell whether the result contains any rules or whether SSSD knew the + * user at all. That information is transferred in the _error parameter. + */ +int sss_sudo_send_recv(uid_t uid, + const char *username, + const char *domainname, + uint32_t *_error, + struct sss_sudo_result **_result); + +/** + * @brief Send a request to SSSD to retrieve the default options, commonly + * stored in the "cn=defaults" record, + * + * @param[in] uid The uid of the user to retrieve the rules for. + * + * @param[in] username The username to retrieve the rules for. + * + * @param[out] _error The result of the search in SSSD's domains. If the + * options were present in the domain, the _error code + * is SSS_SUDO_ERROR_OK and the _result structure is + * returned even if it was empty (in other words + * _result->num_rules == 0). Other problems are returned + * as errno codes. + * + * @param[out] _domainname The domain name the user is a member of. + * + * @param[out] _result Newly allocated structure sss_result that contains + * the options. If no options were found this structure + * is "empty", which means that the num_rules member + * is 0. + * + * @return 0 on success and other errno values on failure. The return value + * denotes whether communication with SSSD was successful. It does not + * tell whether the result contains any rules or whether SSSD knew the + * user at all. That information is transferred in the _error parameter. + * + * @note The _domainname should be freed using free(). + */ +int sss_sudo_send_recv_defaults(uid_t uid, + const char *username, + uint32_t *_error, + char **_domainname, + struct sss_sudo_result **_result); + +/** + * @brief Free the sss_result structure returned by sss_sudo_send_recv + * + * @param[in] result The sss_result structure to free. The structure was + * previously returned by sss_sudo_get_values(). + */ +void sss_sudo_free_result(struct sss_sudo_result *result); + +/** + * @brief Get all values for a given attribute in an sss_rule + * + * @param[in] e The sss_rule to get values from + * @param[in] attrname The name of the attribute to query from the rule + * @param[out] values A newly allocated list of values the attribute has in + * rule. On success, this parameter is an array of + * NULL-terminated strings, the last element is a NULL + * pointer. On failure (including when the attribute is + * not found), the pointer address is not changed. + * + * @return 0 on success, ENOENT in case the attribute is not found and other + * errno values on failure. + * + * @note the returned values should be freed using sss_sudo_free_values() + */ +int sss_sudo_get_values(struct sss_sudo_rule *e, + const char *attrname, + char ***values); + +/** + * @brief Free the values returned by sss_sudo_get_values + * + * @param[in] values The list of values to free. The values were previously + * returned by sss_sudo_get_values() + */ +void sss_sudo_free_values(char **values); + +/** + * @} + */ +#endif /* SSS_SUDO_H_ */ diff --git a/src/sss_client/sudo/sss_sudo_private.h b/src/sss_client/sudo/sss_sudo_private.h new file mode 100644 index 0000000..2827a94 --- /dev/null +++ b/src/sss_client/sudo/sss_sudo_private.h @@ -0,0 +1,33 @@ +/* + Authors: + Pavel Březina <pbrezina@redhat.com> + + Copyright (C) 2011 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#ifndef SSS_SUDO_PRIVATE_H_ +#define SSS_SUDO_PRIVATE_H_ + +#include <stdint.h> +#include "sss_client/sudo/sss_sudo.h" + +int sss_sudo_parse_response(const char *message, + size_t message_len, + char **_domainname, + struct sss_sudo_result **_result, + uint32_t *_error); + +#endif /* SSS_SUDO_PRIVATE_H_ */ diff --git a/src/sss_client/sudo/sss_sudo_response.c b/src/sss_client/sudo/sss_sudo_response.c new file mode 100644 index 0000000..7d4bcc5 --- /dev/null +++ b/src/sss_client/sudo/sss_sudo_response.c @@ -0,0 +1,257 @@ +/* + Authors: + Pavel Březina <pbrezina@redhat.com> + + Copyright (C) 2011 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include "config.h" + +#include <stdlib.h> +#include <errno.h> +#include <string.h> +#include <stdint.h> + +#include "sss_client/sss_cli.h" +#include "sss_client/sudo/sss_sudo.h" +#include "sss_client/sudo/sss_sudo_private.h" + +static int sss_sudo_parse_rule(const char *message, + size_t message_len, + size_t *_cursor, + struct sss_sudo_rule *_rule); + +static int sss_sudo_parse_attr(const char *message, + size_t message_len, + size_t *_cursor, + struct sss_sudo_attr *_attr); + +static int sss_sudo_parse_uint32(const char *message, + size_t message_len, + size_t *_cursor, + uint32_t *_number); + +static int sss_sudo_parse_string(const char *message, + size_t message_len, + size_t *_cursor, + char **_str); + +int sss_sudo_parse_response(const char *message, + size_t message_len, + char **_domainname, + struct sss_sudo_result **_result, + uint32_t *_error) +{ + struct sss_sudo_result *result = NULL; + char *domainname = NULL; + size_t cursor = 0; + int ret = EOK; + int i = 0; + + /* error code */ + ret = sss_sudo_parse_uint32(message, message_len, &cursor, _error); + if (ret != EOK || *_error != SSS_SUDO_ERROR_OK) { + return ret; + } + + /* domain name - deprecated + * it won't be used, but we will read it anyway to ease parsing + * TODO: when possible change the protocol */ + ret = sss_sudo_parse_string(message, message_len, &cursor, &domainname); + if (ret != EOK) { + return ret; + } + + free(domainname); + if (_domainname != NULL) { + *_domainname = NULL; + } + + /* result */ + result = malloc(sizeof(struct sss_sudo_result)); + if (result == NULL) { + return ENOMEM; + } + + memset(result, 0, sizeof(struct sss_sudo_result)); + + /* rules_num */ + ret = sss_sudo_parse_uint32(message, message_len, + &cursor, &result->num_rules); + if (ret != EOK) { + goto fail; + } + + /* rules */ + result->rules = calloc(result->num_rules, sizeof(struct sss_sudo_rule)); + if (result->rules == NULL) { + ret = ENOMEM; + goto fail; + } + + for (i = 0; i < result->num_rules; i++) { + ret = sss_sudo_parse_rule(message, message_len, + &cursor, &result->rules[i]); + if (ret != EOK) { + goto fail; + } + } + + *_result = result; + + return EOK; + +fail: + sss_sudo_free_result(result); + return ret; +} + +int sss_sudo_parse_rule(const char *message, + size_t message_len, + size_t *_cursor, + struct sss_sudo_rule *_rule) +{ + int ret = EOK; + int i = 0; + + /* attrs_num */ + ret = sss_sudo_parse_uint32(message, message_len, + _cursor, &_rule->num_attrs); + if (ret != EOK) { + return ret; + } + + /* attrs */ + _rule->attrs = calloc(_rule->num_attrs, sizeof(struct sss_sudo_attr)); + if (_rule->attrs == NULL) { + return ENOMEM; + } + + for (i = 0; i < _rule->num_attrs; i++) { + ret = sss_sudo_parse_attr(message, message_len, + _cursor, &_rule->attrs[i]); + if (ret != EOK) { + return ret; + } + } + + return EOK; +} + +int sss_sudo_parse_attr(const char *message, + size_t message_len, + size_t *_cursor, + struct sss_sudo_attr *_attr) +{ + char *str = NULL; + int ret = EOK; + int i = 0; + + /* name */ + ret = sss_sudo_parse_string(message, message_len, _cursor, &str); + if (ret != EOK) { + return ret; + } + _attr->name = str; + + /* values_num */ + ret = sss_sudo_parse_uint32(message, message_len, + _cursor, &_attr->num_values); + if (ret != EOK) { + return ret; + } + + /* values */ + _attr->values = calloc(_attr->num_values, sizeof(const char*)); + if (_attr->values == NULL) { + return ENOMEM; + } + + for (i = 0; i < _attr->num_values; i++) { + ret = sss_sudo_parse_string(message, message_len, _cursor, &str); + if (ret != EOK) { + return ret; + } + _attr->values[i] = str; + } + + return EOK; +} + +int sss_sudo_parse_uint32(const char *message, + size_t message_len, + size_t *_cursor, + uint32_t *_number) +{ + size_t start_pos = 0; + + if (_cursor == NULL) { + return EINVAL; + } + + start_pos = *_cursor; + + if (start_pos + sizeof(uint32_t) > message_len) { + return EINVAL; + } + + /* expanded SAFEALIGN_COPY_UINT32 macro from util.h */ + memcpy(_number, message + start_pos, sizeof(uint32_t)); + *_cursor = start_pos + sizeof(uint32_t); + + return EOK; +} + +int sss_sudo_parse_string(const char *message, + size_t message_len, + size_t *_cursor, + char **_str) +{ + const char *current = NULL; + char *str = NULL; + size_t start_pos = 0; + size_t len = 0; + size_t maxlen = 0; + + if (_cursor == NULL) { + return EINVAL; + } + + start_pos = *_cursor; + maxlen = message_len - start_pos; + + if (start_pos >= message_len ) { + return EINVAL; + } + + current = message + start_pos; + len = strnlen(current, maxlen); + if (len == maxlen) { + /* the string exceeds message length */ + return EINVAL; + } + + str = strndup(current, len); + if (str == NULL) { + return ENOMEM; + } + + /* go after \0 */ + *_cursor = start_pos + len + 1; + *_str = str; + + return EOK; +} diff --git a/src/sss_client/sudo_testcli/sudo_testcli.c b/src/sss_client/sudo_testcli/sudo_testcli.c new file mode 100644 index 0000000..271c03b --- /dev/null +++ b/src/sss_client/sudo_testcli/sudo_testcli.c @@ -0,0 +1,159 @@ +/* + Authors: + Pavel Březina <pbrezina@redhat.com> + + Copyright (C) 2011 Red Hat + + 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 <http://www.gnu.org/licenses/>. +*/ + +#include <stdlib.h> +#include <stdio.h> +#include <errno.h> +#include <string.h> +#include <talloc.h> +#include <sys/types.h> +#include <pwd.h> + +#include "sss_client/sss_cli.h" +#include "sss_client/sudo/sss_sudo.h" +#include "sss_client/sudo/sss_sudo_private.h" + +#ifndef EOK +#define EOK 0 +#endif + +void print_sss_result(struct sss_sudo_result *result); + +int main(int argc, char **argv) +{ + int ret = 0; + struct sss_sudo_result *result = NULL; + struct passwd *passwd = NULL; + const char *username = NULL; + char *domainname = NULL; + uid_t uid = 0; + uint32_t error = 0; + + if (argc != 2 && argc != 3) { + fprintf(stderr, "Usage: sss_sudo_cli username [uid]\n"); + goto fail; + } + + username = argv[1]; + if (argc == 3) { + uid = atoi(argv[2]); + } else { + passwd = getpwnam(username); + if (passwd == NULL) { + fprintf(stderr, "Unknown user\n"); + goto fail; + } + uid = passwd->pw_uid; + } + + /* get sss_result - it will send new query to responder */ + + /* get default options */ + + ret = sss_sudo_send_recv_defaults(uid, username, &error, + &domainname, &result); + if (ret != EOK) { + fprintf(stderr, "sss_sudo_send_recv_defaults() failed: %s\n", + strerror(ret)); + goto fail; + } + + printf("[\n"); + printf("\t{\n"); + printf("\t\t\"type\": \"default\",\n"); + printf("\t\t\"retval\": %u,\n", error); + if (error == SSS_SUDO_ERROR_OK) { + print_sss_result(result); + } + printf("\t},\n"); + + sss_sudo_free_result(result); + result = NULL; + + /* get rules */ + + ret = sss_sudo_send_recv(uid, username, domainname, &error, &result); + if (ret != EOK) { + fprintf(stderr, "sss_sudo_send_recv() failed: %s\n", strerror(ret)); + goto fail; + } + + printf("\t{\n"); + printf("\t\t\"type\": \"rules\",\n"); + printf("\t\t\"retval\": %u,\n", error); + if (error == SSS_SUDO_ERROR_OK) { + print_sss_result(result); + } + printf("\t}\n"); + printf("]\n"); + + + free(domainname); + sss_sudo_free_result(result); + return 0; + +fail: + free(domainname); + sss_sudo_free_result(result); + return 1; +} + +void print_sss_result(struct sss_sudo_result *result) +{ + struct sss_sudo_rule *rule = NULL; + struct sss_sudo_attr *attr = NULL; + int i = 0; + int j = 0; + int k = 0; + + printf("\t\t\"result\": {\n"); + printf("\t\t\t\"num_rules\": %d,\n", result->num_rules); + printf("\t\t\t\"rules\": [\n"); + for (i = 0; i < result->num_rules; i++) { + rule = &result->rules[i]; + printf("\t\t\t\t{\n"); + for (j = 0; j < rule->num_attrs; j++) { + attr = &rule->attrs[j]; + printf("\t\t\t\t\t\"%s\": ", attr->name); + if (attr->num_values > 1) { + printf("[ "); + printf("\"%s\"", attr->values[0]); + for (k = 1; k < attr->num_values; k++) { + printf(", \"%s\"", attr->values[k]); + } + printf(" ]"); + } else { + printf("\"%s\"", attr->values[0]); + } + + if (j < rule->num_attrs - 1) { + printf(","); + } + printf("\n"); + } + printf("\t\t\t\t}"); + if (i < result->num_rules - 1) { + printf(","); + } + printf("\n"); + } + printf("\t\t\t]\n"); + printf("\t\t}\n"); +} |