pax_global_header00006660000000000000000000000064136255132540014520gustar00rootroot0000000000000052 comment=cd9368c6a1b4ef91d77bb3fdbe2e5bc34aa6f4c4 openfortivpn-1.12.0/000077500000000000000000000000001362551325400143325ustar00rootroot00000000000000openfortivpn-1.12.0/.github/000077500000000000000000000000001362551325400156725ustar00rootroot00000000000000openfortivpn-1.12.0/.github/SECURITY.md000066400000000000000000000006031362551325400174620ustar00rootroot00000000000000# Security Policy ## Supported Versions Use this section to tell people about which versions of your project are currently being supported with security updates. | Version | Supported | | ----------------------- | ------------------ | | latest stable release | :white_check_mark: | ## Reporting a Vulnerability Send an email to security@openfortivpn.org. openfortivpn-1.12.0/.gitignore000066400000000000000000000002771362551325400163300ustar00rootroot00000000000000*.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.12.0/.travis.yml000066400000000000000000000026741362551325400164540ustar00rootroot00000000000000language: c sudo: false cache: directories: - $HOME/.openfortivpn-deps before_install: - tests/ci/install_astyle.sh $HOME/.openfortivpn-deps - tests/ci/install_openssl.sh $HOME/.openfortivpn-deps install: - ./autogen.sh - PKG_CONFIG_PATH=$HOME/.openfortivpn-deps/lib/pkgconfig ./configure --prefix=/usr --sysconfdir=/etc - make script: - ./tests/lint/run.sh env: global: # COVERITY_SCAN_TOKEN - secure: "HuYAk43itUiq0YJjmyvCyOM3mnRo8bFqSwksOmQ5fjvQscVWqZg6M9h8Abb+lKAc9L9avrwObjhu3EmOqoZ9Cjtp4WS4IdESK/UNe/jHpODFknsKefPgP67Z/yEFNVU1+5pS0+r+gTWQcZMyJrWrDde0lWpWHR/W7rTtqIbZH8Bp/T7oUN5q10x8PBcOZi/yVqNNicyuERIvUkobro5k+e4rY1N1HkptKs4wVY8M4WZUHwokNtuVfs0yoGQtrpi1KVRWq8sDkb8DNTeNv0MMEoQYUmNlEWxPaKJ9DBr65ajGLHzwUkWaNJGYw7mXwXoBwn5uKOyoytRA6Tj1wbVj4ggqqq6P6tbIcZ4YUW6N72gRaqvCnm6mRnbDHQtvzpqqxtr585mD11mh0DNmB15rvjNcZU/4wHHNQBsFcYEr+fN2/2ef/T3n0dymnnv2uZ05d11V5uSC6XYt3h0VxMDwarOVvOcWKYIQqzs4Bhigd2982v3OlIi5tbOSzHkbiCSP1msOKd6/XpCiCFpqed2UtSGZukisp3wQNfPnUOWoguOJ38nNe2o2G/l6HNOLd6u3sFlhzzthnJ6LPFD1CD9LPaOVYIVrRr90l0B2j1vPQM03eiiw7P6XvI6hPdqAM3VSEyjyrzUJRCUXAA8tovRwKTFlc506FWiFlGBFXFFI3zs=" addons: coverity_scan: project: name: adrienverge/openfortivpn description: Client for PPP+SSL VPN tunnel services notification_email: DimitriPapadopoulos@users.noreply.github.com build_command_prepend: ./configure --prefix=/usr --sysconfdir=/etc; make clean build_command: make branch_pattern: coverity_scan openfortivpn-1.12.0/CHANGELOG.md000066400000000000000000000271501362551325400161500ustar00rootroot00000000000000Openfortivpn Changelog ====================== Legend ------ * [+] new feature or improvement * [-] bug fix * [~] change in behavior Releases -------- This high level changelog is usually updated when a release is tagged. On the master branch there may be changes that are not (yet) described here. ### 1.12.0 * [-] fix CVE-2020-7043: TLS Certificate CommonName NULL Byte Vulnerability * [-] fix CVE-2020-7042: use of uninitialized memory in X509_check_host * [-] fix CVE-2020-7041: incorrect use of X509_check_host (regarding return value). * [-] always hide cleartest password in -vv output * [+] add a clear warning about sensitive information in the debug output * [+] add a hint in debug output when password is read from config file * [-] fix segfault when connecting with empty password * [+] use resolvconf if available to update resolv.conf file * [~] replace semicolon by space in dns-suffix string ### 1.11.0 * [+] allow to connect with empty password (and with smartcard instead of username) * [~] properly handle manipulations of resolv.conf * [+] support dns-suffix feature * [-] several codacy fixes * [+] Add smartcard support with openssl-engine * [-] correctly shift masks for cidr notation on MAC * [-] one-byte fix to build with lcc compiler * [-] pass space character as %20 instead of encoding it as '+' ### 1.10.0 * [-] fix openssl 1.1.x compatibility issues * [~] Connect to old TLSv1.0 software - override new openssl defaults. * [~] suppress cleartext password in debug detail output / add new verbosity level * [~] increase speed setting for pppd * [-] work around EAGAIN issue on FreeBSD * [~] configure.ac: rt_dst: don't run tests when option is passed * [~] configure.ac: don't check file path if --with/--disable specified * [+] userinput: pass a hint to the pinentry program * [-] tunnel: make pppd default to logging to stderr * [-] tunnel: pass our stderr to the pppd slave ### 1.9.0 * [+] update of the man page, especially about the dns settings * [+] improved configure output: show detected paths for use at runtime * [-] correctly convert parsed values, fix for an issue e.g. on Raspbian * [+] make search string for the otp-prompt configurable * [+] add an option to specify a configurable delay during otp authentication * [~] make the options that control usepeerdns more consistent ### 1.8.1 * [~] Support longer passowrds by allocation of a larger buffer * [-] With version 1.8.0 /etc/resolv.conf was not updated anymore in some situations. To avoid this regression the change "Rationalize DNS options" has been reverted again to restore the behavior of versions up to 1.7.1. * [-] Correctly use realm together with two factor authentication * [~] If no port is specified use standard https port similar as vendor client * [-] Fix value of Accept-Encoding request header * [-] Bugfix in url_encode for non alphanumerical characters * [-] HTML URL Encoding with uppercase characters * [-] Honor Cipher-list option * [~] Improved detection of pppd/ppp client during configure stage ### 1.8.0 * [-] On Mac OSX and FreeBSD correctly use interface name for routing * [~] On Mac OSX and FreeBSD moved netstat parsing output to higher debug level * [~] When logging traffic also show http traffic (not only tunneled traffic) * [~] Improve error message in case of login failure * [~] Require root privileges for running. They are needed at various places. Previously, just a warning was issued, but in later stage things have failed. * [-] On Mac OSX the protection of the route to the vpn gateway may have failed * [~] Invert order of ssl libraries (this may help linking on some platforms) * [+] Add FreeBSD support and redesigned the autoconf mechanism * [+] Support building with gcc 8 * [-] Prioritize command line arguments over config file parameters * [~] Dynamically allocate routing buffer and therefore allow larger routing table * [+] Support systemd notification upon tunnel up * [+] Support building in a separate directory * [~] Change the way to read passwords such that backspace etc. should work as usual * [~] Rationalize DNS options: pppd and openfortivpn were updating /etc/resolv.conf. Check man page and help output for the documentation of the current behavior. ### 1.7.1 * [~] Be more tolerant about white space in config file * [~] Make better usage of pkg-config * [~] Rework linking against OpenSSL * [-] Build again on Mac OSX where pthread_mutexattr_setrobust is not available ### 1.7.0 * [~] Correctly set up route to vpn gateway (add support for some particular situations) * [+] Support two factor authentication with config file (for NM-plugin) * [~] Change the ip address in the pppd call parameters by a rfc3330 test-net address * [-] Correctly report the exit status codes of pppd * [+] Add --pppd-call option * [~] Use X509_check_host instead of explicit CN match * [+] Add --persistent option * [~] Improve autoconf (check for pkg-conf before using, improve error messages, etc.) ### 1.6.0 * [-] Fix possible buffer overflow in in long requests * [~] Code improvements in terms of header inclusion and some other coverity warnings * [+] Add proxy support * [~] Use the compiled-in fixed full path to pppd * [+] Support pppd ifname option * [+] Print a clear error message at runtime if pppd does not exist * [+] Print clear text error messages of pppd upon failure * [~] Existing config file is not overwritten anymore at installation time * [~] Increase the accepted cookie size and align the error behavior according to RFCs * [-] More gracefully handle unexcpected content of resolv.conf * [~] Dynamically allocate memory for split routes and thus support larger numbers of routes ### 1.5.0 * [~] Improve error handling around the call of pppd * [+] Add half-internet-routes option * [-] realm was not recognized in the config file * [~] Switch from no-routes and no-dns to set-routes and set-dns option * [+] Add pppd-no-peerdns and pppd-log option * [~] Allow passing the otp via the config file for use with NetworkManager plugin * [-] Fix issues initializing memory and with build system * [+] Support building against Openssl 1.1 * [~] use pkg-config for configuration of openssl instead of configure option * [-] Fix string handling of the command line arguments ### 1.4.0 * [+] Allow to specify openssl location via configure option * [+] Introduce autotools build script autogen.sh * [~] Further increase possible number of split routes * [-] Fix locking issues on Mac OS X * [~] Rework signal handling: Handle SIGTERM as SIGINT and ignore SIGHUP ### 1.3.1 * [~] When calling pppd allow passing an ipparam for use in pppd ip-up/down scripts * [-] Command line option -o was not recognized before * [~] Improve Mac OSX support and parse netstat output to obtain routing information * [-] Fix segmentation fault when a gateway route is added on Mac OSX * [-] Fix buffer overflow for name server entries * [~] Increase possible number of split routes * [-] Do not remove route to vpn gateway if it has existed before connecting * [~] Load OS trusted certificate stores * [~} When setting up routes protect the route to the vpn gateway * [-] Add gateway flag to routes that may not be reachable directly at the tunnel end * [-] Correctly detect if pushed routes have a gateway * [-] Correctly mark the route to the vpn gateway as a host route * [-] Clean up routing table upon termination ### 1.3.0 * [+] Support vpn connections over an already existing ppp connection * [-] Fix for diagnostic message colors invisible on light background * [-] Bugfix for building with clang * [+] Add token-based one-time password support * [+] Add Mac OSX support * [+] Support logging via syslog * [-] Honor sysconfdir during runtime, i.e. when loading default configuration * [~] Disable insecure openssl default protocols/ciphers ### 1.2.0 * [+] Support login with client certificate, key, and ca-file specified in config file * [~] Use more meaningful error codes when loading config fails * [-] Correctly report errors of hostname lookup * [+] Add an option not to ask ppp peer for dns servers * [-] Fix array bounds error for trusted cert string * [-] Fix compiler warning about type cast around getchar * [-] Properly initialize memory for tunnel structure to avoid undeterministic behavior * [-] Properly initialize pointer in auth_log_in to avoid crash on http_request * [-] Fix buffer overflow in parse_config ### 1.1.4 * [-] Fix new GCC 6 strict-aliasing errors * [-] For split routes use interface if no gateway address is assigned in received route * [-] Fix rewrite of resolv.conf with non null-terminated buffer * [~] Perform two factor authentication also with zero-length tokeninfo ### 1.1.3 * [~] Support set-dns and set-routes flag from config file as well * [-] Properly URL-encode values sent in http requests * [+] Add support for realm authentication * [+] Add support for two factor authentication ### 1.1.2 * [-] Fix incompatible-pointer-types compiler error for x86 architectures * [~] Increase COOKIE_SIZE (again) ### 1.1.1 * [~] Update of Makefile to treat all warnings as errors * [~] Increase COOKIE_SIZE to 240 as the SVPNCOOKIE is longer in newer FortiOS versions ### 1.1.0 * [~] Rename --plugin to --pppd-plugin for consistency with other pppd-related options * [-] NUL terminate the config buffer * [-] Fix an off-by-one error when reading a quad-dotted attribute from xml * [+] Add support for client keys and certificates * [~] Extend the split VPN support with older FortiOS servers * [+] Add a config parser to handle received non-xml content * [~] Allow ommitting the gateway for split routes * [~] Allow ommitting DNS servers * [-] Fix a memory leak in auth_get_config * [+] Support split routes * [+] Export the configuration of routes and gateway to environment * [~] Several improvements around establishing the tunnel connection and http traffic * [+] Allow using a custom CA * [-] Turn on SSL verification, check the hostname at least for the CN * [+] Add --plugin option * [-] Fix a format string warning in do_log_packet * [~] Improved debugging output * [~] Restore default route ### 1.0.1 * [~] Better error messages in /etc/resolv.conf helpers * [~] Use better colors for warnings and error messages and only if output is a tty * [-] Fix parsing of "trusted-cert" in config file * [~] Add --pedantic to CFLAGS * [+] Add ability to type password interactively * [+] Verify gateway's X509 certificate * [-] Don't delete nameservers at tear down if they were here before * [~] Set /etc/openfortivpn/config not readable by other users * [+] Add ability to use a config file ### 1.0.0 * Start tracking openfortivpn - in this version with the following features: ``` Usage: openfortivpn : -u -p [--no-routes] [--no-dns] [--pppd-log=] [-v|-q] openfortivpn --help openfortivpn --version ``` ### Details of the changes This is a high level changelog meant to provide a rough overview about the version history of openfortivpn. Please see the Github [commit history](https://github.com/adrienverge/openfortivpn/commits) for more details of the individual changes listed here, and for a complete list of the internal code changes. More Information ---------------- * For a list of known issues please check the [issues list](https://github.com/adrienverge/openfortivpn/issues) on GitHub. * We try to avoid backwards incompatible changes, but sometimes it is not avoidable. When we are aware of compatibility issues, then we recommend to check the documentation in the above changelog. When changes turn out to break things for some specific configurations after we have tagged a new release, the issues list is the right place to report it, so that we can add a hint in the changelog for the subsequent release. openfortivpn-1.12.0/LICENSE000066400000000000000000001060631362551325400153450ustar00rootroot00000000000000 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.12.0/LICENSE.OpenSSL000066400000000000000000000142061362551325400166240ustar00rootroot00000000000000 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.12.0/Makefile.am000066400000000000000000000031131362551325400163640ustar00rootroot00000000000000# 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 \ src/openssl_hostname_validation.c \ src/openssl_hostname_validation.h openfortivpn_CFLAGS = -Wall -pedantic -std=gnu99 openfortivpn_CPPFLAGS = -DSYSCONFDIR=\"$(sysconfdir)\" \ -DPPP_PATH=\"@PPP_PATH@\" \ -DNETSTAT_PATH=\"@NETSTAT_PATH@\" \ -DRESOLVCONF_PATH=\"@RESOLVCONF_PATH@\" openfortivpn_CPPFLAGS += $(OPENSSL_CFLAGS) $(LIBSYSTEMD_CFLAGS) openfortivpn_LDADD = $(OPENSSL_LIBS) $(LIBSYSTEMD_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 ; \ sed -i 's/^/# /' $(DESTDIR)$(sysconfdir)/openfortivpn/config ; \ fi dist_man_MANS = doc/openfortivpn.1 doc/openfortivpn.1: $(srcdir)/doc/openfortivpn.1.in mkdir -p doc; sed -e 's|[@]SYSCONFDIR[@]|$(sysconfdir)|g;s|[@]DATADIR[@]|$(datadir)|g;' $(srcdir)/doc/openfortivpn.1.in >$@ EXTRA_DIST = LICENSE README.md doc/openfortivpn.1.in $(data_DATA) openfortivpn-1.12.0/README.md000066400000000000000000000143751362551325400156230ustar00rootroot00000000000000openfortivpn ============ 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 --pppd-no-peerdns ``` * Using a config file: ``` openfortivpn -c /etc/openfortivpn/my-config ``` With `/etc/openfortivpn/my-config` containing: ``` host = vpn-gateway port = 8443 username = foo password = bar set-routes = 0 set-dns = 0 pppd-use-peerdns = 0 # X509 certificate sha256 sum, trust only this one! trusted-cert = e46d4aff08ba6914e64daa85bc6112a422fa7ce16631bff0b592a28556f993db ``` --------- Smartcard --------- Smartcard support needs `openssl pkcs engine` and `opensc` to be installed. The pkcs11-engine from libp11 needs to be compiled with p11-kit-devel installed. Check [#464](https://github.com/adrienverge/openfortivpn/issues/464) for a discussion of known issues in this area. To make use of your smartcard put at least `pkcs11:` to the user-cert config or commandline option. It takes the full or a partial PKCS#11 token URI. ``` user-cert = pkcs11: user-cert = pkcs11:token=someuser user-cert = pkcs11:model=PKCS%2315%20emulated;manufacturer=piv_II;serial=012345678;token=someuser username = none password = none ``` In most cases `user-cert = pkcs11:` will do it, but if needed you can get the token-URI with `p11tool --list-token-urls`. Multiple readers are currently not supported. Smartcard support has been tested with Yubikey under Linux, but other PIV enabled smartcards may work too. On Mac OS X Mojave it is known that the pkcs eingine-by-id is not found. ---------- Installing ---------- ### Installing existing packages Some Linux distibutions provide `openfortivpn` packages: * [Fedora / CentOS](https://apps.fedoraproject.org/packages/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://www.archlinux.org/packages/community/x86_64/openfortivpn) * [Debian (testing)](https://packages.debian.org/buster/openfortivpn) * [Ubuntu (bionic and later)](https://packages.ubuntu.com/search?keywords=openfortivpn) and [pre-bionic (ppa)](https://launchpad.net/~ar-lex/+archive/ubuntu/fortisslvpn) * [Solus](https://dev.getsol.us/source/openfortivpn/) On macOS both [Homebrew](http://brewformulas.org/Openfortivpn) and [MacPorts](https://www.macports.org/ports.php?by=name&substr=openfortivpn) provide an `openfortivpn` package. Either [install Homebrew](https://brew.sh/) then install openfortivpn: ```shell # Install 'Homebrew' /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" # Install 'openfortivpn' brew install openfortivpn ``` or [install MacPorts](https://www.macports.org/install.php) then install openfortivpn: ```shell # Install 'openfortivpn' sudo port install openfortivpn ``` ### Building and installing from source For other distros, you'll need to build and install from source: 1. Install build dependencies. * RHEL/CentOS/Fedora: `gcc` `automake` `autoconf` `openssl-devel` `make` `pkg-config` * Debian/Ubuntu: `gcc` `automake` `autoconf` `libssl-dev` `make` `pkg-config` * Arch Linux: `gcc` `automake` `autoconf` `openssl` `pkg-config` * Gentoo Linux: `net-dialup/ppp` `pkg-config` * openSUSE: `gcc` `automake` `autoconf` `libopenssl-devel` `pkg-config` * macOS(Homebrew): `automake` `autoconf` `openssl@1.0` `pkg-config` * FreeBSD: `automake` `autoconf` `libressl` `pkgconf` 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 pkg-config # You may need to make this openssl available to compilers and pkg-config export LDFLAGS="-L/usr/local/opt/openssl/lib $LDFLAGS" export CPPFLAGS="-I/usr/local/opt/openssl/include $CPPFLAGS" export PKG_CONFIG_PATH="/usr/local/opt/openssl/lib/pkgconfig:$PKG_CONFIG_PATH" ``` 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. For fine-tuning check the available configure arguments with `./configure --help` especially when you are cross compiling. Finally, install runtime dependency `ppp` or `pppd`. ---------------- 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.12.0/autogen.sh000077500000000000000000000006011362551325400163300ustar00rootroot00000000000000#!/bin/sh set -exu if ! type autoconf >/dev/null 2>&1 ; then echo "autoconf not found - please install it" >&2 exit 1 fi if ! type automake >/dev/null 2>&1 ; then echo "automake not found - please install it" >&2 exit 1 fi if type aclocal >/dev/null 2>&1 ; then aclocal fi autoconf automake --add-missing echo "now you can run ./configure && make to build openfortivpn" openfortivpn-1.12.0/configure.ac000066400000000000000000000214531362551325400166250ustar00rootroot00000000000000# -*- Autoconf -*- # Process this file with autoconf to produce a configure script. AC_PREREQ([2.63]) AC_INIT([openfortivpn], [1.12.0]) AC_CONFIG_SRCDIR([src/main.c]) AM_INIT_AUTOMAKE([foreign subdir-objects]) # Checks for programs. AC_PROG_CC AC_GNU_SOURCE m4_ifndef([PKG_PROG_PKG_CONFIG], [m4_fatal([Please install pkg-config.])]) PKG_PROG_PKG_CONFIG # Helps support multiarch by setting 'host_os' and 'host_cpu' AC_CANONICAL_HOST m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])]) # Checks for libraries. PKG_CHECK_MODULES(OPENSSL, [libssl >= 0.9.8 libcrypto >= 0.9.8], [], [AC_MSG_ERROR([Cannot find OpenSSL 0.9.8 or higher.])]) AC_CHECK_LIB([pthread], [pthread_create], [], [AC_MSG_ERROR([Cannot find libpthread.])]) AC_CHECK_LIB([util], [forkpty], [], [AC_MSG_ERROR([Cannot find libutil.])]) PKG_CHECK_MODULES(LIBSYSTEMD, [libsystemd], [AC_DEFINE(HAVE_SYSTEMD)], [AC_MSG_RESULT([libsystemd not present])]) # we assume presence of the follwowing C standard headers # and ommit them in the follwoing header checks # # assert.h # ctype.h # errno.h # limits.h # signal.h # stdarg.h # stdint.h # stdio.h # stdlib.h # string.h # Checks for required header files. AC_CHECK_HEADERS([ \ arpa/inet.h \ fcntl.h \ getopt.h \ ifaddrs.h \ netdb.h \ net/if.h \ netinet/in.h \ netinet/tcp.h \ pthread.h \ sys/ioctl.h \ syslog.h \ sys/socket.h \ sys/stat.h \ sys/types.h \ sys/wait.h \ termios.h \ unistd.h \ ], [], AC_MSG_ERROR([Required header not found])) # Checks for header files with prerequisites of other headers. AC_CHECK_HEADERS([net/route.h], [], AC_MSG_ERROR([Required header not found]), [#include ]) # Checks for optional header files. AC_CHECK_HEADERS([ \ libutil.h \ mach/mach.h \ pty.h \ semaphore.h \ sys/mutex.h \ util.h \ ]) # Checks for optional header files with prerequisites of other headers. AC_CHECK_HEADERS([net/if_var.h],[],[],[#include ]) # 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 AC_CHECK_TYPES([struct termios], [], [], [#include ]) # Checks for library functions. AC_FUNC_MALLOC AC_FUNC_REALLOC AC_CHECK_FUNCS([ \ access \ atoi \ close \ connect \ execv \ exit \ _exit \ fclose \ fcntl \ fflush \ fileno \ fopen \ forkpty \ fprintf \ fputc \ fputs \ fread \ free \ freeaddrinfo \ freeifaddrs \ freopen \ fwrite \ gai_strerror \ getaddrinfo \ getchar \ getenv \ geteuid \ getifaddrs \ getopt_long \ htons \ index \ inet_addr \ inet_ntoa \ ioctl \ isatty \ isdigit \ isspace \ malloc \ memcmp \ memcpy \ memmem \ memmove \ memset \ ntohs \ open \ openlog \ optarg \ optind \ pclose \ popen \ printf \ pthread_cancel \ pthread_cond_init \ pthread_cond_signal \ pthread_cond_wait \ pthread_create \ pthread_join \ pthread_mutexattr_init \ pthread_mutex_destroy \ pthread_mutex_init \ pthread_mutex_lock \ pthread_mutex_unlock \ pthread_self \ pthread_sigmask \ putchar \ puts \ read \ realloc \ rewind \ select \ sem_destroy \ sem_init \ sem_post \ sem_wait \ setenv \ setsockopt \ sigaddset \ sigemptyset \ signal \ sleep \ snprintf \ socket \ sprintf \ sscanf \ strcasecmp \ strcasestr \ strcat \ strchr \ strcmp \ strcpy \ strdup \ strerror \ strlen \ strncasecmp \ strncat \ strncmp \ strncpy \ strsignal \ strstr \ strtok \ strtok_r \ strtol \ strtoul \ syslog \ system \ tcgetattr \ tcsetattr \ usleep \ vprintf \ vsnprintf \ vsyslog \ waitpid \ write \ ], [], AC_MSG_ERROR([Required function not found])) # Checks for optional functions. AC_CHECK_FUNCS([pthread_mutexattr_setrobust]) # Use PKG_CHECK_MODULES compiler/linker flags save_openssl_CPPFLAGS="${CPPFLAGS}" save_openssl_LIBS="${LIBS}" CPPFLAGS="${OPENSSL_CFLAGS} ${CPPFLAGS}" LIBS="${OPENSSL_LIBS} ${LIBS}" AC_CHECK_FUNCS([X509_check_host]) CPPFLAGS="${save_openssl_CPPFLAGS}" LIBS="${save_openssl_LIBS}" # Specialised checks for particular features. # When cross compile, don't run the tests. AC_ARG_WITH([rt_dst], AS_HELP_STRING([--with-rt_dst], [disable rtentry with rt_dst testing (for linux target when cross compile)]), AS_IF([test "x$with_rt_dst" = "xyes"],[ AC_MSG_NOTICE([HAVE_RT_ENTRY_WITH_RT_DST... 1]) AC_DEFINE(HAVE_RT_ENTRY_WITH_RT_DST) ]) ) AS_IF([test "x$with_rt_dst" = "x" ], [ AC_MSG_CHECKING(whether rtentry is available and has rt_dst) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([ #include #include #include static inline struct sockaddr_in *cast_addr(struct sockaddr *addr) { return (struct sockaddr_in *) addr; } ],[ struct rtentry route; cast_addr(&(&route)->rt_dst)->sin_family = AF_INET; ])],[ AC_DEFINE(HAVE_RT_ENTRY_WITH_RT_DST) AC_MSG_RESULT(yes) ], AC_MSG_RESULT(no) ) ]) NETSTAT_PATH="" PPP_PATH="" RESOLVCONF_PATH="" # prepare possibility to override default locations AC_ARG_WITH([netstat], AS_HELP_STRING([--with-netstat], [Set the path to the netstat executable on MacOSX or FreeBSD]), NETSTAT_PATH="$withval" ) # this is for the pppd daemon executable AC_ARG_WITH([pppd], AS_HELP_STRING([--with-pppd], [Set the path to the pppd daemon executable]), AS_IF([test ! "x$with_pppd" = "xno" -a ! "x$with_pppd" = "xyes"],[ PPP_PATH="$withval" with_pppd="yes" with_ppp="no" ]) ) # and this is for the ppp user space client on FreeBSD AC_ARG_WITH([ppp], AS_HELP_STRING([--with-ppp], [Set the path to the ppp userspace client on FreeBSD]), AS_IF([test ! "x$with_ppp" = "xno" -a ! "x$with_ppp" = "xyes"],[ PPP_PATH="$withval" with_ppp="yes" with_pppd="no" ]) ) # resolvconf if present AC_ARG_WITH([resolvconf], AS_HELP_STRING([--with-resolvconf], [Set the path to the resolvconf executable]), RESOLVCONF_PATH="$withval" ) # override for /proc/net/route detection AC_ARG_ENABLE([proc], AS_HELP_STRING([--enable-proc], [Enable route manipulations directly via /proc/net/route \ when cross-compiling, use --disable-proc for the opposite])) # Checks for existence of specific files if not cross-compiling. AS_IF([test "x$enable_proc" = "x" ], [ AC_CHECK_FILE([/proc/net/route],[ AS_IF([test "x$enable_proc" = "x" ], [ enable_proc="yes" ]) ],[ AS_IF([test "x$NETSTAT_PATH" = "x" ], [ AC_CHECK_FILE([/usr/sbin/netstat],[ NETSTAT_PATH="/usr/sbin/netstat" ],[ AC_CHECK_FILE([/usr/bin/netstat],[ NETSTAT_PATH="/usr/bin/netstat" ],[]) ]) ]) ]) ]) # check for ppp user space client if not specified AC_PATH_PROG(PPP, [ppp], [/usr/sbin/ppp], "$PATH:/sbin:/usr/sbin") AS_IF([test "x$PPP_PATH" = "x" ], [ AC_CHECK_FILE([$PPP], [ AS_IF([test "x$PPP_PATH" = "x" ], [ PPP_PATH="$PPP" ]) AS_IF([test "x$with_ppp" = "x" ], [ with_ppp="yes" ]) ],[]) ]) # check for pppd if not specified AC_PATH_PROG(PPPD, [pppd], [/usr/sbin/pppd], "$PATH:/sbin:/usr/sbin") AS_IF([test "x$PPP_PATH" = "x" ], [ AC_CHECK_FILE([$PPPD], [ AS_IF([test "x$PPP_PATH" = "x" ], [ PPP_PATH="$PPPD" ]) AS_IF([test "x$with_pppd" = "x" ], [ with_pppd="yes" ]) ],[]) ]) # replace empty settings with "no" AS_IF([test "x$with_ppp" = "x" ], [ with_ppp="no" ]) AS_IF([test "x$with_pppd" = "x" ], [ with_pppd="no" ]) # when neither ppp nor pppd are enabled fall back to a sensible choice for the platform AS_IF([test "x$with_ppp" = "xno" -a "x$with_pppd" = "xno" ], [ AS_IF([test "x$uname" = "xFreeBSD" ], [ PPP_PATH="/usr/sbin/ppp" with_ppp="yes" ], [ with_pppd="yes" PPP_PATH="/usr/sbin/pppd" ]) ]) # When both are enabled, give pppd the higher priority (we can only use one of them). # Note that PPP_PATH should already be correct since pppd is detected later # and PPP_PATH is overwritten during detection. AS_IF([test "x$with_ppp" = "xyes" -a "x$with_pppd" = "xyes"], [ with_ppp="no" ]) AC_PATH_PROG(RESOLVCONF_PATH, [resolvconf], [/sbin/resolvconf], "$PATH:/sbin:/usr/sbin") AS_IF([test "x$with_ppp" = "xyes"], [ AC_DEFINE(HAVE_USR_SBIN_PPP, 1) AC_MSG_NOTICE([HAVE_USR_SBIN_PPP... 1]) ],[ AC_DEFINE(HAVE_USR_SBIN_PPP, 0) AC_MSG_NOTICE([HAVE_USR_SBIN_PPP... 0]) ]) AS_IF([test "x$with_pppd" = "xyes"], [ AC_DEFINE(HAVE_USR_SBIN_PPPD, 1) AC_MSG_NOTICE([HAVE_USR_SBIN_PPPD... 1]) ],[ AC_DEFINE(HAVE_USR_SBIN_PPPD, 0) AC_MSG_NOTICE([HAVE_USR_SBIN_PPPD... 0]) ]) AS_IF([test "x$enable_proc" = "xyes"], [ AC_DEFINE(HAVE_PROC_NET_ROUTE, 1) AC_MSG_NOTICE([HAVE_PROC_NET_ROUTE... 1]) ],[ AC_DEFINE(HAVE_PROC_NET_ROUTE, 0) AC_MSG_NOTICE([HAVE_PROC_NET_ROUTE... 0]) ]) AC_SUBST(PPP_PATH) AC_MSG_NOTICE([PPP_PATH...] $PPP_PATH) AC_SUBST(NETSTAT_PATH) AS_IF([test "x$NETSTAT_PATH" != "x" ], [ AC_MSG_NOTICE([NETSTAT_PATH...] $NETSTAT_PATH) ]) AC_SUBST(RESOLVCONF_PATH) AS_IF([test "x$RESOLVCONF_PATH" != "x" ], [ AC_MSG_NOTICE([RESOLVCONF_PATH...] $RESOLVCONF_PATH) ]) AC_CONFIG_COMMANDS([timestamp], [touch src/.dirstamp]) AC_OUTPUT(Makefile) openfortivpn-1.12.0/doc/000077500000000000000000000000001362551325400150775ustar00rootroot00000000000000openfortivpn-1.12.0/doc/openfortivpn.1.in000066400000000000000000000242431362551325400203240ustar00rootroot00000000000000.TH OPENFORTIVPN 1 "December 11, 2019" "" .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\-\-otp=\fI\fR] [\fB\-\-otp\-prompt=\fI\fR] [\fB\-\-otp\-delay=\fI\fR] [\fB\-\-realm=\fI\fR] [\fB\-\-set\-routes=\fR] [\fB\-\-no\-routes\fR] [\fB\-\-set\-dns=\fR] [\fB\-\-no\-dns\fR] [\fB\-\-half\-internet\-routes=\fR] [\fB\-\-ca\-file=\fI\fR] [\fB\-\-user\-cert=\fI\fR] [\fB\-\-user-cert=\fIpkcs11:\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\-use\-peerdns=\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\-\-pppd\-call=\fI\fR] [\fB\-\-ppp\-system=\fI\fR] [\fB\-\-persistent=\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 the 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\-o \fI\fR, \fB\-\-otp=\fI\fR One-Time-Password. .TP \fB\-\-otp\-prompt=\fI\fR Search for the OTP password prompt starting with the string \fI\fR. .TP \fB\-\-otp\-delay\=\fI\fR Set the amount of time to wait before sending the One-Time-Password. The delay time must be specified in seconds, where 0 means no wait (this is the default). .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 openfortivpn 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 Set if openfortivpn should add two 0.0.0.0/1 and 128.0.0.0/1 routes with higher priority instead of replacing the default route. .TP \fB\-\-set\-dns=\fI\fR, \fB\-\-no\-dns\fR Set if openfortivpn should add DNS name servers in /etc/resolv.conf when tunnel is up. Also a dns\-suffix may be received from the peer and added to /etc/resolv.conf in the turn of adding the name servers. resolvconf is instructed to do the update of the resolv.conf file if it is installed, otherwise openfortivpn prepends its changes to the existing content of the resolv.conf file. Note that there may be other mechanisms to update /etc/resolv.conf, e.g., \fB\-\-pppd\-use\-peerdns\fR in conjunction with an ip-up-script, which may require that openfortivpn is called with \fB\-\-no\-dns\fR. \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-cert=\fIpkcs11:\fR Use at least the string pkcs11: for using a smartcard. It takes the full or a partial PKCS11-URI (p11tool --list-token-urls) --user-cert = pkcs11: --user-cert = pkcs11:token=someuser --user-cert = pkcs11:model=PKCS%2315%20emulated;manufacturer=piv_II;serial=012345678;token=someuser \fBThis feature requires OpenSSL PKCS engine! .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. The certificate has to be encoded in DER form. 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\-\-use\-peer\-dns=\fI\fR, \fB\-\-pppd\-no\-peerdns\fR Whether to ask peer ppp server for DNS server addresses and let pppd rewrite /etc/resolv.conf. There is no mechanism to tell the dns\-suffix to pppd. If the DNS server addresses are requested, also \fB\-\-set\-dns=\fI1\fR may race with the mechanisms in pppd. \fB\-\-pppd\-no\-peerdns\fR is the same as \fB\-\-pppd\-use\-peerdns=\fI0\fR. .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\-\-pppd\-call=\fI\fR Drop usual arguments from pppd command line and add `call ' instead. This can be useful on Debian and Ubuntu, where unprivileged users in group `dip' can invoke `pppd call ' to make pppd read and apply options from /etc/ppp/peers/ (including privileged ones). .TP \fB\-\-ppp\-system=\fI\fR Only available if compiled for ppp user space client (e.g. on FreeBSD). Connect to the specified system as defined in /etc/ppp/ppp.conf .TP \fB\-\-persistent\=\fI\fR Run the VPN persistently in an endless loop and try to reconnect forever. The reconnect interval may be specified in seconds, where 0 means no reconnect is done (this is the default). .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 an HTTP proxy 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 established 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 If not compiled for pppd the pppd options and features that rely on them are not available. On FreeBSD \fB\-\-ppp\-system\fR is available instead. .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 = 443 .br username = foo .br password = bar .br # realm = some-realm .br # useful for a gui that passes a config file to openfortivpn .br # otp = 123456 .br # otp\-delay = 0 .br # otp\-prompt = Please .br # pinentry = pinentry program .br user\-cert = @SYSCONFDIR@/openfortivpn/user\-cert.pem .br # user\-cert = pkcs1: # use smartcard as client certificate .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.crt: .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 = 0 .br set\-routes = 1 .br half\-internet\-routes = 0 .br pppd\-use\-peerdns = 1 .br # alternatively, 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 ppp interface name to pppd (if supported by a patched pppd) .br # pppd\-ifname = ppp1 .br # pass an ipparam string to pppd, e.g. the device name (a similar use case) .br # pppd\-ipparam = 'device=$DEVICE' .br # instruct pppd to call a script instead of passing arguments (if pppd supports it) .br # pppd\-call = script .br # use\-syslog = 0 .br insecure\-ssl = 0 .br cipher\-list = HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4 .br persistent = 0 .br seclevel-1 = 0 openfortivpn-1.12.0/etc/000077500000000000000000000000001362551325400151055ustar00rootroot00000000000000openfortivpn-1.12.0/etc/openfortivpn/000077500000000000000000000000001362551325400176365ustar00rootroot00000000000000openfortivpn-1.12.0/etc/openfortivpn/config.template000066400000000000000000000002131362551325400226340ustar00rootroot00000000000000### config file for openfortivpn, see man openfortivpn(1) ### host = vpn.example.org port = 443 username = vpnuser password = VPNpassw0rd openfortivpn-1.12.0/etc/ppp/000077500000000000000000000000001362551325400157045ustar00rootroot00000000000000openfortivpn-1.12.0/etc/ppp/ip-down.local.example000077500000000000000000000003561362551325400217360ustar00rootroot00000000000000#!/bin/bash case "$PPP_IPPARAM" in openfortivpn*) rconf=/etc/resolv.conf [[ -f $rconf.openfortivpn ]] && cp -pv $rconf.openfortivpn $rconf exit 0 ;; esac 2>&1 | logger -p daemon.debug -i -t "$0" true openfortivpn-1.12.0/etc/ppp/ip-up.local.example000077500000000000000000000011421362551325400214050ustar00rootroot00000000000000#!/bin/bash case "$PPP_IPPARAM" in openfortivpn*) rconf=/etc/resolv.conf routes=$(echo $PPP_IPPARAM | tr , ' ') for r in $routes; do [[ $r = "openfortivpn" ]] && continue com="ip route add ${r%/*} via ${r##*/}" echo $com $com done cp -pv $rconf $rconf.openfortivpn if [[ "$DNS1" ]]; then echo nameserver $DNS1 > $rconf [[ "$DNS2" ]] && [[ "$DNS1" != "$DNS2" ]] && echo nameserver $DNS2 >> $rconf fi exit 0 ;; esac 2>&1 | logger -p daemon.debug -i -t "$0" true openfortivpn-1.12.0/etc/ppp/peers/000077500000000000000000000000001362551325400170225ustar00rootroot00000000000000openfortivpn-1.12.0/etc/ppp/peers/openfortivpn000066400000000000000000000002101362551325400214670ustar00rootroot0000000000000038400 :192.0.2.1 noipdefault noaccomp noauth default-asyncmap nopcomp receive-all nodefaultroute nodetach lcp-max-configure 40 mru 1354 openfortivpn-1.12.0/etc/ppp/ppp.conf.example000066400000000000000000000004361362551325400210070ustar00rootroot00000000000000# Example configuration for a ppp client # for more examples see # https://github.com/freebsd/freebsd-base-graphics/blob/master/share/examples/ppp/ppp.conf.sample vpn-client: set dial set speed 38400 set mru 1354 set login set timeout 0 disable deflate pred1 deny deflate pred1 openfortivpn-1.12.0/src/000077500000000000000000000000001362551325400151215ustar00rootroot00000000000000openfortivpn-1.12.0/src/config.c000066400000000000000000000324601362551325400165370ustar00rootroot00000000000000/* * 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 #include #include /* work around OpenSSL bug: missing definition of STACK_OF */ #include const struct vpn_config invalid_cfg = { .gateway_host = {'\0'}, .gateway_port = 0, .username = {'\0'}, .password = NULL, .otp = {'\0'}, .otp_prompt = NULL, .otp_delay = -1, .pinentry = NULL, .realm = {'\0'}, .set_routes = -1, .set_dns = -1, .pppd_use_peerdns = -1, .use_syslog = -1, .half_internet_routes = -1, .persistent = -1, #if HAVE_USR_SBIN_PPPD .pppd_log = NULL, .pppd_plugin = NULL, .pppd_ipparam = NULL, .pppd_ifname = NULL, .pppd_call = NULL, #endif #if HAVE_USR_SBIN_PPP .ppp_system = NULL, #endif .ca_file = NULL, .user_cert = NULL, .user_key = NULL, .insecure_ssl = -1, .cipher_list = NULL, .min_tls = -1, .seclevel_1 = -1, .cert_whitelist = NULL, .use_engine = -1 }; /* * 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 i = strtol(str, NULL, 0); if (i < 0 || i > 1) return -1; return i; } /* * Converts string to TLS version * * @params[in] str the string to read from * @return OpenSSL version or -1 */ int parse_min_tls(const char *str) { if (str[0] != '1' || str[1] != '.' || str[2] == 0 || str[3] != 0) return -1; switch (str[2]) { #if OPENSSL_VERSION_NUMBER >= 0x10100000L case '0': return TLS1_VERSION; case '1': return TLS1_1_VERSION; case '2': return TLS1_2_VERSION; #ifdef TLS1_3_VERSION /* * libressl uses version numbers starting with major version 2 * but does not yet support TLS 1.3 */ case '3': return TLS1_3_VERSION; #endif #endif default: return -1; } } /* * 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 (isspace(key[0])) key++; while (isspace(val[0])) val++; // Remove trailing spaces for (i = strlen(key) - 1; i > 0; i--) { if (isspace(key[i])) key[i] = '\0'; else break; } for (i = strlen(val) - 1; i > 0; i--) { if (isspace(val[i])) 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) { unsigned long port = strtoul(val, NULL, 0); if (port == 0 || port > 65535) { log_warn("Bad port in config file: \"%lu\".\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) { cfg->password = strdup(val); } else if (strcmp(key, "otp") == 0) { strncpy(cfg->otp, val, FIELD_SIZE - 1); cfg->otp[FIELD_SIZE] = '\0'; } else if (strcmp(key, "otp-prompt") == 0) { free(cfg->otp_prompt); cfg->otp_prompt = strdup(val); } else if (strcmp(key, "otp-delay") == 0) { long otp_delay = strtol(val, NULL, 0); if (otp_delay < 0 || otp_delay > UINT_MAX) { log_warn("Bad value for otp-delay in config file: \"%s\".\n", val); continue; } cfg->otp_delay = otp_delay; } else if (strcmp(key, "pinentry") == 0) { free(cfg->pinentry); cfg->pinentry = strdup(val); } 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, "persistent") == 0) { unsigned long persistent = strtoul(val, NULL, 0); if (persistent > UINT_MAX) { log_warn("Bad value for persistent in config file: \"%s\".\n", val); continue; } cfg->persistent = persistent; #if HAVE_USR_SBIN_PPPD } 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) { free(cfg->pppd_log); cfg->pppd_log = strdup(val); } else if (strcmp(key, "pppd-plugin") == 0) { free(cfg->pppd_plugin); cfg->pppd_plugin = strdup(val); } else if (strcmp(key, "pppd-ipparam") == 0) { free(cfg->pppd_ipparam); cfg->pppd_ipparam = strdup(val); } else if (strcmp(key, "pppd-ifname") == 0) { free(cfg->pppd_ifname); cfg->pppd_ifname = strdup(val); } else if (strcmp(key, "pppd-call") == 0) { free(cfg->pppd_call); cfg->pppd_call = strdup(val); #else } else if (strcmp(key, "pppd") == 0) { log_warn("Ignoring pppd option \"%s\".\n", key); #endif } else if (strcmp(key, "ppp-system") == 0) { #if HAVE_USR_SBIN_PPP cfg->ppp_system = strdup(val); #else log_warn("Ignoring option \"%s\".\n", key); #endif } 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) { free(cfg->ca_file); cfg->ca_file = strdup(val); } else if (strcmp(key, "user-cert") == 0) { free(cfg->user_cert); cfg->user_cert = strdup(val); if (strncmp(cfg->user_cert, "pkcs11:", 7) == 0) cfg->use_engine = 1; } else if (strcmp(key, "user-key") == 0) { free(cfg->user_key); 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) { free(cfg->cipher_list); cfg->cipher_list = strdup(val); #if OPENSSL_VERSION_NUMBER >= 0x10100000L } else if (strcmp(key, "min-tls") == 0) { int min_tls = parse_min_tls(val); if (min_tls == -1) { log_warn("Bad min-tls in config file: \"%s\".\n", val); continue; } else { cfg->min_tls = min_tls; } #endif } else if (strcmp(key, "seclevel-1") == 0) { int seclevel_1 = strtob(val); if (seclevel_1 < 0) { log_warn("Bad seclevel-1 in config file: \"%s\".\n", val); continue; } cfg->seclevel_1 = seclevel_1; } 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; } void destroy_vpn_config(struct vpn_config *cfg) { free(cfg->password); free(cfg->otp_prompt); free(cfg->pinentry); #if HAVE_USR_SBIN_PPPD free(cfg->pppd_log); free(cfg->pppd_plugin); free(cfg->pppd_ipparam); free(cfg->pppd_ifname); free(cfg->pppd_call); #endif #if HAVE_USR_SBIN_PPP free(cfg->ppp_system); #endif free(cfg->ca_file); free(cfg->user_cert); free(cfg->user_key); free(cfg->cipher_list); while (cfg->cert_whitelist != NULL) { struct x509_digest *tmp = cfg->cert_whitelist->next; free(cfg->cert_whitelist); cfg->cert_whitelist = tmp; } } void merge_config(struct vpn_config *dst, struct vpn_config *src) { if (src->gateway_host[0]) strcpy(dst->gateway_host, src->gateway_host); if (src->gateway_port != invalid_cfg.gateway_port) dst->gateway_port = src->gateway_port; if (src->username[0]) strcpy(dst->username, src->username); if (src->password != NULL && src->password[0]) dst->password = strdup(src->password); if (src->otp[0]) strcpy(dst->otp, src->otp); if (src->otp_delay != invalid_cfg.otp_delay) dst->otp_delay = src->otp_delay; if (src->pinentry) { free(dst->pinentry); dst->pinentry = src->pinentry; } if (src->realm[0]) strcpy(dst->realm, src->realm); if (src->set_routes != invalid_cfg.set_routes) dst->set_routes = src->set_routes; if (src->set_dns != invalid_cfg.set_dns) dst->set_dns = src->set_dns; if (src->pppd_use_peerdns != invalid_cfg.pppd_use_peerdns) dst->pppd_use_peerdns = src->pppd_use_peerdns; if (src->use_syslog != invalid_cfg.use_syslog) dst->use_syslog = src->use_syslog; if (src->half_internet_routes != invalid_cfg.half_internet_routes) dst->half_internet_routes = src->half_internet_routes; if (src->persistent != invalid_cfg.persistent) dst->persistent = src->persistent; #if HAVE_USR_SBIN_PPPD if (src->pppd_log) { free(dst->pppd_log); dst->pppd_log = src->pppd_log; } if (src->pppd_plugin) { free(dst->pppd_plugin); dst->pppd_plugin = src->pppd_plugin; } if (src->pppd_ipparam) { free(dst->pppd_ipparam); dst->pppd_ipparam = src->pppd_ipparam; } if (src->pppd_ifname) { free(dst->pppd_ifname); dst->pppd_ifname = src->pppd_ifname; } if (src->pppd_call) { free(dst->pppd_call); dst->pppd_call = src->pppd_call; } #endif #if HAVE_USR_SBIN_PPP if (src->ppp_system) { free(dst->ppp_system); dst->ppp_system = src->ppp_system; } #endif if (src->ca_file) { free(dst->ca_file); dst->ca_file = src->ca_file; } if (src->user_cert) { free(dst->user_cert); if (strncmp(src->user_cert, "pkcs11:", 7) == 0) dst->use_engine = 1; dst->user_cert = src->user_cert; } if (src->user_key) { free(dst->user_key); dst->user_key = src->user_key; } if (src->insecure_ssl != invalid_cfg.insecure_ssl) dst->insecure_ssl = src->insecure_ssl; if (src->cipher_list) { free(dst->cipher_list); dst->cipher_list = src->cipher_list; } if (src->min_tls > 0) dst->min_tls = src->min_tls; if (src->seclevel_1 != invalid_cfg.seclevel_1) dst->seclevel_1 = src->seclevel_1; if (src->cert_whitelist) { while (dst->cert_whitelist != NULL) { struct x509_digest *tmp = dst->cert_whitelist->next; free(dst->cert_whitelist); dst->cert_whitelist = tmp; } dst->cert_whitelist = src->cert_whitelist; } } openfortivpn-1.12.0/src/config.h000066400000000000000000000055501362551325400165440ustar00rootroot00000000000000/* * 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"; } #if HAVE_USR_SBIN_PPPD #define PPP_DAEMON "pppd" #else #define PPP_DAEMON "ppp" #endif #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; char otp[FIELD_SIZE + 1]; char *otp_prompt; unsigned int otp_delay; char *pinentry; char realm[FIELD_SIZE + 1]; int set_routes; int set_dns; int pppd_use_peerdns; int use_syslog; int half_internet_routes; unsigned int persistent; #if HAVE_USR_SBIN_PPPD char *pppd_log; char *pppd_plugin; char *pppd_ipparam; char *pppd_ifname; char *pppd_call; #endif #if HAVE_USR_SBIN_PPP char *ppp_system; #endif char *ca_file; char *user_cert; char *user_key; int insecure_ssl; int min_tls; int seclevel_1; char *cipher_list; struct x509_digest *cert_whitelist; int use_engine; }; int add_trusted_cert(struct vpn_config *cfg, const char *digest); int strtob(const char *str); int parse_min_tls(const char *str); int load_config(struct vpn_config *cfg, const char *filename); void destroy_vpn_config(struct vpn_config *cfg); /* * merge source config into dest * * memory allocated dynamically is transferred with this function * e.g. ownership goes to dest config */ void merge_config(struct vpn_config *dest, struct vpn_config *source); extern const struct vpn_config invalid_cfg; #endif openfortivpn-1.12.0/src/hdlc.c000066400000000000000000000172271362551325400162100ustar00rootroot00000000000000/* * 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.12.0/src/hdlc.h000066400000000000000000000030601362551325400162030ustar00rootroot00000000000000/* * 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.12.0/src/http.c000066400000000000000000000512161362551325400162510ustar00rootroot00000000000000/* * 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 #include #include #include #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 { static const char hex[] = "0123456789ABCDEF"; *dest++ = '%'; *dest++ = hex[(unsigned char)*str >> 4]; *dest++ = hex[(unsigned char)*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]; char logbuffer[BUFSZ]; int length; int n = 0; va_start(args, request); length = vsnprintf(buffer, BUFSZ, request, args); va_end(args); strcpy(logbuffer, buffer); if (loglevel <= OFV_LOG_DEBUG_DETAILS && tunnel->config->password[0] != '\0') { char *pwstart; char password[3 * FIELD_SIZE + 1]; url_encode(password, tunnel->config->password); pwstart = strstr(logbuffer, password); if (pwstart != NULL) { int pos, pwlen, i; pos = pwstart - logbuffer; pwlen = strlen(tunnel->config->password); for (i = pos; i < pos + pwlen; i++) logbuffer[i] = '*'; } } if (length < 0) return ERR_HTTP_INVALID; else if (length >= BUFSZ) return ERR_HTTP_TOO_LONG; log_debug_details("%s:\n%s\n", __func__, logbuffer); 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, uint32_t response_size ) { const char *line = res; while (memcmp(line, "\r\n", 2)) { int line_len = (char *) memmem( line, response_size - (line - res), "\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, uint32_t *response_size ) { uint32_t res_size = BUFSZ; char *buffer, *res; int n = 0; int bytes_read = 0; int header_size = 0; int content_size = 0; int chunked = 0; buffer = malloc(res_size); 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) { log_debug_details("%s:\n%s\n", __func__, buffer); 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: ", BUFSZ); header_size = eoh - buffer + 4; if (header) content_size = atoi(header); if (find_header(buffer, "Transfer-Encoding: chunked", BUFSZ)) chunked = 1; } } if (header_size) { /* We saw the whole header, is the body 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_size = bytes_read + 1; res = realloc(buffer, res_size); if (res == NULL) { free(buffer); return ERR_HTTP_NO_MEM; } res[bytes_read] = '\0'; *response = res; if (response_size != NULL) *response_size = res_size; return 1; } static int do_http_request(struct tunnel *tunnel, const char *method, const char *uri, const char *data, char **response, uint32_t *response_size ) { int ret; const 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: identity\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->cookie, strlen(data), data); if (ret != 1) return ret; return http_receive(tunnel, response, response_size); } /* * 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, uint32_t *response_size ) { int ret = do_http_request(tunnel, method, uri, data, response, response_size); if (ret == ERR_HTTP_SSL) { ssl_connect(tunnel); ret = do_http_request(tunnel, method, uri, data, response, response_size); } 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 = -1; char *tokens; size_t keylen = strlen(key); tokens = strdup(buf); if (tokens == NULL) { ret = -3; goto end; } for (const char *kv_pair = strtok(tokens, "&,\r\n"); kv_pair != NULL; kv_pair = strtok(NULL, "&,\r\n")) { if (strncmp(key, kv_pair, keylen) == 0) { const char *val = &kv_pair[keylen]; if (strlen(val) > retbuflen - 1) { // value too long ret = -2; } else { strcpy(retbuf, val); ret = 1; } break; } } free(tokens); end: return ret; } static int get_auth_cookie( struct tunnel *tunnel, char *buf, uint32_t buffer_size ) { int ret = 0; const char *line; ret = ERR_HTTP_NO_COOKIE; line = find_header(buf, "Set-Cookie: ", buffer_size); 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->cookie, line, COOKIE_SIZE); tunnel->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 void delay_otp(struct tunnel *tunnel) { if (tunnel->config->otp_delay > 0) { log_info("Delaying OTP by %d seconds...\n", tunnel->config->otp_delay); sleep(tunnel->config->otp_delay); } } static int try_otp_auth( struct tunnel *tunnel, const char *buffer, char **res, uint32_t *response_size ) { 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, assume it starts with 'Please' * Fall back to default prompt if not found/parseable */ p = strstr(s, "Please"); if (tunnel->config->otp_prompt != NULL) p = strstr(s, tunnel->config->otp_prompt); 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(cfg->pinentry, "otp", 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); /* realm workaround */ if (cfg->realm[0] != '\0') { l = strlen(cfg->realm); if (!SPACE_AVAILABLE(3 * l + 8)) return -1; strcat(d, "&realm="); d += strlen(d); url_encode(d, cfg->realm); 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, response_size); #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[1024], token[128], tokenresponse[256]; char *res = NULL; uint32_t response_size; url_encode(username, tunnel->config->username); url_encode(realm, tunnel->config->realm); tunnel->cookie[0] = '\0'; if (tunnel->config->use_engine || (username[0] == '\0' && tunnel->config->password[0] == '\0')) { snprintf(data, sizeof(data), "cert=&nup=1"); ret = http_request(tunnel, "GET", "/remote/login", data, &res, &response_size); } else { if (tunnel->config->password[0] == '\0') { snprintf(data, sizeof(data), "username=%s&realm=%s&ajax=1&redir=%%2Fremote%%2Findex&just_logged_in=1", username, realm); } else { url_encode(password, tunnel->config->password); snprintf(data, sizeof(data), "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, &response_size); } if (ret != 1) goto end; /* Probably one-time password required */ if (strncmp(res, "HTTP/1.1 401 Authorization Required\r\n", 37) == 0) { delay_otp(tunnel); ret = try_otp_auth(tunnel, res, &res, &response_size); if (ret != 1) goto end; } if (strncmp(res, "HTTP/1.1 200 OK\r\n", 17)) { char word[17]; if (sscanf(res, "%16s %d", word, &ret) < 2) ret = ERR_HTTP_BAD_RES_CODE; goto end; } ret = get_auth_cookie(tunnel, res, response_size); if (ret == ERR_HTTP_NO_COOKIE) { struct vpn_config *cfg = tunnel->config; /* * 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); if (cfg->otp[0] == '\0') { read_password(cfg->pinentry, "otp", "Two-factor authentication token: ", cfg->otp, FIELD_SIZE); if (cfg->otp[0] == '\0') { log_error("No token specified\n"); return 0; } } url_encode(tokenresponse, cfg->otp); snprintf(data, sizeof(data), "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); delay_otp(tunnel); ret = http_request( tunnel, "POST", "/remote/logincheck", data, &res, &response_size); if (ret != 1) goto end; if (strncmp(res, "HTTP/1.1 200 OK\r\n", 17)) { char word[17]; if (sscanf(res, "%16s %d", word, &ret) < 2) ret = ERR_HTTP_BAD_RES_CODE; goto end; } ret = get_auth_cookie(tunnel, res, response_size); } end: free(res); return ret; } int auth_log_out(struct tunnel *tunnel) { return http_request(tunnel, "GET", "/remote/logout", "", NULL, NULL); } int auth_request_vpn_allocation(struct tunnel *tunnel) { int ret = http_request(tunnel, "GET", "/remote/index", "", NULL, NULL); if (ret != 1) return ret; return http_request(tunnel, "GET", "/remote/fortisslvpn", "", NULL, NULL); } static int parse_xml_config(struct tunnel *tunnel, const char *buffer) { const char *val; char *gateway; char *dns_server; int ret = 0; if (strncmp(buffer, "HTTP/1.1 200 OK\r\n", 17)) { char word[17]; if (sscanf(buffer, "%16s %d", word, &ret) < 2) ret = ERR_HTTP_BAD_RES_CODE; return ret; } // 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"); // The dns search string val = buffer; while ((val = xml_find('<', "dns", val, 2))) { if (xml_find(' ', "domain=", val, 1)) { tunnel->ipv4.dns_suffix = xml_get(xml_find(' ', "domain=", val, 1)); log_debug("found dns suffix %s in xml config\n", tunnel->ipv4.dns_suffix); break; } } // The dns servers val = buffer; while ((val = xml_find('<', "dns", val, 2))) { if (xml_find(' ', "ip=", val, 1)) { dns_server = xml_get(xml_find(' ', "ip=", val, 1)); log_debug("found dns server %s in xml config\n", dns_server); if (!tunnel->ipv4.ns1_addr.s_addr) tunnel->ipv4.ns1_addr.s_addr = inet_addr(dns_server); else if (!tunnel->ipv4.ns2_addr.s_addr) tunnel->ipv4.ns2_addr.s_addr = inet_addr(dns_server); free(dns_server); } } // 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) { const 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, NULL); if (ret == 1) { ret = parse_xml_config(tunnel, buffer); free(buffer); } if (ret == 1) return ret; ret = http_request(tunnel, "GET", "/remote/fortisslvpn", "", &buffer, NULL); if (ret == 1) { ret = parse_config(tunnel, buffer); free(buffer); } return ret; } openfortivpn-1.12.0/src/http.h000066400000000000000000000035551362551325400162610ustar00rootroot00000000000000/* * 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 > 0) return "HTTP status code"; else 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, uint32_t *response_size); 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.12.0/src/io.c000066400000000000000000000436101362551325400157000ustar00rootroot00000000000000/* * 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 #include #include #if HAVE_MACH_MACH_H /* this is typical for mach kernel used on Mac OS X */ #include /* Mac OS X defines sem_init but actually does not implement them */ 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, const 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 // global variable to pass signal out of its handler volatile sig_atomic_t sig_received = 0; int get_sig_received(void) { return (int)sig_received; } /* * 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("%s thread\n", __func__); // 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 %ld\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_error("malloc: %s\n", strerror(errno)); 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("%s ---> gateway (%lu bytes)\n", PPP_DAEMON, packet->len); #if HAVE_USR_SBIN_PPPD log_packet("pppd: ", packet->len, pkt_data(packet)); #else log_packet("ppp: ", packet->len, pkt_data(packet)); #endif 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("%s thread\n", __func__); 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_error("malloc: %s\n", strerror(errno)); 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); // retry on repeatable failure if ((n == -1) && (errno != EAGAIN)) { 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) || \ ((packet)->len >= 12 \ && pkt_data(packet)[0] == 0x80 \ && pkt_data(packet)[1] == 0x21 \ && pkt_data(packet)[2] == 0x02)) 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 && tunnel->config->pppd_use_peerdns) { memcpy(&tunnel->ipv4.ns1_addr.s_addr, &pkt_data(packet)[14], sizeof(uint32_t)); } if (packet->len >= 24 && pkt_data(packet)[18] == 0x83 && tunnel->config->pppd_use_peerdns) { 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", (const 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("%s thread\n", __func__); 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 != 6 + size || size == 0 || size >= 0xffff) { 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: %s\n", strerror(errno)); 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 ---> %s (%lu bytes)\n", PPP_DAEMON, 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); } if (packet_is_end_negociation(packet)) { log_info("negotiation complete\n"); 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("%s thread\n", __func__); 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("%s thread\n", __func__); // 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("%s: not ready yet...\n", __func__); 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) { sig_received = 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, (const 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 #if !HAVE_MACH_MACH_H // 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; #if !HAVE_MACH_MACH_H // 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.12.0/src/io.h000066400000000000000000000033641362551325400157070ustar00rootroot00000000000000/* * 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); int get_sig_received(void); #endif openfortivpn-1.12.0/src/ipv4.c000066400000000000000000001116171362551325400161560ustar00rootroot00000000000000/* * 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 "xml.h" #include #include #include #include #include #include #include #include #include #include #include #define IPV4_GET_ROUTE_BUFFER_CHUNK_SIZE 65536 #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) != NULL) { strcat(show_route_buffer, " dev "); strncat(show_route_buffer, route_iface(route), SHOW_ROUTE_BUFFER_SIZE - strlen(show_route_buffer) - 1); } return show_route_buffer; } static inline int route_init(struct rtentry *route) { memset(route, 0, sizeof(*route)); 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) { 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 searches for a match in the routing table and returns * that one. Note that dest and mask contain the network address and * the mask of the corresponding routing table entry after calling. * After calling ipv4_get_route it might be necessary to set dest * and mask again to the desired values for further processing. */ static int ipv4_get_route(struct rtentry *route) { size_t buffer_size = IPV4_GET_ROUTE_BUFFER_CHUNK_SIZE; char *buffer = malloc(buffer_size); char *realloc_buffer; int err = 0; char *start, *line; char *saveptr1 = NULL, *saveptr2 = NULL; uint32_t rtdest, rtmask, rtgtw; int rtfound = 0; /* * initialize the buffer with zeroes, aiming to address the * coverity issue "TAINTED_SCALAR passed to a tainted sink" * * Later on, the routing table is read into this buffer using * read() and therefore the content of the buffer is considered * tainted. strtok_r internally uses it in a loop boundary. * The theoretical problem is that the loop could iterate forever, * if the buffer contains a huge string which doesn't contain * the token character, which we are parsing for. * * We can declare this as a false positive, because * - the routing table is to some extent trusted input, * - it's not that large, * - and the loop in strtok_r increments the pointer in each * interation until it reaches the area where we have ensured * that there is a delimiting '\0' character by proper * initialization. We ensure this also when growing the buffer. */ memset(buffer, '\0', IPV4_GET_ROUTE_BUFFER_CHUNK_SIZE); log_debug("ip route show %s\n", ipv4_show_route(route)); // store what we are looking for rtdest = route_dest(route).s_addr; rtmask = route_mask(route).s_addr; rtgtw = route_gtw(route).s_addr; // initialize the output record route_dest(route).s_addr = inet_addr("0.0.0.0"); route_mask(route).s_addr = inet_addr("0.0.0.0"); route_gtw(route).s_addr = inet_addr("0.0.0.0"); #if HAVE_PROC_NET_ROUTE /* this is not present on Mac OS X and FreeBSD */ int fd; uint32_t total_bytes_read = 0; // Cannot stat, mmap not lseek this special /proc file fd = open("/proc/net/route", O_RDONLY); if (fd == -1) { err = ERR_IPV4_SEE_ERRNO; goto end; } int bytes_read; while ((bytes_read = read(fd, buffer + total_bytes_read, buffer_size - total_bytes_read - 1)) > 0) { total_bytes_read += bytes_read; if ((buffer_size - total_bytes_read) < 1) { buffer_size += IPV4_GET_ROUTE_BUFFER_CHUNK_SIZE; realloc_buffer = realloc(buffer, buffer_size); if (realloc_buffer) { buffer = realloc_buffer; } else { err = ERR_IPV4_SEE_ERRNO; goto cleanup; } buffer[buffer_size-1] = '\0'; } } cleanup: close(fd); if (err) goto end; if (bytes_read < 0) { err = ERR_IPV4_SEE_ERRNO; goto end; } #else FILE * fp; uint32_t total_bytes_read = 0; char *saveptr3 = NULL; int have_ref = 0; int have_use = 0; static const char netstat_path[] = NETSTAT_PATH; if (access(netstat_path, F_OK) != 0) { log_error("%s: %s.\n", netstat_path, strerror(errno)); return 1; } log_debug("netstat_path: %s\n", netstat_path); // Open the command for reading fp = popen(NETSTAT_PATH" -f inet -rn", "r"); if (fp == NULL) { err = ERR_IPV4_SEE_ERRNO; goto end; } line = buffer; // Read the output a line at a time while (fgets(line, buffer_size - total_bytes_read - 1, fp) != NULL) { uint32_t bytes_read = strlen(line); total_bytes_read += bytes_read; if (bytes_read > 0 && line[bytes_read - 1] != '\n') { buffer_size += IPV4_GET_ROUTE_BUFFER_CHUNK_SIZE; realloc_buffer = realloc(buffer, buffer_size); if (realloc_buffer) { buffer = realloc_buffer; } else { err = ERR_IPV4_SEE_ERRNO; goto cleanup; } } line = buffer + total_bytes_read; } cleanup: pclose(fp); if (err) goto end; // 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] = { 0 }; /* * Fill the flag_table now. Unfortunately it is not easy * to do this in a more elegant way. The problem here * is that these are already preprocessor macros and * we can't use them as arguments for another macro which * would include the #ifdef statements. * * Also, not all flags might be allowed in the context * of ipv4, and the code depends on which ones are * actually implemented on the target platform, which * might also be varying between Mac OS X versions. * */ #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 (total_bytes_read == 0) { log_debug("routing table is empty.\n"); err = ERR_IPV4_PROC_NET_ROUTE; goto end; } buffer[total_bytes_read] = '\0'; // Skip first line start = index(buffer, '\n'); if (start == NULL) { log_debug("routing table is malformed.\n"); err = ERR_IPV4_PROC_NET_ROUTE; goto end; } start++; #if !HAVE_PROC_NET_ROUTE if (strstr(buffer, "Ref") != NULL) have_ref = 1; if (strstr(buffer, "Use") != NULL) have_use = 1; // Skip 3 more lines from netstat output on Mac OS X and on FreeBSD start = index(start, '\n'); start = index(++start, '\n'); start = index(++start, '\n'); if (start == NULL) { log_debug("routing table is malformed.\n"); err = ERR_IPV4_PROC_NET_ROUTE; goto end; } #endif if (index(start, '\n') == NULL) { log_debug("routing table is malformed.\n"); err = ERR_IPV4_PROC_NET_ROUTE; goto end; } // Look for the route line = strtok_r(start, "\n", &saveptr1); while (line != NULL) { char *iface; uint32_t dest, mask, gtw; unsigned short flags; #if HAVE_PROC_NET_ROUTE unsigned short irtt; short metric; unsigned long mtu, window; iface = strtok_r(line, "\t", &saveptr2); dest = strtoul(strtok_r(NULL, "\t", &saveptr2), NULL, 16); gtw = strtoul(strtok_r(NULL, "\t", &saveptr2), NULL, 16); flags = strtoul(strtok_r(NULL, "\t", &saveptr2), NULL, 16); strtok_r(NULL, "\t", &saveptr2); // "RefCnt" strtok_r(NULL, "\t", &saveptr2); // "Use" metric = strtoul(strtok_r(NULL, "\t", &saveptr2), NULL, 16); mask = strtoul(strtok_r(NULL, "\t", &saveptr2), NULL, 16); mtu = strtoul(strtok_r(NULL, "\t", &saveptr2), NULL, 16); window = strtoul(strtok_r(NULL, "\t", &saveptr2), NULL, 16); irtt = strtoul(strtok_r(NULL, "\t", &saveptr2), NULL, 16); #else /* parse netstat output on Mac OS X and BSD */ char tmp_ip_string[16]; struct in_addr dstaddr; int pos; char *tmpstr; log_debug_details("\n"); log_debug_details("line: %s\n", line); saveptr3 = NULL; dest = UINT32_MAX; mask = UINT32_MAX; // "Destination" tmpstr = strtok_r(line, " ", &saveptr2); if (strncmp(tmpstr, "Internet6", 9) == 0) { // we have arrived at the end of ipv4 output goto end; } log_debug_details("- 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 = strtoul(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)); } // convert mask to reversed byte order mask = ((mask & 0xff000000) >> 24) | ((mask & 0xff0000) >> 8) | ((mask & 0xff00) << 8) | ((mask & 0xff) << 24); } log_debug_details("- Destination IP Hex: %x\n", dest); log_debug_details("- Destination Mask Hex: %x\n", mask); // "Gateway" gtw = 0; if (inet_aton(strtok_r(NULL, " ", &saveptr2), &dstaddr)) { gtw = dstaddr.s_addr; log_debug_details("- 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]]; if (have_ref) strtok_r(NULL, " ", &saveptr2); // "Ref" if (have_use) strtok_r(NULL, " ", &saveptr2); // "Use" iface = strtok_r(NULL, " ", &saveptr2); // "Netif" log_debug_details("- Interface: %s\n", iface); #endif /* * Now that we have parsed a routing entry, check if it * matches the current argument to the function call. * In rtentry we have integer representation, i.e. * the most significant byte corresponds to the last * number of dotted-number representation and vice versa. * In this representation ( address & mask ) is the network * address. * The routing algorithm does the following: * First, check if the network address we are looking for * falls into the network for the current route. * Therefore, calculate the network address for both, the * current route and for the destination we are searching. * If the destination is a smaller network (for instance a * single host), we have to mask again with the netmask of * the routing entry that we are checking in order to obtain * the network address in the context of the current route. * If both network addresses match, we have found a candidate * for a route. * However, there might be another route for a smaller network, * therefore repeat this and only store the resulting route * when the mask is at least as large as the one we may * have already found in a previous iteration (a larger * netmask corresponds to a smaller network in this * representation, and has a higher priority by default). * Also, only consider routing entries for which the * netmask is not larger than the netmask used in the * argument when calling the function - so that we can * distinguish between different routing entries for subnets * of different size but with the same network address. * For routing entries with the same destination and * the same netmask the metric can be used for adjusting * the priority (this is not supported on mac). * If the metric is larger than one found for this network * size, skip the current route (smaller numbers denote * less hops and therefore have a higher priority). */ if (((dest & mask) == (rtdest & rtmask & mask)) && (mask >= route_mask(route).s_addr) && (mask <= rtmask) && ((route_iface(route) == NULL) || (strcmp(iface, route_iface(route)) == 0) || (strlen(route_iface(route)) > 0 && route_iface(route)[0] == '!' && strcmp(iface, &route_iface(route)[1]) != 0) )) { #if HAVE_PROC_NET_ROUTE if (((mask == route_mask(route).s_addr) && (metric <= route->rt_metric)) || (rtfound == 0) || (mask > route_mask(route).s_addr)) { #endif rtfound = 1; // Requested route has been found route_dest(route).s_addr = dest; route_mask(route).s_addr = mask; route_gtw(route).s_addr = gtw; route->rt_flags = flags; free(route_iface(route)); route_iface(route) = strdup(iface); if (!route_iface(route)) { err = ERR_IPV4_NO_MEM; goto end; } #if HAVE_PROC_NET_ROUTE // 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; } #else log_debug_details("- route matches\n"); #endif } line = strtok_r(NULL, "\n", &saveptr1); } end: free(buffer); if (err) return err; if (rtfound == 0) { // should not occur anymore unless there is no default route log_debug("Route not found.\n"); // at least restore input values route_dest(route).s_addr = rtdest; route_mask(route).s_addr = rtmask; route_gtw(route).s_addr = rtgtw; return ERR_IPV4_NO_SUCH_ROUTE; } return 0; } static int ipv4_set_route(struct rtentry *route) { #ifdef HAVE_RT_ENTRY_WITH_RT_DST /* we can copy rtentry struct directly between openfortivpn and kernel */ 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 /* we have to use the route command as tool for route manipulation */ char cmd[SHOW_ROUTE_BUFFER_SIZE]; if (access("/sbin/route", F_OK) != 0) { log_error("/sbin/route: %s.\n", strerror(errno)); return 1; } strcpy(cmd, "/sbin/route -n add "); if (route->rt_flags & RTF_HOST) strcat(cmd, "-host "); else strcat(cmd, "-net "); strncat(cmd, inet_ntoa(route_dest(route)), 15); if (!(route->rt_flags & RTF_HOST)) { 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 "); strncat(cmd, route_iface(route), SHOW_ROUTE_BUFFER_SIZE - strlen(cmd) - 1); } 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) { #ifdef HAVE_RT_ENTRY_WITH_RT_DST /* we can copy rtentry struct directly between openfortivpn and kernel */ 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]; if (access("/sbin/route", F_OK) != 0) { log_error("/sbin/route: %s.\n", strerror(errno)); return 1; } strcpy(cmd, "/sbin/route -n delete "); if (route->rt_flags & RTF_HOST) strcat(cmd, "-host "); else strcat(cmd, "-net "); strncat(cmd, inet_ntoa(route_dest(route)), 15); if (!(route->rt_flags & RTF_HOST)) { 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 "); strncat(cmd, route_iface(route), SHOW_ROUTE_BUFFER_SIZE - strlen(cmd) - 1); } 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"); route_iface(def_rt) = malloc(strlen(tunnel->ppp_iface) + 2); sprintf(route_iface(def_rt), "!%s", tunnel->ppp_iface); 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 up a route to the tunnel gateway route_dest(gtw_rt).s_addr = tunnel->config->gateway_ip.s_addr; route_mask(gtw_rt).s_addr = inet_addr("255.255.255.255"); route_iface(gtw_rt) = malloc(strlen(tunnel->ppp_iface) + 2); sprintf(route_iface(gtw_rt), "%s", tunnel->ppp_iface); ret = ipv4_get_route(gtw_rt); if ((ret == 0) && (route_dest(gtw_rt).s_addr == tunnel->config->gateway_ip.s_addr) && (route_mask(gtw_rt).s_addr == inet_addr("255.255.255.255"))) { log_debug("removing wrong route to vpn server...\n"); log_debug("ip route show %s\n", ipv4_show_route(gtw_rt)); ipv4_del_route(gtw_rt); } sprintf(route_iface(gtw_rt), "!%s", tunnel->ppp_iface); ret = ipv4_get_route(gtw_rt); if (ret != 0) { log_warn("Could not get route to gateway (%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; } 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"); log_debug("ip route show %s\n", ipv4_show_route(gtw_rt)); 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; } #if HAVE_USR_SBIN_PPPD static void add_text_route(struct tunnel *tunnel, const char *dest, const char *mask, const char *gw) { size_t l0, l1; static const char fmt[] = ",%s/%s/%s"; static const char trigger[] = "openfortivpn"; char **target = &tunnel->config->pppd_ipparam; char *ptr; if (*target == NULL || strncmp(*target, trigger, strlen(trigger))) return; if (!dest || !mask || !gw) return; log_info("Registering route %s/%s via %s\n", dest, mask, gw); l0 = strlen(*target); l1 = strlen(fmt) + strlen(dest) + strlen(mask) + strlen(gw) + 1; ptr = realloc(*target, l0 + l1); if (ptr) { *target = ptr; snprintf(*target + l0, l1, fmt, dest, mask, gw); } else { log_error("realloc: %s\n", strerror(errno)); } } #endif int ipv4_add_split_vpn_route(struct tunnel *tunnel, char *dest, char *mask, char *gateway) { struct rtentry *route; char env_var[24]; #if HAVE_USR_SBIN_PPPD add_text_route(tunnel, dest, mask, gateway); #endif 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 { free(route_iface(route)); route_iface(route) = strdup(tunnel->ppp_iface); if (!route_iface(route)) return ERR_IPV4_NO_MEM; } 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]; free(route_iface(route)); route_iface(route) = strdup(tunnel->ppp_iface); if (!route_iface(route)) return ERR_IPV4_NO_MEM; #ifndef HAVE_RT_ENTRY_WITH_RT_DST if (route_gtw(route).s_addr == tunnel->ipv4.ip_addr.s_addr) route_gtw(route).s_addr = 0; if (route_gtw(route).s_addr == 0) route->rt_flags &= ~RTF_GATEWAY; #endif if (route_gtw(route).s_addr != 0) 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"); free(route_iface(ppp_rt)); route_iface(ppp_rt) = strdup(tunnel->ppp_iface); if (!route_iface(ppp_rt)) return ERR_IPV4_NO_MEM; 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"); free(route_iface(ppp_rt)); route_iface(ppp_rt) = strdup(tunnel->ppp_iface); if (!route_iface(ppp_rt)) return ERR_IPV4_NO_MEM; 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; } static inline char *replace_char(char *str, char find, char replace) { int i; for (i = 0; i < strlen(str); i++) if (str[i] == find) str[i] = replace; return str; } 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 dns_suffix[MAX_DOMAIN_LENGTH+8]; // 7 + MAX_DOMAIN_LENGTH + 1 char *buffer = NULL; int use_resolvconf = 0; tunnel->ipv4.ns1_was_there = 0; tunnel->ipv4.ns2_was_there = 0; tunnel->ipv4.dns_suffix_was_there = 0; if (tunnel->ipv4.ns1_addr.s_addr == 0) tunnel->ipv4.ns1_was_there = -1; if (tunnel->ipv4.ns2_addr.s_addr == 0) tunnel->ipv4.ns2_was_there = -1; if (access(RESOLVCONF_PATH, F_OK) == 0) { int resolvconf_call_len = strlen(RESOLVCONF_PATH) + 20 + strlen(tunnel->ppp_iface); char *resolvconf_call = malloc(resolvconf_call_len); if (resolvconf_call == NULL) { log_warn("Could not create command to run resolvconf (%s).\n", strerror(errno)); return 1; } snprintf(resolvconf_call, resolvconf_call_len, "%s -a \"%s.openfortivpn\"", RESOLVCONF_PATH, tunnel->ppp_iface); use_resolvconf = 1; log_debug("resolvconf_call: %s\n", resolvconf_call); file = popen(resolvconf_call, "w"); free(resolvconf_call); if (file == NULL) { log_warn("Could not open pipe %s (%s).\n", resolvconf_call, strerror(errno)); return 1; } } else { 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", strerror(errno)); 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'; } if (tunnel->ipv4.ns1_addr.s_addr != 0) { strcpy(ns1, "nameserver "); strncat(ns1, inet_ntoa(tunnel->ipv4.ns1_addr), 15); } else { ns1[0] = '\0'; } if (tunnel->ipv4.ns2_addr.s_addr != 0) { strcpy(ns2, "nameserver "); strncat(ns2, inet_ntoa(tunnel->ipv4.ns2_addr), 15); } else { ns2[0] = '\0'; } if (tunnel->ipv4.dns_suffix != NULL) { strcpy(dns_suffix, "search "); strncat(dns_suffix, tunnel->ipv4.dns_suffix, MAX_DOMAIN_LENGTH); replace_char(dns_suffix, ';', ' '); } else { dns_suffix[0] = '\0'; } if (use_resolvconf == 0) { for (const char *line = strtok(buffer, "\n"); line != NULL; line = strtok(NULL, "\n")) { if (strcmp(line, ns1) == 0) { tunnel->ipv4.ns1_was_there = 1; log_debug("ns1 already present in /etc/resolv.conf.\n"); } } if (tunnel->ipv4.ns1_was_there == 0) log_debug("Adding \"%s\", to /etc/resolv.conf.\n", ns1); for (const char *line = strtok(buffer, "\n"); line != NULL; line = strtok(NULL, "\n")) { if (strcmp(line, ns2) == 0) { tunnel->ipv4.ns2_was_there = 1; log_debug("ns2 already present in /etc/resolv.conf.\n"); } } if (tunnel->ipv4.ns2_was_there == 0) log_debug("Adding \"%s\", to /etc/resolv.conf.\n", ns2); if (dns_suffix[0] == '\0') { tunnel->ipv4.dns_suffix_was_there = -1; } else { for (const char *line = strtok(buffer, "\n"); line != NULL; line = strtok(NULL, "\n")) { if (dns_suffix[0] != '\0' && strcmp(line, dns_suffix) == 0) { tunnel->ipv4.dns_suffix_was_there = 1; log_debug("dns_suffix already present in /etc/resolv.conf.\n"); } } } if (tunnel->ipv4.dns_suffix_was_there == 0) log_debug("Adding \"%s\", to /etc/resolv.conf.\n", dns_suffix); 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); } if (tunnel->ipv4.ns1_was_there == 0) { strcat(ns1, "\n"); fputs(ns1, file); } if (tunnel->ipv4.ns2_was_there == 0) { strcat(ns2, "\n"); fputs(ns2, file); } if (tunnel->ipv4.dns_suffix_was_there == 0) { strcat(dns_suffix, "\n"); fputs(dns_suffix, file); } if (use_resolvconf == 0) fwrite(buffer, stat.st_size, 1, file); ret = 0; err_free: free(buffer); err_close: if (use_resolvconf == 0) fclose(file); else pclose(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 dns_suffix[MAX_DOMAIN_LENGTH+8]; // 7 + MAX_DOMAIN_LENGTH + 1 char *buffer = NULL; if (access(RESOLVCONF_PATH, F_OK) == 0) { int resolvconf_call_len = strlen(RESOLVCONF_PATH) + 20 + strlen(tunnel->ppp_iface); char *resolvconf_call = malloc(resolvconf_call_len); if (resolvconf_call == NULL) { log_warn("Could not create command to run resolvconf (%s).\n", strerror(errno)); return ERR_IPV4_SEE_ERRNO; } snprintf(resolvconf_call, resolvconf_call_len, "%s -d \"%s.openfortivpn\"", RESOLVCONF_PATH, tunnel->ppp_iface ); log_debug("resolvconf_call: %s\n", resolvconf_call); ret = system(resolvconf_call); free(resolvconf_call); if (ret == -1) return ERR_IPV4_SEE_ERRNO; return 0; } 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", strerror(errno)); 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'; ns1[0] = '\0'; if (tunnel->ipv4.ns1_addr.s_addr != 0) { strcpy(ns1, "nameserver "); strncat(ns1, inet_ntoa(tunnel->ipv4.ns1_addr), 15); } ns2[0] = '\0'; if (tunnel->ipv4.ns2_addr.s_addr != 0) { strcpy(ns2, "nameserver "); strncat(ns2, inet_ntoa(tunnel->ipv4.ns2_addr), 15); } dns_suffix[0] = '\0'; if (tunnel->ipv4.dns_suffix != NULL && tunnel->ipv4.dns_suffix[0] != '\0') { strcpy(dns_suffix, "search "); strncat(dns_suffix, tunnel->ipv4.dns_suffix, MAX_DOMAIN_LENGTH); } 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 (const char *line = strtok(buffer, "\n"); line != NULL; line = strtok(NULL, "\n")) { if (ns1[0] != '\0' && strcmp(line, ns1) == 0 && (tunnel->ipv4.ns1_was_there == 0)) { log_debug("Deleting \"%s\" from /etc/resolv.conf.\n", ns1); } else if (ns2[0] != '\0' && strcmp(line, ns2) == 0 && (tunnel->ipv4.ns2_was_there == 0)) { log_debug("Deleting \"%s\" from /etc/resolv.conf.\n", ns2); } else if (dns_suffix[0] != '\0' && strcmp(line, dns_suffix) == 0 && (tunnel->ipv4.dns_suffix_was_there == 0)) { log_debug("Deleting \"%s\" from /etc/resolv.conf.\n", dns_suffix); } else { fputs(line, file); fputs("\n", file); } } ret = 0; err_free: free(buffer); err_close: if (file) fclose(file); return ret; } openfortivpn-1.12.0/src/ipv4.h000066400000000000000000000073041362551325400161600ustar00rootroot00000000000000/* * 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 HAVE_SYS_MUTEX_H /* Mac OS X and BSD wants this explicit include */ #include #endif #include #include #include #ifdef HAVE_NET_IF_IF_VAR_H /* on FreeBSD we need this additional header */ #include #endif #if !HAVE_RT_ENTRY_WITH_RT_DST /* * On Mac OS X and FreeBSD struct rtentry is not directly available. * On FreeBSD one could #define _WANT_RTENTRY but the struct does not * contain rt_dst for instance. The entries for mask and destination * are maintained in a separate radix_tree structure by the routing * table instance. We can not simply copy rtentry structures. */ /* 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; char *dns_suffix; int ns1_was_there; // were ns1 already in /etc/resolv.conf? int ns2_was_there; // were ns2 already in /etc/resolv.conf? int dns_suffix_was_there; // was the dns suffix already there? 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.12.0/src/log.c000066400000000000000000000061101362551325400160440ustar00rootroot00000000000000/* * 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 #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_ALL + 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}, { "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); #ifdef HAVE_PTHREAD_MUTEXATTR_SETROBUST 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_ALL) 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_ALL || 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: %s\n", strerror(errno)); 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.12.0/src/log.h000066400000000000000000000037121362551325400160560ustar00rootroot00000000000000/* * 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_DETAILS = 5, OFV_LOG_DEBUG_ALL = 6 }; 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_debug_details(...) \ log_level(OFV_LOG_DEBUG_DETAILS, __VA_ARGS__) #define log_debug_all(...) \ log_level(OFV_LOG_DEBUG_ALL, __VA_ARGS__) #define log_packet(...) \ do { \ if (loglevel >= OFV_LOG_DEBUG_DETAILS) \ do_log_packet(__VA_ARGS__); \ } while (0) void do_log_packet(const char *prefix, size_t len, const uint8_t *packet); #endif openfortivpn-1.12.0/src/main.c000066400000000000000000000476441362551325400162300ustar00rootroot00000000000000/* * 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 #include #define PWD_BUFSIZ 4096 #if HAVE_USR_SBIN_PPPD #define PPPD_USAGE \ " [--pppd-use-peerdns=<0|1>] [--pppd-log=]\n" \ " [--pppd-ifname=] [--pppd-ipparam=]\n" \ " [--pppd-call=] [--pppd-plugin=]\n" #define PPPD_HELP \ " --pppd-use-peerdns=[01] Whether to ask peer ppp server for DNS server\n" \ " addresses and make pppd rewrite /etc/resolv.conf.\n" \ " --pppd-no-peerdns Same as --pppd-use-peerdns=0. pppd will not\n" \ " modify DNS resolution then.\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" \ " --pppd-call= Move most pppd options from pppd cmdline to\n" \ " /etc/ppp/peers/ and invoke pppd with\n" \ " 'call '\n" #endif #if HAVE_USR_SBIN_PPP #define PPPD_USAGE \ " [--ppp-system=]\n" #define PPPD_HELP \ " --ppp-system= connect to the specified system as defined in\n" \ " /etc/ppp/ppp.conf\n" #endif #define usage \ "Usage: openfortivpn [[:]] [-u ] [-p ]\n" \ " [--pinentry=]\n" \ " [--realm=] [--otp=] [--otp-delay=]\n" \ " [--otp-prompt=] [--set-routes=<0|1>]\n" \ " [--half-internet-routes=<0|1>] [--set-dns=<0|1>]\n" \ PPPD_USAGE \ " [--ca-file=]\n" \ " [--user-cert=] [--user-key=]\n" \ " [--trusted-cert=] [--use-syslog]\n" \ " [--persistent=] [-c ] [-v|-q]\n" \ " openfortivpn --help\n" \ " openfortivpn --version\n" \ "\n" #define summary \ "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" #if OPENSSL_VERSION_NUMBER >= 0x10100000L #define help_min_tls "" #else #define help_min_tls " This option\n" \ " is not supported by your OpenSSL library." #endif #define help_options \ "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" \ " --otp-prompt= Search for the OTP prompt starting with this string\n" \ " --otp-delay= Wait seconds before sending the OTP.\n" \ " --pinentry= Use the program to supply a secret instead of asking for it\n" \ " --realm= Use specified authentication realm.\n" \ " --set-routes=[01] Set if openfortivpn should configure routes\n" \ " when tunnel is up.\n" \ " --no-routes Do not configure routes, same as --set-routes=0.\n" \ " --half-internet-routes=[01] Add two 0.0.0.0/1 and 128.0.0.0/1 routes with higher\n" \ " priority instead of replacing the default route.\n" \ " --set-dns=[01] Set if openfortivpn should add DNS name servers\n" \ " and domain search list in /etc/resolv.conf.\n" \ " If installed resolvconf is used for the update.\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-cert=pkcs11: Use smartcard. Takes also partial or full PKCS11-URI.\n" \ " --user-key= Use specified PEM-encoded key if the server requires\n" \ " 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" \ " Also enable TLS v1.0 if applicable.\n" \ " If your server requires a specific cipher or protocol,\n" \ " consider using --cipher-list and/or --min-tls 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" \ " --min-tls Use minimum TLS version instead of system default.\n" \ " Valid values are 1.0, 1.1, 1.2, 1.3." help_min_tls "\n" \ " --seclevel-1 If --cipher-list is not specified, add @SECLEVEL=1 to\n" \ " (compiled in) list of ciphers. This lowers limits on\n" \ " dh key.\n" \ " --persistent= Run the vpn persistently in a loop and try to re-\n" \ " connect every seconds when dropping out\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" #define help_config \ "\n" \ "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" int main(int argc, char **argv) { int ret = EXIT_FAILURE; const char *config_file = SYSCONFDIR"/openfortivpn/config"; const char *host; char *port_str; struct vpn_config cfg = { .gateway_host = {'\0'}, .gateway_port = 443, .username = {'\0'}, .password = NULL, .otp = {'\0'}, .otp_prompt = NULL, .otp_delay = 0, .pinentry = NULL, .realm = {'\0'}, .set_routes = 1, .set_dns = 1, .use_syslog = 0, .half_internet_routes = 0, .persistent = 0, #if HAVE_USR_SBIN_PPPD .pppd_use_peerdns = 0, .pppd_log = NULL, .pppd_plugin = NULL, .pppd_ipparam = NULL, .pppd_ifname = NULL, .pppd_call = NULL, #endif #if HAVE_USR_SBIN_PPP .ppp_system = NULL, #endif .ca_file = NULL, .user_cert = NULL, .user_key = NULL, .insecure_ssl = 0, .min_tls = 0, .seclevel_1 = 0, .cipher_list = NULL, .cert_whitelist = NULL }; struct vpn_config cli_cfg = invalid_cfg; const struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 0}, {"config", required_argument, 0, 'c'}, {"pinentry", required_argument, 0, 0}, {"realm", required_argument, 0, 0}, {"username", required_argument, 0, 'u'}, {"password", required_argument, 0, 'p'}, {"otp", required_argument, 0, 'o'}, {"otp-prompt", required_argument, 0, 0}, {"otp-delay", required_argument, 0, 0}, {"set-routes", required_argument, 0, 0}, {"no-routes", no_argument, &cli_cfg.set_routes, 0}, {"half-internet-routes", required_argument, 0, 0}, {"set-dns", required_argument, 0, 0}, {"no-dns", no_argument, &cli_cfg.set_dns, 0}, {"use-syslog", no_argument, &cli_cfg.use_syslog, 1}, {"persistent", required_argument, 0, 0}, {"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, &cli_cfg.insecure_ssl, 1}, {"cipher-list", required_argument, 0, 0}, #if OPENSSL_VERSION_NUMBER >= 0x10100000L {"min-tls", required_argument, 0, 0}, #endif {"seclevel-1", no_argument, &cli_cfg.seclevel_1, 1}, #if HAVE_USR_SBIN_PPPD {"pppd-use-peerdns", required_argument, 0, 0}, {"pppd-no-peerdns", no_argument, &cli_cfg.pppd_use_peerdns, 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}, {"pppd-call", required_argument, 0, 0}, {"plugin", required_argument, 0, 0}, // deprecated #endif #if HAVE_USR_SBIN_PPP {"ppp-system", required_argument, 0, 0}, #endif {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 HAVE_USR_SBIN_PPPD if (strcmp(long_options[option_index].name, "pppd-use-peerdns") == 0) { int pppd_use_peerdns = strtob(optarg); if (pppd_use_peerdns < 0) { log_warn("Bad pppd-use-peerdns option: \"%s\"\n", optarg); break; } cli_cfg.pppd_use_peerdns = pppd_use_peerdns; break; } if (strcmp(long_options[option_index].name, "pppd-log") == 0) { cli_cfg.pppd_log = strdup(optarg); break; } if (strcmp(long_options[option_index].name, "pppd-plugin") == 0) { cli_cfg.pppd_plugin = strdup(optarg); break; } if (strcmp(long_options[option_index].name, "pppd-ifname") == 0) { cli_cfg.pppd_ifname = strdup(optarg); break; } if (strcmp(long_options[option_index].name, "pppd-ipparam") == 0) { cli_cfg.pppd_ipparam = strdup(optarg); break; } if (strcmp(long_options[option_index].name, "pppd-call") == 0) { cli_cfg.pppd_call = strdup(optarg); break; } // --plugin is deprecated, --pppd-plugin should be used if (cli_cfg.pppd_plugin == NULL && strcmp(long_options[option_index].name, "plugin") == 0) { cli_cfg.pppd_plugin = strdup(optarg); break; } #endif #if HAVE_USR_SBIN_PPP if (strcmp(long_options[option_index].name, "ppp-system") == 0) { cfg.ppp_system = strdup(optarg); break; } #endif if (strcmp(long_options[option_index].name, "ca-file") == 0) { cli_cfg.ca_file = strdup(optarg); break; } if (strcmp(long_options[option_index].name, "user-cert") == 0) { cli_cfg.user_cert = strdup(optarg); break; } if (strcmp(long_options[option_index].name, "user-key") == 0) { cli_cfg.user_key = strdup(optarg); break; } if (strcmp(long_options[option_index].name, "pinentry") == 0) { cli_cfg.pinentry = strdup(optarg); break; } if (strcmp(long_options[option_index].name, "realm") == 0) { strncpy(cli_cfg.realm, optarg, FIELD_SIZE); cli_cfg.realm[FIELD_SIZE] = '\0'; break; } if (strcmp(long_options[option_index].name, "trusted-cert") == 0) { if (add_trusted_cert(&cli_cfg, optarg)) log_warn("Could not add certificate digest to whitelist.\n"); break; } if (strcmp(long_options[option_index].name, "cipher-list") == 0) { cli_cfg.cipher_list = strdup(optarg); break; } #if OPENSSL_VERSION_NUMBER >= 0x10100000L if (strcmp(long_options[option_index].name, "min-tls") == 0) { int min_tls = parse_min_tls(optarg); if (min_tls == -1) { log_warn("Bad min-tls option: \"%s\"\n", optarg); } else { cli_cfg.min_tls = min_tls; } break; } #endif if (strcmp(long_options[option_index].name, "otp-prompt") == 0) { cli_cfg.otp_prompt = 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; } cli_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; } cli_cfg.half_internet_routes = half_internet_routes; break; } if (strcmp(long_options[option_index].name, "otp-delay") == 0) { long otp_delay = strtol(optarg, NULL, 0); if (otp_delay < 0 || otp_delay > UINT_MAX) { log_warn("Bad otp-delay option: \"%s\"\n", optarg); break; } cli_cfg.otp_delay = otp_delay; break; } if (strcmp(long_options[option_index].name, "persistent") == 0) { long persistent = strtol(optarg, NULL, 0); if (persistent < 0 || persistent > UINT_MAX) { log_warn("Bad persistent option: \"%s\"\n", optarg); break; } cli_cfg.persistent = persistent; 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; } cli_cfg.set_dns = set_dns; break; } goto user_error; case 'h': printf("%s%s%s%s%s", usage, summary, help_options, PPPD_HELP, 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': strncpy(cli_cfg.username, optarg, FIELD_SIZE); cli_cfg.username[FIELD_SIZE] = '\0'; break; case 'p': cli_cfg.password = strdup(optarg); break; case 'o': strncpy(cli_cfg.otp, optarg, FIELD_SIZE); cli_cfg.otp[FIELD_SIZE] = '\0'; break; default: goto user_error; } } if (optind < argc - 1 || optind > argc) goto user_error; if (cli_cfg.password != NULL && cli_cfg.password[0] != '\0') log_warn("You should not pass the password on the command line. Type it interactively or use a config file instead.\n"); log_debug_all("ATTENTION: the output contains sensitive information such as the THE CLEAR TEXT PASSWORD.\n"); log_debug("openfortivpn " VERSION "\n"); // Load config file if (config_file[0] != '\0') { ret = load_config(&cfg, config_file); 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)); } if (cfg.password != NULL && cli_cfg.password == NULL) { if (cfg.password[0] == '\0') log_debug("Disabled password due to empty entry in config file \"%s\"\n", config_file); else log_debug("Loaded password from config file \"%s\"\n", config_file); } // Then apply CLI config merge_config(&cfg, &cli_cfg); set_syslog(cfg.use_syslog); // Read host and port from the command line if (optind == argc - 1) { host = argv[optind++]; port_str = strchr(host, ':'); if (port_str != NULL) { port_str[0] = '\0'; port_str++; cfg.gateway_port = strtol(port_str, NULL, 0); if (cfg.gateway_port == 0 || cfg.gateway_port > 65535) { log_error("Specify a valid port.\n"); goto user_error; } } strncpy(cfg.gateway_host, host, FIELD_SIZE); cfg.gateway_host[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' && cfg.user_cert == NULL) { log_error("Specify a username.\n"); goto user_error; } // If username but no password given, interactively ask user if (cfg.password == NULL && cfg.username[0] != '\0') { char *tmp_password = malloc(PWD_BUFSIZ); // allocate large buffer read_password(cfg.pinentry, "password", "VPN account password: ", tmp_password, PWD_BUFSIZ); cfg.password = strdup(tmp_password); // copy string of correct size free(tmp_password); } 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); if (cfg.username[0] != '\0') log_debug("Config username = \"%s\"\n", cfg.username); if (cfg.password != NULL) log_debug_all("Config password = \"%s\"\n", cfg.password); else cfg.password = strdup(""); if (cfg.otp[0] != '\0') log_debug("One-time password = \"%s\"\n", cfg.otp); if (geteuid() != 0) { log_error("This process was not spawned with root privileges, which are required.\n"); ret = EXIT_FAILURE; goto exit; } do { if (run_tunnel(&cfg) != 0) ret = EXIT_FAILURE; else ret = EXIT_SUCCESS; if ((cfg.persistent > 0) && (get_sig_received() == 0)) sleep(cfg.persistent); } while ((get_sig_received() == 0) && (cfg.persistent != 0)); goto exit; user_error: fprintf(stderr, "%s", usage); exit: destroy_vpn_config(&cfg); exit(ret); } openfortivpn-1.12.0/src/openssl_hostname_validation.c000066400000000000000000000130031362551325400230550ustar00rootroot00000000000000/* Obtained from: https://github.com/iSECPartners/ssl-conservatory */ /* * Helper functions to perform basic hostname validation using OpenSSL. * * Author: Alban Diquet * * Copyright (C) 2012, iSEC Partners. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include #include #include #define HOSTNAME_MAX_SIZE 255 #ifndef HAVE_X509_CHECK_HOST #include "openssl_hostname_validation.h" /** * Tries to find a match for hostname in the certificate's Common Name field. * * Returns MatchFound if a match was found. * Returns MatchNotFound if no matches were found. * Returns MalformedCertificate if the Common Name had a NUL character embedded in it. * Returns Error if the Common Name could not be extracted. */ static HostnameValidationResult matches_common_name(const char *hostname, const X509 *server_cert) { int common_name_loc = -1; X509_NAME_ENTRY *common_name_entry = NULL; ASN1_STRING *common_name_asn1 = NULL; char *common_name_str = NULL; // Find the position of the CN field in the Subject field of the certificate common_name_loc = X509_NAME_get_index_by_NID(X509_get_subject_name((X509 *) server_cert), NID_commonName, -1); if (common_name_loc < 0) { return Error; } // Extract the CN field common_name_entry = X509_NAME_get_entry(X509_get_subject_name((X509 *) server_cert), common_name_loc); if (common_name_entry == NULL) { return Error; } // Convert the CN field to a C string common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry); if (common_name_asn1 == NULL) { return Error; } common_name_str = (char *) ASN1_STRING_data(common_name_asn1); // Make sure there isn't an embedded NUL character in the CN if (ASN1_STRING_length(common_name_asn1) != strlen(common_name_str)) { return MalformedCertificate; } // Compare expected hostname with the CN if (strcasecmp(hostname, common_name_str) == 0) { return MatchFound; } else { return MatchNotFound; } } /** * Tries to find a match for hostname in the certificate's Subject Alternative Name extension. * * Returns MatchFound if a match was found. * Returns MatchNotFound if no matches were found. * Returns MalformedCertificate if any of the hostnames had a NUL character embedded in it. * Returns NoSANPresent if the SAN extension was not present in the certificate. */ static HostnameValidationResult matches_subject_alternative_name(const char *hostname, const X509 *server_cert) { HostnameValidationResult result = MatchNotFound; int i; int san_names_nb = -1; STACK_OF(GENERAL_NAME) *san_names = NULL; // Try to extract the names within the SAN extension from the certificate san_names = X509_get_ext_d2i((X509 *) server_cert, NID_subject_alt_name, NULL, NULL); if (san_names == NULL) { return NoSANPresent; } san_names_nb = sk_GENERAL_NAME_num(san_names); // Check each name within the extension for (i=0; itype == GEN_DNS) { // Current name is a DNS name, let's check it char *dns_name = (char *) ASN1_STRING_data(current_name->d.dNSName); // Make sure there isn't an embedded NUL character in the DNS name if (ASN1_STRING_length(current_name->d.dNSName) != strlen(dns_name)) { result = MalformedCertificate; break; } else { // Compare expected hostname with the DNS name if (strcasecmp(hostname, dns_name) == 0) { result = MatchFound; break; } } } } sk_GENERAL_NAME_pop_free(san_names, GENERAL_NAME_free); return result; } /** * Validates the server's identity by looking for the expected hostname in the * server's certificate. As described in RFC 6125, it first tries to find a match * in the Subject Alternative Name extension. If the extension is not present in * the certificate, it checks the Common Name instead. * * Returns MatchFound if a match was found. * Returns MatchNotFound if no matches were found. * Returns MalformedCertificate if any of the hostnames had a NUL character embedded in it. * Returns Error if there was an error. */ HostnameValidationResult validate_hostname(const char *hostname, const X509 *server_cert) { HostnameValidationResult result; if((hostname == NULL) || (server_cert == NULL)) return Error; // First try the Subject Alternative Names extension result = matches_subject_alternative_name(hostname, server_cert); if (result == NoSANPresent) { // Extension was not found: try the Common Name result = matches_common_name(hostname, server_cert); } return result; } #endif openfortivpn-1.12.0/src/openssl_hostname_validation.h000066400000000000000000000040271362551325400230700ustar00rootroot00000000000000/* Obtained from: https://github.com/iSECPartners/ssl-conservatory */ /* * Helper functions to perform basic hostname validation using OpenSSL. * * Author: Alban Diquet * * Copyright (C) 2012, iSEC Partners. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #ifndef HAVE_X509_CHECK_HOST typedef enum { MatchFound, MatchNotFound, NoSANPresent, MalformedCertificate, Error } HostnameValidationResult; /** * Validates the server's identity by looking for the expected hostname in the * server's certificate. As described in RFC 6125, it first tries to find a match * in the Subject Alternative Name extension. If the extension is not present in * the certificate, it checks the Common Name instead. * * Returns MatchFound if a match was found. * Returns MatchNotFound if no matches were found. * Returns MalformedCertificate if any of the hostnames had a NUL character embedded in it. * Returns Error if there was an error. */ HostnameValidationResult validate_hostname(const char *hostname, const X509 *server_cert); #endif openfortivpn-1.12.0/src/ssl.h000066400000000000000000000120021362551325400160660ustar00rootroot00000000000000/* * 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 __clang__ /* * Get rid of Mac OS X 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 #ifndef ERESTART /* * ERESTART is one of the recoverable errors which might be returned. * However, in Mac OS X and BSD 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 transferred) * 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 transferred) * 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.12.0/src/tunnel.c000066400000000000000000000751541362551325400166060ustar00rootroot00000000000000/* * 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" #ifndef HAVE_X509_CHECK_HOST #include "openssl_hostname_validation.h" #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #if HAVE_PTY_H #include #elif HAVE_UTIL_H #include #endif #include #include #include #if HAVE_SYSTEMD #include #endif // we use this constant in the source, so define a fallback if not defined #ifndef OPENSSL_API_COMPAT #define OPENSSL_API_COMPAT 0x0908000L #endif struct ofv_varr { unsigned int cap; // current capacity unsigned int off; // next slot to write, always < max(cap - 1, 1) const char **data; // NULL terminated }; static int ofv_append_varr(struct ofv_varr *p, const char *x) { if (p->off + 1 >= p->cap) { const char **ndata; unsigned int ncap = (p->off + 1) * 2; if (p->off + 1 >= ncap) { log_error("%s: ncap exceeded\n", __func__); return 1; }; ndata = realloc(p->data, ncap * sizeof(const char *)); if (ndata) { p->data = ndata; p->cap = ncap; } else { log_error("realloc: %s\n", strerror(errno)); return 1; } } if (p->data == NULL) { log_error("%s: NULL data\n", __func__); return 1; } if (p->off + 1 >= p->cap) { log_error("%s: cap exceeded in p\n", __func__); return 1; } p->data[p->off] = x; p->data[++p->off] = NULL; return 0; } 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"); #if HAVE_SYSTEMD sd_notify(0, "READY=1"); #endif 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; int slave_stderr; #ifdef HAVE_STRUCT_TERMIOS struct termios termp = { .c_cflag = B9600, .c_cc[VTIME] = 0, .c_cc[VMIN] = 1 }; #endif static const char ppp_path[] = PPP_PATH; if (access(ppp_path, F_OK) != 0) { log_error("%s: %s.\n", ppp_path, strerror(errno)); return 1; } log_debug("ppp_path: %s\n", ppp_path); slave_stderr = dup(STDERR_FILENO); if (slave_stderr < 0) { log_error("slave stderr %s\n", strerror(errno)); return 1; } #ifdef HAVE_STRUCT_TERMIOS pid = forkpty(&amaster, NULL, &termp, NULL); #else pid = forkpty(&amaster, NULL, NULL, NULL); #endif if (pid == 0) { // child process struct ofv_varr pppd_args = { 0, 0, NULL }; dup2(slave_stderr, STDERR_FILENO); close(slave_stderr); #if HAVE_USR_SBIN_PPP /* * assume there is a default configuration to start. * Support for taking options from the command line * e.g. the name of the configuration or options * to send interactively to ppp will be added later */ static const char *const v[] = { ppp_path, "-direct" }; for (unsigned int i = 0; i < ARRAY_SIZE(v); i++) if (ofv_append_varr(&pppd_args, v[i])) return 1; #endif #if HAVE_USR_SBIN_PPPD if (tunnel->config->pppd_call) { if (ofv_append_varr(&pppd_args, ppp_path)) return 1; if (ofv_append_varr(&pppd_args, "call")) return 1; if (ofv_append_varr(&pppd_args, tunnel->config->pppd_call)) return 1; } else { static const char *const v[] = { ppp_path, "115200", // speed ":192.0.2.1", // : "noipdefault", "noaccomp", "noauth", "default-asyncmap", "nopcomp", "receive-all", "nodefaultroute", "nodetach", "lcp-max-configure", "40", "mru", "1354" }; for (unsigned int i = 0; i < ARRAY_SIZE(v); i++) if (ofv_append_varr(&pppd_args, v[i])) return 1; } if (tunnel->config->pppd_use_peerdns) if (ofv_append_varr(&pppd_args, "usepeerdns")) return 1; if (tunnel->config->pppd_log) { if (ofv_append_varr(&pppd_args, "debug")) return 1; if (ofv_append_varr(&pppd_args, "logfile")) return 1; if (ofv_append_varr(&pppd_args, tunnel->config->pppd_log)) return 1; } else { /* * pppd defaults to logging to fd=1, clobbering the * actual PPP data */ if (ofv_append_varr(&pppd_args, "logfd")) return 1; if (ofv_append_varr(&pppd_args, "2")) return 1; } if (tunnel->config->pppd_plugin) { if (ofv_append_varr(&pppd_args, "plugin")) return 1; if (ofv_append_varr(&pppd_args, tunnel->config->pppd_plugin)) return 1; } if (tunnel->config->pppd_ipparam) { if (ofv_append_varr(&pppd_args, "ipparam")) return 1; if (ofv_append_varr(&pppd_args, tunnel->config->pppd_ipparam)) return 1; } if (tunnel->config->pppd_ifname) { if (ofv_append_varr(&pppd_args, "ifname")) return 1; if (ofv_append_varr(&pppd_args, tunnel->config->pppd_ifname)) return 1; } #endif #if HAVE_USR_SBIN_PPP if (tunnel->config->ppp_system) { if (ofv_append_varr(&pppd_args, tunnel->config->ppp_system)) return 1; } #endif close(tunnel->ssl_socket); execv(pppd_args.data[0], (char *const *)pppd_args.data); free(pppd_args.data); fprintf(stderr, "execvp: %s\n", strerror(errno)); _exit(EXIT_FAILURE); } else { close(slave_stderr); if (pid == -1) { log_error("forkpty: %s\n", strerror(errno)); return 1; } } // 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[] = { "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.", "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 %s to exit...\n", PPP_DAEMON); 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: %s exit status code %d\n", PPP_DAEMON, exit_status); #if HAVE_USR_SBIN_PPPD if (exit_status >= ARRAY_SIZE(pppd_message) || exit_status < 0) { log_error("%s: Returned an unknown exit status: %d\n", PPP_DAEMON, exit_status); } else { switch (exit_status) { case 0: // success log_debug("%s: %s\n", PPP_DAEMON, pppd_message[exit_status]); break; case 16: // emitted when exiting normally log_info("%s: %s\n", PPP_DAEMON, pppd_message[exit_status]); break; default: log_error("%s: %s\n", PPP_DAEMON, pppd_message[exit_status]); break; } } #else // ppp exit codes in the FreeBSD case switch (exit_status) { case 0: // success and EX_NORMAL as defined in ppp source directly log_debug("%s: %s\n", PPP_DAEMON, pppd_message[exit_status]); break; case 1: case 127: case 255: // abnormal exit with hard-coded error codes in ppp log_error("%s: exited with return value of %d\n", PPP_DAEMON, exit_status); break; default: log_error("%s: %s (%d)\n", PPP_DAEMON, strerror(exit_status), exit_status); break; } #endif } else if (WIFSIGNALED(status)) { int signal_number = WTERMSIG(status); log_debug("waitpid: %s terminated by signal %d\n", PPP_DAEMON, signal_number); log_error("%s: terminated by signal: %s\n", PPP_DAEMON, 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 (( #if HAVE_USR_SBIN_PPPD (tunnel->config->pppd_ifname && strstr(ifa->ifa_name, tunnel->config->pppd_ifname) != NULL) || strstr(ifa->ifa_name, "ppp") != NULL #endif #if HAVE_USR_SBIN_PPP strstr(ifa->ifa_name, "tun") != NULL #endif ) && 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); if (env_proxy == NULL) { log_error("strdup: %s\n", strerror(errno)); goto err_strdup; } // get rid of a trailing slash if (*env_proxy && 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(strtoul(proxy_port, NULL, 10)); } else { server.sin_port = htons(tunnel->config->gateway_port); } // get rid of a trailing slash if (*proxy_host && 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 a FQDN 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) { 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); ssize_t bytes_written = write(handle, request, strlen(request)); if (bytes_written != strlen(request)) { log_error("write error while talking to proxy: %s\n", strerror(errno)); goto err_connect; } // wait for a "200 OK" reply from the proxy, // be careful not to fetch too many bytes at once const char *response = NULL; memset(&(request), '\0', sizeof(request)); for (int j = 0; response == NULL; j++) { /* * Coverity detected a defect: * CID 200508: String not null terminated (STRING_NULL) * * It is actually a false positive: * • Function memset() initializes 'request' with '\0' * • Function read() gets a single char into: request[j] * • The final '\0' cannot be overwritten because: * j < ARRAY_SIZE(request) - 1 */ ssize_t bytes_read = read(handle, &(request[j]), 1); if (bytes_read < 1) { log_error("Proxy response is unexpectedly large and cannot fit in the %lu-bytes buffer.\n", ARRAY_SIZE(request)); goto err_proxy_response; } // detect "200" static const char HTTP_STATUS_200[] = "200"; response = strstr(request, HTTP_STATUS_200); // detect end-of-line after "200" if (response != NULL) { /* * RFC2616 states in section 2.2 Basic Rules: * CR = * LF = * HTTP/1.1 defines the sequence CR LF as the * end-of-line marker for all protocol elements * except the entity-body (see appendix 19.3 * for tolerant applications). * CRLF = CR LF * * RFC2616 states in section 19.3 Tolerant Applications: * The line terminator for message-header fields * is the sequence CRLF. However, we recommend * that applications, when parsing such headers, * recognize a single LF as a line terminator * and ignore the leading CR. */ static const char *const HTTP_EOL[] = { "\r\n\r\n", "\n\n" }; const char *eol = NULL; for (int i = 0; (i < ARRAY_SIZE(HTTP_EOL)) && (eol == NULL); i++) eol = strstr(response, HTTP_EOL[i]); response = eol; } if (j > ARRAY_SIZE(request) - 2) { log_error("Proxy response does not contain \"%s\" as expected.\n", HTTP_STATUS_200); goto err_proxy_response; } } free(env_proxy); // release memory allocated by strdup() } return handle; err_proxy_response: err_connect: free(env_proxy); // release memory allocated by strdup() err_strdup: close(handle); err_socket: return -1; } static int ssl_verify_cert(struct tunnel *tunnel) { int ret = -1; int cert_valid = 0; unsigned char digest[SHA256LEN]; unsigned int len; struct x509_digest *elem; char digest_str[SHA256STRLEN], *subject, *issuer; char *line; int i; X509_NAME *subj; 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); #ifdef HAVE_X509_CHECK_HOST // Use OpenSSL native host validation if v >= 1.0.2. // compare against gateway_host and correctly check return value // to fix piror Incorrect use of X509_check_host if (X509_check_host(cert, tunnel->config->gateway_host, 0, 0, NULL) == 1) cert_valid = 1; #else // Use validate_hostname form iSECPartners if native validation not available // in order to avoid TLS Certificate CommonName NULL Byte Vulnerability if (validate_hostname(tunnel->config->gateway_host, cert) == MatchFound) cert_valid = 1; #endif // Try to validate certificate using local PKI if (cert_valid && 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 an SSL session. */ int ssl_connect(struct tunnel *tunnel) { ssl_disconnect(tunnel); tunnel->ssl_socket = tcp_connect(tunnel); if (tunnel->ssl_socket == -1) return 1; // registration is deprecated from OpenSSL 1.1.0 onward #if OPENSSL_API_COMPAT < 0x10100000L // Register the error strings for libcrypto & libssl SSL_load_error_strings(); // Register the available ciphers and digests SSL_library_init(); #endif 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; } } /* Use engine for PIV if user-cert config starts with pkcs11 URI: */ if (tunnel->config->use_engine > 0) { ENGINE *e; ENGINE_load_builtin_engines(); e = ENGINE_by_id("pkcs11"); if (!e) { log_error("Could not load pkcs11 Engine: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } if (!ENGINE_init(e)) { log_error("Could not init pkcs11 Engine: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); ENGINE_free(e); return 1; } if (!ENGINE_set_default_RSA(e)) abort(); ENGINE_finish(e); ENGINE_free(e); struct token parms; parms.uri = tunnel->config->user_cert; parms.cert = NULL; if (!ENGINE_ctrl_cmd(e, "LOAD_CERT_CTRL", 0, &parms, NULL, 1)) { log_error("PKCS11 ENGINE_ctrl_cmd: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } if (!SSL_CTX_use_certificate(tunnel->ssl_context, parms.cert)) { log_error("PKCS11 SSL_CTX_use_certificate: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } EVP_PKEY * privkey = ENGINE_load_private_key( e, parms.uri, UI_OpenSSL(), NULL); if (!privkey) { log_error("PKCS11 ENGINE_load_private_key: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } if (!SSL_CTX_use_PrivateKey(tunnel->ssl_context, privkey)) { log_error("PKCS11 SSL_CTX_use_PrivateKey_file: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } if (!SSL_CTX_check_private_key(tunnel->ssl_context)) { log_error("PKCS11 SSL_CTX_check_private_key: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } } else { /* end PKCS11-engine */ 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) { if (!tunnel->config->cipher_list) { const char *cipher_list; if (tunnel->config->seclevel_1) cipher_list = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4@SECLEVEL=1"; else cipher_list = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4"; tunnel->config->cipher_list = strdup(cipher_list); } } else { #if OPENSSL_VERSION_NUMBER >= 0x10100000L if (tunnel->config->min_tls <= 0) tunnel->config->min_tls = TLS1_VERSION; #endif if (!tunnel->config->cipher_list && tunnel->config->seclevel_1) { const char *cipher_list = "DEFAULT@SECLEVEL=1"; tunnel->config->cipher_list = strdup(cipher_list); } } if (tunnel->config->cipher_list) { log_debug("Setting cipher list to: %s\n", tunnel->config->cipher_list); if (!SSL_set_cipher_list(tunnel->ssl_handle, tunnel->config->cipher_list)) { log_error("SSL_set_cipher_list failed: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } } #if OPENSSL_VERSION_NUMBER >= 0x10100000L if (tunnel->config->min_tls > 0) { log_debug("Setting min proto version to: 0x%x\n", tunnel->config->min_tls); if (!SSL_set_min_proto_version(tunnel->ssl_handle, tunnel->config->min_tls)) { log_error("SSL_set_min_proto_version failed: %s\n", ERR_error_string(ERR_peek_last_error(), NULL)); return 1; } } #endif 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 (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 = { .config = config, .state = STATE_DOWN, .ssl_context = NULL, .ssl_handle = NULL, .ipv4.ns1_addr.s_addr = 0, .ipv4.ns2_addr.s_addr = 0, .ipv4.dns_suffix = NULL, .on_ppp_if_up = on_ppp_if_up, .on_ppp_if_down = on_ppp_if_down }; // Step 0: get gateway host IP log_debug("Resolving gateway host ip\n"); ret = get_gateway_host_ip(&tunnel); if (ret) goto err_tunnel; // Step 1: open a SSL connection to the gateway log_debug("Establishing ssl connection\n"); 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. Please check the password, client certificate, etc.\n"); log_debug("%s %d\n", err_http_str(ret), ret); ret = 1; goto err_tunnel; } log_info("Authenticated.\n"); log_debug("Cookie: %s\n", tunnel.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 log_debug("Retrieving configuration\n"); 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 log_debug("Establishing the tunnel\n"); ret = pppd_run(&tunnel); if (ret) goto err_tunnel; // Step 5: ask gateway to start tunneling log_debug("Switch to tunneling mode\n"); ret = http_send(&tunnel, "GET /remote/sslvpn-tunnel HTTP/1.1\r\n" "Host: sslvpn\r\n" "Cookie: %s\r\n\r\n", tunnel.cookie); 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 log_debug("Starting IO through the tunnel\n"); io_loop(&tunnel); log_debug("disconnecting\n"); 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 %s.\n", PPP_DAEMON); 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.12.0/src/tunnel.h000066400000000000000000000053051362551325400166020ustar00rootroot00000000000000/* * 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" #if HAVE_LIBUTIL_H #include "libutil.h" #endif #include #include #include #ifdef __clang__ /* * Get rid of Mac OS X 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; char cookie[COOKIE_SIZE + 1]; 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 *tunnel); int (*on_ppp_if_down)(struct tunnel *tunnel); }; struct token { const char *uri; X509 *cert; }; 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.12.0/src/userinput.c000066400000000000000000000155031362551325400173270ustar00rootroot00000000000000/* * Copyright (C) 2015 Davíð Steinn Geirsson * Copyright (C) 2019 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 "userinput.h" #include "log.h" #include #include #include #include #include #include #include #include #include #include static char *uri_escape(const char *string) { char *escaped = NULL; int allocated_len = 0; int real_len = 0; int i; for (i = 0; string[i]; i++) { if (allocated_len + 4 >= real_len) { allocated_len += 16; escaped = realloc(escaped, allocated_len); // bail out if realloc fails if (escaped == NULL) return NULL; } if (isalnum(string[i])) escaped[real_len++] = string[i]; else real_len += sprintf(&escaped[real_len], "%%%02X", string[i]); } escaped[real_len] = '\0'; return escaped; } static char *uri_unescape(const char *string) { int escaped_len = strlen(string) + 1; char *unescaped = malloc(escaped_len); int real_len = 0; int i = 0; while (string[i]) { if (string[i] == '%' && isxdigit(string[i + 1]) && isxdigit(string[i + 2])) { sscanf(&string[i + 1], "%02hhx", (unsigned char *)&unescaped[real_len]); i += 3; } else if (string[i] == '%' && string[i + 1] == '%') { unescaped[real_len] = '%'; i += 2; } else { unescaped[real_len] = string[i]; i += 1; } real_len++; } unescaped[real_len] = '\0'; return unescaped; } static int pinentry_read(int from, char **retstr) { int bufsiz = 0; char *buf = NULL; int len = 0; int ret; do { if (bufsiz - len < 64) { bufsiz += 64; buf = realloc(buf, bufsiz); if (buf == NULL) { if (retstr) *retstr = strdup(strerror(errno)); return -1; } buf[bufsiz-1] = '\0'; } ret = read(from, &buf[len], bufsiz - len); if (ret == -1) { free(buf); if (retstr) *retstr = strdup(strerror(errno)); return -1; } if (ret == 0) { free(buf); if (retstr) *retstr = strdup("Short read"); return -1; } len += ret; } while (buf[len - 1] != '\n'); // overwrite the newline with a null character buf[len - 1] = '\0'; if (strcmp(buf, "OK") == 0 || strncmp(buf, "OK ", 3) == 0 || strncmp(buf, "D ", 2) == 0) { if (retstr) { *retstr = strchr(buf, ' '); *retstr = *retstr ? uri_unescape(*retstr + 1) : NULL; } free(buf); return 0; } if (strncmp(buf, "ERR ", 4) == 0 || strncmp(buf, "S ERROR", 7) == 0) { ret = atoi(&buf[4]); if (!ret) ret = -1; if (retstr) { *retstr = strchr(&buf[4], ' '); *retstr = *retstr ? uri_unescape(*retstr + 1) : NULL; } free(buf); return ret; } free(buf); if (retstr) *retstr = strdup("pinentry protocol error"); return -1; } static int pinentry_exchange(int to, int from, char **retstr, const char *format, ...) { va_list ap; va_start(ap, format); if (vdprintf(to, format, ap) == 0) { if (retstr) *retstr = strdup(strerror(errno)); va_end(ap); return -1; } va_end(ap); return pinentry_read(from, retstr); } static void pinentry_read_password(const char *pinentry, const char *hint, const char *prompt, char *pass, size_t len) { int from_pinentry[2]; int to_pinentry[2]; int pinentry_status; pid_t pinentry_pid; char *escaped; char *retstr; int ret; *pass = '\0'; if (pipe(from_pinentry) == -1) { perror("pipe"); return; } if (pipe(to_pinentry) == -1) { perror("pipe"); close(from_pinentry[0]); close(from_pinentry[1]); return; } pinentry_pid = fork(); if (pinentry_pid == -1) { perror("fork"); return; } if (pinentry_pid == 0) { close(to_pinentry[1]); if (dup2(to_pinentry[0], STDIN_FILENO) == -1) { perror("dup2"); exit(1); } close(to_pinentry[0]); close(from_pinentry[0]); if (dup2(from_pinentry[1], STDOUT_FILENO) == -1) { perror("dup2"); exit(1); } close(from_pinentry[1]); execlp(pinentry, pinentry, NULL); perror(pinentry); exit(1); } close(to_pinentry[0]); close(from_pinentry[1]); ret = pinentry_read(from_pinentry[0], &retstr); if (ret) log_error("Error: %s\n", retstr); free(retstr); if (ret) goto out; ret = pinentry_exchange(to_pinentry[1], from_pinentry[0], &retstr, "SETTITLE %s\n", "VPN Password"); if (ret) log_error("Failed to set title: %s\n", retstr); free(retstr); if (ret) goto out; ret = pinentry_exchange(to_pinentry[1], from_pinentry[0], &retstr, "SETDESC %s\n", "VPN Requires a Password"); if (ret) log_error("Failed to set description: %s\n", retstr); free(retstr); if (ret) goto out; escaped = uri_escape(hint); ret = pinentry_exchange(to_pinentry[1], from_pinentry[0], NULL, "SETKEYINFO %s\n", escaped); if (ret) log_error("Failed to set keyinfo\n"); free(escaped); if (ret) goto out; escaped = uri_escape(prompt); ret = pinentry_exchange(to_pinentry[1], from_pinentry[0], &retstr, "SETPROMPT %s\n", escaped); free(escaped); if (ret) log_error("Failed to set prompt: %s\n", retstr); free(retstr); if (ret) goto out; ret = pinentry_exchange(to_pinentry[1], from_pinentry[0], &retstr, "GETPIN\n"); if (ret) { log_error("Failed to get PIN: %s\n", retstr); free(retstr); goto out; } if (retstr) { strncpy(pass, retstr, len); free(retstr); } else { log_error("No password given\n"); } out: close(to_pinentry[1]); close(from_pinentry[0]); if (waitpid(pinentry_pid, &pinentry_status, 0) == -1) perror("waitpid"); } void read_password(const char *pinentry, const char *hint, const char *prompt, char *pass, size_t len) { int masked = 0; struct termios oldt, newt; int i; if (pinentry && *pinentry) { pinentry_read_password(pinentry, hint, prompt, pass, len); return; } printf("%s", prompt); fflush(stdout); // Try to hide user input if (tcgetattr(STDIN_FILENO, &oldt) == 0) { newt = oldt; newt.c_lflag &= ~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.12.0/src/userinput.h000066400000000000000000000016521362551325400173340ustar00rootroot00000000000000/* * 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 #include void read_password(const char *pinentry, const char *hint, const char *prompt, char *pass, size_t len); #endif openfortivpn-1.12.0/src/xml.c000066400000000000000000000053201362551325400160650ustar00rootroot00000000000000/* * 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 occurrence 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[MAX_DOMAIN_LENGTH]; // just enough to hold a domain search string 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 == MAX_DOMAIN_LENGTH) { 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.12.0/src/xml.h000066400000000000000000000020141362551325400160670ustar00rootroot00000000000000/* * 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 #define MAX_DOMAIN_LENGTH 256 // see https://unix.stackexchange.com/questions/245849 // ... /resolv-conf-limited-to-six-domains-with-a-total-of-256-characters const char *xml_find(char t, const char *tag, const char *buf, int nest); char *xml_get(const char *buf); #endif openfortivpn-1.12.0/tests/000077500000000000000000000000001362551325400154745ustar00rootroot00000000000000openfortivpn-1.12.0/tests/ci/000077500000000000000000000000001362551325400160675ustar00rootroot00000000000000openfortivpn-1.12.0/tests/ci/install_astyle.sh000077500000000000000000000005771362551325400214660ustar00rootroot00000000000000#!/bin/sh set -e PREFIX="$1" ln -fs "${PREFIX}/bin/astyle" "${HOME}/bin/astyle" [ -x "${PREFIX}/bin/astyle" ] && exit 0 VERSION=3.1 SRC="https://sourceforge.net/projects/astyle/files/astyle/astyle%20${VERSION}/astyle_${VERSION}_linux.tar.gz/download" wget -O astyle.tar.gz "$SRC" tar -xf astyle.tar.gz -C "$HOME" cd "${HOME}/astyle/build/gcc" make make prefix="$PREFIX" install openfortivpn-1.12.0/tests/ci/install_openssl.sh000077500000000000000000000004641362551325400216430ustar00rootroot00000000000000#!/bin/sh set -e PREFIX="$1" [ -x "${PREFIX}/bin/openssl" ] && exit 0 VERSION=1.0.2o SRC="https://www.openssl.org/source/openssl-${VERSION}.tar.gz" wget -O openssl.tar.gz "$SRC" tar -xf openssl.tar.gz -C "$HOME" cd "${HOME}/openssl-${VERSION}" ./config --prefix="$PREFIX" shared -fPIC make make install openfortivpn-1.12.0/tests/lint/000077500000000000000000000000001362551325400164425ustar00rootroot00000000000000openfortivpn-1.12.0/tests/lint/astyle.sh000077500000000000000000000010331362551325400202770ustar00rootroot00000000000000#!/bin/bash # Copyright (C) 2015 Adrien Vergé # Check that astyle is installed if ! command -v 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" >&2 git --no-pager diff --no-index -U0 "$file" "$tmp" rc=1 fi rm "$tmp" done exit $rc openfortivpn-1.12.0/tests/lint/eol-at-eof.sh000077500000000000000000000004671362551325400207400ustar00rootroot00000000000000#!/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" >&2 rc=1 fi if [ "$(tail -c 1 "$file")" != "" ]; then echo "$file: no newline at end of file" >&2 rc=1 fi done exit $rc openfortivpn-1.12.0/tests/lint/line_length.py000077500000000000000000000024021362551325400213050ustar00rootroot00000000000000#!/usr/bin/python3 # -*- coding: utf-8 -*- # Copyright (C) 2015 Adrien Vergé import sys # Guidelines say 80, let's tolerate a bit more MAX = 90 def endswithstring(line): """Detect lines from C source code ending with a string. Parameters ---------- line : str Line of C source code. Returns ------- bool True if line ends with string, False otherwise. """ for end in ('"', '",', '");', '";', '" \\'): if line.endswith(end): return True return False def main(): exit_status = 0 for arg in sys.argv[1:]: with open(arg, "r") as source_file: for i, line in enumerate(source_file): line = line.rstrip() # Lines that end with a string are exempted if endswithstring(line): continue # Replace tabs with 8 spaces line = line.replace("\t", " ") # Lines longer than MAX are reported as an error if len(line) > MAX: print("{}: {}: line too long ({} characters)" .format(arg, i, len(line))) exit_status = 1 sys.exit(exit_status) if __name__ == "__main__": main() openfortivpn-1.12.0/tests/lint/run.sh000077500000000000000000000005341362551325400176070ustar00rootroot00000000000000#!/bin/bash # Copyright (C) 2015 Adrien Vergé rc=0 ./tests/lint/eol-at-eof.sh $(git ls-files | grep -v openssl_hostname_validation) || rc=1 ./tests/lint/line_length.py $(git ls-files '*.[ch]' | grep -v openssl_hostname_validation) || rc=1 ./tests/lint/astyle.sh $(git ls-files '*.[ch]' | grep -v openssl_hostname_validation) || rc=1 exit $rc