pax_global_header00006660000000000000000000000064144545674220014527gustar00rootroot0000000000000052 comment=d0150e41610c4cea9bc16e203f74246b0f1af84d ocaml-ssl-0.7.0/000077500000000000000000000000001445456742200134255ustar00rootroot00000000000000ocaml-ssl-0.7.0/.devcontainer.json000077500000000000000000000005561445456742200170700ustar00rootroot00000000000000{ "image":"ocaml/opam:ubuntu-22.04-ocaml-4.12", "extensions": [ "ocamllabs.ocaml-platform", "redhat.vscode-yaml" ], "runArgs": ["--net=host"], "postCreateCommand": "sudo apt update && sudo apt install pkg-config libssl-dev -y && opam install . --deps-only --with-test && opam update && opam install ocaml-lsp-server ocamlformat-rpc" } ocaml-ssl-0.7.0/.git-blame-ignore-revs000066400000000000000000000001371445456742200175260ustar00rootroot00000000000000# Ran ocamlformat for the first time on the codebase 15189ac5559523505076886bf0943b093d702666 ocaml-ssl-0.7.0/.github/000077500000000000000000000000001445456742200147655ustar00rootroot00000000000000ocaml-ssl-0.7.0/.github/workflows/000077500000000000000000000000001445456742200170225ustar00rootroot00000000000000ocaml-ssl-0.7.0/.github/workflows/build.yml000066400000000000000000000033501445456742200206450ustar00rootroot00000000000000name: Build on: pull_request: branches: - master push: branches: - master concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: build: runs-on: ubuntu-latest strategy: matrix: setup: - {ocaml-version: '4.03', runtest: false} - {ocaml-version: '4.09', runtest: true} - {ocaml-version: '4.14', runtest: true} - {ocaml-version: '5.0', runtest: true} steps: - uses: actions/checkout@v2 - uses: ocaml/setup-ocaml@v2 with: ocaml-compiler: ${{ matrix.setup.ocaml-version }} - name: Setup opam run: opam pin add -n . - name: Install dependencies run: opam depext -yt mad - name: Build if: ${{ ! matrix.setup.runtest }} run: opam install . - name: Build and test if: ${{ matrix.setup.runtest }} run: | opam install -t . eval $(opam env) dune build @github_action_tests nix-build: runs-on: ${{ matrix.setup.os }} strategy: matrix: setup: - {ocamlVersion: 4_12, os: ubuntu-latest} - {ocamlVersion: 4_13, os: ubuntu-latest} - {ocamlVersion: 4_14, os: ubuntu-latest} - {ocamlVersion: 5_0, os: ubuntu-latest} - {ocamlVersion: 5_0, os: macos-latest} steps: - uses: actions/checkout@v3 - uses: cachix/install-nix-action@v22 with: extra_nix_config: | extra-substituters = https://anmonteiro.nix-cache.workers.dev extra-trusted-public-keys = ocaml.nix-cache.com-1:/xI2h2+56rwFfKyyFVbkJSeGqSIYMC/Je+7XXqGKDIY= - name: "Run nix-build" run: nix-build ./nix/ci/test.nix --argstr ocamlVersion ${{ matrix.setup.ocamlVersion }} ocaml-ssl-0.7.0/.github/workflows/doc.yml000066400000000000000000000011131445456742200203060ustar00rootroot00000000000000name: Build doc on: push: branches: - master jobs: build_doc: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - uses: ocaml/setup-ocaml@v2 with: ocaml-compiler: 4.14.1 - name: Pin locally run: opam pin -y add -n . - name: Install dependencies run: opam install -y odoc - name: Build doc run: opam exec dune build @doc - name: Deploy doc uses: JamesIves/github-pages-deploy-action@4.1.6 with: branch: gh-pages folder: _build/default/_doc/_html ocaml-ssl-0.7.0/.gitignore000066400000000000000000000000521445456742200154120ustar00rootroot00000000000000.vscode *.install .merlin _build _coverageocaml-ssl-0.7.0/.gitmodules000066400000000000000000000001051445456742200155760ustar00rootroot00000000000000[submodule "m4"] path = m4 url = https://github.com/savonet/m4.git ocaml-ssl-0.7.0/.ocamlformat000066400000000000000000000013101445456742200157250ustar00rootroot00000000000000break-infix = fit-or-vertical break-infix-before-func = false break-fun-decl = fit-or-vertical break-separators = before break-sequences = true cases-exp-indent = 2 dock-collection-brackets = false field-space = loose if-then-else = keyword-first indicate-multiline-delimiters = no infix-precedence = parens leading-nested-match-parens = true let-and = sparse let-module = sparse ocp-indent-compat = true parens-tuple = multi-line-only parse-docstrings = true sequence-blank-line = preserve-one sequence-style = terminator single-case = sparse space-around-arrays= true space-around-lists= true space-around-records= true space-around-variants= true type-decl = sparse wrap-comments = true wrap-fun-args = false ocaml-ssl-0.7.0/.travis.yml000066400000000000000000000003541445456742200155400ustar00rootroot00000000000000language: 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.7.0/CHANGES.md000066400000000000000000000211771445456742200150270ustar00rootroot000000000000000.7.0 (2023-07-12) ===== - Bump OpenSSL minimum requirement to 1.1.0 and stop using deprecated functions (#121). - Make the functions in `Ssl.Runtime_lock` call non-allocating function on the C stubs and mark them with `[@@noalloc]` (#117). - Add Ssl.{get,set}_{min,max}_protocol_version to specify the desired TLS version ranges for a `Ssl.context` (#132) - Add `Ssl.native_library_version` to query the underlying SSL library verion (#140) - `Ssl.Error`: separate library number from reason code (#139, #142) 0.6.0 (2023-06-01) ===== - Raise an error when `Ssl.flush` isn't successful (#104, #120) - Add an API-compatible `Ssl.Runtime_lock` module. The functions in this module don't release the OCaml runtime lock. While they don't allow other OCaml threads to run concurrently, they don't perform any copying in the underlying data, leading certain workloads to be faster than their counterparts that release the lock. (#106) - Guarantee `Ssl.output_string` writes the whole string by retrying the operation with unwritten bytes (#103, #116) - Fix calls in C stubs that need to call `ERR_clear_error` before the underlying OpenSSL call (#118) - Add a module `Ssl.Error` to retrieve OpenSSL errors in a structured way (#119) - Deprecate Ssl.{SSLv23,SSLv3,TLSv1,TLSv1_1}, which were were formally deprecated in March 2021 and earlier (#115). 0.5.13 (2022-10-20) ===== - Add `Ssl.close_notify` to perform a one-way shutdown (#63, #96). 0.5.12 (2022-08-12) ===== - Add a few verification functions (#71): - `add_extra_chain_cert` to send additional chain certificates to the peer. - `add_cert_to_store`: to allow verification of the peer certificate CA. - `set_ip`: sets the expected IP address to be verified on an SSL socket. - Improve `use_certificate_from_string` (#71) to read any type of key (rather than just RSA). - Fix a segmentation fault in the ALPN selection callback under OCaml 5 (#89). - Audit the C FFI and add `CAMLparamX` and `CAMLreturn` calls (#90). 0.5.11 (2022-07-24) ===== - Add `digest` function (#65, #66). - Restore compatibility with openssl < 1.1.0 (#73). - Improved compatibility with OCaml 5 (#79). - Fix `client_verify_callback` for `NO_NAKED_POINTERS` mode. A user-provided verification function in C remains an out-of-heap pointer for 4.x for compatibility, but is boxed for OCaml 5.x or 4.x when configured with `--disable-naked-pointers`. (#83) 0.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). - Explicitly 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 explicitly 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 specified 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 functions (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.7.0/COPYING000066400000000000000000000654351445456742200144750ustar00rootroot00000000000000This 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 2 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.7.0/Makefile000066400000000000000000000014761445456742200150750ustar00rootroot00000000000000.PHONY: build clean test install uninstall clean all-supported-ocaml-versions build: dune build @default coverage: bisect-ppx-report html test: dune runtest --instrument-with bisect_ppx --force 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.7.0/README.md000066400000000000000000000066001445456742200147060ustar00rootroot00000000000000OCaml-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.7.0/dune-project000066400000000000000000000012021445456742200157420ustar00rootroot00000000000000(lang dune 2.7) (name ssl) (version 0.7.0) (generate_opam_files true) (source (github melange-re/melange)) (maintainers "Antonio Monteiro ") (authors "Samuel Mimram ") (homepage "https://github.com/savonet/ocaml-ssl") (bug_reports "https://github.com/savonet/ocaml-ssl/issues") (license "LGPL-2.1-only WITH OCaml-LGPL-linking-exception") (package (name ssl) (synopsis "Bindings for OpenSSL") (depends (ocaml (>= "4.03.0")) (ocaml (and :with_test (>= "4.08.0"))) dune-configurator conf-libssl (alcotest :with-test) (bisect_ppx (and :dev (>= "2.5.0"))))) ocaml-ssl-0.7.0/dune-workspace.dev000066400000000000000000000004221445456742200170520ustar00rootroot00000000000000(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.7.0/examples/000077500000000000000000000000001445456742200152435ustar00rootroot00000000000000ocaml-ssl-0.7.0/examples/alpn.ml000066400000000000000000000056271445456742200165410ustar00rootroot00000000000000let 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 = Unix.domain_of_sockaddr sockaddr 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 "opening 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 ( r := String.sub s (i + 1) (!j - i - 1) :: !r; j := i) 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.7.0/examples/dune000066400000000000000000000001741445456742200161230ustar00rootroot00000000000000(alias (name default) (deps stalkd.exe stelnet.exe)) (executables (names stalkd stelnet) (libraries threads unix ssl)) ocaml-ssl-0.7.0/examples/stalkd.ml000066400000000000000000000062051445456742200170620ustar00rootroot00000000000000(* 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 = Unix.domain_of_sockaddr sockaddr 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 "opening connection for [%s]" ip); server_handler inet_addr s; Ssl.shutdown s in let[@ocaml.alert "-deprecated"] 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 "received '%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.7.0/examples/stelnet.ml000066400000000000000000000052671445456742200172650ustar00rootroot00000000000000(* 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[@ocaml.alert "-deprecated"] 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.7.0/flake.lock000066400000000000000000000040231445456742200153600ustar00rootroot00000000000000{ "nodes": { "flake-utils": { "inputs": { "systems": "systems" }, "locked": { "lastModified": 1685518550, "narHash": "sha256-o2d0KcvaXzTrPRIo0kOLV0/QXHhDQ5DTi+OxcjO8xqY=", "owner": "numtide", "repo": "flake-utils", "rev": "a1720a10a6cfe8234c0e93907ffe81be440f4cef", "type": "github" }, "original": { "owner": "numtide", "repo": "flake-utils", "type": "github" } }, "nixpkgs": { "inputs": { "flake-utils": [ "flake-utils" ], "nixpkgs": "nixpkgs_2" }, "locked": { "lastModified": 1686453844, "narHash": "sha256-et1oAsQIxSSlIoA+2MHyBK5jOsyFLfZy7BjBG3/wNY4=", "owner": "anmonteiro", "repo": "nix-overlays", "rev": "89083d292b7029ff9d21f9ad60b564be3ad9c180", "type": "github" }, "original": { "owner": "anmonteiro", "repo": "nix-overlays", "type": "github" } }, "nixpkgs_2": { "locked": { "lastModified": 1686412476, "narHash": "sha256-inl9SVk6o5h75XKC79qrDCAobTD1Jxh6kVYTZKHzewA=", "owner": "NixOS", "repo": "nixpkgs", "rev": "21951114383770f96ae528d0ae68824557768e81", "type": "github" }, "original": { "owner": "NixOS", "repo": "nixpkgs", "rev": "21951114383770f96ae528d0ae68824557768e81", "type": "github" } }, "root": { "inputs": { "flake-utils": "flake-utils", "nixpkgs": "nixpkgs" } }, "systems": { "locked": { "lastModified": 1681028828, "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", "owner": "nix-systems", "repo": "default", "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", "type": "github" }, "original": { "owner": "nix-systems", "repo": "default", "type": "github" } } }, "root": "root", "version": 7 } ocaml-ssl-0.7.0/flake.nix000066400000000000000000000013511445456742200152270ustar00rootroot00000000000000{ description = "OCaml-SSL Nix Flake"; inputs.flake-utils.url = "github:numtide/flake-utils"; inputs.nixpkgs.inputs.flake-utils.follows = "flake-utils"; inputs.nixpkgs.url = "github:anmonteiro/nix-overlays"; outputs = { self, nixpkgs, flake-utils }: flake-utils.lib.eachDefaultSystem (system: let pkgs = nixpkgs.legacyPackages."${system}"; in rec { defaultPackage = pkgs.callPackage ./nix { }; devShells = { default = pkgs.callPackage ./nix/shell.nix { packages = [ defaultPackage ]; }; release = pkgs.callPackage ./nix/shell.nix { packages = [ defaultPackage ]; release-mode = true; }; }; }); } ocaml-ssl-0.7.0/nix/000077500000000000000000000000001445456742200142235ustar00rootroot00000000000000ocaml-ssl-0.7.0/nix/ci/000077500000000000000000000000001445456742200146165ustar00rootroot00000000000000ocaml-ssl-0.7.0/nix/ci/test.nix000066400000000000000000000011341445456742200163140ustar00rootroot00000000000000{ ocamlVersion }: let lock = builtins.fromJSON (builtins.readFile ./../../flake.lock); src = fetchGit { url = with lock.nodes.nixpkgs.locked; "https://github.com/${owner}/${repo}"; inherit (lock.nodes.nixpkgs.locked) rev; # inherit (lock.nodes.nixpkgs.original) ref; allRefs = true; }; pkgs = import "${src}" { extraOverlays = [ (self: super: { ocamlPackages = super.ocaml-ng."ocamlPackages_${ocamlVersion}"; }) ]; }; in (pkgs.callPackage ./.. { doCheck = true; }).overrideAttrs (o: { nativeBuildInputs = o.nativeBuildInputs ++ [ pkgs.git ]; }) ocaml-ssl-0.7.0/nix/default.nix000066400000000000000000000006551445456742200163750ustar00rootroot00000000000000{ stdenv , lib , ocamlPackages , openssl-oc , doCheck ? false , pkg-config }: with ocamlPackages; buildDunePackage { pname = "ssl"; version = "n/a"; useDune2 = true; src = ../.; nativeBuildInputs = [ ocaml dune findlib pkg-config ]; buildInputs = [ dune-configurator ]; propagatedBuildInputs = [ openssl-oc.dev ]; nativeCheckInputs = [ openssl-oc ]; checkInputs = [ alcotest ]; inherit doCheck; } ocaml-ssl-0.7.0/nix/gh-actions.nix000066400000000000000000000035321445456742200170020ustar00rootroot00000000000000{ lib }: let commonSteps = { name, signingKey }: [ { uses = "actions/checkout@v2"; "with" = { "submodules" = "recursive"; }; } { uses = "cachix/install-nix-action@v14.1"; } { uses = "cachix/cachix-action@v10"; "with" = { inherit name signingKey; }; } ]; job = { steps , ocamlVersions ? [ "4_12" "4_13" "4_14" "5_00" ] , ... }@attrs: (builtins.removeAttrs attrs [ "ocamlVersions" ]) // { strategy = { fail-fast = false; matrix = { ocamlVersion = ocamlVersions ; }; }; }; gh-actions = { cachixBuild = { name, branches ? [ "master" ], os, cachix }: lib.generators.toYAML { } { inherit name; on = { pull_request = null; push = { inherit branches; }; }; jobs = lib.mapAttrs (os: { run, name, ... }@conf: job ({ runs-on = os; steps = commonSteps cachix ++ [{ inherit name run; }]; } // (if (conf ? ocamlVersions) then { inherit (conf) ocamlVersions; } else { }))) os; }; }; in gh-actions.cachixBuild { name = "Build"; cachix = { name = "anmonteiro"; signingKey = "\${{ secrets.CACHIX_SIGNING_KEY }}"; }; os = { macos-latest = { name = "Run nix-build"; ocamlVersions = [ "4_13" "4_14" "5_00" ]; run = "nix-build ./nix/ci/test.nix -A native --argstr ocamlVersion \${{ matrix.ocamlVersion }}"; }; ubuntu-latest = { ocamlVersions = [ "4_12" "4_13" "4_14" "5_00" ]; name = "Run nix-build"; run = "nix-build ./nix/ci/test.nix -A native -A musl64 --argstr ocamlVersion \${{ matrix.ocamlVersion }}"; }; }; } ocaml-ssl-0.7.0/nix/shell.nix000066400000000000000000000005761445456742200160620ustar00rootroot00000000000000{ packages , lib , mkShell , release-mode ? false , cacert , curl , ocamlPackages , git , opam }: mkShell { OCAMLRUNPARAM = "b"; inputsFrom = packages; buildInputs = (with ocamlPackages; [ merlin ocamlformat utop alcotest ]) ++ lib.optional release-mode [ cacert curl ocamlPackages.dune-release git opam ]; } ocaml-ssl-0.7.0/src/000077500000000000000000000000001445456742200142145ustar00rootroot00000000000000ocaml-ssl-0.7.0/src/config/000077500000000000000000000000001445456742200154615ustar00rootroot00000000000000ocaml-ssl-0.7.0/src/config/discover.ml000066400000000000000000000016311445456742200176320ustar00rootroot00000000000000module 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 () = C.main ~name:"ssl" (fun c -> let default = default c in let conf = match C.Pkg_config.get c with | None -> default | Some pc -> (match C.Pkg_config.query pc ~package:"openssl" with | Some s -> s | None -> default) in C.Flags.write_sexp "c_library_flags.sexp" conf.libs; C.Flags.write_sexp "c_flags.sexp" conf.cflags) ocaml-ssl-0.7.0/src/config/dune000066400000000000000000000000751445456742200163410ustar00rootroot00000000000000(executable (name discover) (libraries dune-configurator)) ocaml-ssl-0.7.0/src/dune000066400000000000000000000005411445456742200150720ustar00rootroot00000000000000(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)) (instrumentation (backend bisect_ppx))) (rule (targets c_flags.sexp c_library_flags.sexp) (action (run ./config/discover.exe))) ocaml-ssl-0.7.0/src/ssl.ml000066400000000000000000000540761445456742200153630ustar00rootroot00000000000000(* 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 version = { major : int (** major version *) ; minor : int (** minor version *) ; patch : int (** patch number (fix + patch in version < 3.0) *) } external get_version : unit -> version = "ocaml_ssl_get_version" let native_library_version : version = get_version () 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 | Error_want_async | Error_want_async_job | Error_want_client_hello_cb | Error_want_retry_verify 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" (** Kept for backwards compatibility *) module Error = struct type t = private { library_number : int ; reason_code : int ; lib : string option ; reason : string option } type err_function = | Get_error | Peek_error | Peek_last_error external error_struct : err_function -> t = "ocaml_ssl_error_struct" let get_error () = error_struct Get_error let peek_error () = error_struct Peek_error let peek_last_error () = error_struct Peek_last_error (** Reproduces the string format from ERR_error_string_n *) let peek_last_error_string () = let err = peek_last_error () in let libstring = match err.lib with Some lib -> lib | None -> "lib(0)" in let reasonstring = match err.reason with Some reason -> reason | None -> "reason(0)" in Printf.sprintf "error:%02lX:%06lX:%s::%s" (Int32.of_int err.library_number) (Int32.of_int err.reason_code) libstring reasonstring end 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 exception Flush_error of bool (* true means retry *) 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: Cipher error" | Diffie_hellman_error -> Some "SSL: Diffie-Hellman error" | Ec_curve_error -> Some "SSL: EC curve error" | Private_key_error s -> Some ("SSL: Private 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: " ^ Error.peek_last_error_string ()) | Accept_error _ -> Some ("SSL accept() error: " ^ Error.peek_last_error_string ()) | Read_error _ -> Some ("SSL read() error: " ^ Error.peek_last_error_string ()) | Write_error _ -> Some ("SSL write() error: " ^ Error.peek_last_error_string ()) | Verify_error _ -> Some ("SSL verify() error: " ^ Error.peek_last_error_string ()) | Flush_error b -> Some (Printf.sprintf "SSL flush(%b) error: " b ^ Error.peek_last_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); Callback.register_exception "ssl_exn_flush_error" (Flush_error true) 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 set_min_protocol_version : context -> protocol -> unit = "ocaml_ssl_ctx_set_min_proto_version" external set_max_protocol_version : context -> protocol -> unit = "ocaml_ssl_ctx_set_max_proto_version" external get_min_protocol_version : context -> protocol = "ocaml_ssl_ctx_get_min_proto_version" external get_max_protocol_version : context -> protocol = "ocaml_ssl_ctx_get_max_proto_version" external add_extra_chain_cert : context -> string -> unit = "ocaml_ssl_ctx_add_extra_chain_cert" external add_cert_to_store : context -> string -> unit = "ocaml_ssl_ctx_add_cert_to_store" 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" external digest : [ `SHA1 | `SHA256 | `SHA384 ] -> certificate -> string = "ocaml_ssl_digest" 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 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 set_ip : socket -> string -> unit = "ocaml_ssl_set1_ip" (* Here is the signature of the base communication functions that are implemented below in two versions *) module type Ssl_base = sig val connect : socket -> unit val accept : socket -> unit val ssl_shutdown : socket -> bool val flush : socket -> unit val read : socket -> Bytes.t -> int -> int -> int val read_into_bigarray : socket -> bigarray -> int -> int -> int val write : socket -> Bytes.t -> int -> int -> int val write_substring : socket -> string -> int -> int -> int val write_bigarray : socket -> bigarray -> int -> int -> int end (* Provide the base implementation communication functions that release the OCaml runtime lock, allowing multiple systhreads to execute concurrently. *) module Runtime_unlock_base = struct external connect : socket -> unit = "ocaml_ssl_connect" external accept : socket -> unit = "ocaml_ssl_accept" 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 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 flush : socket -> unit = "ocaml_ssl_flush" external ssl_shutdown : socket -> bool = "ocaml_ssl_shutdown" end (* Same as above, but doesn't release the lock. *) module Runtime_lock_base = struct external get_error : socket -> int -> ssl_error = "ocaml_ssl_get_error_code" [@@noalloc] external connect : socket -> int = "ocaml_ssl_connect_blocking" [@@noalloc] let connect socket = let ret = connect socket in (* From https://www.openssl.org/docs/man1.1.1/man3/SSL_connect.html: RETURN VALUES 0 The TLS/SSL handshake was not successful [...]. Call SSL_get_error() with the return value ret to find out the reason. 1 The TLS/SSL handshake was successfully completed [...]. <0 The TLS/SSL handshake was not successful [...]. Call SSL_get_error() with the return value ret to find out the reason. *) if ret <> 1 then let err = get_error socket ret in raise (Connection_error err) external accept : socket -> int = "ocaml_ssl_accept_blocking" [@@noalloc] let accept socket = let ret = accept socket in (* From https://www.openssl.org/docs/man1.1.1/man3/SSL_accept.html: RETURN VALUES 0 The TLS/SSL handshake was not successful [...]. Call SSL_get_error() with the return value ret to find out the reason. 1 The TLS/SSL handshake was successfully completed [...]. <0 The TLS/SSL handshake was not successful [...]. Call SSL_get_error() with the return value ret to find out the reason. *) if ret <> 1 then let err = get_error socket ret in raise (Accept_error err) external write : socket -> Bytes.t -> int -> int -> int = "ocaml_ssl_write_blocking" [@@noalloc] let write socket buffer start length = if start < 0 then invalid_arg "Ssl.write: start negative"; if length < 0 then invalid_arg "Ssl.write: length negative"; if start + length > Bytes.length buffer then invalid_arg "Ssl.write: Buffer too short"; let ret = write socket buffer start length in (* From https://www.openssl.org/docs/man1.1.1/man3/SSL_write.html: RETURN VALUES > 0 The write operation was successful, the return value is the number of bytes actually written to the TLS/SSL connection. <= 0 The write operation was not successful [...]. Call SSL_get_error() with the return value ret to find out the reason. *) (if ret <= 0 then let err = get_error socket ret in raise (Write_error err)); ret external write_substring : socket -> string -> int -> int -> int = "ocaml_ssl_write_blocking" [@@noalloc] let write_substring socket buffer start length = if start < 0 then invalid_arg "Ssl.write_substring: start negative"; if length < 0 then invalid_arg "Ssl.write_substring: length negative"; if start + length > String.length buffer then invalid_arg "Ssl.write_substring: Buffer too short"; let ret = write_substring socket buffer start length in (if ret <= 0 then let err = get_error socket ret in raise (Write_error err)); ret external write_bigarray : socket -> bigarray -> int -> int -> int = "ocaml_ssl_write_bigarray_blocking" [@@noalloc] let write_bigarray socket buffer start length = if start < 0 then invalid_arg "Ssl.write_bigarray: start negative"; if length < 0 then invalid_arg "Ssl.write_bigarray: length negative"; if start + length > Bigarray.Array1.dim buffer then invalid_arg "Ssl.write_bigarray: Buffer too short"; let ret = write_bigarray socket buffer start length in (if ret <= 0 then let err = get_error socket ret in raise (Write_error err)); ret external read : socket -> Bytes.t -> int -> int -> int = "ocaml_ssl_read_blocking" [@@noalloc] let read socket buffer start length = if start < 0 then invalid_arg "Ssl.read: start negative"; if length < 0 then invalid_arg "Ssl.read: length negative"; if start + length > Bytes.length buffer then invalid_arg "Buffer too short"; let ret = read socket buffer start length in (* From https://www.openssl.org/docs/man1.1.1/man3/SSL_read.html RETURN VALUES > 0 The read operation was successful. The return value is the number of bytes actually read from the TLS/SSL connection. <= 0 The read operation was not successful [...]. Call SSL_get_error(3) with the return value ret to find out the reason. *) (if ret <= 0 then let err = get_error socket ret in raise (Read_error err)); ret external read_into_bigarray : socket -> bigarray -> int -> int -> int = "ocaml_ssl_read_into_bigarray_blocking" [@@noalloc] let read_into_bigarray socket buffer start length = if start < 0 then invalid_arg "Ssl.read_into_big_array: start negative"; if length < 0 then invalid_arg "Ssl.read_into_big_array: length negative"; if start + length > Bigarray.Array1.dim buffer then invalid_arg "Buffer too short"; let ret = read_into_bigarray socket buffer start length in (if ret <= 0 then let err = get_error socket ret in raise (Read_error err)); ret external flush : socket -> int = "ocaml_ssl_flush_blocking" [@@noalloc] let flush socket = let ret = flush socket in (* From https://www.openssl.org/docs/man1.1.1/man3/BIO_flush.html: RETURN VALUES BIO_flush() returns 1 for success and 0 or -1 for failure. Additionally, we use -2 to signal the need to retry without allocation, see [ssl_stubs.c]. *) if ret <> 1 then raise (Flush_error (ret = -2)) external ssl_shutdown : socket -> int = "ocaml_ssl_shutdown_blocking" [@@noalloc] let ssl_shutdown socket = let ret = ssl_shutdown socket in (if ret < 0 then let err = get_error socket ret in raise (Connection_error err)); ret = 1 end (* The functor implementing communication functions from a structure of type Ssl_base *) module Make (Ssl_base : Ssl_base) = struct include Ssl_base let open_connection_with_context context sockaddr = let domain = Unix.domain_of_sockaddr sockaddr 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 close_notify = ssl_shutdown let shutdown sock = if not (close_notify sock) then ignore (close_notify sock : bool) let shutdown_connection = shutdown let output_string ssl s = let len = String.length s in let to_write = ref len in let offset = ref 0 in while !to_write > 0 do let written = write_substring ssl s !offset !to_write in if written <= 0 then failwith "output_string failed to write"; to_write := !to_write - written; offset := !offset + written done let output_char ssl c = let tmp = String.make 1 c in let written = write_substring ssl tmp 0 1 in if written <= 0 then failwith "output_char failed to write" 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 let read = read ssl tmp 0 4 in if read < 4 then failwith "input_int failed to read 4 bytes"; 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 end (* We apply the functor twice. The releasing functions are imported as default *) include Make (Runtime_unlock_base) module Runtime_lock = Make (Runtime_lock_base) (** Deprecated functions for compatibility with older version *) let read_into_bigarray_blocking : socket -> bigarray -> int -> int -> int = Runtime_lock.read_into_bigarray let write_bigarray_blocking : socket -> bigarray -> int -> int -> int = Runtime_lock.write_bigarray ocaml-ssl-0.7.0/src/ssl.mli000066400000000000000000000672761445456742200155420ustar00rootroot00000000000000(* 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 OpenSSL version} *) type version = { major : int (** major version *) ; minor : int (** minor version *) ; patch : int (** patch number *) } (** in version prior to 3.0, details are dropped: 1.1.1n = 1.1.1f *) val native_library_version : version (** {1 Exceptions and errors} *) (** An ssl error has occurred (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 (** A non-recoverable, fatal error in the SSL library occurred, usually a protocol error. The OpenSSL error queue contains more information on the error. If this error occurs then no further I/O operations should be performed on the connection and SSL_shutdown() must not be called. *) | 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. *) | Error_want_async (** The operation did not complete because an asynchronous engine is still processing data. The TLS/SSL I/O function should be called again later. The function must be called from the same thread that the original call was made from. *) | Error_want_async_job (** The asynchronous job could not be started because there were no async jobs available in the pool. The application should retry the operation after a currently executing asynchronous operation for the current thread has completed. *) | Error_want_client_hello_cb (** The operation did not complete because an application callback set by SSL_CTX_set_client_hello_cb() has asked to be called again. The TLS/SSL I/O function should be called again later. Details depend on the application. *) | Error_want_retry_verify (** See https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_verify.html *) type bigarray = (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t exception Method_error (** The SSL method could not be initialized. *) exception Context_error exception Cipher_error exception Diffie_hellman_error exception Ec_curve_error exception Certificate_error of string (** The SSL server certificate could not be initialized. *) exception Private_key_error of string (** The SSL server private key could not be initialized. *) exception Unmatching_keys (** The SSL private key does not match the certificate public key. *) exception Invalid_socket (** The given socket is invalid. *) exception Handler_error (** The SSL handler could not be initialized. *) exception Connection_error of ssl_error (** The connection could not be made with the SSL service. *) exception Accept_error of ssl_error (** Failed to accept an SSL connection. *) exception Read_error of ssl_error (** An error occurred while reading data. *) exception Write_error of ssl_error (** An error occurred while writing data. *) exception Flush_error of bool (** An error occurred while flushing a socket. [Flush_error true] means that the operation should be retried. *) (** 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. *) exception Verify_error of verify_error (** An error occurred while verifying the certificate. *) (** {1 Communication} *) val init : ?thread_safe:bool -> unit -> unit (** 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 achieved by calling [Ssl_threads.init] first. *) val get_error_string : unit -> string [@@ocaml.alert deprecated "Use [Ssl.Error.get_error] instead"] (** Retrieve a human-readable message that corresponds to the earliest error code from the thread's error queue and removes the entry. *) module Error : sig type t = private { library_number : int (** Identifies the OpenSSL sub-library that generated this error. Library values are defined in https://github.com/openssl/openssl/blob/openssl-3.0.0/include/openssl/err.h.in#L72 *) ; reason_code : int (** The reason code is the information about what went wrong. *) ; lib : string option (** The library name that generated the error. *) ; reason : string option (** The reason string for the error message. *) } (** The error code returned by ERR_get_error() consists of a library number, function code and reason code. Each sub-library of OpenSSL has a unique library number; function and reason codes are unique within each sub-library. Note that different libraries may use the same value to signal different functions and reasons. *) val get_error : unit -> t (** Retrieve the earliest error from the error queue then it removes the entry. Returns the code and library and reason strings *) val peek_error : unit -> t (** Retrieve the earliest error from the error queue without modifying it. Returns the code and library and reason strings *) val peek_last_error : unit -> t (** Retrieves the latest error code from the thread's error queue without modifying it. Returns the code and library and reason strings. *) end (** Protocol used by SSL. *) type protocol = | SSLv23 [@ocaml.alert deprecated "SSL 2.0 was deprecated in 2011 by RFC 6176."] (** accept all possible protocols (SSLv2 if supported by openssl, SSLv3, TLSv1, TLSv1.1, TLSv1.2, and TLSv1.3) *) | SSLv3 [@ocaml.alert deprecated "SSL 3.0 was deprecated in June 2015 by RFC 7568."] (** only SSL v3 protocol *) | TLSv1 [@ocaml.alert deprecated "TLS 1.0 and 1.1 were formally deprecated in RFC8996 in March 2021."] (** only TLS v1 protocol *) | TLSv1_1 [@ocaml.alert deprecated "TLS 1.0 and 1.1 were formally deprecated in RFC8996 in March 2021."] (** only TLS v1.1 protocol *) | TLSv1_2 (** only TLS v1.2 protocol *) | TLSv1_3 (** only TLS v1.3 protocol *) type socket (** An SSL abstract 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} *) type context (** 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 of the context to create. *) type context_type = | Client_context (** Client connections. *) | Server_context (** Server connections. *) | Both_context (** Client and server connections. *) val create_context : protocol -> context_type -> context (** Create a context. *) val set_min_protocol_version : context -> protocol -> unit (** [set_min_protocol_version ctx proto] sets the minimum supported protocol version for [ctx] to [proto]. *) val set_max_protocol_version : context -> protocol -> unit (** [set_max_protocol_version ctx proto] sets the maximum supported protocol version for [ctx] to [proto]. *) val get_min_protocol_version : context -> protocol (** [get_min_protocol_version ctx] sets the minimum supported protocol version for [ctx] to [proto]. *) val get_max_protocol_version : context -> protocol (** [get_max_protocol_version ctx proto] sets the maximum supported protocol version for [ctx] to [proto]. *) val add_extra_chain_cert : context -> string -> unit (** Add an additional certificate to the extra chain certificates associated with the [ctx]. Extra chain certificates will be sent to the peer for verification and are sent in order following the end entity certificate. The value should be contents of the certificate as string in PEM format. *) val add_cert_to_store : context -> string -> unit (** Add a certificate to the [ctx] trust storage. The value should be contents of the certificate as string in PEM format. *) val use_certificate : context -> string -> string -> unit (** [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_from_string : 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 set_password_callback : context -> (bool -> 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_client_CA_list_from_file : context -> string -> unit (** Set the list of CAs sent to the client when requesting a client certificate. *) (** 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]. *) type verify_callback (** A callback function for verification. Warning: this might change in the future. *) val client_verify_callback : verify_callback (** Client's verification callback. Warning: this might change in the future. *) val set_client_verify_callback_verbose : bool -> unit (** Set verbosity of {! client_verify_callback } *) val set_verify : context -> verify_mode list -> verify_callback option -> unit (** Set the verify mode and callback, see SSL_CTX_set_verify(3). * Warning: this might change in the future. *) val set_verify_depth : context -> int -> unit (** Set the maximum depth for the certificate chain verification that shall be allowed. *) val set_context_alpn_protos : context -> string list -> unit (** Set the list of supported ALPN protocols for negotiation to the context. *) val set_context_alpn_select_callback : context -> (string list -> string option) -> unit (** Set the callback to allow server to select the preferred protocol from client's available protocols. *) (** {2 Ciphers} *) type cipher (** A cipher. It holds the algorithm information for a particular cipher which * are a core part of the SSL/TLS protocol.*) val disable_protocols : context -> protocol list -> unit (** Disable all protocols from the list. * Note that [SSLv23] disables both SSLv2 and SSLv3 (as opposed to all the * protocols). * *) val set_cipher_list : context -> string -> unit (** Set the list of available ciphers for a context. See man ciphers(1) for the format of the string. *) val honor_cipher_order : context -> 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 init_dh_from_file : context -> string -> unit (** Init DH parameters from file *) val init_ec_from_named_curve : context -> string -> unit (** Init EC curve from curve name *) val get_cipher : socket -> cipher (** Get the cipher used by a socket. *) val get_cipher_description : cipher -> string (** Get a description of a cipher. *) val get_cipher_name : cipher -> string (** Get the name of a cipher. *) val get_cipher_version : cipher -> string (** Get the version of a cipher. *) val version : socket -> protocol (** 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 *) (** {2 Certificates} *) type certificate (** A certificate. *) val read_certificate : string -> certificate (** [read_certificate fname] reads the certificate in the file [fname]. *) val write_certificate : string -> certificate -> unit val get_certificate : socket -> certificate (** Get the certificate used by a socket. *) val get_issuer : certificate -> string (** Get the issuer of a certificate. *) val get_subject : certificate -> string (** Get the subject of a certificate. *) val get_start_date : certificate -> Unix.tm (** Get the start date of a certificate. *) val get_expiration_date : certificate -> Unix.tm (** Get the expiration date of a certificate. *) val load_verify_locations : context -> string -> string -> unit (** [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 set_default_verify_paths : context -> bool (** Specifies that the default locations from which CA certificates are loaded should be used. Returns [true] on success. *) val get_verify_result : socket -> int (** Get the verification result. *) val get_verify_error_string : int -> string (** Get a human readable verification error message for the verification error Its input should be the result of calling [get_verify_result]. *) val digest : [ `SHA1 | `SHA256 | `SHA384 ] -> certificate -> string (** Get the digest of the certificate as a binary string, using the SHA1, SHA256 or SHA384 hashing algorithm. *) (** {2 Creating, connecting, closing and configuring sockets} *) val embed_socket : Unix.file_descr -> context -> socket (** Embed a Unix socket into an SSL socket. *) val set_client_SNI_hostname : socket -> string -> unit (** Set the hostname the client is attempting to connect to using the Server * Name Indication (SNI) TLS extension. *) val set_alpn_protos : socket -> string list -> unit (** Set the list of supported ALPN protocols for negotiation to the connection. *) val get_negotiated_alpn_protocol : socket -> string option (** Get the negotiated protocol from the connection. *) val verify : socket -> unit (** Check the result of the verification of the X509 certificate presented by the peer, if any. Raises a [verify_error] on failure. *) (** 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 val set_ip : socket -> string -> unit (** Set the expected ip address to be verified. Ip address is dotted decimal quad for IPv4 and colon-separated hexadecimal for IPv6. The condensed "::" notation is supported for IPv6 addresses. *) val file_descr_of_socket : socket -> Unix.file_descr (** Get the file descriptor associated with a socket. It is primarily useful for [select]ing on it; you should not write or read on it. *) (** {2 I/O on SSL sockets} *) (** The main SSL communication functions that can block if sockets are in blocking mode. This set of functions releases the OCaml runtime lock, which can require extra copying of application data. The module [Runtime_lock] provided below lifts this limitation by never releasing the OCaml runtime lock. *) val connect : socket -> unit (** Connect an SSL socket. *) val accept : socket -> unit (** Accept an SSL connection. *) val open_connection : protocol -> Unix.sockaddr -> socket (** Open an SSL connection. *) val open_connection_with_context : context -> Unix.sockaddr -> socket (** Open an SSL connection with the specified context. *) val close_notify : socket -> bool (** Send close notify to the peer. This is SSL_shutdown(3). * returns [true] if shutdown is finished, [false] in case [close_notify] * needs to be called a second time. *) val shutdown_connection : socket -> unit (** Close an SSL connection opened with [open_connection]. *) val shutdown : socket -> unit (** Close a SSL connection. * Send close notify to the peer and wait for close notify from peer. *) val flush : socket -> unit (** Flush an SSL connection. *) val read : socket -> Bytes.t -> int -> int -> int (** [read sock buf off len] receives data from a connected SSL socket. *) val read_into_bigarray : socket -> bigarray -> 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 write : socket -> Bytes.t -> int -> int -> int (** [write sock buf off len] sends data over a connected SSL socket. *) val write_substring : socket -> string -> int -> int -> int (** [write_substring sock str off len] sends data over a connected SSL socket. *) val write_bigarray : socket -> bigarray -> 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. *) (** {3 High-level communication functions} *) val input_string : socket -> string (** Input a string on an SSL socket. *) val output_string : socket -> string -> unit (** Write a string on an SSL socket. *) val input_char : socket -> char (** Input a character on an SSL socket. *) val output_char : socket -> char -> unit (** Write a char on an SSL socket. *) val input_int : socket -> int (** Input an integer on an SSL socket. *) val output_int : socket -> int -> unit (** Write an integer on an SSL socket. *) (** [Runtime_lock] is an equivalent, signature compatible, equivalent to the [Ssl] module, with one difference: the OCaml runtime lock isn't released before calling the underlying SSL primitives. Multiple systhreads cannot, therefore, run concurrently. It works well with non blocking sockets where the usual semantics apply, i.e. handling of `EWOULDBLOCK`, `EGAIN`, etc. Additionally, the functions in this module don't perform a copy of application data buffers. *) module Runtime_lock : sig val connect : socket -> unit (** Connect an SSL socket. *) val accept : socket -> unit (** Accept an SSL connection. *) val open_connection : protocol -> Unix.sockaddr -> socket (** Open an SSL connection. *) val open_connection_with_context : context -> Unix.sockaddr -> socket (** Open an SSL connection with the specified context. *) val close_notify : socket -> bool (** Send close notify to the peer. This is SSL_shutdown(3). * returns [true] if shutdown is finished, [false] in case [close_notify] * needs to be called a second time. *) val shutdown_connection : socket -> unit (** Close an SSL connection opened with [open_connection]. *) val shutdown : socket -> unit (** Close a SSL connection. * Send close notify to the peer and wait for close notify from peer. *) val flush : socket -> unit (** Flush an SSL connection. *) val read : socket -> Bytes.t -> int -> int -> int (** [read sock buf off len] receives data from a connected SSL socket. *) val read_into_bigarray : socket -> bigarray -> 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 write : socket -> Bytes.t -> int -> int -> int (** [write sock buf off len] sends data over a connected SSL socket. *) val write_substring : socket -> string -> int -> int -> int (** [write_substring sock str off len] sends data over a connected SSL socket. *) val write_bigarray : socket -> bigarray -> 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. *) (** {3 High-level communication functions} *) val input_string : socket -> string (** Input a string on an SSL socket. *) val output_string : socket -> string -> unit (** Write a string on an SSL socket. *) val input_char : socket -> char (** Input a character on an SSL socket. *) val output_char : socket -> char -> unit (** Write a char on an SSL socket. *) val input_int : socket -> int (** Input an integer on an SSL socket. *) val output_int : socket -> int -> unit (** Write an integer on an SSL socket. *) end val read_into_bigarray_blocking : socket -> bigarray -> int -> int -> int [@@ocaml.alert deprecated "Use [Runtime_lock.read_into_bigarray] instead"] (** This function is deprecated. Use [Runtime_lock.read_into_bigarray] instead. *) val write_bigarray_blocking : socket -> bigarray -> int -> int -> int [@@ocaml.alert deprecated "Use [Runtime_lock.write_bigarray] instead"] (** This function is deprecated. Use [Runtime_lock.write_bigarray] instead. *) ocaml-ssl-0.7.0/src/ssl_stubs.c000066400000000000000000001603351445456742200164110ustar00rootroot00000000000000/* * 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 #define CAML_NAME_SPACE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef WIN32 #include #else #include #endif static int client_verify_callback(int, X509_STORE_CTX *); #if defined(NO_NAKED_POINTERS) || defined(NAKED_POINTERS_CHECKER) static value vclient_verify_callback = Val_int(0); #endif static DH *load_dh_param(const char *dhfile); CAMLprim value ocaml_ssl_get_version() { CAMLparam0(); CAMLlocal1(result); result = caml_alloc_tuple(3); #ifdef OPENSSL_VERSION_MAJOR Store_field(result, 0, Val_int(OPENSSL_VERSION_MAJOR)); Store_field(result, 1, Val_int(OPENSSL_VERSION_MINOR)); Store_field(result, 2, Val_int(OPENSSL_VERSION_PATCH)); #else Store_field(result, 0, Val_int((OPENSSL_VERSION_NUMBER >> 28) & 0xF)); Store_field(result, 1, Val_int((OPENSSL_VERSION_NUMBER >> 20) & 0xFF)); Store_field(result, 2, Val_int((OPENSSL_VERSION_NUMBER >> 12) & 0xFF)); #endif CAMLreturn(result); } /******************* * 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) { CAMLparam1(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); } CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_get_error_code(value socket, value ret) { CAMLparam1(socket); int err; err = SSL_get_error(SSL_val(socket), Int_val(ret)); CAMLreturn(Val_int(err)); } CAMLprim value ocaml_ssl_get_error_string(value unit) { CAMLparam1(unit); char buf[256]; ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); CAMLreturn(caml_copy_string(buf)); } CAMLprim value ocaml_ssl_error_struct(value err_func) { CAMLparam1(err_func); CAMLlocal3(result, libval, reasonval); unsigned long code = 0; switch (Int_val(err_func)) { case 0: code = ERR_get_error(); break; case 1: code = ERR_peek_error(); break; case 2: code = ERR_peek_last_error(); break; } result = caml_alloc_tuple(4); const char *lib = ERR_lib_error_string(code); const char *reason = ERR_reason_error_string(code); if (lib != NULL) { libval = Val_some(caml_copy_string(lib)); } else { libval = Val_none; } if (reason != NULL) { reasonval = Val_some(caml_copy_string(reason)); } else { reasonval = Val_none; } Store_field(result, 0, Val_int(ERR_GET_LIB(code))); #ifdef OPENSSL_VERSION_MAJOR Store_field(result, 1, Val_int(ERR_GET_REASON(code))); #else Store_field(result, 1, Val_int(ERR_GET_REASON(code) | ERR_GET_FUNC(code))); #endif Store_field(result, 2, libval); Store_field(result, 3, reasonval); CAMLreturn(result); } /***************************** * Context-related functions * *****************************/ static int protocol_flags[] = {SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3, SSL_OP_NO_SSLv3, SSL_OP_NO_TLSv1, SSL_OP_NO_TLSv1_1, SSL_OP_NO_TLSv1_2, SSL_OP_NO_TLSv1_3}; static const SSL_METHOD *get_method(int type) { const SSL_METHOD *method = NULL; caml_release_runtime_system(); switch (type) { case 0: method = TLS_client_method(); break; case 1: method = TLS_server_method(); break; case 2: method = TLS_method(); break; } caml_acquire_runtime_system(); if (method == NULL) { caml_raise_constant(*caml_named_value("ssl_exn_method_error")); } return method; } static int ocaml_ssl_version_of_tls_version(int tls_version) { int ret; switch (tls_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: ret = -1; break; } return ret; } static int tls_version_of_ocaml_ssl_version(int ocaml_ssl_version) { int ret; switch (ocaml_ssl_version) { case 1: ret = SSL3_VERSION; break; case 2: ret = TLS1_VERSION; break; case 3: ret = TLS1_1_VERSION; break; case 4: ret = TLS1_2_VERSION; break; case 5: ret = TLS1_3_VERSION; break; default: ret = -1; break; } return ret; } value ocaml_ssl_ctx_set_min_proto_version(value context, value protocol) { CAMLparam2(context, protocol); SSL_CTX *ssl_context = Ctx_val(context); int ssl_protocol = tls_version_of_ocaml_ssl_version(Int_val(protocol)); if (ssl_protocol < 0) { caml_invalid_argument("Illegal protocol version, valid values are " "SSLv3, TLSv1, TLSv1_1, TLSv1_2 or TLSv1_3."); } if (!SSL_CTX_set_min_proto_version(ssl_context, ssl_protocol)) { caml_raise_constant(*caml_named_value("ssl_exn_context_error")); } CAMLreturn(Val_unit); } value ocaml_ssl_ctx_get_min_proto_version(value context) { CAMLparam1(context); SSL_CTX *ssl_context = Ctx_val(context); int tls_version = SSL_CTX_get_min_proto_version(ssl_context); int ret; if (tls_version == 0) { ret = 0; } else { ret = ocaml_ssl_version_of_tls_version(tls_version); if (ret == -1) { caml_failwith("Ssl.version"); } } CAMLreturn(Val_int(ret)); } value ocaml_ssl_ctx_set_max_proto_version(value context, value protocol) { CAMLparam2(context, protocol); SSL_CTX *ssl_context = Ctx_val(context); int ssl_protocol = tls_version_of_ocaml_ssl_version(Int_val(protocol)); if (ssl_protocol < 0) { caml_invalid_argument("Illegal protocol version, valid values are " "SSLv3, TLSv1, TLSv1_1, TLSv1_2 or TLSv1_3."); } if (!SSL_CTX_set_max_proto_version(ssl_context, ssl_protocol)) { caml_raise_constant(*caml_named_value("ssl_exn_context_error")); } CAMLreturn(Val_unit); } value ocaml_ssl_ctx_get_max_proto_version(value context) { CAMLparam1(context); SSL_CTX *ssl_context = Ctx_val(context); int tls_version = SSL_CTX_get_max_proto_version(ssl_context); int ret; if (tls_version == 0) { ret = 0; } else { ret = ocaml_ssl_version_of_tls_version(tls_version); if (ret == -1) { caml_failwith("Ssl.version"); } } CAMLreturn(Val_int(ret)); } /* This function assumes the runtime lock is released. In case of failure, it * acquires the runtime lock and then raises an OCaml exception. */ static void set_protocol(SSL_CTX *ssl_context, int protocol) { int max_proto = TLS1_3_VERSION; switch (protocol) { case 0: if (!SSL_CTX_set_min_proto_version(ssl_context, SSL3_VERSION) || !SSL_CTX_set_max_proto_version(ssl_context, max_proto)) { caml_acquire_runtime_system(); caml_invalid_argument("Failed to set protocol to SSLv3"); } break; case 1: if (!SSL_CTX_set_min_proto_version(ssl_context, SSL3_VERSION) || !SSL_CTX_set_max_proto_version(ssl_context, SSL3_VERSION)) { caml_acquire_runtime_system(); caml_invalid_argument("Failed to set protocol to SSLv3"); } break; case 2: if (!SSL_CTX_set_min_proto_version(ssl_context, TLS1_VERSION) || !SSL_CTX_set_max_proto_version(ssl_context, TLS1_VERSION)) { caml_acquire_runtime_system(); caml_invalid_argument("Failed to set protocol to TLSv1"); } break; case 3: if (!SSL_CTX_set_min_proto_version(ssl_context, TLS1_1_VERSION) || !SSL_CTX_set_max_proto_version(ssl_context, TLS1_1_VERSION)) { caml_acquire_runtime_system(); caml_invalid_argument("Failed to set protocol to TLSv1_1"); } break; case 4: if (!SSL_CTX_set_min_proto_version(ssl_context, TLS1_2_VERSION) || !SSL_CTX_set_max_proto_version(ssl_context, TLS1_2_VERSION)) { caml_acquire_runtime_system(); caml_invalid_argument("Failed to set protocol to TLSv1_2"); } break; case 5: if (!SSL_CTX_set_min_proto_version(ssl_context, TLS1_3_VERSION) || !SSL_CTX_set_max_proto_version(ssl_context, TLS1_3_VERSION)) { caml_acquire_runtime_system(); caml_invalid_argument("Failed to set protocol to TLSv1_3"); } break; default: caml_acquire_runtime_system(); caml_invalid_argument( "Unknown method (this should not have happened, please report)."); break; } } CAMLprim value ocaml_ssl_create_context(value protocol, value type) { CAMLparam2(protocol, type); CAMLlocal1(block); SSL_CTX *ctx; const SSL_METHOD *method = get_method(Int_val(type)); caml_release_runtime_system(); ctx = SSL_CTX_new(method); if (!ctx) { caml_acquire_runtime_system(); caml_raise_constant(*caml_named_value("ssl_exn_context_error")); } set_protocol(ctx, Int_val(protocol)); /* 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_acquire_runtime_system(); block = caml_alloc_custom(&ctx_ops, sizeof(SSL_CTX *), 0, 1); Ctx_val(block) = ctx; CAMLreturn(block); } CAMLprim value ocaml_ssl_ctx_add_extra_chain_cert(value context, value cert) { CAMLparam2(context, cert); SSL_CTX *ctx = Ctx_val(context); const char *cert_data = String_val(cert); int cert_data_length = caml_string_length(cert); char buf[256]; X509 *x509_cert = NULL; BIO *cbio; caml_release_runtime_system(); 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_add_extra_chain_cert(ctx, x509_cert) <= 0) { ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); caml_acquire_runtime_system(); caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string(buf)); } caml_acquire_runtime_system(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_ctx_add_cert_to_store(value context, value cert) { CAMLparam2(context, cert); SSL_CTX *ctx = Ctx_val(context); const char *cert_data = String_val(cert); int cert_data_length = caml_string_length(cert); char buf[256]; X509 *x509_cert = NULL; BIO *cbio; caml_release_runtime_system(); cbio = BIO_new_mem_buf((void *)cert_data, cert_data_length); x509_cert = PEM_read_bio_X509(cbio, NULL, 0, NULL); X509_STORE *store = SSL_CTX_get_cert_store(ctx); if (NULL == x509_cert || X509_STORE_add_cert(store, x509_cert) <= 0) { ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); caml_acquire_runtime_system(); caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string(buf)); } caml_acquire_runtime_system(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_ctx_use_certificate(value context, value cert, value privkey) { CAMLparam3(context, cert, privkey); SSL_CTX *ctx = Ctx_val(context); const char *cert_name = String_val(cert); const char *privkey_name = String_val(privkey); char buf[256]; caml_release_runtime_system(); if (SSL_CTX_use_certificate_chain_file(ctx, cert_name) <= 0) { ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); caml_acquire_runtime_system(); 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_acquire_runtime_system(); caml_raise_with_arg(*caml_named_value("ssl_exn_private_key_error"), caml_copy_string(buf)); } if (!SSL_CTX_check_private_key(ctx)) { caml_acquire_runtime_system(); caml_raise_constant(*caml_named_value("ssl_exn_unmatching_keys")); } caml_acquire_runtime_system(); 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); const char *cert_data = String_val(cert); int cert_data_length = caml_string_length(cert); const char *privkey_data = String_val(privkey); int privkey_data_length = caml_string_length(privkey); char buf[256]; X509 *x509_cert = NULL; EVP_PKEY *pkey = 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); pkey = PEM_read_bio_PrivateKey(kbio, NULL, 0, NULL); if (NULL == pkey || SSL_CTX_use_PrivateKey(ctx, pkey) <= 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_release_runtime_system(); ans = SSL_get_verify_result(ssl); caml_acquire_runtime_system(); CAMLreturn(Val_int(ans)); } CAMLprim value ocaml_ssl_get_verify_error_string(value verrn) { CAMLparam1(verrn); int errn = Int_val(verrn); const char *error_string; caml_release_runtime_system(); error_string = X509_verify_cert_error_string(errn); caml_acquire_runtime_system(); CAMLreturn(caml_copy_string(error_string)); } CAMLprim value ocaml_ssl_digest(value vevp, value vcert) { CAMLparam2(vevp, vcert); CAMLlocal1(vdigest); char buf[384 / 8]; const EVP_MD *evp; if (vevp == caml_hash_variant("SHA384")) evp = EVP_sha384(); else if (vevp == caml_hash_variant("SHA256")) evp = EVP_sha256(); else evp = EVP_sha1(); size_t digest_size = EVP_MD_size(evp); assert(digest_size <= sizeof(buf)); X509 *x509 = *((X509 **)Data_custom_val(vcert)); caml_release_runtime_system(); int status = X509_digest(x509, evp, (unsigned char *)buf, NULL); caml_acquire_runtime_system(); if (0 == status) { 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)); } vdigest = caml_alloc_string(digest_size); /* TODO(anmonteiro): switch this to `Bytes_val` when we bump support to * OCaml 4.06 (https://github.com/ocaml/ocaml/pull/1274) * * In the meantime, reproduce `Bytes_val`, which is effectively `String_val` * + a cast: * https://github.com/ocaml/ocaml/pull/1274/commits/6bc4f2656e435175188018830e7fe049caacebe9 */ memcpy((unsigned char *)String_val(vdigest), buf, digest_size); CAMLreturn(vdigest); } CAMLprim value ocaml_ssl_get_client_verify_callback_ptr(value unit) { CAMLparam1(unit); #if defined(NO_NAKED_POINTERS) || defined(NAKED_POINTERS_CHECKER) if (Is_long(vclient_verify_callback)) { vclient_verify_callback = caml_alloc_shr(1, Abstract_tag); *((int (**)(int, X509_STORE_CTX *))Data_abstract_val( vclient_verify_callback)) = client_verify_callback; caml_register_generational_global_root(&vclient_verify_callback); } CAMLreturn(vclient_verify_callback); #else CAMLreturn((value)client_verify_callback); #endif } 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)) { #if defined(NO_NAKED_POINTERS) || defined(NAKED_POINTERS_CHECKER) vcallback = Field(vcallback, 0); if (!Is_block(vcallback) || Tag_val(vcallback) != Abstract_tag || Wosize_val(vcallback) != 1) caml_invalid_argument("callback"); callback = *((int (**)(int, X509_STORE_CTX *))Data_abstract_val(vcallback)); #else callback = (int (*)(int, X509_STORE_CTX *))Field(vcallback, 0); #endif } caml_release_runtime_system(); SSL_CTX_set_verify(ctx, mode, callback); caml_acquire_runtime_system(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_ctx_set_verify_depth(value context, value vdepth) { CAMLparam2(context, vdepth); SSL_CTX *ctx = Ctx_val(context); int depth = Int_val(vdepth); if (depth < 0) caml_invalid_argument("depth"); caml_release_runtime_system(); SSL_CTX_set_verify_depth(ctx, depth); caml_acquire_runtime_system(); CAMLreturn(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); const char *filename = String_val(vfilename); STACK_OF(X509_NAME) * cert_names; char buf[256]; caml_release_runtime_system(); 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_acquire_runtime_system(); caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string(buf)); } caml_acquire_runtime_system(); CAMLreturn(Val_unit); } 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_release_runtime_system(); SSL_CTX_set_alpn_protos(ctx, protos, sizeof(protos)); caml_acquire_runtime_system(); 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); } /* The `alpn_select_cb` function below acquires the runtime lock before calling * this one. Some more info in https://github.com/ocaml/ocaml/issues/11485 */ CAMLprim value caml_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; protocol_list = build_alpn_protocol_list(in, inlen); selected_protocol_opt = caml_callback(*((value *)arg), protocol_list); if (selected_protocol_opt == Val_none) { CAMLreturn(SSL_TLSEXT_ERR_NOACK); } selected_protocol = Field(selected_protocol_opt, 0); len = caml_string_length(selected_protocol); *out = (const unsigned char *)String_val(selected_protocol); *outlen = len; CAMLreturn(SSL_TLSEXT_ERR_OK); } static int alpn_select_cb(SSL *ssl, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { int res; caml_acquire_runtime_system(); res = caml_alpn_select_cb(ssl, out, outlen, in, inlen, arg); caml_release_runtime_system(); return res; } 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_release_runtime_system(); SSL_CTX_set_alpn_select_cb(ctx, alpn_select_cb, select_cb); caml_acquire_runtime_system(); CAMLreturn(Val_unit); } static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) { value s; int len; caml_acquire_runtime_system(); s = caml_callback(*((value *)userdata), Val_int(rwflag)); len = caml_string_length(s); assert(len <= size); memcpy(buf, String_val(s), len); caml_release_runtime_system(); 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_release_runtime_system(); SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb); SSL_CTX_set_default_passwd_cb_userdata(ctx, pcb); caml_acquire_runtime_system(); 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); const char *ciphers = String_val(ciphers_string); if (*ciphers == 0) caml_raise_constant(*caml_named_value("ssl_exn_cipher_error")); caml_release_runtime_system(); if (SSL_CTX_set_cipher_list(ctx, ciphers) != 1) { caml_acquire_runtime_system(); caml_raise_constant(*caml_named_value("ssl_exn_cipher_error")); } caml_acquire_runtime_system(); 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_release_runtime_system(); SSL_CTX_set_options(ctx, flags); caml_acquire_runtime_system(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_version(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); int version; int ret; caml_release_runtime_system(); version = SSL_version(ssl); caml_acquire_runtime_system(); int ocaml_version = ocaml_ssl_version_of_tls_version(version); if (ocaml_version == -1) { caml_failwith("Ssl.version"); } CAMLreturn(Val_int(ocaml_version)); } CAMLprim value ocaml_ssl_get_current_cipher(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); caml_release_runtime_system(); SSL_CIPHER *cipher = (SSL_CIPHER *)SSL_get_current_cipher(ssl); caml_acquire_runtime_system(); if (!cipher) caml_raise_constant(*caml_named_value("ssl_exn_cipher_error")); CAMLreturn((value)cipher); } CAMLprim value ocaml_ssl_get_cipher_description(value vcipher) { CAMLparam1(vcipher); char buf[1024]; SSL_CIPHER *cipher = (SSL_CIPHER *)vcipher; caml_release_runtime_system(); SSL_CIPHER_description(cipher, buf, 1024); caml_acquire_runtime_system(); CAMLreturn(caml_copy_string(buf)); } CAMLprim value ocaml_ssl_get_cipher_name(value vcipher) { CAMLparam1(vcipher); const char *name; SSL_CIPHER *cipher = (SSL_CIPHER *)vcipher; caml_release_runtime_system(); name = SSL_CIPHER_get_name(cipher); caml_acquire_runtime_system(); CAMLreturn(caml_copy_string(name)); } CAMLprim value ocaml_ssl_get_cipher_version(value vcipher) { CAMLparam1(vcipher); const char *version; SSL_CIPHER *cipher = (SSL_CIPHER *)vcipher; caml_release_runtime_system(); version = SSL_CIPHER_get_version(cipher); caml_acquire_runtime_system(); CAMLreturn(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); const 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_release_runtime_system(); if (dh != NULL) { if (SSL_CTX_set_tmp_dh(ctx, dh) != 1) { caml_acquire_runtime_system(); caml_raise_constant(*caml_named_value("ssl_exn_diffie_hellman_error")); } SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE); caml_acquire_runtime_system(); DH_free(dh); } else { caml_acquire_runtime_system(); caml_raise_constant(*caml_named_value("ssl_exn_diffie_hellman_error")); } CAMLreturn(Val_unit); } 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); const 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_release_runtime_system(); ecdh = EC_KEY_new_by_curve_name(nid); if (ecdh != NULL) { if (SSL_CTX_set_tmp_ecdh(ctx, ecdh) != 1) { caml_acquire_runtime_system(); caml_raise_constant(*caml_named_value("ssl_exn_ec_curve_error")); } SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE); caml_acquire_runtime_system(); EC_KEY_free(ecdh); } else { caml_acquire_runtime_system(); caml_raise_constant(*caml_named_value("ssl_exn_ec_curve_error")); } CAMLreturn(Val_unit); } /********************************* * 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) { CAMLparam1(vfilename); CAMLlocal1(block); const 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_release_runtime_system(); if ((PEM_read_X509(fh, &cert, 0, 0)) == NULL) { fclose(fh); ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); caml_acquire_runtime_system(); caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string(buf)); } fclose(fh); caml_acquire_runtime_system(); block = caml_alloc_custom(&cert_ops, sizeof(X509 *), 0, 1); Cert_val(block) = cert; CAMLreturn(block); } CAMLprim value ocaml_ssl_write_certificate(value vfilename, value certificate) { CAMLparam2(vfilename, certificate); const 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_release_runtime_system(); if (PEM_write_X509(fh, cert) == 0) { fclose(fh); ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); caml_acquire_runtime_system(); caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string(buf)); } fclose(fh); caml_acquire_runtime_system(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_get_certificate(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); char buf[256]; caml_release_runtime_system(); X509 *cert = SSL_get_peer_certificate(ssl); caml_acquire_runtime_system(); 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_release_runtime_system(); char *issuer = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0); caml_acquire_runtime_system(); 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_release_runtime_system(); char *subject = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0); caml_acquire_runtime_system(); 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_release_runtime_system(); ASN1_TIME_to_tm(X509_get0_notBefore(cert), &t); caml_acquire_runtime_system(); CAMLreturn(alloc_tm(&t)); } CAMLprim value ocaml_ssl_get_expiration_date(value certificate) { CAMLparam1(certificate); X509 *cert = Cert_val(certificate); struct tm t; caml_release_runtime_system(); ASN1_TIME_to_tm(X509_get0_notAfter(cert), &t); caml_acquire_runtime_system(); 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); const char *CAfile = String_val(ca_file); const char *CApath = String_val(ca_path); if (*CAfile == 0) CAfile = NULL; if (*CApath == 0) CApath = NULL; caml_release_runtime_system(); if (SSL_CTX_load_verify_locations(ctx, CAfile, CApath) != 1) { caml_acquire_runtime_system(); caml_invalid_argument("cafile or capath"); } caml_acquire_runtime_system(); 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_release_runtime_system(); ret = SSL_CTX_set_default_verify_paths(ctx); caml_acquire_runtime_system(); 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_release_runtime_system(); fd = SSL_get_fd(ssl); caml_acquire_runtime_system(); CAMLreturn(Val_int(fd)); } CAMLprim value ocaml_ssl_embed_socket(value socket_, value context) { CAMLparam2(socket_, 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_release_runtime_system(); ssl = SSL_new(ctx); if (!ssl) { caml_acquire_runtime_system(); caml_raise_constant(*caml_named_value("ssl_exn_handler_error")); } SSL_set_fd(ssl, socket); caml_acquire_runtime_system(); SSL_val(block) = ssl; CAMLreturn(block); } CAMLprim value ocaml_ssl_set_client_SNI_hostname(value socket, value vhostname) { CAMLparam2(socket, vhostname); SSL *ssl = SSL_val(socket); const char *hostname = String_val(vhostname); caml_release_runtime_system(); SSL_set_tlsext_host_name(ssl, hostname); caml_acquire_runtime_system(); CAMLreturn(Val_unit); } 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_release_runtime_system(); SSL_set_alpn_protos(ssl, protos, sizeof(protos)); caml_acquire_runtime_system(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_get_negotiated_alpn_protocol(value socket) { CAMLparam1(socket); CAMLlocal1(proto); 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.1.1/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. */ proto = caml_alloc_string(len); memcpy((char *)String_val(proto), (const char *)data, len); CAMLreturn(Val_some(proto)); } CAMLprim value ocaml_ssl_connect(value socket) { CAMLparam1(socket); int ret, err; SSL *ssl = SSL_val(socket); caml_release_runtime_system(); ERR_clear_error(); ret = SSL_connect(ssl); err = SSL_get_error(ssl, ret); caml_acquire_runtime_system(); 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_connect_blocking(value socket) { CAMLparam1(socket); int ret; SSL *ssl = SSL_val(socket); ERR_clear_error(); ret = SSL_connect(ssl); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_ssl_verify(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); long ans; caml_release_runtime_system(); ans = SSL_get_verify_result(ssl); caml_acquire_runtime_system(); 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_release_runtime_system(); X509_VERIFY_PARAM_set_hostflags(SSL_get0_param(ssl), flags); caml_acquire_runtime_system(); 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_release_runtime_system(); X509_VERIFY_PARAM_set1_host(SSL_get0_param(ssl), hostname, 0); caml_acquire_runtime_system(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_set1_ip(value socket, value ip) { CAMLparam2(socket, ip); SSL *ssl = SSL_val(socket); const char *ipval = String_val(ip); caml_release_runtime_system(); X509_VERIFY_PARAM_set1_ip_asc(SSL_get0_param(ssl), ipval); caml_acquire_runtime_system(); 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) < 0) caml_invalid_argument("Ssl.write: negative offset"); if (Int_val(length) < 0) caml_invalid_argument("Ssl.write: negative length"); if (Int_val(start) + Int_val(length) > caml_string_length(buffer)) caml_invalid_argument("Ssl.write: Buffer too short."); memmove(buf, (char *)String_val(buffer) + Int_val(start), buflen); caml_release_runtime_system(); ERR_clear_error(); ret = SSL_write(ssl, buf, buflen); err = SSL_get_error(ssl, ret); caml_acquire_runtime_system(); 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_blocking(value socket, value buffer, value start, value length) { CAMLparam2(socket, buffer); int ret; int buflen = Int_val(length); char *buf = (char *)String_val(buffer) + Int_val(start); SSL *ssl = SSL_val(socket); if (Int_val(start) < 0) caml_invalid_argument("Ssl.write: negative offset"); if (Int_val(length) < 0) caml_invalid_argument("Ssl.write: negative length"); if (Int_val(start) + Int_val(length) > caml_string_length(buffer)) caml_invalid_argument("Ssl.write: Buffer too short."); ERR_clear_error(); ret = SSL_write(ssl, buf, buflen); 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_release_runtime_system(); ERR_clear_error(); ret = SSL_write(ssl, buf, Int_val(length)); err = SSL_get_error(ssl, ret); caml_acquire_runtime_system(); 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; 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."); ERR_clear_error(); ret = SSL_write(ssl, buf, Int_val(length)); 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) < 0) caml_invalid_argument("Ssl.read: negative offset"); if (Int_val(length) < 0) caml_invalid_argument("Ssl.read: negative length"); if (Int_val(start) + Int_val(length) > caml_string_length(buffer)) caml_invalid_argument("Ssl.read: Buffer too short."); caml_release_runtime_system(); ERR_clear_error(); ret = SSL_read(ssl, buf, buflen); err = SSL_get_error(ssl, ret); caml_acquire_runtime_system(); 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_blocking(value socket, value buffer, value start, value length) { CAMLparam2(socket, buffer); int ret; int buflen = Int_val(length); char *buf = ((char *)String_val(buffer)) + Int_val(start); SSL *ssl = SSL_val(socket); if (Int_val(start) < 0) caml_invalid_argument("Ssl.read: negative offset"); if (Int_val(length) < 0) caml_invalid_argument("Ssl.read: negative length"); if (Int_val(start) + Int_val(length) > caml_string_length(buffer)) caml_invalid_argument("Ssl.read: Buffer too short."); ERR_clear_error(); ret = SSL_read(ssl, buf, buflen); 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_release_runtime_system(); ERR_clear_error(); ret = SSL_read(ssl, buf, Int_val(length)); err = SSL_get_error(ssl, ret); caml_acquire_runtime_system(); 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; 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)); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_ssl_accept(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); int ret, err; caml_release_runtime_system(); ERR_clear_error(); ret = SSL_accept(ssl); err = SSL_get_error(ssl, ret); caml_acquire_runtime_system(); 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_accept_blocking(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); int ret; ERR_clear_error(); ret = SSL_accept(ssl); CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_ssl_flush(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); BIO *bio; caml_release_runtime_system(); bio = SSL_get_wbio(ssl); if (bio) { int ret = BIO_flush(bio); if (ret != 1) { caml_acquire_runtime_system(); caml_raise_with_arg(*caml_named_value("ssl_exn_flush_error"), Val_bool(BIO_should_retry(bio))); }; } caml_acquire_runtime_system(); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_flush_blocking(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); int ret = 0; BIO *bio; bio = SSL_get_wbio(ssl); if (bio) { ret = BIO_flush(bio); /* From https://www.openssl.org/docs/man1.1.1/man3/BIO_flush.html: * * RETURN VALUES * * BIO_flush() returns 1 for success and 0 or -1 for failure. */ if (ret != 1 && BIO_should_retry(bio)) /* We return `-2` as a special return value (BIO_flush can only return * -1 <= ret <= 1) to signal to OCaml, without allocating, that the * operation should be retried. */ ret = -2; } CAMLreturn(Val_int(ret)); } CAMLprim value ocaml_ssl_shutdown(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); int ret; caml_release_runtime_system(); ERR_clear_error(); ret = SSL_shutdown(ssl); caml_acquire_runtime_system(); switch (ret) { case 0: case 1: /* close(SSL_get_fd(SSL_val(socket))); */ CAMLreturn(Val_int(ret)); default: ret = SSL_get_error(ssl, ret); caml_raise_with_arg(*caml_named_value("ssl_exn_connection_error"), Val_int(ret)); } } CAMLprim value ocaml_ssl_shutdown_blocking(value socket) { CAMLparam1(socket); SSL *ssl = SSL_val(socket); int ret; ERR_clear_error(); ret = SSL_shutdown(ssl); CAMLreturn(Val_int(ret)); } /* ======================================================== */ /* 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.7.0/src/ssl_threads.ml000066400000000000000000000015221445456742200170610ustar00rootroot00000000000000(* 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.7.0/src/ssl_threads.mli000066400000000000000000000017561445456742200172430ustar00rootroot00000000000000(* 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 *) val init : unit -> unit (** Make the library thread-safe. The should be called {i before} [Ssl.init]. *) ocaml-ssl-0.7.0/ssl.opam000066400000000000000000000015141445456742200151050ustar00rootroot00000000000000# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "0.7.0" synopsis: "Bindings for OpenSSL" maintainer: ["Antonio Monteiro "] authors: ["Samuel Mimram "] license: "LGPL-2.1-only WITH OCaml-LGPL-linking-exception" homepage: "https://github.com/savonet/ocaml-ssl" bug-reports: "https://github.com/savonet/ocaml-ssl/issues" depends: [ "dune" {>= "2.7"} "ocaml" {>= "4.03.0"} "ocaml" {with_test & >= "4.08.0"} "dune-configurator" "conf-libssl" "alcotest" {with-test} "bisect_ppx" {dev & >= "2.5.0"} "odoc" {with-doc} ] build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@runtest" {with-test} "@doc" {with-doc} ] ] dev-repo: "git+https://github.com/melange-re/melange.git" ocaml-ssl-0.7.0/tests/000077500000000000000000000000001445456742200145675ustar00rootroot00000000000000ocaml-ssl-0.7.0/tests/HACKING.md000066400000000000000000000041301445456742200161530ustar00rootroot00000000000000 ## Generating test certificates ### CA #### Configuration (ca.conf) ``` [ req ] encrypt_key = no default_md = sha256 prompt = no utf8 = yes distinguished_name = my_req_distinguished_name req_extensions = my_extensions [ my_req_distinguished_name ] C = US ST = California L = San Francisco O = ca CN = CA [ my_extensions ] keyUsage=critical, digitalSignature, keyEncipherment basicConstraints=critical,CA:TRUE extendedKeyUsage=critical,serverAuth subjectKeyIdentifier = hash ``` #### Create the CA certificate ```shell $ openssl genpkey -algorithm EC -out ca.key -pkeyopt ec_paramgen_curve:secp384r1 -pkeyopt ec_param_enc:named_curve $ openssl req -new -x509 -days 3650 -config ca.conf -out ca.pem -key ca.key ``` ### Server cert #### Configuration (server.conf) ``` [ req ] encrypt_key = no default_md = sha256 prompt = no utf8 = yes distinguished_name = my_req_distinguished_name [ my_req_distinguished_name ] C = US ST = California L = San Francisco O = ocaml-ssl CN = localhost ``` #### Extensions (ssl-extensions-x509.conf) ``` [v3_ca] keyUsage=critical, digitalSignature, keyEncipherment basicConstraints=critical,CA:FALSE extendedKeyUsage=critical,serverAuth subjectKeyIdentifier = hash # subjectAltName = IP:127.0.0.1 ``` #### Create the server certificate ```shell openssl genpkey -algorithm EC -out server.key -pkeyopt ec_paramgen_curve:secp384r1 -pkeyopt ec_param_enc:named_curve openssl req -new -config server.conf -out server.csr -key server.key openssl x509 -req -in server.csr -CA ca.pem -CAkey ca.key -CAcreateserial -out server.pem -days 3650 -extensions v3_ca -extfile ./ssl-extensions-x509.conf ``` ### Client cert #### Configuration (client.conf) ``` [ req ] encrypt_key = no default_md = sha256 prompt = no utf8 = yes distinguished_name = my_req_distinguished_name [ my_req_distinguished_name ] C = US ST = California L = San Francisco O = ocaml-ssl CN = localhost ``` #### Extensions (ssl-extensions-x509.conf) ``` [v3_ca] keyUsage=critical, digitalSignature, keyEncipherment basicConstraints=critical,CA:FALSE extendedKeyUsage=critical,clientAuth subjectKeyIdentifier = hash ``` ocaml-ssl-0.7.0/tests/ca.key000066400000000000000000000004621445456742200156660ustar00rootroot00000000000000-----BEGIN PRIVATE KEY----- MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDBkdrXwGfmriQHz91uW GFytWEr++SdP15eRSpNSUP4znqzE+Daa4OrdTWaPBxvscN+hZANiAAQvJmpC1QYy +M9pWBnLhYR10AB5fLNIaIUz+0LXT+/ZHIJM5lUNfia1Df2VUFjaGD8FXVpEKCER 5MiudFF9p77TKx3P4X19FVZxaRBVpC3EDc3SbmWVdNRNEJDqtf9Q6+U= -----END PRIVATE KEY----- ocaml-ssl-0.7.0/tests/ca.pem000066400000000000000000000013151445456742200156550ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIB5TCCAWoCFDBrMFYllS8JBuVChmWZEj15A7QeMAoGCCqGSM49BAMCMFYxCzAJ BgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJh bmNpc2NvMQ0wCwYDVQQKDARQaWFmMQswCQYDVQQDDAJDQTAeFw0yMjA3MjYwNTA0 NDJaFw0zMjA3MjMwNTA0NDJaMFYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxp Zm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMQ0wCwYDVQQKDARQaWFmMQsw CQYDVQQDDAJDQTB2MBAGByqGSM49AgEGBSuBBAAiA2IABC8makLVBjL4z2lYGcuF hHXQAHl8s0hohTP7QtdP79kcgkzmVQ1+JrUN/ZVQWNoYPwVdWkQoIRHkyK50UX2n vtMrHc/hfX0VVnFpEFWkLcQNzdJuZZV01E0QkOq1/1Dr5TAKBggqhkjOPQQDAgNp ADBmAjEAp2cn0sd2Y8JrJ6SM0IbtfKMIFm1/IWBD6QlaKXp1K/97cbG2iLxBfA4b di1iUalmAjEArSxnaNRcwR94inRe0X2ye3RjyZ7Y9VV8Gz72RPcMZqCDviM+Z+XE 1L373KW6df6s -----END CERTIFICATE----- ocaml-ssl-0.7.0/tests/client.key000066400000000000000000000004621445456742200165610ustar00rootroot00000000000000-----BEGIN PRIVATE KEY----- MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDBAFIhLeQCh3Vr38W5/ SljAb/8dibzfLx1mSfZa67Rj7146rT+2H5Xt/9kc1gZ5+sahZANiAATf4QnBA5ly rtV1W64/P3Lf5VkKjlbEHK+Cjv9zSFeSOCAAbO9De8MtDPz0TtGIY/3KJYuk55Wk jDIy2hyBmj3PapkzcknY2ehJ9WqVTCmSJeJXOOa8ZDMtPJoKs0N47Bo= -----END PRIVATE KEY----- ocaml-ssl-0.7.0/tests/client.pem000066400000000000000000000015331445456742200165520ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICTjCCAdSgAwIBAgIUWOL/1FKAVbBQ/H8T+jcdZFRHK/AwCgYIKoZIzj0EAwIw VjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDVNh biBGcmFuY2lzY28xDTALBgNVBAoMBFBpYWYxCzAJBgNVBAMMAkNBMB4XDTIyMDcy NjA1MDc1M1oXDTMyMDcyMzA1MDc1M1owYjELMAkGA1UEBhMCVVMxEzARBgNVBAgM CkNhbGlmb3JuaWExFjAUBgNVBAcMDVNhbiBGcmFuY2lzY28xEjAQBgNVBAoMCU9j YW1sLXNzbDESMBAGA1UEAwwJbG9jYWxob3N0MHYwEAYHKoZIzj0CAQYFK4EEACID YgAE3+EJwQOZcq7VdVuuPz9y3+VZCo5WxByvgo7/c0hXkjggAGzvQ3vDLQz89E7R iGP9yiWLpOeVpIwyMtocgZo9z2qZM3JJ2NnoSfVqlUwpkiXiVzjmvGQzLTyaCrND eOwao1cwVTAOBgNVHQ8BAf8EBAMCBaAwDAYDVR0TAQH/BAIwADAWBgNVHSUBAf8E DDAKBggrBgEFBQcDAjAdBgNVHQ4EFgQU/EaKG12PauyLW2p/c7YUoftr94MwCgYI KoZIzj0EAwIDaAAwZQIxANKW81OppCUUhkdqKcYCUC6iHVCVIgUiq2+EGcnpgBc3 P1KXQAuT7UUoFRhaCaQsFAIwb6g0MRYeIFYGOwN0WZAfgBg1pPAcg46OobcYuXLu Xez9As8y7oKlQDAP9G43jZ3k -----END CERTIFICATE----- ocaml-ssl-0.7.0/tests/dh4096.pem000066400000000000000000000014011445456742200162040ustar00rootroot00000000000000-----BEGIN DH PARAMETERS----- MIICCAKCAgEAuP5nM1BZvm05N3AOalZ0kHQOCQxT02a75wXhZiQuKFpvPZTG+9C2 jnmv9byChnpBNf/JlewzvjSejHjpTrR8cylgotfB4Qk5p3GCol3daf1EmsTmCx3C 5c3DqmSmNvQ5BUqK7SpGF9cSzKovLAdXqpxWSNecRUbb7qnogWBuB0ez4HhPfEPn vW/rcg32e5aKapuvSdhIDoj/wVRfxHv4gX1AoUxKpInCCcAr3gDwJr0Gfz5FmCey OJyRZo59FEm5HQpzHOTIhxUMWGFimgJjs1JVt2uCQ3Hka+osh42xViinzxVwtJTW YKf/j24Iw952i6pUAONbgonIlJ5E3JYZg/8RxbDwPNg/GzIVvCFiowEdG/TWlsnK t+68kysWkOHGjZATvkEjLkNnNBKKEkpwHrNmilJ3ygzLTsE9PaEcygTDmm2vVRbC PA5tX8uUzo+OW3HIZmhEiaP7f5zyWQ0ce2lPfxNj6UGTuUcK31x4UwZaMfvMWN6X M8HQmQAaaJNXpSPYIT1xqoRgMKFsWZ3sYddiaKKHnr6pBFT38c43Zhiag033TLAC nmvD0nyYnirUrVnV2HWve3r52+UD2cza5775pnI51s8knyj+b1XMujeeywX9BeRD mgPdM5XkIGGe8oPtaBQmNcs6SuXaHlny2fCP7ef+vDQxV32TTL4TWzMCAQI= -----END DH PARAMETERS----- ocaml-ssl-0.7.0/tests/digicert_certificate.pem000066400000000000000000000025271445456742200214340ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3 LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm +9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3 hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2 Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep +OkuE6N36B9K -----END CERTIFICATE----- ocaml-ssl-0.7.0/tests/dune000066400000000000000000000021461445456742200154500ustar00rootroot00000000000000(alias (name github_action_tests) (deps (alias_rec runtest))) (library (name util) (modules util) (libraries ssl threads str alcotest)) (test (name ssl_test) (modules ssl_test) (libraries ssl alcotest) (deps digicert_certificate.pem)) (test (name ssl_comm) (modules ssl_comm) (libraries ssl alcotest)) (executable (name ssl_version) (modules ssl_version) (libraries ssl alcotest)) (rule (alias github_action_tests) (action (run ./ssl_version.exe))) (test (name ssl_context) (modules ssl_context) (libraries ssl alcotest util) (deps client.pem client.key server.key ca.pem ca.key)) (test (name ssl_ciphers) (modules ssl_ciphers) (libraries ssl alcotest util) (deps client.pem client.key dh4096.pem server.key server.pem)) (test (name ssl_certs) (modules ssl_certs) (libraries ssl alcotest util) (deps client.pem ca.pem ca.key server.key server.pem)) (test (name ssl_sock) (modules ssl_sock) (libraries ssl alcotest util) (deps ca.pem ca.key server.key server.pem)) (test (name ssl_io) (modules ssl_io) (libraries ssl alcotest util) (deps ca.pem ca.key server.key server.pem)) ocaml-ssl-0.7.0/tests/expired.pem000077500000000000000000000036061445456742200167420ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIFSzCCBDOgAwIBAgIQSueVSfqavj8QDxekeOFpCTANBgkqhkiG9w0BAQsFADCB kDELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxNjA0BgNV BAMTLUNPTU9ETyBSU0EgRG9tYWluIFZhbGlkYXRpb24gU2VjdXJlIFNlcnZlciBD QTAeFw0xNTA0MDkwMDAwMDBaFw0xNTA0MTIyMzU5NTlaMFkxITAfBgNVBAsTGERv bWFpbiBDb250cm9sIFZhbGlkYXRlZDEdMBsGA1UECxMUUG9zaXRpdmVTU0wgV2ls ZGNhcmQxFTATBgNVBAMUDCouYmFkc3NsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQAD ggEPADCCAQoCggEBAMIE7PiM7gTCs9hQ1XBYzJMY61yoaEmwIrX5lZ6xKyx2PmzA S2BMTOqytMAPgLaw+XLJhgL5XEFdEyt/ccRLvOmULlA3pmccYYz2QULFRtMWhyef dOsKnRFSJiFzbIRMeVXk0WvoBj1IFVKtsyjbqv9u/2CVSndrOfEk0TG23U3AxPxT uW1CrbV8/q71FdIzSOciccfCFHpsKOo3St/qbLVytH5aohbcabFXRNsKEqveww9H dFxBIuGa+RuT5q0iBikusbpJHAwnnqP7i/dAcgCskgjZjFeEU4EFy+b+a1SYQCeF xxC7c3DvaRhBB0VVfPlkPz0sw6l865MaTIbRyoUCAwEAAaOCAdUwggHRMB8GA1Ud IwQYMBaAFJCvajqUWgvYkOoSVnPfQ7Q6KNrnMB0GA1UdDgQWBBSd7sF7gQs6R2lx GH0RN5O8pRs/+zAOBgNVHQ8BAf8EBAMCBaAwDAYDVR0TAQH/BAIwADAdBgNVHSUE FjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwTwYDVR0gBEgwRjA6BgsrBgEEAbIxAQIC BzArMCkGCCsGAQUFBwIBFh1odHRwczovL3NlY3VyZS5jb21vZG8uY29tL0NQUzAI BgZngQwBAgEwVAYDVR0fBE0wSzBJoEegRYZDaHR0cDovL2NybC5jb21vZG9jYS5j b20vQ09NT0RPUlNBRG9tYWluVmFsaWRhdGlvblNlY3VyZVNlcnZlckNBLmNybDCB hQYIKwYBBQUHAQEEeTB3ME8GCCsGAQUFBzAChkNodHRwOi8vY3J0LmNvbW9kb2Nh LmNvbS9DT01PRE9SU0FEb21haW5WYWxpZGF0aW9uU2VjdXJlU2VydmVyQ0EuY3J0 MCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC5jb21vZG9jYS5jb20wIwYDVR0RBBww GoIMKi5iYWRzc2wuY29tggpiYWRzc2wuY29tMA0GCSqGSIb3DQEBCwUAA4IBAQBq evHa/wMHcnjFZqFPRkMOXxQhjHUa6zbgH6QQFezaMyV8O7UKxwE4PSf9WNnM6i1p OXy+l+8L1gtY54x/v7NMHfO3kICmNnwUW+wHLQI+G1tjWxWrAPofOxkt3+IjEBEH fnJ/4r+3ABuYLyw/zoWaJ4wQIghBK4o+gk783SHGVnRwpDTysUCeK1iiWQ8dSO/r ET7BSp68ZVVtxqPv1dSWzfGuJ/ekVxQ8lEEFeouhN0fX9X3c+s5vMaKwjOrMEpsi 8TRwz311SotoKQwe6Zaoz7ASH1wq7mcvf71z81oBIgxw+s1F73hczg36TuHvzmWf RwxPuzZEaFZcVlmtqoq8 -----END CERTIFICATE----- ocaml-ssl-0.7.0/tests/server.key000066400000000000000000000004621445456742200166110ustar00rootroot00000000000000-----BEGIN PRIVATE KEY----- MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDDHhWjSht5HNmGvrOlg SyEG8EvPIbnnMbqZ1R3RfcVqF9LK2llxvp/JPawIT2IXtFWhZANiAASesxY+SyVB EI9UHLID9jfW2LgKrZw3xUgMsrlf7euIsEbrKqeioF7BUck7E14C+GAfTtBMpcbZ oM1N5bFkb8Pj6lv9fVdssuvCI1BD+YOdZKooxgD2VLY2kHlzrLT0Sbo= -----END PRIVATE KEY----- ocaml-ssl-0.7.0/tests/server.pem000066400000000000000000000015471445456742200166070ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICVTCCAdugAwIBAgIUB93I7gBe/EwcDe6NPT4GJdHkgxwwCgYIKoZIzj0EAwIw VjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDVNh biBGcmFuY2lzY28xDTALBgNVBAoMBFBpYWYxCzAJBgNVBAMMAkNBMB4XDTIyMDcy NjA1MTUyNFoXDTMyMDcyMzA1MTUyNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgM CkNhbGlmb3JuaWExFjAUBgNVBAcMDVNhbiBGcmFuY2lzY28xGTAXBgNVBAoMEE9j YW1sLXNzbC1zZXJ2ZXIxEjAQBgNVBAMMCWxvY2FsaG9zdDB2MBAGByqGSM49AgEG BSuBBAAiA2IABJ6zFj5LJUEQj1QcsgP2N9bYuAqtnDfFSAyyuV/t64iwRusqp6Kg XsFRyTsTXgL4YB9O0EylxtmgzU3lsWRvw+PqW/19V2yy68IjUEP5g51kqijGAPZU tjaQeXOstPRJuqNXMFUwDgYDVR0PAQH/BAQDAgWgMAwGA1UdEwEB/wQCMAAwFgYD VR0lAQH/BAwwCgYIKwYBBQUHAwEwHQYDVR0OBBYEFIahBb2QErL7b8mFRKt0rc37 63B9MAoGCCqGSM49BAMCA2gAMGUCMFYUsczgi7xp6c+cojEcon+GjEPMofA/ni0Z D91IVA87kGkoxDJ+dWG2/RGRiba9XAIxAN/b1g65qLB0ZeEn2F7GyyP2mJfrkGug ZTFUwNLx66gj7u03YfQk5tQzh6t4iObPWg== -----END CERTIFICATE----- ocaml-ssl-0.7.0/tests/ssl_certs.ml000066400000000000000000000036611445456742200171300ustar00rootroot00000000000000open Alcotest open Util let test_read_cert () = let cert = Ssl.read_certificate "client.pem" in check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error); let issuer = Ssl.get_issuer cert in let subject = Ssl.get_subject cert in let start_date = Ssl.get_start_date cert in let expiration_date = Ssl.get_expiration_date cert in let digest = Ssl.digest `SHA1 cert in check string "read issuer" "/C=US/ST=California/L=San Francisco/O=Piaf/CN=CA" issuer; check string "read subject" "/C=US/ST=California/L=San Francisco/O=Ocaml-ssl/CN=localhost" subject; check int "read start date" 26 start_date.tm_mday; check int "read expiration date" 23 expiration_date.tm_mday; check string "read digest" "_m\228R\240\250\023\253\1927\146CP(W'\238z\2489" digest let test_cert_connection () = let addr = Unix.ADDR_INET (Unix.inet_addr_of_string "127.0.0.1", 1338) in Util.server_thread addr None |> ignore; let context = Ssl.create_context TLSv1_3 Client_context in let set_default = Ssl.set_default_verify_paths context in Ssl.load_verify_locations context "ca.pem" ""; let ssl = Ssl.open_connection_with_context context addr in let cert = Ssl.get_certificate ssl in let subject = Ssl.get_subject cert in let verify_result = Ssl.get_verify_result ssl in let error_string = Ssl.get_verify_error_string 0 in Ssl.shutdown_connection ssl; check bool "set default succeded" true set_default; check string "check certificate" "/C=US/ST=California/L=San Francisco/O=Ocaml-ssl-server/CN=localhost" subject; check int "check verify result" 0 verify_result; check string "check error string" "ok" error_string let () = Alcotest.run "Ssl certificate functions" [ ( "Certificates" , [ test_case "Read certificate functions" `Quick test_read_cert ; test_case "Certificate on connection" `Quick test_cert_connection ] ) ] ocaml-ssl-0.7.0/tests/ssl_ciphers.ml000066400000000000000000000047101445456742200174410ustar00rootroot00000000000000open Ssl open Alcotest open Util let test_disable_protocols () = let context = Ssl.create_context TLSv1_3 Server_context in Ssl.disable_protocols context [ (SSLv23 [@ocaml.alert "-deprecated"]) ]; check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error) let test_set_cipher_list () = let context = Ssl.create_context TLSv1_3 Server_context in Ssl.set_cipher_list context "ALL"; Ssl.honor_cipher_order context; check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error); check_raises "empty cipher list" Cipher_error (fun () -> Ssl.set_cipher_list context ""); check_raises "invalid cipher list" Cipher_error (fun () -> Ssl.set_cipher_list context "NULL-MD55:ASD") let test_cipher_init_dh () = let context = Ssl.create_context TLSv1_3 Server_context in Ssl.use_certificate context "client.pem" "client.key"; Ssl.init_dh_from_file context "dh4096.pem"; check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error) let test_init_ec_from_named_curve () = let context = Ssl.create_context TLSv1_3 Server_context in Ssl.init_ec_from_named_curve context "secp384r1"; check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error) let test_socket_cipher_funcs () = let addr = Unix.ADDR_INET (Unix.inet_addr_of_string "127.0.0.1", 1337) in Util.server_thread addr None |> ignore; let context = Ssl.create_context TLSv1_3 Client_context in let ssl = open_connection_with_context context addr in let cipher = Ssl.get_cipher ssl in let name = Ssl.get_cipher_name cipher in let description = Ssl.get_cipher_description cipher in let version = Ssl.get_cipher_version cipher in let socket_version = Ssl.version ssl in Ssl.shutdown_connection ssl; check string "cipher name" "TLS_AES_256_GCM_SHA384" name; check bool "cipher description" true (Str.string_partial_match (Str.regexp ".*Enc=AESGCM(256).*") description 0); check string "cipher version" "TLSv1.3" version; check protocol_testable "socket version" TLSv1_3 socket_version let () = Alcotest.run "Ssl cipher functions" [ ( "Ciphers" , [ test_case "Disable protocols" `Quick test_disable_protocols ; test_case "Set cipher list" `Quick test_set_cipher_list ; test_case "Init DH params" `Quick test_cipher_init_dh ; test_case "Init EC params" `Quick test_init_ec_from_named_curve ; test_case "Cipher funcs" `Quick test_socket_cipher_funcs ] ) ] ocaml-ssl-0.7.0/tests/ssl_comm.ml000066400000000000000000000024731445456742200167430ustar00rootroot00000000000000open Alcotest open Ssl let test_init () = init () |> ignore let test_error_queue () = let context = Ssl.create_context TLSv1_3 Client_context in try use_certificate context "expired.pem" "" with | _ -> (); let err = Error.peek_error () in check int "Error code" 32 err.library_number; check string "Library string" "BIO routines" (Option.get err.lib); check string "Reason string" "system lib" (Option.get err.reason); let err = Error.peek_last_error () in check int "Error code" 20 err.library_number; check string "Library string" "SSL routines" (Option.get err.lib); check string "Reason string" "system lib" (Option.get err.reason); let err = Error.get_error () in check int "Error code" 32 err.library_number; check string "Library string" "BIO routines" (Option.get err.lib); check string "Reason string" "system lib" (Option.get err.reason); let err = Error.get_error () in check int "Error code" 20 err.library_number; check string "Library string" "SSL routines" (Option.get err.lib); check string "Reason string" "system lib" (Option.get err.reason) let () = Alcotest.run "Ssl communication" [ ( "Communication" , [ test_case "Test init" `Quick test_init ; test_case "Test error queue" `Quick test_error_queue ] ) ] ocaml-ssl-0.7.0/tests/ssl_context.ml000066400000000000000000000137061445456742200174750ustar00rootroot00000000000000open Ssl open Alcotest open Util let certfile = open_in "client.pem" let certstring = really_input_string certfile (in_channel_length certfile) let clientkeyfile = open_in "client.key" let clientkeystring = really_input_string clientkeyfile (in_channel_length clientkeyfile) let serverkeyfile = open_in "server.key" let serverkeystring = really_input_string serverkeyfile (in_channel_length serverkeyfile) let test_create_context () = Ssl.create_context TLSv1_3 Server_context |> ignore; check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error) let test_add_extra_chain_cert () = let context = Ssl.create_context TLSv1_3 Server_context in Ssl.add_extra_chain_cert context certstring; check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error); check_raises "certificate error" (Certificate_error "") (fun () -> try Ssl.add_extra_chain_cert context "" with | Certificate_error _ -> raise (Certificate_error "")) let test_add_cert_to_store () = let context = Ssl.create_context TLSv1_3 Server_context in Ssl.add_cert_to_store context certstring; check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error); check_raises "certificate error" (Certificate_error "") (fun () -> try Ssl.add_cert_to_store context "" with | Certificate_error _ -> raise (Certificate_error "")) let test_use_certificate () = let context = Ssl.create_context TLSv1_3 Server_context in Ssl.use_certificate context "client.pem" "client.key"; check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error); check_raises "certificate error" (Certificate_error "") (fun () -> try Ssl.use_certificate context "" "client.key" with | Certificate_error _ -> raise (Certificate_error "")); check_raises "key error" (Private_key_error "") (fun () -> try Ssl.use_certificate context "client.pem" "" with | Private_key_error _ -> raise (Private_key_error "")); check_raises "unmatching key" (Private_key_error "") (fun () -> try Ssl.use_certificate context "client.pem" "server.key" with | Private_key_error _ -> raise (Private_key_error "")) let test_use_certificate_from_string () = let context = Ssl.create_context TLSv1_3 Server_context in Ssl.use_certificate_from_string context certstring clientkeystring; check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error); check_raises "certificate error" (Certificate_error "") (fun () -> try Ssl.use_certificate_from_string context "" clientkeystring with | Certificate_error _ -> raise (Certificate_error "")); check_raises "key error" (Private_key_error "") (fun () -> try Ssl.use_certificate_from_string context certstring "" with | Private_key_error _ -> raise (Private_key_error "")); check_raises "unmatching key" (Private_key_error "") (fun () -> try Ssl.use_certificate_from_string context certstring serverkeystring with | Private_key_error _ -> raise (Private_key_error "")) let test_set_password_callback () = let context = Ssl.create_context TLSv1_3 Server_context in Ssl.set_password_callback context (fun _ -> "password"); check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error) let test_set_client_CA_list_from_file () = let context = Ssl.create_context TLSv1_3 Server_context in Ssl.set_client_CA_list_from_file context "ca.pem"; check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error); check_raises "certificate error" (Certificate_error "") (fun () -> try Ssl.set_client_CA_list_from_file context "" with | Certificate_error _ -> raise (Certificate_error "")) let test_set_client_verify_callback () = let context = Ssl.create_context TLSv1_3 Server_context in Ssl.set_verify_depth context 1; Ssl.use_certificate context "client.pem" "client.key"; Ssl.set_client_verify_callback_verbose true; Ssl.set_verify context [ Verify_peer ] (Some Ssl.client_verify_callback); check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error); check_raises "verify depth error" (Invalid_argument "depth") (fun () -> Ssl.set_verify_depth context (-1)) let test_context_alpn () = let context = Ssl.create_context TLSv1_3 Server_context in Ssl.set_context_alpn_protos context [ "http/1.1" ]; Ssl.set_context_alpn_select_callback context (fun _ -> Some "http/1.1"); check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error) let test_set_version () = let context = Ssl.create_context TLSv1_3 Server_context in check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error); let[@alert "-deprecated"] tlsv1 = TLSv1 in Ssl.set_min_protocol_version context tlsv1; check protocol_testable "min version" tlsv1 (Ssl.get_min_protocol_version context); check protocol_testable "max version" TLSv1_3 (Ssl.get_max_protocol_version context); (* Set max *) Ssl.set_max_protocol_version context TLSv1_2; check protocol_testable "max version" TLSv1_2 (Ssl.get_max_protocol_version context) let () = Alcotest.run "Ssl context" [ ( "Context" , [ test_case "Create context" `Quick test_create_context ; test_case "Add extra chain cert" `Quick test_add_extra_chain_cert ; test_case "Add cert to store" `Quick test_add_cert_to_store ; test_case "Use certificate" `Quick test_use_certificate ; test_case "Use certificate from string" `Quick test_use_certificate_from_string ; test_case "Set password callback" `Quick test_set_password_callback ; test_case "Set client CA list from file" `Quick test_set_client_CA_list_from_file ; test_case "Set verify functions" `Quick test_set_client_verify_callback ; test_case "Context alpn" `Quick test_context_alpn ; test_case "Set min / max protocol version" `Quick test_set_version ] ) ] ocaml-ssl-0.7.0/tests/ssl_io.ml000066400000000000000000000041211445456742200164070ustar00rootroot00000000000000open Alcotest let test_verify () = let addr = Unix.ADDR_INET (Unix.inet_addr_of_string "127.0.0.1", 1342) in Util.server_thread addr None |> ignore; let context = Ssl.create_context TLSv1_3 Client_context in let ssl = Ssl.open_connection_with_context context addr in let verify_result = try Ssl.verify ssl; "" with | e -> Printexc.to_string e in Ssl.shutdown_connection ssl; check bool "no verify errors" true (Str.search_forward (Str.regexp_string "error:00:000000:lib(0)") verify_result 0 > 0) let test_set_host () = let addr = Unix.ADDR_INET (Unix.inet_addr_of_string "127.0.0.1", 1343) in Util.server_thread addr None |> ignore; let context = Ssl.create_context TLSv1_3 Client_context in let domain = Unix.domain_of_sockaddr addr in let sock = Unix.socket domain Unix.SOCK_STREAM 0 in let ssl = Ssl.embed_socket sock context in Ssl.set_host ssl "localhost"; Unix.connect sock addr; Ssl.connect ssl; let verify_result = try Ssl.verify ssl; "" with | e -> Printexc.to_string e in Ssl.shutdown_connection ssl; check bool "no verify errors" true (Str.search_forward (Str.regexp_string "error:00:000000:lib(0)") verify_result 0 > 0) let test_read_write () = let addr = Unix.ADDR_INET (Unix.inet_addr_of_string "127.0.0.1", 1344) in Util.server_thread addr (Some (fun _ -> "received")) |> ignore; let context = Ssl.create_context TLSv1_3 Client_context in let ssl = Ssl.open_connection_with_context context addr in let send_msg = "send" in let write_buf = Bytes.create (String.length send_msg) in Ssl.write ssl write_buf 0 4 |> ignore; let read_buf = Bytes.create 8 in Ssl.read ssl read_buf 0 8 |> ignore; Ssl.shutdown_connection ssl; check string "received message" "received" (Bytes.to_string read_buf) let () = run "Ssl io functions" [ ( "IO" , [ test_case "Verify" `Quick test_verify ; test_case "Set host" `Quick test_set_host ; test_case "Read write" `Quick test_read_write ] ) ] ocaml-ssl-0.7.0/tests/ssl_sock.ml000066400000000000000000000030031445456742200167350ustar00rootroot00000000000000open Alcotest open Util let test_sockets_sni () = let addr = Unix.ADDR_INET (Unix.inet_addr_of_string "127.0.0.1", 1340) in Util.server_thread addr None |> ignore; let context = Ssl.create_context TLSv1_3 Client_context in let domain = Unix.domain_of_sockaddr addr in let sock = Unix.socket domain Unix.SOCK_STREAM 0 in let ssl = Ssl.embed_socket sock context in Ssl.set_client_SNI_hostname ssl "localhost"; Unix.connect sock addr; Ssl.connect ssl; Ssl.flush ssl; Ssl.shutdown_connection ssl; check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error) let test_sockets_alpn () = let addr = Unix.ADDR_INET (Unix.inet_addr_of_string "127.0.0.1", 1341) in Util.server_thread addr None |> ignore; let context = Ssl.create_context TLSv1_3 Client_context in let domain = Unix.domain_of_sockaddr addr in let sock = Unix.socket domain Unix.SOCK_STREAM 0 in let ssl = Ssl.embed_socket sock context in Ssl.set_alpn_protos ssl [ "http/1.1" ]; Unix.connect sock addr; Ssl.connect ssl; let negotatiated_proto = Ssl.get_negotiated_alpn_protocol ssl in Ssl.flush ssl; Ssl.shutdown_connection ssl; check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error); check (option string) "protocol negotiated" (Some "http/1.1") negotatiated_proto let () = Alcotest.run "Ssl socket functions" [ ( "Sockets" , [ test_case "Set client SNI" `Quick test_sockets_sni ; test_case "ALPN protocols" `Quick test_sockets_alpn ] ) ] ocaml-ssl-0.7.0/tests/ssl_test.ml000066400000000000000000000021361445456742200167630ustar00rootroot00000000000000(** Get the colon-separated hex representation of a binary string. *) let hex_digest digest = let rec go acc i = if i < 0 then acc else let byte = Printf.sprintf "%02X" @@ int_of_char digest.[i] in go (byte :: acc) (i - 1) in go [] (String.length digest - 1) |> String.concat ":" (* The reference hashes come from Firefox's certificate viewer. It doesn't show * the SHA384 hash, hence its absence from the tests. *) let test_sha1 () = Alcotest.(check string) "same digest" "5F:B7:EE:06:33:E2:59:DB:AD:0C:4C:9A:E6:D3:8F:1A:61:C7:DC:25" Ssl.( read_certificate "digicert_certificate.pem" |> digest `SHA1 |> hex_digest) let test_sha256 () = Alcotest.(check string) "same digest" "74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF" Ssl.( read_certificate "digicert_certificate.pem" |> digest `SHA256 |> hex_digest) let () = let open Alcotest in run "Ssl" [ ( "digest" , [ test_case "SHA1" `Quick test_sha1 ; test_case "SHA256" `Quick test_sha256 ] ) ] ocaml-ssl-0.7.0/tests/ssl_version.ml000066400000000000000000000015201445456742200174650ustar00rootroot00000000000000open Alcotest open Ssl let test_init () = init () |> ignore (* This test is not super robust b/c `openssl` might not be installed or installed but linked to a different shared libary. For this reason, this test is only run in our internal github action CI. *) let test_version () = let ch = Unix.open_process_in "openssl version" in let m, n, p = Scanf.(bscanf (Scanning.from_channel ch)) "OpenSSL %d.%d.%d" (fun x y z -> x, y, z) in Unix.close_process_in ch |> ignore; check int "major" m Ssl.native_library_version.major; check int "minor" n Ssl.native_library_version.minor; check int "patch" p Ssl.native_library_version.patch let () = Alcotest.run "Ssl version" [ ( "Version" , [ test_case "Test init" `Quick test_init ; test_case "Test version" `Quick test_version ] ) ] ocaml-ssl-0.7.0/tests/util.ml000066400000000000000000000054631445456742200161060ustar00rootroot00000000000000module Ssl = struct include Ssl let[@ocaml.alert "-deprecated"] get_error_string = get_error_string end open Ssl type server_args = { address : Unix.sockaddr ; condition : Condition.t ; mutex : Mutex.t ; parser : (string -> string) option } let server_rw_loop ssl parser_func = let rw_loop = ref true in while !rw_loop do try let read_buf = Bytes.create 256 in let read_bytes = read ssl read_buf 0 256 in if read_bytes > 0 then ( let input = Bytes.to_string read_buf in let response = parser_func input in Ssl.write_substring ssl response 0 (String.length response) |> ignore; Ssl.close_notify ssl |> ignore; rw_loop := false) with | Read_error read_error -> (match read_error with Error_ssl -> rw_loop := false | _ -> ()) done let server_init args = try (* Server initialization *) Mutex.lock args.mutex; let socket = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in Unix.setsockopt socket Unix.SO_REUSEADDR true; Unix.bind socket args.address; let context = create_context TLSv1_3 Server_context in use_certificate context "server.pem" "server.key"; Ssl.set_context_alpn_select_callback context (fun client_protos -> List.find_opt (fun opt -> opt = "http/1.1") client_protos); (* Signal ready and listen for connection *) Unix.listen socket 1; Some (socket, context) with | exn -> Printexc.to_string exn |> print_endline; None let server_listen args = match server_init args with | None -> Mutex.unlock args.mutex; Condition.signal args.condition; Thread.exit () [@warning "-3"] | Some (socket, context) -> Mutex.unlock args.mutex; Condition.signal args.condition; let listen = Unix.accept socket in let ssl = embed_socket (fst listen) context in accept ssl; (* Exit right away unless we need to rw *) (match args.parser with | Some parser_func -> server_rw_loop ssl parser_func | None -> (); shutdown ssl; Thread.exit () [@warning "-3"]) let server_thread addr parser = let mutex = Mutex.create () in Mutex.lock mutex; let condition = Condition.create () in let args = { address = addr; condition; mutex; parser } in let thread = Thread.create server_listen args in Condition.wait condition mutex; thread let check_ssl_no_error err = Str.string_partial_match (Str.regexp_string "error:00000000:lib(0)") err 0 let[@ocaml.alert "-deprecated"] pp_protocol ppf = function | SSLv23 -> Format.fprintf ppf "SSLv23" | SSLv3 -> Format.fprintf ppf "SSLv3" | TLSv1 -> Format.fprintf ppf "TLSv1" | TLSv1_1 -> Format.fprintf ppf "TLSv1_1" | TLSv1_2 -> Format.fprintf ppf "TLSv1_2" | TLSv1_3 -> Format.fprintf ppf "TLSv1_3" let protocol_testable = Alcotest.testable pp_protocol (fun r1 r2 -> r1 == r2)