pax_global_header00006660000000000000000000000064132030221260014501gustar00rootroot0000000000000052 comment=c50ed60c7b405bd3c8da4bf61db42e85caaf4407 openfortivpn-1.6.0/000077500000000000000000000000001320302212600142365ustar00rootroot00000000000000openfortivpn-1.6.0/.gitignore000066400000000000000000000002771320302212600162340ustar00rootroot00000000000000*.o .deps aclocal.m4 autom4te.cache compile config.log config.status configure cscope.* depcomp install-sh Makefile Makefile.in missing openfortivpn .dirstamp doc/*.1 config.sub config.guess openfortivpn-1.6.0/.travis.yml000066400000000000000000000010651320302212600163510ustar00rootroot00000000000000language: c sudo: false install: - > [ -f $HOME/astyle/build/gcc/bin/astyle ] || { wget -O astyle_2.05.1_linux.tar.gz http://sourceforge.net/projects/astyle/files/astyle/astyle%202.05.1/astyle_2.05.1_linux.tar.gz/download; tar -xf astyle_2.05.1_linux.tar.gz -C $HOME; make -C $HOME/astyle/build/gcc; } - make -C $HOME/astyle/build/gcc prefix=$HOME install cache: directories: - $HOME/astyle script: - ./tests/lint/run.sh - > ./autogen.sh && ./configure --prefix=/usr --sysconfdir=/etc && make openfortivpn-1.6.0/LICENSE000066400000000000000000001060631320302212600152510ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . Exception In addition, as a special exception, the copyright holders give permission to link the code of portions of this program with the OpenSSL library under certain conditions as described in each individual source file, and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than OpenSSL. If you modify file(s) with this exception, you may extend this exception to your version of the file(s), but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. If you delete this exception statement from all source files in the program, then also delete it here. openfortivpn-1.6.0/LICENSE.OpenSSL000066400000000000000000000142061320302212600165300ustar00rootroot00000000000000 LICENSE ISSUES ============== The OpenSSL toolkit stays under a dual license, i.e. both the conditions of the OpenSSL License and the original SSLeay license apply to the toolkit. See below for the actual license texts. Actually both licenses are BSD-style Open Source licenses. In case of any license issues related to OpenSSL please contact openssl-core@openssl.org. OpenSSL License --------------- /* ==================================================================== * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved. * * 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ Original SSLeay License ----------------------- /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ openfortivpn-1.6.0/Makefile.am000066400000000000000000000023471320302212600163000ustar00rootroot00000000000000# http://mij.oltrelinux.com/devel/autoconf-automake/ bin_PROGRAMS = openfortivpn openfortivpn_SOURCES = src/config.c src/config.h src/hdlc.c src/hdlc.h \ src/http.c src/http.h src/io.c src/io.h src/ipv4.c \ src/ipv4.h src/log.c src/log.h src/tunnel.c \ src/tunnel.h src/main.c src/ssl.h src/xml.c \ src/xml.h src/userinput.c src/userinput.h openfortivpn_CFLAGS = -Wall --pedantic -std=gnu99 openfortivpn_CPPFLAGS = -DSYSCONFDIR=\"$(sysconfdir)\" openfortivpn_CFLAGS += $(OPENSSL_CFLAGS) openfortivpn_LDADD = $(OPENSSL_LIBS) DISTCHECK_CONFIGURE_FLAGS = CFLAGS=-Werror confdir=$(sysconfdir)/openfortivpn datadir=$(prefix)/share/openfortivpn data_DATA=etc/openfortivpn/config.template install-data-hook: chmod 0600 $(DESTDIR)$(datadir)/config.template ; \ if ! test -e $(DESTDIR)$(sysconfdir)/openfortivpn/config ; then \ mkdir -p $(DESTDIR)$(sysconfdir)/openfortivpn ; \ cp -a $(DESTDIR)$(datadir)/config.template \ $(DESTDIR)$(sysconfdir)/openfortivpn/config ; \ fi dist_man_MANS = doc/openfortivpn.1 doc/openfortivpn.1: $(srcdir)/doc/openfortivpn.1.in sed -e 's|[@]SYSCONFDIR[@]|$(sysconfdir)|g;s|[@]DATADIR[@]|$(datadir)|g;' $^ >$@ EXTRA_DIST = LICENSE README.md doc/openfortivpn.1.in $(data_DATA) openfortivpn-1.6.0/README.md000066400000000000000000000076261320302212600155300ustar00rootroot00000000000000openfortivpn ============ openfortivpn is a client for PPP+SSL VPN tunnel services. It spawns a pppd process and operates the communication between the gateway and this process. It is compatible with Fortinet VPNs. -------- Examples -------- * Simply connect to a VPN: ``` openfortivpn vpn-gateway:8443 --username=foo ``` * Connect to a VPN using an authentication realm: ``` openfortivpn vpn-gateway:8443 --username=foo --realm=bar ``` * Don't set IP routes and don't add VPN nameservers to `/etc/resolv.conf`: ``` openfortivpn vpn-gateway:8443 -u foo -p bar --no-routes --no-dns ``` * Using a config file: ``` openfortivpn ``` With `/etc/openfortivpn/config` containing: ``` host = vpn-gateway port = 8443 username = foo password = bar set-dns = 0 set-routes = 0 # X509 certificate sha256 sum, trust only this one! trusted-cert = e46d4aff08ba6914e64daa85bc6112a422fa7ce16631bff0b592a28556f993db ``` ---------- Installing ---------- openfortivpn is packaged for [Fedora](https://admin.fedoraproject.org/pkgdb/package/rpms/openfortivpn/), [openSUSE / SLE](https://software.opensuse.org/package/openfortivpn), [Gentoo](https://packages.gentoo.org/packages/net-vpn/openfortivpn), [NixOS](https://github.com/NixOS/nixpkgs/tree/master/pkgs/tools/networking/openfortivpn), [Arch Linux](https://aur.archlinux.org/packages/openfortivpn) and [Solus](https://packages.solus-project.com/unstable/o/openfortivpn/) under the package name `openfortivpn`. For other distros, you'll need to build and install from source: 1. Install build dependencies. * RHEL/CentOS/Fedora: `gcc` `automake` `autoconf` `openssl-devel` * Debian/Ubuntu: `gcc` `automake` `autoconf` `libssl-dev` * Arch Linux: `gcc` `automake` `autoconf` `openssl` * Gentoo Linux: `net-dialup/ppp` * openSUSE: `gcc` `automake` `autoconf` `libopenssl-devel` * macOS(Homebrew): `automake` `autoconf` `openssl@1.0` On Linux, if you manage your kernel yourself, ensure to compile those modules: ``` CONFIG_PPP=m CONFIG_PPP_ASYNC=m ``` On macOS, install 'Homebrew' to install the build dependencies: ```shell # Install 'Homebrew' /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" # Install Dependencies brew install automake autoconf openssl@1.0 ``` On macOS, install 'openfortivpn'... ``` brew install openfortivpn ``` ...**or** build a version of your choice from source following the instructions in step 2. 2. Build and install. ```shell ./autogen.sh ./configure --prefix=/usr/local --sysconfdir=/etc make sudo make install ``` If you need to specify the openssl location you can set the `$PKG_CONFIG_PATH` environment variable. ---------------- Running as root? ---------------- openfortivpn needs elevated privileges at three steps during tunnel set up: * when spawning a `/usr/sbin/pppd` process; * when setting IP routes through VPN (when the tunnel is up); * when adding nameservers to `/etc/resolv.conf` (when the tunnel is up). For these reasons, you may need to use `sudo openfortivpn`. If you need it to be usable by non-sudoer users, you might consider adding an entry in `/etc/sudoers`. For example: `visudo -f /etc/sudoers.d/openfortivpn` ``` Cmnd_Alias OPENFORTIVPN = /usr/bin/openfortivpn %adm ALL = (ALL) OPENFORTIVPN ``` **Warning**: Make sure only trusted users can run openfortivpn as root! As described in [#54](https://github.com/adrienverge/openfortivpn/issues/54), a malicious user could use `--pppd-plugin` and `--pppd-log` options to divert the program's behaviour. ------------ Contributing ------------ Feel free to make pull requests! C coding style should follow the [Linux kernel Documentation/CodingStyle](http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/Documentation/process/coding-style.rst?id=refs/heads/master). openfortivpn-1.6.0/autogen.sh000077500000000000000000000000741320302212600162400ustar00rootroot00000000000000#!/bin/sh set -exu aclocal autoconf automake --add-missing openfortivpn-1.6.0/configure.ac000066400000000000000000000022511320302212600165240ustar00rootroot00000000000000# -*- Autoconf -*- # Process this file with autoconf to produce a configure script. AC_PREREQ([2.68]) AC_INIT([openfortivpn], [1.6.0]) AC_CONFIG_SRCDIR([src/main.c]) AM_INIT_AUTOMAKE([foreign subdir-objects]) # Checks for programs. AC_PROG_CC AC_GNU_SOURCE # Helps support multiarch by setting 'host_os' and 'host_cpu' AC_CANONICAL_HOST AM_SILENT_RULES([yes]) # Checks for libraries. PKG_CHECK_MODULES(OPENSSL, [libcrypto libssl]) AC_CHECK_LIB([pthread], [pthread_create], [], [AC_MSG_ERROR([Cannot find libpthread.])]) AC_CHECK_LIB([util], [forkpty], [], [AC_MSG_ERROR([Cannot find libutil.])]) # Checks for header files. AC_CHECK_HEADERS([arpa/inet.h fcntl.h netdb.h netinet/in.h stddef.h stdint.h stdlib.h string.h strings.h sys/ioctl.h sys/socket.h unistd.h]) # Checks for typedefs, structures, and compiler characteristics. AC_C_INLINE AC_TYPE_OFF_T AC_TYPE_PID_T AC_TYPE_SIZE_T AC_TYPE_SSIZE_T AC_TYPE_UINT16_T AC_TYPE_UINT32_T AC_TYPE_UINT8_T # Checks for library functions. AC_FUNC_MALLOC AC_FUNC_REALLOC AC_CHECK_FUNCS([getaddrinfo inet_ntoa ntohs memmove memset memmem select socket strerror strstr strtol]) AC_OUTPUT(Makefile) openfortivpn-1.6.0/doc/000077500000000000000000000000001320302212600150035ustar00rootroot00000000000000openfortivpn-1.6.0/doc/openfortivpn.1.in000066400000000000000000000156461320302212600202370ustar00rootroot00000000000000.TH OPENFORTIVPN 1 "October 23, 2017" "" .SH NAME openfortivpn \- Client for PPP+SSL VPN tunnel services .SH SYNOPSIS .B openfortivpn [\fI\fR:\fI\fR] [\fB\-u\fR \fI\fR] [\fB\-p\fR \fI\fR] [\fB\-\-realm=\fI\fR] [\fB\-\-set-routes=\fR] [\fB\-\-no-routes\fR] [\fB\-\-set-dns=\fR] [\fB\-\-half-internet-routes=\fR] [\fB\-\-no-dns\fR] [\fB\-\-ca-file=\fI\fR] [\fB\-\-user-cert=\fI\fR] [\fB\-\-user-key=\fI\fR] [\fB\-\-use-syslog\fR] [\fB\-\-trusted-cert=\fI\fR] [\fB\-\-insecure-ssl\fR] [\fB\-\-cipher-list=\fI\fR] [\fB\-\-pppd-no-peerdns\fR] [\fB\-\-pppd-log=\fI\fR] [\fB\-\-pppd-plugin=\fI\fR] [\fB\-\-pppd-ipparam=\fI\fR] [\fB\-\-pppd-ifname=\fI\fR] [\fB\-c\fR \fI\fR] [\fB\-v|\-q\fR] .br .B openfortivpn \-\-help .br .B openfortivpn \-\-version .SH DESCRIPTION .B openfortivpn connects to a VPN by setting up a tunnel to the gateway at \fI\fR:\fI\fR. .SH OPTIONS .TP \fB\-\-help\fR Show this help message and exit. .TP \fB\-\-version\fR Show version and exit. .TP \fB\-c \fI\fR, \fB\-\-config=\fI\fR Specify a custom config file (default: @SYSCONFDIR@/openfortivpn/config). .TP \fB\-u \fI\fR, \fB\-\-username=\fI\fR VPN account username. .TP \fB\-p \fI\fR, \fB\-\-password=\fI\fR VPN account password. .TP \fB\-\-realm=\fI\fR Connect to the specified authentication realm. Defaults to empty, which is usually what you want. .TP \fB\-\-set-routes=\fI\fR, \fB\-\-no-routes\fR Set if we should try to configure IP routes through the VPN when tunnel is up. If used multiple times, the last one takes priority. \fB\-\-no-routes\fR is the same as \fB\-\-set-routes=\fI0\fR. .TP \fB\-\-half-internet-routes=\fI\fR, if set to 1, tells openfortivpn not to replace the default route by a different one, but set up two separate /1-routes instead. .TP \fB\-\-set-dns=\fI\fR, \fB\-\-no-dns\fR Set if we should add VPN nameservers in /etc/resolv.conf when tunnel is up. If used multiple times, the last one takes priority. \fB\-\-no-dns\fR is the same as \fB\-\-set-dns=\fI0\fR. .TP \fB\-\-ca-file=\fI\fR Use specified PEM-encoded certificate bundle instead of system-wide store to verify the gateway certificate. .TP \fB\-\-user-cert=\fI\fR Use specified PEM-encoded certificate if the server requires authentication with a certificate. .TP \fB\-\-user-key=\fI\fR Use specified PEM-encoded key if the server requires authentication with a certificate. .TP \fB\-\-use-syslog\fR Log to syslog instead of terminal. .TP \fB\-\-trusted-cert=\fI\fR Trust a given gateway. If classical SSL certificate validation fails, the gateway certificate will be matched against this value. \fI\fR is the X509 certificate's sha256 sum. This option can be used multiple times to trust several certificates. .TP \fB\-\-insecure-ssl\fR Do not disable insecure SSL protocols/ciphers. If your server requires a specific cipher, consider using \fB\-\-cipher-list\fR instead. .TP \fB\-\-cipher-list=\fI\fR Openssl ciphers to use. If default does not work, you can try alternatives such as HIGH:!MD5:!RC4 or as suggested by the Cipher: line in the output of \fBopenssl\fP(1) (e.g. AES256-GCM-SHA384): $ openssl s_client -connect \fI\fR (default: HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4) .TP \fB\-\-pppd-no-peerdns\fR Do not ask peer ppp server for DNS addresses and do not make pppd rewrite /etc/resolv.conf. .TP \fB\-\-pppd-log=\fI\fR Set pppd in debug mode and save its logs into \fI\fR. .TP \fB\-\-pppd-plugin=\fI\fR Use specified pppd plugin instead of configuring the resolver and routes directly. .TP \fB\-\-pppd-ipparam=\fI\fR Provides an extra parameter to the ip-up, ip-pre-up and ip-down scripts. See man .BR pppd(8) for further details .TP \fB\-\-pppd-ifname=\fI\fR Set the ppp interface name. Only if supported by pppd. Patched versions of pppd implement this option but may not be available on your platform. .TP \fB\-v\fR Increase verbosity. Can be used multiple times to be even more verbose. .TP \fB\-q\fR Decrease verbosity. Can be used multiple times to be even less verbose. .SH ENVIRONMENT and proxy support .B openfortivpn can be run behind a http that supports the http connect command. It checks if one of the environment variables .B https_proxy HTTPS_PROXY all_proxy ALL_PROXY is set which are supposed to contain a string of the format .br .B http://[host]:[port] .br where .B [host] is the ip or the fully qualified host name of the proxy server .B [port] is the tcp port number where the proxy is listening for incoming connections. If one of these variables is defined, .B openfortivpn tries to first establish a tcp connection to this proxy (plain http, not encrypted), and then makes a request to connect to the vpn host as given on the command line or in the config file. The proxy is supposed to forward any subsequent packets transparently to the vpn host, so that the tls layer of the connection effectively is establshed between the client and the vpn host, and the proxy just acts as a forwarding instance on the lower level of the tcp connection. The following environment variables are set by .B openfortivpn and .BR pppd(8) or its scripts can obtain information this way: .br VPN_GATEWAY the ip of the gateway host .br and for each route three variables are set up, where an integer number is appended to the variable names, denoting the number of the current route: .br VPN_ROUTE_DEST_... the destination network of the route .br VPN_ROUTE_MASK_... the network mask for this route .br VPN_ROUTE_GATEWAY_... the gateway for the current route entry .SH CONFIG FILE Options can be taken from a configuration file. Options passed in the command line will override those from the config file, though. The default config file is @SYSCONFDIR@/openfortivpn/config, but this can be set using the \fB\-c\fR option. An empty template for the config file is installed to @DATADIR@/config.template .TP A config file looks like: # this is a comment .br host = vpn-gateway .br port = 8443 .br username = foo .br password = bar .br user-cert = @SYSCONFDIR@/openfortivpn/user-cert.pem .br user-key = @SYSCONFDIR@/openfortivpn/user-key.pem .br # the sha256 digest of the trusted host certs obtained by .br # openssl dgst -sha256 server-cert.pem: .br trusted-cert = certificatedigest4daa8c5fe6c... .br trusted-cert = othercertificatedigest6631bf... .br # This would specify a ca bundle instead of system-wide store .br # ca-file = @SYSCONFDIR@/openfortivpn/ca-bundle.pem .br set-dns = 1 .br set-routes = 1 .br half-internet-routes = 0 .br pppd-use-peerdns = 1 .br # aternatively, use a specific pppd plugin instead .br # pppd-plugin = /usr/lib/pppd/default/some-plugin.so .br # for debugging pppd write logs here .br # pppd-log = /var/log/pppd.log .br # pass an ipparam string to pppd .br # pppd-ipparam = somestringtopasstopppd .br insecure-ssl = 0 .br cipher-list = HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4 openfortivpn-1.6.0/etc/000077500000000000000000000000001320302212600150115ustar00rootroot00000000000000openfortivpn-1.6.0/etc/openfortivpn/000077500000000000000000000000001320302212600175425ustar00rootroot00000000000000openfortivpn-1.6.0/etc/openfortivpn/config.template000066400000000000000000000001341320302212600225420ustar00rootroot00000000000000# config file for openfortivpn, see man openfortivpn(1) host = port = username = password = openfortivpn-1.6.0/src/000077500000000000000000000000001320302212600150255ustar00rootroot00000000000000openfortivpn-1.6.0/src/config.c000066400000000000000000000157151320302212600164470ustar00rootroot00000000000000/* * Copyright (C) 2015 Adrien Vergé * * 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 . */ #include "config.h" #include "log.h" #include #include #include #include #include /* * Adds a sha256 digest to the list of trusted certificates. */ int add_trusted_cert(struct vpn_config *cfg, const char *digest) { struct x509_digest *last, *new; new = malloc(sizeof(struct x509_digest)); if (new == NULL) return ERR_CFG_NO_MEM; new->next = NULL; strncpy(new->data, digest, SHA256STRLEN - 1); new->data[SHA256STRLEN - 1] = '\0'; if (cfg->cert_whitelist == NULL) { cfg->cert_whitelist = new; } else { for (last = cfg->cert_whitelist; last->next != NULL; last = last->next) ; last->next = new; } return 0; } /* * Converts string to bool int * * @params[in] str the string to read from * @return 0 or 1 if successful, < 0 if unrecognized value */ int strtob(const char *str) { if (str[0] == '\0') return 0; else if (strcasecmp(str, "true") == 0) return 1; else if (strcasecmp(str, "false") == 0) return 0; else if (isdigit(str[0]) == 0) return -1; long int i = strtol(str, NULL, 0); if (i < 0 || i > 1) return -1; return i; } /* * Reads filename contents and fill cfg with its values. * * @param[out] cfg the struct vpn_config to store configuration values * @param[in] filename the file to read values from * @return 0 if successful, or < 0 in case of error */ int load_config(struct vpn_config *cfg, const char *filename) { int ret = ERR_CFG_UNKNOWN; FILE *file; struct stat stat; char *buffer, *line; file = fopen(filename, "r"); if (file == NULL) return ERR_CFG_SEE_ERRNO; if (fstat(fileno(file), &stat) == -1) { ret = ERR_CFG_SEE_ERRNO; goto err_close; } if (stat.st_size == 0) { ret = ERR_CFG_EMPTY_FILE; goto err_close; } buffer = malloc(stat.st_size + 1); if (buffer == NULL) { ret = ERR_CFG_NO_MEM; goto err_close; } // Copy all file contents at once if (fread(buffer, stat.st_size, 1, file) != 1) { ret = ERR_CFG_CANNOT_READ; goto err_free; } buffer[stat.st_size] = '\0'; // Read line by line for (line = strtok(buffer, "\n"); line != NULL; line = strtok(NULL, "\n")) { char *key, *equals, *val; int i; if (line[0] == '#') continue; // Expect something like: "key = value" equals = strchr(line, '='); if (equals == NULL) { log_warn("Bad line in config file: \"%s\".\n", line); continue; } equals[0] = '\0'; key = line; val = equals + 1; // Remove heading spaces while (key[0] != '\0' && (key[0] == ' ' || key[0] == '\t')) key++; while (val[0] != '\0' && (val[0] == ' ' || val[0] == '\t')) val++; // Remove trailing spaces for (i = strlen(key) - 1; i > 0; i--) { if (key[i] == ' ' || key[i] == '\t') key[i] = '\0'; else break; } for (i = strlen(val) - 1; i > 0; i--) { if (val[i] == ' ' || val[i] == '\t') val[i] = '\0'; else break; } if (strcmp(key, "host") == 0) { strncpy(cfg->gateway_host, val, FIELD_SIZE); cfg->gateway_host[FIELD_SIZE] = '\0'; } else if (strcmp(key, "port") == 0) { long int port = strtol(val, NULL, 0); if (port <= 0 || port > 65535) { log_warn("Bad port in config file: \"%d\".\n", port); continue; } cfg->gateway_port = port; } else if (strcmp(key, "username") == 0) { strncpy(cfg->username, val, FIELD_SIZE - 1); cfg->username[FIELD_SIZE] = '\0'; } else if (strcmp(key, "password") == 0) { strncpy(cfg->password, val, FIELD_SIZE - 1); cfg->password[FIELD_SIZE] = '\0'; } else if (strcmp(key, "otp") == 0) { strncpy(cfg->otp, val, FIELD_SIZE - 1); cfg->otp[FIELD_SIZE] = '\0'; } else if (strcmp(key, "realm") == 0) { strncpy(cfg->realm, val, FIELD_SIZE - 1); cfg->realm[FIELD_SIZE] = '\0'; } else if (strcmp(key, "set-dns") == 0) { int set_dns = strtob(val); if (set_dns < 0) { log_warn("Bad set-dns in config file: \"%s\".\n", val); continue; } cfg->set_dns = set_dns; } else if (strcmp(key, "set-routes") == 0) { int set_routes = strtob(val); if (set_routes < 0) { log_warn("Bad set-routes in config file: \"%s\".\n", val); continue; } cfg->set_routes = set_routes; } else if (strcmp(key, "half-internet-routes") == 0) { int half_internet_routes = strtob(val); if (half_internet_routes < 0) { log_warn("Bad half-internet-routes in config" \ " file: \"%s\".\n", val); continue; } cfg->half_internet_routes = half_internet_routes; } else if (strcmp(key, "pppd-use-peerdns") == 0) { int pppd_use_peerdns = strtob(val); if (pppd_use_peerdns < 0) { log_warn("Bad pppd-use-peerdns in config file:" " \"%s\".\n", val); continue; } cfg->pppd_use_peerdns = pppd_use_peerdns; } else if (strcmp(key, "pppd-log") == 0) { cfg->pppd_log = strdup(val); } else if (strcmp(key, "pppd-plugin") == 0) { cfg->pppd_plugin = strdup(val); } else if (strcmp(key, "pppd-ipparam") == 0) { cfg->pppd_ipparam = strdup(val); } else if (strcmp(key, "pppd-ifname") == 0) { cfg->pppd_ifname = strdup(val); } else if (strcmp(key, "use-syslog") == 0) { int use_syslog = strtob(val); if (use_syslog < 0) { log_warn("Bad use-syslog in config file: \"%s\".\n", val); continue; } cfg->use_syslog = use_syslog; } else if (strcmp(key, "trusted-cert") == 0) { if (strlen(val) != SHA256STRLEN - 1) { log_warn("Bad certificate sha256 digest in " "config file: \"%s\".\n", val); continue; } if (add_trusted_cert(cfg, val)) log_warn("Could not add certificate digest to " "whitelist.\n"); } else if (strcmp(key, "ca-file") == 0) { cfg->ca_file = strdup(val); } else if (strcmp(key, "user-cert") == 0) { cfg->user_cert = strdup(val); } else if (strcmp(key, "user-key") == 0) { cfg->user_key = strdup(val); } else if (strcmp(key, "insecure-ssl") == 0) { int insecure_ssl = strtob(val); if (insecure_ssl < 0) { log_warn("Bad insecure-ssl in config file: \"%s\".\n", val); continue; } cfg->insecure_ssl = insecure_ssl; } else if (strcmp(key, "cipher-list") == 0) { cfg->cipher_list = strdup(val); } else { log_warn("Bad key in config file: \"%s\".\n", key); goto err_free; } } ret = 0; err_free: free(buffer); err_close: fclose(file); return ret; } openfortivpn-1.6.0/src/config.h000066400000000000000000000044461320302212600164530ustar00rootroot00000000000000/* * Copyright (C) 2015 Adrien Vergé * * 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 . */ #ifndef _OPENFORTIVPN_CONFIG_H #define _OPENFORTIVPN_CONFIG_H #include #include #include #include #define ERR_CFG_UNKNOWN -1 #define ERR_CFG_SEE_ERRNO -2 #define ERR_CFG_EMPTY_FILE -3 #define ERR_CFG_NO_MEM -4 #define ERR_CFG_CANNOT_READ -5 static inline const char *err_cfg_str(int code) { if (code == ERR_CFG_SEE_ERRNO) return strerror(errno); else if (code == ERR_CFG_EMPTY_FILE) return "Empty file"; else if (code == ERR_CFG_NO_MEM) return "Not enough memory"; else if (code == ERR_CFG_CANNOT_READ) return "Cannot read file"; return "unknown"; } #define SHA256LEN (256 / 8) #define SHA256STRLEN (2 * SHA256LEN + 1) struct x509_digest { struct x509_digest *next; char data[SHA256STRLEN]; }; #define FIELD_SIZE 64 #define COOKIE_SIZE 4096 struct vpn_config { char gateway_host[FIELD_SIZE + 1]; struct in_addr gateway_ip; uint16_t gateway_port; char username[FIELD_SIZE + 1]; char password[FIELD_SIZE + 1]; char otp[FIELD_SIZE + 1]; char cookie[COOKIE_SIZE + 1]; char realm[FIELD_SIZE + 1]; int set_routes; int set_dns; int pppd_use_peerdns; int use_syslog; int half_internet_routes; char *pppd_log; char *pppd_plugin; char *pppd_ipparam; char *pppd_ifname; char *ca_file; char *user_cert; char *user_key; int verify_cert; int insecure_ssl; char *cipher_list; struct x509_digest *cert_whitelist; }; int add_trusted_cert(struct vpn_config *cfg, const char *digest); int strtob(const char *str); int load_config(struct vpn_config *cfg, const char *filename); #endif openfortivpn-1.6.0/src/hdlc.c000066400000000000000000000172271320302212600161140ustar00rootroot00000000000000/* * Copyright (C) 2015 Adrien Vergé * * 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 . */ #include "hdlc.h" #define in_sending_accm(byte) \ ((byte) < 0x20 || ((byte) & 0x7f) == 0x7d || ((byte) & 0x7f) == 0x7e) #define in_receiving_accm(byte) \ ((byte) < 0x20) static uint16_t fcs_tab[] = { 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78 }; /* * 16-bit frame check sequence from RFC1662. */ static uint16_t frame_checksum_16bit(uint16_t sum, uint8_t *seq, size_t length) { size_t i; for (i = 0; i < length; i++) sum = (sum >> 8) ^ fcs_tab[0xff & (sum ^ seq[i])]; return sum; } static int need_flag_sequence = 1; /* * Wraps a PPP packet into a HDLC frame and write it to a buffer. * * @param[out] frame the buffer to store the encoded frame * @param[in] frmsize the output buffer size * @param[in] packet the buffer containing the packet * @param[in] pktsize the input packet size * @return the number of bytes written to the buffer (i.e. the * HDLC-encoded frame length) or ERR_HDLC_BUFFER_TOO_SMALL * if the output buffer is too small */ ssize_t hdlc_encode(uint8_t *frame, size_t frmsize, uint8_t *packet, size_t pktsize) { ssize_t written = 0; uint16_t checksum; uint8_t address_control_prefix[] = { 0xff, 0x03 }; int i; uint8_t byte; if (frmsize < 7) return ERR_HDLC_BUFFER_TOO_SMALL; if (need_flag_sequence) frame[written++] = 0x7e; // FlagSequence // Escape and write AddressControlPrefix (0xff 0x03) frame[written++] = 0xff; frame[written++] = 0x7d; frame[written++] = 0x23; checksum = frame_checksum_16bit(0xffff, address_control_prefix, 2); checksum = frame_checksum_16bit(checksum, packet, pktsize); for (i = 0; i < pktsize; i++) { byte = packet[i]; if (frmsize < written + 2) return ERR_HDLC_BUFFER_TOO_SMALL; if (in_sending_accm(byte)) { frame[written++] = 0x7d; frame[written++] = byte ^ 0x20; } else { frame[written++] = byte; } } if (frmsize < written + 3) return ERR_HDLC_BUFFER_TOO_SMALL; // Escape and write checksum byte = (checksum ^ 0xffff) & 0xff; if (in_sending_accm(byte)) { frame[written++] = 0x7d; frame[written++] = byte ^ 0x20; } else { frame[written++] = byte; } byte = (checksum ^ 0xffff) >> 8; if (in_sending_accm(byte)) { frame[written++] = 0x7d; frame[written++] = byte ^ 0x20; } else { frame[written++] = byte; } frame[written++] = 0x7e; // FlagSequence need_flag_sequence = 0; return written; } /* * Finds the first frame in a buffer, starting search at start. * * Return ERR_HDLC_NO_FRAME_FOUND if no frame is found. Otherwise, returns the * first frame length and sets start to its beginning offset in the buffer. */ ssize_t hdlc_find_frame(uint8_t *buffer, size_t bufsize, off_t *start) { int i, s = -1, e = -1; // Look for frame start for (i = *start; i < bufsize - 2; i++) { if (buffer[i] == 0x7e) { // FlagSequence s = i + 1; break; } } if (s == -1) return ERR_HDLC_NO_FRAME_FOUND; // Discard empty packets while (s < bufsize - 2 && buffer[s] == 0x7e) s++; // Look for frame end for (i = s; i < bufsize; i++) { if (buffer[i] == 0x7e) { // FlagSequence e = i; break; } } if (e == -1) return ERR_HDLC_NO_FRAME_FOUND; *start = s; return e - s; } /* * Extracts the first PPP packet found in the input buffer. * * The frame should be passed without its surrounding 0x7e bytes. * * @param[in] frame the buffer containing the encoded frame * @param[in] frmsize the input buffer size * @param[out] packet the buffer to store the decoded packet * @param[in] pktsize the output packet buffer size * @return the number of bytes written to the output packet * buffer, or < 0 in case of error */ ssize_t hdlc_decode(uint8_t *frame, size_t frmsize, uint8_t *packet, size_t pktsize) { off_t start = 0; ssize_t written = 0; int has_address_control_prefix = 0; int i; int in_escape; uint16_t checksum; if (frmsize < 5) return ERR_HDLC_INVALID_FRAME; // Remove AddressControlPrefix (0xff 0x03, escaped) if (frame[0] == 0xff && frame[1] == 0x7d && frame[2] == 0x23) { start += 3; has_address_control_prefix = 1; } in_escape = 0; for (i = start; i < frmsize; i++) { uint8_t byte = frame[i]; if (byte == 0x7d) { // ControlEscape if (in_escape) return ERR_HDLC_INVALID_FRAME; in_escape = 1; continue; } else if (in_escape) { byte ^= 0x20; // ControlModifier in_escape = 0; } else if (in_receiving_accm(byte)) { continue; // Drop characters possibly introduced by DCE } if (written >= pktsize) return ERR_HDLC_BUFFER_TOO_SMALL; packet[written++] = byte; } if (in_escape) return ERR_HDLC_INVALID_FRAME; if (written < 3) return ERR_HDLC_INVALID_FRAME; // Control checksum validity and remove it from packet if (has_address_control_prefix) checksum = 0x3de3; // Precomputed checksum for { 0xff, 0x03 } else checksum = 0xffff; checksum = frame_checksum_16bit(checksum, packet, written); if (checksum != 0xf0b8) return ERR_HDLC_BAD_CHECKSUM; written -= 2; return written; } openfortivpn-1.6.0/src/hdlc.h000066400000000000000000000030601320302212600161070ustar00rootroot00000000000000/* * Copyright (C) 2015 Adrien Vergé * * 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 . */ #ifndef _OPENFORTIVPN_HDLC_H #define _OPENFORTIVPN_HDLC_H #include #include #include #include #define ERR_HDLC_BUFFER_TOO_SMALL -1 #define ERR_HDLC_NO_FRAME_FOUND -2 #define ERR_HDLC_INVALID_FRAME -3 #define ERR_HDLC_BAD_CHECKSUM -4 /* * These macros are used to help decide how much to malloc before encoding or * decoding. They over-evaluate the output size so it is sure the output will * fit. */ #define estimated_encoded_size(ppp_pkt_len) (9 + 2 * (ppp_pkt_len)) #define estimated_decoded_size(hdlc_frm_len) (hdlc_frm_len) ssize_t hdlc_encode(uint8_t *frame, size_t frmsize, uint8_t *packet, size_t pktsize); ssize_t hdlc_find_frame(uint8_t *buffer, size_t bufsize, off_t *start); ssize_t hdlc_decode(uint8_t *frame, size_t frmsize, uint8_t *packet, size_t pktsize); #endif openfortivpn-1.6.0/src/http.c000066400000000000000000000411231320302212600161510ustar00rootroot00000000000000/* * Copyright (C) 2015 Adrien Vergé * * 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 . */ #include "http.h" #include "xml.h" #include "ssl.h" #include "ipv4.h" #include "userinput.h" #include "log.h" #include #include #define BUFSZ 0x8000 /* * URL-encodes a string for HTTP requests. * * The dest buffer size MUST be at least strlen(str) * 3 + 1. * * @param[out] dest the buffer to write the URL-encoded string * @param[in] str the input string to be escaped */ static void url_encode(char *dest, const char *str) { while (*str != '\0') { if (isalnum(*str) || *str == '-' || *str == '_' || *str == '.' || *str == '~') *dest++ = *str; else if (*str == ' ') *dest++ = '+'; else { static const char hex[] = "0123456789abcdef"; *dest++ = '%'; *dest++ = hex[*str >> 4]; *dest++ = hex[*str & 15]; } str++; } *dest = '\0'; } /* * Sends data to the HTTP server. * * @param[in] request the data to send to the server * @return 1 in case of success * < 0 in case of error */ int http_send(struct tunnel *tunnel, const char *request, ...) { va_list args; char buffer[BUFSZ]; int length; int n = 0; va_start(args, request); length = vsnprintf(buffer, BUFSZ, request, args); va_end(args); if (length < 0) return ERR_HTTP_INVALID; else if (length == BUFSZ) return ERR_HTTP_TOO_LONG; while (n == 0) n = safe_ssl_write(tunnel->ssl_handle, (uint8_t *) buffer, length); if (n < 0) { log_debug("Error writing to SSL connection (%s).\n", err_ssl_str(n)); return ERR_HTTP_SSL; } return 1; } static const char *find_header(const char *res, const char *header) { const char *line = res; while (memcmp(line, "\r\n", 2)) { int line_len = (char *) memmem(line, BUFSZ, "\r\n", 2) - line; int head_len = strlen(header); if (line_len > head_len && !strncasecmp(line, header, head_len)) return line + head_len; line += line_len + 2; } return NULL; } /* * Receives data from the HTTP server. * * @param[out] response if not NULL, this pointer is set to reference * the new allocated buffer containing the data * sent by the server * @return 1 in case of success * < 0 in case of error */ int http_receive(struct tunnel *tunnel, char **response) { char *buffer, *res; int n = 0; int bytes_read = 0; int header_size = 0; int content_size = 0; int chunked = 0; buffer = malloc(BUFSZ); if (buffer == NULL) return ERR_HTTP_NO_MEM; do { n = safe_ssl_read(tunnel->ssl_handle, (uint8_t *) buffer + bytes_read, BUFSZ - 1 - bytes_read); if (n > 0) { const char *eoh; bytes_read += n; if (!header_size) { /* Did we see the header end? Then get the body size. */ eoh = memmem(buffer, bytes_read, "\r\n\r\n", 4); if (eoh) { const char *header; header = find_header(buffer, "Content-Length: "); header_size = eoh - buffer + 4; if (header) content_size = atoi(header); if (find_header(buffer, "Transfer-Encoding: chunked")) chunked = 1; } } if (header_size) { /* We saw the whole header, let's check if the * body is done as well */ if (chunked) { /* Last chunk terminator. Done naively. */ if (bytes_read >= 7 && !memcmp(&buffer[bytes_read - 7], "\r\n0\r\n\r\n", 7)) break; } else { if (bytes_read >= header_size + content_size) break; } } if (bytes_read == BUFSZ - 1) { log_warn("Response too big\n"); free(buffer); return ERR_HTTP_SSL; } } } while (n >= 0); if (!header_size) { log_debug("Error reading from SSL connection (%s).\n", err_ssl_str(n)); free(buffer); return ERR_HTTP_SSL; } if (memmem(&buffer[header_size], bytes_read - header_size, "", 53) || memmem(buffer, header_size, "permission_denied denied", 24) || memmem(buffer, header_size, "Permission denied", 17)) { free(buffer); return ERR_HTTP_PERMISSION; } if (response == NULL) { free(buffer); return 1; } res = realloc(buffer, bytes_read + 1); if (res == NULL) { free(buffer); return ERR_HTTP_NO_MEM; } res[bytes_read] = '\0'; *response = res; return 1; } static int do_http_request(struct tunnel *tunnel, const char *method, const char *uri, const char *data, char **response) { int ret; char *template = ("%s %s HTTP/1.1\r\n" "Host: %s:%d\r\n" "User-Agent: Mozilla/5.0 SV1\r\n" "Accept: text/plain\r\n" "Accept-Encoding: identify\r\n" "Content-Type: application/x-www-form-urlencoded\r\n" "Cookie: %s\r\n" "Content-Length: %d\r\n" "\r\n%s"); ret = http_send(tunnel, template, method, uri, tunnel->config->gateway_host, tunnel->config->gateway_port, tunnel->config->cookie, strlen(data), data); if (ret != 1) return ret; return http_receive(tunnel, response); } /* * Sends and receives data from the HTTP server. * * @param[out] response if not NULL, this pointer is set to reference * the new allocated buffer containing the data * sent by the server * @return 1 in case of success * < 0 in case of error */ static int http_request(struct tunnel *tunnel, const char *method, const char *uri, const char *data, char **response) { int ret = do_http_request(tunnel, method, uri, data, response); if (ret == ERR_HTTP_SSL) { ssl_connect(tunnel); ret = do_http_request(tunnel, method, uri, data, response); } if (ret != 1) log_warn("Error issuing %s request\n", uri); return ret; } /* * Read value for key from a string like "key1=value1&key2=value2". * The `key` arg is supposed to contains the final "=". * * @return 1 in case of success * -1 key not found * -2 value too large for buffer * -3 if no memory */ static int get_value_from_response(const char *buf, const char *key, char *retbuf, size_t retbuflen) { int ret; char *tokens, *kv_pair; size_t keylen = strlen(key); tokens = strdup(buf); if (tokens == NULL) return -3; ret = -1; kv_pair = strtok(tokens, "&,\r\n"); for (; kv_pair != NULL; kv_pair = strtok(NULL, "&,\r\n")) { if (strncmp(key, kv_pair, keylen) == 0) { char *val = &kv_pair[keylen]; if (strlen(val) > retbuflen - 1) { // value too long ret = -2; } else { strcpy(retbuf, val); ret = 1; } break; } } free(tokens); return ret; } static int get_auth_cookie(struct tunnel *tunnel, char *buf) { int ret = 0; const char *line; ret = ERR_HTTP_NO_COOKIE; line = find_header(buf, "Set-Cookie: "); if (line) { if (strncmp(line, "SVPNCOOKIE=", 11) == 0) { if (line[11] == ';' || line[11] == '\0') { log_debug("Empty cookie.\n"); } else { char *end; end = strstr(line, "\r"); end[0] = '\0'; end = strstr(line, ";"); if (end != NULL) end[0] = '\0'; log_debug("Cookie: %s\n", line); strncpy(tunnel->config->cookie, line, COOKIE_SIZE); tunnel->config->cookie[COOKIE_SIZE] = '\0'; if (strlen(line) > COOKIE_SIZE) { log_error("Cookie larger than expected:" " %zu > %d\n", strlen(line), COOKIE_SIZE); } else { ret = 1; // success } } } } return ret; } static int try_otp_auth(struct tunnel *tunnel, const char *buffer, char **res) { char data[256]; char path[40]; char tmp[40]; char prompt[80]; const char *t = NULL, *n = NULL, *v = NULL, *e = NULL; const char *s = buffer; char *d = data; const char *p = NULL; /* Length-check for destination buffer */ #define SPACE_AVAILABLE(sz) (sizeof(data) - (d - data) >= (sz)) /* Get the form action */ s = strcasestr(s, " sizeof(path)) return -1; strncpy(path, s, e - s); path[e - s] = '\0'; /* Try to get password prompt, asume it starts with 'Please' * Fall back to default prompt if not found/parseable */ p = strstr(s, "Please"); if (p) { e = strchr(p, '<'); if (e != NULL) { if (e - p + 1 < sizeof(prompt)) { strncpy(prompt, p, e - p); prompt[e - p] = '\0'; p = prompt; } else { p = NULL; } } else { p = NULL; } } if (p == NULL) p = "Please enter one-time password:"; /* Search for all inputs */ while ((s = strcasestr(s, " data) { if (!SPACE_AVAILABLE(1)) return -1; *d++ = '&'; } e = strchr(n, '"'); if (e == NULL) return -1; if (e - n + 1 > sizeof(tmp)) return -1; strncpy(tmp, n, e - n); tmp[e - n] = '\0'; if (!SPACE_AVAILABLE(3 * (e - n) + 1)) return -1; url_encode(d, tmp); d += strlen(d); if (!SPACE_AVAILABLE(1)) return -1; *d++ = '='; } if (strncmp(t, "hidden", 6) == 0) { /* Require value for hidden fields */ if (v == NULL) return -1; v += 7; e = strchr(v, '"'); if (e == NULL) return -1; if (e - v + 1 > sizeof(tmp)) return -1; strncpy(tmp, v, e - v); tmp[e - v] = '\0'; if (!SPACE_AVAILABLE(3 * (e - v) + 1)) return -1; url_encode(d, tmp); d += strlen(d); } else if (strncmp(t, "password", 8) == 0) { struct vpn_config *cfg = tunnel->config; size_t l; v = NULL; if (cfg->otp[0] == '\0') { read_password(p, cfg->otp, FIELD_SIZE); if (cfg->otp[0] == '\0') { log_error("No OTP specified\n"); return 0; } } l = strlen(cfg->otp); if (!SPACE_AVAILABLE(3 * l + 1)) return -1; url_encode(d, cfg->otp); d += strlen(d); } else if (strncmp(t, "submit", 6) == 0) { /* avoid adding another '&' */ n = v = e = NULL; } } if (!SPACE_AVAILABLE(1)) return -1; *d++ = '\0'; return http_request(tunnel, "POST", path, data, res); #undef SPACE_AVAILABLE } /* * Authenticates to gateway by sending username and password. * * @return 1 in case of success * < 0 in case of error */ int auth_log_in(struct tunnel *tunnel) { int ret; char username[3 * FIELD_SIZE + 1]; char password[3 * FIELD_SIZE + 1]; char realm[3 * FIELD_SIZE + 1]; char reqid[32] = { '\0' }; char polid[32] = { '\0' }; char group[128] = { '\0' }; char data[256], token[128], tokenresponse[256]; char *res = NULL; url_encode(username, tunnel->config->username); url_encode(password, tunnel->config->password); url_encode(realm, tunnel->config->realm); tunnel->config->cookie[0] = '\0'; snprintf(data, 256, "username=%s&credential=%s&realm=%s&ajax=1" "&redir=%%2Fremote%%2Findex&just_logged_in=1", username, password, realm); ret = http_request(tunnel, "POST", "/remote/logincheck", data, &res); if (ret != 1) goto end; /* Probably one-time password required */ if (strncmp(res, "HTTP/1.1 401 Authorization Required\r\n", 37) == 0) { ret = try_otp_auth(tunnel, res, &res); if (ret != 1) goto end; } if (strncmp(res, "HTTP/1.1 200 OK\r\n", 17)) { ret = ERR_HTTP_BAD_RES_CODE; goto end; } ret = get_auth_cookie(tunnel, res); if (ret == ERR_HTTP_NO_COOKIE) { /* If the response body includes a tokeninfo= parameter, * it means the VPN gateway expects two-factor authentication. * It sends a one-time authentication credential for example * by email or SMS, and expects to receive it back in the * second authentication stage. No SVPNCOOKIE will be provided * until after the second call to /remote/logincheck. * * If we receive neither a tokeninfo= parameter nor an * SVPNCOOKIE, it means our authentication attempt was * rejected. */ ret = get_value_from_response(res, "tokeninfo=", token, 128); if (ret != 1) { // No SVPNCOOKIE and no tokeninfo, return error. ret = ERR_HTTP_NO_COOKIE; goto end; } // Two-factor authentication needed. get_value_from_response(res, "grp=", group, 128); get_value_from_response(res, "reqid=", reqid, 32); get_value_from_response(res, "polid=", polid, 32); read_password("Two-factor authentication token: ", tokenresponse, 255); snprintf(data, 256, "username=%s&realm=%s&reqid=%s&polid=%s&grp=%s" "&code=%s&code2=&redir=%%2Fremote%%2Findex&just_logged_in=1", username, realm, reqid, polid, group, tokenresponse); ret = http_request(tunnel, "POST", "/remote/logincheck", data, &res); if (ret != 1) goto end; if (strncmp(res, "HTTP/1.1 200 OK\r\n", 17)) { ret = ERR_HTTP_BAD_RES_CODE; goto end; } ret = get_auth_cookie(tunnel, res); } end: free(res); return ret; } int auth_log_out(struct tunnel *tunnel) { return http_request(tunnel, "GET", "/remote/logout", "", NULL); } int auth_request_vpn_allocation(struct tunnel *tunnel) { int ret = http_request(tunnel, "GET", "/remote/index", "", NULL); if (ret != 1) return ret; return http_request(tunnel, "GET", "/remote/fortisslvpn", "", NULL); } static int parse_xml_config(struct tunnel *tunnel, const char *buffer) { const char *val; char *gateway; if (strncmp(buffer, "HTTP/1.1 200 OK\r\n", 17)) return ERR_HTTP_BAD_RES_CODE; // Skip the HTTP header buffer = strstr(buffer, "\r\n\r\n"); // The address of a local end of a router val = xml_find('<', "assigned-addr", buffer, 1); gateway = xml_get(xml_find(' ', "ipv4=", val, 1)); if (!gateway) log_warn("No gateway address, using interface for routing\n"); // Routes the tunnel wants to push val = xml_find('<', "split-tunnel-info", buffer, 1); while ((val = xml_find('<', "addr", val, 2))) { char *dest, *mask; dest = xml_get(xml_find(' ', "ip=", val, 1)); if (!dest) { log_warn("No ip address for a route\n"); continue; } mask = xml_get(xml_find(' ', "mask=", val, 1)); if (!mask) { log_warn("No mask for a route\n"); free(dest); continue; } ipv4_add_split_vpn_route(tunnel, dest, mask, gateway); free(dest); free(mask); } free(gateway); return 1; } static int parse_config(struct tunnel *tunnel, const char *buffer) { char *c, *end; buffer = strcasestr(buffer, "NAME=\"text6\""); if (!buffer) return 1; buffer = strcasestr(buffer, "VALUE=\""); if (!buffer) return 1; buffer += 7; end = strchr(buffer, '"'); if (end == NULL || end == buffer) { log_info("No split VPN route\n"); return 1; } do { char dest[16], mask[16]; c = strchr(buffer, '/'); if (c == NULL || c >= end || c - buffer > 15) { log_warn("Wrong addresses in split VPN route: " "expected /\n"); return 1; } memcpy(dest, buffer, c - buffer); dest[c - buffer] = '\0'; buffer = c + 1; c = strchr(buffer, ','); if (c == NULL || c > end) c = end; if (c - buffer > 15) { log_warn("Wrong addresses in split VPN route: " "expected /\n"); return 1; } memcpy(mask, buffer, c - buffer); mask[c - buffer] = '\0'; buffer = c + 1; ipv4_add_split_vpn_route(tunnel, dest, mask, NULL); } while (c < end && *c == ','); return 1; } int auth_get_config(struct tunnel *tunnel) { char *buffer; int ret; ret = http_request(tunnel, "GET", "/remote/fortisslvpn_xml", "", &buffer); if (ret == 1) { ret = parse_xml_config(tunnel, buffer); free(buffer); } if (ret == 1) return ret; ret = http_request(tunnel, "GET", "/remote/fortisslvpn", "", &buffer); if (ret == 1) { ret = parse_config(tunnel, buffer); free(buffer); } return ret; } openfortivpn-1.6.0/src/http.h000066400000000000000000000034431320302212600161610ustar00rootroot00000000000000/* * Copyright (C) 2015 Adrien Vergé * * 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 . */ #ifndef _OPENFORTIVPN_HTTP_H #define _OPENFORTIVPN_HTTP_H #include "tunnel.h" #define ERR_HTTP_INVALID -1 #define ERR_HTTP_TOO_LONG -2 #define ERR_HTTP_NO_MEM -3 #define ERR_HTTP_SSL -4 #define ERR_HTTP_BAD_RES_CODE -5 #define ERR_HTTP_PERMISSION -6 #define ERR_HTTP_NO_COOKIE -7 static inline const char *err_http_str(int code) { if (code == ERR_HTTP_INVALID) return "Invalid input"; else if (code == ERR_HTTP_TOO_LONG) return "Request too long"; else if (code == ERR_HTTP_NO_MEM) return "Not enough memory"; else if (code == ERR_HTTP_SSL) return "SSL error"; else if (code == ERR_HTTP_BAD_RES_CODE) return "Bad HTTP response code"; else if (code == ERR_HTTP_PERMISSION) return "Permission denied"; else if (code == ERR_HTTP_NO_COOKIE) return "No cookie given"; return "unknown"; } int http_send(struct tunnel *tunnel, const char *request, ...); int http_receive(struct tunnel *tunnel, char **response); int auth_log_in(struct tunnel *tunnel); int auth_log_out(struct tunnel *tunnel); int auth_request_vpn_allocation(struct tunnel *tunnel); int auth_get_config(struct tunnel *tunnel); #endif openfortivpn-1.6.0/src/io.c000066400000000000000000000421531320302212600156050ustar00rootroot00000000000000/* * Copyright (C) 2015 Adrien Vergé * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * In addition, as a special exception, the copyright holders give permission * to link the code of portions of this program with the OpenSSL library under * certain conditions as described in each individual source file, and * distribute linked combinations including the two. * You must obey the GNU General Public License in all respects for all of the * code used other than OpenSSL. If you modify file(s) with this exception, * you may extend this exception to your version of the file(s), but you are * not obligated to do so. If you do not wish to do so, delete this exception * statement from your version. If you delete this exception statement from * all source files in the program, then also delete it here. */ #include "io.h" #include "hdlc.h" #include "ssl.h" #include "tunnel.h" #include "log.h" #include #include #include #include #ifdef __APPLE__ /* Mac OS X defines sem_init but actually does not implement them */ #include typedef semaphore_t os_semaphore_t; #define SEM_INIT(sem, x, value) semaphore_create(mach_task_self(), sem, \ SYNC_POLICY_FIFO, value) #define SEM_WAIT(sem) semaphore_wait(*sem) #define SEM_POST(sem) semaphore_signal(*sem) #define SEM_DESTROY(sem) semaphore_destroy(mach_task_self(), *sem) #else #include typedef sem_t os_semaphore_t; #define SEM_INIT(sem, x, value) sem_init(sem, x, value) #define SEM_WAIT(sem) sem_wait(sem) #define SEM_POST(sem) sem_post(sem) #define SEM_DESTROY(sem) sem_destroy(sem) #endif #define PKT_BUF_SZ 0x1000 #if OPENSSL_VERSION_NUMBER < 0x10100000L static pthread_mutex_t *lockarray; static void lock_callback(int mode, int type, char *file, int line) { if (mode & CRYPTO_LOCK) pthread_mutex_lock(&(lockarray[type])); else pthread_mutex_unlock(&(lockarray[type])); } static unsigned long thread_id(void) { return (unsigned long) pthread_self(); } static void init_ssl_locks(void) { int i; lockarray = (pthread_mutex_t *) OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t)); for (i = 0; i < CRYPTO_num_locks(); i++) pthread_mutex_init(&(lockarray[i]), NULL); CRYPTO_set_id_callback((unsigned long (*)()) thread_id); CRYPTO_set_locking_callback((void (*)()) lock_callback); } static void destroy_ssl_locks(void) { int i; CRYPTO_set_locking_callback(NULL); for (i = 0; i < CRYPTO_num_locks(); i++) pthread_mutex_destroy(&(lockarray[i])); OPENSSL_free(lockarray); } #else static void init_ssl_locks(void) { } static void destroy_ssl_locks(void) { } #endif /* * Adds a new packet to a pool. * * Warning: for performance reasons, this function does not check if the packet * is already present in the list. If it is, there will be a loop in the list * and this will result in an unpredictable behavior. */ static void pool_push(struct ppp_packet_pool *pool, struct ppp_packet *new) { struct ppp_packet *current; pthread_mutex_lock(&pool->mutex); new->next = NULL; current = pool->list_head; if (current == NULL) { pool->list_head = new; } else { while (current->next != NULL) current = current->next; current->next = new; } pthread_cond_signal(&pool->new_data); pthread_mutex_unlock(&pool->mutex); } /* * Gets the first packet from a pool. */ static struct ppp_packet *pool_pop(struct ppp_packet_pool *pool) { struct ppp_packet *first; pthread_mutex_lock(&pool->mutex); while (pool->list_head == NULL) pthread_cond_wait(&pool->new_data, &pool->mutex); first = pool->list_head; pool->list_head = first->next; first->next = NULL; pthread_mutex_unlock(&pool->mutex); return first; } static os_semaphore_t sem_pppd_ready; static os_semaphore_t sem_if_config; static os_semaphore_t sem_stop_io; /* * Thread to read bytes from the pppd pty, convert them to ppp packets and add * them to the 'pty_to_ssl' pool. */ static void *pppd_read(void *arg) { struct tunnel *tunnel = (struct tunnel *) arg; uint8_t buf[PKT_BUF_SZ]; int first_time = 1; off_t off_r, off_w; fd_set read_fd; FD_ZERO(&read_fd); FD_SET(tunnel->pppd_pty, &read_fd); log_debug("pppd_read_thread\n"); // Wait for pppd to be ready off_w = 0; while (1) { ssize_t n; int sel; sel = select(tunnel->pppd_pty + 1, &read_fd, NULL, NULL, NULL); if (sel == -1) { log_error("select: %s\n", strerror(errno)); break; } else if (sel == 0) { log_warn("select returned 0\n"); continue; } n = read(tunnel->pppd_pty, &buf[off_w], PKT_BUF_SZ - off_w); if (n == -1) { log_error("read: %s\n", strerror(errno)); break; } else if (n == 0) { log_warn("read returned %d\n", n); continue; } else if (first_time) { // pppd did talk, now we can write to it if we want SEM_POST(&sem_pppd_ready); first_time = 0; } off_w += n; // We have data in the buffer, there may be zero, one or many // packets inside. off_r = 0; while (1) { ssize_t frm_len, pktsize; struct ppp_packet *packet, *repacket; frm_len = hdlc_find_frame(buf, off_w, &off_r); if (frm_len == ERR_HDLC_NO_FRAME_FOUND) break; pktsize = estimated_decoded_size(frm_len); packet = malloc(sizeof(*packet) + 6 + pktsize); if (packet == NULL) { log_warn("malloc failed.\n"); break; } pktsize = hdlc_decode(&buf[off_r], frm_len, pkt_data(packet), pktsize); if (pktsize < 0) { log_error("Failed to decode PPP packet from " "HDLC frame (%s).\n", (pktsize == ERR_HDLC_BAD_CHECKSUM ? "bad checksum" : (pktsize == ERR_HDLC_INVALID_FRAME ? "invalid frame" : "unknown"))); goto exit; } // Reduce the malloc'ed area now that we know the // actual packet length repacket = realloc(packet, sizeof(*packet) + 6 + pktsize); if (repacket == NULL) { free(packet); goto exit; } packet = repacket; packet->len = pktsize; log_debug("pppd ---> gateway (%d bytes)\n", packet->len); log_packet("pppd: ", packet->len, pkt_data(packet)); pool_push(&tunnel->pty_to_ssl_pool, packet); off_r += frm_len; } // Do not discard remaining data if (off_r > 0 && off_r < off_w) memmove(buf, &buf[off_r], off_w - off_r); off_w = off_w - off_r; } exit: // Send message to main thread to stop other threads SEM_POST(&sem_stop_io); return NULL; } /* * Thread to pop packets from the 'ssl_to_pty' pool, and send them to the pppd * process through its pty. */ static void *pppd_write(void *arg) { struct tunnel *tunnel = (struct tunnel *) arg; fd_set write_fd; FD_ZERO(&write_fd); FD_SET(tunnel->pppd_pty, &write_fd); // Write for pppd to talk first, otherwise unpredictable SEM_WAIT(&sem_pppd_ready); log_debug("pppd_write thread\n"); while (1) { struct ppp_packet *packet; ssize_t hdlc_bufsize, len, n, written; uint8_t *hdlc_buffer; // This waits until a packet has arrived from the gateway packet = pool_pop(&tunnel->ssl_to_pty_pool); hdlc_bufsize = estimated_encoded_size(packet->len); hdlc_buffer = malloc(hdlc_bufsize); if (hdlc_buffer == NULL) { log_warn("malloc failed.\n"); break; } len = hdlc_encode(hdlc_buffer, hdlc_bufsize, pkt_data(packet), packet->len); if (len < 0) { log_error("Failed to encode PPP packet into HDLC " "frame.\n"); goto err_free_buf; } written = 0; while (written < len) { int sel; sel = select(tunnel->pppd_pty + 1, NULL, &write_fd, NULL, NULL); if (sel == -1) { log_error("select: %s\n", strerror(errno)); break; } else if (sel == 0) { log_warn("select returned 0\n"); continue; } n = write(tunnel->pppd_pty, &hdlc_buffer[written], len - written); if (n == -1) { log_error("write: %s\n", strerror(errno)); goto err_free_buf; } written += n; } free(hdlc_buffer); free(packet); continue; err_free_buf: free(hdlc_buffer); free(packet); break; } // Send message to main thread to stop other threads SEM_POST(&sem_stop_io); return NULL; } #define packet_is_ip_plus_dns(packet) \ ((packet)->len >= 12 \ && pkt_data(packet)[0] == 0x80 \ && pkt_data(packet)[1] == 0x21 \ && pkt_data(packet)[2] == 0x02 \ && pkt_data(packet)[6] == 0x03) #define packet_is_end_negociation(packet) \ ((packet)->len == 6 \ && pkt_data(packet)[0] == 0x80 \ && pkt_data(packet)[1] == 0x21 \ && pkt_data(packet)[2] == 0x01 \ && pkt_data(packet)[4] == 0x00 \ && pkt_data(packet)[5] == 0x04) static inline void set_tunnel_ips(struct tunnel *tunnel, struct ppp_packet *packet) { memcpy(&tunnel->ipv4.ip_addr.s_addr, &pkt_data(packet)[8], sizeof(uint32_t)); if (packet->len >= 18 && pkt_data(packet)[12] == 0x81) { memcpy(&tunnel->ipv4.ns1_addr.s_addr, &pkt_data(packet)[14], sizeof(uint32_t)); } if (packet->len >= 24 && pkt_data(packet)[18] == 0x83) { memcpy(&tunnel->ipv4.ns2_addr.s_addr, &pkt_data(packet)[20], sizeof(uint32_t)); } } #define printable_char(c) \ (c == '\t' || c == '\n' || (c >= ' ' && c <= '~')) static void debug_bad_packet(struct tunnel *tunnel, uint8_t *header) { uint8_t buffer[256]; int size, i; memcpy(buffer, header, 6 * sizeof(uint8_t)); size = safe_ssl_read(tunnel->ssl_handle, &buffer[6], 256 - 6); if (size < 0) return; size += 6; // Print hex dump do_log_packet(" (hex) ", size, buffer); // then print the raw string, after escaping non-displayable chars for (i = 0; i < size; i++) if (!printable_char((char) buffer[i])) buffer[i] = '.'; buffer[i] = buffer[256 - 1] = '\0'; printf(" (raw) %s\n", (char *) buffer); } /* * Thread to read bytes from the SSL socket, convert them to ppp packets and add * them to the 'ssl_to_pty' pool. */ static void *ssl_read(void *arg) { struct tunnel *tunnel = (struct tunnel *) arg; //uint8_t buf[PKT_BUF_SZ]; log_debug("ssl_read_thread\n"); while (1) { struct ppp_packet *packet; int ret; uint8_t header[6]; uint16_t total, magic, size; ret = safe_ssl_read_all(tunnel->ssl_handle, header, 6); if (ret < 0) { log_debug("Error reading from SSL connection (%s).\n", err_ssl_str(ret)); goto exit; } total = header[0] << 8 | header[1]; magic = header[2] << 8 | header[3]; size = header[4] << 8 | header[5]; if (magic != 0x5050 || total != size + 6) { log_error("Received bad header from gateway:\n"); debug_bad_packet(tunnel, header); break; } packet = malloc(sizeof(struct ppp_packet) + 6 + size); if (packet == NULL) { log_error("malloc failed\n"); break; } memcpy(pkt_header(packet), header, 6); packet->len = size; ret = safe_ssl_read_all(tunnel->ssl_handle, pkt_data(packet), size); if (ret < 0) { log_debug("Error reading from SSL connection (%s).\n", err_ssl_str(ret)); free(packet); goto exit; } log_debug("gateway ---> pppd (%d bytes)\n", packet->len); log_packet("gtw: ", packet->len, pkt_data(packet)); pool_push(&tunnel->ssl_to_pty_pool, packet); if (tunnel->state == STATE_CONNECTING) { if (packet_is_ip_plus_dns(packet)) { char line[57]; // 1 + 15 + 7 + 15 + 2 + 15 + 1 + 1 set_tunnel_ips(tunnel, packet); strcpy(line, "["); strncat(line, inet_ntoa(tunnel->ipv4.ip_addr), 15); strcat(line, "], ns ["); strncat(line, inet_ntoa(tunnel->ipv4.ns1_addr), 15); strcat(line, ", "); strncat(line, inet_ntoa(tunnel->ipv4.ns2_addr), 15); strcat(line, "]"); log_info("Got addresses: %s\n", line); } else if (packet_is_end_negociation(packet)) { SEM_POST(&sem_if_config); } } } exit: // Send message to main thread to stop other threads SEM_POST(&sem_stop_io); return NULL; } /* * Thread to pop packets from the 'pty_to_ssl' pool, and write them to the SSL * socket. */ static void *ssl_write(void *arg) { struct tunnel *tunnel = (struct tunnel *) arg; log_debug("ssl_write_thread\n"); while (1) { struct ppp_packet *packet; int ret; // This waits until a packet has arrived from pppd packet = pool_pop(&tunnel->pty_to_ssl_pool); pkt_header(packet)[0] = (6 + packet->len) >> 8; pkt_header(packet)[1] = (6 + packet->len) & 0xff; pkt_header(packet)[2] = 0x50; pkt_header(packet)[3] = 0x50; pkt_header(packet)[4] = packet->len >> 8; pkt_header(packet)[5] = packet->len & 0xff; do { ret = safe_ssl_write(tunnel->ssl_handle, packet->content, 6 + packet->len); } while (ret == 0); if (ret < 0) { log_debug("Error writing to SSL connection (%s).\n", err_ssl_str(ret)); free(packet); break; } free(packet); } // Send message to main thread to stop other threads SEM_POST(&sem_stop_io); return NULL; } /* * Thread to pop packets from the 'pty_to_ssl' pool, and write them to the SSL * socket. */ static void *if_config(void *arg) { struct tunnel *tunnel = (struct tunnel *) arg; int timeout = 60000000; // one minute log_debug("if_config thread\n"); // Wait for the right moment to configure IP interface SEM_WAIT(&sem_if_config); while (1) { if (ppp_interface_is_up(tunnel)) { if (tunnel->on_ppp_if_up != NULL) if (tunnel->on_ppp_if_up(tunnel)) goto error; tunnel->state = STATE_UP; break; } else if (timeout == 0) { log_error("Timed out waiting for the ppp interface to " "be UP.\n"); break; } log_debug("if_config: not ready yet...\n"); timeout -= 200000; usleep(200000); } if (tunnel->state != STATE_UP) goto error; return NULL; error: // Send message to main thread to stop other threads SEM_POST(&sem_stop_io); return NULL; } static void sig_handler(int signo) { if (signo == SIGINT || signo == SIGTERM) SEM_POST(&sem_stop_io); } int io_loop(struct tunnel *tunnel) { int tcp_nodelay_flag = 1; pthread_t pty_read_thread; pthread_t pty_write_thread; pthread_t ssl_read_thread; pthread_t ssl_write_thread; pthread_t if_config_thread; SEM_INIT(&sem_pppd_ready, 0, 0); SEM_INIT(&sem_if_config, 0, 0); SEM_INIT(&sem_stop_io, 0, 0); init_ppp_packet_pool(&tunnel->ssl_to_pty_pool); init_ppp_packet_pool(&tunnel->pty_to_ssl_pool); init_ssl_locks(); /* * I noticed that using TCP_NODELAY (i.e. disabling Nagle's algorithm) * gives much better performance. Probably because setting up the VPN * is sending and receiving many small packets. * A small benchmark gave these results: * - with TCP_NODELAY: ~ 4000 kbit/s * - without TCP_NODELAY: ~ 1200 kbit/s * - forticlientsslvpn from Fortinet: ~ 3700 kbit/s * - openfortivpn, Python version: ~ 2000 kbit/s * (with or without TCP_NODELAY) */ if (setsockopt(tunnel->ssl_socket, IPPROTO_TCP, TCP_NODELAY, (char *) &tcp_nodelay_flag, sizeof(int))) { log_error("setsockopt: %s\n", strerror(errno)); goto err_sockopt; } // on osx this prevents the program from being stopped with ctrl-c #ifndef __APPLE__ // Disable SIGINT and SIGTERM for the future spawned threads sigset_t sigset, oldset; sigemptyset(&sigset); sigaddset(&sigset, SIGINT); sigaddset(&sigset, SIGTERM); pthread_sigmask(SIG_BLOCK, &sigset, &oldset); #endif // Set signal handler if (signal(SIGINT, sig_handler) == SIG_ERR || signal(SIGTERM, sig_handler) == SIG_ERR) goto err_signal; // Ignore SIGHUP if (signal(SIGHUP, SIG_IGN) == SIG_ERR) goto err_signal; if (pthread_create(&pty_read_thread, NULL, pppd_read, tunnel)) goto err_thread; if (pthread_create(&pty_write_thread, NULL, pppd_write, tunnel)) goto err_thread; if (pthread_create(&ssl_read_thread, NULL, ssl_read, tunnel)) goto err_thread; if (pthread_create(&ssl_write_thread, NULL, ssl_write, tunnel)) goto err_thread; if (pthread_create(&if_config_thread, NULL, if_config, tunnel)) goto err_thread; #ifndef __APPLE__ // Restore the signal for the main thread pthread_sigmask(SIG_SETMASK, &oldset, NULL); #endif // Wait for one of the thread to ask termination SEM_WAIT(&sem_stop_io); log_info("Cancelling threads...\n"); pthread_cancel(if_config_thread); pthread_cancel(ssl_write_thread); pthread_cancel(ssl_read_thread); pthread_cancel(pty_write_thread); pthread_cancel(pty_read_thread); pthread_join(if_config_thread, NULL); pthread_join(ssl_write_thread, NULL); pthread_join(ssl_read_thread, NULL); pthread_join(pty_write_thread, NULL); pthread_join(pty_read_thread, NULL); destroy_ssl_locks(); destroy_ppp_packet_pool(&tunnel->pty_to_ssl_pool); destroy_ppp_packet_pool(&tunnel->ssl_to_pty_pool); SEM_DESTROY(&sem_stop_io); SEM_DESTROY(&sem_if_config); SEM_DESTROY(&sem_pppd_ready); return 0; err_thread: err_signal: err_sockopt: return 1; } openfortivpn-1.6.0/src/io.h000066400000000000000000000033271320302212600156120ustar00rootroot00000000000000/* * Copyright (C) 2015 Adrien Vergé * * 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 . */ #ifndef _OPENFORTIVPN_IO_H #define _OPENFORTIVPN_IO_H #include #include #include /* * For performance reasons, we store the 6-byte header used by the SSL * communication right in front of the real PPP packet data. This way, * SSL_write can be called directly on packet->content, instead of memcpy'ing * the header + data to a temporary buffer. */ struct ppp_packet { struct ppp_packet *next; size_t len; // length of data; actual length is 6 + len uint8_t content[]; }; #define pkt_header(packet) ((packet)->content) #define pkt_data(packet) ((packet)->content + 6) struct ppp_packet_pool { pthread_mutex_t mutex; pthread_cond_t new_data; struct ppp_packet *list_head; }; #define init_ppp_packet_pool(pool) \ do { \ pthread_mutex_init(&(pool)->mutex, NULL); \ pthread_cond_init(&(pool)->new_data, NULL); \ (pool)->list_head = NULL; \ } while (0) #define destroy_ppp_packet_pool(pool) \ pthread_mutex_destroy(&(pool)->mutex) struct tunnel; int io_loop(struct tunnel *tunnel); #endif openfortivpn-1.6.0/src/ipv4.c000066400000000000000000000563071320302212600160660ustar00rootroot00000000000000/* * Copyright (C) 2015 Adrien Vergé * * 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 . */ #include "ipv4.h" #include "tunnel.h" #include "config.h" #include "log.h" #include #include #include #include #include #include #include #include #include #include #define SHOW_ROUTE_BUFFER_SIZE 128 static char show_route_buffer[SHOW_ROUTE_BUFFER_SIZE]; #define ERR_IPV4_SEE_ERRNO -1 #define ERR_IPV4_NO_MEM -2 #define ERR_IPV4_PERMISSION -3 #define ERR_IPV4_NO_SUCH_ROUTE -4 #define ERR_IPV4_PROC_NET_ROUTE -5 static inline const char *err_ipv4_str(int code) { if (code == ERR_IPV4_SEE_ERRNO) return strerror(errno); else if (code == ERR_IPV4_NO_MEM) return "Not enough memory"; else if (code == ERR_IPV4_PERMISSION) return "Permission denied"; else if (code == ERR_IPV4_NO_SUCH_ROUTE) return "Route not found"; else if (code == ERR_IPV4_PROC_NET_ROUTE) return "Parsing /proc/net/route failed"; return "unknown"; } /* * Returns a string representation of the route, such as: * to 192.168.1.0/255.255.255.0 via 172.16.0.1 dev eth0 * * Warning: the returned buffer is static, so multiple calls will overwrite it. */ static char *ipv4_show_route(struct rtentry *route) { strcpy(show_route_buffer, "to "); strncat(show_route_buffer, inet_ntoa(route_dest(route)), 15); strcat(show_route_buffer, "/"); strncat(show_route_buffer, inet_ntoa(route_mask(route)), 15); if (route->rt_flags & RTF_GATEWAY) { strcat(show_route_buffer, " via "); strncat(show_route_buffer, inet_ntoa(route_gtw(route)), 15); } if (route_iface(route)[0] != '\0') { strcat(show_route_buffer, " dev "); strncat(show_route_buffer, route_iface(route), ROUTE_IFACE_LEN - 1); } return show_route_buffer; } static inline int route_init(struct rtentry *route) { memset(route, 0, sizeof(*route)); route_iface(route) = malloc(ROUTE_IFACE_LEN); if (route_iface(route) == NULL) return ERR_IPV4_NO_MEM; route_iface(route)[0] = '\0'; cast_addr(&(route)->rt_dst)->sin_family = AF_INET; cast_addr(&(route)->rt_genmask)->sin_family = AF_INET; cast_addr(&(route)->rt_gateway)->sin_family = AF_INET; return 0; } static inline void route_destroy(struct rtentry *route) { if (route_iface(route) != NULL) { free(route_iface(route)); route_iface(route) = NULL; } } /* * Finds system IP route to a destination. * * The passed route must have dest and mask set. If the route is found, the * function fills the gtw and iface properties. */ static int ipv4_get_route(struct rtentry *route) { size_t size; char buffer[0x1000]; char *start, *line; char *saveptr1 = NULL, *saveptr2 = NULL; log_debug("ip route show %s\n", ipv4_show_route(route)); #ifndef __APPLE__ int fd; // Cannot stat, mmap not lseek this special /proc file fd = open("/proc/net/route", O_RDONLY); if (fd == -1) return ERR_IPV4_SEE_ERRNO; size = read(fd, buffer, sizeof(buffer) - 1); if (size == -1) { close(fd); return ERR_IPV4_SEE_ERRNO; } close(fd); #else FILE *fp; int len = sizeof(buffer) - 1; char *saveptr3 = NULL; // Open the command for reading fp = popen("/usr/sbin/netstat -f inet -rn", "r"); if (fp == NULL) return ERR_IPV4_SEE_ERRNO; line = buffer; // Read the output a line at a time while (fgets(line, len, fp) != NULL) { len -= strlen(line); line += strlen(line); } size = sizeof(buffer)-1 - len; pclose(fp); // reserve enough memory (256 shorts) // to make sure not to access out of bounds later, // for ipv4 only unsigned short is allowed unsigned short flag_table[256]; memset(flag_table, 0, 256*sizeof(short)); // fill the table now (I'm still looking for a more elagant way to do this), // also, not all flags might be allowed in the context of ipv4 #ifdef RTF_PROTO1 // Protocol specific routing flag #1 flag_table['1'] = RTF_PROTO1 & USHRT_MAX; #endif #ifdef RTF_PROTO2 // Protocol specific routing flag #2 flag_table['2'] = RTF_PROTO2 & USHRT_MAX; #endif #ifdef RTF_PROTO3 // Protocol specific routing flag #3 flag_table['3'] = RTF_PROTO3 & USHRT_MAX; #endif #ifdef RTF_BLACKHOLE // Just discard packets (during updates) flag_table['B'] = RTF_BLACKHOLE & USHRT_MAX; #endif #ifdef RTF_BROADCAST // The route represents a broadcast address flag_table['b'] = RTF_BROADCAST & USHRT_MAX; #endif #ifdef RTF_CLONING // Generate new routes on use flag_table['C'] = RTF_CLONING & USHRT_MAX; #endif #ifdef RTF_PRCLONING // Protocol-specified generate new routes on use flag_table['c'] = RTF_PRCLONING & USHRT_MAX; #endif #ifdef RTF_DYNAMIC // Created dynamically (by redirect) flag_table['D'] = RTF_DYNAMIC & USHRT_MAX; #endif #ifdef RTF_GATEWAY // Destination requires forwarding by intermediary flag_table['G'] = RTF_GATEWAY & USHRT_MAX; #endif #ifdef RTF_HOST // Host entry (net otherwise) flag_table['H'] = RTF_HOST & USHRT_MAX; #endif #ifdef RTF_IFSCOPE // Route is associated with an interface scope flag_table['I'] = RTF_IFSCOPE & USHRT_MAX; #endif #ifdef RTF_IFREF // Route is holding a reference to the interface flag_table['i'] = RTF_IFREF & USHRT_MAX; #endif #ifdef RTF_LLINFO // Valid protocol to link address translation flag_table['L'] = RTF_LLINFO & USHRT_MAX; #endif #ifdef RTF_MODIFIED // Modified dynamically (by redirect) flag_table['M'] = RTF_MODIFIED & USHRT_MAX; #endif #ifdef RTF_MULTICAST // The route represents a multicast address flag_table['m'] = RTF_MULTICAST & USHRT_MAX; #endif #ifdef RTF_REJECT // Host or net unreachable flag_table['R'] = RTF_REJECT & USHRT_MAX; #endif #ifdef RTF_ROUTER // Host is a default router flag_table['r'] = RTF_ROUTER & USHRT_MAX; #endif #ifdef RTF_STATIC // Manually added flag_table['S'] = RTF_STATIC & USHRT_MAX; #endif #ifdef RTF_UP // Route usable flag_table['U'] = RTF_UP & USHRT_MAX; #endif #ifdef RTF_WASCLONED // Route was generated as a result of cloning flag_table['W'] = RTF_WASCLONED & USHRT_MAX; #endif #ifdef RTF_XRESOLVE // External daemon translates proto to link address flag_table['X'] = RTF_XRESOLVE & USHRT_MAX; #endif #ifdef RTF_PROXY // Proxying; cloned routes will not be scoped flag_table['Y'] = RTF_PROXY & USHRT_MAX; #endif #endif if (size == 0) { log_debug("routing table is empty.\n"); return ERR_IPV4_PROC_NET_ROUTE; } buffer[size] = '\0'; // Skip first line start = index(buffer, '\n'); if (start == NULL) { log_debug("routing table is malformed.\n"); return ERR_IPV4_PROC_NET_ROUTE; } start++; #ifdef __APPLE__ // Skip 3 more line start = index(start, '\n'); start = index(++start, '\n'); start = index(++start, '\n'); if (start == NULL) { log_debug("routing table is malformed.\n"); return ERR_IPV4_PROC_NET_ROUTE; } #endif // Look for the route line = strtok_r(start, "\n", &saveptr1); while (line != NULL) { char *iface; uint32_t dest, mask, gtw; unsigned short flags; #ifndef __APPLE__ unsigned short irtt; short metric; unsigned long mtu, window; iface = strtok_r(line, "\t", &saveptr2); dest = strtol(strtok_r(NULL, "\t", &saveptr2), NULL, 16); gtw = strtol(strtok_r(NULL, "\t", &saveptr2), NULL, 16); flags = strtol(strtok_r(NULL, "\t", &saveptr2), NULL, 16); strtok_r(NULL, "\t", &saveptr2); // "RefCnt" strtok_r(NULL, "\t", &saveptr2); // "Use" metric = strtol(strtok_r(NULL, "\t", &saveptr2), NULL, 16); mask = strtol(strtok_r(NULL, "\t", &saveptr2), NULL, 16); mtu = strtol(strtok_r(NULL, "\t", &saveptr2), NULL, 16); window = strtol(strtok_r(NULL, "\t", &saveptr2), NULL, 16); irtt = strtol(strtok_r(NULL, "\t", &saveptr2), NULL, 16); #else char tmp_ip_string[16]; struct in_addr dstaddr; int pos; char *tmpstr; log_debug("line: %s\n", line); saveptr3 = NULL; dest = UINT32_MAX; mask = UINT32_MAX; // "Destination" tmpstr = strtok_r(line, " ", &saveptr2); log_debug("- Destination: %s\n", tmpstr); // replace literal "default" route by IPV4 numbers-and-dots notation if (strncmp(tmpstr, "default", 7) == 0) { dest = 0; mask = 0; } else { int is_mask_set = 0; char *tmp_position; int dot_count = -1; if (index(tmpstr, '/') != NULL) { // 123.123.123.123/30 style // 123.123.123/24 style // 123.123/24 style // break CIDR up into address and mask part strcpy(tmp_ip_string, strtok_r(tmpstr, "/", &saveptr3)); mask = strtol(saveptr3, NULL, 10); // convert from CIDR to ipv4 mask mask = 0xffffffff << (32-mask); is_mask_set = 1; } else if (inet_aton(tmpstr, &dstaddr)) { // 123.123.123.123 style // 123.123.123 style // 123.123 style strcpy(tmp_ip_string, tmpstr); is_mask_set = 0; } // Process Destination IP Expression tmp_position = tmp_ip_string; while (tmp_position != NULL) { ++dot_count; tmp_position = index(++tmp_position, '.'); } for (int i = dot_count; i < 3; i++) strcat(tmp_ip_string, ".0"); if (inet_aton(tmp_ip_string, &dstaddr)) dest = dstaddr.s_addr; if (!is_mask_set) { // convert from CIDR to ipv4 mask mask = 0xffffffff << (32-((dot_count + 1) * 8)); } } log_debug("- Destination IP Hex: %x\n", dest); log_debug("- Destination Mask Hex: %x\n", mask); // "Gateway" gtw = 0; if (inet_aton(strtok_r(NULL, " ", &saveptr2), &dstaddr)) { gtw = dstaddr.s_addr; log_debug("- Gateway Mask Hex: %x\n", gtw); } // "Flags" tmpstr = strtok_r(NULL, " ", &saveptr2); flags = 0; // this is the reason for the 256 entries mentioned above for (pos = 0; pos < strlen(tmpstr); pos++) flags |= flag_table[(unsigned char)tmpstr[pos]]; strtok_r(NULL, " ", &saveptr2); // "Refs" strtok_r(NULL, " ", &saveptr2); // "Use" iface = strtok_r(NULL, " ", &saveptr2); // "Netif" log_debug("- Interface: %s\n", iface); log_debug("\n"); #endif if (dest == route_dest(route).s_addr && mask == route_mask(route).s_addr) { // Requested route has been found route_gtw(route).s_addr = gtw; route->rt_flags = flags; #ifndef __APPLE__ // we do not have these values from Mac OS X netstat, // so stay with defaults denoted by values of 0 route->rt_metric = metric; route->rt_mtu = mtu; route->rt_window = window; route->rt_irtt = irtt; #endif strncpy(route_iface(route), iface, ROUTE_IFACE_LEN - 1); return 0; } line = strtok_r(NULL, "\n", &saveptr1); } log_debug("Route not found.\n"); return ERR_IPV4_NO_SUCH_ROUTE; } static int ipv4_set_route(struct rtentry *route) { #ifndef __APPLE__ log_debug("ip route add %s\n", ipv4_show_route(route)); int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); if (sockfd < 0) return ERR_IPV4_SEE_ERRNO; if (ioctl(sockfd, SIOCADDRT, route) == -1) { close(sockfd); return ERR_IPV4_SEE_ERRNO; } close(sockfd); #else char cmd[SHOW_ROUTE_BUFFER_SIZE]; strcpy(cmd, "route -n add -net "); strncat(cmd, inet_ntoa(route_dest(route)), 15); strcat(cmd, " -netmask "); strncat(cmd, inet_ntoa(route_mask(route)), 15); if (route->rt_flags & RTF_GATEWAY) { strcat(cmd, " "); strncat(cmd, inet_ntoa(route_gtw(route)), 15); } else { strcat(cmd, " -interface "); strcat(cmd, route_iface(route)); } log_debug("%s\n", cmd); int res = system(cmd); if (res == -1) return ERR_IPV4_SEE_ERRNO; #endif return 0; } static int ipv4_del_route(struct rtentry *route) { #ifndef __APPLE__ struct rtentry tmp; int sockfd; log_debug("ip route del %s\n", ipv4_show_route(route)); // Copy route to a temp variable to clear some of its properties memcpy(&tmp, route, sizeof(tmp)); tmp.rt_metric = 0; tmp.rt_mtu = 0; tmp.rt_window = 0; tmp.rt_irtt = 0; sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); if (sockfd < 0) return ERR_IPV4_SEE_ERRNO; if (ioctl(sockfd, SIOCDELRT, &tmp) == -1) { close(sockfd); return ERR_IPV4_SEE_ERRNO; } close(sockfd); #else char cmd[SHOW_ROUTE_BUFFER_SIZE]; strcpy(cmd, "route -n delete "); strncat(cmd, inet_ntoa(route_dest(route)), 15); strcat(cmd, " -netmask "); strncat(cmd, inet_ntoa(route_mask(route)), 15); log_debug("%s\n", cmd); int res = system(cmd); if (res == -1) return ERR_IPV4_SEE_ERRNO; #endif return 0; } int ipv4_protect_tunnel_route(struct tunnel *tunnel) { struct rtentry *gtw_rt = &tunnel->ipv4.gtw_rt; struct rtentry *def_rt = &tunnel->ipv4.def_rt; int ret; route_init(def_rt); route_init(gtw_rt); // Back up default route route_dest(def_rt).s_addr = inet_addr("0.0.0.0"); route_mask(def_rt).s_addr = inet_addr("0.0.0.0"); ret = ipv4_get_route(def_rt); if (ret != 0) { log_warn("Could not get current default route (%s).\n", err_ipv4_str(ret)); log_warn("Protecting tunnel route has failed. " "But this can be working except for some cases.\n"); goto err_destroy; } // Set the default route as the route to the tunnel gateway char *iface = route_iface(gtw_rt); memcpy(gtw_rt, def_rt, sizeof(*gtw_rt)); route_iface(gtw_rt) = iface; strncpy(route_iface(gtw_rt), route_iface(def_rt), ROUTE_IFACE_LEN - 1); route_dest(gtw_rt).s_addr = tunnel->config->gateway_ip.s_addr; route_mask(gtw_rt).s_addr = inet_addr("255.255.255.255"); gtw_rt->rt_flags |= RTF_HOST; gtw_rt->rt_metric = 0; tunnel->ipv4.route_to_vpn_is_added = 1; log_debug("Setting route to vpn server...\n"); ret = ipv4_set_route(gtw_rt); if (ret == ERR_IPV4_SEE_ERRNO && errno == EEXIST) { log_warn("Route to vpn server exists already.\n"); tunnel->ipv4.route_to_vpn_is_added = 0; } else if (ret != 0) log_warn("Could not set route to vpn server (%s).\n", err_ipv4_str(ret)); return 0; err_destroy: route_destroy(def_rt); tunnel->ipv4.route_to_vpn_is_added = 0; return ret; } int ipv4_add_split_vpn_route(struct tunnel *tunnel, char *dest, char *mask, char *gateway) { struct rtentry *route; char env_var[24]; if (tunnel->ipv4.split_routes == MAX_SPLIT_ROUTES) return ERR_IPV4_NO_MEM; if ((tunnel->ipv4.split_rt == NULL) || ((tunnel->ipv4.split_routes % STEP_SPLIT_ROUTES) == 0)) { void *new_ptr = realloc( tunnel->ipv4.split_rt, (size_t) (tunnel->ipv4.split_routes + STEP_SPLIT_ROUTES) * sizeof(*(tunnel->ipv4.split_rt)) ); if (new_ptr == NULL) return ERR_IPV4_NO_MEM; tunnel->ipv4.split_rt = new_ptr; } sprintf(env_var, "VPN_ROUTE_DEST_%d", tunnel->ipv4.split_routes); setenv(env_var, dest, 0); sprintf(env_var, "VPN_ROUTE_MASK_%d", tunnel->ipv4.split_routes); setenv(env_var, mask, 0); if (gateway != NULL) { sprintf(env_var, "VPN_ROUTE_GATEWAY_%d", tunnel->ipv4.split_routes); setenv(env_var, gateway, 0); } route = &tunnel->ipv4.split_rt[tunnel->ipv4.split_routes++]; route_init(route); route_dest(route).s_addr = inet_addr(dest); route_mask(route).s_addr = inet_addr(mask); if (gateway != NULL) { route_gtw(route).s_addr = inet_addr(gateway); route->rt_flags |= RTF_GATEWAY; } else { strncpy(route_iface(route), tunnel->ppp_iface, ROUTE_IFACE_LEN - 1); } return 0; } static int ipv4_set_split_routes(struct tunnel *tunnel) { int i; for (i = 0; i < tunnel->ipv4.split_routes; i++) { struct rtentry *route; int ret; route = &tunnel->ipv4.split_rt[i]; strncpy(route_iface(route), tunnel->ppp_iface, ROUTE_IFACE_LEN - 1); if (route_gtw(route).s_addr == 0) route_gtw(route).s_addr = tunnel->ipv4.ip_addr.s_addr; route->rt_flags |= RTF_GATEWAY; ret = ipv4_set_route(route); if (ret == ERR_IPV4_SEE_ERRNO && errno == EEXIST) log_warn("Route to gateway exists already.\n"); else if (ret != 0) log_warn("Could not set route to tunnel gateway (%s).\n", err_ipv4_str(ret)); } return 0; } static int ipv4_set_default_routes(struct tunnel *tunnel) { int ret; struct rtentry *def_rt = &tunnel->ipv4.def_rt; struct rtentry *ppp_rt = &tunnel->ipv4.ppp_rt; struct vpn_config *cfg = tunnel->config; route_init(ppp_rt); if (cfg->half_internet_routes == 0) { // Delete the current default route log_debug("Deleting the current default route...\n"); ret = ipv4_del_route(def_rt); if (ret != 0) log_warn("Could not delete the current default route (%s).\n", err_ipv4_str(ret)); // Set the new default route // ip route add to 0/0 dev ppp0 route_dest(ppp_rt).s_addr = inet_addr("0.0.0.0"); route_mask(ppp_rt).s_addr = inet_addr("0.0.0.0"); route_gtw(ppp_rt).s_addr = inet_addr("0.0.0.0"); log_debug("Setting new default route...\n"); strncpy(route_iface(ppp_rt), tunnel->ppp_iface, ROUTE_IFACE_LEN - 1); ret = ipv4_set_route(ppp_rt); if (ret == ERR_IPV4_SEE_ERRNO && errno == EEXIST) { log_warn("Default route exists already.\n"); } else if (ret != 0) { log_warn("Could not set the new default route (%s).\n", err_ipv4_str(ret)); } } else { // Emulate default routes as two "half internet" routes // This allows for e.g. DHCP renewing default routes without // breaking the tunnel log_debug("Setting new half-internet routes...\n"); route_dest(ppp_rt).s_addr = inet_addr("0.0.0.0"); route_mask(ppp_rt).s_addr = inet_addr("128.0.0.0"); strncpy(route_iface(ppp_rt), tunnel->ppp_iface, ROUTE_IFACE_LEN - 1); ret = ipv4_set_route(ppp_rt); if (ret == ERR_IPV4_SEE_ERRNO && errno == EEXIST) { log_warn("0.0.0.0/1 route exists already.\n"); } else if (ret != 0) { log_warn("Could not set the new 0.0.0.0/1 route (%s).\n", err_ipv4_str(ret)); } route_dest(ppp_rt).s_addr = inet_addr("128.0.0.0"); ret = ipv4_set_route(ppp_rt); if (ret == ERR_IPV4_SEE_ERRNO && errno == EEXIST) { log_warn("128.0.0.0/1 route exists already.\n"); } else if (ret != 0) { log_warn("Could not set the new 128.0.0.0/1 route (%s).\n", err_ipv4_str(ret)); } } return 0; } int ipv4_set_tunnel_routes(struct tunnel *tunnel) { int ret = ipv4_protect_tunnel_route(tunnel); if (tunnel->ipv4.split_routes) // try even if ipv4_protect_tunnel_route has failed return ipv4_set_split_routes(tunnel); else if (ret == 0) { return ipv4_set_default_routes(tunnel); } else { return ret; } } int ipv4_restore_routes(struct tunnel *tunnel) { struct rtentry *def_rt = &tunnel->ipv4.def_rt; struct rtentry *gtw_rt = &tunnel->ipv4.gtw_rt; struct rtentry *ppp_rt = &tunnel->ipv4.ppp_rt; struct vpn_config *cfg = tunnel->config; if (tunnel->ipv4.route_to_vpn_is_added) { int ret; ret = ipv4_del_route(gtw_rt); if (ret != 0) log_warn("Could not delete route to vpn server (%s).\n", err_ipv4_str(ret)); if ((cfg->half_internet_routes == 0) && (tunnel->ipv4.split_routes == 0)) { ret = ipv4_del_route(ppp_rt); if (ret != 0) log_warn("Could not delete route through tunnel (%s).\n", err_ipv4_str(ret)); // Restore the default route. It seems not to be // automatically restored on all linux distributions ret = ipv4_set_route(def_rt); if (ret != 0) { log_warn("Could not restore default route (%s). " "Already restored?\n", err_ipv4_str(ret)); } } } else { log_debug("Route to vpn server was not added\n"); } route_destroy(ppp_rt); route_destroy(def_rt); route_destroy(gtw_rt); return 0; } int ipv4_add_nameservers_to_resolv_conf(struct tunnel *tunnel) { int ret = -1; FILE *file; struct stat stat; char ns1[28], ns2[28]; // 11 + 15 + 1 + 1 char *buffer, *line; tunnel->ipv4.ns_are_new = 1; if (tunnel->ipv4.ns1_addr.s_addr == 0) return 1; file = fopen("/etc/resolv.conf", "r+"); if (file == NULL) { log_warn("Could not open /etc/resolv.conf (%s).\n", strerror(errno)); return 1; } if (fstat(fileno(file), &stat) == -1) { log_warn("Could not stat /etc/resolv.conf (%s).\n", strerror(errno)); goto err_close; } if (stat.st_size == 0) { log_warn("Could not read /etc/resolv.conf (%s).\n", "Empty file"); goto err_close; } buffer = malloc(stat.st_size + 1); if (buffer == NULL) { log_warn("Could not read /etc/resolv.conf (%s).\n", "Not enough memory"); goto err_close; } // Copy all file contents at once if (fread(buffer, stat.st_size, 1, file) != 1) { log_warn("Could not read /etc/resolv.conf.\n"); goto err_free; } buffer[stat.st_size] = '\0'; strcpy(ns1, "nameserver "); strncat(ns1, inet_ntoa(tunnel->ipv4.ns1_addr), 15); if (tunnel->ipv4.ns2_addr.s_addr != 0) { strcpy(ns2, "nameserver "); strncat(ns2, inet_ntoa(tunnel->ipv4.ns2_addr), 15); } else { ns2[0] = '\0'; } for (line = strtok(buffer, "\n"); line != NULL; line = strtok(NULL, "\n")) { if (strcmp(line, ns1) == 0) { tunnel->ipv4.ns_are_new = 0; log_debug("Nameservers already present in " "/etc/resolv.conf.\n"); ret = 0; goto err_free; } } log_debug("Adding \"%s\" and \"%s\" to /etc/resolv.conf.\n", ns1, ns2); rewind(file); if (fread(buffer, stat.st_size, 1, file) != 1) { log_warn("Could not read /etc/resolv.conf.\n"); goto err_free; } buffer[stat.st_size] = '\0'; rewind(file); strcat(ns1, "\n"); fputs(ns1, file); if (tunnel->ipv4.ns2_addr.s_addr != 0) { strcat(ns2, "\n"); fputs(ns2, file); } fwrite(buffer, stat.st_size, 1, file); ret = 0; err_free: free(buffer); err_close: fclose(file); return ret; } int ipv4_del_nameservers_from_resolv_conf(struct tunnel *tunnel) { int ret = -1; FILE *file; struct stat stat; char ns1[27], ns2[27]; // 11 + 15 + 1 char *buffer, *line; // If nameservers were already there before setting up tunnel, // don't delete them from /etc/resolv.conf if (!tunnel->ipv4.ns_are_new) return 0; if (tunnel->ipv4.ns1_addr.s_addr == 0) return 1; file = fopen("/etc/resolv.conf", "r+"); if (file == NULL) { log_warn("Could not open /etc/resolv.conf (%s).\n", strerror(errno)); return 1; } if (fstat(fileno(file), &stat) == -1) { log_warn("Could not stat /etc/resolv.conf (%s).\n", strerror(errno)); goto err_close; } buffer = malloc(stat.st_size + 1); if (buffer == NULL) { log_warn("Could not read /etc/resolv.conf (%s).\n", "Not enough memory"); goto err_close; } // Copy all file contents at once if (fread(buffer, stat.st_size, 1, file) != 1) { log_warn("Could not read /etc/resolv.conf.\n"); goto err_free; } buffer[stat.st_size] = '\0'; strcpy(ns1, "nameserver "); strncat(ns1, inet_ntoa(tunnel->ipv4.ns1_addr), 15); strcpy(ns2, "nameserver "); strncat(ns2, inet_ntoa(tunnel->ipv4.ns2_addr), 15); file = freopen("/etc/resolv.conf", "w", file); if (file == NULL) { log_warn("Could not reopen /etc/resolv.conf (%s).\n", strerror(errno)); goto err_free; } for (line = strtok(buffer, "\n"); line != NULL; line = strtok(NULL, "\n")) { if (strcmp(line, ns1) == 0) { log_debug("Deleting \"%s\" from /etc/resolv.conf.\n", ns1); } else if (strcmp(line, ns2) == 0) { log_debug("Deleting \"%s\" from /etc/resolv.conf.\n", ns1); } else { fputs(line, file); fputs("\n", file); } } ret = 0; err_free: free(buffer); err_close: if (file) fclose(file); return ret; } openfortivpn-1.6.0/src/ipv4.h000066400000000000000000000056701320302212600160700ustar00rootroot00000000000000/* * Copyright (C) 2015 Adrien Vergé * * 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 . */ #ifndef _OPENFORTIVPN_IPV4_H #define _OPENFORTIVPN_IPV4_H #include #include #ifdef __APPLE__ #include /* This structure gets passed by the SIOCADDRT and SIOCDELRT calls. */ struct rtentry { unsigned long rt_hash; /* hash key for lookups */ struct sockaddr rt_dst; /* target address */ struct sockaddr rt_gateway; /* gateway addr (RTF_GATEWAY) */ struct sockaddr rt_genmask; /* target network mask (IP) */ short rt_flags; short rt_refcnt; unsigned long rt_use; struct ifnet *rt_ifp; short rt_metric; /* +1 for binary compatibility! */ char *rt_dev; /* forcing the device at add */ unsigned long rt_mss; /* per route MTU/Window */ unsigned long rt_mtu; /* compatibility */ unsigned long rt_window; /* Window clamping */ unsigned short rt_irtt; /* Initial RTT */ }; #endif #define ROUTE_IFACE_LEN 32 #define MAX_SPLIT_ROUTES 65535 #define STEP_SPLIT_ROUTES 32 struct ipv4_config { struct in_addr ip_addr; struct in_addr ns1_addr; struct in_addr ns2_addr; int ns_are_new; // were ns already in /etc/resolv.conf? int split_routes; int route_to_vpn_is_added; struct rtentry def_rt; // default route struct rtentry gtw_rt; // route to access VPN gateway struct rtentry ppp_rt; // new default route through VPN struct rtentry *split_rt; // split VPN routes }; // Dummy function to make gcc 6 happy static inline struct sockaddr_in *cast_addr(struct sockaddr *addr) { return (struct sockaddr_in *) addr; } #define route_dest(route) (cast_addr(&(route)->rt_dst)->sin_addr) #define route_mask(route) (cast_addr(&(route)->rt_genmask)->sin_addr) #define route_gtw(route) (cast_addr(&(route)->rt_gateway)->sin_addr) #define route_iface(route) ((route)->rt_dev) struct tunnel; int ipv4_add_split_vpn_route(struct tunnel *tunnel, char *dest, char *mask, char *gateway); int ipv4_set_tunnel_routes(struct tunnel *tunnel); int ipv4_restore_routes(struct tunnel *tunnel); int ipv4_add_nameservers_to_resolv_conf(struct tunnel *tunnel); int ipv4_del_nameservers_from_resolv_conf(struct tunnel *tunnel); #endif openfortivpn-1.6.0/src/log.c000066400000000000000000000057541320302212600157650ustar00rootroot00000000000000/* * Copyright (C) 2015 Adrien Vergé * * 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 . */ #include "log.h" #include #include #include #include #include #include #include static pthread_mutex_t mutex; static int do_syslog = 0; enum log_verbosity loglevel; static int is_a_tty = 0; struct log_param_s { const char *prefix; const char *color_string; int syslog_prio; }; static const struct log_param_s log_params[OFV_LOG_DEBUG_PACKETS + 1] = { { " ", "", LOG_ERR}, { "ERROR: ", "\033[0;31m", LOG_ERR}, { "WARN: ", "\033[0;33m", LOG_WARNING}, { "INFO: ", "", LOG_INFO}, { "DEBUG: ", "\033[0;90m", LOG_DEBUG}, { "DEBUG: ", "\033[0;90m", LOG_DEBUG}, }; void init_logging(void) { pthread_mutexattr_t mutexattr; loglevel = OFV_LOG_INFO; is_a_tty = isatty(STDOUT_FILENO); pthread_mutexattr_init(&mutexattr); #ifndef __APPLE__ pthread_mutexattr_setrobust(&mutexattr, PTHREAD_MUTEX_ROBUST); #endif pthread_mutex_init(&mutex, &mutexattr); } void set_syslog(int use_syslog) { if (!use_syslog) return; do_syslog = use_syslog; openlog("openfortivpn", LOG_PID, LOG_DAEMON); } void increase_verbosity(void) { if (loglevel < OFV_LOG_DEBUG_PACKETS) loglevel++; } void decrease_verbosity(void) { if (loglevel > OFV_LOG_MUTE) loglevel--; } void do_log(int verbosity, const char *format, ...) { va_list args; const struct log_param_s *lp = NULL; pthread_mutex_lock(&mutex); // Use sane default if wrong verbosity specified if (verbosity > OFV_LOG_DEBUG || verbosity < 0) verbosity = OFV_LOG_MUTE; lp = &log_params[verbosity]; if (!do_syslog) printf("%s%s", is_a_tty ? lp->color_string : "", lp->prefix); va_start(args, format); if (do_syslog) vsyslog(lp->syslog_prio, format, args); else vprintf(format, args); va_end(args); if (!do_syslog) { if (is_a_tty) printf("\033[0;0m"); fflush(stdout); } pthread_mutex_unlock(&mutex); } void do_log_packet(const char *prefix, size_t len, const uint8_t *packet) { char *str, *pos; size_t i; str = malloc(strlen(prefix) + 3 * len + 1 + 1); if (str == NULL) { log_error("malloc failed\n"); return; } pos = strcpy(str, prefix); pos += strlen(str); for (i = 0; i < len; i++) pos += sprintf(pos, "%02x ", packet[i]); strcpy(pos - 1, "\n"); if (do_syslog) syslog(LOG_DEBUG, "%s", str); else puts(str); free(str); } openfortivpn-1.6.0/src/log.h000066400000000000000000000034321320302212600157610ustar00rootroot00000000000000/* * Copyright (C) 2015 Adrien Vergé * * 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 . */ #ifndef _OPENFORTIVPN_LOG_H #define _OPENFORTIVPN_LOG_H #include #include // Assign enum values explicitly, we're using them in a lookup enum log_verbosity { OFV_LOG_MUTE = 0, OFV_LOG_ERROR = 1, OFV_LOG_WARN = 2, OFV_LOG_INFO = 3, OFV_LOG_DEBUG = 4, OFV_LOG_DEBUG_PACKETS = 5 }; extern enum log_verbosity loglevel; void init_logging(void); void set_syslog(int do_syslog); void increase_verbosity(void); void decrease_verbosity(void); void do_log(int verbosity, const char *format, ...); #define log_level(verbosity, ...) \ do { \ if (loglevel >= verbosity) \ do_log(verbosity, __VA_ARGS__); \ } while (0) #define log_error(...) \ log_level(OFV_LOG_ERROR, __VA_ARGS__) #define log_warn(...) \ log_level(OFV_LOG_WARN, __VA_ARGS__) #define log_info(...) \ log_level(OFV_LOG_INFO, __VA_ARGS__) #define log_debug(...) \ log_level(OFV_LOG_DEBUG, __VA_ARGS__) #define log_packet(...) \ do { \ if (loglevel >= OFV_LOG_DEBUG_PACKETS) \ do_log_packet(__VA_ARGS__); \ } while (0) void do_log_packet(const char *prefix, size_t len, const uint8_t *packet); #endif openfortivpn-1.6.0/src/main.c000066400000000000000000000353431320302212600161250ustar00rootroot00000000000000/* * Copyright (C) 2015 Adrien Vergé * * 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 . */ #include "config.h" #include "tunnel.h" #include "userinput.h" #include "log.h" #include #include #include #include #include #define usage \ "Usage: openfortivpn [:] [-u ] [-p ]\n" \ " [--realm=] [--otp=] [--set-routes=<0|1>]\n" \ " [--half_internet_routes=<0|1>] [--set-dns=<0|1>]\n" \ " [--pppd-no-peerdns] [--pppd-log=]\n" \ " [--pppd-ifname=] [--pppd-ipparam=]\n" \ " [--pppd-plugin=] [--ca-file=]\n" \ " [--user-cert=] [--user-key=]\n" \ " [--trusted-cert=] [--use-syslog]\n" \ " [-c ] [-v|-q]\n" \ " openfortivpn --help\n" \ " openfortivpn --version\n" \ "\n" #define help_options \ "Client for PPP+SSL VPN tunnel services.\n" \ "openfortivpn connects to a VPN by setting up a tunnel to the gateway at\n" \ ":. It spawns a pppd process and operates the communication between\n" \ "the gateway and this process.\n" \ "\n" \ "Options:\n" \ " -h --help Show this help message and exit.\n" \ " --version Show version and exit.\n" \ " -c , --config= Specify a custom config file (default:\n" \ " "SYSCONFDIR"/openfortivpn/config).\n" \ " -u , --username= VPN account username.\n" \ " -p , --password= VPN account password.\n" \ " -o , --otp= One-Time-Password.\n" \ " --realm= Use specified authentication realm on VPN gateway\n" \ " when tunnel is up.\n" \ " --set-routes=[01] Set if we should configure output roues through\n" \ " the VPN when tunnel is up.\n" \ " --no-routes Do not configure routes, same as --set-routes=0.\n" \ " --half-internet-routes=[01] Add /1-routes instead of replacing the default route\n" \ " --set-dns=[01] Set if we should add VPN name servers in\n" \ " /etc/resolv.conf\n" \ " --no-dns Do not reconfigure DNS, same as --set-dns=0\n" \ " --ca-file= Use specified PEM-encoded certificate bundle\n" \ " instead of system-wide store to verify the gateway\n" \ " certificate.\n" \ " --user-cert= Use specified PEM-encoded certificate if the server\n" \ " requires authentication with a certificate.\n" \ " --user-key= Use specified PEM-encoded key if the server if the\n" \ " server requires authentication with a certificate.\n" \ " --use-syslog Log to syslog instead of terminal.\n" \ " --trusted-cert= Trust a given gateway. If classical SSL\n" \ " certificate validation fails, the gateway\n" \ " certificate will be matched against this value.\n" \ " is the X509 certificate's sha256 sum.\n" \ " This option can be used multiple times to trust\n" \ " several certificates.\n" \ " --insecure-ssl Do not disable insecure SSL protocols/ciphers.\n" \ " If your server requires a specific cipher, consider\n" \ " using --cipher-list instead.\n" \ " --cipher-list= Openssl ciphers to use. If default does not work\n" \ " you can try with the cipher suggested in the output\n" \ " of 'openssl s_client -connect '\n" \ " (e.g. AES256-GCM-SHA384)\n" \ " --pppd-no-peerdns Do not ask peer ppp server for DNS addresses\n" \ " and do not make pppd rewrite /etc/resolv.conf\n" \ " --pppd-log= Set pppd in debug mode and save its logs into\n" \ " .\n" \ " --pppd-plugin= Use specified pppd plugin instead of configuring\n" \ " resolver and routes directly.\n" \ " --pppd-ifname= Set the pppd interface name, if supported by pppd.\n" \ " --pppd-ipparam= Provides an extra parameter to the ip-up, ip-pre-up\n" \ " and ip-down scripts. See man (8) pppd\n" \ " -v Increase verbosity. Can be used multiple times\n" \ " to be even more verbose.\n" \ " -q Decrease verbosity. Can be used multiple times\n" \ " to be even less verbose.\n" \ "\n" #define help_config \ "Config file:\n" \ " Options can be taken from a configuration file. Options passed in the\n" \ " command line will override those from the config file, though. The default\n" \ " config file is "SYSCONFDIR"/openfortivpn/config,\n" \ " but this can be set using the -c option.\n" \ " A simple config file example looks like:\n" \ " # this is a comment\n" \ " host = vpn-gateway\n" \ " port = 8443\n" \ " username = foo\n" \ " password = bar\n" \ " trusted-cert = certificatedigest4daa8c5fe6c...\n" \ " trusted-cert = othercertificatedigest6631bf...\n" \ " For a full-featured config see man openfortivpn(1).\n" static inline void destroy_vpn_config(struct vpn_config *cfg) { while (cfg->cert_whitelist != NULL) { struct x509_digest *tmp = cfg->cert_whitelist->next; free(cfg->cert_whitelist); cfg->cert_whitelist = tmp; } free(cfg->cipher_list); free(cfg->user_key); free(cfg->user_cert); free(cfg->ca_file); free(cfg->pppd_ipparam); free(cfg->pppd_plugin); free(cfg->pppd_log); } int main(int argc, char **argv) { int ret = EXIT_FAILURE; char *config_file = SYSCONFDIR"/openfortivpn/config"; char *host, *username = NULL, *password = NULL, *otp = NULL; char *port_str; long int port; struct vpn_config cfg = { .gateway_host = {'\0'}, // gateway_ip .gateway_port = 0, .username = {'\0'}, .password = {'\0'}, .otp = {'\0'}, .cookie = {'\0'}, .realm = {'\0'}, .set_routes = 1, .set_dns = 1, .pppd_use_peerdns = 1, .use_syslog = 0, .half_internet_routes = 0, .pppd_log = NULL, .pppd_plugin = NULL, .pppd_ipparam = NULL, .ca_file = NULL, .user_cert = NULL, .user_key = NULL, .verify_cert = 1, .insecure_ssl = 0, .cipher_list = NULL, .cert_whitelist = NULL }; const struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 0}, {"config", required_argument, 0, 'c'}, {"realm", required_argument, 0, 0}, {"username", required_argument, 0, 'u'}, {"password", required_argument, 0, 'p'}, {"otp", required_argument, 0, 'o'}, {"set-routes", required_argument, 0, 0}, {"no-routes", no_argument, &cfg.set_routes, 0}, {"half-internet-routes", required_argument, 0, 0}, {"set-dns", required_argument, 0, 0}, {"no-dns", no_argument, &cfg.set_dns, 0}, {"pppd-no-peerdns", no_argument, &cfg.pppd_use_peerdns, 0}, {"use-syslog", no_argument, &cfg.use_syslog, 1}, {"ca-file", required_argument, 0, 0}, {"user-cert", required_argument, 0, 0}, {"user-key", required_argument, 0, 0}, {"trusted-cert", required_argument, 0, 0}, {"insecure-ssl", no_argument, &cfg.insecure_ssl, 1}, {"cipher-list", required_argument, 0, 0}, {"pppd-log", required_argument, 0, 0}, {"pppd-plugin", required_argument, 0, 0}, {"pppd-ipparam", required_argument, 0, 0}, {"pppd-ifname", required_argument, 0, 0}, {"plugin", required_argument, 0, 0}, // deprecated {0, 0, 0, 0} }; init_logging(); while (1) { /* getopt_long stores the option index here. */ int c, option_index = 0; c = getopt_long(argc, argv, "hvqc:u:p:o:", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 0: /* If this option set a flag, do nothing else now. */ if (long_options[option_index].flag != 0) break; if (strcmp(long_options[option_index].name, "version") == 0) { printf(VERSION "\n"); ret = EXIT_SUCCESS; goto exit; } if (strcmp(long_options[option_index].name, "pppd-log") == 0) { cfg.pppd_log = strdup(optarg); break; } if (strcmp(long_options[option_index].name, "pppd-plugin") == 0) { cfg.pppd_plugin = strdup(optarg); break; } if (strcmp(long_options[option_index].name, "pppd-ifname") == 0) { cfg.pppd_ifname = strdup(optarg); break; } if (strcmp(long_options[option_index].name, "pppd-ipparam") == 0) { cfg.pppd_ipparam = strdup(optarg); break; } // --plugin is deprecated, --pppd-plugin should be used if (cfg.pppd_plugin == NULL && strcmp(long_options[option_index].name, "plugin") == 0) { cfg.pppd_plugin = strdup(optarg); break; } if (strcmp(long_options[option_index].name, "ca-file") == 0) { cfg.ca_file = strdup(optarg); break; } if (strcmp(long_options[option_index].name, "user-cert") == 0) { cfg.user_cert = strdup(optarg); break; } if (strcmp(long_options[option_index].name, "user-key") == 0) { cfg.user_key = strdup(optarg); break; } if (strcmp(long_options[option_index].name, "realm") == 0) { strncpy(cfg.realm, optarg, FIELD_SIZE); cfg.realm[FIELD_SIZE] = '\0'; break; } if (strcmp(long_options[option_index].name, "trusted-cert") == 0) { if (add_trusted_cert(&cfg, optarg)) log_warn("Could not add certificate " "digest to whitelist.\n"); break; } if (strcmp(long_options[option_index].name, "cipher-list") == 0) { cfg.cipher_list = strdup(optarg); break; } if (strcmp(long_options[option_index].name, "set-routes") == 0) { int set_routes = strtob(optarg); if (set_routes < 0) { log_warn("Bad set-routes option: \"%s\"\n", optarg); break; } cfg.set_routes = set_routes; break; } if (strcmp(long_options[option_index].name, "half-internet-routes") == 0) { int half_internet_routes = strtob(optarg); if (half_internet_routes < 0) { log_warn("Bad half-internet-routes option: " "\"%s\"\n", optarg); break; } cfg.half_internet_routes = half_internet_routes; break; } if (strcmp(long_options[option_index].name, "set-dns") == 0) { int set_dns = strtob(optarg); if (set_dns < 0) { log_warn("Bad set-dns option: \"%s\"\n", optarg); break; } cfg.set_dns = set_dns; break; } goto user_error; case 'h': printf("%s%s%s", usage, help_options, help_config); ret = EXIT_SUCCESS; goto exit; case 'v': increase_verbosity(); break; case 'q': decrease_verbosity(); break; case 'c': config_file = optarg; break; case 'u': username = optarg; break; case 'p': password = optarg; break; case 'o': otp = optarg; break; default: goto user_error; } } if (optind < argc - 1 || optind > argc) goto user_error; set_syslog(cfg.use_syslog); if (password != NULL) log_warn("You should not pass the password on the command " "line. Type it interactively or use a config file " "instead.\n"); // Load config file if (config_file[0] != '\0') { ret = load_config(&cfg, config_file); set_syslog(cfg.use_syslog); if (ret == 0) log_debug("Loaded config file \"%s\".\n", config_file); else log_warn("Could not load config file \"%s\" (%s).\n", config_file, err_cfg_str(ret)); } // Read host and port from the command line if (optind == argc - 1) { host = argv[optind++]; port_str = strchr(host, ':'); if (port_str == NULL) { log_error("Specify a valid host:port couple.\n"); goto user_error; } port_str[0] = '\0'; strncpy(cfg.gateway_host, host, FIELD_SIZE); cfg.gateway_host[FIELD_SIZE] = '\0'; port_str++; port = strtol(port_str, NULL, 0); if (port <= 0 || port > 65535) { log_error("Specify a valid port.\n"); goto user_error; } cfg.gateway_port = port; } // Read username and password from the command line if (username != NULL) { strncpy(cfg.username, username, FIELD_SIZE); cfg.username[FIELD_SIZE] = '\0'; } if (password != NULL) { strncpy(cfg.password, password, FIELD_SIZE); cfg.password[FIELD_SIZE] = '\0'; } if (otp != NULL) { strncpy(cfg.otp, otp, FIELD_SIZE); cfg.otp[FIELD_SIZE] = '\0'; } // Check host and port if (cfg.gateway_host[0] == '\0' || cfg.gateway_port == 0) { log_error("Specify a valid host:port couple.\n"); goto user_error; } // Check username if (cfg.username[0] == '\0') { log_error("Specify an username.\n"); goto user_error; } // If no password given, interactively ask user if (cfg.password[0] == '\0') read_password("VPN account password: ", cfg.password, FIELD_SIZE); // Check password if (cfg.password[0] == '\0') { log_error("Specify a password.\n"); goto user_error; } log_debug("Config host = \"%s\"\n", cfg.gateway_host); log_debug("Config realm = \"%s\"\n", cfg.realm); log_debug("Config port = \"%d\"\n", cfg.gateway_port); log_debug("Config username = \"%s\"\n", cfg.username); log_debug("Config password = \"%s\"\n", "********"); if (cfg.otp[0] != '\0') log_debug("One-time password = \"%s\"\n", cfg.otp); if (geteuid() != 0) log_warn("This process was not spawned with root " "privileges, this will probably not work.\n"); if (run_tunnel(&cfg) == 0) ret = EXIT_SUCCESS; goto exit; user_error: fprintf(stderr, "%s", usage); exit: destroy_vpn_config(&cfg); exit(ret); } openfortivpn-1.6.0/src/ssl.h000066400000000000000000000117251320302212600160050ustar00rootroot00000000000000/* * Copyright (C) 2015 Adrien Vergé * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * In addition, as a special exception, the copyright holders give permission * to link the code of portions of this program with the OpenSSL library under * certain conditions as described in each individual source file, and * distribute linked combinations including the two. * You must obey the GNU General Public License in all respects for all of the * code used other than OpenSSL. If you modify file(s) with this exception, * you may extend this exception to your version of the file(s), but you are * not obligated to do so. If you do not wish to do so, delete this exception * statement from your version. If you delete this exception statement from * all source files in the program, then also delete it here. */ #ifndef _OPENFORTIVPN_SSL_H #define _OPENFORTIVPN_SSL_H #include #include #include #include #ifdef __APPLE__ /* * Get rid of OSX 10.7 and greater deprecation warnings * see for instance https://wiki.openssl.org/index.php/Hostname_validation * this pragma selectively suppresses this type of warnings in clang */ #pragma clang diagnostic ignored "-Wdeprecated-declarations" /* * ERESTART is one of the recoverable errors which might be returned. * However, in OSX this constant is not defined in errno.h so we define * a dummy value here. */ #define ERESTART -1 #endif #define ERR_SSL_AGAIN 0 #define ERR_SSL_CLOSED -1 #define ERR_SSL_CERT -2 #define ERR_SSL_EOF -3 #define ERR_SSL_PROTOCOL -4 #define ERR_SSL_SEE_ERRNO -5 #define ERR_SSL_SEE_SSLERR -6 #define ERR_SSL_UNKNOWN -7 static inline const char *err_ssl_str(int code) { if (code == ERR_SSL_AGAIN) return "Try again"; else if (code == ERR_SSL_CLOSED) return "Connection closed"; else if (code == ERR_SSL_CERT) return "Want X509 lookup"; else if (code == ERR_SSL_EOF) return "Protocol violation with EOF"; else if (code == ERR_SSL_PROTOCOL) return "Protocol error"; else if (code == ERR_SSL_SEE_ERRNO) return strerror(errno); else if (code == ERR_SSL_SEE_SSLERR) return ERR_error_string(ERR_peek_last_error(), NULL); return "unknown"; } static inline int handle_ssl_error(SSL *ssl, int ret) { int code; if (SSL_get_shutdown(ssl) & SSL_RECEIVED_SHUTDOWN) return ERR_SSL_CLOSED; code = SSL_get_error(ssl, ret); if (code == SSL_ERROR_WANT_READ || code == SSL_ERROR_WANT_WRITE) return ERR_SSL_AGAIN; // The caller should try again if (code == SSL_ERROR_ZERO_RETURN) return ERR_SSL_CLOSED; if (code == SSL_ERROR_WANT_X509_LOOKUP) return ERR_SSL_CERT; if (code == SSL_ERROR_SYSCALL) { if (ERR_peek_last_error() != 0) return ERR_SSL_SEE_SSLERR; if (ret == 0) return ERR_SSL_EOF; if (errno == EAGAIN || errno == ERESTART || errno == EINTR) return ERR_SSL_AGAIN; // The caller should try again if (errno == EPIPE) return ERR_SSL_CLOSED; return ERR_SSL_SEE_ERRNO; } if (code == SSL_ERROR_SSL) return ERR_SSL_PROTOCOL; return ERR_SSL_UNKNOWN; } /* * Reads data from the SSL connection. * * @return > 0 in case of success (number of bytes transfered) * ERR_SSL_AGAIN if the caller should try again * < 0 in case of error */ static inline int safe_ssl_read(SSL *ssl, uint8_t *buf, int bufsize) { int ret; ret = SSL_read(ssl, buf, bufsize); if (ret > 0) return ret; return handle_ssl_error(ssl, ret); } /* * Reads all data from the SSL connection. * * @return 1 in case of success * < 0 in case of error */ static inline int safe_ssl_read_all(SSL *ssl, uint8_t *buf, int bufsize) { int n = 0; while (n < bufsize) { int ret; ret = safe_ssl_read(ssl, &buf[n], bufsize - n); if (ret == ERR_SSL_AGAIN) continue; else if (ret < 0) return ret; n += ret; } return 1; } /* * Writes data to the SSL connection. * * Since SSL_MODE_ENABLE_PARTIAL_WRITE is not set by default (see man * SSL_get_mode), SSL_write() will only report success once the complete chunk * has been written. * * @return > 0 in case of success (number of bytes transfered) * ERR_SSL_AGAIN if the caller should try again * < 0 in case of error */ static inline int safe_ssl_write(SSL *ssl, const uint8_t *buf, int n) { int ret; ret = SSL_write(ssl, buf, n); if (ret > 0) return ret; return handle_ssl_error(ssl, ret); } #endif openfortivpn-1.6.0/src/tunnel.c000066400000000000000000000556761320302212600165210ustar00rootroot00000000000000/* * Copyright (C) 2015 Adrien Vergé * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * In addition, as a special exception, the copyright holders give permission * to link the code of portions of this program with the OpenSSL library under * certain conditions as described in each individual source file, and * distribute linked combinations including the two. * You must obey the GNU General Public License in all respects for all of the * code used other than OpenSSL. If you modify file(s) with this exception, * you may extend this exception to your version of the file(s), but you are * not obligated to do so. If you do not wish to do so, delete this exception * statement from your version. If you delete this exception statement from * all source files in the program, then also delete it here. */ #include "tunnel.h" #include "http.h" #include "log.h" #include #include #include #include #include #include #include #include #include #ifndef __APPLE__ #include #else #include #endif #include #include #include static int on_ppp_if_up(struct tunnel *tunnel) { log_info("Interface %s is UP.\n", tunnel->ppp_iface); if (tunnel->config->set_routes) { int ret; log_info("Setting new routes...\n"); ret = ipv4_set_tunnel_routes(tunnel); if (ret != 0) { log_warn("Adding route table is incomplete. " "Please check route table.\n"); } } if (tunnel->config->set_dns) { log_info("Adding VPN nameservers...\n"); ipv4_add_nameservers_to_resolv_conf(tunnel); } log_info("Tunnel is up and running.\n"); return 0; } static int on_ppp_if_down(struct tunnel *tunnel) { log_info("Setting ppp interface down.\n"); if (tunnel->config->set_routes) { log_info("Restoring routes...\n"); ipv4_restore_routes(tunnel); } if (tunnel->config->set_dns) { log_info("Removing VPN nameservers...\n"); ipv4_del_nameservers_from_resolv_conf(tunnel); } return 0; } static int pppd_run(struct tunnel *tunnel) { pid_t pid; int amaster; #ifndef __APPLE__ struct termios termp; #endif static const char pppd_path[] = "/usr/sbin/pppd"; if (access(pppd_path, F_OK) != 0) { log_error("%s: %s.\n", pppd_path, strerror(errno)); return 1; } #ifndef __APPLE__ termp.c_cflag = B9600; termp.c_cc[VTIME] = 0; termp.c_cc[VMIN] = 1; pid = forkpty(&amaster, NULL, &termp, NULL); #else pid = forkpty(&amaster, NULL, NULL, NULL); #endif if (pid == -1) { log_error("forkpty: %s\n", strerror(errno)); return 1; } else if (pid == 0) { // child process static const char *args[] = { pppd_path, "38400", // speed ":1.1.1.1", // : "noipdefault", "noaccomp", "noauth", "default-asyncmap", "nopcomp", "receive-all", "nodefaultroute", "nodetach", "lcp-max-configure", "40", "mru", "1354", NULL, // "usepeerdns" NULL, NULL, NULL, // "debug", "logfile", pppd_log NULL, NULL, // "plugin", pppd_plugin NULL, NULL, // "ipparam", pppd_ipparam NULL, NULL, // "ifname", pppd_ifname NULL // terminal null pointer required by execvp() }; // Dynamically get first NULL pointer so that changes of // args above don't need code changes here int i = ARRAY_SIZE(args) - 1; while (args[i] == NULL) i--; i++; /* * Coverity detected a defect: * CID 196857: Out-of-bounds write (OVERRUN) * It is actually a false positive. Because 'args' is not * constant, Coverity is unable to infer that the NULL * elements 'args' has been initialized with shall still * be present when initializing 'i' in the above loop. */ if (tunnel->config->pppd_use_peerdns) args[i++] = "usepeerdns"; if (tunnel->config->pppd_log) { args[i++] = "debug"; args[i++] = "logfile"; args[i++] = tunnel->config->pppd_log; } if (tunnel->config->pppd_plugin) { args[i++] = "plugin"; args[i++] = tunnel->config->pppd_plugin; } if (tunnel->config->pppd_ipparam) { args[i++] = "ipparam"; args[i++] = tunnel->config->pppd_ipparam; } if (tunnel->config->pppd_ifname) { args[i++] = "ifname"; args[i++] = tunnel->config->pppd_ifname; } // Assert that we didn't use up all NULL pointers above assert(i < ARRAY_SIZE(args)); close(tunnel->ssl_socket); execv(args[0], (char *const *)args); /* * The following call to fprintf() doesn't work, probably * because of the prior call to forkpty(). * TODO: print a meaningful message using strerror(errno) */ fprintf(stderr, "execvp: %s\n", strerror(errno)); _exit(EXIT_FAILURE); } // Set non-blocking int flags = fcntl(amaster, F_GETFL, 0); if (flags == -1) flags = 0; if (fcntl(amaster, F_SETFL, flags | O_NONBLOCK) == -1) { log_error("fcntl: %s\n", strerror(errno)); return 1; } tunnel->pppd_pid = pid; tunnel->pppd_pty = amaster; return 0; } static const char * const pppd_message[] = { "Returned an unknown exit status", // fall back "Has detached, or otherwise the connection was successfully" " established and terminated at the peer's request.", "An immediately fatal error of some kind occurred, such as an" " essential system call failing, or running out of virtual memory.", "An error was detected in processing the options given, such as two" " mutually exclusive options being used.", "Is not setuid-root and the invoking user is not root.", "The kernel does not support PPP, for example, the PPP kernel driver" " is not included or cannot be loaded.", "Terminated because it was sent a SIGINT, SIGTERM or SIGHUP signal.", "The serial port could not be locked.", "The serial port could not be opened.", "The connect script failed (returned a non-zero exit status).", "The command specified as the argument to the pty option" " could not be run.", "The PPP negotiation failed, that is, it didn't reach the point" " where at least one network protocol (e.g. IP) was running.", "The peer system failed (or refused) to authenticate itself.", "The link was established successfully and terminated because" " it was idle.", "The link was established successfully and terminated because the" " connect time limit was reached.", "Callback was negotiated and an incoming call should arrive shortly.", "The link was terminated because the peer is not responding to echo" " requests.", // emitted when exiting normally "The link was terminated by the modem hanging up.", "The PPP negotiation failed because serial loopback was detected.", "The init script failed (returned a non-zero exit status).", "We failed to authenticate ourselves to the peer." }; static int pppd_terminate(struct tunnel *tunnel) { close(tunnel->pppd_pty); log_debug("Waiting for pppd to exit...\n"); int status; if (waitpid(tunnel->pppd_pid, &status, 0) == -1) { log_error("waitpid: %s\n", strerror(errno)); return 1; } if (WIFEXITED(status)) { int exit_status = WEXITSTATUS(status); log_debug("waitpid: pppd exit status code %d\n", exit_status); if (exit_status) { size_t len_pppd_message = ARRAY_SIZE(pppd_message); if (exit_status >= len_pppd_message) exit_status = 0; if (exit_status != 16) // emitted when exiting normally log_error("pppd: %s\n", pppd_message[exit_status]); } } else if (WIFSIGNALED(status)) { int signal_number = WTERMSIG(status); log_debug("waitpid: pppd terminated by signal %d\n", signal_number); log_error("pppd: terminated by signal: %s\n", strsignal(signal_number)); } return 0; } int ppp_interface_is_up(struct tunnel *tunnel) { struct ifaddrs *ifap, *ifa; log_debug("Got Address: %s\n", inet_ntoa(tunnel->ipv4.ip_addr)); if (getifaddrs(&ifap)) { log_error("getifaddrs: %s\n", strerror(errno)); return 0; } for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) { if (((tunnel->config->pppd_ifname && strstr(ifa->ifa_name, tunnel->config->pppd_ifname) != NULL) || strstr(ifa->ifa_name, "ppp") != NULL) && ifa->ifa_flags & IFF_UP) { if (&(ifa->ifa_addr->sa_family) != NULL && ifa->ifa_addr->sa_family == AF_INET) { struct in_addr if_ip_addr = cast_addr(ifa->ifa_addr)->sin_addr; log_debug("Interface Name: %s\n", ifa->ifa_name); log_debug("Interface Addr: %s\n", inet_ntoa(if_ip_addr)); if (tunnel->ipv4.ip_addr.s_addr == if_ip_addr.s_addr) { strncpy(tunnel->ppp_iface, ifa->ifa_name, ROUTE_IFACE_LEN - 1); freeifaddrs(ifap); return 1; } } } } freeifaddrs(ifap); return 0; } static int get_gateway_host_ip(struct tunnel *tunnel) { const struct addrinfo hints = { .ai_family = AF_INET }; struct addrinfo *result = NULL; int ret = getaddrinfo(tunnel->config->gateway_host, NULL, &hints, &result); if (ret) { if (ret == EAI_SYSTEM) log_error("getaddrinfo: %s\n", strerror(errno)); else log_error("getaddrinfo: %s\n", gai_strerror(ret)); return 1; } tunnel->config->gateway_ip = ((struct sockaddr_in *) result->ai_addr)->sin_addr; freeaddrinfo(result); setenv("VPN_GATEWAY", inet_ntoa(tunnel->config->gateway_ip), 0); return 0; } /* * Establish a regular TCP connection. */ static int tcp_connect(struct tunnel *tunnel) { int ret, handle; struct sockaddr_in server; char *env_proxy; handle = socket(AF_INET, SOCK_STREAM, 0); if (handle == -1) { log_error("socket: %s\n", strerror(errno)); goto err_socket; } env_proxy = getenv("https_proxy"); if (env_proxy == NULL) env_proxy = getenv("HTTPS_PROXY"); if (env_proxy == NULL) env_proxy = getenv("all_proxy"); if (env_proxy == NULL) env_proxy = getenv("ALL_PROXY"); if (env_proxy != NULL) { char *proxy_host, *proxy_port; // protect the original environment from modifications env_proxy = strdup(env_proxy); // get rid of a trailing slash if (env_proxy[strlen(env_proxy) - 1] == '/') env_proxy[strlen(env_proxy) - 1] = '\0'; // get rid of a http(s):// prefix in env_proxy proxy_host = strstr(env_proxy, "://"); if (proxy_host == NULL) proxy_host = env_proxy; else proxy_host += 3; // split host and port proxy_port = index(proxy_host, ':'); if (proxy_port != NULL) { proxy_port[0] = '\0'; proxy_port++; server.sin_port = htons(strtol(proxy_port, NULL, 10)); } else { server.sin_port = htons(tunnel->config->gateway_port); } // get rid of a trailing slash if (proxy_host[strlen(proxy_host) - 1] == '/') proxy_host[strlen(proxy_host) - 1] = '\0'; log_debug("proxy_host: %s\n", proxy_host); log_debug("proxy_port: %s\n", proxy_port); server.sin_addr.s_addr = inet_addr(proxy_host); // if host is given as fqhn we have to do a dns lookup if (server.sin_addr.s_addr == INADDR_NONE) { const struct addrinfo hints = { .ai_family = AF_INET }; struct addrinfo *result = NULL; ret = getaddrinfo(proxy_host, NULL, &hints, &result); if (ret) { if (ret == EAI_SYSTEM) log_error("getaddrinfo: %s\n", strerror(errno)); else log_error("getaddrinfo: %s\n", gai_strerror(ret)); goto err_connect; } server.sin_addr = ((struct sockaddr_in *) result->ai_addr)->sin_addr; freeaddrinfo(result); } } else { server.sin_port = htons(tunnel->config->gateway_port); server.sin_addr = tunnel->config->gateway_ip; } log_debug("server_addr: %s\n", inet_ntoa(server.sin_addr)); log_debug("server_port: %u\n", ntohs(server.sin_port)); server.sin_family = AF_INET; memset(&(server.sin_zero), '\0', 8); log_debug("gateway_addr: %s\n", inet_ntoa(tunnel->config->gateway_ip)); log_debug("gateway_port: %u\n", tunnel->config->gateway_port); ret = connect(handle, (struct sockaddr *) &server, sizeof(server)); if (ret == -1) { log_error("connect: %s\n", strerror(errno)); goto err_connect; } if (env_proxy != NULL) { char request[128]; // https://tools.ietf.org/html/rfc7231#section-4.3.6 sprintf(request, "CONNECT %s:%u HTTP/1.1\r\nHost: %s:%u\r\n\r\n", inet_ntoa(tunnel->config->gateway_ip), tunnel->config->gateway_port, inet_ntoa(tunnel->config->gateway_ip), tunnel->config->gateway_port); if (write(handle, request, strlen(request)) != strlen(request)) { log_error("write error when talking to proxy\n"); goto err_connect; } // wait for a "200 OK" reply from the proxy, // be careful not to fetch too many characters at once char *response; int bytes_read, curr_pos = 0; memset(&(request), '\0', sizeof(request)); do { bytes_read = read(handle, &(request[curr_pos++]), 1); response = strstr(request, "200"); } while ( ( // repeat reading until we have got the string "200" (response == NULL) // continue reading until we hit the first empty line || ( // server uses newlines only (strstr(response, "\n\n") == NULL) // server uses cr+lf && (strstr(response, "\r\n\r\n") == NULL) // server uses lf+cr && (strstr(response, "\n\r\n\r") == NULL) ) ) // condition for buffer full or possibly eof && (curr_pos < sizeof(request) - 1) && (bytes_read > 0) ); free(env_proxy); // we have copied the string } return handle; err_connect: free(env_proxy); // we have copied the string close(handle); err_socket: return -1; } static int ssl_verify_cert(struct tunnel *tunnel) { int ret = -1; unsigned char digest[SHA256LEN]; unsigned int len; struct x509_digest *elem; char digest_str[SHA256STRLEN], *subject, *issuer; char *line; int i; X509_NAME *subj; char common_name[FIELD_SIZE + 1]; SSL_set_verify(tunnel->ssl_handle, SSL_VERIFY_PEER, NULL); X509 *cert = SSL_get_peer_certificate(tunnel->ssl_handle); if (cert == NULL) { log_error("Unable to get gateway certificate.\n"); return 1; } subj = X509_get_subject_name(cert); // Try to validate certificate using local PKI if (subj && X509_NAME_get_text_by_NID(subj, NID_commonName, common_name, FIELD_SIZE) > 0 && strncasecmp(common_name, tunnel->config->gateway_host, FIELD_SIZE) == 0 && SSL_get_verify_result(tunnel->ssl_handle) == X509_V_OK) { log_debug("Gateway certificate validation succeeded.\n"); ret = 0; goto free_cert; } log_debug("Gateway certificate validation failed.\n"); // If validation failed, check if cert is in the white list if (X509_digest(cert, EVP_sha256(), digest, &len) <= 0 || len != SHA256LEN) { log_error("Could not compute certificate sha256 digest.\n"); goto free_cert; } // Encode digest in base16 for (i = 0; i < SHA256LEN; i++) sprintf(&digest_str[2 * i], "%02x", digest[i]); digest_str[SHA256STRLEN - 1] = '\0'; // Is it in whitelist? for (elem = tunnel->config->cert_whitelist; elem != NULL; elem = elem->next) if (memcmp(digest_str, elem->data, SHA256STRLEN - 1) == 0) break; if (elem != NULL) { // break before end of loop log_debug("Gateway certificate digest found in white list.\n"); ret = 0; goto free_cert; } subject = X509_NAME_oneline(subj, NULL, 0); issuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0); log_error("Gateway certificate validation failed, and the certificate " "digest in not in the local whitelist. If you trust it, " "rerun with:\n"); log_error(" --trusted-cert %s\n", digest_str); log_error("or add this line to your config file:\n"); log_error(" trusted-cert = %s\n", digest_str); log_error("Gateway certificate:\n"); log_error(" subject:\n"); for (line = strtok(subject, "/"); line != NULL; line = strtok(NULL, "/")) log_error(" %s\n", line); log_error(" issuer:\n"); for (line = strtok(issuer, "/"); line != NULL; line = strtok(NULL, "/")) log_error(" %s\n", line); log_error(" sha256 digest:\n"); log_error(" %s\n", digest_str); free_cert: X509_free(cert); return ret; } /* * Destroy and free the SSL connection to the gateway. */ static void ssl_disconnect(struct tunnel *tunnel) { if (!tunnel->ssl_handle) return; SSL_shutdown(tunnel->ssl_handle); SSL_free(tunnel->ssl_handle); SSL_CTX_free(tunnel->ssl_context); close(tunnel->ssl_socket); tunnel->ssl_handle = NULL; tunnel->ssl_context = NULL; } /* * Connects to the gateway and initiate a SSL session. */ int ssl_connect(struct tunnel *tunnel) { ssl_disconnect(tunnel); tunnel->ssl_socket = tcp_connect(tunnel); if (tunnel->ssl_socket == -1) return 1; // Register the error strings for libcrypto & libssl SSL_load_error_strings(); // Register the available ciphers and digests SSL_library_init(); tunnel->ssl_context = SSL_CTX_new(SSLv23_client_method()); if (tunnel->ssl_context == NULL) { log_error("SSL_CTX_new: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } // Load the OS default CA files if (!SSL_CTX_set_default_verify_paths(tunnel->ssl_context)) log_error("Could not load OS OpenSSL files.\n"); if (tunnel->config->ca_file) { if (!SSL_CTX_load_verify_locations( tunnel->ssl_context, tunnel->config->ca_file, NULL)) { log_error("SSL_CTX_load_verify_locations: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } } if (tunnel->config->user_cert) { if (!SSL_CTX_use_certificate_file( tunnel->ssl_context, tunnel->config->user_cert, SSL_FILETYPE_PEM)) { log_error("SSL_CTX_use_certificate_file: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } } if (tunnel->config->user_key) { if (!SSL_CTX_use_PrivateKey_file( tunnel->ssl_context, tunnel->config->user_key, SSL_FILETYPE_PEM)) { log_error("SSL_CTX_use_PrivateKey_file: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } } if (tunnel->config->user_cert && tunnel->config->user_key) { if (!SSL_CTX_check_private_key(tunnel->ssl_context)) { log_error("SSL_CTX_check_private_key: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } } if (!tunnel->config->insecure_ssl) { long sslctxopt = SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION; long checkopt; checkopt = SSL_CTX_set_options(tunnel->ssl_context, sslctxopt); if ((checkopt & sslctxopt) != sslctxopt) { log_error("SSL_CTX_set_options didn't set opt: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } } tunnel->ssl_handle = SSL_new(tunnel->ssl_context); if (tunnel->ssl_handle == NULL) { log_error("SSL_new: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } if (!tunnel->config->insecure_ssl && !tunnel->config->cipher_list) { char *cipher_list = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4"; if (tunnel->config->cipher_list) cipher_list = tunnel->config->cipher_list; if (!SSL_set_cipher_list(tunnel->ssl_handle, cipher_list)) { log_error("SSL_set_cipher_list failed: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } } if (!SSL_set_fd(tunnel->ssl_handle, tunnel->ssl_socket)) { log_error("SSL_set_fd: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } SSL_set_mode(tunnel->ssl_handle, SSL_MODE_AUTO_RETRY); // Initiate SSL handshake if (SSL_connect(tunnel->ssl_handle) != 1) { log_error("SSL_connect: %s\n" "You might want to try --insecure-ssl or specify " "a different --cipher-list\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } SSL_set_mode(tunnel->ssl_handle, SSL_MODE_AUTO_RETRY); if (tunnel->config->verify_cert) if (ssl_verify_cert(tunnel)) return 1; // Disable SIGPIPE (occurs when trying to write to an already-closed // socket). signal(SIGPIPE, SIG_IGN); return 0; } int run_tunnel(struct vpn_config *config) { int ret; struct tunnel tunnel; memset(&tunnel, 0, sizeof(tunnel)); tunnel.config = config; tunnel.on_ppp_if_up = on_ppp_if_up; tunnel.on_ppp_if_down = on_ppp_if_down; tunnel.ipv4.ns1_addr.s_addr = 0; tunnel.ipv4.ns2_addr.s_addr = 0; tunnel.ssl_handle = NULL; tunnel.ssl_context = NULL; tunnel.state = STATE_DOWN; // Step 0: get gateway host IP ret = get_gateway_host_ip(&tunnel); if (ret) goto err_tunnel; // Step 1: open a SSL connection to the gateway ret = ssl_connect(&tunnel); if (ret) goto err_tunnel; log_info("Connected to gateway.\n"); // Step 2: connect to the HTTP interface and authenticate to get a // cookie ret = auth_log_in(&tunnel); if (ret != 1) { log_error("Could not authenticate to gateway (%s).\n", err_http_str(ret)); ret = 1; goto err_tunnel; } log_info("Authenticated.\n"); log_debug("Cookie: %s\n", config->cookie); ret = auth_request_vpn_allocation(&tunnel); if (ret != 1) { log_error("VPN allocation request failed (%s).\n", err_http_str(ret)); ret = 1; goto err_tunnel; } log_info("Remote gateway has allocated a VPN.\n"); ret = ssl_connect(&tunnel); if (ret) goto err_tunnel; // Step 3: get configuration ret = auth_get_config(&tunnel); if (ret != 1) { log_error("Could not get VPN configuration (%s).\n", err_http_str(ret)); ret = 1; goto err_tunnel; } // Step 4: run a pppd process ret = pppd_run(&tunnel); if (ret) goto err_tunnel; // Step 5: ask gateway to start tunneling ret = http_send(&tunnel, "GET /remote/sslvpn-tunnel HTTP/1.1\n" "Host: sslvpn\n" "Cookie: %s\n\n%c", tunnel.config->cookie, '\0'); if (ret != 1) { log_error("Could not start tunnel (%s).\n", err_http_str(ret)); ret = 1; goto err_start_tunnel; } tunnel.state = STATE_CONNECTING; ret = 0; // Step 6: perform io between pppd and the gateway, while tunnel is up io_loop(&tunnel); if (tunnel.state == STATE_UP) if (tunnel.on_ppp_if_down != NULL) tunnel.on_ppp_if_down(&tunnel); tunnel.state = STATE_DISCONNECTING; err_start_tunnel: pppd_terminate(&tunnel); log_info("Terminated pppd.\n"); err_tunnel: log_info("Closed connection to gateway.\n"); tunnel.state = STATE_DOWN; if (ssl_connect(&tunnel)) { log_info("Could not log out.\n"); } else { auth_log_out(&tunnel); log_info("Logged out.\n"); } // explicitly free the buffer allocated for split routes of the ipv4 config if (tunnel.ipv4.split_rt != NULL) { free(tunnel.ipv4.split_rt); tunnel.ipv4.split_rt = NULL; } return ret; } openfortivpn-1.6.0/src/tunnel.h000066400000000000000000000050301320302212600165010ustar00rootroot00000000000000/* * Copyright (C) 2015 Adrien Vergé * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * In addition, as a special exception, the copyright holders give permission * to link the code of portions of this program with the OpenSSL library under * certain conditions as described in each individual source file, and * distribute linked combinations including the two. * You must obey the GNU General Public License in all respects for all of the * code used other than OpenSSL. If you modify file(s) with this exception, * you may extend this exception to your version of the file(s), but you are * not obligated to do so. If you do not wish to do so, delete this exception * statement from your version. If you delete this exception statement from * all source files in the program, then also delete it here. */ #ifndef _OPENFORTIVPN_TUNNEL_H #define _OPENFORTIVPN_TUNNEL_H #include "config.h" #include "io.h" #include "ipv4.h" #include #include #ifdef __APPLE__ /* * Get rid of OSX 10.7 and greater deprecation warnings * see for instance https://wiki.openssl.org/index.php/Hostname_validation * this pragma selectively suppresses this type of warnings in clang */ #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif enum tunnel_state { STATE_DOWN, STATE_CONNECTING, STATE_UP, STATE_DISCONNECTING }; struct tunnel { struct vpn_config *config; enum tunnel_state state; struct ppp_packet_pool ssl_to_pty_pool; struct ppp_packet_pool pty_to_ssl_pool; pid_t pppd_pid; pid_t pppd_pty; char ppp_iface[ROUTE_IFACE_LEN]; int ssl_socket; SSL_CTX *ssl_context; SSL *ssl_handle; struct ipv4_config ipv4; int (*on_ppp_if_up)(struct tunnel *); int (*on_ppp_if_down)(struct tunnel *); }; int ppp_interface_is_up(struct tunnel *tunnel); int ssl_connect(struct tunnel *tunnel); int run_tunnel(struct vpn_config *config); #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) #endif openfortivpn-1.6.0/src/userinput.c000066400000000000000000000024571320302212600172370ustar00rootroot00000000000000/* * Copyright (C) 2015 Davíð Steinn Geirsson * * 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 . */ #include #include #include #include void read_password(const char *prompt, char *pass, size_t len) { int masked = 0; struct termios oldt, newt; int i; printf("%s", prompt); // Try to hide user input if (tcgetattr(STDIN_FILENO, &oldt) == 0) { newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); masked = 1; } for (i = 0; i < len; i++) { int c = getchar(); if (c == '\n' || c == EOF) break; pass[i] = (char) c; } pass[i] = '\0'; if (masked) tcsetattr(STDIN_FILENO, TCSANOW, &oldt); printf("\n"); } openfortivpn-1.6.0/src/userinput.h000066400000000000000000000015271320302212600172410ustar00rootroot00000000000000/* * Copyright (C) 2015 Davíð Steinn Geirsson * * 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 . */ #ifndef _OPENFORTIVPN_USERINPUT_H #define _OPENFORTIVPN_USERINPUT_H void read_password(const char *prompt, char *pass, size_t len); #endif openfortivpn-1.6.0/src/xml.c000066400000000000000000000052521320302212600157750ustar00rootroot00000000000000/* * Copyright (C) 2015 Lubomir Rintel * * 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 . */ #include "xml.h" #include "log.h" #include /* * Poor man's XML parser. Looks for given tag or attribute. Assumes * there's no CDATA or text content and does not recognize strings: * it would mess up the parsing if they contain '<' or '/'. * * @t '<' if we're looking for a tag, ' ' if we're looking * for an attribute. * @needle name of a tag or attribute (end and attribute with a * '=' to swallow it). * @buf a NUL terminated buffer to look in. * @nest do not escape more than @nest levels of nesting * (1 == look for kids, 2 == look for siblings). * @return a string immediately following the needle if found, * %NULL otherwise. */ const char *xml_find(char t, const char *needle, const char *buf, int nest) { int i; if (!buf) return NULL; for (i = 0; buf[i]; i++) { if (buf[i] == '<' && buf[i + 1] != '/') nest++; if (buf[i] == '/') nest--; if (!nest) return NULL; if (&buf[i+1] == strstr(&buf[i], needle) && buf[i] == t) { return &buf[i + 1 + strlen(needle)]; } } return NULL; } /* * Poor man's XML attribute parser. Takes the first string as a quoting * character and consumes characters until the next occurence or an end * of the buffer. Doesn't return more than 15 characters (enough for an * IPv4 address textural form). * * @buf a NUL terminated buffer to look in. * @return %NULL in case of an error, a character string with * ownership passed upon success */ char *xml_get(const char *buf) { char val[16]; // Just enough to hold an IPv4 address char quote; int i; if (!buf) return NULL; quote = buf[0]; if (!quote) { log_warn("Short read while getting value in config XML\n"); return NULL; } for (i = 1; buf[i]; i++) { if (buf[i] == quote) break; if (i == 16) { log_warn("Value too long in config XML\n"); break; } val[i - 1] = buf[i]; } if (buf[i] != quote) { log_warn("Could not read out an attribute value in config XML\n"); return NULL; } val[i - 1] = '\0'; return strdup(val); } openfortivpn-1.6.0/src/xml.h000066400000000000000000000015541320302212600160030ustar00rootroot00000000000000/* * Copyright (C) 2015 Lubomir Rintel * * 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 . */ #ifndef _OPENFORTIVPN_XML_H #define _OPENFORTIVPN_XML_H const char *xml_find(char t, const char *tag, const char *buf, int nest); char *xml_get(const char *buf); #endif openfortivpn-1.6.0/tests/000077500000000000000000000000001320302212600154005ustar00rootroot00000000000000openfortivpn-1.6.0/tests/lint/000077500000000000000000000000001320302212600163465ustar00rootroot00000000000000openfortivpn-1.6.0/tests/lint/astyle.sh000077500000000000000000000010121320302212600202000ustar00rootroot00000000000000#!/bin/bash # Copyright (C) 2015 Adrien Vergé # Check that astyle is installed if ! which astyle &>/dev/null; then echo "error: astyle is not installed" >&2 exit -1 fi rc=0 for file in "$@"; do tmp=$(mktemp) astyle \ --style=linux \ --indent=tab=8 \ --pad-header \ --align-reference=type \ <"$file" >$tmp if ! cmp -s "$file" $tmp; then echo "error: $file does not comply with coding style" git --no-pager diff --no-index -U0 "$file" $tmp rc=1 fi rm $tmp done exit $rc openfortivpn-1.6.0/tests/lint/eol-at-eof.sh000077500000000000000000000004571320302212600206430ustar00rootroot00000000000000#!/bin/bash # Copyright (C) 2015 Adrien Vergé rc=0 for file in "$@"; do if [ "$(sed -n '$p' "$file")" = "" ]; then echo "$file: too many newlines at end of file" rc=1 fi if [ "$(tail -c 1 "$file")" != "" ]; then echo "$file: no newline at end of file" rc=1 fi done exit $rc openfortivpn-1.6.0/tests/lint/line-length.sh000077500000000000000000000006711320302212600211170ustar00rootroot00000000000000#!/bin/bash # Copyright (C) 2015 Adrien Vergé # Guidelines say 80, let's tolerate a bit more MAX=90 rc=0 for file in "$@"; do tmp=$(mktemp) # Replace tabs with 8 spaces sed 's/\t/ /g' "$file" >$tmp awk "{ if (length(\$0) > $MAX) { print \"$file:\" NR \": line too long (\" length \" char)\" rc = 1 } } END { exit rc }" $tmp [ $? -ne 0 ] && rc=1 rm $tmp done exit $rc openfortivpn-1.6.0/tests/lint/run.sh000077500000000000000000000004321320302212600175100ustar00rootroot00000000000000#!/bin/bash # Copyright (C) 2015 Adrien Vergé rc=0 bash tests/lint/eol-at-eof.sh $(git ls-files) [ $? -ne 0 ] && rc=1 bash tests/lint/line-length.sh $(git ls-files '*.[ch]') [ $? -ne 0 ] && rc=1 bash tests/lint/astyle.sh $(git ls-files '*.[ch]') [ $? -ne 0 ] && rc=1 exit $rc