pax_global_header00006660000000000000000000000064152717272220014521gustar00rootroot0000000000000052 comment=e56a3a63c5566e9df1d646ca96f5548dd4a7df40 ocaml-ssl-0.8.1/000077500000000000000000000000001527172722200134215ustar00rootroot00000000000000ocaml-ssl-0.8.1/.devcontainer.json000077500000000000000000000005561527172722200170640ustar00rootroot00000000000000{ "image":"ocaml/opam:ubuntu-22.04-ocaml-4.14", "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.8.1/.git-blame-ignore-revs000066400000000000000000000003031527172722200175150ustar00rootroot00000000000000# Ran ocamlformat for the first time on the codebase 15189ac5559523505076886bf0943b093d702666 # Switched to ocamlformat 0.28.1 with the liquidsoap style 7e1fd5b629259b82a638a119d606e405fbc3ab24 ocaml-ssl-0.8.1/.github/000077500000000000000000000000001527172722200147615ustar00rootroot00000000000000ocaml-ssl-0.8.1/.github/workflows/000077500000000000000000000000001527172722200170165ustar00rootroot00000000000000ocaml-ssl-0.8.1/.github/workflows/build.yml000066400000000000000000000037121527172722200206430ustar00rootroot00000000000000name: Build on: pull_request: branches: - main push: branches: - main concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: format: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: ocaml/setup-ocaml@v3 with: ocaml-compiler: '5' - name: Install ocamlformat run: opam install ocamlformat.$(awk -F= '/^version/ {print $2}' .ocamlformat) - name: Check formatting run: opam exec -- dune build @fmt build: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: include: - {ocaml-compiler: '4.14', os: ubuntu-latest} - {ocaml-compiler: '5.1', os: ubuntu-latest} - {ocaml-compiler: '5.2', os: ubuntu-latest} - {ocaml-compiler: '5.2', os: windows-latest} steps: - uses: actions/checkout@v7 - uses: ocaml/setup-ocaml@v3 with: ocaml-compiler: ${{ matrix.ocaml-compiler }} - name: Install dependencies run: opam install --deps-only --with-test . - name: Build run: opam exec -- dune build - name: Test run: opam exec -- dune build @github_action_tests nix-build: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: include: - {ocamlVersion: 4_14, os: ubuntu-latest} - {ocamlVersion: 5_1, os: ubuntu-latest} - {ocamlVersion: 5_2, os: ubuntu-latest} - {ocamlVersion: 5_2, os: macos-latest} steps: - uses: actions/checkout@v7 - uses: cachix/install-nix-action@v31 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.ocamlVersion }} ocaml-ssl-0.8.1/.github/workflows/doc.yml000066400000000000000000000010771527172722200203130ustar00rootroot00000000000000name: Build doc on: push: branches: - main permissions: contents: write jobs: build_doc: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: ocaml/setup-ocaml@v3 with: ocaml-compiler: '5' - name: Install dependencies run: opam install --deps-only --with-doc . - name: Build doc run: opam exec -- dune build @doc - name: Deploy doc uses: JamesIves/github-pages-deploy-action@v4 with: branch: gh-pages folder: _build/default/_doc/_html ocaml-ssl-0.8.1/.gitignore000066400000000000000000000001011527172722200154010ustar00rootroot00000000000000.vscode *.install .merlin _build _coverage compile_commands.json ocaml-ssl-0.8.1/.ocamlformat000066400000000000000000000003371527172722200157310ustar00rootroot00000000000000version=0.28.1 profile = conventional break-separators = after space-around-lists = false doc-comments = before match-indent = 2 match-indent-nested = always parens-ite exp-grouping = preserve module-item-spacing = compact ocaml-ssl-0.8.1/.travis.yml000066400000000000000000000003541527172722200155340ustar00rootroot00000000000000language: 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.8.1/CHANGES.md000066400000000000000000000262601527172722200150210ustar00rootroot000000000000000.8.1 (2026-11-01) ===== - `Ssl.create_context SSLv23` works with OpenSSL 4. It asked for SSLv3 as the minimum version, which OpenSSL 4 no longer has, and failed with `Invalid_argument "Failed to set protocol version"`. The minimum is now the lowest version the library supports. 0.8.0 (2026-10-06) ===== - Fix naked pointer in cipher function (#144) - Copy OCaml strings before releasing the runtime lock: another thread could move them, making OpenSSL read a stale path, e.g. `Ssl.use_certificate` failing with `No such file or directory` on an existing key file. - `Ssl.set_ip`, `Ssl.set_host` and `Ssl.set_client_SNI_hostname` raise `Invalid_argument` instead of silently ignoring a value OpenSSL rejects. An unparsable IP address used to disable the check, accepting any certificate. - ALPN: an exception raised by the selection callback, or a protocol the client did not offer, fails the handshake instead of unwinding through OpenSSL. The selected protocol no longer points into the OCaml heap after the runtime lock is released. Protocol names must be 1 to 255 bytes long. - `Ssl.set_password_callback`: an exception from the callback, or a password longer than OpenSSL's buffer, makes loading the key fail with `Private_key_error` instead of unwinding through OpenSSL or aborting. - Fix memory leaks in `add_extra_chain_cert`, `add_cert_to_store`, `use_certificate_from_string`, `get_issuer`, `get_subject`, and in `read` and `write` when given invalid arguments. - `Ssl.use_certificate_from_string` decrypts the key with the context's password callback, like `Ssl.use_certificate`, instead of prompting on the terminal. - Password and ALPN selection callbacks are released with their context, and setting one again replaces it, instead of leaking a GC root on every call. - `Ssl.input_string` returns what it read once the peer closes the connection, instead of always raising `Read_error` (#152). - When pkg-config cannot find OpenSSL, the build warns and the fallback flags always link `-lssl -lcrypto`; on macOS they used to only add a search path, failing at link time (#55). - Read and write functions check their offset and length in one place, without overflowing. A huge offset used to be truncated to 32 bits, silently reading at another position, and on `Runtime_lock` functions raised an exception that could not be caught. - Functions taking a file name, host name, cipher list or curve name raise `Invalid_argument` on a string containing a NUL byte, instead of silently using the part before it. 0.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.8.1/COPYING000066400000000000000000000654351527172722200144710ustar00rootroot00000000000000This 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.8.1/Makefile000066400000000000000000000014761527172722200150710ustar00rootroot00000000000000.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.8.1/README.md000066400000000000000000000101351527172722200147000ustar00rootroot00000000000000OCaml-SSL - OCaml bindings for OpenSSL ====================================== [![LGPL license](https://img.shields.io/badge/License-LGPL-green.svg)](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)](https://opam.ocaml.org/packages/ssl/) [![Build](https://github.com/savonet/ocaml-ssl/actions/workflows/build.yml/badge.svg)](https://github.com/savonet/ocaml-ssl/actions/workflows/build.yml) `ssl` gives OCaml programs TLS client and server sockets on top of `Unix` file descriptors, using the system's OpenSSL. * [API documentation](https://savonet.github.io/ocaml-ssl/ssl/Ssl/index.html) * [Changelog](CHANGES.md) * [Bug reports](https://github.com/savonet/ocaml-ssl/issues) Installation ------------ ``` opam install ssl ``` This requires OCaml 4.14 or later and OpenSSL 1.1.0 or later. opam installs the OpenSSL development files through the `conf-libssl` package. Then add `ssl` to the `libraries` field of your `dune` file. Usage ----- ### Client A client that verifies the server certificate against the system's CA certificates and checks that it matches the host name: ```ocaml let () = let host = "example.org" in let ctx = Ssl.create_context Ssl.TLSv1_3 Ssl.Client_context in Ssl.set_min_protocol_version ctx Ssl.TLSv1_2; Ssl.set_verify ctx [Ssl.Verify_peer] None; if not (Ssl.set_default_verify_paths ctx) then failwith "no CA certificates"; let addr = (Unix.gethostbyname host).Unix.h_addr_list.(0) in let fd = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in Unix.connect fd (Unix.ADDR_INET (addr, 443)); let ssl = Ssl.embed_socket fd ctx in Ssl.set_client_SNI_hostname ssl host; Ssl.set_host ssl host; Ssl.connect ssl; Ssl.output_string ssl (Printf.sprintf "GET / HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n" host); print_string (Ssl.input_string ssl); Ssl.shutdown_connection ssl ``` `Ssl.create_context` pins the context to a single protocol version; `Ssl.set_min_protocol_version` and `Ssl.set_max_protocol_version` widen it to a range. Certificates are not verified unless `Ssl.set_verify` asks for it, and the host name is not checked unless `Ssl.set_host` (or `Ssl.set_ip`) is called. ### Server A server loads its certificate and private key into the context, then calls `Ssl.accept` on each socket accepted from its listening socket: ```ocaml let ctx = Ssl.create_context Ssl.TLSv1_3 Ssl.Server_context in Ssl.use_certificate ctx "cert.pem" "privkey.pem"; (* ... *) let fd, _ = Unix.accept listening_socket in let ssl = Ssl.embed_socket fd ctx in Ssl.accept ssl ``` A self-signed certificate is enough to try this out: ``` openssl req -x509 -newkey rsa:4096 -sha256 -days 365 -nodes \ -keyout privkey.pem -out cert.pem -subj "/CN=localhost" ``` See [`examples`](examples) for complete programs, including ALPN negotiation. ### Threads The library is thread-safe: OpenSSL 1.1.0 and later is thread-safe on its own. `Ssl_threads.init` and the `thread_safe` argument of `Ssl.init` do nothing and are kept for compatibility. The functions in `Ssl` release the OCaml runtime lock while they block. `Ssl.Runtime_lock` offers the same functions without releasing it, which is faster for non-blocking sockets. ### Lwt and Eio [`lwt_ssl`](https://github.com/ocsigen/lwt_ssl) and [`eio-ssl`](https://github.com/anmonteiro/eio-ssl) build on this library. Development ----------- ``` opam install --deps-only --with-test . dune build dune runtest ``` A Nix flake is also provided: `nix develop`. See [`tests/HACKING.md`](tests/HACKING.md) for how the test certificates are generated. License ------- Copyright (c) 2003-2026 the Savonet Team. This library is released under the LGPL version 2.1, with the OCaml linking exception and the additional exemption that compiling, linking, and/or using OpenSSL is allowed. See [`COPYING`](COPYING) for the full text. The examples are under the GPL version 2.0. This product includes software developed by the OpenSSL Project for use in the [OpenSSL Toolkit](https://www.openssl.org/). ocaml-ssl-0.8.1/dune-project000066400000000000000000000010451527172722200157430ustar00rootroot00000000000000(lang dune 3.23) (name ssl) (version 0.8.1) (generate_opam_files true) (source (github savonet/ocaml-ssl)) (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.14")) dune-configurator conf-libssl (alcotest :with-test))) ocaml-ssl-0.8.1/dune-workspace.dev000066400000000000000000000004221527172722200170460ustar00rootroot00000000000000(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.8.1/examples/000077500000000000000000000000001527172722200152375ustar00rootroot00000000000000ocaml-ssl-0.8.1/examples/alpn.ml000066400000000000000000000056531527172722200165340ustar00rootroot00000000000000let 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.8.1/examples/dune000066400000000000000000000001741527172722200161170ustar00rootroot00000000000000(alias (name default) (deps stalkd.exe stelnet.exe)) (executables (names stalkd stelnet) (libraries threads unix ssl)) ocaml-ssl-0.8.1/examples/stalkd.ml000066400000000000000000000061751527172722200170640ustar00rootroot00000000000000(* Copyright (C) 2003-2026 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.8.1/examples/stelnet.ml000066400000000000000000000052621527172722200172540ustar00rootroot00000000000000(* Copyright (C) 2003-2026 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.8.1/flake.lock000066400000000000000000000037271527172722200153660ustar00rootroot00000000000000{ "nodes": { "flake-utils": { "inputs": { "systems": "systems" }, "locked": { "lastModified": 1731533236, "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=", "owner": "numtide", "repo": "flake-utils", "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b", "type": "github" }, "original": { "owner": "numtide", "repo": "flake-utils", "type": "github" } }, "nixpkgs": { "inputs": { "nixpkgs": "nixpkgs_2" }, "locked": { "lastModified": 1790444930, "narHash": "sha256-XlB2mGEYOaEGRgAnoMO8Yeluclm7/79uaBiziBDGua8=", "owner": "anmonteiro", "repo": "nix-overlays", "rev": "95af44d1febadffff73ac2e0e38e758fe3e1f004", "type": "github" }, "original": { "owner": "anmonteiro", "repo": "nix-overlays", "type": "github" } }, "nixpkgs_2": { "locked": { "lastModified": 1790406335, "narHash": "sha256-AERkR3boxGJEFjgW8R8gQ7MxJws2asPI0CUxaVXjQ8U=", "owner": "NixOS", "repo": "nixpkgs", "rev": "36bebc5639fda7c20265de714291da8b628475ee", "type": "github" }, "original": { "owner": "NixOS", "repo": "nixpkgs", "rev": "36bebc5639fda7c20265de714291da8b628475ee", "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.8.1/flake.nix000066400000000000000000000012541527172722200152250ustar00rootroot00000000000000{ description = "OCaml-SSL Nix Flake"; inputs.flake-utils.url = "github:numtide/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.8.1/nix/000077500000000000000000000000001527172722200142175ustar00rootroot00000000000000ocaml-ssl-0.8.1/nix/ci/000077500000000000000000000000001527172722200146125ustar00rootroot00000000000000ocaml-ssl-0.8.1/nix/ci/test.nix000066400000000000000000000011341527172722200163100ustar00rootroot00000000000000{ 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.8.1/nix/default.nix000066400000000000000000000010261527172722200163620ustar00rootroot00000000000000{ stdenv , lib , ocamlPackages , openssl-oc , doCheck ? false , pkg-config }: with ocamlPackages; buildDunePackage { pname = "ssl"; version = "n/a"; src = ../.; nativeBuildInputs = [ ocaml dune findlib pkg-config ]; buildInputs = [ dune-configurator ]; propagatedBuildInputs = [ openssl-oc.dev ]; nativeCheckInputs = [ openssl-oc ]; checkInputs = [ alcotest ]; inherit doCheck; checkPhase = '' dune build -p ssl @runtest @github_action_tests ''${enableParallelBuilding:+-j $NIX_BUILD_CORES} ''; } ocaml-ssl-0.8.1/nix/gh-actions.nix000066400000000000000000000035321527172722200167760ustar00rootroot00000000000000{ 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.8.1/nix/shell.nix000066400000000000000000000005761527172722200160560ustar00rootroot00000000000000{ 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.8.1/src/000077500000000000000000000000001527172722200142105ustar00rootroot00000000000000ocaml-ssl-0.8.1/src/config/000077500000000000000000000000001527172722200154555ustar00rootroot00000000000000ocaml-ssl-0.8.1/src/config/discover.ml000066400000000000000000000022631527172722200176300ustar00rootroot00000000000000module C = Configurator.V1 let directory_exists fsp = Sys.file_exists fsp && Sys.is_directory fsp let libs = ["-lssl"; "-lcrypto"] let default c : C.Pkg_config.package_conf = let prefix = if C.ocaml_config_var_exn c "system" = "macosx" then List.find_opt directory_exists ["/opt/homebrew/opt/openssl"; "/usr/local/opt/openssl"; "/opt/local"] else None in match prefix with | Some prefix -> { libs = ("-L" ^ Filename.concat prefix "lib") :: libs; cflags = ["-I" ^ Filename.concat prefix "include"]; } | None -> { libs; cflags = [] } let () = C.main ~name:"ssl" (fun c -> let conf = match Option.bind (C.Pkg_config.get c) (fun pc -> C.Pkg_config.query pc ~package:"openssl") with | Some conf -> conf | None -> let conf = default c in Printf.eprintf "Warning: pkg-config could not find openssl, building with: %s\n" (String.concat " " (conf.cflags @ conf.libs)); conf in C.Flags.write_sexp "c_library_flags.sexp" conf.libs; C.Flags.write_sexp "c_flags.sexp" conf.cflags) ocaml-ssl-0.8.1/src/config/dune000066400000000000000000000000751527172722200163350ustar00rootroot00000000000000(executable (name discover) (libraries dune-configurator)) ocaml-ssl-0.8.1/src/dune000066400000000000000000000005561527172722200150740ustar00rootroot00000000000000(library (name ssl) (public_name ssl) (libraries unix) (wrapped false) (foreign_stubs (language c) (names ssl_stubs) (flags :standard (: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.8.1/src/ssl.ml000066400000000000000000000540701527172722200153510ustar00rootroot00000000000000(* Copyright (C) 2003-2026 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 (** Kept for backwards compatibility *) external get_error_string : unit -> string = "ocaml_ssl_get_error_string" 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 = Option.value thread_safe ~default:!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" (* The stubs trust their offsets: every read and write is checked here. *) let check_bounds name ~size start length = if start < 0 || length < 0 || start > size - length then invalid_arg (name ^ ": offset and length do not fit in the buffer") (* 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" let write socket buffer start length = check_bounds "Ssl.write" ~size:(Bytes.length buffer) start length; write socket buffer start length external write_substring : socket -> string -> int -> int -> int = "ocaml_ssl_write" let write_substring socket buffer start length = check_bounds "Ssl.write_substring" ~size:(String.length buffer) start length; write_substring socket buffer start length external write_bigarray : socket -> bigarray -> int -> int -> int = "ocaml_ssl_write_bigarray" let write_bigarray socket buffer start length = check_bounds "Ssl.write_bigarray" ~size:(Bigarray.Array1.dim buffer) start length; write_bigarray socket buffer start length external read : socket -> Bytes.t -> int -> int -> int = "ocaml_ssl_read" let read socket buffer start length = check_bounds "Ssl.read" ~size:(Bytes.length buffer) start length; read socket buffer start length external read_into_bigarray : socket -> bigarray -> int -> int -> int = "ocaml_ssl_read_into_bigarray" let read_into_bigarray socket buffer start length = check_bounds "Ssl.read_into_bigarray" ~size:(Bigarray.Array1.dim buffer) start length; read_into_bigarray socket buffer start length 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 = check_bounds "Ssl.Runtime_lock.write" ~size:(Bytes.length buffer) start length; 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 = check_bounds "Ssl.Runtime_lock.write_substring" ~size:(String.length buffer) start length; 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 = check_bounds "Ssl.Runtime_lock.write_bigarray" ~size:(Bigarray.Array1.dim buffer) start length; 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 = check_bounds "Ssl.Runtime_lock.read" ~size:(Bytes.length buffer) start length; 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 = check_bounds "Ssl.Runtime_lock.read_into_bigarray" ~size:(Bigarray.Array1.dim buffer) start length; 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 buf = Bytes.create 1024 in let contents = Buffer.create 1024 in let rec loop () = match read ssl buf 0 (Bytes.length buf) with | length -> Buffer.add_subbytes contents buf 0 length; loop () | exception Read_error Error_zero_return -> Buffer.contents contents in loop () 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.8.1/src/ssl.mli000066400000000000000000000702441527172722200155230ustar00rootroot00000000000000(* Copyright (C) 2003-2026 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} *) (** in version prior to 3.0, details are dropped: 1.1.1n = 1.1.1f *) type version = { major : int; (** major version *) minor : int; (** minor version *) patch : int; (** patch number *) } 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 (** The SSL method could not be initialized. *) exception Method_error exception Context_error exception Cipher_error exception Diffie_hellman_error exception Ec_curve_error (** The SSL server certificate could not be initialized. *) exception Certificate_error of string (** The SSL server private key could not be initialized. *) exception Private_key_error of string (** The SSL private key does not match the certificate public key. *) exception Unmatching_keys (** The given socket is invalid. *) exception Invalid_socket (** The SSL handler could not be initialized. *) exception Handler_error (** The connection could not be made with the SSL service. *) exception Connection_error of ssl_error (** Failed to accept an SSL connection. *) exception Accept_error of ssl_error (** An error occurred while reading data. *) exception Read_error of ssl_error (** An error occurred while writing data. *) exception Write_error of ssl_error (** An error occurred while flushing a socket. [Flush_error true] means that the operation should be retried. *) exception Flush_error of bool (** Why did the certificate verification fail? *) type verify_error = | Error_v_unable_to_get_issuer_cert (** The issuer certificate could not be found: this occurs if the issuer certificate of an untrusted certificate cannot be found.*) | Error_v_unable_to_get_ctl (** The CRL of a certificate could not be found. *) | Error_v_unable_to_decrypt_cert_signature (** The certificate signature could not be decrypted. This means that the actual signature value could not be determined rather than it not matching the expected value, this is only meaningful for RSA keys. *) | Error_v_unable_to_decrypt_CRL_signature (** The CRL signature could not be decrypted: this means that the actual signature value could not be determined rather than it not matching the expected value. Unused. *) | Error_v_unable_to_decode_issuer_public_key (** The public key in the certificate SubjectPublicKeyInfo could not be read. *) | Error_v_cert_signature_failure (** The signature of the certificate is invalid. *) | Error_v_CRL_signature_failure (** The signature of the certificate is invalid. *) | Error_v_cert_not_yet_valid (** The certificate is not yet valid: the notBefore date is after the current time. *) | Error_v_cert_has_expired (** The certificate has expired: that is the notAfter date is before the current time. *) | Error_v_CRL_not_yet_valid (** The CRL is not yet valid. *) | Error_v_CRL_has_expired (** The CRL has expired. *) | Error_v_error_in_cert_not_before_field (** The certificate notBefore field contains an invalid time. *) | Error_v_error_in_cert_not_after_field (** The certificate notAfter field contains an invalid time. *) | Error_v_error_in_CRL_last_update_field (** The CRL lastUpdate field contains an invalid time. *) | Error_v_error_in_CRL_next_update_field (** The CRL nextUpdate field contains an invalid time. *) | Error_v_out_of_mem (** An error occurred trying to allocate memory. This should never happen. *) | Error_v_depth_zero_self_signed_cert (** The passed certificate is self signed and the same certificate cannot be found in the list of trusted certificates. *) | Error_v_self_signed_cert_in_chain (** The certificate chain could be built up using the untrusted certificates but the root could not be found locally. *) | Error_v_unable_to_get_issuer_cert_locally (** The issuer certificate of a locally looked up certificate could not be found. This normally means the list of trusted certificates is not complete. *) | Error_v_unable_to_verify_leaf_signature (** No signatures could be verified because the chain contains only one certificate and it is not self signed. *) | Error_v_cert_chain_too_long (** The certificate chain length is greater than the supplied maximum depth. Unused. *) | Error_v_cert_revoked (** The certificate has been revoked. *) | Error_v_invalid_CA (** A CA certificate is invalid. Either it is not a CA or its extensions are not consistent with the supplied purpose. *) | Error_v_path_length_exceeded (** The basicConstraints pathlength parameter has been exceeded. *) | Error_v_invalid_purpose (** The supplied certificate cannot be used for the specified purpose. *) | Error_v_cert_untrusted (** The root CA is not marked as trusted for the specified purpose. *) | Error_v_cert_rejected (** The root CA is marked to reject the specified purpose. *) | Error_v_subject_issuer_mismatch (** The current candidate issuer certificate was rejected because its subject name did not match the issuer name of the current certificate. *) | Error_v_akid_skid_mismatch (** The current candidate issuer certificate was rejected because its subject key identifier was present and did not match the authority key identifier current certificate. *) | Error_v_akid_issuer_serial_mismatch (** The current candidate issuer certificate was rejected because its issuer name and serial number was present and did not match the authority key identifier of the current certificate. *) | Error_v_keyusage_no_certsign (** The current candidate issuer certificate was rejected because its keyUsage extension does not permit certificate signing. *) | Error_v_application_verification (** An application specific error. Unused. *) (** An error occurred while verifying the certificate. *) exception Verify_error of verify_error (** {1 Communication} *) (** Initialize SSL functions. OpenSSL initializes itself on first use, so calling this is optional. [thread_safe] is ignored: OpenSSL is thread-safe on its own, and the parameter is kept for compatibility. *) val init : ?thread_safe:bool -> unit -> unit (** Retrieve a human-readable message that corresponds to the earliest error code from the thread's error queue and removes the entry. *) val get_error_string : unit -> string [@@ocaml.alert deprecated "Use [Ssl.Error.get_error] instead"] module Error : sig (** 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. *) 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. *) } (** Retrieve the earliest error from the error queue then it removes the entry. Returns the code and library and reason strings *) val get_error : unit -> t (** Retrieve the earliest error from the error queue without modifying it. Returns the code and library and reason strings *) val peek_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. *) val peek_last_error : unit -> t 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 *) (** An SSL abstract socket. *) type socket (** {2 Threads} *) (** Ignored, kept for compatibility: OpenSSL is thread-safe on its own. *) val thread_safe : bool ref (** {2 Contexts} *) (** A context. A context should be created by a server or client once per program life-time and holds mainly default values for the SSL structures which are later created for the connections. *) type context (** Type of the context to create. *) type context_type = | Client_context (** Client connections. *) | Server_context (** Server connections. *) | Both_context (** Client and server connections. *) (** Create a context. *) val create_context : protocol -> context_type -> context (** [set_min_protocol_version ctx proto] sets the minimum supported protocol version for [ctx] to [proto]. *) val set_min_protocol_version : context -> protocol -> unit (** [set_max_protocol_version ctx proto] sets the maximum supported protocol version for [ctx] to [proto]. *) val set_max_protocol_version : context -> protocol -> unit (** [get_min_protocol_version ctx] sets the minimum supported protocol version for [ctx] to [proto]. *) val get_min_protocol_version : context -> protocol (** [get_max_protocol_version ctx proto] sets the maximum supported protocol version for [ctx] to [proto]. *) val get_max_protocol_version : context -> protocol (** 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_extra_chain_cert : 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 add_cert_to_store : context -> 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 : context -> string -> string -> unit (** Use a certificate whose contents is given as argument (you should use instead [use_certificate] if you want to read the certificate from a file). *) val use_certificate_from_string : context -> string -> string -> unit (** Set the callback function called to get passwords for encrypted PEM files. * The callback function takes a boolean argument which indicates if it's used * for reading/decryption ([false]) or writing/encryption ([true]). *) val set_password_callback : context -> (bool -> string) -> unit (** Set the list of CAs sent to the client when requesting a client certificate. *) val set_client_CA_list_from_file : context -> string -> unit (** Verification modes (see SSL_CTX_set_verify(3)). *) type verify_mode = | Verify_peer | Verify_fail_if_no_peer_cert (** Implies [Verify_peer]. *) | Verify_client_once (** Implies [Verify_peer]. *) (** A callback function for verification. Warning: this might change in the future. *) type verify_callback (** Client's verification callback. Warning: this might change in the future. *) val client_verify_callback : verify_callback (** Set verbosity of {! client_verify_callback } *) val set_client_verify_callback_verbose : bool -> unit (** Set the verify mode and callback, see SSL_CTX_set_verify(3). * Warning: this might change in the future. *) val set_verify : context -> verify_mode list -> verify_callback option -> unit (** Set the maximum depth for the certificate chain verification that shall be allowed. *) val set_verify_depth : context -> int -> unit (** Set the list of supported ALPN protocols for negotiation to the context. @raise Invalid_argument if a protocol name is empty or longer than 255 bytes, or if the encoded list is longer than 65535 bytes. *) val set_context_alpn_protos : context -> string list -> unit (** Set the callback to allow server to select the preferred protocol from client's available protocols. The handshake fails if the callback raises or returns a protocol the client did not offer. *) val set_context_alpn_select_callback : context -> (string list -> string option) -> unit (** {2 Ciphers} *) (** A cipher. It holds the algorithm information for a particular cipher which * are a core part of the SSL/TLS protocol.*) type cipher (** Disable all protocols from the list. * Note that [SSLv23] disables both SSLv2 and SSLv3 (as opposed to all the * protocols). * *) val disable_protocols : context -> protocol list -> unit (** Set the list of available ciphers for a context. See man ciphers(1) for the format of the string. *) val set_cipher_list : context -> string -> unit (** When choosing a cipher, use the server's preferences instead of the client * preferences. When not set, the SSL server will always follow the clients * preferences. When set, the SSLv3/TLSv1 server will choose following its * own preferences. Because of the different protocol, for SSLv2 the server * will send its list of preferences to the client and the client chooses.*) val honor_cipher_order : context -> unit (** Init DH parameters from file *) val init_dh_from_file : context -> string -> unit (** Init EC curve from curve name *) val init_ec_from_named_curve : context -> string -> unit (** Get the cipher used by a socket. *) val get_cipher : socket -> cipher (** Get a description of a cipher. *) val get_cipher_description : cipher -> string (** Get the name of a cipher. *) val get_cipher_name : cipher -> string (** Get the version of a cipher. *) val get_cipher_version : cipher -> string (** Get the version used for the connection. As per the {{:https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html} OpenSSL documentation}, should only be called after the initial handshake has been completed. Prior to that the results returned from these functions may be unreliable. @raise Failure if the version is unknown *) val version : socket -> protocol (** {2 Certificates} *) (** A certificate. *) type certificate (** [read_certificate fname] reads the certificate in the file [fname]. *) val read_certificate : string -> certificate val write_certificate : string -> certificate -> unit (** Get the certificate used by a socket. *) val get_certificate : socket -> certificate (** Get the issuer of a certificate. *) val get_issuer : certificate -> string (** Get the subject of a certificate. *) val get_subject : certificate -> string (** Get the start date of a certificate. *) val get_start_date : certificate -> Unix.tm (** Get the expiration date of a certificate. *) val get_expiration_date : certificate -> Unix.tm (** [load_verify_locations ctxt cafile capath] specifies the locations for the context [ctx], at which CA certificates for verification purposes are located. [cafile] should be the name of a CA certificates file in PEM format and [capath] should be the name of a directory which contains CA certificates in PEM format. Empty strings can be used in order not to specify on of the parameters (but not both). @raise Invalid_argument if both strings are empty or if one of the files given in arguments could not be found. *) val load_verify_locations : context -> string -> string -> unit (** Specifies that the default locations from which CA certificates are loaded should be used. Returns [true] on success. *) val set_default_verify_paths : context -> bool (** Get the verification result. *) val get_verify_result : socket -> int (** Get a human readable verification error message for the verification error Its input should be the result of calling [get_verify_result]. *) val get_verify_error_string : int -> string (** Get the digest of the certificate as a binary string, using the SHA1, SHA256 or SHA384 hashing algorithm. *) val digest : [ `SHA1 | `SHA256 | `SHA384 ] -> certificate -> string (** {2 Creating, connecting, closing and configuring sockets} *) (** Embed a Unix socket into an SSL socket. *) val embed_socket : Unix.file_descr -> context -> socket (** Set the hostname the client is attempting to connect to using the Server * Name Indication (SNI) TLS extension. @raise Invalid_argument if the hostname is rejected. *) val set_client_SNI_hostname : socket -> string -> unit (** Set the list of supported ALPN protocols for negotiation to the connection. @raise Invalid_argument if a protocol name is empty or longer than 255 bytes, or if the encoded list is longer than 65535 bytes. *) val set_alpn_protos : socket -> string list -> unit (** Get the negotiated protocol from the connection. *) val get_negotiated_alpn_protocol : socket -> string option (** Check the result of the verification of the X509 certificate presented by the peer, if any. Raises a [verify_error] on failure. *) val verify : socket -> unit (** Flags to specify how a certificate is matched against a given host name *) type x509_check_flag = | Always_check_subject | No_wildcards | No_partial_wildcards | Multi_label_wildcards | Single_label_subdomains (* Specify how a certificate should be matched against the host name *) val set_hostflags : socket -> x509_check_flag list -> unit (** Set the expected host name to be verified. @raise Invalid_argument if the hostname is rejected. *) val set_host : 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. @raise Invalid_argument if the address cannot be parsed. *) val set_ip : socket -> string -> unit (** 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. *) val file_descr_of_socket : socket -> Unix.file_descr (** {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. *) (** Connect an SSL socket. *) val connect : socket -> unit (** Accept an SSL connection. *) val accept : socket -> unit (** Open an SSL connection. *) val open_connection : protocol -> Unix.sockaddr -> socket (** Open an SSL connection with the specified context. *) val open_connection_with_context : context -> Unix.sockaddr -> socket (** 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 close_notify : socket -> bool (** Close an SSL connection opened with [open_connection]. *) val shutdown_connection : socket -> unit (** Close a SSL connection. * Send close notify to the peer and wait for close notify from peer. *) val shutdown : socket -> unit (** Flush an SSL connection. *) val flush : socket -> unit (** [read sock buf off len] receives data from a connected SSL socket. *) val read : socket -> Bytes.t -> int -> int -> int (** [read_into_bigarray sock ba off len] receives data from a connected SSL socket. This function releases the runtime while the read takes place. *) val read_into_bigarray : socket -> bigarray -> int -> int -> int (** [write sock buf off len] sends data over a connected SSL socket. *) val write : socket -> Bytes.t -> int -> int -> int (** [write_substring sock str off len] sends data over a connected SSL socket. *) val write_substring : socket -> string -> int -> int -> int (** [write_bigarray sock ba off len] sends data over a connected SSL socket. This function releases the runtime while the read takes place. *) val write_bigarray : socket -> bigarray -> int -> int -> int (** {3 High-level communication functions} *) (** Read from an SSL socket until the peer closes the connection. *) val input_string : socket -> string (** Write a string on an SSL socket. *) val output_string : socket -> string -> unit (** Input a character on an SSL socket. *) val input_char : socket -> char (** Write a char on an SSL socket. *) val output_char : socket -> char -> unit (** Input an integer on an SSL socket. *) val input_int : socket -> int (** Write an integer on an SSL socket. *) val output_int : socket -> int -> unit (** [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 (** Connect an SSL socket. *) val connect : socket -> unit (** Accept an SSL connection. *) val accept : socket -> unit (** Open an SSL connection. *) val open_connection : protocol -> Unix.sockaddr -> socket (** Open an SSL connection with the specified context. *) val open_connection_with_context : context -> Unix.sockaddr -> socket (** 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 close_notify : socket -> bool (** Close an SSL connection opened with [open_connection]. *) val shutdown_connection : socket -> unit (** Close a SSL connection. * Send close notify to the peer and wait for close notify from peer. *) val shutdown : socket -> unit (** Flush an SSL connection. *) val flush : socket -> unit (** [read sock buf off len] receives data from a connected SSL socket. *) val read : socket -> Bytes.t -> int -> int -> int (** [read_into_bigarray sock ba off len] receives data from a connected SSL socket. This function releases the runtime while the read takes place. *) val read_into_bigarray : socket -> bigarray -> int -> int -> int (** [write sock buf off len] sends data over a connected SSL socket. *) val write : socket -> Bytes.t -> int -> int -> int (** [write_substring sock str off len] sends data over a connected SSL socket. *) val write_substring : socket -> string -> int -> int -> int (** [write_bigarray sock ba off len] sends data over a connected SSL socket. This function releases the runtime while the read takes place. *) val write_bigarray : socket -> bigarray -> int -> int -> int (** {3 High-level communication functions} *) (** Read from an SSL socket until the peer closes the connection. *) val input_string : socket -> string (** Write a string on an SSL socket. *) val output_string : socket -> string -> unit (** Input a character on an SSL socket. *) val input_char : socket -> char (** Write a char on an SSL socket. *) val output_char : socket -> char -> unit (** Input an integer on an SSL socket. *) val input_int : socket -> int (** Write an integer on an SSL socket. *) val output_int : socket -> int -> unit end (** This function is deprecated. Use [Runtime_lock.read_into_bigarray] instead. *) 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.write_bigarray] instead. *) val write_bigarray_blocking : socket -> bigarray -> int -> int -> int [@@ocaml.alert deprecated "Use [Runtime_lock.write_bigarray] instead"] ocaml-ssl-0.8.1/src/ssl_stubs.c000066400000000000000000001607561527172722200164140ustar00rootroot00000000000000/* * Copyright (C) 2003-2026 Samuel Mimram * * This file is part of Ocaml-ssl. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Libssl bindings for OCaml. * * @author Samuel Mimram */ /* * WARNING: because of thread callbacks, all ssl functions should be in * blocking sections. */ #include #include #include #include #define CAML_NAME_SPACE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef WIN32 #include #endif static int client_verify_callback(int, X509_STORE_CTX *); static value vclient_verify_callback = Val_int(0); 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}; /****************** * Initialization * ******************/ CAMLprim value ocaml_ssl_init(value use_threads) { CAMLparam1(use_threads); OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL); 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 = caml_alloc_some(caml_copy_string(lib)); } else { libval = Val_none; } if (reason != NULL) { reasonval = caml_alloc_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); } /* OpenSSL takes NUL-terminated strings, where an embedded NUL would silently * truncate a name or a path. */ static void check_c_string(value string, const char *function_name) { if (!caml_string_is_c_safe(string)) caml_invalid_argument_value( caml_alloc_sprintf("%s: NUL byte in string", function_name)); } /***************************** * 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)); } /* Returns an error message on failure, NULL on success. */ static const char *set_protocol(SSL_CTX *ssl_context, int protocol) { /* Protocol 0 accepts any version, the others exactly one. For protocol 0, the minimum is 0, the lowest version the library supports: OpenSSL 4 has no SSLv3 and rejects SSL3_VERSION as a minimum. */ int min_proto = protocol == 0 ? 0 : tls_version_of_ocaml_ssl_version(protocol); int max_proto = protocol == 0 ? TLS1_3_VERSION : min_proto; if (min_proto < 0) return "Unknown method (this should not have happened, please report)."; if (!SSL_CTX_set_min_proto_version(ssl_context, min_proto) || !SSL_CTX_set_max_proto_version(ssl_context, max_proto)) return "Failed to set protocol version"; return NULL; } CAMLprim value ocaml_ssl_create_context(value protocol, value type) { CAMLparam2(protocol, type); CAMLlocal1(block); SSL_CTX *ctx; const char *protocol_error; 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")); } protocol_error = set_protocol(ctx, Int_val(protocol)); if (protocol_error != NULL) { SSL_CTX_free(ctx); caml_acquire_runtime_system(); caml_invalid_argument(protocol_error); } /* In non-blocking mode, accept a buffer with a different address on a write retry (since the GC may need to move it). In blocking mode, hide SSL_ERROR_WANT_(READ|WRITE) from us. */ SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY); caml_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); int cert_data_length = caml_string_length(cert); char *cert_data = caml_stat_alloc(cert_data_length); char buf[256]; X509 *x509_cert = NULL; BIO *cbio; memcpy(cert_data, String_val(cert), cert_data_length); 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); BIO_free(cbio); /* On success, the context takes ownership of the certificate. */ if (NULL == x509_cert || SSL_CTX_add_extra_chain_cert(ctx, x509_cert) <= 0) { ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); X509_free(x509_cert); caml_acquire_runtime_system(); caml_stat_free(cert_data); caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string(buf)); } caml_acquire_runtime_system(); caml_stat_free(cert_data); 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); int cert_data_length = caml_string_length(cert); char *cert_data = caml_stat_alloc(cert_data_length); char buf[256]; X509 *x509_cert = NULL; BIO *cbio; memcpy(cert_data, String_val(cert), cert_data_length); 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); BIO_free(cbio); X509_STORE *store = SSL_CTX_get_cert_store(ctx); /* The store takes its own reference to the certificate. */ if (NULL == x509_cert || X509_STORE_add_cert(store, x509_cert) <= 0) { ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); X509_free(x509_cert); caml_acquire_runtime_system(); caml_stat_free(cert_data); caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string(buf)); } X509_free(x509_cert); caml_acquire_runtime_system(); caml_stat_free(cert_data); 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); char *cert_name, *privkey_name; char buf[256]; check_c_string(cert, "Ssl.use_certificate"); check_c_string(privkey, "Ssl.use_certificate"); cert_name = caml_stat_strdup(String_val(cert)); privkey_name = caml_stat_strdup(String_val(privkey)); 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_stat_free(cert_name); caml_stat_free(privkey_name); 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_stat_free(cert_name); caml_stat_free(privkey_name); 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_stat_free(cert_name); caml_stat_free(privkey_name); caml_raise_constant(*caml_named_value("ssl_exn_unmatching_keys")); } caml_acquire_runtime_system(); caml_stat_free(cert_name); caml_stat_free(privkey_name); CAMLreturn(Val_unit); } enum certificate_error { CERTIFICATE_OK, CERTIFICATE_ERROR, PRIVATE_KEY_ERROR, UNMATCHING_KEYS }; /* Runs with the runtime lock released, so that an encrypted key can be * decrypted by the context's password callback, which reacquires it. */ static enum certificate_error use_certificate_from_buffers(SSL_CTX *ctx, const char *cert_data, int cert_data_length, const char *privkey_data, int privkey_data_length) { enum certificate_error error = CERTIFICATE_OK; X509 *x509_cert = NULL; EVP_PKEY *pkey = NULL; BIO *bio; bio = BIO_new_mem_buf((void *)cert_data, cert_data_length); x509_cert = PEM_read_bio_X509(bio, NULL, 0, NULL); BIO_free(bio); if (NULL == x509_cert || SSL_CTX_use_certificate(ctx, x509_cert) <= 0) { error = CERTIFICATE_ERROR; goto end; } bio = BIO_new_mem_buf((void *)privkey_data, privkey_data_length); pkey = PEM_read_bio_PrivateKey(bio, NULL, SSL_CTX_get_default_passwd_cb(ctx), SSL_CTX_get_default_passwd_cb_userdata(ctx)); BIO_free(bio); if (NULL == pkey || SSL_CTX_use_PrivateKey(ctx, pkey) <= 0) { error = PRIVATE_KEY_ERROR; goto end; } if (!SSL_CTX_check_private_key(ctx)) error = UNMATCHING_KEYS; end: /* The context takes its own references to the certificate and key. */ X509_free(x509_cert); EVP_PKEY_free(pkey); return error; } 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); int cert_data_length = caml_string_length(cert); int privkey_data_length = caml_string_length(privkey); char *cert_data = caml_stat_alloc(cert_data_length); char *privkey_data = caml_stat_alloc(privkey_data_length); enum certificate_error error; char buf[256]; memcpy(cert_data, String_val(cert), cert_data_length); memcpy(privkey_data, String_val(privkey), privkey_data_length); caml_release_runtime_system(); error = use_certificate_from_buffers(ctx, cert_data, cert_data_length, privkey_data, privkey_data_length); if (error != CERTIFICATE_OK) ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); caml_acquire_runtime_system(); caml_stat_free(cert_data); caml_stat_free(privkey_data); switch (error) { case CERTIFICATE_OK: break; case CERTIFICATE_ERROR: caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string(buf)); case PRIVATE_KEY_ERROR: caml_raise_with_arg(*caml_named_value("ssl_exn_private_key_error"), caml_copy_string(buf)); case UNMATCHING_KEYS: 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); memcpy(Bytes_val(vdigest), buf, digest_size); CAMLreturn(vdigest); } CAMLprim value ocaml_ssl_get_client_verify_callback_ptr(value unit) { CAMLparam1(unit); 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); } 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)) { 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)); } 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); char *filename; STACK_OF(X509_NAME) * cert_names; char buf[256]; check_c_string(vfilename, "Ssl.set_client_CA_list_from_file"); filename = caml_stat_strdup(String_val(vfilename)); 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_stat_free(filename); caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string(buf)); } caml_acquire_runtime_system(); caml_stat_free(filename); CAMLreturn(Val_unit); } /* Callbacks are stored in their context, which unregisters them when freed. */ static int alpn_select_callback_index = -1; static int password_callback_index = -1; static CRYPTO_ONCE callback_indexes_once = CRYPTO_ONCE_STATIC_INIT; static void free_callback_root(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp) { value *callback = ptr; if (callback == NULL) return; caml_remove_generational_global_root(callback); caml_stat_free(callback); } static void init_callback_indexes(void) { alpn_select_callback_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, free_callback_root); password_callback_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, free_callback_root); } /* Returns a root holding the callback, reused if one is already stored. */ static value *set_context_callback(SSL_CTX *ctx, const int *index, value callback) { value *root; if (!CRYPTO_THREAD_run_once(&callback_indexes_once, init_callback_indexes) || *index < 0) caml_failwith("Ssl: could not allocate callback storage"); root = SSL_CTX_get_ex_data(ctx, *index); if (root != NULL) { caml_modify_generational_global_root(root, callback); return root; } root = caml_stat_alloc(sizeof(value)); *root = callback; caml_register_generational_global_root(root); if (!SSL_CTX_set_ex_data(ctx, *index, root)) { caml_remove_generational_global_root(root); caml_stat_free(root); caml_failwith("Ssl: could not store callback"); } return root; } /* Encodes the protocols in the ALPN wire format, each prefixed by its length. * * The result must be freed with caml_stat_free. */ static unsigned char *alpn_protocol_buffer(value vprotos, unsigned int *buffer_length) { unsigned int total_length = 0; unsigned char *protocol_buffer, *position; value protos_tl; for (protos_tl = vprotos; protos_tl != Val_emptylist; protos_tl = Field(protos_tl, 1)) { mlsize_t protocol_length = caml_string_length(Field(protos_tl, 0)); if (protocol_length == 0 || protocol_length > 255) caml_invalid_argument("ALPN protocol names must be 1 to 255 bytes long"); total_length += protocol_length + 1; /* The ALPN extension carries the list length on 16 bits. */ if (total_length > 65535) caml_invalid_argument("ALPN protocol list is too long"); } protocol_buffer = caml_stat_alloc(total_length); position = protocol_buffer; for (protos_tl = vprotos; protos_tl != Val_emptylist; protos_tl = Field(protos_tl, 1)) { value protocol = Field(protos_tl, 0); mlsize_t protocol_length = caml_string_length(protocol); *position++ = protocol_length; memcpy(position, String_val(protocol), protocol_length); position += protocol_length; } *buffer_length = total_length; return protocol_buffer; } CAMLprim value ocaml_ssl_ctx_set_alpn_protos(value context, value vprotos) { CAMLparam2(context, vprotos); SSL_CTX *ctx = Ctx_val(context); unsigned int protocol_buffer_length; unsigned char *protocol_buffer = alpn_protocol_buffer(vprotos, &protocol_buffer_length); int ret; caml_release_runtime_system(); ret = SSL_CTX_set_alpn_protos(ctx, protocol_buffer, protocol_buffer_length); caml_acquire_runtime_system(); caml_stat_free(protocol_buffer); /* Unlike most OpenSSL functions, this one returns 0 on success. */ if (ret != 0) caml_failwith("Ssl.set_context_alpn_protos"); CAMLreturn(Val_unit); } static value build_alpn_protocol_list(const unsigned char *protocol_buffer, unsigned int len) { CAMLparam0(); CAMLlocal4(protocol_list, current, tail, protocol); unsigned int idx = 0; protocol_list = Val_emptylist; while (idx < len) { unsigned int protocol_length = protocol_buffer[idx++]; if (protocol_length > len - idx) break; protocol = caml_alloc_initialized_string( protocol_length, (const char *)protocol_buffer + idx); idx += protocol_length; tail = caml_alloc(2, 0); Store_field(tail, 0, protocol); 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 * * OpenSSL reads `out` after the runtime lock is released again, so it must * point into `in` rather than into a string the GC may move. */ static int caml_alpn_select_cb(const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, value *callback) { CAMLparam0(); CAMLlocal2(protocol_list, selected_protocol); value result; unsigned int idx = 0; protocol_list = build_alpn_protocol_list(in, inlen); result = caml_callback_exn(*callback, protocol_list); if (Is_exception_result(result)) CAMLreturnT(int, SSL_TLSEXT_ERR_ALERT_FATAL); if (result == Val_none) CAMLreturnT(int, SSL_TLSEXT_ERR_NOACK); selected_protocol = Field(result, 0); while (idx < inlen) { unsigned int protocol_length = in[idx++]; if (protocol_length > inlen - idx) break; if (protocol_length == caml_string_length(selected_protocol) && memcmp(in + idx, String_val(selected_protocol), protocol_length) == 0) { *out = in + idx; *outlen = protocol_length; CAMLreturnT(int, SSL_TLSEXT_ERR_OK); } idx += protocol_length; } CAMLreturnT(int, SSL_TLSEXT_ERR_ALERT_FATAL); } 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(out, outlen, in, inlen, (value *)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 = set_context_callback(ctx, &alpn_select_callback_index, cb); caml_release_runtime_system(); SSL_CTX_set_alpn_select_cb(ctx, alpn_select_cb, select_cb); caml_acquire_runtime_system(); CAMLreturn(Val_unit); } /* A password that does not fit in `buf`, like an exception from the callback, * is reported to OpenSSL as a failure. */ static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) { value password; int length = -1; caml_acquire_runtime_system(); password = caml_callback_exn(*((value *)userdata), Val_bool(rwflag)); if (!Is_exception_result(password) && caml_string_length(password) <= (mlsize_t)size) { length = caml_string_length(password); memcpy(buf, String_val(password), length); } caml_release_runtime_system(); return length; } CAMLprim value ocaml_ssl_ctx_set_default_passwd_cb(value context, value cb) { CAMLparam2(context, cb); SSL_CTX *ctx = Ctx_val(context); value *pcb = set_context_callback(ctx, &password_callback_index, cb); 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); char *ciphers; check_c_string(ciphers_string, "Ssl.set_cipher_list"); if (*String_val(ciphers_string) == 0) caml_raise_constant(*caml_named_value("ssl_exn_cipher_error")); ciphers = caml_stat_strdup(String_val(ciphers_string)); caml_release_runtime_system(); if (SSL_CTX_set_cipher_list(ctx, ciphers) != 1) { caml_acquire_runtime_system(); caml_stat_free(ciphers); caml_raise_constant(*caml_named_value("ssl_exn_cipher_error")); } caml_acquire_runtime_system(); caml_stat_free(ciphers); 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; 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)); } #define Cipher_val(v) (*((SSL_CIPHER **)Data_abstract_val(v))) 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")); value vcipher = caml_alloc_shr(1, Abstract_tag); Cipher_val(vcipher) = cipher; CAMLreturn(vcipher); } CAMLprim value ocaml_ssl_get_cipher_description(value vcipher) { CAMLparam1(vcipher); char buf[1024]; SSL_CIPHER *cipher = Cipher_val(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 = Cipher_val(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 = Cipher_val(vcipher); caml_release_runtime_system(); version = SSL_CIPHER_get_version(cipher); caml_acquire_runtime_system(); CAMLreturn(caml_copy_string(version)); } /* Takes ownership of the parameters. */ static int set_dh_parameters(SSL_CTX *ctx, EVP_PKEY *parameters) { #if OPENSSL_VERSION_MAJOR >= 3 if (SSL_CTX_set0_tmp_dh_pkey(ctx, parameters) == 1) return 1; EVP_PKEY_free(parameters); return 0; #else DH *dh = EVP_PKEY_get1_DH(parameters); int ret = dh != NULL && SSL_CTX_set_tmp_dh(ctx, dh) == 1; DH_free(dh); EVP_PKEY_free(parameters); return ret; #endif } CAMLprim value ocaml_ssl_ctx_init_dh_from_file(value context, value dh_file_path) { CAMLparam2(context, dh_file_path); SSL_CTX *ctx = Ctx_val(context); EVP_PKEY *parameters = NULL; char *path; BIO *bio; int ret = 0; check_c_string(dh_file_path, "Ssl.init_dh_from_file"); if (*String_val(dh_file_path) == 0) caml_raise_constant(*caml_named_value("ssl_exn_diffie_hellman_error")); path = caml_stat_strdup(String_val(dh_file_path)); caml_release_runtime_system(); bio = BIO_new_file(path, "r"); if (bio != NULL) { parameters = PEM_read_bio_Parameters(bio, NULL); BIO_free(bio); } if (parameters != NULL && (EVP_PKEY_base_id(parameters) == EVP_PKEY_DH || EVP_PKEY_base_id(parameters) == EVP_PKEY_DHX)) ret = set_dh_parameters(ctx, parameters); else EVP_PKEY_free(parameters); caml_acquire_runtime_system(); caml_stat_free(path); if (!ret) 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); SSL_CTX *ctx = Ctx_val(context); int nid; int ret; check_c_string(curve_name, "Ssl.init_ec_from_named_curve"); nid = OBJ_sn2nid(String_val(curve_name)); if (nid == NID_undef) caml_raise_constant(*caml_named_value("ssl_exn_ec_curve_error")); caml_release_runtime_system(); ret = SSL_CTX_set1_groups(ctx, &nid, 1); caml_acquire_runtime_system(); if (ret != 1) 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]; check_c_string(vfilename, "Ssl.read_certificate"); 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]; check_c_string(vfilename, "Ssl.write_certificate"); 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); CAMLlocal1(result); 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(); result = caml_copy_string(issuer); OPENSSL_free(issuer); CAMLreturn(result); } CAMLprim value ocaml_ssl_get_subject(value certificate) { CAMLparam1(certificate); CAMLlocal1(result); 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(); result = caml_copy_string(subject); OPENSSL_free(subject); CAMLreturn(result); } 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; int ret; caml_release_runtime_system(); ret = ASN1_TIME_to_tm(X509_get0_notBefore(cert), &t); caml_acquire_runtime_system(); if (!ret) caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string("invalid certificate date")); CAMLreturn(alloc_tm(&t)); } CAMLprim value ocaml_ssl_get_expiration_date(value certificate) { CAMLparam1(certificate); X509 *cert = Cert_val(certificate); struct tm t; int ret; caml_release_runtime_system(); ret = ASN1_TIME_to_tm(X509_get0_notAfter(cert), &t); caml_acquire_runtime_system(); if (!ret) caml_raise_with_arg(*caml_named_value("ssl_exn_certificate_error"), caml_copy_string("invalid certificate date")); CAMLreturn(alloc_tm(&t)); } CAMLprim value ocaml_ssl_ctx_load_verify_locations(value context, value ca_file, value ca_path) { CAMLparam3(context, ca_file, ca_path); SSL_CTX *ctx = Ctx_val(context); char *CAfile = NULL; char *CApath = NULL; int ret; check_c_string(ca_file, "Ssl.load_verify_locations"); check_c_string(ca_path, "Ssl.load_verify_locations"); if (*String_val(ca_file) != 0) CAfile = caml_stat_strdup(String_val(ca_file)); if (*String_val(ca_path) != 0) CApath = caml_stat_strdup(String_val(ca_path)); caml_release_runtime_system(); ret = SSL_CTX_load_verify_locations(ctx, CAfile, CApath); caml_acquire_runtime_system(); if (CAfile != NULL) caml_stat_free(CAfile); if (CApath != NULL) caml_stat_free(CApath); if (ret != 1) caml_invalid_argument("cafile or capath"); 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); char *hostname; int ret; check_c_string(vhostname, "Ssl.set_client_SNI_hostname"); hostname = caml_stat_strdup(String_val(vhostname)); caml_release_runtime_system(); ret = SSL_set_tlsext_host_name(ssl, hostname); caml_acquire_runtime_system(); caml_stat_free(hostname); if (ret != 1) caml_invalid_argument("Ssl.set_client_SNI_hostname"); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_set_alpn_protos(value socket, value vprotos) { CAMLparam2(socket, vprotos); SSL *ssl = SSL_val(socket); unsigned int protocol_buffer_length; unsigned char *protocol_buffer = alpn_protocol_buffer(vprotos, &protocol_buffer_length); int ret; caml_release_runtime_system(); ret = SSL_set_alpn_protos(ssl, protocol_buffer, protocol_buffer_length); caml_acquire_runtime_system(); caml_stat_free(protocol_buffer); /* Unlike most OpenSSL functions, this one returns 0 on success. */ if (ret != 0) caml_failwith("Ssl.set_alpn_protos"); 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); /* The selected protocol is not NUL-terminated. */ proto = caml_alloc_initialized_string(len, (const char *)data); CAMLreturn(caml_alloc_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); char *hostname; int ret; check_c_string(host, "Ssl.set_host"); hostname = caml_stat_strdup(String_val(host)); caml_release_runtime_system(); ret = X509_VERIFY_PARAM_set1_host(SSL_get0_param(ssl), hostname, 0); caml_acquire_runtime_system(); caml_stat_free(hostname); if (ret != 1) caml_invalid_argument("Ssl.set_host"); CAMLreturn(Val_unit); } CAMLprim value ocaml_ssl_set1_ip(value socket, value ip) { CAMLparam2(socket, ip); SSL *ssl = SSL_val(socket); char *ipval; int ret; check_c_string(ip, "Ssl.set_ip"); ipval = caml_stat_strdup(String_val(ip)); caml_release_runtime_system(); ret = X509_VERIFY_PARAM_set1_ip_asc(SSL_get0_param(ssl), ipval); caml_acquire_runtime_system(); caml_stat_free(ipval); if (ret != 1) caml_invalid_argument("Ssl.set_ip: invalid IP address"); CAMLreturn(Val_unit); } /* Offsets are checked on the OCaml side; SSL_read and SSL_write take an int, * so longer requests are shortened, as a short read or write would be. */ static int io_length(value length) { return Long_val(length) > INT_MAX ? INT_MAX : (int)Long_val(length); } CAMLprim value ocaml_ssl_write(value socket, value buffer, value start, value length) { CAMLparam2(socket, buffer); int ret, err; int buflen = io_length(length); char *buf; SSL *ssl = SSL_val(socket); buf = caml_stat_alloc(buflen); memmove(buf, (char *)Bytes_val(buffer) + Long_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(); caml_stat_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 = io_length(length); char *buf = (char *)Bytes_val(buffer) + Long_val(start); SSL *ssl = SSL_val(socket); 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) + Long_val(start); caml_release_runtime_system(); ERR_clear_error(); ret = SSL_write(ssl, buf, io_length(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) + Long_val(start); ERR_clear_error(); ret = SSL_write(ssl, buf, io_length(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 = io_length(length); char *buf; SSL *ssl = SSL_val(socket); buf = caml_stat_alloc(buflen); caml_release_runtime_system(); ERR_clear_error(); ret = SSL_read(ssl, buf, buflen); err = SSL_get_error(ssl, ret); caml_acquire_runtime_system(); if (ret > 0) memmove(((char *)Bytes_val(buffer)) + Long_val(start), buf, ret); caml_stat_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 = io_length(length); char *buf = ((char *)Bytes_val(buffer)) + Long_val(start); SSL *ssl = SSL_val(socket); 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) + Long_val(start); SSL *ssl = SSL_val(socket); caml_release_runtime_system(); ERR_clear_error(); ret = SSL_read(ssl, buf, io_length(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) + Long_val(start); SSL *ssl = SSL_val(socket); ERR_clear_error(); ret = SSL_read(ssl, buf, io_length(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. */ OPENSSL_free(subject); OPENSSL_free(issuer); return ok; } ocaml-ssl-0.8.1/src/ssl_threads.ml000066400000000000000000000015221527172722200170550ustar00rootroot00000000000000(* Copyright (C) 2003-2026 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.8.1/src/ssl_threads.mli000066400000000000000000000017551527172722200172360ustar00rootroot00000000000000(* Copyright (C) 2003-2026 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 *) (** Does nothing, kept for compatibility: OpenSSL is thread-safe on its own. *) val init : unit -> unit ocaml-ssl-0.8.1/ssl.opam000066400000000000000000000014471527172722200151060ustar00rootroot00000000000000# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "0.8.1" 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" {>= "3.23"} "ocaml" {>= "4.14"} "dune-configurator" "conf-libssl" "alcotest" {with-test} "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/savonet/ocaml-ssl.git" x-maintenance-intent: ["(latest)"] ocaml-ssl-0.8.1/tests/000077500000000000000000000000001527172722200145635ustar00rootroot00000000000000ocaml-ssl-0.8.1/tests/HACKING.md000066400000000000000000000044401527172722200161530ustar00rootroot00000000000000 ## 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 ``` ### Encrypted client key `client-encrypted.key` is `client.key` encrypted with the password `password`: ``` openssl pkey -in client.key -aes256 -passout pass:password -out client-encrypted.key ``` ocaml-ssl-0.8.1/tests/ca.key000066400000000000000000000004621527172722200156620ustar00rootroot00000000000000-----BEGIN PRIVATE KEY----- MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDBkdrXwGfmriQHz91uW GFytWEr++SdP15eRSpNSUP4znqzE+Daa4OrdTWaPBxvscN+hZANiAAQvJmpC1QYy +M9pWBnLhYR10AB5fLNIaIUz+0LXT+/ZHIJM5lUNfia1Df2VUFjaGD8FXVpEKCER 5MiudFF9p77TKx3P4X19FVZxaRBVpC3EDc3SbmWVdNRNEJDqtf9Q6+U= -----END PRIVATE KEY----- ocaml-ssl-0.8.1/tests/ca.pem000066400000000000000000000013151527172722200156510ustar00rootroot00000000000000-----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.8.1/tests/client-encrypted.key000066400000000000000000000007351527172722200205530ustar00rootroot00000000000000-----BEGIN ENCRYPTED PRIVATE KEY----- MIIBJDBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQw4byRTTUZbPgefpi J+hqdwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEB8ebTGmvIoi1c48 SjfvVWAEgcBEpjVB0aHszTVN1oC+2NNq/g7G15NQYelNUUx1qD6c/iKlcp4NbnbP 0eK9k3PldLONvFPiF8WCmCqHNqM5lAbxMUn/s6MWrjG0+wBmF3LqzwY5TZi+iZq5 7UjWv+pE37lJtn5sVzlTMTTw09mu97JaeVOyUuKFs3pvjKM6KUcnX1nYuo8hticF ywtsG7e6waLm5KzvzgXl3r4ILYOHdXLI8iBKLwv38Wow2Lh/WO3wNdbsSy8RSdha z6xCk1WRovs= -----END ENCRYPTED PRIVATE KEY----- ocaml-ssl-0.8.1/tests/client.key000066400000000000000000000004621527172722200165550ustar00rootroot00000000000000-----BEGIN PRIVATE KEY----- MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDBAFIhLeQCh3Vr38W5/ SljAb/8dibzfLx1mSfZa67Rj7146rT+2H5Xt/9kc1gZ5+sahZANiAATf4QnBA5ly rtV1W64/P3Lf5VkKjlbEHK+Cjv9zSFeSOCAAbO9De8MtDPz0TtGIY/3KJYuk55Wk jDIy2hyBmj3PapkzcknY2ehJ9WqVTCmSJeJXOOa8ZDMtPJoKs0N47Bo= -----END PRIVATE KEY----- ocaml-ssl-0.8.1/tests/client.pem000066400000000000000000000015331527172722200165460ustar00rootroot00000000000000-----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.8.1/tests/dh4096.pem000066400000000000000000000014011527172722200162000ustar00rootroot00000000000000-----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.8.1/tests/dhx.pem000066400000000000000000000014721527172722200160550ustar00rootroot00000000000000-----BEGIN X9.42 DH PARAMETERS----- MIICKQKCAQEArRB+HpEjqdDWYPqnlVnFH6INZOVoO5/RtUsVl7YdCnXm+hQd+VpW 26+aPEB7od8V6z1oijCcGA4d5rhaEnSgpm0/gVKtasISkDfJ7e/aTfjZHo/vVbc5 S3rVt9C2wSIHyfmNEe002/bGugssi7wnvmoA4KC5xJcIs7+KMXCRiDaBKGEwvImF 2xYC5xRBXZMwJ4Jzx94x79xzEPcSH9WgdBWYfZrcCkhtzfk6zEQyg4cxXXXhmMZB pIDNhqG55YfovmDmnMkosrnFIXLkEwQumyPxCw4W55djybU9z0uoCinj+3PBa451 uX7zY+L/ox9xz53lOE5xuBwKxN/+DBDmTwKCAQEArEAy708tmuOd8wtcj/2sUGze vnuJmYyvdIZqCM/k/+OmgkpOELmm8N2SHwGnDEr6q3OddwDCn1LFfbF8YgqGUr5e kAGo1mrXwXZpEBmZAkr00CcnWsE0i7inYtBSG8mK4kcVBCLqHtQJk51U2nRgzbX2 xrJQcXy+8YDrNBGOmNEZUppF1vg0Vm4wJeMWozDvu3eobwwasVsFGuPUKMj4rLcK gTcVC47rEOGD7dGZY93Z4mPkdwWJ72qiHn9fL/OBtTnM40CdE81Wavu0jWwBkYHh vP6UswJp7f5y/ptqpL17Wg8ccc//TBnEGOH27AF5gbwIfypwZbOEuJDTGR8r+gId AIAcDTTFjZP+mXF3EB+AU1pHOM68vziambNjces= -----END X9.42 DH PARAMETERS----- ocaml-ssl-0.8.1/tests/digicert_certificate.pem000066400000000000000000000025271527172722200214300ustar00rootroot00000000000000-----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.8.1/tests/dune000066400000000000000000000016101527172722200154370ustar00rootroot00000000000000(rule (alias github_action_tests) (action (run ./ssl_version.exe)) (deps (alias_rec runtest))) (executable (name ssl_version) (modules ssl_version) (libraries ssl alcotest)) (library (name util) (modules util) (libraries ssl threads str alcotest)) (tests (names ssl_test ssl_certs) (modules ssl_test ssl_certs) (libraries ssl alcotest util) (deps digicert_certificate.pem client.pem client.key dh4096.pem server.key server.pem ca.pem ca.key) (enabled_if (and (<> %{os_type} "Win32") (<> %{system} "macosx")))) (tests (names ssl_comm ssl_context ssl_ciphers ssl_sock ssl_io) (modules ssl_comm ssl_context ssl_ciphers ssl_sock ssl_io) (libraries ssl alcotest util) (deps digicert_certificate.pem client.pem client.key client-encrypted.key dh4096.pem dhx.pem server.key server.pem ca.pem ca.key) (enabled_if (<> %{system} "macosx"))) ocaml-ssl-0.8.1/tests/expired.pem000077500000000000000000000036061527172722200167360ustar00rootroot00000000000000-----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.8.1/tests/server.key000066400000000000000000000004621527172722200166050ustar00rootroot00000000000000-----BEGIN PRIVATE KEY----- MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDDHhWjSht5HNmGvrOlg SyEG8EvPIbnnMbqZ1R3RfcVqF9LK2llxvp/JPawIT2IXtFWhZANiAASesxY+SyVB EI9UHLID9jfW2LgKrZw3xUgMsrlf7euIsEbrKqeioF7BUck7E14C+GAfTtBMpcbZ oM1N5bFkb8Pj6lv9fVdssuvCI1BD+YOdZKooxgD2VLY2kHlzrLT0Sbo= -----END PRIVATE KEY----- ocaml-ssl-0.8.1/tests/server.pem000066400000000000000000000015471527172722200166030ustar00rootroot00000000000000-----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.8.1/tests/ssl_certs.ml000066400000000000000000000035071527172722200171230ustar00rootroot00000000000000open 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 = Util.server_thread None in 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.8.1/tests/ssl_ciphers.ml000066400000000000000000000060661527172722200174430ustar00rootroot00000000000000open 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"; Ssl.init_dh_from_file context "dhx.pem"; check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error) let test_init_dh_errors () = let context = Ssl.create_context TLSv1_3 Server_context in List.iter (fun path -> check_raises path Ssl.Diffie_hellman_error (fun () -> Ssl.init_dh_from_file context path)) [""; "missing.pem"; "client.pem"] 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_init_ec_errors () = let context = Ssl.create_context TLSv1_3 Server_context in List.iter (fun curve -> check_raises curve Ssl.Ec_curve_error (fun () -> Ssl.init_ec_from_named_curve context curve)) [""; "no-such-curve"] let test_socket_cipher_funcs () = let addr = Util.server_thread None in 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 "Init DH errors" `Quick test_init_dh_errors; test_case "Init EC errors" `Quick test_init_ec_errors; test_case "Cipher funcs" `Quick test_socket_cipher_funcs; ] ); ] ocaml-ssl-0.8.1/tests/ssl_comm.ml000066400000000000000000000025111527172722200167300ustar00rootroot00000000000000open 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.8.1/tests/ssl_context.ml000066400000000000000000000241541527172722200174700ustar00rootroot00000000000000open 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) (* SSLv23 accepts every version the library supports, whatever its oldest one: OpenSSL 4 has no SSLv3 any more. *) let test_create_any_version_context () = let[@alert "-deprecated"] any = SSLv23 in let context = Ssl.create_context any Server_context in check bool "no errors" true (Ssl.get_error_string () |> check_ssl_no_error); check protocol_testable "max version" TLSv1_3 (Ssl.get_max_protocol_version context) 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 rec clear_error_queue () = let error = Ssl.Error.get_error () in if error.library_number <> 0 || error.reason_code <> 0 then clear_error_queue () let test_password_callback () = let encrypted_key = In_channel.with_open_bin "client-encrypted.key" In_channel.input_all in let loaders = [ ( "file", fun context -> Ssl.use_certificate context "client.pem" "client-encrypted.key" ); ( "string", fun context -> Ssl.use_certificate_from_string context certstring encrypted_key ); ] in List.iter (fun (loader_name, load) -> let use_encrypted_key password = let context = Ssl.create_context TLSv1_3 Server_context in Ssl.set_password_callback context password; let result = match load context with | () -> "loaded" | exception Private_key_error _ -> "private key error" | exception exn -> Printexc.to_string exn in clear_error_queue (); result in let check_loader name expected password = check string (loader_name ^ ": " ^ name) expected (use_encrypted_key password) in check_loader "right password" "loaded" (fun _ -> "password"); check_loader "wrong password" "private key error" (fun _ -> "wrong"); check_loader "callback raises" "private key error" (fun _ -> raise Exit); check_loader "password too long" "private key error" (fun _ -> String.make 100_000 'a')) loaders let released_callbacks = ref 0 let tracked_callback result = let marker = ref () in Gc.finalise (fun _ -> incr released_callbacks) marker; fun _ -> ignore (Sys.opaque_identity marker); result let[@inline never] set_callbacks_on_dropped_context () = let context = Ssl.create_context TLSv1_3 Server_context in Ssl.set_password_callback context (tracked_callback "password"); Ssl.set_password_callback context (tracked_callback "password"); Ssl.set_context_alpn_select_callback context (tracked_callback None) let test_callbacks_released () = set_callbacks_on_dropped_context (); for _ = 1 to 3 do Gc.full_major () done; check int "released callbacks" 3 !released_callbacks let test_reject_nul_bytes () = let context = Ssl.create_context TLSv1_3 Server_context in let certificate = Ssl.read_certificate "client.pem" in let with_nul = "client.pem\000ignored" in let rejects name f = match f () with | () -> fail (name ^ " accepted a NUL byte") | exception Invalid_argument _ -> () in rejects "use_certificate cert" (fun () -> Ssl.use_certificate context with_nul "client.key"); rejects "use_certificate key" (fun () -> Ssl.use_certificate context "client.pem" "client.key\000ignored"); rejects "set_client_CA_list_from_file" (fun () -> Ssl.set_client_CA_list_from_file context with_nul); rejects "set_cipher_list" (fun () -> Ssl.set_cipher_list context "DEFAULT\000ignored"); rejects "load_verify_locations file" (fun () -> Ssl.load_verify_locations context with_nul ""); rejects "load_verify_locations path" (fun () -> Ssl.load_verify_locations context "" ".\000ignored"); rejects "read_certificate" (fun () -> ignore (Ssl.read_certificate with_nul)); rejects "write_certificate" (fun () -> Ssl.write_certificate "written.pem\000ignored" certificate); rejects "init_dh_from_file" (fun () -> Ssl.init_dh_from_file context "dh4096.pem\000ignored"); rejects "init_ec_from_named_curve" (fun () -> Ssl.init_ec_from_named_curve context "secp384r1\000ignored") 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 "Create any-version context" `Quick test_create_any_version_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 "Password callback" `Quick test_password_callback; test_case "Reject NUL bytes" `Quick test_reject_nul_bytes; test_case "Callbacks released" `Quick test_callbacks_released; 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.8.1/tests/ssl_io.ml000066400000000000000000000131701527172722200164070ustar00rootroot00000000000000open Alcotest let test_verify () = let addr = Util.server_thread None in 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 = Util.server_thread None in 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_reject_invalid_names () = let context = Ssl.create_context TLSv1_3 Client_context in let sock = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in let ssl = Ssl.embed_socket sock context in let rejects name f = match f () with | () -> fail (name ^ " was accepted") | exception Invalid_argument _ -> () in rejects "set_ip with a hostname" (fun () -> Ssl.set_ip ssl "localhost"); rejects "set_host with a NUL byte" (fun () -> Ssl.set_host ssl "evil.com\000.good.com"); rejects "SNI hostname with a NUL byte" (fun () -> Ssl.set_client_SNI_hostname ssl "evil.com\000.good.com"); Ssl.set_ip ssl "127.0.0.1"; Ssl.set_host ssl "localhost"; Unix.close sock let test_bounds () = let context = Ssl.create_context TLSv1_3 Client_context in let sock = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in let ssl = Ssl.embed_socket sock context in let bytes = Bytes.create 8 in let bigarray = Bigarray.(Array1.create char c_layout 8) in let functions = [ ("read", fun start length -> Ssl.read ssl bytes start length); ("write", fun start length -> Ssl.write ssl bytes start length); ( "write_substring", fun start length -> Ssl.write_substring ssl (Bytes.to_string bytes) start length ); ( "read_into_bigarray", fun start length -> Ssl.read_into_bigarray ssl bigarray start length ); ( "write_bigarray", fun start length -> Ssl.write_bigarray ssl bigarray start length ); ( "Runtime_lock.read", fun start length -> Ssl.Runtime_lock.read ssl bytes start length ); ( "Runtime_lock.write", fun start length -> Ssl.Runtime_lock.write ssl bytes start length ); ( "Runtime_lock.read_into_bigarray", fun start length -> Ssl.Runtime_lock.read_into_bigarray ssl bigarray start length ); ( "Runtime_lock.write_bigarray", fun start length -> Ssl.Runtime_lock.write_bigarray ssl bigarray start length ); ] in let out_of_bounds = [(max_int, 1); (1, max_int); (-1, 1); (0, -1); (4, 5)] @ if Sys.int_size > 32 then [(1 lsl 32, 1)] else [] in List.iter (fun (name, f) -> List.iter (fun (start, length) -> match f start length with | _ -> failf "%s %d %d was accepted" name start length | exception Invalid_argument _ -> ()) out_of_bounds) functions; Unix.close sock let test_read_write () = let addr = Util.server_thread (Some (fun _ -> "received")) in 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 test_input_string () = let addr = Util.server_thread (Some (fun _ -> "received")) in let context = Ssl.create_context TLSv1_3 Client_context in let ssl = Ssl.open_connection_with_context context addr in Ssl.output_string ssl "send"; let received = Ssl.input_string ssl in Ssl.shutdown_connection ssl; check string "received message" "received" received let test_read_short_does_not_clobber_tail () = let iterations = 64 in let io_size = 4096 in for _ = 1 to iterations do let addr = Util.server_thread (Some (fun _ -> "z")) in let context = Ssl.create_context TLSv1_3 Client_context in let ssl = Ssl.open_connection_with_context context addr in let write_buf = Bytes.make io_size 'x' in let read_buf = Bytes.make io_size '?' in let bytes_read = Ssl.write ssl write_buf 0 io_size |> ignore; Ssl.read ssl read_buf 0 io_size in Ssl.shutdown_connection ssl; check int "short read length" 1 bytes_read; check char "first byte copied" 'z' (Bytes.get read_buf 0); check string "tail preserved" (String.make (io_size - 1) '?') (Bytes.sub_string read_buf 1 (io_size - 1)) done let () = run "Ssl io functions" [ ( "IO", [ test_case "Verify" `Quick test_verify; test_case "Set host" `Quick test_set_host; test_case "Reject invalid names" `Quick test_reject_invalid_names; test_case "Read write" `Quick test_read_write; test_case "Bounds" `Quick test_bounds; test_case "Input string" `Quick test_input_string; test_case "Short read preserves tail" `Quick test_read_short_does_not_clobber_tail; ] ); ] ocaml-ssl-0.8.1/tests/ssl_sock.ml000066400000000000000000000101401527172722200167310ustar00rootroot00000000000000open Alcotest open Util let test_sockets_sni () = let addr = Util.server_thread None in 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 = Util.server_thread None in 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 (* Runs one handshake against a server using [select], returning how the server-side accept ended. *) let server_accept_with_alpn_select select = let listener = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in Unix.bind listener (Unix.ADDR_INET (Unix.inet_addr_loopback, 0)); Unix.listen listener 1; let server_context = Ssl.create_context TLSv1_3 Server_context in Ssl.use_certificate server_context "server.pem" "server.key"; Ssl.set_context_alpn_select_callback server_context select; let server_result = ref "not run" in let server = Thread.create (fun () -> let sock, _ = Unix.accept listener in let ssl = Ssl.embed_socket sock server_context in (server_result := match Ssl.accept ssl with | () -> "accepted" | exception Ssl.Accept_error _ -> "accept error" | exception exn -> Printexc.to_string exn); Unix.close sock) () in let sock = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in Unix.connect sock (Unix.getsockname listener); let ssl = Ssl.embed_socket sock (Ssl.create_context TLSv1_3 Client_context) in Ssl.set_alpn_protos ssl ["http/1.1"]; (try Ssl.connect ssl with Ssl.Connection_error _ -> ()); Thread.join server; Unix.close sock; Unix.close listener; !server_result let test_alpn_select_offered () = check string "handshake" "accepted" (server_accept_with_alpn_select (fun protos -> List.nth_opt protos 0)) let test_alpn_select_raises () = check string "handshake" "accept error" (server_accept_with_alpn_select (fun _ -> raise Exit)) let test_alpn_select_not_offered () = check string "handshake" "accept error" (server_accept_with_alpn_select (fun _ -> Some "h2")) let test_alpn_invalid_protos () = let context = Ssl.create_context TLSv1_3 Client_context in let sock = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in let ssl = Ssl.embed_socket sock context in List.iter (fun protos -> (match Ssl.set_alpn_protos ssl protos with | () -> fail "invalid socket protocols accepted" | exception Invalid_argument _ -> ()); match Ssl.set_context_alpn_protos context protos with | () -> fail "invalid context protocols accepted" | exception Invalid_argument _ -> ()) [ [""]; [String.make 256 'a']; ["http/1.1"; ""]; List.init 256 (fun _ -> String.make 255 'a'); ]; Ssl.set_alpn_protos ssl [String.make 255 'a']; Unix.close sock let () = Alcotest.run "Ssl socket functions" [ ( "Sockets", [ test_case "Set client SNI" `Quick test_sockets_sni; test_case "ALPN protocols" `Quick test_sockets_alpn; test_case "ALPN select offered" `Quick test_alpn_select_offered; test_case "ALPN select raises" `Quick test_alpn_select_raises; test_case "ALPN select not offered" `Quick test_alpn_select_not_offered; test_case "ALPN invalid protocols" `Quick test_alpn_invalid_protos; ] ); ] ocaml-ssl-0.8.1/tests/ssl_test.ml000066400000000000000000000021431527172722200167550ustar00rootroot00000000000000(** 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.8.1/tests/ssl_version.ml000066400000000000000000000015421527172722200174650ustar00rootroot00000000000000open 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.8.1/tests/util.ml000066400000000000000000000040031527172722200160670ustar00rootroot00000000000000module Ssl = struct include Ssl let[@ocaml.alert "-deprecated"] get_error_string = get_error_string end open Ssl 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 (* Listens on an ephemeral loopback port and serves one connection in a thread, returning the address to connect to. *) let server_thread parser = let socket = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in Unix.bind socket (Unix.ADDR_INET (Unix.inet_addr_loopback, 0)); Unix.listen socket 1; 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); let serve () = let client, _ = Unix.accept socket in Unix.close socket; let ssl = embed_socket client context in accept ssl; match parser with | Some parser_func -> server_rw_loop ssl parser_func | None -> shutdown ssl in ignore (Thread.create serve ()); Unix.getsockname socket 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)