pax_global_header00006660000000000000000000000064140057313130014507gustar00rootroot0000000000000052 comment=c187cce6b40a7af4d2373500ae4bb358a2b1574f ocaml-ssl-0.5.10/000077500000000000000000000000001400573131300134645ustar00rootroot00000000000000ocaml-ssl-0.5.10/.gitignore000066400000000000000000000000301400573131300154450ustar00rootroot00000000000000*.install .merlin _buildocaml-ssl-0.5.10/.gitmodules000066400000000000000000000001051400573131300156350ustar00rootroot00000000000000[submodule "m4"] path = m4 url = https://github.com/savonet/m4.git ocaml-ssl-0.5.10/.travis.yml000066400000000000000000000003541400573131300155770ustar00rootroot00000000000000language: c dist: bionic sudo: required install: test -e .travis.opam.sh || wget https://raw.githubusercontent.com/ocaml/ocaml-ci-scripts/master/.travis-opam.sh script: bash -ex .travis-opam.sh env: - OCAML_VERSION=4.08 os: - linux ocaml-ssl-0.5.10/CHANGES000077700000000000000000000000001400573131300160442CHANGES.mdustar00rootroot00000000000000ocaml-ssl-0.5.10/CHANGES.md000066400000000000000000000144071400573131300150640ustar00rootroot000000000000000.5.10 (2021-02-01) ====== - Add `use_certificate_from_string` (#54). - Add `get_verify_error_string`, `get_start_date`, `get_expiration_date` (#57). - Release master lock on ALPN failure (#58). - Add `version` (#60). - Switch to dune 2 (#61). 0.5.9 (2019-07-15) ===== - Backward compatibility with OpenSSL 1.0.2 (#53). 0.5.8 (2019-07-03) ===== - Better error reporting. - Add support for hostname validation (#49). - Add ALPN support (#37, #38, #48). 0.5.7 (2018-10-25) ===== - Correctly set #defines (#40). - Correctly deal with non-existent directories for Homebrew (#42). 0.5.6 (2018-09-12) ===== - Switch to the dune build system. 0.5.5 (2017-10-13) ===== - Make sure that LDFLAGS is honored during build. 0.5.4 (2017-10-02) ===== - Enable safe-string compatibility (#32). - Add -std=c99 to CFLAGS (#29). 0.5.3 (2016-11-08) ===== - Remove -ansi flag to be compatible with OCaml 4.04 (thanks Mark Shinwell). - Use accessor functions for X509_STORE_CTX. - Change CLIBS order to allow static linking. 0.5.2 (2015-11-23) ===== - Add OPENSSL_NO_SSL3 preprocessor flag to disable SSLv3 (thanks Jérémie Courrèges-Anglas). 0.5.1 (2015-05-27) ===== - Fix META file for versions of OCaml older than 4.02.0 (thanks Anil Madhavapeddy, closes #20). 0.5.0 (2015-05-18) ===== - Allow to honor server cipher preferences (thanks mfp, closes #18). - Add functions for reading into/writing from bigarrays, avoiding copy (thanks mfp, closes #15). - Support disabling SSL protocol versions (thanks Edwin Török, closes #13). - Use Bytes instead of String for read and write, changes the ABI thus the version bump (thanks Vincent Bernardoff, closes #16, and mfp, closes #19). - Make verbosity of client_verify_callback configurable (thanks Nicolas Trangez, closes #12). - Fix build with old versions of SSL (thanks Edwin Török, closes #10). 0.4.7 (2014-04-21) ===== - Add support for TLS1.1 and TLS1.2 (thanks Thomas Calderon). - Add function to initialize Diffie-Hellman and elliptic curve parameters (thanks Thomas Calderon and Edwin Török). - Add set_client_SNI_hostname to specify client-side SNI hostname (thanks Mauricio Fernandez). - Fix double leave of blocking section in ocaml_ssl_accept (thanks Edwin Török). - Check for errors in SSL_connect/SSL_accept (thanks Jérôme Vouillon). - Clear the error queue before calling SSL_read and similar functions; SSL_get_error does not work reliably otherwise (thanks Jérôme Vouillon). - Allow static linking on Mingw64 (thanks schadinger). 0.4.6 (2011-10-16) ===== - Added write_certificate function. - Remove support for SSLv2, which was dropped upstream (thanks Dario Teixeira). - Added support for compiling under Win32 (thanks David Allsopp), see README.win32. - Check for pthreads in configure. 0.4.5 (2011-03-01) ===== - Use pthread mutexes for locking thread-safe version of ssl. 0.4.4 (2010-01-06) ===== - Use SSL_CTX_use_certificate_chain_file instead of SSL_CTX_use_certificate_file. - Added support for --enable-debugging configure option. - Don't link with unix library and don't build in custom mode. 0.4.3 (2008-12-18) ===== - Don't use blocking sections in finalizers since it causes segfaults (thanks Grégoire Henry and Stéphane Glondu). 0.4.2 (2007-03-29) ===== - Added some missing blocking sections (reported by Oscar Hellström). 0.4.1 (2007-02-21) ===== - file_descr_of_socket is not marked as deprecated anymore. - Patched the Makefile to be compatible with FreeBSD (thanks Jaap Boender). - Explicitely link with libcrypto since we use it. Compilation should now work on Mac OS X too (thanks Janne Hellsten). 0.4.0 (2006-09-09) ===== - Using caml_alloc_custom and Data_custom_val to access custom blocks. - Added set_password_callback function. - Integrated a big patch from Chris Waterson: - Added get_error_string function. - Read and write are not blocking anymore, use Unix.select and file_descr_of_socket if you want blocking functions. - Fix SSL_CTX initialization to call SSL_CTX_set_mode(3) with SSL_MODE_AUTO_RETRY flag. This causes SSL_read and SSL_write to "hide" the SSL_ERROR_WANT_(READ|WRITE) errors that may occur during renegotiation on a blocking socket. - Fix SSL_CTX initialization to call SSL_CTX_set_mode(3) with SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER flag. This allows for a different buffer address to be passed to a restarted non-blocking write operation, which is useful since the OCaml garbage collector may move buffers around between calls. - We do not need to store explicitely the file descriptor for SSL sockets. - Corrected checking of errors in ocaml_ssl_read (thanks Vincent Balat and Nataliya Guts). - input_char now raises End_of_file when no byte could be read (thanks Nataliya Guts). 0.3.1 (2005-07-21) ===== - The library is now under the LGPL licence + linking exception + linking with openssl exception (see COPYING for more details). 0.3.0 (2005-06-01) ===== - Added Ssl_threads.init function to make the library thread-safe. - Put connect, accept and flush (and all other functions) in blocking_section to allow other threads to run in the meantime. - Unified the three context creation functions in create_context, the certificate to use should now be sepcified with use_certificate (sorry for the API-breakage). - Added the get_verify_result function. - Using Store_field instead of Field(...) = ... - Using caml namespace functions. 0.2.0 (2004-12-18) ===== - Many thanks to Thomas Fischbacher for his patches: - Corrected int / val bugs when raising exceptions from C (those where found by Mike Furr too, thanks). - Added many fonctions (but in Caml instead of C). - Context creation functions now take the protocol as argument. - Added the create_context function (for client and server connections). - Added functions for verifying certificates: client_verify_callback, set_verify, set_verify_depth, verify. - The cipher now has its own type. - Added functions to handle ciphers: get_current_cipher, get_cipher_description, get_cipher_name, get_cipher_version, set_cipher_list. - Added the read_certificate and load_verify_locations functions. - Added the open_connection_with_context and flush functions. - read and write functions are now thread-safe. - Cleaned the stubs (function prototypes, comments, etc.). - Updated OCamlMakefile and improved build system. 0.1.0 (2004-02-05) ===== - Initial release. ocaml-ssl-0.5.10/COPYING000066400000000000000000000654371400573131300145360ustar00rootroot00000000000000This program is released under the LGPL version 2.1 (see the text below) with the additional exemption that compiling, linking, and/or using OpenSSL is allowed. As a special exception to the GNU Library General Public License, you may also link, statically or dynamically, a "work that uses the Library" with a publicly distributed version of the Library to produce an executable file containing portions of the Library, and distribute that executable file under terms of your choice, without any of the additional requirements listed in clause 6 of the GNU Library General Public License. By "a publicly distributed version of the Library", we mean either the unmodified Library, or a modified version of the Library that is distributed under the conditions defined in clause 3 of the GNU Library General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU Library General Public License. GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! ocaml-ssl-0.5.10/Makefile000066400000000000000000000013661400573131300151320ustar00rootroot00000000000000.PHONY: build clean test install uninstall clean all-supported-ocaml-versions build: dune build @default test: dune runtest install: dune install uninstall: dune uninstall clean: dune clean all-supported-ocaml-versions: dune build @default @runtest --workspace dune-workspace.dev install-dev: opam install -y opam-query opam-publish tls VERSION := $$(opam query --version) NAME_VERSION := $$(opam query --name-version) ARCHIVE := $$(opam query --archive) release: git tag -a $(VERSION) -m "Version $(VERSION)." git push origin $(VERSION) opam publish prepare $(NAME_VERSION) $(ARCHIVE) cp descr $(NAME_VERSION) grep -Ev '^(name|version):' opam >$(NAME_VERSION)/opam opam publish submit $(NAME_VERSION) rm -rf $(NAME_VERSION) ocaml-ssl-0.5.10/README.md000066400000000000000000000066001400573131300147450ustar00rootroot00000000000000OCaml-SSL - OCaml bindings for the libssl ========================================= * Author: Samuel Mimram * Email: savonet-users@lists.sourceforge.net * Homepage: http://savonet.sourceforge.net/ Copyright (c) 2003-2015 the Savonet Team. [![LGPL license](https://img.shields.io/badge/License-LGPL-green.svg)](https://github.com/savonet/liquidsoap/blob/master/COPYING) [![GitHub release](https://img.shields.io/github/release/savonet/ocaml-ssl.svg)](https://GitHub.com/savonet/ocaml-ssl/releases/) [![Install with Opam !](https://img.shields.io/badge/Install%20with-Opam-1abc9c.svg)](http://opam.ocaml.org/packages/ssl/) [![Build Status](https://travis-ci.org/savonet/ocaml-ssl.svg?branch=master)](https://travis-ci.org/savonet/ocaml-ssl) Installation ------------ `ocaml-ssl` can be installed via [OPAM](https://opam.ocaml.org): ``` opam install ssl ``` Is this library thread-safe? ---------------------------- Yes it is if and only if the first function you call in ocaml-ssl is `Ssl_threads.init` (and the second one should be `Ssl.init`). Creating a self-signed ssl certificate -------------------------------------- To get started quickly you can create a self-signed ssl certificate using openssl. 1. First, create a 1024-bit private key to use when creating your CA.: `openssl genrsa -des3 -out privkey.pem 1024` 2. Create a master certificate based on this key, to use when signing other certificates: `openssl req -new -x509 -days 1001 -key privkey.pem -out cert.pem` SSL acknowledgment ------------------ This product includes software developed by the OpenSSL Project for use in the [OpenSSL Toolkit](http://www.openssl.org/). License ------- This library is released under the LGPL version 2.1 with the additional exemption that compiling, linking, and/or using OpenSSL is allowed. As a special exception to the GNU Library General Public License, you may also link, statically or dynamically, a "work that uses the Library" with a publicly distributed version of the Library to produce an executable file containing portions of the Library, and distribute that executable file under terms of your choice, without any of the additional requirements listed in clause 6 of the GNU Library General Public License. By "a publicly distributed version of the Library", we mean either the unmodified Library, or a modified version of the Library that is distributed under the conditions defined in clause 3 of the GNU Library General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU Library General Public License. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA The examples are under the GPL licence version 2.0. ocaml-ssl-0.5.10/dune-project000066400000000000000000000000331400573131300160020ustar00rootroot00000000000000(lang dune 2.0) (name ssl) ocaml-ssl-0.5.10/dune-workspace.dev000066400000000000000000000004221400573131300171110ustar00rootroot00000000000000(lang dune 1.0) ;; This file is used by `make all-supported-ocaml-versions` (context (opam (switch 4.02.3))) (context (opam (switch 4.03.0))) (context (opam (switch 4.04.2))) (context (opam (switch 4.05.0))) (context (opam (switch 4.06.1))) (context (opam (switch 4.07.0)))ocaml-ssl-0.5.10/examples/000077500000000000000000000000001400573131300153025ustar00rootroot00000000000000ocaml-ssl-0.5.10/examples/alpn.ml000066400000000000000000000057461400573131300166020ustar00rootroot00000000000000 let test_client proto_list = Ssl.init (); let ctx = Ssl.create_context Ssl.TLSv1_2 Ssl.Client_context in Ssl.set_context_alpn_protos ctx proto_list; let sockaddr = Unix.ADDR_INET(Unix.inet_addr_of_string "127.0.0.1", 4433) in let ssl = Ssl.open_connection_with_context ctx sockaddr in let () = match Ssl.get_negotiated_alpn_protocol ssl with | None -> print_endline "No protocol selected" | Some proto -> print_endline ("Selected protocol: " ^ proto) in Ssl.shutdown ssl let test_server proto_list = let certfile = "cert.pem" in let privkey = "privkey.key" in let log s = Printf.printf "[II] %s\n%!" s in Ssl.init (); let sockaddr = Unix.ADDR_INET(Unix.inet_addr_of_string "127.0.0.1", 4433) in let domain = begin match sockaddr with | Unix.ADDR_UNIX _ -> Unix.PF_UNIX | Unix.ADDR_INET (_, _) -> Unix.PF_INET end in let sock = Unix.socket domain Unix.SOCK_STREAM 0 in let ctx = Ssl.create_context Ssl.TLSv1_2 Ssl.Server_context in Ssl.use_certificate ctx certfile privkey; let rec first_match l1 = function | [] -> None | x::_ when List.mem x l1 -> Some x | _::xs -> first_match l1 xs in Ssl.set_context_alpn_select_callback ctx (fun client_protos -> first_match client_protos proto_list ); Unix.setsockopt sock Unix.SO_REUSEADDR true; Unix.bind sock sockaddr; Unix.listen sock 100; log "listening for connections"; let (s, caller) = Unix.accept sock in let ssl_s = Ssl.embed_socket s ctx in let () = try Ssl.accept ssl_s with | e -> Printexc.to_string e |> print_endline in let inet_addr_of_sockaddr = function | Unix.ADDR_INET (n, _) -> n | Unix.ADDR_UNIX _ -> Unix.inet_addr_any in let inet_addr = inet_addr_of_sockaddr caller in let ip = Unix.string_of_inet_addr inet_addr in log (Printf.sprintf "openning connection for [%s]" ip); let () = match Ssl.get_negotiated_alpn_protocol ssl_s with | None -> log "no protocol selected" | Some proto -> log (Printf.sprintf "selected protocol: %s" proto) in Ssl.shutdown ssl_s let () = let usage = "usage: ./alpn (server|client) protocol[,protocol]" in let split_on_char sep s = let r = ref [] in let j = ref (String.length s) in for i = String.length s - 1 downto 0 do if s.[i] = sep then begin r := String.sub s (i + 1) (!j - i - 1) :: !r; j := i end done; String.sub s 0 !j :: !r in let typ = ref "" in let protocols = ref [] in Arg.parse [ "-t", Arg.String (fun t -> typ := t), "Type (server or client)"; "-p", Arg.String (fun p -> protocols := split_on_char ',' p), "Comma-separated protocols"; ] (fun _ -> ()) usage; match !typ with | "server" -> test_server !protocols | "client" -> test_client !protocols | _ -> failwith "Invalid type, use server or client." (* Usage: ocamlfind ocamlc alpn.ml -g -o alpn -package ssl -linkpkg -ccopt -L/path/to/openssl/lib -cclib -lssl -cclib -lcrypto ./alpn -t server -p h2,http/1.1 ./alpn -t client -p h2,http/1.1 *) ocaml-ssl-0.5.10/examples/dune000066400000000000000000000001741400573131300161620ustar00rootroot00000000000000(alias (name default) (deps stalkd.exe stelnet.exe)) (executables (names stalkd stelnet) (libraries threads unix ssl)) ocaml-ssl-0.5.10/examples/stalkd.ml000066400000000000000000000063671400573131300171320ustar00rootroot00000000000000(* Copyright (C) 2003-2005 Savonet team This file is part of Ocaml-ssl. 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 2 of the License, or (at your option) any later version. Ocaml-smbclient 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 Ocaml-smbclient; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * A small copycat server using SSL. * * @author Samuel Mimram *) let certfile = ref "cert.pem" let privkey = ref "privkey.pem" let port = ref 9876 let password = ref "toto" let log s = Printf.printf "[II] %s\n%!" s let establish_threaded_server server_handler sockaddr nbconn = log "establishing server"; let domain = begin match sockaddr with | Unix.ADDR_UNIX _ -> Unix.PF_UNIX | Unix.ADDR_INET (_, _) -> Unix.PF_INET end in let sock = Unix.socket domain Unix.SOCK_STREAM 0 in let handle_connexion (s, caller) = let inet_addr_of_sockaddr = function | Unix.ADDR_INET (n, _) -> n | Unix.ADDR_UNIX _ -> Unix.inet_addr_any in let inet_addr = inet_addr_of_sockaddr caller in let ip = Unix.string_of_inet_addr inet_addr in log (Printf.sprintf "openning connection for [%s]" ip); server_handler inet_addr s; Ssl.shutdown s in let ctx = Ssl.create_context Ssl.SSLv23 Ssl.Server_context in if !password <> "" then Ssl.set_password_callback ctx (fun _ -> !password); Ssl.use_certificate ctx !certfile !privkey; Unix.setsockopt sock Unix.SO_REUSEADDR true; Unix.bind sock sockaddr; Unix.listen sock nbconn; (* let ssl_sock = Ssl.embed_socket sock ctx in *) while true do log "listening for connections"; let (s, caller) = Unix.accept sock in let ssl_s = Ssl.embed_socket s ctx in Ssl.accept ssl_s; ignore (Thread.create handle_connexion (ssl_s, caller)); done let () = let bufsize = 1024 in let buf = Bytes.create bufsize in let connected_clients = ref [] in Ssl_threads.init (); Ssl.init (); establish_threaded_server (fun addr ssl -> connected_clients := (addr, ssl) :: !connected_clients; log "accepted a new connection"; let loop = ref true in while !loop do let l = Ssl.read ssl buf 0 bufsize in let m = Bytes.sub buf 0 l in let msg = Bytes.sub m 0 ((Bytes.length m) - 1) in let msg = Bytes.to_string msg in log (Printf.sprintf "revceived '%s'" msg); if msg = "exit" then ( log "A client has quit"; connected_clients := List.filter (fun (_, s) -> s != ssl) !connected_clients; Ssl.shutdown ssl; loop := false ) else List.iter (fun (_, s) -> ignore (Ssl.output_string s (Bytes.to_string m)) ) !connected_clients done ) (Unix.ADDR_INET(Unix.inet_addr_any, !port)) 100 ocaml-ssl-0.5.10/examples/stelnet.ml000066400000000000000000000053301400573131300173130ustar00rootroot00000000000000(* Copyright (C) 2003-2005 Savonet team This file is part of Ocaml-ssl. 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 2 of the License, or (at your option) any later version. Ocaml-smbclient 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 Ocaml-smbclient; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** * Like telnet ... but with ssl! * * @author Samuel Mimram *) (* $Id$ *) open Unix let host = ref "" let port = ref 9876 let parano = ref false let usage = "usage: stelnet host [-p port]" let _ = Arg.parse [ "-p", Arg.Int (fun i -> port := i), "\tPort"; "-w", Arg.Set parano, "\tParanoiac mode"; ] (fun s -> host := s) usage; if !host = "" then (Printf.printf "%s\n\n" usage; exit 1); Ssl_threads.init (); Ssl.init (); let he = ( try gethostbyname !host with | Not_found -> failwith "Host not found" ) in let sockaddr = ADDR_INET(he.h_addr_list.(0), !port) in let ssl = if not !parano then Ssl.open_connection Ssl.SSLv23 sockaddr else ( let ctx = Ssl.create_context Ssl.SSLv23 Ssl.Client_context in Ssl.set_verify ctx [Ssl.Verify_peer] (Some Ssl.client_verify_callback); Ssl.set_verify_depth ctx 3; Ssl.open_connection_with_context ctx sockaddr ) in let cert = Ssl.get_certificate ssl in let cipher = Ssl.get_cipher ssl in let bufsize = 1024 in let buf = Bytes.create bufsize in let loop = ref true in Printf.printf "SSL connection ok.\n%!"; Printf.printf "Certificate issuer: %s\nsubject: %s\n%!" (Ssl.get_issuer cert) (Ssl.get_subject cert); Printf.printf "Cipher: %s (%s)\n%s\n%!" (Ssl.get_cipher_name cipher) (Ssl.get_cipher_version cipher) (Ssl.get_cipher_description cipher); Printf.printf "Type 'exit' to quit.\n\n%!"; ignore ( Thread.create (fun () -> let buf = Bytes.create bufsize in while !loop do let r = Ssl.read ssl buf 0 bufsize in Printf.printf "%s%!" (String.sub (Bytes.to_string buf) 0 r) done ) () ); while !loop do let r = Unix.read Unix.stdin buf 0 bufsize in if Bytes.to_string (Bytes.sub buf 0 4) = "exit" then loop := false; ignore (Ssl.write ssl buf 0 r); done; Ssl.shutdown ssl ocaml-ssl-0.5.10/src/000077500000000000000000000000001400573131300142535ustar00rootroot00000000000000ocaml-ssl-0.5.10/src/config/000077500000000000000000000000001400573131300155205ustar00rootroot00000000000000ocaml-ssl-0.5.10/src/config/discover.ml000066400000000000000000000042331400573131300176720ustar00rootroot00000000000000module C = Configurator.V1 let directory_exists fsp = Sys.file_exists fsp && Sys.is_directory fsp let default c : C.Pkg_config.package_conf = if C.ocaml_config_var_exn c "system" = "macosx" then if directory_exists "/usr/local/opt/openssl" then { libs = ["-L/usr/local/opt/openssl/lib"] ; cflags = ["-I/usr/local/opt/openssl/include"] } else { libs = ["-L/opt/local/lib"] ; cflags = ["-I/opt/local/include"] } else { libs = ["-lssl"; "-lcrypto"] ; cflags = [] } let prog fun_name = Printf.sprintf {c| #include int main(int argc, char **argv) { void *foo = %s; return 0; }|c} fun_name let function_tests = [ "TLSv1_1_method", "HAVE_TLS11" ; "TLSv1_2_method", "HAVE_TLS12" ; "EC_KEY_free", "HAVE_EC" ; "SSL_set_alpn_protos", "HAVE_ALPN" ] let macro_tests = [ "SSL_set_tlsext_host_name", "HAVE_SNI" ; "SSL_EXT_TLS1_3_ONLY", "HAVE_TLS13" ] let () = C.main ~name:"ssl" (fun c -> let default = default c in let conf = match C.Pkg_config.get c with | None -> default | Some pc -> begin match (C.Pkg_config.query pc ~package:"openssl") with | Some s -> s | None -> default end in let results = C.C_define.import c ~c_flags:conf.cflags ~includes:["openssl/ssl.h"] (List.map (fun (c, _) -> (c, C.C_define.Type.Switch)) macro_tests) in let defines = List.combine macro_tests results |> List.map (fun ((name, const), (name', value)) -> assert (name = name'); (const, value)) in let defines = List.fold_left (fun acc (fun_name, var_name) -> let defined = prog fun_name |> C.c_test c ~c_flags:conf.cflags ~link_flags:conf.libs in ( var_name , C.C_define.Value.Switch defined ) :: acc ) defines function_tests in C.C_define.gen_header_file c ~fname:"ocaml_ssl.h" defines; C.Flags.write_sexp "c_library_flags.sexp" conf.libs; C.Flags.write_sexp "c_flags.sexp" conf.cflags) ocaml-ssl-0.5.10/src/config/dune000066400000000000000000000000751400573131300164000ustar00rootroot00000000000000(executable (name discover) (libraries dune-configurator)) ocaml-ssl-0.5.10/src/dune000066400000000000000000000004771400573131300151410ustar00rootroot00000000000000(library (name ssl) (public_name ssl) (libraries unix) (wrapped false) (foreign_stubs (language c) (names ssl_stubs) (flags (:include c_flags.sexp))) (c_library_flags (:include c_library_flags.sexp))) (rule (targets c_flags.sexp c_library_flags.sexp ocaml_ssl.h) (action (run ./config/discover.exe))) ocaml-ssl-0.5.10/src/ssl.ml000066400000000000000000000275231400573131300154170ustar00rootroot00000000000000(* Copyright (C) 2003-2005 Samuel Mimram This file is part of Ocaml-ssl. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *) type protocol = | SSLv23 | SSLv3 | TLSv1 | TLSv1_1 | TLSv1_2 | TLSv1_3 type context type certificate type socket type ssl_error = | Error_none | Error_ssl | Error_want_read | Error_want_write | Error_want_x509_lookup | Error_syscall | Error_zero_return | Error_want_connect | Error_want_accept type verify_error = | Error_v_unable_to_get_issuer_cert | Error_v_unable_to_get_ctl | Error_v_unable_to_decrypt_cert_signature | Error_v_unable_to_decrypt_CRL_signature | Error_v_unable_to_decode_issuer_public_key | Error_v_cert_signature_failure | Error_v_CRL_signature_failure | Error_v_cert_not_yet_valid | Error_v_cert_has_expired | Error_v_CRL_not_yet_valid | Error_v_CRL_has_expired | Error_v_error_in_cert_not_before_field | Error_v_error_in_cert_not_after_field | Error_v_error_in_CRL_last_update_field | Error_v_error_in_CRL_next_update_field | Error_v_out_of_mem | Error_v_depth_zero_self_signed_cert | Error_v_self_signed_cert_in_chain | Error_v_unable_to_get_issuer_cert_locally | Error_v_unable_to_verify_leaf_signature | Error_v_cert_chain_too_long | Error_v_cert_revoked | Error_v_invalid_CA | Error_v_path_length_exceeded | Error_v_invalid_purpose | Error_v_cert_untrusted | Error_v_cert_rejected | Error_v_subject_issuer_mismatch | Error_v_akid_skid_mismatch | Error_v_akid_issuer_serial_mismatch | Error_v_keyusage_no_certsign | Error_v_application_verification type bigarray = (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t external get_error_string : unit -> string = "ocaml_ssl_get_error_string" exception Method_error exception Context_error exception Certificate_error of string exception Cipher_error exception Diffie_hellman_error exception Ec_curve_error exception Private_key_error of string exception Unmatching_keys exception Invalid_socket exception Handler_error exception Connection_error of ssl_error exception Accept_error of ssl_error exception Read_error of ssl_error exception Write_error of ssl_error exception Verify_error of verify_error let () = Printexc.register_printer (function | Method_error -> Some ("SSL: Method error") | Context_error -> Some ("SSL: Context error") | Certificate_error s -> Some ("SSL: Certificate error: " ^ s) | Cipher_error -> Some ("SSL: Cihper error") | Diffie_hellman_error -> Some ("SSL: Diffie Hellman error") | Ec_curve_error -> Some ("SSL: EC curve error") | Private_key_error s -> Some ("SSL: Privte key error: " ^ s) | Unmatching_keys -> Some ("SSL: Unmatching keys") | Invalid_socket -> Some ("SSL: Invalid socket") | Handler_error -> Some ("SSL: Handler error") | Connection_error _ -> Some ("SSL connection() error: " ^ (get_error_string())) | Accept_error _ -> Some ("SSL accept() error: " ^ (get_error_string())) | Read_error _ -> Some ("SSL read() error: " ^ (get_error_string())) | Write_error _ -> Some ("SSL write() error: " ^ (get_error_string())) | Verify_error _ -> Some ("SSL verify() error: " ^ (get_error_string())) | _ -> None) let () = Callback.register_exception "ssl_exn_method_error" Method_error; Callback.register_exception "ssl_exn_context_error" Context_error; Callback.register_exception "ssl_exn_certificate_error" (Certificate_error ""); Callback.register_exception "ssl_exn_cipher_error" Cipher_error; Callback.register_exception "ssl_exn_diffie_hellman_error" Diffie_hellman_error; Callback.register_exception "ssl_exn_ec_curve_error" Ec_curve_error; Callback.register_exception "ssl_exn_private_key_error" (Private_key_error ""); Callback.register_exception "ssl_exn_unmatching_keys" Unmatching_keys; Callback.register_exception "ssl_exn_invalid_socket" Invalid_socket; Callback.register_exception "ssl_exn_handler_error" Handler_error; Callback.register_exception "ssl_exn_connection_error" (Connection_error Error_none); Callback.register_exception "ssl_exn_accept_error" (Accept_error Error_none); Callback.register_exception "ssl_exn_read_error" (Read_error Error_none); Callback.register_exception "ssl_exn_write_error" (Write_error Error_none); Callback.register_exception "ssl_exn_verify_error" (Verify_error Error_v_application_verification) let thread_safe = ref false external init : bool -> unit = "ocaml_ssl_init" let ts = thread_safe let init ?thread_safe () = let thread_safe = match thread_safe with | Some b -> b | None -> !ts in init thread_safe type context_type = | Client_context | Server_context | Both_context external create_context : protocol -> context_type -> context = "ocaml_ssl_create_context" external use_certificate : context -> string -> string -> unit = "ocaml_ssl_ctx_use_certificate" external use_certificate_from_string : context -> string -> string -> unit = "ocaml_ssl_ctx_use_certificate_from_string" external set_password_callback : context -> (bool -> string) -> unit = "ocaml_ssl_ctx_set_default_passwd_cb" external embed_socket : Unix.file_descr -> context -> socket = "ocaml_ssl_embed_socket" external disable_protocols : context -> protocol list -> unit = "ocaml_ssl_disable_protocols" external set_cipher_list : context -> string -> unit = "ocaml_ssl_ctx_set_cipher_list" external honor_cipher_order : context -> unit = "ocaml_ssl_ctx_honor_cipher_order" external init_dh_from_file : context -> string -> unit = "ocaml_ssl_ctx_init_dh_from_file" external init_ec_from_named_curve : context -> string -> unit = "ocaml_ssl_ctx_init_ec_from_named_curve" external load_verify_locations : context -> string -> string -> unit = "ocaml_ssl_ctx_load_verify_locations" external set_default_verify_paths : context -> bool = "ocaml_ssl_ctx_set_default_verify_paths" external get_verify_result : socket -> int = "ocaml_ssl_get_verify_result" external get_verify_error_string : int -> string = "ocaml_ssl_get_verify_error_string" type verify_mode = | Verify_peer | Verify_fail_if_no_peer_cert | Verify_client_once type verify_callback external get_client_verify_callback_ptr : unit -> verify_callback = "ocaml_ssl_get_client_verify_callback_ptr" let client_verify_callback = get_client_verify_callback_ptr () external set_client_verify_callback_verbose : bool -> unit = "ocaml_ssl_set_client_verify_callback_verbose" external set_verify : context -> verify_mode list -> verify_callback option -> unit = "ocaml_ssl_ctx_set_verify" external set_verify_depth : context -> int -> unit = "ocaml_ssl_ctx_set_verify_depth" external set_client_CA_list_from_file : context -> string -> unit = "ocaml_ssl_ctx_set_client_CA_list_from_file" external set_context_alpn_protos : context -> string list -> unit = "ocaml_ssl_ctx_set_alpn_protos" external set_context_alpn_select_callback : context -> (string list -> string option) -> unit = "ocaml_ssl_ctx_set_alpn_select_callback" external version : socket -> protocol = "ocaml_ssl_version" type cipher external get_cipher : socket -> cipher = "ocaml_ssl_get_current_cipher" external get_cipher_description : cipher -> string = "ocaml_ssl_get_cipher_description" (* TODO: get_cipher_bits *) external get_cipher_name : cipher -> string = "ocaml_ssl_get_cipher_name" external get_cipher_version : cipher -> string = "ocaml_ssl_get_cipher_version" external get_certificate : socket -> certificate = "ocaml_ssl_get_certificate" external read_certificate : string -> certificate = "ocaml_ssl_read_certificate" external write_certificate : string -> certificate -> unit = "ocaml_ssl_write_certificate" external get_issuer : certificate -> string = "ocaml_ssl_get_issuer" external get_subject : certificate -> string = "ocaml_ssl_get_subject" external get_start_date : certificate -> Unix.tm = "ocaml_ssl_get_start_date" external get_expiration_date : certificate -> Unix.tm = "ocaml_ssl_get_expiration_date" external file_descr_of_socket : socket -> Unix.file_descr = "ocaml_ssl_get_file_descr" external set_client_SNI_hostname : socket -> string -> unit = "ocaml_ssl_set_client_SNI_hostname" external set_alpn_protos : socket -> string list -> unit = "ocaml_ssl_set_alpn_protos" external get_negotiated_alpn_protocol : socket -> string option = "ocaml_ssl_get_negotiated_alpn_protocol" external connect : socket -> unit = "ocaml_ssl_connect" external verify : socket -> unit = "ocaml_ssl_verify" type x509_check_flag = | Always_check_subject | No_wildcards | No_partial_wildcards | Multi_label_wildcards | Single_label_subdomains external set_hostflags : socket -> x509_check_flag list -> unit = "ocaml_ssl_set_hostflags" external set_host : socket -> string -> unit = "ocaml_ssl_set1_host" external write : socket -> Bytes.t -> int -> int -> int = "ocaml_ssl_write" external write_substring : socket -> string -> int -> int -> int = "ocaml_ssl_write" external write_bigarray : socket -> bigarray -> int -> int -> int = "ocaml_ssl_write_bigarray" external write_bigarray_blocking : socket -> bigarray -> int -> int -> int = "ocaml_ssl_write_bigarray_blocking" external read : socket -> Bytes.t -> int -> int -> int = "ocaml_ssl_read" external read_into_bigarray : socket -> bigarray -> int -> int -> int = "ocaml_ssl_read_into_bigarray" external read_into_bigarray_blocking : socket -> bigarray -> int -> int -> int = "ocaml_ssl_read_into_bigarray_blocking" external accept : socket -> unit = "ocaml_ssl_accept" external flush : socket -> unit = "ocaml_ssl_flush" external shutdown : socket -> unit = "ocaml_ssl_shutdown" let open_connection_with_context context sockaddr = let domain = match sockaddr with | Unix.ADDR_UNIX _ -> Unix.PF_UNIX | Unix.ADDR_INET(_, _) -> Unix.PF_INET in let sock = Unix.socket domain Unix.SOCK_STREAM 0 in try Unix.connect sock sockaddr; let ssl = embed_socket sock context in connect ssl; ssl with | exn -> Unix.close sock; raise exn let open_connection ssl_method sockaddr = open_connection_with_context (create_context ssl_method Client_context) sockaddr let shutdown_connection = shutdown let output_string ssl s = ignore (write_substring ssl s 0 (String.length s)) let output_char ssl c = let tmp = String.make 1 c in ignore (write_substring ssl tmp 0 1) let output_int ssl i = let tmp = Bytes.create 4 in Bytes.set tmp 0 (char_of_int (i lsr 24)); Bytes.set tmp 1 (char_of_int ((i lsr 16) land 0xff)); Bytes.set tmp 2 (char_of_int ((i lsr 8) land 0xff)); Bytes.set tmp 3 (char_of_int (i land 0xff)); if write ssl tmp 0 4 <> 4 then failwith "output_int error: all the byte were not sent" let input_string ssl = let bufsize = 1024 in let buf = Bytes.create bufsize in let ret = ref "" in let r = ref 1 in while !r <> 0 do r := read ssl buf 0 bufsize; ret := !ret ^ (Bytes.sub_string buf 0 !r) done; !ret let input_char ssl = let tmp = Bytes.create 1 in if read ssl tmp 0 1 <> 1 then raise End_of_file else Bytes.get tmp 0 let input_int ssl = let i = ref 0 in let tmp = Bytes.create 4 in ignore (read ssl tmp 0 4); i := int_of_char (Bytes.get tmp 0); i := (!i lsl 8) + int_of_char (Bytes.get tmp 1); i := (!i lsl 8) + int_of_char (Bytes.get tmp 2); i := (!i lsl 8) + int_of_char (Bytes.get tmp 3); !i ocaml-ssl-0.5.10/src/ssl.mli000066400000000000000000000455661400573131300155770ustar00rootroot00000000000000(* Copyright (C) 2003-2005 Samuel Mimram This file is part of Ocaml-ssl. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *) (** Functions for making encrypted communications using the Secure Socket Layer (SSL). These are mostly bindings to the openssl library. @author Samuel Mimram *) (** {1 Exceptions and errors} *) (** An ssl error has occured (see SSL_get_error(3ssl) for details). *) type ssl_error = | Error_none (** No error happened. This is never raised and should disappear in future versions. *) | Error_ssl | Error_want_read (** The operation did not complete; the same TLS/SSL I/O function should be called again later. *) | Error_want_write (** The operation did not complete; the same TLS/SSL I/O function should be called again later. *) | Error_want_x509_lookup (** The operation did not complete because an application callback set by [set_client_cert_cb] has asked to be called again. The TLS/SSL I/O function should be called again later. Details depend on the application. *) | Error_syscall (** Some I/O error occurred. The OpenSSL error queue may contain more information on the error. *) | Error_zero_return (** The TLS/SSL connection has been closed. If the protocol version is SSL 3.0 or TLS 1.0, this result code is returned only if a closure alert has occurred in the protocol, i.e. if the connection has been closed cleanly. Note that in this case [Error_zero_return] does not necessarily indicate that the underlying transport has been closed. *) | Error_want_connect (** The operation did not complete; the same TLS/SSL I/O function should be called again later. *) | Error_want_accept (** The operation did not complete; the same TLS/SSL I/O function should be called again later. *) type bigarray = (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t (** The SSL method could not be initalized. *) exception Method_error exception Context_error exception Cipher_error exception Diffie_hellman_error exception Ec_curve_error (** The SSL server certificate could not be initialized. *) exception Certificate_error of string (** The SSL server private key could not be intialized. *) exception Private_key_error of string (** The SSL private key does not match the certificate public key. *) exception Unmatching_keys (** The given socket is invalid. *) exception Invalid_socket (** The SSL handler could not be initialized. *) exception Handler_error (** The connection could not be made with the SSL service. *) exception Connection_error of ssl_error (** Failed to accept an SSL connection. *) exception Accept_error of ssl_error (** An error occured while reading data. *) exception Read_error of ssl_error (** An error occured while writing data. *) exception Write_error of ssl_error (** Why did the certificate verification fail? *) type verify_error = | Error_v_unable_to_get_issuer_cert (** The issuer certificate could not be found: this occurs if the issuer certificate of an untrusted certificate cannot be found.*) | Error_v_unable_to_get_ctl (** The CRL of a certificate could not be found. *) | Error_v_unable_to_decrypt_cert_signature (** The certificate signature could not be decrypted. This means that the actual signature value could not be determined rather than it not matching the expected value, this is only meaningful for RSA keys. *) | Error_v_unable_to_decrypt_CRL_signature (** The CRL signature could not be decrypted: this means that the actual signature value could not be determined rather than it not matching the expected value. Unused. *) | Error_v_unable_to_decode_issuer_public_key (** The public key in the certificate SubjectPublicKeyInfo could not be read. *) | Error_v_cert_signature_failure (** The signature of the certificate is invalid. *) | Error_v_CRL_signature_failure (** The signature of the certificate is invalid. *) | Error_v_cert_not_yet_valid (** The certificate is not yet valid: the notBefore date is after the current time. *) | Error_v_cert_has_expired (** The certificate has expired: that is the notAfter date is before the current time. *) | Error_v_CRL_not_yet_valid (** The CRL is not yet valid. *) | Error_v_CRL_has_expired (** The CRL has expired. *) | Error_v_error_in_cert_not_before_field (** The certificate notBefore field contains an invalid time. *) | Error_v_error_in_cert_not_after_field (** The certificate notAfter field contains an invalid time. *) | Error_v_error_in_CRL_last_update_field (** The CRL lastUpdate field contains an invalid time. *) | Error_v_error_in_CRL_next_update_field (** The CRL nextUpdate field contains an invalid time. *) | Error_v_out_of_mem (** An error occurred trying to allocate memory. This should never happen. *) | Error_v_depth_zero_self_signed_cert (** The passed certificate is self signed and the same certificate cannot be found in the list of trusted certificates. *) | Error_v_self_signed_cert_in_chain (** The certificate chain could be built up using the untrusted certificates but the root could not be found locally. *) | Error_v_unable_to_get_issuer_cert_locally (** The issuer certificate of a locally looked up certificate could not be found. This normally means the list of trusted certificates is not complete. *) | Error_v_unable_to_verify_leaf_signature (** No signatures could be verified because the chain contains only one certificate and it is not self signed. *) | Error_v_cert_chain_too_long (** The certificate chain length is greater than the supplied maximum depth. Unused. *) | Error_v_cert_revoked (** The certificate has been revoked. *) | Error_v_invalid_CA (** A CA certificate is invalid. Either it is not a CA or its extensions are not consistent with the supplied purpose. *) | Error_v_path_length_exceeded (** The basicConstraints pathlength parameter has been exceeded. *) | Error_v_invalid_purpose (** The supplied certificate cannot be used for the specified purpose. *) | Error_v_cert_untrusted (** The root CA is not marked as trusted for the specified purpose. *) | Error_v_cert_rejected (** The root CA is marked to reject the specified purpose. *) | Error_v_subject_issuer_mismatch (** The current candidate issuer certificate was rejected because its subject name did not match the issuer name of the current certificate. *) | Error_v_akid_skid_mismatch (** The current candidate issuer certificate was rejected because its subject key identifier was present and did not match the authority key identifier current certificate. *) | Error_v_akid_issuer_serial_mismatch (** The current candidate issuer certificate was rejected because its issuer name and serial number was present and did not match the authority key identifier of the current certificate. *) | Error_v_keyusage_no_certsign (** The current candidate issuer certificate was rejected because its keyUsage extension does not permit certificate signing. *) | Error_v_application_verification (** An application specific error. Unused. *) (** An error occured while verifying the certificate. *) exception Verify_error of verify_error (** {1 Communication} *) (** Initialize SSL functions. Should be called before calling any other function. The parameter [thread_safe] should be set to true if you use threads in you application (the same effect can achived by calling [Ssl_threads.init] first. *) val init : ?thread_safe:bool -> unit -> unit (** Retrieve a human-readable message that corresponds to the last error that occurred. *) val get_error_string : unit -> string (** Protocol used by SSL. *) type protocol = | SSLv23 (** accept all possible protocols (SSLv2 if supported by openssl, SSLv3, TLSv1, TLSv1.1, TLSv1.2, and TLSv1.3) *) | SSLv3 (** only SSL v3 protocol *) | TLSv1 (** only TLS v1 protocol *) | TLSv1_1 (** only TLS v1.1 protocol *) | TLSv1_2 (** only TLS v1.2 protocol *) | TLSv1_3 (** only TLS v1.3 protocol *) (** An SSL abstract socket. *) type socket (** {2 Threads} *) (** You should not have to use those functions. They are only here for internal use (they are needed to make the openssl library thread-safe, see the [Ssl_threads] module). *) val thread_safe : bool ref (** {2 Contexts} *) (** A context. A context should be created by a server or client once per program life-time and holds mainly default values for the SSL structures which are later created for the connections. *) type context (** Type of the context to create. *) type context_type = | Client_context (** Client connections. *) | Server_context (** Server connections. *) | Both_context (** Client and server connections. *) (** Create a context. *) val create_context : protocol -> context_type -> context (** [use_certificate ctx cert privkey] makes the context [ctx] use [cert] as * certificate's file name (in PEM format) and [privkey] as private key file * name. *) val use_certificate : context -> string -> string -> unit (** Use a certificate whose contents is given as argument (you should use instead [use_certificate] if you want to read the certificate from a file). *) val use_certificate_from_string : context -> string -> string -> unit (** Set the callback function called to get passwords for encrypted PEM files. * The callback function takes a boolean argument which indicates if it's used * for reading/decryption ([false]) or writing/encryption ([true]). *) val set_password_callback : context -> (bool -> string) -> unit (** Set the list of CAs sent to the client when requesting a client certificate. *) val set_client_CA_list_from_file : context -> string -> unit (** Verification modes (see SSL_CTX_set_verify(3)). *) type verify_mode = | Verify_peer | Verify_fail_if_no_peer_cert (** Implies [Verify_peer]. *) | Verify_client_once (** Implies [Verify_peer]. *) (** A callback function for verification. Warning: this might change in the future. *) type verify_callback (** Client's verification callback. Warning: this might change in the future. *) val client_verify_callback : verify_callback (** Set verbosity of {! client_verify_callback } *) val set_client_verify_callback_verbose : bool -> unit (** Set the verify mode and callback, see SSL_CTX_set_verify(3). * Warning: this might change in the future. *) val set_verify : context -> verify_mode list -> verify_callback option -> unit (** Set the maximum depth for the certificate chain verification that shall be allowed. *) val set_verify_depth : context -> int -> unit (** Set the list of supported ALPN protocols for negotiation to the context. *) val set_context_alpn_protos : context -> string list -> unit (** Set the callback to allow server to select the preferred protocol from client's available protocols. *) val set_context_alpn_select_callback : context -> (string list -> string option) -> unit (** {2 Ciphers} *) (** A cipher. It holds the algorithm information for a particular cipher which * are a core part of the SSL/TLS protocol.*) type cipher (** Disable all protocols from the list. * Note that [SSLv23] disables both SSLv2 and SSLv3 (as opposed to all the * protocols). * *) val disable_protocols : context -> protocol list -> unit (** Set the list of available ciphers for a context. See man ciphers(1) for the format of the string. *) val set_cipher_list : context -> string -> unit (** When choosing a cipher, use the server's preferences instead of the client * preferences. When not set, the SSL server will always follow the clients * preferences. When set, the SSLv3/TLSv1 server will choose following its * own preferences. Because of the different protocol, for SSLv2 the server * will send its list of preferences to the client and the client chooses.*) val honor_cipher_order : context -> unit (** Init DH parameters from file *) val init_dh_from_file : context -> string -> unit (** Init EC curve from curve name *) val init_ec_from_named_curve : context -> string -> unit (** Get the cipher used by a socket. *) val get_cipher : socket -> cipher (** Get a description of a cipher. *) val get_cipher_description : cipher -> string (** Get the name of a cipher. *) val get_cipher_name : cipher -> string (** Get the version of a cipher. *) val get_cipher_version : cipher -> string (** Get the version used for the connection. As per the {{:https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html} OpenSSL documentation}, should only be called after the initial handshake has been completed. Prior to that the results returned from these functions may be unreliable. @raise Failure if the version is unknown *) val version : socket -> protocol (** {2 Certificates} *) (** A certificate. *) type certificate (** [read_certificate fname] reads the certificate in the file [fname]. *) val read_certificate : string -> certificate val write_certificate : string -> certificate -> unit (** Get the certificate used by a socket. *) val get_certificate : socket -> certificate (** Get the issuer of a certificate. *) val get_issuer : certificate -> string (** Get the subject of a certificate. *) val get_subject : certificate -> string (** Get the start date of a certificate. *) val get_start_date : certificate -> Unix.tm (** Get the expiration date of a certificate. *) val get_expiration_date : certificate -> Unix.tm (** [load_verify_locations ctxt cafile capath] specifies the locations for the context [ctx], at which CA certificates for verification purposes are located. [cafile] should be the name of a CA certificates file in PEM format and [capath] should be the name of a directory which contains CA certificates in PEM format. Empty strings can be used in order not to specify on of the parameters (but not both). @raise Invalid_argument if both strings are empty or if one of the files given in arguments could not be found. *) val load_verify_locations : context -> string -> string -> unit (** Specifies that the default locations from which CA certificates are loaded should be used. Returns [true] on success. *) val set_default_verify_paths : context -> bool (** Get the verification result. *) val get_verify_result : socket -> int (** Get a human readable verification error message for the verification error Its input should be the result of calling [get_verify_result]. *) val get_verify_error_string : int -> string (** {2 Creating, connecting and closing sockets} *) (** Embed a Unix socket into an SSL socket. *) val embed_socket : Unix.file_descr -> context -> socket (** Open an SSL connection. *) val open_connection : protocol -> Unix.sockaddr -> socket (** Open an SSL connection with the specified context. *) val open_connection_with_context : context -> Unix.sockaddr -> socket (** Close an SSL connection opened with [open_connection]. *) val shutdown_connection : socket -> unit (** Set the hostname the client is attempting to connect to using the Server * Name Indication (SNI) TLS extension. *) val set_client_SNI_hostname : socket -> string -> unit (** Set the list of supported ALPN protocols for negotiation to the connection. *) val set_alpn_protos : socket -> string list -> unit (** Get the negotiated protocol from the connection. *) val get_negotiated_alpn_protocol : socket -> string option (** Connect an SSL socket. *) val connect : socket -> unit (** Accept an SSL connection. *) val accept : socket -> unit (** Flush an SSL connection. *) val flush : socket -> unit (** Close an SSL connection. *) val shutdown : socket -> unit (** {2 I/O on SSL sockets} *) (** Check the result of the verification of the X509 certificate presented by the peer, if any. Raises a [verify_error] on failure. *) val verify : socket -> unit (** Flags to specify how a certificate is matched against a given host name *) type x509_check_flag = | Always_check_subject | No_wildcards | No_partial_wildcards | Multi_label_wildcards | Single_label_subdomains (* Specify how a certificate should be matched against the host name *) val set_hostflags : socket -> x509_check_flag list -> unit (* Set the expected host name to be verified. *) val set_host : socket -> string -> unit (** Get the file descriptor associated with a socket. It is primarly useful for [select]ing on it; you should not write or read on it. *) val file_descr_of_socket : socket -> Unix.file_descr (** [read sock buf off len] receives data from a connected SSL socket. *) val read : socket -> Bytes.t -> int -> int -> int (** [read_into_bigarray sock ba off len] receives data from a connected SSL socket. This function releases the runtime while the read takes place. *) val read_into_bigarray : socket -> bigarray -> int -> int -> int (** [read_into_bigarray_blocking sock ba off len] receives data from a connected SSL socket. This function DOES NOT release the runtime while the read takes place: it must be used with nonblocking sockets. *) val read_into_bigarray_blocking : socket -> bigarray -> int -> int -> int (** [write sock buf off len] sends data over a connected SSL socket. *) val write : socket -> Bytes.t -> int -> int -> int (** [write_substring sock str off len] sends data over a connected SSL socket. *) val write_substring : socket -> string -> int -> int -> int (** [write_bigarray sock ba off len] sends data over a connected SSL socket. This function releases the runtime while the read takes place. *) val write_bigarray : socket -> bigarray -> int -> int -> int (** [write_bigarray sock ba off len] sends data over a connected SSL socket. This function DOES NOT release the runtime while the read takes place: it must be used with nonblocking sockets. *) val write_bigarray_blocking : socket -> bigarray -> int -> int -> int (** {3 High-level communication functions} *) (** Input a string on an SSL socket. *) val input_string : socket -> string (** Write a string on an SSL socket. *) val output_string : socket -> string -> unit (** Input a character on an SSL socket. *) val input_char : socket -> char (** Write a char on an SSL socket. *) val output_char : socket -> char -> unit (** Input an integer on an SSL socket. *) val input_int : socket -> int (** Write an integer on an SSL socket. *) val output_int : socket -> int -> unit ocaml-ssl-0.5.10/src/ssl_stubs.c000066400000000000000000001276531400573131300164560ustar00rootroot00000000000000/* * Copyright (C) 2003-2005 Samuel Mimram * * This file is part of Ocaml-ssl. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Libssl bindings for OCaml. * * @author Samuel Mimram */ /* * WARNING: because of thread callbacks, all ssl functions should be in * blocking sections. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ocaml_ssl.h" #ifdef WIN32 #include #else #include #endif static int client_verify_callback(int, X509_STORE_CTX *); static DH *load_dh_param(const char *dhfile); /******************* * Data structures * *******************/ /* Contexts */ #define Ctx_val(v) (*((SSL_CTX**)Data_custom_val(v))) static void finalize_ctx(value block) { SSL_CTX *ctx = Ctx_val(block); SSL_CTX_free(ctx); } static struct custom_operations ctx_ops = { "ocaml_ssl_ctx", finalize_ctx, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default }; /* Sockets */ #define SSL_val(v) (*((SSL**)Data_custom_val(v))) static void finalize_ssl_socket(value block) { SSL *ssl = SSL_val(block); SSL_free(ssl); } static struct custom_operations socket_ops = { "ocaml_ssl_socket", finalize_ssl_socket, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default }; /* Option types */ #define Val_none Val_int(0) static value Val_some(value v) { CAMLparam1(v); CAMLlocal1(some); some = caml_alloc(1, 0); Store_field(some, 0, v); CAMLreturn(some); } /****************** * Initialization * ******************/ #ifdef WIN32 struct CRYPTO_dynlock_value { HANDLE mutex; }; static HANDLE *mutex_buf = NULL; static void locking_function(int mode, int n, const char *file, int line) { if (mode & CRYPTO_LOCK) WaitForSingleObject(mutex_buf[n], INFINITE); else ReleaseMutex(mutex_buf[n]); } static struct CRYPTO_dynlock_value *dyn_create_function(const char *file, int line) { struct CRYPTO_dynlock_value *value; value = malloc(sizeof(struct CRYPTO_dynlock_value)); if (!value) return NULL; if (!(value->mutex = CreateMutex(NULL, FALSE, NULL))) { free(value); return NULL; } return value; } static void dyn_lock_function(int mode, struct CRYPTO_dynlock_value *l, const char *file, int line) { if (mode & CRYPTO_LOCK) WaitForSingleObject(l->mutex, INFINITE); else ReleaseMutex(l->mutex); } static void dyn_destroy_function(struct CRYPTO_dynlock_value *l, const char *file, int line) { CloseHandle(l->mutex); free(l); } #else struct CRYPTO_dynlock_value { pthread_mutex_t mutex; }; static pthread_mutex_t *mutex_buf = NULL; static void locking_function(int mode, int n, const char *file, int line) { if (mode & CRYPTO_LOCK) pthread_mutex_lock(&mutex_buf[n]); else pthread_mutex_unlock(&mutex_buf[n]); } static unsigned long id_function(void) { return ((unsigned long) pthread_self()); } static struct CRYPTO_dynlock_value *dyn_create_function(const char *file, int line) { struct CRYPTO_dynlock_value *value; value = malloc(sizeof(struct CRYPTO_dynlock_value)); if (!value) return NULL; pthread_mutex_init(&value->mutex, NULL); return value; } static void dyn_lock_function(int mode, struct CRYPTO_dynlock_value *l, const char *file, int line) { if (mode & CRYPTO_LOCK) pthread_mutex_lock(&l->mutex); else pthread_mutex_unlock(&l->mutex); } static void dyn_destroy_function(struct CRYPTO_dynlock_value *l, const char *file, int line) { pthread_mutex_destroy(&l->mutex); free(l); } #endif CAMLprim value ocaml_ssl_init(value use_threads) { int i; SSL_library_init(); SSL_load_error_strings(); if(Int_val(use_threads)) { #ifdef WIN32 mutex_buf = malloc(CRYPTO_num_locks() * sizeof(HANDLE)); #else mutex_buf = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t)); #endif assert(mutex_buf); for (i = 0; i < CRYPTO_num_locks(); i++) #ifdef WIN32 mutex_buf[i] = CreateMutex(NULL, FALSE, NULL); #else pthread_mutex_init(&mutex_buf[i], NULL); #endif CRYPTO_set_locking_callback(locking_function); #ifndef WIN32 /* Windows does not require id_function, see threads(3) */ CRYPTO_set_id_callback(id_function); #endif CRYPTO_set_dynlock_create_callback(dyn_create_function); CRYPTO_set_dynlock_lock_callback(dyn_lock_function); CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function); } return Val_unit; } CAMLprim value ocaml_ssl_get_error_string(value unit) { char buf[256]; ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); return caml_copy_string(buf); } /***************************** * Context-related functions * *****************************/ static int protocol_flags[] = { SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3, SSL_OP_NO_SSLv3, SSL_OP_NO_TLSv1, #ifdef HAVE_TLS11 SSL_OP_NO_TLSv1_1 #else 0 /* not supported, nothing to disable */ #endif , #ifdef HAVE_TLS12 SSL_OP_NO_TLSv1_2 #else 0 /* not supported ,nothing to disable */ #endif , #ifdef HAVE_TLS13 SSL_OP_NO_TLSv1_3 #else 0 /* not supported, nothing to disable */ #endif }; static const SSL_METHOD *get_method(int protocol, int type) { const SSL_METHOD *method = NULL; caml_enter_blocking_section(); switch (protocol) { case 0: switch (type) { case 0: method = SSLv23_client_method(); break; case 1: method = SSLv23_server_method(); break; case 2: method = SSLv23_method(); break; } break; #ifndef OPENSSL_NO_SSL3 case 1: switch (type) { case 0: method = SSLv3_client_method(); break; case 1: method = SSLv3_server_method(); break; case 2: method = SSLv3_method(); break; } break; #endif case 2: switch (type) { case 0: method = TLSv1_client_method(); break; case 1: method = TLSv1_server_method(); break; case 2: method = TLSv1_method(); break; } break; case 3: #ifdef HAVE_TLS11 switch (type) { case 0: method = TLSv1_1_client_method(); break; case 1: method = TLSv1_1_server_method(); break; case 2: method = TLSv1_1_method(); break; } #endif break; case 4: #ifdef HAVE_TLS12 switch (type) { case 0: method = TLSv1_2_client_method(); break; case 1: method = TLSv1_2_server_method(); break; case 2: method = TLSv1_2_method(); break; } #endif break; case 5: #ifdef HAVE_TLS13 switch (type) { case 0: method = TLS_client_method(); break; case 1: method = TLS_server_method(); break; case 2: method = TLS_method(); break; } #endif break; default: caml_leave_blocking_section(); caml_invalid_argument("Unknown method (this should not have happened, please report)."); break; } caml_leave_blocking_section(); if (method == NULL) caml_raise_constant(*caml_named_value("ssl_exn_method_error")); return method; } CAMLprim value ocaml_ssl_create_context(value protocol, value type) { value block; SSL_CTX *ctx; const SSL_METHOD *method = get_method(Int_val(protocol), Int_val(type)); caml_enter_blocking_section(); ctx = SSL_CTX_new(method); if (!ctx) { caml_leave_blocking_section(); caml_raise_constant(*caml_named_value("ssl_exn_context_error")); } /* In non-blocking mode, accept a buffer with a different address on a write retry (since the GC may need to move it). In blocking mode, hide SSL_ERROR_WANT_(READ|WRITE) from us. */ SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY); caml_leave_blocking_section(); block = caml_alloc_custom(&ctx_ops, sizeof(SSL_CTX*), 0, 1); Ctx_val(block) = ctx; return block; } CAMLprim value ocaml_ssl_ctx_use_certificate(value context, value cert, value privkey) { CAMLparam3(context, cert, privkey); SSL_CTX *ctx = Ctx_val(context); char *cert_name = String_val(cert); char *privkey_name = String_val(privkey); char buf[256]; caml_enter_blocking_section(); if (SSL_CTX_use_certificate_chain_file(ctx, cert_name) <= 0) { ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); caml_leave_blocking_section(); caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string(buf)); } if (SSL_CTX_use_PrivateKey_file(ctx, privkey_name, SSL_FILETYPE_PEM) <= 0) { ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); caml_leave_blocking_section(); caml_raise_with_arg(*caml_named_value("ssl_exn_private_key_error"), caml_copy_string(buf)); } if (!SSL_CTX_check_private_key(ctx)) { caml_leave_blocking_section(); caml_raise_constant(*caml_named_value("ssl_exn_unmatching_keys")); } caml_leave_blocking_section(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_ctx_use_certificate_from_string(value context, value cert, value privkey) { CAMLparam3(context, cert, privkey); SSL_CTX *ctx = Ctx_val(context); char *cert_data = String_val(cert); int cert_data_length = caml_string_length(cert); char *privkey_data = String_val(privkey); int privkey_data_length = caml_string_length(privkey); char buf[256]; X509 *x509_cert = NULL; RSA *rsa = NULL; BIO *cbio, *kbio; cbio = BIO_new_mem_buf((void*)cert_data, cert_data_length); x509_cert = PEM_read_bio_X509(cbio, NULL, 0, NULL); if (NULL == x509_cert || SSL_CTX_use_certificate(ctx, x509_cert) <= 0) { ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string(buf)); } kbio = BIO_new_mem_buf((void*)privkey_data, privkey_data_length); rsa = PEM_read_bio_RSAPrivateKey(kbio, NULL, 0, NULL); if (NULL == rsa || SSL_CTX_use_RSAPrivateKey(ctx, rsa) <= 0) { ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); caml_raise_with_arg(*caml_named_value("ssl_exn_private_key_error"), caml_copy_string(buf)); } if (!SSL_CTX_check_private_key(ctx)) { caml_raise_constant(*caml_named_value("ssl_exn_unmatching_keys")); } CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_get_verify_result(value socket) { CAMLparam1(socket); int ans; SSL *ssl = SSL_val(socket); caml_enter_blocking_section(); ans = SSL_get_verify_result(ssl); caml_leave_blocking_section(); CAMLreturn(Val_int(ans)); } CAMLprim value ocaml_ssl_get_verify_error_string(value verrn) { int errn = Int_val(verrn); const char *error_string; caml_enter_blocking_section(); error_string = X509_verify_cert_error_string(errn); caml_leave_blocking_section(); return caml_copy_string(error_string); } CAMLprim value ocaml_ssl_get_client_verify_callback_ptr(value unit) { return (value)client_verify_callback; } static int client_verify_callback_verbose = 1; CAMLprim value ocaml_ssl_set_client_verify_callback_verbose(value verbose) { CAMLparam1(verbose); client_verify_callback_verbose = Bool_val(verbose); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_ctx_set_verify(value context, value vmode, value vcallback) { CAMLparam3(context, vmode, vcallback); SSL_CTX *ctx = Ctx_val(context); int mode = 0; value mode_tl = vmode; int (*callback) (int, X509_STORE_CTX*) = NULL; if (Is_long(vmode)) mode = SSL_VERIFY_NONE; while (Is_block(mode_tl)) { switch(Int_val(Field(mode_tl, 0))) { case 0: mode |= SSL_VERIFY_PEER; break; case 1: mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_PEER; break; case 2: mode |= SSL_VERIFY_CLIENT_ONCE | SSL_VERIFY_PEER; break; default: caml_invalid_argument("mode"); } mode_tl = Field(mode_tl, 1); } if (Is_block(vcallback)) callback = (int(*) (int, X509_STORE_CTX*))Field(vcallback, 0); caml_enter_blocking_section(); SSL_CTX_set_verify(ctx, mode, callback); caml_leave_blocking_section(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_ctx_set_verify_depth(value context, value vdepth) { SSL_CTX *ctx = Ctx_val(context); int depth = Int_val(vdepth); if (depth < 0) caml_invalid_argument("depth"); caml_enter_blocking_section(); SSL_CTX_set_verify_depth(ctx, depth); caml_leave_blocking_section(); return Val_unit; } CAMLprim value ocaml_ssl_ctx_set_client_CA_list_from_file(value context, value vfilename) { CAMLparam2(context, vfilename); SSL_CTX *ctx = Ctx_val(context); char *filename = String_val(vfilename); STACK_OF(X509_NAME) *cert_names; char buf[256]; caml_enter_blocking_section(); cert_names = SSL_load_client_CA_file(filename); if (cert_names != 0) SSL_CTX_set_client_CA_list(ctx, cert_names); else { ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); caml_leave_blocking_section(); caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string(buf)); } caml_leave_blocking_section(); CAMLreturn(Val_unit); } #ifdef HAVE_ALPN static int get_alpn_buffer_length(value vprotos) { value protos_tl = vprotos; int total_len = 0; while (protos_tl != Val_emptylist) { total_len += caml_string_length(Field(protos_tl, 0)) + 1; protos_tl = Field(protos_tl, 1); } return total_len; } static void build_alpn_protocol_buffer(value vprotos, unsigned char *protos) { int proto_idx = 0; while (vprotos != Val_emptylist) { value head = Field(vprotos, 0); int len = caml_string_length(head); protos[proto_idx++] = len; int i; for (i = 0; i < len; i++) protos[proto_idx++] = Byte_u(head, i); vprotos = Field(vprotos, 1); } } CAMLprim value ocaml_ssl_ctx_set_alpn_protos(value context, value vprotos) { CAMLparam2(context, vprotos); SSL_CTX *ctx = Ctx_val(context); int total_len = get_alpn_buffer_length(vprotos); unsigned char protos[total_len]; build_alpn_protocol_buffer(vprotos, protos); caml_enter_blocking_section(); SSL_CTX_set_alpn_protos(ctx, protos, sizeof(protos)); caml_leave_blocking_section(); CAMLreturn(Val_unit); } static value build_alpn_protocol_list(const unsigned char *protocol_buffer, unsigned int len) { CAMLparam0(); CAMLlocal3(protocol_list, current, tail); int idx = 0; protocol_list = Val_emptylist; while (idx < len) { int proto_len = (int) protocol_buffer[idx++]; char proto[proto_len + 1]; int i; for (i = 0; i < proto_len; i++) proto[i] = (char) protocol_buffer[idx++]; proto[proto_len] = '\0'; tail = caml_alloc(2, 0); Store_field(tail, 0, caml_copy_string(proto)); Store_field(tail, 1, Val_emptylist); if (protocol_list == Val_emptylist) protocol_list = tail; else Store_field(current, 1, tail); current = tail; } CAMLreturn(protocol_list); } static int alpn_select_cb(SSL *ssl, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { CAMLparam0(); CAMLlocal3(protocol_list, selected_protocol, selected_protocol_opt); int len; caml_leave_blocking_section(); protocol_list = build_alpn_protocol_list(in, inlen); selected_protocol_opt = caml_callback(*((value*)arg), protocol_list); if(selected_protocol_opt == Val_none) { caml_enter_blocking_section(); return SSL_TLSEXT_ERR_NOACK; } selected_protocol = Field(selected_protocol_opt, 0); len = caml_string_length(selected_protocol); *out = String_val(selected_protocol); *outlen = len; caml_enter_blocking_section(); return SSL_TLSEXT_ERR_OK; } CAMLprim value ocaml_ssl_ctx_set_alpn_select_callback(value context, value cb) { CAMLparam2(context, cb); SSL_CTX *ctx = Ctx_val(context); value *select_cb; select_cb = malloc(sizeof(value)); *select_cb = cb; caml_register_global_root(select_cb); caml_enter_blocking_section(); SSL_CTX_set_alpn_select_cb(ctx, alpn_select_cb, select_cb); caml_leave_blocking_section(); CAMLreturn(Val_unit); } #else CAMLprim value ocaml_ssl_ctx_set_alpn_protos(value context, value vprotos) { CAMLparam2(context, vprotos); caml_raise_constant(*caml_named_value("ssl_exn_method_error")); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_ctx_set_alpn_select_callback(value context, value cb) { CAMLparam2(context, cb); caml_raise_constant(*caml_named_value("ssl_exn_method_error")); CAMLreturn(Val_unit); } #endif static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) { value s; int len; caml_leave_blocking_section(); s = caml_callback(*((value*)userdata), Val_int(rwflag)); len = caml_string_length(s); assert(len <= size); memcpy(buf, String_val(s), len); caml_enter_blocking_section(); return len; } CAMLprim value ocaml_ssl_ctx_set_default_passwd_cb(value context, value cb) { CAMLparam2(context, cb); SSL_CTX *ctx = Ctx_val(context); value *pcb; /* TODO: this never gets freed or even unregistered */ pcb = malloc(sizeof(value)); *pcb = cb; caml_register_global_root(pcb); caml_enter_blocking_section(); SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb); SSL_CTX_set_default_passwd_cb_userdata(ctx, pcb); caml_leave_blocking_section(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_ctx_honor_cipher_order(value context) { CAMLparam1(context); SSL_CTX *ctx = Ctx_val(context); SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); CAMLreturn(Val_unit); } /**************************** * Cipher-related functions * ****************************/ CAMLprim value ocaml_ssl_ctx_set_cipher_list(value context, value ciphers_string) { CAMLparam2(context, ciphers_string); SSL_CTX *ctx = Ctx_val(context); char *ciphers = String_val(ciphers_string); if(*ciphers == 0) caml_raise_constant(*caml_named_value("ssl_exn_cipher_error")); caml_enter_blocking_section(); if(SSL_CTX_set_cipher_list(ctx, ciphers) != 1) { caml_leave_blocking_section(); caml_raise_constant(*caml_named_value("ssl_exn_cipher_error")); } caml_leave_blocking_section(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_disable_protocols(value context, value protocol_list) { CAMLparam2(context, protocol_list); SSL_CTX *ctx = Ctx_val(context); int flags = caml_convert_flag_list(protocol_list, protocol_flags); caml_enter_blocking_section(); SSL_CTX_set_options(ctx, flags); caml_leave_blocking_section(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_version(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); int version; int ret; caml_enter_blocking_section(); version = SSL_version(ssl); caml_leave_blocking_section(); switch(version) { case SSL3_VERSION: ret = 1; break; case TLS1_VERSION: ret = 2; break; case TLS1_1_VERSION: ret = 3; break; case TLS1_2_VERSION: ret = 4; break; case TLS1_3_VERSION: ret = 5; break; default: caml_failwith("Ssl.version"); } CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_ssl_get_current_cipher(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); caml_enter_blocking_section(); SSL_CIPHER *cipher = (SSL_CIPHER*)SSL_get_current_cipher(ssl); caml_leave_blocking_section(); if (!cipher) caml_raise_constant(*caml_named_value("ssl_exn_cipher_error")); CAMLreturn((value)cipher); } CAMLprim value ocaml_ssl_get_cipher_description(value vcipher) { char buf[1024]; SSL_CIPHER *cipher = (SSL_CIPHER*)vcipher; caml_enter_blocking_section(); SSL_CIPHER_description(cipher, buf, 1024); caml_leave_blocking_section(); return caml_copy_string(buf); } CAMLprim value ocaml_ssl_get_cipher_name(value vcipher) { const char *name; SSL_CIPHER *cipher = (SSL_CIPHER*)vcipher; caml_enter_blocking_section(); name = SSL_CIPHER_get_name(cipher); caml_leave_blocking_section(); return caml_copy_string(name); } CAMLprim value ocaml_ssl_get_cipher_version(value vcipher) { const char *version; SSL_CIPHER *cipher = (SSL_CIPHER*)vcipher; caml_enter_blocking_section(); version = SSL_CIPHER_get_version(cipher); caml_leave_blocking_section(); return caml_copy_string(version); } CAMLprim value ocaml_ssl_ctx_init_dh_from_file(value context, value dh_file_path) { CAMLparam2(context, dh_file_path); DH *dh = NULL; SSL_CTX *ctx = Ctx_val(context); char *dh_cfile_path = String_val(dh_file_path); if(*dh_cfile_path == 0) caml_raise_constant(*caml_named_value("ssl_exn_diffie_hellman_error")); dh = load_dh_param(dh_cfile_path); caml_enter_blocking_section(); if (dh != NULL){ if(SSL_CTX_set_tmp_dh(ctx,dh) != 1){ caml_leave_blocking_section(); caml_raise_constant(*caml_named_value("ssl_exn_diffie_hellman_error")); } SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE); caml_leave_blocking_section(); DH_free(dh); } else{ caml_leave_blocking_section(); caml_raise_constant(*caml_named_value("ssl_exn_diffie_hellman_error")); } CAMLreturn(Val_unit); } #ifdef HAVE_EC CAMLprim value ocaml_ssl_ctx_init_ec_from_named_curve(value context, value curve_name) { CAMLparam2(context, curve_name); EC_KEY *ecdh = NULL; int nid = 0; SSL_CTX *ctx = Ctx_val(context); char *ec_curve_name = String_val(curve_name); if(*ec_curve_name == 0) caml_raise_constant(*caml_named_value("ssl_exn_ec_curve_error")); nid = OBJ_sn2nid(ec_curve_name); if(nid == 0){ caml_raise_constant(*caml_named_value("ssl_exn_ec_curve_error")); } caml_enter_blocking_section(); ecdh = EC_KEY_new_by_curve_name(nid); if(ecdh != NULL){ if(SSL_CTX_set_tmp_ecdh(ctx,ecdh) != 1){ caml_leave_blocking_section(); caml_raise_constant(*caml_named_value("ssl_exn_ec_curve_error")); } SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE); caml_leave_blocking_section(); EC_KEY_free(ecdh); } else{ caml_leave_blocking_section(); caml_raise_constant(*caml_named_value("ssl_exn_ec_curve_error")); } CAMLreturn(Val_unit); } #else CAMLprim value ocaml_ssl_ctx_init_ec_from_named_curve(value context, value curve_name) { CAMLparam2(context, curve_name); caml_raise_constant(*caml_named_value("ssl_exn_ec_curve_error")); CAMLreturn(Val_unit); } #endif /********************************* * Certificate-related functions * *********************************/ #define Cert_val(v) (*((X509**)Data_custom_val(v))) static void finalize_cert(value block) { X509 *cert = Cert_val(block); X509_free(cert); } static struct custom_operations cert_ops = { "ocaml_ssl_cert", finalize_cert, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default }; CAMLprim value ocaml_ssl_read_certificate(value vfilename) { value block; char *filename = String_val(vfilename); X509 *cert = NULL; FILE *fh = NULL; char buf[256]; if((fh = fopen(filename, "r")) == NULL) caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string("couldn't open certificate file")); caml_enter_blocking_section(); if((PEM_read_X509(fh, &cert, 0, 0)) == NULL) { fclose(fh); ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); caml_leave_blocking_section(); caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string(buf)); } fclose(fh); caml_leave_blocking_section(); block = caml_alloc_custom(&cert_ops, sizeof(X509*), 0, 1); Cert_val(block) = cert; return block; } CAMLprim value ocaml_ssl_write_certificate(value vfilename, value certificate) { CAMLparam2(vfilename, certificate); char *filename = String_val(vfilename); X509 *cert = Cert_val(certificate); FILE *fh = NULL; char buf[256]; if((fh = fopen(filename, "w")) == NULL) caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string("couldn't open certificate file")); caml_enter_blocking_section(); if(PEM_write_X509(fh, cert) == 0) { fclose(fh); ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); caml_leave_blocking_section(); caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string(buf)); } fclose(fh); caml_leave_blocking_section(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_get_certificate(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); char buf[256]; caml_enter_blocking_section(); X509 *cert = SSL_get_peer_certificate(ssl); caml_leave_blocking_section(); if (!cert) { ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string(buf)); } CAMLlocal1(block); block = caml_alloc_final(2, finalize_cert, 0, 1); (*((X509 **) Data_custom_val(block))) = cert; CAMLreturn(block); } CAMLprim value ocaml_ssl_get_issuer(value certificate) { CAMLparam1(certificate); X509 *cert = Cert_val(certificate); caml_enter_blocking_section(); char *issuer = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0); caml_leave_blocking_section(); if (!issuer) caml_raise_not_found (); CAMLreturn(caml_copy_string(issuer)); } CAMLprim value ocaml_ssl_get_subject(value certificate) { CAMLparam1(certificate); X509 *cert = Cert_val(certificate); caml_enter_blocking_section(); char *subject = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0); caml_leave_blocking_section(); if (subject == NULL) caml_raise_not_found (); CAMLreturn(caml_copy_string(subject)); } static value alloc_tm(struct tm *tm) { value res; res = caml_alloc_small(9, 0); Field(res,0) = Val_int(tm->tm_sec); Field(res,1) = Val_int(tm->tm_min); Field(res,2) = Val_int(tm->tm_hour); Field(res,3) = Val_int(tm->tm_mday); Field(res,4) = Val_int(tm->tm_mon); Field(res,5) = Val_int(tm->tm_year); Field(res,6) = Val_int(tm->tm_wday); Field(res,7) = Val_int(tm->tm_yday); Field(res,8) = tm->tm_isdst ? Val_true : Val_false; return res; } CAMLprim value ocaml_ssl_get_start_date(value certificate) { CAMLparam1(certificate); X509 *cert = Cert_val(certificate); struct tm t; caml_enter_blocking_section(); ASN1_TIME_to_tm(X509_get0_notBefore(cert), &t); caml_leave_blocking_section(); CAMLreturn(alloc_tm(&t)); } CAMLprim value ocaml_ssl_get_expiration_date(value certificate) { CAMLparam1(certificate); X509 *cert = Cert_val(certificate); struct tm t; caml_enter_blocking_section(); ASN1_TIME_to_tm(X509_get0_notAfter(cert), &t); caml_leave_blocking_section(); CAMLreturn(alloc_tm(&t)); } CAMLprim value ocaml_ssl_ctx_load_verify_locations(value context, value ca_file, value ca_path) { CAMLparam3(context, ca_file, ca_path); SSL_CTX *ctx = Ctx_val(context); char *CAfile = String_val(ca_file); char *CApath = String_val(ca_path); if(*CAfile == 0) CAfile = NULL; if(*CApath == 0) CApath = NULL; caml_enter_blocking_section(); if(SSL_CTX_load_verify_locations(ctx, CAfile, CApath) != 1) { caml_leave_blocking_section(); caml_invalid_argument("cafile or capath"); } caml_leave_blocking_section(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_ctx_set_default_verify_paths(value context) { CAMLparam1(context); int ret; SSL_CTX *ctx = Ctx_val(context); caml_enter_blocking_section(); ret = SSL_CTX_set_default_verify_paths(ctx); caml_leave_blocking_section(); CAMLreturn(Val_bool(ret)); } /************************* * Operations on sockets * *************************/ CAMLprim value ocaml_ssl_get_file_descr(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); int fd; caml_enter_blocking_section(); fd = SSL_get_fd(ssl); caml_leave_blocking_section(); CAMLreturn(Val_int(fd)); } CAMLprim value ocaml_ssl_embed_socket(value socket_, value context) { CAMLparam1(context); CAMLlocal1(block); #ifdef Socket_val SOCKET socket = Socket_val(socket_); #else int socket = Int_val(socket_); #endif SSL_CTX *ctx = Ctx_val(context); SSL *ssl; block = caml_alloc_custom(&socket_ops, sizeof(SSL*), 0, 1); if (socket < 0) caml_raise_constant(*caml_named_value("ssl_exn_invalid_socket")); caml_enter_blocking_section(); ssl = SSL_new(ctx); if (!ssl) { caml_leave_blocking_section(); caml_raise_constant(*caml_named_value("ssl_exn_handler_error")); } SSL_set_fd(ssl, socket); caml_leave_blocking_section(); SSL_val(block) = ssl; CAMLreturn(block); } #ifdef HAVE_SNI CAMLprim value ocaml_ssl_set_client_SNI_hostname(value socket, value vhostname) { CAMLparam2(socket, vhostname); SSL *ssl = SSL_val(socket); char *hostname = String_val(vhostname); caml_enter_blocking_section(); SSL_set_tlsext_host_name(ssl, hostname); caml_leave_blocking_section(); CAMLreturn(Val_unit); } #else CAMLprim value ocaml_ssl_set_client_SNI_hostname(value socket, value vhostname) { CAMLparam2(socket, vhostname); caml_raise_constant(*caml_named_value("ssl_exn_method_error")); CAMLreturn(Val_unit); } #endif #ifdef HAVE_ALPN CAMLprim value ocaml_ssl_set_alpn_protos(value socket, value vprotos) { CAMLparam2(socket, vprotos); SSL *ssl = SSL_val(socket); int total_len = get_alpn_buffer_length(vprotos); unsigned char protos[total_len]; build_alpn_protocol_buffer(vprotos, protos); caml_enter_blocking_section(); SSL_set_alpn_protos(ssl, protos, sizeof(protos)); caml_leave_blocking_section(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_get_negotiated_alpn_protocol(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); const unsigned char *data; unsigned int len; SSL_get0_alpn_selected(ssl, &data, &len); if (len == 0) CAMLreturn(Val_none); /* Note: we use the implementation `caml_alloc_initialized_string` (which * unfortunately requires OCaml >= 4.06) instead of `copy_string` here * because the selected protocol in `data` is not NULL-terminated. * * From https://www.openssl.org/docs/man1.0.2/man3/SSL_get0_alpn_selected.html: * SSL_get0_alpn_selected() returns a pointer to the selected protocol in * data with length len. It is not NUL-terminated. data is set to NULL and * len is set to 0 if no protocol has been selected. data must not be * freed. */ value proto = caml_alloc_string (len); memcpy((char *)String_val(proto), (const char*)data, len); CAMLreturn(Val_some(proto)); } #else CAMLprim value ocaml_ssl_set_alpn_protos(value socket, value vprotos) { CAMLparam2(socket, vprotos); caml_raise_constant(*caml_named_value("ssl_exn_method_error")); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_get_negotiated_alpn_protocol(value socket) { CAMLparam1(socket); caml_raise_constant(*caml_named_value("ssl_exn_method_error")); CAMLreturn(Val_unit); } #endif CAMLprim value ocaml_ssl_connect(value socket) { CAMLparam1(socket); int ret, err; SSL *ssl = SSL_val(socket); caml_enter_blocking_section(); ret = SSL_connect(ssl); err = SSL_get_error(ssl, ret); caml_leave_blocking_section(); if (err != SSL_ERROR_NONE) caml_raise_with_arg(*caml_named_value("ssl_exn_connection_error"), Val_int(err)); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_verify(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); long ans; caml_enter_blocking_section(); ans = SSL_get_verify_result(ssl); caml_leave_blocking_section(); if (ans != 0) { if (2 <= ans && ans <= 32) caml_raise_with_arg(*caml_named_value("ssl_exn_verify_error"), Val_int(ans - 2)); /* Not very nice, but simple */ else caml_raise_with_arg(*caml_named_value("ssl_exn_verify_error"), Val_int(31)); } CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_set_hostflags(value socket, value flag_lst) { CAMLparam2(socket, flag_lst); SSL *ssl = SSL_val(socket); unsigned int flags = 0; while (Is_block(flag_lst)) { switch(Int_val(Field(flag_lst, 0))) { case 0: flags |= X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT; break; case 1: flags |= X509_CHECK_FLAG_NO_WILDCARDS; break; case 2: flags |= X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS; break; case 3: flags |= X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS; break; case 4: flags |= X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS; break; default: caml_invalid_argument("flags"); } flag_lst = Field(flag_lst, 1); } caml_enter_blocking_section(); X509_VERIFY_PARAM_set_hostflags(SSL_get0_param(ssl), flags); caml_leave_blocking_section(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_set1_host(value socket, value host) { CAMLparam2(socket, host); SSL *ssl = SSL_val(socket); const char *hostname = String_val (host); caml_enter_blocking_section(); X509_VERIFY_PARAM_set1_host (SSL_get0_param(ssl), hostname, 0); caml_leave_blocking_section(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_write(value socket, value buffer, value start, value length) { CAMLparam2(socket, buffer); int ret, err; int buflen = Int_val(length); char *buf = malloc(buflen); SSL *ssl = SSL_val(socket); if (Int_val(start) + Int_val(length) > caml_string_length(buffer)) caml_invalid_argument("Buffer too short."); memmove(buf, (char*)String_val(buffer) + Int_val(start), buflen); caml_enter_blocking_section(); ERR_clear_error(); ret = SSL_write(ssl, buf, buflen); err = SSL_get_error(ssl, ret); caml_leave_blocking_section(); free(buf); if (err != SSL_ERROR_NONE) caml_raise_with_arg(*caml_named_value("ssl_exn_write_error"), Val_int(err)); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_ssl_write_bigarray(value socket, value buffer, value start, value length) { CAMLparam2(socket, buffer); int ret, err; SSL *ssl = SSL_val(socket); struct caml_ba_array *ba = Caml_ba_array_val(buffer); char *buf = ((char *)ba->data) + Int_val(start); if(Int_val(start) < 0) caml_invalid_argument("Ssl.write_bigarray: negative offset"); if(Int_val(length) < 0) caml_invalid_argument("Ssl.write_bigarray: negative length"); if (Int_val(start) + Int_val(length) > ba->dim[0]) caml_invalid_argument("Ssl.write_bigarray: buffer too short."); caml_enter_blocking_section(); ERR_clear_error(); ret = SSL_write(ssl, buf, Int_val(length)); err = SSL_get_error(ssl, ret); caml_leave_blocking_section(); if (err != SSL_ERROR_NONE) caml_raise_with_arg(*caml_named_value("ssl_exn_write_error"), Val_int(err)); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_ssl_write_bigarray_blocking(value socket, value buffer, value start, value length) { CAMLparam2(socket, buffer); int ret, err; SSL *ssl = SSL_val(socket); struct caml_ba_array *ba = Caml_ba_array_val(buffer); char *buf = ((char *)ba->data) + Int_val(start); if(Int_val(start) < 0) caml_invalid_argument("Ssl.write_bigarray_blocking: negative offset"); if(Int_val(length) < 0) caml_invalid_argument("Ssl.write_bigarray_blocking: negative length"); if (Int_val(start) + Int_val(length) > ba->dim[0]) caml_invalid_argument("Ssl.write_bigarray: buffer too short."); ERR_clear_error(); ret = SSL_write(ssl, buf, Int_val(length)); err = SSL_get_error(ssl, ret); if (err != SSL_ERROR_NONE) caml_raise_with_arg(*caml_named_value("ssl_exn_write_error"), Val_int(err)); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_ssl_read(value socket, value buffer, value start, value length) { CAMLparam2(socket, buffer); int ret, err; int buflen = Int_val(length); char *buf = malloc(buflen); SSL *ssl = SSL_val(socket); if (Int_val(start) + Int_val(length) > caml_string_length(buffer)) caml_invalid_argument("Buffer too short."); caml_enter_blocking_section(); ERR_clear_error(); ret = SSL_read(ssl, buf, buflen); err = SSL_get_error(ssl, ret); caml_leave_blocking_section(); memmove(((char*)String_val(buffer)) + Int_val(start), buf, buflen); free(buf); if (err != SSL_ERROR_NONE) caml_raise_with_arg(*caml_named_value("ssl_exn_read_error"), Val_int(err)); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_ssl_read_into_bigarray(value socket, value buffer, value start, value length) { CAMLparam2(socket, buffer); int ret, err; struct caml_ba_array *ba = Caml_ba_array_val(buffer); char *buf = ((char *)ba->data) + Int_val(start); SSL *ssl = SSL_val(socket); if(Int_val(start) < 0) caml_invalid_argument("Ssl.read_into_bigarray: negative offset"); if(Int_val(length) < 0) caml_invalid_argument("Ssl.read_into_bigarray: negative length"); if (Int_val(start) + Int_val(length) > ba->dim[0]) caml_invalid_argument("Ssl.read_into_bigarray: buffer too short."); caml_enter_blocking_section(); ERR_clear_error(); ret = SSL_read(ssl, buf, Int_val(length)); err = SSL_get_error(ssl, ret); caml_leave_blocking_section(); if (err != SSL_ERROR_NONE) caml_raise_with_arg(*caml_named_value("ssl_exn_read_error"), Val_int(err)); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_ssl_read_into_bigarray_blocking(value socket, value buffer, value start, value length) { CAMLparam2(socket, buffer); int ret, err; struct caml_ba_array *ba = Caml_ba_array_val(buffer); char *buf = ((char *)ba->data) + Int_val(start); SSL *ssl = SSL_val(socket); if(Int_val(start) < 0) caml_invalid_argument("Ssl.read_into_bigarray: negative offset"); if(Int_val(length) < 0) caml_invalid_argument("Ssl.read_into_bigarray: negative length"); if (Int_val(start) + Int_val(length) > ba->dim[0]) caml_invalid_argument("Ssl.read_into_bigarray: buffer too short."); ERR_clear_error(); ret = SSL_read(ssl, buf, Int_val(length)); err = SSL_get_error(ssl, ret); if (err != SSL_ERROR_NONE) caml_raise_with_arg(*caml_named_value("ssl_exn_read_error"), Val_int(err)); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_ssl_accept(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); int ret, err; caml_enter_blocking_section(); ERR_clear_error(); ret = SSL_accept(ssl); err = SSL_get_error(ssl, ret); caml_leave_blocking_section(); if (err != SSL_ERROR_NONE) caml_raise_with_arg(*caml_named_value("ssl_exn_accept_error"), Val_int(err)); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_flush(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); BIO *bio; caml_enter_blocking_section(); bio = SSL_get_wbio(ssl); if(bio) { /* TODO: raise an error */ assert(BIO_flush(bio) == 1); } caml_leave_blocking_section(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_shutdown(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); int ret; caml_enter_blocking_section(); ret = SSL_shutdown(ssl); if (!ret) SSL_shutdown(ssl); caml_leave_blocking_section(); /* close(SSL_get_fd(SSL_val(socket))); */ CAMLreturn(Val_unit); } /* ======================================================== */ /* T.F.: Here, we steal the client_verify_callback function from netkit-telnet-ssl-0.17.24+0.1/libtelnet/ssl.c From the original file header: The modifications to support SSLeay were done by Tim Hudson tjh@mincom.oz.au You can do whatever you like with these patches except pretend that you wrote them. Email ssl-users-request@mincom.oz.au to get instructions on how to join the mailing list that discusses SSLeay and also these patches. */ #define ONELINE_NAME(X) X509_NAME_oneline(X, 0, 0) /* Quick translation ... */ #ifndef VERIFY_ERR_UNABLE_TO_GET_ISSUER #define VERIFY_ERR_UNABLE_TO_GET_ISSUER X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT #endif #ifndef VERIFY_ERR_DEPTH_ZERO_SELF_SIGNED_CERT #define VERIFY_ERR_DEPTH_ZERO_SELF_SIGNED_CERT X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT #endif #ifndef VERIFY_OK #define VERIFY_OK X509_V_OK #endif #ifndef VERIFY_ERR_UNABLE_TO_GET_ISSUER #define VERIFY_ERR_UNABLE_TO_GET_ISSUER X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT #endif /* Need to think about this mapping in terms of what the real * equivalent of this actually is. */ #ifndef VERIFY_ROOT_OK #define VERIFY_ROOT_OK VERIFY_OK #endif static int client_verify_callback(int ok, X509_STORE_CTX *ctx) { char *subject, *issuer; int depth, error; char *xs; depth = X509_STORE_CTX_get_error_depth(ctx); error = X509_STORE_CTX_get_error(ctx); xs = (char*)X509_STORE_CTX_get_current_cert(ctx); subject = issuer = NULL; /* First thing is to have a meaningful name for the current * certificate that is being verified ... and if we cannot * determine that then something is seriously wrong! */ subject=(char*)ONELINE_NAME(X509_get_subject_name((X509*)xs)); if (subject == NULL) { ERR_print_errors_fp(stderr); ok = 0; goto return_time; } issuer = (char*)ONELINE_NAME(X509_get_issuer_name((X509*)xs)); if (issuer == NULL) { ERR_print_errors_fp(stderr); ok = 0; goto return_time; } /* If the user wants us to be chatty about things then this * is a good time to wizz the certificate chain past quickly :-) */ if (client_verify_callback_verbose) { fprintf(stderr, "Certificate[%d] subject=%s\n", depth, subject); fprintf(stderr, "Certificate[%d] issuer =%s\n", depth, issuer); fflush(stderr); } /* If the server is using a self signed certificate then * we need to decide if that is good enough for us to * accept ... */ if (error == VERIFY_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) { if (1) { /* Make 100% sure that in secure more we drop the * connection if the server does not have a * real certificate! */ if (client_verify_callback_verbose) { fprintf(stderr,"SSL: rejecting connection - server has a self-signed certificate\n"); fflush(stderr); } /* Sometimes it is really handy to be able to debug things * and still get a connection! */ ok = 0; goto return_time; } else { ok = 1; goto return_time; } } /* If we have any form of error in secure mode we reject the connection. */ if (!((error == VERIFY_OK) || (error == VERIFY_ROOT_OK))) { if (1) { if (client_verify_callback_verbose) { fprintf(stderr, "SSL: rejecting connection - error=%d\n", error); if (error == VERIFY_ERR_UNABLE_TO_GET_ISSUER) { fprintf(stderr, "unknown issuer: %s\n", issuer); } else { ERR_print_errors_fp(stderr); } fflush(stderr); } ok = 0; goto return_time; } else { /* Be nice and display a lot more meaningful stuff * so that we know which issuer is unknown no matter * what the callers options are ... */ if (error == VERIFY_ERR_UNABLE_TO_GET_ISSUER && client_verify_callback_verbose) { fprintf(stderr, "SSL: unknown issuer: %s\n", issuer); fflush(stderr); } } } return_time: /* Clean up things. */ if (subject) free(subject); if (issuer) free(issuer); return ok; } static DH *load_dh_param(const char *dhfile) { DH *ret=NULL; BIO *bio; if ((bio=BIO_new_file(dhfile,"r")) == NULL) goto err; ret=PEM_read_bio_DHparams(bio,NULL,NULL,NULL); err: if (bio != NULL) BIO_free(bio); return(ret); } ocaml-ssl-0.5.10/src/ssl_threads.ml000066400000000000000000000015001400573131300171140ustar00rootroot00000000000000(* Copyright (C) 2003-2005 Samuel Mimram This file is part of Ocaml-ssl. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *) let init () = Ssl.thread_safe := true ocaml-ssl-0.5.10/src/ssl_threads.mli000066400000000000000000000017431400573131300172760ustar00rootroot00000000000000(* Copyright (C) 2003-2005 Samuel Mimram This file is part of Ocaml-ssl. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *) (** * Functions for making the openssl library thread-safe. * * @author Samuel Mimram *) (** Make the library thread-safe. The should be called {i before} [Ssl.init]. *) val init : unit -> unit ocaml-ssl-0.5.10/ssl.opam000066400000000000000000000010431400573131300151410ustar00rootroot00000000000000opam-version: "2.0" name: "ssl" version: "0.5.9" maintainer: "Samuel Mimram " homepage: "https://github.com/savonet/ocaml-ssl" dev-repo: "git+https://github.com/savonet/ocaml-ssl.git" bug-reports: "https://github.com/savonet/ocaml-ssl/issues" build: [ ["dune" "subst"] {pinned} ["dune" "build" "-p" name "-j" jobs] ] depends: [ "ocaml" {>= "4.02.0"} "dune" {>= "2.0.0"} "dune-configurator" "base-unix" "conf-libssl" ] synopsis: "Bindings for OpenSSL" authors: "Samuel Mimram "