diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 1e940dbaae8..1fafaac11c5 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -39,3 +39,12 @@ f57431cdc88f22fa4d7962946f0d3187fe058539 # The Great Reformatting - first phase 81d882d5302b8b647202a6893b57dfdc61fd6df2 + +# Fix trailing-whitespace errors in last patch. +3282632d9325267c850072db7545a884a1637f51 + +# The Great Reformatting of 2022 +abe49856d81f51136d543539202a0bf8fb946474 + +# Reformat for sp_after_comma=add +e51d9a73693ee742b36e19fb1718e5e27167831d diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000000..6cbd3ba42ff --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,25 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior. Please make sure to not post any secrets like keys and passwords. + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Version information (please complete the following information):** + - OS: [e.g. Ubuntu 22.04] + - OpenVPN version: [e.g. 2.5.8] + - Repeat for peer if relevant + +**Additional context** +Add any other context about the problem here. diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 3bdf2aa9f00..96211429223 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -1,39 +1,66 @@ + # The name of our workflow name: Build -on: [push, pull_request] +on: + push: + pull_request: jobs: + checkuncrustify: + name: "Check code style with Uncrustify" + # Ubuntu 22.04 has uncrustify 0.72_f + runs-on: ubuntu-22.04 + steps: + - name: Install dependencies + run: sudo apt update && sudo apt install -y uncrustify + - name: Checkout OpenVPN + uses: actions/checkout@v3 + with: + path: openvpn + - name: Show uncrustify version + run: uncrustify --version + - name: Run uncrustify + run: ./dev-tools/reformat-all.sh + working-directory: openvpn + - name: Check for changes + run: git diff --output=uncrustify-changes.patch + working-directory: openvpn + - name: Show changes on standard output + run: git diff + working-directory: openvpn + - uses: actions/upload-artifact@v3 + with: + name: uncrustify-changes.patch + path: 'openvpn/uncrustify-changes.patch' + - name: Set job status + run: test ! -s uncrustify-changes.patch + working-directory: openvpn + mingw: strategy: fail-fast: false matrix: + osslver: [1.1.1q, 3.0.5] + target: [mingw64, mingw] include: - target: mingw64 chost: x86_64-w64-mingw32 - target: mingw chost: i686-w64-mingw32 - name: "gcc-mingw - ${{matrix.target}}" - - runs-on: ubuntu-20.04 + name: "gcc-mingw - ${{matrix.target}} - OSSL ${{ matrix.osslver }}" + runs-on: ubuntu-22.04 env: MAKEFLAGS: -j3 LZO_VERSION: "2.10" - PKCS11_HELPER_VERSION: "1.26" - OPENSSL_VERSION: "1.1.1j" + PKCS11_HELPER_VERSION: "1.29.0" + OPENSSL_VERSION: "${{ matrix.osslver }}" TAP_WINDOWS_VERSION: "9.23.3" - CHOST: ${{ matrix.chost }} - TARGET: ${{ matrix.target }} steps: - name: Install dependencies run: sudo apt update && sudo apt install -y mingw-w64 libtool automake autoconf man2html unzip - - name: Checkout ovpn-dco-win - uses: actions/checkout@v2 - with: - repository: OpenVPN/ovpn-dco-win - path: ovpn-dco-win - name: Checkout OpenVPN - uses: actions/checkout@v2 + uses: actions/checkout@v3 with: path: openvpn @@ -43,83 +70,86 @@ jobs: - name: Cache dependencies id: cache - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: '~/mingw/' - key: ${{ matrix.target }}-mingw-${{ env.LZO_VERSION }}-${{ env.PKCS11_HELPER_VERSION }}-${{ env.TAP_WINDOWS_VERSION }} + key: ${{ matrix.target }}-mingw-${{ matrix.osslver }}-${{ env.LZO_VERSION }}-${{ env.PKCS11_HELPER_VERSION }}-${{ env.TAP_WINDOWS_VERSION }} # Repeating if: steps.cache.outputs.cache-hit != 'true' # on every step for building dependencies is ugly but # I haven't found a better solution so far. - - name: Download mingw depnendencies + - name: Download mingw dependencies if: steps.cache.outputs.cache-hit != 'true' run: | wget -c -P download-cache/ "https://build.openvpn.net/downloads/releases/tap-windows-${TAP_WINDOWS_VERSION}.zip" wget -c -P download-cache/ "https://www.oberhumer.com/opensource/lzo/download/lzo-${LZO_VERSION}.tar.gz" - wget -c -P download-cache/ "https://github.com/OpenSC/pkcs11-helper/archive/pkcs11-helper-${PKCS11_HELPER_VERSION}.tar.gz" - wget -c -P download-cache/ "https://www.openssl.org/source/old/1.1.1/openssl-${OPENSSL_VERSION}.tar.gz" - tar zxf "download-cache/pkcs11-helper-${PKCS11_HELPER_VERSION}.tar.gz" + wget -c -P download-cache/ "https://github.com/OpenSC/pkcs11-helper/releases/download/pkcs11-helper-${PKCS11_HELPER_VERSION}/pkcs11-helper-${PKCS11_HELPER_VERSION}.tar.bz2" + tar jxf "download-cache/pkcs11-helper-${PKCS11_HELPER_VERSION}.tar.bz2" + wget -c -P download-cache/ "https://www.openssl.org/source/old/1.1.1/openssl-${OPENSSL_VERSION}.tar.gz" || wget -c -P download-cache/ "https://www.openssl.org/source/openssl-${OPENSSL_VERSION}.tar.gz" tar zxf "download-cache/openssl-${OPENSSL_VERSION}.tar.gz" tar zxf "download-cache/lzo-${LZO_VERSION}.tar.gz" unzip download-cache/tap-windows-${TAP_WINDOWS_VERSION}.zip - name: Configure OpenSSL if: steps.cache.outputs.cache-hit != 'true' - run: ./Configure --cross-compile-prefix=${CHOST}- shared ${{ matrix.target }} no-capieng --prefix="${HOME}/mingw/opt" --openssldir="${HOME}/mingw/opt" -static-libgcc - working-directory: "./openssl-1.1.1j" + run: ./Configure --cross-compile-prefix=${{ matrix.chost }}- shared ${{ matrix.target }} no-capieng --prefix="${HOME}/mingw/opt" --openssldir="${HOME}/mingw/opt" -static-libgcc + working-directory: "./openssl-${{ env.OPENSSL_VERSION }}" - name: Build OpenSSL if: steps.cache.outputs.cache-hit != 'true' run: make - working-directory: "./openssl-1.1.1j/" + working-directory: "./openssl-${{ env.OPENSSL_VERSION }}" + # OpenSSL 3.0.5 installs itself into mingw/opt/lib64 instead of + # mingw/opt/lib, so we include both dirs in the following steps + # (pkcs11-helper and OpenVPN) so the libraries will be found - name: Install OpenSSL if: steps.cache.outputs.cache-hit != 'true' run: make install - working-directory: "./openssl-1.1.1j/" + working-directory: "./openssl-${{ env.OPENSSL_VERSION }}" - name: autoreconf pkcs11-helper if: steps.cache.outputs.cache-hit != 'true' run: autoreconf -iv - working-directory: "./pkcs11-helper-pkcs11-helper-1.26" + working-directory: "./pkcs11-helper-${{ env.PKCS11_HELPER_VERSION }}" - name: configure pkcs11-helper if: steps.cache.outputs.cache-hit != 'true' - run: OPENSSL_LIBS="-L${HOME}/mingw/opt/lib -lssl -lcrypto" OPENSSL_CFLAGS=-I$HOME/mingw/opt/include PKG_CONFIG_PATH=${HOME}/mingw/opt/lib/pkgconfig ./configure --host=${CHOST} --program-prefix='' --libdir=${HOME}/mingw/opt/lib --prefix=${HOME}/mingw/opt --build=x86_64-pc-linux-gnu --disable-crypto-engine-gnutls --disable-crypto-engine-nss --disable-crypto-engine-polarssl --disable-crypto-engine-mbedtls - working-directory: "./pkcs11-helper-pkcs11-helper-1.26" + run: OPENSSL_LIBS="-L${HOME}/mingw/opt/lib -L${HOME}/mingw/opt/lib64 -lssl -lcrypto" OPENSSL_CFLAGS=-I$HOME/mingw/opt/include PKG_CONFIG_PATH=${HOME}/mingw/opt/lib/pkgconfig ./configure --host=${{ matrix.chost }} --program-prefix='' --libdir=${HOME}/mingw/opt/lib --prefix=${HOME}/mingw/opt --build=x86_64-pc-linux-gnu --disable-crypto-engine-gnutls --disable-crypto-engine-nss --disable-crypto-engine-polarssl --disable-crypto-engine-mbedtls + working-directory: "./pkcs11-helper-${{ env.PKCS11_HELPER_VERSION }}" - name: build pkcs11-helper if: steps.cache.outputs.cache-hit != 'true' run: make all - working-directory: "./pkcs11-helper-pkcs11-helper-1.26" + working-directory: "./pkcs11-helper-${{ env.PKCS11_HELPER_VERSION }}" - name: install pkcs11-helper if: steps.cache.outputs.cache-hit != 'true' run: make install - working-directory: "./pkcs11-helper-pkcs11-helper-1.26" + working-directory: "./pkcs11-helper-${{ env.PKCS11_HELPER_VERSION }}" - name: Configure lzo if: steps.cache.outputs.cache-hit != 'true' - run: ./configure --host=${CHOST} --program-prefix='' --libdir=${HOME}/mingw/opt/lib --prefix=${HOME}/mingw/opt --build=x86_64-pc-linux-gnu - working-directory: "./lzo-2.10" + run: ./configure --host=${{ matrix.chost }} --program-prefix='' --libdir=${HOME}/mingw/opt/lib --prefix=${HOME}/mingw/opt --build=x86_64-pc-linux-gnu + working-directory: "./lzo-${{ env.LZO_VERSION }}" - name: build lzo if: steps.cache.outputs.cache-hit != 'true' - working-directory: "./lzo-2.10" + working-directory: "./lzo-${{ env.LZO_VERSION }}" run: make - name: install lzo if: steps.cache.outputs.cache-hit != 'true' - working-directory: "./lzo-2.10" + working-directory: "./lzo-${{ env.LZO_VERSION }}" run: make install - name: copy tap-windows.h header if: steps.cache.outputs.cache-hit != 'true' - run: cp ./tap-windows-9.23.3/include/tap-windows.h ${HOME}/mingw/opt/include/ + run: cp ./tap-windows-${TAP_WINDOWS_VERSION}/include/tap-windows.h ${HOME}/mingw/opt/include/ - name: configure OpenVPN - run: PKG_CONFIG_PATH=${HOME}/mingw/opt/lib/pkgconfig DCO_SOURCEDIR=$(realpath ../ovpn-dco-win) LDFLAGS=-L$HOME/mingw/opt/lib CFLAGS=-I$HOME/mingw/opt/include OPENSSL_LIBS="-L${HOME}/opt/lib -lssl -lcrypto" OPENSSL_CFLAGS=-I$HOME/mingw/opt/include PREFIX=$HOME/mingw/opt LZO_CFLAGS=-I$HOME/mingw/opt/include LZO_LIBS="-L${HOME}/mingw/opt/lib -llzo2" ./configure --host=${CHOST} --disable-lz4 --enable-dco + run: PKG_CONFIG_PATH=${HOME}/mingw/opt/lib/pkgconfig LDFLAGS=-L$HOME/mingw/opt/lib CFLAGS=-I$HOME/mingw/opt/include OPENSSL_LIBS="-L${HOME}/opt/lib -L$HOME/mingw/opt/lib64 -lssl -lcrypto" OPENSSL_CFLAGS=-I$HOME/mingw/opt/include PREFIX=$HOME/mingw/opt LZO_CFLAGS=-I$HOME/mingw/opt/include LZO_LIBS="-L${HOME}/mingw/opt/lib -llzo2" ./configure --host=${{ matrix.chost }} --disable-lz4 working-directory: openvpn - name: build OpenVPN @@ -177,21 +207,28 @@ jobs: libname: OpenSSL 1.1.1 ssllib: openssl extraconf: "--disable-lzo --disable-lz4" + - os: ubuntu-20.04 + sslpkg: "libssl-dev" + libname: OpenSSL 1.1.1 + ssllib: openssl + extraconf: "--enable-dco" + nlpkg: "libnl-genl-3-dev" name: "gcc - ${{matrix.os}} - ${{matrix.libname}} ${{matrix.extraconf}}" env: SSLPKG: "${{matrix.sslpkg}}" + NLPKG: "${{matrix.nlpkg}}" runs-on: ${{matrix.os}} steps: - name: Install dependencies - run: sudo apt update && sudo apt install -y liblzo2-dev libpam0g-dev liblz4-dev linux-libc-dev man2html libcmocka-dev python3-docutils libtool automake autoconf ${SSLPKG} + run: sudo apt update && sudo apt install -y liblzo2-dev libpam0g-dev liblz4-dev libcap-ng-dev linux-libc-dev man2html libcmocka-dev python3-docutils libtool automake autoconf ${SSLPKG} ${NLPKG} - name: Checkout OpenVPN - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: autoconf run: autoreconf -fvi - name: configure - run: ./configure --with-crypto-library=${{matrix.ssllib}} ${{matrix.extraconf}} + run: ./configure --with-crypto-library=${{matrix.ssllib}} ${{matrix.extraconf}} --enable-werror - name: make all run: make -j3 - name: make check @@ -209,9 +246,9 @@ jobs: runs-on: ${{matrix.os}} steps: - name: Install dependencies - run: sudo apt update && sudo apt install -y liblzo2-dev libpam0g-dev liblz4-dev linux-libc-dev man2html clang libcmocka-dev python3-docutils libtool automake autoconf libmbedtls-dev + run: sudo apt update && sudo apt install -y liblzo2-dev libpam0g-dev liblz4-dev libcap-ng-dev linux-libc-dev man2html clang libcmocka-dev python3-docutils libtool automake autoconf libmbedtls-dev - name: Checkout OpenVPN - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: autoconf run: autoreconf -fvi - name: configure @@ -221,14 +258,13 @@ jobs: - name: make check run: make check - macos: - runs-on: macos-latest strategy: fail-fast: false matrix: - ossl: [ 1.1, 3 ] + ssllib: [ openssl11, openssl3, libressl] build: [ normal, asan ] + os: [macos-11, macos-12] include: - build: asan cflags: "-fsanitize=address -fno-optimize-sibling-calls -fsanitize-address-use-after-scope -fno-omit-frame-pointer -g -O1" @@ -239,22 +275,32 @@ jobs: cflags: "-O2 -g" ldflags: "" configureflags: "" + - ssllib: openssl11 + libdir: openssl@1.1 + configuressllib: "" + - ssllib: openssl3 + libdir: openssl@3 + configuressllib: "" + - ssllib: libressl + libdir: libressl + configuressllib: "--with-openssl-engine=no" - name: "macOS - OpenSSL ${{matrix.ossl}} - ${{matrix.build}}" + runs-on: ${{matrix.os}} + name: "${{matrix.os}} - ${{matrix.libdir}} - ${{matrix.build}}" env: CFLAGS: ${{ matrix.cflags }} LDFLAGS: ${{ matrix.ldflags }} - OPENSSL_CFLAGS: -I/usr/local/opt/openssl@${{matrix.ossl}}/include - OPENSSL_LIBS: "-L/usr/local/opt/openssl@${{matrix.ossl}}/lib -lcrypto -lssl" + OPENSSL_CFLAGS: "-I/usr/local/opt/${{matrix.libdir}}/include" + OPENSSL_LIBS: "-L/usr/local/opt/${{matrix.libdir}}/lib -lcrypto -lssl" steps: - name: Install dependencies - run: brew install openssl@1.1 openssl@3 lzo lz4 man2html cmocka libtool automake autoconf + run: brew install openssl@1.1 openssl@3 lzo lz4 man2html cmocka libtool automake autoconf libressl - name: Checkout OpenVPN - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: autoconf run: autoreconf -fvi - name: configure - run: ./configure ${{matrix.configureflags}} + run: ./configure --enable-werror ${{matrix.configureflags}} ${{matrix.configuressllib}} - name: make all run: make -j4 - name: make check @@ -281,13 +327,13 @@ jobs: runs-on: windows-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: Add MSBuild to PATH - uses: microsoft/setup-msbuild@v1 + uses: microsoft/setup-msbuild@v1.1 - name: Set up Python - uses: actions/setup-python@v2 + uses: actions/setup-python@v4 with: python-version: '3.x' @@ -297,17 +343,19 @@ jobs: - name: Restore artifacts, or setup vcpkg (do not install any package) uses: lukka/run-vcpkg@v10 with: - vcpkgGitCommitId: '4b766c1cd17205e1b768c4fadfd5f867c1d0510e' + vcpkgGitCommitId: 'cafd398be781144787573ca78390e951673c7055' appendedCacheKey: '${{matrix.triplet}}' - name: Run MSBuild consuming vcpkg.json working-directory: ${{env.GITHUB_WORKSPACE}} run: | - vcpkg integrate install + # workaround for GHA runner bug where vcpkg installation is detected at c:\vcpkg + # see https://github.com/lukka/run-vcpkg/issues/170 + ${{ github.workspace }}/vcpkg/vcpkg.exe integrate install msbuild /m /p:Configuration=${{env.BUILD_CONFIGURATION}} /p:Platform="${{ matrix.plat }}" . - name: Archive artifacts - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v3 with: name: artifacts-${{ matrix.plat }} path: | @@ -315,3 +363,78 @@ jobs: ${{ matrix.plat }}-Output/${{env.BUILD_CONFIGURATION}}/*.dll ${{ matrix.plat }}-Output/${{env.BUILD_CONFIGURATION}}/*.pdb doc/openvpn.8.html + + trigger_openvpn_build: + runs-on: windows-latest + needs: [checkuncrustify, mingw, ubuntu, ubuntu-clang-asan, macos, msvc] + if: ${{ github.event_name != 'pull_request' && github.repository == 'openvpn/openvpn' && github.ref == 'refs/heads/master' }} + + steps: + - name: Repository Dispatch + uses: peter-evans/repository-dispatch@v2 + with: + token: ${{ secrets.OPENVPN_BUILD_REPO_DISPATCH }} + repository: openvpn/openvpn-build + event-type: openvpn-commit + + libressl: + strategy: + fail-fast: false + matrix: + os: [ubuntu-22.04] + ssllib: [libressl] + build: [ normal, asan ] + configureflags: ["--with-openssl-engine=no"] + include: + - build: asan + cflags: "-fsanitize=address -fno-optimize-sibling-calls -fsanitize-address-use-after-scope -fno-omit-frame-pointer -g -O1" + ldflags: -fsanitize=address + cc: clang + - build: normal + cflags: "-O2 -g" + ldflags: "" + cc: gcc + + name: "${{matrix.cc}} ${{matrix.build}} - ${{matrix.os}} - ${{matrix.ssllib}}" + runs-on: ${{matrix.os}} + env: + CFLAGS: ${{ matrix.cflags }} + LDFLAGS: ${{ matrix.ldflags }} + CC: ${{matrix.cc}} + + steps: + - name: Install dependencies + run: sudo apt update && sudo apt install -y liblzo2-dev libpam0g-dev liblz4-dev linux-libc-dev man2html clang libcmocka-dev python3-docutils libtool automake autoconf pkg-config libcap-ng-dev + - name: "libressl: checkout" + uses: actions/checkout@v3 + with: + path: libressl + repository: libressl-portable/portable + ref: v3.5.3 + - name: "libressl: autogen.sh" + run: ./autogen.sh + working-directory: libressl + - name: "libressl: autoconf" + run: autoreconf -fvi + working-directory: libressl + - name: "libressl: configure" + run: ./configure --enable-openvpn + working-directory: libressl + - name: "libressl: make all" + run: make -j3 + working-directory: libressl + - name: "libressl: make install" + run: sudo make install + working-directory: libressl + - name: "ldconfig" + run: sudo ldconfig + - name: Checkout OpenVPN + uses: actions/checkout@v3 + - name: autoconf + run: autoreconf -fvi + - name: configure + run: ./configure --with-crypto-library=openssl ${{matrix.configureflags}} + - name: make all + run: make -j3 + - name: make check + run: make check diff --git a/.gitignore b/.gitignore index 7335154ff40..813413feca3 100644 --- a/.gitignore +++ b/.gitignore @@ -68,6 +68,10 @@ tests/t_client-*-20??????-??????/ t_client.rc t_client_ips.rc tests/unit_tests/**/*_testdriver +tests/unit_tests/engine-key/client.key +tests/unit_tests/engine-key/log.txt +tests/unit_tests/engine-key/openssl.cnf +tests/unit_tests/engine-key/passwd src/openvpn/openvpn include/openvpn-plugin.h diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index db47f39732e..a848f89973b 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -18,6 +18,14 @@ When sending patches to "openvpn-devel" the subject line should be prefixed with git-format-patch or sent using git-send-email. Try to split large patches into small, atomic pieces to make reviews easier. +Please make sure that the source code formatting follows the guidelines at +https://community.openvpn.net/openvpn/wiki/CodeStyle. Automated checking can be +done with uncrustify (http://uncrustify.sourceforge.net/) and the configuration +file which can be found in the git repository at dev-tools/uncrustify.conf. +There is also a git pre-commit hook script, which runs uncrustify automatically +each time you commit and lets you format your code conveniently, if needed. +To install the hook simply run: dev-tools/git-pre-commit-uncrustify.sh install + If you want quick feedback on a patch before sending it to openvpn-devel mailing list, you can visit the #openvpn-devel channel on irc.libera.chat. Note that you need to be logged in to Libera to join the channel: diff --git a/COPYING b/COPYING index b05944de463..e12c5141429 100644 --- a/COPYING +++ b/COPYING @@ -1,6 +1,6 @@ OpenVPN (TM) -- An Open Source VPN daemon -Copyright (C) 2002-2022 OpenVPN Inc +Copyright (C) 2002-2023 OpenVPN Inc This distribution contains multiple components, some of which fall under different licenses. By using OpenVPN @@ -31,53 +31,6 @@ OpenVPN license: file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. -Apache2 linking exception: ---------------------------- -OpenVPN is currently undergoing a license change to add an exception for -Apache 2 linking. The following exception is only valid for new contributions -after 2023-05-03 and past contribution where the authors have already agreed -to the exception. - - In addition, as a special exception, OpenVPN Inc and the - contributors give permission to link the code of this program to - libraries (the "Libraries") licensed under the Apache License - version 2.0 (this work and any linked library the "Combined Work") - and copy and distribute the Combined Work without an obligation to - license the Libraries under the GNU General Public License v2 - (GPL-2.0) as required by Section 2 of the GPL-2.0, and without an - obligation to refrain from imposing any additional restrictions in - the Apache License version 2 that are not in the GPL-2.0, as - required by Section 6 of the GPL-2.0. You must comply with the - GPL-2.0 in all other respects for the Combined Work, including - the obligation to provide source code. If you modify this file, you - may extend this exception to your version of the file, but you are - not obligated to do so. If you do not wish to do so, delete this - exception statement from your version. - -For better understanding, in plain non-legalese English this basically says: - - * The intention for this license exception is to allow OpenVPN to be - linked against APL-2 licensed libraries, even where the GPL-2.0 and - APL-2 licenses conflict from a legal perspective. - - * OpenVPN itself will stay GPL-2.0 and the code belonging to the - OpenVPN project must comply to the GPL-2.0 license. This is NOT - dual-licensing of the OpenVPN code base. - - * This license exception DOES NOT require NOR expect a license change - of the APL-2 based library. This exception allows using the APL-2 - library as-is. However, when distributing a compiled OpenVPN binary - linking against APL-2 libraries ("Combined Work"), the REQUIREMENT is - that the APL-2 library MUST also be available on similar terms as in - GPL-2.0, like providing the source code of the library upon request, - except in the two specific ways mentioned. - - * If the APL-2 based library forbids such linking and distribution, - this license exception DOES NOT overrule the restriction of the APL-2 - based library. If the APL-2 library cannot satisfy the requirements - in this license exception, you CANNOT distribute an OpenVPN binary - linked with this library. - LZO license: ------------ diff --git a/ChangeLog b/ChangeLog index 3701823d5df..cd7c0b1b365 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,166 +1,759 @@ -OpenVPN Change Log -Copyright (C) 2002-2022 OpenVPN Inc +OpenVPN ChangeLog +Copyright (C) 2002-2023 OpenVPN Inc -2023.02.14 -- Version 2.5.9 +2023.01.25 -- Version 2.6.0 -Arne Schwabe (6): - Implement optional cipher in --data-ciphers prefixed with ? - Fix handling an optional invalid cipher at the end of data-ciphers +Antonio Quartulli (1): + dco_linux: update license for ovpn_dco_linux.h + +Arne Schwabe (1): + Workaround: make ovpn-dco more reliable + +Gert Doering (3): + Fix OVPN_DEL_PEER_REASON_TRANSPORT_DISCONNECT breakage on FreeBSD+DCO + Repair special-casing of EEXIST for Linux/SITNL route install + preparing release 2.6.0 + +Lev Stipakov (3): + openvpnmsica: remove dco installer custom actions + openvpnmsica: remove unused declarations + openvpnmsica: fix adapters discovery logic for DCO + +Selva Nair (4): + Define and use macros for route addition status code + Warn when pkcs11-id or pkcs11-id-management options are ignored + Cleanup route error and debug logging on Windows + Fix one more 'existing route may get deleted' case + +Timo Rothenpieler (1): + Don't clear capability bounding set on capng_change_id + + +2023.01.12 -- Version 2.6_rc2 + +Antonio Quartulli (4): + dco: properly re-initialize dco_del_peer_reason + dco: bail out when no peer-specific message is delivered + dco: improve comment about hidden debug message + dco: print proper message in case of transport disconnection + +Arne Schwabe (3): + Add connect-freq-initial option to limit initial connection responses + Log peer-id if loglevel is D_DCO_DEBUG and dco is enabled + Deprecate OCC checking + +Frank Lichtenheld (7): + options.c: fix format security error when compiling without optimization + options.c: update usage description of --cipher + Update copyright year to 2023 + xkey_pkcs11h_sign: fix dangling pointer + options: Always define options->management_flags + check_engine_keys: make pass with OpenSSL 3 + documentation: update 'unsupported options' section + +Gert Doering (3): + Undo FreeBSD 12.x workaround on IPv6 ifconfig for 12.4 and up + Reduce logspam about 'dco_update_keys: peer_id=-1' in p2p server mode + preparing release 2.6_rc2 + +Lev Stipakov (1): + tun: move print_windows_driver() out of tun.h + +Selva Nair (11): + Properly unmap ring buffer file-map in interactive service + Use undo_lists for saving ring-buffer handles in interactive service + Cleanup: Close duplicated handles in interactive service + Preparing for better signal handling: some code refactoring + Refactor signal handling in openvpn_getaddrinfo + Use IPAPI for setting ipv6 routes when iservice not available + Fix signal handling on Windows + Assign and honour signal priority order + Distinguish route addition errors from route already exists + Propagate route error to initialization_completed() + Include CE_DISABLED status of remote in "remote-entry-get" response + + +2022.12.29 -- Version 2.6_rc1 + +Arne Schwabe (17): Ensure that argument to parse_line has always space for final sentinel Improve documentation on user/password requirement and unicodize function + Eliminate or comment empty blocks and switch fallthrough Remove unused gc_arena Fix corner case that might lead to leaked file descriptor + Deprecate NTLMv1 proxy auth method. + Use include "buffer.h" instead of include + Ensure that dco keepalive and mssfix options are also set in pure p2p mode + Make management password check constant time + Rename TM_UNTRUSTED to TM_INITIAL, always start session in TM_INITIAL rather than TM_ACTIVE or TM_INITIAL + Move dco_installed back to link_socket from link_socket.info.actual + Do not set nl socket buffer size + Also drop incoming dco packet content when dropping the packet + Improve logging when seeing a message for an unkown peer + Ignore OVPN_DEL_PEER_REASON_USERSPACE to avoid race conditions + Replace custom min macro and use more C99 style in man_remote_entry_get + Replace realloc with new gc_realloc function -Frank Lichtenheld (1): - msvc: always call git-version.py +David Sommerseth (1): + ssl_verify: Fix memleak if creating deferred auth control files fails -Lev Stipakov (1): - git-version.py: proper support for tags +Gert Doering (1): + bandaid fix for TCP multipoint server crash with Linux-DCO -Max Fillinger (1): - Check if pkcs11_cert is NULL before freeing it +Lev Stipakov (2): + git-version.py: proper support for tags + msvc: upgrade to Visual Studio 2022 -Selva Nair (3): - Do not add leading space to pushed options - pull-filter: ignore leading "spaces" in option names +Selva Nair (7): + Reduce default restart pause to 1 second Do not include auth-token in pulled option digest + Persist DCO client data channel traffic stats on restart + Add remote-count and remote-entry query via management + Permit unlimited connection entries and remotes + Use a template for 'unsupported management commands' error + Allow skipping multple remotes via management interface -2022.10.27 -- Version 2.5.8 +2022.12.15 -- Version 2.6_beta2 Antonio Quartulli (1): - tls-crypt-v2: bail out if the client key is too small + disable DCO if --secret is specified -Arne Schwabe (4): - Remove useless empty line from CR_RESPONSE message - Allow running a default configuration with TLS libraries without BF-CBC - Change command help to match man page and implementation - Fix OpenVPN querying user/password if auth-token with user expires +Arne Schwabe (7): + Fix connection cookie not including address and fix endianness in test + Fix unit test of test_pkt on little endian Linux + Disable DCO when TLS mode is not used + Ignore connection attempts while server is shutting down + Improve debug logging of DCO swap key message and Linux dco_new_peer + Trigger a USR1 if dco_update_keys fails + Set DCO_NOT_INSTALLED also for keys not in the get_key_scan range -Frank Lichtenheld (2): - t_client: Allow to force FAIL on prerequisite fails - t_client.sh: do not require fping6 +Frank Lichtenheld (1): + ChangeLog: Fix encoding -Gert Doering (1): - Preparing release 2.5.8 +Kristof Provost (4): + Read DCO traffic stats from the kernel + dco: Update counters when a client disconnects + Read the peer deletion reason from the kernel + dco: cleanup FreeBSD dco_do_read() -Lev Stipakov (1): - msvc: add branch name and commit hash to version output +Lev Stipakov (3): + Rename dco_get_peer_stats to dco_get_peer_stats_multi + management: add timer to output BYTECOUNT + Introduce dco_get_peer_stats API and Windows implementation -Martin Janů (1): - Update the replay-window backtrack log message +Marc Becker (4): + unify code path for adding PKCS#11 providers + use new pkcs11-helper interface to add providers + special handling for PKCS11 providers on win32 + vcpkg-ports/pkcs11-helper: support loader flags -Selva Nair (5): - Do not skip ERROR:/SUCCESS: response from management interface - Fix auth-token usage with management-def-auth - Allow a few levels of recursion in virtual_output_callback() - Ensure --auth-nocache is handled during renegotiation - Purge auth-token as well while purging passwords - Do not copy auth_token username to itself +Max Fillinger (2): + Correct tls-crypt-v2 metadata length in man page + Fix message for too long tls-crypt-v2 metadata -2022.05.24 -- Version 2.5.7 +2022.12.01 -- Version 2.6_beta1 -Antonio Quartulli (4): +Adrian (1): + Fix error in example firewall.sh script + +Antonio Quartulli (99): + tun.c: remove unused variable + openssl: fix EVP_PKEY_CTX memory leak + openssl: avoid NULL pointer dereference + ssl: remove unneeded if block + options: check for blanks in fingerprints and reject string if found + crypto: respect ECB argument type from prototype + Add documentation on EVENT_READ/EVENT_WRITE constants + windows: use appropriate and portable format specifier for 64bit pointer + windows: define variable only where used + windows: list all enum values in switch block + forward: get rid of useless declarations for actually static functions + mbedtls: do not define mbedtls_ctr_drbg_update_ret when not needed + route.c: pass the right parameter to IN6_IS_ADDR_UNSPECIFIED + man/protocol-options: add missing ending metachar + compat-mode: allow user to specify version to be compatible with + reject compression by default + Remove support for PF (Packet Filter) + configure: search also for rst2{man, html}.py + multi: remove extra brackets in multi_process_incoming_link() + do not include --cipher value in data-ciphers + compat-mode: add --data-cipher-fallback auomatically if requested + Set TLS 1.2 as minimum by default + doc: fix indentation in protocol-options.rst + networking: add and implement net_addr_ll_set() API + networking: add missing brackets + set_lladdr: use networking API net_addr_ll_set() on Linux + configure: remove useless -Wno-* from default CFLAGS + options.c: fix version reported in --cipher warning message + doc/cipher-negotiation.rst: avoid warning by fixing indentation + doc: remove PF leftovers from documentation + sig.c: define signal_handler on non-windows only + GitHub Actions: ensure Ubuntu builds are made with the chosen SSL library + ssl.c: use arrow operator to access object member + use 'static inline' instead of 'inline static' + GitHub Actions: add other config flavours + unit-test: fix test_crypto when USE_COMP is not defined + update copyright year to 2022 + keyingmaterialexporter.c: include strings.h + crypto: move validation logic from cipher_get to cipher_valid + crypto: move OpenSSL specific FIPS check to its backend + Get rid of README.IPv6 and TODO.IPv6 + auth_token/tls_crypt: fix usage of md_valid() + crypto: unify key_type creation code + remove unused sitnl.h file + options: drop useless netmask variable networking: use OPENVPN_ETH_ALEN instead of ETH_ALEN + networking: silence warnings about unused arguments networking_iproute2: don't pass M_WARN to openvpn_execve_check() + networking: implement net_iface_new and net_iface_del APIs t_net.sh: delete dummy iface using iproute command auth-pam.c: add missing include limits.h - -Arne Schwabe (11): + dco: introduce low-level code for handling ovpn-dco in the Linux kernel + dco: add helper function to detect if DCO is enabled or not + dco: create DCO interface using SITNL + tls-crypt-v2: bail out if the client key is too small + dco: use specific metric when installing routes + networking: fix doc for net_iface_new() API + options: don't export local function pre_connect_save() + networking_sitnl: always return negative error code in case of failure + networking: add net_iface_type API + tun: create tun_name_is_fixed helper + dco: add option check - disable DCO if conflict is detected + dco: allow user to disable it at runtime + GitHub Actions: add Linux DCO build (on Ubuntu 20.04) + dco: introduce open_tun_dco_generic() to open dynamic or fixed-name DCO devices + dco: initialize context and save pointer in TLS object + dco: configure keys in DCO right after generating them + disable DCO if no --dev was specified + dco: periodically check and possibly rotate/delete keys + dco: split option parsing routines + push: fix compilation with --disable-management and --enable-werror + dco: check that pulled options are compatible + dco: implement dco support for p2p/client code path + dco: add documentation for ovpn-dco-linux + dco: implement dco support for p2mp/server code path + dco: perform pull options check only if we pulled any option + dco: disable DCO if --allow-compress yes/asym was specified + dco: turn supported ciphers list into a function + do_open_tun: restyle 'can preserve TUN' check + do_close_tun: get rid of one level of indentation + ovpn-dco: print some netlink messages to debug level + dco: move message to DCO debug level and reword a bit + dco: properly name variables + dco: don't pass VPN IPs to NEW_PEER API in P2P mode + dco-win: ensure the DCO API is not used when running on Windows + ssl_util: fix prototype style + dco: move availability check to the end of check_option_conflict() function + dco-win: introduce low-level code for handling ovpn-dco-win in Windows + dco-win: check for incompatible options + dco-win: implement ovpn-dco support in P2P Windows code path + dco-win: add documentation to README.dco.md + dco-win: update GH Actions config file + dco: trigger ping timeout event only if the peer expired + delete_routes(_ipv6): avoid memleak if RT_DEFINED is not set + solaris/open_tun: prevent crash when dev is empty string + do not push route-ipv6 entries that are also in the iroute-ipv6 list + auth-user-pass: add support for inline credentials + get_user_pass_cr: get password from stdin if missing inline + close_tun: print interface type consistently in message + +Arne Schwabe (289): + Fix client's poor man NCP fallback + Refactor key_state_export_keying_material functions + Fix compilation with older mbed TLS versions (mbedtls_tls_prf_types undefined) + Fix client NCP OCC fallback when server and client cipher are identical + Move openvpn specific key expansion into its own function + Allow 'none' cipher being specified in --data-ciphers + Implement generating data channel keys via EKM/RFC 5705 + Ignore deprecation warning for daemon on macOS + Add function for common env setting of verify user/pass calls + Inline function tls_get_peer_info + Align reliable_free with other free methods to accept NULL + Remove NULL checks before calling free + Remove explicit setting of peer_id to false + Remove --disable-def-auth configure argument + Replace key_scan array of static pointers with inline function + Add more documentation about our internal TLS functions + Improve keys out of sync message + Clean up tls_authentication_status and document it + Rename DECRYPT_KEY_ENABLED to TLS_AUTHENTICATED + Send AUTH_FAILED message to clients on renegotiation failures + Make any auth failure tls_authentication_status return auth failed + Fix auth-token not being updated if auth-nocache is set + Remove auth_user_pass.wait_for_push variable + Fix port-share option with TLS-Crypt v2 + Zero initialise msghdr prior to calling sendmesg + Fix tls-auth mismatch OCC message when tls-cryptv2 is used. + Remove inetd support from OpenVPN + Change pull request timeout use a timeout rather than a number + Check return values in md_ctx_init and hmac_ctx_init + Implement client side handling of AUTH_PENDING message + Introduce management client state for AUTH_PENDING notifications + Add S_EXITCODE flag for openvpn_run_script to report exit code + Prefer TLS libraries TLS PRF function, fix OpenVPN in FIPS mode + Implement server side of AUTH_PENDING with extending timeout + Refactor extract_var_peer_info into standalone function and add ssl_util.c + Change parameter of send_auth_pending_messages from context to tls_multi + Allow pending auth to be send from a auth plugin + Avoid generating unecessary mbed debug messages + Add README.wolfssl documentating the state of WolfSSL in OpenVPN + Fix multiple problems when compiling with LLVM/Windows (clang-cl) + Move extract_iv_proto to ssl_util.c/h + Extend verify-hash to allow multiple hashes + Implement peer-fingerprint to check fingerprint of peer certificate + Document the simple self-signed certificate setup in examples + Deprecate the --verify-hash option + Remove empty dummy functions + Move restoring pre pull options to initialising of c2 context + Move NCP saving and restore to the prepush restore code + Restore also ping related options on a reconnect + Make buffer related function conversion explicit when narrowing + Fix socket related functions using int instead of socket_descriptor_t + Use correct types for OpenSSL and Windows APIs + Cleanup print_details and add signature/ED certificate print + Remove flexible array member autoconf check + Remove support for non ISO C99 vararg support + Fix #elif TARGET_LINUX missing defined() call + Remove superflous ifdefs around enum like defines + Rename tunnel_server_udp_single_threaded to tunnel_server_udp + Remove code for aligning non-swapped compression + Remove pointless tun_adjust_frame_parameters function + Remove unused field txqueuelen from struct tuntap + Remove unused function tls_test_auth_deferred_interval + Remove unused variable pass_config_info + Move is_proto function to the socket.h header + Implement '--compress migrate' to migrate to non-compression setup + Remove thread_mode field of multi_context + Extract multi_assign_peer_id into its own function + Remove do_init_socket_2 and do_init_socket_1 wrapper function + Always disable TLS renegotiations + Allow running a default configuration with TLS libraries without BF-CBC + Deprecate non TLS mode in OpenVPN + Remove deprecated option '--keysize' + Move auth deferred related members into its own struct + log file descriptor in more socket related error messages + Fix async push broken after auth deferred refactor + Remove conditionals compilation for P2MP, ENABLE_SHAPER and TIME_BACKTRACK_PROTECTION + Remove check for socket functions and Win XP compatbility code + Remove checks for uint* types that are part of C99 + Remove a number of checks for functions/headers that are always present + Use EVP_CTRL_AEAD_* instead EVP_CTRL_GCM_* + Remove OpenSSL configure checks + Always save/restore pull options + Also restore/save compress related options in reconnects + Also restore/save route-gateway options on SIGUSR1 reconnects + Remove LibreSSL specific defines not needed for modern LibreSSL + Add parsing of dhcp-option PROXY_HTTP + Ensure using const variables with EVP_PKEY_get0_* + Move context_auth from context_2 to tls_multi and name it multi_state + Fix condition to generate session keys + Remove always enabled USE_64_BIT_COUNTERS define + Fix a number of mingw warnings + Move tls_select_primary_key into its own function + Allow all GCM ciphers + Change options->data_channel_use_ekm to flags + Implement deferred auth for scripts + Use functions to access key_state instead direct member access + Avoid failing_test unused warning in example_test + Move direct.h header where it is used + Replace OS_SPECIFIC_DIRSEP with PATH_SEPARATOR + Remove a number of platform specific checks in configure.ac + Remove --disable-multihome option + Remove support for blocking connect() + Fix memory leak in misc unit test + Fix binary and (&) used in auth-token check instead of logical and (&&) + Add missing free_key_ctx for auth_token + Remove explicit struct iovec check (HAVE_IOVEC) + Remove getpeername, getpid check + Inline do_init_auth_token_key + Add noreturn attribute for MSVC to assert_failed method. + Move utility function from win32.c to win32-util.c + Document stub-v2 being basically an alias for no compression at all + Return cached result in tls_authentication_status + Use exponential backoff for caching in tls_authentication_status + Add github actions + Silence warning about format string in check_ca_required + Implement auth-token-user + Move auth_token_state from multi to key_state + Add connection_established as state in tls_multi->context_auth + Make waiting on auth an explicit state in the context state machine + Ensure tls session is authenticated before sending push reply + Extracting key_state deferred auth status update into function + Move examples into openvpn-examples(5) man page + Introduce S_GENERATED_KEYS state and generate keys only when authenticated + Fix tls-cert-profile broken on OpenSSL 1.1+ + Cleanup handling of initial auth token + Remove --ncp-disable option + Add detailed man page section to setup a OpenVPN setup with peer-fingerprint + Support NCP in pure P2P VPN setups + Remove unistd.h from unit test + Introduce webauth auth pending method and deprecate openurl + Include Chacha20-Poly1305 into default --data-ciphers when available + Detect unusable ciphers on patched OpenSSL of RHEL/Centos + Fix Ubuntu spelling and duplicate run in Github Actions + Add message when decoding PKCS12 file fails. + Add small unit test for testing HMAC + Deprecate --ecdh-curve with OpenSSL 3.0 and adjust mbed TLS message + Use EVP_PKEY based API for loading DH keys + Remove DES check with OpenSSL 3.0 + Remove DES key fixup code + Do not allow CTS ciphers + Use new EVP_MAC API for HMAC implementation + Add --with-openssl-engine autoconf option (auto|yes|no) + Use EVP_PKEY_get_group_name to query group name + Replace EVP_get_cipherbyname with EVP_CIPHER_fetch + Use EVP_MD_get0_name instead EV_MD_name + Remove dependency on BF-CBC existance from test_ncp + Implement DES ECB encrypt via EVP_CIPHER api + Fix error when BF-CBC is not available + Fix function name in DH error message Add insecure tls-cert-profile options + Remove custom PRNG function + Completely remove DES checks Refactor early initialisation and uninitialisation into methods + Use TYPE_do_all_provided function for listing cipher/digest + Add macos OpenSSL 3.0 and ASAN builds Allow loading of non default providers + Move IV_TCPNL from comp_generate_peer_info_string to push_peer_info + Implement optional cipher in --data-ciphers prefixed with ? + Directly use hardcoed OPENVPN_AEAD_TAG_LENGTH instead lookup + Remove cipher_kt_var_key_size and remaining --keysize documentation + Remove cipher_ctx_get_cipher_kt and replace with direct context calls + Remove key_type->cipher_length field + Remove key_type->hmac_length + Fix handling an optional invalid cipher at the end of data-ciphers + Make --nobind default for --pull + Remove ENABLE_CRYPTO_OPENSSL ifdef inside ENABLE_CRYPTO_OPENSSL ifdef + Remove max_size from buffer_list_new + Add argv_insert_head__empty_argv__head_only to argv tests + Remove cipher_kt_t and change type to const char* in API + Move deprecation of SWEET32/64bit block size ciphers to 2.7 + Adjust cipher-negotiation.rst with compat-mode changes + Remove md_kt_t and change crypto API to use const char* + Initialise kt_cipher even when no crypto is enabled + Remove align_adjust frame code + Fix triggering assertion of ks->authenticated after tls_deauthenticate + Document frame related function and variables a bit more + Remove post_open_mtu code + Make github actions names nicer, include Ubuntu18+OpenSSL 1.0.2 + Add helper functions to calculate header/payload sizes + Decouple MSS fix calculation from frame calculation + Rework occ link-mtu calculation + Remove pointless do_init_frame_tls function + Remove BUFFER_LIST_AGGREGATE_TEST test code + Deprecate link-mtu + Fix mssfix and frame calculation in CBC mode + Change buffer allocation calculation and checks to be more static + Fix datagram_overhead and assorted functions + Implement optional mtu parameter for mssfix + Remove link_mtu parameter when running up/down scripts + Replace TUN_MTU_SIZE with frame->tun_mtu + Change the default for mssfix to mssfix 1492 mtu + Add mtu paramter to --fragment and change fragment calculation + Update fragment and mssfix related warnings + Use new frame header methods to calculate OCC_MTU_LOAD payload size + Remove extra_link from frame + Remove frame->link_mtu + Remove frame.extra_frame and frame.extra_buffer + Default to --cipher BF-CBC if not set and compat-mode < 2.4.0 + Fix 'defined but not used' warnings with enable-small/disable-management + Add Werror to github action ubuntu build + Add better documentation for CAS_* states + Add unit test for mssfix with compression involved + Remove FRAME_HEADROOM, PAYLOAD_SIZE, EXTRA_FRAME and TUN_LINK_DELTA macros + Fix mbed TLS compile if OpenSSL headers are not available + Remove unused function cipher_var_key_size + Implement fixed MSS value for mssfix and use it for non default MTUs + networking: remove duplicate methods from networking_sitnl.c + Remove dead PID_TEST code + Remove inc_pid argument from reliable_mark_deleted that is always true + Remove EXPONENTIAL_BACKOFF define + Remove tls_init_control_channel_frame_parameters wrapper function + Add documentation for swap_hmac function + Make buf_write_u8/16/32 take the type they pretend to take + Move pre decrypt lite check to its own function + Extend tls_pre_decrypt_lite to return type of packet and keep state + Move ssl function related to control channel wrap/unwrap to ssl_pkt.c/h + Add unit tests for test_tls_decrypt_lite + Split out reliable_ack_parse from reliable_ack_read + Refactor tls-auth/tls-crypt wrapping into into own function + Extract session_move_pre_start as own function, use local buffer variable + Change FULL_SYNC macro to no_pending_reliable_packets function + Extract session_move_active into its own function + Move tls_process_state into its own function + Remove pointless indentation from tls_process. + Move CRL reload to key_state_init from S_START transition + Change reliable_get_buf_sequenced to reliable_get_entry_sequenced + Implement constructing a control channel reset client as standalone function + Implement stateless HMAC-based sesssion-id three-way-handshake + Extract read_incoming_tls_ciphertext into function + Fix format specifier for printing size_t on 32bit size_t platforms + Remove workaround for Android 4.4 + Implement HMAC based session id for tls-crypt v2 + Optimise three-way handshake condition for S_PRE_START to S_START + Extract read_incoming_tls_plaintext into its own function + Add uncrustify check to github actions Add ubuntu 22.04 to Github Actions - Add macos OpenSSL 3.0 and ASAN builds - Add --with-openssl-engine autoconf option (auto|yes|no) - Fix allowing/showing unsupported ciphers and digests - Remove dependency on BF-CBC existance from test_ncp - Add message when decoding PKCS12 file fails. + Implement ED448 and ED25519 support in xkey_provider Translate OpenSSL 3.0 digest names to OpenSSL 1.1 digest names Fix client-pending-auth error message to say ERROR instead of SUCCESS + Remove useless empty line from CR_RESPONSE message + Remove leftover frame_set_mtu_dynamic definitions in mtu.h + Inline frame_add_to_extra_tun function and remove frame_defined + tun: extract close_tun_handle into its own fucntion and print correct type + Error out if both remap-usr1 SIGHUP and config stdin are used + Fix segfault when no --config argument is given + Extract check_session_cipher into standalone function + Cleanup receive_auth_failed and simplify method + Fix IV_PLAT_VER and UV_ variables sent without push-peer-info + Rename OPT_P_IPWIN32 to OPT_P_DHCPDNS and include --dns in it + Include DCO status in GLOBAL_STATS status v2 output + Github Actions: Add libreSSL actions + Include libressl and macOS 12 to macOS github actions + Fix declaration of pubkeys in test_provider.c in MSVC builds + Change command help to match man page and implementation + Implement --client-crresponse script options and plugin interface + Add example script demonstrating TOTP via auth-pending + Add OpenSSL 3.0 to mingw build + Update android.txt to reflect more recent changes. + Allow scripts and plugins to set a custom AUTH_FAILED message + Implement exit notification via control channel + Implement AUTH_FAIL, TEMP message support + Document/cleanup event_timeout functions + Fix OpenVPN querying user/password if auth-token with user expires + Enable -Werror on macOS builds + Ensure only CBC, CFB, OFB and AEAD ciphers are considered valid data ciphers + Change exit signal in P2P to be a SIGUSR1 and delayed CC exit in P2MP + Allow Authtoken lifetime to be short than renegotiation time + Allows renegotiation only to start if session is fully established + Fix renewal spelling and actually allow external-auth with renewal time + Fix regression of ignoring --user + Refactor/optimise code sending TLS control channel messages + Add unit test for reliable_get_num_output_sequenced_available + Allow setting control channel packet size with max-packet-size + Always include ACKs for the last seen control packets + Add workaround for Softether server dropping P_ACK_V1 with >= 5 acks + Improve data key id not found error message + Add packet type in accept/reject messages for HMAC packet + Fix md_kt_size in mbed TLS when queried for size of "none" + Add algorithm and bits used in key_print2 method and refactor method + Remove unused addr_inet4or6, addr_guess_family and inline addr_copy_sa + Allow tun-mtu to be pushed + Push server mtu to client when supported and support occ mtu + Fix logic error in checking early negotiation support check + Move dco_installed from sock->info to sock->info.lsa.actual + Use dedicated multi->dco_peer_id for DCO instead of multi->peer_id + Add section about common error with OpenVPN 2.6 and OpenSSL 3.0 + Introduce connection state for reconnecting peer in p2p + Signal USR1 when connection initialising fails + Allow reconnecting in p2p mode work under FreeBSD + +Camille Guérin (1): + Removed error message for an option flag not supported with --server-ipv6 -Gert Doering (1): - Preparing release 2.5.7 - -Jan Mikkelsen (1): - cipher-negotiation.rst missing from doc/Makefile.am - -Lev Stipakov (5): - vcpkg-ports\pkcs11-helper: shorten patch filename - msvc: adjust build options to harden binaries - vcpkg-ports: remove openssl port - vcpkg: switch to manifest - Fix M_ERRNO behavior on Windows - -Marc Becker (1): - vcpkg-ports/pkcs11-helper: bump to release 1.29 - -Simon Rozman (1): - tapctl: Resolve MSVC C4996 warnings +David Korczynski (1): + Fix argv leaks in add_route() and add_route_ipv6() +David Sommerseth (18): + man: Add missing --server-ipv6 + man: Improve --remote entry + sample-plugins: Partially autotoolize the sample-plugins build + build: Fix make distclean/distcheck + compat/lz4: Update to v1.9.2 + build: Fix missing install of man page in certain environments + build: Remove compat-lz4 + Update copyrights + doc: Use generic rules for man/html generation + man: Clarify IV_HWADDR + crypto: Fix OPENSSL_FIPS enabled builds + sample-plugin: New plugin for testing multiple auth plugins + plugins: Remove defer/simple.c sample plugin + plug-ins: Disallow multiple deferred authentication plug-ins + dev-tools: Remove no longer needed openvpn-plugin.h.in patching + dev-tools: Remove uncrustify -p + dev-tools: Avoid uncrustify mangling MAC_FMT macro + The Great Reformatting of 2022 -2022.03.16 -- Version 2.5.6 +Dmitry Zelenkovsky (1): + implement --session-timeout -Antonio Quartulli (4): - GitHub Actions: update script to same version as master - update copyright year to 2022 - keyingmaterialexporter.c: include strings.h - remove unused sitnl.h file +Domagoj Pensa (3): + Fix too early argv freeing when registering DNS + Remove 1 second delay before running netsh + Skip DHCP renew with Wintun adapter -David Sommerseth (2): - sample-plugin: New plugin for testing multiple auth plugins - plug-ins: Disallow multiple deferred authentication plug-ins +Eric Thorpe (1): + Fixes a bug in management_callback_send_cc_message, should be strlen instead of sizeof -Frank Lichtenheld (2): +Frank Lichtenheld (18): doc/Makefile: rebuild rst docs if input files change + doc: fix misc documentation issues doc/options: clean up documentation for --proto and related options + Reformat for sp_after_comma=add + uncrustify: add sp_after_comma=add + uncrustify: have exactly one newline at the end of files + t_client: Allow to force FAIL on prerequisite fails + systemd: remove generated service files on clean + Reduce usage of __DATE__ + config-version.h: remove unused includes + t_client.sh: do not require fping6 + doc: cleanup for --data-ciphers and related + test_crypto: fix test_occ_mtu_calculation with --disable-fragment + msvc: always call git-version.py + GitHub Issues: add note to Changes as well + GitHub Issues: add new links to INSTALL and README + GitHub Issues: Create first issue template (Bug) + documentation: avoid recommending --user nobody -Gert Doering (4): - fix Changes.rst errors in 2.5.3 and 2.5.5 announcement +Gert Doering (67): + Change version.m4 to 2.6_git + Fix stack overflow in OpenSolaris NEXTADDR() + Workaround FreeBSD 12+ race condition on tun/tap open with IPv6. + Document that --push-remove is generally more suitable than --push-reset + Fix error detection / abort in --inetd corner case. + Fix TUNSETGROUP compatibility with very old Linux systems. + Fix handling of 'route remote_host' for IPv6 transport case. + Replace 'echo -n' with 'printf' in tests/t_lpback.sh + Fix description of --client-disconnect calling convention in manpage. + Handle NULL returns from calloc() in sample plugins. + Fix --show-gateway for IPv6 on NetBSD/i386. + socks.c: fix alen for DOMAIN type addresses, bump up buffer sizes + Fix netbits setting (in TAP mode) for IPv6 on Windows. + If IPv6 pool specification sets pool start to ::0 address, increment. + Add demo plugin that excercises "CLIENT_CONNECT" and "CLIENT_CONNECT_V2" paths + Fix combination of --dev tap and --topology subnet across multiple platforms. + Fix redirecting of IPv4 default gateway if connecting over IPv6. + Fix compilation on pre-EKM mbedTLS libraries. + Avoid passing NULL to argv_printf_cat() in temp_file error case. + Change travis build scripts to use https when fetching prerequisites. + Fix line number reporting on config file errors after segments + Clarify --block-ipv6 intent and direction. + Document common uses of 'echo' directive, re-enable logging for 'echo'. + Make OPENVPN_PLUGIN_ENABLE_PF failures FATAL + clean up / rewrite sample-plugins/defer/simple.c + Fix EVP_PKEY_CTX_... compilation with LibreSSL + Require at least 100MB of mlock()-able memory if --mlock is used. + Get rid of last PLUGIN_DEF_AUTH #ifdef + Fix 'compress migrate' for 2.2 clients. + Fix potential NULL ptr crash if compiled with DMALLOC + Repair --secret deprecation warning. + rewrite parse_hash_fingerprint() + Ignore leading whitespace and comment lines for peer-fingerprint. + Add error reporting to get_console_input_win32(). + Ignore --explicit-exit-notify in TCP mode. + Use more C99 initialization in add_route/add_route_ipv6(). + Include --push-remove in the output of --help. + Move '--push-peer-info' documentation from 'server' to 'client options' + add test case(s) to notice 'openvpn --show-cipher' crashing Repair --inactive with 'bytes' argument larger 2Gbytes. Fix --mtu-disc maybe|yes on Linux. - Preparing release 2.5.6 + Fix trailing-whitespace errors in last patch. + Exclude the last two whitespace-only uncrustify fixes from git blame output. + Implement --mtu-disc for IPv6 UDP sockets. + Fix non-compliant whitespace introduced by commit 54800aa975418fe35. + Pass proper sockaddr_* structure for IPv6 socket errors. + Fix error message about extended errors for IPv4-only sockets. + Break 'try 256 dco devices' loop on EPERM + Cleanup: get rid of 'dynamic' argument of open_tun_generic() + Remove outdated information from ChangeLog, point at release branches. + Apply uncrustify changes that were forgotten in the last patch. + Apply uncrustify changes that were forgotten in the FreeBSD DCO 1/2 patch. + FreeBSD-DCO: repair device iteration to find first free interface. + DCO: require valid netbits setting for non-primary iroutes. + Adjust Linux+FreeBSD DCO device name handling to 'non DCO linux style' + cleanup open_tun() for TARGET_NETBSD + t_client: add per-instance arguments to fping + introduce V= level to manage t_client.sh output verbosity + un-break undo_ifconfig_ipv4()/_ipv6() on all non-linux/non-win32 platforms + use boolean '||' to join two bools, not bitwise '|' + denoise tests/t_lpback.sh + FreeBSD: for topology subnet, put tun interface into IFF_BROADCAST mode + FreeBSD DCO: introduce real subnet mode + Improve documentation for --dev and --dev-node. + Update PORTS + rework INSTALL and README to prepare for 2.6 release + Preparing release 2.6_beta1 -Ilya Shipitsin (1): - CI: github actions: keep "pdb" in artifacts - -Lev Stipakov (7): - auth_token.c: add NULL initialization - vcpkg-ports/pkcs11-helper: bump to release 1.28 - vcpkg-ports/pkcs11-helper: indicate OpenSSL EC support - msvc: cleanup - vcpkg: link lzo statically - vcpkg-ports/pkcs11-helper: adapt to new upstream URL - vcpkg-ports: add openssl 1.1.1n +Greg Cox (5): + Fix naming error in sample-plugins/defer/simple.c + Documentation fixes around openvpn_plugin_func_v3 in openvpn-plugin.h.in + Update openvpn_plugin_func_v2 to _v3 in sample-plugins/defer/simple.c + More explicit versioning compatibility in sample-plugins/defer/simple.c + Explain structver usage in sample defer plugin. +Heiko Hund (10): + add support for --dns option + Add git pre-commit hook script to uncrustify + pre-commit: uncrustify based on staged changes + remove foreign_option() call for IPv6 DNS servers + remove dead foreign-option parsing code + rename foreign_option() and move it up + doc: fix literal block in tls-options.rst + dns: also (re)place foreign dhcp options in env + signal --dns support in peer info + make %x destination unsigned + +Ilya Ponetayev (1): + fix compilation issues with small and w/o debug + +Ilya Shipitsin (2): + CI: github actions: keep "pdb" in artifacts + BUILD: enable CFG and Spectre mitigation for MSVC -2021.12.14 -- Version 2.5.5 +Jan Mikkelsen (1): + cipher-negotiation.rst missing from doc/Makefile.am -Adrian (1): - Fix error in example firewall.sh script +Jan Seeger (1): + Added 'route_ipv6_metric_NN' environment variable for IPv6 route metric. -Antonio Quartulli (1): - configure: remove useless -Wno-* from default CFLAGS +Jason A. Donenfeld (1): + Support fingerprint authentication without CA certificate -Arne Schwabe (2): - Add argv_insert_head__empty_argv__head_only to argv tests - Move deprecation of SWEET32/64bit block size ciphers to 2.7 +Jeff (1): + duplicate function declaration. -Gert Doering (3): - Include --push-remove in the output of --help. - Move '--push-peer-info' documentation from 'server' to 'client options' - add test case(s) to notice 'openvpn --show-cipher' crashing +Juliusz Sosinowicz (4): + EVP_DigestSignFinal siglen parameter correction + Support for wolfSSL in OpenVPN + build: Add support for pkg-config < 0.28 for old autoconf versions + README.wolfssl Update -Ilya Shipitsin (1): - BUILD: enable CFG and Spectre mitigation for MSVC +Kristof Provost (6): + Handle exceeding 'max-clients' + ovpn-dco: introduce FreeBSD data-channel offload support + Support creating iroute route entries on FreeBSD + FreeBSD networking cleanup + FreeBSD DCO: support AES-192-GCM + dco: pass control packets through the socket on FreeBSD -Lev Stipakov (12): +Lev Stipakov (68): + tun.c: enable using wintun driver under SYSTEM + openvpnmsica: make adapter renaming non-fatal + msvc: better support for 32bit architecture + Alias ADAPTER_DOMAIN_SUFFIX to DOMAIN + ssl_common.h: fix 'not all control paths return a value' msvc warning + Remove compat-lz4 references from VS project files + tapctl: support for ovpn-dco Windows driver + msvc: add ARM64 configuration + win32: add missing include header + openvpnmsica: properly schedule reboot in the end of installation + options.c: fix msvc build error + msvc: standalone building + contrib/vcpkg-ports: add pkcs11-helper port + vcpkg-ports: restore trailing whitespaces in .patch files + GitHub actions: add MSVC build + crypto_openssl.c: disable explicit initialization on Windows (CVE-2121-3606) + contrib/vcpkg-ports: add openssl port with --no-autoload-config option set (CVE-2121-3606) + Fix console prompts with redirected log + GitHub Actions: fix MSVC builds + contrib/vcpkg-ports: remove openssl port + Add building man page on Windows + GitHub Actions: remove Ubuntu 16.04 environment Fix loading PKCS12 files on Windows msvc: fix product version display - msvc: add missing header to project file config-msvc.h: fix OpenSSL-related defines - contrib/vcpkg-ports: remove openssl port GitHub Actions: use latest working lukka/run-vcpkg Use network address for emulated DHCP server as a default Load OpenSSL config on Windows from trusted location @@ -168,6206 +761,201 @@ Lev Stipakov (12): ssh_openssl.h: remove unused declaration vcpkg/pkcs11-helper: compatibility with latest vcpkg config-msvc.h: indicate key material export support + auth_token.c: add NULL initialization + tun: remove tun_finalize() + vcpkg-ports/pkcs11-helper: bump to release 1.28 + vcpkg-ports/pkcs11-helper: indicate OpenSSL EC support + xkey: fix msvc build + msvc: switch to openssl3 + msvc: cleanup + vcpkg: link lzo statically + openvpnmsica: add ovpn-dco custom actions + vcpkg-ports/pkcs11-helper: adapt to new upstream URL + vcpkg-ports\pkcs11-helper: shorten patch filename + vcpkg-ports\openssl3: update to 3.0.2 + Fix incorrect default mssfix value in server mode + msvc: adjust build options to harden binaries + vcpkg: switch to manifest + Fix M_ERRNO behavior on Windows + GitHub Actions: trigger openvpn-build GHA on success + Set o->use_peer_id flag for p2p mode + openvpnmsica: remove OpenVPNService state check code + tun.c: remove unused gc_arena from init_tun() + error.c: remove unused crash() function + tun: properly handle device interface list + dco.h: fix return type when DCO is not enabled + dco-win: use run-time dynamic linking for GetOverlappedResultEx + vcpkg: bump baseline version + do_persist_tuntap: remove indentation level + msvc: remove .filters files + dco.c: check certain options only on startup + Use DCO on Windows by default + doc: add "ovpn-dco" to usage and man page + dco-win: support for --persist-tun + msvc: add branch name and commit hash to version output + vcpkg: use the latest versions of dependency ports + win32: detect arm64 architecture and emulations + INSTALL: update Windows notes + dco: disable dco on Windows if --remote is not defined -Max Fillinger (2): - Don't use BF-CBC in unit tests if we don't have it - Define have_blowfish variable in ncp unit tests - -Richard T Bonhomme (1): - doc link-options.rst: Use free open-source dynamic-DNS provider URL +Magnus Kroken (2): + doc: fix typos in cipher-negotiation.rst + Changes.rst: fix mistyped option names -Selva Nair (3): - Fix some more wrong defines in config-msvc.h - Ensure the current common_name is in the environment for scripts - Require EC key support in Windows builds +Marc Becker (2): + vcpkg-ports/pkcs11-helper: bump to release 1.29 + fix GitHub workflow working directories in MinGW builds -Sergio E. Nemirowski (1): - resolvconf fails with -p +Martin Janu (1): + Update the replay-window backtrack log message -Todd Zullinger (2): - Update IRC information in CONTRIBUTING.rst - doc/man (vpn-network-options): fix foreign_option_{n} typo +Matthias Andree (1): + Fix SIGSEGV (NULL deref) receiving push "echo" -Ville Skyttä (1): - README.down-root: Fix plugin module name - - -2021.10.04 -- Version 2.5.4 - -Antonio Quartulli (3): - route.c: pass the right parameter to IN6_IS_ADDR_UNSPECIFIED - configure: search also for rst2{man, html}.py - networking: add networking API net_addr_ll_set() and use it on Linux - -Arne Schwabe (1): - Move examples into openvpn-examples(5) man page - -David Korczynski (1): - Fix argv leaks in add_route() and add_route_ipv6() - -David Sommerseth (2): - doc: Use generic rules for man/html generation - man: Clarify IV_HWADDR - -Gert Doering (1): - Add error reporting to get_console_input_win32(). - -Lev Stipakov (3): - Fix console prompts with redirected log - Add building man page on Windows - GitHub Actions: remove Ubuntu 16.04 environment - -Max Fillinger (1): - Update Fox e-mail address in copyright notices - -Selva Nair (1): - Minor doc correction: tls-crypt-v2 key generation - - -2021.06.17 -- Version 2.5.3 - -Arne Schwabe (3): - Add missing free_key_ctx for auth_token - Add github actions - Implement auth-token-user - -David Sommerseth (1): - Update copyrights - -Lev Stipakov (8): - openvpnmsica: properly schedule reboot in the end of installation - msvc: add ARM64 configuration - msvc: standalone building - contrib/vcpkg-ports: add pkcs11-helper port - vcpkg-ports: restore trailing whitespaces in .patch files - GitHub actions: add MSVC build - crypto_openssl.c: disable explicit initialization on Windows (CVE-2121-3606) - contrib/vcpkg-ports: add openssl port with --no-autoload-config option set (CVE-2121-3606) - -Matthias Andree (1): - Fix SIGSEGV (NULL deref) receiving push "echo" - -Max Fillinger (1): +Max Fillinger (15): + Wipe Socks5 credentials after use Fix build with mbedtls w/o SSL renegotiation support - -Selva Nair (2): - Improve documentation of AUTH_PENDING related directives - Apply the connect-retry backoff to only one side of a connection - - -2021.04.20 -- Version 2.5.2 - -Arne Schwabe (10): - Avoid generating unecessary mbed debug messages - Restore also ping related options on a reconnect - Cleanup print_details and add signature/ED certificate print - Always disable TLS renegotiations - Also restore/save route-gateway options on SIGUSR1 reconnects - Move context_auth from context_2 to tls_multi and name it multi_state - Fix condition to generate session keys - Move auth_token_state from multi to key_state - Ensure auth-token is only sent on a fully authenticated session - Ensure key state is authenticated before sending push reply - -Gert Doering (2): - Fix potential NULL ptr crash if compiled with DMALLOC - -Max Fillinger (2): In init_ssl, open the correct CRL path pre-chroot Abort if CRL file can't be stat-ed in ssl_init + Update Fox e-mail address in copyright notices + Replace deprecated mbedtls DRBG update function + Fix build with compression disabled + Don't manually free DH params in OpenSSL 3 + Remove unused havege.h header + Don't use BF-CBC in unit tests if we don't have it + Add warning about mbed TLS licensing problem + Don't "undo" ifconfig on exit if it wasn't done + Update openssl_compat.h for newer LibreSSL + Handle EVP_MD_CTX as an opaque struct + Check if pkcs11_cert is NULL before freeing it -Richard Bonhomme (1): - Do not print Diffie Hellman parameters file to log file - -Simon Rozman (1): - openvpnserv: Cache last error before it is overridden - -Vladislav Grishenko (1): - Fix IPv4 default gateway with multiple route tables - - -2021.02.24 -- Version 2.5.1 - -Arne Schwabe (5): - Fix auth-token not being updated if auth-nocache is set - Remove auth_user_pass.wait_for_push variable - Fix port-share option with TLS-Crypt v2 - Zero initialise msghdr prior to calling sendmesg - Fix tls-auth mismatch OCC message when tls-cryptv2 is used. - -David Sommerseth (1): - build: Fix missing install of man page in certain environments - -Domagoj Pensa (3): - Fix too early argv freeing when registering DNS - Remove 1 second delay before running netsh - Skip DHCP renew with Wintun adapter - -Gert Doering (6): - Change travis build scripts to use https when fetching prerequisites. - Fix line number reporting on config file errors after segments - Clarify --block-ipv6 intent and direction. - Document common uses of 'echo' directive, re-enable logging for 'echo'. - Make OPENVPN_PLUGIN_ENABLE_PF failures FATAL - clean up / rewrite sample-plugins/defer/simple.c - -Greg Cox (5): - Fix naming error in sample-plugins/defer/simple.c - Documentation fixes around openvpn_plugin_func_v3 in openvpn-plugin.h.in - Update openvpn_plugin_func_v2 to _v3 in sample-plugins/defer/simple.c - More explicit versioning compatibility in sample-plugins/defer/simple.c - Explain structver usage in sample defer plugin. - -Richard Bonhomme (1): - Man page sections corrections - -Selva Nair (1): - Quote the domain name argument passed to the wmic command - -Steffan Karger (2): - tls-crypt-v2: fix server memory leak - tls-crypt-v2: also preload tls-crypt-v2 keys (if --persist-key) - - -2020.10.27 -- Version 2.5.0 - (no changes relative to v2.5_rc3) - -2020.10.15 -- Version 2.5_rc3 -Arne Schwabe (2): - Allow 'none' cipher being specified in --data-ciphers - Add function for common env setting of verify user/pass calls - -David Sommerseth (1): - compat/lz4: Update to v1.9.2 - -Gert Doering (2): - Fix redirecting of IPv4 default gateway if connecting over IPv6. - Avoid passing NULL to argv_printf_cat() in temp_file error case. +Michael Baentsch (1): + Enable usage of TLS groups not identified by a NID in OpenSSL 3 -Jan Seeger (1): - Added 'route_ipv6_metric_NN' environment variable for IPv6 route metric. +Paolo Cerrito (1): + Insert client connection data into PAM environment -Richard Bonhomme (1): +Richard Bonhomme (6): Improve error msg when all TAP adapters are in use 'or disabled' + Man page sections corrections + Do not print Diffie Hellman parameters file to log file + Log messages: Replace NCP with --data-ciphers (NFC) + doc link-options.rst: Use free open-source dynamic-DNS provider URL + doc/protocol-options.rst: Correct default for --allow-compression -Steffan Karger (1): - networking_iproute2: fix memory leak in net_iface_mtu_set() - -Vladislav Grishenko (2): - Selectively reformat too long lines - Speedup TCP remote hosts connections - - -2020.09.30 -- Version 2.5_rc2 - -Lev Stipakov (1): - Alias ADAPTER_DOMAIN_SUFFIX to DOMAIN +Saifur Rahman Mohsin (1): + Ignore deprecation warning for daemon() on macOS (plugin/auth-pam) -Selva Nair (2): +Selva Nair (64): + Improve the documentation for --dhcp-option + In tap.c use DiInstallDevice to install the driver on a new adapter + Add a remark on dropping privileges when --mlock is used + Allow --dhcp-option in config file when windows-driver is wintun Set DNS Domain using iservice Improve documentation of --username-as-common-name + Quote the domain name argument passed to the wmic command + Remove automatic service + tun.c on WIN32: remove more unused variables + Make it explicit that WIndows build requires UNICODE support + Use C standard compliant format specs in wprintf functions + Print format spec changes for tapctl and openvpnmscia + Replace TEXT(__FUNCTION__) by __FUNCTION__ in openvpnmscia.c + Fix parsing of IV_SSO string + Do not require CA when peer-fingerprint is used + Improve documentation of AUTH_PENDING related directives + Apply the connect-retry backoff to only one side of a connection + Fix client-pending-auth help message in management interface + Minor doc correction: tls-crypt-v2 key generation + Fix the "default" tls-version-min setting + Fix some more wrong defines in config-msvc.h + Require Windows CNG keys for cryptoapicert + Remove error injection into OpenSSL from cryptoapi.c + Require EC key support in Windows builds + Ensure the current common_name is in the environment for scripts + Avoid memory leak in hmac_ctx_new (OpenSSL 3.0 only) + Fix tls-version-min default once again + A built-in provider for using external key with OpenSSL 3.0 + Implement KEYMGMT in the xkey provider + Implement SIGNATURE operations in xkey provider + Implement import of custom external keys + Initialize the xkey provider and use it in SSL context + A helper function to import private key for management-external-key + Add xkey_provider sources and includes to MSVC project + Enable signing via provider for management-external-key + Add a function to encode digests with PKCS1 DigestInfo wrapper + Allow management client to announce pss padding support + Respect algorithm support announced by management client + Support sending DigestSign request to management client + Increase ERR_BUF_SIZE when management interface support is enabled + Add a generic key loading helper function for xkey provider + pkcs11: Interface the xkey provider with pkcs11-helper + Enable signing using CNG through xkey provider + Add a unit test for external key provider + xkey: Use a custom error level for debug messages + Fix max saltlen calculation in cryptoapi.c + Support PSS signing using pkcs11-helper >= 1.28 + Do not error when md_kt_size() is called with mdname="none" + Fix a potential memory leak in tls_ctx_use_management_external_key + pkcs11_openssl.c: check EVP_get_digestbyname() != NULL + Fix crash in xkey-provider in msvc builds + Remove management_write_peer_info_file and related code + Log the actual management interface port in use + Log address of management client on accept + In x_check_status() read errno early + xkey_provider: fix building with --disable-management + Do not skip ERROR:/SUCCESS: response from management interface + Allow a few levels of recursion in virtual_output_callback() + Fix auth-token usage with management-def-auth + Ensure --auth-nocache is handled during renegotiation + Purge auth-token as well while purging passwords + Do not copy auth_token username to itself + Do not add leading space to pushed options + pull-filter: ignore leading "spaces" in option names -Simon Rozman (4): +Sergio E. Nemirowski (1): + resolvconf fails with -p + +Simon Rozman (9): + iservice: Resolve MSVC C4996 warnings + openvpnserv: Cache last error before it is overridden netsh: Specify interfaces by index rather than name netsh: Clear existing IPv6 DNS servers before configuring new ones netsh: Delete WINS servers on TUN close openvpnmsica: Simplify find_adapters() to void return + tun.c: Remove dead code + interactive.c: Resolve MSVC C4996 warning + tapctl: Resolve MSVC C4996 warnings -Vladislav Grishenko (1): - Fix update_time() and openvpn_gettimeofday() coexistence - - -2020.09.21 -- Version 2.5_rc1 - -David Sommerseth (4): - man: Add missing --server-ipv6 - man: Improve --remote entry - sample-plugins: Partially autotoolize the sample-plugins build - build: Fix make distclean/distcheck - -Gert Doering (10): - Fix handling of 'route remote_host' for IPv6 transport case. - Replace 'echo -n' with 'printf' in tests/t_lpback.sh - Fix description of --client-disconnect calling convention in manpage. - Handle NULL returns from calloc() in sample plugins. - Fix --show-gateway for IPv6 on NetBSD/i386. - socks.c: fix alen for DOMAIN type addresses, bump up buffer sizes - Fix netbits setting (in TAP mode) for IPv6 on Windows. - If IPv6 pool specification sets pool start to ::0 address, increment. - Add demo plugin that excercises "CLIENT_CONNECT" and "CLIENT_CONNECT_V2" paths - Fix combination of --dev tap and --topology subnet across multiple platforms. - -Lev Stipakov (1): - msvc: better support for 32bit architecture - -Selva Nair (2): - Add a remark on dropping privileges when --mlock is used - Allow --dhcp-option in config file when windows-driver is wintun - -Vladislav Grishenko (1): - Fix fatal error at switching remotes (#629) - +Steffan Karger (5): + networking_iproute2: fix memory leak in net_iface_mtu_set() + Simplify key material exporter backend API + tls-crypt-v2: fix server memory leak + tls-crypt-v2: also preload tls-crypt-v2 keys (if --persist-key) + reliable: retransmit if 3 follow-up ACKs are received -2020.09.10 -- Version 2.5_beta4 +Timo Rothenpieler (5): + Linux: Retain CAP_NET_ADMIN when dropping privileges + GitHub Actions: Add new libcap-ng-dev dependency + Github Actions: update used actions + dco: disable DCO if --user specified but unable to retain capabilities + dco: turn platform config checks into separate function -Gert Doering (3): - Document that --push-remove is generally more suitable than --push-reset - Fix error detection / abort in --inetd corner case. - Fix TUNSETGROUP compatibility with very old Linux systems. +Todd Zullinger (2): + Update IRC information in CONTRIBUTING.rst + doc/man (vpn-network-options): fix foreign_option_{n} typo -Lev Stipakov (1): - openvpnmsica: make adapter renaming non-fatal +Tõivo Leedjärv (1): + Stop using deprecated getpass() -Selva Nair (1): - In tap.c use DiInstallDevice to install the driver on a new adapter +Ville Skyttä (1): + README.down-root: Fix plugin module name -Vladislav Grishenko (1): +Vladislav Grishenko (8): Fix best gateway selection over netlink - - -2020.08.31 -- Version 2.5_beta3 - -Arne Schwabe (1): - Fix client NCP OCC fallback when server and client cipher are identical - -2020.08.26 -- Version 2.5_beta2 - -Arne Schwabe (1): - Fix client's poor man NCP fallback - -Eric Thorpe (1): - Fixes a bug in management_callback_send_cc_message, should be strlen instead of sizeof - -Gert Doering (2): - Fix stack overflow in OpenSolaris NEXTADDR() - Workaround FreeBSD 12+ race condition on tun/tap open with IPv6. - -Lev Stipakov (1): - tun.c: enable using wintun driver under SYSTEM - -Magnus Kroken (2): - doc: fix typos in cipher-negotiation.rst - Changes.rst: fix mistyped option names - -Selva Nair (1): - Improve the documentation for --dhcp-option - - -2020.08.12 -- Version 2.5_beta1 - -Adam Ciarcin?ski (1): - Fix subnet topology on NetBSD. - -Antonio Quartulli (113): - attempt to add IPv6 route even when no IPv6 address was configured - fix redirect-gateway behaviour when an IPv4 default route does not exist - CRL: use time_t instead of struct timespec to store last mtime - ignore remote-random-hostname if a numeric host is provided - Ignore auth-nocache for auth-user-pass if auth-token is pushed - crypto: correct typ0 in error message - use M_ERRNO instead of explicitly printing errno - don't print errno twice - ntlm: avoid useless cast - ntlm: unwrap multiple function calls - route: improve error message - management: preserve wait_for_push field when asking for user/pass - tls-crypt: avoid warnings when --disable-crypto is used - ntlm: convert binary buffers to uint8_t * - ntlm: restyle compressed multiple function calls - ntlm: improve code style and readability - OpenSSL: remove unreachable call to SSL_CTX_get0_privatekey() - make function declarations C99 compliant - remove unused functions - use NULL instead of 0 when assigning pointers - add missing static attribute to functions - ntlm: avoid breaking anti-aliasing rules - remove the --disable-multi config switch - rename mroute_extract_addr_ipv4 to mroute_extract_addr_ip - route: avoid definition of unused variables in certain configurations - fix a couple of typ0s in comments and strings - fragment.c: simplify boolean expression - tcp-server: ensure AF family is propagated to child context - Remove ENABLE_CRYPTO - Remove option to disable crypto engine - Remove ENABLE_PUSH_PEER_INFO - Remove SSL_LIB_VER_STR - Remove MD5SUM - reload HTTP proxy credentials when moving to the next connection profile - Allow learning iroutes with network made up of all 0s (only if netbits < 8) - mbedtls: fix typ0 in comment - manpage: fix simple typ0 - pool: restyle ipv4/ipv6 members to improve readability - pool: convert pool 'type' to enum - tun: ensure gc and argv are properly handled - tun: always pass a valid tt pointer - tun: get rid of tt->did_ifconfig member - tun: ensure interface can be configured with IPv6 only - add support for %lu in argv_printf and prevent ASSERT - windows: properly configure TAP driver when no IPv4 is configured - socket: make stream_buf_* functions static - crypto: always reload tls-auth/crypt key contexts - make tls-auth and tls-crypt per-connection-block options - pf: restyle pf_c2c/addr_test() to make them 'struct context' agnostic - merge *-inline.h files with their main header - ensure function declarations are compiled with their definitions - buffer_list: add functions documentation - ifconfig-ipv6(-push): allow using hostnames - tls-crypt: properly cast time_t to uint64_t - implement platform generic networking API - implement networking API for iproute2 - introduce sitnl: Simplified Interface To NetLink - tun.c: use new networking API to handle tun interface on Linux - travis.yml: add test for iproute2 net implementation - route.c: use new networking API to handle routing table on Linux - unit tests: implement test for sitnl - t_net.sh: make bash dep explicit and run only if SITNL is compiled - t_net.sh: properly perform sudo check and print test steps - route.c: fix windows build by removing mismatching function parameter - t_net.sh: fixes for the networking test script - route.c: use sitnl to implement get_default_gateway_ipv6() - networking/best_gw: remove useless prefixlen parameter - sitnl: harden strncpy() by forcing arguments to have the same length - mbedtls: fix segfault by calling mbedtls_cipher_free() in cipher_ctx_free() - networking: extend API for better memory management - tun.c: undo_ifconfig_ipv4/6 remove useless gc argument - networking_sitnl.c: uncrustify file - route.c: simplify ifdef logic - t_net.sh: wait for NO-CARRIER bit to settle before starting test - t_net.sh: execute sleep after checking exit code of previous command - maddr: create helper function to populate maddr object from eth_addr - VLAN: add basic VLAN tagging support - maddr: export VLAN ID from client context to maddr object - VLAN: filter multicast and client-to-client unicast traffic - is_ipv_X: add support for parsing IP header inside a 802.1q frame - VLAN: implement support for forwarding only pre-tagged VLAN packets - VLAN: allow forwarding tagged and untagged packets on the server TAP device - VLAN: add documentation to manpage - socks: use the right function when printing struct openvpn_sockaddr - add -Wno-stringop-truncation to CFLAGS on linux - get rid of 'broadcast' argument when configuring the tun device - auth_token_kt: ensure key_type object is initialized - auth.c: make cast explicit in the crypto API - travis: compile with -Werror on Linux - travis: fix CFLAGS assignment error and add -Werror only when compiling on Linux for Linux - sitnl: fix failure reporting by keeping error negative - sitnl: fix TUN/TAP confusion in error messages - sitnl: fix ignoring EEXIST when sending a netlink command - t_net.sh: use dummy interface instead of tun - remove bogus file check on --genkey argument - t_net.sh: assign MAC address directly during interface creation - convert *_inline attributes to bool - options: fix inlining auth-gen-token-secret file - tls-crypt-v2: fix testing of inline key - get rid of INLINE_FILE_TAG constant - pool: prevent IPv6 pools to be larger than 2^16 addresses - pool: allow to configure an IPv6-only ifconfig-pool - allow usage of --server-ipv6 even when no --server is specified - pool: add support for ifconfig-pool-persist with IPv6 only - route: warn on IPv4 routes installation when no IPv4 is configured - options: enable IPv4 redirection logic only if really required - ipv6-pool: get rid of size constraint - pool: remove useless 'options.h' include - multi: skip IPv4 logic in multi_select_virtual_addr() if no pool is configured - multi.c: use mi->cc_config instead of config variable - options: don't leak inline'd key material in logfile - t_net.sh: drop hard dependency on t_client.rc - travis: don't run t_net.sh test - -Arne Schwabe (124): - Set tls-cipher restriction before loading certificates - Print ec bit details, refuse management-external-key if key is not RSA - Replace buffer backed strings for management_android_control with simple stack variables - Treat dhcp-option DNS6 and DNS identical - show the right string for key-direction - Add MTU to Android IFCONFIG6 control command - Properly free tuntap struct on android when emulating persist-tun - Add OpenSSL compat definition for RSA_meth_set_sign - Skip error about ioctl(SIOCGIFCONF) failed on Android - Factor out convert_tls_list_to_openssl method - Remove AUTO_USERID feature - Remove MANAGMENT_EXTERNAL_KEY, MANAGMENT_IN_EXTRA, ENABLE_CLIENT_CR - Add support for tls-ciphersuites for TLS 1.3 - Add better support for showing TLS 1.3 ciphersuites in --show-tls - Use right function to set TLS1.3 restrictions in show-tls - Refuse mbed TLS external key with non RSA certificates - Add message explaining early TLS client hello failure - Add tls-crypt-v2 to the list of supported inline options - Implement block-ipv6 - Fallback to password authentication when auth-token fails - Fix loading inline tls-crypt-v2 keys with mbed TLS - Refactor tls_crypt_v2_write_server_key_file into crypto.c - Add send_control_channel_string_dowork variant - Rename tls_crypt_v2_read_keyfile into generic pem_read_key_file - Fix poll.h logic in syshead.h - Write key to stdout if filename is not given - Implement --genkey type keyfile syntax and migrate tls-crypt-v2 - Add generate_ephemeral_key that allows a random ephermal key - Remove -no-cpp-precomp flag from Darwin builds - Fix check if iface name is set - Adjust Android code after sitnl patch merge - Rewrite auth-token-gen to be based on HMAC based tokens - Implement a permanent session id in auth-token - Sent indication that a session is expired to clients - Implement unit tests for auth-gen-token - Make tls_version_max return the actual maximum version - Add support for OpenSSL TLS 1.3 when using management-external-key - Document tls-ciphersuites also in --help output - Only announce IV_NCP=2 when we are willing to support these ciphers - Add strsep compat function - Implement dynamic NCP negotiation - Warn about insecure ciphers also in init_key_type - Move NCP related function into a seperate file and add unit tests - Normalise ncp-ciphers option and restrict it to 127 bytes - Fetch OpenSSL versions via source/old links - Fix OpenSSL error stack handling of tls_ctx_add_extra_certs - Fix off-by-one in tls-crypt-v2 client wrapping with custom metadata - Fix OpenSSL 1.1.1 not using auto elliptic curve selection - Refactor counting number of element in a : delimited list into function - Minor style change to improve code style - Another round of uncrustify code cleanup. - Fix tls_ctx_client/server_new leaving error on OpenSSL error stack - Add tls-crypt-v2 test writing metadata - Use crypto library functions for const time memcmp when possible - Fix session id in env missing first byte - Document reneweal mechanic of auth-token in manual - Fix session id and initial timestamp not being preserved - Do not write extra 0 byte for --gen-key with auth-token/tls-crypt-v2 - Refuse server mode on Android - Add .git-blame-ignore-revs with reformat commits - Make cipher_kt_name always return normalised cipher name - Make cipher_kt_get also accept OpenVPN config cipher name - Implement parsing and sending INFO and INFO_PRE control messages - Implement support for signalling IV_SSO to server - Implement sending response to challenge via CR_RESPONSE - Implement sending AUTH_PENDING challenges to clients - Implement forwarding client CR_RESPONSE messages to management - Add unit test for cipher name translations - Make compression asymmetric by default and add warnings - Reformat files using uncrustify - Remove parameter config from multi_client_connect_mda - Remove push_reply_deferred variable - Remove did_open_context, defined and connection_established_flag - merge key_state->authenticated and key_state->auth_deferred - Simplify multi_connection_established. - Deprecate ncp-disable and add improved ncp to Changes.rst - Make key_state->authenticated more state machine like - Extract process_incoming_push_reply from process_incoming_push_msg - Removed unused definition - Code cleanup: remove superflous variable - Move protocol option negotiation from push_prepare to new function - Generate data channel keys after connect options have been parsed - Cleanup: Remove special case code for old poor man's NCP. - Allow changing fallback cipher from ccd files/client-connect - client-connect: Change cas_context from int to enum - client-connect: Move adding inotify watch into its own function - reformat multi_client_generate_tls_keys according to uncrustify - client-connect: Add CC_RET_DEFERRED and cope with deferred client-connect - Remove CAS_PARTIAL state - client-connect: Use inotify for the deferred client-connect status file - client-connect: Implement deferred connect support for plugin API v2 - Drop support for OpenSSL 1.0.1 - Require AEAD support in the crypto library - Remove key-method 1 - Remove ENABLE_OCC #define - Implement tls-groups option to specify eliptic curves/groups - Avoid sending --cipher to clients not supporting NCP - Indicate that a client is in pull mode in IV_PROTO - Deprecate --inetd - Include utun device number in utun error messages - Simplify calling logic of check_connection_established_dowork - Avoid sending push request after receving push reply - Rename ncp-ciphers to data-ciphers - Add a note that ncp-ciphers is replaced by data-ciphers - client-connect: Add documentation for the deferred client connect feature - Rework NCP compability logic and drop BF-CBC support by default - Document different behaviour of dynamic cipher negotiation - Minor cleanup in push.c - Clean up a number of leftover C89 initialisations in ssl.c - Remove buf argument from link_socket_set_outgoing_addr - Remove a number of check/do_work wrapper calls from coarse_timers - Split pf_check_reload check and check timer in process_coarse_timers - Rename check_ping_restart_dowork to trigger_ping_timeout_signal - Eliminate check_fragment function - Eliminate check_incoming_control_channel wrapper function - Eliminate check_tls wrapper function - Merge check_coarse_timers and check_coarse_timers_dowork - Skip existing interfaces on opening the first available utun on macOS - Move parsing IV_PROTO to separate function - Remove S_OP_NORMAL key state. - Document comp-lzo no and compress being incompatible - Refactor/Reformat tls_pre_decrypt - Cleanup tls_pre_decrypt_lite and tls_pre_encrypt - Improve sections about older OpenVPN clients in cipher-negotiation.rst - -Bertrand Bonnefoy-Claudet (1): - Fix typo in error message: "optione" -> "option" - -Christian Ehrhardt (1): - systemd: extend CapabilityBoundingSet for auth_pam - -Christian Hesse (7): - man: fix formatting for alternative option - systemd: Use automake tools to install unit files - systemd: Do not race on RuntimeDirectory - systemd: Add more security feature for systemd units - Clean up plugin path handling - plugin: Remove GNUism in openvpn-plugin.h generation - fix typo in notification message - -Christopher Schenk (3): - Set the correct mtu on windows based systems - Log a note if someone wants to set a MTU below 1280 on IPv6 - Unified success messages for setting mtu - -Conrad Hoffmann (2): - Use provided env vars in up/down script. - Document down-root plugin usage in client.down - -David Sommerseth (64): - docs: Further enhance the documentation related to SWEET32 - man: Remove references to no longer present IV_RGI6 peer-info - build: Ensure Changes.rst is shipped and installed as a doc file - management: >REMOTE operation would overwrite ce change indicator - management: Remove a redundant #ifdef block - git: Merge .gitignore files into a single file - systemd: Move the READY=1 signalling to an earlier point - dev-tools: Simple tool which automates rebasing LZ4 compat library - dev-tools: lz4-rebaser tool carried a typo - plugin: Improve the handling of default plug-in directory - cleanup: Remove faulty env processing functions - auth-token: Ensure tokens are always wiped on de-auth - docs: Fixed man-page warnings discoverd by rpmlint - Make --cipher/--auth none more explicit on the risks - Require minimum OpenSSL 1.0.1 - Fix broken ./configure on systems without openssl.pc - plugin: Fix documentation typo for type_mask - plugin: Export secure_memzero() to plug-ins - crypto: Enable SHA256 fingerprint checking in --verify-hash - copyright: Update GPLv2 license texts - dev-tools: Script generating the source releases in an automated fashion - auth-token with auth-nocache fix broke --disable-crypto builds - doc: The CRL processing is not a deprecated feature - cleanup: Move write_pid() to where it is being used - contrib: Remove keychain-mcd code - cleanup: Move init_random_seed() to where it is being used - Highlight deprecated features - Use consistent version references - docs: Replace all PolarSSL references to mbed TLS - systemd: Ensure systemd shuts down OpenVPN in a proper way - systemd: Enable systemd's auto-restart feature for server profiles - lz4: Move towards a newer LZ4 API - lz4: Fix confused version check - lz4: Fix broken builds when pkg-config is not present but system library is - Remove references to keychain-mcd in Changes.rst - lz4: Rebase compat-lz4 against upstream v1.7.5 - systemd: Add and ship README.systemd - Update copyright to include 2018 plus company name change - man: Add .TQ groff support macro - man: Reword --management to prefer unix sockets over TCP - management: Warn if TCP port is used without password - plugin: Export base64 encode and decode functions - build: Fix build warnings related to get_random() - build: Fix another compile warning in console_systemd.c - cleanup: Remove RPM openvpn.spec build approach - docs: Update INSTALL - build: Package missing mock_msg.h - auth-token: Fix building with --disable-server - auth-token: Fix compiler complaints with --disable-management - Improve the comments related to auth-token-hmac patches - Documented all the argv related code with minor refactoring - build: Remove --disable-server from ./configure - options: Fix failing inline tls-auth/crypt with persist-key - options: Restore --tls-crypt-v2 inline file capability - doc/man: convert openvpn.8 to split-up .rst files - doc/man: Mark compression options as deprecated - doc/man: Adopt compression documentation - doc/man: Documentation for --bind-dev / VRFs on Linux - doc/man: Add misssing renegotiation.rst to Makefile.am - Remove --no-iv - doc/man: Do not install man *.rst files - travis: Fix make distcheck failure - Remove --ifconfig-pool-linear - Remove --client-cert-not-required - -Domagoj Pensa (2): - Fix linking issues on MinGW - Skip DNS address validation - -Emmanuel Deloget (20): - OpenSSL: check for the SSL reason, not the full error - OpenSSL: don't use direct access to the internal of X509_STORE_CTX - OpenSSL: don't use direct access to the internal of SSL_CTX - OpenSSL: don't use direct access to the internal of X509_STORE - OpenSSL: don't use direct access to the internal of X509_OBJECT - OpenSSL: don't use direct access to the internal of RSA_METHOD - OpenSSL: SSLeay symbols are no longer available in OpenSSL 1.1 - OpenSSL: use EVP_CipherInit_ex() instead of EVP_CipherInit() - OpenSSL: don't use direct access to the internal of X509 - OpenSSL: don't use direct access to the internal of EVP_PKEY - OpenSSL: don't use direct access to the internal of RSA - OpenSSL: don't use direct access to the internal of DSA - OpenSSL: force meth->name as non-const when we free() it - OpenSSL: don't use direct access to the internal of EVP_MD_CTX - OpenSSL: don't use direct access to the internal of EVP_CIPHER_CTX - OpenSSL: don't use direct access to the internal of HMAC_CTX - OpenSSL: remove pre-1.1 function from the OpenSSL compat interface - OpenSSL: remove EVP_CIPHER_CTX_new() from the compat layer - OpenSSL: remove EVP_CIPHER_CTX_free() from the compat layer - OpenSSL: check EVP_PKEY key types before returning the pkey - -Eric Thorpe (1): - Fix Building Using MSVC - -Fabian Knittel (7): - client-connect: Split multi_connection_established into separate functions - client-connect: Refactor multi_client_connect_source_ccd - client-connect: Move multi_client_connect_setenv into early_setup - client-connect: Refactor to use return values instead of modifying a passed-in flag - client-connect: Refactor client-connect handling to calling a bunch of hooks in a loop - client-connect: Add deferred support to the client-connect script handler - client-connect: Add deferred support to the client-connect v1 plugin handler - -Gert Doering (50): - Remove IV_RGI6=1 peer-info signalling. - Add openssl_compat.h to openvpn_SOURCES - Fix '--dev null' - Fix installation of IPv6 host route to VPN server when using iservice. - Make ENABLE_OCC no longer depend on !ENABLE_SMALL - Fix NCP behaviour on TLS reconnect. - Remove erroneous limitation on max number of args for --plugin - proxy.c refactoring: remove always-NULL gc parameter - Fix edge case with clients failing to set up cipher on empty PUSH_REPLY. - Fix potential 1-byte overread in TCP option parsing. - Fix remotely-triggerable ASSERT() on malformed IPv6 packet. - Update Changes.rst with relevant info for 2.4.3 release. - Remove warning on pushed tun-ipv6 option. - Fix removal of on-link prefix on windows with netsh - Fix potential double-free() in Interactive Service (CVE-2018-9336) - Add %d, %u and %lu tests to test_argv unit tests. - Extend push-remove to also handle 'ifconfig'. - Print lzo_init() return code in case of errors - Uncrustify sample-plugin sources according to code style - uncrustify openvpnserv/ sources - uncrustify openvpn/ sources - Add 'printing of port number' to mroute_addr_print_ex() for v4-mapped v6. - Stop complaining about IPv6 routes without gateway address. - Copy one byte less in strncpynt() - Remove cmocka submodule, rely on system-wide installation instead. - Increase listen() backlog queue to 32 - repair tap mode on OpenSolaris/OpenIndiana - Fix IPv6 routes on tap interfaces on OpenSolaris/OpenIndiana - OpenSolaris/OpenIllumos: use /bin/bash if available for test scripts. - Force combinationation of --socks-proxy and --proto UDP to use IPv4. - Uncrustify the tests/unit_tests/ part of our tree. - Change client side of t_lpback.sh configs to use inline material. - Simplify pool size handling, fix possible array overrun on pool reading. - Change timestamps in file-based logging to ISO 8601 time format. - Depreciation warning for --topology net30 on servers with IPv4 pools. - Convert plugin/auth-pam.c from stderr logging to plugin_log(). - Add c1ff8f247f91c88a2df5502eeedf42857f9a6831 (engine, pool, SSO) to .git-blame-ignore-revs - Linux: do not change --txqueuelen OS default if not configured. - Fix 'engine' unit test on FreeBSD (specifically 'not GNU make') - t_client.sh: correctly report all failed instances in summary - Remove --writepid file on program exit. - Handle connecting clients without NCP or OCC without crashing. - Add deferred authentication support to plugin-auth-pam - Separate handling of non-deferred return values for client-connect-scripts. - Repair --inetd - Fix sequence of events for async plugin v1 handler. - Abort client-connect handler loop after first handler sets 'disable'. - Add depreciation notice for --ncp-disable to protocol-options.rst - Changes.rst updates in preparation to 2.5_beta1 - Preparing release 2.5_beta1 - -Gert van Dijk (7): - Warn that DH config option is only meaningful in a tls-server context - Add generated openvpn.doxyfile to .gitignore - manpage: improve description of --status and --status-version - Add negotiated cipher to status file format 2 and 3 - Minor reliability layer documentation fixes - Make second parameter to reliable_send_purge() const - Remove unneeded newline in debug message in reliable.c - -Gisle Vanem (2): - Crash in options.c - Wrong FILETYPE in .rc files - -Guido Vranken (6): - refactor my_strupr - Fix 2 memory leaks in proxy authentication routine - Fix memory leak in add_option() for option 'connection' - Ensure option array p[] is always NULL-terminated - Fix a null-pointer dereference in establish_http_proxy_passthru() - Prevent two kinds of stack buffer OOB reads and a crash for invalid input data - -Heiko Hund (3): - re-implement argv_printf_*() - argv: do fewer memory re-allocations - Add gc_arena to struct argv to save allocations - -Hilko Bengen (1): - Do not set pkcs11-helper 'safe fork mode' - -Hristo Venev (1): - Fix extract_x509_field_ssl for external objects, v2 - -Ilya Shipitsin (18): - Resolve several travis-ci issues - github: Add PR template with contributor related information - travis-ci: add 'make distcheck' to test scenario, V2 - travis-ci: remove unused files - v4, travis-ci: add 2 mingw "build only" configurations - travis-ci: added gcc and clang openssl-1.1.0 builds - travis-ci: update openssl to 1.0.2l, update mbedtls to 2.5.1 - travis-ci: update pkcs11-helper to 1.22 - travis-ci: add brew cache, remove ccache - travis-ci: modify openssl build script to support openssl-1.1.0 - travis-ci: cleanup, refactor, upgrade ssl libraries - travis-ci: add "linux-ppc64le" to build matrix - travis-ci: change trusty image to xenial - travis-ci: update osx to xcode9.4 and modernize brew management - configure.ac: fix compile-time error in argv_testdriver - travis-ci: fix osx builds - travis-ci: update components versions - travis-ci: add arm64, s390x builds. - -James Bekkema (2): - Resolves small IV_GUI_VER typo in the documentation. - Adds support for setting the default IPv6 gateway for routes using the route-ipv6-gateway option. - -James Bottomley (7): - autoconf: Fix engine checks for openssl 1.1 - openssl: add engine method for loading the key - crypto_openssl: add initialization to pick up local configuration - crypto_openssl: add include for openssl/conf.h - Add unit tests for engine keys - Fix make distcheck for new engine key unit test - engine-key tests: make check_engine_keys.sh work with --enable-small - -Jan Just Keijser (1): - Added support for DHCP option 119 (dns search suffix list) for Windows. - -Jeremie Courreges-Anglas (5): - Cast time_t to long long in order to print it. - Print time_t as long long and suseconds_t as long - Cast and print another suseconds_t as long - Use long long to format time_t-related environment variables - Fix build with LibreSSL - -Jeremy Evans (1): - Switch assertion failure to returning false - -Jonathan K. Bullard (1): - Clarify and expand management interface documentation - -Jonathan Tooker (1): - Fix various spelling mistakes - -Joost Rijneveld (1): - Make return code external tls key match docs - -Jérémie Courrèges-Anglas (2): - Fix an unaligned access on OpenBSD/sparc64 - Missing include for socket-flags TCP_NODELAY on OpenBSD - -Kyle Evans (1): - tests/t_lpback.sh: Switch sed(1) to POSIX-compatible regex. - -Lev Stipakov (46): - win: support for Visual Studio 2017 - Refactor NCP-negotiable options handling - init.c: refine functions names and description - openvpnserv: clarify return values type - crypto.h: remove unused function declaration - interactive.c: fix usage of potentially uninitialized variable - options.c: fix broken unary minus usage - Introduce openvpn_swprintf() with nul termination guarantee - Wrap openvpn_swprintf into Windows define - test_tls_crypt.c: fix global-buffer-overflow found by AddressSanitizer - crypto_openssl.c: fix heap-buffer-overflow found by AddressSanitizer - Fix various compiler warnings - Fix broken fragment/mssfix with NCP - crypto.c: fix Visual Studio build - tun.h: change tun_set() return value type to void - tun.h: remove TUN_PASS_BUFFER define - tapctl: add optional 'hardware id' parameter - vcxproj: add missing source files - push.c: fix Visual Studio build - Visual Studio: make it easier to build with VS - msvc: OpenSSL 1.1.x support - travis: add Visual Studio build - Visual Studio: upgrade project files to VS2019 - wintun: add --windows-driver config option - wintun: implement opening wintun device - travis: bump MSVC to 2019 - travis: bump clang version - wintun: ring buffers based I/O - wintun: interactive service support - wintun: set adapter properties via interactive service - wintun: clear adapter settings on tun close - tun.c: refactor open_tun() implementation - tun.c: do not add/remove on-link IPv4 route on tun open/close - options.c: do not force route delay when not using DHCP - configure.ac: simplify AC_CHECK_FUNCS statements - cryptoapi.c: fix run-time check failure in msvc debugger - interactive.c: remove unused function - tun.c: fix 'use after free' error - Fix building with --enable-async-push in FreeBSD - Fix broken async push with NCP is used - Fix illegal client float (CVE-2020-11810) - msvc: fix various level2 warnings - tap.c: fix adapter renaming - Improve Windows version detection with manifest - wintun: remove SYSTEM elevation hack - Fix compilation with --disable-lzo and --disable-lz4 - -Matthias Andree (3): - Make openvpn-plugin.h self-contained again. - Merge Makefile.am's AUTOMAKE_OPTIONS into configure.ac's AM_INIT_AUTOMAKE. - Fix stack buffer overruns in NEXTADDR() macro: - -Maxim Plotnikov (1): - OpenSSL: Fix --crl-verify not loading multiple CRLs in one file - -Maximilian Wilhelm (1): - Add --bind-dev option. - -Michal Soltys (1): - man: correct the description of --capath and --crl-verify regarding CRLs - -Mykola Baibuz (1): - Fix typo in NTLM proxy debug message - -Olivier Wahrenberger (1): - Fix building with LibreSSL 2.5.1 by cleaning a hack. - -Richard Bonhomme (3): - man: Corrections to doc/openvpn.8 - Ignore --pull-filter for --mode server - doc/man: Update --txqueuelen default setting (Now OS default) - -Richard van den Berg via Openvpn-devel (1): - Fix error message when using RHEL init script - -Rosen Penev (2): - Remove wrong poll.h include - openssl: Fix compilation without deprecated OpenSSL 1.1 APIs - -Samy Mahmoudi (1): - man: correct a --redirection-gateway option flag - -Santtu Lakkala (1): - Fix OpenSSL private key passphrase notices - -Selva Nair (55): - Fix push options digest update - Always release dhcp address in close_tun() on Windows. - Add a check for -Wl, --wrap support in linker - Fix user's group membership check in interactive service to work with domains - In auth-pam plugin clear the password after use - Pass correct buffer size to GetModuleFileNameW() - Check whether in pull_mode before warning about previous connection blocks - Avoid illegal memory access when malformed data is read from the pipe - Fix missing check for return value of malloc'd buffer - Return NULL if GetAdaptersInfo fails - Use RSA_meth_free instead of free - Bring cryptoapi.c upto speed with openssl 1.1 - Add SSL_CTX_get_max_proto_version() not in openssl 1.0 - TLS v1.2 support for cryptoapicert -- RSA only - Refactor ssl_openssl.c in prep for external EC key support - Refactor get_interface_metric to return metric and auto flag separately - Add management client version - Prompt for signature using '>PK_SIGN' if the client supports it - Allow external EC key through --management-external-key - Ensure strings read from registry are null-terminated - Make most registry values optional - Use lowest metric interface when multiple interfaces match a route - Move code to free cd to a function CAPI_DATA_free() - Disable external ec key support when building with libressl - Adapt to RegGetValue brokenness in Windows 7 - Fix format spec errors in Windows builds - Move setting private key to a function in prep for EC support - Support EC certificates with cryptoapicert - Delete the IPv6 route to the "connected" network on tun close - Management: warn about password only when the option is in use - Avoid overflow in wakeup time computation - Replace M_DEBUG with D_LOW as the former is too verbose - Correct the declaration of handle in 'struct openvpn_plugin_args_open_return' - Parse static challenge response in auth-pam plugin - Bump version of openvpn plugin argument structs to 5 - Accept empty password and/or response in auth-pam plugin - Pass the hash without the DigestInfo header to NCryptSignHash() - Move get system directory to a separate function - Enable dhcp on tap adapter using interactive service - Refactor sending commands to interactive service - Declare Windows version of openvpn_execve() before use - White-list pull-filter and script-security in interactive service - Move OpenSSL vs CNG signature digest type mapping to a function - Handle PSS padding in cryptoapicert - Better error message when script fails due to script-security setting - Correct the return value of cryptoapi RSA signature callbacks - Fix ACL_CHECK_ADD_COMPILE_FLAGS to work with clang - Swap the order of checks for validating interactive service user - Skip expired certificates in Windows certificate store - Allow unicode search string in --cryptoapicert option - Fix possibly uninitialized return value in GetOpenvpnSettings() - Fix possible access of uninitialized pipe handles - Move querying username/password from management to a function - When auth-user-pass file has no password query the management interface (if available). - Persist management-query-remote and proxy prompts - -Simon Matter (2): - Fix segfault when using crypto lib without AES-256-CTR or SHA256 - Add per session pseudo-random jitter to --reneg-sec intervals - -Simon Rozman (67): - Local functions are not supported in MSVC. Bummer. - Mixing wide and regular strings in concatenations is not allowed in MSVC. - RtlIpv6AddressToStringW() and RtlIpv4AddressToStringW() require mstcpip.h - Simplify iphlpapi.dll API calls - Fix local #include to use quoted form - Document ">PASSWORD:Auth-Token" real-time message - Fix typo in "verb" command examples - Uniform swprintf() across MinGW and MSVC compilers - MSVC meta files added to .gitignore list - openvpnserv: Review MSVC down-casting warnings - openvpnserv: Add support for multi-instances - Document missing OpenVPN states - Add Interactive Service developer documentation - Change quoted to angled form when #including external .h files - Signed/unsigned warnings of MSVC resolved - Reference msvc-generate from compat to assure correct build order - msvc: Move common project settings to reusable property sheets - msvc: Unify Unicode/MultiByte string setting across all cfg|plat - Introduce tapctl.exe utility and openvpnmsica.dll MSI CA - Set output name to libopenvpnmsica.dll in MSVC builds too - Prevent __stdcall name mangling of MSVC - Define _WIN32_WINNT=_WIN32_WINNT_VISTA in MSVC - Add MSI custom action for reliable Windows 10 detection - Detect TAP interfaces with root-enumerated hardware ID - Change C++ to C comments - Make MSI custom action debug pop-up more informative - Delete TAP interface before the TAP driver is uninstalled - Add detection of active VPN connections for MSI packages - Add a MSI custom actions to close and relaunch OpenVPN GUI - Make DriverCertification MSI property public - Extend FindSystemInfo custom action to detect OpenVPNService state - Uncrustify tapctl and openvpnmsica - Strip _stdcall suffixes (@nn) for 32-bit builds - Detect missing TAP driver and bail out gracefully - Disambiguate thread local storage references from TLS - Add NULL checks - Add user manual and developer notes URL for tapctl.exe - Refactor OpenVPNService state detection code - Add developer notes URL for openvpnmsica.dll - Limit tapctl.exe and openvpnmsica.dll to TAP-Windows6 adapters only - msvc: Add vlan.c/h - tun.c: make Windows device lookup functions more general - tun.c: upgrade get_device_guid() to return the Windows driver type - tun.c: make wintun_register_ring_buffer() non-fatal on failures - wintun: register ring buffers when iterating adapters - wintun: add support for --dev-node - tun.c: reword the at_least_one_tap_win() error - wintun: stop sending TAP-Windows6 ioctls to NDIS device - wintun: refactor code to use enum driver type - tun.c: refactor driver detection and make it case-insensitive - tun.c: uncrustify - wintun: check for conflicting options - openvpnmsica: Remove required Windows driver certification detection - openvpnmsica: Fix TAPInterface.DisplayName field interpretation - tapctl: Update documentation - wintun: upgrade error message in case of ring registration failure - tun.c: reorder IPv6 ifconfig on Windows - tapctl: Add functions for enabling/disabling adapters - openvpnmsica: Revise MSI custom actions interop - openvpnmsica: Simplify static function names - openvpnmsica, tapctl: "interface" => "adapter" - openvpnmsica: "TAP" => "TUN/TAP" - openvpnmsica: Extend to support arbitrary HWID network adapters - openvpnmsica, tapctl: Revise default hardware ID management - openvpnmsica: Merge FindTUNTAPAdapters into FindSystemInfo - tapctl: Support multiple hardware IDs - tun.c: revise the IPv4 ifconfig flow on Windows - -Stefan Strogin (1): - Use correct ifdefs for LibreSSL support - -Steffan Karger (122): - Document that RSA_SIGN can also request TLS 1.2 signatures - man: encourage user to read on about --tls-crypt - Textual fixes for Changes.rst - Remove deprecated --no-iv option - More broadly enforce Allman style and braces-around-conditionals - Use SHA256 for the internal digest, instead of MD5 - OpenSSL: 1.1 fallout - fix configure on old autoconf - Fix types in WIN32 socket_listen_accept() - Remove duplicate X509 env variables - Fix non-C99-compliant builds: don't use const size_t as array length - Deprecate --ns-cert-type - Be less picky about keyUsage extensions - cleanup: merge packet_id_alloc_outgoing() into packet_id_write() - Don't run packet_id unit tests for --disable-crypto builds - Fix Changes.rst layout - Fix memory leak in x509_verify_cert_ku() - mbedtls: correctly check return value in pkcs11_certificate_dn() - Restore pre-NCP frame parameters for new sessions - Always clear username/password from memory on error - Document tls-crypt security considerations in man page - Don't assert out on receiving too-large control packets (CVE-2017-7478) - Drop packets instead of assert out if packet id rolls over (CVE-2017-7479) - Log the negotiated (NCP) cipher - Avoid a 1 byte overcopy in x509_get_subject (ssl_verify_openssl.c) - Skip tls-crypt unit tests if required crypto mode not supported - openssl: fix overflow check for long --tls-cipher option - Add a DSA test key/cert pair to sample-keys - Fix mbedtls fingerprint calculation - mbedtls: fix --x509-track post-authentication remote DoS (CVE-2017-7522) - mbedtls: require C-string compatible types for --x509-username-field - Fix remote-triggerable memory leaks (CVE-2017-7521) - Restrict --x509-alt-username extension types - Fix potential double-free in --x509-alt-username (CVE-2017-7521) - Fix typo in extract_x509_extension() debug message - init_key_ctx: key and iv arguments can (now) be const - Move adjust_power_of_2() to integer.h - Undo cipher push in client options state if cipher is rejected - Remove strerror_ts() - Move openvpn_sleep() to manage.c - fixup: also change missed openvpn_sleep() occurrences - Always use default keysize for NCP'd ciphers - Move create_temp_file() out of #ifdef ENABLE_CRYPTO - sample-plugins: fix ASN1_STRING_to_UTF8 return value checks - Deprecate --keysize - Move run_up_down() to init.c - tls-crypt: introduce tls_crypt_kt() - crypto: create function to initialize encrypt and decrypt key - Add coverity static analysis to Travis CI config - tls-crypt: don't leak memory for incorrect tls-crypt messages - travis: reorder matrix to speed up build - Fix bounds check in read_key() - buffer_list_aggregate_separator(): add unit tests - doxygen: add make target and use relative paths - Simplify and inline clear_buf() - Add --tls-cert-profile option. - pf: clean up temporary files if plugin init fails - pf: reject client if PF plugin is configured, but init fails - Don't throw fatal errors from create_temp_file() - create_temp_file/gen_path: prevent memory leak if gc == NULL - Use P_DATA_V2 for server->client packets too - Fix memory leak in buffer unit tests - travis: use clang's -fsanitize=address to catch more bugs - Don't throw fatal errors from verify_cert_export_cert() - buffer_list_aggregate_separator(): update list size after aggregating - buffer_list_aggregate_separator(): don't exceed max_len - buffer_list_aggregate_separator(): prevent 0-byte malloc - Fix types around buffer_list_push(_data) - ssl_openssl: fix compiler warning by removing getbio() wrapper - Fix --tls-version-min and --tls-version-max for OpenSSL 1.1+ - Add support for TLS 1.3 in --tls-version-{min, max} - tls_ctx_set_tls_versions: move verify_flags to where it is used - Plug memory leak if push is interrupted - Log pre-handshake packet drops using D_MULTI_DROPPED - Enable stricter compiler warnings by default - reliable: remove reliable_unique_retry() - Get rid of ax_check_compile_flag.m4 - mbedtls: don't use API deprecated in mbed 2.7 - Warn if tls-version-max < tls-version-min - Check for more data in control channel - Move env helper functions into their own module/file - man: add security considerations to --compress section - openssl: don't use deprecated SSLEAY/SSLeay symbols - openssl: add missing #include statements - Move file-related functions from misc.c to platform.c - Move execve/run_script helper functions to run_command.c - Add crypto_pem_{encode,decode}() - Introduce buffer_write_file() - mbedtls: print warning if random personalisation fails - Fix memory leak after sighup - Remove unused void_ptr_hash_function and void_ptr_compare_function - Do not load certificate from tls_ctx_use_external_private_key() - mbedtls: make external signing code generic - mbedtls: remove dependency on mbedtls pkcs11 module - Fix memory leak in SSL_CTX_use_certificate - travis: add OpenSSL 1.1 Windows build - Fix use-after-free in tls_ctx_use_management_external_key - Simplify --genkey option syntax - Don't print OCC warnings about 'key-method', 'keydir' and 'tls-auth' - Add support for CHACHA20-POLY1305 in the data channel - List ChaCha20-Poly1305 as stream cipher - mbedtls: don't print unsupported ciphers in insecure cipher list - Fix mbedtls unit tests - buffer_list_aggregate_separator(): simplify code - tls-crypt-v2: add specification to doc/ - tls-crypt-v2: generate tls-crypt-v2 keys - tls-crypt-v2: add unwrap_client_key - tls-crypt-v2: add P_CONTROL_HARD_RESET_CLIENT_V3 opcode - tls-crypt-v2: implement tls-crypt-v2 handshake - tls-crypt-v2: add script hook to verify metadata - tls-crypt-v2: clarify --tls-crypt-v2-genkey man page section - tls-crypt-v2: fix client reconnect bug - Remove deprecated --compat-x509-names and --no-name-remapping - Extend tls-crypt-v2 unit tests - Fix tls-auth/crypt in connection blocks with --persist-key - cmocka: use relative paths - tests: remove dependency on base64 - configure.ac: add lzo CFLAGS/LIBS to the test flags - Update sample configs to use modern cipher, remove static key examples - mbedtls: add RFC 5705 keying material exporter support - Move keying material exporter check from syshead.h to configure.ac - Make openvpn --version exit with exit code 0 - Gently push users towards --data-ciphers in --show-ciphers output - -Steven McDonald (1): - Fix gateway detection with OpenBSD routing domains - -Szilárd Pfeiffer (1): - OpenSSL: Always set SSL_OP_CIPHER_SERVER_PREFERENCE flag - -Thomas Quinot (1): - Fix documentation of tls-verify script argument - -Thomas Veerman via Openvpn-devel (1): - Fix socks_proxy_port pointing to invalid data - -Tom van Leeuwen (1): - mbedTLS: Make sure TLS session survives move - -ValdikSS (1): - Set a low interface metric for tap adapter when block-outside-dns is in use - -Vladislav Grishenko (1): - Log serial number of revoked certificate - -WGH (1): - docs: Add reference to X509_LOOKUP_hash_dir(3) - -hashiz (1): - Fix '--bind ipv6only' - -tincanteksup (1): - Correct error message for --tls-crypt-v2-genkey client - - -2016.12.16 -- Version 2.4_rc2 -David Sommerseth (9): - Fix wrong configure.ac parsing of --enable-async-push - Changes: Further improve systemd unit file updates - systemd: Intermediate --chroot fix with the new sd_notify() implementation - Further enhance async-push feature description - Changes.rst: Mainatiner update on C99 - dev-tools: Add reformat-all.sh for code style unification - The Great Reformatting - first phase - Merge 'reformatting' branch into master - auth-gen-token: Hardening memory cleanup on auth-token failuers - -Gert Doering (1): - Refactor setting close-on-exec for socket FDs - -Lev Stipakov (2): - Arm inotify only in server mode - Add "async push" feature to Changes.rst - -Magnus Kroken (1): - mbedtls: include correct net/net_sockets header according to version - -Selva Nair (2): - Correctly state the default dhcp server address in man page - Unhide a line in man page by fixing a typo - -Steffan Karger (4): - Fix (and cleanup) crypto flags in combination with NCP - Deprecate --no-iv - man: mention that --ecdh-curve does not work on mbed TLS builds - Don't reopen tun if cipher changes - - -2016.12.01 -- Version 2.4_rc1 -Antonio Quartulli (1): - reload CRL only if file was modified - -Christian Hesse (3): - update year in copyright message - Use systemd service manager notification - Refuse to daemonize when running from systemd - -Gert Doering (1): - Fix windows path in Changes.rst - -Samuli Seppänen (1): - Mention that OpenVPN 2.4 requires Windows Vista or higher - -Selva Nair (4): - Map restart signals from event loop to SIGTERM during exit-notification wait - When parsing '--setenv opt xx ..' make sure a third parameter is present - Force 'def1' method when --redirect-gateway is done through service - Do not restart dns client service as a part of --register-dns processing - -Steffan Karger (4): - tls_process: don't set variable that's never read - Unconditionally enable TLS_AGGREGATE_ACK - Clean up format_hex_ex() - Introduce and use secure_memzero() to erase secrets - - -2016.11.24 -- Version 2.4_beta2 -Arne Schwabe (5): - Document that tls-crypt also supports inline - Fix warning that RAND_bytes is undeclared - Remove compat-stdbool.h. - Fix various compiler warnings - Handle DNS6 option on Android - -David Sommerseth (2): - Changes.rst: Fixing wrong formatting - Document the --auth-token option - -Gert Doering (2): - Remove remaining traces of compat-stdbool.h - Stub implementation of "--dhcp-option DNS6 " - -Selva Nair (3): - Do not set ipv6 address if '--ip-win32 manual' is used - Handle --dhcp-option DNS6 on Windows using netsh - Set IPv6 DNS servers using interactive service - -Steffan Karger (6): - multi_process_float: revert part of c14c4a9e - --tls-crypt fixes - Change cmocka remote to use https in stead of git protocol - generate_key_expansion: make assumption explicit, use C99 features - Poor man's NCP for non-NCP peers - Refactor data channel key generation API - - -2016.11.17 -- Version 2.4_beta1 -Arne Schwabe (1): - Make Changes.rst nicer for 2.4 release - -David Sommerseth (16): - Update .mailmap to unify and clean up odd names and e-mail addresses - cleanup: Remove NOP code sections in ssl.c:tls_process() - Remove last rest of INSTALL-win32.txt references - auth-gen-token: Add --auth-gen-token option - auth-gen-token: Generate an auth-token per client - auth-gen-token: Push generated auth-tokens to the client - auth-gen-token: Authenticate generated auth-tokens when client re-authenticates - Fix builds with --disable-crypto - man: Improve the --keepalive section - console: Fix compiler warning - systemd: Improve the systemd unit files - tun: Fix compiler warnings - file checks: Merge warn_if_group_others_accessible() into check_file_access() - tun: Fix weird commit error causing a double assignment - options: Remove --tls-remote - Remove unused variable in argv_printf_arglist() - -Gert Doering (10): - openvpn version line: remove [IPv6], add [AEAD] if available - clean up *sig_info handling in link_socket_init_phase2() - check c->c2.link_socket before calling do_init_route_ipv6_list() - Check previously-unchecked buf_alloc_write() call in crypto self-test. - Fix potential division by zero in shaper_reset() - Repair topology subnet on FreeBSD 11 - Repair topology subnet on OpenBSD - Add in_port_t check to configure.ac - Fix compilation on MinGW with -std=c99 - Replace WIN32 by _WIN32 - -Heiko Hund (4): - put argv_* functions into own file, add unit tests - Remove unused and unecessary argv interfaces - remove unused system_str from struct argv - Factor out %sc handling from argv_printf() - -Lev Stipakov (1): - Drop recursively routed packets - -Samuli Seppänen (6): - Remove INSTALL-win32.txt that is now hosted in openvpn-build - Fix update_t_client_ips.sh for out of tree builds - Make sure that all relevant files under test go to release tarballs - Allow passing extra arguments to fping/fping6 in t_client.rc - Prevent generation of duplicate EXPECT_IFCONFIG entries - Fix a logic problem in handling of --up scripts in t_client.sh - -Selva Nair (2): - Support --block-outside-dns on multiple tunnels - Unbreak windows build - -Steffan Karger (19): - Fix use-after-free bug in prepare_push_reply() - Remove verbose msg() from send_push_reply() - Limit --reneg-bytes to 64MB when using small block ciphers - Add a revoked cert to the sample keys - Fix --tls-version-max in mbed TLS builds - Don't deference type-punned pointers - Fix builds on compilers without anonymous union support - Refactor static/tls-auth key loading - Add missing includes in error.h - Make argv unit tests obey {MBEDTLS, OPENSSL}_{LIBS, CFLAGS} - Move private file access checks to options_postprocess_filechecks() - Deprecate key-method 1 - Refactor CRL handling - Remove unneeded check for extra_certs_file_inline - Fix missing return value checks in multi_process_float() - Restore pre-NCP cipher options on SIGUSR1 - Remove unused variables from do_init_crypto_static() - Add control channel encryption (--tls-crypt) - Add --tls-crypt unit tests - - -2016.10.19 -- Version 2.4_alpha2 - -David Sommerseth (1): - Update .mailmap to unify and clean up odd names and e-mail addresses - -Steffan Karger (1): - Fix use-after-free bug in prepare_push_reply() - - -2016.10.17 -- Version 2.4_alpha1 - -Adriaan de Jong (2): - Fixed a bug where PolarSSL gave an error when using an inline file tag. - Fix --show-pkcs11-ids (Bug #239) - -Alexander Pyhalov (1): - Default gateway can't be determined on illumos/Solaris platforms - -Alon Bar-Lev (1): - pkcs11: use generic evp key instead of rsa - -Andris Kalnozols (3): - Fix some typos in the man page. - Do not upcase x509-username-field for mixed-case arguments. - extract_x509_extension(): hide status message during normal operation. - -Arne Schwabe (100): - Document man agent-external-key - Options parsing demands unnecessary configuration if PKCS11 is used - Error message if max-routes used incorrectly - Properly require --key even if defined(MANAGMENT_EXTERNAL_KEY) - Remove dnsflags_to_socktype, it is not used anywhere - Fix the proto is used inconsistently warning - Remove dead code path and putenv functionality - Remove unused function xor - Move static prototype definition from header into c file - Remove unused function no_tap_ifconfig - Add the client id (CID) to the output of the status command - Print client id only if compiled with man agent support. Otherwise print an empty string. - Allow routes to be set before opening tun, similar to ifconfig before opening tun - Add ability to send/receive file descriptors via management interface - Android platform specific changes. - Emulate persist-tun on Android - Document the Android implementation in OpenVPN - Only print script warnings when a script is used. Remove stray mention of script-security system. - Fix #ifdefs for P2MP_SERVER - Move settings of user script into set_user_script function - Move checking of script file access into set_user_script - Fix another #ifdef/#if P2MP_SERVER - PATCHv3 Remove unused variables or put them to the defines they are being used in - Add support of utun devices under Mac OS X - Add support to ignore specific options. - Add a note what setenv opt does for OpenVPN < 2.3.3 - Implement custom HTTP header for http-proxy, and always send user-agent: - Add reporting of UI version to basic push-peer-info set. - Change the type of all ports in openvpn to const char* and let getaddrinfo resolve the port together with the hostname. - Fix compile error in ssl_openssl introduced by polar external-management patch - Simplify print_sockaddr_ex function, merge duplicate ipv4/ipv6 logic. - Split the PROTO_UDP_xx options into AF_INET/AF_INET6 and PROTO_TCP/PROTO_UDP part. - Fix two instances of asserting AF_INET - Fix assertion when SIGUSR1 is received while getaddrinfo is successful - Split link_socket_init_phase1 and link_socket_init_phase2 into smaller more managable/readable functions. No functional changes - Change proto_remote() function to return a constant string - Remove the ip-remote-hint option. - change the type of 'remote' to addrinfo*, and rename to 'remote_list'. - When resolving fails print the error message from socket layer - Implement dual stack client support for OpenVPN - Move ASSERT so external-key with OpenSSL works again - Implement listing on IPv4/IPv6 dual socket on all platform - Add warning for using connection block variables after connection blocks - Update IPv6 related readme files - Introduce safety check for http proxy options - Fix warning for max-routes: do not quit when parsing an old configuration. Format the message to be more like the other deprecated options - Fix connecting to localhost on Android - Move the initialization of the environment to the top so c2.es is initialized - Workaround broken Android 4.4 VpnService API for persist-tun mode - Implement an easy parsable log output that allows access to flags of the log message - Introduce an option to resolve dns names in advance for --remote, --local and --http-proxy - Fix for server selecting address family - Don't show the connection profile store in options->ce if there is a connection_list defined. - Add gateway and device to android control messages - Clean up of socket code. - Fix assert when using port-share - Work around Solaris getaddrinfo() returing ai_protocol=0 - Fix man page and OSCP script: tls_serial_{n} is decimal - Remove ENABLE_BUFFER_LIST - Fix server routes not working in topology subnet with --server [v3] - Always enable http-proxy and socks-proxy - Remove deprecated --max-routes option from manual - Add documentation for PERSIST_TUN_ACTION (Android specific) - Remove possibility of using --tls-auth with non OpenVPN Static key files - Remove unused function sock_addr_set - Document the default for tls-cipher. - Report missing end-tags of inline files as errors - Fix commit e473b7c if an inline file happens to have a line break exactly at buffer limit - Show extra-certs in current parameters, fix clang warning and logic error in preresolve - Remove unused function h_errno_msg - Add support for requesting the fd again to rebind to the next interface. - Don't redirect the gateway on Android even if requested - Fix loglevel of protect socket message - Extend network-change command to allow reprotecting on the same network (for short connection losses) - Use pseudo gw as default gw on Android as a workaround for not being able to read /proc/net/route - Remove #ifdefs for client nat support. - Do not install a host route for the VPN on Android - Fix commit c67acea173dc9ee37220f5b9ff14ede081181992 - Do not set the buffer size by default but rely on the operation system default. - Start Changes.rst that lists changes in 2.4.0 - Remove --enable-password-save option - Reflect enable-password-save change in documentation - Also remove second instance of enable-password-save in the man page - Detect config lines that are too long and give a warning/error - Implement the compression V2 data format for stub and lz4. - Fix assert when comp is called with unknown algorithm, always call comp init method - Ignore stamp-h2 we generate during build process - Implement inlining of crl files - Complete push-peer-info documentation and allow IV_PLAT_VER for other platforms than Windows if the client UI supplies it. - Remove http-proxy-timeout, socks timeout and set default of server-poll-timeout to 120s - Add documentation for http-proxy-user-pass option - Remove http-proxy-retry and socks-proxy-retry. - Update android documentation to match source code - Use AES ciphers in our sample configuration files and add a few modern 2.4 examples - Fix ENABLE_CRYPTO_OPENSSL set to YES even with --disable-crypto set - Prefer RECVDSTADDR to PKTINFO for IPv4 in OS X since it actually works (unlike PKTINFO) - Incorporate the Debian typo fixes where appropriate and make show_opt default message clearer - Enable TCP non-linear packet ID - Change the hold command to communicate the time that OpenVPN would wait to the UI. - Remove tun-ipv6 Option. Instead assume that IPv6 is always supported. - -Boris Lytochkin (1): - Log serial number of revoked certificate - -Christian Hesse (1): - fix build with automake 1.13(.1) - -Christian Niessner (1): - Fix corner case in NTLM authentication (trac #172) - -Christos Trochalakis (1): - Adjust server-ipv6 documentation - -Cristian Rodriguez (1): - Use SSL_MODE_RELEASE_BUFFERS if available - -Daniel Hahler (1): - options: fix option check for "plugin" - -Daniel Kubec (4): - Added support for TLS Keying Material Exporters [RFC-5705] - Added document for TLS Keying Material Exporters [RFC-5705] - sample-plugin: TLS Keying Material Exporter [RFC-5705] demonstration plug-in - Fix buffer size parameter for exported keying material. - -David Sommerseth (44): - Make git ignore some more files - Remove the support for using system() when executing external programs or scripts - Fix double-free issue in pf_destroy_context() - Reset the version.m4 version for the master branch - Avoid recursion in virtual_output_callback_func() - The get_default_gateway() function uses warn() instead of msg() - Improve the git revision tracking - man page: Update man page about the tls_digest_{n} environment variable - Remove the --disable-eurephia configure option - plugin: Extend the plug-in v3 API to identify the SSL implementation used - autoconf: Fix typo - t_client.sh: Check for fping/fping6 availability - t_client.sh: Write errors to stderr and document requirements - t_client.sh: Add prepare/cleanup possibilties for each test case - Fix file checks when --chroot is being used - Adjusted autotools files to build more cleanly on newer autoconf/automake versions - Improve error reporting on file access to --client-config-dir and --ccd-exclusive - Don't let openvpn_popen() keep zombies around - Don't try to use systemd-ask-password if it is not available - Clean up the pipe closing in openvpn_popen() - Add systemd unit file for OpenVPN - systemd: Use systemd functions to consider systemd availability - systemd: Reworked the systemd unit file to handle server and client configs better - autotools: Fix wrong ./configure help screen default values - down-root plugin: Replaced system() calls with execve() - down-root: Improve error messages - plugin, down-root: Fix compiler warnings - sockets: Remove the limitation of --tcp-nodelay to be server-only - plugins, down-root: Code style clean-up - Provide compile time OpenVPN version information to plug-ins - Provide OpenVPN runtime version information to plug-ins - Avoid partial authentication state when using --disabled in CCD configs - Only build and run cmocka unit tests if its submodule is initialized - Another fix related to unit test framework - Remove NOP function and callers - Revert "Drop recursively routed packets" - Fix client connection instant timeout - t_client.sh: Make OpenVPN write PID file to avoid various sudo issues - t_client.sh: Add support for Kerberos/ksu - t_client.sh: Improve detection if the OpenVPN process did start during tests - Rework the user input interface to make it more modular - Re-implement the systemd support using the new query user API - systemd: Do not mask usernames when querying for it via systemd-ask-password - Move memcmp_constant_time() to crypto.h - -David Woodhouse (2): - pkcs11: Load p11-kit-proxy.so module by default - Make 'provider' option to --show-pkcs11-ids optional where p11-kit is present - -Davide Brini (2): - Provide more accurate warning message - Document authfile for socks server - -Dmitrij Tejblum (1): - Fix is_ipv6 in case of tap interface. - -Dorian Harmans (1): - Add CHACHA20-POLY1305 ciphersuite IANA name translations. - -Felix Janda (1): - Use OPENVPN_ETH_P_* so that is unecessary - -Fish (1): - Add lz4 support to MSVC. - -Gert Doering (110): - Implement --mssfix handling for IPv6 packets. - Fix option inconsistency warnings about "proto" and "tun-ipv6" - Fix parameter type for IP_TOS setsockopt on non-Linux systems. - Fix client crash on double PUSH_REPLY. - Update README.IPv6 to match what is in 2.3.0 - Repair "tcp server queue overflow" brokenness, more fallout. - Permit pool size of /64.../112 for ifconfig-ipv6-pool - Add MIN() compatibility macro - Fix directly connected routes for "topology subnet" on Solaris. - Print "Virtual IPv6 Address" on management interface queries [v4] - Use constrain_int() instead of MIN()+syshead.c compat definition - v2. - Fix NULL-pointer crash in route_list_add_vpn_gateway(). - Fix usage of 'compression ...' from global config. - Make push-peer-info visible in "normal" per-instance environment. - Fix problem with UDP tunneling due to mishandled pktinfo structures. - Improve documentation and help text for --route-ipv6. - Fix argument type warning introduced by http extra proxy header patch. - Fix IPv6 examples in t_client.rc-sample - Fix slow memory drain on each client renegotiation. - t_client.sh: ignore fields from "ip -6 route show" output that distort results. - Fix IPv6_V6ONLY logic. - Implement LZ4 compression. - Provide LZ4 sources in src/compat/ and use if no system lz4 library found. - Document "lz4" argument to "compress" config option. - Make code and documentation for --remote-random-hostname consistent. - Reduce IV_OPENVPN_GUI_VERSION= to IV_GUI_VER= - remove some 'unused variable' warnings - Cleanup ir6->netbits handling. - Document issue with --chroot, /dev/urandom and PolarSSL. - Rename 'struct route' to 'struct route_ipv4' - Replace copied structure elements with including - Add "test-driver" and "compile" to .gitignore - Fix crash when using --inetd. - IPv6 address/route delete fix for Win8 - Add SSL library version reporting. - Minor t_client.sh cleanups - Repair --multihome on FreeBSD for IPv4 sockets. - Rewrite manpage section about --multihome - More IPv6-related updates to the openvpn man page. - Conditionalize calls to print_default_gateway on !ENABLE_SMALL - Merge get_default_gateway() implementation for all 4+1 BSD variants. - Drop incoming fe80:: packets silently now. - Recognize AIX, define TARGET_AIX - Add tap driver initialization and ifconfig for AIX. - implement adding/deleting routes on AIX, for IPv4 and IPv6 - Make t_client.sh work on AIX. - Fix t_lpback.sh platform-dependent failures - Call init script helpers with explicit path (./) - Fix windows build on older mingw versions. - New approach to handle peer-id related changes to link-mtu. - Print remote IPv4 address on a dual-stack v6 socket in IPv4 format - Fix incorrect use of get_ipv6_addr() for iroute options. - Remove count_netmask_bits(), convert users to use netmask_to_netbits2() - Fix leftover 'if (false) ;' statements - Print helpful error message on --mktun/--rmtun if not available. - explain effect of --topology subnet on --ifconfig - Add note about file permissions and --crl-verify to manpage. - repair --dev null breakage caused by db950be85d37 - assume res_init() is always there. - Correct note about DNS randomization in openvpn.8 - Disallow usage of --server-poll-timeout in --secret key mode. - slightly enhance documentation about --cipher - Enforce "serial-tests" behaviour for tests/Makefile - Revert "Enforce "serial-tests" behaviour for tests/Makefile" - On signal reception, return EAI_SYSTEM from openvpn_getaddrinfo(). - Use configure.ac hack to apply serial_test AM option only if supported. - Use EAI_AGAIN instead of EAI_SYSTEM for openvpn_getaddrinfo(). - Move res_init() call to inner openvpn_getaddrinfo() loop - Fix FreeBSD ifconfig for topology subnet tunnels. - Produce a meaningful error message if --daemon gets in the way of asking for passwords. - Document --daemon changes and consequences (--askpass, --auth-nocache). - Fix build on OpenSolaris (non-gmake) - Un-break --auth-user-pass on windows - refactor struct route_ipv6, bring in line with struct route_ipv4 again - refactor struct route_ipv6_list, bring in line with struct route_list again - Add route_ipv6_gateway* data structures for rgi6 support. - Create basic infrastructure for IPv6 default gateway handling / redirection. - Make client delay less before sending PUSH_REQUEST - get_default_gateway_ipv6(): Linux / Netlink implementation. - Implement handling of overlapping IPv6 routes with IPv6 remote VPN server address - Implement '--redirect-gateway ipv6' - get_default_gateway_ipv6(): *BSD / MacOS / Solaris PF_ROUTE implementation - Fix IPv6 host routes to LAN gateway on OpenSolaris - Replace unaligned 16bit access to TCP MSS value with bytewise access - Repair test_local_addr() on WIN32 - Add custom check for inet_pton()/inet_ntop() on MinGW/WIN32 - get_default_gateway_ipv6(): Win32 implementation using GetBestRoute2() - Remove support for snappy compression. - Fix info.af == AF_UNSPEC case for server with --mtu-disc - Fix FreeBSD-specific mishandling of gc arena pointer in create_arbitrary_remote() - remove unused gc_arena in FreeBSD close_tun() - Un-break compilation on *BSD - Fix isatty() check for good. - Fix openserv/validate.o linking issues on mingw. - Fix library order in -lmbedtls test. - Implement push-remove option to selectively remove pushed options. - Upgrade bundled compat-lz4 to upstream release r131. - Change --enable-pedantic to use -std=c99 and not -ansi (C90). - Fix problems with NCP and --inetd. - Do not abort t_client run if OpenVPN instance does not start. - Fix IP_PKTINFO related compilation failure on NetBSD 7.0 - Show compile-time variant for --multihome in --version output. - Fix win32 building with C99 mode - Fix t_client runs on OpenSolaris - make t_client robust against sudoers misconfiguration - add POSTINIT_CMD_suf to t_client.sh and sample config - Fix --multihome for IPv6 on 64bit BSD systems. - Enable -D_SVR4_2 for compilation on Solaris - Revert "Enable -D_SVR4_2 for compilation on Solaris" - Enable -D_XPG4_2 for compilation on Solaris - -Guy Yur (1): - Fix --redirect-private in --dev tap mode. - -Heikki Hannikainen (1): - Always load intermediate certificates from a PKCS#12 file - -Heiko Hund (20): - Fix display of plugin hook types - Support UTF-8 --client-config-dir - close more file descriptors on exec - Ignore UTF-8 byte order mark - reintroduce --no-name-remapping option - make --tls-remote compatible with pre 2.3 configs - add new option for X.509 name verification - Support non-ASCII TAP adapter names on Windows - Support non-ASCII characters in Windows tmp path - make sure sa_family_t is defined - convert struct signal_info element - grow route lists dynamically - fix route struct name - refine assertion to allow other modes than CBC - Fix compilation on Windows - fix warnings on Windows - extend management interface command "state" - put virtual IPv6 addresses into env - interactive service v3 - Windows: do_ifconfig() after open_tun() - -Holger Kummert (1): - Del ipv6 addr on close of linux tun interface - -Hubert Kario (2): - ocsp_check - signature verification and cert staus results are separate - ocsp_check - double check if ocsp didn't report any errors in execution - -Ilya Shipitsin (3): - initial travis-ci support - skip t_lpback.sh and t_cltsrv.sh if openvpn configured --disable-crypto - enable "--disable-crypto" build configuration for travis - -Ivo Manca (1): - Plug memory leak in mbedTLS backend - -James Bekkema (1): - Fix socket-flag/TCP_NODELAY on Mac OS X - -James Geboski (1): - Fix --askpass not allowing for password input via stdin - -James Yonan (14): - Added support for the Snappy compression algorithm - Always push basic set of peer info values to server. - TLS version negotiation - Added "setenv opt" directive prefix. If present, and if the directive that follows is recognized, it will be processed as if the "setenv opt" prefix was absent. If present and if the directive that follows is not recognized, the directive will be ignored rather than cause a fatal error. - MSVC fixes - Set SSL_OP_NO_TICKET flag in SSL context for OpenSSL builds, to disable TLS stateless session resumption. - Use native strtoull() with MSVC 2013. - Define PATH_SEPARATOR for MSVC builds. - Fixed some compile issues with show_library_versions() - Added flags parameter to format_hex_ex. - Extended x509-track for OpenSSL to report SHA1 fingerprint. - Fixed port-share bug with DoS potential - Added directive to specify HTTP proxy credentials in config. - Bind to local socket before dropping privileges - -Jan Just Keijser (5): - man page patch for missing options - make 'explicit-exit-notify' pullable again - include ifconfig_ environment variables in --up-restart env set - Author: Jan Just Keijser - Make certificate expiry warning patch (091edd8e299686) work on OpenSSL 1.0.1 and earlier. - -Jann Horn (1): - Remove quadratic complexity from openvpn_base64_decode() - -Jeffrey Cutter (1): - Update contrib/pull-resolv-conf/client.up for no DOMAIN - -Jens Neuhalfen (6): - Make intent of utun device name validation clear - Fix buffer overflow by user supplied data - ignore the local config file t_client.rc in git - Prevent integration test timeout bc. of sudo - Add unit testing support via cmocka - Add a test for auth-pam searchandreplace - -Jens Wagner (1): - Fix spurious ignoring of pushed config options (trac#349). - -Jesse Glick (1): - Allow use of NetBeans without saving nbproject/ directory. - -Joachim Schipper (5): - doc/management-notes.txt: fix typo - Fix typo in ./configure message - Refactor tls_ctx_use_external_private_key() - --management-external-key for PolarSSL - external_pkcs1_sign: Support non-RSA_SIG_RAW hash_ids - -Jonathan K. Bullard (3): - Fix mismatch of fprintf format specifier and argument type - Fix null pointer dereference in options.c - Fail if options have extra parameters [v2] - -Josh Cepek (7): - Fix parameter listing in non-debug builds at verb 4 - (updated) [PATCH] Warn when using verb levels >=7 without debug - Fix proto tcp6 for server & non-P2MP modes - Fix Windows script execution when called from script hooks - Correct error text when no Windows TAP device is present - Require a 1.2.x PolarSSL version - Push an IPv6 CIDR mask used by the server, not the pool's size - -Julien Muchembled (1): - Fix --mtu-disc option with IPv6 transport - -Kenneth Rose (1): - Fix v3 plugins to support returning values back to OpenVPN. - -Klee Dienes (1): - tls_ctx_load_ca: Improve certificate error messages - -Leon Klingele (1): - Add link to bug tracker - -Leonardo Basilio (1): - Correctly report TCP connection timeout on windows. - -Lev Stipakov (26): - Peer-id patch v7 - Add the peer-id to the output of the status command - Prevent memory drain for long lasting floating sessions - Disallow lameduck's float to an address taken by another client - Fix NULL dereferencing - Fix mssfix default value in connection_list context - This fixes MSVS 2013 compilation. - Continuation of MSVS fixes - Fast recovery when host is in unreachable network - Fix compilation error with --disable-crypto - Send push reply right after async auth complete - Fix compilation with --disable-server - Refine float logging - Generate openvpn-plugin.h for MSVC build - Replace variable length array with malloc - Use adapter index instead of name for windows IPv6 interface config - Notify clients about server's exit/restart - Use adapter index for add/delete_route_ipv6 - Pass adapter index to up/down scripts - Detecting and logging Windows versions - Report Windows bitness - Fix "implicit declaration" compiler warning - Drop recursively routed packets - Support for disabled peer-id - Exclude peer-id from pulled options digest - Use separate list for per-client push options - -Lukasz Kutyla (1): - Fix privilege drop if first connection attempt fails - -Matthias Andree (1): - Enable TCP_NODELAY configuration on FreeBSD. - -Max Muster (1): - Remove duplicate cipher entries from TLS translation table. - -Michael McConville (1): - Fix undefined signed shift overflow - -Michal Ludvig (1): - Support for username-only auth file. - -Mike Gilbert (2): - Add configure check for the path to systemd-ask-password - Include systemd units in the source tarball (make dist) - -Niels Ole Salscheider (1): - Fix build with libressl - -Peter Sagerson (1): - Fix configure interaction with static OpenSSL libraries - -Philipp Hagemeister (2): - Add topology in sample server configuration file - Implement on-link route adding for iproute2 - -Phillip Smith (1): - Use bob.example.com and alice.example.com to improve clarity of documentation - -Robert Fischer (1): - Updated manpage for --rport and --lport - -Samuel Thibault (1): - Ensure that client-connect files are always deleted - -Samuli Seppänen (15): - Removed ChangeLog.IPv6 - Added cross-compilation information INSTALL-win32.txt - Updated README - Cleaned up and updated INSTALL - Fix to --shaper documentation on the man-page - Properly escape dashes on the man-page - Improve documentation in --script-security section of the man-page - Add CONTRIBUTING.rst - Update CONTRIBUTING.rst to allow GitHub PRs for code review purposes - Clarify the fact that build instructions in README are for release tarballs - Mention tap-windows6 in INSTALL file - Use an up-to-date easy-rsa URL on the man-page - Clarify which Windows versions require which TUN/TAP driver - Deprecate the automatic part of openvpnserv.exe in favor of openvpnserv2.exe - Automatically cache expected IPs for t_client.sh on the first run - -Selva Nair (26): - Fix termination when windows suspends/sleeps - Do not hard-code windows systemroot in env_block - Handle ctrl-C and ctrl-break events on Windows - Unbreak read username password from management - Restrict options/configs for startup through interactive service - Send stdout and stderr of OpenVPN started by interactive service to NUL - Handle localized Administrators group name in windows - Fix interactive service ignoring stop command if openvpn is running - Use appropriate buffer size for WideCharToMultiByte output in interactive.c - Refactor and move the block-outside-dns code to a new file (block_dns.[ch]) - Add support for block-outside-dns through the interactive service - Ensure input read using systemd-ask-password is null terminated - Support reading the challenge-response from console - Make error non-fatal while deleting address using netsh - Add support for register-dns through interactive service - Fix handling of out of memory error in interactive service - Fix the comparison of pull options hash on restart - Set WFP engine handle to NULL in win_wfp_uninit() - Make block-outside-dns work with persist-tun - Add an option to filter options received from server - Ignore SIGUSR1/SIGHUP during exit notification - Fix management-external-cert option parsing error - Return process id of openvpn from interactive service to client - Exponentially back off on repeated connect retries - Promptly close the netcmd_semaphore handle after use - Avoid format specifier %zu for Windows compatibility - -Steffan Karger (180): - PolarSSL-1.2 support - Improve PolarSSL key_state_read_{cipher, plain}text messages - Improve verify_callback messages - Config compatibility patch. Added translate_cipher_name. - Switch to IANA names for TLS ciphers. - Fixed autoconf script to properly detect missing pkcs11 with polarssl. - Use constant time memcmp when comparing HMACs in openvpn_decrypt. - Fixed tls-cipher translation bug in openssl-build - Fixed usage of stale define USE_SSL to ENABLE_SSL - Do not pass struct tls_session* as void* in key_state_ssl_init(). - Require polarssl >= 1.2.10 for polarssl-builds, which fixes CVE-2013-5915. - Also update TLSv1_method() calls in support code to SSLv23_method() calls. - Update TLSv1 error messages to SSLv23 to reflect changes from commit 4b67f98 - If --tls-cipher is supplied, make --show-tls parse the list. - Remove OpenSSL tmp_rsa_callback. Removes support for ephemeral RSA in TLS. - Make tls_ctx_restrict_ciphers accept NULL as char *cipher_list. - Disable export ciphers by default for OpenSSL builds. - Fix compiler warning for unused result of write() - Remove unused variables from ssl_verify_polarssl.c's x509_get_serial() - Fix compiler warnings in ssl_polarssl.c - Bump minimum OpenSSL version to 0.9.8 - Add openssl-specific common cipher list names to ssl.c. - Disable unsupported TLS cipher modes by default, cleans --show-tls output. - configure.ac: check for SSL_OP_NO_TICKET flag in OpenSSL - configure.ac: use CPPFLAGS for SSL_OP_NO_TICKET check - Upgrade to PolarSSL 1.3 - Improve error reporting during key/cert loading with PolarSSL. - Update openvpn-plugin.h for PolarSSL 1.3. - Add support for elliptic curve diffie-hellmann key exchange (ECDH) - Add an elliptic curve testing cert chain to the sample keys - Change signedness of hash in x509_get_sha1_hash(), fixes compiler warning. - Fix OCSP_check.sh to also use decimal for stdout verification. - Make serial env exporting consistent amongst OpenSSL and PolarSSL builds. - Fix build system to accept non-system crypto library locations for plugins. - Remove function without effect (cipher_ok() always returned true). - Remove unneeded wrapper functions in crypto_openssl.c - Remove unneeded defines (were needed for pre-0.9.7 OpenSSL). - Fix merge error in a6c573d, the ssl ctx is now abstracted. - Use generic openvpn_x509_cert_t in ssl_verify_polarssl.c - Fix ssl.c, ssl_verify_* includes - Move #include "ssl_verify.h" from ssl.h to the source files that need it. - Remove dependency on manage.h from ssl_verify.h - Remove unused variable 'proxy' from socket_restart_pause() - Add (default disabled) --enable-werror option to configure - Fix --disable-ssl builds, were broken by cleanup in 63dc03d. - configure.ac: fix SSL_OP_NO_TICKET check - Fix bug that incorrectly refuses oid representation eku's in polar builds - Update README.polarssl - cleanup: remove #if 0'ed function initiate_untrusted_session() from ssl.c. - Rename ALLOW_NON_CBC_CIPHERS to ENABLE_OFB_CFB_MODE, and add to configure. - Add proper check for crypto modes (CBC or OFB/CFB) - Improve --show-ciphers to show if a cipher can be used in static key mode - Extend t_lpback tests to test all ciphers reported by --show-ciphers - Don't issue warning for 'translate to self' tls-ciphers - Don't exit daemon if opening or parsing the CRL fails. - Define dummy SSL_OP_NO_TICKET flag if not present in OpenSSL. - Fix typo in cipher_kt_mode_{cbc, ofb_cfb}() doxygen. - Fix some unintialized variable warnings - Fix clang warning in options.c - Fix compiler warnings in ssl_polarssl.c. - Fix regression with password protected private keys (polarssl) - Remove unused variables from ssl_verify_openssl.c extract_x509_extension() - Fix assertion error when using --cipher none - Add --tls-version-max - Modernize sample keys and sample configs - Drop too-short control channel packets instead of asserting out. - Really fix '--cipher none' regression - Update doxygen (a bit) - Set tls-version-max to 1.1 if cryptoapicert is used - openssl: add crypto_msg(), to easily log openssl errors - openssl: add more descriptive message for 'no shared cipher' error - Remove ENABLE_SSL define (and --disable-ssl configure option) - openssl: use crypto_msg(), get rid of openssl-specific code in error.c - Add option to disable Diffie Hellman key exchange by setting '--dh none' - Account for peer-id in frame size calculation - Disable SSL compression - Use tls-auth in sample config files - Fix frame size calculation for non-CBC modes. - Get rid of old OpenSSL workarounds. - polarssl: make sure to always null-terminate the cn - Allow for CN/username of 64 characters (fixes off-by-one) - Change float log message to include common name, if available. - Remove unneeded parameter 'first_time' from possibly_become_daemon() - Remove size limit for files inlined in config - polarssl: remove code duplication in key_state_write_plaintext{, _const}() - Improve --tls-cipher and --show-tls man page description - polarssl: disable 1/n-1 record splitting - cleanup: remove md5 helper functions - Re-read auth-user-pass file on (re)connect if required - Clarify --capath option in manpage - Call daemon() before initializing crypto library - write pid file immediately after daemonizing - Increase control channel packet size for faster handshakes - Make __func__ work with Visual Studio too - fix regression: query password before becoming daemon - Fix using management interface to get passwords. - reintroduce md5_digest wrapper struct to fix gcc warnings - Fix out-of-tree builds; openvpn-plugin.h should be in AC_CONFIG_HEADERS - Fix overflow check in openvpn_decrypt() - Replace strdup() calls for string_alloc() calls - Check return value of ms_error_text() - polarssl: add easy logging for PolarSSL errors - polarssl: Improve PolarSSL logging - openssl: be less verbose about cipher translation errors - hardening: add insurance to exit on a failed ASSERT() - Fix memory leak in auth-pam plugin - openssl: remove usage of OPENSSL_malloc() from show_available_curves - polarssl: fix --client-cert-not-required - polarssl: add --verify-client-cert optional support - Fix (potential) memory leak in init_route_list() - Add macro to ensure we exit on fatal errors - polarssl: also allocate PKCS#11 certificate object on demand - polarssl: don't use deprecated functions anymore - polarssl: require >= 1.3.8 - Fix memory leak in add_option() by simplifying get_ipv6_addr - remove nonsense const specifier in nonfatal() return value - openssl: properly check return value of RAND_bytes() - Fix rand_bytes return value checking - Fix openssl builds with custom-built library: specify most-dependent first - Support duplicate x509 field values in environment - Warn user if their certificate has expired - Disable certificate notBefore/notAfter sanity check on OpenSSL < 1.0.2 - Make assert_failed() print the failed condition - cleanup: get rid of httpdigest.c type warnings - Fix regression in setups without a client certificate - polarssl: actually use polarssl debug logging - polarssl: optimize polar_ok() for non-errors - Update manpage: OpenSSL might also need /dev/urandom inside chroot - polarssl: use wrappers to access md_info_t member functions - polarssl: remove now redundant 128-bit blowfish key override - socks.c: fix check on get_user_pass() return value(s) - configure.ac: simplify crypto library configuration - configure.ac: fix polarssl autodetection - Allow NULL argument in cipher_ctx_get_cipher_kt() - Remove reuse of key_type during init of data channel auth and tls-auth - Move crypto_options into key_state and stop using context in SSL-mode. - Move key_ctx_bi into crypto_options - Move packet_id into crypto_options - Change openvpn_encrypt() to append to work buffer only - Create separate function for replay check - Add AEAD cipher support (GCM) - Add cipher name translation for OpenSSL. - Add preliminary server-side support for negotiable crypto parameters - Minor AEAD patch cleanup - Clean up get_tls_handhake_key() - Fix OCSP_check.sh - Make AEAD modes work with OpenSSL 1.0.1-1.0.1c - hardening: add safe FD_SET() wrapper openvpn_fd_set() - Only include aead encrypt/decrypt functions if AEAD modes are supported - Fix potential null-pointer dereference - Fix memory leak in argv_extract_cmd_name() - Replace MSG_TEST() macro for static inline msg_test() - fixup: change init_key_type() param name in declaration too - Further restrict default cipher list - PolarSSL x509_get_sha1_hash now returns correct SHA1 fingerprint. - Implemented x509-track for PolarSSL. - Migrate to mbed TLS 2.x - Rename files with 'polarssl' in the name to 'mbedtls' - configure.ac: link to all mbed TLS libs during library detection - mbedtls: check that private key and certificate match on start - mbedtls: improve error reporting in tls verify callback - Remove trailing newline from verify callback error messages - Don't limit max incoming message size based on c2->frame - cleanup: remove alloc_buffers argument from multi_top_init() - mbedtls: don't set debug threshold if compiled without MBEDTLS_DEBUG_C - Add client-side support for cipher negotiation - Add options to restrict cipher negotiation - Add server-side support for cipher negotiation - Allow ncp-disable and ncp-ciphers to be specified in ccd files - Fix '--cipher none --cipher' crash - Discourage using 64-bit block ciphers - Fix unittests for out-of-source builds - Fix --mssfix when using NCP - Drop gnu89/c89 support, switch to c99 - cleanup: remove code duplication in msg_test() - Add SHA256 fingerprint support - Make sure options->ciphername and options->authname are always defined - Update cipher-related man page text - Fix duplicate PUSH_REPLY options - Check --ncp-ciphers list on startup - -TDivine (1): - Fix "code=995" bug with windows NDIS6 tap driver. - -Tamas TEVESZ (1): - Add support for client-cert-not-required for PolarSSL. - -Thomas Veerman (2): - Fix "." in description of utun. - Update expiry date in management event loop - -ValdikSS (4): - Add Windows DNS Leak fix using WFP ('block-outside-dns') - Clarify mssfix documentation - Clarify --block-outside-dns documentation - Update --block-outside-dns to work on Windows Vista - -Vasily Kulikov (1): - Mac OS X Keychain management client - -Yawning Angel (1): - Fix SOCKSv5 method selection - -Yegor Yefremov (3): - socket: remove duplicate expression - polarssl: fix unreachable code - cert_data: fix memory leak - -janjust (1): - Fix "White space before end tags can break the config parser" - -kangsterizer (1): - Fix typo in sample build script to use LDFLAGS - -svimik (1): - Fix segfault when enabling pf plug-ins - - -2012.09.12 -- Version 2.3_beta1 -Arne Schwabe (7): - Fixes error: --key fails with EXTERNAL_PRIVATE_KEY: No such file or directory if --management-external-key is used - Merge almost identical create_socket_tcp and create_socket_tcp6 - Document the inlining of files in openvpn and document key-direction - Merge getaddr_multi and getaddr6 into one function - Document --management-client and --management-signal a bit better - Document that keep alive will double the second value in server mode and give a short explanation why the value is chosen. - Add checks for external-key-managements - -David Sommerseth (1): - Fix reconnect issues when --push and UDP is used on the server - -Gert Doering (4): - Reduce --version string detail about IPv6 to just "[IPv6]". - Put actual OpenVPN command line on top of corresponding log file. - Keep pre-existing tun/tap devices around on *BSD - make "ipv6 ifconfig" on linux compatible with busybox ifconfig - -Heiko Hund (6): - fix regression with --http-proxy[-*] options - add x_msg_va() log function - add API for plug-ins to write to openvpn log - remove stale _openssl_get_subject() prototype - remove unused flag SSLF_NO_NAME_REMAPPING - Add --compat-names option - -2012.07.20 -- Version 2.3_alpha3 -Arne Schwabe (1): - Fix compiling with --disable-management - -Gert Doering (1): - Repair "tap server" mode brokenness caused by fallout - -Heiko Hund (4): - make non-blocking connect work on Windows - don't treat socket related errors special anymore - remove unused show_connection_list debug function - add option --management-query-proxy - -2012.06.29 -- Version 2.3_alpha2 -Adriaan de Jong (11): - Fixed off-by-one in serial length calculation - Migrated x509_get_subject to use of the garbage collector - Migrated x509_get_serial to use the garbage collector - Migrated x509_get_sha1_hash to use the garbage collector - Ensure sys/un.h autoconf detection includes sys/socket.h - Added support for new PolarSSL 1.1 RNG - Added a configuration option to enable prediction resistance in the PolarSSL random number generator. - Use POLARSSL_CFLAGS instead of POLARSSL_CRYPTO_CFLAGS in configure.ac - Removed support for PolarSSL < 1.1 - Updated README.polarssl with build system changes. - Removed stray "Fox-IT hardening" string. - -Alon Bar-Lev (94): - build: version should not contain '-' - package: rpm: strip should be handled by package management - cleanup: options.c: remove redundant include - cleanup: remove C++ warnings - cleanup: win32.c: wrong printf format - cleanup: remove redundant ';' - cleanup: crypto_openssl.c: remove support for pre-openssl-0.9.6 - cleanup: tun.c: fix incorrect option in message (ip-win32) - cleanup: memcmp.c: remove unused source - fixup: init.c: add missing conditional for ENABLE_CLIENT_CR - build: correct place to alter WINVER is at build system - Update .gitignore - build: handle printf style format in mingw - build: rename plugin directory to plugins - build: plugins: properly use CC, CFLAGS and LDFLAGS - build: we need the sample.ovpn in future - Remove install-win32 - Remove easy-rsa - Remove tap-win32 - cleanup: rename tap-windows function from win32 to win - build: remove windows specific build system - build: split acinclude.m4 into m4/* - build: m4/ax_varargs.m4: cleanup - build: m4/ax_emptyarray.m4: cleanup - build: m4/ax_socklen_t.m4: cleanup - build: autotools: first pass of trivial autotools changes - build: autoconf: remove OPENVPN_ADD_LIBS useless macro - build: remove awk and non-standard autoconf output processing - build: standard directory layout - build: add libtool + windows resources for executables - build: autoconf: commands as environment - build: libdl usage - build: properly detect and use socket libs - build: autoconf: minor cleanups - build: proper selinux detection and usage - build: distribute pkg.m4 - build: proper pkcs11-helper detection and usage - build: properly process lzo-stub - build: proper lzo detection and usage - build: proper crypto detection and usage - build: autoconf: update defaults for options - build: win-msvc: msbuild format - build: move out config.h include from syshead - build: split out compat - build: move gettimeofday() emulation to compat - build: move daemon() emulation into compat - build: move inet_ntop(), inet_pton() emulation into compat - cleanup: move console related function into its own module - build: move wrappers into platform module - build: windows: install version.sh to allow installer read version - build: distribute samples in windows - build: use tap-windows.h as external dependency - build: ax_varargs.m4: fixups - build: autoconf: misc sockets fixups - build: enable lzo by default - build: windows: set vendor to openvpn project + cleanups - build: assume dlfcn is available on all supported platforms - build: openbsd: detect netinet/ip.h correctly - build: tap: search for tap header - build: msvc: upgrade to Visual Studio 2010 + fixups - Enable pedantic in windows compilation - cleanup: flags should not be bool - cleanup: avoid using ~0 - generic - cleanup: avoid using ~0 - ipv6 - cleanup: avoid using ~0 - netmask - cleanup: avoid using ~0 - windows - cleanup: gc usage - build: fix some statement left from conversion - build: properly detect netinet/ip.h structs - build: properly detect TUNSETPERSIST - cleanup: plugin: support C++ plugin - cleanup: remove C++ comments - cleanup: add .gitattributes to control eol style explicitly - crash: packet_id_debug_print: sl may be null - build: use stdbool.h if available - build: fix typo in --enable-save-password - build: windows: convert resources to UTF-8 - build: check minimum polarssl version - cleanup: update .gitignore - cleanup: spec: make space/tab consistent - build: spec: we support openssl >= 0.9.7 - build: insall README* document using build system - build: detect sys/wait.h required for *bsd - build: add git revision to --version output if build from git repository - build: cleanup: yet another forgotten brackets - build: update INSTALL to recent changes - build: support platforms that does not need explicit tun headers - build: do not support authenticated in verify_user_pass - Moved gc_new and gc_free to begin end of function - Fixed a bug in the return value of ssl_verify when pre_verify failed - Unified verification function return values: - Removed a stray Fox-IT tag - Fixed a typo: print the subject instead of the serial for verification errors - Made SSL_CIPHER const in print_details, to fix warning - Moved to PolarSSL 1.0.0: - Added missing #ifdef to allow --disable-managent to work again - Fixed disabling crypto and SSL - Got rid of a few magic numbers in ntlm.c - Removed obsolete des_cblock and des_keyschedule - Further removal of des_old.h based calls - Fixed missing comma in plugin.h - Moved prng_uninit out of crypto_uninit_lib - Moved CryptoAPI header include to the ssl_openssl.c - Reordered functions to ensure warning-free Windows build - Added options to switch between OpenSSL and PolarSSL and PKCS11... - Moved from strsep to strtok, for Windows compatibility - Minor cleanup to enable warning-free Windows build: - Fixed a typo when initialising cryptoapi certs - Minor code cleanup: cleaned up error handling in verify_cert. - Moved out of memory prototype to error.h, as the definition is in error.c - Removed support for calling gc_malloc with a NULL gc_arena struct - - (The follwing patches from Adriaan was mistakenly merged with - the wrong commit author in the git tree) - Doxygen: Added data channel crypto docs - Added control channel crypto docs - Added compression docs - Added reliability layer documentation - Added memory management documentation - Added data channel fragmentation docs - Added main/control docs - Moved doxygen-specific files to a separate directory - -Byron Ellacott (1): - autoconf fixes for building on OSX - -David Sommerseth (50): - Provide 'dev_type' environment variable to plug-ins and script hooks - Define the new openvpn_plugin_{open,func}_v3() API - Implement the core v3 plug-in function calls. - Extend the v3 plug-in API to send over X509 certificates - Added a simple plug-in demonstrating the v3 plug-in API. - Separate the general plug-in version constant and v3 plug-in structs version - Use a version-less version identifier on the master branch - Fix the --client-cert-not-required feature - Change the default --tmp-dir path to a more suitable path - Improve the mysprintf() issue in openvpnserv.c - Add a simple comment regarding openvpn_snprintf() is duplicated - Merge branch 'feat_ipv6_transport' - Merge branch 'feat_ipv6_payload' - Merge branch 'svn-branch-2.1' into merge - Solved hidden merge conflicts between master and svn-branch-2.1 - Fix const declarations in plug-in v3 structs - Merge remote-tracking branch 'cron2/feat_ipv6_payload_2.3' - Don't define ENABLE_PUSH_PEER_INFO if SSL is not available - Fix compiling issues with pkcs11 when --disable-management is configured - Remove support for Linux 2.2 configuration fallback - Revert "Add new openssl.cnf to easy-rsa/Windows" - Merge remote branch SVN 2.1 into the git tree - Merge branch 'svn-merger' - Fix Microsoft Visual Studio incompatibility in plugin.c - Fixed compile issues on FreeBSD and Solaris - Fix PolarSSL and --pkcs12 option issues - Fix FreeBSD/OpenBSD/NetBSD compiler warnings in get_default_gateway() - Make '--win-sys env' default - Do some file/directory tests before really starting openvpn - Fix bug after removing Linux 2.2 support - Don't look for 'stdin' file when using --auth-user-pass - Fix compiling with --disable-crypto and/or --disable-ssl - Fix a couple of issues in openvpn_execve() - Move away from openvpn_basename() over to platform provided basename() - Enable access() when building in Visual Studio - New Windows build fixes - Fix compilation errors on Linux platforms without SO_MARK - autotools ./configure don't like compat.h - Fix pool logging when IPv6 is not enabled - Don't check for file presence on inline files - Add --route-pre-down/OPENVPN_PLUGIN_ROUTE_PREDOWN script/plug-in hook - Enhance the error handling in _openssl_get_subject() - Fix assert() situations where gc_malloc() is called without a gc_arena object - Fix compile issues when plug-ins are disabled. - Remove --show-gateway if debug info is not enabled (--disable-debug) - Fix compile issues with status.c - Connection entry {tun,link}_mtu_defined not set correctly - Makefile.am referenced a now non-existing config-win32.h - Makefile.am was missing ssl_common.h - Revamp check_file_access() checks in stdin scenarios - -Davide Guerri (1): - New feauture: Add --stale-routes-check - -Frank de Brabander (1): - Fixed wrong return type of cipher_kt_mode - -Frederic Crozat (1): - Add support to forward console query to systemd - -Gert Doering (45): - Add more detailed explanation regarding the function of "--rdns-internal" - Enable IPv6 Payload in OpenVPN p2mp tun server mode. 20100104-1 release. - remove NOTES file from commit - private scribbling - NetBSD fixes - on 4.0 and up, use multi-af mode. - new feature: "ifconfig-ipv6-push" (from ccd/ config) - add some TODOs to TODO.IPv6 - undo accidential duplication of existing "--iroute" line in the help text - basic documentation of IPv6 related options and their syntax - Enable IPv6 Payload in OpenVPN p2mp tun server mode. - remove NOTES file from commit - private scribbling - env_block(): if PATH is not set, add standard PATH setting to env - add IPv6 route add / route delete code for windows (using "netsh") - - Win32 IPv6 ifconfig support, using "netsh" calls - drop "book ipv6" from open_tun() and tuncfg() prototypes - document recent changes and open TODOs, adapt --version info, tag release - Win32: set next-hop for IPv6 routes according to TUN/TAP mode - when deleting a route on win32, also add gateway address - WIN32: if IPv6 requested in TUN mode, check if TUN/TAP driver < 9.7 - revert unconditionally-enabling of setenv_es() logging - implement IPv6 ifconfig + route setup/deletion on OpenBSD - full "VPN client connect" test framework for OpenVPN t_client.rc-sample - renamed t_client.sh to t_client.sh.in - 2.2-beta3 has a signed TAP driver with the IPv6 code - test for 9.8 - correct URL for "more information about IPv6 patch is *here*" - bugfix for linux/iproute2: IPv6 ifconfig code block was not called for "dev tun"+"topology subnet" - bump IPv6 version number (openvpn --version) to 20100922-1 - Implement "ipv6 ifconfig" for TAP interfaces on Solaris interfaces - rebased to 2.2RC2 (beta 2.2 branch) - Windows IPv6 cleanup - properly remove IPv6 routes and interface config - For all accesses to "struct route_list * rl", check first that rl is non-NULL - Replace 32-bit-based add_in6_addr() implementation by an 8-bit based one - Platform cleanup for NetBSD - Move block for "stale-routes-check" config inside #ifdef P2MP_SERVER block - add missing break between "case IPv4" and "case IPv6" - bump tap driver version from 9.8 to 9.9 - log error message and exit for "win32, tun mode, tap driver version 9.8" - work around inet_ntop/inet_pton problems for MSVC builds on WinXP - Fix build-up of duplicate IPv6 routes on reconnect. - Fix list-overrun checks in copy_route_[ipv6_]option_list() - add "print test titles" and "use sudo" functionality to t_client.rc - Platform cleanup for FreeBSD - Implement IPv6 interface config with non-/64 prefix lengths. - Fix RUN_SUDO functionality for t_client.sh - Document IPv6-related environment variables. - Platform cleanup for OpenBSD - -Gisle Vanem (1): - Avoid re-defining uint32_t when using mingw compiler - -Gustavo Zacarias (1): - Fix compile issues when using --enable-small and --disable-ssl/--disable-crypto - -Heiko Hund (16): - add .gitignore to official repository - remove function is_proto_tcp() - remove legacy code to query IE proxy information - lowercase include header name in syshead.h - define IN6_ARE_ADDR_EQUAL macro for WIN32 - add --mark option to set SO_MARK sockopt - Windows UTF-8 input/output - UTF-8 X.509 distinguished names - set Windows environment variables as UCS-2 - handle Windows unicode paths - replace check for TARGET_WIN32 with WIN32 - do not use mode_t on Windows - use the underscore version of stat on Windows - make MSVC link against shell32 as well - move variable declaration to top of function - define access mode flag X_OK as 0 on Windows - -Igor Novgorodov (1): - The code blocks enabled by ENABLE_CLIENT_CR depends on management - -James Yonan (57): - Added "management-external-key" option. - Minor addition of logging info before and after execution of Windows net commands. - Misc fixes to r6708. - Added --x509-track option. - * added --management-up-down option to allow management interface to be notified of tunnel up/down events. - Fixed minor compile issue triggered on builds where MANAGEMENT_DEF_AUTH is not enabled. - Implemented get_default_gateway_mac_addr for Mac OS X - Fixes to r6925. - Properly handle certificate serial numbers > 32 bits. - Added "client-nat" option for stateless, one-to-one NAT on the client side. - Renamed branch to reflect that it is no longer beta. - env_filter_match now includes the serial number of all certs - Fixed issue where a client might receive multiple push replies from a server - Fixed bug introduced in r7031 that might cause this error message: - Extended "client-kill" management interface command (server-side) - Client will now try to reconnect if no push reply received within handshake-window seconds. - Version 2.1.3n - Fixed compiling issues when using --disable-crypto - Added "management-external-key" option. - Misc fixes to r6708. - win/sign.py now accepts an optional tap-dir argument. - Added "auth-token" client directive - Added ./configure --enable-osxipconfig option for Mac OS X - Added more packet ID debug info at debug level 3 for debugging false positive packet replays. - Fixed bug that incorrectly placed stricter TCP packet replay rules on UDP sessions - Fixed bug in port-share that could cause port share process to crash - For Mac OSX, when DARWIN_USE_IPCONFIG is defined, retry ipconfig command on failure - Version 2.1.3t - Revert r7092 and r7151, i.e. remove --enable-osxipconfig configure option. - Added 'dir' flag to "crl-verify" (see man page for info). - Added new "extra-certs" and "verify-hash" options - Fixed compile issues on Windows. - Added --enable-lzo-stub configure option to build an OpenVPN client without LZO - Added optional journal directory argument to "port-share" directive - Reduce log verbosity at level 3, with a focus on removing excessive log verbosity generated by port-share activity. - env_filter_match now includes the serial number of all certs in chain - Added support for static challenge/response protocol. - r7316 fixes. - Added redirect-gateway block-local flag, with support for Linux, Mac OS X - Extended x509-track to allow SHA1 certificate hash to be extracted - Added "management-query-remote" directive (client) to allow the management interface to override the "remote" directive. - Version 2.1.5. - Fixed MSVC compile error related to r7408. - Redact "echo" directive strings from log, since these strings (going forward) could conceivably contain security-sensitive data. - Modified sanitize_control_message to remove redacted data from control string rather than blotting it out with "_" chars. - Changed CC_PRINT character class to allow UTF-8 chars. - Increased the --verb threshold for "PID_ERR replay" messages to 4 from 3. - Fixed issue where redirect-gateway block-local code was not correctly calculating... - CC_PRINT character class now allows any 8-bit character value >= 32. - "status" management interface command (version >= 2) will now include the username for each connected user. - Minor fix to CC_PRINT char class - Fixed management interface bug where >FATAL notifications were not being output properly - Raised D_PID_DEBUG_LOW from level 3 to 4 to reduce replay error verbosity at level 3. - Added "memstats" option to maintain real-time operating stats in a memory-mapped file. - Fixed client issues with DHCP Router option extraction/deletion when using layer 2 with DHCP proxy: - Allow "tap-win32 dynamic " to be used in topology subnet mode. - Added support for "on-link" routes on Linux client - -Jan Just Keijser (1): - Made some options connection-entry specific - -Joe Patterson (1): - common_name passing in auth_pam plugin - -JuanJo Ciarlante (40): - * rebased openvpn-2.1_rc1b.jjo.20061206.d.patch - * created getaddr6(), use it from resolve_remote() - * migrated all getaddrinfo() to getaddr6 - * socket.c: use USE_PF_INET6 in switch constructs to actually toss them out, - * support --disable-ipv6 build properly: - * important fix for tcp6 reconnection was incorrectly creating a PF_INET socket - * added README.ipv6.txt - * fixed win32 non-ipv6 build - * ipv6 on win32 "milestone": 1st snapshot that passes all unittests - * document ipv6 milestone status - * doc update w/unittests results - * make possible to x-compile openvpn/win32 in Linux - * correctly setup hints.ai_socktype for getaddrinfo(), althought sorta hacky, see TODO.ipv6. - * renamed README.ipv6{.txt,} - * updated {README,TODO}.ipv6 from feedback at openvpn-devel mlist - * init.c: document the ENABLE_MANAGEMENT place to work on - * init.c: small in-doc tweaks - * fix multi-tcp crash (corrected assertion) - * TODO.ipv6 update - * socket.c: better buf logic in print_sockaddr_ex - * fixed segfault for undef address family in print_sockaddr_ex (thanks Marcel!) - * doc updates - * openbsd: no IFF_MULTICAST, #ifdef around it - * no new funcionality, just small cleanups - * (prototype) fix for supporting "redirect-gateway" for tunneled ipv4 over ipv6 endpoints - * polished redirect-gateway (ipv4 on ipv6 endpoints) support - * updated doc - * fix --disable-ipv6 build - * doc updates - * rebased to v2.1.1 release - * undo mroute.c changes related to ipv6 payload - * fix --multihome for ipv4 - * fix --multihome for ipv6 - * ipv6-0.4.14: fix xinetd usage - * ipv6-0.4.15: add --multihome support to xBSD - * ipv6-0.4.15b: rebase over openvpn-testing-master - * ipv6-0.4.16: fix mingw32 build - * make ipv6_payload compile under windowze - USE_PF_INET6 by default for v2.3 - fix ipv6 compilation under macosx >= 1070 - v3 - -Markus Koetter (1): - Add extv3 X509 field support to --x509-username-field - -Matthew L. Creech (1): - Fix 2.2.0 build failure when management interface disabled - -Matthias Andree (1): - Skip rather than fail test in addressless FreeBSD jails. - -Robert Fischer (8): - Update man page with info about --capath - Update man page with info about --connect-timeout - Added info about --show-proxy-settings - Documented --x509-username-field option - Documented --errors-to-stderr option - Documented --push-peer-info option - Update man page with info about --remote-random-hostname - Added man page entry for --management-client - -Samuli Seppänen (19): - Add man page entry for --redirect-private - Change all CRLF linefeeds to LF linefeeds - Fix a bug in devcon source code handling - Removed Win2k from supported platforms list in INSTALL and win/openvpn.nsi - Fixed copying of tapinstall.exe to dist/bin when using prebuilt TAP-drivers - Fixed a bug with GUI icon deletion on upgrade from 2.2-RC or earlier - Fix a build-ca issue on Windows - Add new openssl.cnf to easy-rsa/Windows - Updated "easy-rsa" for OpenSSL 1.0.0 - Made domake-win builds to use easy-rsa/2.0/openssl-1.0.0.cnf - Fixes to easy-rsa/2.0 - Merged TODO.IPv6 with TODO.ipv6 and README.IPv6 with README.ipv6 - Fixed a number of fatal build errors on Visual Studio 2008 - Fix a Visual Studio 2008 build issue in socket.c - Additional Visual Studio 2008 build fixes to tun.c - Fixed a typo in win32.h that prevented building with Visual Studio - Fixed a regression causing VS2008/Python build failure - Fix a Visual Studio 2008 build error in tun.c - Fix a Visual Studio 2008 build error in options.c - -Simon Matter (1): - Fix issues with some older GCC compilers - -Stefan Hellermann (2): - plugin.h: update prototype of plugin_call dummy in !ENABLE_PLUGIN case - Fixed typo in plugin.h - -chantra (1): - Clarify --tmp-dir option - -smos (1): - Change the netsh.exe command from "add" to "set". - -2011.12.25 -- Version 2.x-master -James Yonan (1): - Added support for "on-link" routes on Linux client -- these are - routes where the gateway is specified as an interface rather than - an address. This allows redirect-gateway to work on Linux clients - whose connection to the internet is via a point-to-point link - such as PPP. - - Note that at the moment, this capability is incompatible with - the "redirect-gateway block-local" directive -- this is because - the block-local directive blocks all traffic from the local LAN - except for the local and gateway addresses. Since a PPP link - is essentially a subnet of two addresses, local and remote (i.e. - gateway), the set of addresses that would be blocked by block-local - is empty. Therefore, the "redirect-gateway block-local" directive - will be ignored on PPP links. - - To view the OpenVPN client's current determination of the default - gateway, use this command: - - ./openvpn --show-gateway - -2011.03.24 -- Version 2.2-RC2 -Alon Bar-Lev (1): - Windows cross-compile cleanup - -David Sommerseth (2): - Open log files as text files on Windows - Clarify default value for the --inactive option. - -Gert Doering (1): - Implement IPv6 in TUN mode for Windows TAP driver. - -Samuli Seppänen (6): - Added support for prebuilt TAP-drivers. Automated embedding manifests. - Fixes to win/openvpn.nsi - Replaced config-win32.h with win/config.h.in - Updated INSTALL-win32.txt - Fixes to Makefile.am - Clarified --client-config-dir section on the man-page. - -Ville Skyttä (1): - Fix line continuation in chkconfig init script description. - -2011.02.28 -- Version 2.2-RC -David Sommerseth (3): - Make the --x509-username-field feature an opt-in feature - Fix compiler warning when compiling against OpenSSL 1.0.0 - Fix packaging of config-win32.h and service-win32/msvc.mak - -James Yonan (1): - Minor addition of logging info before and after execution of Windows net commands. - -Matthias Andree (1): - Change variadic macros to C99 style. - -Samuli Seppänen (15): - Added ENABLE_PASSWORD_SAVE to config-win32.h - Added a nmake makefile for openvpnserv.exe building - Moved TAP-driver version info to version.m4. Cleaned up win/settings.in. - Added helper functionality to win/wb.py - Added support for viewing config-win32.h paramters to win/show.py - Added comments and made small modifications to win/msvc.mak.in - Added command-line switch to win/build_all.py to skip TAP driver building - Added configure.h and version.m4 variable parsing to win/config.py - Added openvpnserv.exe building to win/build.py - Added comments to win/build_ddk.py - Several modifications to win/make_dist.py to allow building the NSI installer - Copied install-win32/setpath.nsi to win/setpath.nsi - Added first version of NSI installer script to win/openvpn.nsi - Changes to buildsystem patchset - Temporary snprintf-related fix to service-win32/openvpnserv.c - -2010.11.25 -- Version 2.2-beta5 - -Samuli Seppänen (1): - Fixed an issue causing a build failure with MS Visual Studio 2008. - -2010.11.18 -- Version 2.2-beta4 - -David Sommerseth (10): - Clarified --explicit-exit-notify man page entry - Clean-up: Remove pthread and mutex locking code - Clean-up: Remove more dead and inactive code paths - Clean-up: Removing useless code - hash related functions - Use stricter snprintf() formatting in socks_username_password_auth() (v3) - Fix compiler warnings about not used dummy() functions - Fixed potential misinterpretation of boolean logic - Only add some functions when really needed - Removed functions not being used anywhere - Merged add_bypass_address() and add_host_route_if_nonlocal() - -Gert Doering (3): - Integrate support for TAP mode on Solaris, written by Kazuyoshi Aizawa . - Make "topology subnet" work on Solaris - Improved man page entry for script_type - -James Yonan (5): - Fixed initialization bug in route_list_add_default_gateway (Gert Doering). - Implement challenge/response authentication support in client mode - Make base64.h have the same conditional compilation expression as base64.c. - Fixed compiling issues when using --disable-crypto - In verify_callback, the subject var should be freed by OPENSSL_free, not free - -Jesse Young (1): - Remove hardcoded path to resolvconf - -Lars Hupel (1): - Add HTTP/1.1 Host header - -Pierre Bourdon (1): - Adding support for SOCKS plain text authentication - -Samuli Seppänen (2): - Added check for variable CONFIGURE_DEFINES into options.c - Added command-line option parser and an unsigned build option to build_all.py - -2010.08.21 -- Version 2.2-beta3 - -* Attempt to fix issue where domake-win build system was not properly - signing drivers and .exe files. - - Added win/tap_span.py for building multiple versions of the TAP driver - and tapinstall binaries using different DDK versions to span from Win2K - to Win7 and beyond. - -* Community patches - David Sommerseth (2): - Test framework improvment - Do not FAIL if t_client.rc is missing - More t_client.sh updates - exit with SKIP when we want to skip - - Gert Doering (4): - Fix compile problems on NetBSD and OpenBSD - Fix compile time problems on OpenBSD for good - full "VPN client connect" test framework for OpenVPN - Build t_client.sh by configure at run-time. - - chantra (1): - Fixes openssl-1.0.0 compilation warning - -2010.08.16 -- Version 2.2-beta2 - -* Windows security issue: - Fixed potential local privilege escalation vulnerability in - Windows service. The Windows service did not properly quote the - executable filename passed to CreateService. A local attacker - with write access to the root directory C:\ could create an - executable that would be run with the same privilege level as - the OpenVPN Windows service. However, since non-Administrative - users normally lack write permission on C:\, this vulnerability - is generally not exploitable except on older versions of Windows - (such as Win2K) where the default permissions on C:\ would allow - any user to create files there. - Credit: Scott Laurie, MWR InfoSecurity - -* Added Python-based based alternative build system for Windows using - Visual Studio 2008 (in win directory). - -* When aborting in a non-graceful way, try to execute do_close_tun in - init.c prior to daemon exit to ensure that the tun/tap interface is - closed and any added routes are deleted. - -* Fixed an issue where AUTH_FAILED was not being properly delivered - to the client when a bad password is given for mid-session reauth, - causing the connection to fail without an error indication. - -* Don't advance to the next connection profile on AUTH_FAILED errors. - -* Fixed an issue in the Management Interface that could cause - a process hang with 100% CPU utilization in --management-client - mode if the management interface client disconnected at the - point where credentials are queried. - -* Fixed an issue where if reneg-sec was set to 0 on the client, - so that the server-side value would take precedence, - the auth_deferred_expire_window function would incorrectly - return a window period of 0 seconds. In this case, the - correct window period should be the handshake window - period. - -* Modified ">PASSWORD:Verification Failed" management interface - notification to include a client reason string: - - >PASSWORD:Verification Failed: 'AUTH_TYPE' ['REASON_STRING'] - -* Enable exponential backoff in reliability layer - retransmits. - -* Set socket buffers (SO_SNDBUF and SO_RCVBUF) immediately after - socket is created rather than waiting until after connect/listen. - -* Management interface performance optimizations: - - 1. Added env-filter MI command to perform filtering on env vars - passed through as a part of --management-client-auth - - 2. man_write will now try to aggregate output into larger blocks - (up to 1024 bytes) for more efficient i/o - -* Fixed minor issue in Windows TAP driver DEBUG builds - where non-null-terminated unicode strings were being - printed incorrectly. - -* Fixed issue on Windows with MSVC compiler, where TCP_NODELAY support - was not being compiled in. - -* Proxy improvements: - - Improved the ability of http-auth "auto" flag to dynamically detect - the auth method required by the proxy. - - Added http-auth "auto-nct" flag to reject weak proxy auth methods. - - Added HTTP proxy digest authentication method. - - Removed extraneous openvpn_sleep calls from proxy.c. - -* Implemented http-proxy-override and http-proxy-fallback directives to make it - easier for OpenVPN client UIs to start a pre-existing client config file with - proxy options, or to adaptively fall back to a proxy connection if a direct - connection fails. - -* Implemented a key/value auth channel from client to server. - -* Fixed issue where bad creds provided by the management interface - for HTTP Proxy Basic Authentication would go into an infinite - retry-fail loop instead of requerying the management interface for - new creds. - -* Added support for MSVC debugging of openvpn.exe in settings.in: - - # Build debugging version of openvpn.exe - !define PRODUCT_OPENVPN_DEBUG - -* Implemented multi-address DNS expansion on the network field of route - commands. - - When only a single IP address is desired from a multi-address DNS - expansion, use the first address rather than a random selection. - -* Added --register-dns option for Windows. - - Fixed some issues on Windows with --log, subprocess creation - for command execution, and stdout/stderr redirection. - -* Fixed an issue where application payload transmissions on the - TLS control channel (such as AUTH_FAILED) that occur during - or immediately after a TLS renegotiation might be dropped. - -* Added warning about tls-remote option in man page. - -2009.12.11 -- Version 2.1.1 - -* Fixed some breakage in openvpn.spec (which is required to build an - RPM distribution) where it was referencing a non-existent - subdirectory in the tarball, causing it to fail (patch from - David Sommerseth). - -2009.12.11 -- Version 2.1.0 - -* Fixed a couple issues in sample plugins auth-pam.c and down-root.c. - (1) Fail gracefully rather than segfault if calloc returns NULL. - (2) The openvpn_plugin_abort_v1 function can potentially be called - with handle == NULL. Add code to detect this case, and if so, avoid - dereferencing pointers derived from handle (Thanks to David - Sommerseth for finding this bug). - -* Documented "multihome" option in the man page. - -2009.11.20 -- Version 2.1_rc22 - -* Fixed a client-side bug on Windows that occurred when the - "dhcp-pre-release" or "dhcp-renew" options were combined with - "route-gateway dhcp". The release/renew would not occur - because the Windows DHCP renew function is blocking and - therefore must be called from another process or thread - so as not to stall the tunnel. - -* Added a hard failure when peer provides a certificate chain - with depth > 16. Previously, a warning was issued. - -2009.11.12 -- Version 2.1_rc21 - -* Rebuilt OpenVPN Windows installer with OpenSSL 0.9.8l to address - CVE-2009-3555. Note that OpenVPN has never relied on the session - renegotiation capabilities that are built into the SSL/TLS protocol, - therefore the fix in OpenSSL 0.9.8l (disable SSL/TLS renegotiation - completely) will not adversely affect OpenVPN mid-session SSL/TLS - renegotation or any other OpenVPN capabilities. - -* Added additional session renegotiation hardening. OpenVPN has always - required that mid-session renegotiations build up a new SSL/TLS - session from scratch. While the client certificate common name is - already locked against changes in mid-session TLS renegotiations, we - now extend this locking to the auth-user-pass username as well as all - certificate content in the full client certificate chain. - -2009.10.01 -- Version 2.1_rc20 - -* Fixed a bug introduced in 2.1_rc17 (svn r4436) where using the - redirect-gateway option by itself, without any extra parameters, - would cause the option to be ignored. - -* Fixed build problem when ./configure --disable-server is used. - -* Fixed ifconfig command for "topology subnet" on FreeBSD (Stefan Bethke). - -* Added --remote-random-hostname option. - -* Added "load-stats" management interface command to get global server - load statistics. - -* Added new ./configure flags: - - --disable-def-auth Disable deferred authentication - --disable-pf Disable internal packet filter - -* Added "setcon" directive for interoperability with SELinux (Sebastien - Raveau). - -* Optimized PUSH_REQUEST handshake sequence to shave several seconds - off of a typical client connection initiation. - -* The maximum number of "route" directives (specified in the config - file or pulled from a server) can now be configured via the new - "max-routes" directive. - -* Eliminated the limitation on the number of options that can be pushed - to clients, including routes. Previously, all pushed options needed - to fit within a 1024 byte options string. - -* Added --server-poll-timeout option : when polling possible remote - servers to connect to in a round-robin fashion, spend no more than - n seconds waiting for a response before trying the next server. - -* Added the ability for the server to provide a custom reason string - when an AUTH_FAILED message is returned to the client. This - string can be set by the server-side managment interface and read - by the client-side management interface. - -* client-kill management interface command, when issued on server, will - now send a RESTART message to client. - This feature is intended to make UDP clients respond the same as TCP - clients in the case where the server issues a RESTART message in - order to force the client to reconnect and pull a new options/route - list. - -2009.07.16 -- Version 2.1_rc19 - -* In Windows TAP driver, refactor DHCP/ARP packet injection code to - use a DPC (deferred procedure call) to defer packet injection until - IRQL < DISPATCH_LEVEL, rather than calling NdisMEthIndicateReceive - in the context of AdapterTransmit. This is an attempt to reduce kernel - stack usage, and prevent EXCEPTION_DOUBLE_FAULT BSODs that have been - observed on Vista. Updated TAP driver version number to 9.6. - -* In configure.ac, use datadir instead of datarootdir for compatibility - with CLIENT:ESTABLISHED" notification. - -* Build fixes: - - 1. Fixed some issues with C++ style comments that leaked into the code. - - 2. Updated configure.ac to work on MinGW64. - - 3. Updated common.h types for _WIN64. - - 4. Fixed issue involving an #ifdef in a macro reference that breaks early gcc - compilers. - - 5. In cryptoapi.c, renamed CryptAcquireCertificatePrivateKey to - OpenVPNCryptAcquireCertificatePrivateKey to work around - a symbol conflict in MinGW-5.1.4. - -2008.11.19 -- Version 2.1_rc15 - -* Fixed issue introduced in 2.1_rc14 that may cause a - segfault when a --plugin module is used. - -* Added server-side --opt-verify option: clients that connect - with options that are incompatible with those of the server - will be disconnected (without this option, incompatible - clients would trigger a warning message in the server log - but would not be disconnected). - -* Added --tcp-nodelay option: Macro that sets TCP_NODELAY socket - flag on the server as well as pushes it to connecting clients. - -* Minor options check fix: --no-name-remapping is a - server-only option and should therefore generate an - error when used on the client. - -* Added --prng option to control PRNG (pseudo-random - number generator) parameters. In previous OpenVPN - versions, the PRNG was hardcoded to use the SHA1 - hash. Now any OpenSSL hash may be used. This is - part of an effort to remove hardcoded references to - a specific cipher or cryptographic hash algorithm. - -* Cleaned up man page synopsis. - -2008.11.16 -- Version 2.1_rc14 - -* Added AC_GNU_SOURCE to configure.ac to enable struct ucred, - with the goal of fixing a build issue on Fedora 9 that was - introduced in 2.1_rc13. - -* Added additional method parameter to --script-security to preserve - backward compatibility with system() call semantics used in OpenVPN - 2.1_rc8 and earlier. To preserve backward compatibility use: - - script-security 3 system - -* Added additional warning messages about --script-security 2 - or higher being required to execute user-defined scripts or - executables. - -* Windows build system changes: - - Modified Windows domake-win build system to write all openvpn.nsi - input files to gen, so that gen can be disconnected from - the rest of the source tree and makensis openvpn.nsi will - still function correctly. - - Added additional SAMPCONF_(CA|CRT|KEY) macros to settings.in - (commented out by default). - - Added optional files SAMPCONF_CONF2 (second sample configuration - file) and SAMPCONF_DH (Diffie-Helman parameters) to Windows - build system, and may be defined in settings.in. - -* Extended Management Interface "bytecount" command - to work when OpenVPN is running as a server. - Documented Management Interface "bytecount" command in - management/management-notes.txt. - -* Fixed informational message in ssl.c to properly indicate - deferred authentication. - -* Added server-side --auth-user-pass-optional directive, to allow - connections by clients that do not specify a username/password, when a - user-defined authentication script/module is in place (via - --auth-user-pass-verify, --management-client-auth, or a plugin module). - -* Changes to easy-rsa/2.0/pkitool and related openssl.cnf: - - Calling scripts can set the KEY_NAME environmental variable to set - the "name" X509 subject field in generated certificates. - - Modified pkitool to allow flexibility in separating the Common Name - convention from the cert/key filename convention. - - For example: - - KEY_CN="James's Laptop" KEY_NAME="james" ./pkitool james - - will create a client certificate/key pair of james.crt/james.key - having a Common Name of "James's Laptop" and a Name of "james". - -* Added --no-name-remapping option to allow Common Name, X509 Subject, - and username strings to include any printable character including - space, but excluding control characters such as tab, newline, and - carriage-return (this is important for compatibility with external - authentication systems). - - As a related change, added --status-version 3 format (and "status 3" - in the management interface) which uses the version 2 format except - that tabs are used as delimiters instead of commas so that there - is no ambiguity when parsing a Common Name that contains a comma. - - Also, save X509 Subject fields to environment, using the naming - convention: - - X509_{cert_depth}_{name}={value} - - This is to avoid ambiguities when parsing out the X509 subject string - since "/" characters could potentially be used in the common name. - -* Fixed some ifconfig-pool issues that precluded it from being combined - with --server directive. - - Now, for example, we can configure thusly: - - server 10.8.0.0 255.255.255.0 nopool - ifconfig-pool 10.8.0.2 10.8.0.99 255.255.255.0 - - to have ifconfig-pool manage only a subset - of the VPN subnet. - -* Added config file option "setenv FORWARD_COMPATIBLE 1" to relax - config file syntax checking to allow directives for future OpenVPN - versions to be ignored. - -2008.10.07 -- Version 2.1_rc13 - -* Bundled OpenSSL 0.9.8i with Windows installer. - -* Management interface can now listen on a unix - domain socket, for example: - - management /tmp/openvpn unix - - Also added management-client-user and management-client-group - directives to control which processes are allowed to connect - to the socket. - -* Copyright change to OpenVPN Technologies, Inc. - -2008.09.23 -- Version 2.1_rc12 - -* Patched Makefile.am so that the new t_cltsrv-down.sh script becomes - part of the tarball (Matthias Andree). - -* Fixed --lladdr bug introduced in 2.1-rc9 where input validation code - was incorrectly expecting the lladdr parameter to be an IP address - when it is actually a MAC address (HoverHell). - -2008.09.14 -- Version 2.1_rc11 - -* Fixed a bug that can cause SSL/TLS negotiations in UDP mode - to fail if UDP packets are dropped. - -2008.09.10 -- Version 2.1_rc10 - -* Added "--server-bridge" (without parameters) to enable - DHCP proxy mode: Configure server mode for ethernet - bridging using a DHCP-proxy, where clients talk to the - OpenVPN server-side DHCP server to receive their IP address - allocation and DNS server addresses. - -* Added "--route-gateway dhcp", to enable the extraction - of the gateway address from a DHCP negotiation with the - OpenVPN server-side LAN. - -* Fixed minor issue with --redirect-gateway bypass-dhcp or bypass-dns - on Windows. If the bypass IP address is 0.0.0.0 or 255.255.255.255, - ignore it. - -* Warn when ethernet bridging that the IP address of the bridge adapter - is probably not the same address that the LAN adapter was set to - previously. - -* When running as a server, warn if the LAN network address is - the all-popular 192.168.[0|1].x, since this condition commonly - leads to subnet conflicts down the road. - -* Primarily on the client, check for subnet conflicts between - the local LAN and the VPN subnet. - -* Added a 'netmask' parameter to get_default_gateway, to return - the netmask of the adapter containing the default gateway. - Only implemented on Windows so far. Other platforms will - return 255.255.255.0. Currently the netmask information is - only used to warn about subnet conflicts. - -* Minor fix to cryptoapi.c to not compile itself unless USE_CRYPTO - and USE_SSL flags are enabled (Alon Bar-Lev). - -* Updated openvpn/t_cltsrv.sh (used by "make check") to conform to new - --script-security rules. Also adds retrying if the addresses are in - use (Matthias Andree). - -* Fixed build issue with ./configure --disable-socks --disable-http. - -* Fixed separate compile errors in options.c and ntlm.c that occur - on strict C compilers (such as old versions of gcc) that require - that C variable declarations occur at the start of a {} block, - not in the middle. - -* Workaround bug in OpenSSL 0.9.6b ASN1_STRING_to_UTF8, which - the new implementation of extract_x509_field_ssl depends on. - -* LZO compression buffer overflow errors will now invalidate - the packet rather than trigger a fatal assertion. - -* Fixed minor compile issue in ntlm.c (mid-block declaration). - -* Added --allow-pull-fqdn option which allows client to pull DNS names - from server (rather than only IP address) for --ifconfig, --route, and - --route-gateway. OpenVPN versions 2.1_rc7 and earlier allowed DNS names - for these options to be pulled and translated to IP addresses by default. - Now --allow-pull-fqdn will be explicitly required on the client to enable - DNS-name-to-IP-address translation of pulled options. - -* 2.1_rc8 and earlier did implicit shell expansion on script - arguments since all scripts were called by system(). - The security hardening changes made to 2.1_rc9 no longer - use system(), but rather use the safer execve or CreateProcess - system calls. The security hardening also introduced a - backward incompatibility with 2.1_rc8 and earlier in that - script parameters were no longer shell-expanded, so - for example: - - client-connect "docc CLIENT-CONNECT" - - would fail to work because execve would try to execute - a script called "docc CLIENT-CONNECT" instead of "docc" - with "CLIENT-CONNECT" as the first argument. - - This patch fixes the issue, bringing the script argument - semantics back to pre 2.1_rc9 behavior in order to preserve - backward compatibility while still using execve or CreateProcess - to execute the script/executable. - -* Modified ip_or_dns_addr_safe, which validates pulled DNS names, - to more closely conform to RFC 3696: - - (1) DNS name length must not exceed 255 characters - - (2) DNS name characters must be limited to alphanumeric, - dash ('-'), and dot ('.') - -* Fixed bug in intra-session TLS key rollover that was introduced with - deferred authentication features in 2.1_rc8. - -2008.07.31 -- Version 2.1_rc9 - -* Security Fix -- affects non-Windows OpenVPN clients running - OpenVPN 2.1-beta14 through 2.1-rc8 (OpenVPN 2.0.x clients are NOT - vulnerable nor are any versions of the OpenVPN server vulnerable). - An OpenVPN client connecting to a malicious or compromised - server could potentially receive an "lladdr" or "iproute" configuration - directive from the server which could cause arbitrary code execution on - the client. A successful attack requires that (a) the client has agreed - to allow the server to push configuration directives to it by including - "pull" or the macro "client" in its configuration file, (b) the client - successfully authenticates the server, (c) the server is malicious or has - been compromised and is under the control of the attacker, and (d) the - client is running a non-Windows OS. Credit: David Wagner. - CVE-2008-3459 - -* Miscellaneous defensive programming changes to multiple - areas of the code. In particular, use of the system() call - for calling executables such as ifconfig, route, and - user-defined scripts has been completely revamped in favor - of execve() on unix and CreateProcess() on Windows. - -* In Windows build, package a statically linked openssl.exe to work around - observed instabilities in the dynamic build since the migration to - OpenSSL 0.9.8h. - -2008.06.11 -- Version 2.1_rc8 - -* Added client authentication and packet filtering capability - to management interface. In addition, allow OpenVPN plugins - to take advantage of deferred authentication and packet - filtering capability. - -* Added support for client-side connection profiles. - -* Fixed unbounded memory growth bug in environmental variable - code that could have caused long-running OpenVPN sessions - with many TLS renegotiations to incrementally - increase memory usage over time. - -* Windows release now packages openssl-0.9.8h. - -* Build system changes -- allow building on Windows using - autoconf/automake scripts (Alon Bar-Lev). - -* Changes to Windows build system to make it easier to do - partial builds, with a reduced set of prerequisites, - where only a subset of OpenVPN installer - components are built. See ./domake-win comments. - -* Cleanup IP address for persistence interfaces for tap and also - using ifconfig, gentoo#209055 (Alon Bar-Lev). - -* Fall back to old version of extract_x509_field for OpenSSL 0.9.6. - -* Clarified tcp-queue-limit man page entry (Matti Linnanvuori). - -* Added new OpenVPN icon and installer graphic. - -* Minor pkitool changes. - -* Added --pkcs11-id-management option, which will cause OpenVPN to - query the management interface via the new NEED-STR asynchronous - notification query to get additional PKCS#11 options (Alon Bar-Lev). - -* Added NEED-STR management interface asynchronous query and - "needstr" management interface command to respond to the query - (Alon Bar-Lev). - -* Added Dragonfly BSD support (Francis-Gudin). - -* Quote device names before passing to up/down script (Josh Cepek). - -* Bracketed struct openvpn_pktinfo with #pragma pack(1) to - prevent structure padding from causing an incorrect length - to be returned by sizeof (struct openvpn_pktinfo) on 64-bit - platforms. - -* On systems that support res_init, always call it - before calling gethostbyname to ensure that - resolver configuration state is current. - -* Added NTLMv2 proxy support (Miroslav Zajic). - -* Fixed an issue in extract_x509_field_ssl where the extraction - would fail on the first field of the subject name, such as - the common name in: /CN=foo/emailAddress=foo@bar.com - -* Made "Linux ip addr del failed" error nonfatal. - -* Amplified --client-cert-not-required warning. - -* Added #pragma pack to proto.h. - -2008.01.29 -- Version 2.1_rc7 - -* Added a few extra files that exist in the svn repo but were - not being copied into the tarball by make dist. - -* Fixup null interface on close, don't use ip addr flush (Alon Bar-Lev). - -2008.01.24 -- Version 2.1_rc6 - -* Fixed options checking bug introduced in rc5 where legitimate configuration - files might elicit the error: "Options error: Parameter pkcs11_private_mode - can only be specified in TLS-mode, i.e. where --tls-server or --tls-client - is also specified." - -2008.01.23 -- Version 2.1_rc5 - -* Fixed Win2K TAP driver bug that was introduced by Vista fixes, - incremented driver version to 9.4. - -* Windows build system changes: - - Incremented included OpenSSL version to openssl-0.9.7m. - - Updated openssl.patch for openssl-0.9.7m and added some - brief usage comments to the head of the patch. - - Added build-pkcs11-helper.sh for building the pkcs11-helper - library. - - Integrated inclusion of pkcs11-helper into Windows build - system. - - Upgraded TAP build scripts to use WDK 6001.17121 - (Windows 2008 Server pre-RTM). - -* Windows installer changes: - - Clean up the start menu folder. - - Allow for a site-specific sample configuration file and keys - to be included in a custom installer (see SAMPCONF macros - in settings.in). - - New icon (temporary). - -* Added "forget-passwords" command to the management interface - (Alon Bar-Lev). - -* Added --management-signal option to signal SIGUSR1 when the - management interface disconnects (Alon Bar-Lev). - -* Modified command line and config file parser to allow - quoted strings using single quotes ('') (Alon Bar-Lev). - -* Use pkcs11-helper as external library, can be downloaded from - https://www.opensc-project.org/pkcs11-helper (Alon Bar-Lev). - -* Fixed interim memory growth issue in TCP connect loop where - "TCP: connect to %s failed, will try again in %d seconds: %s" - is output. - -* Fixed bug in epoll driver in event.c, where the lack of a - handler for EPOLLHUP could cause 99% CPU usage. - -* Defined ALLOW_NON_CBC_CIPHERS for people who don't - want to use a CBC cipher for OpenVPN's data channel. - -* Added PLUGIN_LIBDIR preprocessor string to prepend a default - plugin directory to the dlopen search list when the user - specifies the basename of the plugin only (Marius Tomaschewski). - -* Rewrote extract_x509_field and modified COMMON_NAME_CHAR_CLASS - to allow forward slash characters ("/") in the X509 common name - (Pavel Shramov). - -* Allow OpenVPN to run completely unprivileged under Linux - by allowing openvpn --mktun to be used with --user and --group - to set the UID/GID of the tun device node. Also added --iproute - option to allow an alternative command to be executed in place - of the default iproute2 command (Alon Bar-Lev). - -* Fixed --disable-iproute2 in ./configure to actually disable - iproute2 usage (Alon Bar-Lev). - -* Added --management-forget-disconnect option -- forget - passwords when management session disconnects (Alon Bar-Lev). - -2007.04.25 -- Version 2.1_rc4 - -* Worked out remaining issues with TAP driver signing - on Vista x64. OpenVPN will now run on Vista x64 - with driver signing enforcement enabled. - -* Fixed 64-bit portability bug in time_string function - (Thomas Habets). - -2007.04.22 -- Version 2.1_rc3 - -* Additional fixes to TAP driver for Windows x64. Driver - now runs successfully on Vista x64 if driver signing - enforcement is disabled. - -* The Windows Installer and TAP driver are now signed by - OpenVPN Solutions LLC (in addition to the usual GnuPG - signatures). - -* Added OpenVPN GUI (Mathias Sundman version) as install - option in Windows installer. - -* Clean up configure on FreeBSD for recent autotool versions - that require that all .h files have to be compiled. - Also, FreeBSD install does not support GNU long options - which the Makefile in easy-rsa/2.0 uses (not checked the - others as we don't install those on Gentoo) (Roy Marples). - -* Added additional scripts to easy-rsa/Windows for working - with password-protected keys; also add -extensions server - option when generating server cert via - build-key-server-pass.bat (Daniel Zauft). - -2007.02.27 -- Version 2.1_rc2 - -* auth-pam change: link with -lpam rather - than dlopen (Roy Marples). - -* Prevent SIGUSR1 or SIGHUP from causing program - exit from initial management hold. - -* SO_REUSEADDR should not be set on Windows TCP sockets - because it will cause bind to succeed on port conflicts. - -* Added time_ascii, time_duration, and time_unix - environmental variables for plugins and callback - scripts. - -* Fixed issue where OpenVPN does not apply the --txqueuelen option - to persistent interfaces made with --mktun (Roy Marples). - -* Attempt at rational signal handling when in the - management hold state. During management hold, ignore - SIGUSR1/SIGHUP signals thrown with the "signal" command. - Also, "signal" command will now apply remapping as - specified with the --remap-usr1 option. - When a signal entered using the "signal" command from a management - hold is ignored, output: >HOLD:Waiting for hold release - -* Fixed issue where struct env_set methods that - change the value of an existing name=value pair - would delay the freeing of the memory held by - the previous name=value pair until the underlying - client instance object is closed. - This could cause a server that handles long-term - client connections, resulting in many periodic calls - to verify_callback, to needlessly grow the env_set - memory allocation until the underlying client instance - object is closed. - -* Renamed TAP-Win32 driver from tap0801.sys to tap0901.sys - to reflect the fact that Vista has blacklisted the tap0801.sys - file name due to previous compatibility issues which have now - been resolved. TAP-Win32 major/minor version number is now 9/1. - -* Windows installer will delete a previously installed - tap0801.sys TAP driver before installing tap0901.sys. - -* Added code to Windows installer to fail gracefully on 64 bit - installs until 64-bit TAP driver issues can be resolved. - -* Added code to Windows installer to fail gracefully on - versions of Windows which are not explicitly supported. - -* The Windows version will now use a default route-delay - of 5 seconds to deal with an apparent routing table race - condition on Vista. - -* Worked around an incompatibility in the Windows Vista - version of CreateIpForwardEntry as described in - http://www.nynaeve.net/?p=59 - This issue would cause route additions using the - IP Helper API to fail on Vista. - -* On Windows, revert to "ip-win32 dynamic" as the default. - -2006.10.31 -- Version 2.1_rc1 - -* Support recovery (return to hold) from signal at - management password prompt. - -* Added workaround for OpenSC PKCS#11 bug#108 - (Alon Bar-Lev). - -2006.10.01 -- Version 2.1-beta16 - -* Windows installer updated with OpenSSL 0.9.7l DLLs to fix - published vulnerabilities. - -* Fixed TAP-Win32 bug that caused BSOD on Windows Vista - (Henry Nestler). - -* Autodetect 32/64 bit Windows in installer and install - appropriate TAP driver (Mathias Sundman, Hypherion). - -* Fixed bug in loopback self-test introduced - in 2.1-beta15 where self test as invoked by - "make check" would not properly exit after - 2 minutes (Paul Howarth). - -2006.09.12 -- Version 2.1-beta15 - -* Windows installer updated with OpenSSL 0.9.7k DLLs to fix - RSA Signature Forgery (CVE-2006-4339). - -* Fixed bug introduced with the --port-share directive - (back in 2.1-beta9 which causes TLS soft resets - (1 per hour by default) in TCP server mode to force - a blockage of tunnel packets and later time-out and - restart the connection. - -* easy-rsa update (Alon Bar-Lev) - Makefile (install) is now available so that - distribs will be able to install it safely. - -* PKCS#11 changes: (Alon Bar-Lev) - - Modified ssl.c to not FATAL and return to init.c - so auth-retry will work. - - Modifed pkcs11-helper.c to fix some problem with - multiple providers. - - Added retry counter to PKCS#11 PIN hook. - - Modified PKCS#11 PIN retry loop to return correct error - code when PIN is incorrect. - - Fix handling (ignoring) zero sized attributes. - - Fix gcc-2 issues. - - Fix openssl 0.9.6 (first version) issues. - -* Minor fixes of lladdr (Alon Bar-Lev) - Updated makefile.w32-vc to include lladdr.*, updated - linkage libraries. - Modified lladdr.c to be compiled under visual C. - -* Added two new management states: - OPENVPN_STATE_RESOLVE -- DNS lookup - OPENVPN_STATE_TCP_CONNECT -- Connecting to TCP server - -* Echo management state change to log. - -* Minor syshead.h change for NetBSD to allow - TCP_NODELAY flag to work. - -* Modified --port-share code to remove the assumption that - CMSG_SPACE always evaluates to a constant, to enable - compilation on NetBSD and possibly other BSDs as well. - -* Eliminated gcc 3.3.3 warnings on NetBSD - when ./configure --enable-strict is used. - -* Added optional minimum-number-of-bytes parameter - to --inactive directive. - -2006.04.13 -- Version 2.1-beta14 - -* Fixed Windows server bug in time backtrack handling code which - could cause TLS negotiation failures on legitimate clients. - -* Rewrote gettimeofday function for Windows to be - simpler and more efficient. - -* Merged PKCS#11 extensions to easy-rsa/2.0 (Alon Bar-Lev). - -* Added --route-metric option to set a default route metric - for --route (Roy Marples). - -* Added --lladdr option to specify the link layer (MAC) address - for the tap interface on non-Windows platforms (Roy Marples). - -2006.04.12 -- Version 2.1-beta13 - -* Code added in 2.1-beta7 and 2.0.6-rc1 to extend byte counters - to 64 bits caused a bug in the Windows version which has now - been fixed. The bug could cause intermittent crashes. - -2006.04.05 -- Version 2.1-beta12 - -* Security Vulnerability -- An OpenVPN client connecting to a - malicious or compromised server could potentially receive - "setenv" configuration directives from the server which could - cause arbitrary code execution on the client via a LD_PRELOAD - attack. A successful attack appears to require that (a) the - client has agreed to allow the server to push configuration - directives to it by including "pull" or the macro "client" in - its configuration file, (b) the client configuration file uses - a scripting directive such as "up" or "down", (c) the client - succesfully authenticates the server, (d) the server is - malicious or has been compromised and is under the control of - the attacker, and (e) the attacker has at least some level of - pre-existing control over files on the client (this might be - accomplished by having the server respond to a client web request - with a specially crafted file). Credit: Hendrik Weimer. - CVE-2006-1629. - - The fix is to disallow "setenv" to be pushed to clients from - the server, and to add a new directive "setenv-safe" which is - pushable from the server, but which appends "OPENVPN_" to the - name of each remotely set environmental variable. - -* "topology subnet" fix for FreeBSD (Benoit Bourdin). - -* PKCS11 fixes (Alon Bar-Lev). For full description: - svn log -r990 http://svn.openvpn.net/projects/openvpn/branches/BETA21 - -* When deleting routes under Linux, use the route metric - as a differentiator to ensure that the route teardown - process only deletes the identical route which was originally - added via the "route" directive (Roy Marples). - -* Fix the t_cltsrv.sh file in FreeBSD 4 jails - (Matthias Andree, Dirk Meyer, Vasil Dimov). - -* Extended tun device configure code to support ethernet - bridging on NetBSD (Emmanuel Kasper). - -2006.02.19 -- Version 2.1-beta11 - -* Fixed --port-share bug that caused premature closing - of proxied sessions. - -2006.02.17 -- Version 2.1-beta10 - -* Fixed --port-share breakage introduced in 2.1-beta9. - -2006.02.16 -- Version 2.1-beta9 - -* Added --port-share option for allowing OpenVPN and HTTPS - server to share the same port number. -* Added --management-client option to connect as a client - to management GUI app rather than be connected to as a - server. -* Added "bytecount" command to management interface. -* --remote-cert-tls fixes (Alon Bar-Lev). - -2006.01.03 -- Version 2.1-beta8 - -* --remap-usr1 will now also remap signals thrown during - initialization. -* Added --connect-timeout option to control the timeout - on TCP client connection attempts (doesn't work on all - OSes). This patch also makes OpenVPN signalable during - TCP connection attempts. -* Fixed bug in acinclude.m4 where capability of compiler - to handle zero-length arrays in structs is tested - (David Stipp). -* Fixed typo in manage.c where inline function declaration - was declared without the "static" keyword (David Stipp). -* Patch to support --topology subnet on Mac OS X (Mathias Sundman). -* Added --auto-proxy directive to auto-detect HTTP or SOCKS - proxy settings (currently Windows only). -* Removed redundant base64 code. -* Better sanity checking of --server and --server-bridge - IP pool ranges, so as not to hit the assertion at - pool.c:119 (2.0.5). -* Fixed bug where --daemon and --management-query-passwords - used together would cause OpenVPN to block prior to - daemonization. -* Fixed client/server race condition which could occur - when --auth-retry interact is set and the initially - provided auth-user-pass credentials are incorrect, - forcing a username/password re-query. -* Fixed bug where if --daemon and --management-hold are - used together, --user or --group options would be ignored. -* --ip-win32 adaptive is now the default. -* --ip-win32 netsh (or --ip-win32 adaptive when in netsh - mode) can now set DNS/WINS addresses on the TAP-Win32 - adapter. -* Added new option --route-method adaptive (Win32) - which tries IP helper API first, then falls back to - route.exe. -* Made --route-method adaptive the default. - -2005.11.12 -- Version 2.1-beta7 - -* Allow blank passwords to be passed via the management - interface. -* Fixed bug where "make check" inside a FreeBSD "jail" - would never complete (Matthias Andree). -* Fixed bug where --server directive in --dev tap mode - claimed that it would support subnets of /30 or less - but actually would only accept /29 or less. -* Extend byte counters to 64 bits (M. van Cuijk). -* Fixed bug in Linux get_default_gateway function - introduced in 2.0.4, which would cause redirect-gateway - on Linux clients to fail. -* Moved easy-rsa 2.0 scripts to easy-rsa/2.0 to - be compatible with 2.0.x distribution. -* Documented --route-nopull. -* Documented --ip-win32 adaptive. -* Windows build now linked with LZO2. -* Allow ca, cert, key, and dh files to be specified - inline via XML-like syntax without needing to - reference an explicit file. - For example: - - data here... - -* Allow plugin and push directives to have multi-line - parameter lists such as: - - my-plugin.so - parm1 - parm2 - -* Added connect-retry-max option (Alon Bar-Lev). -* Fixed problems where signals thrown during initialization - were not returning to a management-hold state. -* Added a backtrack-hardened system time algorithm. -* Added --remote-cert-ku, --remote-cert-eku, and - --remote-cert-tls options for verifying certificate - attributes (Alon Bar-Lev). -* For Windows, reverted --ip-win32 default back to "dynamic". - To use new adaptive mode, set explicitly. - -2005.11.01 -- Version 2.1-beta6 - -* Security fix (merged from 2.0.4) -- Affects non-Windows - OpenVPN clients of version 2.0 or higher which connect to - a malicious or compromised server. A format string - vulnerability in the foreign_option function in options.c - could potentially allow a malicious or compromised server - to execute arbitrary code on the client. Only - non-Windows clients are affected. The vulnerability - only exists if (a) the client's TLS negotiation with - the server succeeds, (b) the server is malicious or - has been compromised such that it is configured to - push a maliciously crafted options string to the client, - and (c) the client indicates its willingness to accept - pushed options from the server by having "pull" or - "client" in its configuration file (Credit: Vade79). - CVE-2005-3393 -* Security fix -- (merged from 2.0.4) Potential DoS - vulnerability on the server in TCP mode. If the TCP - server accept() call returns an error status, the resulting - exception handler may attempt to indirect through a NULL - pointer, causing a segfault. Affects all OpenVPN 2.0 versions. - CVE-2005-3409 -* Fix attempt of assertion at multi.c:1586 (note that - this precise line number will vary across different - versions of OpenVPN). -* Windows reliability changes: - (a) Added code to make sure that the local PATH environmental - variable points to the Windows system32 directory. - (b) Added new --ip-win32 adaptive mode which tries 'dynamic' - and then fails over to 'netsh' if the DHCP negotiation fails. - (c) Made --ip-win32 adaptive the default. -* More PKCS#11 additions/changes (Alon Bar-Lev). -* Added ".PHONY: plugin" to Makefile.am to work around - "make dist" issue. -* Fixed double fork issue that occurs when --management-hold - is used. -* Moved TUN/TAP read/write log messages from --verb 8 to 6. -* Warn when multiple clients having the same common name or - username usurp each other when --duplicate-cn is not used. -* Modified Windows and Linux versions of get_default_gateway - to return the route with the smallest metric - if multiple 0.0.0.0/0.0.0.0 entries are present. -* Added ">NEED-OK" alert and "needok" command to management - interface to provide a general interface for sending - alerts to the end-user. Used by the PKCS#11 code - to send Token Insertion Requests to the user. -* Added actual remote address used to the ">STATE" alert - in the management interface (Rolf Fokkens). - -2005.10.17 -- Version 2.1-beta4 - -* Fixed bug introduced in 2.1-beta3 where management - socket bind would fail. -* --capath fix in ssl.c (Zhuang Yuyao). -* Added ".PHONY: plugin" to Makefile.am, reverted - location of "plugin" directory (thanks to - Matthias Andree for figuring this out). - -2005.10.16 -- Version 2.1-beta3 - -* Added PKCS#11 support (Alon Bar-Lev). -* Enable the use of --ca together with --pkcs12. If --ca is - used at the same time as --pkcs12, the CA certificate is loaded - from the file specified by --ca regardless if the pkcs12 file - contains a CA cert or not (Mathias Sundman). -* Merged --capath patch (Thomas Noel). -* Merged --multihome patch. -* Added --bind option for TCP client connections (Ewan Bhamrah - Harley). -* Moved "plugin" directory to "plugins" to deal with strange - automake problem that ended up being also fixable with - ".PHONY: plugin" in Makefile.am. - -2005.10.13 -- Version 2.1-beta2 - -* Made --sndbuf and --rcvbuf pushable. - -2005.10.01 -- Version 2.1-beta1 - -* Made LZO setting pushable. -* Renamed sample-keys/tmp-ca.crt to ca.crt. -* Fixed bug where remove_iroutes_from_push_route_list - was missing routes if those routes had - an implied netmask (by omission) of 255.255.255.255. -* Merged with 2.0.3-rc1 -* easy-rsa/2.0 moved to easy-rsa -* old easy-rsa moved to easy-rsa/1.0 - -2005.09.23 -- Version 2.0.2-TO4 - -* Added feature to TAP-Win32 adapter to allow it to be - opened from non-administrator mode. This feature - is enabled by default, and can be enabled/disabled - in the adapter advanced properties dialog. -* Added --allow-nonadmin standalone option for Windows to - set TAP adapter to allow non-admin access. This - is a user-mode version of the code, and duplicates - the same feature as the above entry. -* Added fix that attempts to solve corner case of tunnel not - forwarding packets when system clock is reset to an earlier time. -* Added --redirect-gateway bypass-dns option. (Developers: - To add bypass-dhcp or bypass-dns support to other OSes, - add a get_bypass_addresses function to route.c for - your OS.) -* Added OPENVPN_PLUGIN_CLIENT_CONNECT_V2 plugin callback, which - allows a client-connect plugin to return configuration text - in memory, rather than via a file. -* Fixed a bug where --mode server --proto tcp-server --cipher none - operation could cause tunnel packet truncation. -* openvpn --version will show [LZO1] or [LZO2], depending on - version that was linked. - -2005.09.07 -- Version 2.0.2-TO1 - -* Added --topology directive. See man page. -* Added --redirect-gateway bypass-dhcp option to add a route - allowing DHCP packets to bypass the tunnel, when the - DHCP server is non-local. Currently only implemented - on Windows clients. -* Modified OpenVPN Service on Windows to declare the DHCP - client service as a dependency. -* Extended the plugin interface to allow plugins to declare - per-client constructor and destructor functions, to make - it simpler for plugins to maintain per-client state. - -2005.09.25 -- Version 2.0.3-rc1 - -* openvpn_plugin_abort_v1 function wasn't being properly - registered on Windows. -* Fixed a bug where --mode server --proto tcp-server --cipher none - operation could cause tunnel packet truncation. - -2005.08.25 -- Version 2.0.2 - -* No change from 2.0.2-rc1. - -2005.08.24 -- Version 2.0.2-rc1 - -* Fixed regression bug in Win32 installer, introduced in 2.0.1, - which incorrectly set OpenVPN service to autostart. -* Don't package source code zip file in Windows installer - in order to reduce the size of the installer. The source - zip file can always be downloaded separately if needed. -* Fixed bug in route.c in FreeBSD, Darwin, OpenBSD and NetBSD - version of get_default_gateway. Allocated socket for route - manipulation is never freed so number of mbufs continuously - grow and exhaust system resources after a while (Jaroslav Klaus). -* Fixed bug where "--proto tcp-server --mode p2p --management - host port" would cause the management port to not respond until - the OpenVPN peer connects. -* Modified pkitool script to be /bin/sh compatible (Johnny Lam). - -2005.08.16 -- Version 2.0.1 - -* Security Fix -- DoS attack against server when run with "verb 0" and - without "tls-auth". If a client connection to the server fails - certificate verification, the OpenSSL error queue is not properly - flushed, which can result in another unrelated client instance on the - server seeing the error and responding to it, resulting in disconnection - of the unrelated client (CAN-2005-2531). -* Security Fix -- DoS attack against server by authenticated client. - This bug presents a potential DoS attack vector against the server - which can only be initiated by a connected and authenticated client. - If the client sends a packet which fails to decrypt on the server, - the OpenSSL error queue is not properly flushed, which can result in - another unrelated client instance on the server seeing the error and - responding to it, resulting in disconnection of the unrelated client - (CAN-2005-2532). Credit: Mike Ireton. -* Security Fix -- DoS attack against server by authenticated client. - A malicious client in "dev tap" ethernet bridging mode could - theoretically flood the server with packets appearing to come from - hundreds of thousands of different MAC addresses, causing the OpenVPN - process to deplete system virtual memory as it expands its internal - routing table. A --max-routes-per-client directive has been added - (default=256) to limit the maximum number of routes in OpenVPN's - internal routing table which can be associated with a given client - (CAN-2005-2533). -* Security Fix -- DoS attack against server by authenticated client. - If two or more client machines try to connect to the server at the - same time via TCP, using the same client certificate, and when - --duplicate-cn is not enabled on the server, a race condition can - crash the server with "Assertion failed at mtcp.c:411" - (CAN-2005-2534). -* Fixed server bug where under certain circumstances, the client instance - object deletion function would try to delete iroutes which had never been - added in the first place, triggering "Assertion failed at mroute.c:349". -* Added --auth-retry option to prevent auth errors from being fatal - on the client side, and to permit username/password requeries in case - of error. Also controllable via new "auth-retry" management interface - command. See man page for more info. -* Added easy-rsa 2.0 scripts to the tarball in easy-rsa/2.0 -* Fixed bug in openvpn.spec where rpmbuild --define 'without_pam 1' - would fail to build. -* Implement "make check" to perform loopback tests (Matthias Andree). - -2005.07.21 -- Version 2.0.1-rc7 - -* Support LZO 2.01 which renamed its library to lzo2 (Matthias Andree). -* Include linux/types.h before checking for linux/errqueue.h (Matthias - Andree). - -2005.07.15 -- Version 2.0.1-rc6 - -* Commented out "user nobody" and "group nobody" in sample - client/server config files. -* Allow '@' character to be used in --client-config-dir - file names. - -2005.07.04 -- Version 2.0.1-rc5 - -* Windows version will log a for-further-info URL when - initialization sequence is completed with errors. -* Added DLOPEN_PAM parameter to plugin/auth-pam/Makefile - to control whether auth-pam plugin links to PAM via - dlopen or -lpam. By default, DLOPEN_PAM=1 so pre-existing - behavior should be preserved. DLOPEN_PAM=0 is the preferred - setting to link via -lpam, but DLOPEN_PAM=1 works around - a bug in SuSE 9.1 (and possibly other distros as well) - where the PAM modules are not linked with -lpam. See - thread on openvpn-devel for more discussion about this - patch (Simon Perreault). - -2005.06.15 -- Version 2.0.1-rc4 - -* Support LZO 2.00, including changes to configure script to - autodetect LZO version. - -2005.06.12 -- Version 2.0.1-rc3 - -* Fixed a bug which caused standard file handles to not be closed - after daemonization when --plugin and --daemon are used together, - and if the plugin initialization function forks (as does auth-pam - and down-root) (Simon Perreault). -* Added client-side up/down scripts in contrib/pull-resolv-conf - for accepting server-pushed "dhcp-option DOMAIN" and "dhcp-option DNS" - on Linux/Unix systems (Jesse Adelman). -* Fixed bug where if client-connect scripts/plugins were cascaded, - and one (but not all) of them returned an error status, there might - be cases where for an individual script/plugin, client-connect was - called but not client-disconnect. The goal of this fix is to - ensure that if client-connect is called on a given client instance, - then client-disconnect will definitely be called. A potential - complication of this fix is that when client-connect functions are - cascaded, it's possible that the client-disconnect function would - be called in cases where the related client-connect function returned - an error status. This fix should not alter OpenVPN behavior when - scripts/plugins are not cascaded. -* Changed the hard-to-reproduce "Assertion failed at fragment.c:312" - fatal error to a warning: "FRAG: outgoing buffer is not empty". - Need more info on how to reproduce this one. -* When --duplicate-cn is used, the --ifconfig-pool allocation - algorithm will now allocate the first available IP address. -* When --daemon and --management-hold are used together, - OpenVPN will daemonize before it enters the management hold state. - -2005.05.16 -- Version 2.0.1-rc2 - -* Modified vendor test in openvpn.spec file to match against - "Mandrakesoft" in addition to "MandrakeSoft". -* Using --iroute in a --client-config-dir file while in --dev tap - mode is not currently supported and will produce a warning - message. Fixed bug where in certain cases, in addition to - generating a warning message, this combination of options - would also produce a fatal assertion in mroute.c. -* Pass --auth-user-pass username to server-side plugin without - performing any string remapping (plugins, unlike scripts, - don't get any security benefit from string remapping). - This is intended to fix an issue with openvpn-auth-pam/pam_winbind - where backslash characters in a username ('\') were being remapped - to underscore ('_'). -* Updated OpenSSL DLLs in Windows build to 0.9.7g. -* Documented --explicit-exit-notify in man page. -* --explicit-exit-notify seconds parameter defaults to 1 if - unspecified. - -2005.04.30 -- Version 2.0.1-rc1 - -* Fixed bug where certain kinds of fatal errors after - initialization (such as port in use) would leave plugin - processes (such as openvpn-auth-pam) still running. -* Added optional openvpn_plugin_abort_v1 plugin function for - closing initialized plugin objects in the event of a fatal - error by main OpenVPN process. -* When the --remote list is > 1, and --resolv-retry is not - specified (meaning that it defaults to "infinite"), apply the - infinite timeout to the --remote list as a whole, but try each - list item only once before moving on to the next item. -* Added new --syslog directive which redirects output - to syslog without requiring the use of the --daemon or --inetd - directives. -* Added openvpn.spec option to allow RPM to be built with support - for passwords read from a file: - rpmbuild -tb [openvpn.x.tar.gz] --define 'with_password_save 1' - -2005.04.17 -- Version 2.0 - -* Fixed minor options string typo in options.c. - -2005.04.10 -- Version 2.0-rc21 - -* Change license description from "GPL Version 2 or (at your - option) any later version" to just "GPL Version 2". - -2005.04.04 -- Version 2.0-rc20 - -* Dag Wieers has put together an OpenVPN/LZO binary RPM set with - excellent distro/version coverage for RH/EL/Fedora, though - using his own SPEC. I modified openvpn.spec to follow some of - the same conventions such as putting sample scripts and doc - files in %doc rather than /usr/share/openvpn. -* Minor change to init scripts to run the user-defined script - /etc/openvpn/openvpn-startup (if it exists) before any OpenVPN - configs are started, and to run /etc/openvpn/openvpn-shutdown - after all OpenVPN configs have been stopped. The - openvpn-startup script can be used for stuff like - insmod tun.o, setting up firewall rules, or starting - ethernet bridges. - -2005.03.29 -- Version 2.0-rc19 - -* Omit additions of routes where the network and - gateway are equal and the netmask is 255.255.255.255. - This can come up if you are using both - server/ifconfig-pool and client-config-dir with - ifconfig-push static addresses for some subset of clients - which directly reference the server IP address as the - remote endpoint. - -2005.03.28 -- Version 2.0-rc18 - -* Packaged Windows installer with OpenSSL 0.9.7f. -* Built Windows installer with NSIS 2.06. - -2005.03.12 -- Version 2.0-rc17 - -* "MANAGEMENT: CMD" log file output will now only occur - at --verb 7 or greater. -* Added an optional name/value configuration list to - the openvpn-auth-pam plugin module argument list. See - plugin/auth-pam/README for documentation. This is necessary - in order for openvpn-auth-pam to work with queries generated - by arbitrary PAM modules. -* In both auth-pam and down-root plugins, in the forked process, - a read error on the parent process socket is no longer fatal. -* MandrakeSoft liblzo1 RPM only Provides for a 'liblzo1'. - A conditional test of the vendor has been added to - Require the appropriately named 'lzo' (liblzo1 / lzo). - (Tom Walsh - http://openhardware.net) - - -2005.02.20 -- Version 2.0-rc16 - -* Fixed bug introduced in rc13 where Windows service wrapper - would be installed with a startup type of Automatic. - This fix restores the previous behavior of installing - with a startup type of Manual. - -2005.02.19 -- Version 2.0-rc15 - -* Added warning when --keepalive is not used in a server - configuration. -* Don't include OpenSSL md4.h file if we are not building - NTLM proxy support (Waldemar Brodkorb). -* Added easy-rsa/build-key-pkcs12 and - easy-rsa/Windows/build-key-pkcs12.bat scripts - (Mathias Sundman). - -2005.02.16 -- Version 2.0-rc14 - -* Fixed small memory leak that occurs when --crl-verify - is used. -* Upgraded Windows installer and .nsi script to NSIS 2.05 - (Mathias Sundman). -* Changed #include backslash usage in cryptoapi.c to use - forward slashes instead (Gisle Vanem). -* Created easy-rsa/revoke-full to handle revocations in - a single step: (a) revoke crt, (b) regenerate CRL, and - (c) verify that revocation succeeded. -* Renamed easy-rsa/Windows/revoke-key to revoke-full so - that both *nix and Windows scripts are equivalent. - -2005.02.11 -- Version 2.0-rc13 - -* Improve human-readability of local/remote options - diff, when inconsistencies are present. -* For Windows easy-rsa, distribute vars.bat.sample and - openssl.cnf.sample, then copy them to their normal - filenames (without the .sample) when init-config.bat - is run. This is to prevent OpenVPN upgrades from - wiping out vars.bat and openssl.cnf edits. -* Modified service wrapper (Windows) to use a - case-insensitive search when scanning for .ovpn files - in \Program Files\OpenVPN\config. Prior versions - required an all-lower-case .ovpn file extension. -* Miscellaneous service wrapper code cleanup. -* If --user/--group is used on Windows, treat it - as a no-op with a warning (this makes it easier to - distribute the same client config file to Windows - and *nix users). -* Warn if --ifconfig-pool-persist is used with - --duplicate-cn. - -2005.02.05 -- Version 2.0-rc12 - -* Removed some debugging code inadvertently included - in rc11 which would print the --auth-user-pass - username/password provided by clients in the server - logfile. -* Client code for cycling through --remote list will - retry the last address which successfully authenticated - before moving on through the list. -* Windows installer will now install sample configuration - files in \Program Files\OpenVPN\sample-configs as well - as generate a start menu shortcut to this directory. -* Minor type change in buffer.[ch] to work around char-type - ambiguity bug. Caused management interface lock-ups on - ARM when building with armv4b-hardhat-linux-gcc 2.95.3. - -2005.02.03 -- Version 2.0-rc11 - -* Windows installer will now install easy-rsa directory - in \Program Files\OpenVPN -* Allow syslog facility to be controlled at compile time, - e.g. -DLOG_OPENVPN=LOG_LOCAL6 (P Kern). -* Changed certain shell scripts in distribution to use - #!/bin/sh rather than #!/bin/bash for better portability. -* If --ifconfig-pool-persist seconds parameter is 0, treat - persist file as an allocation of fixed IP addresses - (previous versions took IP-to-common-name associations - from this list as hints, not mandatory static allocations). -* Fixed bug on *nix where if --auth-user-pass and --log - were used together, the username prompt would be sent to - the log file rather than /dev/tty. -* Spurious text in openvpn.8 detected by doclifter - (Eric S. Raymond). -* Call closelog later on daemon kill so that process - exit message is written to syslog. - -2005.01.27 -- Version 2.0-rc10 - -* When ./configure is run with plugins enabled (the default), - check whether or not dlopen exists in libc before testing - for libdl. This is to fix an issue on FreeBSD and possibly - other OSes which bundle libdl functions in libc. -* On Windows, filter initial WSAEINVAL warning which occurs - on the initial read attempt of an unbound socket. -* The easy-rsa scripts build-key, build-key-pass, and - build-key-server will now chmod the .key file - to 0600. This is in addition to the fact the generated - keys directory has always been similarly protected - (Pete Harlan). - -2005.01.23 -- Version 2.0-rc9 - -* Fixed error "ROUTE: route addition failed using - CreateIpForwardEntry ..." on Windows when --redirect-gateway - is used over a RRAS internet link. -* When using --route-method exe on Windows, include the - gateway parameter on route delete commands (Mathias Sundman). -* Try not to do a hard reset (i.e. SIGHUP) when two - SIGUSR1 signals are received in close succession. -* If the push list tries to grow beyond its buffer capacity, - the resulting error will be non-fatal. -* To increase the push list capacity (must be done on both - client and server), increase TLS_CHANNEL_BUF_SIZE in - common.h (default=1024). - -2005.01.15 -- Version 2.0-rc8 - -* Fixed bug introduced in rc7 where options error - "--auth-user-pass requires --pull" might occur even - if --pull was correctly specified. -* Changed management interface code to bind once - to TCP socket, rather than rebinding after every - client disconnect. -* Added "disable" directive for client-config-dir - files. -* Windows binary install is now distributed with - OpenSSL 0.9.7e. -* Query the management interface for --http-proxy - username/password if authfile is set to "stdin". -* Added current OpenVPN version number to "Unrecognized - option or missing parameter" error message. -* Added "-extensions server" to "openssl req" command - in easy-rsa/build-key-server (Nir Yeffet). - -2005.01.10 -- Version 2.0-rc7 - -* Fixed bug in management interface which could cause - 100% CPU utilization in --proto tcp-server mode - on all *nix OSes except for Linux 2.6. -* --ifconfig-push now accepts DNS names as well as - IP addresses. -* Added sanity check errors when --pull or - --auth-user-pass is used in an incorrect mode. -* Updated man page entries for --client-connect and - --ifconfig-push. -* Added "String Types and Remapping" section to man - page to consisely document the way which OpenVPN - may convert certain types of characters in strings - to ('_'). -* Modified bridging description in HOWTO to emphasize - the fact that bridging allows Windows file and print - sharing without a WINS server (Charles Duffy). - -2004.12.20 -- Version 2.0-rc6 - -* Improved checking for epoll support in ./configure - to fix false positive on RH9 (Jan Just Keijser). -* Made the "MULTI TCP: I/O wait required blocking in - multi_tcp_action, action=7" error nonfatal and replaced - with "MULTI: Outgoing TUN queue full, dropped packet". - So far the issue only seems to occur on Linux 2.2 - in --mode server --proto tcp mode. It occurs when - the TUN/TAP driver locks up and refuses to accept - new packet writes for a second or more. -* Fixed bug where if a --client-config-dir file tried - to include another file using "config", and if that - include failed, OpenVPN would abort with a fatal - error. Now such inclusion failures will be logged - but are no longer fatal. -* Global changes to the way that packet buffer alignment - is handled. Previously we didn't care about alignment - and took care, when handling 16 and 32 bit words - in buffers, to always use alignment-safe transfers. - This approach appears to be inadequate on some - architectures such as alpha. The new approach is - to initialize packet buffers in a way that anticipates - how component structures will be allocated within - them, to maintain correct alignment. -* Added --dhcp-option DISABLE-NBT to disable NetBIOS - over TCP (Jan Just Keijser). -* Added --http-proxy-option directive for controlling - miscellaneous HTTP proxy options. -* Management state will no longer transition to "WAIT" - during TLS renegotiations. - -2004.12.16 -- Version 2.0-rc5 - -* The --client-config-dir option will now try to open - a default file called "DEFAULT" if no file matching - the common name of the incoming client was found. -* The --client-connect script/plugin can now veto client - authentication by returning a failure code. -* The --learn-address script/plugin can now prevent a - client-instance/address association from being learned - by returning a failure code. -* Changed RPM group in .spec file to Applications/Internet. - -2004.12.14 -- Version 2.0-rc4 - -* SuSE only -- Fixed interaction between openvpn.spec and - suse/openvpn.init where the .spec file was writing the - OpenVPN binary to a different location than where the - .init script was referencing it (Stefan Engel). -* Solaris only -- Split Solaris ifconfig command into two - parts (Jan Just Keijser). -* Some cleanup in add_option(). -* Better error checking on input dotted quad IP addresses. -* Verify that --push argument is quoted, if there is - more than one. -* More miscellaneous option sanity checks. - -2004.12.13 -- Version 2.0-rc3 - -* On Windows, when --log or --log-append is used, - save the original stderr for username and password - prompts. -* Fixed a bug introduced in the late 2.0 betas where - if a "verb" parameter >= 16 was used, it would be - ignored and the actual verb level would remain at 1. -* Fixed a bug mostly seen on OS X where --management-hold - or --management-query-passwords would cause the management - interface to be unresponsive to incoming client connections. -* Trigger an options error if one of the management-modifying - options is used without "management" itself. - -2004.12.12 -- Version 2.0-rc2 - -* Amplified warnings in documentation about possible - man-in-the-middle attack when clients do not properly - verify server certificate. Changes to easy-rsa README, - FAQ, HOWTO, man page, and sample client config file. -* Added a warning message if --tls-client or --client - is used without also specifying one of either - --ns-cert-type, --tls-remote, or --tls-verify. -* status_open() fixes for MSVC builds (Blaine Fleming). -* Fix attempt of "ntlm.c:55: error: `des_cblock' undeclared" - compiler error which has been reported on some platforms. -* The openvpn.spec file for rpmbuild has several - new build-time options. See comments in the file. -* Plugins are now built and packaged in the RPM and - will be saved in /usr/share/openvpn/plugin/lib. -* Added --management-hold directive to start OpenVPN - in a hibernating state until released by the - management interface. Also added "hold" command - to the management interface. - -2004.12.07 -- Version 2.0-rc1 - -* openvpn.spec workaround for SuSE confusion regarding - /etc/init.d vs. /etc/rc.d/init.d (Stefan Engel). - -2004.12.05 -- Version 2.0-beta20 - -* The ability to read --askpass and --auth-user-pass - passwords from a file has been disabled by default. - To re-enable, use ./configure --enable-password-save. -* Added additional pre-connected states to management - interface. See management/management-notes.txt - for more info. -* State history is now recorded by the management - interface, and the "state" command now works like - the log or echo commands. -* State history and real-time state change notifications - are now prepended with an integer unix timestamp. -* Added --http-proxy-timeout option, previously - the timeout was hardcoded to 5 seconds. - -2004.12.02 -- Version 2.0-beta19 - -* Fixed bug in management interface line termination - where output lines incorrectly contained a \00 char - after the customary \0d \0a. -* Fixed bug introduced in beta18 where Windows version - would segfault on options errors. -* Fixed bug in management interface where an empty - quoted string ("") entered as a parameter would cause - a segfault. -* Fixed bug where --resolv-retry was not working - properly with multiple --remote hosts. -* Added additional ./configure options to reduce - executable size for embedded applications. - See ./configure --help. - -2004.11.28 -- Version 2.0-beta18 - -* Added management interface. See new --management-* - options or the full management interface documentation - in management/management-notes.txt in the tarball. - Management interface inclusion can be disabled by - ./configure --disable-management. -* Added two new plugin modules: auth-pam and down-root. - Auth-pam supports pam-based authentication using a - split privilege execution model, while down-root enables - a down script to be executed with root privileges, even - when --user/--group is used to drop root privileges. - See the plugin directory in the tarball for READMEs, - source code, and Makefiles. -* Plugin developers should note that some changes were - made to the plugin interface since beta17. See - openvpn-plugin.h for details. - Plugin interface inclusion can be disabled with - ./configure --disable-plugins -* Added easy-rsa/build-key-server script which will - build a certificate with with nsCertType=server. -* Added --ns-cert-type option for verification - of nsCertType field in peer certificate. -* If --fragment n is specified and --mssfix is specified - without a parameter, default --mssfix to n. This restores - the 1.6 behavior when using --mssfix without a parameter. -* Fixed SSL context initialization bug introduced in beta14 - where this error might occur on restarts: "Cannot load - certificate chain ... PEM_read_bio:no start line". - -2004.11.11 -- Version 2.0-beta17 - -* Changed default port number to 1194 per IANA official - port number assignment. -* Added --plugin directive which allows compiled - modules to intercept script callbacks. See - plugin folder in tarball for more info. -* Fixed bug introduced in beta12 where --key-method 1 - authentications which should have succeeded would fail. -* Ignore SIGUSR1 during DNS resolution. -* Added SuSE support to openvpn.spec (Umberto Nicoletti). -* Fixed --cryptoapicert SUBJ: parsing bug (Peter 'Luna' - Runestig). - -2004.11.07 -- Version 2.0-beta16 - -* Modified sample-scripts/auth-pam.pl to get username - and password from OpenVPN via a file rather than - via environmental variables. -* Added bytes_sent and bytes_received environmental - variables to be set prior to client-disconnect script. -* Changed client virtual IP derivation precedence: - (1) use --ifconfig-push directive from --client-connect - script, (2) use --ifconfig-push directive from - --client-config-dir, and (3) use --ifconfig-pool - address. -* If a --client-config-dir file specifies --ifconfig-push, - it will be visible to the --client-connect-script in - the ifconfig_pool_remote_ip environmental variable. -* For tun-style tunnels, the ifconfig_pool_local_ip - environmental variable will be set, while for - tap-style tunnels, the ifconfig_pool_netmask variable - will be set. -* Added intelligence to autoconf script to test - compiler for the accepted form of zero-length arrays. -* Fixed a bug introduced in beta12 where --ip-win32 - netsh would fail if --dev-node was not explicitly - specified. -* --ip-win32 netsh will now work on hidden adapters. -* Fix attempt of "Assertion failed at crypto.c:149". - This assertion has also been reported on 1.x with a - slightly different line number. The fix is twofold: - (1) In previous releases, --mtu-test may trigger this - assertion -- this bug has been fixed. (2) If something - else causes the assertion to be thrown, don't panic, - just output a nonfatal warning to the log and drop - the packet which generated the error. -* Support TAP interfaces on Mac OS X (Waldemar Brodkorb). -* Added --echo directive. -* Added --auth-nocache directive. - -2004.10.28 -- Version 2.0-beta15 - -* Changed environmental variable character classes - so that names must consist of alphanumeric or - underbar chars and values must consist of printable - characters. Illegal chars will be deleted. - Versions prior to 2.0-beta12 were more restrictive - and would map spaces to '.'. -* On Windows, when the TAP adapter fails to - initialize with the correct IP address, output - "Initialization Sequence Completed with Errors" - to the console or log file. -* Added a warning when user/group/chroot is used - without persist-tun and persist-key. -* Added cryptoapi.[ch] to tarball and source zip. -* --tls-remote option now works with common name - prefixes as well as with the full X509 subject - string. This is a useful alternative to using - a CRL on the client. -* common names associated with a static - --ifconfig-push setting will no longer leave - any state in the --ifconfig-pool-persist file. -* Hard TLS errors (TLS handshake failed) will now - trigger either a SIGUSR1 signal by default - or SIGTERM (if --tls-exit is specified). In TCP - mode, all TLS errors are considered to be hard. - In server mode, the signal will be local to the - client instance. -* Added method parameter to --auth-user-pass-verify - directive to select whether username/password - is passed to script via environment or a temporary - file. -* Added --status-version option to control format - of --status file. The --mode server - --status-version 2 format now includes a line - type token, the virtual IP address is shown - in the client list (even in --dev tap mode), - and the integer time_t value is shown anywhere - an ascii-formatted time/date is also shown. -* Added --remap-usr1 directive which can be used - to control whether internally or externally - generated SIGUSR1 signals are remapped to - SIGHUP (restart without persisting state) or - SIGTERM (exit). -* When running as a Windows service (using - --service option), check the exit event before - and after reading one line of input from - stdin, when reading username/password info. -* For developers: Extended the --gremlin function - to better stress-test the new 2.0 features, - added Valgrind support on Linux and Dmalloc - support on Windows. - -2004.10.19 -- Version 2.0-beta14 - -* Fixed a bug introduced in Beta12 that would occur - if you use a --client-connect script without also - defining --tmp-dir. -* Fixed a bug introduced in Beta12 where a learn-address - script might segfault on the delete method. -* Added Crypto API support in Windows version via - the --cryptoapicert option (Peter 'Luna' Runestig). - -2004.10.18 -- Version 2.0-beta13 - -* Fixed an issue introduced in Beta12 where the private - key password would not be prompted for unless --askpass - was explicitly specified in the config. - -2004.10.17 -- Version 2.0-beta12 - -* Added support for username/password-based authentication. - Clients can now authentication themselves with the server - using either a certificate, a username/password, or both. - New directives: --auth-user-pass, --auth-user-pass-verify, - --client-cert-not-required, and --username-as-common-name. -* Added NTLM proxy patch (William Preston). -* Added --ifconfig-pool-linear server flag to allocate - individual tun addresses for clients rather than /30 - subnets (won't work with Windows clients). -* Modified --http-proxy code to cache username/password - across restarts. -* Modified --http-proxy code to read username/password - from the console when the auth file is given as "stdin". -* Modified --askpass to take an optional filename argument. -* --persist-tun and --persist-key now work in client mode - and can be pushed to clients as well. -* Added --ifconfig-pool-persist directive, to maintain - ifconfig-pool info in a file which is persistent across - daemon instantiations. -* --user and --group privilege downgrades as well as - --chroot now also work in client mode (the - dowgrade/chroot will be delayed until the initialization - sequence is completed). -* Added --show-engines standalone directive to show - available OpenSSL crypto accelerator engine support. -* --engine directive now accepts an optional engine-ID - parameter to control which engine is used. -* "Connection reset, restarting" log message now shows - which client is being reset. -* Added --dhcp-pre-release directive in Windows version. -* Second parm to --ip-win32 can be "default", e.g. - --ip-win32 dynamic default 60. -* Fixed documentation bug regarding environmental - variable settings for --ifconfig-pool IP addresses. - The correct environmental variable names are: - ifconfig_pool_local_ip and ifconfig_pool_remote_ip. -* ifconfig_pool_local_ip and ifconfig_pool_remote_ip - environmental variables are now passed to the - client-disconnect script. -* In server mode, environmental variables are now scoped - according to the client they are associated with, - to solve the problem of "crosstalk" between different - client's environmental variable sets. -* Added --down-pre flag to cause --down script to be - called before TUN/TAP close (rather than after). -* Added --tls-exit flag which will cause OpenVPN - to exit on any TLS errors. -* Don't push a route to a client if it exactly - matches an iroute (this lets you push routes to - all clients, and OpenVPN will automatically remove - the route from the route push list only for that client - which the route actually belongs to). -* Made '--resolv-retry infinite' the default. - --resolv-retry can be disabled by using a parameter of 0. -* For clients which plan to pull config info from server, - set an initial default ping-restart of 60 seconds. -* Optimized mute code to lessen the load on the processor - when messages are being muted at a higher frequency. -* Made route log messages non-mutable. -* Silence the Linux "No buffer space available" message. -* Added miscellaneous additional option sanity checks. -* Added Windows version of easy-rsa scripts in - easy-rsa/Windows directory (Andrew J. Richardson). -* Added NetBSD route patch (Ed Ravin). -* Added OpenBSD patch for TAP + --redirect-gateway - (Waldemar Brodkorb). -* Directives which prompt for a username and/or password - will now work with --daemon (OpenVPN will prompt - before forking). -* Warn if CRL is from a different issuer than the - issuer of the peer certificate (Bernhard Weisshuhn). -* Changed init script chkconfig parameters to start - OpenVPN daemon(s) before NFS. -* Bug fix attempt of "too many I/O wait events" which occurs - on OSes which prefer select() over poll() such as Mac OS X. -* Added --ccd-exclusive flag. This flag will require, as a - condition of authentication, that a connecting client has - a --client-config-dir file. -* TAP-Win32 open code will attempt to open a free adapter - if --dev-node is not specified (Mathias Sundman). -* Resequenced --nice and --chroot ordering so that --nice - occurs first. -* Added --suppress-timestamps flag (Charles Duffy). -* Source code changes to allow compilation by MSVC - (Peter 'Luna' Runestig). -* Added experimental --fast-io flag which optimizes - TUN/TAP/UDP writes on non-Windows systems. - -2004.08.18 -- Version 2.0-beta11 - -* Added --server, --server-bridge, --client, and - --keepalive helper directives. See client.conf - and server.conf in sample-config-files for sample - configurations which use the new directives. -* On Windows, added --route-method to control - whether IP Helper API or route.exe is used - to add/delete routes. -* On Windows, added a second parameter to - --route-delay to control the maximum time period - to wait for the TAP-Win32 adapter to come up - before adding routes. -* Fixed bug in Windows version where configurations - which omit --ifconfig might fail to recognize when - the TAP adapter is up. -* Proxy connection failures will now retry according - to the --connect-retry parameter. -* Fixed --dev null handling on Windows so that TLS - loopback test described in INSTALL file works - correctly on Windows. -* Added "Initialization Sequence Completed" message - after all initialization steps have been completed - and the VPN can be considered "up". -* Better sanity-checking on --ifconfig-pool parameters. -* Added --tcp-queue-limit option to control - TUN/TAP -> TCP socket overflow. -* --ifconfig-nowarn flag will now silence general - warnings about possible --ifconfig address - conflicts, including the warning about --ifconfig - and --remote addresses being in same /24 subnet. -* Fixed case where server mode did not correctly - identify certain types of ethernet multicast packets - (Marcel de Kogel). -* Added --explicit-exit-notify option (experimental). - -2004.08.02 -- Version 2.0-beta10 - -* Fixed possible reference after free of option strings - after a restart, bug was introduced in beta8. -* Fixed segfault at route.c:919 in the beta9 - Windows version that was being caused by indirection - through a NULL pointer. -* Mistakenly built debug version of TAP-Win32 driver - for beta9. Beta10 has correct release build. - -2004.07.30 -- Version 2.0-beta9 - -* Fixed --route issue on Windows that was introduced with - the new beta8 route implementation based on the - IP Helper API. - -2004.07.27 -- Version 2.0-beta8 - -* Added TCP support in server mode. -* Added PKCS #12 support (Mathias Sundman). -* Added patch to make revoke-crt and make-crl work - seamlessly within the easy-rsa environment (Jan Kiszka). -* Modified --mode server ethernet bridge code to forward - special IEEE 802.1d MAC Groups, i.e. 01:80:C2:XX:XX:XX. -* Added --dhcp-renew and --dhcp-release flags to Windows - version. Normally DHCP renewal and release on the TAP - adapter occurs automatically under Windows, however - if you set the TAP-Win32 adapter Media Status property - to "Always Connected", you may need these flags. -* Added --show-net standalone flag to Windows version to - show OpenVPN's view of the system adapter and routing - tables. -* Added --show-net-up flag to Windows version to output - the system routing table and network adapter list to - the log file after the TAP-Win32 adapter has been brought - up and any routes have been added. -* Modified Windows version to add routes using the IP Helper - API rather than by calling route.exe. -* Fixed bug where --route-up script was not being called - if no --route options were specified. -* Added --mute-replay-warnings to suppress packet replay - warnings. This is a common false alarm on WiFi nets. -* Added "def1" flag to --redirect-gateway option to override - the default gateway by using 0.0.0.0/1 and 128.0.0.0/1 - rather than 0.0.0.0/0. This has the benefit of overriding - but not wiping out the original default gateway. - (Thanks to Jim Carter for pointing out this idea). -* You can now run OpenVPN with a single config file argument. - For example, you can now say "openvpn config.conf" - rather than "openvpn --config config.conf". -* On Windows, made --route and --route-delay more adaptive - with respect to waiting for interfaces referenced by the - route destination to come up. Routes added by --route - should now be added as soon as the interface comes up, - rather than after an obligatory 10 second delay. The - way this works internally is that --route-delay now - defaults to 0 on Windows. Previous versions would - wait for --route-delay seconds then add the routes. - This version will wait --route-delay seconds and then - test the routing table at one second intervals for the - next 30 seconds and will not add the routes until they - can be added without errors. -* On Windows, don't setsockopt SO_SNDBUF or SO_RCVBUF by - default on TCP/UDP socket in light of reports that this - action can have undesirable global side effects on the - MTU settings of other adapters. These parameters can - still be set, but you need to explicitly specify - --sndbuf and/or --rcvbuf. -* Added --max-clients option to limit the maximum number - of simultaneously connected clients in server mode. -* Added error message to illuminate shell escape gotcha when - single backslashes are used in Windows path names. -* Added optional netmask parm to --ifconfig-pool. -* Fixed bug where http-proxy connect retry attempts were - incorrectly going to the remote OpenVPN server, - not to the HTTP proxy server. - -2004.06.29 -- Version 2.0-beta7 - -* Fixed bug in link_socket_verify_incoming_addr() which - under certain circumstances could have caused --float - behavior even if --float was not specified. -* --tls-auth option now works with --mode server. - All clients and the server should use the same - --tls-auth key when operating in client/server mode. -* Added --engine option to make use of OpenSSL-supported - crypto acceleration hardware. -* Fixed some high verbosity print format size issues - in event.c for 64 bit platforms (Janne Johansson). -* Made failure to open --log or --log-append file - a non-fatal error. - -2004.06.23 -- Version 2.0-beta6 - -* Fixed Windows installer to intelligently put - up a reboot dialog only if tapinstall tells - us that it's really necessary. -* Fixed "Assertion failed at fragment.c:309" - bug when --mode server and --fragment are used - together. -* Ignore HUP, USR1, and USR2 signals during - initialization. Prior versions would abort. -* Fixed bug on OS X: "Assertion failed at event.c:406". -* Added --service option to Windows version, for use - when OpenVPN is being programmatically instantiated - by another process (see man page for info). -* --log and --log-append options now work on Windows. -* Update OpenBSD INSTALL notes (Janne Johansson). -* Enable multicast on tun interface when running on - OpenBSD (Pavlin Radoslavov). -* Fixed recent --test-crypto breakage, where options - such as --cipher were not being parsed correctly. -* Modified options compatibility string by removing - ifconfig substring if it is empty. Incremented - options compatibility string version number to 4. -* Fixed typo in --tls-timeout option parsing - (Mikael Lonnroth). - -2004.06.13 -- Version 2.0-beta5 - -* Fixed rare --mode server crash that could occur - if data was being routed to a client at - high bandwidth at the precise moment that the - client instance object on the server was being - deleted. -* Fixed issue on machines which have epoll.h and - the epoll_create glibc call defined, but which - don't actually implement epoll in the kernel. - OpenVPN will now gracefully fall back to the - poll API in this case. -* Fixed Windows bug which would cause the following - error in a --mode server --dev tap configuration: - "resource limit WSA_MAXIMUM_WAIT_EVENTS has been - exceeded". -* Added CRL (certificate revocation list) management - scripts to easy-rsa directory (Jon Bendtsen). -* Do a better job of getting the ifconfig component - of the options consistency check to work correctly - when --up-delay is used. -* De-inlined some functions which were too complex - to be inlined anyway with gcc. -* If a --dhcp-option option is pushed to a non-windows - client, the option will be saved in the client's - environment before the --up script is called, under - the name "foreign_option_{n}". -* Added --learn-address script (see man page) which - allows for firewall access through the VPN to be - controlled based on the client common name. -* In mode --server mode, when a client connects to - the server, the server will disconnect any - still-active clients which use the same common - name. Use --duplicate-cn flag to revert to - previous behavior of allowing multiple clients - to concurrently connect with the same common name. - -2004.06.08 -- Version 2.0-beta4 - -* Fixed issue with beta3 where Win32 service wrapper - was keying off of old TAP HWID as a dependency. To - ensure that the new service wrapper is correctly - installed, the Windows install script will uninstall - the old wrapper before installing the new one, - causing a reset of service properties. -* Fixed permissions issue on --status output file, - with default access permissions of owner read/write - only (default permissions can be changed of course with - chmod). - -2004.06.05 -- Version 2.0-beta3 - -* More changes to TAP-Win32 driver's INF file which - affects the placement of the driver in the Windows - device namespace. This is done to work around an - apparent bug in Windows when short HWIDs are used, - and will also ease the upgrade from 1.x to 2.0 by - reducing the chances that a reboot will be needed - on upgrade. Like beta2, this upgrade will - delete existing TAP-Win32 interfaces, and reinstall - a single new interface with default properties. -* Major rewrite of I/O event wait layer in the style - of libevent. This is a precursor to TCP support - in --mode server. -* New feature: --status. Outputs a SIGUSR2-like - status summary to a given file, updated once - per n seconds. The status file is comma delimited - for easy machine parsing. -* --ifconfig-pool now remembers common names and - will try to assign a consistent IP to a given - common name. Still to do: persist --ifconfig-pool - memory across restarts by saving state in file. -* Fixed bug in event timer queue which could cause - recurring timer events such as --ping to not - correctly schedule again after firing. This in - turn would cause spurrious ping restarts and possible - connection outages. Thanks to Denis Vlasenko for - tracking this down. -* Possible fix to reported bug where --daemon argument - was not printing to syslog correctly after restart. -* Fixed bug where pulling --route or --dhcp-option - directives from a server would problematically - interact with --persist-tun on the client. -* Updated contrib/multilevel-init.patch (Farkas Levente). -* Added RPM build option to .spec and .spec.in files - to optionally disable LZO inclusion (Ian Pilcher). -* The latest MingW runtime and headers define - 'ssize_t', so a patch is needed (Gisle Vanem). - -2004.05.14 -- Version 2.0-beta2 - -* Fixed signal handling bug in --mode server, where - SIGHUP and SIGUSR1 were treated as SIGTERM. -* Changed the TAP-Win32 HWID from "TAP" to "TAPDEV". - Apparently the larger string may work around - a problem where the TAP adapter is sometimes missing - from the network connections panel, especially under - XP SP2. Also note that installing this upgrade will - uninstall any pre-existing TAP-Win32 adapters, and then - install a single new adapter, meaning that old adapter - properties will be lost. Thanks to Md5Chap for solving - this one. -* For --mode server --dev tap, the options --ifconfig and - --ifconfig-pool are now optional. This allows address - assignment via DHCP or use of a TAP VPN without - IP support, as has always been possible with 1.x. -* Fixed bug where --ifconfig may not work correctly on - Linux 2.2. -* Added 'local' flag to --redirect-gateway for use on - networks where both OpenVPN daemons are connected - to a shared subnet, such as wireless. - -2004.05.09 -- Version 2.0-beta1 - -* Unchanged from test29 except for version number - upgrade. - -2004.05.08 -- Version 2.0-test29 - -* Modified --dev-node on Windows to accept a TAP-Win32 - GUID name. In addition, --show-adapters will now - display the high-level name and GUID of each adapter. - This is an attempt to work around an issue in Windows - where sometimes the TAP-Win32 adapter installs correctly - but has no icon in the network connections control - panel. In such cases, being able to specify - --dev-node {TAP-GUID} can work around the missing icon. - -2004.05.07 -- Version 2.0-test28 - -* Fixed bug which could cause segfault on program - shutdown if --route and --persist-tun are used - together. - -2004.05.06 -- Version 2.0-test27 - -* Fixed bug in close_instance() which might cause - memory to be accessed after it had already been freed. -* Fixed bug in verify_callback() that might have - caused uninitialized data to be referenced. -* --iroute now allows full CIDR subnet routing. -* In "--mode server --dev tun" usage, source addresses - on VPN packets coming from a particular client must - be associated with that client in the OpenVPN internal - routing table. - -2004.04.28 -- Version 2.0-test26 - -* Optimized broadcast path in multi-client mode. -* Added socket buffer size options --rcvbuf & --sndbuf. -* Configure Linux tun/tap driver to use a more sensible - txqueuelen default. Also allow explicit setting - via --txqueuelen option (Harald Roelle). -* The --remote option now allows the port number - to be specified as the second parameter. If - unspecified, the port number defaults to the - --rport value. -* Multiple --remote options on the client can now be - specified for load balancing and failover. The - --remote-random flag can be used to initially randomize - the --remote list for basic load balancing. -* If a remote DNS name resolves to multiple DNS addresses, - one will be chosen by random as a kind of basic - load-balancing feature if --remote-random is used. -* Added --connect-freq option to control maximum - new connection frequency in multi-client mode. -* In multi-client mode, all syslog messages associated - with a specific client now include a client-ID prefix. -* For Windows, use a gettimeofday() function based - on QueryPerformanceCounter (Derek Burdick). -* Fixed bug in interaction between --key-method 2 - and DES ciphers, where dynamic keys would be generated - with bad parity and then be rejected. - -2004.04.17 -- Version 2.0-test24 - -* Reworked multi-client broadcast handling. - -2004.04.13 -- Version 2.0-test23 - -* Fixed bug in --dev tun --client-to-client routing. -* Fixed a potential deadlock in --pull. -* Fixed a problem with select() usage which could - cause a repeating sequence of "select : Invalid - argument (code=22)" - -2004.04.11 -- Version 2.0-test22 - -* Fixed bug where --mode server + --daemon was - prematurely closing syslog connection. -* Added support for --redirect-gateway on Mac OS X - (Jeremy Apple). -* Minor changes to TAP-Win32 driver based on feedback - from the NDISTest tool. - -2004.04.11 -- Version 2.0-test21 - -* Optimizations in multi-client server event loop. - -2004.04.10 -- Version 2.0-test20 - -* --mode server capability now works with either tun - or tap interfaces. When used with tap interfaces, - OpenVPN will internally bridge all client tap - interfaces with the server tap interface. -* Connecting clients can now have a client-specific - configuration on the server, based on the client - common name embedded in the client certificate. - See --client-config-dir and --client-connect. - These options can be used to configure client-specific - routes. -* Added an option --client-to-client that enables - internal client-to-client routing or bridging. - Otherwise, clients will only "see" the server, - not other connected clients. -* Fixed bug in route scheduling which would have caused - --mode server to not work on Windows in test18 - and test19 with the sample config file. -* Man page is up to date with all new options. -* OpenVPN 2.0 release notes on web site updated - with tap-style tunnel examples. - -2004.04.02 -- Version 2.0-test19 - -* Fixed bug where routes pushed from server were - not working correctly on Windows clients. -* Added Mac OS X route patch (Jeremy Apple). - -2004.03.30 -- Version 2.0-test18 - -* Minor fixes + Windows self-install modified - to use OpenSSL 0.9.7d. - -2004.03.29 -- Version 2.0-test17 - -* Fixed some bugs related to instance timeout and deletion. -* Extended --push/--pull option to support additional - option classes. - -2004.03.28 -- Version 2.0-test16 - -* Successful test of --mode udp-server, --push, - --pull, and --ifconfig-pool with server on - Linux 2.4 and clients on Linux and Windows. - -2004.03.25 -- Version 2.0-test15 - -* Implemented hash-table lookup of client instances - based either on remote UDP address/port or remote - ifconfig endpoint. -* Implemented a randomized binary tree based - scheduler for scalably scheduling a large number - of client instance events. Uses the treap - data structure and node rotation algorithm - to keep the tree balanced. -* Initial implementation of ifconfig-pool. -* Made --key-method 2 the default. - -2004.03.20 -- Version 2.0-test14 - -* Implemented --push and --pull. - -2004.03.20 -- Version 2.0-test13 - -* Reduced struct tls_multi and --single-session - memory footprint. -* Modified --single-session flag to be used - in multi-client UDP server client instances. - -2004.03.19 -- Version 2.0-test12 - -* Added the key multi-client UDP server options, - --mode, --push, --pull, and --ifconfig-pool. -* Revamped GC (garbage collection) code to not rely - on any global data. -* Modifications to thread.[ch] to allow a more - flexible thread model. - -2004.03.16 -- Version 2.0-test11 - -* Moved all timer code to interval.h, added new file - interval.c. -* Fixed missing include. - -2004.03.16 -- Version 2.0-test10 - -* More TAP-Win32 fixes. -* Initial debugging and testing of multi.[ch]. - -2004.03.14 -- Version 2.0-test9 - -* Branch merge with 1.6-rc3 -* More point-to-multipoint work in multi.[ch]. -* Major TAP-Win32 driver restructuring to use - NdisMRegisterDevice instead of - IoCreateDevice/IoCreateSymbolicLink. -* Changed TAP-Win32 symbolic links to use \DosDevices\Global\ - pathname prefix. -* In the majority of cases, TAP-Win32 should now be - able to install and uninstall on Win2K without requiring - a reboot. -* TAP-Win32 MAC address can now be explicitly set in the - adapter advanced properties page. - -2004.03.04 -- Version 2.0-test8 - -* Branch merge with 1.6-rc2. - -2004.03.03 -- Version 2.0-test7 - -* Branch merge with 1.6-rc1.2. - -2004.03.02 -- Version 2.0-test6 - -* Branch merge with 1.6-rc1. - -2004.03.02 -- Version 2.0-test5 - -* Move Socks5 UDP header append/remove to socks.c, and is - called from forward.c. -* Moved verify statics from ssl.c into struct tls_session. -* Wrote multi.[ch] to handle top level of point-to-multipoint - mode. -* Wrote some code to allow a struct link_socket in a child context - to be slaved to the parent context. -* Broke up packet read and process functions in forward.c - (from socket or tuntap) into separate functions for read - and process, so that point-to-point and point-to-multipoint can - share the same code. -* Expand TLS control channel to allow the passing of configuration - commands. -* Wrote mroute.[ch] to handle internal packet routing for - point-to-multipoint mode. - -2004.02.22 -- Version 2.0-test3 - -* Initial work on UDP multi-client server. -* Branch merge of 1.6-beta7 - -2004.02.14 -- Version 2.0-test2 - -* Refactorization of openvpn.c into openvpn.[ch] - init.[ch] forward.[ch] forward-inline.h - occ.[ch] occ-inline.h ping.[ch] ping-inline.h - sig.[ch]. Created a master per-tunnel - struct context in openvpn.h. -* Branch merge of 1.6-beta6.2 - -2003.11.06 -- Version 2.0-test1 - -* Initial testbed for 2.0. - -2004.05.09 -- Version 1.6.0 - -* Unchanged from 1.6-rc4 except for version number - upgrade. - -2004.04.01 -- Version 1.6-rc4 - -* Made minor customizations to devcon and - renamed as tapinstall.exe for Windows version. -* Fixed "storage size of `iv' isn't known" build - problem on FreeBSD. -* OpenSSL 0.9.7d bundled with Windows self-install. - -2004.03.13 -- Version 1.6-rc3 - -* Minor Windows fixes for --ip-win32 dynamic, relating to - the way the TAP-Win32 driver responds to a DHCP request - from the Windows DHCP client. -* The net_gateway environmental variable wasn't being - set correctly for called scripts (Paul Zuber). -* Added code to determine the default gateway on FreeBSD, - allowing the --redirect-gateway option to work - (Juan Rodriguez Hervella). - -2004.03.04 -- Version 1.6-rc2 - -* Fixed bug in Windows version where the NetBIOS node-type - DHCP option might have been passed even if it was not - specified. -* Fixed bug in Windows version introduced in 1.6-rc1, where - DHCP timeout would be set to 0 seconds if --ifconfig option - was used and --ip-win32 option was not explicitly specified. -* Added some new --dhcp-option types for Windows version. - -2004.03.02 -- Version 1.6-rc1 - -* For Windows, make "--ip-win32 dynamic" the default. -* For Windows, make "--route-delay 10" the default - unless --ip-win32 dynamic is not used or --route-delay - is explicitly specified. -* L_TLS mutex could have been left in a locked state - for certain kinds of TLS errors. - -2004.02.22 -- Version 1.6-beta7 - -* Allow scheduling priority increase (--nice) together - with UID/GID downgrade (--user/--group). -* Code that causes SIGUSR1 restart on TLS errors in TCP - mode was not activated in pthread builds. -* Save the certificate serial number in an environmental - variable called tls_serial_{n} prior to calling the - --tls-verify script. n is the current cert chain level. -* Added NetBSD IPv6 tunnel capability (also requires - a kernel patch) (Horst Laschinsky). -* Fixed bug in checking the return value of the nice() - function (Ian Pilcher). -* Bug fix in new FreeBSD IPv6 over TUN code which was - originally added in 1.6-beta5 (Nathanael Rensen). -* More Socks5 fixes -- extended the struct frame - infrastructure to accomodate proxy-based encapsulation - overhead. -* Added --dhcp-option to Windows version for setting - adapter properties such as WINS & DNS servers. -* Use a default route-delay of 5 seconds when - --ip-win32 dynamic is specified (only applicable when - --route-delay is not explicitly specified). -* Added "log_append" registry variable to control - whether the OpenVPN service wrapper on Windows - opens log files in append (log_append="1") or - truncate (log_append="0") mode. The default - is truncate. - -2004.02.05 -- Version 1.6-beta6 - -* UDP over Socks5 fix to accomodate Socks5 encapsulation - overhead (Christof Meerwald). -* Minor --ip-win32 dynamic tweaks (use long lease time, - invalidate existing lease with DHCPNAK). - -2004.02.01 -- Version 1.6-beta5 - -* Added Socks5 proxy support (Christof Meerwald). -* IPv6 tun support for FreeBSD (Thomas Glanzmann). -* Special TAP-Win32 debug mode for Windows self-install that was - enabled in beta4 is now turned off. -* Added some new Solaris notes to INSTALL (Koen Maris). -* More work on --ip-win32 dynamic. - -2004.01.27 -- Version 1.6-beta4 - -* For this beta, the Windows self-install is a debug version - and will run slower -- use only for testing. -* Reverted the --ip-win32 default back to 'ipapi' - from 'dynamic'. -* Added the offset parameter to '--ip-win32 dynamic' which - can be used to control the address of the masqueraded - DHCP server which replies to Windows DHCP requests. -* Added a wait/nowait option to --inetd (nowait can only - be used with TCP sockets, TLS authentication, and over - a bridged configuration -- see FAQ for more info) - (Stefan `Sec` Zehl). -* Added a build-time capability where TAP-Win32 driver - debug messages can be output by OpenVPN at --verb 6 - or higher. - -2004.01.20 -- Version 1.6-beta2 - -* Added ./configure --enable-iproute2 flag which - uses iproute2 instead of route + ifconfig -- - this is necessary for the LEAF Linux distro - (Martin Hejl). -* Added renewal-time and rebind-time to set of - DHCP options returned by the TAP-Win32 driver when - "--ip-win32 dynamic" is used. - -2004.01.14 -- Version 1.6-beta1 - -* Fixed --proxy bug that sometimes caused plaintext - control info generated by the proxy prior to http - CONNECT method establishment to be incorrectly - parsed as OpenVPN data. -* For Windows version, implemented the - "--ip-win32 dynamic" method and made it the default. - This method sets the TAP-Win32 adapter IP address - and netmask by replying to the kernel's DHCP queries. - See the man page for more detailed info. -* Added --connect-retry parameter which controls - the time interval (in seconds) between connect() - retries when --proto tcp-client is used. Previously, - this value was hardcoded to 5 seconds, and still - defaults as such. -* --resolv-retry can now be used with a parameter - of "infinite" to retry indefinitely. -* Added SSL_CTX_use_certificate_chain_file() to ssl.c - for support of multi-level certificate chains - (Sten Kalenda). -* Fixed --tls-auth incompatibility with 1.4.x and earlier - versions of OpenVPN when the passphrase file is an - OpenVPN static key file (as generated by --genkey). -* Added shell-escape support in config files using - the backslash character ("\") so that (for example) - double quotes can be passed to the shell. -* Added "contrib" subdirectory on tarball, source zip, - and CVS containing user-submitted contributions. -* Added an optional patch to the Redhat init script to - allow the configuration file directory to be a - multi-level directory hierarchy (Farkas Levente). - See contrib/multilevel-init.patch -* Added some scripts and documentation on using - Linux "fwmark" iptables rules to enable - fine-grained routing control over the VPN - (Sean Reifschneider, ). - See contrib/openvpn-fwmarkroute-1.00 - -2003.11.20 -- Version 1.5.0 - -* Minor documentation changes. - -2003.11.04 -- Version 1.5-beta14 - -* Fixed build problem with ./configure --disable-ssl - that was reported on Debian woody. -* Fixed bug where --redirect-gateway could not be used - together with --resolv-retry. - -2003.11.03 -- Version 1.5-beta13 - -* Added CRL (certificate revocation list) capability using - --crl-verify option (Stefano Bracalenti). -* Added --replay-window option for variable replay-protection - window sizes. -* Fixed --fragment bug which might have caused certain large - packets to be sent unfragmented. -* Modified --secret and --tls-auth to permit different cipher and - HMAC keys to be used for each data flow direction. Also - increased static key file size generated by --genkey from - 1024 to 2048 bits, where 512 bits each are reserved for - send-HMAC, encrypt, receive-HMAC, and decrypt. Key file forward - and backward compatibility is maintained. See --secret option - documentation on the man page for more info. -* Added --tls-remote option (Teemu Kiviniemi). -* Fixed --tls-cipher documention regarding correct delimiter - usage (Teemu Kiviniemi). -* Added --key-method option for selecting alternative data - channel key negotiation methods. Method 1 is the default. - Method 2 has been added (see man page for more info). -* Added French translation of HOWTO to web site - (Guillaume Lehmann). -* Fixed problem caused by late resolver library load on - certain platforms when --resolv-retry and --chroot are - used together (Teemu Kiviniemi). -* In TCP mode, all decryption or TLS errors will abort the current - connection (this is not done in UDP mode because UDP is - "connectionless"). -* Fixed a TCP client reconnect bug that only occurs on the - BSDs, where connect() fails with an invalid argument. This - bug was partially (but not completely) fixed in beta7. -* Added "route_net_gateway" environmental variable which contains - the pre-existing default gateway address from the routing table - (there's no standard API for getting the default gateway, so - right now this feature only works on Windows or Linux). -* Renamed the "route_default_gateway" enviromental variable to - "route_vpn_gateway" -- this is the remote VPN endpoint. -* The special keywords vpn_gateway, net_gateway, and remote_host - can now be used for the network or gateway components of the - --route option. See the man page for more info. -* Added the --redirect-gateway option to configure the VPN - as the default gateway (implemented on Linux and Windows only). -* Added the --http-proxy option with basic authentication - support for use in TCP client mode. Successfully tested - using Squid as the HTTP proxy, with and without authentication. - -2003.10.12 -- Version 1.5-beta12 - -* Fixed Linux-only bug in --mktun and --rmtun which was - introduced around beta8 or so, which would cause - an error such as "I don't recognize device tun0 as a - tun or tap device1". -* Added --ifconfig-nowarn option to disable options - consistency warnings about --ifconfig parameters. -* Don't allow any kind of sequence number backtracking or - message reordering when in TCP mode. -* Changed beta naming convention to use '_' (underscore) - rather than '-' (dash) to pacify rpmbuild. - -2003.10.08 -- Version 1.5-beta11 - -* Modified code in the Windows version which sets the IP address - and netmask of the TAP-Win32 adapter using the IP Helper API. - Most of the changes involve better error recovery when - the IP Helper API returns an error status. See the - manual page entry on --ip-win32 for more info. - -2003.10.08 -- Version 1.5-beta10 - -* Added getpass() function for Windows version so that --askpass - option works correctly (Stefano Bracalenti). -* Added reboot advisory to end of Win32 install script. -* Changed crypto code to use pseudo-random IVs rather than - carrying forward the IV state from the previous packet. - This is in response to item 2 in the following document: - http://www.openssl.org/~bodo/tls-cbc.txt which points - out weaknesses in TLS's use of the same IV carryforward - approach. This change does not break protocol compatibility - with previous versions of OpenVPN. -* Made a change to the crypto replay protection code to also - protect against certain kinds of packet reordering attacks. - This change does not break protocol compatibility with - previous versions of OpenVPN. -* Added --ip-win32 option to provide several choices for - setting the IP address on the TAP-Win32 adapter. -* #ifdefed out non-CBC crypto modes by default. -* Added --up-delay option to delay TUN/TAP open and --up script - execution until after connection establishment. This option - replaces the earlier windows-only option --tap-delay. - -2003.10.01 -- Version 1.5-beta9 - -* Fixed --route-noexec bug where option was not parsed correctly. -* Complain if --dev tun is specified without --ifconfig on Windows. -* Fixed bug where TCP connections on windows would sometimes cause - an assertion failure. -* Added a new flag to TAP-Win32 advanced properties that allows one - to set the adapter to be always "connected" even when an OpenVPN - process doesn't have it open. The default behavior is to report - a media status of connected only when an OpenVPN process has the - adapter open. -* Rebuilt the Windows self-install distribution with OpenSSL 0.9.7c - DLLs in response to an OpenSSL security advisory. - -2003.09.30 -- Version 1.5-beta8 - -* Extended the --ifconfig option to work on tap devices as well - as tun devices. -* Implemented the --ifconfig option for Windows, by calling the - netsh tool. -* By default, do an "arp -d *" on Windows after TAP-Win32 open to - refresh the MAC cache. This behaviour can be disabled with - --no-arp-del. -* On Windows, allow the --dev-node parameter (which specifies - the name of the TAP-Win32 adapter) to be omitted in cases where - there is a single TAP-Win32 adapter on the system which can be - assumed to be the default. -* Modified the diagnostic --verb 5 debugging level to print 'R' - for TCP/UDP read, 'W' for TCP/UDP write, 'r' for TUN/TAP read, - and 'w' for TUN/TAP write. -* Conditionalize OpenBSD read_tun and write_tun based on tun or tap - mode. -* Added IPv6 tun support to OpenBSD (Thomas Glanzmann). -* Make the --enable-mtu-dynamic ./configure option enabled by - default. -* Deprecated the --mtu-dynamic run-time option, in favor of - --fragment. -* DNS names can now be used as --ifconfig parameters. -* Significant work on TAP-Win32 driver to bring up to SMP standards. -* On Windows, fixed dangling IRP problem if TAP-Win32 driver is - unloaded or disabled, while a user-space process has it open. -* On Windows, if --tun-mtu is not specified, it will be read from - the TAP-Win32 driver via ioctl. -* On Windows, added TAP-Win32 driver status info to "F2" keyboard - signal (only when run from a console window). -* Added --mssfix option to control TCP MSS size (YANO Hirokuni). -* Renamed --mtu-dynamic option to --fragment to more accurately - reflect its function. Fragment accepts a single parameter which - is the upper limit on acceptable UDP packet size. -* Changed default --tun-mtu-extra parameter to 32 from 64. -* Eliminated reference to malloc.o in configure.ac. -* Added tun device emulation to the TAP-Win32 driver. -* Added --route and related options. -* Added init script for SuSE Linux (Frank Plohmann). -* Extended option consistency check between peers to function - in all crypto modes, including static-key and cleartext modes. - Previously only TLS mode was supported. Disable with - --disable-occ. -* Overall, increased the amount of configuration option sanity - checking, especially of networking parameters. -* Added --mtu-test option for empirical MTU measurement. -* Added Windows-only option --tap-delay to not set the TAP-Win32 - adapter media state to 'connected' until TCP/UDP connection - establishment with peer. -* Slightly modified --route/--route-delay semantics so that when - --route is given without --route-delay, routes are added - immediately after tun/tap device open. When --route-delay is - specified, routes will be added n seconds after connection - initiation, where n is the --route-delay parameter (which - can be set to 0). -* Made TCP framing error into a non-fatal error that triggers a - connection reset. - -2003.08.28 -- Version 1.5-beta7 - -* Fixed bug that caused OpenVPN not to respond to exit/restart - signals when --resolv-retry is used and a local or remote DNS - name cannot be resolved. -* Exported a series of environmental variables with useful - info for scripts. See man page for more info. Based - on a suggestion by Anthony Ciaravalo. -* Moved TCP/UDP socket bind to a point in the initialization - before the --up script gets called. This is desirable - because (a) a socket bind failure will happen before - daemonization, allowing an error status code to be returned - to the shell and (b) the possibility is eliminated of a - socket bind failure causing the --up script to be run - but not the --down script. This change has a side effect - that --resolv-retry will no longer work with --local. -* Fixed bug where if an OpenVPN TCP server went down and back - up again, Solaris or FreeBSD clients would fail to reconnect - to it. -* Fixed bug that prevented OpenVPN from being run by - inetd/xinetd in TCP mode. -* Added --log and --log-append options for logging messages to - a file. -* On Windows, check that the current user is a member of the - Administrator group before attempting install or uninstall. - -2003.08.16 -- Version 1.5-beta6 - -* Fixed TAP-Win32 driver to properly increment the Rx/Tx count. - -2003.08.14 -- Version 1.5-beta5 - -* Added user-configurability of the TAP-Win32 adapter MTU - through the adapter advanced properties page. -* Added Windows Service support. -* On Windows, added file association and right-clickability - for .ovpn files (OpenVPN config files). - -2003.08.05 -- Version 1.5-beta4 - -* Extra refinements and error checking added to Windows - NSIS install script. - -2003.08.05 -- Version 1.5-beta3 - -* Added md5.h include to crypto.c to fix build problem on - OpenBSD. -* Created a Win32 installer using NSIS. -* Removed DelService command from TAP-Win32 INF file. It appears - to be not necessary and it interfered with the ability to - uninstall and reinstall the driver without needing to reboot. -* On Windows version, added "addtap" and "deltapall" batch - files to add and delete TAP-Win32 adapter instances. - -2003.07.31 -- Version 1.5-beta2 - -* Renamed INSTALL.w32 to INSTALL-win32.txt and reformatted - in Windows ASCII so it's easier to click and view. -* Added postscript and PDF versions of the HOWTO to the web - site (C R Zamana). -* Merged Michael Clarke's stability patch into TAP-Win32 - driver which appears to fix the suspend/resume driver bug - and significantly improve driver stability. -* Added Christof Meerwald's Media Status patch to the - TAP-Win32 driver which shows the TAP adapter to be - disconnected when OpenVPN is not running. -* Moved socket connect and TCP server listen code to a later - point in openvpn() function so that the TCP server listen - state is entered after daemonization. -* Added keyboard shortcuts to simulate signals in the Windows - version, see the window title bar for descriptions. - -2003.07.24 -- Version 1.5-beta1 - -* Added TCP support via the new --proto option. -* Renamed udp-centric options such as --udp-mtu to - --link-mtu (old option names preserved for compatibility). -* Ported to Windows 2000 + XP using mingw and a TAP driver - derived from the Cipe-Win32 project by Damion K. Wilson. -* Added --show-adapters flag for windows version. -* Reworked the SSL/TLS packet acknowledge code to better - handle certain corner cases. -* Turned off the default enabling of IP forwarding in the - sample-scripts/openvpn.init script for Redhat. - Forwarding can be enabled by users in their --up scripts - or firewall config. -* Added --up-restart option based on suggestion from Sean - Reifschneider. -* If --dev tap or --dev-type tap is specified, --tun-mtu - defaults to 1500 and --tun-mtu-extra defaults to 64. -* Enabled --verb 5 debugging mode that prints 'R' and 'W' - for each packet read or write on the TCP/UDP socket. - -2003.08.04 -- Version 1.4.3 - -* Added md5.h include to crypto.c - to fix build problem on OpenBSD. - -2003.07.15 -- Version 1.4.2 - -* Removed adaptive bandwidth from - --mtu-dynamic -- its absence appears - to work better than its existence (1.4.1.2). -* Minor changes to --shaper to fix long - retransmit timeouts at low bandwidth - (1.4.1.2). -* Added LOG_RW flag to openvpn.h for - debugging (1.4.1.2). -* Silenced spurious configure warnings (1.4.1.2). -* Backed out --dev-name patch, modified --dev - to offer equivalent functionality (1.4.1.4). -* Added an optional parameter to --daemon and - --inetd to support the passing of a custom - program name to the system logger (1.4.1.5). -* Add compiled-in options to the program title - (1.4.1.5). -* Coded the beginnings of a WIN32 port (1.4.1.5). -* Succeeded in porting to Win32 Mingw environment - and running loopback tests (1.4.1.6). Still - need a kernel driver for full Win32 - functionality. -* Fixed a bug in error.h where - HAVE_CPP_VARARG_MACRO_GCC was misspelled. - This would have caused a significant slowdown - of OpenVPN when built by compilers that - lack ISO C99 vararg macros (1.4.1.6). -* Created an init script for Gentoo Linux - in ./gentoo directory (1.4.1.6). - -2003.05.15 -- Version 1.4.1 - -* Modified the Linux 2.4 TUN/TAP open code to - fall back to the 2.2 TUN/TAP interface if the - open or ioctl fails. -* Fixed bug when --verb is set to 0 and non-fatal - socket errors occur, causing 100% CPU utilization. - Occurs on platorms where - EXTENDED_SOCKET_ERROR_CAPABILITY is defined, - such as Linux 2.4. -* Fixed typo in tun.c that was preventing - OpenBSD build. -* Added --enable-mtu-dynamic configure option - to enable --mtu-dynamic experimental option. - -2003.05.07 -- Version 1.4.0 - -* Added --replay-persist feature to allow replay - protection across sessions. -* Fixed bug where --ifconfig could not be used - with --tun-mtu. -* Added --tun-mtu-extra parameter to deal with - the situation where a read on a TUN/TAP device - returns more data than the device's MTU size. -* Fixed bug where some IPv6 support code for - Linux was not being properly ifdefed out for - Linux 2.2, causing compile errors. -* Added OPENVPN_EXIT_STATUS_x codes to - openvpn.h to control which status value - openvpn returns to its caller (such as - a shell or inetd/xinetd) for various conditions. -* Added OPENVPN_DEBUG_COMMAND_LINE flag to - openvpn.h to allow debugging in situations - where stdout, stderr, and syslog cannot be used - for message output, such as when OpenVPN is - instantiated by inetd/xinetd. -* Removed owner-execute permission from file - created by static key generator (Herbert Xu - and Alberto Gonzalez Iniesta). -* Added --passtos option to allow IPv4 TOS bits - to be passed from TUN/TAP input packets to - the outgoing UDP socket (Craig Knox). -* Added code to prevent open socket file descriptors - from being accessible to called scripts. -* Added --dev-name option (Christian Lademann). -* Added --mtu-disc option for manual control - over MTU options. -* Show OS MTU value on UDP socket write failures - (linux only). -* Numerous build system and portability - fixes (Matthias Andree). -* Added better sensing of compiler support for - variable argument macros, including (a) gcc - style, (b) ISO C 1999 style, and (c) no support. -* Removed generated files from CVS. Note INSTALL - file for new CVS build commands. -* Changed certain internal symbol names - for C standards compliance. -* Added TUN/TAP open code to cycle dynamically - through unit numbers until it finds a free - unit (based on code from Thomas Gielfeldt - and VTun). -* Added dynamic MTU and fragmenting infrastructure - (Experimental). Rebuild with FRAGMENT_ENABLE - defined to enable. -* Minor changes to SSL/TLS negotiation, use - exponential backoff on retransmits, and use - a smaller MTU size (note that no protocol - changes have been made which would break - compatibility with 1.3.x). -* Added --enable-strict-options flag - to ./configure. This option will cause - a more strict check for options compatibility - between peers when SSL/TLS negotiation is used, - but should only be used when both OpenVPN peers - are of the same version. -* Reorganization of debugging levels. -* Added a workaround in configure.ac for - default SSL header location on Linux - to fix RH9 build problem. -* Fixed potential deadlock when pthread support - is used on OSes that allocate a small socketpair() - message buffer. -* Fixed openvpn.init to be sh compliant - (Bishop Clark). -* Changed --daemon to wait until all - initialization is finished before becoming a - daemon, for the benefit of initialization - scripts that want a useful return status from - the openvpn command. -* Made openvpn.init script more robust, including - positive indication of initialization errors - in the openvpn daemon and better sanity checks. -* Changed --chroot to wait until initialization - is finished before calling chroot(), and allow - the use of --user and --group with --chroot. -* When syslog logging is enabled (--daemon or - --inetd), set stdin/stdout/stderr to point - to /dev/null. -* For inetd instantiations, dup socket descriptor - to a >2 value. -* Fixed bug in verify-cn script, where test would - incorrectly fail if CN=x was the last component - of the X509 composite string (Anonymous). -* Added Markus F.X.J. Oberhumer's special - license exception to COPYING. - -2002.10.23 -- Version 1.3.2 - -* Added SSL_CTX_set_client_CA_list call - to follow the canonical form for TLS initialization - recommended by the OpenSSL docs. This change allows - better support for intermediate CAs and has no impact - on security. -* Added build-inter script to easy-rsa package, to - facilitate the generation of intermediate CAs. -* Ported to NetBSD (Dimitri Goldin). -* Fixed minor bug in easy-rsa/sign-req. It refers to - openssl.cnf file, instead of $KEY_CONFIG, like all - other scripts (Ernesto Baschny). -* Added --days 3650 to the root CA generation command - in the HOWTO to override the woefully small 30 day - default (Dominik 'Aeneas' Schnitzer). -* Fixed bug where --ping-restart would sometimes - not re-resolve remote DNS hostname. -* Added --tun-ipv6 option and related infrastructure - support for IPv6 over tun. -* Added IPv6 over tun support for Linux (Aaron Sethman). -* Added FreeBSD 4.1.1+ TUN/TAP driver notes to - INSTALL (Matthias Andree). -* Added inetd/xinetd support (--inetd) including - documentation in the HOWTO. -* Added "Important Note on the use of commercial certificate - authorities (CAs) with OpenVPN" to HOWTO based on - issues raised on the openvpn-users list. - -2002.07.10 -- Version 1.3.1 - -* Fixed bug in openvpn.spec and openvpn.init - which caused RPM upgrade to fail. - -2002.07.10 -- Version 1.3.0 - -* Added --dev-node option to allow explicit selection of - tun/tap device node. -* Removed mlockall call from child thread, as it doesn't - appear to be necessary (child thread inherits mlockall - state from parent). -* Added --ping-timer-rem which causes timer for --ping-exit - and --ping-restart not to run unless we have a remote IP - address. -* Added condrestart to openvpn.init and openvpn.spec - (Bishop Clark). -* Added --ifconfig case for FreeBSD (Matthias Andree). -* Call openlog with facility=LOG_DAEMON (Matthias Andree). -* Changed LOG_INFO messages to LOG_NOTICE. -* Added warning when key files are group/others accessible. -* Added --single-session flag for TLS mode. -* Fixed bug where --writepid would segfault if used with - an invalid filename. -* Fixed bug where --ipchange status message was formatted - incorrectly. -* Print more concise error message when system() call - fails. -* Added --disable-occ option. -* Added --local, --remote, and --ifconfig options sanity - check. -* Changed default UDP MTU to 1300 and TUN/TAP MTU to - 1300. -* Successfully tested with OpenSSL 0.9.7 Beta 2. -* Broke out debug level definitions to errlevel.h -* Minor documentation and web site changes. -* All changes maintain protocol compatibility - with OpenVPN versions since 1.1.0, however default - MTU changes will require setting the MTU explicitly - by command line option, if you want 1.3.0 to - communicate with previous versions. - -2002.06.12 -- Version 1.2.1 - -* Added --ping-restart option to restart - connection on ping timeout using SIGUSR1 - logic (Matthias Andree). -* Added --persist-tun, --persist-key, - --persist-local-ip, and --persist-remote-ip - options for finer-grained control over SIGUSR1 - and --ping-restart restarts. To - replicate previous SIGUSR1 functionality, - use --persist-remote-ip. -* Changed residual IV fetching code to take - IV from tail of ciphertext. -* Added check to make sure that CFB or OFB - cipher modes are only used with SSL/TLS - authentication mode, and added a caveat - to INSTALL. -* Changed signal handling during initialization - (including re-initialization during restarts) - to exit on SIGTERM or SIGINT and ignore other - signals which would ordinarily be caught. -* Added --resolv-retry option to allow - retries on hostname resolution. -* Expanded the --float option to also - allow dynamic changes in source port number - on incoming datagrams. -* Added --mute option to limit repetitive - logging of similar message types. -* Added --group option to downgrade GID - after initialization. -* Try to set ifconfig path automatically - in configure. -* Added --ifconfig code for Mac OS X - (Christoph Pfisterer). -* Moved "Peer Connection Initiated" message - to --verb level 1. -* Successfully tested with - OpenSSL 0.9.7 Beta 1 and AES cipher. -* Added RPM notes to INSTALL. -* Added ACX_PTHREAD (from the autoconf - macro archive) to configure.ac - to figure out the right pthread - options for a given platform. -* Broke out macro definitions from - configure.ac to acinclude.m4. -* Minor changes to docs and HOWTO. -* All changes maintain protocol compatibility - with OpenVPN versions since 1.1.0. - -2002.05.22 -- Version 1.2.0 - -* Added configuration file support via - the --config option. -* Added pthread support to improve latency. - With pthread support, OpenVPN - will offload CPU-intensive tasks such as RSA - key number crunching to a background thread - to improve tunnel packet forwarding - latency. pthread support can be enabled - with the --enable-pthread configure option. - Pthread support is currently available - only for Linux and Solaris. -* Added --dev-type option so that tun/tap - device names don't need to begin with - "tun" or "tap". -* Added --writepid option to write main - process ID to a file. -* Numerous portability fixes to ease - porting to other OSes including changing - all network types to uint8_t and uint32_t, - and not assuming that time_t is 32 bits. -* Backported to OpenSSL 0.9.5. -* Ported to Solaris. -* Finished OpenBSD port except for - pthread support. -* Added initialization script: - sample-scripts/openvpn.init - (Douglas Keller) -* Ported to Mac OS X (Christoph Pfisterer). -* Improved resilience to DoS attacks when - TLS mode is used without --remote or - --tls-auth, or when --float is used - with --remote. Note however that the best - defense against DoS attacks in TLS mode - is to use --tls-auth. -* Eliminated automake/autoconf dependency - for non-developers. -* Ported configure.in to configure.ac - and autoconf 2.50+. -* SIGHUP signal now causes OpenVPN to restart - and re-read command line and or config file, - in conformance with canonical daemon behaviour. -* SIGUSR1 now does what SIGHUP did in - version 1.1.1 and earlier -- close and reopen - the UDP socket for use when DHCP changes - host's IP address and preserve most recently - authenticated peer address without rereading - config file. -* SIGUSR2 added -- outputs current statistics, - including compression statistics. -* All changes maintain protocol compatibility - with 1.1.1 and 1.1.0. - -2002.04.22 -- Version 1.1.1 - -* Added --ifconfig option to automatically configure - TUN device. -* Added inactivity disconnect (--inactive - and --ping-exit options). -* Added --ping option to keep stateful firewalls - from timing out. -* Added sanity check to command line parser to - err if any TLS options are used in non-TLS mode. -* Fixed build problem with compiler environments that - define printf as a macro. -* Fixed build problem on linux systems that have - an integrated TUN/TAP driver but lack the persistent - tunnel feature (TUNSETPERSIST). Some linux kernels - >= 2.4.0 and < 2.4.7 fall into this category. -* Changed all calls to EVP_CipherInit to use explicit - encrypt/decrypt mode in order to fix problem with - IDEA-CBC and AES-256-CBC ciphers. -* Minor changes to control channel transmit limiter - algorithm to fix problem where TLS control channel - might not renegotiate within the default 60 second window. -* Simplified man page examples by taking advantage - of the new --ifconfig option. -* Minor changes to configure.in to check more - rigourously for OpenSSL 0.9.6 or greater. -* Put back openvpn.spec, eliminated - openvpn.spec.in. -* Modified openvpn.spec to reflect new automake-based - build environment (Bishop Clark). -* Other documentation changes. -* Added --test-crypto option for debugging. -* Added "missing" and "mkinstalldirs" automake - support files. - - -2002.04.09 -- Version 1.1.0 - -* Strengthened replay protection and IV handling, - extending it fully to both static key and - TLS dynamic key exchange modes. -* Added --mlock option to disable paging and ensure that key - material and tunnel data is never paged to disk. -* Added optional traffic shaping feature to cap the maximum - data rate of the tunnel. -* Converted to automake (The Platypus Brothers 2002-04-01). -* Ported to OpenBSD by Janne Johansson. -* Added --tun-af-inet option to work around an incompatibility - between Linux and BSD tun drivers. -* Sequence number-based replay protection using the - IPSec sliding window model is now the default, - disable with --no-replay. -* Explicit IV is now the default, disable with --no-iv. -* Disabled all cipher modes except CBC, CFB, and OFB. -* In CBC mode, use explicit IV and carry forward residuals, - using IPSec model. -* In CFB/OFB mode, IV is timestamp, sequence number. -* Eliminated --packet-id, --timestamp, and max-delta parameter to - the --tls-auth option as they are now supplanted by improved - replay code which is enabled by default. -* Eliminated --rand-iv as it is now obsolete with improved - IV code. -* Eliminated --reneg-err option as it increases vulnerability - to DoS attacks. -* Added weak key check for DES ciphers. -* --tls-freq option is no longer specified on the command line, - instead it now inherits its parameter from the - --tls-timeout option. -* Fixed bug that would try to free memory on exit that was - never malloced if --comp-lzo was not specified. -* Errata fixed in the man page examples: "test-ca" should be - "tmp-ca". -* Updated manual page. -* Preliminary work in porting to OpenSSL 0.9.7. -* Changed license to allowing linking with OpenSSL. - -2002.03.29 -- Version 1.0.3 - -* Fixed a problem in configure with library ordering on the - command line. - -2002.03.28 -- Version 1.0.2 - -* Improved the efficiency of the inner event loop. -* Fixed a minor bug with timeout handling. -* Improved the build system to build on RH 6.2 through 7.2. -* Added an openvpn.spec file for RPM builders (Bishop Clark). - -2002.03.23 -- Version 1.0 - -* Added TLS-based authentication and key exchange. -* Added gremlin mode to stress test. -* Wrote man page. - -2001.12.26 -- Version 0.91 - -* Added any choice of cipher or HMAC digest. - -2001.5.13 -- Version 0.90 - -* Initial release. -* IP tunnel over UDP, with blowfish cipher and SHA1 HMAC signature. + Fix fatal error at switching remotes (#629) + Fix update_time() and openvpn_gettimeofday() coexistence + Selectively reformat too long lines + Speedup TCP remote hosts connections + Support X509 field list to be username + Fix IPv4 default gateway with multiple route tables + Add CRL extractor script for --crl-verify dir mode diff --git a/Changes.rst b/Changes.rst index 3ba78c6c7a7..9ed68245df2 100644 --- a/Changes.rst +++ b/Changes.rst @@ -1,463 +1,476 @@ -Overview of changes in 2.5.9 -============================ +Overview of changes in 2.6.0, relative to 2.6_rc2 +================================================= -New features ------------- -- Optional ciphers in ``--data-ciphers`` - Ciphers in ``--data-ciphers`` can now be prefixed with a ``?`` to mark - those as optional and only use them if the SSL library supports them. - -User-visible Changes --------------------- -- when compiling from a git checkout, put proper branch names into - windows builds - -Bugfixes --------- -- do not include auth-token in pulled-option digest (interferes with - persist-tun when auth-token is in use, GH #200). - -- fix corner case that might lead to leaked file descriptor - -- fix parser bug (parse_line()) that can lead to buffer overflows on - malformed command line or server ccd file handling. Not exploitable. - -- pull-filter: ignore leading spaces in option names (work around server side - bug with erroneous extra spaces) - -- push: do not add leading spaces to "out of renegotiations" pushed auth-token - -- fix NULL pointer crash on "openvpn --show-tls" with mbedtls - - -Overview of changes in 2.5.8 -============================ +(See below for changes in 2.6 relative to 2.5) New features ------------ -- allow running a default configuration with TLS libraries without BF-CBC - (even if TLS cipher negotiation would not actually use BF-CBC, the - long-term compatibility "default cipher BF-CBC" would trigger an error - on such TLS libraries) +- no new features relative to 2.6_rc2 -User-visible Changes +User-Visible Changes -------------------- -- add git branch name + commit ID to OpenVPN version string on - MSVC builds (windows) +- no user-visible changes relative to 2.6_rc2 -Testing Enhancements --------------------- -- t_client.sh: if fping is found and fping6 is not, assume we have - fping 4.0 and up, and call "fping -6" for IPv6 ping tests +Bugfixes / minor improvements +----------------------------- +- repair handling of "route already exists" errors for Linux/sitnl builds, + which would lead to erroneous attempts to remove routes later on, possibly + removing "non openvpn installed" routes. -- t_client.sh: allow to force FAIL on prerequisite fails, so a CI - environment will no longer "silently skip" t_client runs if fping (etc) - can not be found, but will error out - -Bugfixes --------- -- ``--auth-nocache'' was not always correctly clearing username+password - after a renegotiation +- repair error handling for Linux/iproute2 builds - this was ignoring + all errors on route installation, causing issues on route removal. -- ensure that auth-token received from server is cleared if requested - by the management interface ("forget password" or automatically - via ``--management-forget-disconnect'') +- improve logging (errors and debug messages) for route handling on Windows -- in a setup without username+password, but with auth-token and - auth-token-username pushed by the server, OpenVPN would start asking - for username+password on token expiry. Fix. +- print warning if pkcs11-id or pkcs11-id-management options are used but + no pkcs11-providers has been selected -- using ``--auth-token`` together with ``--management-client-auth`` - (on the server) would lead to TLS keys getting out of sync and client - being disconnected. Fix. +- openvpnmsica: improve handling of win-dco driver (use MSM now) -- management interface would sometimes get stuck if client and server - try to write something simultaneously. Fix by allowing a limited - level of recursion in virtual_output_callback() +- for Linux/DCO builds, increase libnl buffer size to reduce propability + of ENOBUFS occurance if kernel-to-userland netlink queue overruns + (bandaid fix) -- fix management interface not returning ERROR:/SUCCESS: response - on "signal SIGxxx" commands when in HOLD state +- re-enable use of suid binaries in scripts run by OpenVPN - new + capability-handling code was too strict and cleared all capabilities, + breaking users' use of "sudo" (etc) in scripts (Github OpenVPN/openvpn#220). -- tls-crypt-v2: abort connection if client-key is too short - -- make man page agree with actual code on replay-window backtrag log message - -- remove useless empty line from CR_RESPONSE message - - -Overview of changes in 2.5.7 -============================ +Overview of changes in 2.6_rc2 +============================== New features ------------ -- Limited OpenSSL 3.0 support - OpenSSL 3.0 support has been added. OpenSSL 3.0 support in 2.5 relies - on the compatiblity layer and full OpenSSL 3.0 support is coming with - OpenVPN 2.6. Only features that impact usage directly have been - backported: - - ``--tls-cert-profile insecure`` has been added to allow selecting the - lowest OpenSSL security level (not recommended, use only if you must). - - OpenSSL 3.0 no longer supports the Blowfish (and other deprecated) - algorithm by default and the new option ``--providers`` allows loading - the legacy provider to renable these algorithms. Most notably, - reading of many PKCS#12 files encrypted with the RC2 algorithm fails - unless ``--providers legacy default`` is configured. +- ``remote-entry-get`` management command will now show enabled/disabled + status for each connection entry - The OpenSSL engine feature ``--engine`` is not enabled by default - anymore if OpenSSL 3.0 is detected. +- report ``CONNECTED,ROUTE_ERROR`` to management GUI if connection to + server succeeds but not all routes can be installed (Windows and + Linux/Netlink only, so far) -- print OpenSSL error stack if decoding PKCS12 file fails +- add rate limiter for incoming "initial handshake packets", enabled by + default with a limit of 100 packets per 10 seconds. New option + ``--connect-freq-initial`` to configure values. This change makes + OpenVPN servers uninteresting as an UDP reflection DDoS engine. -User-visible Changes +User-Visible Changes -------------------- -- windows vcpkg building includes pkcs11-helper 1.29 now - -- add MSVC build options to harden windows binaries (HW-enforced - stack protection, SHA256 object hashes, SDL). - -Bugfixes --------- -- fix omission of cipher-negotiation.rst in tarballs - -- fix errno handling on Windows (Windows has different classes of - error codes, GetLastError() and C runtime errno, these should now - be handled correctly) - -- fix PATH_MAX build failure in auth-pam.c +- OCC (options compatibility check) log messages are considered obsolete + and are only shown on loglevel 7 or higher now -- fix t_net.sh self-test leaving around stale "ovpn-dummy0" interface +- copyright line has been updated in all files to "xxx-2023" -- fix overlong path names, leading to missing pkcs11-helper patch - in tarball +- include peer-id=nn in multi prefix for DCO servers if loglevel is 7+ + (helps with DCO debugging) +Bugfixes / minor improvements +----------------------------- +- improve documentation on no-longer-supported options -Overview of changes in 2.5.6 -============================ - -User-visible Changes --------------------- -- update copyright year to 2022 - -New features ------------- -- new plugin (sample-plugin/defer/multi-auth.c) to help testing with - multiple parallel plugins that succeed/fail in direct/deferred mode +- reduce amount of log messages about "dco_update_keys: peer_id=-1" -- various build improvements (github actions etc) +- undo FreeBSD "ipv6 ifconfig" workaround for FreeBSD 12.4 and up (Trac 1226) -- upgrade pkcs11-helper to release 1.28.4 +- fix signal handling issues where a SIGUSR1 "restart" signal could overwrite + a SIGTERM/SIGINT "please end!" signal already queued, making OpenVPN hard + to stop (Trac 311, Trac 639, GH issue #205) -Bugfixes --------- -- CVE-2022-0547 - see https://community.openvpn.net/openvpn/wiki/SecurityAnnouncements +- fix signal handling issues on windows, where OpenVPN could not be + interrupted by ctrl-c when sleep()ing between connection attempts - If openvpn is configured with multiple authentication plugins and - more than one plugin tries to do deferred authentication, the result - is not well-defined - creating a possible authentication bypass. +- use IPAPI for IPv6 route installation on Windows, if OpenVPN runs without + service pipe ("run as admin from cmd.exe") - In this situation the server process will now abort itself with a clear - log message. Only one plugin is allowed to do deferred authentication. +- fix spurious DCO log messages about "peer-id unknown to OpenVPN: -1" -- Fix "--mtu-disc maybe|yes" on Linux +- on Windows, repair wintun buffer cleanup on program end - Due to configure/syshead.h/#ifdef confusion, the code in question was - not compiled-in since a long time. Fixed. Trac: #1452 -- Fix $common_name variable passed to scripts when username-as-common-name - is in effect. +Overview of changes in 2.6_rc1 +============================== - This was not consistently set - sometimes, OpenVPN exported the username, - sometimes the common name from the client cert. Fixed. Trac: #1434 +New features +------------ +Support unlimited number of connection entries and remote entries -- Fix potential memory leaks in add_route() and add_route_ipv6(). +New management commands to enumerate and list remote entries + Use ``remote-entry-count`` and ``remote-entry-get`` + commands from the management interface to get the number of + remote entries and the entries themselves. -- Apply connect-retry backoff only to one side of the connection in - p2p mode. Without that fix/enhancement, two sides could end up - only sending packets when the other end is not ready. Trac: #1010, #1384 -- remove unused sitnl.h file +Bugfixes / minor improvements +----------------------------- +Improve DCO-related logging in many places. -- clean up msvc build files, remove unused MSVC build .bat files +DCO/Linux robustness fixes. -- repair "--inactive" handling with a 'bytes' parameter larger than 2 Gbytes +DCO/Linux TCP crashbug (recvfrom(-1) endless loop) worked around - root + cause has not been found, but the condition is detected and the + offending client is removed, instead of crashing the server. - due to integer overflow, this ended up being "0" on Linux, but on - Windows with MSVC it ends up being "always 2 Gbyte", both not doing - what is requested. Trac: #1448 +Rename internal TLS state TM_UNTRUSTED to TM_INITIAL, always start new + peer handshake (new connect or renegotiation) in TM_INITIAL state. -- repair handling of EC certificates on Windows with pkcs11-helper +Upgrade Windows build environment to MSVC 2022 - (wrong compile-time defines for OpenSSL 1.1.1) +Make management password check constant time -Documentation -------------- -- documentation improvements related to DynDNS. Trac: #1417 +Repair keepalive and mss setting in DCO peer-to-peer mode. -- clean up documentation for --proto and related options +Persist DCO client data channel traffic stats on restart (Windows only). -- rebuild rst docs if input files change (proper dependency handling) +Do not include auth-token in pulled option digest. +Reduce default restart pause (--connect-retry) to 1 second. +Deprecate NTLMv1 proxy auth method. -Overview of changes in 2.5.5 -============================ +Fix possible buffer-overrun in command line and ccd/ argument parsing. -User-visible Changes --------------------- -- SWEET32/64bit cipher deprecation change was postponed to 2.7 +Fix memleak if creating deferred auth control files fails -- Windows: use network address for emulated DHCP server as default - this enables use of a /30 subnet, which is needed when connecting - to OpenVPN Cloud. -- require EC support in windows builds - (this means it's no longer possible to build a Windows OpenVPN binary - with an OpenSSL lib without EC support) +Overview of changes in 2.6_beta2 +================================ New features ------------ -- Windows build: use CFG and Spectre mitigations on MSVC builds - -- bring back OpenSSL config loading to Windows builds. - OpenSSL config is loaded from %installdir%\\ssl\\openssl.cnf - (typically: c:\\program files\\openvpn\\ssl\\openssl.cnf) if it exists. - - This is important for some hardware tokens which need special - OpenSSL config for correct operation. Trac #1296 - -Bugfixes --------- -- Windows build: enable EKM - -- Windows build: improve various vcpkg related build issues - -- Windows build: fix regression related to non-writeable status files - (Trac #1430) +Transport statistics (bytes in/out) for DCO environments + With DCO, OpenVPN userland will not see data packets and can not + count them, thus, no statistics. This feature implements server-side + statistics for FreeBSD+DCO and client-side statistics for Windows+DCO, + Linux and FreeBSD client will follow. -- Windows build: fix regression that broke OpenSSL EC support +pkcs11-helper updates + improve shared library loading on Windows, so "copy .dll to application + directory" recipes should no longer be necessary for pkcs#11 providers -- Windows build: fix "product version" display (2.5..4 -> 2.5.4) +Bugfixes / minor improvements +----------------------------- +- add proper documentation for tls-crypt-v2 metadata limits, and better + error messages when these are exceeded -- Windows build: fix regression preventing use of PKCS12 files +- trigger SIGUSR1 if dco_update_keys() fails - this is, when OpenVPN + userland and kernel side key handling gets out of sync, restart instance + to recover. -- improve "make check" to notice if "openvpn --show-cipher" crashes +- improve logging for DCO key update handling -- improve argv unit tests +- ignore incoming client connects while server is being shutdown + (Github: OpenVPN/openvpn#189) -- ensure unit tests work with mbedTLS builds without BF-CBC ciphers +- disable DCO for p2p modes with no crypto or --secret pre-shared key + (= everything that is not TLS) -- include "--push-remove" in the output of "openvpn --help" +- fix endianness issues for TLS cookie handling and unit test -- fix error in iptables syntax in example firewall.sh script -- fix "resolvconf -p" invocation in example "up" script -- fix "common_name" environment for script calls when - "--username-as-common-name" is in effect (Trac #1434) - -Documentation -------------- -- move "push-peer-info" documentation from "server options" to "client" - (where it belongs) - -- correct "foreign_option_{n}" typo in manpage - -- update IRC information in CONTRIBUTING.rst (libera.chat) - -- README.down-root: fix plugin module name - - -Overview of changes in 2.5.4 -============================ -Bugfixes --------- -- fix prompting for password on windows console if stderr redirection - is in use - this breaks 2.5.x on Win11/ARM, and might also break - on Win11/adm64 when released. - -- fix setting MAC address on TAP adapters (--lladdr) to use sitnl - (was overlooked, and still used "ifconfig" calls) - -- various improvements for man page building (rst2man/rst2html etc) - -- minor bugfix with IN6_IS_ADDR_UNSPECIFIED() use (breaks build on - at least one platform strictly checking this) - -- fix minor memory leak under certain conditions in add_route() and - add_route_ipv6() - -User-visible Changes --------------------- -- documentation improvements +Overview of changes in 2.6 +========================== -- copyright updates where needed +Project changes +--------------- -- better error reporting when win32 console access fails +We want to deprecate our old Trac bug tracking system. +Please report any issues with this release in GitHub +instead: https://github.com/OpenVPN/openvpn/issues New features ------------ -- also build man page on Windows builds - - -Overview of changes in 2.5.3 -============================ -Bugfixes --------- -- CVE-2021-3606 - see https://community.openvpn.net/openvpn/wiki/SecurityAnnouncements - - OpenVPN windows builds could possibly load OpenSSL Config files from - world writeable locations, thus posing a security risk to OpenVPN. - - As a fix, disable OpenSSL config loading completely on Windows. - -- disable connect-retry backoff for p2p (--secret) instances - (Trac #1010, #1384) - -- fix build with mbedtls w/o SSL renegotiation support - -- Fix SIGSEGV (NULL deref) receiving push "echo" (Trac #1409) - -- MSI installers: properly schedule reboot in the end of installation - -- fix small memory leak in free_key_ctx for auth_token +Keying Material Exporters (RFC 5705) based key generation + As part of the cipher negotiation OpenVPN will automatically prefer + the RFC5705 based key material generation to the current custom + OpenVPN PRF. This feature requires OpenSSL or mbed TLS 2.18+. + +Compatibility with OpenSSL in FIPS mode + OpenVPN will now work with OpenSSL in FIPS mode. Note, no effort + has been made to check or implement all the + requirements/recommendation of FIPS 140-2. This just allows OpenVPN + to be run on a system that be configured OpenSSL in FIPS mode. + +``mlock`` will now check if enough memlock-able memory has been reserved, + and if less than 100MB RAM are available, use setrlimit() to upgrade + the limit. See Trac #1390. Not available on OpenSolaris. + +Certificate pinning/verify peer fingerprint + The ``--peer-fingerprint`` option has been introduced to give users an + easy to use alternative to the ``tls-verify`` for matching the + fingerprint of the peer. The option takes use a number of allowed + SHA256 certificate fingerprints. + + See the man page section "Small OpenVPN setup with peer-fingerprint" + for a tutorial on how to use this feature. This is also available online + under https://github.com/openvpn/openvpn/blob/master/doc/man-sections/example-fingerprint.rst + +TLS mode with self-signed certificates + When ``--peer-fingerprint`` is used, the ``--ca`` and ``--capath`` option + become optional. This allows for small OpenVPN setups without setting up + a PKI with Easy-RSA or similar software. + +Deferred auth support for scripts + The ``--auth-user-pass-verify`` script supports now deferred authentication. + +Pending auth support for plugins and scripts + Both auth plugin and script can now signal pending authentication to + the client when using deferred authentication. The new ``client-crresponse`` + script option and ``OPENVPN_PLUGIN_CLIENT_CRRESPONSE`` plugin function can + be used to parse a client response to a ``CR_TEXT`` two factor challenge. + + See ``sample/sample-scripts/totpauth.py`` for an example. + +Compatibility mode (``--compat-mode``) + The modernisation of defaults can impact the compatibility of OpenVPN 2.6.0 + with older peers. The options ``--compat-mode`` allows UIs to provide users + with an easy way to still connect to older servers. + +OpenSSL 3.0 support + OpenSSL 3.0 has been added. Most of OpenSSL 3.0 changes are not user visible but + improve general compatibility with OpenSSL 3.0. ``--tls-cert-profile insecure`` + has been added to allow selecting the lowest OpenSSL security level (not + recommended, use only if you must). OpenSSL 3.0 no longer supports the Blowfish + (and other deprecated) algorithm by default and the new option ``--providers`` + allows loading the legacy provider to renable these algorithms. + +Optional ciphers in ``--data-ciphers`` + Ciphers in ``--data-ciphers`` can now be prefixed with a ``?`` to mark + those as optional and only use them if the SSL library supports them. + + +Improved ``--mssfix`` and ``--fragment`` calculation + The ``--mssfix`` and ``--fragment`` options now allow an optional :code:`mtu` + parameter to specify that different overhead for IPv4/IPv6 should taken into + account and the resulting size is specified as the total size of the VPN packets + including IP and UDP headers. + +Cookie based handshake for UDP server + Instead of allocating a connection for each client on the initial packet + OpenVPN server will now use an HMAC based cookie as its session id. This + way the server can verify it on completing the handshake without keeping + state. This eliminates the amplification and resource exhaustion attacks. + For tls-crypt-v2 clients, this requires OpenVPN 2.6 clients or later + because the client needs to resend its client key on completing the hand + shake. The tls-crypt-v2 option allows controlling if older clients are + accepted. + + By default the rate of initial packet responses is limited to 100 per 10s + interval to avoid OpenVPN servers being abused in reflection attacks + (see ``--connect-freq-initial``). + +Data channel offloading with ovpn-dco + 2.6.0+ implements support for data-channel offloading where the data packets + are directly processed and forwarded in kernel space thanks to the ovpn-dco + kernel module. The userspace openvpn program acts purely as a control plane + application. Note that DCO will use DATA_V2 packets in P2P mode, therefore, + this implies that peers must be running 2.6.0+ in order to have P2P-NCP + which brings DATA_V2 packet support. + +Session timeout + It is now possible to terminate a session (or all) after a specified amount + of seconds has passed session commencement. This behaviour can be configured + using ``--session-timeout``. This option can be configured on the server, on + the client or can also be pushed. + +Inline auth username and password + Username and password can now be specified inline in the configuration file + within the tags. If the password is + missing OpenVPN will prompt for input via stdin. This applies to inline'd + http-proxy-user-pass too. + +Tun MTU can be pushed + The client can now also dynamically configure its MTU and the server + will try to push the client MTU when the client supports it. The + directive ``--tun-mtu-max`` has been introduced to increase the maximum + pushable MTU size (defaults to 1600). + +Improved control channel packet size control (``max-packet-size``) + The size of control channel is no longer tied to + ``--link-mtu``/``--tun-mtu`` and can be set using ``--max-packet-size``. + Sending large control channel frames is also optimised by allowing 6 + outstanding packets instead of just 4. ``max-packet-size`` will also set + ``mssfix`` to try to limit data-channel packets as well. +Deprecated features +------------------- +``inetd`` has been removed + This was a very limited and not-well-tested way to run OpenVPN, on TCP + and TAP mode only. + +``verify-hash`` has been deprecated + This option has very limited usefulness and should be replaced by either + a better ``--ca`` configuration or with a ``--tls-verify`` script. + +``secret`` has been deprecated + static key mode (non-TLS) is no longer considered "good and secure enough" + for today's requirements. Use TLS mode instead. If deploying a PKI CA + is considered "too complicated", using ``--peer-fingerprint`` makes + TLS mode about as easy as using ``--secret``. + +``ncp-disable`` has been removed + This option mainly served a role as debug option when NCP was first + introduced. It should now no longer be necessary. + +TLS 1.0 and 1.1 are deprecated + ``tls-version-min`` is set to 1.2 by default. OpenVPN 2.6.0 defaults + to a minimum TLS version of 1.2 as TLS 1.0 and 1.1 should be generally + avoided. Note that OpenVPN versions older than 2.3.7 use TLS 1.0 only. + +``--cipher`` argument is no longer appended to ``--data-ciphers`` + by default. Data cipher negotiation has been introduced in 2.4.0 + and been significantly improved in 2.5.0. The implicit fallback + to the cipher specified in ``--cipher`` has been removed. + Effectively, ``--cipher`` is a no-op in TLS mode now, and will + only have an effect in pre-shared-key mode (``--secret``). + From now on ``--cipher`` should not be used in new configurations + for TLS mode. + Should backwards compatibility with older OpenVPN peers be + required, please see the ``--compat-mode`` instead. + +``--prng`` has beeen removed + OpenVPN used to implement its own PRNG based on a hash. However implementing + a PRNG is better left to a crypto library. So we use the PRNG + mbed TLS or OpenSSL now. + + +Compression no longer enabled by default + Unless an explicit compression option is specified in the configuration, + ``--allow-compression`` defaults to ``no`` in OpeNVPN 2.6.0. + By default, OpenVPN 2.5 still allowed a server to enable compression by + pushing compression related options. + +PF (Packet Filtering) support has been removed + The built-in PF functionality has been removed from the code base. This + feature wasn't really easy to use and was long unmaintained. + This implies that also ``--management-client-pf`` and any other compile + time or run time related option do not exist any longer. + +Option conflict checking is being deprecated and phased out + The static option checking (OCC) is no longer useful in typical setups + that negotiate most connection parameters. The ``--opt-verify`` and + ``--occ-disable`` options are deprecated, and the configure option + ``--enable-strict-options`` has been removed. Logging of mismatched + options has been moved to debug logging (verb 7). User-visible Changes -------------------- -- update copyright messages in files and --version output - -New features ------------- -- add --auth-token-user option (for --auth-token deployments without - --auth-user-pass in client config) - -- improve MSVC building for Windows - -- official MSI installers will now contain arm64 drivers and binaries - (x86, amd64, arm64) - - -Overview of changes in 2.5.2 -============================ - -Bugfixes --------- -- CVE-2020-15078 - see https://community.openvpn.net/openvpn/wiki/SecurityAnnouncements +- CHACHA20-POLY1305 is included in the default of ``--data-ciphers`` when available. +- Option ``--prng`` is ignored as we rely on the SSL library random number generator. +- Option ``--nobind`` is default when ``--client`` or ``--pull`` is used in the configuration +- :code:`link_mtu` parameter is removed from environment or replaced with 0 when scripts are + called with parameters. This parameter is unreliable and no longer internally calculated. - This bug allows - under very specific circumstances - to trick a - server using delayed authentication (plugin or management) into - returning a PUSH_REPLY before the AUTH_FAILED message, which can - possibly be used to gather information about a VPN setup. +- control channel packet maximum size is no longer influenced by + ``--link-mtu``/``--tun-mtu`` and must be set by ``--max-packet-size`` now. + The default is 1250 for the control channel size. - In combination with "--auth-gen-token" or an user-specific token auth - solution it can be possible to get access to a VPN with an - otherwise-invalid account. +- In point-to-point OpenVPN setups (no ``--server``), using + ``--explict-exit-notiy`` on one end would terminate the other side at + session end. This is considered a no longer useful default and has + been changed to "restart on reception of explicit-exit-notify message". + If the old behaviour is still desired, ``--remap-usr1 SIGTERM`` can be used. -- restore pushed "ping" settings correctly on a SIGUSR1 restart +- FreeBSD tun interfaces with ``--topology subnet`` are now put into real + subnet mode (IFF_BROADCAST instead of IFF_POINTOPOINT) - this might upset + software that enumerates interfaces, looking for "broadcast capable?" and + expecting certain results. Normal uses should not see any difference. -- avoid generating unecessary mbed debug messages - this is actually - a workaround for an mbedTLS 2.25 bug when using Curve25519 and Curve448 - ED curves - mbedTLS crashes on preparing debug infos that we do not - actually need unless running with "--verb 8" +- The default configurations will no longer allow connections to OpenVPN 2.3.x + peer or earlier, use the new ``--compat-mode`` option if you need + compatibility with older versions. See the manual page on the + ``--compat-mode`` for details. -- do not print inlined (...) Diffie Hellman parameters to log file +Common errors with OpenSSL 3.0 and OpenVPN 2.6 +---------------------------------------------- +Both OpenVPN 2.6 and OpenSSL 3.0 tighten the security considerable, so some +configuration will no longer work. This section will cover the most common +causes and error message we have seen and explain their reason and temporary +workarounds. You should fix the underlying problems as soon as possible since +these workaround are not secure and will eventually stop working in a future +update. -- fix Linux/SITNL default route lookup in case of multiple routing tables - with more than one default route present (always use "main table" for now) +- weak SHA1 or MD5 signature on certificates -- Fix CRL file handling in combination with chroot + This will happen on either loading of certificates or on connection + to a server:: -User-visible Changes --------------------- + OpenSSL: error:0A00018E:SSL routines::ca md too weak + Cannot load certificate file cert.crt + Exiting due to fatal error -- OpenVPN will now refuse to start if CRL file is not present at startup - time. At "reload time" absense of the CRL file is still OK (and the - in memory copy is used) but at startup it is now considered an error. + OpenSSL 3.0 no longer allows weak signatures on certificates. You can + downgrade your security to allow them by using ``--tls-cert-profile insecure`` + but should replace/regenerate these certificates as soon as possible. -New features ------------- -- printing of the TLS ciphers negotiated has been extended, especially - displaying TLS 1.3 and EC certificates more correctly. +- 1024 bit RSA certificates, 1024 bit DH parameters, other weak keys + This happens if you use private keys or other cryptographic material that + does not meet today's cryptographic standards anymore. Messages are similar + to:: -Overview of changes in 2.5.1 -============================ + OpenSSL: error:0A00018F:SSL routines::ee key too small + OpenSSL: error:1408518A:SSL routines:ssl3_ctx_ctrl:dh key too small -New features ------------- -- "echo msg" support, to enable the server to pushed messages that are - then displayed by the client-side GUI. See doc/gui-notes.txt and - doc/management-notes.txt. + DH parameters (``--dh``) can be regenerated with ``openssl dhparam 2048``. + For other cryptographic keys, these keys and certificates need to be + regenerated. TLS Security level can be temporarily lowered with + ``--tls-cert-profile legacy`` or even ``--tls-cert-profile insecure``. - Supported by the Windows GUI shipped in 2.5.1, not yet supported by - Tunnelblick and the Android GUI. +- Connecting to a OpenVPN 2.3.x server or allowing OpenVPN 2.3.x or earlier + clients -User-visible Changes --------------------- -- make OPENVPN_PLUGIN_ENABLE_PF plugin failures FATAL - if a plugin offers - to set the "openvpn packet filter", and returns a failure when requested - to, OpenVPN 2.5.0 would crash trying to clean up not-yet-initialized - structure members. Since PF is going away in 2.6.0, this is just turning - the crash into a well-defined program abort, and no further effort has - been spent in rewriting the PF plugin error handling (see trac #1377). - -Documentation -------------- -- rework sample-plugins/defer/simple.c - this is an extensive rewrite - of the plugin to bring code quality to acceptable standards and add - documentation on the various plugin API aspects. Since it's just - example code, filed under "Documentation", not under "Bugfix". + This will normally result in messages like:: -- various man page improvements. + OPTIONS ERROR: failed to negotiate cipher with server. Add the server's cipher ('AES-128-CBC') to --data-ciphers (currently 'AES-256-GCM:AES-128-GCM:CHACHA20-POLY1305') if you want to connect to this server. -- clarify ``--block-ipv6`` intent and direction + or -Bugfixes --------- -- fix installation of openvpn.8 manpage on systems without docutils. + client/127.0.0.1:49954 SENT CONTROL [client]: 'AUTH_FAILED,Data channel cipher negotiation failed (no shared cipher)' (status=1) -- Windows: fix DNS search list setup for domains with "-" chars. + You can manually add the missing cipher to the ``--data-ciphers``. The + standard ciphers should be included as well, e.g. + ``--data-ciphers AES-256-GCM:AES-128-GCM:?Chacha20-Poly1305:?AES-128-CBC``. + You can also use the ``--compat-mode`` option. Note that these message may + also indicate other cipher configuration problems. See the data channel + cipher negotiation manual section for more details. (Available online under + https://github.com/OpenVPN/openvpn/blob/master/doc/man-sections/cipher-negotiation.rst) -- Fix tls-auth mismatch OCC message when tls-cryptv2 is used. +- Use of a legacy or deprecated cipher (e.g. 64bit block ciphers) -- Windows: Skip DHCP renew with Wintun adapter (Wintun does not support - DHCP, so this was just causing an - harmless - error and needless delay). + OpenSSL 3.0 no longer supports a number of insecure and outdated ciphers in + its default configuration. Some of these ciphers are known to be vulnerable (SWEET32 attack). -- Windows: Remove 1 second delay before running netsh - speeds up - interface init for wintun setups not using the interactive service. + This will typically manifest itself in messages like:: -- Windows: Fix too early argv freeing when registering DNS - this would - cause a client side crash on Windows if ``register-dns`` is used, - and the interactive service is not used. + OpenSSL: error:0308010C:digital envelope routines::unsupported + Cipher algorithm 'BF-CBC' not found + Unsupported cipher in --data-ciphers: BF-CBC -- Android: Zero initialise msghdr prior to calling sendmesg. + If your OpenSSL distribution comes with the legacy provider (see + also ``man OSSL_PROVIDER-legacy``), you can load it with + ``--providers legacy default``. This will re-enable the old algorithms. -- Fix line number reporting on config file errors after segments - (see Trac #1325). +- OpenVPN version not supporting TLS 1.2 or later -- Fix port-share option with TLS-Crypt v2. + The default in OpenVPN 2.6 and also in many distributions is now TLS 1.2 or + later. Connecting to a peer that does not support this will results in + messages like:: -- tls-crypt-v2: also preload tls-crypt-v2 keys (if --persist-key), otherwise - dropping privs on the server would fail. + TLS error: Unsupported protocol. This typically indicates that client and + server have no common TLS version enabled. This can be caused by mismatched + tls-version-min and tls-version-max options on client and server. If your + OpenVPN client is between v2.3.6 and v2.3.2 try adding tls-version-min 1.0 + to the client configuration to use TLS 1.0+ instead of TLS 1.0 only + OpenSSL: error:0A000102:SSL routines::unsupported protocol -- tls-crypt-v2: fix server memory leak (about 600 bytes per connecting - client with tls-crypt-v2) + This can be an OpenVPN 2.3.6 or earlier version. ``compat-version 2.3.0`` will + enable TLS 1.0 support if supported by the OpenSSL distribution. Note that + on some Linux distributions enabling TLS 1.1 or 1.0 is not possible. -- rework handling of server-pushed ``--auth-token`` in combination with - ``--auth-nocache`` on reconnection / TLS renegotiation events. This - used to "forget" to update new incoming token after a reconnection event - (leading to failure to reauth some time later) and now works in all - tested cases. -Overview of changes in 2.5.0 -============================ +Overview of changes in 2.5 +========================== New features ------------ @@ -1216,4 +1229,3 @@ Version 2.4.1 ``--remote-cert-tls`` uses the far more common keyUsage and extendedKeyUsage extension instead. Make sure your certificates carry these to be able to use ``--remote-cert-tls``. - diff --git a/INSTALL b/INSTALL index 9db5b645744..a63bab6acd6 100644 --- a/INSTALL +++ b/INSTALL @@ -1,6 +1,6 @@ Installation instructions for OpenVPN, a Secure Tunneling Daemon -Copyright (C) 2002-2019 OpenVPN Inc. This program is free software; +Copyright (C) 2002-2022 OpenVPN Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. @@ -24,9 +24,9 @@ OpenVPN releases are also available as Debian/RPM packages: OpenVPN development versions can be found here: - https://github.com/OpenVPN/openvpn - https://gitlab.com/OpenVPN/openvpn - https://sourceforge.net/p/openvpn/openvpn/ci/master/tree/ + https://github.com/OpenVPN/openvpn + https://gitlab.com/OpenVPN/openvpn + https://sourceforge.net/p/openvpn/openvpn/ci/master/tree/ They should all be in sync at any time. @@ -38,6 +38,10 @@ To download tap-windows (NDIS 6) driver source code go to: https://github.com/OpenVPN/tap-windows6 +To download ovpn-dco Windows driver source code go to: + + https://github.com/OpenVPN/ovpn-dco-win + To get the cross-compilation environment go to: https://github.com/OpenVPN/openvpn-build @@ -52,45 +56,39 @@ Also see the man page for more information. ************************************************************************* -SUPPORTED PLATFORMS: - (1) Linux (kernel 2.6+) - (2) Solaris - (3) OpenBSD 5.1+ - (4) Mac OS X Darwin 10.5+ - (5) FreeBSD 7.4+ - (6) NetBSD 5.0+ - (7) Windows Vista or later for OpenVPN 2.4 - (8) Windows XP or later for OpenVPN 2.3 - -SUPPORTED PROCESSOR ARCHITECTURES: - In general, OpenVPN is word size and endian independent, so - most processors should be supported. Architectures known to - work include Intel x86, Alpha, Sparc, Amd64, and ARM. - -REQUIRES: +For a list of supported platforms and architectures, and for +instructions how to port OpenVPN to a yet-unsupported architecture, +see the file "PORTS". + +************************************************************************* + +SYSTEM REQUIREMENTS: (1) TUN and/or TAP driver to allow user-space programs to control - a virtual point-to-point IP or Ethernet device. See - TUN/TAP Driver Configuration section below for more info. - (2) OpenSSL library, necessary for encryption, version 1.0.2 or higher + a virtual point-to-point IP or Ethernet device. + See TUN/TAP Driver References section below for more info. + (2a) OpenSSL library, necessary for encryption, version 1.0.2 or higher required, available from http://www.openssl.org/ or - (3) mbed TLS library, an alternative for encryption, version 2.0 or higher + (2b) mbed TLS library, an alternative for encryption, version 2.0 or higher required, available from https://tls.mbed.org/ + (3) on Linux, "libnl-gen" is required for kernel netlink support + (4) on Linux, "libcap-ng" is required for Linux capability handling OPTIONAL: - (3) LZO real-time compression library, required for link compression, + (5) LZO real-time compression library, required for link compression, available from http://www.oberhumer.com/opensource/lzo/ - OpenBSD users can use ports or packages to install lzo, but remember - to add CFLAGS="-I/usr/local/include" LDFLAGS="-L/usr/local/lib" - directives to "configure", since gcc will not find them otherwise. + (most supported operating systems have LZO in their installable + packages repository. It might be necessary to add LZO_CFLAGS= + and LZO_LIBS= to the configure call to make it find the LZO pieces) + (6) LZ4 compression library OPTIONAL (for developers only): - (1) Autoconf 2.59 or higher + Automake 1.9 or higher - -- available from http://www.gnu.org/software/software.html - (2) Dmalloc library - -- available from http://dmalloc.com/ + (1) Autoconf 2.59 or higher + Automake 1.9 or higher + Libtool + Git + (2) cmocka test framework (http://cmocka.org) (3) If using t_client.sh test framework, fping/fping6 is needed - -- Available from http://www.fping.org/ Note: t_client.sh needs an external configured OpenVPN server. See t_client.rc-sample for more info. @@ -106,7 +104,7 @@ CHECK OUT SOURCE FROM SOURCE REPOSITORY: Check out stable version: - git checkout release/2.4 + git checkout release/2.6 Check out master (unstable) branch: @@ -119,7 +117,7 @@ BUILD COMMANDS FROM TARBALL: ./configure make - make install + sudo make install ************************************************************************* @@ -128,7 +126,7 @@ BUILD COMMANDS FROM SOURCE REPOSITORY CHECKOUT: autoreconf -i -v -f ./configure make - make install + sudo make install ************************************************************************* @@ -175,98 +173,17 @@ you can install cmocka with these commands: OPTIONS for ./configure: - --disable-lzo disable LZO compression support [default=yes] - --disable-lz4 Disable LZ4 compression support - --enable-comp-stub Don't compile compression support but still allow limited interoperability with compression-enabled peers - --disable-crypto disable crypto support [default=yes] - --disable-ofb-cfb disable support for OFB and CFB cipher modes - [default=yes] - --enable-x509-alt-username - enable the --x509-username-field feature - [default=no] - --disable-server disable server support only (but retain client - support) [default=yes] - --disable-plugins disable plug-in support [default=yes] - --disable-management disable management server support [default=yes] - --enable-pkcs11 enable pkcs11 support [default=no] - --disable-fragment disable internal fragmentation support (--fragment) - [default=yes] - --disable-multihome disable multi-homed UDP server support (--multihome) - [default=yes] - --disable-port-share disable TCP server port-share support (--port-share) - [default=yes] - --disable-debug disable debugging support (disable gremlin and verb - 7+ messages) [default=yes] - --enable-small enable smaller executable size (disable OCC, usage - message, and verb 4 parm list) [default=no] - --enable-iproute2 enable support for iproute2 [default=no] - --disable-def-auth disable deferred authentication [default=yes] - --disable-pf disable internal packet filter [default=yes] - --disable-plugin-auth-pam - disable auth-pam plugin [default=platform specific] - --disable-plugin-down-root - disable down-root plugin [default=platform specific] - --enable-pam-dlopen dlopen libpam [default=no] - --enable-strict enable strict compiler warnings (debugging option) - [default=no] - --enable-pedantic enable pedantic compiler warnings, will not generate - a working executable (debugging option) [default=no] - --enable-werror promote compiler warnings to errors, will cause - builds to fail if the compiler issues warnings - (debugging option) [default=no] - --enable-strict-options enable strict options check between peers (debugging - option) [default=no] - --enable-selinux enable SELinux support [default=no] - --enable-systemd enable systemd support [default=no] - --enable-async-push enable async-push support for plugins providing - deferred authentication [default=no] + To get an overview of all the configure options, run "./configure --help" ENVIRONMENT for ./configure: - PLUGINDIR Path of plug-in directory [default=LIBDIR/openvpn/plugins] - IFCONFIG full path to ipconfig utility - ROUTE full path to route utility - IPROUTE full path to ip utility - NETSTAT path to netstat utility - GIT path to git utility - SYSTEMD_ASK_PASSWORD - path to systemd-ask-password utility - SYSTEMD_UNIT_DIR - Path of systemd unit directory [default=LIBDIR/systemd/system] - TMPFILES_DIR - Path of tmpfiles directory [default=LIBDIR/tmpfiles.d] - RST2MAN Path to rst2man utility - RST2HTML Path to rst2html utility - -ENVIRONMENT variables adjusting parameters related to dependencies - - TAP_CFLAGS C compiler flags for tap - LIBPAM_CFLAGS - C compiler flags for libpam - LIBPAM_LIBS linker flags for libpam - PKCS11_HELPER_CFLAGS - C compiler flags for PKCS11_HELPER, overriding pkg-config - PKCS11_HELPER_LIBS - linker flags for PKCS11_HELPER, overriding pkg-config - OPENSSL_CFLAGS - C compiler flags for OpenSSL - OPENSSL_LIBS - linker flags for OpenSSL - MBEDTLS_CFLAGS - C compiler flags for mbedtls - MBEDTLS_LIBS - linker flags for mbedtls - LZO_CFLAGS C compiler flags for lzo - LZO_LIBS linker flags for lzo - LZ4_CFLAGS C compiler flags for lz4 - LZ4_LIBS linker flags for lz4 - libsystemd_CFLAGS - C compiler flags for libsystemd, overriding pkg-config - libsystemd_LIBS - linker flags for libsystemd, overriding pkg-config - P11KIT_CFLAGS - C compiler flags for P11KIT, overriding pkg-config - P11KIT_LIBS linker flags for P11KIT, overriding pkg-config + For more fine-grained control on include + library paths for external + components etc., configure can be called with environment variables on + the command line, e.g. + + ./configure OPENSSL_CFLAGS="-I/usr/local/include" ... + + these are also explained in "./configure --help", so not repeated here. ************************************************************************* @@ -302,13 +219,13 @@ For more details: * Ubuntu https://packages.ubuntu.com/search?keywords=openvpn -In addition, the OpenVPN community provides a best-effort APT repository -for Debian and Ubuntu: +In addition, the OpenVPN community provides best-effort package +repositories for CentOS/Fedora, Debian and Ubuntu: https://community.openvpn.net/openvpn/wiki/OpenvpnSoftwareRepos ************************************************************************* -TUN/TAP Driver Configuration: +TUN/TAP Driver References: * Linux 2.6 or higher (with integrated TUN/TAP driver): @@ -322,17 +239,17 @@ TUN/TAP Driver Configuration: FreeBSD ships with the TUN/TAP driver, and the device nodes for tap0, tap1, tap2, tap3, tun0, tun1, tun2 and tun3 are made by default. - However, only the TUN driver is linked into the GENERIC kernel. - To load the TAP driver, enter: + On FreeBSD versions prior to 12.0-RELEASE, there were independent + TUN and TAP drivers, and the TAP driver needed to be loaded manually, + using the command: - kldload if_tap + # kldload if_tap - See man rc(8) to find out how you can do this at boot time. + For recent FreeBSD versions, TUN/TAP are integrated and always loaded. - The easiest way is to install OpenVPN from the FreeBSD ports system, - the port includes a sample script to automatically load the TAP driver - at boot-up time. + FreeBSD 14 contains the ovpn(4) for kernel-level OpenVPN acceleration + (DCO) which will be used by OpenVPN 2.6 and up if available. * OpenBSD: @@ -350,35 +267,17 @@ TUN/TAP Driver Configuration: OpenVPN on Windows needs a TUN/TAP kernel driver to work. OpenVPN installers include this driver, so installing it separately is not usually required. - Windows XP/2003 must use the NDIS 5 (tap-windows) driver, whereas on more - recent Windows versions it is recommended to use the NDIS 6 driver - (tap-windows6) instead. + + Starting from Windows 10 2004 / Windows Server 2022, OpenVPN can use the + dco-win driver for kernel-level acceleration for OpenVPN client setups. + This driver is also included in the community-provided OpenVPN installers. ************************************************************************* CAVEATS & BUGS: -* I have noticed cases where TCP sessions tunneled over the Linux - TAP driver (kernel 2.4.21 and 2.4.22) stall when lower --mssfix - values are used. The TCP sessions appear to unstall and resume - normally when the remote VPN endpoint is pinged. - -* If run through a firewall using OpenBSDs packet filter PF and the - filter rules include a "scrub" directive, you may get problems talking - to Linux hosts over the tunnel, since the scrubbing will kill packets - sent from Linux hosts if they are fragmented. This is usually seen as - tunnels where small packets and pings get through but large packets - and "regular traffic" don't. To circumvent this, add "no-df" to - the scrub directive so that the packet filter will let fragments with - the "dont fragment"-flag set through anyway. - -* Mixing OFB or CFB cipher modes with static key mode is not recommended, - and is flagged as an error on OpenVPN versions 1.2.1 and greater. - If you use the --cipher option to explicitly select an OFB or CFB - cipher AND you are using static key mode, it is possible that there - could be an IV collision if the OpenVPN daemons on both sides - of the connection are started at exactly the same time, since - OpenVPN uses a timestamp combined with a sequence number as the cipher - IV for OFB and CFB modes. This is not an issue if you are - using CBC cipher mode (the default), or if you are using OFB or CFB - cipher mode with SSL/TLS authentication. +* See the bug tracker on https://github.com/OpenVPN/openvpn/issues + and the wiki on https://community.openvpn.net/wiki for more detailed + caveats on operating systems, and for open and resolved bug reports. +* Note: We only recently switched to GitHub for reporting new issues, + old issues can be found at https://community.openvpn.net/openvpn/report diff --git a/Makefile.am b/Makefile.am index 28a7ef76fb2..31a08a837da 100644 --- a/Makefile.am +++ b/Makefile.am @@ -5,8 +5,8 @@ # packet encryption, packet authentication, and # packet compression. # -# Copyright (C) 2002-2022 OpenVPN Inc -# Copyright (C) 2010-2022 David Sommerseth +# Copyright (C) 2002-2023 OpenVPN Inc +# Copyright (C) 2010-2023 David Sommerseth # Copyright (C) 2006-2012 Alon Bar-Lev # # This program is free software; you can redistribute it and/or modify @@ -54,7 +54,6 @@ SUBDIRS = build distro include src sample doc tests dist_doc_DATA = \ README \ - README.IPv6 \ README.mbedtls \ Changes.rst \ COPYRIGHT.GPL \ @@ -64,7 +63,6 @@ dist_noinst_DATA = \ .gitignore \ .gitattributes \ PORTS \ - README.IPv6 TODO.IPv6 \ README.mbedtls \ openvpn.sln @@ -92,4 +90,4 @@ config-version.h: fi doxygen: - $(MAKE) -C doc/doxygen doxygen + $(MAKE) -C doc/doxygen doxygen \ No newline at end of file diff --git a/PORTS b/PORTS index ff76850dd2a..32d3dab24af 100644 --- a/PORTS +++ b/PORTS @@ -1,5 +1,5 @@ OpenVPN -Copyright (C) 2002-2022 OpenVPN Inc +Copyright (C) 2002-2023 OpenVPN Inc OpenVPN has been written to try to avoid features that are not standardized well across different @@ -11,20 +11,31 @@ Copyright (C) 2002-2022 OpenVPN Inc PLATFORM STATUS: - * Linux 2.2+ (supported) - * Solaris (supported) - * OpenBSD 3.0 (supported but pthreads are broken) - * Max OS X Darwin +Tier 1 platforms - actively tested for every source commit, across +multiple operating system versions + + * Windows 7 and newer + * Windows Server 2012 and newer + * Linux * FreeBSD + * macOS + +Tier 2 platforms - it worked at some point, but is not actively tested +on "latest OS, latest OS libraries" so might break if larger changes +are done on the platform side + + * OpenBSD * NetBSD - * Windows - * 64 bit platforms -- I have heard reports that - OpenVPN runs on Alpha Linux and FreeBSD. - * ARM -- I have heard of at least one case - where OpenVPN was successfully built and - run on the ARM architecture. + * DragonFly BSD + * Solaris + * AIX + +For underlying CPU architecture, everything 32 bit or 64 bit (Intel, AMD, +ARM, PowerPC, SPARC*) should work fine. 16 bit Architectures are unlikely +to work. + -PORTING NOTES: +PORTING GUIDELINE TO A NEW PLATFORM: * Make sure that OpenSSL will build on your platform. @@ -42,7 +53,7 @@ PORTING NOTES: function in tun.c to generate a correct "ifconfig" command for your platform. Note that OpenVPN determines the ifconfig path at ./configure time. - * Add an ifconfig_order() variant for your OS so + * Possibly add an ifconfig_order() variant for your OS so openvpn knows whether to call ifconfig before or after tun/tap dev open. * Add an #ifdef TARGET_YOUROS block in tun.c and define @@ -77,12 +88,8 @@ PORTING NOTES: disabled with an explicit ioctl call if cross-platform compatibility is to be preserved. You can see some examples of this in tun.c. - * If your system supports pthreads, try building - with ./configure --enable-pthread and do a stress - test in TLS mode. - * Try the ultimate stress test which is --gremlin - --reneg-sec 10 in TLS mode (preferably with pthreads - enabled), then do a flood ping across the tunnel + * Try the ultimate stress test which is --gremlin --reneg-sec 10 + in TLS mode then do a flood ping across the tunnel (ping -f remote-endpoint) in both directions and let it run overnight. --gremlin will induce massive corruption and packet loss, but you win if you @@ -91,4 +98,4 @@ PORTING NOTES: attempted once-per-10-seconds TLS handshake. * When it's working, submit your patch to - and rejoice :) + and rejoice :) \ No newline at end of file diff --git a/README b/README index b75a568e93e..04eb16ff9fe 100644 --- a/README +++ b/README @@ -1,6 +1,6 @@ OpenVPN -- A Secure tunneling daemon -Copyright (C) 2002-2018 OpenVPN Inc. This program is free software; +Copyright (C) 2002-2022 OpenVPN Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. @@ -9,7 +9,7 @@ as published by the Free Software Foundation. To get the latest release of OpenVPN, go to: - https://openvpn.net/index.php/download/community-downloads.html + https://openvpn.net/community-downloads/ To Build and Install, @@ -30,7 +30,10 @@ For a sample VPN configuration, see http://openvpn.net/howto.html To report an issue, see - https://community.openvpn.net/openvpn/report + https://github.com/OpenVPN/openvpn/issues/new + (Note: We recently switched to GitHub for reporting new issues, + old issues can be found at: + https://community.openvpn.net/openvpn/report) For a description of OpenVPN's underlying protocol, see the file ssl.h included in the source distribution. @@ -64,7 +67,7 @@ Note that easy-rsa and tap-windows are now maintained in their own subprojects. Their source code is available here: https://github.com/OpenVPN/easy-rsa - https://github.com/OpenVPN/tap-windows + https://github.com/OpenVPN/tap-windows6 The old cross-compilation environment (domake-win) and the Python-based buildsystem have been replaced with openvpn-build: diff --git a/README.IPv6 b/README.IPv6 deleted file mode 100644 index 18068feede5..00000000000 --- a/README.IPv6 +++ /dev/null @@ -1,56 +0,0 @@ -Since 2.3.0, OpenVPN officially supports IPv6, and all widely used -patches floating around for older versions have been integrated. - -IPv6 payload support --------------------- - -This is for "IPv6 inside OpenVPN", with server-pushed IPv6 configuration -on the client, and support for IPv6 configuration on the tun/tap interface -from within the openvpn config. - -The code in 2.3.0 supersedes the IPv6 payload patches from Gert Doering, -formerly located at http://www.greenie.net/ipv6/openvpn.html - - -The following options have been added to handle IPv6 configuration, -analogous to their IPv4 counterparts (--server <-> --server-ipv6, etc.) - - - server-ipv6 - - ifconfig-ipv6 - - ifconfig-ipv6-pool - - ifconfig-ipv6-push - - route-ipv6 - - iroute-ipv6 - -see "man openvpn" for details how they are used. - - - -IPv6 transport support ----------------------- - -This is to enable OpenVPN peers or client/servers to talk to each other -over an IPv6 network ("OpenVPN over IPv6"). - -The code in 2.3.0 supersedes the IPv6 transport patches from JuanJo Ciarlante, -formerly located at http://github.com/jjo/openvpn-ipv6 - -OpenVPN 2.4.0 includes a big overhaul of the IPv6 transport patches -originally implemented for the Android client (ics-openvpn) - -IPv4/IPv6 transport is automatically is selected when resolving addresses. -Use a 6 or 4 suffix to force IPv6/IPv4: - - --proto udp6 - --proto tcp4 - --proto tcp6-client - --proto tcp4-server - --proto tcp6 --client / --proto tcp6 --server - -On systems that allow IPv4 connections on IPv6 sockets -(all systems supporting IPV6_V6ONLY setsockopt), an OpenVPN server can -handle IPv4 connections on the IPv6 socket as well, making it a true -dual-stacked server. Use bind ipv6only to disable this behaviour. - -On other systems, as of 2.3.0, you need to run separate server instances -for IPv4 and IPv6. diff --git a/README.dco.md b/README.dco.md new file mode 100644 index 00000000000..aa93d667660 --- /dev/null +++ b/README.dco.md @@ -0,0 +1,131 @@ +OpenVPN data channel offload +============================ +2.6.0+ implements support for data-channel offloading where the data packets +are directly processed and forwarded in kernel space thanks to the ovpn-dco +kernel module. The userspace openvpn program acts purely as a control plane +application. + + +Overview of current release +--------------------------- +- See the "Limitations by design" and "Current limitations" sections for + features that are not and/or will not be supported by OpenVPN + ovpn-dco. + + +Getting started (Linux) +----------------------- +- Use a recent Linux kernel. Linux 5.4.0 and newer are known to work with + ovpn-dco. + +Get the ovpn-dco module from one these urls and build it: + +* https://gitlab.com/openvpn/ovpn-dco +* https://github.com/OpenVPN/ovpn-dco + +e.g. + + git clone https://github.com/OpenVPN/ovpn-dco + cd ovpn-dco + make + sudo make install + +If you want to report bugs please ensure to compile ovpn-dco with +`make DEBUG=1` and include any debug message being printed by the +kernel (you can view those messages with `dmesg`). + +Clone and build OpenVPN (or use OpenVPN 2.6+). For example: + + git clone https://github.com/openvpn/openvpn.git + cd openvpn + autoreconf -vi + ./configure --enable-dco + make + sudo make install # Or just run src/openvpn/openvpn + +When starting openvpn it will automatically detect DCO support and use the +kernel module. Add the option `--disable-dco` to disable data channel offload +support. If the configuration contains an option that is incompatible with +data channel offloading, OpenVPN will automatically disable DCO support and +warn the user. + +Should OpenVPN be configured to use a feature that is not supported by ovpn-dco +or should the ovpn-dco kernel module not be available on the system, you will +see a message like + + Note: Kernel support for ovpn-dco missing, disabling data channel offload. + +in your log. + + +Getting started (Windows) +------------------------- +The simplest way to test DCO under Windows is to download the latest installer +from https://build.openvpn.net/downloads/snapshots/github-actions/openvpn2/ . +This installer contains the latest OpenVPN code and the ovpn-dco-win driver. + + +DCO and P2P mode +---------------- +DCO is also available when running OpenVPN in P2P mode without `--pull` / +`--client` option. P2P mode is useful for scenarios when the OpenVPN tunnel +should not interfere with overall routing and behave more like a "dumb" tunnel, +like GRE. + +However, DCO requires DATA_V2 to be enabled, which is available for P2P mode +only in OpenVPN 2.6 and later. + +OpenVPN prints a diagnostic message for the P2P NCP result when running in P2P +mode: + + P2P mode NCP negotiation result: TLS_export=1, DATA_v2=1, peer-id 9484735, cipher=AES-256-GCM + +Double check that you have `DATA_v2=1` in your output and a supported AEAD +cipher (AES-XXX-GCM or CHACHA20POLY1305). + + +Routing with ovpn-dco +--------------------- +The ovpn-dco kernel module implements a more transparent approach to +configuring routes to clients (aka "iroutes") and consults the main kernel +routing tables for forwarding decisions. + +- Each client has a VPN IPv4 and/or a VPN IPv6 assigned to it; +- additional IP ranges can be routed to a client by adding a route with + a client VPN IP as the gateway/nexthop (i.e. ip route add a.b.c.d/24 via + $VPNIP); +- due to the point above, there is no real need to add a companion `--route` for + each `--iroute` directive, unless you want to blackhole traffic when the + specific client is not connected; +- no internal routing is available. If you need truly internal routes, this can + be achieved either with filtering using `iptables` or using `ip rule`; +- client-to-client behaviour, as implemented in userspace, does not exist: + packets always reach the tunnel interface and are then re-routed to the + destination peer based on the system routing table. + + +Limitations by design +---------------------- +- Layer 3 (dev tun) only; +- only the following AEAD ciphers are currently supported: Chacha20-Poly1305 + and AES-GCM-128/192/256; +- no support for compression or compression framing: + - see also the `--compress migrate` option to move to a setup without + compression; +- various features not implemented since they have better replacements: + - `--shaper`, use tc instead; + - packet manipulation, use nftables/iptables instead; +- OpenVPN 2.4.0 is the minimum version required for peers to connect: + - older versions are missing support for the AEAD ciphers; +- topology subnet is the only supported `--topology` for servers; +- iroute directives install routes on the host operating system, see also + Routing with ovpn-dco; +- (ovpn-dco-win) client and p2p mode only; +- (ovpn-dco-win) Chacha20-Poly1305 support available starting with Windows 11. + + +Current implementation limitations +------------------- +- `--persist-tun` not tested; +- IPv6 mapped IPv4 addresses need Linux 5.4.189+/5.10.110+/5.12+ to work; +- some incompatible options may not properly fallback to non-dco; +- no per client statistics. Only total statistics available on the interface. diff --git a/README.mbedtls b/README.mbedtls index 4875822da47..d3466fa9079 100644 --- a/README.mbedtls +++ b/README.mbedtls @@ -11,6 +11,24 @@ This version depends on mbed TLS 2.0 (and requires at least 2.0.0). ************************************************************************* +Warning: + +As of mbed TLS 2.17, it can be licensed *only* under the Apache v2.0 license. +That license is incompatible with OpenVPN's GPLv2. + +If you wish to distribute OpenVPN linked with mbed TLS, there are two options: + + * Ensure that your case falls under the system library exception in GPLv2, or + + * Use an earlier version of mbed TLS. Version 2.16.12 is the last release + that may be licensed under GPLv2. Unfortunately, this version is + unsupported and won't receive any more updates. + +If nothing changes about the license situation, mbed TLS support may be +deprecated in a future release of OpenVPN. + +************************************************************************* + Due to limitations in the mbed TLS library, the following features are missing in the mbed TLS version of OpenVPN: diff --git a/README.wolfssl b/README.wolfssl new file mode 100644 index 00000000000..a5dfe31f970 --- /dev/null +++ b/README.wolfssl @@ -0,0 +1,30 @@ +Support for wolfSSL is implemented and maintained by wolfSSL Inc. The support is +implemented using wolfSSL's compatibility layer. The wolfSSL support in OpenVPN +receives very limited testing/support from the OpenVPN community itself. + +If bugs in OpenVPN when using wolfSSL are encountered, the user should try to +also compile OpenVPN with OpenSSL to determine if these are bugs in the +wolfSSL TLS implementation or OpenVPN itself. If bugs are caused by compiling +with wolfSSL, please contact support@wolfssl.com directly. + +To Build and Install, + + ./configure --with-crypto-library=wolfssl + make + make install + + +The wolfSSL library will include the installed options.h file by default. +To include a custom user_settings.h file for wolfSSL, + +./configure --with-crypto-library=wolfssl --disable-wolfssl-options-h +make +make install + +************************************************************************* +Due to limitations in the wolfSSL TLS library or its compatibility layer, the +following features are missing + + * blowfish support (BF-CBC), you must use something like + cipher AES-128-CBC to avoid trying to use BF-CBC + * Windows CryptoAPI support diff --git a/TODO.IPv6 b/TODO.IPv6 deleted file mode 100644 index 465eaa66d97..00000000000 --- a/TODO.IPv6 +++ /dev/null @@ -1,215 +0,0 @@ -TODO for IPv6 payload support ------------------------------ - -1.) "--topology subnet" doesn't work together with IPv6 payload on FreeBSD - (verified for FreeBSD server, Linux/ifconfig client, problems - with ICMP6 neighbor solicitations from BSD not being answered by Linux) - - * 2012-01-22 fixed in platform cleanup, commit 62c613d46dc495d74 - -2.) NetBSD IPv6 support doesn't work - ("connected" route is not auto-created, "route-ipv6" adding fails) - - * fixed, 3.1.10 * - -3.) route deletion for IPv6 routes is not yet done - - * fixed for configured routes, 3.1.10 * - * missing for manual-ifconfig-connected (NetBSD, Darwin, Win32) - - * 2012-06-10 - fixed somewhere in 2010 - -4.) do "ifconfig tun0 inet6 unplumb" or "ifconfig tun0 destroy" for - Solaris, *BSD, ... at program termination time, to clean up leftovers - (unless tunnel persistence is desired). - - For Solaris, only the "ipv6 tun0" is affected, for the *BSDs all tun0 - stay around. - - * 2012-06-10 - fixed in individual platform cleanups early-2012 - -4a.) deconfigure IPv6 on tun interface on session termination, otherwise - one could end up with something like this (on NetBSD): - -tun0: flags=8051 mtu 1500 - inet 10.9.0.18 -> 10.9.0.17 netmask 0xffffffff - inet6 fe80::a00:20ff:fece:d299%tun0 -> prefixlen 64 scopeid 0x3 - inet6 2001:608:4:eff::2000:3 -> prefixlen 64 - inet6 2001:608:4:eff::1:3 -> prefixlen 64 - - (pool was changed, previous address still active on tun0, breakage) - - * semi-fixed for NetBSD, 28.2.10, always do tun0 destroy / tun0 create - before actual ifconfig -- tunnel still lingers after OpenVPN quits - - * 2011-09-16 fixed in platform cleanup, commit 8ca19c014c149cf69 - -4b.) verify this - on FreeBSD, tun0 is auto-destroyed if created by - opening /dev/tun (and lingers if created by "ifconfig tun0 create") - - -> use for persistent tunnels on not-linux? - - * 2012-06-10 tun interface behaviour is documented in "man tun(4)" - -5.) add new option "ifconfig-ipv6-push" - (per-client static IPv6 assignment, -> radiusplugin, etc) - - * implemented, 14.1.10 * - -6.) add new option "route-ipv6-gateway" - - * 2012-06-09 - decided there is no current need (but fairly trivial) - -7.) add "full" gateway handling for IPv6 in route.c - (right now, the routes are just sent down the tun interface, if the - operating system in questions supports that, without care for the - gateway address - which does not work for gateways that are supposed - to point elsewhere. Also, it doesn't work for TAP interfaces. - - * 2012-06-09 use "dev tun" for tun devices, "via $gateway" for tap - (and purposely do not support off-link routes) - -8.) full IPv6 support for TAP interfaces - (main issue should be routes+gateway - and testing :-) ) - - test 2010/09/24: TAP itself works on linux/ifconfig+iproute2, but - route-via-tap doesn't work at all (route points to "tap0" which fails) - -17:51:14.075412 fe:ab:6e:c5:53:71 > 33:33:ff:00:00:01, ethertype IPv6 (0x86dd), length 86: 2001:608:4:a053::1:0 > ff02::1:ff00:1: ICMP6, neighbor solicitation, who has 2001:608:4:a001::1, length 32 - - * 2012-06-09 missing gateway support implemented - -8a.) - how is iroute-via-tap supposed to work?? - - * 2012-06-10 - answer: not at all, OpenVPN doesn't do "iroute" in - tap mode - set up "route-ipv6" with gateway address = individual - client's tap0 address to get the per-client routes - - -9.) verify that iroute-ipv6 and route-ipv6 interact in the same way as - documented for iroute/route: - - A's subnet, OpenVPN must push this route to all clients - EXCEPT for A, since the subnet is already owned by A. - OpenVPN accomplishes this by not - not pushing a route to a client - if it matches one of the client's iroutes. - -10.) extend "ifconfig-ipv6" to handle specification of /netbits, pushing - of /netbits, and correctly ifconfig'ing this - (default, if not specified: /64) - - * done * 2012-02-03 - -11.) do not add ipv6-routes if tun-ipv6 is not set - complain instead - - * done * 12.1.10 - -12.) handle incoming [::] and [fe80:...] packets in tun-p2mp MULTI mode - (most likely those are DAD packets) - silently ignore DAD? - Or accept-and-forward iff (multicast && client2client)? - handle NS/NA - -13.) from Martin List-Petersen: - - One thing, and I guess this requires modifications in - network-manager-openvpn: It also works, BUT ignores "push - route-ipv6-gateway" and "push route-ipv6 ...." (obviously routes pushed - from the server) entirely. - -14.) from ##openvpn-discussion: - - new features should be #ifdef'ed - - (check whether this is feasible at all) - -15.) IPv6 related environment variables - - - document all of them in openvpn.8 - - make sure that all existing IPv4 stuff has IPv6 counterparts - -16.) OpenBSD - - implement ifconfig/route for IPv6 - - revert ifconfig/open_tun order to "normal" (separate commit!!!) - (openvpn-devel, Subject: OpenBSD) - - test - - * 2012-02-05 platform cleanup, commit 82d4e12068774b0a6ca - -17.) client-option (Elwood) - - ignore-v6-push-options yes/no - - ignore-v6-route-push ("as for IPv4 routes") - -18.) fail-save? "what if 'ip -6 addr add' fails" -> fail, or fallback to v4? - (-> recomment setting "ignore-v6-push-options yes") - -19.) safety check: if connecting over IPv6 (v6 transport) and the pushed - route-ipv6 network encompasses the server IPv6 address, make sure - we at least log a warning (until we can fiddle with external routing - to make this work correctly). - -20.) show "route add" / "route delete" commands for IPv6 in log file - (we show the "ifconfig" commands, so why not the routes?) - - 2010-08-07: this is a null-feature - it's already there, but with - different debug level (M_INFO vs. D_ROUTE) so user - didn't notice - -21.) enable ipv6-only server operations - - decouple ipv6 pool handling from ipv4 pool - - make sure Rest of OpenVPN doesn't assume "there will always be IPv4" - -22.) implement --learn-address for IPv6 - -23.) FreeBSD 8 seems to require explicit setting of the "ifconfig" IPv6 - route, while FreeBSD 6+7 don't --> more testing, and code fix - - workaround for the time being: just add - - server-ipv6 2001:608:4:a051::/64 - route-ipv6 2001:608:4:a051::/64 - - to the config - - (problem + workaround applies both to tun and tap style devices) - - * 2012-06-09 - this got fixed in one of the platform cleanups - - - - -TODO for IPv6 transport support -------------------------------- - -[ Last updated: 2014-01-03. ] - -* All platforms: - o mgmt console: as currently passes straight in_addr_t bits around - - o make possible to get AF from getaddrinfo() answer, ie allow openvpn to - use ipv4/6 if DNS returns A/AAAA without specifying protocol. - Hard: requires deep changes in initialization/calling logic - - Done by dual stack patches - - o use AI_PASSIVE - - Done by dual stack patches - - o the getaddr()/getaddr6() interface is not prepared for handling socktype - "tagging", currently I abuse the sockflags bits for getting the ai_socktype - downstream. - - Still done by flags, seems clean enough. - - o implement comparison for mapped addresses: server in dual stack - listening IPv6 must permit incoming streams from allowed IPv4 peer, - currently you need to pass eg: --remote ffff::1.2.3.4 - - OpenVPN will compare all address of a remote - but will still fail on mapped addresses - -* win32: - o find out about mapped addresses, as I can't make it work - with bound at ::1 and connect to 127.0.0.1 - - Should be fixed by 8832c6c - "Implement listing on IPv4/IPv6 dual - socket on all platform" - diff --git a/build/Makefile.am b/build/Makefile.am index 6305ac1ffbe..9324100d5f0 100644 --- a/build/Makefile.am +++ b/build/Makefile.am @@ -5,7 +5,7 @@ # packet encryption, packet authentication, and # packet compression. # -# Copyright (C) 2002-2022 OpenVPN Inc +# Copyright (C) 2002-2023 OpenVPN Inc # MAINTAINERCLEANFILES = \ @@ -14,4 +14,4 @@ MAINTAINERCLEANFILES = \ EXTRA_DIST = \ ltrc.inc -SUBDIRS = msvc +SUBDIRS = msvc \ No newline at end of file diff --git a/build/msvc/Makefile.am b/build/msvc/Makefile.am index 77e14ea006d..008e90fcce0 100644 --- a/build/msvc/Makefile.am +++ b/build/msvc/Makefile.am @@ -5,11 +5,11 @@ # packet encryption, packet authentication, and # packet compression. # -# Copyright (C) 2002-2022 OpenVPN Inc +# Copyright (C) 2002-2023 OpenVPN Inc # Copyright (C) 2006-2012 Alon Bar-Lev # MAINTAINERCLEANFILES = \ $(srcdir)/Makefile.in -SUBDIRS = msvc-generate +SUBDIRS = msvc-generate \ No newline at end of file diff --git a/build/msvc/msvc-generate/Makefile.am b/build/msvc/msvc-generate/Makefile.am index 4c095c16793..a3f617ec75b 100644 --- a/build/msvc/msvc-generate/Makefile.am +++ b/build/msvc/msvc-generate/Makefile.am @@ -5,7 +5,7 @@ # packet encryption, packet authentication, and # packet compression. # -# Copyright (C) 2002-2022 OpenVPN Inc +# Copyright (C) 2002-2023 OpenVPN Inc # Copyright (C) 2006-2012 Alon Bar-Lev # @@ -15,4 +15,4 @@ MAINTAINERCLEANFILES = \ dist_noinst_DATA = \ msvc-generate.vcxproj \ Makefile.mak \ - msvc-generate.js + msvc-generate.js \ No newline at end of file diff --git a/build/msvc/msvc-generate/Makefile.mak b/build/msvc/msvc-generate/Makefile.mak index 1c1c4bab181..0f9da846a87 100644 --- a/build/msvc/msvc-generate/Makefile.mak +++ b/build/msvc/msvc-generate/Makefile.mak @@ -5,7 +5,7 @@ # packet encryption, packet authentication, and # packet compression. # -# Copyright (C) 2002-2022 OpenVPN Inc +# Copyright (C) 2002-2023 OpenVPN Inc # Copyright (C) 2008-2012 Alon Bar-Lev # Copyright (C) 2022-2022 Lev Stipakov # @@ -64,4 +64,4 @@ clean: -del "$(OUTPUT_PLUGIN)" -del "$(OUTPUT_PLUGIN_CONFIG)" -del "$(OUTPUT_MAN)" - -del "$(OUTPUT_MSVC_GIT_CONFIG)" + -del "$(OUTPUT_MSVC_GIT_CONFIG)" \ No newline at end of file diff --git a/build/msvc/msvc-generate/git-version.py b/build/msvc/msvc-generate/git-version.py index 00458955af9..b2164e80d06 100644 --- a/build/msvc/msvc-generate/git-version.py +++ b/build/msvc/msvc-generate/git-version.py @@ -5,7 +5,7 @@ # packet encryption, packet authentication, and # packet compression. # -# Copyright (C) 2022-2022 OpenVPN Inc +# Copyright (C) 2022-2023 OpenVPN Inc # Copyright (C) 2022-2022 Lev Stipakov # # This program is free software; you can redistribute it and/or modify @@ -72,4 +72,4 @@ def main(): print("Content of %s hasn't changed" % name) if __name__ == "__main__": - main() + main() \ No newline at end of file diff --git a/build/msvc/msvc-generate/msvc-generate.vcxproj b/build/msvc/msvc-generate/msvc-generate.vcxproj index eae94709408..70d411e4685 100644 --- a/build/msvc/msvc-generate/msvc-generate.vcxproj +++ b/build/msvc/msvc-generate/msvc-generate.vcxproj @@ -35,27 +35,27 @@ Makefile - v142 + v143 Makefile - v142 + v143 Makefile - v142 + v143 Makefile - v142 + v143 Makefile - v142 + v143 Makefile - v142 + v143 diff --git a/compat.m4 b/compat.m4 index e54a72031b5..8fa9abee128 100644 --- a/compat.m4 +++ b/compat.m4 @@ -47,23 +47,21 @@ ifdef( [AC_DEFUN([AC_PROG_SED], [AC_CHECK_PROGS([SED], [sed])])] ) ifdef( - [AC_TYPE_INT8_T], + [PKG_CHECK_VAR], , [ - AC_CHECK_HEADERS([inttypes.h stdint.h]) - test -z "${ac_cv_header_inttypes_h}${ac_cv_header_stdint_h}" && \ - AC_MSG_ERROR([Required inttypes.h stdint.h not found]) - - AC_DEFUN([AC_TYPE_INT8_T], []) - AC_DEFUN([AC_TYPE_INT16_T], []) - AC_DEFUN([AC_TYPE_INT32_T], []) - AC_DEFUN([AC_TYPE_INT64_T], []) - AC_DEFUN([AC_TYPE_UINT8_T], []) - AC_DEFUN([AC_TYPE_UINT16_T], []) - AC_DEFUN([AC_TYPE_UINT32_T], []) - AC_DEFUN([AC_TYPE_UINT64_T], []) + AC_DEFUN([PKG_CHECK_VAR], + [AC_REQUIRE([PKG_PROG_PKG_CONFIG]) + AC_ARG_VAR([$1], [value of $3 for $2, overriding pkg-config]) + + _PKG_CONFIG([$1], [variable="][$3]["], [$2]) + AS_VAR_COPY([$1], [pkg_cv_][$1]) + + AS_VAR_IF([$1], [""], [$5], [$4]) + ]) ] ) + if test -z "${docdir}"; then docdir="\$(datadir)/doc/\$(PACKAGE_NAME)" AC_SUBST([docdir]) diff --git a/config-msvc.h b/config-msvc.h index 47c5ba07ef6..db13f382b27 100644 --- a/config-msvc.h +++ b/config-msvc.h @@ -2,28 +2,21 @@ #define CONFIGURE_DEFINES "N/A" -#define ENABLE_DEF_AUTH 1 #define ENABLE_PF 1 #define ENABLE_CRYPTO_OPENSSL 1 #define ENABLE_FRAGMENT 1 #define ENABLE_HTTP_PROXY 1 #define ENABLE_LZO 1 #define ENABLE_LZ4 1 -#define NEED_COMPAT_LZ4 1 #define ENABLE_MANAGEMENT 1 -#define ENABLE_MULTIHOME 1 #define ENABLE_PKCS11 1 #define ENABLE_PLUGIN 1 #define ENABLE_PORT_SHARE 1 #define ENABLE_SOCKS 1 -#define HAVE_ERRNO_H 1 #define HAVE_FCNTL_H 1 -#define HAVE_CTYPE_H 1 -#define HAVE_STDARG_H 1 #define HAVE_STDIO_H 1 #define HAVE_STDLIB_H 1 -#define HAVE_STRDUP 1 #define HAVE_STRERROR 1 #define HAVE_STRINGS_H 1 #define HAVE_STRING_H 1 @@ -31,13 +24,10 @@ #define HAVE_SYSTEM 1 #define HAVE_TIME 1 #define HAVE_TIME_H 1 -#define HAVE_UNLINK 1 -#define HAVE_VSNPRINTF 1 #define HAVE_WINDOWS_H 1 #define HAVE_WINSOCK2_H 1 #define HAVE_WS2TCPIP_H 1 #define HAVE_IO_H 1 -#define HAVE_DIRECT_H 1 #define HAVE_SYS_TYPES_H 1 #define HAVE_SYS_STAT_H 1 #define HAVE_LZO_LZO1X_H 1 @@ -47,84 +37,17 @@ #define HAVE_ACCESS 1 #define HAVE_CHDIR 1 #define HAVE_CHSIZE 1 -#define HAVE_CPP_VARARG_MACRO_ISO 1 -#define HAVE_CTIME 1 -#define HAVE_EVP_CIPHER_CTX_SET_KEY_LENGTH 1 #define HAVE_IN_PKTINFO 1 -#define HAVE_MEMSET 1 -#define HAVE_PUTENV 1 -#define HAVE_STAT 1 - -#define HAVE_SOCKET 1 -#define HAVE_RECV 1 -#define HAVE_RECVFROM 1 -#define HAVE_SEND 1 -#define HAVE_SENDTO 1 -#define HAVE_LISTEN 1 -#define HAVE_ACCEPT 1 -#define HAVE_CONNECT 1 -#define HAVE_BIND 1 -#define HAVE_SELECT 1 -#define HAVE_GETHOSTBYNAME 1 -#define HAVE_INET_NTOA 1 -#define HAVE_SETSOCKOPT 1 -#define HAVE_GETSOCKOPT 1 -#define HAVE_GETSOCKNAME 1 -#define HAVE_POLL 1 #define HAVE_OPENSSL_ENGINE 1 -/* hardcode usage of OpenSSL 1.1.x */ -#define HAVE_EVP_MD_CTX_RESET 1 -#define HAVE_EVP_MD_CTX_FREE 1 -#define HAVE_EVP_MD_CTX_NEW 1 -#define HAVE_HMAC_CTX_RESET 1 -#define HAVE_HMAC_CTX_FREE 1 -#define HAVE_HMAC_CTX_NEW 1 -#define HAVE_SSL_CTX_GET_DEFAULT_PASSWD_CB_USERDATA 1 -#define HAVE_SSL_CTX_GET_DEFAULT_PASSWD_CB 1 -#define HAVE_SSL_CTX_NEW 1 -#define HAVE_SSL_CTX_SET_SECURITY_LEVEL 1 -#define HAVE_X509_GET0_PUBKEY 1 -#define HAVE_X509_STORE_GET0_OBJECTS 1 -#define HAVE_X509_OBJECT_FREE 1 -#define HAVE_X509_OBJECT_GET_TYPE 1 -#define HAVE_X509_GET0_NOTAFTER 1 -#define HAVE_X509_GET0_NOTBEFORE 1 -#define HAVE_EVP_PKEY_GET0_RSA 1 -#define HAVE_EVP_PKEY_GET0_EC_KEY 1 -#define HAVE_EVP_PKEY_GET0_DSA 1 -#define HAVE_RSA_SET_FLAGS 1 -#define HAVE_RSA_GET0_KEY 1 -#define HAVE_RSA_SET0_KEY 1 -#define HAVE_RSA_BITS 1 -#define HAVE_DSA_GET0_PQG 1 -#define HAVE_DSA_BITS 1 -#define HAVE_RSA_METH_NEW 1 -#define HAVE_RSA_METH_FREE 1 -#define HAVE_RSA_METH_SET_PUB_ENC 1 -#define HAVE_RSA_METH_SET_PUB_DEC 1 -#define HAVE_RSA_METH_SET_PRIV_ENC 1 -#define HAVE_RSA_METH_SET_PRIV_DEC 1 -#define HAVE_RSA_METH_SET_INIT 1 -#define HAVE_RSA_METH_SET_SIGN 1 -#define HAVE_RSA_METH_SET_FINISH 1 -#define HAVE_RSA_METH_SET0_APP_DATA 1 -#define HAVE_RSA_METH_GET0_APP_DATA 1 -#define HAVE_EC_GROUP_ORDER_BITS 1 -#define HAVE_EVP_CIPHER_CTX_RESET 1 - #define HAVE_EXPORT_KEYING_MATERIAL 1 #define HAVE_DIINSTALLDEVICE 1 -#define PATH_SEPARATOR '\\' -#define PATH_SEPARATOR_STR "\\" - #ifndef __cplusplus #define inline __inline #endif -#define EMPTY_ARRAY_SIZE 0 #define TARGET_WIN32 1 #define TARGET_ALIAS "Windows-MSVC" @@ -158,24 +81,13 @@ #define SIGUSR2 12 #define SIGTERM 15 -typedef unsigned __int64 uint64_t; -typedef unsigned __int32 uint32_t; -typedef unsigned __int16 uint16_t; -typedef unsigned __int8 uint8_t; -typedef __int64 int64_t; -typedef __int32 int32_t; -typedef __int16 int16_t; -typedef __int8 int8_t; +#include typedef uint16_t in_port_t; #ifdef HAVE_CONFIG_MSVC_LOCAL_H #include #endif -/* Vista and above has implementation of inet_ntop / inet_pton */ -#if _WIN32_WINNT >= _WIN32_WINNT_VISTA - #define HAVE_INET_NTOP - #define HAVE_INET_PTON -#endif +#define ENABLE_DCO 1 -#define HAVE_CONFIG_VERSION_H 1 +#define HAVE_CONFIG_VERSION_H 1 \ No newline at end of file diff --git a/configure.ac b/configure.ac index 2f5f6bc7c11..633cfcae507 100644 --- a/configure.ac +++ b/configure.ac @@ -4,7 +4,7 @@ dnl session authentication and key exchange, dnl packet encryption, packet authentication, and dnl packet compression. dnl -dnl Copyright (C) 2002-2022 OpenVPN Inc +dnl Copyright (C) 2002-2023 OpenVPN Inc dnl Copyright (C) 2006-2012 Alon Bar-Lev dnl dnl This program is free software; you can redistribute it and/or modify @@ -121,13 +121,6 @@ AC_ARG_ENABLE( [enable_fragment="yes"] ) -AC_ARG_ENABLE( - [multihome], - [AS_HELP_STRING([--disable-multihome], [disable multi-homed UDP server support (--multihome) @<:@default=yes@:>@])], - , - [enable_multihome="yes"] -) - AC_ARG_ENABLE( [port-share], [AS_HELP_STRING([--disable-port-share], [disable TCP server port-share support (--port-share) @<:@default=yes@:>@])], @@ -150,24 +143,17 @@ AC_ARG_ENABLE( ) AC_ARG_ENABLE( - [iproute2], - [AS_HELP_STRING([--enable-iproute2], [enable support for iproute2 @<:@default=no@:>@])], + [dco], + [AS_HELP_STRING([--enable-dco], [enable data channel offload support using the ovpn-dco kernel module (always enabled on Windows) @<:@default=no@:>@])], , - [enable_iproute2="no"] + [enable_dco="no"] ) AC_ARG_ENABLE( - [def-auth], - [AS_HELP_STRING([--disable-def-auth], [disable deferred authentication @<:@default=yes@:>@])], - , - [enable_def_auth="yes"] -) - -AC_ARG_ENABLE( - [pf], - [AS_HELP_STRING([--disable-pf], [disable internal packet filter @<:@default=yes@:>@])], + [iproute2], + [AS_HELP_STRING([--enable-iproute2], [enable support for iproute2 @<:@default=no@:>@])], , - [enable_pf="yes"] + [enable_iproute2="no"] ) AC_ARG_ENABLE( @@ -271,16 +257,23 @@ AC_ARG_WITH( AC_ARG_WITH( [crypto-library], - [AS_HELP_STRING([--with-crypto-library=library], [build with the given crypto library, TYPE=openssl|mbedtls @<:@default=openssl@:>@])], + [AS_HELP_STRING([--with-crypto-library=library], [build with the given crypto library, TYPE=openssl|mbedtls|wolfssl @<:@default=openssl@:>@])], [ case "${withval}" in - openssl|mbedtls) ;; + openssl|mbedtls|wolfssl) ;; *) AC_MSG_ERROR([bad value ${withval} for --with-crypto-library]) ;; esac ], [with_crypto_library="openssl"] ) +AC_ARG_ENABLE( + [wolfssl-options-h], + [AS_HELP_STRING([--disable-wolfssl-options-h], [Disable including options.h in wolfSSL @<:@default=yes@:>@])], + , + [enable_wolfssl_options_h="yes"] +) + AC_ARG_WITH( [openssl-engine], [AS_HELP_STRING([--with-openssl-engine], [enable engine support with OpenSSL. Default enabled for OpenSSL < 3.0, auto,yes,no @<:@default=auto@:>@])], @@ -335,6 +328,7 @@ case "$host" in ;; *-mingw*) AC_DEFINE([TARGET_WIN32], [1], [Are we running WIN32?]) + AC_DEFINE([ENABLE_DCO], [1], [DCO is always enabled on Windows]) AC_DEFINE_UNQUOTED([TARGET_PREFIX], ["W"], [Target prefix]) CPPFLAGS="${CPPFLAGS} -DWIN32_LEAN_AND_MEAN" CPPFLAGS="${CPPFLAGS} -DNTDDI_VERSION=NTDDI_VISTA -D_WIN32_WINNT=_WIN32_WINNT_VISTA" @@ -421,44 +415,29 @@ AC_TYPE_OFF_T AC_TYPE_PID_T AC_TYPE_SIZE_T AC_TYPE_UID_T -AC_TYPE_INT8_T -AC_TYPE_INT16_T -AC_TYPE_INT32_T -AC_TYPE_INT64_T -AC_TYPE_UINT8_T -AC_TYPE_UINT16_T -AC_TYPE_UINT32_T -AC_TYPE_UINT64_T AC_TYPE_SIGNAL -AX_CPP_VARARG_MACRO_ISO -AX_CPP_VARARG_MACRO_GCC AX_TYPE_SOCKLEN_T -AX_EMPTY_ARRAY AC_CHECK_SIZEOF([unsigned int]) AC_CHECK_SIZEOF([unsigned long]) AC_CHECK_HEADERS([ \ - stdio.h stdarg.h limits.h \ - time.h errno.h fcntl.h io.h direct.h \ - ctype.h sys/types.h sys/socket.h \ - signal.h unistd.h dlfcn.h \ + fcntl.h io.h \ + sys/types.h sys/socket.h \ + unistd.h dlfcn.h \ netinet/in.h netinet/in_systm.h \ netinet/tcp.h arpa/inet.h netdb.h \ - windows.h winsock2.h ws2tcpip.h \ versionhelpers.h \ ]) AC_CHECK_HEADERS([ \ sys/time.h sys/ioctl.h sys/stat.h \ sys/mman.h sys/file.h sys/wait.h \ - unistd.h signal.h libgen.h stropts.h \ - syslog.h pwd.h grp.h \ + unistd.h libgen.h stropts.h \ + syslog.h pwd.h grp.h termios.h \ sys/sockio.h sys/uio.h linux/sockios.h \ linux/types.h linux/errqueue.h poll.h sys/epoll.h err.h \ ]) SOCKET_INCLUDES=" -#ifdef HAVE_STDLIB_H #include -#endif #ifdef HAVE_SYS_TYPES_H #include #endif @@ -471,13 +450,13 @@ SOCKET_INCLUDES=" #ifdef HAVE_NETINET_IN_H #include #endif -#ifdef HAVE_WINDOWS_H +#ifdef _WIN32 #include #endif -#ifdef HAVE_WINSOCK2_H +#ifdef _WIN32 #include #endif -#ifdef HAVE_WS2TCPIP_H +#ifdef _WIN32 #include #endif #ifdef HAVE_NETINET_IN_SYSTM_H @@ -608,9 +587,7 @@ AC_CHECK_DECLS( , [AC_DEFINE([SIGHUP], [1], [SIGHUP replacement])], [[ - #ifdef HAVE_SIGNAL_H #include - #endif ]] ) AC_CHECK_DECLS( @@ -618,9 +595,7 @@ AC_CHECK_DECLS( , [AC_DEFINE([SIGINT], [2], [SIGINT replacement])], [[ - #ifdef HAVE_SIGNAL_H #include - #endif ]] ) AC_CHECK_DECLS( @@ -628,9 +603,7 @@ AC_CHECK_DECLS( , [AC_DEFINE([SIGUSR1], [10], [SIGUSR1 replacement])], [[ - #ifdef HAVE_SIGNAL_H #include - #endif ]] ) AC_CHECK_DECLS( @@ -638,9 +611,7 @@ AC_CHECK_DECLS( , [AC_DEFINE([SIGUSR2], [12], [SIGUSR2 replacement])], [[ - #ifdef HAVE_SIGNAL_H #include - #endif ]] ) AC_CHECK_DECLS( @@ -648,21 +619,18 @@ AC_CHECK_DECLS( , [AC_DEFINE([SIGTERM], [15], [SIGTERM replacement])], [[ - #ifdef HAVE_SIGNAL_H #include - #endif ]] ) AC_FUNC_FORK AC_CHECK_FUNCS([ \ - daemon chroot getpwnam setuid nice system getpid dup dup2 \ - getpass syslog openlog mlockall getgrnam setgid \ - setgroups stat flock readv writev time gettimeofday \ - ctime memset vsnprintf strdup \ - setsid chdir putenv getpeername unlink \ - chsize ftruncate execve getpeereid umask basename dirname access \ + daemon chroot getpwnam setuid nice system dup dup2 \ + syslog openlog mlockall getrlimit getgrnam setgid \ + setgroups flock readv writev time gettimeofday \ + setsid chdir \ + chsize ftruncate execve getpeereid basename dirname access \ epoll_create strsep \ ]) @@ -693,53 +661,7 @@ AC_SUBST([SOCKETS_LIBS]) old_LIBS="${LIBS}" LIBS="${LIBS} ${SOCKETS_LIBS}" AC_CHECK_FUNCS([sendmsg recvmsg]) -# Windows use stdcall for winsock so we cannot auto detect these -m4_define( - [SOCKET_FUNCS], -[socket recv recvfrom send sendto listen dnl -accept connect bind select gethostbyname inet_ntoa]dnl -) -m4_define( - [SOCKET_OPT_FUNCS], - [setsockopt getsockopt getsockname poll]dnl -) -if test "${WIN32}" = "yes"; then -# normal autoconf function checking does not find inet_ntop/inet_pton -# because they need to include the actual header file and link ws2_32.dll - LIBS="${LIBS} -lws2_32" - AC_MSG_CHECKING([for MinGW inet_ntop()/inet_pton()]) - AC_LINK_IFELSE( - [AC_LANG_PROGRAM( - [[ -#include - ]], - [[ -int r = (int) inet_ntop (0, NULL, NULL, 0); - r += inet_pton(AF_INET, NULL, NULL); -return r; - ]] - )], - [AC_MSG_RESULT([OK]) - AC_DEFINE([HAVE_INET_NTOP],[1],[MinGW inet_ntop]) - AC_DEFINE([HAVE_INET_PTON],[1],[MinGW inet_pton]) - ], - [AC_MSG_RESULT([not found])] - ) - m4_foreach( - [F], - m4_split(SOCKET_FUNCS SOCKET_OPT_FUNCS), - m4_define([UF], [[m4_join([_], [HAVE], m4_toupper(F))]]) - AC_DEFINE([UF], [1], [Win32 builtin]) - ) -else - AC_CHECK_FUNCS([inet_ntop inet_pton]) - AC_CHECK_FUNCS( - SOCKET_FUNCS, - , - [AC_MSG_ERROR([Required library function not found])] - ) - AC_CHECK_FUNCS(SOCKET_OPT_FUNCS) -fi + LIBS="${old_LIBS}" # we assume res_init() always exist, but need to find out *where*... @@ -846,6 +768,58 @@ PKG_CHECK_MODULES( [] ) + +if test "$enable_dco" = "yes"; then +dnl +dnl Include generic netlink library used to talk to ovpn-dco +dnl + case "$host" in + *-*-linux*) + PKG_CHECK_MODULES([LIBNL_GENL], + [libnl-genl-3.0 >= 3.4.0], + [have_libnl="yes"], + [AC_MSG_ERROR([libnl-genl-3.0 package not found or too old. Is the development package and pkg-config installed? Must be version 3.4.0 or newer])] + ) + + CFLAGS="${CFLAGS} ${LIBNL_GENL_CFLAGS}" + LIBS="${LIBS} ${LIBNL_GENL_LIBS}" + + AC_DEFINE(ENABLE_DCO, 1, [Enable shared data channel offload]) + AC_MSG_NOTICE([Enabled ovpn-dco support for Linux]) + ;; + *-*-freebsd*) + LIBS="${LIBS} -lnv" + AC_DEFINE(ENABLE_DCO, 1, [Enable data channel offload for FreeBSD]) + AC_MSG_NOTICE([Enabled ovpn-dco support for FreeBSD]) + ;; + *-mingw*) + AC_MSG_NOTICE([NOTE: --enable-dco ignored on Windows because it's always enabled]) + ;; + *) + AC_MSG_NOTICE([Ignoring --enable-dco on non supported platform]) + ;; + esac +fi + +dnl +dnl Depend on libcap-ng on Linux +dnl +case "$host" in + *-*-linux*) + PKG_CHECK_MODULES([LIBCAPNG], + [libcap-ng], + [], + [AC_MSG_ERROR([libcap-ng package not found. Is the development package and pkg-config installed?])] + ) + AC_CHECK_HEADER([sys/prctl.h],,[AC_MSG_ERROR([sys/prctl.h not found!])]) + + CFLAGS="${CFLAGS} ${LIBCAPNG_CFALGS}" + LIBS="${LIBS} ${LIBCAPNG_LIBS}" + AC_DEFINE(HAVE_LIBCAPNG, 1, [Enable libcap-ng support]) + ;; +esac + + if test "${with_crypto_library}" = "openssl"; then AC_ARG_VAR([OPENSSL_CFLAGS], [C compiler flags for OpenSSL]) AC_ARG_VAR([OPENSSL_LIBS], [linker flags for OpenSSL]) @@ -887,7 +861,7 @@ if test "${with_crypto_library}" = "openssl"; then ) fi - AC_CHECK_FUNCS([SSL_CTX_new EVP_CIPHER_CTX_set_key_length], + AC_CHECK_FUNCS([SSL_CTX_new], , [AC_MSG_ERROR([openssl check failed])] ) @@ -945,50 +919,6 @@ if test "${with_crypto_library}" = "openssl"; then # have this feature have_export_keying_material="yes" - AC_CHECK_FUNCS( - [ \ - HMAC_CTX_new \ - HMAC_CTX_free \ - HMAC_CTX_reset \ - EVP_MD_CTX_new \ - EVP_MD_CTX_free \ - EVP_MD_CTX_reset \ - EVP_CIPHER_CTX_reset \ - OpenSSL_version \ - SSL_CTX_get_default_passwd_cb \ - SSL_CTX_get_default_passwd_cb_userdata \ - SSL_CTX_set1_groups \ - SSL_CTX_set_security_level \ - X509_get0_notBefore \ - X509_get0_notAfter \ - X509_get0_pubkey \ - X509_STORE_get0_objects \ - X509_OBJECT_free \ - X509_OBJECT_get_type \ - EVP_PKEY_get0_RSA \ - EVP_PKEY_get0_DSA \ - EVP_PKEY_get0_EC_KEY \ - RSA_set_flags \ - RSA_bits \ - RSA_get0_key \ - RSA_set0_key \ - DSA_get0_pqg \ - DSA_bits \ - RSA_meth_new \ - RSA_meth_free \ - RSA_meth_set_pub_enc \ - RSA_meth_set_pub_dec \ - RSA_meth_set_priv_enc \ - RSA_meth_set_priv_dec \ - RSA_meth_set_init \ - RSA_meth_set_sign \ - RSA_meth_set_finish \ - RSA_meth_set0_app_data \ - RSA_meth_get0_app_data \ - EC_GROUP_order_bits - ] - ) - CFLAGS="${saved_CFLAGS}" LIBS="${saved_LIBS}" @@ -1049,11 +979,76 @@ elif test "${with_crypto_library}" = "mbedtls"; then [have_export_keying_material="no"] ) + AC_CHECK_FUNC( + [mbedtls_ctr_drbg_update_ret], + AC_DEFINE([HAVE_CTR_DRBG_UPDATE_RET], [1], + [Use mbedtls_ctr_drbg_update_ret from mbed TLS]), + ) + CFLAGS="${saved_CFLAGS}" LIBS="${saved_LIBS}" AC_DEFINE([ENABLE_CRYPTO_MBEDTLS], [1], [Use mbed TLS library]) CRYPTO_CFLAGS="${MBEDTLS_CFLAGS}" CRYPTO_LIBS="${MBEDTLS_LIBS}" + +elif test "${with_crypto_library}" = "wolfssl"; then + AC_ARG_VAR([WOLFSSL_CFLAGS], [C compiler flags for wolfssl. The include directory should + contain the regular wolfSSL header files but also the + wolfSSL OpenSSL header files. Ex: -I/usr/local/include + -I/usr/local/include/wolfssl]) + AC_ARG_VAR([WOLFSSL_LIBS], [linker flags for wolfssl]) + + saved_CFLAGS="${CFLAGS}" + saved_LIBS="${LIBS}" + + if test -z "${WOLFSSL_CFLAGS}" -a -z "${WOLFSSL_LIBS}"; then + # if the user did not explicitly specify flags, try to autodetect + PKG_CHECK_MODULES( + [WOLFSSL], + [wolfssl], + [], + [AC_MSG_ERROR([Could not find wolfSSL.])] + ) + PKG_CHECK_VAR( + [WOLFSSL_INCLUDEDIR], + [wolfssl], + [includedir], + [], + [AC_MSG_ERROR([Could not find wolfSSL includedir variable.])] + ) + WOLFSSL_CFLAGS="${WOLFSSL_CFLAGS} -I${WOLFSSL_INCLUDEDIR}/wolfssl" + fi + saved_CFLAGS="${CFLAGS}" + saved_LIBS="${LIBS}" + CFLAGS="${CFLAGS} ${WOLFSSL_CFLAGS}" + LIBS="${LIBS} ${WOLFSSL_LIBS}" + + AC_CHECK_LIB( + [wolfssl], + [wolfSSL_Init], + [], + [AC_MSG_ERROR([Could not link wolfSSL library.])] + ) + AC_CHECK_HEADER([wolfssl/options.h],,[AC_MSG_ERROR([wolfSSL header wolfssl/options.h not found!])]) + + # wolfSSL signal EKM support + have_export_keying_material="yes" + + if test "${enable_wolfssl_options_h}" = "yes"; then + AC_DEFINE([EXTERNAL_OPTS_OPENVPN], [1], [Include options.h from wolfSSL library]) + else + AC_DEFINE([WOLFSSL_USER_SETTINGS], [1], [Use custom user_settings.h file for wolfSSL library]) + fi + + have_export_keying_material="yes" + + CFLAGS="${saved_CFLAGS}" + LIBS="${saved_LIBS}" + + AC_DEFINE([ENABLE_CRYPTO_WOLFSSL], [1], [Use wolfSSL crypto library]) + AC_DEFINE([ENABLE_CRYPTO_OPENSSL], [1], [Use wolfSSL openssl compatibility layer]) + CRYPTO_CFLAGS="${WOLFSSL_CFLAGS}" + CRYPTO_LIBS="${WOLFSSL_LIBS}" else AC_MSG_ERROR([Invalid crypto library: ${with_crypto_library}]) fi @@ -1145,7 +1140,7 @@ if test "$enable_lz4" = "yes" && test "$enable_comp_stub" = "no"; then AC_MSG_RESULT([ok]) have_lz4="yes" ], - [AC_MSG_RESULT([system LZ4 library is too old])] + [AC_MSG_ERROR([system LZ4 library is too old])] ) fi fi @@ -1163,8 +1158,7 @@ if test "$enable_lz4" = "yes" && test "$enable_comp_stub" = "no"; then fi if test "${have_lz4}" != "yes" ; then - AC_MSG_RESULT([ usable LZ4 library or header not found, using version in src/compat/compat-lz4.*]) - AC_DEFINE([NEED_COMPAT_LZ4], [1], [use copy of LZ4 source in compat/]) + AC_MSG_ERROR([No compatible LZ4 compression library found. Consider --disable-lz4]) LZ4_LIBS="" fi OPTIONAL_LZ4_CFLAGS="${LZ4_CFLAGS}" @@ -1225,14 +1219,6 @@ if test -n "${GIT}" -a -d "${srcdir}/.git"; then fi AC_MSG_RESULT([${GIT_CHECKOUT}]) -if test -n "${SP_PLATFORM_WINDOWS}"; then - AC_DEFINE_UNQUOTED([PATH_SEPARATOR], ['\\\\'], [Path separator]) #" - AC_DEFINE_UNQUOTED([PATH_SEPARATOR_STR], ["\\\\"], [Path separator]) #" -else - AC_DEFINE_UNQUOTED([PATH_SEPARATOR], ['/'], [Path separator]) - AC_DEFINE_UNQUOTED([PATH_SEPARATOR_STR], ["/"], [Path separator]) -fi - dnl enable --x509-username-field feature if requested if test "${enable_x509_alt_username}" = "yes"; then if test "${with_crypto_library}" = "mbedtls" ; then @@ -1242,16 +1228,11 @@ if test "${enable_x509_alt_username}" = "yes"; then AC_DEFINE([ENABLE_X509ALTUSERNAME], [1], [Enable --x509-username-field feature]) fi -test "${ac_cv_header_sys_uio_h}" = "yes" && AC_DEFINE([HAVE_IOVEC], [1], [struct iovec needed for IPv6 support]) test "${enable_management}" = "yes" && AC_DEFINE([ENABLE_MANAGEMENT], [1], [Enable management server capability]) -test "${enable_multihome}" = "yes" && AC_DEFINE([ENABLE_MULTIHOME], [1], [Enable multi-homed UDP server capability]) test "${enable_debug}" = "yes" && AC_DEFINE([ENABLE_DEBUG], [1], [Enable debugging support]) test "${enable_small}" = "yes" && AC_DEFINE([ENABLE_SMALL], [1], [Enable smaller executable size]) test "${enable_fragment}" = "yes" && AC_DEFINE([ENABLE_FRAGMENT], [1], [Enable internal fragmentation support]) test "${enable_port_share}" = "yes" && AC_DEFINE([ENABLE_PORT_SHARE], [1], [Enable TCP Server port sharing]) -test "${enable_def_auth}" = "yes" && AC_DEFINE([ENABLE_DEF_AUTH], [1], [Enable deferred authentication]) -test "${enable_pf}" = "yes" && AC_DEFINE([ENABLE_PF], [1], [Enable internal packet filter]) -test "${enable_strict_options}" = "yes" && AC_DEFINE([ENABLE_STRICT_OPTIONS_CHECK], [1], [Enable strict options check between peers]) test "${enable_crypto_ofb_cfb}" = "yes" && AC_DEFINE([ENABLE_OFB_CFB_MODE], [1], [Enable OFB and CFB cipher modes]) if test "${have_export_keying_material}" = "yes"; then @@ -1274,6 +1255,7 @@ fi AM_CONDITIONAL([HAVE_SITNL], [false]) if test "${enable_iproute2}" = "yes"; then + test "${enable_dco}" = "yes" && AC_MSG_ERROR([iproute2 support cannot be enabled when using DCO]) test -z "${IPROUTE}" && AC_MSG_ERROR([ip utility is required but missing]) AC_DEFINE([ENABLE_IPROUTE], [1], [enable iproute2 support]) else if test "${have_sitnl}" = "yes"; then @@ -1479,4 +1461,4 @@ AC_CONFIG_FILES([ sample/Makefile ]) AC_CONFIG_FILES([tests/t_client.sh], [chmod +x tests/t_client.sh]) -AC_OUTPUT +AC_OUTPUT \ No newline at end of file diff --git a/contrib/extract-crl/extractcrl.py b/contrib/extract-crl/extractcrl.py new file mode 100755 index 00000000000..441464e9d8a --- /dev/null +++ b/contrib/extract-crl/extractcrl.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +''' +Helper script for CRL (certificate revocation list) file extraction +to a directory containing files named as decimal serial numbers of +the revoked certificates, to be used with OpenVPN CRL directory +verify mode. To enable this mode, directory and 'dir' flag needs to +be specified as parameters of '--crl-verify' option. +For more information refer OpenVPN tls-options.rst. + +Usage example: + extractcrl.py -f pem /path/to/crl.pem /path/to/outdir + extractcrl.py -f der /path/to/crl.crl /path/to/outdir + cat /path/to/crl.pem | extractcrl.py -f pem - /path/to/outdir + cat /path/to/crl.crl | extractcrl.py -f der - /path/to/outdir + +Output example: + Loaded: 309797 revoked certs in 4.136s + Scanned: 312006 files in 0.61s + Created: 475 files in 0.05s + Removed: 2684 files in 0.116s +''' + +import argparse +import os +import sys +import time +from subprocess import check_output + +FILETYPE_PEM = 'PEM' +FILETYPE_DER = 'DER' + +def measure_time(method): + def elapsed(*args, **kwargs): + start = time.time() + result = method(*args, **kwargs) + return result, round(time.time() - start, 3) + return elapsed + +@measure_time +def load_crl(filename, format): + + def try_openssl_module(filename, format): + from OpenSSL import crypto + types = { + FILETYPE_PEM: crypto.FILETYPE_PEM, + FILETYPE_DER: crypto.FILETYPE_ASN1 + } + if filename == '-': + crl = crypto.load_crl(types[format], sys.stdin.buffer.read()) + else: + with open(filename, 'rb') as f: + crl = crypto.load_crl(types[format], f.read()) + return set(int(r.get_serial(), 16) for r in crl.get_revoked()) + + def try_openssl_exec(filename, format): + args = ['openssl', 'crl', '-inform', format, '-text'] + if filename != '-': + args += ['-in', filename] + serials = set() + for line in check_output(args, universal_newlines=True).splitlines(): + _, _, serial = line.partition('Serial Number:') + if serial: + serials.add(int(serial.strip(), 16)) + return serials + + try: + return try_openssl_module(filename, format) + except ImportError: + return try_openssl_exec(filename, format) + +@measure_time +def scan_dir(dirname): + _, _, files = next(os.walk(dirname)) + return set(int(f) for f in files if f.isdigit()) + +@measure_time +def create_new_files(dirname, newset, oldset): + addset = newset.difference(oldset) + for serial in addset: + try: + with open(os.path.join(dirname, str(serial)), 'xb'): pass + except FileExistsError: + pass + return addset + +@measure_time +def remove_old_files(dirname, newset, oldset): + delset = oldset.difference(newset) + for serial in delset: + try: + os.remove(os.path.join(dirname, str(serial))) + except FileNotFoundError: + pass + return delset + +def check_crlfile(arg): + if arg == '-' or os.path.isfile(arg): + return arg + raise argparse.ArgumentTypeError('No such file "{}"'.format(arg)) + +def check_outdir(arg): + if os.path.isdir(arg): + return arg + raise argparse.ArgumentTypeError('No such directory: "{}"'.format(arg)) + +def main(): + parser = argparse.ArgumentParser(description='OpenVPN CRL extractor') + parser.add_argument('-f', '--format', + type=str.upper, + default=FILETYPE_PEM, choices=[FILETYPE_PEM, FILETYPE_DER], + help='input CRL format - default {}'.format(FILETYPE_PEM) + ) + parser.add_argument('crlfile', metavar='CRLFILE|-', + type=lambda x: check_crlfile(x), + help='input CRL file or "-" for stdin' + ) + parser.add_argument('outdir', metavar='OUTDIR', + type=lambda x: check_outdir(x), + help='output directory for serials numbers' + ) + args = parser.parse_args() + + certs, t = load_crl(args.crlfile, args.format) + print('Loaded: {} revoked certs in {}s'.format(len(certs), t)) + + files, t = scan_dir(args.outdir) + print('Scanned: {} files in {}s'.format(len(files), t)) + + created, t = create_new_files(args.outdir, certs, files) + print('Created: {} files in {}s'.format(len(created), t)) + + removed, t = remove_old_files(args.outdir, certs, files) + print('Removed: {} files in {}s'.format(len(removed), t)) + +if __name__ == "__main__": + main() diff --git a/contrib/vcpkg-ports/pkcs11-helper/pkcs11-helper-002-dynamic_loader_flags.patch b/contrib/vcpkg-ports/pkcs11-helper/pkcs11-helper-002-dynamic_loader_flags.patch new file mode 100644 index 00000000000..325dea8b8ef --- /dev/null +++ b/contrib/vcpkg-ports/pkcs11-helper/pkcs11-helper-002-dynamic_loader_flags.patch @@ -0,0 +1,102 @@ +From 934197611dd1260d17ae0f11ae81c1d2e85612d2 Mon Sep 17 00:00:00 2001 +From: Marc Becker +Date: Fri, 22 Jul 2022 10:33:05 +0200 +Subject: [PATCH] core: add provider property for loader flags + +support flags for dynamic loader via provider property +set original values as defaults, use verbatim (user-supplied) value +--- + include/pkcs11-helper-1.0/pkcs11h-core.h | 11 ++++++++++- + lib/_pkcs11h-core.h | 2 ++ + lib/pkcs11h-core.c | 13 +++++++++++-- + 3 files changed, 23 insertions(+), 3 deletions(-) + +diff --git a/include/pkcs11-helper-1.0/pkcs11h-core.h b/include/pkcs11-helper-1.0/pkcs11h-core.h +index 9028c277..56f87718 100644 +--- a/include/pkcs11-helper-1.0/pkcs11h-core.h ++++ b/include/pkcs11-helper-1.0/pkcs11h-core.h +@@ -384,8 +384,17 @@ extern "C" { + */ + #define PKCS11H_PROVIDER_PROPERTY_PROVIDER_DESTRUCT_HOOK_DATA 8 + ++/** ++ * @brief Provider loader flags for platform. ++ * Value type is unsigned. ++ * Default value is platform dependent: ++ * win32 -> 0 ++ * dlopen -> RTLD_NOW | RTLD_LOCAL ++ */ ++#define PKCS11H_PROVIDER_PROPERTY_LOADER_FLAGS 9 ++ + /** @private */ +-#define _PKCS11H_PROVIDER_PROPERTY_LAST 9 ++#define _PKCS11H_PROVIDER_PROPERTY_LAST 10 + + /** @} */ + +diff --git a/lib/_pkcs11h-core.h b/lib/_pkcs11h-core.h +index f879c0e8..1c02e35d 100644 +--- a/lib/_pkcs11h-core.h ++++ b/lib/_pkcs11h-core.h +@@ -134,6 +134,8 @@ struct _pkcs11h_provider_s { + #if defined(ENABLE_PKCS11H_SLOTEVENT) + _pkcs11h_thread_t slotevent_thread; + #endif ++ ++ unsigned loader_flags; + }; + + struct _pkcs11h_session_s { +diff --git a/lib/pkcs11h-core.c b/lib/pkcs11h-core.c +index 0bf11e87..409ad9e2 100644 +--- a/lib/pkcs11h-core.c ++++ b/lib/pkcs11h-core.c +@@ -138,6 +138,7 @@ static const char * __pkcs11h_provider_preperty_names[] = { + "init_args", + "provider_destruct_hook", + "provider_destruct_hook_data", ++ "provider_loader_flags", + NULL + }; + +@@ -916,6 +917,10 @@ pkcs11h_registerProvider ( + reference + ); + ++#if !defined(_WIN32) ++ provider->loader_flags = RTLD_NOW | RTLD_LOCAL; ++#endif ++ + _PKCS11H_DEBUG ( + PKCS11H_LOG_DEBUG2, + "PKCS#11: pkcs11h_registerProvider Provider '%s'", +@@ -1001,6 +1006,7 @@ pkcs11h_setProviderPropertyByName ( + case PKCS11H_PROVIDER_PROPERTY_SLOT_EVENT_METHOD: + case PKCS11H_PROVIDER_PROPERTY_MASK_PRIVATE_MODE: + case PKCS11H_PROVIDER_PROPERTY_SLOT_POLL_INTERVAL: ++ case PKCS11H_PROVIDER_PROPERTY_LOADER_FLAGS: + *(unsigned *)value = (unsigned)strtol(value_str, 0, 0); + value_size = sizeof(unsigned); + break; +@@ -1084,6 +1090,9 @@ __pkcs11h_providerPropertyAddress( + case PKCS11H_PROVIDER_PROPERTY_PROVIDER_DESTRUCT_HOOK_DATA: + *value = &provider->destruct_hook_data; + *value_size = sizeof(provider->destruct_hook_data); ++ case PKCS11H_PROVIDER_PROPERTY_LOADER_FLAGS: ++ *value = &provider->loader_flags; ++ *value_size = sizeof(provider->loader_flags); + break; + } + rv = CKR_OK; +@@ -1254,9 +1263,9 @@ pkcs11h_initializeProvider ( + } + + #if defined(_WIN32) +- provider->handle = LoadLibraryA (provider->provider_location); ++ provider->handle = LoadLibraryExA (provider->provider_location, NULL, provider->loader_flags); + #else +- provider->handle = dlopen (provider->provider_location, RTLD_NOW | RTLD_LOCAL); ++ provider->handle = dlopen (provider->provider_location, provider->loader_flags); + #endif + + if (provider->handle == NULL) { diff --git a/contrib/vcpkg-ports/pkcs11-helper/portfile.cmake b/contrib/vcpkg-ports/pkcs11-helper/portfile.cmake index 4432b5502bc..d05dcb1d375 100644 --- a/contrib/vcpkg-ports/pkcs11-helper/portfile.cmake +++ b/contrib/vcpkg-ports/pkcs11-helper/portfile.cmake @@ -14,6 +14,7 @@ vcpkg_extract_source_archive_ex( 0001-nmake-compatibility-with-vcpkg-nmake.patch 0002-config-w32-vc.h.in-indicate-OpenSSL.patch pkcs11-helper-001-RFC7512.patch + pkcs11-helper-002-dynamic_loader_flags.patch ) vcpkg_build_nmake( @@ -32,4 +33,4 @@ file(INSTALL ${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-dbg/lib/pkcs11-helper.d file(INSTALL ${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-rel/lib/libpkcs11-helper-1.dll DESTINATION ${CURRENT_PACKAGES_DIR}/bin) file(INSTALL ${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-dbg/lib/libpkcs11-helper-1.dll DESTINATION ${CURRENT_PACKAGES_DIR}/debug/bin) -file(INSTALL ${SOURCE_PATH}/COPYING DESTINATION ${CURRENT_PACKAGES_DIR}/share/${PORT} RENAME copyright) +file(INSTALL ${SOURCE_PATH}/COPYING DESTINATION ${CURRENT_PACKAGES_DIR}/share/${PORT} RENAME copyright) \ No newline at end of file diff --git a/dev-tools/gen-release-tarballs.sh b/dev-tools/gen-release-tarballs.sh index 14734f6239c..5b862aeb810 100755 --- a/dev-tools/gen-release-tarballs.sh +++ b/dev-tools/gen-release-tarballs.sh @@ -1,7 +1,7 @@ #!/bin/sh # gen-release-tarballs.sh - Generates release tarballs with signatures # -# Copyright (C) 2017-2022 - David Sommerseth +# Copyright (C) 2017-2023 - David Sommerseth # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License @@ -244,4 +244,4 @@ mv $workdir/*.log "$destdir/logs" # Finally, done! rm -rf "$workdir" echo "-- Done" -exit 0 +exit 0 \ No newline at end of file diff --git a/dev-tools/git-pre-commit-uncrustify.sh b/dev-tools/git-pre-commit-uncrustify.sh new file mode 100755 index 00000000000..9851c212f45 --- /dev/null +++ b/dev-tools/git-pre-commit-uncrustify.sh @@ -0,0 +1,161 @@ +#!/bin/sh + +# Copyright (c) 2015, David Martin +# 2022, Heiko Hund +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +# git pre-commit hook that runs an Uncrustify stylecheck. +# Features: +# - abort commit when commit does not comply with the style guidelines +# - create a patch of the proposed style changes +# +# More info on Uncrustify: http://uncrustify.sourceforge.net/ + +# This file was taken from a set of unofficial pre-commit hooks available +# at https://github.com/ddddavidmartin/Pre-commit-hooks and modified to +# fit the openvpn project's needs + +# exit on error +set -e + + +# If called so, install this script as pre-commit hook +if [ "$1" = "install" ] ; then + TARGET="$(git rev-parse --git-path hooks)/pre-commit" + + if [ -e "$TARGET" ] ; then + printf "$TARGET file exists. Won't overwrite.\n" + printf "Aborting installation.\n" + exit 1 + fi + + read -p "Install as $TARGET? [y/N] " INPUT + [ "$INPUT" = "y" ] || exit 0 + cp "$0" "$TARGET" + chmod +x $TARGET + exit 0 +fi + +# check whether the given file matches any of the set extensions +matches_extension() { + local filename="$(basename -- "$1")" + local extension=".${filename##*.}" + local ext + + for ext in .c .h ; do [ "$ext" = "$extension" ] && return 0; done + + return 1 +} + +# necessary check for initial commit +if git rev-parse --verify HEAD >/dev/null 2>&1 ; then + against=HEAD +else + # Initial commit: diff against an empty tree object + against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 +fi + +UNCRUSTIFY=$(command -v uncrustify) +UNCRUST_CONFIG="$(git rev-parse --show-toplevel)/dev-tools/uncrustify.conf" + +# make sure the config file and executable are correctly set +if [ ! -f "$UNCRUST_CONFIG" ] ; then + printf "Error: uncrustify config file not found.\n" + printf "Expected to find it at $UNCRUST_CONFIG.\n" + printf "Aborting commit.\n" + exit 1 +fi + +if [ -z "$UNCRUSTIFY" ] ; then + printf "Error: uncrustify executable not found.\n" + printf "Is it installed and in your \$PATH?\n" + printf "Aborting commit.\n" + exit 1 +fi + +# create a filename to store our generated patch +patch=$(mktemp /tmp/ovpn-fmt-XXXXXX) +tmpout=$(mktemp /tmp/uncrustify-XXXXXX) + +# create one patch containing all changes to the files +# sed to remove quotes around the filename, if inserted by the system +# (done sometimes, if the filename contains special characters, like the quote itself) +git diff-index --cached --diff-filter=ACMR --name-only $against -- | \ +sed -e 's/^"\(.*\)"$/\1/' | \ +while read file +do + # ignore file if we do check for file extensions and the file + # does not match the extensions .c or .h + if ! matches_extension "$file"; then + continue; + fi + + # escape special characters in the target filename: + # phase 1 (characters escaped in the output diff): + # - '\': backslash needs to be escaped in the output diff + # - '"': quote needs to be escaped in the output diff if present inside + # of the filename, as it used to bracket the entire filename part + # phase 2 (characters escaped in the match replacement): + # - '\': backslash needs to be escaped again for sed itself + # (i.e. double escaping after phase 1) + # - '&': would expand to matched string + # - '|': used as sed split char instead of '/' + # printf %s particularly important if the filename contains the % character + file_escaped_target=$(printf "%s" "$file" | sed -e 's/[\"]/\\&/g' -e 's/[\&|]/\\&/g') + + # uncrustify our sourcefile, create a patch with diff and append it to our $patch + # The sed call is necessary to transform the patch from + # --- - timestamp + # +++ $tmpout timestamp + # to both lines working on the same file and having a a/ and b/ prefix. + # Else it can not be applied with 'git apply'. + git show ":$file" | "$UNCRUSTIFY" -q -l C -c "$UNCRUST_CONFIG" -o "$tmpout" + git show ":$file" | diff -u -- - "$tmpout" | \ + sed -e "1s|--- -|--- \"b/$file_escaped_target\"|" -e "2s|+++ $tmpout|+++ \"a/$file_escaped_target\"|" >> "$patch" +done + +rm -f "$tmpout" + +# if no patch has been generated all is ok, clean up the file stub and exit +if [ ! -s "$patch" ] ; then + rm -f "$patch" + exit 0 +fi + +# a patch has been created, notify the user and exit +printf "Formatting of some code does not follow the project guidelines.\n" + +if [ $(wc -l < $patch) -gt 80 ] ; then + printf "The file $patch contains the necessary fixes.\n" +else + printf "Here's the patch that fixes the formatting:\n\n" + cat $patch +fi + +printf "\nYou can apply these changes with:\n git apply $patch\n" +printf "(from the root directory of the repository) and then commit again.\n" +printf "\nAborting commit.\n" + +exit 1 diff --git a/dev-tools/reformat-all.sh b/dev-tools/reformat-all.sh index dc2bfc4e9a8..afa67ff05db 100755 --- a/dev-tools/reformat-all.sh +++ b/dev-tools/reformat-all.sh @@ -2,7 +2,7 @@ # reformat-all.sh - Reformat all git files in the checked out # git branch using uncrustify. # -# Copyright (C) 2016-2022 - David Sommerseth +# Copyright (C) 2016-2023 - David Sommerseth # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License @@ -80,8 +80,8 @@ cd "$srcroot" # Kick off uncrustify echo - echo "** INFO ** Running: uncrustify -c $cfg --no-backup -l C -p debug.uncr -F $files" - uncrustify -c "$cfg" --no-backup -l C -p debug.uncr -F "$files" 2>&1 + echo "** INFO ** Running: uncrustify -c $cfg --no-backup -l C -F $files" + uncrustify -c "$cfg" --no-backup -l C -F "$files" 2>&1 res=$? echo "** INFO ** Uncrustify completed (exit code $res)" } | tee "${log}-1" # Log needs to be closed here, to be processed in next block @@ -133,4 +133,4 @@ cat "${log}-1" "${log}-2" > "$log" } | tee -a "$log" rm -f "${files}" -exit $ec +exit $ec \ No newline at end of file diff --git a/dev-tools/reformat-patches/after_include_openvpn-plugin.h.in.patch b/dev-tools/reformat-patches/after_include_openvpn-plugin.h.in.patch deleted file mode 100644 index 100da078ce7..00000000000 --- a/dev-tools/reformat-patches/after_include_openvpn-plugin.h.in.patch +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/include/openvpn-plugin.h.in b/include/openvpn-plugin.h.in -index 05bffab..05b4b6a 100644 ---- a/include/openvpn-plugin.h.in -+++ b/include/openvpn-plugin.h.in -@@ -169,7 +169,7 @@ typedef void *openvpn_plugin_handle_t; - /* - * We are compiling OpenVPN. - */ --/* #define OPENVPN_PLUGIN_DEF typedef */ -+#define OPENVPN_PLUGIN_DEF typedef - #define OPENVPN_PLUGIN_FUNC(name) (*name) - - #else /* ifdef OPENVPN_PLUGIN_H */ diff --git a/dev-tools/reformat-patches/before_include_openvpn-plugin.h.in.patch b/dev-tools/reformat-patches/before_include_openvpn-plugin.h.in.patch deleted file mode 100644 index 679c414971d..00000000000 --- a/dev-tools/reformat-patches/before_include_openvpn-plugin.h.in.patch +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/include/openvpn-plugin.h.in b/include/openvpn-plugin.h.in -index 34ad18b..f4c5472 100644 ---- a/include/openvpn-plugin.h.in -+++ b/include/openvpn-plugin.h.in -@@ -169,7 +169,7 @@ typedef void *openvpn_plugin_handle_t; - /* - * We are compiling OpenVPN. - */ --#define OPENVPN_PLUGIN_DEF typedef -+// #define OPENVPN_PLUGIN_DEF typedef - #define OPENVPN_PLUGIN_FUNC(name) (*name) - - #else diff --git a/dev-tools/special-files.lst b/dev-tools/special-files.lst index f3f77ea3b3b..e5f2fc2712f 100644 --- a/dev-tools/special-files.lst +++ b/dev-tools/special-files.lst @@ -1,4 +1,5 @@ E:doc/doxygen/doc_key_generation.h # @verbatim section gets mistreated, exclude it E:src/compat/compat-lz4.c # Preserve LZ4 upstream formatting E:src/compat/compat-lz4.h # Preserve LZ4 upstream formatting -P:include/openvpn-plugin.h.in # uncrustify segfaults, patch it before+after +E:src/openvpn/ovpn_dco_linux.h # Preserve ovpn-dco upstream formatting +E:src/openvpn/ovpn_dco_win.h # Preserve ovpn-dco-win upstream formatting diff --git a/dev-tools/uncrustify.conf b/dev-tools/uncrustify.conf index 25eb4cddb5d..325f3108c3b 100644 --- a/dev-tools/uncrustify.conf +++ b/dev-tools/uncrustify.conf @@ -36,6 +36,7 @@ sp_cond_question=add sp_bool=add sp_else_brace=add sp_brace_else=add +sp_after_comma=add pos_arith=Lead pos_bool=Lead nl_func_type_name=add @@ -45,6 +46,8 @@ nl_enum_leave_one_liners=true nl_brace_fparen=add nl_max=4 nl_after_func_proto=2 +nl_end_of_file_min=1 +nl_end_of_file=force # Always use scoping braces for conditionals mod_full_brace_if=add diff --git a/dev-tools/update-copyright.sh b/dev-tools/update-copyright.sh index 497b709e89a..6357fb896dc 100755 --- a/dev-tools/update-copyright.sh +++ b/dev-tools/update-copyright.sh @@ -2,8 +2,8 @@ # update-copyright-sh - Simple tool to update the Copyright lines # in all files checked into git # -# Copyright (C) 2016-2022 OpenVPN Inc -# Copyright (C) 2016-2022 David Sommerseth +# Copyright (C) 2016-2023 OpenVPN Inc +# Copyright (C) 2016-2023 David Sommerseth # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License @@ -48,4 +48,4 @@ done echo echo "** All files updated with $COPY_YEAR as the ending copyright year" echo -exit 0 +exit 0 \ No newline at end of file diff --git a/distro/Makefile.am b/distro/Makefile.am index 8f4e3498cd3..263818e4777 100644 --- a/distro/Makefile.am +++ b/distro/Makefile.am @@ -5,11 +5,11 @@ # packet encryption, packet authentication, and # packet compression. # -# Copyright (C) 2002-2022 OpenVPN Inc +# Copyright (C) 2002-2023 OpenVPN Inc # Copyright (C) 2006-2012 Alon Bar-Lev # MAINTAINERCLEANFILES = \ $(srcdir)/Makefile.in -SUBDIRS = systemd +SUBDIRS = systemd \ No newline at end of file diff --git a/distro/systemd/Makefile.am b/distro/systemd/Makefile.am index 322bd535d56..9074915b360 100644 --- a/distro/systemd/Makefile.am +++ b/distro/systemd/Makefile.am @@ -5,7 +5,7 @@ # packet encryption, packet authentication, and # packet compression. # -# Copyright (C) 2017-2022 OpenVPN Inc +# Copyright (C) 2017-2023 OpenVPN Inc # %.service: %.service.in Makefile @@ -21,6 +21,7 @@ if ENABLE_SYSTEMD systemdunit_DATA = \ openvpn-client@.service \ openvpn-server@.service +CLEANFILES = $(systemdunit_DATA) tmpfiles_DATA = \ tmpfiles-openvpn.conf dist_doc_DATA = \ @@ -31,4 +32,4 @@ install-data-hook: endif MAINTAINERCLEANFILES = \ - $(srcdir)/Makefile.in + $(srcdir)/Makefile.in \ No newline at end of file diff --git a/distro/systemd/openvpn-client@.service.in b/distro/systemd/openvpn-client@.service.in index cbcef6533c3..159fb4dcdb5 100644 --- a/distro/systemd/openvpn-client@.service.in +++ b/distro/systemd/openvpn-client@.service.in @@ -11,7 +11,7 @@ Type=notify PrivateTmp=true WorkingDirectory=/etc/openvpn/client ExecStart=@sbindir@/openvpn --suppress-timestamps --nobind --config %i.conf -CapabilityBoundingSet=CAP_IPC_LOCK CAP_NET_ADMIN CAP_NET_RAW CAP_SETGID CAP_SETUID CAP_SYS_CHROOT CAP_DAC_OVERRIDE +CapabilityBoundingSet=CAP_IPC_LOCK CAP_NET_ADMIN CAP_NET_RAW CAP_SETGID CAP_SETUID CAP_SETPCAP CAP_SYS_CHROOT CAP_DAC_OVERRIDE LimitNPROC=10 DeviceAllow=/dev/null rw DeviceAllow=/dev/net/tun rw diff --git a/distro/systemd/openvpn-server@.service.in b/distro/systemd/openvpn-server@.service.in index d1cc72cbd5d..6e8e7d945aa 100644 --- a/distro/systemd/openvpn-server@.service.in +++ b/distro/systemd/openvpn-server@.service.in @@ -11,7 +11,7 @@ Type=notify PrivateTmp=true WorkingDirectory=/etc/openvpn/server ExecStart=@sbindir@/openvpn --status %t/openvpn-server/status-%i.log --status-version 2 --suppress-timestamps --config %i.conf -CapabilityBoundingSet=CAP_IPC_LOCK CAP_NET_ADMIN CAP_NET_BIND_SERVICE CAP_NET_RAW CAP_SETGID CAP_SETUID CAP_SYS_CHROOT CAP_DAC_OVERRIDE CAP_AUDIT_WRITE +CapabilityBoundingSet=CAP_IPC_LOCK CAP_NET_ADMIN CAP_NET_BIND_SERVICE CAP_NET_RAW CAP_SETGID CAP_SETUID CAP_SETPCAP CAP_SYS_CHROOT CAP_DAC_OVERRIDE CAP_AUDIT_WRITE LimitNPROC=10 DeviceAllow=/dev/null rw DeviceAllow=/dev/net/tun rw diff --git a/doc/Makefile.am b/doc/Makefile.am index adf85446ced..b6e42816767 100644 --- a/doc/Makefile.am +++ b/doc/Makefile.am @@ -5,7 +5,7 @@ # packet encryption, packet authentication, and # packet compression. # -# Copyright (C) 2002-2022 OpenVPN Inc +# Copyright (C) 2002-2023 OpenVPN Inc # Copyright (C) 2006-2012 Alon Bar-Lev # @@ -50,6 +50,7 @@ openvpn_sections = \ man-sections/windows-options.rst openvpn_examples_sections = \ + man-sections/example-fingerprint.rst \ man-sections/examples.rst dist_noinst_DATA = \ @@ -99,4 +100,4 @@ else dist_man_MANS = $(build_man_pages) endif -dist-hook : $(build_man_pages) $(build_html_pages) +dist-hook : $(build_man_pages) $(build_html_pages) \ No newline at end of file diff --git a/doc/android.txt b/doc/android.txt index e287be0a8b2..394baf441e0 100644 --- a/doc/android.txt +++ b/doc/android.txt @@ -1,4 +1,6 @@ -This file documents the support in OpenVPN for Android 4.0 and up. +This file documents the support in OpenVPN for Android using the +VPNService API (https://developer.android.com/reference/android/net/VpnService) +that has been introduced in Android 4.0 (API 14). This support is primarily used in the "OpenVPN for Android" app (https://github.com/schwabe/ics-openvpn). For building see the developer @@ -8,26 +10,26 @@ Android provides the VPNService API (http://developer.android.com/reference/android/net/VpnService.html) which allows establishing VPN connections without rooting the device. -Since all the interfaces are are Android specific the calls to this -interface are made from the UI instead of OpenVPN directly. The API -needs the following parameters: +Unlike on other platforms, the tun device is openend by UI instead of +OpenVPN itself. The VpnService API needs the following parameters: - IP and netmask of tun interface - Networks that should be routed to the tun interface - DNS Servers and DNS Domain - MTU -All IPs/Routes are in CIDR style. Non CIDR routes are not supported. +All IPs/Routes are in CIDR style. Non-CIDR routes are not supported. Notable is the lack of support for setting routes to other interfaces usually used to avoid the server connection going over the tun -interface. The Android VPNService API has the concept of protecting -a socket from being routed over a interface. Calling protect (fd) -will internally bind the socket to the interface used for the +interface. However, Android 13 adds support for exclusion routes that +serve the same purpose. The Android VPNService API has the concept +of protecting a socket from being routed over an interface. Calling +protect (fd) will internally bind the socket to the interface used for the external connection (usually WiFi or mobile data). -To use OpenVPN with the VPNService API OpenVPN must be build with -the TARGET_ANDROID compile option. Also the UI must use a UNIX -domain socket to connect to OpenVPN. When compiled as TARGET_ANDROID +To use OpenVPN with the VPNService API OpenVPN must be built with +the TARGET_ANDROID compile option. Also the UI must use a UNIX +domain socket to connect to OpenVPN. When compiled as TARGET_ANDROID OpenVPN will use management callbacks instead of executing traditional ifconfig/route commands use the need-ok callback mechanism which will ask @@ -58,18 +60,16 @@ The GUI will then respond with a "needok 'command' ok' or "needok PERSIST_TUN_ACTION -In Android 4.4-4.4.2 a bug exists that does not allow to open a new tun fd -while a tun fd is still open. When OpenVPN wants to open an fd it will do -this query. The UI should compare the last configuration of -the tun device with the current tun configuration and reply with either (or -always respond with OPEN_AFTER_BEFORE/OPEN_BEFORE_CLOSE) +When OpenVPN wants to open an fd it will do this query via management. +The UI should compare the last configuration of the tun device with the current +tun configuration and reply with either NOACTION (or always respond with +OPEN_BEFORE_CLOSE). - NOACTION: Keep using the old fd -- OPEN_AFTER_CLOSE: First close the old fd and then open a new to workaround the bug - OPEN_BEFORE_CLOSE: the normal behaviour when the VPN configuration changed For example the UI could respond with -needok 'PERSIST_TUN_ACTION' OPEN_AFTER_CLOSE +needok 'PERSIST_TUN_ACTION' OPEN_BEFORE_CLOSE To protect a socket the OpenVPN will send a PROTECTFD to the UI. When sending the PROTECTFD command command to the UI it will send @@ -80,7 +80,7 @@ it from being routed over the VPN. When opening a tun device the OpenVPN process will first send all route, ifconfig and DNS related configuration to the UI and after that calls the OPENTUN command to receive a tun fd with the requested -configuration. The UI will than use the collected information to +configuration. The UI will then use the collected information to call the VPNService's establish() method to receive a fd which in turn is send to the OpenVPN process as ancillary message to the "needok 'OPENTUN' ok' response. @@ -95,7 +95,7 @@ To better support handover between networks, a the management command network-change [samenetwork] -is used on the Android platform. It tells OpenVPN to do the necessary -action when the network changes. Currently this is just calling +is used on the Android platform. It tells OpenVPN to do the necessary +action when the network changes. Currently this is just calling the protect callback when using peer-id regardless of the samenetwork. Without peer-id OpenVPN will generate USR1 when samenetwork is not set. diff --git a/doc/doxygen/doc_eventloop.h b/doc/doxygen/doc_eventloop.h index b0ff8da6a47..48d0c500353 100644 --- a/doc/doxygen/doc_eventloop.h +++ b/doc/doxygen/doc_eventloop.h @@ -61,6 +61,6 @@ * event loop function is called to drive the event processing. The * following implementations are available: * - Client mode using UDP or TCP: \c tunnel_point_to_point() - * - Server mode using UDP: \c tunnel_server_udp_single_threaded() + * - Server mode using UDP: \c tunnel_server_udp() * - Server mode using TCP: \c tunnel_server_tcp() */ diff --git a/doc/doxygen/doc_key_generation.h b/doc/doxygen/doc_key_generation.h index 44c2175a8ac..d32f9d89cfe 100644 --- a/doc/doxygen/doc_key_generation.h +++ b/doc/doxygen/doc_key_generation.h @@ -58,6 +58,12 @@ * * @subsection key_generation_method_2 Key method 2 * + * There are two methods for generating key data when using key method 2 + * the first is OpenVPN's traditional approach that exchanges random + * data and uses a PRF and the other is using the RFC5705 keying material + * exporter to generate the key material. For both methods the random + * data is exchange but only used in the traditional method. + * * -# The client generates random material in the following amounts: * - Pre-master secret: 48 bytes * - Client's PRF seed for master secret: 32 bytes @@ -73,8 +79,12 @@ * server's random material. * * %Key method 2 %key expansion is performed by the \c - * generate_key_expansion() function. Please refer to its source code for - * details of the %key expansion process. + * generate_key_expansion_openvpn_prf() function. Please refer to its source + * code for details of the %key expansion process. + * + * When the client sends the IV_PROTO_TLS_KEY_EXPORT flag and the server replies + * with `key-derivation tls-ekm` the RFC5705 key material exporter with the + * label EXPORTER-OpenVPN-datakeys is used for the key data. * * @subsection key_generation_random Source of random material * diff --git a/doc/doxygen/doc_protocol_overview.h b/doc/doxygen/doc_protocol_overview.h index f26ce3a36f6..37de1cb0e4d 100644 --- a/doc/doxygen/doc_protocol_overview.h +++ b/doc/doxygen/doc_protocol_overview.h @@ -118,6 +118,8 @@ * parts: * * - local \c session_id (random 64 bit value to identify TLS session). + * (the tls-server side uses a HMAC of the client to create a pseudo + * random number for a SYN Cookie like approach) * - HMAC signature of entire encapsulation header for HMAC firewall * [only if \c --tls-auth is specified] (usually 16 or 20 bytes). * - packet-id for replay protection (4 or 8 bytes, includes sequence diff --git a/doc/doxygen/doc_tunnel_state.h b/doc/doxygen/doc_tunnel_state.h index 299384ff76e..cbc1fa278b8 100644 --- a/doc/doxygen/doc_tunnel_state.h +++ b/doc/doxygen/doc_tunnel_state.h @@ -118,7 +118,7 @@ * tunnel_point_to_point() or \c tunnel_server(). * * In server-mode, \c main() calls the \c tunnel_server() function, which - * transfers control to \c tunnel_server_udp_single_threaded() or \c + * transfers control to \c tunnel_server_udp() or \c * tunnel_server_tcp() depending on the external transport protocol. * * These functions receive the \c context created in \c main(). This diff --git a/doc/man-sections/advanced-options.rst b/doc/man-sections/advanced-options.rst index bedc8841c0b..d5a6b4f2616 100644 --- a/doc/man-sections/advanced-options.rst +++ b/doc/man-sections/advanced-options.rst @@ -45,23 +45,6 @@ used when debugging or testing out special usage scenarios. Preserve most recently authenticated remote IP address and port number across :code:`SIGUSR1` or ``--ping-restart`` restarts. ---prng args - *(Advanced)* Change the PRNG (Pseudo-random number generator) parameters - - Valid syntaxes: - :: - - prng alg - prng alg nsl - - Changes the PRNG to use digest algorithm **alg** (default :code:`sha1`), - and set ``nsl`` (default :code:`16`) to the size in bytes of the nonce - secret length (between 16 and 64). - - Set ``alg`` to :code:`none` to disable the PRNG and use the OpenSSL - RAND\_bytes function instead for all of OpenVPN's pseudo-random number - needs. - --rcvbuf size Set the TCP/UDP socket receive buffer size. Defaults to operating system default. @@ -108,3 +91,16 @@ used when debugging or testing out special usage scenarios. *(Linux only)* Set the TX queue length on the TUN/TAP interface. Currently defaults to operating system default. +--disable-dco + Disables the opportunistic use of data channel offloading if available. + Without this option, OpenVPN will opportunistically use DCO mode if + the config options and the running kernel supports using DCO. + + Data channel offload currently requires data-ciphers to only contain + AEAD ciphers (AES-GCM and Chacha20-Poly1305) and Linux with the + ovpn-dco module. + + Note that some options have no effect or cannot be used when DCO mode + is enabled. + + On platforms that do not support DCO ``disable-dco`` has no effect. diff --git a/doc/man-sections/cipher-negotiation.rst b/doc/man-sections/cipher-negotiation.rst index a2feb5f9c55..b07176cd2b3 100644 --- a/doc/man-sections/cipher-negotiation.rst +++ b/doc/man-sections/cipher-negotiation.rst @@ -5,7 +5,7 @@ OpenVPN 2.4 and higher have the capability to negotiate the data cipher that is used to encrypt data packets. This section describes the mechanism in more detail and the different backwards compatibility mechanism with older server and clients. -OpenVPN 2.5 and higher behaviour +OpenVPN 2.5 and later behaviour -------------------------------- When both client and server are at least running OpenVPN 2.5, that the order of the ciphers of the server's ``--data-ciphers`` is used to pick the the data cipher. @@ -15,10 +15,14 @@ with a AUTH_FAILED message (as seen in client log): AUTH: Received control message: AUTH_FAILED,Data channel cipher negotiation failed (no shared cipher) -OpenVPN 2.5 will only allow the ciphers specified in ``--data-ciphers``. To ensure -backwards compatibility also if a cipher is specified using the ``--cipher`` option -it is automatically added to this list. If both options are unset the default is -:code:`AES-256-GCM:AES-128-GCM`. +OpenVPN 2.5 and later will only allow the ciphers specified in ``--data-ciphers``. +If ``--data-ciphers`` is not set the default is :code:`AES-256-GCM:AES-128-GCM`. +In 2.6 and later the default is changed to +:code:`AES-256-GCM:AES-128-GCM:CHACHA20-POLY1305` when Chacha20-Poly1305 is available. + +For backwards compatibility OpenVPN 2.6 and later with ``--compat-mode 2.4.x`` +(or lower) and OpenVPN 2.5 will automatically add a cipher specified using the +``--cipher`` option to this list. OpenVPN 2.4 clients ------------------- @@ -30,7 +34,7 @@ mode and does not have ``--ncp-disable`` will always announce support for This only causes a problem if ``--ncp-ciphers`` option has been changed from the default of :code:`AES-256-GCM:AES-128-GCM` to a value that does not include -these two ciphers. When a OpenVPN servers try to use `AES-256-GCM` or +these two ciphers. When an OpenVPN server tries to use `AES-256-GCM` or `AES-128-GCM` the connection will then fail. It is therefore recommended to always have the `AES-256-GCM` and `AES-128-GCM` ciphers to the ``--ncp-ciphers`` options to avoid this behaviour. @@ -80,15 +84,15 @@ support. If the server is 2.3 or older and has been configured with the ``--enable-small`` :code:`./configure` argument, adding -``data-ciphers-fallback cipher`` to the client config with the explicit +``--data-ciphers-fallback cipher`` to the client config with the explicit cipher used by the server is necessary. Blowfish in CBC mode (BF-CBC) deprecation ------------------------------------------ -The ``--cipher`` option defaulted to ``BF-CBC`` in OpenVPN 2.4 and older +The ``--cipher`` option defaulted to `BF-CBC` in OpenVPN 2.4 and older version. The default was never changed to ensure backwards compatibility. In OpenVPN 2.5 this behaviour has now been changed so that if the ``--cipher`` -is not explicitly set it does not allow the weak ``BF-CBC`` cipher any more +is not explicitly set it does not allow the weak `BF-CBC` cipher any more and needs to explicitly added as ``--cipher BFC-CBC`` or added to ``--data-ciphers``. diff --git a/doc/man-sections/client-options.rst b/doc/man-sections/client-options.rst index 7f0b8313852..e0678d36c5a 100644 --- a/doc/man-sections/client-options.rst +++ b/doc/man-sections/client-options.rst @@ -138,12 +138,19 @@ configuration. Set ``--verb 6`` for debugging info showing the transformation of src/dest addresses in packets. ---connect-retry n - Wait ``n`` seconds between connection attempts (default :code:`5`). +--connect-retry args + Wait ``n`` seconds between connection attempts (default :code:`1`). Repeated reconnection attempts are slowed down after 5 retries per - remote by doubling the wait time after each unsuccessful attempt. An - optional argument ``max`` specifies the maximum value of wait time in - seconds at which it gets capped (default :code:`300`). + remote by doubling the wait time after each unsuccessful attempt. + + Valid syntaxes: + :: + + connect retry n + connect retry n max + + If the optional argument ``max`` is specified, the maximum wait time in + seconds gets capped at that value (default :code:`300`). --connect-retry-max n ``n`` specifies the number of times each ``--remote`` or @@ -154,6 +161,65 @@ configuration. --connect-timeout n See ``--server-poll-timeout``. +--dns args + Client DNS configuration to be used with the connection. + + Valid syntaxes: + :: + + dns search-domains domain [domain ...] + dns server n address addr[:port] [addr[:port]] + dns server n resolve-domains|exclude-domains domain [domain ...] + dns server n dnssec yes|optional|no + dns server n transport DoH|DoT|plain + dns server n sni server-name + + The ``--dns search-domains`` directive takes one or more domain names + to be added as DNS domain suffixes. If it is repeated multiple times within + a configuration the domains are appended, thus e.g. domain names pushed by + a server will amend locally defined ones. + + The ``--dns server`` directive is used to configure DNS server ``n``. + The server id ``n`` must be a value between -128 and 127. For pushed + DNS server options it must be between 0 and 127. The server id is used + to group options and also for ordering the list of configured DNS servers; + lower numbers come first. DNS servers being pushed to a client replace + already configured DNS servers with the same server id. + + The ``address`` option configures the IPv4 and / or IPv6 address of + the DNS server. Optionally a port can be appended after a colon. IPv6 + addresses need to be enclosed in brackets if a port is appended. + + The ``resolve-domains`` and ``exclude-domains`` options take one or + more DNS domains which are explicitly resolved or explicitly not resolved + by a server. Only one of the options can be configured for a server. + ``resolve-domains`` is used to define a split-dns setup, where only + given domains are resolved by a server. ``exclude-domains`` is used to + define domains which will never be resolved by a server (e.g. domains + which can only be resolved locally). Systems which do not support fine + grained DNS domain configuration, will ignore these settings. + + The ``dnssec`` option is used to configure validation of DNSSEC records. + While the exact semantics may differ for resolvers on different systems, + ``yes`` likely makes validation mandatory, ``no`` disables it, and ``optional`` + uses it opportunistically. + + The ``transport`` option enables DNS-over-HTTPS (``DoH``) or DNS-over-TLS (``DoT``) + for a DNS server. The ``sni`` option can be used with them to specify the + ``server-name`` for TLS server name indication. + + Each server has to have at least one address configured for a configuration + to be valid. All the other options can be omitted. + + Note that not all options may be supported on all platforms. As soon support + for different systems is implemented, information will be added here how + unsupported options are treated. + + The ``--dns`` option will eventually obsolete the ``--dhcp-option`` directive. + Until then it will replace configuration at the places ``--dhcp-option`` puts it, + so that ``--dns`` overrides ``--dhcp-option``. Thus, ``--dns`` can be used today + to migrate from ``--dhcp-option``. + --explicit-exit-notify n In UDP client mode or point-to-point mode, send server/peer an exit notification if tunnel is restarted or OpenVPN process is exited. In @@ -161,9 +227,14 @@ configuration. immediately close its client instance object rather than waiting for a timeout. + If both server and client support sending this message using the control + channel, the message will be sent as control-channel message. Otherwise + the message is sent as data-channel message, which will be ignored by + data-channel offloaded peers. + The **n** parameter (default :code:`1` if not present) controls the maximum number of attempts that the client will try to resend the exit - notification message. + notification message if messages are sent in data-channel mode. In UDP server mode, send :code:`RESTART` control channel command to connected clients. The ``n`` parameter (default :code:`1` if not present) @@ -299,6 +370,10 @@ configuration. The client announces the list of supported ciphers configured with the ``--data-ciphers`` option to the server. + :code:`IV_MTU=` + The client announces the support of pushable MTU and the maximum MTU + it is willing to accept. + :code:`IV_GUI_VER= ` The UI version of a UI if one is running, for example :code:`de.blinkt.openvpn 0.5.47` for the Android app. @@ -408,7 +483,7 @@ configuration. If hostname resolve fails for ``--remote``, retry resolve for ``n`` seconds before failing. - Set ``n`` to "infinite" to retry indefinitely. + Set ``n`` to :code:`infinite` to retry indefinitely. By default, ``--resolv-retry infinite`` is enabled. You can disable by setting n=0. @@ -427,7 +502,7 @@ configuration. --server-poll-timeout n When connecting to a remote server do not wait for more than ``n`` seconds for a response before trying the next server. The default value - is 120s. This timeout includes proxy and TCP connect timeouts. + is :code:`120`. This timeout includes proxy and TCP connect timeouts. --static-challenge args Enable static challenge/response protocol @@ -445,4 +520,4 @@ configuration. See management-notes.txt in the OpenVPN distribution for a description of the OpenVPN challenge/response protocol. -.. include:: proxy-options.rst +.. include:: proxy-options.rst \ No newline at end of file diff --git a/doc/man-sections/encryption-options.rst b/doc/man-sections/encryption-options.rst index ee34f14e46d..abc73d90c10 100644 --- a/doc/man-sections/encryption-options.rst +++ b/doc/man-sections/encryption-options.rst @@ -104,7 +104,8 @@ Generating key material If supplied, include the supplied ``metadata`` in the wrapped client key. This metadata must be supplied in base64-encoded form. The - metadata must be at most 735 bytes long (980 bytes in base64). + metadata must be at most 733 bytes long (980 characters in base64, though + note that 980 base64 characters can encode more than 733 bytes). If no metadata is supplied, OpenVPN will use a 64-bit unix timestamp representing the current time in UTC, encoded in network order, as diff --git a/doc/man-sections/example-fingerprint.rst b/doc/man-sections/example-fingerprint.rst new file mode 100644 index 00000000000..852cca498d3 --- /dev/null +++ b/doc/man-sections/example-fingerprint.rst @@ -0,0 +1,196 @@ +Small OpenVPN setup with peer-fingerprint +========================================= +This section consists of instructions how to build a small OpenVPN setup with the +:code:`peer-fingerprint` option. This has the advantage of being easy to setup +and should be suitable for most small lab and home setups without the need for a PKI. +For bigger scale setup setting up a PKI (e.g. via easy-rsa) is still recommended. + +Both server and client configuration can be further modified to customise the +setup. + +Server setup +------------ +1. Install openvpn + + Compile from source-code (see `INSTALL` file) or install via a distribution (apt/yum/ports) + or via installer (Windows). + +2. Generate a self-signed certificate for the server: + :: + + openssl req -x509 -newkey ec:<(openssl ecparam -name secp384r1) -keyout server.key -out server.crt -nodes -sha256 -days 3650 -subj '/CN=server' + +3. Generate SHA256 fingerprint of the server certificate + + Use the OpenSSL command line utility to view the fingerprint of just + created certificate: + :: + + openssl x509 -fingerprint -sha256 -in server.crt -noout + + This output something similar to: + :: + + SHA256 Fingerprint=00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff + + +3. Write a server configuration (`server.conf`): +:: + + # The server certificate we created in step 1 + cert server.crt + key server.key + + dh none + dev tun + + # Listen on IPv6+IPv4 simultaneously + proto udp6 + + # The ip address the server will distribute + server 10.8.0.0 255.255.255.0 + server-ipv6 fd00:6f76:706e::/64 + + # A tun-mtu of 1400 avoids problems of too big packets after VPN encapsulation + tun-mtu 1400 + + # The fingerprints of your clients. After adding/removing one here restart the + # server + + + + # Notify clients when you restart the server to reconnect quickly + explicit-exit-notify 1 + + # Ping every 60s, restart if no data received for 5 minutes + keepalive 60 300 + +4. Add at least one client as described in the client section. + +5. Start the server. + - On systemd based distributions move `server.crt`, `server.key` and + `server.conf` to :code:`/etc/openvpn/server` and start it via systemctl + + :: + + sudo mv server.conf server.key server.crt /etc/openvpn/server + + sudo systemctl start openvpn-server@server + +Adding a client +--------------- +1. Install OpenVPN + +2. Generate a self-signed certificate for the client. In this example the client + name is alice. Each client should have a unique name. Replace alice with a + different name for each client. + :: + + openssl req -x509 -newkey ec:<(openssl ecparam -name secp384r1) -nodes -sha256 -days 3650 -subj '/CN=alice' + + This generate a certificate and a key for the client. The output of the command will look + something like this: + :: + + -----BEGIN PRIVATE KEY----- + [base64 content] + -----END PRIVATE KEY----- + ----- + -----BEGIN CERTIFICATE----- + [base 64 content] + -----END CERTIFICATE----- + + +3. Create a new client configuration file. In this example we will name the file + `alice.ovpn`: + + :: + + # The name of your server to connect to + remote yourserver.example.net + client + # use a random source port instead the fixed 1194 + nobind + + # Uncomment the following line if you want to route + # all traffic via the VPN + # redirect-gateway def1 ipv6 + + # To set a DNS server + # dhcp-option DNS 192.168.234.1 + + + -----BEGIN PRIVATE KEY----- + [Insert here the key created in step 2] + -----END PRIVATE KEY----- + + + -----BEGIN CERTIFICATE----- + [Insert here the certificate created in step 2] + -----END CERTIFICATE----- + + + # This is the fingerprint of the server that we trust. We generated this fingerprint + # in step 2 of the server setup + peer-fingerprint 00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff + + # The tun-mtu of the client should match the server MTU + tun-mtu 1400 + dev tun + + +4. Generate the fingerprint of the client certificate. For that we will + let OpenSSL read the client configuration file as the x509 command will + ignore anything that is not between the begin and end markers of the certificate: + + :: + + openssl x509 -fingerprint -sha256 -noout -in alice.ovpn + + This will again output something like + :: + + SHA256 Fingerprint=ff:ee:dd:cc:bb:aa:99:88:77:66:55:44:33:22:11:00:ff:ee:dd:cc:bb:aa:99:88:77:66:55:44:33:22:11:00 + +5. Edit the `server.conf` configuration file and add this new client + fingerprint as additional line between :code:`` + and :code:`` + + After adding *two* clients the part of configuration would look like this: + + :: + + + ff:ee:dd:cc:bb:aa:99:88:77:66:55:44:33:22:11:00:ff:ee:dd:cc:bb:aa:99:88:77:66:55:44:33:22:11:00 + 99:88:77:66:55:44:33:22:11:00:ff:ee:dd:cc:bb:aa:99:88:77:66:55:44:33:22:11:00:88:77:66:55:44:33 + + +6. (optional) if the client is an older client that does not support the + :code:`peer-fingerprint` (e.g. OpenVPN 2.5 and older, OpenVPN Connect 3.3 + and older), the client config `alice.ovpn` can be modified to still work with + these clients. + + Remove the line starting with :code:`peer-fingerprint`. Then + add a new :code:`` section at the end of the configuration file + with the contents of the :code:`server.crt` created in step 2 of the + server setup. The end of `alice.ovpn` file should like: + + :: + + [...] # Beginning of the file skipped + + + # The tun-mtu of the client should match the server MTU + tun-mtu 1400 + dev tun + + + [contents of the server.crt] + + + Note that we put the :code:`` section after the :code:`` section + to make the fingerprint generation from step 4 still work since it will + only use the first certificate it finds. + +7. Import the file into the OpenVPN client or just use the + :code:`openvpn alice.ovpn` to start the VPN. diff --git a/doc/man-sections/examples.rst b/doc/man-sections/examples.rst index 3f494ea4c34..3148601711c 100644 --- a/doc/man-sections/examples.rst +++ b/doc/man-sections/examples.rst @@ -60,8 +60,8 @@ that is part of your local subnet for either of the tunnel endpoints, you will get a weird feedback loop. -Example 1: A simple tunnel without security -------------------------------------------- +Example 1: A simple tunnel without security (not recommended) +------------------------------------------------------------- On bob: :: @@ -92,31 +92,41 @@ The ``--verb 9`` option will produce verbose output, similar to the quietly. -Example 2: A tunnel with static-key security (i.e. using a pre-shared secret) ------------------------------------------------------------------------------ +Example 2: A tunnel with self-signed certificates and fingerprint +----------------------------------------------------------------- -First build a static key on bob. +First build a self-signed certificate on bob and display its fingerprint. :: - openvpn --genkey --secret key + openssl req -x509 -newkey ec:<(openssl ecparam -name secp384r1) -keyout bob.pem -out bob.pem -nodes -sha256 -days 3650 -subj '/CN=bob' + openssl x509 -noout -sha256 -fingerprint -in bob.pem -This command will build a key file called ``key`` (in ascii format). Now -copy ``key`` to ``alice.example.com`` over a secure medium such as by using -the ``scp``\(1) program. +and the same on alice: +:: + + openssl req -x509 -newkey ec:<(openssl ecparam -name secp384r1) -keyout alice.pem -out alice.pem -nodes -sha256 -days 3650 -subj '/CN=alice' + openssl x509 -noout -sha256 -fingerprint -in alice.pem + + +These commands will build a text file called ``bob.pem`` or ``alice.pem`` (in ascii format) +that contain both self-signed certificate and key and show the fingerprint of the certificates. +Transfer the fingerprints over a secure medium such as by using +the ``scp``\(1) or ``ssh``\(1) program. On bob: :: - openvpn --remote alice.example.com --dev tun1 \ - --ifconfig 10.4.0.1 10.4.0.2 --verb 5 \ - --secret key + openvpn --ifconfig 10.4.0.1 10.4.0.2 --tls-server --dev tun --dh none \ + --cert bob.pem --key bob.pem --cipher AES-256-GCM \ + --peer-fingerprint "$fingerprint_of_alices_cert" On alice: :: - openvpn --remote bob.example.com --dev tun1 \ - --ifconfig 10.4.0.2 10.4.0.1 --verb 5 \ - --secret key + openvpn --remote bob.example.com --tls-client --dev tun1 \ + --ifconfig 10.4.0.2 10.4.0.1 --cipher AES-256-GCM \ + --cert alice.pem --key alice.pem + --peer-fingerprint "$fingerprint_of_bobs_cert" Now verify the tunnel is working by pinging across the tunnel. @@ -130,9 +140,11 @@ On alice: ping 10.4.0.1 +Note: This example use a elliptic curve (`secp384`), which allows +``--dh`` to be set to ``none``. -Example 3: A tunnel with full TLS-based security ------------------------------------------------- +Example 3: A tunnel with full PKI and TLS-based security +-------------------------------------------------------- For this test, we will designate ``bob`` as the TLS client and ``alice`` as the TLS server. diff --git a/doc/man-sections/generic-options.rst b/doc/man-sections/generic-options.rst index 18085f9bd6d..0bc83dea333 100644 --- a/doc/man-sections/generic-options.rst +++ b/doc/man-sections/generic-options.rst @@ -48,13 +48,34 @@ which mode OpenVPN is configured as. Note: The SSL library will probably need /dev/urandom to be available inside the chroot directory ``dir``. This is because SSL libraries - occasionally need to collect fresh random. Newer linux kernels and some + occasionally need to collect fresh randomness. Newer linux kernels and some BSDs implement a getrandom() or getentropy() syscall that removes the need for /dev/urandom to be available. +--compat-mode version + This option provides a way to alter the default of OpenVPN to be more + compatible with the version ``version`` specified. All of the changes + this option does can also be achieved using individual configuration + options. + + Note: Using this option reverts defaults to no longer recommended + values and should be avoided if possible. + + The following table details what defaults are changed depending on the + version specified. + + - 2.5.x or lower: ``--allow-compression asym`` is automatically added + to the configuration if no other compression options are present. + - 2.4.x or lower: The cipher in ``--cipher`` is appended to + ``--data-ciphers`` + - 2.3.x or lower: ``--data-cipher-fallback`` is automatically added with + the same cipher as ``--cipher`` + - 2.3.6 or lower: ``--tls-version-min 1.0`` is added to the configuration + when ``--tls-version-min`` is not explicitly set. + --config file Load additional config options from ``file`` where each line corresponds - to one command line option, but with the leading '--' removed. + to one command line option, but with the leading :code:`--` removed. If ``--config file`` is the only option to the openvpn command, the ``--config`` can be removed, and the command can be given as ``openvpn @@ -109,8 +130,14 @@ which mode OpenVPN is configured as. secret static.key --daemon progname - Become a daemon after all initialization functions are completed. This - option will cause all message and error output to be sent to the syslog + Become a daemon after all initialization functions are completed. + + Valid syntaxes:: + + daemon + daemon progname + + This option will cause all message and error output to be sent to the syslog file (such as :code:`/var/log/messages`), except for the output of scripts and ifconfig commands, which will go to :code:`/dev/null` unless otherwise redirected. The syslog redirection occurs immediately at the @@ -121,7 +148,7 @@ which mode OpenVPN is configured as. The optional ``progname`` parameter will cause OpenVPN to report its program name to the system logger as ``progname``. This can be useful in linking OpenVPN messages in the syslog file with specific tunnels. When - unspecified, ``progname`` defaults to "openvpn". + unspecified, ``progname`` defaults to :code:`openvpn`. When OpenVPN is run with the ``--daemon`` option, it will try to delay daemonization until the majority of initialization functions which are @@ -144,7 +171,19 @@ which mode OpenVPN is configured as. on console) and ``--auth-nocache`` will fail as soon as key renegotiation (and reauthentication) occurs. +--disable-dco + Disable "data channel offload" (DCO). + + On Linux don't use the ovpn-dco device driver, but rather rely on the + legacy tun module. + + You may want to use this option if your server needs to allow clients + older than version 2.4 to connect. + --disable-occ + **DEPRECATED** Disable "options consistency check" (OCC) in configurations + that do not use TLS. + Don't output a warning message if option inconsistencies are detected between peers. An example of an option inconsistency would be where one peer uses ``--dev tun`` while the other peer uses ``--dev tap``. @@ -156,6 +195,11 @@ which mode OpenVPN is configured as. --engine engine-name Enable OpenSSL hardware-based crypto engine functionality. + Valid syntaxes:: + + engine + engine engine-name + If ``engine-name`` is specified, use a specific crypto engine. Use the ``--show-engines`` standalone option to list the crypto engines which are supported by OpenSSL. @@ -170,7 +214,7 @@ which mode OpenVPN is configured as. call, improving CPU efficiency by 5% to 10%. This option can only be used on non-Windows systems, when ``--proto - udp`` is specified, and when ``--shaper`` is NOT specified. + udp`` is specified, and when ``--shaper`` is *NOT* specified. --group group Similar to the ``--user`` option, this option changes the group ID of @@ -200,7 +244,7 @@ which mode OpenVPN is configured as. May be used in order to execute OpenVPN in unprivileged environment. --keying-material-exporter args - Save Exported Keying Material [RFC5705] of len bytes (must be between 16 + Save Exported Keying Material [RFC5705] of ``len`` bytes (must be between 16 and 4095 bytes) using ``label`` in environment (:code:`exported_keying_material`) for use by plugins in :code:`OPENVPN_PLUGIN_TLS_FINAL` callback. @@ -237,6 +281,13 @@ which mode OpenVPN is configured as. likely fail. The limit can be increased using ulimit or systemd directives depending on how OpenVPN is started. + If the platform has the getrlimit(2) system call, OpenVPN will check + for the amount of mlock-able memory before calling mlockall(2), and + tries to increase the limit to 100 MB if less than this is configured. + 100 Mb is somewhat arbitrary - it is enough for a moderately-sized + OpenVPN deployment, but the memory usage might go beyond that if the + number of concurrent clients is high. + --nice n Change process priority after initialization (``n`` greater than 0 is lower priority, ``n`` less than zero is higher priority). @@ -244,7 +295,7 @@ which mode OpenVPN is configured as. --persist-key Don't re-read key files across :code:`SIGUSR1` or ``--ping-restart``. - This option can be combined with ``--user nobody`` to allow restarts + This option can be combined with ``--user`` to allow restarts triggered by the :code:`SIGUSR1` signal. Normally if you drop root privileges in OpenVPN, the daemon cannot be restarted since it will now be unable to re-read protected key files. @@ -261,13 +312,13 @@ which mode OpenVPN is configured as. --providers legacy default - Behaviour of changing this option between SIGHUP might not be well behaving. + Behaviour of changing this option between :code:`SIGHUP` might not be well behaving. If you need to change/add/remove this option, fully restart OpenVPN. --remap-usr1 signal Control whether internally or externally generated :code:`SIGUSR1` signals are remapped to :code:`SIGHUP` (restart without persisting state) or - SIGTERM (exit). + :code:`SIGTERM` (exit). ``signal`` can be set to :code:`SIGHUP` or :code:`SIGTERM`. By default, no remapping occurs. @@ -344,7 +395,8 @@ which mode OpenVPN is configured as. consider using the ``--persist-key`` and ``--persist-tun`` options. --status args - Write operational status to ``file`` every ``n`` seconds. + Write operational status to ``file`` every ``n`` seconds. ``n`` defaults + to :code:`60` if not specified. Valid syntaxes: :: @@ -421,10 +473,7 @@ which mode OpenVPN is configured as. * :code:`OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY` plug-in hooks returns success/failure via :code:`auth_control_file` when using deferred auth - method - - * :code:`OPENVPN_PLUGIN_ENABLE_PF` plugin hook to pass filtering rules - via ``pf_file`` + method and pending authentification via :code:`pending_auth_file`. --use-prediction-resistance Enable prediction resistance on mbed TLS's RNG. @@ -443,7 +492,7 @@ which mode OpenVPN is configured as. able to gain control of an OpenVPN session. Though OpenVPN's security features make this unlikely, it is provided as a second line of defense. - By setting ``user`` to :code:`nobody` or somebody similarly unprivileged, + By setting ``user`` to an unprivileged user dedicated to run openvpn, the hostile party would be limited in what damage they could cause. Of course once you take away privileges, you cannot return them to an OpenVPN session. This means, for example, that if you want to reset an @@ -453,5 +502,10 @@ which mode OpenVPN is configured as. operations in order to restart (such as re-reading key files or running ``ifconfig`` on the TUN device). + NOTE: Previous versions of openvpn used :code:`nobody` as the example + unpriviledged user. It is not recommended to actually use that user + since it is usually used by other system services already. Always + create a dedicated user for openvpn. + --writepid file - Write OpenVPN's main process ID to ``file``. + Write OpenVPN's main process ID to ``file``. \ No newline at end of file diff --git a/doc/man-sections/inline-files.rst b/doc/man-sections/inline-files.rst index 819bd3c8238..01e4a840604 100644 --- a/doc/man-sections/inline-files.rst +++ b/doc/man-sections/inline-files.rst @@ -4,8 +4,8 @@ INLINE FILE SUPPORT OpenVPN allows including files in the main configuration for the ``--ca``, ``--cert``, ``--dh``, ``--extra-certs``, ``--key``, ``--pkcs12``, ``--secret``, ``--crl-verify``, ``--http-proxy-user-pass``, ``--tls-auth``, -``--auth-gen-token-secret``, ``--tls-crypt`` and ``--tls-crypt-v2`` -options. +``--auth-gen-token-secret``, ``--peer-fingerprint``, ``--tls-crypt``, +``--tls-crypt-v2`` and ``--verify-hash`` options. Each inline file started by the line ```` diff --git a/doc/man-sections/link-options.rst b/doc/man-sections/link-options.rst index 71387805102..14e76b45193 100644 --- a/doc/man-sections/link-options.rst +++ b/doc/man-sections/link-options.rst @@ -24,13 +24,25 @@ the local and the remote host. from any address, not only the address which was specified in the ``--remote`` option. ---fragment max +--fragment args + + Valid syntax: + :: + + fragment max + fragment max mtu + Enable internal datagram fragmentation so that no UDP datagrams are sent which are larger than ``max`` bytes. - The ``max`` parameter is interpreted in the same way as the - ``--link-mtu`` parameter, i.e. the UDP packet size after encapsulation - overhead has been added in, but not including the UDP header itself. + If the :code:`mtu` parameter is present the ``max`` parameter is + interpreted to include IP and UDP encapsulation overhead. The + :code:`mtu` parameter is introduced in OpenVPN version 2.6.0. + + If the :code:`mtu` parameter is absent, the ``max`` parameter is + interpreted in the same way as the ``--link-mtu`` parameter, i.e. + the UDP packet size after encapsulation overhead has been added in, + but not including the UDP header itself. The ``--fragment`` option only makes sense when you are using the UDP protocol (``--proto udp``). @@ -59,6 +71,9 @@ the local and the remote host. keepalive interval timeout + Send ping once every ``interval`` seconds, restart if ping is not received + for ``timeout`` seconds. + This option can be used on both client and server side, but it is enough to add this on the server side as it will push appropriate ``--ping`` and ``--ping-restart`` options to the client. If used on both server and @@ -82,10 +97,15 @@ the local and the remote host. ping-restart 60 # Argument: timeout --link-mtu n - Sets an upper bound on the size of UDP packets which are sent between + **DEPRECATED** Sets an upper bound on the size of UDP packets which are sent between OpenVPN peers. *It's best not to set this parameter unless you know what you're doing.* + Due to variable header size of IP header (20 bytes for IPv4 and 40 bytes + for IPv6) and dynamically negotiated data channel cipher, this option + is not reliable. It is recommended to set tun-mtu with enough headroom + instead. + --local host Local host name or IP address for bind. If specified, OpenVPN will bind to this address only. If unspecified, OpenVPN will bind to all @@ -96,7 +116,7 @@ the local and the remote host. ``--nobind`` option. --mark value - Mark encrypted packets being sent with value. The mark value can be + Mark encrypted packets being sent with ``value``. The mark value can be matched in policy routing and packetfilter rules. This option is only supported in Linux and does nothing on other operating systems. @@ -105,19 +125,44 @@ the local and the remote host. (:code:`p2p`). OpenVPN 2.0 introduces a new mode (:code:`server`) which implements a multi-client server capability. ---mssfix max +--mssfix args + + Valid syntax: + :: + + mssfix max [mtu] + + mssfix max [fixed] + + mssfix + Announce to TCP sessions running over the tunnel that they should limit their send packet sizes such that after OpenVPN has encapsulated them, the resulting UDP packet size that OpenVPN sends to its peer will not - exceed ``max`` bytes. The default value is :code:`1450`. - - The ``max`` parameter is interpreted in the same way as the - ``--link-mtu`` parameter, i.e. the UDP packet size after encapsulation - overhead has been added in, but not including the UDP header itself. - Resulting packet would be at most 28 bytes larger for IPv4 and 48 bytes - for IPv6 (20/40 bytes for IP header and 8 bytes for UDP header). Default - value of 1450 allows IPv4 packets to be transmitted over a link with MTU - 1473 or higher without IP level fragmentation. + exceed ``max`` bytes. The default value is :code:`1492 mtu`. Use :code:`0` + as max to disable mssfix. + + If the :code:`mtu` parameter is specified the ``max`` value is interpreted + as the resulting packet size of VPN packets including the IP and UDP header. + Support for the :code:`mtu` parameter was added with OpenVPN version 2.6.0. + + If the :code:`mtu` parameter is not specified, the ``max`` parameter + is interpreted in the same way as the ``--link-mtu`` parameter, i.e. + the UDP packet size after encapsulation overhead has been added in, but + not including the UDP header itself. Resulting packet would be at most 28 + bytes larger for IPv4 and 48 bytes for IPv6 (20/40 bytes for IP header and + 8 bytes for UDP header). Default value of 1450 allows OpenVPN packets to be + transmitted over IPv4 on a link with MTU 1478 or higher without IP level + fragmentation (and 1498 for IPv6). + + If the :code:`fixed` parameter is specified, OpenVPN will make no attempt + to calculate the VPN encapsulation overhead but instead will set the MSS to + limit the size of the payload IP packets to the specified number. IPv4 packets + will have the MSS value lowered to mssfix - 40 and IPv6 packets to mssfix - 60. + + if ``--mssfix`` is specified is specified without any parameter it + inherits the parameters of ``--fragment`` if specified or uses the + default for ``--mssfix`` otherwise. The ``--mssfix`` option only makes sense when you are using the UDP protocol for OpenVPN peer-to-peer communication, i.e. ``--proto udp``. @@ -127,9 +172,9 @@ the local and the remote host. the first place, and if big packets come through anyhow (from protocols other than TCP), ``--fragment`` will internally fragment them. - Both ``--fragment`` and ``--mssfix`` are designed to work around cases - where Path MTU discovery is broken on the network path between OpenVPN - peers. + ``--max-packet-size``, ``--fragment``, and ``--mssfix`` are designed to + work around cases where Path MTU discovery is broken on the network path + between OpenVPN peers. The usual symptom of such a breakdown is an OpenVPN connection which successfully starts, but then stalls during active usage. @@ -144,6 +189,10 @@ the local and the remote host. --tun-mtu 1500 --fragment 1300 --mssfix + If the ``max-packet-size size`` option is used in the configuration + it will also act as if ``mssfix size mtu`` was specified in the + configuration. + --mtu-disc type Should we do Path MTU discovery on TCP/UDP channel? Only supported on OSes such as Linux that supports the necessary system call to set. @@ -167,7 +216,7 @@ the local and the remote host. Do not bind to local address and port. The IP stack will allocate a dynamic port for returning packets. Since the value of the dynamic port could not be known in advance by a peer, this option is only suitable - for peers which will be initiating connections by using the --remote + for peers which will be initiating connections by using the ``--remote`` option. --passtos @@ -191,6 +240,8 @@ the local and the remote host. (2) To provide a basis for the remote to test the existence of its peer using the ``--ping-exit`` option. + When using OpenVPN in server mode see also ``--keepalive``. + --ping-exit n Causes OpenVPN to exit after ``n`` seconds pass without reception of a ping or other packet from remote. This option can be combined with @@ -294,18 +345,19 @@ the local and the remote host. --replay-window args Modify the replay protection sliding-window size and time window. - Valid syntax: - :: + Valid syntaxes:: - replay-window n [t] + replay-window n + replay-window n t - Use a replay protection sliding-window of size **n** and a time window - of **t** seconds. + Use a replay protection sliding-window of size ``n`` and a time window + of ``t`` seconds. - By default **n** is 64 (the IPSec default) and **t** is 15 seconds. + By default ``n`` is :code:`64` (the IPSec default) and ``t`` is + :code:`15` seconds. - This option is only relevant in UDP mode, i.e. when either **--proto - udp** is specified, or no **--proto** option is specified. + This option is only relevant in UDP mode, i.e. when either ``--proto + udp`` is specified, or no ``--proto`` option is specified. When OpenVPN tunnels IP packets over UDP, there is the possibility that packets might be dropped or delivered out of order. Because OpenVPN, @@ -369,10 +421,6 @@ the local and the remote host. Persist replay-protection state across sessions using ``file`` to save and reload the state. - This option will strengthen protection against replay attacks, - especially when you are using OpenVPN in a dynamic context (such as with - ``--inetd``) when OpenVPN sessions are frequently started and stopped. - This option will keep a disk copy of the current replay protection state (i.e. the most recent packet timestamp and sequence number received from the remote peer), so that if an OpenVPN session is stopped and @@ -383,6 +431,17 @@ the local and the remote host. default) and you are using either ``--secret`` (shared-secret key mode) or TLS mode with ``--tls-auth``. +--session-timeout n + Raises :code:`SIGTERM` for the client instance after ``n`` seconds since + the beginning of the session, forcing OpenVPN to disconnect. + In client mode, OpenVPN will disconnect and exit, while in server mode + all client sessions are terminated. + + This option can also be specified in a client instance config file + using ``--client-config-dir`` or dynamically generated using a + ``--client-connect`` script. In these cases, only the related client + session is terminated. + --socket-flags flags Apply the given flags to the OpenVPN transport socket. Currently, only :code:`TCP_NODELAY` is supported. @@ -410,3 +469,27 @@ the local and the remote host. if mode server: socket-flags TCP_NODELAY push "socket-flags TCP_NODELAY" + +--max-packet-size size + This option will instruct OpenVPN to try to limit the maximum on-write packet + size by restricting the control channel packet size and setting ``--mssfix``. + + OpenVPN will try to keep its control channel messages below this size but + due to some constraints in the protocol this is not always possible. If the + option is not set, the control packet maximum size defaults to 1250. + The control channel packet size will be restricted to values between + 154 and 2048. The maximum packet size includes encapsulation overhead like + UDP and IP. + + In terms of ``--mssfix`` it will expand to: + :: + + mssfix size mtu + + If you need to set ``--mssfix`` for data channel and control channel maximum + packet size independently, use ``--max-packet-size`` first, followed by a + ``--mssfix`` in the configuration. + + In general the default size of 1250 should work almost universally apart + from specific corner cases, especially since IPv6 requires a MTU of 1280 + or larger. diff --git a/doc/man-sections/log-options.rst b/doc/man-sections/log-options.rst index e385d1801ea..d2451d8a12c 100644 --- a/doc/man-sections/log-options.rst +++ b/doc/man-sections/log-options.rst @@ -15,8 +15,8 @@ Log options Output logging messages to ``file``, including output to stdout/stderr which is generated by called scripts. If ``file`` already exists it will be truncated. This option takes effect immediately when it is parsed in - the command line and will supersede syslog output if ``--daemon`` or - ``--inetd`` is also specified. This option is persistent over the entire + the command line and will supersede syslog output if ``--daemon`` + is also specified. This option is persistent over the entire course of an OpenVPN instantiation and will not be reset by :code:`SIGHUP`, :code:`SIGUSR1`, or ``--ping-restart``. diff --git a/doc/man-sections/management-options.rst b/doc/man-sections/management-options.rst index de0d47e7c60..8dad52b38ec 100644 --- a/doc/man-sections/management-options.rst +++ b/doc/man-sections/management-options.rst @@ -65,11 +65,6 @@ server and client mode operations. When the management interface is listening on a unix domain socket, only allow connections from group ``g``. ---management-client-pf - Management interface clients must specify a packet filter file for each - connecting client. See :code:`management-notes.txt` in OpenVPN - distribution for detailed notes. - --management-client-user u When the management interface is listening on a unix domain socket, only allow connections from user ``u``. @@ -90,9 +85,15 @@ server and client mode operations. management-external-key management-external-key nopadding management-external-key pkcs1 + management-external-key pss + + or any combination like: + :: + management-external-key nopadding pkcs1 + management-external-key pkcs1 pss - The optional parameters :code:`nopadding` and :code:`pkcs1` signal + The optional parameters :code:`nopadding` :code:`pkcs1` and :code:`pss` signal support for different padding algorithms. See :code:`doc/mangement-notes.txt` for a complete description of this feature. diff --git a/doc/man-sections/pkcs11-options.rst b/doc/man-sections/pkcs11-options.rst index c064aca5dfe..de1662b7ee7 100644 --- a/doc/man-sections/pkcs11-options.rst +++ b/doc/man-sections/pkcs11-options.rst @@ -13,7 +13,8 @@ PKCS#11 / SmartCard options --pkcs11-id name Specify the serialized certificate id to be used. The id can be gotten - by the standalone ``--show-pkcs11-ids`` option. + by the standalone ``--show-pkcs11-ids`` option. See also the description + of ``--pkcs11-providers`` option. --pkcs11-id-management Acquire PKCS#11 id from management interface. In this case a @@ -21,6 +22,7 @@ PKCS#11 / SmartCard options application may use pkcs11-id-count command to retrieve available number of certificates, and pkcs11-id-get command to retrieve certificate id and certificate body. + See also the description of ``--pkcs11-providers`` option. --pkcs11-pin-cache seconds Specify how many seconds the PIN can be cached, the default is until the @@ -51,15 +53,18 @@ PKCS#11 / SmartCard options pkcs11-protected-authentication 0 pkcs11-protected-authentication 1 ---pkcs11-providers provider +--pkcs11-providers providers Specify an RSA Security Inc. PKCS #11 Cryptographic Token Interface - (Cryptoki) providers to load. This option can be used instead of - ``--cert``, ``--key`` and ``--pkcs12``. - - If p11-kit is present on the system, its :code:`p11-kit-proxy.so` module - will be loaded by default if either the ``--pkcs11-id`` or - ``--pkcs11-id-management`` options are specified without - ``--pkcs11-provider`` being given. + (Cryptoki) providers to load. A space-separated list of one or more + provider library names may be specified. This option along with ``--pkcs11-id`` + or ``pkcs11-id-management`` can be used instead of + ``--cert`` and ``--key`` or ``--pkcs12``. + + If p11-kit is present on the system and was enabled during build, its + :code:`p11-kit-proxy.so` module will be loaded by default if either + the ``--pkcs11-id`` or ``--pkcs11-id-management`` options is present without + ``--pkcs11-providers``. If default loading is not enabled in the build and + no providers are specified, the former options will be ignored. --show-pkcs11-ids args (Standalone) Show PKCS#11 token object list. diff --git a/doc/man-sections/protocol-options.rst b/doc/man-sections/protocol-options.rst index 25f8db12d95..8b2117d4b23 100644 --- a/doc/man-sections/protocol-options.rst +++ b/doc/man-sections/protocol-options.rst @@ -18,13 +18,13 @@ configured in a compatible way between both the local and remote side. The ``mode`` argument can be one of the following values: - :code:`asym` (default) + :code:`asym` OpenVPN will only *decompress downlink packets* but *not compress uplink packets*. This also allows migrating to disable compression when changing both server and client configurations to remove compression at the same time is not a feasible option. - :code:`no` + :code:`no` (default) OpenVPN will refuse any non-stub compression. :code:`yes` @@ -57,37 +57,42 @@ configured in a compatible way between both the local and remote side. http://www.cs.ucsd.edu/users/mihir/papers/hmac.html --cipher alg - This option is deprecated for server-client mode. ``--data-ciphers`` - or possibly `--data-ciphers-fallback`` should be used instead. - - Encrypt data channel packets with cipher algorithm ``alg``. - - The default is :code:`BF-CBC`, an abbreviation for Blowfish in Cipher - Block Chaining mode. When cipher negotiation (NCP) is allowed, - OpenVPN 2.4 and newer on both client and server side will automatically - upgrade to :code:`AES-256-GCM`. See ``--data-ciphers`` and - ``--ncp-disable`` for more details on NCP. - - Using :code:`BF-CBC` is no longer recommended, because of its 64-bit - block size. This small block size allows attacks based on collisions, as - demonstrated by SWEET32. See - https://community.openvpn.net/openvpn/wiki/SWEET32 - for details. Due to this, support for :code:`BF-CBC`, :code:`DES`, - :code:`CAST5`, :code:`IDEA` and :code:`RC2` ciphers will be removed in - OpenVPN 2.6. - - To see other ciphers that are available with OpenVPN, use the + This option should not be used any longer in TLS mode and still + exists for two reasons: + + * compatibility with old configurations still carrying it + around; + + * allow users connecting to OpenVPN peers older than 2.6.0 + to have ``--cipher`` configured the same way as the remote + counterpart. This can avoid MTU/frame size warnings. + + Before 2.4.0, this option was used to select the cipher to be + configured on the data channel, however, later versions usually + ignored this directive in favour of a negotiated cipher. + Starting with 2.6.0, this option is always ignored in TLS mode + when it comes to configuring the cipher and will only control the + cipher for ``--secret`` pre-shared-key mode (note: this mode is + deprecated and strictly not recommended). + + If you wish to specify the cipher to use on the data channel, + please see ``--data-ciphers`` (for regular negotiation) and + ``--data-ciphers-fallback`` (for a fallback option when the + negotiation cannot take place because the other peer is old or + has negotiation disabled). + + To see ciphers that are available with OpenVPN, use the ``--show-ciphers`` option. Set ``alg`` to :code:`none` to disable encryption. --compress algorithm - **DEPRECATED** Enable a compression algorithm. Compression is generally - not recommended. VPN tunnels which use compression are susceptible to - the VORALCE attack vector. + **DEPRECATED** Enable a compression algorithm. Compression is generally + not recommended. VPN tunnels which use compression are susceptible to + the VORALCE attack vector. See also the :code:`migrate` parameter below. The ``algorithm`` parameter may be :code:`lzo`, :code:`lz4`, - :code:`lz4-v2`, :code:`stub`, :code:`stub-v2` or empty. + :code:`lz4-v2`, :code:`stub`, :code:`stub-v2`, :code:`migrate` or empty. LZO and LZ4 are different compression algorithms, with LZ4 generally offering the best performance with least CPU usage. @@ -96,6 +101,11 @@ configured in a compatible way between both the local and remote side. other variants always add one extra framing byte compared to no compression framing. + Especially :code:`stub-v2` is essentially identical to no compression and + no compression framing as its header indicates IP version 5 in a tun setup + and can (ab)used to complete disable compression to clients. (See the + :code:`migrate` option below) + If the ``algorithm`` parameter is :code:`stub`, :code:`stub-v2` or empty, compression will be turned off, but the packet framing for compression will still be enabled, allowing a different setting to be pushed later. @@ -106,6 +116,15 @@ configured in a compatible way between both the local and remote side. Note: the :code:`stub` (or empty) option is NOT compatible with the older option ``--comp-lzo no``. + Using :code:`migrate` as compression algorithm enables a special migration mode. + It allows migration away from the ``--compress``/``--comp-lzo`` options to no compression. + This option sets the server to no compression mode and the server behaves identical to + a server without a compression option for all clients without a compression in their + config. However, if a client is detected that indicates that compression is used (via OCC), + the server will automatically add ``--push compress stub-v2`` to the client specific + configuration if supported by the client and otherwise switch to ``comp-lzo no`` + and add ``--push comp-lzo`` to the client specific configuration. + ***Security Considerations*** Compression and encryption is a tricky combination. If an attacker knows @@ -164,27 +183,21 @@ configured in a compatible way between both the local and remote side. ``--tls-auth`` and ``--secret`` options. Useful when using inline files (See section on inline files). ---keysize n - **DEPRECATED** This option will be removed in OpenVPN 2.6. - - Size of cipher key in bits (optional). If unspecified, defaults to - cipher-specific default. The ``--show-ciphers`` option (see below) shows - all available OpenSSL ciphers, their default key sizes, and whether the - key size can be changed. Use care in changing a cipher's default key - size. Many ciphers have not been extensively cryptanalyzed with - non-standard key lengths, and a larger key may offer no real guarantee - of greater security, or may even reduce security. - --data-ciphers cipher-list Restrict the allowed ciphers to be negotiated to the ciphers in ``cipher-list``. ``cipher-list`` is a colon-separated list of ciphers, - and defaults to :code:`AES-256-GCM:AES-128-GCM`. + and defaults to :code:`AES-256-GCM:AES-128-GCM:CHACHA20-POLY1305` when + Chacha20-Poly1305 is available and otherwise :code:`AES-256-GCM:AES-128-GCM`. For servers, the first cipher from ``cipher-list`` that is also supported by the client will be pushed to clients that support cipher negotiation. - Starting with OpenVPN 2.5.9 a cipher can be prefixed with a :code:`?` to mark + For more details see the chapter on `Data channel cipher negotiation`_. + *Especially* if you need to support clients with OpenVPN versions older + than 2.4! + + Starting with OpenVPN 2.6 a cipher can be prefixed with a :code:`?` to mark it as optional. This allows including ciphers in the list that may not be available on all platforms. E.g. :code:`AES-256-GCM:AES-128-GCM:?CHACHA20-POLY1305` would only enable @@ -192,25 +205,17 @@ configured in a compatible way between both the local and remote side. supports it. Cipher negotiation is enabled in client-server mode only. I.e. if - ``--mode`` is set to 'server' (server-side, implied by setting + ``--mode`` is set to `server` (server-side, implied by setting ``--server`` ), or if ``--pull`` is specified (client-side, implied by - setting --client). + setting ``--client``). If no common cipher is found during cipher negotiation, the connection is terminated. To support old clients/old servers that do not provide any cipher negotiation support see ``--data-ciphers-fallback``. - Additionally, to allow for more smooth transition, if NCP is enabled, - OpenVPN will inherit the cipher of the peer if that cipher is different - from the local ``--cipher`` setting, but the peer cipher is one of the - ciphers specified in ``--data-ciphers``. E.g. a non-NCP client (<=v2.3, - or with --ncp-disabled set) connecting to a NCP server (v2.4+) with - ``--cipher BF-CBC`` and ``--data-ciphers AES-256-GCM:AES-256-CBC`` set can - either specify ``--cipher BF-CBC`` or ``--cipher AES-256-CBC`` and both - will work. - - Note for using NCP with an OpenVPN 2.4 peer: This list must include the - :code:`AES-256-GCM` and :code:`AES-128-GCM` ciphers. + If ``--compat-mode`` is set to a version older than 2.5.0 the cipher + specified by ``--cipher`` will be appended to ``--data-ciphers`` if + not already present. This list is restricted to be 127 chars long after conversion to OpenVPN ciphers. @@ -219,21 +224,16 @@ configured in a compatible way between both the local and remote side. to ``--data-ciphers`` in OpenVPN 2.5 to more accurately reflect its meaning. --data-ciphers-fallback alg + Configure a cipher that is used to fall back to if we could not determine + which cipher the peer is willing to use. - Configure a cipher that is used to fall back to if we could not determine - which cipher the peer is willing to use. - - This option should only be needed to - connect to peers that are running OpenVPN 2.3 and older version, and - have been configured with `--enable-small` - (typically used on routers or other embedded devices). - ---ncp-disable - **DEPRECATED** Disable "Negotiable Crypto Parameters". This completely - disables cipher negotiation. + This option should only be needed to + connect to peers that are running OpenVPN 2.3 or older versions, and + have been configured with ``--enable-small`` + (typically used on routers or other embedded devices). --secret args - Enable Static Key encryption mode (non-TLS). Use pre-shared secret + **DEPRECATED** Enable Static Key encryption mode (non-TLS). Use pre-shared secret ``file`` which was generated with ``--genkey``. Valid syntaxes: @@ -285,4 +285,4 @@ configured in a compatible way between both the local and remote side. Transition window -- our old key can live this many seconds after a new a key renegotiation begins (default :code:`3600` seconds). This feature allows for a graceful transition from old to new key, and removes the key - renegotiation sequence from the critical path of tunnel data forwarding. + renegotiation sequence from the critical path of tunnel data forwarding. \ No newline at end of file diff --git a/doc/man-sections/script-options.rst b/doc/man-sections/script-options.rst index 03b3dd77b51..3d2c7445373 100644 --- a/doc/man-sections/script-options.rst +++ b/doc/man-sections/script-options.rst @@ -52,6 +52,11 @@ Script Order of Execution Executed in ``--mode server`` mode on new client connections, when the client is still untrusted. +#. ``--client-crresponse`` + + Execute in ``--mode server`` whenever a client sends a + :code:`CR_RESPONSE` message + SCRIPT HOOKS ------------ @@ -72,7 +77,7 @@ SCRIPT HOOKS double-quoted and/or escaped using a backslash, and should be separated by one or more spaces. - If ``method`` is set to :code:`via-env`, OpenVPN will call ``script`` + If ``method`` is set to :code:`via-env`, OpenVPN will call ``cmd`` with the environmental variables :code:`username` and :code:`password` set to the username/password strings provided by the client. *Beware* that this method is insecure on some platforms which make the environment @@ -80,7 +85,7 @@ SCRIPT HOOKS If ``method`` is set to :code:`via-file`, OpenVPN will write the username and password to the first two lines of a temporary file. The filename - will be passed as an argument to ``script``, and the file will be + will be passed as an argument to ``cmd``, and the file will be automatically deleted by OpenVPN after the script returns. The location of the temporary file is controlled by the ``--tmp-dir`` option, and will default to the current directory if unspecified. For security, @@ -90,7 +95,55 @@ SCRIPT HOOKS The script should examine the username and password, returning a success exit code (:code:`0`) if the client's authentication request is to be - accepted, or a failure code (:code:`1`) to reject the client. + accepted, a failure code (:code:`1`) to reject the client, or a that + the authentication is deferred (:code:`2`). If the authentication is + deferred, the script must fork/start a background or another non-blocking + operation to continue the authentication in the background. When finshing + the authentication, a :code:`1` or :code:`0` must be written to the + file specified by the :code:`auth_control_file`. + + If the file specified by :code:`auth_failed_reason_file` exists and has + non-empty content, the content of this file will be used as AUTH_FAILED + message. To avoid race conditions, this file should be written before + :code:`auth_control_file`. + + This auth fail reason can be something simple like "User has been permanently + disabled" but there are also some special auth failed messages. + + The ``TEMP`` message indicates that the authentication + temporarily failed and that the client should continue to retry to connect. + The server can optionally give a user readable message and hint the client a + behavior how to proceed. The keywords of the ``AUTH_FAILED,TEMP`` message + are comma separated keys/values and provide a hint to the client how to + proceed. Currently defined keywords are: + + ``backoff`` :code:`s` + instructs the client to wait at least :code:`s` seconds before the next + connection attempt. If the client already uses a higher delay for + reconnection attempt, the delay will not be shortened. + + ``advance addr`` + Instructs the client to reconnect to the next (IP) address of the + current server. + + ``advance remote`` + Instructs the client to skip the remaining IP addresses of the current + server and instead connect to the next server specified in the + configuration file. + + ``advance no`` + Instructs the client to retry connecting to the same server again. + + For example, the message ``TEMP[backoff 42,advance no]: No free IP addresses`` + indicates that the VPN connection can currently not succeed and instructs + the client to retry in 42 seconds again. + + When deferred authentication is in use, the script can also request + pending authentication by writing to the file specified by the + :code:`auth_pending_file`. The first line must be the timeout in + seconds, the required method on the second line (e.g. crtext) and + third line must be the EXTRA as documented in the + ``client-pending-auth`` section of `doc/management.txt`. This directive is designed to enable a plugin-style interface for extending OpenVPN's authentication capabilities. @@ -111,6 +164,28 @@ SCRIPT HOOKS For a sample script that performs PAM authentication, see :code:`sample-scripts/auth-pam.pl` in the OpenVPN source distribution. +--client-crresponse + Executed when the client sends a text based challenge response. + + Valid syntax: + :: + + client-crresponse cmd + + OpenVPN will write the response of the client into a temporary file. + The filename will be passed as an argument to ``cmd``, and the file will be + automatically deleted by OpenVPN after the script returns. + + The response is passed as is from the client. The script needs to check + itself if the input is valid, e.g. if the input is valid base64 encoding. + + The script can either directly write the result of the verification to + :code:`auth_control_file or further defer it. See ``--auth-user-pass-verify`` + for details. + + For a sample script that implement TOTP (RFC 6238) based two-factor + authentication, see :code:`sample-scripts/totpauth.py`. + --client-connect cmd Run command ``cmd`` on client connection. @@ -364,15 +439,17 @@ SCRIPT HOOKS For ``--dev tun`` execute as: :: - cmd tun_dev tun_mtu link_mtu ifconfig_local_ip ifconfig_remote_ip [init | restart] + cmd tun_dev tun_mtu 0 ifconfig_local_ip ifconfig_remote_ip [init | restart] For ``--dev tap`` execute as: :: - cmd tap_dev tap_mtu link_mtu ifconfig_local_ip ifconfig_netmask [init | restart] + cmd tap_dev tap_mtu 0 ifconfig_local_ip ifconfig_netmask [init | restart] See the `Environmental Variables`_ section below for additional - parameters passed as environmental variables. + parameters passed as environmental variables. The ``0`` argument + used to be ``link_mtu`` which is no longer passed to scripts - to + keep the argument order, it was replaced with ``0``. Note that if ``cmd`` includes arguments, all OpenVPN-generated arguments will be appended to them to build an argument list with which the @@ -574,6 +651,25 @@ instances. netsh.exe calls which sometimes just do not work right with interface names). Set prior to ``--up`` or ``--down`` script execution. +:code:`dns_*` + The ``--dns`` configuration options will be made available to script + execution through this set of environment variables. Variables appear + only if the corresponding option has a value assigned. For the semantics + of each individual variable, please refer to the documentation for ``--dns``. + + :: + + dns_search_domain_{n} + dns_server_{n}_address4 + dns_server_{n}_port4 + dns_server_{n}_address6 + dns_server_{n}_port6 + dns_server_{n}_resolve_domain_{m} + dns_server_{n}_exclude_domain_{m} + dns_server_{n}_dnssec + dns_server_{n}_transport + dns_server_{n}_sni + :code:`foreign_option_{n}` An option pushed via ``--push`` to a client which does not natively support it, such as ``--dhcp-option`` on a non-Windows system, will be @@ -652,9 +748,9 @@ instances. ``--client-connect`` and ``--client-disconnect`` scripts. :code:`link_mtu` - The maximum packet size (not including the IP header) of tunnel data in - UDP tunnel transport mode. Set prior to ``--up`` or ``--down`` script - execution. + No longer passed to scripts since OpenVPN 2.6.0. Used to be the + maximum packet size (not including the IP header) of tunnel data in + UDP tunnel transport mode. :code:`local` The ``--local`` parameter. Set on program initiation and reset on diff --git a/doc/man-sections/server-options.rst b/doc/man-sections/server-options.rst index 55c2c30bf9e..0134b670404 100644 --- a/doc/man-sections/server-options.rst +++ b/doc/man-sections/server-options.rst @@ -14,7 +14,7 @@ fast hardware. SSL/TLS authentication must be used in this mode. Valid syntax: :: - auth-gen-token [lifetime] [external-auth] + auth-gen-token [lifetime] [renewal-time] [external-auth] After successful user/password authentication, the OpenVPN server will with this option generate a temporary authentication token and push that @@ -31,13 +31,17 @@ fast hardware. SSL/TLS authentication must be used in this mode. The lifetime is defined in seconds. If lifetime is not set or it is set to :code:`0`, the token will never expire. + If ``renewal-time`` is not set it defaults to ``reneg-sec``. + + The token will expire either after the configured ``lifetime`` of the token is reached or after not being renewed for more than 2 \* - ``reneg-sec`` seconds. Clients will be sent renewed tokens on every TLS - renogiation to keep the client's token updated. This is done to - invalidate a token if a client is disconnected for a sufficently long - time, while at the same time permitting much longer token lifetimes for - active clients. + ``renewal-time`` seconds. Clients will be sent renewed tokens on every TLS + renegotiation. If ``renewal-time`` is lower than ``reneg-sec`` the server + will push an updated temporary authentication token every ``reneweal-time`` + seconds. This is done to invalidate a token if a client is disconnected for a + sufficiently long time, while at the same time permitting much longer token + lifetimes for active clients. This feature is useful for environments which are configured to use One Time Passwords (OTP) as part of the user/password authentications and @@ -46,7 +50,7 @@ fast hardware. SSL/TLS authentication must be used in this mode. When the :code:`external-auth` keyword is present the normal authentication method will always be called even if auth-token succeeds. Normally other authentications method are skipped if auth-token - verification suceeds or fails. + verification succeeds or fails. This option postpones this decision to the external authentication methods and checks the validity of the account and do other checks. @@ -146,6 +150,10 @@ fast hardware. SSL/TLS authentication must be used in this mode. server. Don't use this option if you want to firewall tunnel traffic using custom, per-client rules. + Please note that when using data channel offload this option has no + effect. Packets are always sent to the tunnel interface and then + routed based on the system routing table. + --disable Disable a particular client (based on the common name) from connecting. Don't use this option to disable a client due to key or password @@ -170,12 +178,36 @@ fast hardware. SSL/TLS authentication must be used in this mode. with connection requests using certificates which will ultimately fail to authenticate. + This limit applies after ``--connect-freq-initial`` and + only applies to client that have completed the three-way handshake + or client that use ``--tls-crypt-v2`` without cookie support + (``allow-noncookie`` argument to ``--tls-crypt-v2``). + This is an imperfect solution however, because in a real DoS scenario, legitimate connections might also be refused. For the best protection against DoS attacks in server mode, use ``--proto udp`` and either ``--tls-auth`` or ``--tls-crypt``. +--connect-freq-initial args + (UDP only) Allow a maximum of ``n`` initial connection packet responses + per ``sec`` seconds from the OpenVPN server to clients. + + Valid syntax: + :: + + connect-freq-initial n sec + + OpenVPN starting at 2.6 is very efficient in responding to initial + connection packets. When not limiting the initial responses + an OpenVPN daemon can be abused in reflection attacks. + This option is designed to limit the rate OpenVPN will respond to initial + attacks. + + Connection attempts that complete the initial three-way handshake + will not be counted against the limit. The default is to allow + 100 initial connection per 10s. + --duplicate-cn Allow multiple clients with the same common name to concurrently connect. In the absence of this option, OpenVPN will disconnect a client @@ -286,37 +318,6 @@ fast hardware. SSL/TLS authentication must be used in this mode. ifconfig-ipv6-push ipv6addr/bits ipv6remote ---inetd args - Valid syntaxes: - :: - - inetd - inetd wait - inetd nowait - inetd wait progname - - Use this option when OpenVPN is being run from the inetd or ``xinetd``\(8) - server. - - The :code:`wait` and :code:`nowait` option must match what is specified - in the inetd/xinetd config file. The :code:`nowait` mode can only be used - with ``--proto tcp-server`` The default is :code:`wait`. The - :code:`nowait` mode can be used to instantiate the OpenVPN daemon as a - classic TCP server, where client connection requests are serviced on a - single port number. For additional information on this kind of - configuration, see the OpenVPN FAQ: - https://community.openvpn.net/openvpn/wiki/325-openvpn-as-a--forking-tcp-server-which-can-service-multiple-clients-over-a-single-tcp-port - - This option precludes the use of ``--daemon``, ``--local`` or - ``--remote``. Note that this option causes message and error output to - be handled in the same way as the ``--daemon`` option. The optional - ``progname`` parameter is also handled exactly as in ``--daemon``. - - Also note that in ``wait`` mode, each OpenVPN tunnel requires a separate - TCP/UDP port and a separate inetd or xinetd entry. See the OpenVPN 1.x - HOWTO for an example on using OpenVPN with xinetd: - https://openvpn.net/community-resources/1xhowto/ - --multihome Configure a multi-homed UDP server. This option needs to be used when a server has more than one IP address (e.g. multiple interfaces, or @@ -352,6 +353,12 @@ fast hardware. SSL/TLS authentication must be used in this mode. from the kernel to OpenVPN. Once in OpenVPN, the ``--iroute`` directive routes to the specific client. + However, when using DCO, the ``--iroute`` directive is usually enough + for DCO to fully configure the routing table. The extra ``--route`` + directive is required only if the expected behaviour is to route the + traffic for a specific network to the VPN interface also when the + responsible client is not connected (traffic will then be dropped). + This option must be specified either in a client instance config file using ``--client-config-dir`` or dynamically generated using a ``--client-connect`` script. @@ -393,8 +400,8 @@ fast hardware. SSL/TLS authentication must be used in this mode. the kernel routing table. --opt-verify - Clients that connect with options that are incompatible with those of the - server will be disconnected. + **DEPRECATED** Clients that connect with options that are incompatible with + those of the server will be disconnected. Options that will be compared for compatibility include ``dev-type``, ``link-mtu``, ``tun-mtu``, ``proto``, ``ifconfig``, @@ -443,11 +450,11 @@ fast hardware. SSL/TLS authentication must be used in this mode. This is a partial list of options which can currently be pushed: ``--route``, ``--route-gateway``, ``--route-delay``, - ``--redirect-gateway``, ``--ip-win32``, ``--dhcp-option``, + ``--redirect-gateway``, ``--ip-win32``, ``--dhcp-option``, ``--dns``, ``--inactive``, ``--ping``, ``--ping-exit``, ``--ping-restart``, ``--setenv``, ``--auth-token``, ``--persist-key``, ``--persist-tun``, ``--echo``, ``--comp-lzo``, ``--socket-flags``, ``--sndbuf``, - ``--rcvbuf`` + ``--rcvbuf``, ``--session-timeout`` --push-remove opt Selectively remove all ``--push`` options matching "opt" from the option @@ -744,4 +751,4 @@ fast hardware. SSL/TLS authentication must be used in this mode. the client context, the global value is inherited. In some switch implementations, the *PVID* is also referred to as "Native - VLAN". + VLAN". \ No newline at end of file diff --git a/doc/man-sections/tls-options.rst b/doc/man-sections/tls-options.rst index b7f44739175..d51aff77e66 100644 --- a/doc/man-sections/tls-options.rst +++ b/doc/man-sections/tls-options.rst @@ -200,6 +200,9 @@ certificates and keys: https://github.com/OpenVPN/easy-rsa will still use our expiring key for up to ``--tran-window`` seconds to maintain continuity of transmission of tunnel data. + The ``--hand-window`` parameter also controls the amount of time that + the OpenVPN client repeats the pull request until it times out. + --key file Local peer's private key in .pem format. Use the private key which was generated when you built your peer's certificate (see ``--cert file`` @@ -268,7 +271,8 @@ certificates and keys: https://github.com/OpenVPN/easy-rsa man-in-the-middle attack where an authorized client attempts to connect to another client by impersonating the server. The attack is easily prevented by having clients verify the server certificate using any one - of ``--remote-cert-tls``, ``--verify-x509-name``, or ``--tls-verify``. + of ``--remote-cert-tls``, ``--verify-x509-name``, ``--peer-fingerprint`` + or ``--tls-verify``. --tls-auth args Add an additional layer of HMAC authentication on top of the TLS control @@ -482,6 +486,13 @@ certificates and keys: https://github.com/OpenVPN/easy-rsa 8000 years'. --tls-crypt-v2 keyfile + + Valid syntax:: + + tls-crypt-v2 keyfile + tls-crypt-v2 keyfile force-cookie + tls-crypt-v2 keyfile allow-noncookie + Use client-specific tls-crypt keys. For clients, ``keyfile`` is a client-specific tls-crypt key. Such a key @@ -497,6 +508,13 @@ certificates and keys: https://github.com/OpenVPN/easy-rsa client is using client-specific keys, and automatically select the right mode. + The optional parameters :code:`force-cookie` allows only tls-crypt-v2 + clients that support a cookie based stateless three way handshake that + avoids replay attacks and state exhaustion on the server side (OpenVPN + 2.6 and later). The option :code:`allow-noncookie` explicitly allows + older tls-crypt-v2 clients. The default is (currently) + :code:`allow-noncookie`. + --tls-crypt-v2-verify cmd Run command ``cmd`` to verify the metadata of the client-specific tls-crypt-v2 key of a connecting client. This allows server @@ -547,8 +565,8 @@ certificates and keys: https://github.com/OpenVPN/easy-rsa them. --tls-version-min args - Sets the minimum TLS version we will accept from the peer (default is - "1.0"). + Sets the minimum TLS version we will accept from the peer (default in + 2.6.0 and later is "1.2"). Valid syntax: :: @@ -566,7 +584,7 @@ certificates and keys: https://github.com/OpenVPN/easy-rsa :code:`1.2`. --verify-hash args - Specify SHA1 or SHA256 fingerprint for level-1 cert. + **DEPRECATED** Specify SHA1 or SHA256 fingerprint for level-1 cert. Valid syntax: :: @@ -585,6 +603,39 @@ certificates and keys: https://github.com/OpenVPN/easy-rsa The ``algo`` flag can be either :code:`SHA1` or :code:`SHA256`. If not provided, it defaults to :code:`SHA1`. + This option can also be inlined + :: + + + 00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff + 11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00 + + +If the option is inlined, ``algo`` is always :code:`SHA256`. + +--peer-fingerprint args + Specify a SHA256 fingerprint or list of SHA256 fingerprints to verify + the peer certificate against. The peer certificate must match one of the + fingerprint or certificate verification will fail. The option can also + be inlined + + Valid syntax: + :: + + peer-fingerprint AD:B0:95:D8:09:... + + or inline: + :: + + + 00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff + 11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00 + + + When the ``--peer-fingerprint`` option is used, specifying a CA with ``--ca`` or ``--capath`` is + optional. This allows the he ``--peer-fingerprint`` to be used as alternative to a PKI with + self-signed certificates for small setups. See the examples section for such a setup. + --verify-x509-name args Accept connections only if a host's X.509 name is equal to **name.** The remote host must also pass all other tests of verification. @@ -638,20 +689,23 @@ certificates and keys: https://github.com/OpenVPN/easy-rsa options can be defined to track multiple attributes. --x509-username-field args - Field in the X.509 certificate subject to be used as the username - (default :code:`CN`). + Fields in the X.509 certificate subject to be used as the username + (default :code:`CN`). If multiple fields are specified their values + will be concatenated into the one username using :code:`_` symbol + as a separator. Valid syntax: :: - x509-username-field [ext:]fieldname + x509-username-field [ext:]fieldname [[ext:]fieldname...] - Typically, this option is specified with **fieldname** as + Typically, this option is specified with **fieldname** arguments as either of the following: :: x509-username-field emailAddress x509-username-field ext:subjectAltName + x509-username-field CN serialNumber The first example uses the value of the :code:`emailAddress` attribute in the certificate's Subject field as the username. The second example @@ -659,16 +713,22 @@ certificates and keys: https://github.com/OpenVPN/easy-rsa ``fieldname`` :code:`subjectAltName` be searched for an rfc822Name (email) field to be used as the username. In cases where there are multiple email addresses in :code:`ext:fieldname`, the last occurrence - is chosen. + is chosen. The last example uses the value of the :code:`CN` attribute + in the Subject field, combined with the :code:`_` separator and the + hexadecimal representation of the certificate's :code:`serialNumber`. When this option is used, the ``--verify-x509-name`` option will match against the chosen ``fieldname`` instead of the Common Name. Only the :code:`subjectAltName` and :code:`issuerAltName` X.509 - extensions are supported. + extensions and :code:`serialNumber` X.509 attribute are supported. **Please note:** This option has a feature which will convert an all-lowercase ``fieldname`` to uppercase characters, e.g., :code:`ou` -> :code:`OU`. A mixed-case ``fieldname`` or one having the :code:`ext:` prefix will be left as-is. This automatic upcasing feature is deprecated and will be removed in a future release. + + Non-compliant symbols are being replaced with the :code:`_` symbol, same as + the field separator, so concatenating multiple fields with such or :code:`_` + symbols can potentially lead to username collisions. diff --git a/doc/man-sections/unsupported-options.rst b/doc/man-sections/unsupported-options.rst index 05ba3ca2052..5c4e3a0e047 100644 --- a/doc/man-sections/unsupported-options.rst +++ b/doc/man-sections/unsupported-options.rst @@ -17,6 +17,14 @@ longer supported ``key-method`` weakens the VPN tunnel security. The old ``key-method`` was also only needed when the remote side was older than OpenVPN 2.0. +--management-client-pf + Removed in OpenVPN 2.6. The built-in packet filtering (pf) functionality + has been removed. + +--ncp-disable + Removed in OpenVPN 2.6. This option mainly served a role as debug option + when NCP was first introduced. It should no longer be necessary. + --no-iv Removed in OpenVPN 2.5. This option should not be used as it weakens the VPN tunnel security. This has been a NOOP option since OpenVPN 2.4. @@ -30,3 +38,6 @@ longer supported in recent SSL/TLS libraries. If your certificates does not include *key usage* and *extended key usage* fields, they must be upgraded and the ``--remote-cert-tls`` option should be used instead. + +--prng + Removed in OpenVPN 2.6. We now always use the PRNG of the SSL library. diff --git a/doc/man-sections/vpn-network-options.rst b/doc/man-sections/vpn-network-options.rst index 645fd1efb61..989dc844e7e 100644 --- a/doc/man-sections/vpn-network-options.rst +++ b/doc/man-sections/vpn-network-options.rst @@ -69,15 +69,34 @@ routing. dev tap4 dev ovpn - When the device name starts with :code:`tun` or :code:`tap`, the device - type is extracted automatically. Otherwise the ``--dev-type`` option - needs to be added as well. + What happens if the device name is not :code:`tun` or :code:`tap` is + platform dependent. + + On most platforms, :code:`tunN` (e.g. tun2, tun30) and :code:`tapN` + (e.g. tap3) will create a numbered tun/tap interface with the number + specified - this is useful if multiple OpenVPN instances are active, + and the instance-to-device mapping needs to be known. Some platforms + do not support "numbered tap", so trying ``--dev tap3`` will fail. + + Arbitrary device names (e.g. ``--dev tun-home``) will only work on + FreeBSD (with the DCO kernel driver for ``tun`` devices) and Linux + (for both ``tun`` and ``tap`` devices, DCO and tun/tap driver). + + If such a device name starts with ``tun`` or ``tap`` (e.g. ``tun-home``), + OpenVPN will choose the right device type automatically. Otherwise the + desired device type needs to be specified with ``--dev-type tun`` or + ``--dev-type tap``. + + On Windows, only the names :code:`tun` and :code:`tap` are supported. + Selection among multiple installed drivers or driver instances is done + with ``--dev-node`` and ``--windows-driver``. --dev-node node - Explicitly set the device node rather than using :code:`/dev/net/tun`, - :code:`/dev/tun`, :code:`/dev/tap`, etc. If OpenVPN cannot figure out - whether ``node`` is a TUN or TAP device based on the name, you should - also specify ``--dev-type tun`` or ``--dev-type tap``. + This is a highly system dependent option to influence tun/tap driver + selection. + + On Linux, tun/tap devices are created by accessing :code:`/dev/net/tun`, + and this device name can be changed using ``--dev-node ...``. Under Mac OS X this option can be used to specify the default tun implementation. Using ``--dev-node utun`` forces usage of the native @@ -93,6 +112,11 @@ routing. both the network connections control panel name and the GUID for each TAP-Win32 adapter. + On other platforms, ``--dev-node node`` will influence the naming of the + created tun/tap device, if supported on that platform. If OpenVPN cannot + figure out whether ``node`` is a TUN or TAP device based on the name, + you should also specify ``--dev-type tun`` or ``--dev-type tap``. + --dev-type device-type Which device type are we using? ``device-type`` should be :code:`tun` (OSI Layer 3) or :code:`tap` (OSI Layer 2). Use this option only if @@ -183,6 +207,12 @@ routing. :code:`DISABLE-NBT` Disable Netbios-over-TCP/IP. + :code: `PROXY_HTTP` ``host`` ``port`` + Sets a HTTP proxy that should be used when connected to the VPN. + + This option currently only works on OpenVPN for Android and requires + Android 10 or later. + --ifconfig args Set TUN/TAP adapter parameters. It requires the *IP address* of the local VPN endpoint. For TUN devices in point-to-point mode, the next argument @@ -494,10 +524,23 @@ routing. arguments of ``--ifconfig`` to mean "address netmask", no longer "local remote". ---tun-mtu n - Take the TUN device MTU to be **n** and derive the link MTU from it - (default :code:`1500`). In most cases, you will probably want to leave - this parameter set to its default value. +--tun-mtu args + + Valid syntaxes: + :: + + tun-mtu tun-mtu + tun-mtu tun-mtu occ-mtu + + Take the TUN device MTU to be ``tun-mtu`` and derive the link MTU from it. + In most cases, you will probably want to leave this parameter set to + its default value. + + The default for :code:`tun-mtu` is 1500. + + The OCC MTU can be used to avoid warnings about mismatched MTU from + clients. If :code:`occ-mtu` is not specified, it will to default to the + tun-mtu. The MTU (Maximum Transmission Units) is the maximum datagram size in bytes that can be sent unfragmented over a particular network path. @@ -510,6 +553,16 @@ routing. It's best to use the ``--fragment`` and/or ``--mssfix`` options to deal with MTU sizing issues. + Note: Depending on the platform, the operating system allows to receive + packets larger than ``tun-mtu`` (e.g. Linux and FreeBSD) but other platforms + (like macOS) limit received packets to the same size as the MTU. + +--tun-max-mtu maxmtu + This configures the maximum MTU size that a server can push to ``maxmtu``, + by configuring the internal buffers to allow at least this packet size. + The default for ``maxmtu`` is 1600. Currently, only increasing beyond 1600 + is possible, and attempting to reduce max-mtu below 1600 will be ignored. + --tun-mtu-extra n Assume that the TUN/TAP device might return as many as ``n`` bytes more than the ``--tun-mtu`` size on read. This parameter defaults to 0, which diff --git a/doc/man-sections/windows-options.rst b/doc/man-sections/windows-options.rst index c389fbc4ba6..368f7b19025 100644 --- a/doc/man-sections/windows-options.rst +++ b/doc/man-sections/windows-options.rst @@ -238,7 +238,7 @@ Windows-Specific Options logged when this is found in the configuration file. --windows-driver drv - Specifies which tun driver to use. Values are :code:`tap-windows6` - (default) and :code:`wintun`. This is a Windows-only option. - :code:`wintun`" requires ``--dev tun`` and the OpenVPN process to run + Specifies which tun driver to use. Values are :code:`ovpn-dco` (default), + :code:`tap-windows6` and :code:`wintun`. :code:`ovpn-dco` and :code:`wintun` + require ``--dev tun``. :code:`wintun` also requires OpenVPN process to run elevated, or be invoked using the Interactive Service. diff --git a/doc/management-notes.txt b/doc/management-notes.txt index c2034429864..d014e6597ce 100644 --- a/doc/management-notes.txt +++ b/doc/management-notes.txt @@ -645,11 +645,11 @@ Before issuing a client-pending-auth to a client instead of a client-auth/client-deny, the server should check the IV_SSO environment variable for whether the method is supported. Currently defined methods are crtext for challenge/response using text -(e.g., TOTP), openurl and proxy_url for opening a URL in the client to -continue authentication. A client supporting the first two methods would -set +(e.g., TOTP), openurl (deprecated) and webauth for opening a URL in +the client to continue authentication. A client supporting webauth and +crtext would set - setenv IV_SSO openurl,crtext + setenv IV_SSO webauth,crtext The variable name IV_SSO is historic as AUTH_PENDING was first used to signal single sign on support. To keep compatibility with existing @@ -658,7 +658,7 @@ implementations the name IV_SSO is kept in lieu of a better name. The management interface of the client receives notification of pending auth via ->STATE:datetime,AUTH_PENDING,[timeout number] +>STATE:datetime,AUTH_PENDING,[timeout number],,,,, If {EXTRA} is present the client is informed using INFOMSG notification as @@ -668,33 +668,50 @@ notification as where {EXTRA} is formatted as received from the server. Currently defined formats for {EXTRA} are detailed below. -openurl -======== +webauth and openurl +=================== For a web based extra authentication (like for SSO/SAML) {EXTRA} should be OPEN_URL:url -and client should ask the user to open the URL to continue. +or + + WEB_AUTH:flags:url + +The OPEN_URL method is deprecated as it does not allow to send flags which +proved to be needed to signal certain behaviour to the client. + +The client should ask the user to open the URL to continue. The space in a control message is limited, so this url should be kept short to avoid issues. If a longer url is required a URL that redirects -to the longer URL should be sent instead. +to the longer URL should be sent instead. The total length is limited to 1024 +bytes which includes the INFO_PRE:WEB_AUTH:flags. + +flags is a list of flags which are separated by commas. Currently defined +flags are: + +- proxy (see next pargraph) +- hidden start the webview in hidden mode (see openvpn3 webauth documentation) +- external Do not use an internal webview but use an external browser. Some + authentication providers refuse to work in an internal webview. + A complete documentation how URLs should be handled on the client is available in the openvpn3 repository: https://github.com/OpenVPN/openvpn3/blob/master/doc/webauth.md -proxy_url -======== -This is a variant of openurl that allows opening a url via an +webauth with proxy +================== +This is a variant of webauth that allows opening a url via an HTTP proxy. It could be used to avoid issues with OpenVPN connection's persist-tun that may cause the web server to be unreachable. -The client should announce proxy_url in its IV_SSO and parse the -PROXY_URL message. The format of {EXTRA} in this case is +The client should announce proxy in its IV_SSO and parse the +proxy flag in the WEB_AUTH message. The format of {EXTRA} in this case is - PROXY_URL:::::url + WEB_AUTH:proxy=;;;,flags:url The proxy should be a literal IPv4 address or IPv6 address enclosed in [] to avoid ambiguity in parsing. A literal IP address is preferred as DNS might not be @@ -768,117 +785,68 @@ Immediately kill a client instance by CID. CID -- client ID. See documentation for ">CLIENT:" notification for more info. -COMMAND -- client-pf (OpenVPN 2.1 or higher) ---------------------------------------------- +COMMAND -- remote-entry-count (OpenVPN 2.6+ management version > 3) +------------------------------------------------------------------- -Push a packet filter file to a specific client. +Retrieve available number of remote host/port entries -The OpenVPN server should have been started with the ---management-client-pf directive so that it will require that -VPN tunnel packets sent or received by client instances must -conform to that client's packet filter configuration. +Example: - client-pf {CID} - line_1 - line_2 - ... - line_n + Management interface client sends: + + remote-entry-count + + OpenVPN daemon responds with + + 5 END -CID -- client ID. See documentation for ">CLIENT:" notification for -more info. - -line_1 to line_n -- the packet filter configuration file for this -client. - -Packet filter file grammar: - - [CLIENTS DROP|ACCEPT] - {+|-}common_name1 - {+|-}common_name2 - . . . - [SUBNETS DROP|ACCEPT] - {+|-}subnet1 - {+|-}subnet2 - . . . - [END] - - Subnet: IP-ADDRESS | IP-ADDRESS/NUM_NETWORK_BITS | "unknown" - - CLIENTS refers to the set of clients (by their common-name) which - this instance is allowed ('+') to connect to, or is excluded ('-') - from connecting to. Note that in the case of client-to-client - connections, such communication must be allowed by the packet filter - configuration files of both clients AND the --client-to-client - directive must have been specified in the OpenVPN server config. - - SUBNETS refers to IP addresses or IP address subnets which this - client instance may connect to ('+') or is excluded ('-') from - connecting to, and applies to IPv4 and ARP packets. The special - "unknown" tag refers to packets of unknown type, i.e. a packet that - is not IPv4 or ARP. - - DROP or ACCEPT defines default policy when there is no explicit match - for a common-name or subnet. The [END] tag must exist. - - Notes: - - * The SUBNETS section currently only supports IPv4 addresses and - subnets. - - * A given client or subnet rule applies to both incoming and - outgoing packets. - - * The CLIENTS list is order-invariant. Because the list is stored - as a hash-table, the order of the list does not affect its function. - - * The SUBNETS table is scanned sequentially, and the first item to - match is chosen. Therefore the SUBNETS table is NOT order-invariant. - - * No client-to-client communication is allowed unless the - --client-to-client configuration directive is enabled AND - the CLIENTS list of BOTH clients allows the communication. - -Example packet filter spec, as transmitted to the management interface: - - client-pf 42 - [CLIENTS ACCEPT] - -accounting - -enigma - [SUBNETS DROP] - -10.46.79.9 - +10.0.0.0/8 - [END] - END - -The above example sets the packet filter policy for the client -identified by CID=42. This client may connect to all other clients -except those having a common name of "accounting" or "enigma". -The client may only interact with external IP addresses in the -10.0.0.0/8 subnet, however access to 10.46.79.9 is specifically -excluded. - -Another example packet filter spec, as transmitted to the -management interface: - - client-pf 99 - [CLIENTS DENY] - +public - [SUBNETS ACCEPT] - +10.10.0.1 - -10.0.0.0/8 - -unknown - [END] - END - -The above example sets the packet filter policy for the client -identified by CID=99. This client may not connect to any other -clients except those having a common name of "public". It may -interact with any external IP address except those in the -10.0.0.0/8 netblock. However interaction with one address in -the 10.0.0.0/8 netblock is allowed: 10.10.0.1. Also, the client -may not interact with external IP addresses using an "unknown" -protocol (i.e. one that is not IPv4 or ARP). +COMMAND -- remote-entry-get (OpenVPN 2.6+ management version > 3) +------------------------------------------------------------------ + + remote-entry-get [] + +Retrieve remote entry (host, port, protocol, and status) for index + or indices from to -1. Alternatively + = "all" retrieves all remote entries. The index is 0-based. +If the entry is disabled due to protocol or proxy restrictions +(i.e., ce->flag & CE_DISABLED == 1), the status is returned as "disabled", +otherwise it reads "enabled" without quotes. + +Example 1: + + Management interface client sends: + + remote-entry-get 1 + + OpenVPN daemon responds with + + 1,vpn.example.com,1194,udp,enabled + END + +Example 2: + + Management interface client sends: + + remote-entry-get 1 3 + + OpenVPN daemon responds with + + 1,vpn.example.com,1194,udp,enabled + 2,vpn.example.net,443,tcp-client,disabled + END + +Example 3: + Management interface client sends: + + remote-entry-get all + + OpenVPN daemon with 3 connection entries responds with + + 0,vpn.example.com,1194,udp,enabled + 1,vpn.example.com,443,tcp-client,enabled + 2,vpn.example.net,443,udp,enabled + END COMMAND -- remote (OpenVPN AS 2.1.5/OpenVPN 2.3 or higher) -------------------------------------------- @@ -912,6 +880,13 @@ use this command: remote SKIP +Starting OpenVPN version 2.6 (management version > 3), skip +multiple remotes using: + + remote SKIP n + +where n > 0 is the number of remotes to skip. + COMMAND -- proxy (OpenVPN 2.3 or higher) -------------------------------------------- @@ -1002,10 +977,24 @@ can be indicated in the signing request only if the client version is > 2" The currently defined padding algorithms are: - - RSA_PKCS1_PADDING - PKCS1 padding and RSA signature - - RSA_NO_PADDING - No padding may be added for the signature - - ECDSA - EC signature. + - RSA_PKCS1_PADDING - PKCS1 padding and RSA signature + - RSA_NO_PADDING - No padding may be added for the signature + - ECDSA - EC signature. + - RSA_PKCS1_PSS_PADDING,params - RSA signature with PSS padding + + The params for PSS are specified as 'hashalg=name,saltlen=[max|digest]'. + + The hashalg names are short common names such as SHA256, SHA224, etc. + PSS saltlen="digest" means use the same size as the hash to sign, while + "max" indicates maximum possible saltlen which is + '(nbits-1)/8 - hlen - 2'. Here 'nbits' is the number of bits in the + key modulus and 'hlen' the size in octets of the hash. + (See: RFC 8017 sec 8.1.1 and 9.1.1) + In the case of PKCS1_PADDING, when the hash algorithm is not legacy + MD5-SHA1, the hash is encoded with DigestInfo header before presenting + to the management interface. This is identical to CKM_RSA_PKCS in Cryptoki + as well as what RSA_private_encrypt() in OpenSSL expects. COMMAND -- certificate (OpenVPN 2.4 or higher) ---------------------------------------------- @@ -1373,4 +1362,4 @@ issued: password "Auth" "SCRV1:YmFy:ODY3NTMwOQ==" ("YmFy" is the base 64 encoding of "bar" and "ODY3NTMwOQ==" is the - base 64 encoding of "8675309".) + base 64 encoding of "8675309".) \ No newline at end of file diff --git a/doc/openvpn-examples.5.rst b/doc/openvpn-examples.5.rst index 988b6027be5..0e1b6c4f6aa 100644 --- a/doc/openvpn-examples.5.rst +++ b/doc/openvpn-examples.5.rst @@ -14,4 +14,5 @@ INTRODUCTION This man page gives a few simple examples to create OpenVPN setups and configuration files. +.. include:: man-sections/example-fingerprint.rst .. include:: man-sections/examples.rst diff --git a/doc/tls-crypt-v2.txt b/doc/tls-crypt-v2.txt index f6a6a13958c..7dcd0415fd5 100644 --- a/doc/tls-crypt-v2.txt +++ b/doc/tls-crypt-v2.txt @@ -157,6 +157,50 @@ When setting up the openvpn connection: messages. +HMAC Cookie support +------------------- +To avoid exhaustion attack and keeping state for connections that fail to +complete the three-way handshake, the OpenVPN server will use its own session +id as challenge that the client must repeat in the third packet of the +handshake. This introduces a problem. If the server does not keep the wrapped +client key from the initial packet, the server cannot decode the third packet. +Therefore, tls-crypt-v2 in 2.6 allows resending the wrapped key in the third +packet of the handshake with the P_CONTROL_WKC_V1 message. The modified +handshake is as follows (the rest of the handshake is unmodified): + +1. The client creates the P_CONTROL_HARD_RESET_CLIENT_V3 message as before + but indicates that it supports resending the wrapped key. This is done + by setting the packet id of the replay id to 0x0f000000. The first byte + indicates the early negotiation support and the next byte the flags. + All tls-crypt-v2 implementations that support early negotiation, must + also support resending the wrapped key. The flags byte is therefore + empty. + +2. The server responds with a P_CONTROL_HARD_RESET_V2 message. Instead of having + an empty payload like normally, the payload consists of TLV (type (uint16), + length (uint16), value) packets. TLV was chosen + to allow extensibility in the future. Currently only the following TLV is + defined: + + flags - type 0x01, length 2. + + Bit 1 indicates that the client needs to resend the WKc in the third packet. + +3. Instead of normal P_ACK_V1 or P_CONTROL_V1 packet, the client will send a + P_CONTROL_WKC_V1 packet. The P_CONTROL_WKC_V1 is identical to a normal + P_CONTROL_V1 packet but with the WKc appended. + + Normally the first message of the client is either P_ACK_V1, directly + followed by a P_CONTROL_V1 message that contains the TLS Client Hello or + just a P_CONTROL_V1 message. Instead of a P_ACK_V1 message the client should + send a P_CONTROL_WKC_V1 message with an empty payload. This message must + also include an ACK for the P_CONTROL_HARD_RESET_V2 message. + + When directly sending the TLS Client Hello message in the P_CONTROL_WKC_V1 + message, the client must ensure that the resulting P_CONTROL_WKC_V1 message + with the appended WKc does not extend the control message length. + + Considerations -------------- diff --git a/include/Makefile.am b/include/Makefile.am index 3a4870f20ae..fa722843677 100644 --- a/include/Makefile.am +++ b/include/Makefile.am @@ -5,7 +5,7 @@ # packet encryption, packet authentication, and # packet compression. # -# Copyright (C) 2002-2022 OpenVPN Inc +# Copyright (C) 2002-2023 OpenVPN Inc # Copyright (C) 2006-2012 Alon Bar-Lev # @@ -15,4 +15,4 @@ MAINTAINERCLEANFILES = \ include_HEADERS = \ openvpn-plugin.h \ - openvpn-msg.h + openvpn-msg.h \ No newline at end of file diff --git a/include/openvpn-msg.h b/include/openvpn-msg.h index b16577cc39c..c98b3676915 100644 --- a/include/openvpn-msg.h +++ b/include/openvpn-msg.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2013-2022 Heiko Hund + * Copyright (C) 2013-2023 Heiko Hund * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -135,4 +135,4 @@ typedef struct { int mtu; } set_mtu_message_t; -#endif /* ifndef OPENVPN_MSG_H_ */ +#endif /* ifndef OPENVPN_MSG_H_ */ \ No newline at end of file diff --git a/include/openvpn-plugin.h.in b/include/openvpn-plugin.h.in index 6b7120872d7..ecce8aa1a65 100644 --- a/include/openvpn-plugin.h.in +++ b/include/openvpn-plugin.h.in @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -71,7 +71,6 @@ extern "C" { * New Client Connection: * * FUNC: openvpn_plugin_client_constructor_v1 - * FUNC: openvpn_plugin_func_v1 OPENVPN_PLUGIN_ENABLE_PF * FUNC: openvpn_plugin_func_v1 OPENVPN_PLUGIN_TLS_VERIFY (called once for every cert * in the server chain) * FUNC: openvpn_plugin_func_v1 OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY @@ -84,12 +83,14 @@ extern "C" { * FUNC: openvpn_plugin_func_v1 OPENVPN_PLUGIN_CLIENT_CONNECT_V2 * FUNC: openvpn_plugin_func_v1 OPENVPN_PLUGIN_LEARN_ADDRESS * + * The OPENVPN_PLUGIN_CLIENT_CRRESPONSE function is called when the client sends + * the CR_RESPONSE message, this is *typically* after OPENVPN_PLUGIN_TLS_FINAL + * but may also occur much later. + * * [Client session ensues] * * For each "TLS soft reset", according to reneg-sec option (or similar): * - * FUNC: openvpn_plugin_func_v1 OPENVPN_PLUGIN_ENABLE_PF - * * FUNC: openvpn_plugin_func_v1 OPENVPN_PLUGIN_TLS_VERIFY (called once for every cert * in the server chain) * FUNC: openvpn_plugin_func_v1 OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY @@ -127,11 +128,12 @@ extern "C" { #define OPENVPN_PLUGIN_LEARN_ADDRESS 8 #define OPENVPN_PLUGIN_CLIENT_CONNECT_V2 9 #define OPENVPN_PLUGIN_TLS_FINAL 10 -#define OPENVPN_PLUGIN_ENABLE_PF 11 +/*#define OPENVPN_PLUGIN_ENABLE_PF 11 *REMOVED FEATURE* */ #define OPENVPN_PLUGIN_ROUTE_PREDOWN 12 #define OPENVPN_PLUGIN_CLIENT_CONNECT_DEFER 13 #define OPENVPN_PLUGIN_CLIENT_CONNECT_DEFER_V2 14 -#define OPENVPN_PLUGIN_N 15 +#define OPENVPN_PLUGIN_CLIENT_CRRESPONSE 15 +#define OPENVPN_PLUGIN_N 16 /* * Build a mask out of a set of plug-in types. @@ -567,6 +569,14 @@ OPENVPN_PLUGIN_DEF openvpn_plugin_handle_t OPENVPN_PLUGIN_FUNC(openvpn_plugin_op * auth_control_file/client_connect_deferred_file * in the environmental variable list (envp). * + * Additionally the auth_pending_file can be written, which causes the openvpn + * server to send a pending auth request to the client. See doc/management.txt + * for more details on this authentication mechanism. The format of the + * auth_pending_file is + * line 1: timeout in seconds + * line 2: Pending auth method the client needs to support (e.g. openurl) + * line 3: EXTRA (e.g. WEBAUTH::http://www.example.com) + * * In addition the OPENVPN_PLUGIN_CLIENT_CONNECT_DEFER and * OPENVPN_PLUGIN_CLIENT_CONNECT_DEFER_V2 are called when OpenVPN tries to * get the deferred result. For a V2 call implementing this function is @@ -579,49 +589,8 @@ OPENVPN_PLUGIN_DEF openvpn_plugin_handle_t OPENVPN_PLUGIN_FUNC(openvpn_plugin_op * * OpenVPN will delete the auth_control_file after it goes out of scope. * - * If an OPENVPN_PLUGIN_ENABLE_PF handler is defined and returns success - * for a particular client instance, packet filtering will be enabled for that - * instance. OpenVPN will then attempt to read the packet filter configuration - * from the temporary file named by the environmental variable pf_file. This - * file may be generated asynchronously and may be dynamically updated during the - * client session, however the client will be blocked from sending or receiving - * VPN tunnel packets until the packet filter file has been generated. OpenVPN - * will periodically test the packet filter file over the life of the client - * instance and reload when modified. OpenVPN will delete the packet filter file - * when the client instance goes out of scope. - * - * Packet filter file grammar: - * - * [CLIENTS DROP|ACCEPT] - * {+|-}common_name1 - * {+|-}common_name2 - * . . . - * [SUBNETS DROP|ACCEPT] - * {+|-}subnet1 - * {+|-}subnet2 - * . . . - * [END] - * - * Subnet: IP-ADDRESS | IP-ADDRESS/NUM_NETWORK_BITS - * - * CLIENTS refers to the set of clients (by their common-name) which - * this instance is allowed ('+') to connect to, or is excluded ('-') - * from connecting to. Note that in the case of client-to-client - * connections, such communication must be allowed by the packet filter - * configuration files of both clients. - * - * SUBNETS refers to IP addresses or IP address subnets which this - * instance may connect to ('+') or is excluded ('-') from connecting - * to. - * - * DROP or ACCEPT defines default policy when there is no explicit match - * for a common-name or subnet. The [END] tag must exist. A special - * purpose tag called [KILL] will immediately kill the client instance. - * A given client or subnet rule applies to both incoming and outgoing - * packets. - * - * See plugin/defer/simple.c for an example on using asynchronous - * authentication and client-specific packet filtering. + * See sample/sample-plugins/defer/multi-auth.c for an example on using + * asynchronous authentication. */ OPENVPN_PLUGIN_DEF int OPENVPN_PLUGIN_FUNC(openvpn_plugin_func_v2) (openvpn_plugin_handle_t handle, @@ -695,49 +664,8 @@ OPENVPN_PLUGIN_DEF int OPENVPN_PLUGIN_FUNC(openvpn_plugin_open_v3) * * OpenVPN will delete the auth_control_file after it goes out of scope. * - * If an OPENVPN_PLUGIN_ENABLE_PF handler is defined and returns success - * for a particular client instance, packet filtering will be enabled for that - * instance. OpenVPN will then attempt to read the packet filter configuration - * from the temporary file named by the environmental variable pf_file. This - * file may be generated asynchronously and may be dynamically updated during the - * client session, however the client will be blocked from sending or receiving - * VPN tunnel packets until the packet filter file has been generated. OpenVPN - * will periodically test the packet filter file over the life of the client - * instance and reload when modified. OpenVPN will delete the packet filter file - * when the client instance goes out of scope. - * - * Packet filter file grammar: - * - * [CLIENTS DROP|ACCEPT] - * {+|-}common_name1 - * {+|-}common_name2 - * . . . - * [SUBNETS DROP|ACCEPT] - * {+|-}subnet1 - * {+|-}subnet2 - * . . . - * [END] - * - * Subnet: IP-ADDRESS | IP-ADDRESS/NUM_NETWORK_BITS - * - * CLIENTS refers to the set of clients (by their common-name) which - * this instance is allowed ('+') to connect to, or is excluded ('-') - * from connecting to. Note that in the case of client-to-client - * connections, such communication must be allowed by the packet filter - * configuration files of both clients. - * - * SUBNETS refers to IP addresses or IP address subnets which this - * instance may connect to ('+') or is excluded ('-') from connecting - * to. - * - * DROP or ACCEPT defines default policy when there is no explicit match - * for a common-name or subnet. The [END] tag must exist. A special - * purpose tag called [KILL] will immediately kill the client instance. - * A given client or subnet rule applies to both incoming and outgoing - * packets. - * * See sample/sample-plugins/defer/simple.c for an example on using - * asynchronous authentication and client-specific packet filtering. + * asynchronous authentication. */ OPENVPN_PLUGIN_DEF int OPENVPN_PLUGIN_FUNC(openvpn_plugin_func_v3) (const int version, @@ -879,4 +807,4 @@ OPENVPN_PLUGIN_DEF int OPENVPN_PLUGIN_FUNC(openvpn_plugin_func_v1) } #endif -#endif /* OPENVPN_PLUGIN_H_ */ +#endif /* OPENVPN_PLUGIN_H_ */ \ No newline at end of file diff --git a/m4/ax_emptyarray.m4 b/m4/ax_emptyarray.m4 deleted file mode 100644 index c6781c179c2..00000000000 --- a/m4/ax_emptyarray.m4 +++ /dev/null @@ -1,40 +0,0 @@ -dnl @synopsis AX_EMPTY_ARRAY -dnl -dnl Define EMPTY_ARRAY_SIZE to be either "0" -dnl or "" depending on which syntax the compiler -dnl prefers for empty arrays in structs. -dnl -dnl @version -dnl @author James Yonan -AC_DEFUN([AX_EMPTY_ARRAY], [ - AS_VAR_PUSHDEF([VAR],[ax_cv_c_empty_array])dnl - AC_CACHE_CHECK( - [for C compiler empty array size], - [VAR], - [AC_COMPILE_IFELSE( - [AC_LANG_PROGRAM( - , - [[ -struct { int foo; int bar[0]; } mystruct; - ]] - )], - [VAR=0], - [AC_COMPILE_IFELSE( - [AC_LANG_PROGRAM( - , - [[ -struct { int foo; int bar[]; } mystruct; - ]] - )], - [VAR=], - [AC_MSG_ERROR([C compiler is unable to creaty empty arrays])] - )] - )] - )dnl - AC_DEFINE_UNQUOTED( - [EMPTY_ARRAY_SIZE], - [$VAR], - [Dimension to use for empty array declaration] - )dnl - AS_VAR_POPDEF([VAR])dnl -]) diff --git a/m4/ax_varargs.m4 b/m4/ax_varargs.m4 deleted file mode 100644 index c295d21f4e2..00000000000 --- a/m4/ax_varargs.m4 +++ /dev/null @@ -1,77 +0,0 @@ -dnl @synopsis AX_CPP_VARARG_MACRO_GCC -dnl -dnl Test if the preprocessor understands GNU GCC-style vararg macros. -dnl If it does, defines HAVE_CPP_VARARG_MACRO_GCC to 1. -dnl -dnl @version -dnl @author James Yonan , Matthias Andree -AC_DEFUN([AX_CPP_VARARG_MACRO_GCC], [dnl - AS_VAR_PUSHDEF([VAR], [ax_cv_cpp_vararg_macro_gcc])dnl - AC_CACHE_CHECK( - [for GNU GCC vararg macro support], - [VAR], - [AC_COMPILE_IFELSE( - [AC_LANG_PROGRAM( - [[ -#define macro(a, b...) func(a, b) -int func(int a, int b, int c); - ]], - [[ -int i = macro(1, 2, 3); - ]] - )], - [VAR=yes], - [VAR=no] - )] - )dnl - - AS_VAR_IF( - [VAR], - [yes], - [AC_DEFINE( - [HAVE_CPP_VARARG_MACRO_GCC], - [1], - [Define to 1 if your compiler supports GNU GCC-style variadic macros] - )] - )dnl - AS_VAR_POPDEF([VAR])dnl -]) - -dnl @synopsis AX_CPP_VARARG_MACRO_ISO -dnl -dnl Test if the preprocessor understands ISO C 1999 vararg macros. -dnl If it does, defines HAVE_CPP_VARARG_MACRO_ISO to 1. -dnl -dnl @version -dnl @author James Yonan , Matthias Andree -AC_DEFUN([AX_CPP_VARARG_MACRO_ISO], [dnl - AS_VAR_PUSHDEF([VAR],[ax_cv_cpp_vararg_macro_iso])dnl - AC_CACHE_CHECK( - [for ISO C 1999 vararg macro support], - [VAR], - [AC_COMPILE_IFELSE( - [AC_LANG_PROGRAM( - [[ -#define macro(a, ...) func(a, __VA_ARGS__) -int func(int a, int b, int c); - ]], - [[ -int i = macro(1, 2, 3); - ]] - )], - [VAR=yes], - [VAR=no] - )] - )dnl - - AS_VAR_IF( - [VAR], - [yes], - [AC_DEFINE( - [HAVE_CPP_VARARG_MACRO_ISO], - [1], - [Define to 1 if your compiler supports ISO C99 variadic macros] - )] - )dnl - AS_VAR_POPDEF([VAR])dnl -]) diff --git a/sample/Makefile.am b/sample/Makefile.am index 1f466586c21..ef2d0a81ab3 100644 --- a/sample/Makefile.am +++ b/sample/Makefile.am @@ -5,7 +5,7 @@ # packet encryption, packet authentication, and # packet compression. # -# Copyright (C) 2002-2022 OpenVPN Inc +# Copyright (C) 2002-2023 OpenVPN Inc # Copyright (C) 2006-2012 Alon Bar-Lev # @@ -34,4 +34,4 @@ client.ovpn: sample-config-files/client.conf server.ovpn: sample-config-files/server.conf -rm -f server.ovpn cp "$(srcdir)/sample-config-files/server.conf" server.ovpn -endif +endif \ No newline at end of file diff --git a/sample/sample-config-files/client.conf b/sample/sample-config-files/client.conf index 47ca4099213..15cb1b37512 100644 --- a/sample/sample-config-files/client.conf +++ b/sample/sample-config-files/client.conf @@ -58,8 +58,8 @@ resolv-retry infinite nobind # Downgrade privileges after initialization (non-Windows only) -;user nobody -;group nobody +;user openvpn +;group openvpn # Try to preserve some state across restarts. persist-key diff --git a/sample/sample-config-files/server.conf b/sample/sample-config-files/server.conf index e70206395aa..d9345b648d1 100644 --- a/sample/sample-config-files/server.conf +++ b/sample/sample-config-files/server.conf @@ -269,10 +269,10 @@ cipher AES-256-CBC # It's a good idea to reduce the OpenVPN # daemon's privileges after initialization. # -# You can uncomment this out on -# non-Windows systems. -;user nobody -;group nobody +# You can uncomment this on non-Windows +# systems after creating a dedicated user. +;user openvpn +;group openvpn # The persist options will try to avoid # accessing certain resources on restart diff --git a/sample/sample-config-files/tls-home.conf b/sample/sample-config-files/tls-home.conf index 3a9297cc83b..ff19d50d46f 100644 --- a/sample/sample-config-files/tls-home.conf +++ b/sample/sample-config-files/tls-home.conf @@ -47,11 +47,11 @@ cipher AES-256-GCM # for local and remote. ; port 1194 -# Downgrade UID and GID to -# "nobody" after initialization +# Downgrade UID and GID to an +# unpriviledged user after initialization # for extra security. -; user nobody -; group nobody +; user openvpn +; group openvpn # If you built OpenVPN with # LZO compression, uncomment diff --git a/sample/sample-config-files/tls-office.conf b/sample/sample-config-files/tls-office.conf index 81052211710..152e58a0ddf 100644 --- a/sample/sample-config-files/tls-office.conf +++ b/sample/sample-config-files/tls-office.conf @@ -50,11 +50,11 @@ cipher AES-256-GCM # for local and remote. ; port 1194 -# Downgrade UID and GID to -# "nobody" after initialization +# Downgrade UID and GID to an +# unpriviledged user after initialization # for extra security. -; user nobody -; group nobody +; user openvpn +; group openvpn # If you built OpenVPN with # LZO compression, uncomment diff --git a/sample/sample-config-files/xinetd-client-config b/sample/sample-config-files/xinetd-client-config deleted file mode 100644 index 03c5c1faa98..00000000000 --- a/sample/sample-config-files/xinetd-client-config +++ /dev/null @@ -1,11 +0,0 @@ -# This OpenVPN config file -# is the client side counterpart -# of xinetd-server-config - -dev tun -ifconfig 10.4.0.1 10.4.0.2 -remote my-server -port 1194 -user nobody -secret /root/openvpn/key -inactive 600 diff --git a/sample/sample-config-files/xinetd-server-config b/sample/sample-config-files/xinetd-server-config deleted file mode 100644 index 803a6f8ff33..00000000000 --- a/sample/sample-config-files/xinetd-server-config +++ /dev/null @@ -1,25 +0,0 @@ -# An xinetd configuration file for OpenVPN. -# -# This file should be renamed to openvpn or something suitably -# descriptive and copied to the /etc/xinetd.d directory. -# xinetd can then be made aware of this file by restarting -# it or sending it a SIGHUP signal. -# -# For each potential incoming client, create a separate version -# of this configuration file on a unique port number. Also note -# that the key file and ifconfig endpoints should be unique for -# each client. This configuration assumes that the OpenVPN -# executable and key live in /root/openvpn. Change this to fit -# your environment. - -service openvpn_1 -{ - type = UNLISTED - port = 1194 - socket_type = dgram - protocol = udp - wait = yes - user = root - server = /root/openvpn/openvpn - server_args = --inetd --dev tun --ifconfig 10.4.0.2 10.4.0.1 --secret /root/openvpn/key --inactive 600 --user nobody -} diff --git a/sample/sample-keys/gen-sample-keys.sh b/sample/sample-keys/gen-sample-keys.sh index b9e73703e6b..bff12f3b9cf 100755 --- a/sample/sample-keys/gen-sample-keys.sh +++ b/sample/sample-keys/gen-sample-keys.sh @@ -3,7 +3,7 @@ # Run this script to set up a test CA, and test key-certificate pair for a # server, and various clients. # -# Copyright (C) 2014-2022 Steffan Karger +# Copyright (C) 2014-2023 Steffan Karger set -eu command -v openssl >/dev/null 2>&1 || { echo >&2 "Unable to find openssl. Please make sure openssl is installed and in your path."; exit 1; } @@ -100,4 +100,4 @@ openssl dhparam -out dh2048.pem 2048 cp sample-ca/*.key . cp sample-ca/*.crt . cp sample-ca/*.p12 . -cp sample-ca/*.crl . +cp sample-ca/*.crl . \ No newline at end of file diff --git a/sample/sample-plugins/Makefile.am b/sample/sample-plugins/Makefile.am index 06d701df108..eca3bacfa37 100644 --- a/sample/sample-plugins/Makefile.am +++ b/sample/sample-plugins/Makefile.am @@ -5,7 +5,7 @@ # packet encryption, packet authentication, and # packet compression. # -# Copyright (C) 2002-2022 OpenVPN Inc +# Copyright (C) 2002-2023 OpenVPN Inc # MAINTAINERCLEANFILES = \ @@ -31,4 +31,4 @@ include Makefile.plugins dist-hook : - make -f Makefile.plugins clean + make -f Makefile.plugins clean \ No newline at end of file diff --git a/sample/sample-plugins/Makefile.plugins b/sample/sample-plugins/Makefile.plugins index 8bfbad09400..b46e4f85c16 100644 --- a/sample/sample-plugins/Makefile.plugins +++ b/sample/sample-plugins/Makefile.plugins @@ -1,13 +1,12 @@ # SPDX-License-Identifier: GPL-2.0-only # -# Copyright (C) 2020-2022 OpenVPN Inc +# Copyright (C) 2020-2023 OpenVPN Inc # # # Plug-ins to build - listed entries should not carry any extensions # PLUGINS = \ - defer/simple \ defer/multi-auth \ keying-material-exporter-demo/keyingmaterialexporter \ log/log log/log_v3 \ @@ -35,4 +34,4 @@ all : $(foreach var, $(PLUGINS), $(var).so) # Clean up all build object and shared object files clean : rm -f $(foreach var, $(PLUGINS), $(var).o) \ - $(foreach var, $(PLUGINS), $(var).so) + $(foreach var, $(PLUGINS), $(var).so) \ No newline at end of file diff --git a/sample/sample-plugins/README b/sample/sample-plugins/README index cf1b355e245..f1c631fb3d5 100644 --- a/sample/sample-plugins/README +++ b/sample/sample-plugins/README @@ -5,8 +5,10 @@ Examples provided: * authentication and logging simple/simple.c -- using the --auth-user-pass-verify callback, verify that the username/password is "foo"/"bar". -defer/simple.c -- using the --auth-user-pass-verify callback, - test deferred authentication. +defer/multi-auth.c + -- using the --auth-user-pass-verify callback, + test deferred authentication. Can be used to test multiple + authentication plugins in the same server config. log/log.c -- Extended variant of simple/simple.c which adds more logging of what is happening inside the plug-in log/log_v3.c -- A variant of log/log.c, which makes use of the @@ -40,4 +42,4 @@ To build on Windows platform (MinGW): To use in OpenVPN, add to config file: plugin simple.so (Linux/BSD/etc.) - plugin simple.dll + plugin simple.dll \ No newline at end of file diff --git a/sample/sample-plugins/client-connect/sample-client-connect.c b/sample/sample-plugins/client-connect/sample-client-connect.c index f31032d42a2..0fc08c6e576 100644 --- a/sample/sample-plugins/client-connect/sample-client-connect.c +++ b/sample/sample-plugins/client-connect/sample-client-connect.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -173,10 +173,7 @@ openvpn_plugin_open_v3(const int v3structver, return OPENVPN_PLUGIN_FUNC_SUCCESS; error: - if (context) - { - free(context); - } + free(context); return OPENVPN_PLUGIN_FUNC_ERROR; } @@ -213,7 +210,7 @@ write_cc_options_file(const char *name, const char **envp) return OPENVPN_PLUGIN_FUNC_SUCCESS; } - FILE *fp = fopen(name,"w"); + FILE *fp = fopen(name, "w"); if (!fp) { plugin_log(PLOG_ERR, MODULE, "fopen('%s') failed", name); @@ -609,4 +606,4 @@ openvpn_plugin_close_v1(openvpn_plugin_handle_t handle) struct plugin_context *context = (struct plugin_context *) handle; printf("FUNC: openvpn_plugin_close_v1\n"); free(context); -} +} \ No newline at end of file diff --git a/sample/sample-plugins/defer/multi-auth.c b/sample/sample-plugins/defer/multi-auth.c index 20c9dac5b69..74bb2fdfc71 100644 --- a/sample/sample-plugins/defer/multi-auth.c +++ b/sample/sample-plugins/defer/multi-auth.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2021 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -72,7 +72,8 @@ struct plugin_context { /* local wrapping of the log function, to add more details */ static plugin_vlog_t _plugin_vlog_func = NULL; -static void plog(const struct plugin_context *ctx, int flags, char *fmt, ...) +static void +plog(const struct plugin_context *ctx, int flags, char *fmt, ...) { char logid[129]; @@ -243,11 +244,11 @@ do_auth_user_pass(struct plugin_context *context, const char *username, const char *password) { plog(context, PLOG_NOTE, - "expect_user=%s, received_user=%s, expect_passw=%s, received_passw=%s", - np(context->test_valid_user), - np(username), - np(context->test_valid_pass), - np(password)); + "expect_user=%s, received_user=%s, expect_passw=%s, received_passw=%s", + np(context->test_valid_user), + np(username), + np(context->test_valid_pass), + np(password)); if (context->test_valid_user && context->test_valid_pass) { @@ -255,13 +256,13 @@ do_auth_user_pass(struct plugin_context *context, || (strcmp(context->test_valid_pass, password) != 0)) { plog(context, PLOG_ERR, - "User/Password auth result: FAIL"); + "User/Password auth result: FAIL"); return false; } else { plog(context, PLOG_NOTE, - "User/Password auth result: PASS"); + "User/Password auth result: PASS"); return true; } } @@ -282,7 +283,7 @@ auth_user_pass_verify(struct plugin_context *context, { plog(context, PLOG_NOTE, "Direct authentication"); return do_auth_user_pass(context, username, password) ? - OPENVPN_PLUGIN_FUNC_SUCCESS : OPENVPN_PLUGIN_FUNC_ERROR; + OPENVPN_PLUGIN_FUNC_SUCCESS : OPENVPN_PLUGIN_FUNC_ERROR; } /* get auth_control_file filename from envp string array*/ @@ -334,7 +335,7 @@ auth_user_pass_verify(struct plugin_context *context, /* do mighty complicated work that will really take time here... */ plog(context, PLOG_NOTE, "in async/deferred handler, usleep(%d)", - context->test_deferred_auth*1000); + context->test_deferred_auth*1000); usleep(context->test_deferred_auth*1000); /* now signal success state to openvpn */ @@ -342,7 +343,7 @@ auth_user_pass_verify(struct plugin_context *context, if (fd < 0) { plog(context, PLOG_ERR|PLOG_ERRNO, - "open('%s') failed", auth_control_file); + "open('%s') failed", auth_control_file); exit(1); } @@ -410,4 +411,4 @@ openvpn_plugin_close_v1(openvpn_plugin_handle_t handle) struct plugin_context *context = (struct plugin_context *) handle; plog(context, PLOG_NOTE, "FUNC: openvpn_plugin_close_v1"); free(context); -} +} \ No newline at end of file diff --git a/sample/sample-plugins/defer/simple.def b/sample/sample-plugins/defer/simple.def deleted file mode 100755 index a87507d1fdc..00000000000 --- a/sample/sample-plugins/defer/simple.def +++ /dev/null @@ -1,6 +0,0 @@ -LIBRARY OpenVPN_PLUGIN_SAMPLE -DESCRIPTION "Sample OpenVPN plug-in module." -EXPORTS - openvpn_plugin_open_v1 @1 - openvpn_plugin_func_v1 @2 - openvpn_plugin_close_v1 @3 diff --git a/sample/sample-plugins/keying-material-exporter-demo/keyingmaterialexporter.c b/sample/sample-plugins/keying-material-exporter-demo/keyingmaterialexporter.c index e28204187cf..c0a0d9eec86 100644 --- a/sample/sample-plugins/keying-material-exporter-demo/keyingmaterialexporter.c +++ b/sample/sample-plugins/keying-material-exporter-demo/keyingmaterialexporter.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -55,7 +55,7 @@ struct plugin { struct session { char user[48]; - char key [48]; + char key[48]; }; /* @@ -105,7 +105,7 @@ openvpn_plugin_open_v3(const int version, plugin->mask = OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_FINAL); plugin->mask |= OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_TLS_VERIFY); - ovpn_note("vpn endpoint type=%s",plugin->type == CLIENT ? "client" : "server"); + ovpn_note("vpn endpoint type=%s", plugin->type == CLIENT ? "client" : "server"); rv->type_mask = plugin->mask; rv->handle = (void *)plugin; @@ -296,4 +296,4 @@ openvpn_plugin_close_v1(openvpn_plugin_handle_t handle) { struct plugin *plugin = (struct plugin *)handle; free(plugin); -} +} \ No newline at end of file diff --git a/sample/sample-plugins/log/log.c b/sample/sample-plugins/log/log.c index 2adbb2dfa06..df3e802b142 100644 --- a/sample/sample-plugins/log/log.c +++ b/sample/sample-plugins/log/log.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -207,4 +207,4 @@ openvpn_plugin_close_v1(openvpn_plugin_handle_t handle) { struct plugin_context *context = (struct plugin_context *) handle; free(context); -} +} \ No newline at end of file diff --git a/sample/sample-plugins/log/log_v3.c b/sample/sample-plugins/log/log_v3.c index 5f569c928c4..27801f6ded9 100644 --- a/sample/sample-plugins/log/log_v3.c +++ b/sample/sample-plugins/log/log_v3.c @@ -5,8 +5,8 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc - * Copyright (C) 2010-2022 David Sommerseth + * Copyright (C) 2002-2023 OpenVPN Inc + * Copyright (C) 2010-2023 David Sommerseth * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -293,4 +293,4 @@ openvpn_plugin_close_v1(openvpn_plugin_handle_t handle) { struct plugin_context *context = (struct plugin_context *) handle; free(context); -} +} \ No newline at end of file diff --git a/sample/sample-plugins/simple/base64.c b/sample/sample-plugins/simple/base64.c index e94ee9635b6..ad991795f30 100644 --- a/sample/sample-plugins/simple/base64.c +++ b/sample/sample-plugins/simple/base64.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2017-2022 David Sommerseth + * Copyright (C) 2017-2023 David Sommerseth * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -200,4 +200,4 @@ openvpn_plugin_close_v1(openvpn_plugin_handle_t handle) { struct plugin_context *context = (struct plugin_context *) handle; free(context); -} +} \ No newline at end of file diff --git a/sample/sample-plugins/simple/simple.c b/sample/sample-plugins/simple/simple.c index 57c3a719869..91e71dcca83 100644 --- a/sample/sample-plugins/simple/simple.c +++ b/sample/sample-plugins/simple/simple.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -127,4 +127,4 @@ openvpn_plugin_close_v1(openvpn_plugin_handle_t handle) { struct plugin_context *context = (struct plugin_context *) handle; free(context); -} +} \ No newline at end of file diff --git a/sample/sample-scripts/totpauth.py b/sample/sample-scripts/totpauth.py new file mode 100755 index 00000000000..41f88c2e1d6 --- /dev/null +++ b/sample/sample-scripts/totpauth.py @@ -0,0 +1,111 @@ +#! /usr/bin/python3 +# Copyright (c) 2021 OpenVPN Inc +# Copyright (c) 2021 Arne Schwabe +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import sys +import os +from base64 import standard_b64decode + +import pyotp + +# Example script demonstrating how to use the auth-pending API in +# OpenVPN. This script is provided under MIT license to allow easy +# modification for other purposes. +# +# This needs support of crtext support on the client (e.g. OpenVPN for Android) +# See also the management-notes.txt file for more information about the auth pending +# protocol +# +# To use this script add the following lines in the openvpn config + +# client-crresponse /path/to/totpauth.py +# auth-user-pass-verify /path/to/totpauth.py via-file +# auth-user-pass-optional +# auth-gen-token + +# Note that this script does NOT verify username/password +# It is only meant for querying additional 2FA when certificates are +# used to authenticate + + +# For this demo script we hardcode the TOTP secrets in a simple dictionary. +secrets = {"Test-Client": "OS6JDNRK2BNUPQVX", + "Client-2": "IXWEMP7SK2QWSHTG"} + + +def main(): + # Get common name and script type from environment + script_type = os.environ['script_type'] + cn = os.environ['common_name'] + + if script_type == 'user-pass-verify': + # signal text based challenge response + if cn in secrets: + extra = "CR_TEXT:E,R:Please enter your TOTP code!" + write_auth_pending(300, 'crtext', extra) + + # Signal authentication being deferred + sys.exit(2) + else: + # For unknown CN we report failure. Change to 0 + # to allow CNs without secret to auth without 2FA + sys.exit(1) + + elif script_type == 'client-crresponse': + response = None + + # Read the crresponse from the argument file + # and convert it into text. A failure because of bad user + # input (e.g. invalid base64) will make the script throw + # an error and make OpenVPN return AUTH_FAILED + with open(sys.argv[1], 'r') as crinput: + response = crinput.read() + response = standard_b64decode(response) + response = response.decode().strip() + + if cn not in secrets: + write_auth_control(1) + return + + totp = pyotp.TOTP(secrets[cn]) + + # Check if the code is valid (and also allow code +/-1) + if totp.verify(response, valid_window=1): + write_auth_control(1) + else: + write_auth_control(0) + else: + print(f"Unknown script type {script_type}") + sys.exit(1) + + +def write_auth_control(status): + with open(os.environ['auth_control_file'], 'w') as auth_control: + auth_control.write("%d" % status) + + +def write_auth_pending(timeout, method, extra): + with open(os.environ['auth_pending_file'], 'w') as auth_pending: + auth_pending.write("%d\n%s\n%s" % (timeout, method, extra)) + + +if __name__ == '__main__': + main() diff --git a/src/Makefile.am b/src/Makefile.am index 40bcda2c22a..9fdbe21cb89 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -5,11 +5,11 @@ # packet encryption, packet authentication, and # packet compression. # -# Copyright (C) 2002-2022 OpenVPN Inc +# Copyright (C) 2002-2023 OpenVPN Inc # Copyright (C) 2006-2012 Alon Bar-Lev # MAINTAINERCLEANFILES = \ $(srcdir)/Makefile.in -SUBDIRS = compat openvpn openvpnmsica openvpnserv plugins tapctl +SUBDIRS = compat openvpn openvpnmsica openvpnserv plugins tapctl \ No newline at end of file diff --git a/src/compat/Makefile.am b/src/compat/Makefile.am index 522797e721a..aa28d913203 100644 --- a/src/compat/Makefile.am +++ b/src/compat/Makefile.am @@ -5,7 +5,7 @@ # packet encryption, packet authentication, and # packet compression. # -# Copyright (C) 2002-2022 OpenVPN Inc +# Copyright (C) 2002-2023 OpenVPN Inc # Copyright (C) 2006-2012 Alon Bar-Lev # @@ -14,7 +14,6 @@ MAINTAINERCLEANFILES = \ EXTRA_DIST = \ compat.vcxproj \ - compat.vcxproj.filters \ PropertySheet.props \ Debug.props \ Release.props @@ -27,8 +26,5 @@ libcompat_la_SOURCES = \ compat-basename.c \ compat-gettimeofday.c \ compat-daemon.c \ - compat-inet_ntop.c \ - compat-inet_pton.c \ - compat-lz4.c compat-lz4.h \ compat-strsep.c \ - compat-versionhelpers.h + compat-versionhelpers.h \ No newline at end of file diff --git a/src/compat/compat-daemon.c b/src/compat/compat-daemon.c index 4ef28faf080..460b9e99a2f 100644 --- a/src/compat/compat-daemon.c +++ b/src/compat/compat-daemon.c @@ -33,9 +33,7 @@ #include #endif -#ifdef HAVE_STDLIB_H #include -#endif #ifdef HAVE_SYS_TYPES_H #include @@ -49,9 +47,7 @@ #include #endif -#ifdef HAVE_ERRNO_H #include -#endif int daemon(int nochdir, int noclose) @@ -106,4 +102,3 @@ daemon(int nochdir, int noclose) } #endif /* ifndef HAVE_DAEMON */ - diff --git a/src/compat/compat-gettimeofday.c b/src/compat/compat-gettimeofday.c index 30ed162efd0..e7a33c1d939 100644 --- a/src/compat/compat-gettimeofday.c +++ b/src/compat/compat-gettimeofday.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -93,7 +93,7 @@ gettimeofday(struct timeval *tv, void *tz) { /* We try to dampen out backtracks of less than backtrack_hold_seconds. * Larger backtracks will be passed through and dealt with by the - * TIME_BACKTRACK_PROTECTION code (if enabled) */ + * TIME_BACKTRACK_PROTECTION code */ if (sec > last_sec - backtrack_hold_seconds) { sec = last_sec; @@ -102,7 +102,8 @@ gettimeofday(struct timeval *tv, void *tz) bt = 1; } - tv->tv_sec = (long)last_sec = (long)sec; + last_sec = sec; + tv->tv_sec = (long)sec; tv->tv_usec = (last_msec = msec) * 1000; if (bt && !bt_last) @@ -116,9 +117,7 @@ gettimeofday(struct timeval *tv, void *tz) #else /* ifdef _WIN32 */ -#ifdef HAVE_TIME_H #include -#endif int gettimeofday(struct timeval *tv, void *tz) @@ -131,4 +130,4 @@ gettimeofday(struct timeval *tv, void *tz) #endif /* _WIN32 */ -#endif /* HAVE_GETTIMEOFDAY */ +#endif /* HAVE_GETTIMEOFDAY */ \ No newline at end of file diff --git a/src/compat/compat-inet_ntop.c b/src/compat/compat-inet_ntop.c deleted file mode 100644 index f2a181e86a8..00000000000 --- a/src/compat/compat-inet_ntop.c +++ /dev/null @@ -1,78 +0,0 @@ -/* - * OpenVPN -- An application to securely tunnel IP networks - * over a single UDP port, with support for SSL/TLS-based - * session authentication and key exchange, - * packet encryption, packet authentication, and - * packet compression. - * - * Copyright (C) 2011 - David Sommerseth - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#elif defined(_MSC_VER) -#include "config-msvc.h" -#endif - -#ifndef HAVE_INET_NTOP - -#include "compat.h" - -#ifdef _WIN32 - -#include - -/* - * inet_ntop() and inet_pton() wrap-implementations using - * WSAAddressToString() and WSAStringToAddress() functions - * - * this is needed as long as we support running OpenVPN on WinXP - */ - -const char * -inet_ntop(int af, const void *src, char *dst, socklen_t size) -{ - struct sockaddr_storage ss; - unsigned long s = size; - - ZeroMemory(&ss, sizeof(ss)); - ss.ss_family = af; - - switch (af) - { - case AF_INET: - ((struct sockaddr_in *)&ss)->sin_addr = *(struct in_addr *)src; - break; - - case AF_INET6: - ((struct sockaddr_in6 *)&ss)->sin6_addr = *(struct in6_addr *)src; - break; - - default: - return NULL; - } - /* cannot direclty use &size because of strict aliasing rules */ - return (WSAAddressToString((struct sockaddr *)&ss, sizeof(ss), NULL, dst, &s) == 0) ? - dst : NULL; -} - -#else /* ifdef _WIN32 */ - -#error no emulation for inet_ntop - -#endif /* ifdef _WIN32 */ - -#endif /* ifndef HAVE_INET_NTOP */ diff --git a/src/compat/compat-inet_pton.c b/src/compat/compat-inet_pton.c deleted file mode 100644 index 9d451ccad32..00000000000 --- a/src/compat/compat-inet_pton.c +++ /dev/null @@ -1,81 +0,0 @@ -/* - * OpenVPN -- An application to securely tunnel IP networks - * over a single UDP port, with support for SSL/TLS-based - * session authentication and key exchange, - * packet encryption, packet authentication, and - * packet compression. - * - * Copyright (C) 2011 - David Sommerseth - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#elif defined(_MSC_VER) -#include "config-msvc.h" -#endif - -#ifndef HAVE_INET_PTON - -#include "compat.h" - -#ifdef _WIN32 - -#include -#include - -/* - * inet_ntop() and inet_pton() wrap-implementations using - * WSAAddressToString() and WSAStringToAddress() functions - * - * this is needed as long as we support running OpenVPN on WinXP - */ - - -int -inet_pton(int af, const char *src, void *dst) -{ - struct sockaddr_storage ss; - int size = sizeof(ss); - char src_copy[INET6_ADDRSTRLEN+1]; - - ZeroMemory(&ss, sizeof(ss)); - /* stupid non-const API */ - strncpy(src_copy, src, INET6_ADDRSTRLEN+1); - src_copy[INET6_ADDRSTRLEN] = 0; - - if (WSAStringToAddress(src_copy, af, NULL, (struct sockaddr *)&ss, &size) == 0) - { - switch (af) - { - case AF_INET: - *(struct in_addr *)dst = ((struct sockaddr_in *)&ss)->sin_addr; - return 1; - - case AF_INET6: - *(struct in6_addr *)dst = ((struct sockaddr_in6 *)&ss)->sin6_addr; - return 1; - } - } - return 0; -} - -#else /* ifdef _WIN32 */ - -#error no emulation for inet_ntop - -#endif /* ifdef _WIN32 */ - -#endif /* ifndef HAVE_INET_PTON */ diff --git a/src/compat/compat-strsep.c b/src/compat/compat-strsep.c index 760573ae0f0..4801a950735 100644 --- a/src/compat/compat-strsep.c +++ b/src/compat/compat-strsep.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2019-2022 Arne Schwabe + * Copyright (C) 2019-2023 Arne Schwabe * Copyright (C) 1992-2019 Free Software Foundation, Inc. * * This program is free software; you can redistribute it and/or modify @@ -58,4 +58,4 @@ strsep(char **stringp, const char *delim) } return begin; } -#endif /* ifndef HAVE_STRSEP */ +#endif /* ifndef HAVE_STRSEP */ \ No newline at end of file diff --git a/src/compat/compat-versionhelpers.h b/src/compat/compat-versionhelpers.h index 9e25470eb7a..b071602bd64 100644 --- a/src/compat/compat-versionhelpers.h +++ b/src/compat/compat-versionhelpers.h @@ -19,17 +19,17 @@ #define _WIN32_WINNT_WINBLUE 0x0603 #ifndef _WIN32_WINNT_WINTHRESHOLD -#define _WIN32_WINNT_WINTHRESHOLD 0x0A00 // Windows 10 +#define _WIN32_WINNT_WINTHRESHOLD 0x0A00 /* Windows 10 */ #endif VERSIONHELPERAPI IsWindowsVersionOrGreater(WORD major, WORD minor, WORD servpack) { - OSVERSIONINFOEXW vi = {sizeof(vi),major,minor,0,0,{0},servpack}; + OSVERSIONINFOEXW vi = {sizeof(vi), major, minor, 0, 0, {0}, servpack}; return VerifyVersionInfoW(&vi, VER_MAJORVERSION|VER_MINORVERSION|VER_SERVICEPACKMAJOR, VerSetConditionMask(VerSetConditionMask(VerSetConditionMask(0, - VER_MAJORVERSION,VER_GREATER_EQUAL), - VER_MINORVERSION,VER_GREATER_EQUAL), + VER_MAJORVERSION, VER_GREATER_EQUAL), + VER_MINORVERSION, VER_GREATER_EQUAL), VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL)); } @@ -108,7 +108,7 @@ IsWindows10OrGreater() VERSIONHELPERAPI IsWindowsServer(void) { - OSVERSIONINFOEXW vi = {sizeof(vi),0,0,0,0,{0},0,0,0,VER_NT_WORKSTATION}; + OSVERSIONINFOEXW vi = {sizeof(vi), 0, 0, 0, 0, {0}, 0, 0, 0, VER_NT_WORKSTATION}; return !VerifyVersionInfoW(&vi, VER_PRODUCT_TYPE, VerSetConditionMask(0, VER_PRODUCT_TYPE, VER_EQUAL)); } diff --git a/src/compat/compat.h b/src/compat/compat.h index a66a423500d..026974a81b2 100644 --- a/src/compat/compat.h +++ b/src/compat/compat.h @@ -24,11 +24,8 @@ #ifndef COMPAT_H #define COMPAT_H -#ifdef HAVE_WINSOCK2_H +#ifdef _WIN32 #include -#endif - -#ifdef HAVE_WS2TCPIP_H #include #endif @@ -60,16 +57,6 @@ int daemon(int nochdir, int noclose); #endif -#ifndef HAVE_INET_NTOP -const char *inet_ntop(int af, const void *src, char *dst, socklen_t size); - -#endif - -#ifndef HAVE_INET_PTON -int inet_pton(int af, const char *src, void *dst); - -#endif - #ifndef HAVE_STRSEP char *strsep(char **stringp, const char *delim); diff --git a/src/compat/compat.vcxproj b/src/compat/compat.vcxproj index e138fe91636..aedada1f98b 100644 --- a/src/compat/compat.vcxproj +++ b/src/compat/compat.vcxproj @@ -37,39 +37,39 @@ StaticLibrary MultiByte true - v142 + v143 Spectre StaticLibrary MultiByte true - v142 + v143 Spectre StaticLibrary MultiByte true - v142 + v143 Spectre StaticLibrary MultiByte - v142 + v143 Spectre StaticLibrary MultiByte - v142 + v143 Spectre StaticLibrary MultiByte - v142 + v143 Spectre @@ -162,10 +162,7 @@ - - - diff --git a/src/openvpn/Makefile.am b/src/openvpn/Makefile.am index 2c522009774..8a27ead00f3 100644 --- a/src/openvpn/Makefile.am +++ b/src/openvpn/Makefile.am @@ -5,7 +5,7 @@ # packet encryption, packet authentication, and # packet compression. # -# Copyright (C) 2002-2022 OpenVPN Inc +# Copyright (C) 2002-2023 OpenVPN Inc # Copyright (C) 2006-2012 Alon Bar-Lev # @@ -16,7 +16,6 @@ MAINTAINERCLEANFILES = \ EXTRA_DIST = \ openvpn.vcxproj \ - openvpn.vcxproj.filters \ openvpn.manifest AM_CPPFLAGS = \ @@ -53,7 +52,12 @@ openvpn_SOURCES = \ crypto.c crypto.h crypto_backend.h \ crypto_openssl.c crypto_openssl.h \ crypto_mbedtls.c crypto_mbedtls.h \ + dco.c dco.h dco_internal.h \ + dco_freebsd.c dco_freebsd.h \ + dco_linux.c dco_linux.h \ + dco_win.c dco_win.h \ dhcp.c dhcp.h \ + dns.c dns.h \ env_set.c env_set.h \ errlevel.h \ error.c error.h \ @@ -74,6 +78,8 @@ openvpn_SOURCES = \ mbuf.c mbuf.h \ memdbg.h \ misc.c misc.h \ + ovpn_dco_linux.h \ + ovpn_dco_win.h \ platform.c platform.h \ console.c console.h console_builtin.c console_systemd.c \ mroute.c mroute.h \ @@ -83,6 +89,7 @@ openvpn_SOURCES = \ mtu.c mtu.h \ mudp.c mudp.h \ multi.c multi.h \ + networking_freebsd.c \ networking_iproute2.c networking_iproute2.h \ networking_sitnl.c networking_sitnl.h \ networking.h \ @@ -94,10 +101,10 @@ openvpn_SOURCES = \ pkcs11_mbedtls.c \ openvpn.c openvpn.h \ options.c options.h \ + options_util.c options_util.h \ otime.c otime.h \ packet_id.c packet_id.h \ perf.c perf.h \ - pf.c pf.h \ ping.c ping.h \ plugin.c plugin.h \ pool.c pool.h \ @@ -106,6 +113,7 @@ openvpn_SOURCES = \ ps.c ps.h \ push.c push.h \ pushlist.h \ + reflect_filter.c reflect_filter.h \ reliable.c reliable.h \ route.c route.h \ run_command.c run_command.h \ @@ -119,6 +127,8 @@ openvpn_SOURCES = \ ssl_openssl.c ssl_openssl.h \ ssl_mbedtls.c ssl_mbedtls.h \ ssl_ncp.c ssl_ncp.h \ + ssl_pkt.c ssl_pkt.h \ + ssl_util.c ssl_util.h \ ssl_common.h \ ssl_verify.c ssl_verify.h ssl_verify_backend.h \ ssl_verify_openssl.c ssl_verify_openssl.h \ @@ -128,7 +138,10 @@ openvpn_SOURCES = \ tls_crypt.c tls_crypt.h \ tun.c tun.h \ vlan.c vlan.h \ + xkey_provider.c xkey_common.h \ + xkey_helper.c \ win32.h win32.c \ + win32-util.h win32-util.c \ cryptoapi.h cryptoapi.c openvpn_LDADD = \ $(top_builddir)/src/compat/libcompat.la \ @@ -143,5 +156,5 @@ openvpn_LDADD = \ $(OPTIONAL_INOTIFY_LIBS) if WIN32 openvpn_SOURCES += openvpn_win32_resources.rc block_dns.c block_dns.h ring_buffer.h -openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -endif +openvpn_LDADD += -lgdi32 -lws2_32 -lwininet -lcrypt32 -liphlpapi -lwinmm -lfwpuclnt -lrpcrt4 -lncrypt -lsetupapi -lbcrypt +endif \ No newline at end of file diff --git a/src/openvpn/argv.c b/src/openvpn/argv.c index f1542a47053..65350fb5904 100644 --- a/src/openvpn/argv.c +++ b/src/openvpn/argv.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -501,4 +501,4 @@ argv_parse_cmd(struct argv *argres, const char *cmdstr) { argv_append(argres, string_alloc(cmdstr, &argres->gc)); } -} +} \ No newline at end of file diff --git a/src/openvpn/argv.h b/src/openvpn/argv.h index 138f6bd9002..da875f58f35 100644 --- a/src/openvpn/argv.h +++ b/src/openvpn/argv.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -73,4 +73,4 @@ __attribute__ ((format(__printf__, 2, 3))) #endif ; -#endif /* ifndef ARGV_H */ +#endif /* ifndef ARGV_H */ \ No newline at end of file diff --git a/src/openvpn/auth_token.c b/src/openvpn/auth_token.c index 7c4d15d1adf..716572fb767 100644 --- a/src/openvpn/auth_token.c +++ b/src/openvpn/auth_token.c @@ -21,6 +21,8 @@ const char *auth_token_pem_name = "OpenVPN auth-token server key"; #define AUTH_TOKEN_SESSION_ID_LEN 12 +#define AUTH_TOKEN_SESSION_ID_BASE64_LEN (AUTH_TOKEN_SESSION_ID_LEN * 8 / 6) + #if AUTH_TOKEN_SESSION_ID_LEN % 3 #error AUTH_TOKEN_SESSION_ID_LEN needs to be multiple a 3 #endif @@ -31,23 +33,9 @@ const char *auth_token_pem_name = "OpenVPN auth-token server key"; static struct key_type auth_token_kt(void) { - struct key_type kt = { 0 }; - /* We do not encrypt our session tokens */ - kt.cipher = NULL; - kt.digest = md_kt_get("SHA256"); - - if (!kt.digest) - { - msg(M_WARN, "ERROR: --tls-crypt requires HMAC-SHA-256 support."); - return (struct key_type) { 0 }; - } - - kt.hmac_length = md_kt_size(kt.digest); - - return kt; + return create_kt("none", "SHA256", "auth-gen-token"); } - void add_session_token_env(struct tls_session *session, struct tls_multi *multi, const struct user_pass *up) @@ -87,7 +75,6 @@ add_session_token_env(struct tls_session *session, struct tls_multi *multi, default: /* Silence compiler warning, all four possible combinations are covered */ - state = NULL; ASSERT(0); } } @@ -110,11 +97,11 @@ add_session_token_env(struct tls_session *session, struct tls_multi *multi, /* * No session before, generate a new session token for the new session */ - if (!multi->auth_token) + if (!multi->auth_token_initial) { generate_auth_token(up, multi); } - session_id_source = multi->auth_token; + session_id_source = multi->auth_token_initial; } /* * In the auth-token the auth token is already base64 encoded @@ -185,21 +172,24 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi) uint8_t sessid[AUTH_TOKEN_SESSION_ID_LEN]; - if (multi->auth_token) + if (multi->auth_token_initial) { - /* Just enough space to fit 8 bytes+ 1 extra to decode a non padded + /* Just enough space to fit 8 bytes+ 1 extra to decode a non-padded * base64 string (multiple of 3 bytes). 9 bytes => 12 bytes base64 * bytes */ char old_tstamp_decode[9]; - /* - * reuse the same session id and timestamp and null terminate it at - * for base64 decode it only decodes the session id part of it - */ - char *old_sessid = multi->auth_token + strlen(SESSION_ID_PREFIX); + /* Make a copy of the string to not modify multi->auth_token_initial */ + char *initial_token_copy = string_alloc(multi->auth_token_initial, &gc); + + char *old_sessid = initial_token_copy + strlen(SESSION_ID_PREFIX); char *old_tsamp_initial = old_sessid + AUTH_TOKEN_SESSION_ID_LEN*8/6; + /* + * We null terminate the old token just after the session ID to let + * our base64 decode function only decode the session ID + */ old_tsamp_initial[12] = '\0'; ASSERT(openvpn_base64_decode(old_tsamp_initial, old_tstamp_decode, 9) == 9); @@ -212,11 +202,7 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi) initial_timestamp = *tstamp_ptr; old_tsamp_initial[0] = '\0'; - ASSERT(openvpn_base64_decode(old_sessid, sessid, AUTH_TOKEN_SESSION_ID_LEN)==AUTH_TOKEN_SESSION_ID_LEN); - - - /* free the auth-token, we will replace it with a new one */ - free(multi->auth_token); + ASSERT(openvpn_base64_decode(old_sessid, sessid, AUTH_TOKEN_SESSION_ID_LEN) == AUTH_TOKEN_SESSION_ID_LEN); } else if (!rand_bytes(sessid, AUTH_TOKEN_SESSION_ID_LEN)) { @@ -273,11 +259,22 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi) free(b64output); + /* free the auth-token if defined, we will replace it with a new one */ + free(multi->auth_token); multi->auth_token = strdup((char *)BPTR(&session_token)); dmsg(D_SHOW_KEYS, "Generated token for client: %s (%s)", multi->auth_token, up->username); + if (!multi->auth_token_initial) + { + /* + * Save the initial auth token to continue using the same session ID + * and timestamp in updates + */ + multi->auth_token_initial = strdup(multi->auth_token); + } + gc_free(&gc); } @@ -344,25 +341,19 @@ verify_auth_token(struct user_pass *up, struct tls_multi *multi, } else { - msg(M_WARN, "--auth-token-gen: HMAC on token from client failed (%s)", + msg(M_WARN, "--auth-gen-token: HMAC on token from client failed (%s)", up->username); return 0; } /* Accept session tokens only if their timestamp is in the acceptable range * for renegotiations */ - bool in_renog_time = now >= timestamp - && now < timestamp + 2 * session->opt->renegotiate_seconds; - - /* We could still have a client that does not update - * its auth-token, so also allow the initial auth-token */ - bool initialtoken = multi->auth_token_initial - && memcmp_constant_time(up->password, multi->auth_token_initial, - strlen(multi->auth_token_initial)) == 0; + bool in_renegotiation_time = now >= timestamp + && now < timestamp + 2 * session->opt->auth_token_renewal; - if (!in_renog_time && !initialtoken) + if (!in_renegotiation_time) { - msg(M_WARN, "Timestamp (%" PRIu64 ") of auth-token is out of the renegotiation window", + msg(M_WARN, "Timestamp (%" PRIu64 ") of auth-token is out of the renewal window", timestamp); ret |= AUTH_TOKEN_EXPIRED; } @@ -386,7 +377,20 @@ verify_auth_token(struct user_pass *up, struct tls_multi *multi, { /* Tell client that the session token is expired */ auth_set_client_reason(multi, "SESSION: token expired"); - msg(M_INFO, "--auth-token-gen: auth-token from client expired"); + msg(M_INFO, "--auth-gen-token: auth-token from client expired"); + } + + /* Check that we do have the same session ID in the token as in our stored + * auth-token to ensure that it did not change. + * This also compares the prefix and session part of the + * tokens, which should be identical if the session ID stayed the same */ + if (multi->auth_token_initial + && memcmp_constant_time(multi->auth_token_initial, up->password, + strlen(SESSION_ID_PREFIX) + AUTH_TOKEN_SESSION_ID_BASE64_LEN)) + { + msg(M_WARN, "--auth-gen-token: session id in token changed (Rejecting " + "token."); + ret = 0; } return ret; } @@ -411,3 +415,63 @@ wipe_auth_token(struct tls_multi *multi) multi->auth_token_initial = NULL; } } + +void +check_send_auth_token(struct context *c) +{ + struct tls_multi *multi = c->c2.tls_multi; + struct tls_session *session = &multi->session[TM_ACTIVE]; + + if (get_primary_key(multi)->state < S_GENERATED_KEYS + || get_primary_key(multi)->authenticated != KS_AUTH_TRUE) + { + /* the currently active session is still in renegotiation or another + * not fully authorized state. We are either very close to a + * renegotiation or have deauthorized the client. In both cases + * we just ignore the request to send another token + */ + return; + } + + if (!multi->auth_token_initial) + { + msg(D_SHOW_KEYS, "initial auth-token not generated yet, skipping " + "auth-token renewal."); + return; + } + + if (!multi->locked_username) + { + msg(D_SHOW_KEYS, "username not locked, skipping auth-token renewal."); + return; + } + + struct user_pass up; + strncpynt(up.username, multi->locked_username, sizeof(up.username)); + + generate_auth_token(&up, multi); + + resend_auth_token_renegotiation(multi, session); +} + +void +resend_auth_token_renegotiation(struct tls_multi *multi, struct tls_session *session) +{ + /* + * Auth token already sent to client, update auth-token on client. + * The initial auth-token is sent as part of the push message, for this + * update we need to schedule an extra push message. + * + * Otherwise, the auth-token get pushed out as part of the "normal" + * push-reply + */ + if (multi->auth_token_initial) + { + /* + * We do not explicitly reschedule the sending of the + * control message here. This might delay this reply + * a few seconds but this message is not time critical + */ + send_push_reply_auth_token(multi); + } +} \ No newline at end of file diff --git a/src/openvpn/auth_token.h b/src/openvpn/auth_token.h index 0fa4dbaec72..3a41c50c336 100644 --- a/src/openvpn/auth_token.h +++ b/src/openvpn/auth_token.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -46,11 +46,11 @@ * (2 * renogiation timeout) * * The session id is a random string of 12 byte (or 16 in base64) that is not - * used by OpenVPN itself but kept intact so that external logging/managment - * can track the session multiple reconnects/servers. It is delibrately chosen + * used by OpenVPN itself but kept intact so that external logging/management + * can track the session multiple reconnects/servers. It is deliberately chosen * be a multiple of 3 bytes to have a base64 encoding without padding. * - * The hmac is calculated over the username contactinated with the + * The hmac is calculated over the username concatenated with the * raw auth-token bytes to include authentication of the username in the token * * We encode the auth-token with base64 and then prepend "SESS_ID_" before @@ -117,7 +117,7 @@ void wipe_auth_token(struct tls_multi *multi); /** * Return if the password string has the format of a password. * - * This fuction will always read as many bytes as SESSION_ID_PREFIX is longer + * This function will always read as many bytes as SESSION_ID_PREFIX is longer * the caller needs ensure that password memory is at least that long (true for * calling with struct user_pass) * @param password @@ -129,4 +129,21 @@ is_auth_token(const char *password) return (memcmp_constant_time(SESSION_ID_PREFIX, password, strlen(SESSION_ID_PREFIX)) == 0); } -#endif /* AUTH_TOKEN_H */ +/** + * Checks if a client should be sent a new auth token to update its + * current auth-token + * @param multi Pointer the multi object of the TLS session + * @param session Pointer to the TLS session itself + */ +void +resend_auth_token_renegotiation(struct tls_multi *multi, struct tls_session *session); + + +/** + * Checks if the timer to resend the auth-token has expired and if a new + * auth-token should be send to the client and triggers the resending + */ +void +check_send_auth_token(struct context *c); + +#endif /* AUTH_TOKEN_H */ \ No newline at end of file diff --git a/src/openvpn/base64.h b/src/openvpn/base64.h index f49860fc65a..7b4224a51b4 100644 --- a/src/openvpn/base64.h +++ b/src/openvpn/base64.h @@ -38,6 +38,10 @@ #define OPENVPN_BASE64_LENGTH(binary_length) \ ((((8 * binary_length) / 6) + 3) & ~3) +/** Compute the maximal number of bytes encoded in a base64 string. */ +#define OPENVPN_BASE64_DECODED_LENGTH(base64_length) \ + ((base64_length / 4) * 3) + int openvpn_base64_encode(const void *data, int size, char **str); int openvpn_base64_decode(const char *str, void *data, int size); diff --git a/src/openvpn/basic.h b/src/openvpn/basic.h index f33ce875485..816b63bff6a 100644 --- a/src/openvpn/basic.h +++ b/src/openvpn/basic.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -34,4 +34,4 @@ #define IPV4_NETMASK_HOST 0xffffffffU -#endif +#endif \ No newline at end of file diff --git a/src/openvpn/block_dns.c b/src/openvpn/block_dns.c index 88e933fbfdc..a065c33b183 100644 --- a/src/openvpn/block_dns.c +++ b/src/openvpn/block_dns.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * 2015-2016 * 2016 Selva Nair * @@ -28,9 +28,6 @@ #elif defined(_MSC_VER) #include "config-msvc.h" #endif -#ifdef HAVE_CONFIG_VERSION_H -#include "config-version.h" -#endif #include "syshead.h" @@ -425,4 +422,4 @@ set_interface_metric(const NET_IFINDEX index, const ADDRESS_FAMILY family, return err; } -#endif /* ifdef _WIN32 */ +#endif /* ifdef _WIN32 */ \ No newline at end of file diff --git a/src/openvpn/block_dns.h b/src/openvpn/block_dns.h index b937a92293c..25a4613685f 100644 --- a/src/openvpn/block_dns.h +++ b/src/openvpn/block_dns.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2016-2022 Selva Nair + * Copyright (C) 2016-2023 Selva Nair * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -66,4 +66,4 @@ set_interface_metric(const NET_IFINDEX index, const ADDRESS_FAMILY family, const ULONG metric); #endif /* ifndef OPENVPN_BLOCK_DNS_H */ -#endif /* ifdef _WIN32 */ +#endif /* ifdef _WIN32 */ \ No newline at end of file diff --git a/src/openvpn/buffer.c b/src/openvpn/buffer.c index e422ab7ce77..39a8b66e70f 100644 --- a/src/openvpn/buffer.c +++ b/src/openvpn/buffer.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -184,10 +184,7 @@ buf_assign(struct buffer *dest, const struct buffer *src) void free_buf(struct buffer *buf) { - if (buf->data) - { - free(buf->data); - } + free(buf->data); CLEAR(*buf); } @@ -276,7 +273,7 @@ buf_puts(struct buffer *buf, const char *str) int cap = buf_forward_capacity(buf); if (cap > 0) { - strncpynt((char *)ptr,str, cap); + strncpynt((char *)ptr, str, cap); *(buf->data + buf->capacity - 1) = 0; /* windows vsnprintf needs this */ buf->len += (int) strlen((char *)ptr); ret = true; @@ -415,6 +412,39 @@ gc_malloc(size_t size, bool clear, struct gc_arena *a) return ret; } +void * +gc_realloc(void *ptr, size_t size, struct gc_arena *a) +{ + void *ret = realloc(ptr, size); + check_malloc_return(ret); + if (a) + { + if (ptr && ptr != ret) + { + /* find the old entry and modify it if realloc changed + * the pointer */ + struct gc_entry_special *e = NULL; + for (e = a->list_special; e != NULL; e = e->next) + { + if (e->addr == ptr) + { + break; + } + } + ASSERT(e); + ASSERT(e->addr == ptr); + e->addr = ret; + } + else if (!ptr) + { + /* sets e->addr to newptr */ + gc_addspecial(ret, free, a); + } + } + + return ret; +} + void x_gc_free(struct gc_arena *a) { @@ -641,7 +671,7 @@ rm_trailing_chars(char *str, const char *what_to_delete) bool modified; do { - const int len = strlen(str); + const size_t len = strlen(str); modified = false; if (len > 0) { @@ -667,7 +697,7 @@ string_alloc(const char *str, struct gc_arena *gc) { if (str) { - const int n = strlen(str) + 1; + const size_t n = strlen(str) + 1; char *ret; if (gc) @@ -793,7 +823,7 @@ string_alloc_buf(const char *str, struct gc_arena *gc) bool buf_string_match_head_str(const struct buffer *src, const char *match) { - const int size = strlen(match); + const size_t size = strlen(match); if (size < 0 || size > src->len) { return false; @@ -806,7 +836,7 @@ buf_string_compare_advance(struct buffer *src, const char *match) { if (buf_string_match_head_str(src, match)) { - buf_advance(src, strlen(match)); + buf_advance(src, (int)strlen(match)); return true; } else @@ -1174,11 +1204,10 @@ valign4(const struct buffer *buf, const char *file, const int line) * struct buffer_list */ struct buffer_list * -buffer_list_new(const int max_size) +buffer_list_new(void) { struct buffer_list *ret; ALLOC_OBJ_CLEAR(ret, struct buffer_list); - ret->max_size = max_size; ret->size = 0; return ret; } @@ -1223,7 +1252,7 @@ buffer_list_push(struct buffer_list *ol, const char *str) struct buffer_entry *e = buffer_list_push_data(ol, str, len+1); if (e) { - e->buf.len = len; /* Don't count trailing '\0' as part of length */ + e->buf.len = (int)len; /* Don't count trailing '\0' as part of length */ } } } @@ -1232,7 +1261,7 @@ struct buffer_entry * buffer_list_push_data(struct buffer_list *ol, const void *data, size_t size) { struct buffer_entry *e = NULL; - if (data && (!ol->max_size || ol->size < ol->max_size)) + if (data) { ALLOC_OBJ_CLEAR(e, struct buffer_entry); @@ -1272,7 +1301,7 @@ void buffer_list_aggregate_separator(struct buffer_list *bl, const size_t max_len, const char *sep) { - const int sep_len = strlen(sep); + const size_t sep_len = strlen(sep); struct buffer_entry *more = bl->head; size_t size = 0; int count = 0; @@ -1362,7 +1391,7 @@ buffer_list_file(const char *fn, int max_line_len) char *line = (char *) malloc(max_line_len); if (line) { - bl = buffer_list_new(0); + bl = buffer_list_new(); while (fgets(line, max_line_len, fp) != NULL) { buffer_list_push(bl, line); @@ -1379,7 +1408,7 @@ buffer_read_from_file(const char *filename, struct gc_arena *gc) { struct buffer ret = { 0 }; - platform_stat_t file_stat = {0}; + platform_stat_t file_stat = { 0 }; if (platform_stat(filename, &file_stat) < 0) { return ret; @@ -1393,16 +1422,16 @@ buffer_read_from_file(const char *filename, struct gc_arena *gc) const size_t size = file_stat.st_size; ret = alloc_buf_gc(size + 1, gc); /* space for trailing \0 */ - ssize_t read_size = fread(BPTR(&ret), 1, size, fp); - if (read_size < 0) + size_t read_size = fread(BPTR(&ret), 1, size, fp); + if (read_size == 0) { free_buf_gc(&ret, gc); goto cleanup; } - ASSERT(buf_inc_len(&ret, read_size)); + ASSERT(buf_inc_len(&ret, (int)read_size)); buf_null_terminate(&ret); cleanup: fclose(fp); return ret; -} +} \ No newline at end of file diff --git a/src/openvpn/buffer.h b/src/openvpn/buffer.h index 94d63b7f926..b0c7470c175 100644 --- a/src/openvpn/buffer.h +++ b/src/openvpn/buffer.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -187,6 +187,19 @@ struct buffer string_alloc_buf(const char *str, struct gc_arena *gc); void gc_addspecial(void *addr, void (*free_function)(void *), struct gc_arena *a); +/** + * allows to realloc a pointer previously allocated by gc_malloc or gc_realloc + * + * @note only use this function on pointers returned by gc_malloc or re_alloc + * with the same gc_arena + * + * @param ptr Pointer of the previously allocated memory + * @param size New size + * @param a gc_arena to use + * @return new pointer + */ +void * +gc_realloc(void *ptr, size_t size, struct gc_arena *a); #ifdef BUF_INIT_TRACKING #define buf_init(buf, offset) buf_init_debug(buf, offset, __FILE__, __LINE__) @@ -198,7 +211,7 @@ bool buf_init_debug(struct buffer *buf, int offset, const char *file, int line); /* inline functions */ -inline static void +static inline void gc_freeaddrinfo_callback(void *addr) { freeaddrinfo((struct addrinfo *) addr); @@ -332,13 +345,13 @@ buf_set_write(struct buffer *buf, uint8_t *data, int size) } static inline void -buf_set_read(struct buffer *buf, const uint8_t *data, int size) +buf_set_read(struct buffer *buf, const uint8_t *data, size_t size) { if (!buf_size_valid(size)) { buf_size_error(size); } - buf->len = buf->capacity = size; + buf->len = buf->capacity = (int)size; buf->offset = 0; buf->data = (uint8_t *)data; } @@ -356,9 +369,9 @@ strncpynt(char *dest, const char *src, size_t maxlen) /* return true if string contains at least one numerical digit */ static inline bool -has_digit(const unsigned char *src) +has_digit(const char *src) { - unsigned char c; + char c; while ((c = *src++)) { if (isdigit(c)) @@ -522,10 +535,10 @@ struct buffer buf_sub(struct buffer *buf, int size, bool prepend); */ static inline bool -buf_safe(const struct buffer *buf, int len) +buf_safe(const struct buffer *buf, size_t len) { return buf_valid(buf) && buf_size_valid(len) - && buf->offset + buf->len + len <= buf->capacity; + && buf->offset + buf->len + (int)len <= buf->capacity; } static inline bool @@ -533,7 +546,7 @@ buf_safe_bidir(const struct buffer *buf, int len) { if (buf_valid(buf) && buf_size_valid_signed(len)) { - const int newlen = buf->len + len; + int newlen = buf->len + len; return newlen >= 0 && buf->offset + newlen <= buf->capacity; } else @@ -637,7 +650,7 @@ buf_advance(struct buffer *buf, int size) */ static inline uint8_t * -buf_write_alloc(struct buffer *buf, int size) +buf_write_alloc(struct buffer *buf, size_t size) { uint8_t *ret; if (!buf_safe(buf, size)) @@ -645,7 +658,7 @@ buf_write_alloc(struct buffer *buf, int size) return NULL; } ret = BPTR(buf) + buf->len; - buf->len += size; + buf->len += (int)size; return ret; } @@ -670,7 +683,7 @@ buf_read_alloc(struct buffer *buf, int size) } static inline bool -buf_write(struct buffer *dest, const void *src, int size) +buf_write(struct buffer *dest, const void *src, size_t size) { uint8_t *cp = buf_write_alloc(dest, size); if (!cp) @@ -694,23 +707,22 @@ buf_write_prepend(struct buffer *dest, const void *src, int size) } static inline bool -buf_write_u8(struct buffer *dest, int data) +buf_write_u8(struct buffer *dest, uint8_t data) { - uint8_t u8 = (uint8_t) data; - return buf_write(dest, &u8, sizeof(uint8_t)); + return buf_write(dest, &data, sizeof(uint8_t)); } static inline bool -buf_write_u16(struct buffer *dest, int data) +buf_write_u16(struct buffer *dest, uint16_t data) { - uint16_t u16 = htons((uint16_t) data); + uint16_t u16 = htons(data); return buf_write(dest, &u16, sizeof(uint16_t)); } static inline bool -buf_write_u32(struct buffer *dest, int data) +buf_write_u32(struct buffer *dest, uint32_t data) { - uint32_t u32 = htonl((uint32_t) data); + uint32_t u32 = htonl(data); return buf_write(dest, &u32, sizeof(uint32_t)); } @@ -1102,11 +1114,9 @@ struct buffer_list /** * Allocate an empty buffer list of capacity \c max_size. * - * @param max_size the capacity of the list to allocate - * * @return the new list */ -struct buffer_list *buffer_list_new(const int max_size); +struct buffer_list *buffer_list_new(void); /** * Frees a buffer list and all the buffers in it. @@ -1203,4 +1213,4 @@ struct buffer_list *buffer_list_file(const char *fn, int max_line_len); */ struct buffer buffer_read_from_file(const char *filename, struct gc_arena *gc); -#endif /* BUFFER_H */ +#endif /* BUFFER_H */ \ No newline at end of file diff --git a/src/openvpn/circ_list.h b/src/openvpn/circ_list.h index 225dfae1819..829327de911 100644 --- a/src/openvpn/circ_list.h +++ b/src/openvpn/circ_list.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -34,7 +34,7 @@ int x_size; \ int x_cap; \ int x_sizeof; \ - type x_list[EMPTY_ARRAY_SIZE]; \ + type x_list[]; \ } #define CIRC_LIST_PUSH(obj, item) \ @@ -74,4 +74,4 @@ #define CIRC_LIST_FREE(dest) \ free(dest) -#endif /* ifndef CIRC_LIST_H */ +#endif /* ifndef CIRC_LIST_H */ \ No newline at end of file diff --git a/src/openvpn/clinat.c b/src/openvpn/clinat.c index 1f272231df7..7ace2e5ab67 100644 --- a/src/openvpn/clinat.c +++ b/src/openvpn/clinat.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -275,4 +275,4 @@ client_nat_transform(const struct client_nat_option_list *list, } } } -} +} \ No newline at end of file diff --git a/src/openvpn/clinat.h b/src/openvpn/clinat.h index 0135c5eaf70..25c8ae0e020 100644 --- a/src/openvpn/clinat.h +++ b/src/openvpn/clinat.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -64,4 +64,4 @@ void client_nat_transform(const struct client_nat_option_list *list, struct buffer *ipbuf, const int direction); -#endif /* if !defined(CLINAT_H) */ +#endif /* if !defined(CLINAT_H) */ \ No newline at end of file diff --git a/src/openvpn/common.h b/src/openvpn/common.h index f36df3e625c..f2655faa870 100644 --- a/src/openvpn/common.h +++ b/src/openvpn/common.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -25,19 +25,10 @@ #define COMMON_H /* - * Statistics counters and associated printf formats. + * Statistics counters and associated printf format. */ -#ifdef USE_64_BIT_COUNTERS -typedef unsigned long long int counter_type; -#ifdef _WIN32 -#define counter_format "%I64u" -#else -#define counter_format "%llu" -#endif -#else /* ifdef USE_64_BIT_COUNTERS */ -typedef unsigned int counter_type; -#define counter_format "%u" -#endif +typedef uint64_t counter_type; +#define counter_format "%" PRIu64 /* * Time intervals @@ -53,7 +44,7 @@ typedef int interval_t; * Printf formats for special types */ #ifdef _WIN64 -#define ptr_format "0x%I64x" +#define ptr_format "0x%016" PRIx64 #else #define ptr_format "0x%08lx" #endif @@ -77,6 +68,19 @@ typedef unsigned long ptr_type; */ #define TLS_CHANNEL_BUF_SIZE 2048 +/* TLS control buffer minimum size + * + * A control frame might have IPv6 header (40 byte), + * UDP (8 byte), opcode (1), session id (8), + * ACK array with 4 ACKs in non-ACK_V1 packets (25 bytes) + * tls-crypt(56) or tls-auth(up to 72). To allow secure + * renegotiation (dynamic tls-crypt), we set this minimum + * to 154, which only allows 16 byte of payload and should + * be considered an absolute minimum and not a good value to + * set + */ +#define TLS_CHANNEL_MTU_MIN 154 + /* * This parameter controls the maximum size of a bundle * of pushed options. @@ -93,4 +97,4 @@ typedef unsigned long ptr_type; */ #define SCRIPT_SECURITY_WARNING "WARNING: External program may not be called unless '--script-security 2' or higher is enabled. See --help text or man page for detailed info." -#endif /* ifndef COMMON_H */ +#endif /* ifndef COMMON_H */ \ No newline at end of file diff --git a/src/openvpn/comp-lz4.c b/src/openvpn/comp-lz4.c index 620c1f48f75..cbd77e1c7e0 100644 --- a/src/openvpn/comp-lz4.c +++ b/src/openvpn/comp-lz4.c @@ -5,8 +5,8 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc - * Copyright (C) 2013-2022 Gert Doering + * Copyright (C) 2002-2023 OpenVPN Inc + * Copyright (C) 2013-2023 Gert Doering * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -31,12 +31,7 @@ #include "syshead.h" #if defined(ENABLE_LZ4) - -#if defined(NEED_COMPAT_LZ4) -#include "compat-lz4.h" -#else #include -#endif #include "comp.h" #include "error.h" @@ -74,11 +69,11 @@ do_lz4_compress(struct buffer *buf, */ if (buf->len >= COMPRESS_THRESHOLD && (compctx->flags & COMP_F_ALLOW_COMPRESS)) { - const size_t ps = PAYLOAD_SIZE(frame); + const size_t ps = frame->buf.payload_size; int zlen_max = ps + COMP_EXTRA_BUFFER(ps); int zlen; - ASSERT(buf_init(work, FRAME_HEADROOM(frame))); + ASSERT(buf_init(work, frame->buf.headroom)); ASSERT(buf_safe(work, zlen_max)); if (buf->len > ps) @@ -218,7 +213,7 @@ lz4_decompress(struct buffer *buf, struct buffer work, struct compress_context *compctx, const struct frame *frame) { - size_t zlen_max = EXPANDED_SIZE(frame); + size_t zlen_max = frame->buf.payload_size; uint8_t c; /* flag indicating whether or not our peer compressed */ if (buf->len <= 0) @@ -226,7 +221,7 @@ lz4_decompress(struct buffer *buf, struct buffer work, return; } - ASSERT(buf_init(&work, FRAME_HEADROOM(frame))); + ASSERT(buf_init(&work, frame->buf.headroom)); /* do unframing/swap (assumes buf->len > 0) */ { @@ -242,6 +237,7 @@ lz4_decompress(struct buffer *buf, struct buffer work, } else if (c == NO_COMPRESS_BYTE_SWAP) /* packet was not compressed */ { + /* nothing to do */ } else { @@ -255,7 +251,7 @@ lz4v2_decompress(struct buffer *buf, struct buffer work, struct compress_context *compctx, const struct frame *frame) { - size_t zlen_max = EXPANDED_SIZE(frame); + size_t zlen_max = frame->buf.payload_size; uint8_t c; /* flag indicating whether or not our peer compressed */ if (buf->len <= 0) @@ -263,7 +259,7 @@ lz4v2_decompress(struct buffer *buf, struct buffer work, return; } - ASSERT(buf_init(&work, FRAME_HEADROOM(frame))); + ASSERT(buf_init(&work, frame->buf.headroom)); /* do unframing/swap (assumes buf->len > 0) */ uint8_t *head = BPTR(buf); @@ -285,12 +281,12 @@ lz4v2_decompress(struct buffer *buf, struct buffer work, c = head[1]; if (c == COMP_ALGV2_LZ4_BYTE) /* packet was compressed */ { - buf_advance(buf,2); + buf_advance(buf, 2); do_lz4_decompress(zlen_max, &work, buf, compctx); } else if (c == COMP_ALGV2_UNCOMPRESSED_BYTE) { - buf_advance(buf,2); + buf_advance(buf, 2); } else { @@ -314,10 +310,4 @@ const struct compress_alg lz4v2_alg = { lz4v2_compress, lz4v2_decompress }; - -#else /* if defined(ENABLE_LZ4) */ -static void -dummy(void) -{ -} -#endif /* ENABLE_LZ4 */ +#endif /* ENABLE_LZ4 */ \ No newline at end of file diff --git a/src/openvpn/comp-lz4.h b/src/openvpn/comp-lz4.h index 827253da985..d8a1accbef5 100644 --- a/src/openvpn/comp-lz4.h +++ b/src/openvpn/comp-lz4.h @@ -5,8 +5,8 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc - * Copyright (C) 2013-2022 Gert Doering + * Copyright (C) 2002-2023 OpenVPN Inc + * Copyright (C) 2013-2023 Gert Doering * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -38,4 +38,4 @@ struct lz4_workspace }; #endif /* ENABLE_LZ4 */ -#endif +#endif \ No newline at end of file diff --git a/src/openvpn/comp.c b/src/openvpn/comp.c index fbc920bcb59..7f34878a872 100644 --- a/src/openvpn/comp.c +++ b/src/openvpn/comp.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -116,21 +116,6 @@ comp_uninit(struct compress_context *compctx) } } -void -comp_add_to_extra_frame(struct frame *frame) -{ - /* Leave room for our one-byte compressed/didn't-compress prefix byte. */ - frame_add_to_extra_frame(frame, COMP_PREFIX_LEN); -} - -void -comp_add_to_extra_buffer(struct frame *frame) -{ - /* Leave room for compression buffer to expand in worst case scenario - * where data is totally incompressible */ - frame_add_to_extra_buffer(frame, COMP_EXTRA_BUFFER(EXPANDED_SIZE(frame))); -} - void comp_print_stats(const struct compress_context *compctx, struct status_output *so) { @@ -169,8 +154,7 @@ comp_generate_peer_info_string(const struct compress_options *opt, struct buffer } buf_printf(out, "IV_COMP_STUB=1\n"); buf_printf(out, "IV_COMP_STUBv2=1\n"); - buf_printf(out, "IV_TCPNL=1\n"); } } -#endif /* USE_COMP */ +#endif /* USE_COMP */ \ No newline at end of file diff --git a/src/openvpn/comp.h b/src/openvpn/comp.h index 94f3fa7e322..16901e9a865 100644 --- a/src/openvpn/comp.h +++ b/src/openvpn/comp.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -58,6 +58,8 @@ #define COMP_F_ADVERTISE_STUBS_ONLY (1<<3) /* tell server that we only support compression stubs */ #define COMP_F_ALLOW_STUB_ONLY (1<<4) /* Only accept stub compression, even with COMP_F_ADVERTISE_STUBS_ONLY * we still accept other compressions to be pushed */ +#define COMP_F_MIGRATE (1<<5) /* push stub-v2 or comp-lzo no when we see a client with comp-lzo in occ */ +#define COMP_F_ALLOW_ASYM (1<<6) /* Compression was explicitly set to allow asymetric compression */ /* @@ -174,10 +176,6 @@ struct compress_context *comp_init(const struct compress_options *opt); void comp_uninit(struct compress_context *compctx); -void comp_add_to_extra_frame(struct frame *frame); - -void comp_add_to_extra_buffer(struct frame *frame); - void comp_print_stats(const struct compress_context *compctx, struct status_output *so); void comp_generate_peer_info_string(const struct compress_options *opt, struct buffer *out); @@ -198,11 +196,5 @@ comp_non_stub_enabled(const struct compress_options *info) && info->alg != COMP_ALG_UNDEF; } -static inline bool -comp_unswapped_prefix(const struct compress_options *info) -{ - return !(info->flags & COMP_F_SWAP); -} - #endif /* USE_COMP */ -#endif /* ifndef OPENVPN_COMP_H */ +#endif /* ifndef OPENVPN_COMP_H */ \ No newline at end of file diff --git a/src/openvpn/compstub.c b/src/openvpn/compstub.c index 8adf5084014..26f0d46e490 100644 --- a/src/openvpn/compstub.c +++ b/src/openvpn/compstub.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -175,10 +175,4 @@ const struct compress_alg comp_stub_alg = { stub_compress, stub_decompress }; - -#else /* if defined(USE_COMP) */ -static void -dummy(void) -{ -} -#endif /* USE_STUB */ +#endif /* USE_STUB */ \ No newline at end of file diff --git a/src/openvpn/console.c b/src/openvpn/console.c index 6ee179fe446..a6a6d7056d3 100644 --- a/src/openvpn/console.c +++ b/src/openvpn/console.c @@ -5,9 +5,9 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * Copyright (C) 2014-2015 David Sommerseth - * Copyright (C) 2016-2022 David Sommerseth + * Copyright (C) 2016-2023 David Sommerseth * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -83,4 +83,4 @@ query_user_add(char *prompt, size_t prompt_len, query_user[i].response = resp; query_user[i].response_len = resp_len; query_user[i].echo = echo; -} +} \ No newline at end of file diff --git a/src/openvpn/console.h b/src/openvpn/console.h index 97d5ae81bd5..1bcc42599b4 100644 --- a/src/openvpn/console.h +++ b/src/openvpn/console.h @@ -5,9 +5,9 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * Copyright (C) 2014-2015 David Sommerseth - * Copyright (C) 2016-2022 David Sommerseth + * Copyright (C) 2016-2023 David Sommerseth * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -116,4 +116,4 @@ query_user_SINGLE(char *prompt, size_t prompt_len, return query_user_exec(); } -#endif /* ifndef CONSOLE_H */ +#endif /* ifndef CONSOLE_H */ \ No newline at end of file diff --git a/src/openvpn/console_builtin.c b/src/openvpn/console_builtin.c index b00594e4d56..948b59a4106 100644 --- a/src/openvpn/console_builtin.c +++ b/src/openvpn/console_builtin.c @@ -5,9 +5,9 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * Copyright (C) 2014-2015 David Sommerseth - * Copyright (C) 2016-2022 David Sommerseth + * Copyright (C) 2016-2023 David Sommerseth * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -40,6 +40,10 @@ #include "buffer.h" #include "misc.h" +#ifdef HAVE_TERMIOS_H +#include +#endif + #ifdef _WIN32 #include "win32.h" @@ -65,7 +69,7 @@ get_console_input_win32(const char *prompt, const bool echo, char *input, const input[0] = '\0'; HANDLE in = GetStdHandle(STD_INPUT_HANDLE); - int orig_stderr = get_orig_stderr(); // guaranteed to be always valid + int orig_stderr = get_orig_stderr(); /* guaranteed to be always valid */ if ((in == INVALID_HANDLE_VALUE) || win32_service_interrupt(&win32_signal) || (_write(orig_stderr, prompt, strlen(prompt)) == -1)) @@ -137,7 +141,7 @@ get_console_input_win32(const char *prompt, const bool echo, char *input, const #endif /* _WIN32 */ -#ifdef HAVE_GETPASS +#ifdef HAVE_TERMIOS_H /** * Open the current console TTY for read/write operations @@ -176,7 +180,7 @@ close_tty(FILE *fp) } } -#endif /* HAVE_GETPASS */ +#endif /* HAVE_TERMIOS_H */ /** @@ -200,7 +204,9 @@ get_console_input(const char *prompt, const bool echo, char *input, const int ca #if defined(_WIN32) return get_console_input_win32(prompt, echo, input, capacity); -#elif defined(HAVE_GETPASS) +#elif defined(HAVE_TERMIOS_H) + bool restore_tty = false; + struct termios tty_tmp, tty_save; /* did we --daemon'ize before asking for passwords? * (in which case neither stdin or stderr are connected to a tty and @@ -219,33 +225,41 @@ get_console_input(const char *prompt, const bool echo, char *input, const int ca close(fd); } - if (echo) - { - FILE *fp; + FILE *fp = open_tty(true); + fprintf(fp, "%s", prompt); + fflush(fp); + close_tty(fp); - fp = open_tty(true); - fprintf(fp, "%s", prompt); - fflush(fp); - close_tty(fp); + fp = open_tty(false); - fp = open_tty(false); - if (fgets(input, capacity, fp) != NULL) - { - chomp(input); - ret = true; - } - close_tty(fp); + if (!echo && (tcgetattr(fileno(fp), &tty_tmp) == 0)) + { + tty_save = tty_tmp; + tty_tmp.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL | ISIG); + restore_tty = (tcsetattr(fileno(fp), TCSAFLUSH, &tty_tmp) == 0); } - else + + if (fgets(input, capacity, fp) != NULL) { - char *gp = getpass(prompt); - if (gp) + chomp(input); + ret = true; + } + + if (restore_tty) + { + if (tcsetattr(fileno(fp), TCSAFLUSH, &tty_save) == -1) { - strncpynt(input, gp, capacity); - secure_memzero(gp, strlen(gp)); - ret = true; + msg(M_WARN | M_ERRNO, "tcsetattr() failed to restore tty settings"); } + + /* Echo the non-echoed newline */ + close_tty(fp); + fp = open_tty(true); + fprintf(fp, "\n"); + fflush(fp); } + + close_tty(fp); #else /* if defined(_WIN32) */ msg(M_FATAL, "Sorry, but I can't get console input on this OS (%s)", prompt); #endif /* if defined(_WIN32) */ @@ -283,4 +297,4 @@ query_user_exec_builtin(void) } return ret; -} +} \ No newline at end of file diff --git a/src/openvpn/crypto.c b/src/openvpn/crypto.c index 6e2e235646b..b64a7a43e71 100644 --- a/src/openvpn/crypto.c +++ b/src/openvpn/crypto.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * Copyright (C) 2010-2021 Fox Crypto B.V. * * This program is free software; you can redistribute it and/or modify @@ -49,14 +49,14 @@ * work is a workspace buffer we are given of size BUF_SIZE. * work may be used to return output data, or the input buffer * may be modified and returned as output. If output data is - * returned in work, the data should start after FRAME_HEADROOM bytes + * returned in work, the data should start after buf.headroom bytes * of padding to leave room for downstream routines to prepend. * - * Up to a total of FRAME_HEADROOM bytes may be prepended to the input buf + * Up to a total of buf.headroom bytes may be prepended to the input buf * by all routines (encryption, decryption, compression, and decompression). * * Note that the buf_prepend return will assert if we try to - * make a header bigger than FRAME_HEADROOM. This should not + * make a header bigger than buf.headroom. This should not * happen unless the frame parameters are wrong. */ @@ -68,12 +68,10 @@ openvpn_encrypt_aead(struct buffer *buf, struct buffer work, int outlen = 0; const struct key_ctx *ctx = &opt->key_ctx_bi.encrypt; uint8_t *mac_out = NULL; - const cipher_kt_t *cipher_kt = cipher_ctx_get_cipher_kt(ctx->cipher); - const int mac_len = cipher_kt_tag_size(cipher_kt); + const int mac_len = OPENVPN_AEAD_TAG_LENGTH; /* IV, packet-ID and implicit IV required for this mode. */ ASSERT(ctx->cipher); - ASSERT(cipher_kt_mode_aead(cipher_kt)); ASSERT(packet_id_initialized(&opt->packet_id)); gc_init(&gc); @@ -171,7 +169,6 @@ openvpn_encrypt_v1(struct buffer *buf, struct buffer work, { uint8_t iv_buf[OPENVPN_MAX_IV_LENGTH] = {0}; const int iv_size = cipher_ctx_iv_length(ctx->cipher); - const cipher_kt_t *cipher_kt = cipher_ctx_get_cipher_kt(ctx->cipher); int outlen; /* Reserve space for HMAC */ @@ -182,7 +179,7 @@ openvpn_encrypt_v1(struct buffer *buf, struct buffer work, hmac_start = BEND(&work); } - if (cipher_kt_mode_cbc(cipher_kt)) + if (cipher_ctx_mode_cbc(ctx->cipher)) { /* generate pseudo-random IV */ prng_bytes(iv_buf, iv_size); @@ -197,7 +194,7 @@ openvpn_encrypt_v1(struct buffer *buf, struct buffer work, goto err; } } - else if (cipher_kt_mode_ofb_cfb(cipher_kt)) + else if (cipher_ctx_mode_ofb_cfb(ctx->cipher)) { struct buffer b; @@ -212,7 +209,7 @@ openvpn_encrypt_v1(struct buffer *buf, struct buffer work, ASSERT(0); } - /* set the IV pseudo-randomly */ + /* write the pseudo-randomly IV (CBC)/packet ID (OFB/CFB) */ ASSERT(buf_write(&work, iv_buf, iv_size)); dmsg(D_PACKET_CONTENT, "ENCRYPT IV: %s", format_hex(iv_buf, iv_size, 0, &gc)); @@ -245,7 +242,7 @@ openvpn_encrypt_v1(struct buffer *buf, struct buffer work, ASSERT(buf_inc_len(&work, outlen)); /* For all CBC mode ciphers, check the last block is complete */ - ASSERT(cipher_kt_mode(cipher_kt) != OPENVPN_MODE_CBC + ASSERT(cipher_ctx_mode(ctx->cipher) != OPENVPN_MODE_CBC || outlen == iv_size); } else /* No Encryption */ @@ -301,10 +298,7 @@ openvpn_encrypt(struct buffer *buf, struct buffer work, { if (buf->len > 0 && opt) { - const cipher_kt_t *cipher_kt = - cipher_ctx_get_cipher_kt(opt->key_ctx_bi.encrypt.cipher); - - if (cipher_kt_mode_aead(cipher_kt)) + if (cipher_ctx_mode_aead(opt->key_ctx_bi.encrypt.cipher)) { openvpn_encrypt_aead(buf, work, opt); } @@ -360,9 +354,7 @@ openvpn_decrypt_aead(struct buffer *buf, struct buffer work, static const char error_prefix[] = "AEAD Decrypt error"; struct packet_id_net pin = { 0 }; const struct key_ctx *ctx = &opt->key_ctx_bi.decrypt; - const cipher_kt_t *cipher_kt = cipher_ctx_get_cipher_kt(ctx->cipher); uint8_t *tag_ptr = NULL; - int tag_size = 0; int outlen; struct gc_arena gc; @@ -372,14 +364,13 @@ openvpn_decrypt_aead(struct buffer *buf, struct buffer work, ASSERT(frame); ASSERT(buf->len > 0); ASSERT(ctx->cipher); - ASSERT(cipher_kt_mode_aead(cipher_kt)); dmsg(D_PACKET_CONTENT, "DECRYPT FROM: %s", format_hex(BPTR(buf), BLEN(buf), 80, &gc)); ASSERT(ad_start >= buf->data && ad_start <= BPTR(buf)); - ASSERT(buf_init(&work, FRAME_HEADROOM_ADJ(frame, FRAME_HEADROOM_MARKER_DECRYPT))); + ASSERT(buf_init(&work, frame->buf.headroom)); /* IV and Packet ID required for this mode */ ASSERT(packet_id_initialized(&opt->packet_id)); @@ -415,7 +406,7 @@ openvpn_decrypt_aead(struct buffer *buf, struct buffer work, } /* keep the tag value to feed in later */ - tag_size = cipher_kt_tag_size(cipher_kt); + const int tag_size = OPENVPN_AEAD_TAG_LENGTH; if (buf->len < tag_size) { CRYPT_ERROR("missing tag"); @@ -538,12 +529,11 @@ openvpn_decrypt_v1(struct buffer *buf, struct buffer work, if (ctx->cipher) { const int iv_size = cipher_ctx_iv_length(ctx->cipher); - const cipher_kt_t *cipher_kt = cipher_ctx_get_cipher_kt(ctx->cipher); uint8_t iv_buf[OPENVPN_MAX_IV_LENGTH] = { 0 }; int outlen; - /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */ - ASSERT(buf_init(&work, FRAME_HEADROOM_ADJ(frame, FRAME_HEADROOM_MARKER_DECRYPT))); + /* initialize work buffer with buf.headroom bytes of prepend capacity */ + ASSERT(buf_init(&work, frame->buf.headroom)); /* read the IV from the packet */ if (buf->len < iv_size) @@ -590,7 +580,7 @@ openvpn_decrypt_v1(struct buffer *buf, struct buffer work, /* Get packet ID from plaintext buffer or IV, depending on cipher mode */ { - if (cipher_kt_mode_cbc(cipher_kt)) + if (cipher_ctx_mode_cbc(ctx->cipher)) { if (packet_id_initialized(&opt->packet_id)) { @@ -601,7 +591,7 @@ openvpn_decrypt_v1(struct buffer *buf, struct buffer work, have_pin = true; } } - else if (cipher_kt_mode_ofb_cfb(cipher_kt)) + else if (cipher_ctx_mode_ofb_cfb(ctx->cipher)) { struct buffer b; @@ -661,8 +651,7 @@ openvpn_decrypt(struct buffer *buf, struct buffer work, if (buf->len > 0 && opt) { - const struct key_ctx *ctx = &opt->key_ctx_bi.decrypt; - if (cipher_kt_mode_aead(cipher_ctx_get_cipher_kt(ctx->cipher))) + if (cipher_ctx_mode_aead(opt->key_ctx_bi.decrypt.cipher)) { ret = openvpn_decrypt_aead(buf, work, opt, frame, ad_start); } @@ -678,38 +667,53 @@ openvpn_decrypt(struct buffer *buf, struct buffer work, return ret; } -void -crypto_adjust_frame_parameters(struct frame *frame, - const struct key_type *kt, - bool packet_id, - bool packet_id_long_form) +unsigned int +calculate_crypto_overhead(const struct key_type *kt, + unsigned int pkt_id_size, + bool occ) { unsigned int crypto_overhead = 0; - if (packet_id) + if (!cipher_kt_mode_cbc(kt->cipher)) { - crypto_overhead += packet_id_size(packet_id_long_form); + /* In CBC mode, the packet id is part of the payload size/overhead */ + crypto_overhead += pkt_id_size; } - if (kt->cipher) + if (cipher_kt_mode_aead(kt->cipher)) { - crypto_overhead += cipher_kt_iv_size(kt->cipher); + /* For AEAD ciphers, we basically use a stream cipher/CTR for + * the encryption, so no overhead apart from the extra bytes + * we add */ + crypto_overhead += cipher_kt_tag_size(kt->cipher); - if (cipher_kt_mode_aead(kt->cipher)) + if (occ) { - crypto_overhead += cipher_kt_tag_size(kt->cipher); + /* the frame calculation of old clients adds these to the link-mtu + * even though they are not part of the actual packet */ + crypto_overhead += cipher_kt_iv_size(kt->cipher); + crypto_overhead += cipher_kt_block_size(kt->cipher); + } + } + else + { + if (cipher_defined(kt->cipher)) + { + /* CBC, OFB or CFB mode */ + if (occ) + { + crypto_overhead += cipher_kt_block_size(kt->cipher); + } + /* IV is always added (no-iv has been removed a while ago) */ + crypto_overhead += cipher_kt_iv_size(kt->cipher); + } + if (md_defined(kt->digest)) + { + crypto_overhead += md_kt_size(kt->digest); } - - /* extra block required by cipher_ctx_update() */ - crypto_overhead += cipher_kt_block_size(kt->cipher); } - crypto_overhead += kt->hmac_length; - - frame_add_to_extra_frame(frame, crypto_overhead); - - msg(D_MTU_DEBUG, "%s: Adjusting frame parameters for crypto by %u bytes", - __func__, crypto_overhead); + return crypto_overhead; } unsigned int @@ -721,16 +725,16 @@ crypto_max_overhead(void) } static void -warn_insecure_key_type(const char *ciphername, const cipher_kt_t *cipher) +warn_insecure_key_type(const char *ciphername) { - if (cipher_kt_insecure(cipher)) + if (cipher_kt_insecure(ciphername)) { msg(M_WARN, "WARNING: INSECURE cipher (%s) with block size less than 128" " bit (%d bit). This allows attacks like SWEET32. Mitigate by " "using a --cipher with a larger block size (e.g. AES-256-CBC). " "Support for these insecure ciphers will be removed in " "OpenVPN 2.7.", - ciphername, cipher_kt_block_size(cipher)*8); + ciphername, cipher_kt_block_size(ciphername)*8); } } @@ -739,7 +743,7 @@ warn_insecure_key_type(const char *ciphername, const cipher_kt_t *cipher) */ void init_key_type(struct key_type *kt, const char *ciphername, - const char *authname, int keysize, bool tls_mode, bool warn) + const char *authname, bool tls_mode, bool warn) { bool aead_cipher = false; @@ -747,20 +751,14 @@ init_key_type(struct key_type *kt, const char *ciphername, ASSERT(authname); CLEAR(*kt); + kt->cipher = ciphername; if (strcmp(ciphername, "none") != 0) { - kt->cipher = cipher_kt_get(ciphername); - if (!kt->cipher) + if (!cipher_valid(ciphername)) { msg(M_FATAL, "Cipher %s not supported", ciphername); } - kt->cipher_length = cipher_kt_key_size(kt->cipher); - if (keysize > 0 && keysize <= MAX_CIPHER_KEY_LENGTH) - { - kt->cipher_length = keysize; - } - /* check legal cipher mode */ aead_cipher = cipher_kt_mode_aead(kt->cipher); if (!(cipher_kt_mode_cbc(kt->cipher) @@ -779,7 +777,7 @@ init_key_type(struct key_type *kt, const char *ciphername, } if (warn) { - warn_insecure_key_type(ciphername, kt->cipher); + warn_insecure_key_type(ciphername); } } else @@ -792,14 +790,18 @@ init_key_type(struct key_type *kt, const char *ciphername, "PLEASE DO RECONSIDER THIS SETTING!"); } } + kt->digest = authname; if (strcmp(authname, "none") != 0) { - if (!aead_cipher) /* Ignore auth for AEAD ciphers */ + if (aead_cipher) /* Ignore auth for AEAD ciphers */ + { + kt->digest = "none"; + } + else { - kt->digest = md_kt_get(authname); - kt->hmac_length = md_kt_size(kt->digest); + int hmac_length = md_kt_size(kt->digest); - if (OPENVPN_MAX_HMAC_SIZE < kt->hmac_length) + if (OPENVPN_MAX_HMAC_SIZE < hmac_length) { msg(M_FATAL, "HMAC '%s' not allowed: digest size too big.", authname); } @@ -826,37 +828,34 @@ init_key_ctx(struct key_ctx *ctx, const struct key *key, { struct gc_arena gc = gc_new(); CLEAR(*ctx); - if (kt->cipher && kt->cipher_length > 0) + if (cipher_defined(kt->cipher)) { ctx->cipher = cipher_ctx_new(); - cipher_ctx_init(ctx->cipher, key->cipher, kt->cipher_length, - kt->cipher, enc); + cipher_ctx_init(ctx->cipher, key->cipher, kt->cipher, enc); const char *ciphername = cipher_kt_name(kt->cipher); msg(D_HANDSHAKE, "%s: Cipher '%s' initialized with %d bit key", - prefix, - ciphername, - kt->cipher_length *8); + prefix, ciphername, cipher_kt_key_size(kt->cipher) * 8); dmsg(D_SHOW_KEYS, "%s: CIPHER KEY: %s", prefix, - format_hex(key->cipher, kt->cipher_length, 0, &gc)); + format_hex(key->cipher, cipher_kt_key_size(kt->cipher), 0, &gc)); dmsg(D_CRYPTO_DEBUG, "%s: CIPHER block_size=%d iv_size=%d", prefix, cipher_kt_block_size(kt->cipher), cipher_kt_iv_size(kt->cipher)); - warn_insecure_key_type(ciphername, kt->cipher); + warn_insecure_key_type(ciphername); } - if (kt->digest && kt->hmac_length > 0) + if (md_defined(kt->digest)) { ctx->hmac = hmac_ctx_new(); - hmac_ctx_init(ctx->hmac, key->hmac, kt->hmac_length, kt->digest); + hmac_ctx_init(ctx->hmac, key->hmac, kt->digest); msg(D_HANDSHAKE, "%s: Using %d bit message hash '%s' for HMAC authentication", prefix, md_kt_size(kt->digest) * 8, md_kt_name(kt->digest)); dmsg(D_SHOW_KEYS, "%s: HMAC KEY: %s", prefix, - format_hex(key->hmac, kt->hmac_length, 0, &gc)); + format_hex(key->hmac, md_kt_size(kt->digest), 0, &gc)); dmsg(D_CRYPTO_DEBUG, "%s: HMAC size=%d block_size=%d", prefix, @@ -914,8 +913,8 @@ free_key_ctx_bi(struct key_ctx_bi *ctx) static bool key_is_zero(struct key *key, const struct key_type *kt) { - int i; - for (i = 0; i < kt->cipher_length; ++i) + int cipher_length = cipher_kt_key_size(kt->cipher); + for (int i = 0; i < cipher_length; ++i) { if (key->cipher[i]) { @@ -932,7 +931,7 @@ key_is_zero(struct key *key, const struct key_type *kt) bool check_key(struct key *key, const struct key_type *kt) { - if (kt->cipher) + if (cipher_defined(kt->cipher)) { /* * Check for zero key @@ -941,64 +940,10 @@ check_key(struct key *key, const struct key_type *kt) { return false; } - - /* - * Check for weak or semi-weak DES keys. - */ - { - const int ndc = key_des_num_cblocks(kt->cipher); - if (ndc) - { - return key_des_check(key->cipher, kt->cipher_length, ndc); - } - else - { - return true; - } - } } return true; } -/* - * Make safe mutations to key to ensure it is valid, - * such as ensuring correct parity on DES keys. - * - * This routine cannot guarantee it will generate a good - * key. You must always call check_key after this routine - * to make sure. - */ -void -fixup_key(struct key *key, const struct key_type *kt) -{ - struct gc_arena gc = gc_new(); - if (kt->cipher) - { -#ifdef ENABLE_DEBUG - const struct key orig = *key; -#endif - const int ndc = key_des_num_cblocks(kt->cipher); - - if (ndc) - { - key_des_fixup(key->cipher, kt->cipher_length, ndc); - } - -#ifdef ENABLE_DEBUG - if (check_debug_level(D_CRYPTO_DEBUG)) - { - if (memcmp(orig.cipher, key->cipher, kt->cipher_length)) - { - dmsg(D_CRYPTO_DEBUG, "CRYPTO INFO: fixup_key: before=%s after=%s", - format_hex(orig.cipher, kt->cipher_length, 0, &gc), - format_hex(key->cipher, kt->cipher_length, 0, &gc)); - } - } -#endif - } - gc_free(&gc); -} - void check_replay_consistency(const struct key_type *kt, bool packet_id) { @@ -1028,14 +973,13 @@ generate_key_random(struct key *key, const struct key_type *kt) CLEAR(*key); if (kt) { - if (kt->cipher && kt->cipher_length > 0 && kt->cipher_length <= cipher_len) - { - cipher_len = kt->cipher_length; - } + cipher_len = cipher_kt_key_size(kt->cipher); - if (kt->digest && kt->hmac_length > 0 && kt->hmac_length <= hmac_len) + int kt_hmac_length = md_kt_size(kt->digest); + + if (kt->digest && kt_hmac_length > 0 && kt_hmac_length <= hmac_len) { - hmac_len = kt->hmac_length; + hmac_len = kt_hmac_length; } } if (!rand_bytes(key->cipher, cipher_len) @@ -1047,17 +991,27 @@ generate_key_random(struct key *key, const struct key_type *kt) dmsg(D_SHOW_KEY_SOURCE, "Cipher source entropy: %s", format_hex(key->cipher, cipher_len, 0, &gc)); dmsg(D_SHOW_KEY_SOURCE, "HMAC source entropy: %s", format_hex(key->hmac, hmac_len, 0, &gc)); - if (kt) - { - fixup_key(key, kt); - } } while (kt && !check_key(key, kt)); gc_free(&gc); } -/* - * Print key material +static void +key_print(const struct key *key, + const struct key_type *kt, + const char *prefix) +{ + struct gc_arena gc = gc_new(); + dmsg(D_SHOW_KEY_SOURCE, "%s (cipher, %s, %d bits): %s", + prefix, cipher_kt_name(kt->cipher), cipher_kt_key_size(kt->cipher) * 8, + format_hex(key->cipher, cipher_kt_key_size(kt->cipher), 0, &gc)); + dmsg(D_SHOW_KEY_SOURCE, "%s (hmac, %s, %d bits): %s", + prefix, md_kt_name(kt->digest), md_kt_size(kt->digest) * 8, + format_hex(key->hmac, md_kt_size(kt->digest), 0, &gc)); + gc_free(&gc); +} +/** + * Prints the keys in a key2 structure. */ void key2_print(const struct key2 *k, @@ -1065,21 +1019,9 @@ key2_print(const struct key2 *k, const char *prefix0, const char *prefix1) { - struct gc_arena gc = gc_new(); ASSERT(k->n == 2); - dmsg(D_SHOW_KEY_SOURCE, "%s (cipher): %s", - prefix0, - format_hex(k->keys[0].cipher, kt->cipher_length, 0, &gc)); - dmsg(D_SHOW_KEY_SOURCE, "%s (hmac): %s", - prefix0, - format_hex(k->keys[0].hmac, kt->hmac_length, 0, &gc)); - dmsg(D_SHOW_KEY_SOURCE, "%s (cipher): %s", - prefix1, - format_hex(k->keys[1].cipher, kt->cipher_length, 0, &gc)); - dmsg(D_SHOW_KEY_SOURCE, "%s (hmac): %s", - prefix1, - format_hex(k->keys[1].hmac, kt->hmac_length, 0, &gc)); - gc_free(&gc); + key_print(&k->keys[0], kt, prefix0); + key_print(&k->keys[1], kt, prefix1); } void @@ -1087,7 +1029,7 @@ test_crypto(struct crypto_options *co, struct frame *frame) { int i, j; struct gc_arena gc = gc_new(); - struct buffer src = alloc_buf_gc(TUN_MTU_SIZE(frame), &gc); + struct buffer src = alloc_buf_gc(frame->buf.payload_size, &gc); struct buffer work = alloc_buf_gc(BUF_SIZE(frame), &gc); struct buffer encrypt_workspace = alloc_buf_gc(BUF_SIZE(frame), &gc); struct buffer decrypt_workspace = alloc_buf_gc(BUF_SIZE(frame), &gc); @@ -1095,18 +1037,16 @@ test_crypto(struct crypto_options *co, struct frame *frame) void *buf_p; /* init work */ - ASSERT(buf_init(&work, FRAME_HEADROOM(frame))); + ASSERT(buf_init(&work, frame->buf.headroom)); /* init implicit IV */ { - const cipher_kt_t *cipher = - cipher_ctx_get_cipher_kt(co->key_ctx_bi.encrypt.cipher); - - if (cipher_kt_mode_aead(cipher)) + cipher_ctx_t *cipher = co->key_ctx_bi.encrypt.cipher; + if (cipher_ctx_mode_aead(cipher)) { - size_t impl_iv_len = cipher_kt_iv_size(cipher) - sizeof(packet_id_type); - ASSERT(cipher_kt_iv_size(cipher) <= OPENVPN_MAX_IV_LENGTH); - ASSERT(cipher_kt_iv_size(cipher) >= OPENVPN_AEAD_MIN_IV_LEN); + size_t impl_iv_len = cipher_ctx_iv_length(cipher) - sizeof(packet_id_type); + ASSERT(cipher_ctx_iv_length(cipher) <= OPENVPN_MAX_IV_LENGTH); + ASSERT(cipher_ctx_iv_length(cipher) >= OPENVPN_AEAD_MIN_IV_LEN); /* Generate dummy implicit IV */ ASSERT(rand_bytes(co->key_ctx_bi.encrypt.implicit_iv, @@ -1120,7 +1060,7 @@ test_crypto(struct crypto_options *co, struct frame *frame) } msg(M_INFO, "Entering " PACKAGE_NAME " crypto self-test mode."); - for (i = 1; i <= TUN_MTU_SIZE(frame); ++i) + for (i = 1; i <= frame->buf.payload_size; ++i) { update_time(); @@ -1140,8 +1080,8 @@ test_crypto(struct crypto_options *co, struct frame *frame) ASSERT(buf_p); memcpy(buf_p, BPTR(&src), BLEN(&src)); - /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */ - ASSERT(buf_init(&encrypt_workspace, FRAME_HEADROOM(frame))); + /* initialize work buffer with buf.headroom bytes of prepend capacity */ + ASSERT(buf_init(&encrypt_workspace, frame->buf.headroom)); /* encrypt */ openvpn_encrypt(&buf, encrypt_workspace, co); @@ -1360,6 +1300,7 @@ read_key_file(struct key2 *key2, const char *file, const unsigned int flags) } else if (isspace(c)) { + /* ignore white space characters */ } else { @@ -1593,9 +1534,6 @@ verify_fix_key2(struct key2 *key2, const struct key_type *kt, const char *shared for (i = 0; i < key2->n; ++i) { - /* Fix parity for DES keys and make sure not a weak key */ - fixup_key(&key2->keys[i], kt); - /* This should be a very improbable failure */ if (!check_key(&key2->keys[i], kt)) { @@ -1610,22 +1548,26 @@ bool write_key(const struct key *key, const struct key_type *kt, struct buffer *buf) { - ASSERT(kt->cipher_length <= MAX_CIPHER_KEY_LENGTH - && kt->hmac_length <= MAX_HMAC_KEY_LENGTH); + ASSERT(cipher_kt_key_size(kt->cipher) <= MAX_CIPHER_KEY_LENGTH + && md_kt_size(kt->digest) <= MAX_HMAC_KEY_LENGTH); - if (!buf_write(buf, &kt->cipher_length, 1)) + const uint8_t cipher_length = cipher_kt_key_size(kt->cipher); + if (!buf_write(buf, &cipher_length, 1)) { return false; } - if (!buf_write(buf, &kt->hmac_length, 1)) + + uint8_t hmac_length = md_kt_size(kt->digest); + + if (!buf_write(buf, &hmac_length, 1)) { return false; } - if (!buf_write(buf, key->cipher, kt->cipher_length)) + if (!buf_write(buf, key->cipher, cipher_kt_key_size(kt->cipher))) { return false; } - if (!buf_write(buf, key->hmac, kt->hmac_length)) + if (!buf_write(buf, key->hmac, hmac_length)) { return false; } @@ -1655,7 +1597,7 @@ read_key(struct key *key, const struct key_type *kt, struct buffer *buf) goto read_err; } - if (cipher_length != kt->cipher_length || hmac_length != kt->hmac_length) + if (cipher_length != cipher_kt_key_size(kt->cipher) || hmac_length != md_kt_size(kt->digest)) { goto key_len_err; } @@ -1678,100 +1620,14 @@ read_key(struct key *key, const struct key_type *kt, struct buffer *buf) key_len_err: msg(D_TLS_ERRORS, "TLS Error: key length mismatch, local cipher/hmac %d/%d, remote cipher/hmac %d/%d", - kt->cipher_length, kt->hmac_length, cipher_length, hmac_length); + cipher_kt_key_size(kt->cipher), md_kt_size(kt->digest), cipher_length, hmac_length); return 0; } -/* - * Random number functions, used in cases where we want - * reasonably strong cryptographic random number generation - * without depleting our entropy pool. Used for random - * IV values and a number of other miscellaneous tasks. - */ - -static uint8_t *nonce_data = NULL; /* GLOBAL */ -static const md_kt_t *nonce_md = NULL; /* GLOBAL */ -static int nonce_secret_len = 0; /* GLOBAL */ - -/* Reset the nonce value, also done periodically to refresh entropy */ -static void -prng_reset_nonce(void) -{ - const int size = md_kt_size(nonce_md) + nonce_secret_len; -#if 1 /* Must be 1 for real usage */ - if (!rand_bytes(nonce_data, size)) - { - msg(M_FATAL, "ERROR: Random number generator cannot obtain entropy for PRNG"); - } -#else - /* Only for testing -- will cause a predictable PRNG sequence */ - { - int i; - for (i = 0; i < size; ++i) - { - nonce_data[i] = (uint8_t) i; - } - } -#endif -} - -void -prng_init(const char *md_name, const int nonce_secret_len_parm) -{ - prng_uninit(); - nonce_md = md_name ? md_kt_get(md_name) : NULL; - if (nonce_md) - { - ASSERT(nonce_secret_len_parm >= NONCE_SECRET_LEN_MIN && nonce_secret_len_parm <= NONCE_SECRET_LEN_MAX); - nonce_secret_len = nonce_secret_len_parm; - { - const int size = md_kt_size(nonce_md) + nonce_secret_len; - dmsg(D_CRYPTO_DEBUG, "PRNG init md=%s size=%d", md_kt_name(nonce_md), size); - nonce_data = (uint8_t *) malloc(size); - check_malloc_return(nonce_data); - prng_reset_nonce(); - } - } -} - -void -prng_uninit(void) -{ - free(nonce_data); - nonce_data = NULL; - nonce_md = NULL; - nonce_secret_len = 0; -} - void prng_bytes(uint8_t *output, int len) { - static size_t processed = 0; - - if (nonce_md) - { - const int md_size = md_kt_size(nonce_md); - while (len > 0) - { - const int blen = min_int(len, md_size); - md_full(nonce_md, nonce_data, md_size + nonce_secret_len, nonce_data); - memcpy(output, nonce_data, blen); - output += blen; - len -= blen; - - /* Ensure that random data is reset regularly */ - processed += blen; - if (processed > PRNG_NONCE_RESET_BYTES) - { - prng_reset_nonce(); - processed = 0; - } - } - } - else - { - ASSERT(rand_bytes(output, len)); - } + ASSERT(rand_bytes(output, len)); } /* an analogue to the random() function, but use prng_bytes */ @@ -1788,29 +1644,32 @@ get_random(void) } void -print_cipher(const cipher_kt_t *cipher) +print_cipher(const char *ciphername) { - const char *var_key_size = cipher_kt_var_key_size(cipher) ? - " by default" : ""; + printf("%s (%d bit key, ", + cipher_kt_name(ciphername), + cipher_kt_key_size(ciphername) * 8); - printf("%s (%d bit key%s, ", - cipher_kt_name(cipher), - cipher_kt_key_size(cipher) * 8, var_key_size); - - if (cipher_kt_block_size(cipher) == 1) + if (cipher_kt_block_size(ciphername) == 1) { printf("stream cipher"); } else { - printf("%d bit block", cipher_kt_block_size(cipher) * 8); + printf("%d bit block", cipher_kt_block_size(ciphername) * 8); } - if (!cipher_kt_mode_cbc(cipher)) + if (!cipher_kt_mode_cbc(ciphername)) { printf(", TLS client/server mode only"); } + const char *reason; + if (!cipher_valid_reason(ciphername, &reason)) + { + printf(", %s", reason); + } + printf(")\n"); } @@ -1954,4 +1813,4 @@ read_pem_key_file(struct buffer *key, const char *pem_name, } gc_free(&gc); return ret; -} +} \ No newline at end of file diff --git a/src/openvpn/crypto.h b/src/openvpn/crypto.h index ffb446925bb..b3bd9cb8f69 100644 --- a/src/openvpn/crypto.h +++ b/src/openvpn/crypto.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * Copyright (C) 2010-2021 Fox Crypto B.V. * * This program is free software; you can redistribute it and/or modify @@ -138,10 +138,8 @@ struct sha256_digest { */ struct key_type { - uint8_t cipher_length; /**< Cipher length, in bytes */ - uint8_t hmac_length; /**< HMAC length, in bytes */ - const cipher_kt_t *cipher; /**< Cipher static parameters */ - const md_kt_t *digest; /**< Message digest static parameters */ + const char *cipher; /**< const name of the cipher */ + const char *digest; /**< Message digest static parameters */ }; /** @@ -254,6 +252,23 @@ struct crypto_options #define CO_MUTE_REPLAY_WARNINGS (1<<2) /**< Bit-flag indicating not to display * replay warnings. */ +#define CO_USE_TLS_KEY_MATERIAL_EXPORT (1<<3) + /**< Bit-flag indicating that data channel key derivation + * is done using TLS keying material export [RFC5705] + */ +#define CO_RESEND_WKC (1<<4) + /**< Bit-flag indicating that the client is expected to + * resend the wrapped client key with the 2nd packet (packet-id 1) + * like with the HARD_RESET_CLIENT_V3 packet */ +#define CO_FORCE_TLSCRYPTV2_COOKIE (1<<5) + /**< Bit-flag indicating that we do not allow clients that do + * not support resending the wrapped client key (WKc) with the + * third packet of the three-way handshake */ +#define CO_USE_CC_EXIT_NOTIFY (1<<6) + /**< Bit-flag indicating that explicit exit notifies should be + * sent via the control channel instead of using an OCC message + */ + unsigned int flags; /**< Bit-flags determining behavior of * security operation functions. */ }; @@ -284,8 +299,6 @@ void check_replay_consistency(const struct key_type *kt, bool packet_id); bool check_key(struct key *key, const struct key_type *kt); -void fixup_key(struct key *key, const struct key_type *kt); - bool write_key(const struct key *key, const struct key_type *kt, struct buffer *buf); @@ -297,14 +310,12 @@ int read_key(struct key *key, const struct key_type *kt, struct buffer *buf); * @param kt The struct key_type to initialize * @param ciphername The name of the cipher to use * @param authname The name of the HMAC digest to use - * @param keysize The length of the cipher key to use, in bytes. Only valid - * for ciphers that support variable length keys. * @param tls_mode Specifies whether we are running in TLS mode, which allows * more ciphers than static key mode. * @param warn Print warnings when null cipher / auth is used. */ void init_key_type(struct key_type *kt, const char *ciphername, - const char *authname, int keysize, bool tls_mode, bool warn); + const char *authname, bool tls_mode, bool warn); /* * Key context functions @@ -417,6 +428,24 @@ void crypto_adjust_frame_parameters(struct frame *frame, bool packet_id, bool packet_id_long_form); +/** Calculate the maximum overhead that our encryption has + * on a packet. This does not include needed additional buffer size + * + * This does NOT include the padding and rounding of CBC size + * as the users (mssfix/fragment) of this function need to adjust for + * this and add it themselves. + * + * @param kt Struct with the crypto algorithm to use + * @param packet_id_size Size of the packet id, can be 0 if no-replay is used + * @param occ if true calculates the overhead for crypto in the same + * incorrect way as all previous OpenVPN versions did, to + * end up with identical numbers for OCC compatibility + */ +unsigned int +calculate_crypto_overhead(const struct key_type *kt, + unsigned int pkt_id_size, + bool occ); + /** Return the worst-case OpenVPN crypto overhead (in bytes) */ unsigned int crypto_max_overhead(void); @@ -454,24 +483,6 @@ bool read_pem_key_file(struct buffer *key, const char *pem_name, const char *key_file, bool key_inline); -/* Minimum length of the nonce used by the PRNG */ -#define NONCE_SECRET_LEN_MIN 16 - -/* Maximum length of the nonce used by the PRNG */ -#define NONCE_SECRET_LEN_MAX 64 - -/** Number of bytes of random to allow before resetting the nonce */ -#define PRNG_NONCE_RESET_BYTES 1024 - -/** - * Pseudo-random number generator initialisation. - * (see \c prng_rand_bytes()) - * - * @param md_name Name of the message digest to use - * @param nonce_secret_len_param Length of the nonce to use - */ -void prng_init(const char *md_name, const int nonce_secret_len_parm); - /* * Message digest-based pseudo random number generator. * @@ -489,13 +500,11 @@ void prng_init(const char *md_name, const int nonce_secret_len_parm); */ void prng_bytes(uint8_t *output, int len); -void prng_uninit(void); - /* an analogue to the random() function, but use prng_bytes */ long int get_random(void); /** Print a cipher list entry */ -void print_cipher(const cipher_kt_t *cipher); +void print_cipher(const char *cipher); void test_crypto(struct crypto_options *co, struct frame *f); @@ -551,4 +560,35 @@ key_ctx_bi_defined(const struct key_ctx_bi *key) */ const char *print_key_filename(const char *str, bool is_inline); -#endif /* CRYPTO_H */ +/** + * Creates and validates an instance of struct key_type with the provided + * algs. + * + * @param cipher the cipher algorithm to use (must be a string literal) + * @param md the digest algorithm to use (must be a string literal) + * @param optname the name of the option requiring the key_type object + * + * @return the initialized key_type instance + */ +static inline struct key_type +create_kt(const char *cipher, const char *md, const char *optname) +{ + struct key_type kt; + kt.cipher = cipher; + kt.digest = md; + + if (cipher_defined(kt.cipher) && !cipher_valid(kt.cipher)) + { + msg(M_WARN, "ERROR: --%s requires %s support.", optname, kt.cipher); + return (struct key_type) { 0 }; + } + if (md_defined(kt.digest) && !md_valid(kt.digest)) + { + msg(M_WARN, "ERROR: --%s requires %s support.", optname, kt.digest); + return (struct key_type) { 0 }; + } + + return kt; +} + +#endif /* CRYPTO_H */ \ No newline at end of file diff --git a/src/openvpn/crypto_backend.h b/src/openvpn/crypto_backend.h index aebda3d6515..90df8f14029 100644 --- a/src/openvpn/crypto_backend.h +++ b/src/openvpn/crypto_backend.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * Copyright (C) 2010-2021 Fox Crypto B.V. * * This program is free software; you can redistribute it and/or modify @@ -103,18 +103,6 @@ void crypto_init_dmalloc(void); #endif /* DMALLOC */ -/** - * Translate a data channel cipher name from the OpenVPN config file - * 'language' to the crypto library specific name. - */ -const char *translate_cipher_name_from_openvpn(const char *cipher_name); - -/** - * Translate a data channel cipher name from the crypto library specific name - * to the OpenVPN config file 'language'. - */ -const char *translate_cipher_name_from_openvpn(const char *cipher_name); - void show_available_ciphers(void); void show_available_digests(void); @@ -169,43 +157,6 @@ bool crypto_pem_decode(const char *name, struct buffer *dst, */ int rand_bytes(uint8_t *output, int len); -/* - * - * Key functions, allow manipulation of keys. - * - */ - - -/** - * Return number of DES cblocks (1 cblock = length of a single-DES key) for the - * current key type or 0 if not a DES cipher. - * - * @param kt Type of key - * - * @return Number of DES cblocks that the key consists of, or 0. - */ -int key_des_num_cblocks(const cipher_kt_t *kt); - -/* - * Check the given DES key. Checks the given key's length, weakness and parity. - * - * @param key Key to check - * @param key_len Length of the key, in bytes - * @param ndc Number of DES cblocks that the key is made up of. - * - * @return \c true if the key is valid, \c false otherwise. - */ -bool key_des_check(uint8_t *key, int key_len, int ndc); - -/* - * Fix the given DES key, setting its parity to odd. - * - * @param key Key to check - * @param key_len Length of the key, in bytes - * @param ndc Number of DES cblocks that the key is made up of. - */ -void key_des_fixup(uint8_t *key, int key_len, int ndc); - /** * Encrypt the given block, using DES ECB mode * @@ -237,114 +188,136 @@ void cipher_des_encrypt_ecb(const unsigned char key[DES_KEY_LENGTH], #define MAX_CIPHER_KEY_LENGTH 64 /** - * Return cipher parameters, based on the given cipher name. The - * contents of these parameters are library-specific, and can be used to - * initialise encryption/decryption. + * Returns if the cipher is valid, based on the given cipher name and provides a + * reason if invalid. + * + * @param ciphername Name of the cipher to check for validity (e.g. + * \c AES-128-CBC). Will be translated to the library name + * from the openvpn config name if needed. + * @param reason Pointer where a static string indicating the reason + * for rejecting the cipher should be stored. It is set to + * NULL if the cipher is valid. + * + * @return if the cipher is valid + */ +bool cipher_valid_reason(const char *ciphername, const char **reason); + +/** + * Returns if the cipher is valid, based on the given cipher name. * - * @param ciphername Name of the cipher to retrieve parameters for (e.g. + * @param ciphername Name of the cipher to check for validity (e.g. * \c AES-128-CBC). Will be translated to the library name * from the openvpn config name if needed. * - * @return A statically allocated structure containing parameters - * for the given cipher, or NULL if no matching parameters - * were found. + * @return if the cipher is valid + */ +static inline bool +cipher_valid(const char *ciphername) +{ + const char *reason; + return cipher_valid_reason(ciphername, &reason); +} + +/** + * Checks if the cipher is defined and is not the null (none) cipher + * + * @param ciphername Name of the cipher to check if it is defined, may not + * be NULL + * @return The cipher is defined and not the null (none) cipher */ -const cipher_kt_t *cipher_kt_get(const char *ciphername); +static inline bool +cipher_defined(const char *ciphername) +{ + ASSERT(ciphername); + return strcmp(ciphername, "none") != 0; +} /** - * Retrieve a string describing the cipher (e.g. \c AES-128-CBC). + * Retrieve a normalised string describing the cipher (e.g. \c AES-128-CBC). * The returned name is normalised to the OpenVPN config name in case the * name differs from the name used by the crypto library. * - * Returns [null-cipher] in case the cipher_kt is NULL. + * Returns [null-cipher] in case the ciphername is none. NULL if the cipher + * is not valid. * - * @param cipher_kt Static cipher parameters + * @param ciphername Name of the cipher * * @return a statically allocated string describing the cipher. */ -const char *cipher_kt_name(const cipher_kt_t *cipher_kt); +const char *cipher_kt_name(const char *ciphername); /** * Returns the size of keys used by the cipher, in bytes. If the cipher has a * variable key size, return the default key size. * - * @param cipher_kt Static cipher parameters + * @param ciphername Cipher name to lookup * * @return (Default) size of keys used by the cipher, in bytes. */ -int cipher_kt_key_size(const cipher_kt_t *cipher_kt); +int cipher_kt_key_size(const char *ciphername); /** * Returns the size of the IV used by the cipher, in bytes, or 0 if no IV is * used. * - * @param cipher_kt Static cipher parameters + * @param ciphername cipher name to lookup * * @return Size of the IV, in bytes, or 0 if the cipher does not * use an IV. */ -int cipher_kt_iv_size(const cipher_kt_t *cipher_kt); +int cipher_kt_iv_size(const char *ciphername); /** * Returns the block size of the cipher, in bytes. * - * @param cipher_kt Static cipher parameters + * @param ciphername cipher name * * @return Block size, in bytes. */ -int cipher_kt_block_size(const cipher_kt_t *cipher_kt); +int cipher_kt_block_size(const char *ciphername); /** * Returns the MAC tag size of the cipher, in bytes. * - * @param ctx Static cipher parameters. + * @param ciphername Name of the cipher * * @return Tag size in bytes, or 0 if the tag size could not be * determined. */ -int cipher_kt_tag_size(const cipher_kt_t *cipher_kt); +int cipher_kt_tag_size(const char *ciphername); /** * Returns true if we consider this cipher to be insecure. */ -bool cipher_kt_insecure(const cipher_kt_t *cipher); +bool cipher_kt_insecure(const char *ciphername); -/** - * Returns the mode that the cipher runs in. - * - * @param cipher_kt Static cipher parameters. May not be NULL. - * - * @return Cipher mode, either \c OPENVPN_MODE_CBC, \c - * OPENVPN_MODE_OFB or \c OPENVPN_MODE_CFB - */ -int cipher_kt_mode(const cipher_kt_t *cipher_kt); /** * Check if the supplied cipher is a supported CBC mode cipher. * - * @param cipher Static cipher parameters. + * @param ciphername cipher name * * @return true iff the cipher is a CBC mode cipher. */ -bool cipher_kt_mode_cbc(const cipher_kt_t *cipher); +bool cipher_kt_mode_cbc(const char *ciphername); /** * Check if the supplied cipher is a supported OFB or CFB mode cipher. * - * @param cipher Static cipher parameters. + * @param ciphername cipher name * * @return true iff the cipher is a OFB or CFB mode cipher. */ -bool cipher_kt_mode_ofb_cfb(const cipher_kt_t *cipher); +bool cipher_kt_mode_ofb_cfb(const char *ciphername); /** * Check if the supplied cipher is a supported AEAD mode cipher. * - * @param cipher Static cipher parameters. + * @param ciphername name of the cipher * * @return true iff the cipher is a AEAD mode cipher. */ -bool cipher_kt_mode_aead(const cipher_kt_t *cipher); +bool cipher_kt_mode_aead(const char *ciphername); /** @@ -372,13 +345,12 @@ void cipher_ctx_free(cipher_ctx_t *ctx); * * @param ctx Cipher context. May not be NULL * @param key Buffer containing the key to use - * @param key_len Length of the key, in bytes - * @param kt Static cipher parameters to use + * @param ciphername Ciphername of the cipher to use * @param enc Whether to encrypt or decrypt (either * \c MBEDTLS_OP_ENCRYPT or \c MBEDTLS_OP_DECRYPT). */ -void cipher_ctx_init(cipher_ctx_t *ctx, const uint8_t *key, int key_len, - const cipher_kt_t *kt, int enc); +void cipher_ctx_init(cipher_ctx_t *ctx, const uint8_t *key, + const char *cipername, int enc); /** * Returns the size of the IV used by the cipher, in bytes, or 0 if no IV is @@ -387,7 +359,7 @@ void cipher_ctx_init(cipher_ctx_t *ctx, const uint8_t *key, int key_len, * @param ctx The cipher's context * * @return Size of the IV, in bytes, or \c 0 if the cipher does not - * use an IV or ctx was NULL. + * use an IV. */ int cipher_ctx_iv_length(const cipher_ctx_t *ctx); @@ -420,14 +392,31 @@ int cipher_ctx_block_size(const cipher_ctx_t *ctx); int cipher_ctx_mode(const cipher_ctx_t *ctx); /** - * Returns the static cipher parameters for this context. + * Check if the supplied cipher is a supported CBC mode cipher. * - * @param ctx Cipher's context. + * @param ctx Cipher's context. May not be NULL. * - * @return Static cipher parameters for the supplied context, or - * NULL if unable to determine cipher parameters. + * @return true iff the cipher is a CBC mode cipher. */ -const cipher_kt_t *cipher_ctx_get_cipher_kt(const cipher_ctx_t *ctx); +bool cipher_ctx_mode_cbc(const cipher_ctx_t *ctx); + +/** + * Check if the supplied cipher is a supported OFB or CFB mode cipher. + * + * @param ctx Cipher's context. May not be NULL. + * + * @return true iff the cipher is a OFB or CFB mode cipher. + */ +bool cipher_ctx_mode_ofb_cfb(const cipher_ctx_t *ctx); + +/** + * Check if the supplied cipher is a supported AEAD mode cipher. + * + * @param ctx Cipher's context. May not be NULL. + * + * @return true iff the cipher is a AEAD mode cipher. + */ +bool cipher_ctx_mode_aead(const cipher_ctx_t *ctx); /** * Resets the given cipher context, setting the IV to the specified value. @@ -517,36 +506,45 @@ int cipher_ctx_final_check_tag(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len, #define MAX_HMAC_KEY_LENGTH 64 /** - * Return message digest parameters, based on the given digest name. The - * contents of these parameters are library-specific, and can be used to - * initialise HMAC or message digest operations. + * Checks if the cipher is defined and is not the null (none) cipher + * + * @param mdname Name of the digest + * @return + */ +static inline bool +md_defined(const char *mdname) +{ + return strcmp(mdname, "none") != 0; +} + + +/** + * Return if a message digest parameters is valid given the name of the digest. * - * @param digest Name of the digest to retrieve parameters for (e.g. - * \c MD5). + * @param digest Name of the digest to verify, e.g. \c MD5). * - * @return A statically allocated structure containing parameters - * for the given message digest. + * @return Whether a digest of the given name is available */ -const md_kt_t *md_kt_get(const char *digest); +bool md_valid(const char *digest); /** * Retrieve a string describing the digest digest (e.g. \c SHA1). * - * @param kt Static message digest parameters + * @param mdname Message digest name * * @return Statically allocated string describing the message * digest. */ -const char *md_kt_name(const md_kt_t *kt); +const char *md_kt_name(const char *mdname); /** * Returns the size of the message digest, in bytes. * - * @param kt Static message digest parameters + * @param mdname Message digest name * * @return Message digest size, in bytes, or 0 if ctx was NULL. */ -unsigned char md_kt_size(const md_kt_t *kt); +unsigned char md_kt_size(const char *mdname); /* @@ -555,17 +553,17 @@ unsigned char md_kt_size(const md_kt_t *kt); * */ -/* +/** * Calculates the message digest for the given buffer. * - * @param kt Static message digest parameters + * @param mdname message digest name * @param src Buffer to digest. May not be NULL. * @param src_len The length of the incoming buffer. * @param dst Buffer to write the message digest to. May not be NULL. * * @return \c 1 on success, \c 0 on failure */ -int md_full(const md_kt_t *kt, const uint8_t *src, int src_len, uint8_t *dst); +int md_full(const char *mdname, const uint8_t *src, int src_len, uint8_t *dst); /* * Allocate a new message digest context @@ -581,13 +579,13 @@ md_ctx_t *md_ctx_new(void); */ void md_ctx_free(md_ctx_t *ctx); -/* +/** * Initialises the given message digest context. * * @param ctx Message digest context - * @param kt Static message digest parameters + * @param mdname Message digest name */ -void md_ctx_init(md_ctx_t *ctx, const md_kt_t *kt); +void md_ctx_init(md_ctx_t *ctx, const char *mdname); /* * Free the given message digest context. @@ -649,12 +647,11 @@ void hmac_ctx_free(hmac_ctx_t *ctx); * * @param ctx HMAC context to initialise * @param key The key to use for the HMAC - * @param key_len The key length to use - * @param kt Static message digest parameters + * @param mdname message digest name * */ -void hmac_ctx_init(hmac_ctx_t *ctx, const uint8_t *key, int key_length, - const md_kt_t *kt); +void hmac_ctx_init(hmac_ctx_t *ctx, const uint8_t *key, const char *mdname); + /* * Free the given HMAC context. @@ -670,7 +667,7 @@ void hmac_ctx_cleanup(hmac_ctx_t *ctx); * * @return Size of the HMAC, or \0 if ctx is NULL. */ -int hmac_ctx_size(const hmac_ctx_t *ctx); +int hmac_ctx_size(hmac_ctx_t *ctx); /* * Resets the given HMAC context, preserving the associated key information @@ -716,4 +713,21 @@ const char *translate_cipher_name_from_openvpn(const char *cipher_name); */ const char *translate_cipher_name_to_openvpn(const char *cipher_name); -#endif /* CRYPTO_BACKEND_H_ */ + +/** + * Calculates the TLS 1.0-1.1 PRF function. For the exact specification of the + * function definition see the TLS RFCs like RFC 4346. + * + * @param seed seed to use + * @param seed_len length of the seed + * @param secret secret to use + * @param secret_len length of the secret + * @param output output destination + * @param output_len length of output/number of bytes to generate + * + * @return true if successful, false on any error + */ +bool ssl_tls1_PRF(const uint8_t *seed, int seed_len, const uint8_t *secret, + int secret_len, uint8_t *output, int output_len); + +#endif /* CRYPTO_BACKEND_H_ */ \ No newline at end of file diff --git a/src/openvpn/crypto_mbedtls.c b/src/openvpn/crypto_mbedtls.c index 000815209c9..5e67a8a3517 100644 --- a/src/openvpn/crypto_mbedtls.c +++ b/src/openvpn/crypto_mbedtls.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * Copyright (C) 2010-2021 Fox Crypto B.V. * * This program is free software; you can redistribute it and/or modify @@ -50,10 +50,10 @@ #include #include #include -#include #include #include +#include /* @@ -69,7 +69,8 @@ crypto_init_lib_engine(const char *engine_name) "available"); } -provider_t *crypto_load_provider(const char *provider) +provider_t * +crypto_load_provider(const char *provider) { if (provider) { @@ -78,7 +79,8 @@ provider_t *crypto_load_provider(const char *provider) return NULL; } -void crypto_unload_provider(const char *provname, provider_t *provider) +void +crypto_unload_provider(const char *provname, provider_t *provider) { } @@ -169,11 +171,11 @@ show_available_ciphers(void) while (*ciphers != 0) { - const cipher_kt_t *info = mbedtls_cipher_info_from_type(*ciphers); - if (info && !cipher_kt_insecure(info) - && (cipher_kt_mode_aead(info) || cipher_kt_mode_cbc(info))) + const mbedtls_cipher_info_t *info = mbedtls_cipher_info_from_type(*ciphers); + if (info && !cipher_kt_insecure(info->name) + && (cipher_kt_mode_aead(info->name) || cipher_kt_mode_cbc(info->name))) { - print_cipher(info); + print_cipher(info->name); } ciphers++; } @@ -183,11 +185,11 @@ show_available_ciphers(void) ciphers = mbedtls_cipher_list(); while (*ciphers != 0) { - const cipher_kt_t *info = mbedtls_cipher_info_from_type(*ciphers); - if (info && cipher_kt_insecure(info) - && (cipher_kt_mode_aead(info) || cipher_kt_mode_cbc(info))) + const mbedtls_cipher_info_t *info = mbedtls_cipher_info_from_type(*ciphers); + if (info && cipher_kt_insecure(info->name) + && (cipher_kt_mode_aead(info->name) || cipher_kt_mode_cbc(info->name))) { - print_cipher(info); + print_cipher(info->name); } ciphers++; } @@ -387,105 +389,33 @@ rand_bytes(uint8_t *output, int len) /* * - * Key functions, allow manipulation of keys. + * Generic cipher key type functions * */ - - -int -key_des_num_cblocks(const mbedtls_cipher_info_t *kt) -{ - int ret = 0; - if (kt->type == MBEDTLS_CIPHER_DES_CBC) - { - ret = 1; - } - if (kt->type == MBEDTLS_CIPHER_DES_EDE_CBC) - { - ret = 2; - } - if (kt->type == MBEDTLS_CIPHER_DES_EDE3_CBC) - { - ret = 3; - } - - dmsg(D_CRYPTO_DEBUG, "CRYPTO INFO: n_DES_cblocks=%d", ret); - return ret; -} - -bool -key_des_check(uint8_t *key, int key_len, int ndc) +static const mbedtls_cipher_info_t * +cipher_get(const char *ciphername) { - int i; - struct buffer b; - - buf_set_read(&b, key, key_len); - - for (i = 0; i < ndc; ++i) - { - unsigned char *key = buf_read_alloc(&b, MBEDTLS_DES_KEY_SIZE); - if (!key) - { - msg(D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: insufficient key material"); - goto err; - } - if (0 != mbedtls_des_key_check_weak(key)) - { - msg(D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: weak key detected"); - goto err; - } - if (0 != mbedtls_des_key_check_key_parity(key)) - { - msg(D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: bad parity detected"); - goto err; - } - } - return true; - -err: - return false; -} + ASSERT(ciphername); -void -key_des_fixup(uint8_t *key, int key_len, int ndc) -{ - int i; - struct buffer b; + const mbedtls_cipher_info_t *cipher = NULL; - buf_set_read(&b, key, key_len); - for (i = 0; i < ndc; ++i) - { - unsigned char *key = buf_read_alloc(&b, MBEDTLS_DES_KEY_SIZE); - if (!key) - { - msg(D_CRYPT_ERRORS, "CRYPTO INFO: fixup_key_DES: insufficient key material"); - return; - } - mbedtls_des_key_set_parity(key); - } + ciphername = translate_cipher_name_from_openvpn(ciphername); + cipher = mbedtls_cipher_info_from_string(ciphername); + return cipher; } -/* - * - * Generic cipher key type functions - * - */ - - -const mbedtls_cipher_info_t * -cipher_kt_get(const char *ciphername) +bool +cipher_valid_reason(const char *ciphername, const char **reason) { - const mbedtls_cipher_info_t *cipher = NULL; - - ASSERT(ciphername); + ASSERT(reason); - ciphername = translate_cipher_name_from_openvpn(ciphername); - cipher = mbedtls_cipher_info_from_string(ciphername); + const mbedtls_cipher_info_t *cipher = cipher_get(ciphername); if (NULL == cipher) { msg(D_LOW, "Cipher algorithm '%s' not found", ciphername); - return NULL; + *reason = "disabled because unknown"; + return false; } if (cipher->key_bitlen/8 > MAX_CIPHER_KEY_LENGTH) @@ -493,15 +423,18 @@ cipher_kt_get(const char *ciphername) msg(D_LOW, "Cipher algorithm '%s' uses a default key size (%d bytes) " "which is larger than " PACKAGE_NAME "'s current maximum key size " "(%d bytes)", ciphername, cipher->key_bitlen/8, MAX_CIPHER_KEY_LENGTH); - return NULL; + *reason = "disabled due to key size too large"; + return false; } - return cipher; + *reason = NULL; + return true; } const char * -cipher_kt_name(const mbedtls_cipher_info_t *cipher_kt) +cipher_kt_name(const char *ciphername) { + const mbedtls_cipher_info_t *cipher_kt = cipher_get(ciphername); if (NULL == cipher_kt) { return "[null-cipher]"; @@ -511,8 +444,10 @@ cipher_kt_name(const mbedtls_cipher_info_t *cipher_kt) } int -cipher_kt_key_size(const mbedtls_cipher_info_t *cipher_kt) +cipher_kt_key_size(const char *ciphername) { + const mbedtls_cipher_info_t *cipher_kt = cipher_get(ciphername); + if (NULL == cipher_kt) { return 0; @@ -522,8 +457,10 @@ cipher_kt_key_size(const mbedtls_cipher_info_t *cipher_kt) } int -cipher_kt_iv_size(const mbedtls_cipher_info_t *cipher_kt) +cipher_kt_iv_size(const char *ciphername) { + const mbedtls_cipher_info_t *cipher_kt = cipher_get(ciphername); + if (NULL == cipher_kt) { return 0; @@ -532,8 +469,9 @@ cipher_kt_iv_size(const mbedtls_cipher_info_t *cipher_kt) } int -cipher_kt_block_size(const mbedtls_cipher_info_t *cipher_kt) +cipher_kt_block_size(const char *ciphername) { + const mbedtls_cipher_info_t *cipher_kt = cipher_get(ciphername); if (NULL == cipher_kt) { return 0; @@ -542,9 +480,9 @@ cipher_kt_block_size(const mbedtls_cipher_info_t *cipher_kt) } int -cipher_kt_tag_size(const mbedtls_cipher_info_t *cipher_kt) +cipher_kt_tag_size(const char *ciphername) { - if (cipher_kt && cipher_kt_mode_aead(cipher_kt)) + if (cipher_kt_mode_aead(ciphername)) { return OPENVPN_AEAD_TAG_LENGTH; } @@ -552,16 +490,22 @@ cipher_kt_tag_size(const mbedtls_cipher_info_t *cipher_kt) } bool -cipher_kt_insecure(const mbedtls_cipher_info_t *cipher_kt) +cipher_kt_insecure(const char *ciphername) { - return !(cipher_kt_block_size(cipher_kt) >= 128 / 8 + const mbedtls_cipher_info_t *cipher_kt = cipher_get(ciphername); + if (!cipher_kt) + { + return true; + } + + return !(cipher_kt_block_size(ciphername) >= 128 / 8 #ifdef MBEDTLS_CHACHAPOLY_C || cipher_kt->type == MBEDTLS_CIPHER_CHACHA20_POLY1305 #endif ); } -int +static int cipher_kt_mode(const mbedtls_cipher_info_t *cipher_kt) { ASSERT(NULL != cipher_kt); @@ -569,21 +513,24 @@ cipher_kt_mode(const mbedtls_cipher_info_t *cipher_kt) } bool -cipher_kt_mode_cbc(const cipher_kt_t *cipher) +cipher_kt_mode_cbc(const char *ciphername) { + const mbedtls_cipher_info_t *cipher = cipher_get(ciphername); return cipher && cipher_kt_mode(cipher) == OPENVPN_MODE_CBC; } bool -cipher_kt_mode_ofb_cfb(const cipher_kt_t *cipher) +cipher_kt_mode_ofb_cfb(const char *ciphername) { + const mbedtls_cipher_info_t *cipher = cipher_get(ciphername); return cipher && (cipher_kt_mode(cipher) == OPENVPN_MODE_OFB || cipher_kt_mode(cipher) == OPENVPN_MODE_CFB); } bool -cipher_kt_mode_aead(const cipher_kt_t *cipher) +cipher_kt_mode_aead(const char *ciphername) { + const mbedtls_cipher_info_t *cipher = cipher_get(ciphername); return cipher && (cipher_kt_mode(cipher) == OPENVPN_MODE_GCM #ifdef MBEDTLS_CHACHAPOLY_C || cipher_kt_mode(cipher) == MBEDTLS_MODE_CHACHAPOLY @@ -614,13 +561,17 @@ cipher_ctx_free(mbedtls_cipher_context_t *ctx) } void -cipher_ctx_init(mbedtls_cipher_context_t *ctx, const uint8_t *key, int key_len, - const mbedtls_cipher_info_t *kt, const mbedtls_operation_t operation) +cipher_ctx_init(mbedtls_cipher_context_t *ctx, const uint8_t *key, + const char *ciphername, const mbedtls_operation_t operation) { - ASSERT(NULL != kt && NULL != ctx); - + ASSERT(NULL != ciphername && NULL != ctx); CLEAR(*ctx); + const mbedtls_cipher_info_t *kt = cipher_get(ciphername); + int key_len = kt->key_bitlen/8; + + ASSERT(kt); + if (!mbed_ok(mbedtls_cipher_setup(ctx, kt))) { msg(M_FATAL, "mbed TLS cipher context init #1"); @@ -671,10 +622,28 @@ cipher_ctx_mode(const mbedtls_cipher_context_t *ctx) return cipher_kt_mode(ctx->cipher_info); } -const cipher_kt_t * -cipher_ctx_get_cipher_kt(const cipher_ctx_t *ctx) +bool +cipher_ctx_mode_cbc(const cipher_ctx_t *ctx) { - return ctx ? ctx->cipher_info : NULL; + return ctx && cipher_ctx_mode(ctx) == OPENVPN_MODE_CBC; +} + + +bool +cipher_ctx_mode_ofb_cfb(const cipher_ctx_t *ctx) +{ + return ctx && (cipher_ctx_mode(ctx) == OPENVPN_MODE_OFB + || cipher_ctx_mode(ctx) == OPENVPN_MODE_CFB); +} + +bool +cipher_ctx_mode_aead(const cipher_ctx_t *ctx) +{ + return ctx && (cipher_ctx_mode(ctx) == OPENVPN_MODE_GCM +#ifdef MBEDTLS_CHACHAPOLY_C + || cipher_ctx_mode(ctx) == MBEDTLS_MODE_CHACHAPOLY +#endif + ); } int @@ -780,8 +749,8 @@ cipher_ctx_final_check_tag(mbedtls_cipher_context_t *ctx, uint8_t *dst, void cipher_des_encrypt_ecb(const unsigned char key[DES_KEY_LENGTH], - unsigned char *src, - unsigned char *dst) + unsigned char src[DES_KEY_LENGTH], + unsigned char dst[DES_KEY_LENGTH]) { mbedtls_des_context ctx; @@ -798,8 +767,8 @@ cipher_des_encrypt_ecb(const unsigned char key[DES_KEY_LENGTH], */ -const mbedtls_md_info_t * -md_kt_get(const char *digest) +static const mbedtls_md_info_t * +md_get(const char *digest) { const mbedtls_md_info_t *md = NULL; ASSERT(digest); @@ -819,23 +788,32 @@ md_kt_get(const char *digest) return md; } +bool +md_valid(const char *digest) +{ + const mbedtls_md_info_t *md = mbedtls_md_info_from_string(digest); + return md != NULL; +} + const char * -md_kt_name(const mbedtls_md_info_t *kt) +md_kt_name(const char *mdname) { - if (NULL == kt) + if (!strcmp("none", mdname)) { return "[null-digest]"; } + const mbedtls_md_info_t *kt = md_get(mdname); return mbedtls_md_get_name(kt); } unsigned char -md_kt_size(const mbedtls_md_info_t *kt) +md_kt_size(const char *mdname) { - if (NULL == kt) + if (!strcmp("none", mdname)) { return 0; } + const mbedtls_md_info_t *kt = md_get(mdname); return mbedtls_md_get_size(kt); } @@ -846,8 +824,9 @@ md_kt_size(const mbedtls_md_info_t *kt) */ int -md_full(const md_kt_t *kt, const uint8_t *src, int src_len, uint8_t *dst) +md_full(const char *mdname, const uint8_t *src, int src_len, uint8_t *dst) { + const mbedtls_md_info_t *kt = md_get(mdname); return 0 == mbedtls_md(kt, src, src_len, dst); } @@ -866,8 +845,9 @@ md_ctx_free(mbedtls_md_context_t *ctx) } void -md_ctx_init(mbedtls_md_context_t *ctx, const mbedtls_md_info_t *kt) +md_ctx_init(mbedtls_md_context_t *ctx, const char *mdname) { + const mbedtls_md_info_t *kt = md_get(mdname); ASSERT(NULL != ctx && NULL != kt); mbedtls_md_init(ctx); @@ -931,12 +911,13 @@ hmac_ctx_free(mbedtls_md_context_t *ctx) } void -hmac_ctx_init(mbedtls_md_context_t *ctx, const uint8_t *key, int key_len, - const mbedtls_md_info_t *kt) +hmac_ctx_init(mbedtls_md_context_t *ctx, const uint8_t *key, const char *mdname) { + const mbedtls_md_info_t *kt = md_get(mdname); ASSERT(NULL != kt && NULL != ctx); mbedtls_md_init(ctx); + int key_len = mbedtls_md_get_size(kt); ASSERT(0 == mbedtls_md_setup(ctx, kt, 1)); ASSERT(0 == mbedtls_md_hmac_starts(ctx, key, key_len)); @@ -951,7 +932,7 @@ hmac_ctx_cleanup(mbedtls_md_context_t *ctx) } int -hmac_ctx_size(const mbedtls_md_context_t *ctx) +hmac_ctx_size(mbedtls_md_context_t *ctx) { if (NULL == ctx) { @@ -997,4 +978,144 @@ memcmp_constant_time(const void *a, const void *b, size_t size) return diff; } -#endif /* ENABLE_CRYPTO_MBEDTLS */ +/* mbedtls-2.18.0 or newer */ +#ifdef HAVE_MBEDTLS_SSL_TLS_PRF +bool +ssl_tls1_PRF(const uint8_t *seed, int seed_len, const uint8_t *secret, + int secret_len, uint8_t *output, int output_len) +{ + return mbed_ok(mbedtls_ssl_tls_prf(MBEDTLS_SSL_TLS_PRF_TLS1, secret, + secret_len, "", seed, seed_len, output, + output_len)); +} +#else /* ifdef HAVE_MBEDTLS_SSL_TLS_PRF */ +/* + * Generate the hash required by for the \c tls1_PRF function. + * + * @param md_kt Message digest to use + * @param sec Secret to base the hash on + * @param sec_len Length of the secret + * @param seed Seed to hash + * @param seed_len Length of the seed + * @param out Output buffer + * @param olen Length of the output buffer + */ +static void +tls1_P_hash(const mbedtls_md_info_t *md_kt, const uint8_t *sec, int sec_len, + const uint8_t *seed, int seed_len, uint8_t *out, int olen) +{ + struct gc_arena gc = gc_new(); + uint8_t A1[MAX_HMAC_KEY_LENGTH]; + +#ifdef ENABLE_DEBUG + /* used by the D_SHOW_KEY_SOURCE, guarded with ENABLE_DEBUG to avoid unused + * variables warnings if compiled with --enable-small */ + const int olen_orig = olen; + const uint8_t *out_orig = out; +#endif + + hmac_ctx_t *ctx = hmac_ctx_new(); + hmac_ctx_t *ctx_tmp = hmac_ctx_new(); + + dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash sec: %s", format_hex(sec, sec_len, 0, &gc)); + dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash seed: %s", format_hex(seed, seed_len, 0, &gc)); + + int chunk = mbedtls_md_get_size(md_kt); + unsigned int A1_len = mbedtls_md_get_size(md_kt); + + /* This is the only place where we init an HMAC with a key that is not + * equal to its size, therefore we init the hmac ctx manually here */ + mbedtls_md_init(ctx); + ASSERT(0 == mbedtls_md_setup(ctx, md_kt, 1)); + ASSERT(0 == mbedtls_md_hmac_starts(ctx, sec, sec_len)); + + mbedtls_md_init(ctx_tmp); + ASSERT(0 == mbedtls_md_setup(ctx_tmp, md_kt, 1)); + ASSERT(0 == mbedtls_md_hmac_starts(ctx_tmp, sec, sec_len)); + + hmac_ctx_update(ctx, seed, seed_len); + hmac_ctx_final(ctx, A1); + + for (;; ) + { + hmac_ctx_reset(ctx); + hmac_ctx_reset(ctx_tmp); + hmac_ctx_update(ctx, A1, A1_len); + hmac_ctx_update(ctx_tmp, A1, A1_len); + hmac_ctx_update(ctx, seed, seed_len); + + if (olen > chunk) + { + hmac_ctx_final(ctx, out); + out += chunk; + olen -= chunk; + hmac_ctx_final(ctx_tmp, A1); /* calc the next A1 value */ + } + else /* last one */ + { + hmac_ctx_final(ctx, A1); + memcpy(out, A1, olen); + break; + } + } + hmac_ctx_cleanup(ctx); + hmac_ctx_free(ctx); + hmac_ctx_cleanup(ctx_tmp); + hmac_ctx_free(ctx_tmp); + secure_memzero(A1, sizeof(A1)); + + dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash out: %s", format_hex(out_orig, olen_orig, 0, &gc)); + gc_free(&gc); +} + +/* + * Use the TLS PRF function for generating data channel keys. + * This code is based on the OpenSSL library. + * + * TLS generates keys as such: + * + * master_secret[48] = PRF(pre_master_secret[48], "master secret", + * ClientHello.random[32] + ServerHello.random[32]) + * + * key_block[] = PRF(SecurityParameters.master_secret[48], + * "key expansion", + * SecurityParameters.server_random[32] + + * SecurityParameters.client_random[32]); + * + * Notes: + * + * (1) key_block contains a full set of 4 keys. + * (2) The pre-master secret is generated by the client. + */ +bool +ssl_tls1_PRF(const uint8_t *label, int label_len, const uint8_t *sec, + int slen, uint8_t *out1, int olen) +{ + struct gc_arena gc = gc_new(); + const md_kt_t *md5 = md_get("MD5"); + const md_kt_t *sha1 = md_get("SHA1"); + + uint8_t *out2 = (uint8_t *)gc_malloc(olen, false, &gc); + + int len = slen/2; + const uint8_t *S1 = sec; + const uint8_t *S2 = &(sec[len]); + len += (slen&1); /* add for odd, make longer */ + + tls1_P_hash(md5, S1, len, label, label_len, out1, olen); + tls1_P_hash(sha1, S2, len, label, label_len, out2, olen); + + for (int i = 0; i + * Copyright (C) 2002-2023 OpenVPN Inc * Copyright (C) 2010-2021 Fox Crypto B.V. * * This program is free software; you can redistribute it and/or modify @@ -33,9 +33,6 @@ #include #include -/** Generic cipher key type %context. */ -typedef mbedtls_cipher_info_t cipher_kt_t; - /** Generic message digest key type %context. */ typedef mbedtls_md_info_t md_kt_t; @@ -149,10 +146,4 @@ mbed_log_func_line_lite(unsigned int flags, int errval, #define mbed_ok(errval) \ mbed_log_func_line_lite(D_CRYPT_ERRORS, errval, __func__, __LINE__) -static inline bool -cipher_kt_var_key_size(const cipher_kt_t *cipher) -{ - return cipher->flags & MBEDTLS_CIPHER_VARIABLE_KEY_LEN; -} - -#endif /* CRYPTO_MBEDTLS_H_ */ +#endif /* CRYPTO_MBEDTLS_H_ */ \ No newline at end of file diff --git a/src/openvpn/crypto_openssl.c b/src/openvpn/crypto_openssl.c index 7a05a352ad0..5c9a5555616 100644 --- a/src/openvpn/crypto_openssl.c +++ b/src/openvpn/crypto_openssl.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * Copyright (C) 2010-2021 Fox Crypto B.V. * * This program is free software; you can redistribute it and/or modify @@ -51,6 +51,9 @@ #include #include +#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER) +#include +#endif #if OPENSSL_VERSION_NUMBER >= 0x30000000L #include #endif @@ -59,6 +62,11 @@ #error Windows build with OPENSSL_NO_EC: disabling EC key is not supported. #endif +#ifdef _MSC_VER +/* mute ossl3 deprecation warnings treated as errors in msvc */ +#pragma warning(disable: 4996) +#endif + /* * Check for key size creepage. */ @@ -231,7 +239,7 @@ crypto_clear_error(void) void crypto_print_openssl_errors(const unsigned int flags) { - size_t err = 0; + unsigned long err = 0; while ((err = ERR_get_error())) { @@ -309,68 +317,85 @@ cipher_name_cmp(const void *a, const void *b) const EVP_CIPHER *const *cipher_a = a; const EVP_CIPHER *const *cipher_b = b; - return strcmp(cipher_kt_name(*cipher_a), cipher_kt_name(*cipher_b)); + return strcmp(EVP_CIPHER_get0_name(*cipher_a), EVP_CIPHER_get0_name(*cipher_b)); +} + +struct collect_ciphers { + /* If we ever exceed this, we must be more selective */ + const EVP_CIPHER *list[1000]; + size_t num; +}; + +static void +collect_ciphers(EVP_CIPHER *cipher, void *list) +{ + if (!cipher) + { + return; + } + struct collect_ciphers *cipher_list = list; + if (cipher_list->num == SIZE(cipher_list->list)) + { + msg(M_WARN, "WARNING: Too many ciphers, not showing all"); + return; + } + + const char *ciphername = EVP_CIPHER_get0_name(cipher); + + if (ciphername && (cipher_kt_mode_cbc(ciphername) +#ifdef ENABLE_OFB_CFB_MODE + || cipher_kt_mode_ofb_cfb(ciphername) +#endif + || cipher_kt_mode_aead(ciphername) + )) + { + cipher_list->list[cipher_list->num++] = cipher; + } } void show_available_ciphers(void) { - int nid; - size_t i; + struct collect_ciphers cipher_list = { 0 }; - /* If we ever exceed this, we must be more selective */ - const EVP_CIPHER *cipher_list[1000]; - size_t num_ciphers = 0; #ifndef ENABLE_SMALL printf("The following ciphers and cipher modes are available for use\n" "with " PACKAGE_NAME ". Each cipher shown below may be used as a\n" - "parameter to the --data-ciphers (or --cipher) option. The\n" - "default key size is shown as well as whether or not it can be\n" - "changed with the --keysize directive. Using a GCM or CBC mode\n" - "is recommended. In static key mode only CBC mode is allowed.\n\n"); + "parameter to the --data-ciphers (or --cipher) option. In static \n" + "key mode only CBC mode is allowed.\n"); + printf("See also openssl list -cipher-algorithms\n\n"); #endif - for (nid = 0; nid < 10000; ++nid) +#if OPENSSL_VERSION_NUMBER >= 0x30000000L + EVP_CIPHER_do_all_provided(NULL, collect_ciphers, &cipher_list); +#else + for (int nid = 0; nid < 10000; ++nid) { const EVP_CIPHER *cipher = EVP_get_cipherbynid(nid); - if (cipher && (cipher_kt_mode_cbc(cipher) -#ifdef ENABLE_OFB_CFB_MODE - || cipher_kt_mode_ofb_cfb(cipher) -#endif - || cipher_kt_mode_aead(cipher) - )) - { - /* Check explicit availibility (for OpenSSL 3.0) */ - if (cipher_kt_get(cipher_kt_name(cipher))) - { - cipher_list[num_ciphers++] = cipher; - } - } - if (num_ciphers == (sizeof(cipher_list)/sizeof(*cipher_list))) - { - msg(M_WARN, "WARNING: Too many ciphers, not showing all"); - break; - } + /* We cast the const away so we can keep the function prototype + * compatible with EVP_CIPHER_do_all_provided */ + collect_ciphers((EVP_CIPHER *) cipher, &cipher_list); } +#endif /* cast to non-const to prevent warning */ - qsort((EVP_CIPHER *)cipher_list, num_ciphers, sizeof(*cipher_list), cipher_name_cmp); + qsort((EVP_CIPHER *)cipher_list.list, cipher_list.num, sizeof(*cipher_list.list), cipher_name_cmp); - for (i = 0; i < num_ciphers; i++) + for (size_t i = 0; i < cipher_list.num; i++) { - if (!cipher_kt_insecure(cipher_list[i])) + if (!cipher_kt_insecure(EVP_CIPHER_get0_name(cipher_list.list[i]))) { - print_cipher(cipher_list[i]); + print_cipher(EVP_CIPHER_get0_name(cipher_list.list[i])); } } printf("\nThe following ciphers have a block size of less than 128 bits, \n" "and are therefore deprecated. Do not use unless you have to.\n\n"); - for (i = 0; i < num_ciphers; i++) + for (int i = 0; i < cipher_list.num; i++) { - if (cipher_kt_insecure(cipher_list[i])) + if (cipher_kt_insecure(EVP_CIPHER_get0_name(cipher_list.list[i]))) { - print_cipher(cipher_list[i]); + print_cipher(EVP_CIPHER_get0_name(cipher_list.list[i])); } } printf("\n"); @@ -379,27 +404,26 @@ show_available_ciphers(void) void print_digest(EVP_MD *digest, void *unused) { - printf("%s %d bit digest size\n", md_kt_name(digest), + printf("%s %d bit digest size\n", md_kt_name(EVP_MD_get0_name(digest)), EVP_MD_size(digest) * 8); } void show_available_digests(void) { - int nid; - #ifndef ENABLE_SMALL printf("The following message digests are available for use with\n" PACKAGE_NAME ". A message digest is used in conjunction with\n" "the HMAC function, to authenticate received packets.\n" "You can specify a message digest as parameter to\n" - "the --auth option.\n\n"); + "the --auth option.\n"); + printf("See also openssl list -digest-algorithms\n\n"); #endif #if OPENSSL_VERSION_NUMBER >= 0x30000000L EVP_MD_do_all_provided(NULL, print_digest, NULL); #else - for (nid = 0; nid < 10000; ++nid) + for (int nid = 0; nid < 10000; ++nid) { const EVP_MD *digest = EVP_get_digestbynid(nid); if (digest) @@ -409,8 +433,8 @@ show_available_digests(void) print_digest((EVP_MD *)digest, NULL); } } - printf("\n"); #endif + printf("\n"); } void @@ -541,164 +565,100 @@ rand_bytes(uint8_t *output, int len) /* * - * Key functions, allow manipulation of keys. + * Generic cipher key type functions * */ - -int -key_des_num_cblocks(const EVP_CIPHER *kt) +static evp_cipher_type * +cipher_get(const char *ciphername) { - int ret = 0; - const char *name = OBJ_nid2sn(EVP_CIPHER_nid(kt)); - if (name) - { - if (!strncmp(name, "DES-", 4)) - { - ret = EVP_CIPHER_key_length(kt) / sizeof(DES_cblock); - } - else if (!strncmp(name, "DESX-", 5)) - { - ret = 1; - } - } - dmsg(D_CRYPTO_DEBUG, "CRYPTO INFO: n_DES_cblocks=%d", ret); - return ret; -} - -bool -key_des_check(uint8_t *key, int key_len, int ndc) -{ - int i; - struct buffer b; - - buf_set_read(&b, key, key_len); - - for (i = 0; i < ndc; ++i) - { - DES_cblock *dc = (DES_cblock *) buf_read_alloc(&b, sizeof(DES_cblock)); - if (!dc) - { - crypto_msg(D_CRYPT_ERRORS, - "CRYPTO INFO: check_key_DES: insufficient key material"); - goto err; - } - if (DES_is_weak_key(dc)) - { - crypto_msg(D_CRYPT_ERRORS, - "CRYPTO INFO: check_key_DES: weak key detected"); - goto err; - } - if (!DES_check_key_parity(dc)) - { - crypto_msg(D_CRYPT_ERRORS, - "CRYPTO INFO: check_key_DES: bad parity detected"); - goto err; - } - } - return true; + ASSERT(ciphername); -err: - ERR_clear_error(); - return false; + ciphername = translate_cipher_name_from_openvpn(ciphername); + return EVP_CIPHER_fetch(NULL, ciphername, NULL); } -void -key_des_fixup(uint8_t *key, int key_len, int ndc) +bool +cipher_valid_reason(const char *ciphername, const char **reason) { - int i; - struct buffer b; - - buf_set_read(&b, key, key_len); - for (i = 0; i < ndc; ++i) + bool ret = false; + evp_cipher_type *cipher = cipher_get(ciphername); + if (!cipher) { - DES_cblock *dc = (DES_cblock *) buf_read_alloc(&b, sizeof(DES_cblock)); - if (!dc) - { - msg(D_CRYPT_ERRORS, "CRYPTO INFO: fixup_key_DES: insufficient key material"); - ERR_clear_error(); - return; - } - DES_set_odd_parity(dc); + crypto_msg(D_LOW, "Cipher algorithm '%s' not found", ciphername); + *reason = "disabled because unknown"; + goto out; } -} - - -/* - * - * Generic cipher key type functions - * - */ - - -const EVP_CIPHER * -cipher_kt_get(const char *ciphername) -{ - const EVP_CIPHER *cipher = NULL; - ASSERT(ciphername); - - ciphername = translate_cipher_name_from_openvpn(ciphername); - cipher = EVP_get_cipherbyname(ciphername); +#ifdef OPENSSL_FIPS + /* Rhel 8/CentOS 8 have a patched OpenSSL version that return a cipher + * here that is actually not usable if in FIPS mode */ - /* This is a workaround for OpenSSL 3.0 to infer if the cipher is valid - * without doing all the refactoring that OpenVPN 2.6 has. This will - * not support custom algorithm from providers but at least ignore - * algorithms that are not available without providers (legacy) */ -#if OPENSSL_VERSION_NUMBER >= 0x30000000L - EVP_CIPHER *tmpcipher = EVP_CIPHER_fetch(NULL, ciphername, NULL); - if (!tmpcipher) + if (FIPS_mode() && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_FIPS)) { - cipher = NULL; + msg(D_LOW, "Cipher algorithm '%s' is known by OpenSSL library but " + "currently disabled by running in FIPS mode.", ciphername); + *reason = "disabled by FIPS mode"; + goto out; } - EVP_CIPHER_free(tmpcipher); #endif - - if (NULL == cipher) - { - crypto_msg(D_LOW, "Cipher algorithm '%s' not found", ciphername); - return NULL; - } - - if (EVP_CIPHER_key_length(cipher) > MAX_CIPHER_KEY_LENGTH) { msg(D_LOW, "Cipher algorithm '%s' uses a default key size (%d bytes) " "which is larger than " PACKAGE_NAME "'s current maximum key size " "(%d bytes)", ciphername, EVP_CIPHER_key_length(cipher), MAX_CIPHER_KEY_LENGTH); - return NULL; + *reason = "disabled due to key size too large"; + goto out; } - return cipher; + ret = true; + *reason = NULL; +out: + EVP_CIPHER_free(cipher); + return ret; } const char * -cipher_kt_name(const EVP_CIPHER *cipher_kt) +cipher_kt_name(const char *ciphername) { - if (NULL == cipher_kt) + ASSERT(ciphername); + if (strcmp("none", ciphername) == 0) { return "[null-cipher]"; } + evp_cipher_type *cipher_kt = cipher_get(ciphername); + if (!cipher_kt) + { + return NULL; + } + const char *name = EVP_CIPHER_name(cipher_kt); + EVP_CIPHER_free(cipher_kt); return translate_cipher_name_to_openvpn(name); } int -cipher_kt_key_size(const EVP_CIPHER *cipher_kt) +cipher_kt_key_size(const char *ciphername) { - return EVP_CIPHER_key_length(cipher_kt); + evp_cipher_type *cipher = cipher_get(ciphername); + int size = EVP_CIPHER_key_length(cipher); + EVP_CIPHER_free(cipher); + return size; } int -cipher_kt_iv_size(const EVP_CIPHER *cipher_kt) +cipher_kt_iv_size(const char *ciphername) { - return EVP_CIPHER_iv_length(cipher_kt); + evp_cipher_type *cipher = cipher_get(ciphername); + int ivsize = EVP_CIPHER_iv_length(cipher); + EVP_CIPHER_free(cipher); + return ivsize; } int -cipher_kt_block_size(const EVP_CIPHER *cipher) +cipher_kt_block_size(const char *ciphername) { /* * OpenSSL reports OFB/CFB/GCM cipher block sizes as '1 byte'. To work @@ -709,7 +669,12 @@ cipher_kt_block_size(const EVP_CIPHER *cipher) char *name = NULL; char *mode_str = NULL; const char *orig_name = NULL; - const EVP_CIPHER *cbc_cipher = NULL; + evp_cipher_type *cbc_cipher = NULL; + evp_cipher_type *cipher = cipher_get(ciphername); + if (!cipher) + { + return 0; + } int block_size = EVP_CIPHER_block_size(cipher); @@ -728,21 +693,23 @@ cipher_kt_block_size(const EVP_CIPHER *cipher) strcpy(mode_str, "-CBC"); - cbc_cipher = EVP_get_cipherbyname(translate_cipher_name_from_openvpn(name)); + cbc_cipher = EVP_CIPHER_fetch(NULL, translate_cipher_name_from_openvpn(name), NULL); if (cbc_cipher) { block_size = EVP_CIPHER_block_size(cbc_cipher); } cleanup: + EVP_CIPHER_free(cbc_cipher); + EVP_CIPHER_free(cipher); free(name); return block_size; } int -cipher_kt_tag_size(const EVP_CIPHER *cipher_kt) +cipher_kt_tag_size(const char *ciphername) { - if (cipher_kt_mode_aead(cipher_kt)) + if (cipher_kt_mode_aead(ciphername)) { return OPENVPN_AEAD_TAG_LENGTH; } @@ -753,13 +720,26 @@ cipher_kt_tag_size(const EVP_CIPHER *cipher_kt) } bool -cipher_kt_insecure(const EVP_CIPHER *cipher) +cipher_kt_insecure(const char *ciphername) { - return !(cipher_kt_block_size(cipher) >= 128 / 8 + + if (cipher_kt_block_size(ciphername) >= 128 / 8) + { + return false; + } #ifdef NID_chacha20_poly1305 - || EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305 + evp_cipher_type *cipher = cipher_get(ciphername); + if (cipher) + { + bool ischachapoly = (EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305); + EVP_CIPHER_free(cipher); + if (ischachapoly) + { + return false; + } + } #endif - ); + return true; } int @@ -770,40 +750,56 @@ cipher_kt_mode(const EVP_CIPHER *cipher_kt) } bool -cipher_kt_mode_cbc(const cipher_kt_t *cipher) +cipher_kt_mode_cbc(const char *ciphername) { - return cipher && cipher_kt_mode(cipher) == OPENVPN_MODE_CBC - /* Exclude AEAD cipher modes, they require a different API */ - && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER); + evp_cipher_type *cipher = cipher_get(ciphername); + + bool ret = cipher && (cipher_kt_mode(cipher) == OPENVPN_MODE_CBC + /* Exclude AEAD cipher modes, they require a different API */ +#ifdef EVP_CIPH_FLAG_CTS + && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_CTS) +#endif + && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)); + EVP_CIPHER_free(cipher); + return ret; } bool -cipher_kt_mode_ofb_cfb(const cipher_kt_t *cipher) +cipher_kt_mode_ofb_cfb(const char *ciphername) { - return cipher && (cipher_kt_mode(cipher) == OPENVPN_MODE_OFB - || cipher_kt_mode(cipher) == OPENVPN_MODE_CFB) - /* Exclude AEAD cipher modes, they require a different API */ - && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER); + evp_cipher_type *cipher = cipher_get(ciphername); + bool ofb_cfb = cipher && (cipher_kt_mode(cipher) == OPENVPN_MODE_OFB + || cipher_kt_mode(cipher) == OPENVPN_MODE_CFB) + /* Exclude AEAD cipher modes, they require a different API */ + && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER); + EVP_CIPHER_free(cipher); + return ofb_cfb; } bool -cipher_kt_mode_aead(const cipher_kt_t *cipher) +cipher_kt_mode_aead(const char *ciphername) { + bool isaead = false; + + evp_cipher_type *cipher = cipher_get(ciphername); if (cipher) { - switch (EVP_CIPHER_nid(cipher)) + if (EVP_CIPHER_mode(cipher) == OPENVPN_MODE_GCM) { - case NID_aes_128_gcm: - case NID_aes_192_gcm: - case NID_aes_256_gcm: + isaead = true; + } + #ifdef NID_chacha20_poly1305 - case NID_chacha20_poly1305: -#endif - return true; + if (EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305) + { + isaead = true; } +#endif } - return false; + EVP_CIPHER_free(cipher); + + return isaead; } /* @@ -827,29 +823,25 @@ cipher_ctx_free(EVP_CIPHER_CTX *ctx) } void -cipher_ctx_init(EVP_CIPHER_CTX *ctx, const uint8_t *key, int key_len, - const EVP_CIPHER *kt, int enc) +cipher_ctx_init(EVP_CIPHER_CTX *ctx, const uint8_t *key, + const char *ciphername, int enc) { - ASSERT(NULL != kt && NULL != ctx); + ASSERT(NULL != ciphername && NULL != ctx); + evp_cipher_type *kt = cipher_get(ciphername); EVP_CIPHER_CTX_reset(ctx); if (!EVP_CipherInit(ctx, kt, NULL, NULL, enc)) { crypto_msg(M_FATAL, "EVP cipher init #1"); } -#ifdef HAVE_EVP_CIPHER_CTX_SET_KEY_LENGTH - if (!EVP_CIPHER_CTX_set_key_length(ctx, key_len)) - { - crypto_msg(M_FATAL, "EVP set key size"); - } -#endif if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, NULL, enc)) { crypto_msg(M_FATAL, "EVP cipher init #2"); } + EVP_CIPHER_free(kt); /* make sure we used a big enough key */ - ASSERT(EVP_CIPHER_CTX_key_length(ctx) <= key_len); + ASSERT(EVP_CIPHER_CTX_key_length(ctx) <= EVP_CIPHER_key_length(kt)); } int @@ -861,7 +853,7 @@ cipher_ctx_iv_length(const EVP_CIPHER_CTX *ctx) int cipher_ctx_get_tag(EVP_CIPHER_CTX *ctx, uint8_t *tag_buf, int tag_size) { - return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, tag_size, tag_buf); + return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, tag_size, tag_buf); } int @@ -876,10 +868,61 @@ cipher_ctx_mode(const EVP_CIPHER_CTX *ctx) return EVP_CIPHER_CTX_mode(ctx); } -const cipher_kt_t * -cipher_ctx_get_cipher_kt(const cipher_ctx_t *ctx) + +bool +cipher_ctx_mode_cbc(const cipher_ctx_t *ctx) +{ + if (!ctx) + { + return false; + } + + int flags = EVP_CIPHER_CTX_flags(ctx); + int mode = EVP_CIPHER_CTX_mode(ctx); + + return mode == EVP_CIPH_CBC_MODE + /* Exclude AEAD cipher modes, they require a different API */ +#ifdef EVP_CIPH_FLAG_CTS + && !(flags & EVP_CIPH_FLAG_CTS) +#endif + && !(flags & EVP_CIPH_FLAG_AEAD_CIPHER); +} + +bool +cipher_ctx_mode_ofb_cfb(const cipher_ctx_t *ctx) +{ + if (!ctx) + { + return false; + } + + int mode = EVP_CIPHER_CTX_get_mode(ctx); + + return (mode == EVP_CIPH_OFB_MODE || mode == EVP_CIPH_CFB_MODE) + /* Exclude AEAD cipher modes, they require a different API */ + && !(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_FLAG_AEAD_CIPHER); +} + +bool +cipher_ctx_mode_aead(const cipher_ctx_t *ctx) { - return ctx ? EVP_CIPHER_CTX_cipher(ctx) : NULL; + if (ctx) + { + int flags = EVP_CIPHER_CTX_flags(ctx); + if (flags & EVP_CIPH_FLAG_AEAD_CIPHER) + { + return true; + } + +#if defined(NID_chacha20_poly1305) && OPENSSL_VERSION_NUMBER < 0x30000000L + if (EVP_CIPHER_CTX_nid(ctx) == NID_chacha20_poly1305) + { + return true; + } +#endif + } + + return false; } @@ -922,7 +965,7 @@ cipher_ctx_final_check_tag(EVP_CIPHER_CTX *ctx, uint8_t *dst, int *dst_len, uint8_t *tag, size_t tag_len) { ASSERT(tag_len < SIZE_MAX); - if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, tag_len, tag)) + if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tag_len, tag)) { return 0; } @@ -932,13 +975,47 @@ cipher_ctx_final_check_tag(EVP_CIPHER_CTX *ctx, uint8_t *dst, int *dst_len, void cipher_des_encrypt_ecb(const unsigned char key[DES_KEY_LENGTH], - unsigned char *src, - unsigned char *dst) + unsigned char src[DES_KEY_LENGTH], + unsigned char dst[DES_KEY_LENGTH]) { - DES_key_schedule sched; + /* We are using 3DES here with three times the same key to cheat + * and emulate DES as 3DES is better supported than DES */ + EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + if (!ctx) + { + crypto_msg(M_FATAL, "%s: EVP_CIPHER_CTX_new() failed", __func__); + } - DES_set_key_unchecked((DES_cblock *)key, &sched); - DES_ecb_encrypt((DES_cblock *)src, (DES_cblock *)dst, &sched, DES_ENCRYPT); + unsigned char key3[DES_KEY_LENGTH*3]; + for (int i = 0; i < 3; i++) + { + memcpy(key3 + (i * DES_KEY_LENGTH), key, DES_KEY_LENGTH); + } + + if (!EVP_EncryptInit_ex(ctx, EVP_des_ede3_ecb(), NULL, key3, NULL)) + { + crypto_msg(M_FATAL, "%s: EVP_EncryptInit_ex() failed", __func__); + } + + int len; + + /* The EVP_EncryptFinal method will write to the dst+len pointer even + * though there is nothing to encrypt anymore, provide space for that to + * not overflow the stack */ + unsigned char dst2[DES_KEY_LENGTH * 2]; + if (!EVP_EncryptUpdate(ctx, dst2, &len, src, DES_KEY_LENGTH)) + { + crypto_msg(M_FATAL, "%s: EVP_EncryptUpdate() failed", __func__); + } + + if (!EVP_EncryptFinal(ctx, dst2 + len, &len)) + { + crypto_msg(M_FATAL, "%s: EVP_EncryptFinal() failed", __func__); + } + + memcpy(dst, dst2, DES_KEY_LENGTH); + + EVP_CIPHER_CTX_free(ctx); } /* @@ -948,26 +1025,12 @@ cipher_des_encrypt_ecb(const unsigned char key[DES_KEY_LENGTH], */ -const EVP_MD * -md_kt_get(const char *digest) +static evp_md_type * +md_get(const char *digest) { - const EVP_MD *md = NULL; + evp_md_type *md = NULL; ASSERT(digest); - md = EVP_get_digestbyname(digest); - - /* This is a workaround for OpenSSL 3.0 to infer if the digest is valid - * without doing all the refactoring that OpenVPN 2.6 has. This will - * not support custom algorithm from providers but at least ignore - * algorithms that are not available without providers (legacy) */ -#if OPENSSL_VERSION_NUMBER >= 0x30000000L - EVP_MD *tmpmd = EVP_MD_fetch(NULL, digest, NULL); - if (!tmpmd) - { - md = NULL; - } - EVP_MD_free(tmpmd); -#endif - + md = EVP_MD_fetch(NULL, digest, NULL); if (!md) { crypto_msg(M_FATAL, "Message hash algorithm '%s' not found", digest); @@ -982,6 +1045,17 @@ md_kt_get(const char *digest) return md; } + +bool +md_valid(const char *digest) +{ + evp_md_type *md = EVP_MD_fetch(NULL, digest, NULL); + bool valid = (md != NULL); + EVP_MD_free(md); + return valid; +} + + /* Since we used the OpenSSL <=1.1 names as part of our OCC message, they * are now unfortunately part of our wire protocol. * @@ -1005,14 +1079,14 @@ const size_t digest_name_translation_table_count = sizeof(digest_name_translation_table) / sizeof(*digest_name_translation_table); const char * -md_kt_name(const EVP_MD *kt) +md_kt_name(const char *mdname) { - if (NULL == kt) + if (!strcmp("none", mdname)) { return "[null-digest]"; } - - const char *name = EVP_MD_name(kt); + evp_md_type *kt = md_get(mdname); + const char *name = EVP_MD_get0_name(kt); /* Search for a digest name translation */ for (size_t i = 0; i < digest_name_translation_table_count; i++) @@ -1024,13 +1098,21 @@ md_kt_name(const EVP_MD *kt) } } + EVP_MD_free(kt); return name; } unsigned char -md_kt_size(const EVP_MD *kt) +md_kt_size(const char *mdname) { - return (unsigned char)EVP_MD_size(kt); + if (!strcmp("none", mdname)) + { + return 0; + } + evp_md_type *kt = md_get(mdname); + unsigned char size = (unsigned char)EVP_MD_size(kt); + EVP_MD_free(kt); + return size; } @@ -1041,11 +1123,14 @@ md_kt_size(const EVP_MD *kt) */ int -md_full(const EVP_MD *kt, const uint8_t *src, int src_len, uint8_t *dst) +md_full(const char *mdname, const uint8_t *src, int src_len, uint8_t *dst) { unsigned int in_md_len = 0; + evp_md_type *kt = md_get(mdname); - return EVP_Digest(src, src_len, dst, &in_md_len, kt, NULL); + int ret = EVP_Digest(src, src_len, dst, &in_md_len, kt, NULL); + EVP_MD_free(kt); + return ret; } EVP_MD_CTX * @@ -1063,12 +1148,17 @@ md_ctx_free(EVP_MD_CTX *ctx) } void -md_ctx_init(EVP_MD_CTX *ctx, const EVP_MD *kt) +md_ctx_init(EVP_MD_CTX *ctx, const char *mdname) { + evp_md_type *kt = md_get(mdname); ASSERT(NULL != ctx && NULL != kt); EVP_MD_CTX_init(ctx); - EVP_DigestInit(ctx, kt); + if (!EVP_DigestInit(ctx, kt)) + { + crypto_msg(M_FATAL, "EVP_DigestInit failed"); + } + EVP_MD_free(kt); } void @@ -1103,7 +1193,7 @@ md_ctx_final(EVP_MD_CTX *ctx, uint8_t *dst) * Generic HMAC functions * */ - +#if OPENSSL_VERSION_NUMBER < 0x30000000L HMAC_CTX * hmac_ctx_new(void) { @@ -1119,13 +1209,17 @@ hmac_ctx_free(HMAC_CTX *ctx) } void -hmac_ctx_init(HMAC_CTX *ctx, const uint8_t *key, int key_len, - const EVP_MD *kt) +hmac_ctx_init(HMAC_CTX *ctx, const uint8_t *key, const char *mdname) { + evp_md_type *kt = md_get(mdname); ASSERT(NULL != kt && NULL != ctx); + int key_len = EVP_MD_size(kt); HMAC_CTX_reset(ctx); - HMAC_Init_ex(ctx, key, key_len, kt, NULL); + if (!HMAC_Init_ex(ctx, key, key_len, kt, NULL)) + { + crypto_msg(M_FATAL, "HMAC_Init_ex failed"); + } /* make sure we used a big enough key */ ASSERT(HMAC_size(ctx) <= key_len); @@ -1138,7 +1232,7 @@ hmac_ctx_cleanup(HMAC_CTX *ctx) } int -hmac_ctx_size(const HMAC_CTX *ctx) +hmac_ctx_size(HMAC_CTX *ctx) { return HMAC_size(ctx); } @@ -1146,7 +1240,10 @@ hmac_ctx_size(const HMAC_CTX *ctx) void hmac_ctx_reset(HMAC_CTX *ctx) { - HMAC_Init_ex(ctx, NULL, 0, NULL, NULL); + if (!HMAC_Init_ex(ctx, NULL, 0, NULL, NULL)) + { + crypto_msg(M_FATAL, "HMAC_Init_ex failed"); + } } void @@ -1162,6 +1259,99 @@ hmac_ctx_final(HMAC_CTX *ctx, uint8_t *dst) HMAC_Final(ctx, dst, &in_hmac_len); } +#else /* if OPENSSL_VERSION_NUMBER < 0x30000000L */ +hmac_ctx_t * +hmac_ctx_new(void) +{ + hmac_ctx_t *ctx; + ALLOC_OBJ_CLEAR(ctx, hmac_ctx_t); + EVP_MAC *hmac = EVP_MAC_fetch(NULL, "HMAC", NULL); + ctx->ctx = EVP_MAC_CTX_new(hmac); + check_malloc_return(ctx->ctx); + + EVP_MAC_free(hmac); + + return ctx; +} + +void +hmac_ctx_free(hmac_ctx_t *ctx) +{ + EVP_MAC_CTX_free(ctx->ctx); + secure_memzero(ctx, sizeof(hmac_ctx_t)); + free(ctx); +} + +void +hmac_ctx_init(hmac_ctx_t *ctx, const uint8_t *key, const char *mdname) +{ + evp_md_type *kt = md_get(mdname); + ASSERT(NULL != kt && NULL != ctx && ctx->ctx != NULL); + + /* We need to make a copy of the key since the OSSL parameters + * only reference it */ + memcpy(ctx->key, key, EVP_MD_size(kt)); + + /* Lookup/setting of parameters in OpenSSL 3.0 are string based + * + * The OSSL_PARAM_construct_utf8_string needs a non const str but this + * only used for lookup so we cast (as OpenSSL also does internally) + * the constness away here. + */ + ctx->params[0] = OSSL_PARAM_construct_utf8_string("digest", + (char *) EVP_MD_get0_name(kt), 0); + ctx->params[1] = OSSL_PARAM_construct_octet_string("key", + ctx->key, EVP_MD_size(kt)); + ctx->params[2] = OSSL_PARAM_construct_end(); + + if (!EVP_MAC_init(ctx->ctx, NULL, 0, ctx->params)) + { + crypto_msg(M_FATAL, "EVP_MAC_init failed"); + } + + EVP_MD_free(kt); +} + +void +hmac_ctx_cleanup(hmac_ctx_t *ctx) +{ + EVP_MAC_init(ctx->ctx, NULL, 0, NULL); +} + +int +hmac_ctx_size(hmac_ctx_t *ctx) +{ + return (int)EVP_MAC_CTX_get_mac_size(ctx->ctx); +} + +void +hmac_ctx_reset(hmac_ctx_t *ctx) +{ + /* The OpenSSL MAC API lacks a reset method and passing NULL as params + * does not reset it either, so use the params array to reinitialise it the + * same way as before */ + if (!EVP_MAC_init(ctx->ctx, NULL, 0, ctx->params)) + { + crypto_msg(M_FATAL, "EVP_MAC_init failed"); + } +} + +void +hmac_ctx_update(hmac_ctx_t *ctx, const uint8_t *src, int src_len) +{ + EVP_MAC_update(ctx->ctx, src, src_len); +} + +void +hmac_ctx_final(hmac_ctx_t *ctx, uint8_t *dst) +{ + /* The calling code always gives us a buffer that has the size of our + * algorithm */ + size_t in_hmac_len = EVP_MAC_CTX_get_mac_size(ctx->ctx); + + EVP_MAC_final(ctx->ctx, dst, &in_hmac_len, in_hmac_len); +} +#endif /* if OPENSSL_VERSION_NUMBER < 0x30000000L */ int memcmp_constant_time(const void *a, const void *b, size_t size) @@ -1229,4 +1419,230 @@ engine_load_key(const char *file, SSL_CTX *ctx) #endif /* if HAVE_OPENSSL_ENGINE */ } -#endif /* ENABLE_CRYPTO_OPENSSL */ +#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER) +bool +ssl_tls1_PRF(const uint8_t *seed, int seed_len, const uint8_t *secret, + int secret_len, uint8_t *output, int output_len) +{ + EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1_PRF, NULL); + if (!pctx) + { + return false; + } + + bool ret = false; + if (!EVP_PKEY_derive_init(pctx)) + { + goto out; + } + + if (!EVP_PKEY_CTX_set_tls1_prf_md(pctx, EVP_md5_sha1())) + { + goto out; + } + + if (!EVP_PKEY_CTX_set1_tls1_prf_secret(pctx, secret, secret_len)) + { + goto out; + } + + if (!EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed, seed_len)) + { + goto out; + } + + size_t out_len = output_len; + if (!EVP_PKEY_derive(pctx, output, &out_len)) + { + goto out; + } + if (out_len != output_len) + { + goto out; + } + ret = true; +out: + EVP_PKEY_CTX_free(pctx); + return ret; +} +#else /* if OPENSSL_VERSION_NUMBER >= 0x10100000L */ +/* + * Generate the hash required by for the \c tls1_PRF function. + * + * We cannot use our normal hmac_* function as they do not work + * in a FIPS environment (no MD5 allowed, which we need). Instead + * we need to directly use the EVP_MD_* API with the special + * EVP_MD_CTX_FLAG_NON_FIPS_ALLOW flag. + * + * The function below is adapted from OpenSSL 1.0.2t + * + * @param md_kt Message digest to use + * @param sec Secret to base the hash on + * @param sec_len Length of the secret + * @param seed Seed to hash + * @param seed_len Length of the seed + * @param out Output buffer + * @param olen Length of the output buffer + */ +static +bool +tls1_P_hash(const EVP_MD *md, const unsigned char *sec, + int sec_len, const void *seed, int seed_len, + unsigned char *out, int olen) +{ + int chunk; + size_t j; + EVP_MD_CTX *ctx, *ctx_tmp, *ctx_init; + EVP_PKEY *mac_key; + unsigned char A1[EVP_MAX_MD_SIZE]; + size_t A1_len = EVP_MAX_MD_SIZE; + int ret = false; + + chunk = EVP_MD_size(md); + OPENSSL_assert(chunk >= 0); + + ctx = md_ctx_new(); + ctx_tmp = md_ctx_new(); + ctx_init = md_ctx_new(); + EVP_MD_CTX_set_flags(ctx_init, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); + mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len); + if (!mac_key) + { + goto err; + } + if (!EVP_DigestSignInit(ctx_init, NULL, md, NULL, mac_key)) + { + goto err; + } + if (!EVP_MD_CTX_copy_ex(ctx, ctx_init)) + { + goto err; + } + if (!EVP_DigestSignUpdate(ctx, seed, seed_len)) + { + goto err; + } + if (!EVP_DigestSignFinal(ctx, A1, &A1_len)) + { + goto err; + } + + for (;; ) + { + /* Reinit mac contexts */ + if (!EVP_MD_CTX_copy_ex(ctx, ctx_init)) + { + goto err; + } + if (!EVP_DigestSignUpdate(ctx, A1, A1_len)) + { + goto err; + } + if (olen > chunk && !EVP_MD_CTX_copy_ex(ctx_tmp, ctx)) + { + goto err; + } + if (!EVP_DigestSignUpdate(ctx, seed, seed_len)) + { + goto err; + } + + if (olen > chunk) + { + j = olen; + if (!EVP_DigestSignFinal(ctx, out, &j)) + { + goto err; + } + out += j; + olen -= j; + /* calc the next A1 value */ + if (!EVP_DigestSignFinal(ctx_tmp, A1, &A1_len)) + { + goto err; + } + } + else + { + A1_len = EVP_MAX_MD_SIZE; + /* last one */ + if (!EVP_DigestSignFinal(ctx, A1, &A1_len)) + { + goto err; + } + memcpy(out, A1, olen); + break; + } + } + ret = true; +err: + EVP_PKEY_free(mac_key); + EVP_MD_CTX_free(ctx); + EVP_MD_CTX_free(ctx_tmp); + EVP_MD_CTX_free(ctx_init); + OPENSSL_cleanse(A1, sizeof(A1)); + return ret; +} + +/* + * Use the TLS PRF function for generating data channel keys. + * This code is based on the OpenSSL library. + * + * TLS generates keys as such: + * + * master_secret[48] = PRF(pre_master_secret[48], "master secret", + * ClientHello.random[32] + ServerHello.random[32]) + * + * key_block[] = PRF(SecurityParameters.master_secret[48], + * "key expansion", + * SecurityParameters.server_random[32] + + * SecurityParameters.client_random[32]); + * + * Notes: + * + * (1) key_block contains a full set of 4 keys. + * (2) The pre-master secret is generated by the client. + */ +bool +ssl_tls1_PRF(const uint8_t *label, int label_len, const uint8_t *sec, + int slen, uint8_t *out1, int olen) +{ + bool ret = true; + struct gc_arena gc = gc_new(); + /* For some reason our md_get("MD5") fails otherwise in the unit test */ + const EVP_MD *md5 = EVP_md5(); + const EVP_MD *sha1 = EVP_sha1(); + + uint8_t *out2 = (uint8_t *)gc_malloc(olen, false, &gc); + + int len = slen/2; + const uint8_t *S1 = sec; + const uint8_t *S2 = &(sec[len]); + len += (slen&1); /* add for odd, make longer */ + + if (!tls1_P_hash(md5, S1, len, label, label_len, out1, olen)) + { + ret = false; + goto done; + } + + if (!tls1_P_hash(sha1, S2, len, label, label_len, out2, olen)) + { + ret = false; + goto done; + } + + for (int i = 0; i < olen; i++) + { + out1[i] ^= out2[i]; + } + + secure_memzero(out2, olen); + + dmsg(D_SHOW_KEY_SOURCE, "tls1_PRF out[%d]: %s", olen, format_hex(out1, olen, 0, &gc)); +done: + gc_free(&gc); + return ret; +} +#endif /* if OPENSSL_VERSION_NUMBER >= 0x10100000L */ +#endif /* ENABLE_CRYPTO_OPENSSL */ \ No newline at end of file diff --git a/src/openvpn/crypto_openssl.h b/src/openvpn/crypto_openssl.h index 9bb58adae40..1d9fd7398f5 100644 --- a/src/openvpn/crypto_openssl.h +++ b/src/openvpn/crypto_openssl.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * Copyright (C) 2010-2021 Fox Crypto B.V. * * This program is free software; you can redistribute it and/or modify @@ -37,13 +37,6 @@ #include #endif - -/** Generic cipher key type %context. */ -typedef EVP_CIPHER cipher_kt_t; - -/** Generic message digest key type %context. */ -typedef EVP_MD md_kt_t; - /** Generic cipher %context. */ typedef EVP_CIPHER_CTX cipher_ctx_t; @@ -51,15 +44,32 @@ typedef EVP_CIPHER_CTX cipher_ctx_t; typedef EVP_MD_CTX md_ctx_t; /** Generic HMAC %context. */ +#if OPENSSL_VERSION_NUMBER < 0x30000000L typedef HMAC_CTX hmac_ctx_t; -#if OPENSSL_VERSION_NUMBER < 0x30000000L /* Use a dummy type for the provider */ typedef void provider_t; #else +typedef struct { + OSSL_PARAM params[3]; + uint8_t key[EVP_MAX_KEY_LENGTH]; + EVP_MAC_CTX *ctx; +} hmac_ctx_t; + typedef OSSL_PROVIDER provider_t; #endif +/* In OpenSSL 3.0 the method that returns EVP_CIPHER, the cipher needs to be + * freed afterwards, thus needing a non-const type. In constrast OpenSSL 1.1.1 + * and lower returns a const type, needing a const type */ +#if OPENSSL_VERSION_NUMBER < 0x30000000L +typedef const EVP_CIPHER evp_cipher_type; +typedef const EVP_MD evp_md_type; +#else +typedef EVP_CIPHER evp_cipher_type; +typedef EVP_MD evp_md_type; +#endif + /** Maximum length of an IV */ #define OPENVPN_MAX_IV_LENGTH EVP_MAX_IV_LENGTH @@ -108,12 +118,6 @@ void crypto_print_openssl_errors(const unsigned int flags); msg((flags), __VA_ARGS__); \ } while (false) -static inline bool -cipher_kt_var_key_size(const cipher_kt_t *cipher) -{ - return EVP_CIPHER_flags(cipher) & EVP_CIPH_VARIABLE_LENGTH; -} - /** * Load a key file from an engine * @@ -126,4 +130,4 @@ cipher_kt_var_key_size(const cipher_kt_t *cipher) EVP_PKEY * engine_load_key(const char *file, SSL_CTX *ctx); -#endif /* CRYPTO_OPENSSL_H_ */ +#endif /* CRYPTO_OPENSSL_H_ */ \ No newline at end of file diff --git a/src/openvpn/cryptoapi.c b/src/openvpn/cryptoapi.c index 4becef4d1d0..285adff6d23 100644 --- a/src/openvpn/cryptoapi.c +++ b/src/openvpn/cryptoapi.c @@ -52,58 +52,9 @@ #include "buffer.h" #include "openssl_compat.h" #include "win32.h" +#include "xkey_common.h" -/* MinGW w32api 3.17 is still incomplete when it comes to CryptoAPI while - * MinGW32-w64 defines all macros used. This is a hack around that problem. - */ -#ifndef CERT_SYSTEM_STORE_LOCATION_SHIFT -#define CERT_SYSTEM_STORE_LOCATION_SHIFT 16 -#endif -#ifndef CERT_SYSTEM_STORE_CURRENT_USER_ID -#define CERT_SYSTEM_STORE_CURRENT_USER_ID 1 -#endif -#ifndef CERT_SYSTEM_STORE_CURRENT_USER -#define CERT_SYSTEM_STORE_CURRENT_USER (CERT_SYSTEM_STORE_CURRENT_USER_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT) -#endif -#ifndef CERT_STORE_READONLY_FLAG -#define CERT_STORE_READONLY_FLAG 0x00008000 -#endif -#ifndef CERT_STORE_OPEN_EXISTING_FLAG -#define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000 -#endif - -/* Size of an SSL signature: MD5+SHA1 */ -#define SSL_SIG_LENGTH 36 - -/* try to funnel any Windows/CryptoAPI error messages to OpenSSL ERR_... */ -#define ERR_LIB_CRYPTOAPI (ERR_LIB_USER + 69) /* 69 is just a number... */ -#define CRYPTOAPIerr(f) err_put_ms_error(GetLastError(), (f), __FILE__, __LINE__) -#define CRYPTOAPI_F_CERT_OPEN_SYSTEM_STORE 100 -#define CRYPTOAPI_F_CERT_FIND_CERTIFICATE_IN_STORE 101 -#define CRYPTOAPI_F_CRYPT_ACQUIRE_CERTIFICATE_PRIVATE_KEY 102 -#define CRYPTOAPI_F_CRYPT_CREATE_HASH 103 -#define CRYPTOAPI_F_CRYPT_GET_HASH_PARAM 104 -#define CRYPTOAPI_F_CRYPT_SET_HASH_PARAM 105 -#define CRYPTOAPI_F_CRYPT_SIGN_HASH 106 -#define CRYPTOAPI_F_LOAD_LIBRARY 107 -#define CRYPTOAPI_F_GET_PROC_ADDRESS 108 -#define CRYPTOAPI_F_NCRYPT_SIGN_HASH 109 - -static ERR_STRING_DATA CRYPTOAPI_str_functs[] = { - { ERR_PACK(ERR_LIB_CRYPTOAPI, 0, 0), "microsoft cryptoapi"}, - { ERR_PACK(0, CRYPTOAPI_F_CERT_OPEN_SYSTEM_STORE, 0), "CertOpenSystemStore" }, - { ERR_PACK(0, CRYPTOAPI_F_CERT_FIND_CERTIFICATE_IN_STORE, 0), "CertFindCertificateInStore" }, - { ERR_PACK(0, CRYPTOAPI_F_CRYPT_ACQUIRE_CERTIFICATE_PRIVATE_KEY, 0), "CryptAcquireCertificatePrivateKey" }, - { ERR_PACK(0, CRYPTOAPI_F_CRYPT_CREATE_HASH, 0), "CryptCreateHash" }, - { ERR_PACK(0, CRYPTOAPI_F_CRYPT_GET_HASH_PARAM, 0), "CryptGetHashParam" }, - { ERR_PACK(0, CRYPTOAPI_F_CRYPT_SET_HASH_PARAM, 0), "CryptSetHashParam" }, - { ERR_PACK(0, CRYPTOAPI_F_CRYPT_SIGN_HASH, 0), "CryptSignHash" }, - { ERR_PACK(0, CRYPTOAPI_F_LOAD_LIBRARY, 0), "LoadLibrary" }, - { ERR_PACK(0, CRYPTOAPI_F_GET_PROC_ADDRESS, 0), "GetProcAddress" }, - { ERR_PACK(0, CRYPTOAPI_F_NCRYPT_SIGN_HASH, 0), "NCryptSignHash" }, - { 0, NULL } -}; - +#ifndef HAVE_XKEY_PROVIDER /* index for storing external data in EC_KEY: < 0 means uninitialized */ static int ec_data_idx = -1; @@ -112,44 +63,19 @@ static EVP_PKEY_METHOD *pmethod; static int (*default_pkey_sign_init) (EVP_PKEY_CTX *ctx); static int (*default_pkey_sign) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, const unsigned char *tbs, size_t tbslen); +#else /* ifndef HAVE_XKEY_PROVIDER */ +static XKEY_EXTERNAL_SIGN_fn xkey_cng_sign; +#endif /* HAVE_XKEY_PROVIDER */ typedef struct _CAPI_DATA { const CERT_CONTEXT *cert_context; HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov; + EVP_PKEY *pubkey; DWORD key_spec; BOOL free_crypt_prov; int ref_count; } CAPI_DATA; -/* Translate OpenSSL padding type to CNG padding type - * Returns 0 for unknown/unsupported padding. - */ -static DWORD -cng_padding_type(int padding) -{ - DWORD pad = 0; - - switch (padding) - { - case RSA_NO_PADDING: - break; - - case RSA_PKCS1_PADDING: - pad = BCRYPT_PAD_PKCS1; - break; - - case RSA_PKCS1_PSS_PADDING: - pad = BCRYPT_PAD_PSS; - break; - - default: - msg(M_WARN|M_INFO, "cryptoapicert: unknown OpenSSL padding type %d.", - padding); - } - - return pad; -} - /* * Translate OpenSSL hash OID to CNG algorithm name. Returns * "UNKNOWN" for unsupported algorithms and NULL for MD5+SHA1 @@ -215,114 +141,40 @@ CAPI_DATA_free(CAPI_DATA *cd) { CertFreeCertificateContext(cd->cert_context); } + EVP_PKEY_free(cd->pubkey); /* passing NULL is okay */ + free(cd); } -static char * -ms_error_text(DWORD ms_err) -{ - LPVOID lpMsgBuf = NULL; - char *rv = NULL; - - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER - |FORMAT_MESSAGE_FROM_SYSTEM - |FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, ms_err, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ - (LPTSTR) &lpMsgBuf, 0, NULL); - if (lpMsgBuf) - { - char *p; - rv = string_alloc(lpMsgBuf, NULL); - LocalFree(lpMsgBuf); - /* trim to the left */ - if (rv) - { - for (p = rv + strlen(rv) - 1; p >= rv; p--) - { - if (isspace(*p)) - { - *p = '\0'; - } - else - { - break; - } - } - } - } - return rv; -} +#ifndef HAVE_XKEY_PROVIDER -static void -err_put_ms_error(DWORD ms_err, int func, const char *file, int line) +/* Translate OpenSSL padding type to CNG padding type + * Returns 0 for unknown/unsupported padding. + */ +static DWORD +cng_padding_type(int padding) { - static int init = 0; -#define ERR_MAP_SZ 16 - static struct { - int err; - DWORD ms_err; /* I don't think we get more than 16 *different* errors */ - } err_map[ERR_MAP_SZ]; /* in here, before we give up the whole thing... */ - int i; + DWORD pad = 0; - if (ms_err == 0) - { - /* 0 is not an error */ - return; - } - if (!init) - { - ERR_load_strings(ERR_LIB_CRYPTOAPI, CRYPTOAPI_str_functs); - memset(&err_map, 0, sizeof(err_map)); - init++; - } - /* since MS error codes are 32 bit, and the ones in the ERR_... system is - * only 12, we must have a mapping table between them. */ - for (i = 0; i < ERR_MAP_SZ; i++) + switch (padding) { - if (err_map[i].ms_err == ms_err) - { - ERR_PUT_error(ERR_LIB_CRYPTOAPI, func, err_map[i].err, file, line); - break; - } - else if (err_map[i].ms_err == 0) - { - /* end of table, add new entry */ - ERR_STRING_DATA *esd = calloc(2, sizeof(*esd)); - if (esd == NULL) - { - break; - } - err_map[i].ms_err = ms_err; - err_map[i].err = esd->error = i + 100; - esd->string = ms_error_text(ms_err); - check_malloc_return(esd->string); - ERR_load_strings(ERR_LIB_CRYPTOAPI, esd); - ERR_PUT_error(ERR_LIB_CRYPTOAPI, func, err_map[i].err, file, line); + case RSA_NO_PADDING: break; - } - } -} -/* encrypt */ -static int -rsa_pub_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) -{ - /* I haven't been able to trigger this one, but I want to know if it happens... */ - assert(0); + case RSA_PKCS1_PADDING: + pad = BCRYPT_PAD_PKCS1; + break; - return 0; -} + case RSA_PKCS1_PSS_PADDING: + pad = BCRYPT_PAD_PSS; + break; -/* verify arbitrary data */ -static int -rsa_pub_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) -{ - /* I haven't been able to trigger this one, but I want to know if it happens... */ - assert(0); + default: + msg(M_WARN|M_INFO, "cryptoapicert: unknown OpenSSL padding type %d.", + padding); + } - return 0; + return pad; } /** @@ -363,14 +215,14 @@ priv_enc_CNG(const CAPI_DATA *cd, const wchar_t *hash_algo, const unsigned char } else { - RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE); + msg(M_NONFATAL, "Error in cryptoapicert: Unknown padding type"); return 0; } if (status != ERROR_SUCCESS) { SetLastError(status); - CRYPTOAPIerr(CRYPTOAPI_F_NCRYPT_SIGN_HASH); + msg(M_NONFATAL|M_ERRNO, "Error in cryptoapicert: NCryptSignHash failed"); len = 0; } @@ -378,152 +230,9 @@ priv_enc_CNG(const CAPI_DATA *cd, const wchar_t *hash_algo, const unsigned char return len; } -/* sign arbitrary data */ -static int -rsa_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) -{ - CAPI_DATA *cd = (CAPI_DATA *) RSA_meth_get0_app_data(RSA_get_method(rsa)); - HCRYPTHASH hash; - DWORD hash_size, len, i; - unsigned char *buf; - - if (cd == NULL) - { - RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_PASSED_NULL_PARAMETER); - return 0; - } - - if (padding != RSA_PKCS1_PADDING) - { - /* AFAICS, CryptSignHash() *always* uses PKCS1 padding. */ - RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE); - return 0; - } - - if (cd->key_spec == CERT_NCRYPT_KEY_SPEC) - { - return priv_enc_CNG(cd, NULL, from, flen, to, RSA_size(rsa), - cng_padding_type(padding), 0); - } - - /* Unfortunately, there is no "CryptSign()" function in CryptoAPI, that would - * be way to straightforward for M$, I guess... So we have to do it this - * tricky way instead, by creating a "Hash", and load the already-made hash - * from 'from' into it. */ - /* For now, we only support NID_md5_sha1 */ - if (flen != SSL_SIG_LENGTH) - { - RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, RSA_R_INVALID_MESSAGE_LENGTH); - return 0; - } - if (!CryptCreateHash(cd->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash)) - { - CRYPTOAPIerr(CRYPTOAPI_F_CRYPT_CREATE_HASH); - return 0; - } - len = sizeof(hash_size); - if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len, 0)) - { - CRYPTOAPIerr(CRYPTOAPI_F_CRYPT_GET_HASH_PARAM); - CryptDestroyHash(hash); - return 0; - } - if ((int) hash_size != flen) - { - RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, RSA_R_INVALID_MESSAGE_LENGTH); - CryptDestroyHash(hash); - return 0; - } - if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) - { - CRYPTOAPIerr(CRYPTOAPI_F_CRYPT_SET_HASH_PARAM); - CryptDestroyHash(hash); - return 0; - } - - len = RSA_size(rsa); - buf = malloc(len); - if (buf == NULL) - { - RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE); - CryptDestroyHash(hash); - return 0; - } - if (!CryptSignHash(hash, cd->key_spec, NULL, 0, buf, &len)) - { - CRYPTOAPIerr(CRYPTOAPI_F_CRYPT_SIGN_HASH); - CryptDestroyHash(hash); - free(buf); - return 0; - } - /* and now, we have to reverse the byte-order in the result from CryptSignHash()... */ - for (i = 0; i < len; i++) - { - to[i] = buf[len - i - 1]; - } - free(buf); - - CryptDestroyHash(hash); - return len; -} - -/** - * Sign the hash in |m| and return the signature in |sig|. - * Returns 1 on success, 0 on error. - * NCryptSignHash() is used to sign and it is instructed to add the - * the PKCS #1 DigestInfo header to |m| unless the hash algorithm is - * the MD5/SHA1 combination used in TLS 1.1 and earlier versions. - * OpenSSL exercises this callback only when padding is PKCS1 v1.5. - */ -static int -rsa_sign_CNG(int type, const unsigned char *m, unsigned int m_len, - unsigned char *sig, unsigned int *siglen, const RSA *rsa) -{ - CAPI_DATA *cd = (CAPI_DATA *) RSA_meth_get0_app_data(RSA_get_method(rsa)); - const wchar_t *alg = NULL; - int padding = RSA_PKCS1_PADDING; - - *siglen = 0; - if (cd == NULL) - { - RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_PASSED_NULL_PARAMETER); - return 0; - } - - alg = cng_hash_algo(type); - if (alg && wcscmp(alg, L"UNKNOWN") == 0) - { - RSAerr(RSA_F_RSA_SIGN, RSA_R_UNKNOWN_ALGORITHM_TYPE); - return 0; - } - - *siglen = priv_enc_CNG(cd, alg, m, (int)m_len, sig, RSA_size(rsa), - cng_padding_type(padding), 0); - - return (*siglen == 0) ? 0 : 1; -} - -/* decrypt */ -static int -rsa_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) -{ - /* I haven't been able to trigger this one, but I want to know if it happens... */ - assert(0); - - return 0; -} - -/* called at RSA_new */ -static int -init(RSA *rsa) -{ - - return 0; -} - /* called at RSA_free */ static int -finish(RSA *rsa) +rsa_finish(RSA *rsa) { const RSA_METHOD *rsa_meth = RSA_get_method(rsa); CAPI_DATA *cd = (CAPI_DATA *) RSA_meth_get0_app_data(rsa_meth); @@ -537,8 +246,6 @@ finish(RSA *rsa) return 1; } -#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) - static EC_KEY_METHOD *ec_method = NULL; /** EC_KEY_METHOD callback: called when the key is freed */ @@ -558,6 +265,7 @@ ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp) { return 1; } +#endif /* HAVE_XKEY_PROVIDER */ /** * Helper to convert ECDSA signature returned by NCryptSignHash @@ -593,6 +301,8 @@ ecdsa_bin2sig(unsigned char *buf, int len) return NULL; } +#ifndef HAVE_XKEY_PROVIDER + /** EC_KEY_METHOD callback sign_sig(): sign and return an ECDSA_SIG pointer. */ static ECDSA_SIG * ecdsa_sign_sig(const unsigned char *dgst, int dgstlen, @@ -613,7 +323,7 @@ ecdsa_sign_sig(const unsigned char *dgst, int dgstlen, if (status != ERROR_SUCCESS) { SetLastError(status); - CRYPTOAPIerr(CRYPTOAPI_F_NCRYPT_SIGN_HASH); + msg(M_NONFATAL|M_ERRNO, "Error in cryptoapticert: NCryptSignHash failed"); } else { @@ -642,7 +352,7 @@ ecdsa_sign(int type, const unsigned char *dgst, int dgstlen, unsigned char *sig, if (len > ECDSA_size(ec)) { ECDSA_SIG_free(s); - msg(M_NONFATAL,"Error: DER encoded ECDSA signature is too long (%d bytes)", len); + msg(M_NONFATAL, "Error in cryptoapicert: DER encoded ECDSA signature is too long (%d bytes)", len); return 0; } *siglen = i2d_ECDSA_SIG(s, &sig); @@ -657,12 +367,6 @@ ssl_ctx_set_eckey(SSL_CTX *ssl_ctx, CAPI_DATA *cd, EVP_PKEY *pkey) EC_KEY *ec = NULL; EVP_PKEY *privkey = NULL; - if (cd->key_spec != CERT_NCRYPT_KEY_SPEC) - { - msg(M_NONFATAL, "ERROR: cryptoapicert with only legacy private key handle available." - " EC certificate not supported."); - goto err; - } /* create a method struct with default callbacks filled in */ ec_method = EC_KEY_METHOD_new(EC_KEY_OpenSSL()); if (!ec_method) @@ -730,7 +434,7 @@ ssl_ctx_set_eckey(SSL_CTX *ssl_ctx, CAPI_DATA *cd, EVP_PKEY *pkey) return 0; } -#endif /* OPENSSL_VERSION_NUMBER >= 1.1.0 */ +#endif /* !HAVE_XKEY_PROVIDER */ static const CERT_CONTEXT * find_certificate_in_store(const char *cert_prop, HCERTSTORE cert_store) @@ -780,7 +484,7 @@ find_certificate_in_store(const char *cert_prop, HCERTSTORE cert_store) } if (!*++p) /* unexpected end of string */ { - msg(M_WARN, "WARNING: cryptoapicert: error parsing .", cert_prop); + msg(M_WARN|M_INFO, "WARNING: cryptoapicert: error parsing .", cert_prop); goto out; } if (*p >= '0' && *p <= '9') @@ -805,7 +509,7 @@ find_certificate_in_store(const char *cert_prop, HCERTSTORE cert_store) } else { - msg(M_WARN, "WARNING: cryptoapicert: unsupported certificate specification <%s>", cert_prop); + msg(M_NONFATAL, "Error in cryptoapicert: unsupported certificate specification <%s>", cert_prop); goto out; } @@ -823,7 +527,7 @@ find_certificate_in_store(const char *cert_prop, HCERTSTORE cert_store) { break; } - msg(M_WARN, "WARNING: cryptoapicert: ignoring certificate in store %s.", + msg(M_WARN|M_INFO, "WARNING: cryptoapicert: ignoring certificate in store %s.", validity < 0 ? "not yet valid" : "that has expired"); } @@ -832,7 +536,7 @@ find_certificate_in_store(const char *cert_prop, HCERTSTORE cert_store) return rv; } -#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) +#ifndef HAVE_XKEY_PROVIDER static const CAPI_DATA * retrieve_capi_data(EVP_PKEY *pkey) @@ -905,7 +609,7 @@ pkey_rsa_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, } else /* This should not happen */ { - msg(M_FATAL, "cryptopaicert: Unknown key and no default sign operation to fallback on"); + msg(M_FATAL, "Error in cryptoapicert: Unknown key and no default sign operation to fallback on"); return -1; } } @@ -926,20 +630,19 @@ pkey_rsa_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, */ if (alg && wcscmp(alg, L"UNKNOWN") == 0) { - RSAerr(RSA_F_PKEY_RSA_SIGN, RSA_R_UNKNOWN_ALGORITHM_TYPE); + msg(M_NONFATAL, "Error in cryptoapicert: Unknown hash algorithm <%d>", EVP_MD_type(md)); return -1; } } else { - msg(M_NONFATAL, "cryptoapicert: could not determine the signature digest algorithm"); - RSAerr(RSA_F_PKEY_RSA_SIGN, RSA_R_UNKNOWN_ALGORITHM_TYPE); + msg(M_NONFATAL, "Error in cryptoapicert: could not determine the signature digest algorithm"); return -1; } if (tbslen != (size_t)hashlen) { - RSAerr(RSA_F_PKEY_RSA_SIGN, RSA_R_INVALID_DIGEST_LENGTH); + msg(M_NONFATAL, "Error in cryptoapicert: data size does not match hash"); return -1; } @@ -957,14 +660,14 @@ pkey_rsa_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, if (!EVP_PKEY_CTX_get_rsa_mgf1_md(ctx, &mgf1md) || EVP_MD_type(mgf1md) != EVP_MD_type(md)) { - msg(M_NONFATAL, "cryptoapicert: Unknown MGF1 digest type or does" + msg(M_NONFATAL, "Error in cryptoapicert: Unknown MGF1 digest type or does" " not match the signature digest type."); - RSAerr(RSA_F_PKEY_RSA_SIGN, RSA_R_UNSUPPORTED_MASK_PARAMETER); + return -1; } if (!EVP_PKEY_CTX_get_rsa_pss_saltlen(ctx, &saltlen)) { - msg(M_WARN, "cryptoapicert: unable to get the salt length from context." + msg(M_WARN|M_INFO, "cryptoapicert: unable to get the salt length from context." " Using the default value."); saltlen = -1; } @@ -990,140 +693,247 @@ pkey_rsa_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, if (saltlen < 0) { - RSAerr(RSA_F_PKEY_RSA_SIGN, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); + msg(M_NONFATAL, "Error in cryptoapicert: invalid salt length (%d). Digest too large for keysize?", saltlen); return -1; } msg(D_LOW, "cryptoapicert: PSS padding using saltlen = %d", saltlen); } msg(D_LOW, "cryptoapicert: calling priv_enc_CNG with alg = %ls", alg); - *siglen = priv_enc_CNG(cd, alg, tbs, (int)tbslen, sig, *siglen, + *siglen = priv_enc_CNG(cd, alg, tbs, (int)tbslen, sig, (int)*siglen, cng_padding_type(padding), (DWORD)saltlen); return (*siglen == 0) ? 0 : 1; } -#endif /* OPENSSL_VERSION >= 1.1.0 */ - static int ssl_ctx_set_rsakey(SSL_CTX *ssl_ctx, CAPI_DATA *cd, EVP_PKEY *pkey) { - RSA *rsa = NULL, *pub_rsa; + RSA *rsa = NULL; RSA_METHOD *my_rsa_method = NULL; - bool rsa_method_set = false; + EVP_PKEY *privkey = NULL; + int ret = 0; my_rsa_method = RSA_meth_new("Microsoft Cryptography API RSA Method", RSA_METHOD_FLAG_NO_CHECK); check_malloc_return(my_rsa_method); - RSA_meth_set_pub_enc(my_rsa_method, rsa_pub_enc); - RSA_meth_set_pub_dec(my_rsa_method, rsa_pub_dec); - RSA_meth_set_priv_enc(my_rsa_method, rsa_priv_enc); - RSA_meth_set_priv_dec(my_rsa_method, rsa_priv_dec); - RSA_meth_set_init(my_rsa_method, NULL); - RSA_meth_set_finish(my_rsa_method, finish); + RSA_meth_set_finish(my_rsa_method, rsa_finish); /* we use this callback to cleanup CAPI_DATA */ RSA_meth_set0_app_data(my_rsa_method, cd); - /* - * For CNG, set the RSA_sign method which gets priority over priv_enc(). - * This method is called with the raw hash without the digestinfo - * header and works better when using NCryptSignHash() with some tokens. - * However, if PSS padding is in use, openssl does not call this - * function but adds the padding and then calls rsa_priv_enc() - * with padding set to NONE which is not supported by CNG. - * So, when posisble (OpenSSL 1.1.0 and up), we hook on to the sign - * operation in EVP_PKEY_METHOD struct. - */ - if (cd->key_spec == CERT_NCRYPT_KEY_SPEC) + /* pmethod is global -- initialize only if NULL */ + if (!pmethod) { -#if (OPENSSL_VERSION_NUMBER < 0x10100000L) - RSA_meth_set_sign(my_rsa_method, rsa_sign_CNG); -#else - /* pmethod is global -- initialize only if NULL */ + pmethod = EVP_PKEY_meth_new(EVP_PKEY_RSA, 0); if (!pmethod) { - pmethod = EVP_PKEY_meth_new(EVP_PKEY_RSA, 0); - if (!pmethod) - { - SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_MALLOC_FAILURE); - goto err; - } - const EVP_PKEY_METHOD *default_pmethod = EVP_PKEY_meth_find(EVP_PKEY_RSA); - EVP_PKEY_meth_copy(pmethod, default_pmethod); + msg(M_NONFATAL, "Error in cryptoapicert: failed to create EVP_PKEY_METHOD"); + return 0; + } + const EVP_PKEY_METHOD *default_pmethod = EVP_PKEY_meth_find(EVP_PKEY_RSA); + EVP_PKEY_meth_copy(pmethod, default_pmethod); - /* We want to override only sign_init() and sign() */ - EVP_PKEY_meth_set_sign(pmethod, pkey_rsa_sign_init, pkey_rsa_sign); - EVP_PKEY_meth_add0(pmethod); + /* We want to override only sign_init() and sign() */ + EVP_PKEY_meth_set_sign(pmethod, pkey_rsa_sign_init, pkey_rsa_sign); + EVP_PKEY_meth_add0(pmethod); - /* Keep a copy of the default sign and sign_init methods */ + /* Keep a copy of the default sign and sign_init methods */ -#if (OPENSSL_VERSION_NUMBER < 0x1010009fL) /* > version 1.1.0i */ - /* The function signature is not const-correct in these versions */ - EVP_PKEY_meth_get_sign((EVP_PKEY_METHOD *)default_pmethod, &default_pkey_sign_init, - &default_pkey_sign); -#else - EVP_PKEY_meth_get_sign(default_pmethod, &default_pkey_sign_init, - &default_pkey_sign); + EVP_PKEY_meth_get_sign(default_pmethod, &default_pkey_sign_init, + &default_pkey_sign); + } -#endif - } -#endif /* (OPENSSL_VERSION_NUMBER < 0x10100000L) */ + rsa = EVP_PKEY_get1_RSA(pkey); + + RSA_set_flags(rsa, RSA_flags(rsa) | RSA_FLAG_EXT_PKEY); + if (!RSA_set_method(rsa, my_rsa_method)) + { + goto cleanup; } + my_rsa_method = NULL; /* we do not want to free it in cleanup */ + cd->ref_count++; /* with method, cd gets assigned to the key as well */ - rsa = RSA_new(); - if (rsa == NULL) + privkey = EVP_PKEY_new(); + if (!EVP_PKEY_assign_RSA(privkey, rsa)) { - SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_MALLOC_FAILURE); - goto err; + goto cleanup; } + rsa = NULL; /* privkey has taken ownership */ - pub_rsa = EVP_PKEY_get0_RSA(pkey); - if (!pub_rsa) + if (!SSL_CTX_use_PrivateKey(ssl_ctx, privkey)) { - goto err; + goto cleanup; } + ret = 1; - /* Our private key is external, so we fill in only n and e from the public key */ - const BIGNUM *n = NULL; - const BIGNUM *e = NULL; - RSA_get0_key(pub_rsa, &n, &e, NULL); - BIGNUM *rsa_n = BN_dup(n); - BIGNUM *rsa_e = BN_dup(e); - if (!rsa_n || !rsa_e || !RSA_set0_key(rsa, rsa_n, rsa_e, NULL)) +cleanup: + if (rsa) { - BN_free(rsa_n); /* ok to free even if NULL */ - BN_free(rsa_e); - msg(M_NONFATAL, "ERROR: %s: out of memory", __func__); - goto err; + RSA_free(rsa); } - RSA_set_flags(rsa, RSA_flags(rsa) | RSA_FLAG_EXT_PKEY); - if (!RSA_set_method(rsa, my_rsa_method)) + if (my_rsa_method) { - goto err; + RSA_meth_free(my_rsa_method); } - rsa_method_set = true; /* flag that method pointer will get freed with the key */ - cd->ref_count++; /* with method, cd gets assigned to the key as well */ + if (privkey) + { + EVP_PKEY_free(privkey); + } + + return ret; +} + +#else /* HAVE_XKEY_PROVIDER */ + +/** Sign hash in tbs using EC key in cd and NCryptSignHash */ +static int +xkey_cng_ec_sign(CAPI_DATA *cd, unsigned char *sig, size_t *siglen, const unsigned char *tbs, + size_t tbslen) +{ + BYTE buf[1024]; /* large enough for EC keys upto 1024 bits */ + DWORD len = _countof(buf); - if (!SSL_CTX_use_RSAPrivateKey(ssl_ctx, rsa)) + msg(D_LOW, "Signing using NCryptSignHash with EC key"); + + DWORD status = NCryptSignHash(cd->crypt_prov, NULL, (BYTE *)tbs, tbslen, buf, len, &len, 0); + + if (status != ERROR_SUCCESS) { - goto err; + SetLastError(status); + msg(M_NONFATAL|M_ERRNO, "Error in cryptoapicert: ECDSA signature using CNG failed."); + return 0; } - /* SSL_CTX_use_RSAPrivateKey() increased the reference count in 'rsa', so - * we decrease it here with RSA_free(), or it will never be cleaned up. */ - RSA_free(rsa); - return 1; -err: - if (rsa) + /* NCryptSignHash returns r|s -- convert to OpenSSL's ECDSA_SIG */ + ECDSA_SIG *ecsig = ecdsa_bin2sig(buf, len); + if (!ecsig) { - RSA_free(rsa); + msg(M_NONFATAL, "Error in cryptopicert: Failed to convert ECDSA signature"); + return 0; } - if (my_rsa_method && !rsa_method_set) + + /* convert internal signature structure 's' to DER encoded byte array in sig */ + if (i2d_ECDSA_SIG(ecsig, NULL) > EVP_PKEY_size(cd->pubkey)) { - RSA_meth_free(my_rsa_method); + ECDSA_SIG_free(ecsig); + msg(M_NONFATAL, "Error in cryptoapicert: DER encoded ECDSA signature is too long"); + return 0; } - return 0; + + *siglen = i2d_ECDSA_SIG(ecsig, &sig); + ECDSA_SIG_free(ecsig); + + return (*siglen > 0); +} + +/** Sign hash in tbs using RSA key in cd and NCryptSignHash */ +static int +xkey_cng_rsa_sign(CAPI_DATA *cd, unsigned char *sig, size_t *siglen, const unsigned char *tbs, + size_t tbslen, XKEY_SIGALG sigalg) +{ + dmsg(D_LOW, "In xkey_cng_rsa_sign"); + + ASSERT(cd); + ASSERT(sig); + ASSERT(tbs); + + DWORD status = ERROR_SUCCESS; + DWORD len = 0; + + const wchar_t *hashalg = cng_hash_algo(OBJ_sn2nid(sigalg.mdname)); + + if (hashalg && wcscmp(hashalg, L"UNKNOWN") == 0) + { + msg(M_NONFATAL, "Error in cryptoapicert: Unknown hash name <%s>", sigalg.mdname); + return 0; + } + + if (!strcmp(sigalg.padmode, "pkcs1")) + { + msg(D_LOW, "Signing using NCryptSignHash with PKCS1 padding: hashalg <%s>", sigalg.mdname); + + BCRYPT_PKCS1_PADDING_INFO padinfo = {hashalg}; + status = NCryptSignHash(cd->crypt_prov, &padinfo, (BYTE *)tbs, (DWORD)tbslen, + sig, (DWORD)*siglen, &len, BCRYPT_PAD_PKCS1); + } + else if (!strcmp(sigalg.padmode, "pss")) + { + int saltlen = tbslen; /* digest size by default */ + if (!strcmp(sigalg.saltlen, "max")) + { + saltlen = xkey_max_saltlen(EVP_PKEY_bits(cd->pubkey), tbslen); + if (saltlen < 0) + { + msg(M_NONFATAL, "Error in cryptoapicert: invalid salt length (%d)", saltlen); + return 0; + } + } + + msg(D_LOW, "Signing using NCryptSignHash with PSS padding: hashalg <%s>, saltlen <%d>", + sigalg.mdname, saltlen); + + BCRYPT_PSS_PADDING_INFO padinfo = {hashalg, (DWORD) saltlen}; /* cast is safe as saltlen >= 0 */ + status = NCryptSignHash(cd->crypt_prov, &padinfo, (BYTE *)tbs, (DWORD) tbslen, + sig, (DWORD)*siglen, &len, BCRYPT_PAD_PSS); + } + else + { + msg(M_NONFATAL, "Error in cryptoapicert: Unsupported padding mode <%s>", sigalg.padmode); + return 0; + } + + if (status != ERROR_SUCCESS) + { + SetLastError(status); + msg(M_NONFATAL|M_ERRNO, "Error in cryptoapicert: RSA signature using CNG failed."); + return 0; + } + + *siglen = len; + return (*siglen > 0); } +/** Dispatch sign op to xkey_cng__sign */ +static int +xkey_cng_sign(void *handle, unsigned char *sig, size_t *siglen, const unsigned char *tbs, + size_t tbslen, XKEY_SIGALG sigalg) +{ + dmsg(D_LOW, "In xkey_cng_sign"); + + CAPI_DATA *cd = handle; + ASSERT(cd); + ASSERT(sig); + ASSERT(tbs); + + unsigned char mdbuf[EVP_MAX_MD_SIZE]; + size_t buflen = _countof(mdbuf); + + /* compute digest if required */ + if (!strcmp(sigalg.op, "DigestSign")) + { + if (!xkey_digest(tbs, tbslen, mdbuf, &buflen, sigalg.mdname)) + { + return 0; + } + tbs = mdbuf; + tbslen = buflen; + } + + if (!strcmp(sigalg.keytype, "EC")) + { + return xkey_cng_ec_sign(cd, sig, siglen, tbs, tbslen); + } + else if (!strcmp(sigalg.keytype, "RSA")) + { + return xkey_cng_rsa_sign(cd, sig, siglen, tbs, tbslen, sigalg); + } + else + { + return 0; /* Unknown keytype -- should not happen */ + } +} + +#endif /* HAVE_XKEY_PROVIDER */ + int SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop) { @@ -1133,7 +943,7 @@ SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop) if (cd == NULL) { - SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_MALLOC_FAILURE); + msg(M_NONFATAL, "Error in cryptoapicert: out of memory"); goto err; } /* search CURRENT_USER first, then LOCAL_MACHINE */ @@ -1141,7 +951,7 @@ SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop) |CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG, L"MY"); if (cs == NULL) { - CRYPTOAPIerr(CRYPTOAPI_F_CERT_OPEN_SYSTEM_STORE); + msg(M_NONFATAL|M_ERRNO, "Error in cryptoapicert: failed to open user certficate store"); goto err; } cd->cert_context = find_certificate_in_store(cert_prop, cs); @@ -1152,14 +962,14 @@ SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop) |CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG, L"MY"); if (cs == NULL) { - CRYPTOAPIerr(CRYPTOAPI_F_CERT_OPEN_SYSTEM_STORE); + msg(M_NONFATAL|M_ERRNO, "Error in cryptoapicert: failed to open machine certficate store"); goto err; } cd->cert_context = find_certificate_in_store(cert_prop, cs); CertCloseStore(cs, 0); if (cd->cert_context == NULL) { - CRYPTOAPIerr(CRYPTOAPI_F_CERT_FIND_CERTIFICATE_IN_STORE); + msg(M_NONFATAL, "Error in cryptoapicert: certificate matching <%s> not found", cert_prop); goto err; } } @@ -1169,46 +979,22 @@ SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop) cd->cert_context->cbCertEncoded); if (cert == NULL) { - SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_ASN1_LIB); + msg(M_NONFATAL, "Error in cryptoapicert: X509 certificate decode failed"); goto err; } /* set up stuff to use the private key */ - /* We prefer to get an NCRYPT key handle so that TLS1.2 can be supported */ + /* We support NCRYPT key handles only */ DWORD flags = CRYPT_ACQUIRE_COMPARE_KEY_FLAG - | CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG; + | CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG; if (!CryptAcquireCertificatePrivateKey(cd->cert_context, flags, NULL, &cd->crypt_prov, &cd->key_spec, &cd->free_crypt_prov)) { - /* if we don't have a smart card reader here, and we try to access a - * smart card certificate, we get: - * "Error 1223: The operation was canceled by the user." */ - CRYPTOAPIerr(CRYPTOAPI_F_CRYPT_ACQUIRE_CERTIFICATE_PRIVATE_KEY); + /* private key may be in a token not available, or incompatible with CNG */ + msg(M_NONFATAL|M_ERRNO, "Error in cryptoapicert: failed to acquire key. Key not present or " + "is in a legacy token not supported by Windows CNG API"); goto err; } - /* here we don't need to do CryptGetUserKey() or anything; all necessary key - * info is in cd->cert_context, and then, in cd->crypt_prov. */ - - /* if we do not have an NCRYPT key handle restrict TLS to v1.1 or lower */ - int max_version = SSL_CTX_get_max_proto_version(ssl_ctx); - if ((!max_version || max_version > TLS1_1_VERSION) - && cd->key_spec != CERT_NCRYPT_KEY_SPEC) - { - msg(M_WARN, "WARNING: cryptoapicert: private key is in a legacy store." - " Restricting TLS version to 1.1"); - if (SSL_CTX_get_min_proto_version(ssl_ctx) > TLS1_1_VERSION) - { - msg(M_NONFATAL, - "ERROR: cryptoapicert: min TLS version larger than 1.1." - " Try config option --tls-version-min 1.1"); - goto err; - } - if (!SSL_CTX_set_max_proto_version(ssl_ctx, TLS1_1_VERSION)) - { - msg(M_NONFATAL, "ERROR: cryptoapicert: set max TLS version failed"); - goto err; - } - } /* Public key in cert is NULL until we call SSL_CTX_use_certificate(), * so we do it here then... */ @@ -1218,13 +1004,23 @@ SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop) } /* the public key */ - EVP_PKEY *pkey = X509_get0_pubkey(cert); + EVP_PKEY *pkey = X509_get_pubkey(cert); + cd->pubkey = pkey; /* will be freed with cd */ /* SSL_CTX_use_certificate() increased the reference count in 'cert', so * we decrease it here with X509_free(), or it will never be cleaned up. */ X509_free(cert); cert = NULL; +#ifdef HAVE_XKEY_PROVIDER + + EVP_PKEY *privkey = xkey_load_generic_key(tls_libctx, cd, pkey, + xkey_cng_sign, (XKEY_PRIVKEY_FREE_fn *) CAPI_DATA_free); + SSL_CTX_use_PrivateKey(ssl_ctx, privkey); + return 1; /* do not free cd -- its kept by xkey provider */ + +#else /* ifdef HAVE_XKEY_PROVIDER */ + if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA) { if (!ssl_ctx_set_rsakey(ssl_ctx, cd, pkey)) @@ -1232,7 +1028,6 @@ SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop) goto err; } } -#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) else if (EVP_PKEY_id(pkey) == EVP_PKEY_EC) { if (!ssl_ctx_set_eckey(ssl_ctx, cd, pkey)) @@ -1240,25 +1035,19 @@ SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop) goto err; } } -#endif /* OPENSSL_VERSION_NUMBER >= 1.1.0 */ else { - msg(M_WARN, "WARNING: cryptoapicert: certificate type not supported"); + msg(M_WARN|M_INFO, "WARNING: cryptoapicert: key type <%d> not supported", + EVP_PKEY_id(pkey)); goto err; } CAPI_DATA_free(cd); /* this will do a ref_count-- */ return 1; +#endif /* HAVE_XKEY_PROVIDER */ + err: CAPI_DATA_free(cd); return 0; } - -#else /* ifdef ENABLE_CRYPTOAPI */ -#ifdef _MSC_VER /* Dummy function needed to avoid empty file compiler warning in Microsoft VC */ -static void -dummy(void) -{ -} -#endif -#endif /* _WIN32 */ +#endif /* _WIN32 */ \ No newline at end of file diff --git a/src/openvpn/dco.c b/src/openvpn/dco.c new file mode 100644 index 00000000000..3087a0df8f9 --- /dev/null +++ b/src/openvpn/dco.c @@ -0,0 +1,701 @@ +/* + * OpenVPN -- An application to securely tunnel IP networks + * over a single TCP/UDP port, with support for SSL/TLS-based + * session authentication and key exchange, + * packet encryption, packet authentication, and + * packet compression. + * + * Copyright (C) 2021-2023 Arne Schwabe + * Copyright (C) 2021-2023 Antonio Quartulli + * Copyright (C) 2021-2023 OpenVPN Inc + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program (see the file COPYING included with this + * distribution); if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#elif defined(_MSC_VER) +#include "config-msvc.h" +#endif + +#if defined(ENABLE_DCO) + +#include "syshead.h" +#include "crypto.h" +#include "dco.h" +#include "errlevel.h" +#include "multi.h" +#include "networking.h" +#include "openvpn.h" +#include "options.h" +#include "ssl_common.h" +#include "ssl_ncp.h" +#include "tun.h" + +#ifdef HAVE_LIBCAPNG +#include +#endif + +static int +dco_install_key(struct tls_multi *multi, struct key_state *ks, + const uint8_t *encrypt_key, const uint8_t *encrypt_iv, + const uint8_t *decrypt_key, const uint8_t *decrypt_iv, + const char *ciphername) + +{ + msg(D_DCO_DEBUG, "%s: peer_id=%d keyid=%d, currently %d keys installed", + __func__, multi->dco_peer_id, ks->key_id, multi->dco_keys_installed); + + /* Install a key in the PRIMARY slot only when no other key exist. + * From that moment on, any new key will be installed in the SECONDARY + * slot and will be promoted to PRIMARY when userspace says so (a swap + * will be performed in that case) + */ + dco_key_slot_t slot = OVPN_KEY_SLOT_PRIMARY; + if (multi->dco_keys_installed > 0) + { + slot = OVPN_KEY_SLOT_SECONDARY; + } + + int ret = dco_new_key(multi->dco, multi->dco_peer_id, ks->key_id, slot, + encrypt_key, encrypt_iv, + decrypt_key, decrypt_iv, + ciphername); + if ((ret == 0) && (multi->dco_keys_installed < 2)) + { + multi->dco_keys_installed++; + ks->dco_status = (slot == OVPN_KEY_SLOT_PRIMARY) ? DCO_INSTALLED_PRIMARY : + DCO_INSTALLED_SECONDARY; + } + + return ret; +} + +int +init_key_dco_bi(struct tls_multi *multi, struct key_state *ks, + const struct key2 *key2, int key_direction, + const char *ciphername, bool server) +{ + struct key_direction_state kds; + key_direction_state_init(&kds, key_direction); + + return dco_install_key(multi, ks, + key2->keys[kds.out_key].cipher, + key2->keys[(int)server].hmac, + key2->keys[kds.in_key].cipher, + key2->keys[1 - (int)server].hmac, + ciphername); +} + +/** + * Find a usable key that is not the primary (i.e. the secondary key) + * + * @param multi The TLS struct to retrieve keys from + * @param primary The primary key that should be skipped during the scan + * + * @return The secondary key or NULL if none could be found + */ +static struct key_state * +dco_get_secondary_key(struct tls_multi *multi, const struct key_state *primary) +{ + for (int i = 0; i < KEY_SCAN_SIZE; ++i) + { + struct key_state *ks = get_key_scan(multi, i); + struct key_ctx_bi *key = &ks->crypto_options.key_ctx_bi; + + if (ks == primary) + { + continue; + } + + if (ks->state >= S_GENERATED_KEYS && ks->authenticated == KS_AUTH_TRUE) + { + ASSERT(key->initialized); + return ks; + } + } + + return NULL; +} + +bool +dco_update_keys(dco_context_t *dco, struct tls_multi *multi) +{ + msg(D_DCO_DEBUG, "%s: peer_id=%d", __func__, multi->dco_peer_id); + + /* this function checks if keys have to be swapped or erased, therefore it + * can't do much if we don't have any key installed + */ + if (multi->dco_keys_installed == 0) + { + return true; + } + + struct key_state *primary = tls_select_encryption_key(multi); + /* no primary key available -> no usable key exists, therefore we should + * tell DCO to simply wipe all keys + */ + if (!primary) + { + msg(D_DCO, "No encryption key found. Purging data channel keys"); + + int ret = dco_del_key(dco, multi->dco_peer_id, OVPN_KEY_SLOT_PRIMARY); + if (ret < 0) + { + msg(D_DCO, "Cannot delete primary key during wipe: %s (%d)", strerror(-ret), ret); + return false; + } + + ret = dco_del_key(dco, multi->dco_peer_id, OVPN_KEY_SLOT_SECONDARY); + if (ret < 0) + { + msg(D_DCO, "Cannot delete secondary key during wipe: %s (%d)", strerror(-ret), ret); + return false; + } + + multi->dco_keys_installed = 0; + return true; + } + + /* if we have a primary key, it must have been installed already (keys + * are installed upon generation in the TLS code) + */ + ASSERT(primary->dco_status != DCO_NOT_INSTALLED); + + struct key_state *secondary = dco_get_secondary_key(multi, primary); + /* if the current primary key was installed as secondary in DCO, + * this means we have promoted it since installation in DCO, and + * we now need to tell DCO to swap keys + */ + if (primary->dco_status == DCO_INSTALLED_SECONDARY) + { + if (secondary) + { + msg(D_DCO_DEBUG, "Swapping primary and secondary keys to " + "primary-id=%d secondary-id=%d", + primary->key_id, secondary->key_id); + } + else + { + msg(D_DCO_DEBUG, "Swapping primary and secondary keys to" + "primary-id=%d secondary-id=(to be deleted)", + primary->key_id); + } + + int ret = dco_swap_keys(dco, multi->dco_peer_id); + if (ret < 0) + { + msg(D_DCO, "Cannot swap keys: %s (%d)", strerror(-ret), ret); + return false; + } + + primary->dco_status = DCO_INSTALLED_PRIMARY; + if (secondary) + { + ASSERT(secondary->dco_status == DCO_INSTALLED_PRIMARY); + secondary->dco_status = DCO_INSTALLED_SECONDARY; + } + } + + /* if we have no secondary key anymore, inform DCO about it */ + if (!secondary && multi->dco_keys_installed == 2) + { + int ret = dco_del_key(dco, multi->dco_peer_id, OVPN_KEY_SLOT_SECONDARY); + if (ret < 0) + { + msg(D_DCO, "Cannot delete secondary key: %s (%d)", strerror(-ret), ret); + return false; + } + multi->dco_keys_installed = 1; + } + + /* all keys that are not installed are set to NOT installed. Include also + * keys that might even be considered as active keys to be sure*/ + for (int i = 0; i < TM_SIZE; ++i) + { + for (int j = 0; j < KS_SIZE; j++) + { + struct key_state *ks = &multi->session[i].key[j]; + if (ks != primary && ks != secondary) + { + ks->dco_status = DCO_NOT_INSTALLED; + } + } + } + return true; +} + +static bool +dco_check_option_ce(const struct connection_entry *ce, int msglevel) +{ + if (ce->fragment) + { + msg(msglevel, "Note: --fragment disables data channel offload."); + return false; + } + + if (ce->http_proxy_options) + { + msg(msglevel, "Note: --http-proxy disables data channel offload."); + return false; + } + + if (ce->socks_proxy_server) + { + msg(msglevel, "Note: --socks-proxy disables data channel offload."); + return false; + } + +#if defined(TARGET_FREEBSD) + if (!proto_is_udp(ce->proto)) + { + msg(msglevel, "NOTE: TCP transport disables data channel offload on FreeBSD."); + return false; + } +#endif + +#if defined(_WIN32) + if (!ce->remote) + { + msg(msglevel, "NOTE: --remote is not defined, disabling data channel offload."); + return false; + } +#endif + + return true; +} + +bool +dco_check_startup_option(int msglevel, const struct options *o) +{ + /* check if no dev name was specified at all. In the case, + * later logic will most likely stop OpenVPN, so no need to + * print any message here. + */ + if (!o->dev) + { + return false; + } + + if (!o->tls_client && !o->tls_server) + { + msg(msglevel, "No tls-client or tls-server option in configuration " + "detected. Disabling data channel offload."); + return false; + } + + if (dev_type_enum(o->dev, o->dev_type) != DEV_TYPE_TUN) + { + msg(msglevel, "Note: dev-type not tun, disabling data channel offload."); + return false; + } + + if (o->connection_list) + { + const struct connection_list *l = o->connection_list; + for (int i = 0; i < l->len; ++i) + { + if (!dco_check_option_ce(l->array[i], msglevel)) + { + return false; + } + } + } + else + { + if (!dco_check_option_ce(&o->ce, msglevel)) + { + return false; + } + } + +#if defined(_WIN32) + if (o->mode == MODE_SERVER) + { + msg(msglevel, "--mode server is set. Disabling Data Channel Offload"); + return false; + } + + if ((o->windows_driver == WINDOWS_DRIVER_WINTUN) + || (o->windows_driver == WINDOWS_DRIVER_TAP_WINDOWS6)) + { + msg(msglevel, "--windows-driver is set to '%s'. Disabling Data Channel Offload", + print_windows_driver(o->windows_driver)); + return false; + } + +#elif defined(TARGET_LINUX) + /* if the device name is fixed, we need to check if an interface with this + * name already exists. IF it does, it must be a DCO interface, otherwise + * DCO has to be disabled in order to continue. + */ + if (tun_name_is_fixed(o->dev)) + { + char iftype[IFACE_TYPE_LEN_MAX]; + /* we pass NULL as net_ctx because using DCO on Linux implies that we + * are using SITNL and the latter does not need any context. This way we + * don't need to have the net_ctx percolate all the way here + */ + int ret = net_iface_type(NULL, o->dev, iftype); + if ((ret == 0) && (strcmp(iftype, "ovpn-dco") != 0)) + { + msg(msglevel, "Interface %s exists and is non-DCO. Disabling data channel offload", + o->dev); + return false; + } + else if ((ret < 0) && (ret != -ENODEV)) + { + msg(msglevel, "Cannot retrieve type of device %s: %s (%d)", o->dev, + strerror(-ret), ret); + } + } +#endif /* if defined(_WIN32) */ + +#if defined(HAVE_LIBCAPNG) + /* DCO can't operate without CAP_NET_ADMIN. To retain it when switching user + * we need CAP_SETPCAP. CAP_NET_ADMIN also needs to be part of the permitted set + * of capabilities in order to retain it. + */ + if (o->username) + { + if (!capng_have_capability(CAPNG_EFFECTIVE, CAP_SETPCAP)) + { + msg(msglevel, "--user specified but lacking CAP_SETPCAP. " + "Cannot retain CAP_NET_ADMIN. Disabling data channel offload"); + return false; + } + if (!capng_have_capability(CAPNG_PERMITTED, CAP_NET_ADMIN)) + { + msg(msglevel, "--user specified but not permitted to retain CAP_NET_ADMIN. " + "Disabling data channel offload"); + return false; + } + } +#endif /* if defined(HAVE_LIBCAPNG) */ + + if (o->mode == MODE_SERVER && o->topology != TOP_SUBNET) + { + msg(msglevel, "Note: NOT using '--topology subnet' disables data channel offload."); + return false; + } + + /* now that all options have been confirmed to be supported, check + * if DCO is truly available on the system + */ + return dco_available(msglevel); +} + +bool +dco_check_option(int msglevel, const struct options *o) +{ + /* At this point the ciphers have already been normalised */ + if (o->enable_ncp_fallback + && !tls_item_in_cipher_list(o->ciphername, dco_get_supported_ciphers())) + { + msg(msglevel, "Note: --data-cipher-fallback with cipher '%s' " + "disables data channel offload.", o->ciphername); + return false; + } + +#if defined(USE_COMP) + if (o->comp.alg != COMP_ALG_UNDEF + || o->comp.flags & COMP_F_ALLOW_ASYM + || o->comp.flags & COMP_F_ALLOW_COMPRESS) + { + msg(msglevel, "Note: '--allow-compression' is not set to 'no', disabling data channel offload."); + + if (o->mode == MODE_SERVER && !(o->comp.flags & COMP_F_MIGRATE)) + { + /* We can end up here from the multi.c call, only print the + * note if it is not already enabled */ + msg(msglevel, "Consider using the '--compress migrate' option."); + } + return false; + } +#endif + + struct gc_arena gc = gc_new(); + char *tmp_ciphers = string_alloc(o->ncp_ciphers, &gc); + const char *token; + while ((token = strsep(&tmp_ciphers, ":"))) + { + if (!tls_item_in_cipher_list(token, dco_get_supported_ciphers())) + { + msg(msglevel, "Note: cipher '%s' in --data-ciphers is not supported " + "by ovpn-dco, disabling data channel offload.", token); + gc_free(&gc); + return false; + } + } + gc_free(&gc); + + return true; +} + +bool +dco_check_pull_options(int msglevel, const struct options *o) +{ + if (!o->use_peer_id) + { + msg(msglevel, "OPTIONS IMPORT: Server did not request DATA_V2 packet " + "format required for data channel offload"); + return false; + } + return true; +} + +int +dco_p2p_add_new_peer(struct context *c) +{ + if (!dco_enabled(&c->options)) + { + return 0; + } + + struct link_socket *ls = c->c2.link_socket; + + ASSERT(ls->info.connection_established); + + struct sockaddr *remoteaddr = &ls->info.lsa->actual.dest.addr.sa; + struct tls_multi *multi = c->c2.tls_multi; +#ifdef TARGET_FREEBSD + /* In Linux in P2P mode the kernel automatically removes an existing peer + * when adding a new peer. FreeBSD needs to explicitly be told to do that */ + if (c->c2.tls_multi->dco_peer_id != -1) + { + dco_del_peer(&c->c1.tuntap->dco, c->c2.tls_multi->dco_peer_id); + c->c2.tls_multi->dco_peer_id = -1; + } +#endif + int ret = dco_new_peer(&c->c1.tuntap->dco, multi->peer_id, + c->c2.link_socket->sd, NULL, remoteaddr, NULL, NULL); + if (ret < 0) + { + return ret; + } + + c->c2.tls_multi->dco_peer_id = multi->peer_id; + c->c2.link_socket->dco_installed = true; + + return 0; +} + +void +dco_remove_peer(struct context *c) +{ + if (!dco_enabled(&c->options)) + { + return; + } + + if (c->c1.tuntap && c->c2.tls_multi && c->c2.tls_multi->dco_peer_id != -1) + { + dco_del_peer(&c->c1.tuntap->dco, c->c2.tls_multi->dco_peer_id); + c->c2.tls_multi->dco_peer_id = -1; + } +} + +static bool +dco_multi_get_localaddr(struct multi_context *m, struct multi_instance *mi, + struct sockaddr_storage *local) +{ +#if ENABLE_IP_PKTINFO + struct context *c = &mi->context; + + if (!(c->options.sockflags & SF_USE_IP_PKTINFO)) + { + return false; + } + + struct link_socket_actual *actual = &c->c2.link_socket_info->lsa->actual; + + switch (actual->dest.addr.sa.sa_family) + { + case AF_INET: + { + struct sockaddr_in *sock_in4 = (struct sockaddr_in *)local; +#if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) + sock_in4->sin_addr = actual->pi.in4.ipi_addr; +#elif defined(IP_RECVDSTADDR) + sock_in4->sin_addr = actual->pi.in4; +#else + /* source IP not available on this platform */ + return false; +#endif + sock_in4->sin_family = AF_INET; + break; + } + + case AF_INET6: + { + struct sockaddr_in6 *sock_in6 = (struct sockaddr_in6 *)local; + sock_in6->sin6_addr = actual->pi.in6.ipi6_addr; + sock_in6->sin6_family = AF_INET6; + break; + } + + default: + ASSERT(false); + } + + return true; +#else /* if ENABLE_IP_PKTINFO */ + return false; +#endif /* if ENABLE_IP_PKTINFO */ +} + +int +dco_multi_add_new_peer(struct multi_context *m, struct multi_instance *mi) +{ + struct context *c = &mi->context; + + int peer_id = c->c2.tls_multi->peer_id; + struct sockaddr *remoteaddr, *localaddr = NULL; + struct sockaddr_storage local = { 0 }; + int sd = c->c2.link_socket->sd; + + + if (c->mode == CM_CHILD_TCP) + { + /* the remote address will be inferred from the TCP socket endpoint */ + remoteaddr = NULL; + } + else + { + ASSERT(c->c2.link_socket_info->connection_established); + remoteaddr = &c->c2.link_socket_info->lsa->actual.dest.addr.sa; + } + + /* In server mode we need to fetch the remote addresses from the push config */ + struct in_addr vpn_ip4 = { 0 }; + struct in_addr *vpn_addr4 = NULL; + if (c->c2.push_ifconfig_defined) + { + vpn_ip4.s_addr = htonl(c->c2.push_ifconfig_local); + vpn_addr4 = &vpn_ip4; + } + + struct in6_addr *vpn_addr6 = NULL; + if (c->c2.push_ifconfig_ipv6_defined) + { + vpn_addr6 = &c->c2.push_ifconfig_ipv6_local; + } + + if (dco_multi_get_localaddr(m, mi, &local)) + { + localaddr = (struct sockaddr *)&local; + } + + int ret = dco_new_peer(&c->c1.tuntap->dco, peer_id, sd, localaddr, + remoteaddr, vpn_addr4, vpn_addr6); + if (ret < 0) + { + return ret; + } + + c->c2.tls_multi->dco_peer_id = peer_id; + + if (c->mode == CM_CHILD_TCP) + { + multi_tcp_dereference_instance(m->mtcp, mi); + if (close(sd)) + { + msg(D_DCO|M_ERRNO, "error closing TCP socket after DCO handover"); + } + c->c2.link_socket->dco_installed = true; + c->c2.link_socket->sd = SOCKET_UNDEFINED; + } + + return 0; +} + +void +dco_install_iroute(struct multi_context *m, struct multi_instance *mi, + struct mroute_addr *addr) +{ +#if defined(TARGET_LINUX) || defined(TARGET_FREEBSD) + if (!dco_enabled(&m->top.options)) + { + return; + } + + int addrtype = (addr->type & MR_ADDR_MASK); + + /* If we do not have local IP addr to install, skip the route */ + if ((addrtype == MR_ADDR_IPV6 && !mi->context.c2.push_ifconfig_ipv6_defined) + || (addrtype == MR_ADDR_IPV4 && !mi->context.c2.push_ifconfig_defined)) + { + return; + } + + struct context *c = &mi->context; + const char *dev = c->c1.tuntap->actual_name; + + if (addrtype == MR_ADDR_IPV6) + { + net_route_v6_add(&m->top.net_ctx, &addr->v6.addr, addr->netbits, + &mi->context.c2.push_ifconfig_ipv6_local, dev, 0, + DCO_IROUTE_METRIC); + } + else if (addrtype == MR_ADDR_IPV4) + { + in_addr_t dest = htonl(addr->v4.addr); + net_route_v4_add(&m->top.net_ctx, &dest, addr->netbits, + &mi->context.c2.push_ifconfig_local, dev, 0, + DCO_IROUTE_METRIC); + } +#endif /* if defined(TARGET_LINUX) || defined(TARGET_FREEBSD) */ +} + +void +dco_delete_iroutes(struct multi_context *m, struct multi_instance *mi) +{ +#if defined(TARGET_LINUX) || defined(TARGET_FREEBSD) + if (!dco_enabled(&m->top.options)) + { + return; + } + ASSERT(TUNNEL_TYPE(mi->context.c1.tuntap) == DEV_TYPE_TUN); + + struct context *c = &mi->context; + const char *dev = c->c1.tuntap->actual_name; + + if (mi->context.c2.push_ifconfig_defined) + { + for (const struct iroute *ir = c->options.iroutes; + ir; + ir = ir->next) + { + net_route_v4_del(&m->top.net_ctx, &ir->network, ir->netbits, + &mi->context.c2.push_ifconfig_local, dev, + 0, DCO_IROUTE_METRIC); + } + } + + if (mi->context.c2.push_ifconfig_ipv6_defined) + { + for (const struct iroute_ipv6 *ir6 = c->options.iroutes_ipv6; + ir6; + ir6 = ir6->next) + { + net_route_v6_del(&m->top.net_ctx, &ir6->network, ir6->netbits, + &mi->context.c2.push_ifconfig_ipv6_local, dev, + 0, DCO_IROUTE_METRIC); + } + } +#endif /* if defined(TARGET_LINUX) || defined(TARGET_FREEBSD) */ +} + +#endif /* defined(ENABLE_DCO) */ diff --git a/src/openvpn/dco.h b/src/openvpn/dco.h new file mode 100644 index 00000000000..18a9d78be6f --- /dev/null +++ b/src/openvpn/dco.h @@ -0,0 +1,385 @@ +/* + * OpenVPN -- An application to securely tunnel IP networks + * over a single TCP/UDP port, with support for SSL/TLS-based + * session authentication and key exchange, + * packet encryption, packet authentication, and + * packet compression. + * + * Copyright (C) 2021-2023 Arne Schwabe + * Copyright (C) 2021-2023 Antonio Quartulli + * Copyright (C) 2021-2023 OpenVPN Inc + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program (see the file COPYING included with this + * distribution); if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#ifndef DCO_H +#define DCO_H + +#include "buffer.h" +#include "error.h" +#include "dco_internal.h" +#include "networking.h" + +/* forward declarations (including other headers leads to nasty include + * order problems) + */ +struct event_set; +struct key2; +struct key_state; +struct multi_context; +struct multi_instance; +struct mroute_addr; +struct options; +struct tls_multi; +struct tuntap; + +#define DCO_IROUTE_METRIC 100 +#define DCO_DEFAULT_METRIC 200 + +#if defined(ENABLE_DCO) + +/** + * Check whether ovpn-dco is available on this platform (i.e. kernel support is + * there) + * + * @param msglevel level to print messages to + * @return true if ovpn-dco is available, false otherwise + */ +bool dco_available(int msglevel); + +/** + * Check whether the options struct has any option that is not supported by + * our current dco implementation. If so print a warning at warning level + * for the first conflicting option found and return false. + * + * @param msglevel the msg level to use to print the warnings + * @param o the options struct that hold the options + * @return true if no conflict was detected, false otherwise + */ +bool dco_check_option(int msglevel, const struct options *o); + +/** + * Check whether the options struct has any further option that is not supported + * by our current dco implementation during early startup. + * If so print a warning at warning level for the first conflicting option + * found and return false. + * + * @param msglevel the msg level to use to print the warnings + * @param o the options struct that hold the options + * @return true if no conflict was detected, false otherwise + */ +bool dco_check_startup_option(int msglevel, const struct options *o); + +/** + * Check whether any of the options pushed by the server is not supported by + * our current dco implementation. If so print a warning at warning level + * for the first conflicting option found and return false. + * + * @param msglevel the msg level to use to print the warnings + * @param o the options struct that hold the options + * @return true if no conflict was detected, false otherwise + */ +bool dco_check_pull_options(int msglevel, const struct options *o); + +/** + * Initialize the DCO context + * + * @param mode the instance operating mode (P2P or multi-peer) + * @param dco the context to initialize + * @return true on success, false otherwise + */ +bool ovpn_dco_init(int mode, dco_context_t *dco); + +/** + * Open/create a DCO interface + * + * @param tt the tuntap context + * @param ctx the networking API context + * @param dev the name of the interface to create + * @return 0 on success or a negative error code otherwise + */ +int open_tun_dco(struct tuntap *tt, openvpn_net_ctx_t *ctx, const char *dev); + +/** + * Close/destroy a DCO interface + * + * @param tt the tuntap context + * @param ctx the networking API context + */ +void close_tun_dco(struct tuntap *tt, openvpn_net_ctx_t *ctx); + +/** + * Read data from the DCO communication channel (i.e. a control packet) + * + * @param dco the DCO context + * @return 0 on success or a negative error code otherwise + */ +int dco_do_read(dco_context_t *dco); + +/** + * Write data to the DCO communication channel (control packet expected) + * + * @param dco the DCO context + * @param peer_id the ID of the peer to send the data to + * @param buf the buffer containing the data to send + */ +int dco_do_write(dco_context_t *dco, int peer_id, struct buffer *buf); + +/** + * Install a DCO in the main event loop + */ +void dco_event_set(dco_context_t *dco, struct event_set *es, void *arg); + +/** + * Install the key material in DCO for the specified peer. + * The key is installed in the primary slot when no other key was yet installed. + * Any subsequent invocation will install the key in the secondary slot. + * + * @param multi the TLS context of the current instance + * @param ks the state of the key being installed + * @param key2 the container for the raw key material + * @param key_direction the key direction to be used to extract the material + * @param ciphername the name of the cipher to use the key with + * @param server whether we are running on a server instance or not + * + * @return 0 on success or a negative error code otherwise + */ +int init_key_dco_bi(struct tls_multi *multi, struct key_state *ks, + const struct key2 *key2, int key_direction, + const char *ciphername, bool server); + +/** + * Possibly swap or wipe keys from DCO + * + * @param dco DCO device context + * @param multi TLS multi instance + * + * @return returns false if an error occurred that is not + * recoverable and should reset the connection + */ +bool dco_update_keys(dco_context_t *dco, struct tls_multi *multi); +/** + * Install a new peer in DCO - to be called by a CLIENT (or P2P) instance + * + * @param c the main instance context + * @return 0 on success or a negative error code otherwise + */ +int dco_p2p_add_new_peer(struct context *c); + +/** + * Modify DCO peer options. Special values are 0 (disable) + * and -1 (do not touch). + * + * @param dco DCO device context + * @param peer_id the ID of the peer to be modified + * @param keepalive_interval keepalive interval in seconds + * @param keepalive_timeout keepalive timeout in seconds + * @param mss TCP MSS value + * + * @return 0 on success or a negative error code otherwise + */ +int dco_set_peer(dco_context_t *dco, unsigned int peerid, + int keepalive_interval, int keepalive_timeout, int mss); + +/** + * Remove a peer from DCO + * + * @param c the main instance context of the peer to remove + */ +void dco_remove_peer(struct context *c); + +/** + * Install a new peer in DCO - to be called by a SERVER instance + * + * @param m the server context + * @param mi the client instance + * @return 0 on success or a negative error code otherwise + */ +int dco_multi_add_new_peer(struct multi_context *m, struct multi_instance *mi); + +/** + * Install an iroute in DCO, which means adding a route to the system routing + * table. To be called by a SERVER instance only. + * + * @param m the server context + * @param mi the client instance acting as nexthop for the route + * @param addr the route to add + */ +void dco_install_iroute(struct multi_context *m, struct multi_instance *mi, + struct mroute_addr *addr); + +/** + * Remove all routes added through the specified client + * + * @param m the server context + * @param mi the client instance for which routes have to be removed + */ +void dco_delete_iroutes(struct multi_context *m, struct multi_instance *mi); + +/** + * Update traffic statistics for all peers + * + * @param dco DCO device context + * @param m the server context + **/ +int dco_get_peer_stats_multi(dco_context_t *dco, struct multi_context *m); + +/** + * Update traffic statistics for single peer + * + * @param c instance context of the peer + **/ +int dco_get_peer_stats(struct context *c); + +/** + * Retrieve the list of ciphers supported by the current platform + * + * @return list of colon-separated ciphers + */ +const char *dco_get_supported_ciphers(); + +#else /* if defined(ENABLE_DCO) */ + +typedef void *dco_context_t; + +static inline bool +dco_available(int msglevel) +{ + return false; +} + +static inline bool +dco_check_option(int msglevel, const struct options *o) +{ + return false; +} + +static inline bool +dco_check_startup_option(int msglevel, const struct options *o) +{ + return false; +} + +static inline bool +dco_check_pull_options(int msglevel, const struct options *o) +{ + return false; +} + +static inline bool +ovpn_dco_init(int mode, dco_context_t *dco) +{ + return true; +} + +static inline int +open_tun_dco(struct tuntap *tt, openvpn_net_ctx_t *ctx, const char *dev) +{ + return 0; +} + +static inline void +close_tun_dco(struct tuntap *tt, openvpn_net_ctx_t *ctx) +{ +} + +static inline int +dco_do_read(dco_context_t *dco) +{ + ASSERT(false); + return 0; +} + +static inline int +dco_do_write(dco_context_t *dco, int peer_id, struct buffer *buf) +{ + ASSERT(false); + return 0; +} + +static inline void +dco_event_set(dco_context_t *dco, struct event_set *es, void *arg) +{ +} + +static inline int +init_key_dco_bi(struct tls_multi *multi, struct key_state *ks, + const struct key2 *key2, int key_direction, + const char *ciphername, bool server) +{ + return 0; +} + +static inline bool +dco_update_keys(dco_context_t *dco, struct tls_multi *multi) +{ + ASSERT(false); + return false; +} + +static inline int +dco_p2p_add_new_peer(struct context *c) +{ + return 0; +} + +static inline int +dco_set_peer(dco_context_t *dco, unsigned int peerid, + int keepalive_interval, int keepalive_timeout, int mss) +{ + return 0; +} + +static inline void +dco_remove_peer(struct context *c) +{ +} + +static inline int +dco_multi_add_new_peer(struct multi_context *m, struct multi_instance *mi) +{ + return 0; +} + +static inline void +dco_install_iroute(struct multi_context *m, struct multi_instance *mi, + struct mroute_addr *addr) +{ +} + +static inline void +dco_delete_iroutes(struct multi_context *m, struct multi_instance *mi) +{ +} + +static inline int +dco_get_peer_stats_multi(dco_context_t *dco, struct multi_context *m) +{ + return 0; +} + +static inline int +dco_get_peer_stats(struct context *c) +{ + return 0; +} + +static inline const char * +dco_get_supported_ciphers() +{ + return ""; +} + +#endif /* defined(ENABLE_DCO) */ +#endif /* ifndef DCO_H */ diff --git a/src/openvpn/dco_freebsd.c b/src/openvpn/dco_freebsd.c new file mode 100644 index 00000000000..cd4083c4968 --- /dev/null +++ b/src/openvpn/dco_freebsd.c @@ -0,0 +1,762 @@ +/* + * Interface to FreeBSD dco networking code + * + * Copyright (C) 2022 Rubicon Communications, LLC (Netgate). All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program (see the file COPYING included with this + * distribution); if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#elif defined(_MSC_VER) +#include "config-msvc.h" +#endif + +#if defined(ENABLE_DCO) && defined(TARGET_FREEBSD) + +#include "syshead.h" + +#include +#include +#include +#include + +#include "dco_freebsd.h" +#include "dco.h" +#include "tun.h" +#include "crypto.h" +#include "multi.h" +#include "ssl_common.h" + +static nvlist_t * +sockaddr_to_nvlist(const struct sockaddr *sa) +{ + nvlist_t *nvl = nvlist_create(0); + + nvlist_add_number(nvl, "af", sa->sa_family); + + switch (sa->sa_family) + { + case AF_INET: + { + const struct sockaddr_in *in = (const struct sockaddr_in *)sa; + nvlist_add_binary(nvl, "address", &in->sin_addr, sizeof(in->sin_addr)); + nvlist_add_number(nvl, "port", in->sin_port); + break; + } + + case AF_INET6: + { + const struct sockaddr_in6 *in6 = (const struct sockaddr_in6 *)sa; + nvlist_add_binary(nvl, "address", &in6->sin6_addr, sizeof(in6->sin6_addr)); + nvlist_add_number(nvl, "port", in6->sin6_port); + break; + } + + default: + ASSERT(0); + } + + return (nvl); +} + +int +dco_new_peer(dco_context_t *dco, unsigned int peerid, int sd, + struct sockaddr *localaddr, struct sockaddr *remoteaddr, + struct in_addr *remote_in4, struct in6_addr *remote_in6) +{ + struct ifdrv drv; + nvlist_t *nvl; + int ret; + + nvl = nvlist_create(0); + + msg(D_DCO_DEBUG, "%s: peer-id %d, fd %d", __func__, peerid, sd); + + if (localaddr) + { + nvlist_add_nvlist(nvl, "local", sockaddr_to_nvlist(localaddr)); + } + + if (remoteaddr) + { + nvlist_add_nvlist(nvl, "remote", sockaddr_to_nvlist(remoteaddr)); + } + + if (remote_in4) + { + nvlist_add_binary(nvl, "vpn_ipv4", &remote_in4->s_addr, + sizeof(remote_in4->s_addr)); + } + + if (remote_in6) + { + nvlist_add_binary(nvl, "vpn_ipv6", remote_in6, sizeof(*remote_in6)); + } + + nvlist_add_number(nvl, "fd", sd); + nvlist_add_number(nvl, "peerid", peerid); + + CLEAR(drv); + snprintf(drv.ifd_name, IFNAMSIZ, "%s", dco->ifname); + drv.ifd_cmd = OVPN_NEW_PEER; + drv.ifd_data = nvlist_pack(nvl, &drv.ifd_len); + + ret = ioctl(dco->fd, SIOCSDRVSPEC, &drv); + if (ret) + { + msg(M_ERR | M_ERRNO, "Failed to create new peer"); + } + + free(drv.ifd_data); + nvlist_destroy(nvl); + + return ret; +} + +static int +open_fd(dco_context_t *dco) +{ + int ret; + + ret = pipe2(dco->pipefd, O_CLOEXEC | O_NONBLOCK); + if (ret != 0) + { + return -1; + } + + dco->fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0); + if (dco->fd != -1) + { + dco->open = true; + } + dco->dco_packet_in = alloc_buf(PAGE_SIZE); + + return dco->fd; +} + +static void +close_fd(dco_context_t *dco) +{ + close(dco->pipefd[0]); + close(dco->pipefd[1]); + close(dco->fd); +} + +bool +ovpn_dco_init(int mode, dco_context_t *dco) +{ + if (open_fd(dco) < 0) + { + msg(M_ERR, "Failed to open socket"); + return false; + } + return true; +} + +static int +dco_set_ifmode(dco_context_t *dco, int ifmode) +{ + struct ifdrv drv; + nvlist_t *nvl; + int ret; + + nvl = nvlist_create(0); + nvlist_add_number(nvl, "ifmode", ifmode); + + CLEAR(drv); + snprintf(drv.ifd_name, IFNAMSIZ, "%s", dco->ifname); + drv.ifd_cmd = OVPN_SET_IFMODE; + drv.ifd_data = nvlist_pack(nvl, &drv.ifd_len); + + ret = ioctl(dco->fd, SIOCSDRVSPEC, &drv); + if (ret) + { + msg(M_WARN | M_ERRNO, "dco_set_ifmode: failed to set ifmode=%08x", ifmode); + } + + free(drv.ifd_data); + nvlist_destroy(nvl); + + return ret; +} + +static int +create_interface(struct tuntap *tt, const char *dev) +{ + int ret; + struct ifreq ifr; + + CLEAR(ifr); + + /* Create ovpnx first, then rename it. */ + snprintf(ifr.ifr_name, IFNAMSIZ, "ovpn"); + ret = ioctl(tt->dco.fd, SIOCIFCREATE2, &ifr); + if (ret) + { + ret = -errno; + msg(M_WARN|M_ERRNO, "Failed to create interface %s (SIOCIFCREATE2)", ifr.ifr_name); + return ret; + } + + /* Rename */ + if (!strcmp(dev, "tun")) + { + ifr.ifr_data = "ovpn"; + } + else + { + ifr.ifr_data = (char *)dev; + } + ret = ioctl(tt->dco.fd, SIOCSIFNAME, &ifr); + if (ret) + { + ret = -errno; + /* Delete the created interface again. */ + (void)ioctl(tt->dco.fd, SIOCIFDESTROY, &ifr); + msg(M_WARN|M_ERRNO, "Failed to create interface %s (SIOCSIFNAME)", ifr.ifr_data); + return ret; + } + + snprintf(tt->dco.ifname, IFNAMSIZ, "%s", ifr.ifr_data); + tt->actual_name = string_alloc(tt->dco.ifname, NULL); + + /* see "Interface Flags" in ifnet(9) */ + int i = IFF_POINTOPOINT | IFF_MULTICAST; + if (tt->topology == TOP_SUBNET) + { + i = IFF_BROADCAST | IFF_MULTICAST; + } + dco_set_ifmode(&tt->dco, i); + + return 0; +} + +static int +remove_interface(struct tuntap *tt) +{ + int ret; + struct ifreq ifr; + + CLEAR(ifr); + snprintf(ifr.ifr_name, IFNAMSIZ, "%s", tt->dco.ifname); + + ret = ioctl(tt->dco.fd, SIOCIFDESTROY, &ifr); + if (ret) + { + msg(M_ERR | M_ERRNO, "Failed to remove interface %s", ifr.ifr_name); + } + + tt->dco.ifname[0] = 0; + + return ret; +} + +int +open_tun_dco(struct tuntap *tt, openvpn_net_ctx_t *ctx, const char *dev) +{ + return create_interface(tt, dev); +} + +void +close_tun_dco(struct tuntap *tt, openvpn_net_ctx_t *ctx) +{ + remove_interface(tt); + close_fd(&tt->dco); +} + +int +dco_swap_keys(dco_context_t *dco, unsigned int peerid) +{ + struct ifdrv drv; + nvlist_t *nvl; + int ret; + + msg(D_DCO_DEBUG, "%s: peer-id %d", __func__, peerid); + + nvl = nvlist_create(0); + nvlist_add_number(nvl, "peerid", peerid); + + CLEAR(drv); + snprintf(drv.ifd_name, IFNAMSIZ, "%s", dco->ifname); + drv.ifd_cmd = OVPN_SWAP_KEYS; + drv.ifd_data = nvlist_pack(nvl, &drv.ifd_len); + + ret = ioctl(dco->fd, SIOCSDRVSPEC, &drv); + if (ret) + { + msg(M_WARN | M_ERRNO, "Failed to swap keys"); + } + + free(drv.ifd_data); + nvlist_destroy(nvl); + + return ret; +} + +int +dco_del_peer(dco_context_t *dco, unsigned int peerid) +{ + struct ifdrv drv; + nvlist_t *nvl; + int ret; + + msg(D_DCO_DEBUG, "%s: peer-id %d", __func__, peerid); + + nvl = nvlist_create(0); + nvlist_add_number(nvl, "peerid", peerid); + + CLEAR(drv); + snprintf(drv.ifd_name, IFNAMSIZ, "%s", dco->ifname); + drv.ifd_cmd = OVPN_DEL_PEER; + drv.ifd_data = nvlist_pack(nvl, &drv.ifd_len); + + ret = ioctl(dco->fd, SIOCSDRVSPEC, &drv); + if (ret) + { + msg(M_WARN | M_ERRNO, "Failed to delete peer"); + } + + free(drv.ifd_data); + nvlist_destroy(nvl); + + return ret; +} + +int +dco_del_key(dco_context_t *dco, unsigned int peerid, + dco_key_slot_t slot) +{ + struct ifdrv drv; + nvlist_t *nvl; + int ret; + + msg(D_DCO_DEBUG, "%s: peer-id %d, slot %d", __func__, peerid, slot); + + nvl = nvlist_create(0); + nvlist_add_number(nvl, "slot", slot); + nvlist_add_number(nvl, "peerid", peerid); + + CLEAR(drv); + snprintf(drv.ifd_name, IFNAMSIZ, "%s", dco->ifname); + drv.ifd_cmd = OVPN_DEL_KEY; + drv.ifd_data = nvlist_pack(nvl, &drv.ifd_len); + + ret = ioctl(dco->fd, SIOCSDRVSPEC, &drv); + if (ret) + { + msg(M_WARN | M_ERRNO, "Failed to delete key"); + } + + free(drv.ifd_data); + nvlist_destroy(nvl); + + return ret; +} + +static nvlist_t * +key_to_nvlist(const uint8_t *key, const uint8_t *implicit_iv, const char *ciphername) +{ + nvlist_t *nvl; + size_t key_len; + + nvl = nvlist_create(0); + + nvlist_add_string(nvl, "cipher", ciphername); + + if (strcmp(ciphername, "none") != 0) + { + key_len = cipher_kt_key_size(ciphername); + + nvlist_add_binary(nvl, "key", key, key_len); + nvlist_add_binary(nvl, "iv", implicit_iv, 8); + } + + return (nvl); +} + +static int +start_tun(dco_context_t *dco) +{ + struct ifdrv drv; + int ret; + + CLEAR(drv); + snprintf(drv.ifd_name, IFNAMSIZ, "%s", dco->ifname); + drv.ifd_cmd = OVPN_START_VPN; + + ret = ioctl(dco->fd, SIOCSDRVSPEC, &drv); + if (ret) + { + msg(M_ERR | M_ERRNO, "Failed to start vpn"); + } + + return ret; +} + +int +dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, + dco_key_slot_t slot, + const uint8_t *encrypt_key, const uint8_t *encrypt_iv, + const uint8_t *decrypt_key, const uint8_t *decrypt_iv, + const char *ciphername) +{ + struct ifdrv drv; + nvlist_t *nvl; + int ret; + + msg(D_DCO_DEBUG, "%s: slot %d, key-id %d, peer-id %d, cipher %s", + __func__, slot, keyid, peerid, ciphername); + + nvl = nvlist_create(0); + + nvlist_add_number(nvl, "slot", slot); + nvlist_add_number(nvl, "keyid", keyid); + nvlist_add_number(nvl, "peerid", peerid); + + nvlist_add_nvlist(nvl, "encrypt", + key_to_nvlist(encrypt_key, encrypt_iv, ciphername)); + nvlist_add_nvlist(nvl, "decrypt", + key_to_nvlist(decrypt_key, decrypt_iv, ciphername)); + + CLEAR(drv); + snprintf(drv.ifd_name, IFNAMSIZ, "%s", dco->ifname); + drv.ifd_cmd = OVPN_NEW_KEY; + drv.ifd_data = nvlist_pack(nvl, &drv.ifd_len); + + ret = ioctl(dco->fd, SIOCSDRVSPEC, &drv); + if (ret) + { + msg(M_ERR | M_ERRNO, "Failed to set key"); + } + else + { + ret = start_tun(dco); + } + + free(drv.ifd_data); + nvlist_destroy(nvl); + + return ret; +} + +int +dco_set_peer(dco_context_t *dco, unsigned int peerid, + int keepalive_interval, int keepalive_timeout, + int mss) +{ + struct ifdrv drv; + nvlist_t *nvl; + int ret; + + msg(D_DCO_DEBUG, "%s: peer-id %d, ping interval %d, ping timeout %d", + __func__, peerid, keepalive_interval, keepalive_timeout); + + nvl = nvlist_create(0); + nvlist_add_number(nvl, "peerid", peerid); + nvlist_add_number(nvl, "interval", keepalive_interval); + nvlist_add_number(nvl, "timeout", keepalive_timeout); + + CLEAR(drv); + snprintf(drv.ifd_name, IFNAMSIZ, "%s", dco->ifname); + drv.ifd_cmd = OVPN_SET_PEER; + drv.ifd_data = nvlist_pack(nvl, &drv.ifd_len); + + ret = ioctl(dco->fd, SIOCSDRVSPEC, &drv); + if (ret) + { + msg(M_WARN | M_ERRNO, "Failed to set keepalive"); + } + + free(drv.ifd_data); + nvlist_destroy(nvl); + + return ret; +} + +int +dco_do_read(dco_context_t *dco) +{ + struct ifdrv drv; + uint8_t buf[4096]; + nvlist_t *nvl; + enum ovpn_notif_type type; + int ret; + + /* Flush any pending data from the pipe. */ + (void)read(dco->pipefd[1], buf, sizeof(buf)); + + CLEAR(drv); + snprintf(drv.ifd_name, IFNAMSIZ, "%s", dco->ifname); + drv.ifd_cmd = OVPN_GET_PKT; + drv.ifd_data = buf; + drv.ifd_len = sizeof(buf); + + ret = ioctl(dco->fd, SIOCGDRVSPEC, &drv); + if (ret) + { + msg(M_WARN | M_ERRNO, "Failed to read control packet"); + return -errno; + } + + nvl = nvlist_unpack(buf, drv.ifd_len, 0); + if (!nvl) + { + msg(M_WARN, "Failed to unpack nvlist"); + return -EINVAL; + } + + dco->dco_message_peer_id = nvlist_get_number(nvl, "peerid"); + + type = nvlist_get_number(nvl, "notification"); + switch (type) + { + case OVPN_NOTIF_DEL_PEER: + dco->dco_del_peer_reason = OVPN_DEL_PEER_REASON_EXPIRED; + + if (nvlist_exists_number(nvl, "del_reason")) + { + uint32_t reason = nvlist_get_number(nvl, "del_reason"); + if (reason == OVPN_DEL_REASON_TIMEOUT) + { + dco->dco_del_peer_reason = OVPN_DEL_PEER_REASON_EXPIRED; + } + else + { + dco->dco_del_peer_reason = OVPN_DEL_PEER_REASON_USERSPACE; + } + } + + if (nvlist_exists_nvlist(nvl, "bytes")) + { + const nvlist_t *bytes = nvlist_get_nvlist(nvl, "bytes"); + + dco->dco_read_bytes = nvlist_get_number(bytes, "in"); + dco->dco_write_bytes = nvlist_get_number(bytes, "out"); + } + + dco->dco_message_type = OVPN_CMD_DEL_PEER; + break; + + default: + msg(M_WARN, "Unknown kernel notification %d", type); + break; + } + + nvlist_destroy(nvl); + + return 0; +} + +int +dco_do_write(dco_context_t *dco, int peer_id, struct buffer *buf) +{ + /* Control packets are passed through the socket, so this should never get + * called. See should_use_dco_socket(). */ + ASSERT(0); + return -EINVAL; +} + +bool +dco_available(int msglevel) +{ + struct if_clonereq ifcr; + char *buf = NULL; + int fd; + int ret; + bool available = false; + + /* Attempt to load the module. Ignore errors, because it might already be + * loaded, or built into the kernel. */ + (void)kldload("if_ovpn"); + + fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0); + if (fd < 0) + { + return false; + } + + CLEAR(ifcr); + + /* List cloners and check if openvpn is there. That tells us if this kernel + * supports if_ovpn (i.e. DCO) or not. */ + ret = ioctl(fd, SIOCIFGCLONERS, &ifcr); + if (ret != 0) + { + goto out; + } + + buf = malloc(ifcr.ifcr_total * IFNAMSIZ); + + ifcr.ifcr_count = ifcr.ifcr_total; + ifcr.ifcr_buffer = buf; + ret = ioctl(fd, SIOCIFGCLONERS, &ifcr); + if (ret != 0) + { + goto out; + } + + for (int i = 0; i < ifcr.ifcr_total; i++) + { + if (strcmp(buf + (i * IFNAMSIZ), "openvpn") == 0) + { + available = true; + goto out; + } + } + +out: + free(buf); + close(fd); + + return available; +} + +void +dco_event_set(dco_context_t *dco, struct event_set *es, void *arg) +{ + struct ifdrv drv; + nvlist_t *nvl; + uint8_t buf[128]; + int ret; + + if (!dco || !dco->open) + { + return; + } + + CLEAR(drv); + snprintf(drv.ifd_name, IFNAMSIZ, "%s", dco->ifname); + drv.ifd_cmd = OVPN_POLL_PKT; + drv.ifd_len = sizeof(buf); + drv.ifd_data = buf; + + ret = ioctl(dco->fd, SIOCGDRVSPEC, &drv); + if (ret) + { + msg(M_WARN | M_ERRNO, "Failed to poll for packets"); + return; + } + + nvl = nvlist_unpack(buf, drv.ifd_len, 0); + if (!nvl) + { + msg(M_WARN, "Failed to unpack nvlist"); + return; + } + + if (nvlist_get_number(nvl, "pending") > 0) + { + (void)write(dco->pipefd[0], " ", 1); + event_ctl(es, dco->pipefd[1], EVENT_READ, arg); + } + + nvlist_destroy(nvl); +} + +static void +dco_update_peer_stat(struct multi_context *m, uint32_t peerid, const nvlist_t *nvl) +{ + struct hash_element *he; + struct hash_iterator hi; + + hash_iterator_init(m->hash, &hi); + + while ((he = hash_iterator_next(&hi))) + { + struct multi_instance *mi = (struct multi_instance *) he->value; + + if (mi->context.c2.tls_multi->peer_id != peerid) + { + continue; + } + + mi->context.c2.dco_read_bytes = nvlist_get_number(nvl, "in"); + mi->context.c2.dco_write_bytes = nvlist_get_number(nvl, "out"); + + return; + } + + msg(M_INFO, "Peer %d returned by kernel, but not found locally", peerid); +} + +int +dco_get_peer_stats_multi(dco_context_t *dco, struct multi_context *m) +{ + + struct ifdrv drv; + uint8_t buf[4096]; + nvlist_t *nvl; + const nvlist_t *const *nvpeers; + size_t npeers; + int ret; + + if (!dco || !dco->open) + { + return 0; + } + + CLEAR(drv); + snprintf(drv.ifd_name, IFNAMSIZ, "%s", dco->ifname); + drv.ifd_cmd = OVPN_GET_PEER_STATS; + drv.ifd_len = sizeof(buf); + drv.ifd_data = buf; + + ret = ioctl(dco->fd, SIOCGDRVSPEC, &drv); + if (ret) + { + msg(M_WARN | M_ERRNO, "Failed to get peer stats"); + return -EINVAL; + } + + nvl = nvlist_unpack(buf, drv.ifd_len, 0); + if (!nvl) + { + msg(M_WARN, "Failed to unpack nvlist"); + return -EINVAL; + } + + if (!nvlist_exists_nvlist_array(nvl, "peers")) + { + /* no peers */ + return 0; + } + + nvpeers = nvlist_get_nvlist_array(nvl, "peers", &npeers); + for (size_t i = 0; i < npeers; i++) + { + const nvlist_t *peer = nvpeers[i]; + uint32_t peerid = nvlist_get_number(peer, "peerid"); + + dco_update_peer_stat(m, peerid, nvlist_get_nvlist(peer, "bytes")); + } + + return 0; +} + +int +dco_get_peer_stats(struct context *c) +{ + /* Not implemented. */ + return 0; +} + +const char * +dco_get_supported_ciphers() +{ + return "none:AES-256-GCM:AES-192-GCM:AES-128-GCM:CHACHA20-POLY1305"; +} + +#endif /* defined(ENABLE_DCO) && defined(TARGET_FREEBSD) */ diff --git a/src/openvpn/dco_freebsd.h b/src/openvpn/dco_freebsd.h new file mode 100644 index 00000000000..2e35f3acecf --- /dev/null +++ b/src/openvpn/dco_freebsd.h @@ -0,0 +1,63 @@ +/* + * Interface to FreeBSD dco networking code + * + * Copyright (C) 2022 Rubicon Communications, LLC (Netgate). All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program (see the file COPYING included with this + * distribution); if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#ifndef DCO_FREEBSD_H +#define DCO_FREEBSD_H + +#if defined(ENABLE_DCO) && defined(TARGET_FREEBSD) + +#include "buffer.h" +#include "event.h" + +#include "ovpn_dco_freebsd.h" + +#define DCO_IROUTE_METRIC 100 + +typedef enum ovpn_key_slot dco_key_slot_t; +typedef enum ovpn_key_cipher dco_cipher_t; + +enum ovpn_message_type_t { + OVPN_CMD_DEL_PEER, + OVPN_CMD_PACKET, +}; + +enum ovpn_del_reason_t { + OVPN_DEL_PEER_REASON_EXPIRED, + OVPN_DEL_PEER_REASON_TRANSPORT_ERROR, + OVPN_DEL_PEER_REASON_USERSPACE, +}; + +typedef struct dco_context { + bool open; + int fd; + int pipefd[2]; + + char ifname[IFNAMSIZ]; + + struct buffer dco_packet_in; + + int dco_message_type; + int dco_message_peer_id; + int dco_del_peer_reason; + uint64_t dco_read_bytes; + uint64_t dco_write_bytes; +} dco_context_t; + +#endif /* defined(ENABLE_DCO) && defined(TARGET_FREEBSD) */ +#endif /* ifndef DCO_FREEBSD_H */ diff --git a/src/openvpn/dco_internal.h b/src/openvpn/dco_internal.h new file mode 100644 index 00000000000..7afcfc4486b --- /dev/null +++ b/src/openvpn/dco_internal.h @@ -0,0 +1,80 @@ +/* + * OpenVPN -- An application to securely tunnel IP networks + * over a single TCP/UDP port, with support for SSL/TLS-based + * session authentication and key exchange, + * packet encryption, packet authentication, and + * packet compression. + * + * Copyright (C) 2022-2023 Antonio Quartulli + * Copyright (C) 2022-2023 OpenVPN Inc + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program (see the file COPYING included with this + * distribution); if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#ifndef DCO_INTERNAL_H +#define DCO_INTERNAL_H + +#if defined(ENABLE_DCO) + +#include "dco_freebsd.h" +#include "dco_linux.h" +#include "dco_win.h" + +/** + * This file contains the internal DCO API definition. + * It is expected that this file is included only in dco.h. + * The OpenVPN code should never directly include this file + */ + +static inline dco_cipher_t +dco_get_cipher(const char *cipher) +{ + if (strcmp(cipher, "AES-256-GCM") == 0 || strcmp(cipher, "AES-128-GCM") == 0 + || strcmp(cipher, "AES-192-GCM") == 0) + { + return OVPN_CIPHER_ALG_AES_GCM; + } + else if (strcmp(cipher, "CHACHA20-POLY1305") == 0) + { + return OVPN_CIPHER_ALG_CHACHA20_POLY1305; + } + else + { + msg(M_FATAL, "DCO: provided unsupported cipher: %s", cipher); + } +} + +/** + * The following are the DCO APIs used to control the driver. + * They are implemented by dco_linux.c + */ + +int dco_new_peer(dco_context_t *dco, unsigned int peerid, int sd, + struct sockaddr *localaddr, struct sockaddr *remoteaddr, + struct in_addr *remote_in4, struct in6_addr *remote_in6); + +int dco_del_peer(dco_context_t *dco, unsigned int peerid); + +int dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, + dco_key_slot_t slot, + const uint8_t *encrypt_key, const uint8_t *encrypt_iv, + const uint8_t *decrypt_key, const uint8_t *decrypt_iv, + const char *ciphername); + +int dco_del_key(dco_context_t *dco, unsigned int peerid, dco_key_slot_t slot); + +int dco_swap_keys(dco_context_t *dco, unsigned int peerid); + +#endif /* defined(ENABLE_DCO) */ +#endif /* ifndef DCO_INTERNAL_H */ diff --git a/src/openvpn/dco_linux.c b/src/openvpn/dco_linux.c new file mode 100644 index 00000000000..c84f9cfe1ba --- /dev/null +++ b/src/openvpn/dco_linux.c @@ -0,0 +1,963 @@ +/* + * Interface to linux dco networking code + * + * Copyright (C) 2020-2023 Antonio Quartulli + * Copyright (C) 2020-2023 Arne Schwabe + * Copyright (C) 2020-2023 OpenVPN Inc + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program (see the file COPYING included with this + * distribution); if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#elif defined(_MSC_VER) +#include "config-msvc.h" +#endif + +#if defined(ENABLE_DCO) && defined(TARGET_LINUX) + +#include "syshead.h" + +#include "dco_linux.h" +#include "errlevel.h" +#include "buffer.h" +#include "networking.h" +#include "openvpn.h" + +#include "socket.h" +#include "tun.h" +#include "ssl.h" +#include "fdmisc.h" +#include "ssl_verify.h" + +#include "ovpn_dco_linux.h" + +#include +#include +#include +#include +#include + + +/* libnl < 3.5.0 does not set the NLA_F_NESTED on its own, therefore we + * have to explicitly do it to prevent the kernel from failing upon + * parsing of the message + */ +#define nla_nest_start(_msg, _type) \ + nla_nest_start(_msg, (_type) | NLA_F_NESTED) + +static int ovpn_get_mcast_id(dco_context_t *dco); + +void dco_check_key_ctx(const struct key_ctx_bi *key); + +typedef int (*ovpn_nl_cb)(struct nl_msg *msg, void *arg); + +/** + * @brief resolves the netlink ID for ovpn-dco + * + * This function queries the kernel via a netlink socket + * whether the ovpn-dco netlink namespace is available + * + * This function can be used to determine if the kernel + * supports DCO offloading. + * + * @return ID on success, negative error code on error + */ +static int +resolve_ovpn_netlink_id(int msglevel) +{ + int ret; + struct nl_sock *nl_sock = nl_socket_alloc(); + + ret = genl_connect(nl_sock); + if (ret) + { + msg(msglevel, "Cannot connect to generic netlink: %s", + nl_geterror(ret)); + goto err_sock; + } + set_cloexec(nl_socket_get_fd(nl_sock)); + + ret = genl_ctrl_resolve(nl_sock, OVPN_NL_NAME); + if (ret < 0) + { + msg(msglevel, "Cannot find ovpn_dco netlink component: %s", + nl_geterror(ret)); + } + +err_sock: + nl_socket_free(nl_sock); + return ret; +} + +static struct nl_msg * +ovpn_dco_nlmsg_create(dco_context_t *dco, enum ovpn_nl_commands cmd) +{ + struct nl_msg *nl_msg = nlmsg_alloc(); + if (!nl_msg) + { + msg(M_ERR, "cannot allocate netlink message"); + return NULL; + } + + genlmsg_put(nl_msg, 0, 0, dco->ovpn_dco_id, 0, 0, cmd, 0); + NLA_PUT_U32(nl_msg, OVPN_ATTR_IFINDEX, dco->ifindex); + + return nl_msg; +nla_put_failure: + nlmsg_free(nl_msg); + msg(M_INFO, "cannot put into netlink message"); + return NULL; +} + +static int +ovpn_nl_recvmsgs(dco_context_t *dco, const char *prefix) +{ + int ret = nl_recvmsgs(dco->nl_sock, dco->nl_cb); + + switch (ret) + { + case -NLE_INTR: + msg(M_WARN, "%s: netlink received interrupt due to signal - ignoring", prefix); + break; + + case -NLE_NOMEM: + msg(M_ERR, "%s: netlink out of memory error", prefix); + break; + + case -M_ERR: + msg(M_WARN, "%s: netlink reports blocking read - aborting wait", prefix); + break; + + case -NLE_NODEV: + msg(M_ERR, "%s: netlink reports device not found:", prefix); + break; + + case -NLE_OBJ_NOTFOUND: + msg(M_INFO, "%s: netlink reports object not found, ovpn-dco unloaded?", prefix); + break; + + default: + if (ret) + { + msg(M_NONFATAL|M_ERRNO, "%s: netlink reports error (%d): %s", prefix, ret, nl_geterror(-ret)); + } + break; + } + + return ret; +} + +/** + * Send a prepared netlink message and registers cb as callback if non-null. + * + * The method will also free nl_msg + * @param dco The dco context to use + * @param nl_msg the message to use + * @param cb An optional callback if the caller expects an answer + * @param prefix A prefix to report in the error message to give the user context + * @return status of sending the message + */ +static int +ovpn_nl_msg_send(dco_context_t *dco, struct nl_msg *nl_msg, ovpn_nl_cb cb, + const char *prefix) +{ + dco->status = 1; + + nl_cb_set(dco->nl_cb, NL_CB_VALID, NL_CB_CUSTOM, cb, dco); + nl_send_auto(dco->nl_sock, nl_msg); + + while (dco->status == 1) + { + ovpn_nl_recvmsgs(dco, prefix); + } + + if (dco->status < 0) + { + msg(M_INFO, "%s: failed to send netlink message: %s (%d)", + prefix, strerror(-dco->status), dco->status); + } + + return dco->status; +} + +struct sockaddr * +mapped_v4_to_v6(struct sockaddr *sock, struct gc_arena *gc) +{ + struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)sock; + if (sock->sa_family == AF_INET6 && IN6_IS_ADDR_V4MAPPED(&sock6->sin6_addr)) + { + + struct sockaddr_in *sock4; + ALLOC_OBJ_CLEAR_GC(sock4, struct sockaddr_in, gc); + memcpy(&sock4->sin_addr, sock6->sin6_addr.s6_addr + 12, 4); + sock4->sin_port = sock6->sin6_port; + sock4->sin_family = AF_INET; + return (struct sockaddr *)sock4; + } + return sock; +} + +int +dco_new_peer(dco_context_t *dco, unsigned int peerid, int sd, + struct sockaddr *localaddr, struct sockaddr *remoteaddr, + struct in_addr *remote_in4, struct in6_addr *remote_in6) +{ + struct gc_arena gc = gc_new(); + const char *remotestr = "[undefined]"; + if (remoteaddr) + { + remotestr = print_sockaddr(remoteaddr, &gc); + } + msg(D_DCO_DEBUG, "%s: peer-id %d, fd %d, remote addr: %s", __func__, + peerid, sd, remotestr); + + struct nl_msg *nl_msg = ovpn_dco_nlmsg_create(dco, OVPN_CMD_NEW_PEER); + struct nlattr *attr = nla_nest_start(nl_msg, OVPN_ATTR_NEW_PEER); + int ret = -EMSGSIZE; + + NLA_PUT_U32(nl_msg, OVPN_NEW_PEER_ATTR_PEER_ID, peerid); + NLA_PUT_U32(nl_msg, OVPN_NEW_PEER_ATTR_SOCKET, sd); + + /* Set the remote endpoint if defined (for UDP) */ + if (remoteaddr) + { + remoteaddr = mapped_v4_to_v6(remoteaddr, &gc); + int alen = af_addr_size(remoteaddr->sa_family); + + NLA_PUT(nl_msg, OVPN_NEW_PEER_ATTR_SOCKADDR_REMOTE, alen, remoteaddr); + } + + if (localaddr) + { + localaddr = mapped_v4_to_v6(localaddr, &gc); + if (localaddr->sa_family == AF_INET) + { + NLA_PUT(nl_msg, OVPN_NEW_PEER_ATTR_LOCAL_IP, sizeof(struct in_addr), + &((struct sockaddr_in *)localaddr)->sin_addr); + } + else if (localaddr->sa_family == AF_INET6) + { + NLA_PUT(nl_msg, OVPN_NEW_PEER_ATTR_LOCAL_IP, sizeof(struct in6_addr), + &((struct sockaddr_in6 *)localaddr)->sin6_addr); + } + } + + /* Set the primary VPN IP addresses of the peer */ + if (remote_in4) + { + NLA_PUT_U32(nl_msg, OVPN_NEW_PEER_ATTR_IPV4, remote_in4->s_addr); + } + if (remote_in6) + { + NLA_PUT(nl_msg, OVPN_NEW_PEER_ATTR_IPV6, sizeof(struct in6_addr), + remote_in6); + } + nla_nest_end(nl_msg, attr); + + ret = ovpn_nl_msg_send(dco, nl_msg, NULL, __func__); + +nla_put_failure: + nlmsg_free(nl_msg); + gc_free(&gc); + return ret; +} + +static int +ovpn_nl_cb_finish(struct nl_msg (*msg) __attribute__ ((unused)), void *arg) +{ + int *status = arg; + + *status = 0; + return NL_SKIP; +} + +/* This function is used as error callback on the netlink socket. + * When something goes wrong and the kernel returns an error, this function is + * invoked. + * + * We pass the error code to the user by means of a variable pointed by *arg + * (supplied by the user when setting this callback) and we parse the kernel + * reply to see if it contains a human-readable error. If found, it is printed. + */ +static int +ovpn_nl_cb_error(struct sockaddr_nl (*nla) __attribute__ ((unused)), + struct nlmsgerr *err, void *arg) +{ + struct nlmsghdr *nlh = (struct nlmsghdr *)err - 1; + struct nlattr *tb_msg[NLMSGERR_ATTR_MAX + 1]; + int len = nlh->nlmsg_len; + struct nlattr *attrs; + int *ret = arg; + int ack_len = sizeof(*nlh) + sizeof(int) + sizeof(*nlh); + + *ret = err->error; + + if (!(nlh->nlmsg_flags & NLM_F_ACK_TLVS)) + { + return NL_STOP; + } + + if (!(nlh->nlmsg_flags & NLM_F_CAPPED)) + { + ack_len += err->msg.nlmsg_len - sizeof(*nlh); + } + + if (len <= ack_len) + { + return NL_STOP; + } + + attrs = (void *)((unsigned char *)nlh + ack_len); + len -= ack_len; + + nla_parse(tb_msg, NLMSGERR_ATTR_MAX, attrs, len, NULL); + if (tb_msg[NLMSGERR_ATTR_MSG]) + { + len = strnlen((char *)nla_data(tb_msg[NLMSGERR_ATTR_MSG]), + nla_len(tb_msg[NLMSGERR_ATTR_MSG])); + msg(M_WARN, "kernel error: %*s\n", len, + (char *)nla_data(tb_msg[NLMSGERR_ATTR_MSG])); + } + + return NL_STOP; +} + +static void +ovpn_dco_init_netlink(dco_context_t *dco) +{ + dco->ovpn_dco_id = resolve_ovpn_netlink_id(M_ERR); + + dco->nl_sock = nl_socket_alloc(); + + if (!dco->nl_sock) + { + msg(M_ERR, "Cannot create netlink socket"); + } + + int ret = genl_connect(dco->nl_sock); + if (ret) + { + msg(M_ERR, "Cannot connect to generic netlink: %s", + nl_geterror(ret)); + } + + set_cloexec(nl_socket_get_fd(dco->nl_sock)); + + dco->nl_cb = nl_cb_alloc(NL_CB_DEFAULT); + if (!dco->nl_cb) + { + msg(M_ERR, "failed to allocate netlink callback"); + } + + nl_socket_set_cb(dco->nl_sock, dco->nl_cb); + + nl_cb_err(dco->nl_cb, NL_CB_CUSTOM, ovpn_nl_cb_error, &dco->status); + nl_cb_set(dco->nl_cb, NL_CB_FINISH, NL_CB_CUSTOM, ovpn_nl_cb_finish, + &dco->status); + nl_cb_set(dco->nl_cb, NL_CB_ACK, NL_CB_CUSTOM, ovpn_nl_cb_finish, + &dco->status); + + /* The async PACKET messages confuse libnl and it will drop them with + * wrong sequence numbers (NLE_SEQ_MISMATCH), so disable libnl's sequence + * number check */ + nl_socket_disable_seq_check(dco->nl_sock); + + /* nl library sets the buffer size to 32k/32k by default which is sometimes + * overrun with very fast connecting/disconnecting clients. + * TODO: fix this in a better and more reliable way */ + ASSERT(!nl_socket_set_buffer_size(dco->nl_sock, 1024*1024, 1024*1024)); +} + +bool +ovpn_dco_init(int mode, dco_context_t *dco) +{ + switch (mode) + { + case CM_TOP: + dco->ifmode = OVPN_MODE_MP; + break; + + case CM_P2P: + dco->ifmode = OVPN_MODE_P2P; + break; + + default: + ASSERT(false); + } + + ovpn_dco_init_netlink(dco); + return true; +} + +static void +ovpn_dco_uninit_netlink(dco_context_t *dco) +{ + nl_socket_free(dco->nl_sock); + dco->nl_sock = NULL; + + /* Decrease reference count */ + nl_cb_put(dco->nl_cb); + + CLEAR(dco); +} + +static void +ovpn_dco_register(dco_context_t *dco) +{ + msg(D_DCO_DEBUG, __func__); + ovpn_get_mcast_id(dco); + + if (dco->ovpn_dco_mcast_id < 0) + { + msg(M_ERR, "cannot get mcast group: %s", nl_geterror(dco->ovpn_dco_mcast_id)); + } + + /* Register for ovpn-dco specific multicast messages that the kernel may + * send + */ + int ret = nl_socket_add_membership(dco->nl_sock, dco->ovpn_dco_mcast_id); + if (ret) + { + msg(M_ERR, "%s: failed to join groups: %d", __func__, ret); + } + + /* Register for non-data packets that ovpn-dco may receive. They will be + * forwarded to userspace + */ + struct nl_msg *nl_msg = ovpn_dco_nlmsg_create(dco, OVPN_CMD_REGISTER_PACKET); + if (!nl_msg) + { + msg(M_ERR, "%s: cannot allocate message to register for control packets", + __func__); + } + + ret = ovpn_nl_msg_send(dco, nl_msg, NULL, __func__); + if (ret) + { + msg(M_ERR, "%s: failed to register for control packets: %d", __func__, + ret); + } + nlmsg_free(nl_msg); +} + +int +open_tun_dco(struct tuntap *tt, openvpn_net_ctx_t *ctx, const char *dev) +{ + msg(D_DCO_DEBUG, "%s: %s", __func__, dev); + ASSERT(tt->type == DEV_TYPE_TUN); + + int ret = net_iface_new(ctx, dev, "ovpn-dco", &tt->dco); + if (ret < 0) + { + msg(D_DCO_DEBUG, "Cannot create DCO interface %s: %d", dev, ret); + return ret; + } + + tt->dco.ifindex = if_nametoindex(dev); + if (!tt->dco.ifindex) + { + msg(M_FATAL, "DCO: cannot retrieve ifindex for interface %s", dev); + } + + tt->actual_name = string_alloc(dev, NULL); + uint8_t *dcobuf = malloc(65536); + buf_set_write(&tt->dco.dco_packet_in, dcobuf, 65536); + tt->dco.dco_message_peer_id = -1; + + ovpn_dco_register(&tt->dco); + + return 0; +} + +void +close_tun_dco(struct tuntap *tt, openvpn_net_ctx_t *ctx) +{ + msg(D_DCO_DEBUG, __func__); + + net_iface_del(ctx, tt->actual_name); + ovpn_dco_uninit_netlink(&tt->dco); + free(tt->dco.dco_packet_in.data); +} + +int +dco_swap_keys(dco_context_t *dco, unsigned int peerid) +{ + msg(D_DCO_DEBUG, "%s: peer-id %d", __func__, peerid); + + struct nl_msg *nl_msg = ovpn_dco_nlmsg_create(dco, OVPN_CMD_SWAP_KEYS); + if (!nl_msg) + { + return -ENOMEM; + } + + struct nlattr *attr = nla_nest_start(nl_msg, OVPN_ATTR_SWAP_KEYS); + int ret = -EMSGSIZE; + NLA_PUT_U32(nl_msg, OVPN_SWAP_KEYS_ATTR_PEER_ID, peerid); + nla_nest_end(nl_msg, attr); + + ret = ovpn_nl_msg_send(dco, nl_msg, NULL, __func__); + +nla_put_failure: + nlmsg_free(nl_msg); + return ret; +} + + +int +dco_del_peer(dco_context_t *dco, unsigned int peerid) +{ + msg(D_DCO_DEBUG, "%s: peer-id %d", __func__, peerid); + + struct nl_msg *nl_msg = ovpn_dco_nlmsg_create(dco, OVPN_CMD_DEL_PEER); + if (!nl_msg) + { + return -ENOMEM; + } + + struct nlattr *attr = nla_nest_start(nl_msg, OVPN_ATTR_DEL_PEER); + int ret = -EMSGSIZE; + NLA_PUT_U32(nl_msg, OVPN_DEL_PEER_ATTR_PEER_ID, peerid); + nla_nest_end(nl_msg, attr); + + ret = ovpn_nl_msg_send(dco, nl_msg, NULL, __func__); + +nla_put_failure: + nlmsg_free(nl_msg); + return ret; +} + + +int +dco_del_key(dco_context_t *dco, unsigned int peerid, + dco_key_slot_t slot) +{ + msg(D_DCO_DEBUG, "%s: peer-id %d, slot %d", __func__, peerid, slot); + + struct nl_msg *nl_msg = ovpn_dco_nlmsg_create(dco, OVPN_CMD_DEL_KEY); + if (!nl_msg) + { + return -ENOMEM; + } + + struct nlattr *attr = nla_nest_start(nl_msg, OVPN_ATTR_DEL_KEY); + int ret = -EMSGSIZE; + NLA_PUT_U32(nl_msg, OVPN_DEL_KEY_ATTR_PEER_ID, peerid); + NLA_PUT_U8(nl_msg, OVPN_DEL_KEY_ATTR_KEY_SLOT, slot); + nla_nest_end(nl_msg, attr); + + ret = ovpn_nl_msg_send(dco, nl_msg, NULL, __func__); + +nla_put_failure: + nlmsg_free(nl_msg); + return ret; +} + +int +dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, + dco_key_slot_t slot, + const uint8_t *encrypt_key, const uint8_t *encrypt_iv, + const uint8_t *decrypt_key, const uint8_t *decrypt_iv, + const char *ciphername) +{ + msg(D_DCO_DEBUG, "%s: slot %d, key-id %d, peer-id %d, cipher %s", + __func__, slot, keyid, peerid, ciphername); + + const size_t key_len = cipher_kt_key_size(ciphername); + const int nonce_tail_len = 8; + + struct nl_msg *nl_msg = ovpn_dco_nlmsg_create(dco, OVPN_CMD_NEW_KEY); + if (!nl_msg) + { + return -ENOMEM; + } + + dco_cipher_t dco_cipher = dco_get_cipher(ciphername); + + int ret = -EMSGSIZE; + struct nlattr *attr = nla_nest_start(nl_msg, OVPN_ATTR_NEW_KEY); + NLA_PUT_U32(nl_msg, OVPN_NEW_KEY_ATTR_PEER_ID, peerid); + NLA_PUT_U8(nl_msg, OVPN_NEW_KEY_ATTR_KEY_SLOT, slot); + NLA_PUT_U8(nl_msg, OVPN_NEW_KEY_ATTR_KEY_ID, keyid); + NLA_PUT_U16(nl_msg, OVPN_NEW_KEY_ATTR_CIPHER_ALG, dco_cipher); + + struct nlattr *key_enc = nla_nest_start(nl_msg, + OVPN_NEW_KEY_ATTR_ENCRYPT_KEY); + if (dco_cipher != OVPN_CIPHER_ALG_NONE) + { + NLA_PUT(nl_msg, OVPN_KEY_DIR_ATTR_CIPHER_KEY, key_len, encrypt_key); + NLA_PUT(nl_msg, OVPN_KEY_DIR_ATTR_NONCE_TAIL, nonce_tail_len, + encrypt_iv); + } + nla_nest_end(nl_msg, key_enc); + + struct nlattr *key_dec = nla_nest_start(nl_msg, + OVPN_NEW_KEY_ATTR_DECRYPT_KEY); + if (dco_cipher != OVPN_CIPHER_ALG_NONE) + { + NLA_PUT(nl_msg, OVPN_KEY_DIR_ATTR_CIPHER_KEY, key_len, decrypt_key); + NLA_PUT(nl_msg, OVPN_KEY_DIR_ATTR_NONCE_TAIL, nonce_tail_len, + decrypt_iv); + } + nla_nest_end(nl_msg, key_dec); + + nla_nest_end(nl_msg, attr); + + ret = ovpn_nl_msg_send(dco, nl_msg, NULL, __func__); + +nla_put_failure: + nlmsg_free(nl_msg); + return ret; +} + +int +dco_set_peer(dco_context_t *dco, unsigned int peerid, + int keepalive_interval, int keepalive_timeout, int mss) +{ + msg(D_DCO_DEBUG, "%s: peer-id %d, keepalive %d/%d, mss %d", __func__, + peerid, keepalive_interval, keepalive_timeout, mss); + + struct nl_msg *nl_msg = ovpn_dco_nlmsg_create(dco, OVPN_CMD_SET_PEER); + if (!nl_msg) + { + return -ENOMEM; + } + + struct nlattr *attr = nla_nest_start(nl_msg, OVPN_ATTR_SET_PEER); + int ret = -EMSGSIZE; + NLA_PUT_U32(nl_msg, OVPN_SET_PEER_ATTR_PEER_ID, peerid); + NLA_PUT_U32(nl_msg, OVPN_SET_PEER_ATTR_KEEPALIVE_INTERVAL, + keepalive_interval); + NLA_PUT_U32(nl_msg, OVPN_SET_PEER_ATTR_KEEPALIVE_TIMEOUT, + keepalive_timeout); + nla_nest_end(nl_msg, attr); + + ret = ovpn_nl_msg_send(dco, nl_msg, NULL, __func__); + +nla_put_failure: + nlmsg_free(nl_msg); + return ret; +} + +/* This function parses the reply provided by the kernel to the CTRL_CMD_GETFAMILY + * message. We parse the reply and we retrieve the multicast group ID associated + * with the "ovpn-dco" netlink family. + * + * The ID is later used to subscribe to the multicast group and be notified + * about any multicast message sent by the ovpn-dco kernel module. + */ +static int +mcast_family_handler(struct nl_msg *msg, void *arg) +{ + dco_context_t *dco = arg; + struct nlattr *tb[CTRL_ATTR_MAX + 1]; + struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg)); + + nla_parse(tb, CTRL_ATTR_MAX, genlmsg_attrdata(gnlh, 0), + genlmsg_attrlen(gnlh, 0), NULL); + + if (!tb[CTRL_ATTR_MCAST_GROUPS]) + { + return NL_SKIP; + } + + struct nlattr *mcgrp; + int rem_mcgrp; + nla_for_each_nested(mcgrp, tb[CTRL_ATTR_MCAST_GROUPS], rem_mcgrp) + { + struct nlattr *tb_mcgrp[CTRL_ATTR_MCAST_GRP_MAX + 1]; + + nla_parse(tb_mcgrp, CTRL_ATTR_MCAST_GRP_MAX, + nla_data(mcgrp), nla_len(mcgrp), NULL); + + if (!tb_mcgrp[CTRL_ATTR_MCAST_GRP_NAME] + || !tb_mcgrp[CTRL_ATTR_MCAST_GRP_ID]) + { + continue; + } + + if (strncmp(nla_data(tb_mcgrp[CTRL_ATTR_MCAST_GRP_NAME]), + OVPN_NL_MULTICAST_GROUP_PEERS, + nla_len(tb_mcgrp[CTRL_ATTR_MCAST_GRP_NAME])) != 0) + { + continue; + } + dco->ovpn_dco_mcast_id = nla_get_u32(tb_mcgrp[CTRL_ATTR_MCAST_GRP_ID]); + break; + } + + return NL_SKIP; +} +/** + * Lookup the multicast id for OpenVPN. This method and its help method currently + * hardcode the lookup to OVPN_NL_NAME and OVPN_NL_MULTICAST_GROUP_PEERS but + * extended in the future if we need to lookup more than one mcast id. + */ +static int +ovpn_get_mcast_id(dco_context_t *dco) +{ + dco->ovpn_dco_mcast_id = -ENOENT; + + /* Even though 'nlctrl' is a constant, there seem to be no library + * provided define for it */ + int ctrlid = genl_ctrl_resolve(dco->nl_sock, "nlctrl"); + + struct nl_msg *nl_msg = nlmsg_alloc(); + if (!nl_msg) + { + return -ENOMEM; + } + + genlmsg_put(nl_msg, 0, 0, ctrlid, 0, 0, CTRL_CMD_GETFAMILY, 0); + + int ret = -EMSGSIZE; + NLA_PUT_STRING(nl_msg, CTRL_ATTR_FAMILY_NAME, OVPN_NL_NAME); + + ret = ovpn_nl_msg_send(dco, nl_msg, mcast_family_handler, __func__); + +nla_put_failure: + nlmsg_free(nl_msg); + return ret; +} + +/* This function parses any netlink message sent by ovpn-dco to userspace */ +static int +ovpn_handle_msg(struct nl_msg *msg, void *arg) +{ + dco_context_t *dco = arg; + + struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg)); + struct nlattr *attrs[OVPN_ATTR_MAX + 1]; + struct nlmsghdr *nlh = nlmsg_hdr(msg); + + if (!genlmsg_valid_hdr(nlh, 0)) + { + msg(D_DCO, "ovpn-dco: invalid header"); + return NL_SKIP; + } + + if (nla_parse(attrs, OVPN_ATTR_MAX, genlmsg_attrdata(gnlh, 0), + genlmsg_attrlen(gnlh, 0), NULL)) + { + msg(D_DCO, "received bogus data from ovpn-dco"); + return NL_SKIP; + } + + /* we must know which interface this message is referring to in order to + * avoid mixing messages for other instances + */ + if (!attrs[OVPN_ATTR_IFINDEX]) + { + msg(D_DCO, "ovpn-dco: Received message without ifindex"); + return NL_SKIP; + } + + uint32_t ifindex = nla_get_u32(attrs[OVPN_ATTR_IFINDEX]); + if (ifindex != dco->ifindex) + { + msg(D_DCO_DEBUG, + "ovpn-dco: ignoring message (type=%d) for foreign ifindex %d", + gnlh->cmd, ifindex); + return NL_SKIP; + } + + /* based on the message type, we parse the subobject contained in the + * message, that stores the type-specific attributes. + * + * the "dco" object is then filled accordingly with the information + * retrieved from the message, so that the rest of the OpenVPN code can + * react as need be. + */ + switch (gnlh->cmd) + { + case OVPN_CMD_DEL_PEER: + { + if (!attrs[OVPN_ATTR_DEL_PEER]) + { + msg(D_DCO, "ovpn-dco: no attributes in OVPN_DEL_PEER message"); + return NL_SKIP; + } + + struct nlattr *dp_attrs[OVPN_DEL_PEER_ATTR_MAX + 1]; + if (nla_parse_nested(dp_attrs, OVPN_DEL_PEER_ATTR_MAX, + attrs[OVPN_ATTR_DEL_PEER], NULL)) + { + msg(D_DCO, "received bogus del peer packet data from ovpn-dco"); + return NL_SKIP; + } + + if (!dp_attrs[OVPN_DEL_PEER_ATTR_REASON]) + { + msg(D_DCO, "ovpn-dco: no reason in DEL_PEER message"); + return NL_SKIP; + } + if (!dp_attrs[OVPN_DEL_PEER_ATTR_PEER_ID]) + { + msg(D_DCO, "ovpn-dco: no peer-id in DEL_PEER message"); + return NL_SKIP; + } + int reason = nla_get_u8(dp_attrs[OVPN_DEL_PEER_ATTR_REASON]); + unsigned int peerid = nla_get_u32(dp_attrs[OVPN_DEL_PEER_ATTR_PEER_ID]); + + msg(D_DCO_DEBUG, "ovpn-dco: received CMD_DEL_PEER, ifindex: %d, peer-id %d, reason: %d", + ifindex, peerid, reason); + dco->dco_message_peer_id = peerid; + dco->dco_del_peer_reason = reason; + dco->dco_message_type = OVPN_CMD_DEL_PEER; + + break; + } + + case OVPN_CMD_PACKET: + { + if (!attrs[OVPN_ATTR_PACKET]) + { + msg(D_DCO, "ovpn-dco: no packet in OVPN_CMD_PACKET message"); + return NL_SKIP; + } + struct nlattr *pkt_attrs[OVPN_PACKET_ATTR_MAX + 1]; + + if (nla_parse_nested(pkt_attrs, OVPN_PACKET_ATTR_MAX, + attrs[OVPN_ATTR_PACKET], NULL)) + { + msg(D_DCO, "received bogus cmd packet data from ovpn-dco"); + return NL_SKIP; + } + if (!pkt_attrs[OVPN_PACKET_ATTR_PEER_ID]) + { + msg(D_DCO, "ovpn-dco: Received OVPN_CMD_PACKET message without peer id"); + return NL_SKIP; + } + if (!pkt_attrs[OVPN_PACKET_ATTR_PACKET]) + { + msg(D_DCO, "ovpn-dco: Received OVPN_CMD_PACKET message without packet"); + return NL_SKIP; + } + + unsigned int peerid = nla_get_u32(pkt_attrs[OVPN_PACKET_ATTR_PEER_ID]); + + uint8_t *data = nla_data(pkt_attrs[OVPN_PACKET_ATTR_PACKET]); + int len = nla_len(pkt_attrs[OVPN_PACKET_ATTR_PACKET]); + + msg(D_DCO_DEBUG, "ovpn-dco: received OVPN_PACKET_ATTR_PACKET, ifindex: %d peer-id: %d, len %d", + ifindex, peerid, len); + if (BLEN(&dco->dco_packet_in) > 0) + { + msg(D_DCO, "DCO packet buffer still full?!"); + return NL_SKIP; + } + buf_init(&dco->dco_packet_in, 0); + buf_write(&dco->dco_packet_in, data, len); + dco->dco_message_peer_id = peerid; + dco->dco_message_type = OVPN_CMD_PACKET; + break; + } + + default: + msg(D_DCO, "ovpn-dco: received unknown command: %d", gnlh->cmd); + dco->dco_message_type = 0; + return NL_SKIP; + } + + return NL_OK; +} + +int +dco_do_read(dco_context_t *dco) +{ + msg(D_DCO_DEBUG, __func__); + nl_cb_set(dco->nl_cb, NL_CB_VALID, NL_CB_CUSTOM, ovpn_handle_msg, dco); + + return ovpn_nl_recvmsgs(dco, __func__); +} + +int +dco_do_write(dco_context_t *dco, int peer_id, struct buffer *buf) +{ + packet_size_type len = BLEN(buf); + dmsg(D_STREAM_DEBUG, "DCO: WRITE %d offset=%d", (int)len, buf->offset); + + msg(D_DCO_DEBUG, "%s: peer-id %d, len=%d", __func__, peer_id, len); + + struct nl_msg *nl_msg = ovpn_dco_nlmsg_create(dco, OVPN_CMD_PACKET); + + if (!nl_msg) + { + return -ENOMEM; + } + + struct nlattr *attr = nla_nest_start(nl_msg, OVPN_ATTR_PACKET); + int ret = -EMSGSIZE; + NLA_PUT_U32(nl_msg, OVPN_PACKET_ATTR_PEER_ID, peer_id); + NLA_PUT(nl_msg, OVPN_PACKET_ATTR_PACKET, len, BSTR(buf)); + nla_nest_end(nl_msg, attr); + + ret = ovpn_nl_msg_send(dco, nl_msg, NULL, __func__); + if (ret) + { + goto nla_put_failure; + } + + /* return the length of the written data in case of success */ + ret = len; + +nla_put_failure: + nlmsg_free(nl_msg); + return ret; +} + +int +dco_get_peer_stats_multi(dco_context_t *dco, struct multi_context *m) +{ + /* Not implemented. */ + return 0; +} + +int +dco_get_peer_stats(struct context *c) +{ + /* Not implemented. */ + return 0; +} + +bool +dco_available(int msglevel) +{ + if (resolve_ovpn_netlink_id(D_DCO_DEBUG) < 0) + { + msg(msglevel, + "Note: Kernel support for ovpn-dco missing, disabling data channel offload."); + return false; + } + return true; +} + +void +dco_event_set(dco_context_t *dco, struct event_set *es, void *arg) +{ + if (dco && dco->nl_sock) + { + event_ctl(es, nl_socket_get_fd(dco->nl_sock), EVENT_READ, arg); + } +} + +const char * +dco_get_supported_ciphers() +{ + return "AES-128-GCM:AES-256-GCM:AES-192-GCM:CHACHA20-POLY1305"; +} + +#endif /* defined(ENABLE_DCO) && defined(TARGET_LINUX) */ diff --git a/src/openvpn/dco_linux.h b/src/openvpn/dco_linux.h new file mode 100644 index 00000000000..4d996d98c6b --- /dev/null +++ b/src/openvpn/dco_linux.h @@ -0,0 +1,61 @@ +/* + * Interface to linux dco networking code + * + * Copyright (C) 2020-2023 Antonio Quartulli + * Copyright (C) 2020-2023 Arne Schwabe + * Copyright (C) 2020-2023 OpenVPN Inc + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program (see the file COPYING included with this + * distribution); if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#ifndef DCO_LINUX_H +#define DCO_LINUX_H + +#if defined(ENABLE_DCO) && defined(TARGET_LINUX) + +#include "event.h" + +#include "ovpn_dco_linux.h" + +#include +#include + +typedef enum ovpn_key_slot dco_key_slot_t; +typedef enum ovpn_cipher_alg dco_cipher_t; + + +typedef struct +{ + struct nl_sock *nl_sock; + struct nl_cb *nl_cb; + int status; + + enum ovpn_mode ifmode; + + int ovpn_dco_id; + int ovpn_dco_mcast_id; + + unsigned int ifindex; + + struct buffer dco_packet_in; + + int dco_message_type; + int dco_message_peer_id; + int dco_del_peer_reason; + uint64_t dco_read_bytes; + uint64_t dco_write_bytes; +} dco_context_t; + +#endif /* defined(ENABLE_DCO) && defined(TARGET_LINUX) */ +#endif /* ifndef DCO_LINUX_H */ diff --git a/src/openvpn/dco_win.c b/src/openvpn/dco_win.c new file mode 100644 index 00000000000..7594024ceb0 --- /dev/null +++ b/src/openvpn/dco_win.c @@ -0,0 +1,467 @@ +/* + * Interface to ovpn-win-dco networking code + * + * Copyright (C) 2020-2023 Arne Schwabe + * Copyright (C) 2020-2023 OpenVPN Inc + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program (see the file COPYING included with this + * distribution); if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#elif defined(_MSC_VER) +#include "config-msvc.h" +#endif + +#if defined(_WIN32) + +#include "syshead.h" + +#include "dco.h" +#include "tun.h" +#include "crypto.h" +#include "ssl_common.h" +#include "openvpn.h" + +#include +#include +#include + +#if defined(__MINGW32__) +const IN_ADDR in4addr_any = { 0 }; +#endif + +struct tuntap +create_dco_handle(const char *devname, struct gc_arena *gc) +{ + struct tuntap tt = { .windows_driver = WINDOWS_DRIVER_DCO }; + const char *device_guid; + + tun_open_device(&tt, devname, &device_guid, gc); + + return tt; +} + +bool +ovpn_dco_init(int mode, dco_context_t *dco) +{ + return true; +} + +int +open_tun_dco(struct tuntap *tt, openvpn_net_ctx_t *ctx, const char *dev) +{ + ASSERT(0); + return 0; +} + +static void +dco_wait_ready(DWORD idx) +{ + for (int i = 0; i < 20; ++i) + { + MIB_IPINTERFACE_ROW row = {.InterfaceIndex = idx, .Family = AF_INET}; + if (GetIpInterfaceEntry(&row) != ERROR_NOT_FOUND) + { + break; + } + msg(D_DCO_DEBUG, "interface %ld not yet ready, retrying", idx); + Sleep(50); + } +} + +void +dco_start_tun(struct tuntap *tt) +{ + msg(D_DCO_DEBUG, "%s", __func__); + + /* reference the tt object inside the DCO context, because the latter will + * be passed around + */ + tt->dco.tt = tt; + + DWORD bytes_returned = 0; + if (!DeviceIoControl(tt->hand, OVPN_IOCTL_START_VPN, NULL, 0, NULL, 0, + &bytes_returned, NULL)) + { + msg(M_ERR, "DeviceIoControl(OVPN_IOCTL_START_VPN) failed"); + } + + /* Sometimes IP Helper API, which we use for setting IP address etc, + * complains that interface is not found. Give it some time to settle + */ + dco_wait_ready(tt->adapter_index); +} + +static void +dco_connect_wait(HANDLE handle, OVERLAPPED *ov, int timeout, struct signal_info *sig_info) +{ + volatile int *signal_received = &sig_info->signal_received; + /* GetOverlappedResultEx is available starting from Windows 8 */ + typedef BOOL (*get_overlapped_result_ex_t) (HANDLE, LPOVERLAPPED, LPDWORD, DWORD, BOOL); + get_overlapped_result_ex_t get_overlapped_result_ex = + (get_overlapped_result_ex_t)GetProcAddress(GetModuleHandle("Kernel32.dll"), + "GetOverlappedResultEx"); + + if (get_overlapped_result_ex == NULL) + { + msg(M_ERR, "Failed to load GetOverlappedResult()"); + } + + DWORD timeout_msec = timeout * 1000; + const int poll_interval_ms = 50; + + while (timeout_msec > 0) + { + timeout_msec -= poll_interval_ms; + + DWORD transferred; + if (get_overlapped_result_ex(handle, ov, &transferred, poll_interval_ms, FALSE) != 0) + { + /* TCP connection established by dco */ + return; + } + + DWORD err = GetLastError(); + if ((err != WAIT_TIMEOUT) && (err != ERROR_IO_INCOMPLETE)) + { + /* dco reported connection error */ + msg(M_NONFATAL | M_ERRNO, "dco connect error"); + register_signal(sig_info, SIGUSR1, "dco-connect-error"); + return; + } + + get_signal(signal_received); + if (*signal_received) + { + return; + } + + management_sleep(0); + } + + /* we end up here when timeout occurs in userspace */ + msg(M_NONFATAL, "dco connect timeout"); + register_signal(sig_info, SIGUSR1, "dco-connect-timeout"); +} + +void +dco_create_socket(HANDLE handle, struct addrinfo *remoteaddr, bool bind_local, + struct addrinfo *bind, int timeout, + struct signal_info *sig_info) +{ + msg(D_DCO_DEBUG, "%s", __func__); + + OVPN_NEW_PEER peer = { 0 }; + + struct sockaddr *local = NULL; + struct sockaddr *remote = remoteaddr->ai_addr; + + if (remoteaddr->ai_protocol == IPPROTO_TCP + || remoteaddr->ai_socktype == SOCK_STREAM) + { + peer.Proto = OVPN_PROTO_TCP; + } + else + { + peer.Proto = OVPN_PROTO_UDP; + } + + if (bind_local) + { + /* Use first local address with correct address family */ + while (bind && !local) + { + if (bind->ai_family == remote->sa_family) + { + local = bind->ai_addr; + } + bind = bind->ai_next; + } + } + + if (bind_local && !local) + { + msg(M_FATAL, "DCO: Socket bind failed: Address to bind lacks %s record", + addr_family_name(remote->sa_family)); + } + + if (remote->sa_family == AF_INET6) + { + peer.Remote.Addr6 = *((SOCKADDR_IN6 *)(remoteaddr->ai_addr)); + if (local) + { + peer.Local.Addr6 = *((SOCKADDR_IN6 *)local); + } + else + { + peer.Local.Addr6.sin6_addr = in6addr_any; + peer.Local.Addr6.sin6_port = 0; + peer.Local.Addr6.sin6_family = AF_INET6; + } + } + else if (remote->sa_family == AF_INET) + { + peer.Remote.Addr4 = *((SOCKADDR_IN *)(remoteaddr->ai_addr)); + if (local) + { + peer.Local.Addr4 = *((SOCKADDR_IN *)local); + } + else + { + peer.Local.Addr4.sin_addr = in4addr_any; + peer.Local.Addr4.sin_port = 0; + peer.Local.Addr4.sin_family = AF_INET; + } + } + else + { + ASSERT(0); + } + + OVERLAPPED ov = { 0 }; + if (!DeviceIoControl(handle, OVPN_IOCTL_NEW_PEER, &peer, sizeof(peer), NULL, 0, NULL, &ov)) + { + DWORD err = GetLastError(); + if (err != ERROR_IO_PENDING) + { + msg(M_ERR, "DeviceIoControl(OVPN_IOCTL_NEW_PEER) failed"); + } + else + { + dco_connect_wait(handle, &ov, timeout, sig_info); + } + } +} + +int +dco_new_peer(dco_context_t *dco, unsigned int peerid, int sd, + struct sockaddr *localaddr, struct sockaddr *remoteaddr, + struct in_addr *remote_in4, struct in6_addr *remote_in6) +{ + msg(D_DCO_DEBUG, "%s: peer-id %d, fd %d", __func__, peerid, sd); + return 0; +} + +int +dco_del_peer(dco_context_t *dco, unsigned int peerid) +{ + msg(D_DCO_DEBUG, "%s: peer-id %d", __func__, peerid); + + DWORD bytes_returned = 0; + if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_DEL_PEER, NULL, + 0, NULL, 0, &bytes_returned, NULL)) + { + msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_DEL_PEER) failed"); + return -1; + } + return 0; +} + +int +dco_set_peer(dco_context_t *dco, unsigned int peerid, + int keepalive_interval, int keepalive_timeout, int mss) +{ + msg(D_DCO_DEBUG, "%s: peer-id %d, keepalive %d/%d, mss %d", __func__, + peerid, keepalive_interval, keepalive_timeout, mss); + + OVPN_SET_PEER peer; + + peer.KeepaliveInterval = keepalive_interval; + peer.KeepaliveTimeout = keepalive_timeout; + peer.MSS = mss; + + DWORD bytes_returned = 0; + if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_SET_PEER, &peer, + sizeof(peer), NULL, 0, &bytes_returned, NULL)) + { + msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_SET_PEER) failed"); + return -1; + } + return 0; +} + +int +dco_new_key(dco_context_t *dco, unsigned int peerid, int keyid, + dco_key_slot_t slot, + const uint8_t *encrypt_key, const uint8_t *encrypt_iv, + const uint8_t *decrypt_key, const uint8_t *decrypt_iv, + const char *ciphername) +{ + msg(D_DCO_DEBUG, "%s: slot %d, key-id %d, peer-id %d, cipher %s", + __func__, slot, keyid, peerid, ciphername); + + const int nonce_len = 8; + size_t key_len = cipher_kt_key_size(ciphername); + + OVPN_CRYPTO_DATA crypto_data; + ZeroMemory(&crypto_data, sizeof(crypto_data)); + + crypto_data.CipherAlg = dco_get_cipher(ciphername); + crypto_data.KeyId = keyid; + crypto_data.PeerId = peerid; + crypto_data.KeySlot = slot; + + CopyMemory(crypto_data.Encrypt.Key, encrypt_key, key_len); + crypto_data.Encrypt.KeyLen = (char)key_len; + CopyMemory(crypto_data.Encrypt.NonceTail, encrypt_iv, nonce_len); + + CopyMemory(crypto_data.Decrypt.Key, decrypt_key, key_len); + crypto_data.Decrypt.KeyLen = (char)key_len; + CopyMemory(crypto_data.Decrypt.NonceTail, decrypt_iv, nonce_len); + + ASSERT(crypto_data.CipherAlg > 0); + + DWORD bytes_returned = 0; + + if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_NEW_KEY, &crypto_data, + sizeof(crypto_data), NULL, 0, &bytes_returned, NULL)) + { + msg(M_ERR, "DeviceIoControl(OVPN_IOCTL_NEW_KEY) failed"); + return -1; + } + return 0; +} +int +dco_del_key(dco_context_t *dco, unsigned int peerid, dco_key_slot_t slot) +{ + msg(D_DCO, "%s: peer-id %d, slot %d called but ignored", __func__, peerid, + slot); + /* FIXME: Implement in driver first */ + return 0; +} + +int +dco_swap_keys(dco_context_t *dco, unsigned int peer_id) +{ + msg(D_DCO_DEBUG, "%s: peer-id %d", __func__, peer_id); + + DWORD bytes_returned = 0; + if (!DeviceIoControl(dco->tt->hand, OVPN_IOCTL_SWAP_KEYS, NULL, 0, NULL, 0, + &bytes_returned, NULL)) + { + msg(M_ERR, "DeviceIoControl(OVPN_IOCTL_SWAP_KEYS) failed"); + return -1; + } + return 0; +} + +bool +dco_available(int msglevel) +{ + /* try to open device by symbolic name */ + HANDLE h = CreateFile("\\\\.\\ovpn-dco", GENERIC_READ | GENERIC_WRITE, + 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, NULL); + + if (h != INVALID_HANDLE_VALUE) + { + CloseHandle(h); + return true; + } + + DWORD err = GetLastError(); + if (err == ERROR_ACCESS_DENIED) + { + /* this likely means that device exists but is already in use, + * don't bail out since later we try to open all existing dco + * devices and then bail out if all devices are in use + */ + return true; + } + + msg(msglevel, "Note: ovpn-dco-win driver is missing, disabling data channel offload."); + return false; +} + +int +dco_do_read(dco_context_t *dco) +{ + /* no-op on windows */ + ASSERT(0); + return 0; +} + +int +dco_do_write(dco_context_t *dco, int peer_id, struct buffer *buf) +{ + /* no-op on windows */ + ASSERT(0); + return 0; +} + +int +dco_get_peer_stats_multi(dco_context_t *dco, struct multi_context *m) +{ + /* Not implemented. */ + return 0; +} + +int +dco_get_peer_stats(struct context *c) +{ + struct tuntap *tt = c->c1.tuntap; + + if (!tuntap_defined(tt)) + { + return -1; + } + + OVPN_STATS stats; + ZeroMemory(&stats, sizeof(OVPN_STATS)); + + DWORD bytes_returned = 0; + if (!DeviceIoControl(tt->hand, OVPN_IOCTL_GET_STATS, NULL, 0, + &stats, sizeof(stats), &bytes_returned, NULL)) + { + msg(M_WARN | M_ERRNO, "DeviceIoControl(OVPN_IOCTL_GET_STATS) failed"); + return -1; + } + + c->c2.dco_read_bytes = stats.TransportBytesReceived; + c->c2.dco_write_bytes = stats.TransportBytesSent; + + return 0; +} + +void +dco_event_set(dco_context_t *dco, struct event_set *es, void *arg) +{ + /* no-op on windows */ + ASSERT(0); +} + +const char * +dco_get_supported_ciphers() +{ + /* + * this API can be called either from user mode or kernel mode, + * which enables us to probe driver's chachapoly support + * (available starting from Windows 11) + */ + + BCRYPT_ALG_HANDLE h; + NTSTATUS status = BCryptOpenAlgorithmProvider(&h, L"CHACHA20_POLY1305", NULL, 0); + if (BCRYPT_SUCCESS(status)) + { + BCryptCloseAlgorithmProvider(h, 0); + return "AES-128-GCM:AES-256-GCM:AES-192-GCM:CHACHA20-POLY1305"; + } + else + { + return "AES-128-GCM:AES-256-GCM:AES-192-GCM"; + } +} + +#endif /* defined(_WIN32) */ diff --git a/src/openvpn/dco_win.h b/src/openvpn/dco_win.h new file mode 100644 index 00000000000..f20c47eb41c --- /dev/null +++ b/src/openvpn/dco_win.h @@ -0,0 +1,60 @@ +/* + * Interface to ovpn-win-dco networking code + * + * Copyright (C) 2020-2023 Arne Schwabe + * Copyright (C) 2020-2023 OpenVPN Inc + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program (see the file COPYING included with this + * distribution); if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef DCO_WIN_H +#define DCO_WIN_H + +#if defined(ENABLE_DCO) && defined(_WIN32) + +#include "buffer.h" +#include "ovpn_dco_win.h" +#include "sig.h" + +typedef OVPN_KEY_SLOT dco_key_slot_t; +typedef OVPN_CIPHER_ALG dco_cipher_t; + +struct dco_context { + struct tuntap *tt; +}; + +typedef struct dco_context dco_context_t; + +struct tuntap +create_dco_handle(const char *devname, struct gc_arena *gc); + +void +dco_create_socket(HANDLE handle, struct addrinfo *remoteaddr, bool bind_local, + struct addrinfo *bind, int timeout, + struct signal_info *sig_info); + +void +dco_start_tun(struct tuntap *tt); + +#else /* if defined(ENABLE_DCO) && defined(_WIN32) */ + +static inline void +dco_start_tun(struct tuntap *tt) +{ + ASSERT(false); +} + +#endif /* defined(_WIN32) */ +#endif /* ifndef DCO_H */ diff --git a/src/openvpn/dhcp.c b/src/openvpn/dhcp.c index b1274255d83..d54423e212e 100644 --- a/src/openvpn/dhcp.c +++ b/src/openvpn/dhcp.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -187,4 +187,4 @@ dhcp_extract_router_msg(struct buffer *ipbuf) } } return 0; -} +} \ No newline at end of file diff --git a/src/openvpn/dhcp.h b/src/openvpn/dhcp.h index 65fecf75e70..a8f43e3de0a 100644 --- a/src/openvpn/dhcp.h +++ b/src/openvpn/dhcp.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -83,4 +83,4 @@ struct dhcp_full { in_addr_t dhcp_extract_router_msg(struct buffer *ipbuf); -#endif /* ifndef DHCP_H */ +#endif /* ifndef DHCP_H */ \ No newline at end of file diff --git a/src/openvpn/dns.c b/src/openvpn/dns.c new file mode 100644 index 00000000000..9f2a7d5ecaf --- /dev/null +++ b/src/openvpn/dns.c @@ -0,0 +1,516 @@ +/* + * OpenVPN -- An application to securely tunnel IP networks + * over a single UDP port, with support for SSL/TLS-based + * session authentication and key exchange, + * packet encryption, packet authentication, and + * packet compression. + * + * Copyright (C) 2022-2023 OpenVPN Inc + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#elif defined(_MSC_VER) +#include "config-msvc.h" +#endif + +#include "syshead.h" + +#include "dns.h" +#include "socket.h" + +/** + * Parses a string as port and stores it + * + * @param port Pointer to in_port_t where the port value is stored + * @param addr Port number as string + * @return True if parsing was successful + */ +static bool +dns_server_port_parse(in_port_t *port, char *port_str) +{ + char *endptr; + errno = 0; + unsigned long tmp = strtoul(port_str, &endptr, 10); + if (errno || *endptr != '\0' || tmp == 0 || tmp > UINT16_MAX) + { + return false; + } + *port = (in_port_t)tmp; + return true; +} + +bool +dns_server_addr_parse(struct dns_server *server, const char *addr) +{ + if (!addr) + { + return false; + } + + char addrcopy[INET6_ADDRSTRLEN] = {0}; + size_t copylen = 0; + in_port_t port = 0; + int af; + + char *first_colon = strchr(addr, ':'); + char *last_colon = strrchr(addr, ':'); + + if (!first_colon || first_colon == last_colon) + { + /* IPv4 address with optional port, e.g. 1.2.3.4 or 1.2.3.4:853 */ + if (last_colon) + { + if (last_colon == addr || !dns_server_port_parse(&port, last_colon + 1)) + { + return false; + } + copylen = first_colon - addr; + } + af = AF_INET; + } + else + { + /* IPv6 address with optional port, e.g. ab::cd or [ab::cd]:853 */ + if (addr[0] == '[') + { + addr += 1; + char *bracket = last_colon - 1; + if (*bracket != ']' || bracket == addr || !dns_server_port_parse(&port, last_colon + 1)) + { + return false; + } + copylen = bracket - addr; + } + af = AF_INET6; + } + + /* Copy the address part into a temporary buffer and use that */ + if (copylen) + { + if (copylen >= sizeof(addrcopy)) + { + return false; + } + strncpy(addrcopy, addr, copylen); + addr = addrcopy; + } + + struct addrinfo *ai = NULL; + if (openvpn_getaddrinfo(0, addr, NULL, 0, NULL, af, &ai) != 0) + { + return false; + } + + if (ai->ai_family == AF_INET) + { + struct sockaddr_in *sin = (struct sockaddr_in *)ai->ai_addr; + server->addr4_defined = true; + server->addr4.s_addr = ntohl(sin->sin_addr.s_addr); + server->port4 = port; + } + else + { + struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)ai->ai_addr; + server->addr6_defined = true; + server->addr6 = sin6->sin6_addr; + server->port6 = port; + } + + freeaddrinfo(ai); + return true; +} + +void +dns_domain_list_append(struct dns_domain **entry, char **domains, struct gc_arena *gc) +{ + /* Fast forward to the end of the list */ + while (*entry) + { + entry = &((*entry)->next); + } + + /* Append all domains to the end of the list */ + while (*domains) + { + ALLOC_OBJ_CLEAR_GC(*entry, struct dns_domain, gc); + struct dns_domain *new = *entry; + new->name = *domains++; + entry = &new->next; + } +} + +bool +dns_server_priority_parse(long *priority, const char *str, bool pulled) +{ + char *endptr; + const long min = pulled ? 0 : INT8_MIN; + const long max = INT8_MAX; + long prio = strtol(str, &endptr, 10); + if (*endptr != '\0' || prio < min || prio > max) + { + return false; + } + *priority = prio; + return true; +} + +struct dns_server * +dns_server_get(struct dns_server **entry, long priority, struct gc_arena *gc) +{ + struct dns_server *obj = *entry; + while (true) + { + if (!obj || obj->priority > priority) + { + ALLOC_OBJ_CLEAR_GC(*entry, struct dns_server, gc); + (*entry)->next = obj; + (*entry)->priority = priority; + return *entry; + } + else if (obj->priority == priority) + { + return obj; + } + entry = &obj->next; + obj = *entry; + } +} + +bool +dns_options_verify(int msglevel, const struct dns_options *o) +{ + const struct dns_server *server = + o->servers ? o->servers : o->servers_prepull; + while (server) + { + if (!server->addr4_defined && !server->addr6_defined) + { + msg(msglevel, "ERROR: dns server %ld does not have an address assigned", server->priority); + return false; + } + server = server->next; + } + return true; +} + +static struct dns_domain * +clone_dns_domains(const struct dns_domain *domain, struct gc_arena *gc) +{ + struct dns_domain *new_list = NULL; + struct dns_domain **new_entry = &new_list; + + while (domain) + { + ALLOC_OBJ_CLEAR_GC(*new_entry, struct dns_domain, gc); + struct dns_domain *new_domain = *new_entry; + *new_domain = *domain; + new_entry = &new_domain->next; + domain = domain->next; + } + + return new_list; +} + +static struct dns_server * +clone_dns_servers(const struct dns_server *server, struct gc_arena *gc) +{ + struct dns_server *new_list = NULL; + struct dns_server **new_entry = &new_list; + + while (server) + { + ALLOC_OBJ_CLEAR_GC(*new_entry, struct dns_server, gc); + struct dns_server *new_server = *new_entry; + *new_server = *server; + new_server->domains = clone_dns_domains(server->domains, gc); + new_entry = &new_server->next; + server = server->next; + } + + return new_list; +} + +struct dns_options +clone_dns_options(const struct dns_options o, struct gc_arena *gc) +{ + struct dns_options clone; + memset(&clone, 0, sizeof(clone)); + clone.search_domains = clone_dns_domains(o.search_domains, gc); + clone.servers = clone_dns_servers(o.servers, gc); + clone.servers_prepull = clone_dns_servers(o.servers_prepull, gc); + return clone; +} + +void +dns_options_preprocess_pull(struct dns_options *o) +{ + o->servers_prepull = o->servers; + o->servers = NULL; +} + +void +dns_options_postprocess_pull(struct dns_options *o) +{ + struct dns_server **entry = &o->servers; + struct dns_server *server = *entry; + struct dns_server *server_pp = o->servers_prepull; + + while (server && server_pp) + { + if (server->priority > server_pp->priority) + { + /* Merge static server in front of pulled one */ + struct dns_server *next_pp = server_pp->next; + server_pp->next = server; + *entry = server_pp; + server = *entry; + server_pp = next_pp; + } + else if (server->priority == server_pp->priority) + { + /* Pulled server overrides static one */ + server_pp = server_pp->next; + } + entry = &server->next; + server = *entry; + } + + /* Append remaining local servers */ + if (server_pp) + { + *entry = server_pp; + } + + o->servers_prepull = NULL; +} + +static const char * +dnssec_value(const enum dns_security dnssec) +{ + switch (dnssec) + { + case DNS_SECURITY_YES: + return "yes"; + + case DNS_SECURITY_OPTIONAL: + return "optional"; + + case DNS_SECURITY_NO: + return "no"; + + default: + return "unset"; + } +} + +static const char * +transport_value(const enum dns_server_transport transport) +{ + switch (transport) + { + case DNS_TRANSPORT_HTTPS: + return "DoH"; + + case DNS_TRANSPORT_TLS: + return "DoT"; + + case DNS_TRANSPORT_PLAIN: + return "plain"; + + default: + return "unset"; + } +} + +static void +setenv_dns_option(struct env_set *es, + const char *format, int i, int j, + const char *value) +{ + char name[64]; + bool name_ok = false; + + if (j < 0) + { + name_ok = openvpn_snprintf(name, sizeof(name), format, i); + } + else + { + name_ok = openvpn_snprintf(name, sizeof(name), format, i, j); + } + + if (!name_ok) + { + msg(M_WARN, "WARNING: dns option setenv name buffer overflow"); + } + + setenv_str(es, name, value); +} + +void +setenv_dns_options(const struct dns_options *o, struct env_set *es) +{ + struct gc_arena gc = gc_new(); + const struct dns_server *s; + const struct dns_domain *d; + int i, j; + + for (i = 1, d = o->search_domains; d != NULL; i++, d = d->next) + { + setenv_dns_option(es, "dns_search_domain_%d", i, -1, d->name); + } + + for (i = 1, s = o->servers; s != NULL; i++, s = s->next) + { + if (s->addr4_defined) + { + setenv_dns_option(es, "dns_server_%d_address4", i, -1, + print_in_addr_t(s->addr4.s_addr, 0, &gc)); + } + if (s->port4) + { + setenv_dns_option(es, "dns_server_%d_port4", i, -1, + print_in_port_t(s->port4, &gc)); + } + + if (s->addr6_defined) + { + setenv_dns_option(es, "dns_server_%d_address6", i, -1, + print_in6_addr(s->addr6, 0, &gc)); + } + if (s->port6) + { + setenv_dns_option(es, "dns_server_%d_port6", i, -1, + print_in_port_t(s->port6, &gc)); + } + + if (s->domains) + { + const char *format = s->domain_type == DNS_RESOLVE_DOMAINS ? + "dns_server_%d_resolve_domain_%d" : "dns_server_%d_exclude_domain_%d"; + for (j = 1, d = s->domains; d != NULL; j++, d = d->next) + { + setenv_dns_option(es, format, i, j, d->name); + } + } + + if (s->dnssec) + { + setenv_dns_option(es, "dns_server_%d_dnssec", i, -1, + dnssec_value(s->dnssec)); + } + + if (s->transport) + { + setenv_dns_option(es, "dns_server_%d_transport", i, -1, + transport_value(s->transport)); + } + if (s->sni) + { + setenv_dns_option(es, "dns_server_%d_sni", i, -1, s->sni); + } + } + + gc_free(&gc); +} + +void +show_dns_options(const struct dns_options *o) +{ + struct gc_arena gc = gc_new(); + + int i = 1; + struct dns_server *server = o->servers_prepull ? o->servers_prepull : o->servers; + while (server) + { + msg(D_SHOW_PARMS, " DNS server #%d:", i++); + + if (server->addr4_defined) + { + const char *addr = print_in_addr_t(server->addr4.s_addr, 0, &gc); + if (server->port4) + { + const char *port = print_in_port_t(server->port4, &gc); + msg(D_SHOW_PARMS, " address4 = %s:%s", addr, port); + } + else + { + msg(D_SHOW_PARMS, " address4 = %s", addr); + } + } + if (server->addr6_defined) + { + const char *addr = print_in6_addr(server->addr6, 0, &gc); + if (server->port6) + { + const char *port = print_in_port_t(server->port6, &gc); + msg(D_SHOW_PARMS, " address6 = [%s]:%s", addr, port); + } + else + { + msg(D_SHOW_PARMS, " address6 = %s", addr); + } + } + + if (server->dnssec) + { + msg(D_SHOW_PARMS, " dnssec = %s", dnssec_value(server->dnssec)); + } + + if (server->transport) + { + msg(D_SHOW_PARMS, " transport = %s", transport_value(server->transport)); + } + if (server->sni) + { + msg(D_SHOW_PARMS, " sni = %s", server->sni); + } + + struct dns_domain *domain = server->domains; + if (domain) + { + if (server->domain_type == DNS_RESOLVE_DOMAINS) + { + msg(D_SHOW_PARMS, " resolve domains:"); + } + else + { + msg(D_SHOW_PARMS, " exclude domains:"); + } + while (domain) + { + msg(D_SHOW_PARMS, " %s", domain->name); + domain = domain->next; + } + } + + server = server->next; + } + + struct dns_domain *search_domain = o->search_domains; + if (search_domain) + { + msg(D_SHOW_PARMS, " DNS search domains:"); + while (search_domain) + { + msg(D_SHOW_PARMS, " %s", search_domain->name); + search_domain = search_domain->next; + } + } + + gc_free(&gc); +} diff --git a/src/openvpn/dns.h b/src/openvpn/dns.h new file mode 100644 index 00000000000..03a894f28a8 --- /dev/null +++ b/src/openvpn/dns.h @@ -0,0 +1,164 @@ +/* + * OpenVPN -- An application to securely tunnel IP networks + * over a single UDP port, with support for SSL/TLS-based + * session authentication and key exchange, + * packet encryption, packet authentication, and + * packet compression. + * + * Copyright (C) 2022-2023 OpenVPN Inc + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef DNS_H +#define DNS_H + +#include "buffer.h" +#include "env_set.h" + +enum dns_domain_type { + DNS_DOMAINS_UNSET, + DNS_RESOLVE_DOMAINS, + DNS_EXCLUDE_DOMAINS +}; + +enum dns_security { + DNS_SECURITY_UNSET, + DNS_SECURITY_NO, + DNS_SECURITY_YES, + DNS_SECURITY_OPTIONAL +}; + +enum dns_server_transport { + DNS_TRANSPORT_UNSET, + DNS_TRANSPORT_PLAIN, + DNS_TRANSPORT_HTTPS, + DNS_TRANSPORT_TLS +}; + +struct dns_domain { + struct dns_domain *next; + const char *name; +}; + +struct dns_server { + struct dns_server *next; + long priority; + bool addr4_defined; + bool addr6_defined; + struct in_addr addr4; + struct in6_addr addr6; + in_port_t port4; + in_port_t port6; + struct dns_domain *domains; + enum dns_domain_type domain_type; + enum dns_security dnssec; + enum dns_server_transport transport; + const char *sni; +}; + +struct dns_options { + struct dns_domain *search_domains; + struct dns_server *servers_prepull; + struct dns_server *servers; + struct gc_arena gc; +}; + +/** + * Parses a string DNS server priority and validates it. + * + * @param priority Pointer to where the priority should be stored + * @param str Priority string to parse + * @param pulled Whether this was pulled from a server + * @return True if priority in string is valid + */ +bool dns_server_priority_parse(long *priority, const char *str, bool pulled); + +/** + * Find or create DNS server with priority in a linked list. + * The list is ordered by priority. + * + * @param entry Address of the first list entry pointer + * @param priority Priority of the DNS server to find / create + * @param gc The gc new list items should be allocated in + */ +struct dns_server *dns_server_get(struct dns_server **entry, long priority, struct gc_arena *gc); + +/** + * Appends DNS domain parameters to a linked list. + * + * @param entry Address of the first list entry pointer + * @param domains Address of the first domain parameter + * @param gc The gc the new list items should be allocated in + */ +void dns_domain_list_append(struct dns_domain **entry, char **domains, struct gc_arena *gc); + +/** + * Parses a string IPv4 or IPv6 address and optional colon separated port, + * into a in_addr or in6_addr respectively plus a in_port_t port. + * + * @param server Pointer to DNS server the address is parsed for + * @param addr Address as string + * @return True if parsing was successful + */ +bool dns_server_addr_parse(struct dns_server *server, const char *addr); + +/** + * Checks validity of DNS options + * + * @param msglevel The message level to log errors with + * @param o Pointer to the DNS options to validate + * @return True if no error was found + */ +bool dns_options_verify(int msglevel, const struct dns_options *o); + +/** + * Makes a deep copy of the passed DNS options. + * + * @param o Pointer to the DNS options to clone + * @param gc Pointer to the gc_arena to use for the clone + * @return The dns_options clone + */ +struct dns_options clone_dns_options(const struct dns_options o, struct gc_arena *gc); + +/** + * Saves and resets the server options, so that pulled ones don't mix in. + * + * @param o Pointer to the DNS options to modify + */ +void dns_options_preprocess_pull(struct dns_options *o); + +/** + * Merges pulled DNS servers with static ones into an ordered list. + * + * @param o Pointer to the DNS options to modify + */ +void dns_options_postprocess_pull(struct dns_options *o); + +/** + * Puts the DNS options into an environment set. + * + * @param o Pointer to the DNS options to set + * @param es Pointer to the env_set to set the options into + */ +void setenv_dns_options(const struct dns_options *o, struct env_set *es); + +/** + * Prints configured DNS options. + * + * @param o Pointer to the DNS options to print + */ +void show_dns_options(const struct dns_options *o); + +#endif /* ifndef DNS_H */ diff --git a/src/openvpn/env_set.c b/src/openvpn/env_set.c index 12d836430f8..5b86e5f048c 100644 --- a/src/openvpn/env_set.c +++ b/src/openvpn/env_set.c @@ -5,9 +5,9 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Technologies, Inc. + * Copyright (C) 2002-2023 OpenVPN Technologies, Inc. * Copyright (C) 2014-2015 David Sommerseth - * Copyright (C) 2016-2022 David Sommerseth + * Copyright (C) 2016-2023 David Sommerseth * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -456,4 +456,4 @@ make_env_array(const struct env_set *es, ret[i] = NULL; return (const char **)ret; -} +} \ No newline at end of file diff --git a/src/openvpn/env_set.h b/src/openvpn/env_set.h index 81e39982f52..dfaf1ce47d3 100644 --- a/src/openvpn/env_set.h +++ b/src/openvpn/env_set.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Technologies, Inc. + * Copyright (C) 2002-2023 OpenVPN Technologies, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -120,4 +120,4 @@ const char **make_env_array(const struct env_set *es, const bool check_allowed, struct gc_arena *gc); -#endif /* ifndef ENV_SET_H */ +#endif /* ifndef ENV_SET_H */ \ No newline at end of file diff --git a/src/openvpn/errlevel.h b/src/openvpn/errlevel.h index 13cd9efa9ed..1182f3abf33 100644 --- a/src/openvpn/errlevel.h +++ b/src/openvpn/errlevel.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -90,16 +90,14 @@ #define D_ROUTE_QUOTA LOGLEV(3, 42, 0) /* show route quota exceeded messages */ #define D_OSBUF LOGLEV(3, 43, 0) /* show socket/tun/tap buffer sizes */ #define D_PS_PROXY LOGLEV(3, 44, 0) /* messages related to --port-share option */ -#define D_PF_INFO LOGLEV(3, 45, 0) /* packet filter informational messages */ #define D_IFCONFIG LOGLEV(3, 0, 0) /* show ifconfig info (don't mute) */ +#define D_DCO LOGLEV(3, 0, 0) /* show DCO related messages */ #define D_SHOW_PARMS LOGLEV(4, 50, 0) /* show all parameters on program initiation */ -#define D_SHOW_OCC LOGLEV(4, 51, 0) /* show options compatibility string */ #define D_LOW LOGLEV(4, 52, 0) /* miscellaneous low-frequency debug info */ #define D_DHCP_OPT LOGLEV(4, 53, 0) /* show DHCP options binary string */ #define D_MBUF LOGLEV(4, 54, 0) /* mbuf.[ch] routines */ #define D_PACKET_TRUNC_ERR LOGLEV(4, 55, 0) /* PACKET_TRUNCATION_CHECK */ -#define D_PF_DROPPED LOGLEV(4, 56, 0) /* packet filter dropped a packet */ #define D_MULTI_DROPPED LOGLEV(4, 57, 0) /* show point-to-multipoint packet drops */ #define D_MULTI_MEDIUM LOGLEV(4, 58, 0) /* show medium frequency multi messages */ #define D_X509_ATTR LOGLEV(4, 59, 0) /* show x509-track attributes on connection */ @@ -115,6 +113,8 @@ #define D_TUN_RW LOGLEV(6, 69, M_DEBUG) /* show TUN/TAP reads/writes */ #define D_TAP_WIN_DEBUG LOGLEV(6, 69, M_DEBUG) /* show TAP-Windows driver debug info */ #define D_CLIENT_NAT LOGLEV(6, 69, M_DEBUG) /* show client NAT debug info */ +#define D_XKEY LOGLEV(6, 69, M_DEBUG) /* show xkey-provider debug info */ +#define D_DCO_DEBUG LOGLEV(6, 69, M_DEBUG) /* show DCO related lowlevel debug messages */ #define D_SHOW_KEYS LOGLEV(7, 70, M_DEBUG) /* show data channel encryption keys */ #define D_SHOW_KEY_SOURCE LOGLEV(7, 70, M_DEBUG) /* show data channel key source entropy */ @@ -145,9 +145,9 @@ #define D_ARGV_PARSE_CMD LOGLEV(7, 70, M_DEBUG) /* show parse_line() errors in argv_parse_cmd */ #define D_CRYPTO_DEBUG LOGLEV(7, 70, M_DEBUG) /* show detailed info from crypto.c routines */ #define D_PID_DEBUG LOGLEV(7, 70, M_DEBUG) /* show packet-id debugging info */ -#define D_PF_DROPPED_BCAST LOGLEV(7, 71, M_DEBUG) /* packet filter dropped a broadcast packet */ -#define D_PF_DEBUG LOGLEV(7, 72, M_DEBUG) /* packet filter debugging, must also define PF_DEBUG in pf.h */ #define D_PUSH_DEBUG LOGLEV(7, 73, M_DEBUG) /* show push/pull debugging info */ +#define D_SHOW_OCC LOGLEV(7, 74, M_DEBUG) /* show options compatibility string */ + #define D_VLAN_DEBUG LOGLEV(7, 74, M_DEBUG) /* show VLAN tagging/untagging debug info */ @@ -178,4 +178,4 @@ /*#define D_THREAD_DEBUG LOGLEV(4, 70, M_DEBUG)*/ /* show pthread debug information */ -#endif /* ifndef ERRLEVEL_H */ +#endif /* ifndef ERRLEVEL_H */ \ No newline at end of file diff --git a/src/openvpn/error.c b/src/openvpn/error.c index 7fbda8442f9..e2b52c6dce6 100644 --- a/src/openvpn/error.c +++ b/src/openvpn/error.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -62,7 +62,7 @@ static int mute_category; /* GLOBAL */ * Output mode priorities are as follows: * * (1) --log-x overrides everything - * (2) syslog is used if --daemon or --inetd is defined and not --log-x + * (2) syslog is used if --daemon is defined and not --log-x * (3) if OPENVPN_DEBUG_COMMAND_LINE is defined, output * to constant logfile name. * (4) Output to stdout. @@ -220,7 +220,7 @@ x_msg(const unsigned int flags, const char *format, ...) va_end(arglist); } -static const char* +static const char * openvpn_strerror(int err, bool crt_error, struct gc_arena *gc) { #ifdef _WIN32 @@ -248,13 +248,11 @@ x_msg_va(const unsigned int flags, const char *format, va_list arglist) void usage_small(void); -#ifndef HAVE_VARARG_MACROS /* the macro has checked this otherwise */ if (!msg_test(flags)) { return; } -#endif bool crt_error = false; e = openvpn_errno_maybe_crt(&crt_error); @@ -262,13 +260,11 @@ x_msg_va(const unsigned int flags, const char *format, va_list arglist) /* * Apply muting filter. */ -#ifndef HAVE_VARARG_MACROS /* the macro has checked this otherwise */ if (!dont_mute(flags)) { return; } -#endif gc_init(&gc); @@ -489,7 +485,7 @@ open_syslog(const char *pgmname, bool stdio_to_null) } } #else /* if SYSLOG_CAPABILITY */ - msg(M_WARN, "Warning on use of --daemon/--inetd: this operating system lacks daemon logging features, therefore when I become a daemon, I won't be able to log status or error messages"); + msg(M_WARN, "Warning on use of --daemon: this operating system lacks daemon logging features, therefore when I become a daemon, I won't be able to log status or error messages"); #endif } @@ -501,11 +497,8 @@ close_syslog(void) { closelog(); use_syslog = false; - if (pgmname_syslog) - { - free(pgmname_syslog); - pgmname_syslog = NULL; - } + free(pgmname_syslog); + pgmname_syslog = NULL; } #endif } @@ -513,7 +506,8 @@ close_syslog(void) #ifdef _WIN32 static int orig_stderr; -int get_orig_stderr() +int +get_orig_stderr() { return orig_stderr ? orig_stderr : _fileno(stderr); } @@ -664,6 +658,9 @@ x_check_status(int status, { const char *extended_msg = NULL; + bool crt_error = false; + int my_errno = openvpn_errno_maybe_crt(&crt_error); + msg(x_cs_verbose_level, "%s %s returned %d", sock ? proto2ascii(sock->info.proto, sock->info.af, true) : "", description, @@ -694,22 +691,21 @@ x_check_status(int status, } #endif - bool crt_error = false; - int my_errno = openvpn_errno_maybe_crt(&crt_error); - if (!ignore_sys_error(my_errno, crt_error)) { if (extended_msg) { - msg(x_cs_info_level, "%s %s [%s]: %s (code=%d)", description, + msg(x_cs_info_level, "%s %s [%s]: %s (fd=%d,code=%d)", description, sock ? proto2ascii(sock->info.proto, sock->info.af, true) : "", - extended_msg, openvpn_strerror(my_errno, crt_error, &gc), my_errno); + extended_msg, openvpn_strerror(my_errno, crt_error, &gc), + sock ? sock->sd : -1, my_errno); } else { - msg(x_cs_info_level, "%s %s: %s (code=%d)", description, + msg(x_cs_info_level, "%s %s: %s (fd=%d,code=%d)", description, sock ? proto2ascii(sock->info.proto, sock->info.af, true) : "", - openvpn_strerror(my_errno, crt_error, &gc), my_errno); + openvpn_strerror(my_errno, crt_error, &gc), + sock ? sock->sd : -1, my_errno); } if (x_cs_err_delay_ms) @@ -812,15 +808,6 @@ msg_flags_string(const unsigned int flags, struct gc_arena *gc) return BSTR(&out); } -#ifdef ENABLE_DEBUG -void -crash(void) -{ - char *null = NULL; - *null = 0; -} -#endif - #ifdef _WIN32 const char * @@ -1017,4 +1004,4 @@ strerror_win32(DWORD errnum, struct gc_arena *gc) } } -#endif /* ifdef _WIN32 */ +#endif /* ifdef _WIN32 */ \ No newline at end of file diff --git a/src/openvpn/error.h b/src/openvpn/error.h index fc878a56a8c..28028c05adb 100644 --- a/src/openvpn/error.h +++ b/src/openvpn/error.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -31,10 +31,14 @@ #include +#if _WIN32 +#include +#endif + /* #define ABORT_ON_ERROR */ -#ifdef ENABLE_PKCS11 -#define ERR_BUF_SIZE 8192 +#if defined(ENABLE_PKCS11) || defined(ENABLE_MANAGEMENT) +#define ERR_BUF_SIZE 10240 #else #define ERR_BUF_SIZE 1280 #endif @@ -143,33 +147,12 @@ bool dont_mute(unsigned int flags); /* Macro to ensure (and teach static analysis tools) we exit on fatal errors */ #define EXIT_FATAL(flags) do { if ((flags) & M_FATAL) {_exit(1);}} while (false) -#if defined(HAVE_CPP_VARARG_MACRO_ISO) && !defined(__LCLINT__) -#define HAVE_VARARG_MACROS #define msg(flags, ...) do { if (msg_test(flags)) {x_msg((flags), __VA_ARGS__);} EXIT_FATAL(flags); } while (false) #ifdef ENABLE_DEBUG #define dmsg(flags, ...) do { if (msg_test(flags)) {x_msg((flags), __VA_ARGS__);} EXIT_FATAL(flags); } while (false) #else #define dmsg(flags, ...) #endif -#elif defined(HAVE_CPP_VARARG_MACRO_GCC) && !defined(__LCLINT__) -#define HAVE_VARARG_MACROS -#define msg(flags, args ...) do { if (msg_test(flags)) {x_msg((flags), args);} EXIT_FATAL(flags); } while (false) -#ifdef ENABLE_DEBUG -#define dmsg(flags, args ...) do { if (msg_test(flags)) {x_msg((flags), args);} EXIT_FATAL(flags); } while (false) -#else -#define dmsg(flags, args ...) -#endif -#else /* if defined(HAVE_CPP_VARARG_MACRO_ISO) && !defined(__LCLINT__) */ -#if !PEDANTIC -#ifdef _MSC_VER -#pragma message("this compiler appears to lack vararg macros which will cause a significant degradation in efficiency") -#else -#warning this compiler appears to lack vararg macros which will cause a significant degradation in efficiency (you can ignore this warning if you are using LCLINT) -#endif -#endif -#define msg x_msg -#define dmsg x_msg -#endif /* if defined(HAVE_CPP_VARARG_MACRO_ISO) && !defined(__LCLINT__) */ void x_msg(const unsigned int flags, const char *format, ...) #ifdef __GNUC__ @@ -220,8 +203,14 @@ FILE *msg_fp(const unsigned int flags); #define ASSERT(x) do { if (!(x)) {assert_failed(__FILE__, __LINE__, NULL);}} while (false) #endif +#ifdef _MSC_VER +__declspec(noreturn) +#endif void assert_failed(const char *filename, int line, const char *condition) -__attribute__((__noreturn__)); +#ifndef _MSC_VER +__attribute__((__noreturn__)) +#endif +; /* Poor-man's static_assert() for when not supplied by assert.h, taken from * Linux's sys/cdefs.h under GPLv2 */ @@ -231,11 +220,6 @@ __attribute__((__noreturn__)); [!!sizeof(struct { int __error_if_negative : (expr) ? 2 : -1; })] #endif -#ifdef ENABLE_DEBUG -void crash(void); /* force a segfault (debugging only) */ - -#endif - /* Inline functions */ static inline bool @@ -410,7 +394,7 @@ openvpn_errno_maybe_crt(bool *crt_error) *crt_error = true; err = errno; } -#else +#else /* ifdef _WIN32 */ *crt_error = true; err = errno; #endif @@ -419,4 +403,4 @@ openvpn_errno_maybe_crt(bool *crt_error) #include "errlevel.h" -#endif /* ifndef ERROR_H */ +#endif /* ifndef ERROR_H */ \ No newline at end of file diff --git a/src/openvpn/event.c b/src/openvpn/event.c index 40bb36e3fc6..4111fd15d45 100644 --- a/src/openvpn/event.c +++ b/src/openvpn/event.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -35,6 +35,10 @@ #include "event.h" #include "fdmisc.h" +#if EPOLL +#include +#endif + #include "memdbg.h" /* @@ -555,7 +559,10 @@ ep_del(struct event_set *es, event_t event) ASSERT(!eps->fast); CLEAR(ev); - epoll_ctl(eps->epfd, EPOLL_CTL_DEL, event, &ev); + if (epoll_ctl(eps->epfd, EPOLL_CTL_DEL, event, &ev) < 0) + { + msg(M_WARN|M_ERRNO, "EVENT: epoll_ctl EPOLL_CTL_DEL failed, sd=%d", (int)event); + } } static void @@ -844,7 +851,8 @@ po_wait(struct event_set *es, const struct timeval *tv, struct event_set_return } else if (pfdp->revents) { - msg(D_EVENT_ERRORS, "Error: poll: unknown revents=0x%04x", (unsigned int)pfdp->revents); + msg(D_EVENT_ERRORS, "Error: poll: unknown revents=0x%04x for fd=%d", + (unsigned int)pfdp->revents, pfdp->fd); } ++pfdp; } @@ -1187,4 +1195,4 @@ event_set_init(int *maxevents, unsigned int flags) { return event_set_init_scalable(maxevents, flags); } -} +} \ No newline at end of file diff --git a/src/openvpn/event.h b/src/openvpn/event.h index 9eff8471a87..6d5310222c1 100644 --- a/src/openvpn/event.h +++ b/src/openvpn/event.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -32,9 +32,50 @@ * rwflags passed to event_ctl and returned by * struct event_set_return. */ -#define EVENT_UNDEF 4 -#define EVENT_READ (1<<0) -#define EVENT_WRITE (1<<1) +#define READ_SHIFT 0 +#define WRITE_SHIFT 1 + +#define EVENT_UNDEF 4 +#define EVENT_READ (1 << READ_SHIFT) +#define EVENT_WRITE (1 << WRITE_SHIFT) + +/* event flags returned by io_wait. + * + * All these events are defined as bits in a bitfield. + * Each event 'type' owns two bits in the bitfield: one for the READ + * event and one for the WRITE event. + * + * For this reason, the specific event bit is calculated by adding + * the event type identifier (always a multiple of 2, as defined + * below) to 0 for READ and 1 for WRITE. + * + * E.g. + * MANAGEMENT_SHIFT = 6; <---- event type identifier + * MANAGEMENT_READ = (1 << (6 + 0)), <---- READ event + * MANAGEMENT_WRITE = (1 << (6 + 1)) <---- WRITE event + * + * 'error' and 'file_close' are special and use read/write for different + * signals. + */ + +#define SOCKET_SHIFT 0 +#define SOCKET_READ (1 << (SOCKET_SHIFT + READ_SHIFT)) +#define SOCKET_WRITE (1 << (SOCKET_SHIFT + WRITE_SHIFT)) +#define TUN_SHIFT 2 +#define TUN_READ (1 << (TUN_SHIFT + READ_SHIFT)) +#define TUN_WRITE (1 << (TUN_SHIFT + WRITE_SHIFT)) +#define ERR_SHIFT 4 +#define ES_ERROR (1 << (ERR_SHIFT + READ_SHIFT)) +#define ES_TIMEOUT (1 << (ERR_SHIFT + WRITE_SHIFT)) +#define MANAGEMENT_SHIFT 6 +#define MANAGEMENT_READ (1 << (MANAGEMENT_SHIFT + READ_SHIFT)) +#define MANAGEMENT_WRITE (1 << (MANAGEMENT_SHIFT + WRITE_SHIFT)) +#define FILE_SHIFT 8 +#define FILE_CLOSED (1 << (FILE_SHIFT + READ_SHIFT)) +#define DCO_SHIFT 10 +#define DCO_READ (1 << (DCO_SHIFT + READ_SHIFT)) +#define DCO_WRITE (1 << (DCO_SHIFT + WRITE_SHIFT)) + /* * Initialization flags passed to event_set_init */ @@ -158,4 +199,4 @@ wait_signal(struct event_set *es, void *arg) #endif -#endif /* ifndef EVENT_H */ +#endif /* ifndef EVENT_H */ \ No newline at end of file diff --git a/src/openvpn/fdmisc.c b/src/openvpn/fdmisc.c index 0b3fa5d792e..d123687fe12 100644 --- a/src/openvpn/fdmisc.c +++ b/src/openvpn/fdmisc.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -36,7 +36,7 @@ /* Set a file descriptor to non-blocking */ bool -set_nonblock_action(int fd) +set_nonblock_action(socket_descriptor_t fd) { #ifdef _WIN32 u_long arg = 1; @@ -55,7 +55,7 @@ set_nonblock_action(int fd) /* Set a file descriptor to not be passed across execs */ bool -set_cloexec_action(int fd) +set_cloexec_action(socket_descriptor_t fd) { #ifndef _WIN32 if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) @@ -68,7 +68,7 @@ set_cloexec_action(int fd) /* Set a file descriptor to non-blocking */ void -set_nonblock(int fd) +set_nonblock(socket_descriptor_t fd) { if (!set_nonblock_action(fd)) { @@ -78,10 +78,10 @@ set_nonblock(int fd) /* Set a file descriptor to not be passed across execs */ void -set_cloexec(int fd) +set_cloexec(socket_descriptor_t fd) { if (!set_cloexec_action(fd)) { msg(M_ERR, "Set FD_CLOEXEC flag on file descriptor failed"); } -} +} \ No newline at end of file diff --git a/src/openvpn/fdmisc.h b/src/openvpn/fdmisc.h index d55150c844d..5ebde8d1907 100644 --- a/src/openvpn/fdmisc.h +++ b/src/openvpn/fdmisc.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -28,16 +28,16 @@ #include "error.h" #include "syshead.h" -bool set_nonblock_action(int fd); +bool set_nonblock_action(socket_descriptor_t fd); -bool set_cloexec_action(int fd); +bool set_cloexec_action(socket_descriptor_t fd); -void set_nonblock(int fd); +void set_nonblock(socket_descriptor_t fd); -void set_cloexec(int fd); +void set_cloexec(socket_descriptor_t fd); static inline void -openvpn_fd_set(int fd, fd_set *setp) +openvpn_fd_set(socket_descriptor_t fd, fd_set *setp) { #ifndef _WIN32 /* The Windows FD_SET() implementation does not overflow */ ASSERT(fd >= 0 && fd < FD_SETSIZE); @@ -46,4 +46,4 @@ openvpn_fd_set(int fd, fd_set *setp) } #undef FD_SET /* prevent direct use of FD_SET() */ -#endif /* FD_MISC_H */ +#endif /* FD_MISC_H */ \ No newline at end of file diff --git a/src/openvpn/forward.c b/src/openvpn/forward.c index de7cafded4b..5767fb00c06 100644 --- a/src/openvpn/forward.c +++ b/src/openvpn/forward.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -36,12 +36,13 @@ #include "mss.h" #include "event.h" #include "occ.h" -#include "pf.h" #include "ping.h" #include "ps.h" #include "dhcp.h" #include "common.h" #include "ssl_verify.h" +#include "dco.h" +#include "auth_token.h" #include "memdbg.h" @@ -54,7 +55,7 @@ counter_type link_write_bytes_global; /* GLOBAL */ #ifdef ENABLE_DEBUG -const char * +static const char * wait_status_string(struct context *c, struct gc_arena *gc) { struct buffer out = alloc_buf_gc(64, gc); @@ -67,7 +68,7 @@ wait_status_string(struct context *c, struct gc_arena *gc) return BSTR(&out); } -void +static void show_wait_status(struct context *c) { struct gc_arena gc = gc_new(); @@ -77,6 +78,19 @@ show_wait_status(struct context *c) #endif /* ifdef ENABLE_DEBUG */ +static void +check_tls_errors_co(struct context *c) +{ + msg(D_STREAM_ERRORS, "Fatal TLS error (check_tls_errors_co), restarting"); + register_signal(c->sig, c->c2.tls_exit_signal, "tls-error"); /* SOFT-SIGUSR1 -- TLS error */ +} + +static void +check_tls_errors_nco(struct context *c) +{ + register_signal(c->sig, c->c2.tls_exit_signal, "tls-error"); /* SOFT-SIGUSR1 -- TLS error */ +} + /* * TLS errors are fatal in TCP mode. * Also check for --tls-exit trigger. @@ -128,6 +142,29 @@ context_reschedule_sec(struct context *c, int sec) } } +void +check_dco_key_status(struct context *c) +{ + /* DCO context is not yet initialised or enabled */ + if (!dco_enabled(&c->options)) + { + return; + } + + /* no active peer (p2p tls-server mode) */ + if (c->c2.tls_multi->dco_peer_id == -1) + { + return; + } + + if (!dco_update_keys(&c->c1.tuntap->dco, c->c2.tls_multi)) + { + /* Something bad happened. Kill the connection to + * be able to recover. */ + register_signal(c->sig, SIGUSR1, "dco update keys error"); + } +} + /* * In TLS mode, let TLS level respond to any control-channel * packets which were received, or prepare any packets for @@ -138,7 +175,7 @@ context_reschedule_sec(struct context *c, int sec) * traffic on the control-channel. * */ -void +static void check_tls(struct context *c) { interval_t wakeup = BIG_TIMEOUT; @@ -148,14 +185,28 @@ check_tls(struct context *c) const int tmp_status = tls_multi_process (c->c2.tls_multi, &c->c2.to_link, &c->c2.to_link_addr, get_link_socket_info(c), &wakeup); - if (tmp_status == TLSMP_ACTIVE) + + if (tmp_status == TLSMP_RECONNECT) + { + event_timeout_init(&c->c2.wait_for_connect, 1, now); + reset_coarse_timers(c); + } + + if (tmp_status == TLSMP_ACTIVE || tmp_status == TLSMP_RECONNECT) { update_time(); interval_action(&c->c2.tmp_int); } else if (tmp_status == TLSMP_KILL) { - register_signal(c, SIGTERM, "auth-control-exit"); + if (c->options.mode == MODE_SERVER) + { + send_auth_failed(c, c->c2.tls_multi->client_reason); + } + else + { + register_signal(c->sig, SIGTERM, "auth-control-exit"); + } } interval_future_trigger(&c->c2.tmp_int, wakeup); @@ -163,32 +214,29 @@ check_tls(struct context *c) interval_schedule_wakeup(&c->c2.tmp_int, &wakeup); + /* + * Our current code has no good hooks in the TLS machinery to update + * DCO keys. So we check the key status after the whole TLS machinery + * has been completed and potentially update them + * + * We have a hidden state transition from secondary to primary key based + * on ks->auth_deferred_expire that DCO needs to check that the normal + * TLS state engine does not check. So we call the \c check_dco_key_status + * function even if tmp_status does not indicate that something has changed. + */ + check_dco_key_status(c); + if (wakeup) { context_reschedule_sec(c, wakeup); } } -void -check_tls_errors_co(struct context *c) -{ - msg(D_STREAM_ERRORS, "Fatal TLS error (check_tls_errors_co), restarting"); - register_signal(c, c->c2.tls_exit_signal, "tls-error"); /* SOFT-SIGUSR1 -- TLS error */ -} - -void -check_tls_errors_nco(struct context *c) -{ - register_signal(c, c->c2.tls_exit_signal, "tls-error"); /* SOFT-SIGUSR1 -- TLS error */ -} - -#if P2MP - /* * Handle incoming configuration * messages on the control channel. */ -void +static void check_incoming_control_channel(struct context *c) { int len = tls_test_payload_len(c->c2.tls_multi); @@ -233,6 +281,14 @@ check_incoming_control_channel(struct context *c) { receive_cr_response(c, &buf); } + else if (buf_string_match_head_str(&buf, "AUTH_PENDING")) + { + receive_auth_pending(c, &buf); + } + else if (buf_string_match_head_str(&buf, "EXIT")) + { + receive_exit_message(c); + } else { msg(D_PUSH_ERRORS, "WARNING: Received unknown control message: %s", BSTR(&buf)); @@ -249,7 +305,7 @@ check_incoming_control_channel(struct context *c) /* * Periodically resend PUSH_REQUEST until PUSH message received */ -void +static void check_push_request(struct context *c) { send_push_request(c); @@ -258,8 +314,6 @@ check_push_request(struct context *c) event_timeout_modify_wakeup(&c->c2.push_request_interval, PUSH_REQUEST_INTERVAL); } -#endif /* P2MP */ - /* * Things that need to happen immediately after connection initiation should go here. * @@ -269,13 +323,11 @@ check_push_request(struct context *c) * Note: The process_incoming_push_reply currently assumes that this function * only sets up the pull request timer when pull is enabled. */ -void +static void check_connection_established(struct context *c) { - - if (CONNECTION_ESTABLISHED(c)) + if (connection_established(c)) { -#if P2MP /* if --pull was specified, send a push request to server */ if (c->c2.tls_multi && c->options.pull) { @@ -292,18 +344,25 @@ check_connection_established(struct context *c) } #endif /* fire up push request right away (already 1s delayed) */ + /* We might receive a AUTH_PENDING request before we armed this + * timer. In that case we don't change the value */ + if (c->c2.push_request_timeout < now) + { + c->c2.push_request_timeout = now + c->options.handshake_window; + } event_timeout_init(&c->c2.push_request_interval, 0, now); reset_coarse_timers(c); } else -#endif /* if P2MP */ { - do_up(c, false, 0); + if (!do_up(c, false, 0)) + { + register_signal(c->sig, SIGUSR1, "connection initialisation failed"); + } } event_timeout_clear(&c->c2.wait_for_connect); } - } bool @@ -325,6 +384,13 @@ send_control_channel_string_dowork(struct tls_multi *multi, return stat; } +void +reschedule_multi_process(struct context *c) +{ + interval_action(&c->c2.tmp_int); + context_immediate_reschedule(c); /* ZERO-TIMEOUT */ +} + bool send_control_channel_string(struct context *c, const char *str, int msglevel) { @@ -332,15 +398,8 @@ send_control_channel_string(struct context *c, const char *str, int msglevel) { bool ret = send_control_channel_string_dowork(c->c2.tls_multi, str, msglevel); - /* - * Reschedule tls_multi_process. - * NOTE: in multi-client mode, usually the below two statements are - * insufficient to reschedule the client instance object unless - * multi_schedule_context_wakeup(m, mi) is also called. - */ + reschedule_multi_process(c); - interval_action(&c->c2.tmp_int); - context_immediate_reschedule(c); /* ZERO-TIMEOUT */ return ret; } return true; @@ -352,15 +411,19 @@ send_control_channel_string(struct context *c, const char *str, int msglevel) static void check_add_routes_action(struct context *c, const bool errors) { - do_route(&c->options, c->c1.route_list, c->c1.route_ipv6_list, - c->c1.tuntap, c->plugins, c->c2.es, &c->net_ctx); + bool route_status = do_route(&c->options, c->c1.route_list, c->c1.route_ipv6_list, + c->c1.tuntap, c->plugins, c->c2.es, &c->net_ctx); + + int flags = (errors ? ISC_ERRORS : 0); + flags |= (!route_status ? ISC_ROUTE_ERRORS : 0); + update_time(); event_timeout_clear(&c->c2.route_wakeup); event_timeout_clear(&c->c2.route_wakeup_expire); - initialization_sequence_completed(c, errors ? ISC_ERRORS : 0); /* client/p2p --route-delay was defined */ + initialization_sequence_completed(c, flags); /* client/p2p --route-delay was defined */ } -void +static void check_add_routes(struct context *c) { if (test_routes(c->c1.route_list, c->c1.tuntap)) @@ -378,7 +441,7 @@ check_add_routes(struct context *c) { if (!tun_standby(c->c1.tuntap)) { - register_signal(c, SIGHUP, "ip-fail"); + register_signal(c->sig, SIGHUP, "ip-fail"); c->persist.restart_sleep_seconds = 10; #ifdef _WIN32 show_routes(M_INFO|M_NOPREFIX); @@ -398,11 +461,11 @@ check_add_routes(struct context *c) /* * Should we exit due to inactivity timeout? */ -void +static void check_inactivity_timeout(struct context *c) { msg(M_INFO, "Inactivity timeout (--inactive), exiting"); - register_signal(c, SIGTERM, "inactive"); + register_signal(c->sig, SIGTERM, "inactive"); } int @@ -412,9 +475,8 @@ get_server_poll_remaining_time(struct event_timeout *server_poll_timeout) int remaining = event_timeout_remaining(server_poll_timeout); return max_int(0, remaining); } -#if P2MP -void +static void check_server_poll_timeout(struct context *c) { event_timeout_reset(&c->c2.server_poll_interval); @@ -422,7 +484,7 @@ check_server_poll_timeout(struct context *c) if (!tls_initial_packet_received(c->c2.tls_multi)) { msg(M_INFO, "Server poll timeout, restarting"); - register_signal(c, SIGUSR1, "server_poll"); + register_signal(c->sig, SIGUSR1, "server_poll"); c->persist.restart_sleep_seconds = -1; } } @@ -444,18 +506,16 @@ schedule_exit(struct context *c, const int n_seconds, const int signal) /* * Scheduled exit? */ -void +static void check_scheduled_exit(struct context *c) { - register_signal(c, c->c2.scheduled_exit_signal, "delayed-exit"); + register_signal(c->sig, c->c2.scheduled_exit_signal, "delayed-exit"); } -#endif /* if P2MP */ - /* * Should we write timer-triggered status file. */ -void +static void check_status_file(struct context *c) { if (c->c1.status_output) @@ -468,16 +528,15 @@ check_status_file(struct context *c) /* * Should we deliver a datagram fragment to remote? */ -void +static void check_fragment(struct context *c) { struct link_socket_info *lsi = get_link_socket_info(c); /* OS MTU Hint? */ - if (lsi->mtu_changed) + if (lsi->mtu_changed && lsi->lsa) { - frame_adjust_path_mtu(&c->c2.frame_fragment, c->c2.link_socket->mtu, - c->options.ce.proto); + frame_adjust_path_mtu(c); lsi->mtu_changed = false; } @@ -524,12 +583,19 @@ encrypt_sign(struct context *c, bool comp_frag) const uint8_t *orig_buf = c->c2.buf.data; struct crypto_options *co = NULL; + if (dco_enabled(&c->options)) + { + msg(M_WARN, "Attempting to send data packet while data channel offload is in use. " + "Dropping packet"); + c->c2.buf.len = 0; + } + /* * Drop non-TLS outgoing packet if client-connect script/plugin - * has not yet succeeded. In non-TLS mode tls_multi is not defined + * has not yet succeeded. In non-TLS tls_multi mode is not defined * and we always pass packets. */ - if (c->c2.tls_multi && c->c2.tls_multi->multi_state != CAS_SUCCEEDED) + if (c->c2.tls_multi && c->c2.tls_multi->multi_state < CAS_CONNECT_DONE) { c->c2.buf.len = 0; } @@ -551,8 +617,8 @@ encrypt_sign(struct context *c, bool comp_frag) #endif } - /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */ - ASSERT(buf_init(&b->encrypt_buf, FRAME_HEADROOM(&c->c2.frame))); + /* initialize work buffer with buf.headroom bytes of prepend capacity */ + ASSERT(buf_init(&b->encrypt_buf, c->c2.frame.buf.headroom)); if (c->c2.tls_multi) { @@ -594,6 +660,21 @@ encrypt_sign(struct context *c, bool comp_frag) buffer_turnover(orig_buf, &c->c2.to_link, &c->c2.buf, &b->read_tun_buf); } +/* + * Should we exit due to session timeout? + */ +static void +check_session_timeout(struct context *c) +{ + if (c->options.session_timeout + && event_timeout_trigger(&c->c2.session_interval, &c->c2.timeval, + ETT_DEFAULT)) + { + msg(M_INFO, "Session timeout, exiting"); + register_signal(c->sig, SIGTERM, "session-timeout"); + } +} + /* * Coarse timers work to 1 second resolution. */ @@ -620,21 +701,12 @@ process_coarse_timers(struct context *c) { check_connection_established(c); } -#if P2MP + /* see if we should send a push_request (option --pull) */ if (event_timeout_trigger(&c->c2.push_request_interval, &c->c2.timeval, ETT_DEFAULT)) { check_push_request(c); } -#endif - -#ifdef PLUGIN_PF - if (c->c2.pf.enabled - && event_timeout_trigger(&c->c2.pf.reload, &c->c2.timeval, ETT_DEFAULT)) - { - pf_check_reload(c); - } -#endif /* process --route options */ if (event_timeout_trigger(&c->c2.route_wakeup, &c->c2.timeval, ETT_DEFAULT)) @@ -642,6 +714,12 @@ process_coarse_timers(struct context *c) check_add_routes(c); } + /* check if we want to refresh the auth-token */ + if (event_timeout_trigger(&c->c2.auth_token_renewal_interval, &c->c2.timeval, ETT_DEFAULT)) + { + check_send_auth_token(c); + } + /* possibly exit due to --inactive */ if (c->options.inactivity_timeout && event_timeout_trigger(&c->c2.inactivity_interval, &c->c2.timeval, ETT_DEFAULT)) @@ -654,6 +732,13 @@ process_coarse_timers(struct context *c) return; } + /* kill session if time is over */ + check_session_timeout(c); + if (c->sig->signal_received) + { + return; + } + /* restart if ping not received */ check_ping_restart(c); if (c->sig->signal_received) @@ -661,7 +746,6 @@ process_coarse_timers(struct context *c) return; } -#if P2MP if (c->c2.tls_multi) { if (c->options.ce.connect_timeout @@ -682,7 +766,6 @@ process_coarse_timers(struct context *c) return; } } -#endif /* Should we send an OCC_REQUEST message? */ check_send_occ_req(c); @@ -698,6 +781,13 @@ process_coarse_timers(struct context *c) /* Should we ping the remote? */ check_ping_send(c); + +#ifdef ENABLE_MANAGEMENT + if (management) + { + management_check_bytecount(c, management, &c->c2.timeval); + } +#endif /* ENABLE_MANAGEMENT */ } static void @@ -808,7 +898,7 @@ read_incoming_link(struct context *c) perf_push(PERF_READ_IN_LINK); c->c2.buf = c->c2.buffers->read_link_buf; - ASSERT(buf_init(&c->c2.buf, FRAME_HEADROOM_ADJ(&c->c2.frame, FRAME_HEADROOM_MARKER_READ_LINK))); + ASSERT(buf_init(&c->c2.buf, c->c2.frame.buf.headroom)); status = link_socket_read(c->c2.link_socket, &c->c2.buf, @@ -822,38 +912,38 @@ read_incoming_link(struct context *c) const struct buffer *fbuf = socket_foreign_protocol_head(c->c2.link_socket); const int sd = socket_foreign_protocol_sd(c->c2.link_socket); port_share_redirect(port_share, fbuf, sd); - register_signal(c, SIGTERM, "port-share-redirect"); + register_signal(c->sig, SIGTERM, "port-share-redirect"); } else #endif { /* received a disconnect from a connection-oriented protocol */ - if (c->options.inetd) + if (event_timeout_defined(&c->c2.explicit_exit_notification_interval)) { - register_signal(c, SIGTERM, "connection-reset-inetd"); - msg(D_STREAM_ERRORS, "Connection reset, inetd/xinetd exit [%d]", status); + msg(D_STREAM_ERRORS, "Connection reset during exit notification period, ignoring [%d]", status); + management_sleep(1); } else { - if (event_timeout_defined(&c->c2.explicit_exit_notification_interval)) - { - msg(D_STREAM_ERRORS, "Connection reset during exit notification period, ignoring [%d]", status); - management_sleep(1); - } - else - { - register_signal(c, SIGUSR1, "connection-reset"); /* SOFT-SIGUSR1 -- TCP connection reset */ - msg(D_STREAM_ERRORS, "Connection reset, restarting [%d]", status); - } + register_signal(c->sig, SIGUSR1, "connection-reset"); /* SOFT-SIGUSR1 -- TCP connection reset */ + msg(D_STREAM_ERRORS, "Connection reset, restarting [%d]", status); } } perf_pop(); return; } + /* check_status() call below resets last-error code */ + bool dco_win_timeout = tuntap_is_dco_win_timeout(c->c1.tuntap, status); + /* check recvfrom status */ check_status(status, "read", c->c2.link_socket, NULL); + if (dco_win_timeout) + { + trigger_ping_timeout_signal(c); + } + /* Remove socks header if applicable */ socks_postprocess_incoming_link(c); @@ -880,10 +970,8 @@ process_incoming_link_part1(struct context *c, struct link_socket_info *lsi, boo #ifdef ENABLE_MANAGEMENT if (management) { - management_bytes_in(management, c->c2.buf.len); -#ifdef MANAGEMENT_DEF_AUTH + management_bytes_client(management, c->c2.buf.len, 0); management_bytes_server(management, &c->c2.link_read_bytes, &c->c2.link_write_bytes, &c->c2.mda_context); -#endif } #endif } @@ -977,7 +1065,7 @@ process_incoming_link_part1(struct context *c, struct link_socket_info *lsi, boo * has not yet succeeded. In non-TLS mode tls_multi is not defined * and we always pass packets. */ - if (c->c2.tls_multi && c->c2.tls_multi->multi_state != CAS_SUCCEEDED) + if (c->c2.tls_multi && c->c2.tls_multi->multi_state < CAS_CONNECT_DONE) { c->c2.buf.len = 0; } @@ -989,7 +1077,7 @@ process_incoming_link_part1(struct context *c, struct link_socket_info *lsi, boo if (!decrypt_status && link_socket_connection_oriented(c->c2.link_socket)) { /* decryption errors are fatal in TCP mode */ - register_signal(c, SIGUSR1, "decryption-error"); /* SOFT-SIGUSR1 -- decryption error in TCP mode */ + register_signal(c->sig, SIGUSR1, "decryption-error"); /* SOFT-SIGUSR1 -- decryption error in TCP mode */ msg(D_STREAM_ERRORS, "Fatal decryption error (process_incoming_link), restarting"); } } @@ -1099,6 +1187,55 @@ process_incoming_link(struct context *c) perf_pop(); } +static void +process_incoming_dco(struct context *c) +{ +#if defined(ENABLE_DCO) && (defined(TARGET_LINUX) || defined(TARGET_FREEBSD)) + struct link_socket_info *lsi = get_link_socket_info(c); + dco_context_t *dco = &c->c1.tuntap->dco; + + dco_do_read(dco); + + /* FreeBSD currently sends us removal notifcation with the old peer-id in + * p2p mode with the ping timeout reason, so ignore that one to not shoot + * ourselves in the foot and removing the just established session */ + if (dco->dco_message_peer_id != c->c2.tls_multi->dco_peer_id) + { + msg(D_DCO_DEBUG, "%s: received message for mismatching peer-id %d, " + "expected %d", __func__, dco->dco_message_peer_id, + c->c2.tls_multi->dco_peer_id); + /* ensure we also drop a message if there is one in the buffer */ + buf_init(&dco->dco_packet_in, 0); + return; + } + + if ((dco->dco_message_type == OVPN_CMD_DEL_PEER) + && (dco->dco_del_peer_reason == OVPN_DEL_PEER_REASON_EXPIRED)) + { + msg(D_DCO_DEBUG, "%s: received peer expired notification of for peer-id " + "%d", __func__, dco->dco_message_peer_id); + trigger_ping_timeout_signal(c); + return; + } + + if (dco->dco_message_type != OVPN_CMD_PACKET) + { + msg(D_DCO_DEBUG, "%s: received message of type %u - ignoring", __func__, + dco->dco_message_type); + return; + } + + struct buffer orig_buff = c->c2.buf; + c->c2.buf = dco->dco_packet_in; + c->c2.from = lsi->lsa->actual; + + process_incoming_link(c); + + c->c2.buf = orig_buff; + buf_init(&dco->dco_packet_in, 0); +#endif /* if defined(ENABLE_DCO) && (defined(TARGET_LINUX) || defined(TARGET_FREEBSD)) */ +} + /* * Output: c->c2.buf */ @@ -1121,7 +1258,7 @@ read_incoming_tun(struct context *c) read_wintun(c->c1.tuntap, &c->c2.buf); if (c->c2.buf.len == -1) { - register_signal(c, SIGHUP, "tun-abort"); + register_signal(c->sig, SIGHUP, "tun-abort"); c->persist.restart_sleep_seconds = 1; msg(M_INFO, "Wintun read error, restarting"); perf_pop(); @@ -1130,12 +1267,13 @@ read_incoming_tun(struct context *c) } else { - read_tun_buffered(c->c1.tuntap, &c->c2.buf); + sockethandle_t sh = { .is_handle = true, .h = c->c1.tuntap->hand }; + sockethandle_finalize(sh, &c->c1.tuntap->reads, &c->c2.buf, NULL); } #else /* ifdef _WIN32 */ - ASSERT(buf_init(&c->c2.buf, FRAME_HEADROOM(&c->c2.frame))); - ASSERT(buf_safe(&c->c2.buf, MAX_RW_SIZE_TUN(&c->c2.frame))); - c->c2.buf.len = read_tun(c->c1.tuntap, BPTR(&c->c2.buf), MAX_RW_SIZE_TUN(&c->c2.frame)); + ASSERT(buf_init(&c->c2.buf, c->c2.frame.buf.headroom)); + ASSERT(buf_safe(&c->c2.buf, c->c2.frame.buf.payload_size)); + c->c2.buf.len = read_tun(c->c1.tuntap, BPTR(&c->c2.buf), c->c2.frame.buf.payload_size); #endif /* ifdef _WIN32 */ #ifdef PACKET_TRUNCATION_CHECK @@ -1149,7 +1287,7 @@ read_incoming_tun(struct context *c) /* Was TUN/TAP interface stopped? */ if (tuntap_stop(c->c2.buf.len)) { - register_signal(c, SIGTERM, "tun-stop"); + register_signal(c->sig, SIGTERM, "tun-stop"); msg(M_INFO, "TUN/TAP interface has been stopped, exiting"); perf_pop(); return; @@ -1158,7 +1296,7 @@ read_incoming_tun(struct context *c) /* Was TUN/TAP I/O operation aborted? */ if (tuntap_abort(c->c2.buf.len)) { - register_signal(c, SIGHUP, "tun-abort"); + register_signal(c->sig, SIGHUP, "tun-abort"); c->persist.restart_sleep_seconds = 10; msg(M_INFO, "TUN/TAP I/O operation aborted, restarting"); perf_pop(); @@ -1395,7 +1533,7 @@ ipv6_send_icmp_unreachable(struct context *c, struct buffer *buf, bool client) * packet */ int max_payload_size = min_int(MAX_ICMPV6LEN, - TUN_MTU_SIZE(&c->c2.frame) - icmpheader_len); + c->c2.frame.tun_mtu - icmpheader_len); int payload_len = min_int(max_payload_size, BLEN(&inputipbuf)); pip6out.payload_len = htons(sizeof(struct openvpn_icmp6hdr) + payload_len); @@ -1508,7 +1646,7 @@ process_ip_header(struct context *c, unsigned int flags, struct buffer *buf) /* possibly alter the TCP MSS */ if (flags & PIP_MSSFIX) { - mss_fixup_ipv4(&ipbuf, MTU_TO_MSS(TUN_MTU_SIZE_DYNAMIC(&c->c2.frame))); + mss_fixup_ipv4(&ipbuf, c->c2.frame.mss_fix); } /* possibly do NAT on packet */ @@ -1532,8 +1670,7 @@ process_ip_header(struct context *c, unsigned int flags, struct buffer *buf) /* possibly alter the TCP MSS */ if (flags & PIP_MSSFIX) { - mss_fixup_ipv6(&ipbuf, - MTU_TO_MSS(TUN_MTU_SIZE_DYNAMIC(&c->c2.frame))); + mss_fixup_ipv6(&ipbuf, c->c2.frame.mss_fix); } if (!(flags & PIP_OUTGOING) && (flags &(PIPV6_IMCP_NOHOST_CLIENT | PIPV6_IMCP_NOHOST_SERVER))) @@ -1549,6 +1686,30 @@ process_ip_header(struct context *c, unsigned int flags, struct buffer *buf) } } +/* + * Linux DCO implementations pass the socket to the kernel and + * disallow usage of it from userland for TCP, so (control) packets + * sent and received by OpenVPN need to go through the DCO interface. + * + * Windows DCO needs control packets to be sent via the normal + * standard Overlapped I/O. + * + * FreeBSD DCO allows control packets to pass through the socket in both + * directions. + * + * Hide that complexity (...especially if more platforms show up + * in the future...) in a small inline function. + */ +static inline bool +should_use_dco_socket(struct link_socket *ls) +{ +#if defined(TARGET_LINUX) + return ls->dco_installed && proto_is_tcp(ls->info.proto); +#else + return false; +#endif +} + /* * Input: c->c2.to_link */ @@ -1561,7 +1722,7 @@ process_outgoing_link(struct context *c) perf_push(PERF_PROC_OUT_LINK); - if (c->c2.to_link.len > 0 && c->c2.to_link.len <= EXPANDED_SIZE(&c->c2.frame)) + if (c->c2.to_link.len > 0 && c->c2.to_link.len <= c->c2.frame.buf.payload_size) { /* * Setup for call to send/sendto which will send @@ -1579,13 +1740,14 @@ process_outgoing_link(struct context *c) * Let the traffic shaper know how many bytes * we wrote. */ -#ifdef ENABLE_FEATURE_SHAPER if (c->options.shaper) { - shaper_wrote_bytes(&c->c2.shaper, BLEN(&c->c2.to_link) - + datagram_overhead(c->options.ce.proto)); + int overhead = datagram_overhead(c->c2.to_link_addr->dest.addr.sa.sa_family, + c->options.ce.proto); + shaper_wrote_bytes(&c->c2.shaper, + BLEN(&c->c2.to_link) + overhead); } -#endif + /* * Let the pinger know that we sent a packet. */ @@ -1621,9 +1783,17 @@ process_outgoing_link(struct context *c) socks_preprocess_outgoing_link(c, &to_addr, &size_delta); /* Send packet */ - size = link_socket_write(c->c2.link_socket, - &c->c2.to_link, - to_addr); + if (should_use_dco_socket(c->c2.link_socket)) + { + size = dco_do_write(&c->c1.tuntap->dco, + c->c2.tls_multi->dco_peer_id, + &c->c2.to_link); + } + else + { + size = link_socket_write(c->c2.link_socket, &c->c2.to_link, + to_addr); + } /* Undo effect of prepend */ link_socket_write_post_size_adjust(&size, size_delta, &c->c2.to_link); @@ -1643,10 +1813,8 @@ process_outgoing_link(struct context *c) #ifdef ENABLE_MANAGEMENT if (management) { - management_bytes_out(management, size); -#ifdef MANAGEMENT_DEF_AUTH + management_bytes_client(management, 0, size); management_bytes_server(management, &c->c2.link_read_bytes, &c->c2.link_write_bytes, &c->c2.mda_context); -#endif } #endif } @@ -1679,15 +1847,15 @@ process_outgoing_link(struct context *c) bool unreachable = error_code == #ifdef _WIN32 - WSAENETUNREACH; + WSAENETUNREACH; #else - ENETUNREACH; + ENETUNREACH; #endif if (size < 0 && unreachable && c->c2.tls_multi && !tls_initial_packet_received(c->c2.tls_multi) && c->options.mode == MODE_POINT_TO_POINT) { msg(M_INFO, "Network unreachable, restarting"); - register_signal(c, SIGUSR1, "network-unreachable"); + register_signal(c->sig, SIGUSR1, "network-unreachable"); } } else @@ -1697,7 +1865,7 @@ process_outgoing_link(struct context *c) msg(D_LINK_ERRORS, "TCP/UDP packet too large on write to %s (tried=%d,max=%d)", print_link_socket_actual(c->c2.to_link_addr, &gc), c->c2.to_link.len, - EXPANDED_SIZE(&c->c2.frame)); + c->c2.frame.buf.payload_size); } } @@ -1733,7 +1901,7 @@ process_outgoing_tun(struct context *c) PIP_MSSFIX | PIPV4_EXTRACT_DHCP_ROUTER | PIPV4_CLIENT_NAT | PIP_OUTGOING, &c->c2.to_tun); - if (c->c2.to_tun.len <= MAX_RW_SIZE_TUN(&c->c2.frame)) + if (c->c2.to_tun.len <= c->c2.frame.buf.payload_size) { /* * Write to TUN/TAP device. @@ -1793,7 +1961,7 @@ process_outgoing_tun(struct context *c) */ msg(D_LINK_ERRORS, "tun packet too large on write (tried=%d,max=%d)", c->c2.to_tun.len, - MAX_RW_SIZE_TUN(&c->c2.frame)); + c->c2.frame.buf.payload_size); } buf_reset(&c->c2.to_tun); @@ -1845,14 +2013,12 @@ pre_select(struct context *c) return; } -#if P2MP /* check for incoming control messages on the control channel like * push request/reply, or authentication failure and 2FA messages */ if (tls_test_payload_len(c->c2.tls_multi) > 0) { check_incoming_control_channel(c); } -#endif /* Should we send an OCC message? */ check_send_occ_msg(c); @@ -1882,15 +2048,20 @@ io_wait_dowork(struct context *c, const unsigned int flags) unsigned int tuntap = 0; struct event_set_return esr[4]; - /* These shifts all depend on EVENT_READ and EVENT_WRITE */ - static int socket_shift = 0; /* depends on SOCKET_READ and SOCKET_WRITE */ - static int tun_shift = 2; /* depends on TUN_READ and TUN_WRITE */ - static int err_shift = 4; /* depends on ES_ERROR */ + /* These shifts all depend on EVENT_READ (=1) and EVENT_WRITE (=2) + * and are added to the shift. Check openvpn.h for more details. + */ + static int socket_shift = SOCKET_SHIFT; + static int tun_shift = TUN_SHIFT; + static int err_shift = ERR_SHIFT; #ifdef ENABLE_MANAGEMENT - static int management_shift = 6; /* depends on MANAGEMENT_READ and MANAGEMENT_WRITE */ + static int management_shift = MANAGEMENT_SHIFT; #endif #ifdef ENABLE_ASYNC_PUSH - static int file_shift = 8; /* listening inotify events */ + static int file_shift = FILE_SHIFT; +#endif +#if defined(TARGET_LINUX) || defined(TARGET_FREEBSD) + static int dco_shift = DCO_SHIFT; /* Event from DCO linux kernel module */ #endif /* @@ -1921,7 +2092,6 @@ io_wait_dowork(struct context *c, const unsigned int flags) * quota, don't send -- instead compute the delay we must wait * until it will be OK to send the packet. */ -#ifdef ENABLE_FEATURE_SHAPER int delay = 0; /* set traffic shaping delay in microseconds */ @@ -1938,9 +2108,6 @@ io_wait_dowork(struct context *c, const unsigned int flags) { shaper_soonest_event(&c->c2.timeval, delay); } -#else /* ENABLE_FEATURE_SHAPER */ - socket |= EVENT_WRITE; -#endif /* ENABLE_FEATURE_SHAPER */ } else { @@ -2003,6 +2170,12 @@ io_wait_dowork(struct context *c, const unsigned int flags) */ socket_set(c->c2.link_socket, c->c2.event_set, socket, (void *)&socket_shift, NULL); tun_set(c->c1.tuntap, c->c2.event_set, tuntap, (void *)&tun_shift, NULL); +#if defined(TARGET_LINUX) || defined(TARGET_FREEBSD) + if (socket & EVENT_READ && c->c2.did_open_tun) + { + dco_event_set(&c->c1.tuntap->dco, c->c2.event_set, (void *)&dco_shift); + } +#endif #ifdef ENABLE_MANAGEMENT if (management) @@ -2125,4 +2298,11 @@ process_io(struct context *c) process_incoming_tun(c); } } -} + else if (status & DCO_READ) + { + if (!IS_SIG(c)) + { + process_incoming_dco(c); + } + } +} \ No newline at end of file diff --git a/src/openvpn/forward.h b/src/openvpn/forward.h index 5d937ee4674..c90c064ada1 100644 --- a/src/openvpn/forward.h +++ b/src/openvpn/forward.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -68,47 +68,12 @@ extern counter_type link_read_bytes_global; extern counter_type link_write_bytes_global; -void check_tls(struct context *c); - -void check_tls_errors_co(struct context *c); - -void check_tls_errors_nco(struct context *c); - -#if P2MP -void check_incoming_control_channel(struct context *c); - -void check_scheduled_exit(struct context *c); - -void check_push_request(struct context *c); - -#endif /* P2MP */ - -#ifdef ENABLE_FRAGMENT -void check_fragment(struct context *c); - -#endif /* ENABLE_FRAGMENT */ - -void check_connection_established(struct context *c); - -void check_add_routes(struct context *c); - -void check_inactivity_timeout(struct context *c); - -void check_server_poll_timeout(struct context *c); - -void check_status_file(struct context *c); - void io_wait_dowork(struct context *c, const unsigned int flags); void pre_select(struct context *c); void process_io(struct context *c); -const char *wait_status_string(struct context *c, struct gc_arena *gc); - -void show_wait_status(struct context *c); - - /**********************************************************************/ /** * Process a data channel packet that will be sent through a VPN tunnel. @@ -317,6 +282,15 @@ bool send_control_channel_string_dowork(struct tls_multi *multi, const char *str, int msglevel); + +/** + * Reschedule tls_multi_process. + * NOTE: in multi-client mode, usually calling the function is + * insufficient to reschedule the client instance object unless + * multi_schedule_context_wakeup(m, mi) is also called. + */ +void reschedule_multi_process(struct context *c); + #define PIPV4_PASSTOS (1<<0) #define PIP_MSSFIX (1<<1) /* v4 and v6 */ #define PIP_OUTGOING (1<<2) @@ -327,11 +301,8 @@ send_control_channel_string_dowork(struct tls_multi *multi, void process_ip_header(struct context *c, unsigned int flags, struct buffer *buf); -#if P2MP void schedule_exit(struct context *c, const int n_seconds, const int signal); -#endif - static inline struct link_socket_info * get_link_socket_info(struct context *c) { @@ -391,8 +362,6 @@ p2p_iow_flags(const struct context *c) static inline void io_wait(struct context *c, const unsigned int flags) { - void io_wait_dowork(struct context *c, const unsigned int flags); - if (c->c2.fast_io && (flags & (IOW_TO_TUN|IOW_TO_LINK|IOW_MBUF))) { /* fast path -- only for TUN/TAP/UDP writes */ @@ -442,6 +411,17 @@ io_wait(struct context *c, const unsigned int flags) } } -#define CONNECTION_ESTABLISHED(c) (get_link_socket_info(c)->connection_established) +static inline bool +connection_established(struct context *c) +{ + if (c->c2.tls_multi) + { + return c->c2.tls_multi->multi_state >= CAS_WAITING_OPTIONS_IMPORT; + } + else + { + return get_link_socket_info(c)->connection_established; + } +} -#endif /* FORWARD_H */ +#endif /* FORWARD_H */ \ No newline at end of file diff --git a/src/openvpn/fragment.c b/src/openvpn/fragment.c index b70e610d0cf..f457a2ed6f2 100644 --- a/src/openvpn/fragment.c +++ b/src/openvpn/fragment.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -96,9 +96,6 @@ fragment_init(struct frame *frame) * fragment_master assume an initial CLEAR */ ALLOC_OBJ_CLEAR(ret, struct fragment_master); - /* add in the size of our contribution to the expanded frame size */ - frame_add_to_extra_frame(frame, sizeof(fragment_header_type)); - /* * Outgoing sequence ID is randomized to reduce * the probability of sequence number collisions @@ -214,7 +211,7 @@ fragment_incoming(struct fragment_master *f, struct buffer *buf, frag->defined = true; frag->max_frag_size = size; frag->map = 0; - ASSERT(buf_init(&frag->buf, FRAME_HEADROOM_ADJ(frame, FRAME_HEADROOM_MARKER_FRAGMENT))); + ASSERT(buf_init(&frag->buf, frame->buf.headroom)); } /* copy the data to fragment buffer */ @@ -335,17 +332,17 @@ fragment_outgoing(struct fragment_master *f, struct buffer *buf, msg(D_FRAG_ERRORS, "FRAG: outgoing buffer is not empty, len=[%d,%d]", buf->len, f->outgoing.len); } - if (buf->len > PAYLOAD_SIZE_DYNAMIC(frame)) /* should we fragment? */ + if (buf->len > frame->max_fragment_size) /* should we fragment? */ { /* * Send the datagram as a series of 2 or more fragments. */ - f->outgoing_frag_size = optimal_fragment_size(buf->len, PAYLOAD_SIZE_DYNAMIC(frame)); + f->outgoing_frag_size = optimal_fragment_size(buf->len, frame->max_fragment_size); if (buf->len > f->outgoing_frag_size * MAX_FRAGS) { FRAG_ERR("too many fragments would be required to send datagram"); } - ASSERT(buf_init(&f->outgoing, FRAME_HEADROOM(frame))); + ASSERT(buf_init(&f->outgoing, frame->buf.headroom)); ASSERT(buf_copy(&f->outgoing, buf)); f->outgoing_seq_id = modulo_add(f->outgoing_seq_id, 1, N_SEQ_ID); f->outgoing_frag_id = 0; @@ -394,7 +391,7 @@ fragment_ready_to_send(struct fragment_master *f, struct buffer *buf, /* initialize return buffer */ *buf = f->outgoing_return; - ASSERT(buf_init(buf, FRAME_HEADROOM(frame))); + ASSERT(buf_init(buf, frame->buf.headroom)); ASSERT(buf_copy_n(buf, &f->outgoing, size)); /* fragment flags differ based on whether or not we are sending the last fragment */ @@ -436,10 +433,4 @@ fragment_wakeup(struct fragment_master *f, struct frame *frame) /* delete fragments with expired TTLs */ fragment_ttl_reap(f); } - -#else /* ifdef ENABLE_FRAGMENT */ -static void -dummy(void) -{ -} -#endif /* ifdef ENABLE_FRAGMENT */ +#endif /* ifdef ENABLE_FRAGMENT */ \ No newline at end of file diff --git a/src/openvpn/fragment.h b/src/openvpn/fragment.h index 0d330bc1868..e0b591e8319 100644 --- a/src/openvpn/fragment.h +++ b/src/openvpn/fragment.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -477,4 +477,4 @@ fragment_housekeeping(struct fragment_master *f, struct frame *frame, struct tim #endif /* ifdef ENABLE_FRAGMENT */ -#endif /* ifndef FRAGMENT_H */ +#endif /* ifndef FRAGMENT_H */ \ No newline at end of file diff --git a/src/openvpn/gremlin.c b/src/openvpn/gremlin.c index 9c9dfbde684..c5f6f2dcad7 100644 --- a/src/openvpn/gremlin.c +++ b/src/openvpn/gremlin.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -233,10 +233,4 @@ corrupt_gremlin(struct buffer *buf, int flags) } } } - -#else /* ifdef ENABLE_DEBUG */ -static void -dummy(void) -{ -} -#endif /* ifdef ENABLE_DEBUG */ +#endif /* ifdef ENABLE_DEBUG */ \ No newline at end of file diff --git a/src/openvpn/gremlin.h b/src/openvpn/gremlin.h index b75ae7e011a..89d2b1f531e 100644 --- a/src/openvpn/gremlin.h +++ b/src/openvpn/gremlin.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -70,4 +70,4 @@ void corrupt_gremlin(struct buffer *buf, int flags); struct packet_flood_parms get_packet_flood_parms(int level); #endif /* ifdef ENABLE_DEBUG */ -#endif /* ifndef GREMLIN_H */ +#endif /* ifndef GREMLIN_H */ \ No newline at end of file diff --git a/src/openvpn/helper.c b/src/openvpn/helper.c index ff4928675ee..a04cda6403b 100644 --- a/src/openvpn/helper.c +++ b/src/openvpn/helper.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -149,11 +149,9 @@ helper_client_server(struct options *o) { struct gc_arena gc = gc_new(); -#if P2MP - -/* - * Get tun/tap/null device type - */ + /* + * Get tun/tap/null device type + */ const int dev = dev_type_enum(o->dev, o->dev_type); const int topology = o->topology; @@ -494,8 +492,6 @@ helper_client_server(struct options *o) o->tls_client = true; } -#endif /* P2MP */ - gc_free(&gc); } @@ -590,4 +586,4 @@ helper_tcp_nodelay(struct options *o) o->sockflags |= SF_TCP_NODELAY; } } -} +} \ No newline at end of file diff --git a/src/openvpn/helper.h b/src/openvpn/helper.h index 0f0d0f11f82..176cc68473c 100644 --- a/src/openvpn/helper.h +++ b/src/openvpn/helper.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -36,4 +36,4 @@ void helper_client_server(struct options *o); void helper_tcp_nodelay(struct options *o); -#endif +#endif \ No newline at end of file diff --git a/src/openvpn/httpdigest.c b/src/openvpn/httpdigest.c index 3c518b02a78..a3f5489776c 100644 --- a/src/openvpn/httpdigest.c +++ b/src/openvpn/httpdigest.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -81,9 +81,8 @@ DigestCalcHA1( { HASH HA1; md_ctx_t *md5_ctx = md_ctx_new(); - const md_kt_t *md5_kt = md_kt_get("MD5"); - md_ctx_init(md5_ctx, md5_kt); + md_ctx_init(md5_ctx, "MD5"); md_ctx_update(md5_ctx, (const uint8_t *) pszUserName, strlen(pszUserName)); md_ctx_update(md5_ctx, (const uint8_t *) ":", 1); md_ctx_update(md5_ctx, (const uint8_t *) pszRealm, strlen(pszRealm)); @@ -92,7 +91,7 @@ DigestCalcHA1( md_ctx_final(md5_ctx, HA1); if (pszAlg && strcasecmp(pszAlg, "md5-sess") == 0) { - md_ctx_init(md5_ctx, md5_kt); + md_ctx_init(md5_ctx, "MD5"); md_ctx_update(md5_ctx, HA1, HASHLEN); md_ctx_update(md5_ctx, (const uint8_t *) ":", 1); md_ctx_update(md5_ctx, (const uint8_t *) pszNonce, strlen(pszNonce)); @@ -124,10 +123,9 @@ DigestCalcResponse( HASHHEX HA2Hex; md_ctx_t *md5_ctx = md_ctx_new(); - const md_kt_t *md5_kt = md_kt_get("MD5"); /* calculate H(A2) */ - md_ctx_init(md5_ctx, md5_kt); + md_ctx_init(md5_ctx, "MD5"); md_ctx_update(md5_ctx, (const uint8_t *) pszMethod, strlen(pszMethod)); md_ctx_update(md5_ctx, (const uint8_t *) ":", 1); md_ctx_update(md5_ctx, (const uint8_t *) pszDigestUri, strlen(pszDigestUri)); @@ -140,7 +138,7 @@ DigestCalcResponse( CvtHex(HA2, HA2Hex); /* calculate response */ - md_ctx_init(md5_ctx, md5_kt); + md_ctx_init(md5_ctx, "MD5"); md_ctx_update(md5_ctx, HA1, HASHHEXLEN); md_ctx_update(md5_ctx, (const uint8_t *) ":", 1); md_ctx_update(md5_ctx, (const uint8_t *) pszNonce, strlen(pszNonce)); @@ -161,4 +159,4 @@ DigestCalcResponse( CvtHex(RespHash, Response); } -#endif /* if PROXY_DIGEST_AUTH */ +#endif /* if PROXY_DIGEST_AUTH */ \ No newline at end of file diff --git a/src/openvpn/httpdigest.h b/src/openvpn/httpdigest.h index b3909a65fdb..e7755764afb 100644 --- a/src/openvpn/httpdigest.h +++ b/src/openvpn/httpdigest.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -56,4 +56,4 @@ void DigestCalcResponse( OUT HASHHEX Response /* request-digest or response-digest */ ); -#endif /* if PROXY_DIGEST_AUTH */ +#endif /* if PROXY_DIGEST_AUTH */ \ No newline at end of file diff --git a/src/openvpn/init.c b/src/openvpn/init.c index be8ff80fd84..11d7dae7b7e 100644 --- a/src/openvpn/init.c +++ b/src/openvpn/init.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -53,6 +53,9 @@ #include "tls_crypt.h" #include "forward.h" #include "auth_token.h" +#include "mss.h" +#include "mudp.h" +#include "dco.h" #include "memdbg.h" @@ -69,6 +72,8 @@ static const char *saved_pid_file_name; /* GLOBAL */ static void do_init_first_time(struct context *c); +static bool do_deferred_p2p_ncp(struct context *c); + void context_clear(struct context *c) { @@ -111,7 +116,6 @@ run_up_down(const char *command, #endif const char *dev_type, int tun_mtu, - int link_mtu, const char *ifconfig_local, const char *ifconfig_remote, const char *context, @@ -127,7 +131,6 @@ run_up_down(const char *command, } setenv_str(es, "script_context", context); setenv_int(es, "tun_mtu", tun_mtu); - setenv_int(es, "link_mtu", link_mtu); setenv_str(es, "dev", arg); if (dev_type) { @@ -155,11 +158,8 @@ run_up_down(const char *command, struct argv argv = argv_new(); ASSERT(arg); argv_printf(&argv, - "%s %d %d %s %s %s", - arg, - tun_mtu, link_mtu, - ifconfig_local, ifconfig_remote, - context); + "%s %d 0 %s %s %s", + arg, tun_mtu, ifconfig_local, ifconfig_remote, context); if (plugin_call(plugins, plugin_type, &argv, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS) { @@ -175,7 +175,7 @@ run_up_down(const char *command, ASSERT(arg); setenv_str(es, "script_type", script_type); argv_parse_cmd(&argv, command); - argv_printf_cat(&argv, "%s %d %d %s %s %s", arg, tun_mtu, link_mtu, + argv_printf_cat(&argv, "%s %d 0 %s %s %s", arg, tun_mtu, ifconfig_local, ifconfig_remote, context); argv_msg(M_INFO, &argv); openvpn_run_script(&argv, es, S_FATAL, "--up/--down"); @@ -192,7 +192,6 @@ run_up_down(const char *command, static void update_options_ce_post(struct options *options) { -#if P2MP /* * In pull mode, we usually import --ping/--ping-restart parameters from * the server. However we should also set an initial default --ping-restart @@ -206,7 +205,6 @@ update_options_ce_post(struct options *options) options->ping_rec_timeout = PRE_PULL_INITIAL_PING_RESTART; options->ping_rec_timeout_action = PING_RESTART; } -#endif } #ifdef ENABLE_MANAGEMENT @@ -331,6 +329,50 @@ management_callback_send_cc_message(void *arg, return status; } +static unsigned int +management_callback_remote_entry_count(void *arg) +{ + assert(arg); + struct context *c = (struct context *) arg; + struct connection_list *l = c->options.connection_list; + + return l->len; +} + +static bool +management_callback_remote_entry_get(void *arg, unsigned int index, char **remote) +{ + assert(arg); + assert(remote); + + struct context *c = (struct context *) arg; + struct connection_list *l = c->options.connection_list; + bool ret = true; + + if (index < l->len) + { + struct connection_entry *ce = l->array[index]; + const char *proto = proto2ascii(ce->proto, ce->af, false); + const char *status = (ce->flags & CE_DISABLED) ? "disabled" : "enabled"; + + /* space for output including 3 commas and a nul */ + int len = strlen(ce->remote) + strlen(ce->remote_port) + strlen(proto) + + strlen(status) + 3 + 1; + char *out = malloc(len); + check_malloc_return(out); + + openvpn_snprintf(out, len, "%s,%s,%s,%s", ce->remote, ce->remote_port, proto, status); + *remote = out; + } + else + { + ret = false; + msg(M_WARN, "Out of bounds index in management query for remote entry: index = %u", index); + } + + return ret; +} + static bool management_callback_remote_cmd(void *arg, const char **p) { @@ -349,6 +391,7 @@ management_callback_remote_cmd(void *arg, const char **p) { flags = CE_MAN_QUERY_REMOTE_SKIP; ret = true; + c->options.ce_advance_count = (p[2]) ? atoi(p[2]) : 1; } else if (!strcmp(p[1], "MOD") && p[2] && p[3]) { @@ -487,13 +530,15 @@ next_connection_entry(struct context *c) /* Check if there is another resolved address to try for * the current connection */ if (c->c1.link_socket_addr.current_remote - && c->c1.link_socket_addr.current_remote->ai_next) + && c->c1.link_socket_addr.current_remote->ai_next + && !c->options.advance_next_remote) { c->c1.link_socket_addr.current_remote = c->c1.link_socket_addr.current_remote->ai_next; } else { + c->options.advance_next_remote = false; /* FIXME (schwabe) fix the persist-remote-ip option for real, * this is broken probably ever since connection lists and multiple * remote existed @@ -521,18 +566,28 @@ next_connection_entry(struct context *c) c->c1.link_socket_addr.remote_list; } + int advance_count = 1; + + /* If previous connection entry was skipped by management client + * with a count to advance by, apply it. + */ + if (c->options.ce_advance_count > 0) + { + advance_count = c->options.ce_advance_count; + } + /* * Increase the number of connection attempts * If this is connect-retry-max * size(l) * OpenVPN will quit */ - c->options.unsuccessful_attempts++; + c->options.unsuccessful_attempts += advance_count; + l->current += advance_count; - if (++l->current >= l->len) + if (l->current >= l->len) { - - l->current = 0; + l->current %= l->len; if (++n_cycles >= 2) { msg(M_FATAL, "No usable connection profiles are present"); @@ -541,6 +596,7 @@ next_connection_entry(struct context *c) } } + c->options.ce_advance_count = 1; ce = l->array[l->current]; if (ce->flags & CE_DISABLED) @@ -592,18 +648,19 @@ init_query_passwords(const struct context *c) pem_password_setup(c->options.key_pass_file); } -#if P2MP /* Auth user/pass input */ if (c->options.auth_user_pass_file) { enable_auth_user_pass(); #ifdef ENABLE_MANAGEMENT - auth_user_pass_setup(c->options.auth_user_pass_file, &c->options.sc_info); + auth_user_pass_setup(c->options.auth_user_pass_file, + c->options.auth_user_pass_file_inline, + &c->options.sc_info); #else - auth_user_pass_setup(c->options.auth_user_pass_file, NULL); + auth_user_pass_setup(c->options.auth_user_pass_file, + c->options.auth_user_pass_file_inline, NULL); #endif } -#endif } /* @@ -669,27 +726,6 @@ uninit_proxy(struct context *c) uninit_proxy_dowork(c); } -/* - * Saves the initial state of NCP-regotiable - * options into a storage which persists over SIGUSR1. - */ -static void -save_ncp_options(struct context *c) -{ - c->c1.ciphername = c->options.ciphername; - c->c1.authname = c->options.authname; - c->c1.keysize = c->options.keysize; -} - -/* Restores NCP-negotiable options to original values */ -static void -restore_ncp_options(struct context *c) -{ - c->options.ciphername = c->c1.ciphername; - c->options.authname = c->c1.authname; - c->options.keysize = c->c1.keysize; -} - void context_init_1(struct context *c) { @@ -699,8 +735,6 @@ context_init_1(struct context *c) init_connection_list(c); - save_ncp_options(c); - #if defined(ENABLE_PKCS11) if (c->first_time) { @@ -766,7 +800,7 @@ init_port_share(struct context *c) { port_share = port_share_open(c->options.port_share_host, c->options.port_share_port, - MAX_RW_SIZE_LINK(&c->c2.frame), + c->c2.frame.buf.payload_size, c->options.port_share_journal_dir); if (port_share == NULL) { @@ -822,16 +856,6 @@ init_static(void) init_ssl_lib(); - /* init PRNG used for IV generation */ - /* When forking, copy this to more places in the code to avoid fork - * random-state predictability */ - prng_init(NULL, 0); - -#ifdef PID_TEST - packet_id_interactive_test(); /* test the sequence number code */ - return false; -#endif - #ifdef SCHEDULE_TEST schedule_test(); return false; @@ -901,93 +925,6 @@ init_static(void) return false; #endif -#ifdef PRNG_TEST - { - struct gc_arena gc = gc_new(); - uint8_t rndbuf[8]; - int i; - prng_init("sha1", 16); - /*prng_init (NULL, 0);*/ - const int factor = 1; - for (i = 0; i < factor * 8; ++i) - { -#if 1 - prng_bytes(rndbuf, sizeof(rndbuf)); -#else - ASSERT(rand_bytes(rndbuf, sizeof(rndbuf))); -#endif - printf("[%d] %s\n", i, format_hex(rndbuf, sizeof(rndbuf), 0, &gc)); - } - gc_free(&gc); - prng_uninit(); - return false; - } -#endif /* ifdef PRNG_TEST */ - -#ifdef BUFFER_LIST_AGGREGATE_TEST - /* test buffer_list_aggregate function */ - { - static const char *text[] = { - "It was a bright cold day in April, ", - "and the clocks were striking ", - "thirteen. ", - "Winston Smith, ", - "his chin nuzzled into his breast in an ", - "effort to escape the vile wind, ", - "slipped quickly through the glass doors ", - "of Victory Mansions, though not quickly ", - "enough to prevent a swirl of gritty dust from ", - "entering along with him." - }; - - int iter, listcap; - for (listcap = 0; listcap < 12; ++listcap) - { - for (iter = 0; iter < 512; ++iter) - { - struct buffer_list *bl = buffer_list_new(listcap); - { - int i; - for (i = 0; i < SIZE(text); ++i) - { - buffer_list_push(bl, (unsigned char *)text[i]); - } - } - printf("[cap=%d i=%d] *************************\n", listcap, iter); - if (!(iter & 8)) - { - buffer_list_aggregate(bl, iter/2); - } - if (!(iter & 16)) - { - buffer_list_push(bl, (unsigned char *)"Even more text..."); - } - buffer_list_aggregate(bl, iter); - if (!(iter & 1)) - { - buffer_list_push(bl, (unsigned char *)"More text..."); - } - { - struct buffer *buf; - while ((buf = buffer_list_peek(bl))) - { - int c; - printf("'"); - while ((c = buf_read_u8(buf)) >= 0) - { - putchar(c); - } - printf("'\n"); - buffer_list_advance(bl, 0); - } - } - buffer_list_free(bl); - } - } - return false; - } -#endif /* ifdef BUFFER_LIST_AGGREGATE_TEST */ - #ifdef MSTATS_TEST { int i; @@ -1181,39 +1118,61 @@ do_genkey(const struct options *options) * Persistent TUN/TAP device management mode? */ bool -do_persist_tuntap(const struct options *options, openvpn_net_ctx_t *ctx) +do_persist_tuntap(struct options *options, openvpn_net_ctx_t *ctx) { - if (options->persist_config) - { - /* sanity check on options for --mktun or --rmtun */ - notnull(options->dev, "TUN/TAP device (--dev)"); - if (options->ce.remote || options->ifconfig_local - || options->ifconfig_remote_netmask - || options->shared_secret_file - || options->tls_server || options->tls_client - ) + if (!options->persist_config) + { + return false; + } + + /* sanity check on options for --mktun or --rmtun */ + notnull(options->dev, "TUN/TAP device (--dev)"); + if (options->ce.remote || options->ifconfig_local + || options->ifconfig_remote_netmask + || options->shared_secret_file + || options->tls_server || options->tls_client + ) + { + msg(M_FATAL|M_OPTERR, + "options --mktun or --rmtun should only be used together with --dev"); + } + +#if defined(ENABLE_DCO) + if (dco_enabled(options)) + { + /* creating a DCO interface via --mktun is not supported as it does not + * make much sense. Since DCO is enabled by default, people may run into + * this without knowing, therefore this case should be properly handled. + * + * Disable DCO if --mktun was provided and print a message to let + * user know. + */ + if (dev_type_enum(options->dev, options->dev_type) == DEV_TYPE_TUN) { - msg(M_FATAL|M_OPTERR, - "options --mktun or --rmtun should only be used together with --dev"); + msg(M_WARN, "Note: --mktun does not support DCO. Creating TUN interface."); } + + options->tuntap_options.disable_dco = true; + } +#endif + #ifdef ENABLE_FEATURE_TUN_PERSIST - tuncfg(options->dev, options->dev_type, options->dev_node, - options->persist_mode, - options->username, options->groupname, &options->tuntap_options, - ctx); - if (options->persist_mode && options->lladdr) - { - set_lladdr(ctx, options->dev, options->lladdr, NULL); - } - return true; + tuncfg(options->dev, options->dev_type, options->dev_node, + options->persist_mode, + options->username, options->groupname, &options->tuntap_options, + ctx); + if (options->persist_mode && options->lladdr) + { + set_lladdr(ctx, options->dev, options->lladdr, NULL); + } + return true; #else /* ifdef ENABLE_FEATURE_TUN_PERSIST */ - msg( M_FATAL|M_OPTERR, - "options --mktun and --rmtun are not available on your operating " - "system. Please check 'man tun' (or 'tap'), whether your system " - "supports using 'ifconfig %s create' / 'destroy' to create/remove " - "persistent tunnel interfaces.", options->dev ); + msg(M_FATAL|M_OPTERR, + "options --mktun and --rmtun are not available on your operating " + "system. Please check 'man tun' (or 'tap'), whether your system " + "supports using 'ifconfig %s create' / 'destroy' to create/remove " + "persistent tunnel interfaces.", options->dev ); #endif - } return false; } @@ -1236,12 +1195,19 @@ possibly_become_daemon(const struct options *options) if (options->daemon) { - ASSERT(!options->inetd); /* Don't chdir immediately, but the end of the init sequence, if needed */ + +#if defined(__APPLE__) && defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#endif if (daemon(1, options->log) < 0) { msg(M_ERR, "daemon() failed or unsupported"); } +#if defined(__APPLE__) && defined(__clang__) +#pragma clang diagnostic pop +#endif restore_signal_state(); if (options->log) { @@ -1282,8 +1248,9 @@ do_uid_gid_chroot(struct context *c, bool no_delay) { if (no_delay) { - platform_group_set(&c0->platform_state_group); - platform_user_set(&c0->platform_state_user); + platform_user_group_set(&c0->platform_state_user, + &c0->platform_state_group, + c); } else if (c->first_time) { @@ -1414,16 +1381,43 @@ do_init_timers(struct context *c, bool deferred) event_timeout_init(&c->c2.inactivity_interval, c->options.inactivity_timeout, now); } - /* initialize pings */ + /* initialize inactivity timeout */ + if (c->options.session_timeout) + { + event_timeout_init(&c->c2.session_interval, c->options.session_timeout, + now); + } - if (c->options.ping_send_timeout) + /* initialize pings */ + if (dco_enabled(&c->options)) + { + /* The DCO kernel module will send the pings instead of user space */ + event_timeout_clear(&c->c2.ping_rec_interval); + event_timeout_clear(&c->c2.ping_send_interval); + } + else { - event_timeout_init(&c->c2.ping_send_interval, c->options.ping_send_timeout, 0); + if (c->options.ping_send_timeout) + { + event_timeout_init(&c->c2.ping_send_interval, c->options.ping_send_timeout, 0); + } + + if (c->options.ping_rec_timeout) + { + event_timeout_init(&c->c2.ping_rec_interval, c->options.ping_rec_timeout, now); + } } - if (c->options.ping_rec_timeout) + /* If the auth-token renewal interval is shorter than reneg-sec, arm + * "auth-token renewal" timer to send additional auth-token to update the + * token on the client more often. If not, this happens automatically + * at renegotiation time, without needing an extra event. + */ + if (c->options.auth_token_generate + && c->options.auth_token_renewal < c->options.renegotiate_seconds) { - event_timeout_init(&c->c2.ping_rec_interval, c->options.ping_rec_timeout, now); + event_timeout_init(&c->c2.auth_token_renewal_interval, + c->options.auth_token_renewal, now); } if (!deferred) @@ -1463,14 +1457,12 @@ do_init_timers(struct context *c, bool deferred) static void do_init_traffic_shaper(struct context *c) { -#ifdef ENABLE_FEATURE_SHAPER /* initialize traffic shaper (i.e. transmit bandwidth limiter) */ if (c->options.shaper) { shaper_init(&c->c2.shaper, c->options.shaper); shaper_msg(&c->c2.shaper); } -#endif } /* @@ -1507,6 +1499,15 @@ do_init_route_list(const struct options *options, int dev = dev_type_enum(options->dev, options->dev_type); int metric = 0; + /* if DCO is enabled we have both regular routes and iroutes in the system + * routing table, and normal routes must have a higher metric for that to + * work so that iroutes are always matched first + */ + if (dco_enabled(options)) + { + metric = DCO_DEFAULT_METRIC; + } + if (dev == DEV_TYPE_TUN && (options->topology == TOP_NET30 || options->topology == TOP_P2P)) { gw = options->ifconfig_remote_netmask; @@ -1543,6 +1544,12 @@ do_init_route_ipv6_list(const struct options *options, const char *gw = NULL; int metric = -1; /* no metric set */ + /* see explanation in do_init_route_list() */ + if (dco_enabled(options)) + { + metric = DCO_DEFAULT_METRIC; + } + gw = options->ifconfig_ipv6_remote; /* default GW = remote end */ if (options->route_ipv6_default_gateway) { @@ -1643,6 +1650,15 @@ initialization_sequence_completed(struct context *c, const unsigned int flags) { detail = "ERROR"; } + /* Flag route error only on platforms where trivial "already exists" errors + * are filtered out. Currently this is the case on Windows or if usng netlink. + */ +#if defined(_WIN32) || defined(ENABLE_SITNL) + else if (flags & ISC_ROUTE_ERRORS) + { + detail = "ROUTE_ERROR"; + } +#endif CLEAR(local); actual = &get_link_socket_info(c)->lsa->actual; @@ -1692,7 +1708,7 @@ initialization_sequence_completed(struct context *c, const unsigned int flags) * Possibly add routes and/or call route-up script * based on options. */ -void +bool do_route(const struct options *options, struct route_list *route_list, struct route_ipv6_list *route_ipv6_list, @@ -1701,10 +1717,11 @@ do_route(const struct options *options, struct env_set *es, openvpn_net_ctx_t *ctx) { + bool ret = true; if (!options->route_noexec && ( route_list || route_ipv6_list ) ) { - add_routes(route_list, route_ipv6_list, tt, ROUTE_OPTION_FLAGS(options), - es, ctx); + ret = add_routes(route_list, route_ipv6_list, tt, ROUTE_OPTION_FLAGS(options), + es, ctx); setenv_int(es, "redirect_gateway", route_did_redirect_default_gateway(route_list)); } #ifdef ENABLE_MANAGEMENT @@ -1743,6 +1760,7 @@ do_route(const struct options *options, show_adapters(D_SHOW_NET|M_NOPREFIX); } #endif + return ret; } /* @@ -1763,7 +1781,8 @@ do_init_tun(struct context *c) c->c1.link_socket_addr.remote_list, !c->options.ifconfig_nowarn, c->c2.es, - &c->net_ctx); + &c->net_ctx, + c->c1.tuntap); #ifdef _WIN32 c->c1.tuntap->windows_driver = c->options.windows_driver; @@ -1780,161 +1799,122 @@ do_init_tun(struct context *c) * Open tun/tap device, ifconfig, call up script, etc. */ + +static bool +can_preserve_tun(struct tuntap *tt) +{ +#ifdef TARGET_ANDROID + return false; +#else + return is_tun_type_set(tt); +#endif +} + static bool -do_open_tun(struct context *c) +do_open_tun(struct context *c, int *error_flags) { struct gc_arena gc = gc_new(); bool ret = false; + *error_flags = 0; -#ifndef TARGET_ANDROID - if (!c->c1.tuntap) + if (!can_preserve_tun(c->c1.tuntap)) { -#endif - #ifdef TARGET_ANDROID - /* If we emulate persist-tun on android we still have to open a new tun and - * then close the old */ - int oldtunfd = -1; - if (c->c1.tuntap) - { - oldtunfd = c->c1.tuntap->fd; - free(c->c1.tuntap); - c->c1.tuntap = NULL; - c->c1.tuntap_owned = false; - } + /* If we emulate persist-tun on android we still have to open a new tun and + * then close the old */ + int oldtunfd = -1; + if (c->c1.tuntap) + { + oldtunfd = c->c1.tuntap->fd; + free(c->c1.tuntap); + c->c1.tuntap = NULL; + c->c1.tuntap_owned = false; + } #endif - /* initialize (but do not open) tun/tap object */ - do_init_tun(c); + /* initialize (but do not open) tun/tap object */ + do_init_tun(c); + + /* inherit the dco context from the tuntap object */ + if (c->c2.tls_multi) + { + c->c2.tls_multi->dco = &c->c1.tuntap->dco; + } #ifdef _WIN32 - /* store (hide) interactive service handle in tuntap_options */ - c->c1.tuntap->options.msg_channel = c->options.msg_channel; - msg(D_ROUTE, "interactive service msg_channel=%" PRIu64, (unsigned long long) c->options.msg_channel); + /* store (hide) interactive service handle in tuntap_options */ + c->c1.tuntap->options.msg_channel = c->options.msg_channel; + msg(D_ROUTE, "interactive service msg_channel=%" PRIu64, (unsigned long long) c->options.msg_channel); #endif - /* allocate route list structure */ - do_alloc_route_list(c); + /* allocate route list structure */ + do_alloc_route_list(c); - /* parse and resolve the route option list */ - ASSERT(c->c2.link_socket); - if (c->options.routes && c->c1.route_list) - { - do_init_route_list(&c->options, c->c1.route_list, - &c->c2.link_socket->info, c->c2.es, &c->net_ctx); - } - if (c->options.routes_ipv6 && c->c1.route_ipv6_list) - { - do_init_route_ipv6_list(&c->options, c->c1.route_ipv6_list, - &c->c2.link_socket->info, c->c2.es, - &c->net_ctx); - } + /* parse and resolve the route option list */ + ASSERT(c->c2.link_socket); + if (c->options.routes && c->c1.route_list) + { + do_init_route_list(&c->options, c->c1.route_list, + &c->c2.link_socket->info, c->c2.es, &c->net_ctx); + } + if (c->options.routes_ipv6 && c->c1.route_ipv6_list) + { + do_init_route_ipv6_list(&c->options, c->c1.route_ipv6_list, + &c->c2.link_socket->info, c->c2.es, + &c->net_ctx); + } - /* do ifconfig */ - if (!c->options.ifconfig_noexec - && ifconfig_order() == IFCONFIG_BEFORE_TUN_OPEN) - { - /* guess actual tun/tap unit number that will be returned - * by open_tun */ - const char *guess = guess_tuntap_dev(c->options.dev, - c->options.dev_type, - c->options.dev_node, - &gc); - do_ifconfig(c->c1.tuntap, guess, TUN_MTU_SIZE(&c->c2.frame), c->c2.es, - &c->net_ctx); - } + /* do ifconfig */ + if (!c->options.ifconfig_noexec + && ifconfig_order() == IFCONFIG_BEFORE_TUN_OPEN) + { + /* guess actual tun/tap unit number that will be returned + * by open_tun */ + const char *guess = guess_tuntap_dev(c->options.dev, + c->options.dev_type, + c->options.dev_node, + &gc); + do_ifconfig(c->c1.tuntap, guess, c->c2.frame.tun_mtu, c->c2.es, + &c->net_ctx); + } - /* possibly add routes */ - if (route_order() == ROUTE_BEFORE_TUN) - { - /* Ignore route_delay, would cause ROUTE_BEFORE_TUN to be ignored */ - do_route(&c->options, c->c1.route_list, c->c1.route_ipv6_list, - c->c1.tuntap, c->plugins, c->c2.es, &c->net_ctx); - } + /* possibly add routes */ + if (route_order() == ROUTE_BEFORE_TUN) + { + /* Ignore route_delay, would cause ROUTE_BEFORE_TUN to be ignored */ + bool status = do_route(&c->options, c->c1.route_list, c->c1.route_ipv6_list, + c->c1.tuntap, c->plugins, c->c2.es, &c->net_ctx); + *error_flags |= (status ? 0 : ISC_ROUTE_ERRORS); + } #ifdef TARGET_ANDROID - /* Store the old fd inside the fd so open_tun can use it */ - c->c1.tuntap->fd = oldtunfd; -#endif - /* open the tun device */ - open_tun(c->options.dev, c->options.dev_type, c->options.dev_node, - c->c1.tuntap); - - /* set the hardware address */ - if (c->options.lladdr) - { - set_lladdr(&c->net_ctx, c->c1.tuntap->actual_name, c->options.lladdr, - c->c2.es); - } - - /* do ifconfig */ - if (!c->options.ifconfig_noexec - && ifconfig_order() == IFCONFIG_AFTER_TUN_OPEN) - { - do_ifconfig(c->c1.tuntap, c->c1.tuntap->actual_name, - TUN_MTU_SIZE(&c->c2.frame), c->c2.es, &c->net_ctx); - } - - /* run the up script */ - run_up_down(c->options.up_script, - c->plugins, - OPENVPN_PLUGIN_UP, - c->c1.tuntap->actual_name, -#ifdef _WIN32 - c->c1.tuntap->adapter_index, + /* Store the old fd inside the fd so open_tun can use it */ + c->c1.tuntap->fd = oldtunfd; #endif - dev_type_string(c->options.dev, c->options.dev_type), - TUN_MTU_SIZE(&c->c2.frame), - EXPANDED_SIZE(&c->c2.frame), - print_in_addr_t(c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc), - print_in_addr_t(c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc), - "init", - NULL, - "up", - c->c2.es); - -#if defined(_WIN32) - if (c->options.block_outside_dns) - { - dmsg(D_LOW, "Blocking outside DNS"); - if (!win_wfp_block_dns(c->c1.tuntap->adapter_index, c->options.msg_channel)) + if (dco_enabled(&c->options)) { - msg(M_FATAL, "Blocking DNS failed!"); + ovpn_dco_init(c->mode, &c->c1.tuntap->dco); } - } -#endif - /* possibly add routes */ - if ((route_order() == ROUTE_AFTER_TUN) && (!c->options.route_delay_defined)) - { - do_route(&c->options, c->c1.route_list, c->c1.route_ipv6_list, - c->c1.tuntap, c->plugins, c->c2.es, &c->net_ctx); - } + /* open the tun device */ + open_tun(c->options.dev, c->options.dev_type, c->options.dev_node, + c->c1.tuntap, &c->net_ctx); - /* - * Did tun/tap driver give us an MTU? - */ - if (c->c1.tuntap->post_open_mtu) - { - frame_set_mtu_dynamic(&c->c2.frame, - c->c1.tuntap->post_open_mtu, - SET_MTU_TUN | SET_MTU_UPPER_BOUND); - } - - ret = true; - static_context = c; -#ifndef TARGET_ANDROID -} -else -{ - msg(M_INFO, "Preserving previous TUN/TAP instance: %s", - c->c1.tuntap->actual_name); + /* set the hardware address */ + if (c->options.lladdr) + { + set_lladdr(&c->net_ctx, c->c1.tuntap->actual_name, c->options.lladdr, + c->c2.es); + } - /* explicitly set the ifconfig_* env vars */ - do_ifconfig_setenv(c->c1.tuntap, c->c2.es); + /* do ifconfig */ + if (!c->options.ifconfig_noexec + && ifconfig_order() == IFCONFIG_AFTER_TUN_OPEN) + { + do_ifconfig(c->c1.tuntap, c->c1.tuntap->actual_name, + c->c2.frame.tun_mtu, c->c2.es, &c->net_ctx); + } - /* run the up script if user specified --up-restart */ - if (c->options.up_restart) - { + /* run the up script */ run_up_down(c->options.up_script, c->plugins, OPENVPN_PLUGIN_UP, @@ -1943,28 +1923,75 @@ else c->c1.tuntap->adapter_index, #endif dev_type_string(c->options.dev, c->options.dev_type), - TUN_MTU_SIZE(&c->c2.frame), - EXPANDED_SIZE(&c->c2.frame), + c->c2.frame.tun_mtu, print_in_addr_t(c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc), print_in_addr_t(c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc), - "restart", + "init", NULL, "up", c->c2.es); - } + #if defined(_WIN32) - if (c->options.block_outside_dns) - { - dmsg(D_LOW, "Blocking outside DNS"); - if (!win_wfp_block_dns(c->c1.tuntap->adapter_index, c->options.msg_channel)) + if (c->options.block_outside_dns) + { + dmsg(D_LOW, "Blocking outside DNS"); + if (!win_wfp_block_dns(c->c1.tuntap->adapter_index, c->options.msg_channel)) + { + msg(M_FATAL, "Blocking DNS failed!"); + } + } +#endif + + /* possibly add routes */ + if ((route_order() == ROUTE_AFTER_TUN) && (!c->options.route_delay_defined)) { - msg(M_FATAL, "Blocking DNS failed!"); + int status = do_route(&c->options, c->c1.route_list, c->c1.route_ipv6_list, + c->c1.tuntap, c->plugins, c->c2.es, &c->net_ctx); + *error_flags |= (status ? 0 : ISC_ROUTE_ERRORS); } + + ret = true; + static_context = c; } + else + { + msg(M_INFO, "Preserving previous TUN/TAP instance: %s", + c->c1.tuntap->actual_name); + + /* explicitly set the ifconfig_* env vars */ + do_ifconfig_setenv(c->c1.tuntap, c->c2.es); + + /* run the up script if user specified --up-restart */ + if (c->options.up_restart) + { + run_up_down(c->options.up_script, + c->plugins, + OPENVPN_PLUGIN_UP, + c->c1.tuntap->actual_name, +#ifdef _WIN32 + c->c1.tuntap->adapter_index, +#endif + dev_type_string(c->options.dev, c->options.dev_type), + c->c2.frame.tun_mtu, + print_in_addr_t(c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc), + print_in_addr_t(c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc), + "restart", + NULL, + "up", + c->c2.es); + } +#if defined(_WIN32) + if (c->options.block_outside_dns) + { + dmsg(D_LOW, "Blocking outside DNS"); + if (!win_wfp_block_dns(c->c1.tuntap->adapter_index, c->options.msg_channel)) + { + msg(M_FATAL, "Blocking DNS failed!"); + } + } #endif -} -#endif /* ifndef TARGET_ANDROID */ + } gc_free(&gc); return ret; } @@ -1976,147 +2003,160 @@ else static void do_close_tun_simple(struct context *c) { - msg(D_CLOSE, "Closing TUN/TAP interface"); + msg(D_CLOSE, "Closing %s interface", + dco_enabled(&c->options) ? "DCO" : "TUN/TAP"); + if (c->c1.tuntap) { + if (!c->options.ifconfig_noexec) + { + undo_ifconfig(c->c1.tuntap, &c->net_ctx); + } close_tun(c->c1.tuntap, &c->net_ctx); c->c1.tuntap = NULL; } c->c1.tuntap_owned = false; -#if P2MP CLEAR(c->c1.pulled_options_digest_save); -#endif } static void do_close_tun(struct context *c, bool force) { - struct gc_arena gc = gc_new(); - if (c->c1.tuntap && c->c1.tuntap_owned) + /* With dco-win we open tun handle in the very beginning. + * In case when tun wasn't opened - like we haven't connected, + * we still need to close tun handle + */ + if (tuntap_is_dco_win(c->c1.tuntap) && !is_tun_type_set(c->c1.tuntap)) + { + do_close_tun_simple(c); + return; + } + + if (!c->c1.tuntap || !c->c1.tuntap_owned) { - const char *tuntap_actual = string_alloc(c->c1.tuntap->actual_name, &gc); + return; + } + + struct gc_arena gc = gc_new(); + const char *tuntap_actual = string_alloc(c->c1.tuntap->actual_name, &gc); #ifdef _WIN32 - DWORD adapter_index = c->c1.tuntap->adapter_index; + DWORD adapter_index = c->c1.tuntap->adapter_index; #endif - const in_addr_t local = c->c1.tuntap->local; - const in_addr_t remote_netmask = c->c1.tuntap->remote_netmask; + const in_addr_t local = c->c1.tuntap->local; + const in_addr_t remote_netmask = c->c1.tuntap->remote_netmask; - if (force || !(c->sig->signal_received == SIGUSR1 && c->options.persist_tun)) - { - static_context = NULL; + if (force || !(c->sig->signal_received == SIGUSR1 && c->options.persist_tun)) + { + static_context = NULL; #ifdef ENABLE_MANAGEMENT - /* tell management layer we are about to close the TUN/TAP device */ - if (management) - { - management_pre_tunnel_close(management); - management_up_down(management, "DOWN", c->c2.es); - } -#endif - - /* delete any routes we added */ - if (c->c1.route_list || c->c1.route_ipv6_list) - { - run_up_down(c->options.route_predown_script, - c->plugins, - OPENVPN_PLUGIN_ROUTE_PREDOWN, - tuntap_actual, -#ifdef _WIN32 - adapter_index, + /* tell management layer we are about to close the TUN/TAP device */ + if (management) + { + management_pre_tunnel_close(management); + management_up_down(management, "DOWN", c->c2.es); + } #endif - NULL, - TUN_MTU_SIZE(&c->c2.frame), - EXPANDED_SIZE(&c->c2.frame), - print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc), - print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc), - "init", - signal_description(c->sig->signal_received, - c->sig->signal_text), - "route-pre-down", - c->c2.es); - - delete_routes(c->c1.route_list, c->c1.route_ipv6_list, - c->c1.tuntap, ROUTE_OPTION_FLAGS(&c->options), - c->c2.es, &c->net_ctx); - } - - /* actually close tun/tap device based on --down-pre flag */ - if (!c->options.down_pre) - { - do_close_tun_simple(c); - } - /* Run the down script -- note that it will run at reduced - * privilege if, for example, "--user nobody" was used. */ - run_up_down(c->options.down_script, + /* delete any routes we added */ + if (c->c1.route_list || c->c1.route_ipv6_list) + { + run_up_down(c->options.route_predown_script, c->plugins, - OPENVPN_PLUGIN_DOWN, + OPENVPN_PLUGIN_ROUTE_PREDOWN, tuntap_actual, #ifdef _WIN32 adapter_index, #endif NULL, - TUN_MTU_SIZE(&c->c2.frame), - EXPANDED_SIZE(&c->c2.frame), + c->c2.frame.tun_mtu, print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc), print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc), "init", signal_description(c->sig->signal_received, c->sig->signal_text), - "down", + "route-pre-down", c->c2.es); + delete_routes(c->c1.route_list, c->c1.route_ipv6_list, + c->c1.tuntap, ROUTE_OPTION_FLAGS(&c->options), + c->c2.es, &c->net_ctx); + } + + /* actually close tun/tap device based on --down-pre flag */ + if (!c->options.down_pre) + { + do_close_tun_simple(c); + } + + /* Run the down script -- note that it will run at reduced + * privilege if, for example, "--user" was used. */ + run_up_down(c->options.down_script, + c->plugins, + OPENVPN_PLUGIN_DOWN, + tuntap_actual, +#ifdef _WIN32 + adapter_index, +#endif + NULL, + c->c2.frame.tun_mtu, + print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc), + print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc), + "init", + signal_description(c->sig->signal_received, + c->sig->signal_text), + "down", + c->c2.es); + #if defined(_WIN32) - if (c->options.block_outside_dns) + if (c->options.block_outside_dns) + { + if (!win_wfp_uninit(adapter_index, c->options.msg_channel)) { - if (!win_wfp_uninit(adapter_index, c->options.msg_channel)) - { - msg(M_FATAL, "Uninitialising WFP failed!"); - } + msg(M_FATAL, "Uninitialising WFP failed!"); } + } #endif - /* actually close tun/tap device based on --down-pre flag */ - if (c->options.down_pre) - { - do_close_tun_simple(c); - } + /* actually close tun/tap device based on --down-pre flag */ + if (c->options.down_pre) + { + do_close_tun_simple(c); } - else + } + else + { + /* run the down script on this restart if --up-restart was specified */ + if (c->options.up_restart) { - /* run the down script on this restart if --up-restart was specified */ - if (c->options.up_restart) - { - run_up_down(c->options.down_script, - c->plugins, - OPENVPN_PLUGIN_DOWN, - tuntap_actual, + run_up_down(c->options.down_script, + c->plugins, + OPENVPN_PLUGIN_DOWN, + tuntap_actual, #ifdef _WIN32 - adapter_index, + adapter_index, #endif - NULL, - TUN_MTU_SIZE(&c->c2.frame), - EXPANDED_SIZE(&c->c2.frame), - print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc), - print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc), - "restart", - signal_description(c->sig->signal_received, - c->sig->signal_text), - "down", - c->c2.es); - } + NULL, + c->c2.frame.tun_mtu, + print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc), + print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc), + "restart", + signal_description(c->sig->signal_received, + c->sig->signal_text), + "down", + c->c2.es); + } #if defined(_WIN32) - if (c->options.block_outside_dns) + if (c->options.block_outside_dns) + { + if (!win_wfp_uninit(adapter_index, c->options.msg_channel)) { - if (!win_wfp_uninit(adapter_index, c->options.msg_channel)) - { - msg(M_FATAL, "Uninitialising WFP failed!"); - } + msg(M_FATAL, "Uninitialising WFP failed!"); } + } #endif - } } gc_free(&gc); } @@ -2136,7 +2176,6 @@ tun_abort(void) * Handle delayed tun/tap interface bringup due to --up-delay or --pull */ -#if P2MP /** * Helper for do_up(). Take two option hashes and return true if they are not * equal, or either one is all-zeroes. @@ -2149,11 +2188,62 @@ options_hash_changed_or_zero(const struct sha256_digest *a, return memcmp(a, b, sizeof(struct sha256_digest)) || !memcmp(a, &zero, sizeof(struct sha256_digest)); } -#endif /* P2MP */ + +static bool +p2p_set_dco_keepalive(struct context *c) +{ + if (dco_enabled(&c->options) + && (c->options.ping_send_timeout || c->c2.frame.mss_fix)) + { + int ret = dco_set_peer(&c->c1.tuntap->dco, + c->c2.tls_multi->dco_peer_id, + c->options.ping_send_timeout, + c->options.ping_rec_timeout, + c->c2.frame.mss_fix); + if (ret < 0) + { + msg(D_DCO, "Cannot set parameters for DCO peer (id=%u): %s", + c->c2.tls_multi->dco_peer_id, strerror(-ret)); + return false; + } + } + return true; +} +/** + * This function is expected to be invoked after open_tun() was performed. + * + * This kind of behaviour is required by DCO, because the following operations + * can be done only after the DCO device was created and the new peer was + * properly added. + */ +static bool +do_deferred_options_part2(struct context *c) +{ + struct frame *frame_fragment = NULL; +#ifdef ENABLE_FRAGMENT + if (c->options.ce.fragment) + { + frame_fragment = &c->c2.frame_fragment; + } +#endif + + struct tls_session *session = &c->c2.tls_multi->session[TM_ACTIVE]; + if (!tls_session_update_crypto_params(c->c2.tls_multi, session, + &c->options, &c->c2.frame, + frame_fragment, + get_link_socket_info(c))) + { + msg(D_TLS_ERRORS, "OPTIONS ERROR: failed to import crypto options"); + return false; + } + + return true; +} bool do_up(struct context *c, bool pulled_options, unsigned int option_types_found) { + int error_flags = 0; if (!c->c2.do_up_ran) { reset_coarse_timers(c); @@ -2167,38 +2257,98 @@ do_up(struct context *c, bool pulled_options, unsigned int option_types_found) } } - /* if --up-delay specified, open tun, do ifconfig, and run up script now */ - if (c->options.up_delay || PULL_DEFINED(&c->options)) + /* if --up-delay specified, open tun, do ifconfig, and run up script now */ + if (c->options.up_delay || PULL_DEFINED(&c->options)) + { + c->c2.did_open_tun = do_open_tun(c, &error_flags); + update_time(); + + /* + * Was tun interface object persisted from previous restart iteration, + * and if so did pulled options string change from previous iteration? + */ + if (!c->c2.did_open_tun + && PULL_DEFINED(&c->options) + && c->c1.tuntap + && options_hash_changed_or_zero(&c->c1.pulled_options_digest_save, + &c->c2.pulled_options_digest)) + { + /* if so, close tun, delete routes, then reinitialize tun and add routes */ + msg(M_INFO, "NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device."); + + bool tt_dco_win = tuntap_is_dco_win(c->c1.tuntap); + do_close_tun(c, true); + + if (tt_dco_win) + { + msg(M_NONFATAL, "dco-win doesn't yet support reopening TUN device"); + /* prevent link_socket_close() from closing handle with WinSock API */ + c->c2.link_socket->sd = SOCKET_UNDEFINED; + return false; + } + else + { + management_sleep(1); + c->c2.did_open_tun = do_open_tun(c, &error_flags); + update_time(); + } + } + } + } + + /* This part needs to be run in p2p mode (without pull) when the client + * reconnects to setup various things (like DCO and NCP cipher) that + * might have changed from the previous connection. + */ + if (!c->c2.do_up_ran || (c->c2.tls_multi && c->c2.tls_multi->multi_state == CAS_RECONNECT_PENDING)) + { + if (c->mode == MODE_POINT_TO_POINT) + { + /* ovpn-dco requires adding the peer now, before any option can be set, + * but *after* having parsed the pushed peer-id in do_deferred_options() + */ + int ret = dco_p2p_add_new_peer(c); + if (ret < 0) + { + msg(D_DCO, "Cannot add peer to DCO: %s (%d)", strerror(-ret), ret); + return false; + } + } + + /* do_deferred_options_part2() and do_deferred_p2p_ncp() *must* be + * invoked after open_tun(). + * This is required by DCO because we must have created the interface + * and added the peer before we can fiddle with the keys or any other + * data channel per-peer setting. + */ + if (pulled_options) + { + if (!do_deferred_options_part2(c)) + { + return false; + } + } + else + { + if (c->mode == MODE_POINT_TO_POINT) + { + if (!do_deferred_p2p_ncp(c)) + { + msg(D_TLS_ERRORS, "ERROR: Failed to apply P2P negotiated protocol options"); + return false; + } + } + } + + if (c->mode == MODE_POINT_TO_POINT && !p2p_set_dco_keepalive(c)) { - c->c2.did_open_tun = do_open_tun(c); - update_time(); - -#if P2MP - /* - * Was tun interface object persisted from previous restart iteration, - * and if so did pulled options string change from previous iteration? - */ - if (!c->c2.did_open_tun - && PULL_DEFINED(&c->options) - && c->c1.tuntap - && options_hash_changed_or_zero(&c->c1.pulled_options_digest_save, - &c->c2.pulled_options_digest)) - { - /* if so, close tun, delete routes, then reinitialize tun and add routes */ - msg(M_INFO, "NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device."); - do_close_tun(c, true); - management_sleep(1); - c->c2.did_open_tun = do_open_tun(c); - update_time(); - } -#endif + msg(D_TLS_ERRORS, "ERROR: Failed to apply DCO keepalive or MSS fix parameters"); + return false; } if (c->c2.did_open_tun) { -#if P2MP c->c1.pulled_options_digest_save = c->c2.pulled_options_digest; -#endif /* if --route-delay was specified, start timer */ if ((route_order() == ROUTE_AFTER_TUN) && c->options.route_delay_defined) @@ -2212,15 +2362,19 @@ do_up(struct context *c, bool pulled_options, unsigned int option_types_found) } else { - initialization_sequence_completed(c, 0); /* client/p2p --route-delay undefined */ + initialization_sequence_completed(c, error_flags); /* client/p2p --route-delay undefined */ } } else if (c->options.mode == MODE_POINT_TO_POINT) { - initialization_sequence_completed(c, 0); /* client/p2p restart with --persist-tun */ + initialization_sequence_completed(c, error_flags); /* client/p2p restart with --persist-tun */ } c->c2.do_up_ran = true; + if (c->c2.tls_multi) + { + c->c2.tls_multi->multi_state = CAS_CONNECT_DONE; + } } return true; } @@ -2245,19 +2399,61 @@ pull_permission_mask(const struct context *c) | OPT_P_EXPLICIT_NOTIFY | OPT_P_ECHO | OPT_P_PULL_MODE - | OPT_P_PEER_ID; + | OPT_P_PEER_ID + | OPT_P_NCP + | OPT_P_PUSH_MTU; if (!c->options.route_nopull) { - flags |= (OPT_P_ROUTE | OPT_P_IPWIN32); + flags |= (OPT_P_ROUTE | OPT_P_DHCPDNS); + } + + return flags; +} + +static bool +do_deferred_p2p_ncp(struct context *c) +{ + if (!c->c2.tls_multi) + { + return true; + } + + c->options.use_peer_id = c->c2.tls_multi->use_peer_id; + + struct tls_session *session = &c->c2.tls_multi->session[TM_ACTIVE]; + + const char *ncp_cipher = get_p2p_ncp_cipher(session, c->c2.tls_multi->peer_info, + &c->options.gc); + + if (ncp_cipher) + { + c->options.ciphername = ncp_cipher; + } + else if (!c->options.enable_ncp_fallback) + { + msg(D_TLS_ERRORS, "ERROR: failed to negotiate cipher with peer and " + "--data-ciphers-fallback not enabled. No usable " + "data channel cipher"); + return false; } - if (c->options.ncp_enabled) + struct frame *frame_fragment = NULL; +#ifdef ENABLE_FRAGMENT + if (c->options.ce.fragment) { - flags |= OPT_P_NCP; + frame_fragment = &c->c2.frame_fragment; } +#endif - return flags; + if (!tls_session_update_crypto_params(c->c2.tls_multi, session, &c->options, + &c->c2.frame, frame_fragment, + get_link_socket_info(c))) + { + msg(D_TLS_ERRORS, "ERROR: failed to set crypto cipher"); + return false; + } + return true; } /* @@ -2333,7 +2529,7 @@ do_deferred_options(struct context *c, const unsigned int found) { msg(D_PUSH, "OPTIONS IMPORT: route-related options modified"); } - if (found & OPT_P_IPWIN32) + if (found & OPT_P_DHCPDNS) { msg(D_PUSH, "OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified"); } @@ -2347,43 +2543,42 @@ do_deferred_options(struct context *c, const unsigned int found) msg(D_PUSH, "OPTIONS IMPORT: peer-id set"); c->c2.tls_multi->use_peer_id = true; c->c2.tls_multi->peer_id = c->options.peer_id; - frame_add_to_extra_frame(&c->c2.frame, +3); /* peer-id overhead */ - if (!c->options.ce.link_mtu_defined) - { - frame_add_to_link_mtu(&c->c2.frame, +3); - msg(D_PUSH, "OPTIONS IMPORT: adjusting link_mtu to %d", - EXPANDED_SIZE(&c->c2.frame)); - } - else - { - msg(M_WARN, "OPTIONS IMPORT: WARNING: peer-id set, but link-mtu" - " fixed by config - reducing tun-mtu to %d, expect" - " MTU problems", TUN_MTU_SIZE(&c->c2.frame) ); - } } - /* process (potentially pushed) crypto options */ + /* process (potentially) pushed options */ if (c->options.pull) { if (!check_pull_client_ncp(c, found)) { return false; } - struct frame *frame_fragment = NULL; -#ifdef ENABLE_FRAGMENT - if (c->options.ce.fragment) + + /* Check if pushed options are compatible with DCO, if enabled */ + if (dco_enabled(&c->options) + && !dco_check_pull_options(D_PUSH_ERRORS, &c->options)) { - frame_fragment = &c->c2.frame_fragment; + msg(D_PUSH_ERRORS, "OPTIONS ERROR: pushed options are incompatible " + "with data channel offload. Use --disable-dco to connect to " + "this server"); + return false; } -#endif + } + + if (found & OPT_P_PUSH_MTU) + { + /* MTU has changed, check that the pushed MTU is small enough to + * be able to change it */ + msg(D_PUSH, "OPTIONS IMPORT: tun-mtu set to %d", c->options.ce.tun_mtu); + + struct frame *frame = &c->c2.frame; - struct tls_session *session = &c->c2.tls_multi->session[TM_ACTIVE]; - if (!tls_session_update_crypto_params(session, &c->options, &c->c2.frame, - frame_fragment)) + if (c->options.ce.tun_mtu > frame->tun_max_mtu) { - msg(D_TLS_ERRORS, "OPTIONS ERROR: failed to import crypto options"); - return false; + msg(D_PUSH_ERRORS, "Server-pushed tun-mtu is too large, please add " + "tun-mtu-max %d in the client configuration", + c->options.ce.tun_mtu); } + frame->tun_mtu = min_int(frame->tun_max_mtu, c->options.ce.tun_mtu); } return true; @@ -2437,12 +2632,10 @@ socket_restart_pause(struct context *c) } #endif -#if P2MP if (auth_retry_get() == AR_NOINTERACT) { sec = 10; } -#endif /* Slow down reconnection after 5 retries per remote -- for TCP client or UDP tls-client only */ if (c->options.ce.proto == PROTO_TCP_CLIENT @@ -2454,6 +2647,11 @@ socket_restart_pause(struct context *c) /* sec is less than 2^16; we can left shift it by up to 15 bits without overflow */ sec = max_int(sec, 1) << min_int(backoff, 15); } + if (c->options.server_backoff_time) + { + sec = max_int(sec, c->options.server_backoff_time); + c->options.server_backoff_time = 0; + } if (sec > c->options.ce.connect_retry_seconds_max) { @@ -2500,6 +2698,35 @@ do_startup_pause(struct context *c) } } +static size_t +get_frame_mtu(struct context *c, const struct options *o) +{ + size_t mtu; + + if (o->ce.link_mtu_defined) + { + ASSERT(o->ce.link_mtu_defined); + /* if we have a link mtu defined we calculate what the old code + * would have come up with as tun-mtu */ + size_t overhead = frame_calculate_protocol_header_size(&c->c1.ks.key_type, + o, true); + mtu = o->ce.link_mtu - overhead; + + } + else + { + ASSERT(o->ce.tun_mtu_defined); + mtu = o->ce.tun_mtu; + } + + if (mtu < TUN_MTU_MIN) + { + msg(M_WARN, "TUN MTU value (%zu) must be at least %d", mtu, TUN_MTU_MIN); + frame_print(&c->c2.frame, M_FATAL, "MTU is too small"); + } + return mtu; +} + /* * Finalize MTU parameters based on command line or config file options. */ @@ -2511,25 +2738,73 @@ frame_finalize_options(struct context *c, const struct options *o) o = &c->options; } - /* - * Set adjustment factor for buffer alignment when no - * cipher is used. - */ - if (!CIPHER_ENABLED(c)) + struct frame *frame = &c->c2.frame; + + frame->tun_mtu = get_frame_mtu(c, o); + frame->tun_max_mtu = o->ce.tun_mtu_max; + + /* max mtu needs to be at least as large as the tun mtu */ + frame->tun_max_mtu = max_int(frame->tun_mtu, frame->tun_max_mtu); + + /* We always allow at least 1600 MTU packets to be received in our buffer + * space to allow server to push "baby giant" MTU sizes */ + frame->tun_max_mtu = max_int(1600, frame->tun_max_mtu); + + size_t payload_size = frame->tun_max_mtu; + + /* we need to be also large enough to hold larger control channel packets + * if configured */ + payload_size = max_int(payload_size, o->ce.tls_mtu); + + /* The extra tun needs to be added to the payload size */ + if (o->ce.tun_mtu_defined) { - frame_align_to_extra_frame(&c->c2.frame); - frame_or_align_flags(&c->c2.frame, - FRAME_HEADROOM_MARKER_FRAGMENT - |FRAME_HEADROOM_MARKER_READ_LINK - |FRAME_HEADROOM_MARKER_READ_STREAM); + payload_size += o->ce.tun_mtu_extra; } - frame_add_to_extra_buffer(&c->c2.frame, PAYLOAD_ALIGN); - frame_finalize(&c->c2.frame, - o->ce.link_mtu_defined, - o->ce.link_mtu, - o->ce.tun_mtu_defined, - o->ce.tun_mtu); + /* Add 32 byte of extra space in the buffer to account for small errors + * in the calculation */ + payload_size += 32; + + + /* the space that is reserved before the payload to add extra headers to it + * we always reserve the space for the worst case */ + size_t headroom = 0; + + /* includes IV and packet ID */ + headroom += crypto_max_overhead(); + + /* peer id + opcode */ + headroom += 4; + + /* socks proxy header */ + headroom += 10; + + /* compression header and fragment header (part of the encrypted payload) */ + headroom += 1 + 1; + + /* Round up headroom to the next multiple of 4 to ensure alignment */ + headroom = (headroom + 3) & ~3; + + /* Add the headroom to the payloadsize as a received (IP) packet can have + * all the extra headers in it */ + payload_size += headroom; + + /* the space after the payload, this needs some extra buffer space for + * encryption so headroom is probably too much but we do not really care + * the few extra bytes */ + size_t tailroom = headroom; + +#ifdef USE_COMP + msg(D_MTU_DEBUG, "MTU: adding %zu buffer tailroom for compression for %zu " + "bytes of payload", + COMP_EXTRA_BUFFER(payload_size), payload_size); + tailroom += COMP_EXTRA_BUFFER(payload_size); +#endif + + frame->buf.payload_size = payload_size; + frame->buf.headroom = headroom; + frame->buf.tailroom = tailroom; } /* @@ -2606,7 +2881,7 @@ do_init_crypto_static(struct context *c, const unsigned int flags) { /* Get cipher & hash algorithms */ init_key_type(&c->c1.ks.key_type, options->ciphername, options->authname, - options->keysize, options->test_crypto, true); + options->test_crypto, true); /* Read cipher and hmac keys from shared secret file */ crypto_read_openvpn_key(&c->c1.ks.key_type, &c->c1.ks.static_key, @@ -2623,10 +2898,6 @@ do_init_crypto_static(struct context *c, const unsigned int flags) /* Get key schedule */ c->c2.crypto_options.key_ctx_bi = c->c1.ks.static_key; - /* Compute MTU parameters */ - crypto_adjust_frame_parameters(&c->c2.frame, &c->c1.ks.key_type, - options->replay, true); - /* Sanity check on sequence number, and cipher mode options */ check_replay_consistency(&c->c1.ks.key_type, options->replay); } @@ -2644,13 +2915,9 @@ do_init_tls_wrap_key(struct context *c) { /* Initialize key_type for tls-auth with auth only */ CLEAR(c->c1.ks.tls_auth_key_type); - if (!streq(options->authname, "none")) - { - c->c1.ks.tls_auth_key_type.digest = md_kt_get(options->authname); - c->c1.ks.tls_auth_key_type.hmac_length = - md_kt_size(c->c1.ks.tls_auth_key_type.digest); - } - else + c->c1.ks.tls_auth_key_type.cipher = "none"; + c->c1.ks.tls_auth_key_type.digest = options->authname; + if (!md_valid(options->authname)) { msg(M_FATAL, "ERROR: tls-auth enabled, but no valid --auth " "algorithm specified ('%s')", options->authname); @@ -2689,25 +2956,24 @@ do_init_tls_wrap_key(struct context *c) options->ce.tls_crypt_v2_file, options->ce.tls_crypt_v2_file_inline); } - } - + /* We have to ensure that the loaded tls-crypt key is small enough + * to fit into the initial hard reset v3 packet */ + int wkc_len = buf_len(&c->c1.ks.tls_crypt_v2_wkc); -} + /* empty ACK/message id, tls-crypt, Opcode, UDP, ipv6 */ + int required_size = 5 + wkc_len + tls_crypt_buf_overhead() + 1 + 8 + 40; -/* - * Initialise the auth-token key context - */ -static void -do_init_auth_token_key(struct context *c) -{ - if (!c->options.auth_token_generate) - { - return; + if (required_size > c->options.ce.tls_mtu) + { + msg(M_WARN, "ERROR: tls-crypt-v2 client key too large to work with " + "requested --max-packet-size %d, requires at least " + "--max-packet-size %d. Packets will ignore requested " + "maximum packet size", c->options.ce.tls_mtu, + required_size); + } } - auth_token_init_secret(&c->c1.ks.auth_token_key, - c->options.auth_token_secret_file, - c->options.auth_token_secret_file_inline); + } /* @@ -2728,7 +2994,6 @@ do_init_crypto_tls_c1(struct context *c) init_ssl(options, &(c->c1.ks.ssl_ctx), c->c0 && c->c0->uid_gid_chroot_set); if (!tls_ctx_initialised(&c->c1.ks.ssl_ctx)) { -#if P2MP switch (auth_retry_get()) { case AR_NONE: @@ -2737,19 +3002,17 @@ do_init_crypto_tls_c1(struct context *c) case AR_INTERACT: ssl_purge_auth(false); + /* Intentional [[fallthrough]]; */ case AR_NOINTERACT: - c->sig->signal_received = SIGUSR1; /* SOFT-SIGUSR1 -- Password failure error */ + /* SOFT-SIGUSR1 -- Password failure error */ + register_signal(c->sig, SIGUSR1, "private-key-password-failure"); break; default: ASSERT(0); } - c->sig->signal_text = "private-key-password-failure"; return; -#else /* if P2MP */ - msg(M_FATAL, "Error: private key password verification failed"); -#endif /* if P2MP */ } /* @@ -2761,8 +3024,6 @@ do_init_crypto_tls_c1(struct context *c) * * Therefore, the key structure has to be initialized when: * - any non-BF-CBC cipher was selected; or - * - BF-CBC is selected and NCP is disabled (explicit request to - * use the BF-CBC cipher); or * - BF-CBC is selected, NCP is enabled and fallback is enabled * (BF-CBC will be the fallback). * - BF-CBC is in data-ciphers and we negotiate to use BF-CBC: @@ -2772,23 +3033,29 @@ do_init_crypto_tls_c1(struct context *c) * Note that BF-CBC will still be part of the OCC string to retain * backwards compatibility with older clients. */ - if (!streq(options->ciphername, "BF-CBC") || !options->ncp_enabled - || (options->ncp_enabled && tls_item_in_cipher_list("BF-CBC", options->ncp_ciphers)) - || options->enable_ncp_fallback) + const char *ciphername = options->ciphername; + if (streq(options->ciphername, "BF-CBC") + && !tls_item_in_cipher_list("BF-CBC", options->ncp_ciphers) + && !options->enable_ncp_fallback) { - /* Do not warn if the if the cipher is used only in OCC */ - bool warn = !options->ncp_enabled || options->enable_ncp_fallback; - init_key_type(&c->c1.ks.key_type, options->ciphername, options->authname, - options->keysize, true, warn); + ciphername = "none"; } - /* Initialize PRNG with config-specified digest */ - prng_init(options->prng_hash, options->prng_nonce_secret_len); + + /* Do not warn if the cipher is used only in OCC */ + bool warn = options->enable_ncp_fallback; + init_key_type(&c->c1.ks.key_type, ciphername, options->authname, + true, warn); /* initialize tls-auth/crypt/crypt-v2 key */ do_init_tls_wrap_key(c); /* initialise auth-token crypto support */ - do_init_auth_token_key(c); + if (c->options.auth_token_generate) + { + auth_token_init_secret(&c->c1.ks.auth_token_key, + c->options.auth_token_secret_file, + c->options.auth_token_secret_file_inline); + } #if 0 /* was: #if ENABLE_INLINE_FILES -- Note that enabling this code will break restarts */ if (options->priv_key_file_inline) @@ -2838,19 +3105,6 @@ do_init_crypto_tls(struct context *c, const unsigned int flags) /* In short form, unique datagram identifier is 32 bits, in long form 64 bits */ packet_id_long_form = cipher_kt_mode_ofb_cfb(c->c1.ks.key_type.cipher); - /* Compute MTU parameters (postpone if we push/pull options) */ - if (c->options.pull || c->options.mode == MODE_SERVER) - { - /* Account for worst-case crypto overhead before allocating buffers */ - frame_add_to_extra_frame(&c->c2.frame, crypto_max_overhead()); - } - else - { - crypto_adjust_frame_parameters(&c->c2.frame, &c->c1.ks.key_type, - options->replay, packet_id_long_form); - } - tls_adjust_frame_parameters(&c->c2.frame); - /* Set all command-line TLS-related options */ CLEAR(to); @@ -2872,9 +3126,8 @@ do_init_crypto_tls(struct context *c, const unsigned int flags) to.replay_window = options->replay_window; to.replay_time = options->replay_time; to.tcp_mode = link_socket_proto_connection_oriented(options->ce.proto); - to.config_ciphername = c->c1.ciphername; - to.config_ncp_ciphers = options->ncp_ciphers; - to.ncp_enabled = options->ncp_enabled; + to.config_ciphername = c->options.ciphername; + to.config_ncp_ciphers = c->options.ncp_ciphers; to.transition_window = options->transition_window; to.handshake_window = options->handshake_window; to.packet_timeout = options->tls_timeout; @@ -2899,16 +3152,21 @@ do_init_crypto_tls(struct context *c, const unsigned int flags) to.pull = options->pull; if (options->push_peer_info) /* all there is */ { - to.push_peer_info_detail = 2; + to.push_peer_info_detail = 3; } else if (options->pull) /* pull clients send some details */ { - to.push_peer_info_detail = 1; + to.push_peer_info_detail = 2; } - else /* default: no peer-info at all */ + else if (options->mode == MODE_SERVER) /* server: no peer info at all */ { to.push_peer_info_detail = 0; } + else /* default: minimal info to allow NCP in P2P mode */ + { + to.push_peer_info_detail = 1; + } + /* should we not xmit any packets until we get an initial * response from client? */ @@ -2917,8 +3175,6 @@ do_init_crypto_tls(struct context *c, const unsigned int flags) to.xmit_hold = true; } - to.disable_occ = !options->occ; - to.verify_command = options->tls_verify; to.verify_export_cert = options->tls_export_cert; to.verify_x509_type = (options->verify_x509_type & 0xff); @@ -2927,14 +3183,16 @@ do_init_crypto_tls(struct context *c, const unsigned int flags) to.crl_file_inline = options->crl_file_inline; to.ssl_flags = options->ssl_flags; to.ns_cert_type = options->ns_cert_type; - memmove(to.remote_cert_ku, options->remote_cert_ku, sizeof(to.remote_cert_ku)); + memcpy(to.remote_cert_ku, options->remote_cert_ku, sizeof(to.remote_cert_ku)); to.remote_cert_eku = options->remote_cert_eku; to.verify_hash = options->verify_hash; to.verify_hash_algo = options->verify_hash_algo; + to.verify_hash_depth = options->verify_hash_depth; + to.verify_hash_no_ca = options->verify_hash_no_ca; #ifdef ENABLE_X509ALTUSERNAME - to.x509_username_field = (char *) options->x509_username_field; + memcpy(to.x509_username_field, options->x509_username_field, sizeof(to.x509_username_field)); #else - to.x509_username_field = X509_USERNAME_FIELD_DEFAULT; + to.x509_username_field[0] = X509_USERNAME_FIELD_DEFAULT; #endif to.es = c->c2.es; to.net_ctx = &c->net_ctx; @@ -2945,30 +3203,31 @@ do_init_crypto_tls(struct context *c, const unsigned int flags) to.plugins = c->plugins; -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT to.mda_context = &c->c2.mda_context; #endif to.auth_user_pass_verify_script = options->auth_user_pass_verify_script; to.auth_user_pass_verify_script_via_file = options->auth_user_pass_verify_script_via_file; + to.client_crresponse_script = options->client_crresponse_script; to.tmp_dir = options->tmp_dir; if (options->ccd_exclusive) { to.client_config_dir_exclusive = options->client_config_dir; } to.auth_user_pass_file = options->auth_user_pass_file; + to.auth_user_pass_file_inline = options->auth_user_pass_file_inline; to.auth_token_generate = options->auth_token_generate; to.auth_token_lifetime = options->auth_token_lifetime; + to.auth_token_renewal = options->auth_token_renewal; to.auth_token_call_auth = options->auth_token_call_auth; to.auth_token_key = c->c1.ks.auth_token_key; to.x509_track = options->x509_track; -#if P2MP #ifdef ENABLE_MANAGEMENT to.sci = &options->sc_info; #endif -#endif #ifdef USE_COMP to.comp_options = options->comp; @@ -2999,8 +3258,6 @@ do_init_crypto_tls(struct context *c, const unsigned int flags) to.tls_wrap.opt.key_ctx_bi = c->c1.ks.tls_wrap_key; to.tls_wrap.opt.pid_persist = &c->c1.pid_persist; to.tls_wrap.opt.flags |= CO_PACKET_ID_LONG_FORM; - crypto_adjust_frame_parameters(&to.frame, &c->c1.ks.tls_auth_key_type, - true, true); } /* TLS handshake encryption (--tls-crypt) */ @@ -3011,7 +3268,6 @@ do_init_crypto_tls(struct context *c, const unsigned int flags) to.tls_wrap.opt.key_ctx_bi = c->c1.ks.tls_wrap_key; to.tls_wrap.opt.pid_persist = &c->c1.pid_persist; to.tls_wrap.opt.flags |= CO_PACKET_ID_LONG_FORM; - tls_crypt_adjust_frame_parameters(&to.frame); if (options->ce.tls_crypt_v2_file) { @@ -3026,12 +3282,15 @@ do_init_crypto_tls(struct context *c, const unsigned int flags) { to.tls_wrap.tls_crypt_v2_server_key = c->c1.ks.tls_crypt_v2_server_key; to.tls_crypt_v2_verify_script = c->options.tls_crypt_v2_verify_script; + if (options->ce.tls_crypt_v2_force_cookie) + { + to.tls_wrap.opt.flags |= CO_FORCE_TLSCRYPTV2_COOKIE; + } } } - /* If we are running over TCP, allow for - * length prefix */ - socket_adjust_frame_parameters(&to.frame, options->ce.proto); + /* let the TLS engine know if keys have to be installed in DCO or not */ + to.dco_enabled = dco_enabled(options); /* * Initialize OpenVPN's master TLS-mode object. @@ -3039,30 +3298,41 @@ do_init_crypto_tls(struct context *c, const unsigned int flags) if (flags & CF_INIT_TLS_MULTI) { c->c2.tls_multi = tls_multi_init(&to); + /* inherit the dco context from the tuntap object */ + if (c->c1.tuntap) + { + c->c2.tls_multi->dco = &c->c1.tuntap->dco; + } } if (flags & CF_INIT_TLS_AUTH_STANDALONE) { c->c2.tls_auth_standalone = tls_auth_standalone_init(&to, &c->c2.gc); + c->c2.session_id_hmac = session_id_hmac_init(); } } static void -do_init_finalize_tls_frame(struct context *c) +do_init_frame_tls(struct context *c) { if (c->c2.tls_multi) { - tls_multi_init_finalize(c->c2.tls_multi, &c->c2.frame); - ASSERT(EXPANDED_SIZE(&c->c2.tls_multi->opt.frame) <= - EXPANDED_SIZE(&c->c2.frame)); + tls_multi_init_finalize(c->c2.tls_multi, c->options.ce.tls_mtu); + ASSERT(c->c2.tls_multi->opt.frame.buf.payload_size <= + c->c2.frame.buf.payload_size); frame_print(&c->c2.tls_multi->opt.frame, D_MTU_INFO, "Control Channel MTU parms"); + + /* Keep the max mtu also in the frame of tls multi so it can access + * it in push_peer_info */ + c->c2.tls_multi->opt.frame.tun_max_mtu = c->c2.frame.tun_max_mtu; } if (c->c2.tls_auth_standalone) { - tls_auth_standalone_finalize(c->c2.tls_auth_standalone, &c->c2.frame); + tls_init_control_channel_frame_parameters(&c->c2.tls_auth_standalone->frame, c->options.ce.tls_mtu); frame_print(&c->c2.tls_auth_standalone->frame, D_MTU_INFO, "TLS-Auth MTU parms"); + c->c2.tls_auth_standalone->tls_wrap.work = alloc_buf_gc(BUF_SIZE(&c->c2.frame), &c->c2.gc); } } @@ -3070,9 +3340,15 @@ do_init_finalize_tls_frame(struct context *c) * No encryption or authentication. */ static void -do_init_crypto_none(const struct context *c) +do_init_crypto_none(struct context *c) { ASSERT(!c->options.test_crypto); + + /* Initialise key_type with auth/cipher "none", so the key_type struct is + * valid */ + init_key_type(&c->c1.ks.key_type, "none", "none", + c->options.test_crypto, true); + msg(M_WARN, "******* WARNING *******: All encryption and authentication features " "disabled -- All data will be tunnelled as clear text and will not be " @@ -3100,102 +3376,20 @@ do_init_crypto(struct context *c, const unsigned int flags) static void do_init_frame(struct context *c) { -#ifdef USE_COMP - /* - * modify frame parameters if compression is enabled - */ - if (comp_enabled(&c->options.comp)) - { - comp_add_to_extra_frame(&c->c2.frame); - -#if !defined(ENABLE_LZ4) - /* - * Compression usage affects buffer alignment when non-swapped algs - * such as LZO is used. - * Newer algs like LZ4 and comp-stub with COMP_F_SWAP don't need - * any special alignment because of the control-byte swap approach. - * LZO alignment (on the other hand) is problematic because - * the presence of the control byte means that either the output of - * decryption must be written to an unaligned buffer, or the input - * to compression (or packet dispatch if packet is uncompressed) - * must be read from an unaligned buffer. - * This code tries to align the input to compression (or packet - * dispatch if packet is uncompressed) at the cost of requiring - * decryption output to be written to an unaligned buffer, so - * it's more of a tradeoff than an optimal solution and we don't - * include it when we are doing a modern build with LZ4. - * Strictly speaking, on the server it would be better to execute - * this code for every connection after we decide the compression - * method, but currently the frame code doesn't appear to be - * flexible enough for this, since the frame is already established - * before it is known which compression options will be pushed. - */ - if (comp_unswapped_prefix(&c->options.comp) && CIPHER_ENABLED(c)) - { - frame_add_to_align_adjust(&c->c2.frame, COMP_PREFIX_LEN); - frame_or_align_flags(&c->c2.frame, - FRAME_HEADROOM_MARKER_FRAGMENT - |FRAME_HEADROOM_MARKER_DECRYPT); - } -#endif - -#ifdef ENABLE_FRAGMENT - comp_add_to_extra_frame(&c->c2.frame_fragment_omit); /* omit compression frame delta from final frame_fragment */ -#endif - } -#endif /* USE_COMP */ - - /* - * Adjust frame size for UDP Socks support. - */ - if (c->options.ce.socks_proxy_server) - { - socks_adjust_frame_parameters(&c->c2.frame, c->options.ce.proto); - } - /* * Adjust frame size based on the --tun-mtu-extra parameter. */ if (c->options.ce.tun_mtu_extra_defined) { - tun_adjust_frame_parameters(&c->c2.frame, c->options.ce.tun_mtu_extra); + c->c2.frame.extra_tun += c->options.ce.tun_mtu_extra; } - /* - * Adjust frame size based on link socket parameters. - * (Since TCP is a stream protocol, we need to insert - * a packet length uint16_t in the buffer.) - */ - socket_adjust_frame_parameters(&c->c2.frame, c->options.ce.proto); - /* * Fill in the blanks in the frame parameters structure, * make sure values are rational, etc. */ frame_finalize_options(c, NULL); -#ifdef USE_COMP - /* - * Modify frame parameters if compression is compiled in. - * Should be called after frame_finalize_options. - */ - comp_add_to_extra_buffer(&c->c2.frame); -#ifdef ENABLE_FRAGMENT - comp_add_to_extra_buffer(&c->c2.frame_fragment_omit); /* omit compression frame delta from final frame_fragment */ -#endif -#endif /* USE_COMP */ - - /* packets with peer-id (P_DATA_V2) need 3 extra bytes in frame (on client) - * and need link_mtu+3 bytes on socket reception (on server). - * - * accommodate receive path in f->extra_link, which has the side effect of - * also increasing send buffers (BUF_SIZE() macro), which need to be - * allocated big enough before receiving peer-id option from server. - * - * f->extra_frame is adjusted when peer-id option is push-received - */ - frame_add_to_extra_link(&c->c2.frame, 3); - #ifdef ENABLE_FRAGMENT /* * Set frame parameter for fragment code. This is necessary because @@ -3203,7 +3397,6 @@ do_init_frame(struct context *c) * passed through the compression code. */ c->c2.frame_fragment = c->c2.frame; - frame_subtract_extra(&c->c2.frame_fragment, &c->c2.frame_fragment_omit); c->c2.frame_fragment_initial = c->c2.frame_fragment; #endif @@ -3219,12 +3412,17 @@ do_init_frame(struct context *c) #endif #ifdef ENABLE_FRAGMENT - if ((c->options.ce.mssfix || c->options.ce.fragment) - && TUN_MTU_SIZE(&c->c2.frame_fragment) != ETHERNET_MTU) + if (c->options.ce.fragment > 0 && c->options.ce.mssfix > c->options.ce.fragment) { - msg(M_WARN, - "WARNING: normally if you use --mssfix and/or --fragment, you should also set --tun-mtu %d (currently it is %d)", - ETHERNET_MTU, TUN_MTU_SIZE(&c->c2.frame_fragment)); + msg(M_WARN, "WARNING: if you use --mssfix and --fragment, you should " + "set --fragment (%d) larger or equal than --mssfix (%d)", + c->options.ce.fragment, c->options.ce.mssfix); + } + if (c->options.ce.fragment > 0 && c->options.ce.mssfix > 0 + && c->options.ce.fragment_encap != c->options.ce.mssfix_encap) + { + msg(M_WARN, "WARNING: if you use --mssfix and --fragment, you should " + "use the \"mtu\" flag for both or none of of them."); } #endif } @@ -3264,7 +3462,6 @@ do_option_warnings(struct context *c) msg(M_WARN, "WARNING: you are using chroot without specifying user and group -- this may cause the chroot jail to be insecure"); } -#if P2MP if (o->pull && o->ifconfig_local && c->first_time) { msg(M_WARN, "WARNING: using --pull/--client and --ifconfig together is probably not what you want"); @@ -3290,7 +3487,6 @@ do_option_warnings(struct context *c) msg(M_WARN, "WARNING: --keepalive option is missing from server config"); } } -#endif /* if P2MP */ if (!o->replay) { @@ -3332,12 +3528,6 @@ do_option_warnings(struct context *c) } } -static void -do_init_frame_tls(struct context *c) -{ - do_init_finalize_tls_frame(c); -} - struct context_buffers * init_context_buffers(const struct frame *frame) { @@ -3345,17 +3535,19 @@ init_context_buffers(const struct frame *frame) ALLOC_OBJ_CLEAR(b, struct context_buffers); - b->read_link_buf = alloc_buf(BUF_SIZE(frame)); - b->read_tun_buf = alloc_buf(BUF_SIZE(frame)); + size_t buf_size = BUF_SIZE(frame); + + b->read_link_buf = alloc_buf(buf_size); + b->read_tun_buf = alloc_buf(buf_size); - b->aux_buf = alloc_buf(BUF_SIZE(frame)); + b->aux_buf = alloc_buf(buf_size); - b->encrypt_buf = alloc_buf(BUF_SIZE(frame)); - b->decrypt_buf = alloc_buf(BUF_SIZE(frame)); + b->encrypt_buf = alloc_buf(buf_size); + b->decrypt_buf = alloc_buf(buf_size); #ifdef USE_COMP - b->compress_buf = alloc_buf(BUF_SIZE(frame)); - b->decompress_buf = alloc_buf(BUF_SIZE(frame)); + b->compress_buf = alloc_buf(buf_size); + b->decompress_buf = alloc_buf(buf_size); #endif return b; @@ -3402,8 +3594,8 @@ static void do_init_fragment(struct context *c) { ASSERT(c->options.ce.fragment); - frame_set_mtu_dynamic(&c->c2.frame_fragment, - c->options.ce.fragment, SET_MTU_UPPER_BOUND); + frame_calculate_dynamic(&c->c2.frame_fragment, &c->c1.ks.key_type, + &c->options, get_link_socket_info(c)); fragment_frame_init(c->c2.fragment, &c->c2.frame_fragment); } #endif @@ -3419,63 +3611,6 @@ do_link_socket_new(struct context *c) c->c2.link_socket_owned = true; } -/* - * bind the TCP/UDP socket - */ -static void -do_init_socket_1(struct context *c, const int mode) -{ - unsigned int sockflags = c->options.sockflags; - -#if PORT_SHARE - if (c->options.port_share_host && c->options.port_share_port) - { - sockflags |= SF_PORT_SHARE; - } -#endif - - link_socket_init_phase1(c->c2.link_socket, - c->options.ce.local, - c->options.ce.local_port, - c->options.ce.remote, - c->options.ce.remote_port, - c->c1.dns_cache, - c->options.ce.proto, - c->options.ce.af, - c->options.ce.bind_ipv6_only, - mode, - c->c2.accept_from, - c->c1.http_proxy, - c->c1.socks_proxy, -#ifdef ENABLE_DEBUG - c->options.gremlin, -#endif - c->options.ce.bind_local, - c->options.ce.remote_float, - c->options.inetd, - &c->c1.link_socket_addr, - c->options.ipchange, - c->plugins, - c->options.resolve_retry_seconds, - c->options.ce.mtu_discover_type, - c->options.rcvbuf, - c->options.sndbuf, - c->options.mark, - c->options.bind_dev, - &c->c2.server_poll_interval, - sockflags); -} - -/* - * finalize the TCP/UDP socket - */ -static void -do_init_socket_2(struct context *c) -{ - link_socket_init_phase2(c->c2.link_socket, &c->c2.frame, - c->sig); -} - /* * Print MTU INFO */ @@ -3539,10 +3674,14 @@ do_init_first_time(struct context *c) ALLOC_OBJ_CLEAR_GC(c->c0, struct context_0, &c->gc); c0 = c->c0; - /* get user and/or group that we want to setuid/setgid to */ - c0->uid_gid_specified = - platform_group_get(c->options.groupname, &c0->platform_state_group) - |platform_user_get(c->options.username, &c0->platform_state_user); + /* get user and/or group that we want to setuid/setgid to, + * sets also platform_x_state */ + bool group_defined = platform_group_get(c->options.groupname, + &c0->platform_state_group); + bool user_defined = platform_user_get(c->options.username, + &c0->platform_state_user); + + c0->uid_gid_specified = user_defined || group_defined; /* perform postponed chdir if --daemon */ if (c->did_we_daemonize && c->options.cd_dir == NULL) @@ -3555,23 +3694,6 @@ do_init_first_time(struct context *c) } } -/* - * If xinetd/inetd mode, don't allow restart. - */ -static void -do_close_check_if_restart_permitted(struct context *c) -{ - if (c->options.inetd - && (c->sig->signal_received == SIGHUP - || c->sig->signal_received == SIGUSR1)) - { - c->sig->signal_received = SIGTERM; - msg(M_INFO, - PACKAGE_NAME - " started by inetd/xinetd cannot restart... Exiting."); - } -} - /* * free buffers */ @@ -3599,14 +3721,9 @@ do_close_tls(struct context *c) } /* free options compatibility strings */ - if (c->c2.options_string_local) - { - free(c->c2.options_string_local); - } - if (c->c2.options_string_remote) - { - free(c->c2.options_string_remote); - } + free(c->c2.options_string_local); + free(c->c2.options_string_remote); + c->c2.options_string_local = c->c2.options_string_remote = NULL; if (c->c2.pulled_options_state) @@ -3644,6 +3761,15 @@ do_close_free_key_schedule(struct context *c, bool free_ssl_ctx) static void do_close_link_socket(struct context *c) { + /* in dco-win case, link socket is a tun handle which is + * closed in do_close_tun(). Set it to UNDEFINED so + * we won't use WinSock API to close it. */ + if (tuntap_is_dco_win(c->c1.tuntap) && c->c2.link_socket + && c->c2.link_socket->dco_installed) + { + c->c2.link_socket->sd = SOCKET_UNDEFINED; + } + if (c->c2.link_socket && c->c2.link_socket_owned) { link_socket_close(c->c2.link_socket); @@ -3851,13 +3977,11 @@ do_setup_fast_io(struct context *c) } else { -#ifdef ENABLE_FEATURE_SHAPER if (c->options.shaper) { msg(M_INFO, "NOTE: --fast-io is disabled since we are using --shaper"); } else -#endif { c->c2.fast_io = true; } @@ -4030,6 +4154,8 @@ init_management_callback_p2p(struct context *c) #ifdef TARGET_ANDROID cb.network_change = management_callback_network_change; #endif + cb.remote_entry_count = management_callback_remote_entry_count; + cb.remote_entry_get = management_callback_remote_entry_get; management_set_callback(management, &cb); } #endif @@ -4068,7 +4194,6 @@ open_management(struct context *c) c->options.management_log_history_cache, c->options.management_echo_buffer_size, c->options.management_state_buffer_size, - c->options.management_write_peer_info_file, c->options.remap_sigusr1, flags)) { @@ -4121,6 +4246,17 @@ uninit_management_callback(void) #endif } +void +persist_client_stats(struct context *c) +{ +#ifdef ENABLE_MANAGEMENT + if (management) + { + man_persist_client_stats(management, c); + } +#endif +} + /* * Initialize a tunnel instance, handle pre and post-init * signal settings. @@ -4164,9 +4300,7 @@ init_instance(struct context *c, const struct env_set *env, const unsigned int f } /* signals caught here will abort */ - c->sig->signal_received = 0; - c->sig->signal_text = NULL; - c->sig->source = SIG_SOURCE_SOFT; + signal_reset(c->sig); if (c->mode == CM_P2P) { @@ -4192,6 +4326,9 @@ init_instance(struct context *c, const struct env_set *env, const unsigned int f } } + /* Resets all values to the initial values from the config where needed */ + pre_connect_restore(&c->options, &c->c2.gc); + /* map in current connection entry */ next_connection_entry(c); @@ -4216,13 +4353,11 @@ init_instance(struct context *c, const struct env_set *env, const unsigned int f platform_mlockall(true); } -#if P2MP /* get passwords if undefined */ if (auth_retry_get() == AR_INTERACT) { init_query_passwords(c); } -#endif /* initialize context level 2 --verb/--mute parms */ init_verb_mute(c, IVM_LEVEL_2); @@ -4351,20 +4486,18 @@ init_instance(struct context *c, const struct env_set *env, const unsigned int f } #endif - /* initialize dynamic MTU variable */ - frame_init_mssfix(&c->c2.frame, &c->options); - /* bind the TCP/UDP socket */ if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP) { - do_init_socket_1(c, link_socket_mode); + link_socket_init_phase1(c, link_socket_mode); } /* initialize tun/tap device object, * open tun/tap device, ifconfig, run up script, etc. */ if (!(options->up_delay || PULL_DEFINED(options)) && (c->mode == CM_P2P || c->mode == CM_TOP)) { - c->c2.did_open_tun = do_open_tun(c); + int error_flags = 0; + c->c2.did_open_tun = do_open_tun(c, &error_flags); } c->c2.frame_initial = c->c2.frame; @@ -4401,9 +4534,16 @@ init_instance(struct context *c, const struct env_set *env, const unsigned int f /* finalize the TCP/UDP socket */ if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP) { - do_init_socket_2(c); + link_socket_init_phase2(c); } + /* Update dynamic frame calculation as exact transport socket information + * (IP vs IPv6) may be only available after socket phase2 has finished. + * This is only needed for --static or no crypto, NCP will recalculate this + * in tls_session_update_crypto_params (P2MP) */ + frame_calculate_dynamic(&c->c2.frame, &c->c1.ks.key_type, &c->options, + get_link_socket_info(c)); + /* * Actually do UID/GID downgrade, and chroot, if requested. * May be delayed by --client, --pull, or --up-delay. @@ -4432,13 +4572,6 @@ init_instance(struct context *c, const struct env_set *env, const unsigned int f } #endif -#ifdef ENABLE_PF - if (child) - { - pf_init_context(c); - } -#endif - /* Check for signals */ if (IS_SIG(c)) { @@ -4470,9 +4603,6 @@ close_instance(struct context *c) || c->mode == CM_CHILD_UDP || c->mode == CM_TOP) { - /* if xinetd/inetd mode, don't allow restart */ - do_close_check_if_restart_permitted(c); - #ifdef USE_COMP if (c->c2.comp_context) { @@ -4484,31 +4614,29 @@ close_instance(struct context *c) /* free buffers */ do_close_free_buf(c); + /* close peer for DCO if enabled, needs peer-id so must be done before + * closing TLS contexts */ + dco_remove_peer(c); + /* close TLS */ do_close_tls(c); /* free key schedules */ do_close_free_key_schedule(c, (c->mode == CM_P2P || c->mode == CM_TOP)); - restore_ncp_options(c); - /* close TCP/UDP connection */ do_close_link_socket(c); /* close TUN/TAP device */ do_close_tun(c, false); -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT if (management) { management_notify_client_close(management, &c->c2.mda_context, NULL); } #endif -#ifdef ENABLE_PF - pf_destroy_context(&c->c2.pf); -#endif - #ifdef ENABLE_PLUGIN /* call plugin close functions and unload */ do_close_plugins(c); @@ -4562,9 +4690,8 @@ inherit_context_child(struct context *dest, dest->c1.ks.tls_auth_key_type = src->c1.ks.tls_auth_key_type; dest->c1.ks.tls_crypt_v2_server_key = src->c1.ks.tls_crypt_v2_server_key; /* inherit pre-NCP ciphers */ - dest->c1.ciphername = src->c1.ciphername; - dest->c1.authname = src->c1.authname; - dest->c1.keysize = src->c1.keysize; + dest->options.ciphername = src->options.ciphername; + dest->options.authname = src->options.authname; /* inherit auth-token */ dest->c1.ks.auth_token_key = src->c1.ks.auth_token_key; @@ -4588,15 +4715,18 @@ inherit_context_child(struct context *dest, #endif /* context init */ + + /* inherit tun/tap interface object now as it may be required + * to initialize the DCO context in init_instance() + */ + dest->c1.tuntap = src->c1.tuntap; + init_instance(dest, src->c2.es, CC_NO_CLOSE | CC_USR1_TO_HUP); if (IS_SIG(dest)) { return; } - /* inherit tun/tap interface object */ - dest->c1.tuntap = src->c1.tuntap; - /* UDP inherits some extra things which TCP does not */ if (dest->mode == CM_CHILD_UDP) { @@ -4673,7 +4803,7 @@ close_context(struct context *c, int sig, unsigned int flags) if (sig >= 0) { - c->sig->signal_received = sig; + register_signal(c->sig, sig, "close_context"); } if (c->sig->signal_received == SIGUSR1) @@ -4681,8 +4811,7 @@ close_context(struct context *c, int sig, unsigned int flags) if ((flags & CC_USR1_TO_HUP) || (c->sig->source == SIG_SOURCE_HARD && (flags & CC_HARD_USR1_TO_HUP))) { - c->sig->signal_received = SIGHUP; - c->sig->signal_text = "close_context usr1 to hup"; + register_signal(c->sig, SIGHUP, "close_context usr1 to hup"); } } @@ -4783,4 +4912,4 @@ do_test_crypto(const struct options *o) return true; } return false; -} +} \ No newline at end of file diff --git a/src/openvpn/init.h b/src/openvpn/init.h index 0c5a2e99369..a6184f5f40a 100644 --- a/src/openvpn/init.h +++ b/src/openvpn/init.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -30,7 +30,7 @@ * Baseline maximum number of events * to wait for. */ -#define BASE_N_EVENTS 4 +#define BASE_N_EVENTS 5 void context_clear(struct context *c); @@ -56,7 +56,7 @@ bool print_openssl_info(const struct options *options); bool do_genkey(const struct options *options); -bool do_persist_tuntap(const struct options *options, openvpn_net_ctx_t *ctx); +bool do_persist_tuntap(struct options *options, openvpn_net_ctx_t *ctx); bool possibly_become_daemon(const struct options *options); @@ -71,12 +71,9 @@ void init_instance(struct context *c, const struct env_set *env, const unsigned */ void init_query_passwords(const struct context *c); -void do_route(const struct options *options, - struct route_list *route_list, - struct route_ipv6_list *route_ipv6_list, - const struct tuntap *tt, - const struct plugin_list *plugins, - struct env_set *es, +bool do_route(const struct options *options, struct route_list *route_list, + struct route_ipv6_list *route_ipv6_list, const struct tuntap *tt, + const struct plugin_list *plugins, struct env_set *es, openvpn_net_ctx_t *ctx); void close_instance(struct context *c); @@ -116,6 +113,7 @@ void free_context_buffers(struct context_buffers *b); #define ISC_ERRORS (1<<0) #define ISC_SERVER (1<<1) +#define ISC_ROUTE_ERRORS (1<<2) void initialization_sequence_completed(struct context *c, const unsigned int flags); #ifdef ENABLE_MANAGEMENT @@ -144,6 +142,9 @@ void open_plugins(struct context *c, const bool import_options, int init_point); void tun_abort(void); void write_pid_file(const char *filename, const char *chroot_dir); + void remove_pid_file(void); -#endif /* ifndef INIT_H */ +void persist_client_stats(struct context *c); + +#endif /* ifndef INIT_H */ \ No newline at end of file diff --git a/src/openvpn/integer.h b/src/openvpn/integer.h index 88c3711b2e1..fc143dd160a 100644 --- a/src/openvpn/integer.h +++ b/src/openvpn/integer.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -39,6 +39,31 @@ /* * min/max functions */ +static inline unsigned int +max_uint(unsigned int x, unsigned int y) +{ + if (x > y) + { + return x; + } + else + { + return y; + } +} + +static inline unsigned int +min_uint(unsigned int x, unsigned int y) +{ + if (x < y) + { + return x; + } + else + { + return y; + } +} static inline int max_int(int x, int y) @@ -160,4 +185,13 @@ index_verify(int index, int size, const char *file, int line) return index; } -#endif /* ifndef INTEGER_H */ +/** + * Rounds down num to the nearest multiple of multiple + */ +static inline unsigned int +round_down_uint(unsigned int num, unsigned int multiple) +{ + return (num / multiple) * multiple; +} + +#endif /* ifndef INTEGER_H */ \ No newline at end of file diff --git a/src/openvpn/interval.c b/src/openvpn/interval.c index 2f0fc42ddf3..7887a2b1b84 100644 --- a/src/openvpn/interval.c +++ b/src/openvpn/interval.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -46,39 +46,40 @@ event_timeout_trigger(struct event_timeout *et, struct timeval *tv, const int et_const_retry) { + if (!et->defined) + { + return false; + } + bool ret = false; - const time_t local_now = now; + time_t wakeup = event_timeout_remaining(et); - if (et->defined) + if (wakeup <= 0) { - time_t wakeup = et->last - local_now + et->n; - if (wakeup <= 0) - { #if INTERVAL_DEBUG - dmsg(D_INTERVAL, "EVENT event_timeout_trigger (%d) etcr=%d", et->n, - et_const_retry); + dmsg(D_INTERVAL, "EVENT event_timeout_trigger (%d) etcr=%d", et->n, + et_const_retry); #endif - if (et_const_retry < 0) - { - et->last = local_now; - wakeup = et->n; - ret = true; - } - else - { - wakeup = et_const_retry; - } + if (et_const_retry < 0) + { + et->last = now; + wakeup = et->n; + ret = true; } - - if (tv && wakeup < tv->tv_sec) + else { + wakeup = et_const_retry; + } + } + + if (tv && wakeup < tv->tv_sec) + { #if INTERVAL_DEBUG - dmsg(D_INTERVAL, "EVENT event_timeout_wakeup (%d/%d) etcr=%d", - (int) wakeup, et->n, et_const_retry); + dmsg(D_INTERVAL, "EVENT event_timeout_wakeup (%d/%d) etcr=%d", + (int) wakeup, et->n, et_const_retry); #endif - tv->tv_sec = wakeup; - tv->tv_usec = 0; - } + tv->tv_sec = wakeup; + tv->tv_usec = 0; } return ret; -} +} \ No newline at end of file diff --git a/src/openvpn/interval.h b/src/openvpn/interval.h index f58bfacf680..b20f45cfe9b 100644 --- a/src/openvpn/interval.h +++ b/src/openvpn/interval.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -135,9 +135,9 @@ interval_action(struct interval *top) struct event_timeout { - bool defined; - interval_t n; - time_t last; /* time of last event */ + bool defined; /**< This timeout is active */ + interval_t n; /**< periodic interval for periodic timeouts */ + time_t last; /**< time of last event */ }; static inline bool @@ -145,7 +145,12 @@ event_timeout_defined(const struct event_timeout *et) { return et->defined; } - +/** + * Clears the timeout and reset all values to 0. Following timer checks will + * not trigger. + * + * @param et timer struct + */ static inline void event_timeout_clear(struct event_timeout *et) { @@ -154,22 +159,32 @@ event_timeout_clear(struct event_timeout *et) et->last = 0; } -static inline struct event_timeout -event_timeout_clear_ret(void) -{ - struct event_timeout ret; - event_timeout_clear(&ret); - return ret; -} +/** + * Initialises a timer struct. The timer will become true/trigger after + * last + n seconds. + * + * + * @param et Timer struct + * @param n Interval of the timer for periodic timer. A negative + * value for n will be interpreted as 0. + * @param last Sets the base time of the timer. + */ static inline void -event_timeout_init(struct event_timeout *et, interval_t n, const time_t local_now) +event_timeout_init(struct event_timeout *et, interval_t n, const time_t last) { et->defined = true; et->n = (n >= 0) ? n : 0; - et->last = local_now; + et->last = last; } +/** + * Resets a timer. + * + * Sets the last time the timer has been triggered for the calculation of the + * next event. + * @param et + */ static inline void event_timeout_reset(struct event_timeout *et) { @@ -179,42 +194,70 @@ event_timeout_reset(struct event_timeout *et) } } +/** + * Sets the interval n of a timeout. + * @param et + * @param n Interval value of the timer, negative values + * will be interpreted as 0 + * + * @note you might need to call reset_coarse_timers after this + */ static inline void event_timeout_modify_wakeup(struct event_timeout *et, interval_t n) { - /* note that you might need to call reset_coarse_timers after this */ if (et->defined) { et->n = (n >= 0) ? n : 0; } } -/* - * Will return the time left for a timeout, this function does not check - * if the timeout is actually valid +/** + * Returns the time until the timeout should triggered, from \c now. + * This function does not check if the timeout is actually valid. */ static inline interval_t event_timeout_remaining(struct event_timeout *et) { - return (interval_t) (et->last - now + et->n); + return (interval_t) ((et->last + et->n) - now); } -/* - * This is the principal function for testing and triggering recurring - * timers and will return true on a timer signal event. - * If et_const_retry == ETT_DEFAULT and a signal occurs, - * the function will return true and *et will be armed for the - * next event. If et_const_retry >= 0 and a signal occurs, - * *et will not be touched, but *tv will be set to - * minimum (*tv, et_const_retry) for a future re-test, - * and the function will return true. - */ - #define ETT_DEFAULT (-1) +/** + * This is the principal function for testing and triggering recurring + * timers. + * + * If *et is not triggered, *tv is set to remaining time until the timeout if + * not already lower: + * + * *tv = minimum(*tv, event_timeout_remaining(*et)) + * + * If *et triggers and et_const_retry is negative (ETT_DEFAULT is -1): + * - the function will return true + * - *et will be armed for the next event (et->last set to now). + * - *tv will be lowered to the event period (n) if larger than the + * period of the event (set to *et's next timeout) + * - *et will not changed (ie also not rearmed, stays armed) + * + * If *et triggers and et_const_retry >= 0, *tv will be lowered to et_const_try + * if larger: + * + * *tv = *minimum(*tv, et_const_retry) + * + * This is mainly useful if the trigger cannot yet be triggered for other + * reasons and a backoff timeout should be returned if the timer is ready + * to trigger. + * + * + * @param et the timeout to check + * @param tv will be set to timeout for next check for this + * timeout unless already smaller. + * @param et_const_retry see above + * @return if the timeout has triggered and event has been reset + */ bool event_timeout_trigger(struct event_timeout *et, struct timeval *tv, - const int et_const_retry); + int et_const_retry); /* * Measure time intervals in microseconds @@ -258,4 +301,4 @@ usec_timer_interval(struct usec_timer *obj) return tv_subtract(&obj->end, &obj->start, USEC_TIMER_MAX); } -#endif /* INTERVAL_H */ +#endif /* INTERVAL_H */ \ No newline at end of file diff --git a/src/openvpn/list.c b/src/openvpn/list.c index 7e4e8081272..59e3e79a708 100644 --- a/src/openvpn/list.c +++ b/src/openvpn/list.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -572,7 +572,7 @@ list_test(void) * -------------------------------------------------------------------- */ -#define mix(a,b,c) \ +#define mix(a, b, c) \ { \ a -= b; a -= c; a ^= (c>>13); \ b -= c; b -= a; b ^= (a<<8); \ @@ -654,4 +654,4 @@ hash_func(const uint8_t *k, uint32_t length, uint32_t initval) mix(a, b, c); /*-------------------------------------- report the result */ return c; -} +} \ No newline at end of file diff --git a/src/openvpn/list.h b/src/openvpn/list.h index e66f6052e3a..6ee2fc53cc9 100644 --- a/src/openvpn/list.h +++ b/src/openvpn/list.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -192,4 +192,4 @@ hash_remove(struct hash *hash, const void *key) return ret; } -#endif /* LIST */ +#endif /* LIST */ \ No newline at end of file diff --git a/src/openvpn/lzo.c b/src/openvpn/lzo.c index da28ecb5f4e..95976e558e4 100644 --- a/src/openvpn/lzo.c +++ b/src/openvpn/lzo.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -160,8 +160,8 @@ lzo_compress(struct buffer *buf, struct buffer work, */ if (buf->len >= COMPRESS_THRESHOLD && lzo_compression_enabled(compctx)) { - const size_t ps = PAYLOAD_SIZE(frame); - ASSERT(buf_init(&work, FRAME_HEADROOM(frame))); + const size_t ps = frame->buf.payload_size; + ASSERT(buf_init(&work, frame->buf.headroom)); ASSERT(buf_safe(&work, ps + COMP_EXTRA_BUFFER(ps))); if (buf->len > ps) @@ -213,7 +213,7 @@ lzo_decompress(struct buffer *buf, struct buffer work, struct compress_context *compctx, const struct frame *frame) { - lzo_uint zlen = EXPANDED_SIZE(frame); + lzo_uint zlen = frame->buf.payload_size; int err; uint8_t c; /* flag indicating whether or not our peer compressed */ @@ -222,7 +222,7 @@ lzo_decompress(struct buffer *buf, struct buffer work, return; } - ASSERT(buf_init(&work, FRAME_HEADROOM(frame))); + ASSERT(buf_init(&work, frame->buf.headroom)); c = *BPTR(buf); ASSERT(buf_advance(buf, 1)); @@ -250,6 +250,7 @@ lzo_decompress(struct buffer *buf, struct buffer work, } else if (c == NO_COMPRESS_BYTE) /* packet was not compressed */ { + /* nothing to do */ } else { @@ -265,10 +266,4 @@ const struct compress_alg lzo_alg = { lzo_compress, lzo_decompress }; - -#else /* if defined(ENABLE_LZO) */ -static void -dummy(void) -{ -} -#endif /* ENABLE_LZO */ +#endif /* ENABLE_LZO */ \ No newline at end of file diff --git a/src/openvpn/lzo.h b/src/openvpn/lzo.h index d0430d2c8ea..e4fcd0ba142 100644 --- a/src/openvpn/lzo.h +++ b/src/openvpn/lzo.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -127,4 +127,4 @@ struct lzo_compress_workspace #endif /* ENABLE_LZO && USE_COMP */ -#endif /* ifndef OPENVPN_LZO_H */ +#endif /* ifndef OPENVPN_LZO_H */ \ No newline at end of file diff --git a/src/openvpn/manage.c b/src/openvpn/manage.c index 0a0b67fbba6..4a56cd69ec1 100644 --- a/src/openvpn/manage.c +++ b/src/openvpn/manage.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -42,6 +42,8 @@ #include "ssl.h" #include "common.h" #include "manage.h" +#include "openvpn.h" +#include "dco.h" #include "memdbg.h" @@ -94,25 +96,22 @@ man_help(void) msg(M_CLIENT, "net : (Windows only) Show network info and routing table."); msg(M_CLIENT, "password type p : Enter password p for a queried OpenVPN password."); msg(M_CLIENT, "remote type [host port] : Override remote directive, type=ACCEPT|MOD|SKIP."); + msg(M_CLIENT, "remote-entry-count : Get number of available remote entries."); + msg(M_CLIENT, "remote-entry-get i|all [j]: Get remote entry at index = i to to j-1 or all."); msg(M_CLIENT, "proxy type [host port flags] : Enter dynamic proxy server info."); msg(M_CLIENT, "pid : Show process ID of the current OpenVPN process."); #ifdef ENABLE_PKCS11 msg(M_CLIENT, "pkcs11-id-count : Get number of available PKCS#11 identities."); msg(M_CLIENT, "pkcs11-id-get index : Get PKCS#11 identity at index."); #endif -#ifdef MANAGEMENT_DEF_AUTH msg(M_CLIENT, "client-auth CID KID : Authenticate client-id/key-id CID/KID (MULTILINE)"); msg(M_CLIENT, "client-auth-nt CID KID : Authenticate client-id/key-id CID/KID"); msg(M_CLIENT, "client-deny CID KID R [CR] : Deny auth client-id/key-id CID/KID with log reason"); msg(M_CLIENT, " text R and optional client reason text CR"); - msg(M_CLIENT, "client-pending-auth CID MSG : Instruct OpenVPN to send AUTH_PENDING and INFO_PRE msg" - " to the client and wait for a final client-auth/client-deny"); + msg(M_CLIENT, "client-pending-auth CID MSG timeout : Instruct OpenVPN to send AUTH_PENDING and INFO_PRE msg"); + msg(M_CLIENT, " to the client and wait for a final client-auth/client-deny"); msg(M_CLIENT, "client-kill CID [M] : Kill client instance CID with message M (def=RESTART)"); msg(M_CLIENT, "env-filter [level] : Set env-var filter level"); -#ifdef MANAGEMENT_PF - msg(M_CLIENT, "client-pf CID : Define packet filter for client CID (MULTILINE)"); -#endif -#endif msg(M_CLIENT, "rsa-sig : Enter a signature in response to >RSA_SIGN challenge"); msg(M_CLIENT, " Enter signature base64 on subsequent lines followed by END"); msg(M_CLIENT, "pk-sig : Enter a signature in response to >PK_SIGN challenge"); @@ -171,6 +170,9 @@ man_state_name(const int state) case OPENVPN_STATE_TCP_CONNECT: return "TCP_CONNECT"; + case OPENVPN_STATE_AUTH_PENDING: + return "AUTH_PENDING"; + default: return "?"; } @@ -198,7 +200,12 @@ man_check_password(struct management *man, const char *line) { if (man_password_needed(man)) { - if (streq(line, man->settings.up.password)) + /* This comparison is not fixed time but since strlen(time) is based on + * the attacker choice, it should not give any indication of the real + * password length, use + 1 to include the NUL byte that terminates the + * string*/ + size_t compare_len = min_uint(strlen(line) + 1, sizeof(man->settings.up.password)); + if (memcmp_constant_time(line, man->settings.up.password, compare_len) == 0) { man->connection.password_verified = true; msg(M_CLIENT, "SUCCESS: password is correct"); @@ -446,6 +453,12 @@ man_signal(struct management *man, const char *name) } } +static void +man_command_unsupported(const char *command_name) +{ + msg(M_CLIENT, "ERROR: The '%s' command is not supported by the current daemon mode", command_name); +} + static void man_status(struct management *man, const int version, struct status_output *so) { @@ -455,41 +468,44 @@ man_status(struct management *man, const int version, struct status_output *so) } else { - msg(M_CLIENT, "ERROR: The 'status' command is not supported by the current daemon mode"); + man_command_unsupported("status"); } } static void man_bytecount(struct management *man, const int update_seconds) { - if (update_seconds >= 0) + if (update_seconds > 0) { man->connection.bytecount_update_seconds = update_seconds; + event_timeout_init(&man->connection.bytecount_update_interval, + man->connection.bytecount_update_seconds, + now); } else { man->connection.bytecount_update_seconds = 0; + event_timeout_clear(&man->connection.bytecount_update_interval); } msg(M_CLIENT, "SUCCESS: bytecount interval changed"); } -void -man_bytecount_output_client(struct management *man) +static void +man_bytecount_output_client(struct management *man, + counter_type dco_read_bytes, + counter_type dco_write_bytes) { char in[32]; char out[32]; + /* do in a roundabout way to work around possible mingw or mingw-glibc bug */ - openvpn_snprintf(in, sizeof(in), counter_format, man->persist.bytes_in); - openvpn_snprintf(out, sizeof(out), counter_format, man->persist.bytes_out); + openvpn_snprintf(in, sizeof(in), counter_format, man->persist.bytes_in + dco_read_bytes); + openvpn_snprintf(out, sizeof(out), counter_format, man->persist.bytes_out + dco_write_bytes); msg(M_CLIENT, ">BYTECOUNT:%s,%s", in, out); - man->connection.bytecount_last_update = now; } -#ifdef MANAGEMENT_DEF_AUTH - void -man_bytecount_output_server(struct management *man, - const counter_type *bytes_in_total, +man_bytecount_output_server(const counter_type *bytes_in_total, const counter_type *bytes_out_total, struct man_def_auth_context *mdac) { @@ -502,8 +518,6 @@ man_bytecount_output_server(struct management *man, mdac->bytecount_last_update = now; } -#endif - static void man_kill(struct management *man, const char *victim) { @@ -575,7 +589,7 @@ man_kill(struct management *man, const char *victim) } else { - msg(M_CLIENT, "ERROR: The 'kill' command is not supported by the current daemon mode"); + man_command_unsupported("kill"); } gc_free(&gc); @@ -781,7 +795,7 @@ man_net(struct management *man) } else { - msg(M_CLIENT, "ERROR: The 'net' command is not supported by the current daemon mode"); + man_command_unsupported("net"); } } @@ -803,7 +817,7 @@ man_send_cc_message(struct management *man, const char *message, const char *par } else { - msg(M_CLIENT, "ERROR: This command is not supported by the current daemon mode"); + man_command_unsupported("cr-repsonse"); } } #ifdef ENABLE_PKCS11 @@ -829,17 +843,64 @@ man_pkcs11_id_get(struct management *man, const int index) msg(M_CLIENT, ">PKCS11ID-ENTRY:'%d'", index); } - if (id != NULL) + free(id); + free(base64); +} + +#endif /* ifdef ENABLE_PKCS11 */ + +static void +man_remote_entry_count(struct management *man) +{ + unsigned count = 0; + if (man->persist.callback.remote_entry_count) { - free(id); + count = (*man->persist.callback.remote_entry_count)(man->persist.callback.arg); + msg(M_CLIENT, "%u", count); + msg(M_CLIENT, "END"); } - if (base64 != NULL) + else { - free(base64); + man_command_unsupported("remote-entry-count"); } } -#endif /* ifdef ENABLE_PKCS11 */ +static void +man_remote_entry_get(struct management *man, const char *p1, const char *p2) +{ + ASSERT(p1); + + if (man->persist.callback.remote_entry_get + && man->persist.callback.remote_entry_count) + { + unsigned int count = (*man->persist.callback.remote_entry_count)(man->persist.callback.arg); + + unsigned int from = (unsigned int) atoi(p1); + unsigned int to = p2 ? (unsigned int) atoi(p2) : from + 1; + + if (!strcmp(p1, "all")) + { + from = 0; + to = count; + } + + for (unsigned int i = from; i < min_uint(to, count); i++) + { + char *remote = NULL; + bool res = (*man->persist.callback.remote_entry_get)(man->persist.callback.arg, i, &remote); + if (res && remote) + { + msg(M_CLIENT, "%u,%s", i, remote); + } + free(remote); + } + msg(M_CLIENT, "END"); + } + else + { + man_command_unsupported("remote-entry-get"); + } +} static void man_hold(struct management *man, const char *cmd) @@ -883,10 +944,8 @@ in_extra_reset(struct man_connection *mc, const int mode) if (mode != IER_NEW) { mc->in_extra_cmd = IEC_UNDEF; -#ifdef MANAGEMENT_DEF_AUTH mc->in_extra_cid = 0; mc->in_extra_kid = 0; -#endif } if (mc->in_extra) { @@ -895,7 +954,7 @@ in_extra_reset(struct man_connection *mc, const int mode) } if (mode == IER_NEW) { - mc->in_extra = buffer_list_new(0); + mc->in_extra = buffer_list_new(); } } } @@ -905,7 +964,6 @@ in_extra_dispatch(struct management *man) { switch (man->connection.in_extra_cmd) { -#ifdef MANAGEMENT_DEF_AUTH case IEC_CLIENT_AUTH: if (man->persist.callback.client_auth) { @@ -929,36 +987,10 @@ in_extra_dispatch(struct management *man) } else { - msg(M_CLIENT, "ERROR: The client-auth command is not supported by the current daemon mode"); - } - break; - -#endif /* ifdef MANAGEMENT_DEF_AUTH */ -#ifdef MANAGEMENT_PF - case IEC_CLIENT_PF: - if (man->persist.callback.client_pf) - { - const bool status = (*man->persist.callback.client_pf) - (man->persist.callback.arg, - man->connection.in_extra_cid, - man->connection.in_extra); - man->connection.in_extra = NULL; - if (status) - { - msg(M_CLIENT, "SUCCESS: client-pf command succeeded"); - } - else - { - msg(M_CLIENT, "ERROR: client-pf command failed"); - } - } - else - { - msg(M_CLIENT, "ERROR: The client-pf command is not supported by the current daemon mode"); + man_command_unsupported("client-auth"); } break; -#endif /* ifdef MANAGEMENT_PF */ case IEC_PK_SIGN: man->connection.ext_key_state = EKS_READY; buffer_list_free(man->connection.ext_key_input); @@ -976,8 +1008,6 @@ in_extra_dispatch(struct management *man) in_extra_reset(&man->connection, IER_RESET); } -#ifdef MANAGEMENT_DEF_AUTH - static bool parse_cid(const char *str, unsigned long *cid) { @@ -993,15 +1023,15 @@ parse_cid(const char *str, unsigned long *cid) } static bool -parse_kid(const char *str, unsigned int *kid) +parse_uint(const char *str, const char *what, unsigned int *uint) { - if (sscanf(str, "%u", kid) == 1) + if (sscanf(str, "%u", uint) == 1) { return true; } else { - msg(M_CLIENT, "ERROR: cannot parse KID"); + msg(M_CLIENT, "ERROR: cannot parse %s", what); return false; } } @@ -1016,15 +1046,18 @@ parse_kid(const char *str, unsigned int *kid) * the information of the additional steps */ static void -man_client_pending_auth(struct management *man, const char *cid_str, const char *extra) +man_client_pending_auth(struct management *man, const char *cid_str, + const char *extra, const char *timeout_str) { unsigned long cid = 0; - if (parse_cid(cid_str, &cid)) + unsigned int timeout = 0; + if (parse_cid(cid_str, &cid) + && parse_uint(timeout_str, "TIMEOUT", &timeout)) { if (man->persist.callback.client_pending_auth) { bool ret = (*man->persist.callback.client_pending_auth) - (man->persist.callback.arg, cid, extra); + (man->persist.callback.arg, cid, extra, timeout); if (ret) { @@ -1038,7 +1071,7 @@ man_client_pending_auth(struct management *man, const char *cid_str, const char } else { - msg(M_CLIENT, "ERROR: The client-pending-auth command is not supported by the current daemon mode"); + man_command_unsupported("client-pending-auth"); } } } @@ -1050,7 +1083,7 @@ man_client_auth(struct management *man, const char *cid_str, const char *kid_str mc->in_extra_cid = 0; mc->in_extra_kid = 0; if (parse_cid(cid_str, &mc->in_extra_cid) - && parse_kid(kid_str, &mc->in_extra_kid)) + && parse_uint(kid_str, "KID", &mc->in_extra_kid)) { mc->in_extra_cmd = IEC_CLIENT_AUTH; in_extra_reset(mc, IER_NEW); @@ -1066,7 +1099,7 @@ man_client_deny(struct management *man, const char *cid_str, const char *kid_str { unsigned long cid = 0; unsigned int kid = 0; - if (parse_cid(cid_str, &cid) && parse_kid(kid_str, &kid)) + if (parse_cid(cid_str, &cid) && parse_uint(kid_str, "KID", &kid)) { if (man->persist.callback.client_auth) { @@ -1089,7 +1122,7 @@ man_client_deny(struct management *man, const char *cid_str, const char *kid_str } else { - msg(M_CLIENT, "ERROR: The client-deny command is not supported by the current daemon mode"); + man_command_unsupported("client-deny"); } } } @@ -1114,7 +1147,7 @@ man_client_kill(struct management *man, const char *cid_str, const char *kill_ms } else { - msg(M_CLIENT, "ERROR: The client-kill command is not supported by the current daemon mode"); + man_command_unsupported("client-kill"); } } } @@ -1129,7 +1162,7 @@ man_client_n_clients(struct management *man) } else { - msg(M_CLIENT, "ERROR: The nclients command is not supported by the current daemon mode"); + man_command_unsupported("nclients"); } } @@ -1140,23 +1173,6 @@ man_env_filter(struct management *man, const int level) msg(M_CLIENT, "SUCCESS: env_filter_level=%d", level); } -#ifdef MANAGEMENT_PF - -static void -man_client_pf(struct management *man, const char *cid_str) -{ - struct man_connection *mc = &man->connection; - mc->in_extra_cid = 0; - mc->in_extra_kid = 0; - if (parse_cid(cid_str, &mc->in_extra_cid)) - { - mc->in_extra_cmd = IEC_CLIENT_PF; - in_extra_reset(mc, IER_NEW); - } -} - -#endif /* MANAGEMENT_PF */ -#endif /* MANAGEMENT_DEF_AUTH */ static void man_pk_sig(struct management *man, const char *cmd_name) @@ -1254,7 +1270,7 @@ man_proxy(struct management *man, const char **p) } else { - msg(M_CLIENT, "ERROR: The proxy command is not supported by the current daemon mode"); + man_command_unsupported("proxy"); } } @@ -1275,7 +1291,7 @@ man_remote(struct management *man, const char **p) } else { - msg(M_CLIENT, "ERROR: The remote command is not supported by the current daemon mode"); + man_command_unsupported("remote"); } } @@ -1340,7 +1356,6 @@ man_dispatch_command(struct management *man, struct status_output *so, const cha { msg(M_CLIENT, "SUCCESS: pid=%d", platform_getpid()); } -#ifdef MANAGEMENT_DEF_AUTH else if (streq(p[0], "nclients")) { man_client_n_clients(man); @@ -1354,7 +1369,6 @@ man_dispatch_command(struct management *man, struct status_output *so, const cha } man_env_filter(man, level); } -#endif else if (streq(p[0], "signal")) { if (man_need(man, p, 1, 0)) @@ -1434,7 +1448,6 @@ man_dispatch_command(struct management *man, struct status_output *so, const cha } else if (streq(p[0], "auth-retry")) { -#if P2MP if (p[1]) { if (auth_retry_set(M_CLIENT, p[1])) @@ -1450,9 +1463,6 @@ man_dispatch_command(struct management *man, struct status_output *so, const cha { msg(M_CLIENT, "SUCCESS: auth-retry=%s", auth_retry_print()); } -#else /* if P2MP */ - msg(M_CLIENT, "ERROR: auth-retry feature is unavailable"); -#endif } else if (streq(p[0], "state")) { @@ -1554,7 +1564,6 @@ man_dispatch_command(struct management *man, struct status_output *so, const cha man_bytecount(man, atoi(p[1])); } } -#ifdef MANAGEMENT_DEF_AUTH else if (streq(p[0], "client-kill")) { if (man_need(man, p, 1, MN_AT_LEAST)) @@ -1585,21 +1594,11 @@ man_dispatch_command(struct management *man, struct status_output *so, const cha } else if (streq(p[0], "client-pending-auth")) { - if (man_need(man, p, 2, 0)) - { - man_client_pending_auth(man, p[1], p[2]); - } - } -#ifdef MANAGEMENT_PF - else if (streq(p[0], "client-pf")) - { - if (man_need(man, p, 1, 0)) + if (man_need(man, p, 3, 0)) { - man_client_pf(man, p[1]); + man_client_pending_auth(man, p[1], p[2], p[3]); } } -#endif -#endif /* ifdef MANAGEMENT_DEF_AUTH */ else if (streq(p[0], "rsa-sig")) { man_pk_sig(man, "rsa-sig"); @@ -1625,6 +1624,17 @@ man_dispatch_command(struct management *man, struct status_output *so, const cha } } #endif + else if (streq(p[0], "remote-entry-count")) + { + man_remote_entry_count(man); + } + else if (streq(p[0], "remote-entry-get")) + { + if (man_need(man, p, 1, MN_AT_LEAST)) + { + man_remote_entry_get(man, p[1], p[2]); + } + } else if (streq(p[0], "proxy")) { if (man_need(man, p, 1, MN_AT_LEAST)) @@ -1691,48 +1701,6 @@ man_stop_ne32(struct management *man) #endif /* ifdef _WIN32 */ -static void -man_record_peer_info(struct management *man) -{ - struct gc_arena gc = gc_new(); - if (man->settings.write_peer_info_file) - { - bool success = false; -#ifdef HAVE_GETSOCKNAME - if (socket_defined(man->connection.sd_cli)) - { - struct sockaddr_in addr; - socklen_t addrlen = sizeof(addr); - int status; - - CLEAR(addr); - status = getsockname(man->connection.sd_cli, (struct sockaddr *)&addr, &addrlen); - if (!status && addrlen == sizeof(addr)) - { - const in_addr_t a = ntohl(addr.sin_addr.s_addr); - const int p = ntohs(addr.sin_port); - FILE *fp = platform_fopen(man->settings.write_peer_info_file, "w"); - if (fp) - { - fprintf(fp, "%s\n%d\n", print_in_addr_t(a, 0, &gc), p); - if (!fclose(fp)) - { - success = true; - } - } - } - } -#endif /* ifdef HAVE_GETSOCKNAME */ - if (!success) - { - msg(D_MANAGEMENT, "MANAGEMENT: failed to write peer info to file %s", - man->settings.write_peer_info_file); - throw_signal_soft(SIGTERM, "management-connect-failed"); - } - } - gc_free(&gc); -} - static void man_connection_settings_reset(struct management *man) { @@ -1768,9 +1736,27 @@ man_new_connection_post(struct management *man, const char *description) } else #endif - msg(D_MANAGEMENT, "MANAGEMENT: %s %s", - description, - print_sockaddr(man->settings.local->ai_addr, &gc)); + if (man->settings.flags & MF_CONNECT_AS_CLIENT) + { + msg(D_MANAGEMENT, "MANAGEMENT: %s %s", + description, + print_sockaddr(man->settings.local->ai_addr, &gc)); + } + else + { + struct sockaddr_storage addr; + socklen_t addrlen = sizeof(addr); + if (!getpeername(man->connection.sd_cli, (struct sockaddr *) &addr, + &addrlen)) + { + msg(D_MANAGEMENT, "MANAGEMENT: %s %s", description, + print_sockaddr((struct sockaddr *) &addr, &gc)); + } + else + { + msg(D_MANAGEMENT, "MANAGEMENT: %s %s", description, "unknown"); + } + } buffer_list_reset(man->connection.out); @@ -1852,7 +1838,7 @@ man_accept(struct management *man) } man_new_connection_post(man, "Client connected from"); - openvpn_close_socket(man->connection.sd_top); + openvpn_close_socket(man->connection.sd_top); man->connection.sd_top = SOCKET_UNDEFINED; man_update_io_state(man); } @@ -1910,8 +1896,22 @@ man_listen(struct management *man) } else #endif - msg(D_MANAGEMENT, "MANAGEMENT: TCP Socket listening on %s", - print_sockaddr(man->settings.local->ai_addr, &gc)); + { + const struct sockaddr *man_addr = man->settings.local->ai_addr; + struct sockaddr_storage addr; + socklen_t addrlen = sizeof(addr); + if (!getsockname(man->connection.sd_top, (struct sockaddr *) &addr, &addrlen)) + { + man_addr = (struct sockaddr *) &addr; + } + else + { + msg(M_WARN|M_ERRNO, + "Failed to get the management socket address"); + } + msg(D_MANAGEMENT, "MANAGEMENT: TCP Socket listening on %s", + print_sockaddr(man_addr, &gc)); + } } #ifdef _WIN32 @@ -1983,7 +1983,6 @@ man_connect(struct management *man) goto done; } - man_record_peer_info(man); man_new_connection_post(man, "Connected to management server at"); done: @@ -2200,7 +2199,7 @@ management_android_control(struct management *man, const char *command, const ch CLEAR(up); strncpy(up.username, msg, sizeof(up.username)-1); - management_query_user_pass(management, &up, command, GET_USER_PASS_NEED_OK,(void *) 0); + management_query_user_pass(management, &up, command, GET_USER_PASS_NEED_OK, (void *) 0); return strcmp("ok", up.password)==0; } @@ -2215,17 +2214,13 @@ managment_android_persisttun_action(struct management *man) { struct user_pass up; CLEAR(up); - strcpy(up.username,"tunmethod"); + strcpy(up.username, "tunmethod"); management_query_user_pass(management, &up, "PERSIST_TUN_ACTION", - GET_USER_PASS_NEED_OK,(void *) 0); + GET_USER_PASS_NEED_OK, (void *) 0); if (!strcmp("NOACTION", up.password)) { return ANDROID_KEEP_OLD_TUN; } - else if (!strcmp("OPEN_AFTER_CLOSE", up.password)) - { - return ANDROID_OPEN_AFTER_CLOSE; - } else if (!strcmp("OPEN_BEFORE_CLOSE", up.password)) { return ANDROID_OPEN_BEFORE_CLOSE; @@ -2236,7 +2231,7 @@ managment_android_persisttun_action(struct management *man) } ASSERT(0); - return ANDROID_OPEN_AFTER_CLOSE; + return ANDROID_OPEN_BEFORE_CLOSE; } @@ -2351,7 +2346,7 @@ man_write(struct management *man) #ifdef TARGET_ANDROID if (man->connection.fdtosend > 0) { - sent = man_send_with_fd(man->connection.sd_cli, BPTR(buf), len, MSG_NOSIGNAL,man->connection.fdtosend); + sent = man_send_with_fd(man->connection.sd_cli, BPTR(buf), len, MSG_NOSIGNAL, man->connection.fdtosend); man->connection.fdtosend = -1; } else @@ -2461,7 +2456,6 @@ man_settings_init(struct man_settings *ms, const int log_history_cache, const int echo_buffer_size, const int state_buffer_size, - const char *write_peer_info_file, const int remap_sigusr1, const unsigned int flags) { @@ -2501,8 +2495,6 @@ man_settings_init(struct man_settings *ms, ASSERT(ms->client_gid >= 0); } - ms->write_peer_info_file = string_alloc(write_peer_info_file, NULL); - #if UNIX_SOCK_SUPPORT if (ms->flags & MF_UNIX_SOCK) { @@ -2566,7 +2558,6 @@ man_settings_close(struct man_settings *ms) { freeaddrinfo(ms->local); } - free(ms->write_peer_info_file); CLEAR(*ms); } @@ -2589,7 +2580,7 @@ man_connection_init(struct management *man) * command output from/to the socket. */ man->connection.in = command_line_new(1024); - man->connection.out = buffer_list_new(0); + man->connection.out = buffer_list_new(); /* * Initialize event set for standalone usage, when we are @@ -2621,10 +2612,7 @@ man_connection_close(struct management *man) { struct man_connection *mc = &man->connection; - if (mc->es) - { - event_free(mc->es); - } + event_free(mc->es); #ifdef _WIN32 net_event_win32_close(&mc->ne32); #endif @@ -2637,14 +2625,12 @@ man_connection_close(struct management *man) { man_close_socket(man, mc->sd_cli); } - if (mc->in) - { - command_line_free(mc->in); - } - if (mc->out) - { - buffer_list_free(mc->out); - } + + command_line_free(mc->in); + buffer_list_free(mc->out); + + event_timeout_clear(&mc->bytecount_update_interval); + in_extra_reset(&man->connection, IER_RESET); buffer_list_free(mc->ext_key_input); man_connection_clear(mc); @@ -2676,7 +2662,6 @@ management_open(struct management *man, const int log_history_cache, const int echo_buffer_size, const int state_buffer_size, - const char *write_peer_info_file, const int remap_sigusr1, const unsigned int flags) { @@ -2695,7 +2680,6 @@ management_open(struct management *man, log_history_cache, echo_buffer_size, state_buffer_size, - write_peer_info_file, remap_sigusr1, flags); @@ -2913,8 +2897,6 @@ management_notify_generic(struct management *man, const char *str) msg(M_CLIENT, "%s", str); } -#ifdef MANAGEMENT_DEF_AUTH - static void man_output_peer_info_env(struct management *man, const struct man_def_auth_context *mdac) { @@ -3030,8 +3012,6 @@ management_learn_addr(struct management *management, gc_free(&gc); } -#endif /* MANAGEMENT_DEF_AUTH */ - void management_echo(struct management *man, const char *string, const bool pull) { @@ -3900,6 +3880,10 @@ command_line_reset(struct command_line *cl) void command_line_free(struct command_line *cl) { + if (!cl) + { + return; + } command_line_reset(cl); free_buf(&cl->buf); free_buf(&cl->residual); @@ -4019,10 +4003,8 @@ log_entry_print(const struct log_entry *e, unsigned int flags, struct gc_arena * static void log_entry_free_contents(struct log_entry *e) { - if (e->string) - { - free((char *)e->string); - } + /* Cast away constness of const char* */ + free((char *)e->string); CLEAR(*e); } @@ -4138,21 +4120,68 @@ management_sleep(const int n) { management_event_loop_n_seconds(management, n); } - else if (n > 0) + else { - sleep(n); +#ifdef _WIN32 + win32_sleep(n); +#else + if (n > 0) + { + sleep(n); + } +#endif + } +} + +void +management_check_bytecount(struct context *c, struct management *man, struct timeval *timeval) +{ + if (event_timeout_trigger(&man->connection.bytecount_update_interval, + timeval, ETT_DEFAULT)) + { + counter_type dco_read_bytes = 0; + counter_type dco_write_bytes = 0; + + if (dco_enabled(&c->options) && (dco_get_peer_stats(c) == 0)) + { + dco_read_bytes = c->c2.dco_read_bytes; + dco_write_bytes = c->c2.dco_write_bytes; + } + + if (!(man->persist.callback.flags & MCF_SERVER)) + { + man_bytecount_output_client(man, dco_read_bytes, dco_write_bytes); + } + } +} + +/* DCO resets stats on reconnect. Since client expects stats + * to be preserved across reconnects, we need to save DCO + * stats before tearing the tunnel down. + */ +void +man_persist_client_stats(struct management *man, struct context *c) +{ + if (dco_enabled(&c->options) && (dco_get_peer_stats(c) == 0)) + { + management_bytes_client(man, c->c2.dco_read_bytes, c->c2.dco_write_bytes); } } #else /* ifdef ENABLE_MANAGEMENT */ +#include "win32.h" void management_sleep(const int n) { +#ifdef _WIN32 + win32_sleep(n); +#else if (n > 0) { sleep(n); } +#endif /* ifdef _WIN32 */ } -#endif /* ENABLE_MANAGEMENT */ +#endif /* ENABLE_MANAGEMENT */ \ No newline at end of file diff --git a/src/openvpn/manage.h b/src/openvpn/manage.h index 86e727f26a2..085ffb4de97 100644 --- a/src/openvpn/manage.h +++ b/src/openvpn/manage.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -24,6 +24,27 @@ #ifndef MANAGE_H #define MANAGE_H +/* management_open flags */ +#define MF_SERVER (1<<0) +#define MF_QUERY_PASSWORDS (1<<1) +#define MF_HOLD (1<<2) +#define MF_SIGNAL (1<<3) +#define MF_FORGET_DISCONNECT (1<<4) +#define MF_CONNECT_AS_CLIENT (1<<5) +#define MF_CLIENT_AUTH (1<<6) +/* #define MF_CLIENT_PF (1<<7) *REMOVED FEATURE* */ +#define MF_UNIX_SOCK (1<<8) +#define MF_EXTERNAL_KEY (1<<9) +#define MF_EXTERNAL_KEY_NOPADDING (1<<10) +#define MF_EXTERNAL_KEY_PKCS1PAD (1<<11) +#define MF_UP_DOWN (1<<12) +#define MF_QUERY_REMOTE (1<<13) +#define MF_QUERY_PROXY (1<<14) +#define MF_EXTERNAL_CERT (1<<15) +#define MF_EXTERNAL_KEY_PSSPAD (1<<16) +#define MF_EXTERNAL_KEY_DIGEST (1<<17) + + #ifdef ENABLE_MANAGEMENT #include "misc.h" @@ -31,7 +52,7 @@ #include "socket.h" #include "mroute.h" -#define MANAGEMENT_VERSION 3 +#define MANAGEMENT_VERSION 4 #define MANAGEMENT_N_PASSWORD_RETRIES 3 #define MANAGEMENT_LOG_HISTORY_INITIAL_SIZE 100 #define MANAGEMENT_ECHO_BUFFER_SIZE 100 @@ -40,7 +61,6 @@ /* * Management-interface-based deferred authentication */ -#ifdef MANAGEMENT_DEF_AUTH struct man_def_auth_context { unsigned long cid; @@ -53,7 +73,6 @@ struct man_def_auth_context { time_t bytecount_last_update; }; -#endif /* * Manage build-up of command line @@ -165,7 +184,6 @@ struct management_callback void (*delete_event) (void *arg, event_t event); int (*n_clients) (void *arg); bool (*send_cc_message) (void *arg, const char *message, const char *parameter); -#ifdef MANAGEMENT_DEF_AUTH bool (*kill_by_cid)(void *arg, const unsigned long cid, const char *kill_msg); bool (*client_auth) (void *arg, const unsigned long cid, @@ -176,19 +194,16 @@ struct management_callback struct buffer_list *cc_config); /* ownership transferred */ bool (*client_pending_auth) (void *arg, const unsigned long cid, - const char *url); + const char *extra, + unsigned int timeout); char *(*get_peer_info) (void *arg, const unsigned long cid); -#endif -#ifdef MANAGEMENT_PF - bool (*client_pf)(void *arg, - const unsigned long cid, - struct buffer_list *pf_config); /* ownership transferred */ -#endif bool (*proxy_cmd)(void *arg, const char **p); bool (*remote_cmd) (void *arg, const char **p); #ifdef TARGET_ANDROID int (*network_change)(void *arg, bool samenetwork); #endif + unsigned int (*remote_entry_count)(void *arg); + bool (*remote_entry_get)(void *arg, unsigned int index, char **remote); }; /* @@ -237,7 +252,6 @@ struct man_settings { int log_history_cache; int echo_buffer_size; int state_buffer_size; - char *write_peer_info_file; int client_uid; int client_gid; @@ -281,16 +295,14 @@ struct man_connection { #define IEC_UNDEF 0 #define IEC_CLIENT_AUTH 1 -#define IEC_CLIENT_PF 2 +/* #define IEC_CLIENT_PF 2 *REMOVED FEATURE* */ #define IEC_RSA_SIGN 3 #define IEC_CERTIFICATE 4 #define IEC_PK_SIGN 5 int in_extra_cmd; struct buffer_list *in_extra; -#ifdef MANAGEMENT_DEF_AUTH unsigned long in_extra_cid; unsigned int in_extra_kid; -#endif #define EKS_UNDEF 0 #define EKS_SOLICIT 1 #define EKS_INPUT 2 @@ -306,7 +318,7 @@ struct man_connection { bool log_realtime; bool echo_realtime; int bytecount_update_seconds; - time_t bytecount_last_update; + struct event_timeout bytecount_update_interval; const char *up_query_type; int up_query_mode; @@ -332,28 +344,6 @@ struct user_pass; struct management *management_init(void); -/* management_open flags */ -#define MF_SERVER (1<<0) -#define MF_QUERY_PASSWORDS (1<<1) -#define MF_HOLD (1<<2) -#define MF_SIGNAL (1<<3) -#define MF_FORGET_DISCONNECT (1<<4) -#define MF_CONNECT_AS_CLIENT (1<<5) -#ifdef MANAGEMENT_DEF_AUTH -#define MF_CLIENT_AUTH (1<<6) -#endif -#ifdef MANAGEMENT_PF -#define MF_CLIENT_PF (1<<7) -#endif -#define MF_UNIX_SOCK (1<<8) -#define MF_EXTERNAL_KEY (1<<9) -#define MF_EXTERNAL_KEY_NOPADDING (1<<10) -#define MF_EXTERNAL_KEY_PKCS1PAD (1<<11) -#define MF_UP_DOWN (1<<12) -#define MF_QUERY_REMOTE (1<<13) -#define MF_QUERY_PROXY (1<<14) -#define MF_EXTERNAL_CERT (1<<15) - bool management_open(struct management *man, const char *addr, const char *port, @@ -363,7 +353,6 @@ bool management_open(struct management *man, const int log_history_cache, const int echo_buffer_size, const int state_buffer_size, - const char *write_peer_info_file, const int remap_sigusr1, const unsigned int flags); @@ -395,8 +384,7 @@ bool management_query_user_pass(struct management *man, bool management_android_control(struct management *man, const char *command, const char *msg); #define ANDROID_KEEP_OLD_TUN 1 -#define ANDROID_OPEN_AFTER_CLOSE 2 -#define ANDROID_OPEN_BEFORE_CLOSE 3 +#define ANDROID_OPEN_BEFORE_CLOSE 2 int managment_android_persisttun_action(struct management *man); #endif @@ -415,7 +403,6 @@ void management_notify(struct management *man, const char *severity, const char void management_notify_generic(struct management *man, const char *str); -#ifdef MANAGEMENT_DEF_AUTH void management_notify_client_needing_auth(struct management *management, const unsigned int auth_id, struct man_def_auth_context *mdac, @@ -439,8 +426,6 @@ void management_notify_client_cr_response(unsigned mda_key_id, const struct env_set *es, const char *response); -#endif /* ifdef MANAGEMENT_DEF_AUTH */ - char *management_query_pk_sig(struct management *man, const char *b64_data, const char *algorithm); @@ -470,21 +455,12 @@ management_query_proxy_enabled(const struct management *man) return BOOL_CAST(man->settings.flags & MF_QUERY_PROXY); } -#ifdef MANAGEMENT_PF -static inline bool -management_enable_pf(const struct management *man) -{ - return man && BOOL_CAST(man->settings.flags & MF_CLIENT_PF); -} -#endif -#ifdef MANAGEMENT_DEF_AUTH static inline bool management_enable_def_auth(const struct management *man) { return man && BOOL_CAST(man->settings.flags & MF_CLIENT_AUTH); } -#endif /* * OpenVPN tells the management layer what state it's in @@ -505,6 +481,8 @@ management_enable_def_auth(const struct management *man) #define OPENVPN_STATE_GET_CONFIG 9 /* Downloading configuration from server */ #define OPENVPN_STATE_RESOLVE 10 /* DNS lookup */ #define OPENVPN_STATE_TCP_CONNECT 11 /* Connecting to TCP server */ +#define OPENVPN_STATE_AUTH_PENDING 12 /* Waiting in auth-pending mode + * technically variant of GET_CONFIG */ #define OPENVPN_STATE_CLIENT_BASE 7 /* Base index of client-only states */ @@ -537,57 +515,27 @@ void management_auth_token(struct management *man, const char *token); * These functions drive the bytecount in/out counters. */ -void man_bytecount_output_client(struct management *man); +void +management_check_bytecount(struct context *c, + struct management *man, + struct timeval *timeval); static inline void -man_bytecount_possible_output_client(struct management *man) -{ - if (man->connection.bytecount_update_seconds > 0 - && now >= man->connection.bytecount_last_update - + man->connection.bytecount_update_seconds) - { - man_bytecount_output_client(man); - } -} - -static inline void -management_bytes_out_client(struct management *man, const int size) -{ - man->persist.bytes_out += size; - man_bytecount_possible_output_client(man); -} - -static inline void -management_bytes_in_client(struct management *man, const int size) -{ - man->persist.bytes_in += size; - man_bytecount_possible_output_client(man); -} - -static inline void -management_bytes_out(struct management *man, const int size) +management_bytes_client(struct management *man, + const int size_in, + const int size_out) { if (!(man->persist.callback.flags & MCF_SERVER)) { - management_bytes_out_client(man, size); + man->persist.bytes_in += size_in; + man->persist.bytes_out += size_out; } } -static inline void -management_bytes_in(struct management *man, const int size) -{ - if (!(man->persist.callback.flags & MCF_SERVER)) - { - management_bytes_in_client(man, size); - } -} - -#ifdef MANAGEMENT_DEF_AUTH - -void man_bytecount_output_server(struct management *man, - const counter_type *bytes_in_total, - const counter_type *bytes_out_total, - struct man_def_auth_context *mdac); +void +man_bytecount_output_server(const counter_type *bytes_in_total, + const counter_type *bytes_out_total, + struct man_def_auth_context *mdac); static inline void management_bytes_server(struct management *man, @@ -597,13 +545,14 @@ management_bytes_server(struct management *man, { if (man->connection.bytecount_update_seconds > 0 && now >= mdac->bytecount_last_update + man->connection.bytecount_update_seconds - && (mdac->flags & (DAF_CONNECTION_ESTABLISHED|DAF_CONNECTION_CLOSED)) == DAF_CONNECTION_ESTABLISHED) + && (mdac->flags & (DAF_CONNECTION_ESTABLISHED | DAF_CONNECTION_CLOSED)) == DAF_CONNECTION_ESTABLISHED) { - man_bytecount_output_server(man, bytes_in_total, bytes_out_total, mdac); + man_bytecount_output_server(bytes_in_total, bytes_out_total, mdac); } } -#endif /* MANAGEMENT_DEF_AUTH */ +void +man_persist_client_stats(struct management *man, struct context *c); #endif /* ifdef ENABLE_MANAGEMENT */ @@ -613,4 +562,4 @@ management_bytes_server(struct management *man, */ void management_sleep(const int n); -#endif /* ifndef MANAGE_H */ +#endif /* ifndef MANAGE_H */ \ No newline at end of file diff --git a/src/openvpn/mbuf.c b/src/openvpn/mbuf.c index 4c62fcf45f7..7a829c19b0c 100644 --- a/src/openvpn/mbuf.c +++ b/src/openvpn/mbuf.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -29,8 +29,6 @@ #include "syshead.h" -#if P2MP - #include "buffer.h" #include "error.h" #include "integer.h" @@ -170,11 +168,4 @@ mbuf_dereference_instance(struct mbuf_set *ms, struct multi_instance *mi) } } } -} - -#else /* if P2MP */ -static void -dummy(void) -{ -} -#endif /* P2MP */ +} \ No newline at end of file diff --git a/src/openvpn/mbuf.h b/src/openvpn/mbuf.h index cd9b339c754..0998575ae89 100644 --- a/src/openvpn/mbuf.h +++ b/src/openvpn/mbuf.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -28,8 +28,6 @@ * Handle both multicast and broadcast functions. */ -#if P2MP - /* define this to enable special test mode */ /*#define MBUF_TEST*/ @@ -111,5 +109,4 @@ mbuf_peek(struct mbuf_set *ms) } } -#endif /* if P2MP */ -#endif /* ifndef MBUF_H */ +#endif /* ifndef MBUF_H */ \ No newline at end of file diff --git a/src/openvpn/memdbg.h b/src/openvpn/memdbg.h index e7dd7892cee..83934ec3dcc 100644 --- a/src/openvpn/memdbg.h +++ b/src/openvpn/memdbg.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -110,4 +110,4 @@ */ /*#define ZERO_BUFFER_ON_ALLOC*/ -#endif /* MEMDBG_H */ +#endif /* MEMDBG_H */ \ No newline at end of file diff --git a/src/openvpn/misc.c b/src/openvpn/misc.c index e4662a7bdb0..b63afb494a0 100644 --- a/src/openvpn/misc.c +++ b/src/openvpn/misc.c @@ -5,9 +5,9 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * Copyright (C) 2014-2015 David Sommerseth - * Copyright (C) 2016-2022 David Sommerseth + * Copyright (C) 2016-2023 David Sommerseth * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -75,26 +75,6 @@ set_std_files_to_null(bool stdin_only) #endif } -/* - * dup inetd/xinetd socket descriptor and save - */ - -int inetd_socket_descriptor = SOCKET_UNDEFINED; /* GLOBAL */ - -void -save_inetd_socket_descriptor(void) -{ - inetd_socket_descriptor = INETD_SOCKET_DESCRIPTOR; -#if defined(HAVE_DUP) && defined(HAVE_DUP2) - /* use handle passed by inetd/xinetd */ - if ((inetd_socket_descriptor = dup(INETD_SOCKET_DESCRIPTOR)) < 0) - { - msg(M_ERR, "INETD_SOCKET_DESCRIPTOR dup(%d) failed", INETD_SOCKET_DESCRIPTOR); - } - set_std_files_to_null(true); -#endif -} - /* * Prepend a random string to hostname to prevent DNS caching. * For example, foo.bar.gov would be modified to .foo.bar.gov. @@ -217,6 +197,11 @@ get_user_pass_cr(struct user_pass *up, buf_parse(&buf, '\n', up->username, USER_PASS_LEN); } buf_parse(&buf, '\n', up->password, USER_PASS_LEN); + + if (strlen(up->password) == 0) + { + password_from_stdin = 1; + } } /* * Read from auth file unless this is a dynamic challenge request. @@ -819,4 +804,4 @@ prepend_dir(const char *dir, const char *path, struct gc_arena *gc) ASSERT(combined_path.len > 0); return combined_path; -} +} \ No newline at end of file diff --git a/src/openvpn/misc.h b/src/openvpn/misc.h index 1e5205671ad..b06d26de92e 100644 --- a/src/openvpn/misc.h +++ b/src/openvpn/misc.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -32,9 +32,6 @@ #include "buffer.h" #include "platform.h" -/* socket descriptor passed by inetd/xinetd server to us */ -#define INETD_SOCKET_DESCRIPTOR 0 - /* forward declarations */ struct plugin_list; @@ -42,10 +39,6 @@ struct plugin_list; /* Set standard file descriptors to /dev/null */ void set_std_files_to_null(bool stdin_only); -/* dup inetd/xinetd socket descriptor and save */ -extern int inetd_socket_descriptor; -void save_inetd_socket_descriptor(void); - /* Make arrays of strings */ const char **make_arg_array(const char *first, const char *parms, struct gc_arena *gc); @@ -220,10 +213,12 @@ struct buffer prepend_dir(const char *dir, const char *path, struct gc_arena *gc); #define _STRINGIFY(S) #S +/* *INDENT-OFF* - uncrustify need to ignore this macro */ #define MAC_FMT _STRINGIFY(%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx) +/* *INDENT-ON* */ #define MAC_PRINT_ARG(_mac) _mac[0], _mac[1], _mac[2], \ - _mac[3], _mac[4], _mac[5] + _mac[3], _mac[4], _mac[5] #define MAC_SCAN_ARG(_mac) &_mac[0], &_mac[1], &_mac[2], \ - &_mac[3], &_mac[4], &_mac[5] + &_mac[3], &_mac[4], &_mac[5] -#endif /* ifndef MISC_H */ +#endif /* ifndef MISC_H */ \ No newline at end of file diff --git a/src/openvpn/mroute.c b/src/openvpn/mroute.c index 851047dd23b..49fc15f8c39 100644 --- a/src/openvpn/mroute.c +++ b/src/openvpn/mroute.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -148,38 +148,6 @@ mroute_is_mcast_ipv6(const struct in6_addr addr) return (addr.s6_addr[0] == 0xff); } -#ifdef ENABLE_PF - -static unsigned int -mroute_extract_addr_arp(struct mroute_addr *src, - struct mroute_addr *dest, - const struct buffer *buf) -{ - unsigned int ret = 0; - if (BLEN(buf) >= (int) sizeof(struct openvpn_arp)) - { - const struct openvpn_arp *arp = (const struct openvpn_arp *) BPTR(buf); - if (arp->mac_addr_type == htons(0x0001) - && arp->proto_addr_type == htons(0x0800) - && arp->mac_addr_size == 0x06 - && arp->proto_addr_size == 0x04) - { - mroute_get_in_addr_t(src, arp->ip_src, MR_ARP); - mroute_get_in_addr_t(dest, arp->ip_dest, MR_ARP); - - /* multicast packet? */ - if (mroute_is_mcast(arp->ip_dest)) - { - ret |= MROUTE_EXTRACT_MCAST; - } - - ret |= MROUTE_EXTRACT_SUCCEEDED; - } - } - return ret; -} - -#endif /* ifdef ENABLE_PF */ unsigned int mroute_extract_addr_ip(struct mroute_addr *src, struct mroute_addr *dest, @@ -262,8 +230,6 @@ mroute_copy_ether_to_addr(struct mroute_addr *maddr, unsigned int mroute_extract_addr_ether(struct mroute_addr *src, struct mroute_addr *dest, - struct mroute_addr *esrc, - struct mroute_addr *edest, uint16_t vid, const struct buffer *buf) { @@ -288,42 +254,6 @@ mroute_extract_addr_ether(struct mroute_addr *src, ret |= MROUTE_EXTRACT_SUCCEEDED; -#ifdef ENABLE_PF - if (esrc || edest) - { - struct buffer b = *buf; - if (!buf_advance(&b, sizeof(struct openvpn_ethhdr))) - { - return 0; - } - - uint16_t proto = eth->proto; - if (proto == htons(OPENVPN_ETH_P_8021Q)) - { - if (!buf_advance(&b, SIZE_ETH_TO_8021Q_HDR)) - { - /* It's an 802.1Q packet, but doesn't have a full header, - * so something went wrong */ - return 0; - } - - const struct openvpn_8021qhdr *tag; - tag = (const struct openvpn_8021qhdr *)BPTR(buf); - proto = tag->proto; - } - - switch (ntohs(proto)) - { - case OPENVPN_ETH_P_IPV4: - ret |= (mroute_extract_addr_ip(esrc, edest, &b) << MROUTE_SEC_SHIFT); - break; - - case OPENVPN_ETH_P_ARP: - ret |= (mroute_extract_addr_arp(esrc, edest, &b) << MROUTE_SEC_SHIFT); - break; - } - } -#endif /* ifdef ENABLE_PF */ } return ret; } @@ -612,4 +542,4 @@ void mroute_helper_free(struct mroute_helper *mh) { free(mh); -} +} \ No newline at end of file diff --git a/src/openvpn/mroute.h b/src/openvpn/mroute.h index 3210ac238c5..1f91ae15f32 100644 --- a/src/openvpn/mroute.h +++ b/src/openvpn/mroute.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -177,8 +177,6 @@ unsigned int mroute_extract_addr_ip(struct mroute_addr *src, unsigned int mroute_extract_addr_ether(struct mroute_addr *src, struct mroute_addr *dest, - struct mroute_addr *esrc, - struct mroute_addr *edest, uint16_t vid, const struct buffer *buf); @@ -189,8 +187,6 @@ unsigned int mroute_extract_addr_ether(struct mroute_addr *src, static inline unsigned int mroute_extract_addr_from_packet(struct mroute_addr *src, struct mroute_addr *dest, - struct mroute_addr *esrc, - struct mroute_addr *edest, uint16_t vid, const struct buffer *buf, int tunnel_type) @@ -203,7 +199,7 @@ mroute_extract_addr_from_packet(struct mroute_addr *src, } else if (tunnel_type == DEV_TYPE_TAP) { - ret = mroute_extract_addr_ether(src, dest, esrc, edest, vid, buf); + ret = mroute_extract_addr_ether(src, dest, vid, buf); } return ret; } @@ -268,4 +264,4 @@ mroute_addr_reset(struct mroute_addr *ma) ma->type = MR_ADDR_NONE; } -#endif /* MROUTE_H */ +#endif /* MROUTE_H */ \ No newline at end of file diff --git a/src/openvpn/mss.c b/src/openvpn/mss.c index 94ae52b97cc..6eb415a8564 100644 --- a/src/openvpn/mss.c +++ b/src/openvpn/mss.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -30,7 +30,10 @@ #include "syshead.h" #include "error.h" #include "mss.h" +#include "crypto.h" +#include "ssl_common.h" #include "memdbg.h" +#include "forward.h" /* * Lower MSS on TCP SYN packets to fix MTU @@ -204,3 +207,188 @@ mss_fixup_dowork(struct buffer *buf, uint16_t maxmss) } } } + +static inline unsigned int +adjust_payload_max_cbc(const struct key_type *kt, unsigned int target) +{ + if (!cipher_kt_mode_cbc(kt->cipher)) + { + /* With stream ciphers (or block cipher in stream modes like CFB, AEAD) + * we can just use the target as is */ + return target; + } + else + { + /* With CBC we need at least one extra byte for padding and then need + * to ensure that the resulting CBC ciphertext length, which is always + * a multiple of the block size, is not larger than the target value */ + unsigned int block_size = cipher_kt_block_size(kt->cipher); + target = round_down_uint(target, block_size); + return target - 1; + } +} + +static unsigned int +get_ip_encap_overhead(const struct options *options, + const struct link_socket_info *lsi) +{ + /* Add the overhead of the encapsulating IP packets */ + sa_family_t af; + int proto; + + if (lsi && lsi->lsa) + { + af = lsi->lsa->actual.dest.addr.sa.sa_family; + proto = lsi->proto; + } + else + { + /* In the early init before the connection is established or we + * are in listen mode we can only make an educated guess + * from the af of the connection entry, in p2mp this will be + * later updated */ + af = options->ce.af; + proto = options->ce.proto; + } + return datagram_overhead(af, proto); +} + +static void +frame_calculate_fragment(struct frame *frame, struct key_type *kt, + const struct options *options, + struct link_socket_info *lsi) +{ +#if defined(ENABLE_FRAGMENT) + unsigned int overhead; + + overhead = frame_calculate_protocol_header_size(kt, options, false); + + if (options->ce.fragment_encap) + { + overhead += get_ip_encap_overhead(options, lsi); + } + + unsigned int target = options->ce.fragment - overhead; + /* The 4 bytes of header that fragment adds itself. The other extra payload + * bytes (Ethernet header/compression) are handled by the fragment code + * just as part of the payload and therefore automatically taken into + * account if the packet needs to fragmented */ + frame->max_fragment_size = adjust_payload_max_cbc(kt, target) - 4; + + if (cipher_kt_mode_cbc(kt->cipher)) + { + /* The packet id gets added to *each* fragment in CBC mode, so we need + * to account for it */ + frame->max_fragment_size -= calc_packet_id_size_dc(options, kt); + } +#endif +} + +static void +frame_calculate_mssfix(struct frame *frame, struct key_type *kt, + const struct options *options, + struct link_socket_info *lsi) +{ + if (options->ce.mssfix_fixed) + { + /* we subtract IPv4 and TCP overhead here, mssfix method will add the + * extra 20 for IPv6 */ + frame->mss_fix = options->ce.mssfix - (20 + 20); + return; + } + + unsigned int overhead, payload_overhead; + + overhead = frame_calculate_protocol_header_size(kt, options, false); + + /* Calculate the number of bytes that the payload differs from the payload + * MTU. This are fragment/compression/ethernet headers */ + payload_overhead = frame_calculate_payload_overhead(frame, options, kt, true); + + /* We are in a "liberal" position with respect to MSS, + * i.e. we assume that MSS can be calculated from MTU + * by subtracting out only the IP and TCP header sizes + * without options. + * + * (RFC 879, section 7). */ + + if (options->ce.mssfix_encap) + { + /* Add the overhead of the encapsulating IP packets */ + overhead += get_ip_encap_overhead(options, lsi); + } + + /* Add 20 bytes for the IPv4 header and 20 byte for the TCP header of the + * payload, the mssfix method will add 20 extra if payload is IPv6 */ + payload_overhead += 20 + 20; + + /* Calculate the maximum MSS value from the max link layer size specified + * by ce.mssfix */ + + /* This is the target value our payload needs to be smaller */ + unsigned int target = options->ce.mssfix - overhead; + frame->mss_fix = adjust_payload_max_cbc(kt, target) - payload_overhead; + + +} + +void +frame_calculate_dynamic(struct frame *frame, struct key_type *kt, + const struct options *options, + struct link_socket_info *lsi) +{ + if (options->ce.fragment > 0) + { + frame_calculate_fragment(frame, kt, options, lsi); + } + + if (options->ce.mssfix > 0) + { + frame_calculate_mssfix(frame, kt, options, lsi); + } +} + +/* + * Adjust frame structure based on a Path MTU value given + * to us by the OS. + */ +void +frame_adjust_path_mtu(struct context *c) +{ + struct link_socket_info *lsi = get_link_socket_info(c); + struct options *o = &c->options; + + int pmtu = c->c2.link_socket->mtu; + sa_family_t af = lsi->lsa->actual.dest.addr.sa.sa_family; + int proto = lsi->proto; + + int encap_overhead = datagram_overhead(af, proto); + + /* check if mssfix and fragment need to be adjusted */ + if (pmtu < o->ce.mssfix + || (o->ce.mssfix_encap && pmtu < o->ce.mssfix + encap_overhead)) + { + const char *mtustr = o->ce.mssfix_encap ? " mtu" : ""; + msg(D_MTU_INFO, "Note adjusting 'mssfix %d%s' to 'mssfix %d mtu' " + "according to path MTU discovery", o->ce.mssfix, + mtustr, pmtu); + o->ce.mssfix = pmtu; + o->ce.mssfix_encap = true; + frame_calculate_dynamic(&c->c2.frame, &c->c1.ks.key_type, o, lsi); + } + +#if defined(ENABLE_FRAGMENT) + if (pmtu < o->ce.fragment + || (o->ce.fragment_encap && pmtu < o->ce.fragment + encap_overhead)) + { + const char *mtustr = o->ce.fragment_encap ? " mtu" : ""; + msg(D_MTU_INFO, "Note adjusting 'fragment %d%s' to 'fragment %d mtu' " + "according to path MTU discovery", o->ce.fragment, + mtustr, pmtu); + o->ce.fragment = pmtu; + o->ce.fragment_encap = true; + frame_calculate_dynamic(&c->c2.frame_fragment, &c->c1.ks.key_type, + o, lsi); + } +#endif +} \ No newline at end of file diff --git a/src/openvpn/mss.h b/src/openvpn/mss.h index fa29bf1a269..fc134db7256 100644 --- a/src/openvpn/mss.h +++ b/src/openvpn/mss.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -26,6 +26,8 @@ #include "proto.h" #include "error.h" +#include "mtu.h" +#include "ssl_common.h" void mss_fixup_ipv4(struct buffer *buf, int maxmss); @@ -33,4 +35,16 @@ void mss_fixup_ipv6(struct buffer *buf, int maxmss); void mss_fixup_dowork(struct buffer *buf, uint16_t maxmss); -#endif +/** Set the --mssfix option. */ +void frame_calculate_dynamic(struct frame *frame, struct key_type *kt, + const struct options *options, + struct link_socket_info *lsi); + +/** + * Checks and adjusts the fragment and mssfix value according to the + * discovered path mtu value + * @param c context to adjust + */ +void frame_adjust_path_mtu(struct context *c); + +#endif /* ifndef MSS_H */ \ No newline at end of file diff --git a/src/openvpn/mstats.c b/src/openvpn/mstats.c index dd252d2cbdd..fd4fb5b9845 100644 --- a/src/openvpn/mstats.c +++ b/src/openvpn/mstats.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -124,4 +124,4 @@ mstats_close(void) } } -#endif /* if defined(ENABLE_MEMSTATS) */ +#endif /* if defined(ENABLE_MEMSTATS) */ \ No newline at end of file diff --git a/src/openvpn/mstats.h b/src/openvpn/mstats.h index a66700d1d88..8d43a972ccb 100644 --- a/src/openvpn/mstats.h +++ b/src/openvpn/mstats.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -48,4 +48,4 @@ void mstats_open(const char *fn); void mstats_close(void); -#endif /* if !defined(OPENVPN_MEMSTATS_H) && defined(ENABLE_MEMSTATS) */ +#endif /* if !defined(OPENVPN_MEMSTATS_H) && defined(ENABLE_MEMSTATS) */ \ No newline at end of file diff --git a/src/openvpn/mtcp.c b/src/openvpn/mtcp.c index bb62ebc2962..1a99b35b462 100644 --- a/src/openvpn/mtcp.c +++ b/src/openvpn/mtcp.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -59,13 +59,9 @@ #define MTCP_SOCKET ((void *)1) #define MTCP_TUN ((void *)2) #define MTCP_SIG ((void *)3) /* Only on Windows */ -#ifdef ENABLE_MANAGEMENT #define MTCP_MANAGEMENT ((void *)4) -#endif - -#ifdef ENABLE_ASYNC_PUSH #define MTCP_FILE_CLOSE_WRITE ((void *)5) -#endif +#define MTCP_DCO ((void *)6) #define MTCP_N ((void *)16) /* upper bound on MTCP_x */ @@ -77,6 +73,7 @@ struct ta_iow_flags unsigned int sock; }; +#ifdef ENABLE_DEBUG static const char * pract(int action) { @@ -119,6 +116,7 @@ pract(int action) return "?"; } } +#endif /* ENABLE_DEBUG */ static struct multi_instance * multi_create_instance_tcp(struct multi_context *m) @@ -134,6 +132,8 @@ multi_create_instance_tcp(struct multi_context *m) const uint32_t hv = hash_value(hash, &mi->real); struct hash_bucket *bucket = hash_bucket(hash, hv); + multi_assign_peer_id(m, mi); + he = hash_lookup_fast(hash, bucket, &mi->real, hv); if (he) @@ -229,10 +229,7 @@ multi_tcp_free(struct multi_tcp *mtcp) if (mtcp) { event_free(mtcp->es); - if (mtcp->esr) - { - free(mtcp->esr); - } + free(mtcp->esr); free(mtcp); } } @@ -244,6 +241,7 @@ multi_tcp_dereference_instance(struct multi_tcp *mtcp, struct multi_instance *mi if (ls && mi->socket_set_called) { event_del(mtcp->es, socket_event_handle(ls)); + mi->socket_set_called = false; } mtcp->n_esr = 0; } @@ -285,6 +283,9 @@ multi_tcp_wait(const struct context *c, } #endif tun_set(c->c1.tuntap, mtcp->es, EVENT_READ, MTCP_TUN, persistent); +#if defined(TARGET_LINUX) || defined(TARGET_FREEBSD) + dco_event_set(&c->c1.tuntap->dco, mtcp->es, MTCP_DCO); +#endif #ifdef ENABLE_MANAGEMENT if (management) @@ -401,6 +402,18 @@ multi_tcp_wait_lite(struct multi_context *m, struct multi_instance *mi, const in tv_clear(&c->c2.timeval); /* ZERO-TIMEOUT */ + if (mi && mi->context.c2.link_socket->dco_installed) + { + /* If we got a socket that has been handed over to the kernel + * we must not call the normal socket function to figure out + * if it is readable or writable */ + /* Assert that we only have the DCO exptected flags */ + ASSERT(action & (TA_SOCKET_READ | TA_SOCKET_WRITE)); + + /* We are always ready! */ + return action; + } + switch (action) { case TA_TUN_READ: @@ -524,7 +537,10 @@ multi_tcp_dispatch(struct multi_context *m, struct multi_instance *mi, const int case TA_INITIAL: ASSERT(mi); - multi_tcp_set_global_rw_flags(m, mi); + if (!mi->context.c2.link_socket->dco_installed) + { + multi_tcp_set_global_rw_flags(m, mi); + } multi_process_post(m, mi, mpp_flags); break; @@ -574,7 +590,10 @@ multi_tcp_post(struct multi_context *m, struct multi_instance *mi, const int act } else { - multi_tcp_set_global_rw_flags(m, mi); + if (!c->c2.link_socket->dco_installed) + { + multi_tcp_set_global_rw_flags(m, mi); + } } break; @@ -631,23 +650,22 @@ multi_tcp_action(struct multi_context *m, struct multi_instance *mi, int action, /* * Dispatch the action */ - { - struct multi_instance *touched = multi_tcp_dispatch(m, mi, action); + struct multi_instance *touched = multi_tcp_dispatch(m, mi, action); - /* - * Signal received or TCP connection - * reset by peer? - */ - if (touched && IS_SIG(&touched->context)) + /* + * Signal received or TCP connection + * reset by peer? + */ + if (touched && IS_SIG(&touched->context)) + { + if (mi == touched) { - if (mi == touched) - { - mi = NULL; - } - multi_close_instance_on_signal(m, touched); + mi = NULL; } + multi_close_instance_on_signal(m, touched); } + /* * If dispatch produced any pending output * for a particular instance, point to @@ -745,6 +763,13 @@ multi_tcp_process_io(struct multi_context *m) multi_tcp_action(m, mi, TA_INITIAL, false); } } +#if defined(ENABLE_DCO) && (defined(TARGET_LINUX) || defined(TARGET_FREEBSD)) + /* incoming data on DCO? */ + else if (e->arg == MTCP_DCO) + { + multi_process_incoming_dco(m); + } +#endif /* signal received? */ else if (e->arg == MTCP_SIG) { @@ -797,7 +822,7 @@ tunnel_server_tcp(struct context *top) } /* initialize global multi_context object */ - multi_init(&multi, top, true, MC_SINGLE_THREADED); + multi_init(&multi, top, true); /* initialize our cloned top object */ multi_top_init(&multi, top); @@ -858,4 +883,4 @@ tunnel_server_tcp(struct context *top) multi_uninit(&multi); multi_top_free(&multi); close_instance(top); -} +} \ No newline at end of file diff --git a/src/openvpn/mtcp.h b/src/openvpn/mtcp.h index 4f3fb266831..005563c0f96 100644 --- a/src/openvpn/mtcp.h +++ b/src/openvpn/mtcp.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -73,4 +73,4 @@ void tunnel_server_tcp(struct context *top); void multi_tcp_delete_event(struct multi_tcp *mtcp, event_t event); -#endif /* ifndef MTCP_H */ +#endif /* ifndef MTCP_H */ \ No newline at end of file diff --git a/src/openvpn/mtu.c b/src/openvpn/mtu.c index 5e2f3a64abd..94369362829 100644 --- a/src/openvpn/mtu.c +++ b/src/openvpn/mtu.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -35,6 +35,7 @@ #include "integer.h" #include "mtu.h" #include "options.h" +#include "crypto.h" #include "memdbg.h" @@ -42,97 +43,166 @@ void alloc_buf_sock_tun(struct buffer *buf, const struct frame *frame, - const bool tuntap_buffer, - const unsigned int align_mask) + const bool tuntap_buffer) { /* allocate buffer for overlapped I/O */ *buf = alloc_buf(BUF_SIZE(frame)); - ASSERT(buf_init(buf, FRAME_HEADROOM_ADJ(frame, align_mask))); - buf->len = tuntap_buffer ? MAX_RW_SIZE_TUN(frame) : MAX_RW_SIZE_LINK(frame); + ASSERT(buf_init(buf, frame->buf.headroom)); + buf->len = frame->buf.payload_size; ASSERT(buf_safe(buf, 0)); } -void -frame_finalize(struct frame *frame, - bool link_mtu_defined, - int link_mtu, - bool tun_mtu_defined, - int tun_mtu) +unsigned int +calc_packet_id_size_dc(const struct options *options, const struct key_type *kt) { - /* Set link_mtu based on command line options */ - if (tun_mtu_defined) + /* Unless no-replay is enabled, we have a packet id, no matter if + * encryption is used or not */ + if (!options->replay) { - ASSERT(!link_mtu_defined); - frame->link_mtu = tun_mtu + TUN_LINK_DELTA(frame); + return 0; } - else + + bool tlsmode = options->tls_server || options->tls_client; + + bool packet_id_long_form = !tlsmode || cipher_kt_mode_ofb_cfb(kt->cipher); + + return packet_id_size(packet_id_long_form); +} + +size_t +frame_calculate_protocol_header_size(const struct key_type *kt, + const struct options *options, + bool occ) +{ + /* Sum of all the overhead that reduces the usable packet size */ + size_t header_size = 0; + + bool tlsmode = options->tls_server || options->tls_client; + + /* A socks proxy adds 10 byte of extra header to each packet + * (we only support Socks with IPv4, this value is different for IPv6) */ + if (options->ce.socks_proxy_server && proto_is_udp(options->ce.proto)) + { + header_size += 10; + } + + /* TCP stream based packets have a 16 bit length field */ + if (proto_is_tcp(options->ce.proto)) { - ASSERT(link_mtu_defined); - frame->link_mtu = link_mtu; + header_size += 2; } - if (TUN_MTU_SIZE(frame) < TUN_MTU_MIN) + /* Add the opcode and peerid */ + if (tlsmode) { - msg(M_WARN, "TUN MTU value (%d) must be at least %d", TUN_MTU_SIZE(frame), TUN_MTU_MIN); - frame_print(frame, M_FATAL, "MTU is too small"); + header_size += options->use_peer_id ? 4 : 1; } - frame->link_mtu_dynamic = frame->link_mtu; + unsigned int pkt_id_size = calc_packet_id_size_dc(options, kt); + + /* For figuring out the crypto overhead, we need the size of the payload + * including all headers that also get encrypted as part of the payload */ + header_size += calculate_crypto_overhead(kt, pkt_id_size, occ); + return header_size; } -/* - * Set the tun MTU dynamically. - */ -void -frame_set_mtu_dynamic(struct frame *frame, int mtu, unsigned int flags) -{ -#ifdef ENABLE_DEBUG - const int orig_mtu = mtu; - const int orig_link_mtu_dynamic = frame->link_mtu_dynamic; -#endif +size_t +frame_calculate_payload_overhead(const struct frame *frame, + const struct options *options, + const struct key_type *kt, + bool extra_tun) +{ + size_t overhead = 0; - ASSERT(mtu >= 0); + /* This is the overhead of tap device that is not included in the MTU itself + * i.e. Ethernet header that we still need to transmit as part of the + * payload */ + if (extra_tun) + { + overhead += frame->extra_tun; + } - if (flags & SET_MTU_TUN) +#if defined(USE_COMP) + /* v1 Compression schemes add 1 byte header. V2 only adds a header when it + * does not increase the packet length. We ignore the unlikely escaping + * for tap here */ + if (options->comp.alg == COMP_ALG_LZ4 || options->comp.alg == COMP_ALG_STUB + || options->comp.alg == COMP_ALG_LZO) + { + overhead += 1; + } +#endif +#if defined(ENABLE_FRAGMENT) + /* Add the size of the fragment header (uint32_t) */ + if (options->ce.fragment) { - mtu += TUN_LINK_DELTA(frame); + overhead += 4; } +#endif - if (!(flags & SET_MTU_UPPER_BOUND) || mtu < frame->link_mtu_dynamic) + if (cipher_kt_mode_cbc(kt->cipher)) { - frame->link_mtu_dynamic = constrain_int( - mtu, - EXPANDED_SIZE_MIN(frame), - EXPANDED_SIZE(frame)); + /* The packet id is part of the plain text payload instead of the + * cleartext protocol header and needs to be included in the payload + * overhead instead of the protocol header */ + overhead += calc_packet_id_size_dc(options, kt); } - dmsg(D_MTU_DEBUG, "MTU DYNAMIC mtu=%d, flags=%u, %d -> %d", - orig_mtu, - flags, - orig_link_mtu_dynamic, - frame->link_mtu_dynamic); + return overhead; } -/* - * Move extra_frame octets into extra_tun. Used by fragmenting code - * to adjust frame relative to its position in the buffer processing - * queue. - */ -void -frame_subtract_extra(struct frame *frame, const struct frame *src) +size_t +frame_calculate_payload_size(const struct frame *frame, + const struct options *options, + const struct key_type *kt) { - frame->extra_frame -= src->extra_frame; - frame->extra_tun += src->extra_frame; + size_t payload_size = options->ce.tun_mtu; + payload_size += frame_calculate_payload_overhead(frame, options, kt, true); + return payload_size; } -void -frame_init_mssfix(struct frame *frame, const struct options *options) +size_t +calc_options_string_link_mtu(const struct options *o, const struct frame *frame) { - if (options->ce.mssfix) + struct key_type occ_kt; + + /* neither --secret nor TLS mode */ + if (!o->tls_client && !o->tls_server && !o->shared_secret_file) { - frame_set_mtu_dynamic(frame, options->ce.mssfix, SET_MTU_UPPER_BOUND); + init_key_type(&occ_kt, "none", "none", false, false); + return frame_calculate_payload_size(frame, o, &occ_kt); } + + /* o->ciphername might be BF-CBC even though the underlying SSL library + * does not support it. For this reason we workaround this corner case + * by pretending to have no encryption enabled and by manually adding + * the required packet overhead to the MTU computation. + */ + const char *ciphername = o->ciphername; + + unsigned int overhead = 0; + + if (strcmp(o->ciphername, "BF-CBC") == 0) + { + /* none has no overhead, so use this to later add only --auth + * overhead */ + + /* overhead of BF-CBC: 64 bit block size, 64 bit IV size */ + overhead += 64/8 + 64/8; + /* set ciphername to none, so its size does get added in the + * fake_kt and the cipher is not tried to be resolved */ + ciphername = "none"; + } + + /* We pass tlsmode always true here since as we do not need to check if + * the ciphers are actually valid for non tls in occ calucation */ + init_key_type(&occ_kt, ciphername, o->authname, true, false); + + unsigned int payload = frame_calculate_payload_size(frame, o, &occ_kt); + overhead += frame_calculate_protocol_header_size(&occ_kt, o, true); + + return payload + overhead; } void @@ -147,16 +217,16 @@ frame_print(const struct frame *frame, buf_printf(&out, "%s ", prefix); } buf_printf(&out, "["); - buf_printf(&out, " L:%d", frame->link_mtu); - buf_printf(&out, " D:%d", frame->link_mtu_dynamic); - buf_printf(&out, " EF:%d", frame->extra_frame); - buf_printf(&out, " EB:%d", frame->extra_buffer); + buf_printf(&out, " mss_fix:%d", frame->mss_fix); +#ifdef ENABLE_FRAGMENT + buf_printf(&out, " max_frag:%d", frame->max_fragment_size); +#endif + buf_printf(&out, " tun_mtu:%d", frame->tun_mtu); + buf_printf(&out, " tun_max_mtu:%d", frame->tun_max_mtu); + buf_printf(&out, " headroom:%d", frame->buf.headroom); + buf_printf(&out, " payload:%d", frame->buf.payload_size); + buf_printf(&out, " tailroom:%d", frame->buf.tailroom); buf_printf(&out, " ET:%d", frame->extra_tun); - buf_printf(&out, " EL:%d", frame->extra_link); - if (frame->align_flags && frame->align_adjust) - { - buf_printf(&out, " AF:%u/%d", frame->align_flags, frame->align_adjust); - } buf_printf(&out, " ]"); msg(level, "%s", out.data); @@ -166,13 +236,13 @@ frame_print(const struct frame *frame, #define MTUDISC_NOT_SUPPORTED_MSG "--mtu-disc is not supported on this OS" void -set_mtu_discover_type(int sd, int mtu_type, sa_family_t proto_af) +set_mtu_discover_type(socket_descriptor_t sd, int mtu_type, sa_family_t proto_af) { if (mtu_type >= 0) { switch (proto_af) { -#if defined(HAVE_SETSOCKOPT) && defined(IP_MTU_DISCOVER) +#if defined(IP_MTU_DISCOVER) case AF_INET: if (setsockopt(sd, IPPROTO_IP, IP_MTU_DISCOVER, (void *) &mtu_type, sizeof(mtu_type))) @@ -183,7 +253,7 @@ set_mtu_discover_type(int sd, int mtu_type, sa_family_t proto_af) break; #endif -#if defined(HAVE_SETSOCKOPT) && defined(IPV6_MTU_DISCOVER) +#if defined(IPV6_MTU_DISCOVER) case AF_INET6: if (setsockopt(sd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, (void *) &mtu_type, sizeof(mtu_type))) @@ -243,7 +313,7 @@ format_extended_socket_error(int fd, int *mtu, struct gc_arena *gc) struct msghdr msg; struct cmsghdr *cmsg; struct sock_extended_err *e; - struct sockaddr_in addr; + struct sockaddr_storage addr; struct buffer out = alloc_buf_gc(256, gc); char *cbuf = (char *) gc_malloc(256, false, gc); @@ -280,7 +350,18 @@ format_extended_socket_error(int fd, int *mtu, struct gc_arena *gc) } else { - buf_printf(&out,"CMSG=%d|", cmsg->cmsg_type); + buf_printf(&out, "CMSG=%d|", cmsg->cmsg_type); + } + } + else if (cmsg->cmsg_level == IPPROTO_IPV6) + { + if (cmsg->cmsg_type == IPV6_RECVERR) + { + e = (struct sock_extended_err *) CMSG_DATA(cmsg); + } + else + { + buf_printf(&out, "CMSG=%d|", cmsg->cmsg_type); } } } @@ -333,14 +414,26 @@ format_extended_socket_error(int fd, int *mtu, struct gc_arena *gc) } void -set_sock_extended_error_passing(int sd) +set_sock_extended_error_passing(int sd, sa_family_t proto_af) { int on = 1; - if (setsockopt(sd, SOL_IP, IP_RECVERR, (void *) &on, sizeof(on))) + /* see "man 7 ip" (on Linux) + * this works on IPv4 and IPv6(-dual-stack) sockets (v4-mapped) + */ + if (setsockopt(sd, SOL_IP, IP_RECVERR, (void *) &on, sizeof(on)) != 0) { msg(M_WARN | M_ERRNO, "Note: enable extended error passing on TCP/UDP socket failed (IP_RECVERR)"); } + /* see "man 7 ipv6" (on Linux) + * this only works on IPv6 sockets + */ + if (proto_af == AF_INET6 + && setsockopt(sd, IPPROTO_IPV6, IPV6_RECVERR, (void *) &on, sizeof(on)) != 0) + { + msg(M_WARN | M_ERRNO, + "Note: enable extended error passing on TCP/UDP socket failed (IPV6_RECVERR)"); + } } -#endif /* if EXTENDED_SOCKET_ERROR_CAPABILITY */ +#endif /* if EXTENDED_SOCKET_ERROR_CAPABILITY */ \ No newline at end of file diff --git a/src/openvpn/mtu.h b/src/openvpn/mtu.h index b24ef512b6f..a648ded81dd 100644 --- a/src/openvpn/mtu.h +++ b/src/openvpn/mtu.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -28,7 +28,7 @@ /* * - * Packet maninipulation routes such as encrypt, decrypt, compress, decompress + * Packet manipulation routes such as encrypt, decrypt, compress, decompress * are passed a frame buffer that looks like this: * * [extra_frame bytes] [mtu bytes] [extra_frame_bytes] [compression overflow bytes] @@ -77,7 +77,12 @@ /* * Default MSSFIX value, used for reducing TCP MTU size */ -#define MSSFIX_DEFAULT 1450 +#define MSSFIX_DEFAULT 1492 + +/* + * Default maximum size of control channel packets + */ +#define TLS_MTU_DEFAULT 1250 /* * Alignment of payload data such as IP packet or @@ -91,147 +96,177 @@ * Packet geometry parameters. */ struct frame { - int link_mtu; /**< Maximum packet size to be sent over - * the external network interface. */ + struct { + /* This struct holds all the information about the buffers that are + * allocated to match this frame */ + int payload_size; /**< the maximum size that a payload that our + * buffers can hold from either tun device + * or network link. + */ - int link_mtu_dynamic; /**< Dynamic MTU value for the external - * network interface. */ - int extra_frame; /**< Maximum number of bytes that all - * processing steps together could add. - * @code - * frame.link_mtu = "socket MTU" - extra_frame; - * @endcode + int headroom; /**< the headroom in the buffer, this is choosen + * to allow all potential header to be added + * before the packet */ + + int tailroom; /**< the tailroom in the buffer. Chosen large + * enough to also accompany any extrea header + * or work space required by + * decryption/encryption or compression. */ + } buf; + + unsigned int mss_fix; /**< The actual MSS value that should be + * written to the payload packets. This + * is the value for IPv4 TCP packets. For + * IPv6 packets another 20 bytes must + * be subtracted */ + + int max_fragment_size; /**< The maximum size of a fragment. + * Fragmentation is done on the unencrypted + * payload after (potential) compression. So + * this value specifies the maximum payload + * size that can be send in a single fragment */ - int extra_buffer; /**< Maximum number of bytes that - * processing steps could expand the - * internal work buffer. + int tun_mtu; /**< the (user) configured tun-mtu. This is used + * in configuring the tun interface or + * in calculations that use the desired size + * of the payload in the buffer. * - * This is used by the \link compression - * Data Channel Compression - * module\endlink to give enough working - * space for worst-case expansion of - * incompressible content. */ + * This variable is also used in control + * frame context to set the desired maximum + * control frame payload (although most of + * code ignores it) + */ + int tun_max_mtu; /**< the maximum tun-mtu size the buffers are + * are sized for. This is the upper bound that + * a server can push as MTU */ int extra_tun; /**< Maximum number of bytes in excess of * the tun/tap MTU that might be read * from or written to the virtual - * tun/tap network interface. */ - - int extra_link; /**< Maximum number of bytes in excess of - * external network interface's MTU that - * might be read from or written to it. */ - - /* - * Alignment control - */ -#define FRAME_HEADROOM_MARKER_DECRYPT (1<<0) -#define FRAME_HEADROOM_MARKER_FRAGMENT (1<<1) -#define FRAME_HEADROOM_MARKER_READ_LINK (1<<2) -#define FRAME_HEADROOM_MARKER_READ_STREAM (1<<3) - unsigned int align_flags; - int align_adjust; + * tun/tap network interface. + * + * Only set with the option --tun-mtu-extra + * which defaults to 0 for tun and 32 + * (\c TAP_MTU_EXTRA_DEFAULT) for tap. + * */ }; /* Forward declarations, to prevent includes */ struct options; -/* Routines which read struct frame should use the macros below */ - -/* - * Overhead added to packet payload due to encapsulation - */ -#define EXTRA_FRAME(f) ((f)->extra_frame) - -/* - * Delta between tun payload size and final TCP/UDP datagram size - * (not including extra_link additions) - */ -#define TUN_LINK_DELTA(f) ((f)->extra_frame + (f)->extra_tun) - -/* - * This is the size to "ifconfig" the tun or tap device. - */ -#define TUN_MTU_SIZE(f) ((f)->link_mtu - TUN_LINK_DELTA(f)) -#define TUN_MTU_SIZE_DYNAMIC(f) ((f)->link_mtu_dynamic - TUN_LINK_DELTA(f)) - -/* - * This is the maximum packet size that we need to be able to - * read from or write to a tun or tap device. For example, - * a tap device ifconfiged to an MTU of 1200 might actually want - * to return a packet size of 1214 on a read(). - */ -#define PAYLOAD_SIZE(f) ((f)->link_mtu - (f)->extra_frame) -#define PAYLOAD_SIZE_DYNAMIC(f) ((f)->link_mtu_dynamic - (f)->extra_frame) - -/* - * Max size of a payload packet after encryption, compression, etc. - * overhead is added. - */ -#define EXPANDED_SIZE(f) ((f)->link_mtu) -#define EXPANDED_SIZE_DYNAMIC(f) ((f)->link_mtu_dynamic) -#define EXPANDED_SIZE_MIN(f) (TUN_MTU_MIN + TUN_LINK_DELTA(f)) - -/* - * These values are used as maximum size constraints - * on read() or write() from TUN/TAP device or TCP/UDP port. - */ -#define MAX_RW_SIZE_TUN(f) (PAYLOAD_SIZE(f)) -#define MAX_RW_SIZE_LINK(f) (EXPANDED_SIZE(f) + (f)->extra_link) - /* * Control buffer headroom allocations to allow for efficient prepending. */ -#define FRAME_HEADROOM_BASE(f) (TUN_LINK_DELTA(f) + (f)->extra_buffer + (f)->extra_link) -#define FRAME_HEADROOM(f) frame_headroom(f, 0) -#define FRAME_HEADROOM_ADJ(f, fm) frame_headroom(f, fm) /* * Max size of a buffer used to build a packet for output to - * the TCP/UDP port. + * the TCP/UDP port or to read a packet from a tap/tun device. + * + * Most of our code only prepends headers but compression needs the extra bytes + * *after* the data as compressed data might end up larger than the original + * data. Also crypto needs an extra block for encryption. Therefore tailroom is + * larger than the headroom. */ -#define BUF_SIZE(f) (TUN_MTU_SIZE(f) + FRAME_HEADROOM_BASE(f) * 2) +#define BUF_SIZE(f) ((f)->buf.headroom + (f)->buf.payload_size + (f)->buf.tailroom) /* * Function prototypes. */ -void frame_finalize(struct frame *frame, - bool link_mtu_defined, - int link_mtu, - bool tun_mtu_defined, - int tun_mtu); - -void frame_subtract_extra(struct frame *frame, const struct frame *src); - void frame_print(const struct frame *frame, int level, const char *prefix); -void set_mtu_discover_type(int sd, int mtu_type, sa_family_t proto_af); +void set_mtu_discover_type(socket_descriptor_t sd, int mtu_type, sa_family_t proto_af); int translate_mtu_discover_type_name(const char *name); -/* - * frame_set_mtu_dynamic and flags +/* forward declaration of key_type */ +struct key_type; + +/** + * Calculates the size of the payload according to tun-mtu and tap overhead. In + * this context payload is identical to the size of the plaintext. + * This also includes compression, fragmentation overhead, and packet id in CBC + * mode if these options are used. + * + * + * * [IP][UDP][OPENVPN PROTOCOL HEADER][ **PAYLOAD incl compression header** ] */ +size_t +frame_calculate_payload_size(const struct frame *frame, + const struct options *options, + const struct key_type *kt); -#define SET_MTU_TUN (1<<0) /* use tun/tap rather than link sizing */ -#define SET_MTU_UPPER_BOUND (1<<1) /* only decrease dynamic MTU */ +/** + * Calculates the size of the payload overhead according to tun-mtu and + * tap overhead. This all the overhead that is considered part of the payload + * itself. The compression and fragmentation header and extra header from tap + * are considered part of this overhead that increases the payload larger than + * tun-mtu. + * + * In CBC mode, the IV is part of the payload instead of part of the OpenVPN + * protocol header and is included in the returned value. + * + * In this context payload is identical to the size of the plaintext and this + * method can be also understand as number of bytes that are added to the + * plaintext before encryption. + * + * * [IP][UDP][OPENVPN PROTOCOL HEADER][ **PAYLOAD incl compression header** ] + */ +size_t +frame_calculate_payload_overhead(const struct frame *frame, + const struct options *options, + const struct key_type *kt, + bool extra_tun); -void frame_set_mtu_dynamic(struct frame *frame, int mtu, unsigned int flags); +/** + * Calculates the size of the OpenVPN protocol header. This includes + * the crypto IV/tag/HMAC but does not include the IP encapsulation + * + * This does NOT include the padding and rounding of CBC size + * as the users (mssfix/fragment) of this function need to adjust for + * this and add it themselves. + * + * [IP][UDP][ **OPENVPN PROTOCOL HEADER**][PAYLOAD incl compression header] + * + * @param kt the key_type to use to calculate the crypto overhead + * @param options the options struct to be used to calculate + * @param occ Use the calculation for the OCC link-mtu + * @return size of the overhead in bytes + */ +size_t +frame_calculate_protocol_header_size(const struct key_type *kt, + const struct options *options, + bool occ); + +/** + * Calculate the link-mtu to advertise to our peer. The actual value is not + * relevant, because we will possibly perform data channel cipher negotiation + * after this, but older clients will log warnings if we do not supply them the + * value they expect. This assumes that the traditional cipher/auth directives + * in the config match the config of the peer. + */ +size_t +calc_options_string_link_mtu(const struct options *options, + const struct frame *frame); + +/** + * Return the size of the packet ID size that is currently in use by cipher and + * options for the data channel. + */ +unsigned int +calc_packet_id_size_dc(const struct options *options, + const struct key_type *kt); /* * allocate a buffer for socket or tun layer */ void alloc_buf_sock_tun(struct buffer *buf, const struct frame *frame, - const bool tuntap_buffer, - const unsigned int align_mask); - -/** Set the --mssfix option. */ -void frame_init_mssfix(struct frame *frame, const struct options *options); + const bool tuntap_buffer); /* * EXTENDED_SOCKET_ERROR_CAPABILITY functions -- print extra error info @@ -241,87 +276,10 @@ void frame_init_mssfix(struct frame *frame, const struct options *options); #if EXTENDED_SOCKET_ERROR_CAPABILITY -void set_sock_extended_error_passing(int sd); +void set_sock_extended_error_passing(int sd, sa_family_t proto_af); const char *format_extended_socket_error(int fd, int *mtu, struct gc_arena *gc); #endif -/* - * Calculate a starting offset into a buffer object, dealing with - * headroom and alignment issues. - */ -static inline int -frame_headroom(const struct frame *f, const unsigned int flag_mask) -{ - const int offset = FRAME_HEADROOM_BASE(f); - const int adjust = (flag_mask & f->align_flags) ? f->align_adjust : 0; - const int delta = ((PAYLOAD_ALIGN << 24) - (offset + adjust)) & (PAYLOAD_ALIGN - 1); - return offset + delta; -} - -/* - * frame member adjustment functions - */ - -static inline void -frame_add_to_link_mtu(struct frame *frame, const int increment) -{ - frame->link_mtu += increment; -} - -static inline void -frame_add_to_extra_frame(struct frame *frame, const unsigned int increment) -{ - frame->extra_frame += increment; -} - -static inline void -frame_remove_from_extra_frame(struct frame *frame, const unsigned int decrement) -{ - frame->extra_frame -= decrement; -} - -static inline void -frame_add_to_extra_tun(struct frame *frame, const int increment) -{ - frame->extra_tun += increment; -} - -static inline void -frame_add_to_extra_link(struct frame *frame, const int increment) -{ - frame->extra_link += increment; -} - -static inline void -frame_add_to_extra_buffer(struct frame *frame, const int increment) -{ - frame->extra_buffer += increment; -} - -static inline void -frame_add_to_align_adjust(struct frame *frame, const int increment) -{ - frame->align_adjust += increment; -} - -static inline void -frame_align_to_extra_frame(struct frame *frame) -{ - frame->align_adjust = frame->extra_frame + frame->extra_link; -} - -static inline void -frame_or_align_flags(struct frame *frame, const unsigned int flag_mask) -{ - frame->align_flags |= flag_mask; -} - -static inline bool -frame_defined(const struct frame *frame) -{ - return frame->link_mtu > 0; -} - -#endif /* ifndef MTU_H */ +#endif /* ifndef MTU_H */ \ No newline at end of file diff --git a/src/openvpn/mudp.c b/src/openvpn/mudp.c index d9c6efb861b..c533dd2fcfc 100644 --- a/src/openvpn/mudp.c +++ b/src/openvpn/mudp.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -34,11 +34,152 @@ #include "forward.h" #include "memdbg.h" +#include "ssl_pkt.h" #ifdef HAVE_SYS_INOTIFY_H #include #endif +static void +send_hmac_reset_packet(struct multi_context *m, + struct tls_pre_decrypt_state *state, + struct tls_auth_standalone *tas, + struct session_id *sid, + bool request_resend_wkc) +{ + reset_packet_id_send(&state->tls_wrap_tmp.opt.packet_id.send); + state->tls_wrap_tmp.opt.packet_id.rec.initialized = true; + uint8_t header = 0 | (P_CONTROL_HARD_RESET_SERVER_V2 << P_OPCODE_SHIFT); + struct buffer buf = tls_reset_standalone(&state->tls_wrap_tmp, tas, sid, + &state->peer_session_id, header, + request_resend_wkc); + + struct context *c = &m->top; + + buf_reset_len(&c->c2.buffers->aux_buf); + buf_copy(&c->c2.buffers->aux_buf, &buf); + m->hmac_reply = c->c2.buffers->aux_buf; + m->hmac_reply_dest = &m->top.c2.from; + msg(D_MULTI_DEBUG, "Reset packet from client, sending HMAC based reset challenge"); +} + + +/* Returns true if this packet should create a new session */ +static bool +do_pre_decrypt_check(struct multi_context *m, + struct tls_pre_decrypt_state *state, + struct mroute_addr addr) +{ + ASSERT(m->top.c2.tls_auth_standalone); + + enum first_packet_verdict verdict; + + struct tls_auth_standalone *tas = m->top.c2.tls_auth_standalone; + + verdict = tls_pre_decrypt_lite(tas, state, &m->top.c2.from, &m->top.c2.buf); + + hmac_ctx_t *hmac = m->top.c2.session_id_hmac; + struct openvpn_sockaddr *from = &m->top.c2.from.dest; + int handwindow = m->top.options.handshake_window; + + if (verdict == VERDICT_VALID_RESET_V3 || verdict == VERDICT_VALID_RESET_V2) + { + /* Check if we are still below our limit for sending out + * responses */ + if (!reflect_filter_rate_limit_check(m->initial_rate_limiter)) + { + return false; + } + } + + if (verdict == VERDICT_VALID_RESET_V3) + { + /* Extract the packet id to check if it has the special format that + * indicates early negotiation support */ + struct packet_id_net pin; + struct buffer tmp = m->top.c2.buf; + ASSERT(buf_advance(&tmp, 1 + SID_SIZE)); + ASSERT(packet_id_read(&pin, &tmp, true)); + + /* The most significant byte is 0x0f if early negotiation is supported */ + bool early_neg_support = ((pin.id & EARLY_NEG_MASK) & EARLY_NEG_START) == EARLY_NEG_START; + + /* All clients that support early negotiation and tls-crypt are assumed + * to also support resending the WKc in the 2nd packet */ + if (early_neg_support) + { + /* Calculate the session ID HMAC for our reply and create reset packet */ + struct session_id sid = calculate_session_id_hmac(state->peer_session_id, + from, hmac, handwindow, 0); + send_hmac_reset_packet(m, state, tas, &sid, true); + + return false; + } + else + { + /* For tls-crypt-v2 we need to keep the state of the first packet + * to store the unwrapped key if the client doesn't support resending + * the wrapped key. Unless the user specifically disallowed + * compatibility with such clients to avoid state exhaustion */ + if (tas->tls_wrap.opt.flags & CO_FORCE_TLSCRYPTV2_COOKIE) + { + struct gc_arena gc = gc_new(); + const char *peer = print_link_socket_actual(&m->top.c2.from, &gc); + msg(D_MULTI_DEBUG, "tls-crypt-v2 force-cookie is enabled, " + "ignoring connection attempt from old client (%s)", peer); + gc_free(&gc); + return false; + } + else + { + return true; + } + } + } + else if (verdict == VERDICT_VALID_RESET_V2) + { + /* Calculate the session ID HMAC for our reply and create reset packet */ + struct session_id sid = calculate_session_id_hmac(state->peer_session_id, + from, hmac, handwindow, 0); + + send_hmac_reset_packet(m, state, tas, &sid, false); + + /* We have a reply do not create a new session */ + return false; + + } + else if (verdict == VERDICT_VALID_CONTROL_V1 || verdict == VERDICT_VALID_ACK_V1 + || verdict == VERDICT_VALID_WKC_V1) + { + /* ACK_V1 contains the peer id (our id) while CONTROL_V1 can but does not + * need to contain the peer id */ + struct gc_arena gc = gc_new(); + + bool ret = check_session_id_hmac(state, from, hmac, handwindow); + + const char *peer = print_link_socket_actual(&m->top.c2.from, &gc); + uint8_t pkt_firstbyte = *BPTR( &m->top.c2.buf); + int op = pkt_firstbyte >> P_OPCODE_SHIFT; + + if (!ret) + { + msg(D_MULTI_MEDIUM, "Packet (%s) with invalid or missing SID from %s", + packet_opcode_name(op), peer); + } + else + { + msg(D_MULTI_DEBUG, "Valid packet (%s) with HMAC challenge from peer (%s), " + "accepting new connection.", packet_opcode_name(op), peer); + } + gc_free(&gc); + + return ret; + } + + /* VERDICT_INVALID */ + return false; +} + /* * Get a client instance based on real address. If * the instance doesn't exist, create it while @@ -93,37 +234,46 @@ multi_get_create_instance_udp(struct multi_context *m, bool *floated) mi = (struct multi_instance *) he->value; } } + + /* we have no existing multi instance for this connection */ if (!mi) { - if (!m->top.c2.tls_auth_standalone - || tls_pre_decrypt_lite(m->top.c2.tls_auth_standalone, &m->top.c2.from, &m->top.c2.buf)) + struct tls_pre_decrypt_state state = {0}; + if (m->deferred_shutdown_signal.signal_received) + { + msg(D_MULTI_ERRORS, + "MULTI: Connection attempt from %s ignored while server is " + "shutting down", mroute_addr_print(&real, &gc)); + } + else if (do_pre_decrypt_check(m, &state, real)) { + /* This is an unknown session but with valid tls-auth/tls-crypt + * (or no auth at all). If this is the initial packet of a + * session, we just send a reply with a HMAC session id and + * do not generate a session slot */ + if (frequency_limit_event_allowed(m->new_connection_limiter)) { + /* a successful three-way handshake only counts against + * connect-freq but not against connect-freq-initial */ + reflect_filter_rate_limit_decrease(m->initial_rate_limiter); + mi = multi_create_instance(m, &real); if (mi) { - int i; - hash_add_fast(hash, bucket, &mi->real, hv, mi); mi->did_real_hash = true; + multi_assign_peer_id(m, mi); - /* max_clients must be less then max peer-id value */ - ASSERT(m->max_clients < MAX_PEER_ID); - - for (i = 0; i < m->max_clients; ++i) + /* If we have a session id already, ensure that the + * state is using the same */ + if (session_id_defined(&state.server_session_id) + && session_id_defined((&state.peer_session_id))) { - if (!m->instances[i]) - { - mi->context.c2.tls_multi->peer_id = i; - m->instances[i] = mi; - break; - } + mi->context.c2.tls_multi->n_sessions++; + struct tls_session *session = &mi->context.c2.tls_multi->session[TM_INITIAL]; + session_skip_to_pre_start(session, &state, &m->top.c2.from); } - - /* should not really end up here, since multi_create_instance returns null - * if amount of clients exceeds max_clients */ - ASSERT(i < m->max_clients); } } else @@ -133,6 +283,7 @@ multi_get_create_instance_udp(struct multi_context *m, bool *floated) mroute_addr_print(&real, &gc)); } } + free_tls_pre_decrypt_state(&state); } #ifdef ENABLE_DEBUG @@ -153,7 +304,7 @@ multi_get_create_instance_udp(struct multi_context *m, bool *floated) } /* - * Send a packet to TCP/UDP socket. + * Send a packet to UDP socket. */ static inline void multi_process_outgoing_link(struct multi_context *m, const unsigned int mpp_flags) @@ -163,6 +314,14 @@ multi_process_outgoing_link(struct multi_context *m, const unsigned int mpp_flag { multi_process_outgoing_link_dowork(m, mi, mpp_flags); } + if (m->hmac_reply_dest && m->hmac_reply.len > 0) + { + msg_set_prefix("Connection Attempt"); + m->top.c2.to_link = m->hmac_reply; + m->top.c2.to_link_addr = m->hmac_reply_dest; + process_outgoing_link(&m->top); + m->hmac_reply_dest = NULL; + } } /* @@ -195,12 +354,10 @@ multi_process_io_udp(struct multi_context *m) { strcat(buf, "TW/"); } -#ifdef ENABLE_ASYNC_PUSH else if (status & FILE_CLOSED) { strcat(buf, "FC/"); } -#endif printf("IO %s\n", buf); #endif /* ifdef MULTI_DEBUG_EVENT_LOOP */ @@ -247,6 +404,19 @@ multi_process_io_udp(struct multi_context *m) multi_process_file_closed(m, mpp_flags); } #endif +#if defined(ENABLE_DCO) && (defined(TARGET_LINUX) || defined(TARGET_FREEBSD)) + else if (status & DCO_READ) + { + if (!IS_SIG(&m->top)) + { + bool ret = true; + while (ret) + { + ret = multi_process_incoming_dco(m); + } + } + } +#endif } /* @@ -272,6 +442,10 @@ p2mp_iow_flags(const struct multi_context *m) { flags |= IOW_MBUF; } + else if (m->hmac_reply_dest) + { + flags |= IOW_TO_LINK; + } else { flags |= IOW_READ; @@ -286,19 +460,8 @@ p2mp_iow_flags(const struct multi_context *m) } -/**************************************************************************/ -/** - * Main event loop for OpenVPN in UDP server mode. - * @ingroup eventloop - * - * This function implements OpenVPN's main event loop for UDP server mode. - * At this time, OpenVPN does not yet support multithreading. This - * function's name is therefore slightly misleading. - * - * @param top - Top-level context structure. - */ -static void -tunnel_server_udp_single_threaded(struct context *top) +void +tunnel_server_udp(struct context *top) { struct multi_context multi; @@ -313,7 +476,7 @@ tunnel_server_udp_single_threaded(struct context *top) } /* initialize global multi_context object */ - multi_init(&multi, top, false, MC_SINGLE_THREADED); + multi_init(&multi, top, false); /* initialize our cloned top object */ multi_top_init(&multi, top); @@ -374,11 +537,4 @@ tunnel_server_udp_single_threaded(struct context *top) multi_uninit(&multi); multi_top_free(&multi); close_instance(top); -} - -void -tunnel_server_udp(struct context *top) -{ - tunnel_server_udp_single_threaded(top); -} - +} \ No newline at end of file diff --git a/src/openvpn/mudp.h b/src/openvpn/mudp.h index ea89b2ce1f0..d42c86f4f17 100644 --- a/src/openvpn/mudp.h +++ b/src/openvpn/mudp.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -32,14 +32,13 @@ struct context; struct multi_context; -/**************************************************************************/ /** - * Main event loop wrapper function for OpenVPN in UDP server mode. + * Main event loop for OpenVPN in UDP server mode. * @ingroup eventloop * - * This function simply calls \c tunnel_server_udp_single_threaded(). + * This function implements OpenVPN's main event loop for UDP server mode. * - * @param top - Top-level context structure. + * @param top - Top-level context structure. */ void tunnel_server_udp(struct context *top); @@ -64,4 +63,4 @@ void tunnel_server_udp(struct context *top); */ struct multi_instance *multi_get_create_instance_udp(struct multi_context *m, bool *floated); -#endif /* ifndef MUDP_H */ +#endif /* ifndef MUDP_H */ \ No newline at end of file diff --git a/src/openvpn/multi.c b/src/openvpn/multi.c index 752cfd89670..820a7114b48 100644 --- a/src/openvpn/multi.c +++ b/src/openvpn/multi.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -39,7 +39,6 @@ #include "push.h" #include "run_command.h" #include "otime.h" -#include "pf.h" #include "gremlin.h" #include "mstats.h" #include "ssl_verify.h" @@ -51,6 +50,9 @@ #include "crypto_backend.h" +#include "ssl_util.h" +#include "dco.h" +#include "reflect_filter.h" /*#define MULTI_DEBUG_EVENT_LOOP*/ @@ -69,14 +71,11 @@ id(struct multi_instance *mi) } #endif -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT static void set_cc_config(struct multi_instance *mi, struct buffer_list *cc_config) { - if (mi->cc_config) - { - buffer_list_free(mi->cc_config); - } + buffer_list_free(mi->cc_config); mi->cc_config = cc_config; } #endif @@ -252,7 +251,7 @@ reap_buckets_per_pass(int n_buckets) return constrain_int(n_buckets / REAP_DIVISOR, REAP_MIN, REAP_MAX); } -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT static uint32_t cid_hash_function(const void *key, uint32_t iv) @@ -292,7 +291,7 @@ int_compare_function(const void *key1, const void *key2) * Main initialization function, init multi_context object. */ void -multi_init(struct multi_context *m, struct context *t, bool tcp_mode, int thread_mode) +multi_init(struct multi_context *m, struct context *t, bool tcp_mode) { int dev = DEV_TYPE_UNDEF; @@ -310,8 +309,6 @@ multi_init(struct multi_context *m, struct context *t, bool tcp_mode, int thread */ CLEAR(*m); - m->thread_mode = thread_mode; - /* * Real address hash table (source port number is * considered to be part of the address). Used @@ -342,7 +339,7 @@ multi_init(struct multi_context *m, struct context *t, bool tcp_mode, int thread mroute_addr_hash_function, mroute_addr_compare_function); -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT m->cid_hash = hash_init(t->options.real_hash_size, 0, cid_hash_function, @@ -372,6 +369,8 @@ multi_init(struct multi_context *m, struct context *t, bool tcp_mode, int thread */ m->new_connection_limiter = frequency_limit_init(t->options.cf_max, t->options.cf_per); + m->initial_rate_limiter = initial_rate_limit_init(t->options.cf_initial_max, + t->options.cf_initial_per); /* * Allocate broadcast/multicast buffer list @@ -477,6 +476,12 @@ multi_instance_string(const struct multi_instance *mi, bool null, struct gc_aren buf_printf(&out, "%s/", cn); } buf_printf(&out, "%s", mroute_addr_print(&mi->real, gc)); + if (mi->context.c2.tls_multi + && check_debug_level(D_DCO_DEBUG) + && dco_enabled(&mi->context.options)) + { + buf_printf(&out, " peer-id=%d", mi->context.c2.tls_multi->peer_id); + } return BSTR(&out); } else if (null) @@ -513,19 +518,6 @@ ungenerate_prefix(struct multi_instance *mi) set_prefix(mi); } -static const char * -mi_prefix(const struct multi_instance *mi) -{ - if (mi && mi->msg_prefix[0]) - { - return mi->msg_prefix; - } - else - { - return "UNDEF_I"; - } -} - /* * Tell the route helper about deleted iroutes so * that it can update its mask of currently used @@ -537,6 +529,9 @@ multi_del_iroutes(struct multi_context *m, { const struct iroute *ir; const struct iroute_ipv6 *ir6; + + dco_delete_iroutes(m, mi); + if (TUNNEL_TYPE(mi->context.c1.tuntap) == DEV_TYPE_TUN) { for (ir = mi->context.options.iroutes; ir != NULL; ir = ir->next) @@ -552,29 +547,31 @@ multi_del_iroutes(struct multi_context *m, } static void -setenv_stats(struct context *c) +setenv_stats(struct multi_context *m, struct context *c) { - setenv_counter(c->c2.es, "bytes_received", c->c2.link_read_bytes); - setenv_counter(c->c2.es, "bytes_sent", c->c2.link_write_bytes); + dco_get_peer_stats_multi(&m->top.c1.tuntap->dco, m); + + setenv_counter(c->c2.es, "bytes_received", c->c2.link_read_bytes + c->c2.dco_read_bytes); + setenv_counter(c->c2.es, "bytes_sent", c->c2.link_write_bytes + c->c2.dco_write_bytes); } static void -multi_client_disconnect_setenv(struct multi_instance *mi) +multi_client_disconnect_setenv(struct multi_context *m, struct multi_instance *mi) { /* setenv client real IP address */ setenv_trusted(mi->context.c2.es, get_link_socket_info(&mi->context)); /* setenv stats */ - setenv_stats(&mi->context); + setenv_stats(m, &mi->context); /* setenv connection duration */ setenv_long_long(mi->context.c2.es, "time_duration", now - mi->created); } static void -multi_client_disconnect_script(struct multi_instance *mi) +multi_client_disconnect_script(struct multi_context *m, struct multi_instance *mi) { - multi_client_disconnect_setenv(mi); + multi_client_disconnect_setenv(m, mi); if (plugin_defined(mi->context.plugins, OPENVPN_PLUGIN_CLIENT_DISCONNECT)) { @@ -592,7 +589,7 @@ multi_client_disconnect_script(struct multi_instance *mi) openvpn_run_script(&argv, mi->context.c2.es, 0, "--client-disconnect"); argv_free(&argv); } -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT if (management) { management_notify_client_close(management, &mi->context.c2.mda_context, mi->context.c2.es); @@ -637,7 +634,7 @@ multi_close_instance(struct multi_context *m, { ASSERT(hash_remove(m->iter, &mi->real)); } -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT if (mi->did_cid_hash) { ASSERT(hash_remove(m->cid_hash, &mi->context.c2.mda_context.cid)); @@ -675,12 +672,13 @@ multi_close_instance(struct multi_context *m, mbuf_dereference_instance(m->mbuf, mi); } -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT set_cc_config(mi, NULL); #endif - if (mi->context.c2.tls_multi->multi_state == CAS_SUCCEEDED) + + if (mi->context.c2.tls_multi->multi_state >= CAS_CONNECT_DONE) { - multi_client_disconnect_script(mi); + multi_client_disconnect_script(m, mi); } close_context(&mi->context, SIGTERM, CC_GC_FREE); @@ -705,53 +703,45 @@ multi_close_instance(struct multi_context *m, void multi_uninit(struct multi_context *m) { - if (m->thread_mode & MC_WORK_THREAD) - { - multi_top_free(m); - m->thread_mode = MC_UNDEF; - } - else if (m->thread_mode) + if (m->hash) { - if (m->hash) - { - struct hash_iterator hi; - struct hash_element *he; + struct hash_iterator hi; + struct hash_element *he; - hash_iterator_init(m->iter, &hi); - while ((he = hash_iterator_next(&hi))) - { - struct multi_instance *mi = (struct multi_instance *) he->value; - mi->did_iter = false; - multi_close_instance(m, mi, true); - } - hash_iterator_free(&hi); + hash_iterator_init(m->iter, &hi); + while ((he = hash_iterator_next(&hi))) + { + struct multi_instance *mi = (struct multi_instance *) he->value; + mi->did_iter = false; + multi_close_instance(m, mi, true); + } + hash_iterator_free(&hi); - multi_reap_all(m); + multi_reap_all(m); - hash_free(m->hash); - hash_free(m->vhash); - hash_free(m->iter); -#ifdef MANAGEMENT_DEF_AUTH - hash_free(m->cid_hash); + hash_free(m->hash); + hash_free(m->vhash); + hash_free(m->iter); +#ifdef ENABLE_MANAGEMENT + hash_free(m->cid_hash); #endif - m->hash = NULL; + m->hash = NULL; - free(m->instances); + free(m->instances); #ifdef ENABLE_ASYNC_PUSH - hash_free(m->inotify_watchers); - m->inotify_watchers = NULL; + hash_free(m->inotify_watchers); + m->inotify_watchers = NULL; #endif - schedule_free(m->schedule); - mbuf_free(m->mbuf); - ifconfig_pool_free(m->ifconfig_pool); - frequency_limit_free(m->new_connection_limiter); - multi_reap_free(m->reaper); - mroute_helper_free(m->route_helper); - multi_tcp_free(m->mtcp); - m->thread_mode = MC_UNDEF; - } + schedule_free(m->schedule); + mbuf_free(m->mbuf); + ifconfig_pool_free(m->ifconfig_pool); + frequency_limit_free(m->new_connection_limiter); + initial_rate_limit_free(m->initial_rate_limiter); + multi_reap_free(m->reaper); + mroute_helper_free(m->route_helper); + multi_tcp_free(m->mtcp); } } @@ -788,7 +778,7 @@ multi_create_instance(struct multi_context *m, const struct mroute_addr *real) goto err; } - mi->context.c2.tls_multi->multi_state = CAS_PENDING; + mi->context.c2.tls_multi->multi_state = CAS_NOT_CONNECTED; if (hash_n_elements(m->hash) >= m->max_clients) { @@ -813,7 +803,7 @@ multi_create_instance(struct multi_context *m, const struct mroute_addr *real) } mi->did_iter = true; -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT do { mi->context.c2.mda_context.cid = m->cid_counter++; @@ -859,7 +849,9 @@ multi_print_status(struct multi_context *m, struct status_output *so, const int status_reset(so); - if (version == 1) /* WAS: m->status_file_version */ + dco_get_peer_stats_multi(&m->top.c1.tuntap->dco, m); + + if (version == 1) { /* * Status file version 1 @@ -878,8 +870,8 @@ multi_print_status(struct multi_context *m, struct status_output *so, const int status_printf(so, "%s,%s," counter_format "," counter_format ",%s", tls_common_name(mi->context.c2.tls_multi, false), mroute_addr_print(&mi->real, &gc), - mi->context.c2.link_read_bytes, - mi->context.c2.link_write_bytes, + mi->context.c2.link_read_bytes + mi->context.c2.dco_read_bytes, + mi->context.c2.link_write_bytes + mi->context.c2.dco_write_bytes, time_string(mi->created, 0, false, &gc)); } gc_free(&gc); @@ -944,7 +936,7 @@ multi_print_status(struct multi_context *m, struct status_output *so, const int if (!mi->halt) { status_printf(so, "CLIENT_LIST%c%s%c%s%c%s%c%s%c" counter_format "%c" counter_format "%c%s%c%u%c%s%c" -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT "%lu" #else "" @@ -954,12 +946,12 @@ multi_print_status(struct multi_context *m, struct status_output *so, const int sep, mroute_addr_print(&mi->real, &gc), sep, print_in_addr_t(mi->reporting_addr, IA_EMPTY_IF_UNDEF, &gc), sep, print_in6_addr(mi->reporting_addr_ipv6, IA_EMPTY_IF_UNDEF, &gc), - sep, mi->context.c2.link_read_bytes, - sep, mi->context.c2.link_write_bytes, + sep, mi->context.c2.link_read_bytes + mi->context.c2.dco_read_bytes, + sep, mi->context.c2.link_write_bytes + mi->context.c2.dco_write_bytes, sep, time_string(mi->created, 0, false, &gc), sep, (unsigned int)mi->created, sep, tls_username(mi->context.c2.tls_multi, false), -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT sep, mi->context.c2.mda_context.cid, #else sep, @@ -1006,6 +998,7 @@ multi_print_status(struct multi_context *m, struct status_output *so, const int sep, sep, mbuf_maximum_queued(m->mbuf)); } + status_printf(so, "GLOBAL_STATS%cdco_enabled%c%d", sep, sep, dco_enabled(&m->top.options)); status_printf(so, "END"); } else @@ -1250,16 +1243,23 @@ multi_learn_in_addr_t(struct multi_context *m, addr.netbits = (uint8_t) netbits; } + struct multi_instance *owner = multi_learn_addr(m, mi, &addr, 0); +#ifdef ENABLE_MANAGEMENT + if (management && owner) { - struct multi_instance *owner = multi_learn_addr(m, mi, &addr, 0); -#ifdef MANAGEMENT_DEF_AUTH - if (management && owner) - { - management_learn_addr(management, &mi->context.c2.mda_context, &addr, primary); - } + management_learn_addr(management, &mi->context.c2.mda_context, &addr, primary); + } #endif - return owner; + if (!primary) + { + /* "primary" is the VPN ifconfig address of the peer and already + * known to DCO, so only install "extra" iroutes (primary = false) + */ + ASSERT(netbits >= 0); /* DCO requires populated netbits */ + dco_install_iroute(m, mi, &addr); } + + return owner; } static struct multi_instance * @@ -1283,16 +1283,23 @@ multi_learn_in6_addr(struct multi_context *m, mroute_addr_mask_host_bits( &addr ); } + struct multi_instance *owner = multi_learn_addr(m, mi, &addr, 0); +#ifdef ENABLE_MANAGEMENT + if (management && owner) { - struct multi_instance *owner = multi_learn_addr(m, mi, &addr, 0); -#ifdef MANAGEMENT_DEF_AUTH - if (management && owner) - { - management_learn_addr(management, &mi->context.c2.mda_context, &addr, primary); - } + management_learn_addr(management, &mi->context.c2.mda_context, &addr, primary); + } #endif - return owner; + if (!primary) + { + /* "primary" is the VPN ifconfig address of the peer and already + * known to DCO, so only install "extra" iroutes (primary = false) + */ + ASSERT(netbits >= 0); /* DCO requires populated netbits */ + dco_install_iroute(m, mi, &addr); } + + return owner; } /* @@ -1716,7 +1723,7 @@ multi_client_connect_mda(struct multi_context *m, /* We never return CC_RET_DEFERRED */ ASSERT(!deferred); enum client_connect_return ret = CC_RET_SKIPPED; -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT if (mi->cc_config) { struct buffer_entry *be; @@ -1742,7 +1749,7 @@ multi_client_connect_mda(struct multi_context *m, ret = CC_RET_SUCCEEDED; } -#endif /* ifdef MANAGEMENT_DEF_AUTH */ +#endif /* ifdef ENABLE_MANAGEMENT */ return ret; } @@ -1771,28 +1778,6 @@ multi_client_connect_setenv(struct multi_context *m, gc_free(&gc); } -/** - * Extracts the IV_PROTO variable and returns its value or 0 - * if it cannot be extracted. - * - */ -static unsigned int -extract_iv_proto(const char *peer_info) -{ - - const char *optstr = peer_info ? strstr(peer_info, "IV_PROTO=") : NULL; - if (optstr) - { - int proto = 0; - int r = sscanf(optstr, "IV_PROTO=%d", &proto); - if (r == 1 && proto > 0) - { - return proto; - } - } - return 0; -} - /** * Calculates the options that depend on the client capabilities * based on local options and available peer info @@ -1811,24 +1796,41 @@ multi_client_set_protocol_options(struct context *c) if (proto & IV_PROTO_DATA_V2) { tls_multi->use_peer_id = true; + o->use_peer_id = true; } + else if (dco_enabled(o)) + { + msg(M_INFO, "Client does not support DATA_V2. Data channel offloaing " + "requires DATA_V2. Dropping client."); + auth_set_client_reason(tls_multi, "Data channel negotiation " + "failed (missing DATA_V2)"); + return false; + } + if (proto & IV_PROTO_REQUEST_PUSH) { c->c2.push_request_received = true; } - /* Select cipher if client supports Negotiable Crypto Parameters */ - if (!o->ncp_enabled) +#ifdef HAVE_EXPORT_KEYING_MATERIAL + if (proto & IV_PROTO_TLS_KEY_EXPORT) { - return true; + o->imported_protocol_flags |= CO_USE_TLS_KEY_MATERIAL_EXPORT; + } +#endif + + if (proto & IV_PROTO_CC_EXIT_NOTIFY) + { + o->imported_protocol_flags |= CO_USE_CC_EXIT_NOTIFY; } + /* Select cipher if client supports Negotiable Crypto Parameters */ + /* if we have already created our key, we cannot *change* our own * cipher -> so log the fact and push the "what we have now" cipher * (so the client is always told what we expect it to use) */ - const struct tls_session *session = &tls_multi->session[TM_ACTIVE]; - if (session->key[KS_PRIMARY].crypto_options.key_ctx_bi.initialized) + if (get_primary_key(tls_multi)->crypto_options.key_ctx_bi.initialized) { msg(M_INFO, "PUSH: client wants to negotiate cipher (NCP), but " "server has already generated data channel keys, " @@ -1892,7 +1894,7 @@ multi_client_set_protocol_options(struct context *c) if (!ret) { auth_set_client_reason(tls_multi, "Data channel cipher negotiation " - "failed (no shared cipher)"); + "failed (no shared cipher)"); } gc_free(&gc); @@ -2317,6 +2319,42 @@ multi_client_connect_call_script(struct multi_context *m, return ret; } +static bool +multi_client_setup_dco_initial(struct multi_context *m, + struct multi_instance *mi, + struct gc_arena *gc) +{ + if (!dco_enabled(&mi->context.options)) + { + /* DCO not enabled, nothing to do, return sucess */ + return true; + } + int ret = dco_multi_add_new_peer(m, mi); + if (ret < 0) + { + msg(D_DCO, "Cannot add peer to DCO for %s: %s (%d)", + multi_instance_string(mi, false, gc), strerror(-ret), ret); + return false; + } + + if (mi->context.options.ping_send_timeout || mi->context.c2.frame.mss_fix) + { + ret = dco_set_peer(&mi->context.c1.tuntap->dco, + mi->context.c2.tls_multi->dco_peer_id, + mi->context.options.ping_send_timeout, + mi->context.options.ping_rec_timeout, + mi->context.c2.frame.mss_fix); + if (ret < 0) + { + msg(D_DCO, "Cannot set DCO peer parameters for %s (id=%u): %s", + multi_instance_string(mi, false, gc), + mi->context.c2.tls_multi->dco_peer_id, strerror(-ret)); + return false; + } + } + return true; +} + /** * Generates the data channel keys */ @@ -2331,11 +2369,12 @@ multi_client_generate_tls_keys(struct context *c) } #endif struct tls_session *session = &c->c2.tls_multi->session[TM_ACTIVE]; - if (!tls_session_update_crypto_params(session, &c->options, - &c->c2.frame, frame_fragment)) + if (!tls_session_update_crypto_params(c->c2.tls_multi, session, &c->options, + &c->c2.frame, frame_fragment, + get_link_socket_info(c))) { msg(D_TLS_ERRORS, "TLS Error: initializing data channel failed"); - register_signal(c, SIGUSR1, "process-push-msg-failed"); + register_signal(c->sig, SIGUSR1, "process-push-msg-failed"); return false; } @@ -2436,15 +2475,20 @@ multi_client_connect_late_setup(struct multi_context *m, mi->reporting_addr_ipv6 = mi->context.c2.push_ifconfig_ipv6_local; /* set context-level authentication flag */ - mi->context.c2.tls_multi->multi_state = CAS_SUCCEEDED; + mi->context.c2.tls_multi->multi_state = CAS_CONNECT_DONE; /* authentication complete, calculate dynamic client specific options */ if (!multi_client_set_protocol_options(&mi->context)) { mi->context.c2.tls_multi->multi_state = CAS_FAILED; } + /* only continue if setting protocol options worked */ + else if (!multi_client_setup_dco_initial(m, mi, &gc)) + { + mi->context.c2.tls_multi->multi_state = CAS_FAILED; + } /* Generate data channel keys only if setting protocol options - * has not failed */ + * and DCO initial setup has not failed */ else if (!multi_client_generate_tls_keys(&mi->context)) { mi->context.c2.tls_multi->multi_state = CAS_FAILED; @@ -2455,7 +2499,6 @@ multi_client_connect_late_setup(struct multi_context *m, { process_incoming_push_request(&mi->context); } - gc_free(&gc); } @@ -2489,6 +2532,42 @@ multi_client_connect_early_setup(struct multi_context *m, multi_client_connect_setenv(m, mi); } +/** + * Do the necessary modification for doing the compress migrate. This is + * implemented as a connect handler as it fits the modify config for a client + * paradigm and also is early enough in the chain to be overwritten by another + * ccd/script to do compression on a special client. + */ +static enum client_connect_return +multi_client_connect_compress_migrate(struct multi_context *m, + struct multi_instance *mi, + bool deferred, + unsigned int *option_types_found) +{ +#ifdef USE_COMP + struct options *o = &mi->context.options; + const char *const peer_info = mi->context.c2.tls_multi->peer_info; + + if (o->comp.flags & COMP_F_MIGRATE && mi->context.c2.tls_multi->remote_usescomp) + { + if (peer_info && strstr(peer_info, "IV_COMP_STUBv2=1")) + { + push_option(o, "compress stub-v2", M_USAGE); + } + else + { + /* Client is old and does not support STUBv2 but since it + * announced comp-lzo via OCC we assume it uses comp-lzo, so + * switch to that and push the uncompressed variant. */ + push_option(o, "comp-lzo no", M_USAGE); + o->comp.alg = COMP_ALG_STUB; + *option_types_found |= OPT_P_COMP; + } + } +#endif + return CC_RET_SUCCEEDED; +} + /** * Try to source a dynamic config file from the * --client-config-dir directory. @@ -2557,6 +2636,7 @@ typedef enum client_connect_return (*multi_client_connect_handler) bool from_deferred, unsigned int *option_types_found); static const multi_client_connect_handler client_connect_handlers[] = { + multi_client_connect_compress_migrate, multi_client_connect_source_ccd, multi_client_connect_call_plugin_v1, multi_client_connect_call_plugin_v2, @@ -2587,12 +2667,6 @@ static const multi_client_connect_handler client_connect_handlers[] = { static void multi_connection_established(struct multi_context *m, struct multi_instance *mi) { - if (tls_authentication_status(mi->context.c2.tls_multi, 0) - != TLS_AUTHENTICATION_SUCCEEDED) - { - return; - } - /* We are only called for the CAS_PENDING_x states, so we * can ignore other states here */ bool from_deferred = (mi->context.c2.tls_multi->multi_state != CAS_PENDING); @@ -2642,9 +2716,9 @@ multi_connection_established(struct multi_context *m, struct multi_instance *mi) case CC_RET_DEFERRED: /* - * we already set client_connect_status to DEFERRED_RESULT or + * we already set multi_status to DEFERRED_RESULT or * DEFERRED_NO_RESULT. We just return - * from the function as having client_connect_status + * from the function as having multi_status */ return; @@ -2674,6 +2748,14 @@ multi_connection_established(struct multi_context *m, struct multi_instance *mi) (*cur_handler_index)++; } + /* Check if we have forbidding options in the current mode */ + if (dco_enabled(&mi->context.options) + && !dco_check_option(D_MULTI_ERRORS, &mi->context.options)) + { + msg(D_MULTI_ERRORS, "MULTI: client has been rejected due to incompatible DCO options"); + cc_succeeded = false; + } + if (cc_succeeded) { multi_client_connect_late_setup(m, mi, *option_types_found); @@ -2684,7 +2766,7 @@ multi_connection_established(struct multi_context *m, struct multi_instance *mi) * did not fail */ if (mi->context.c2.tls_multi->multi_state == CAS_PENDING_DEFERRED_PARTIAL) { - multi_client_disconnect_script(mi); + multi_client_disconnect_script(m, mi); } mi->context.c2.tls_multi->multi_state = CAS_FAILED; @@ -2695,7 +2777,7 @@ multi_connection_established(struct multi_context *m, struct multi_instance *mi) update_mstat_n_clients(m->n_clients); --mi->n_clients_delta; -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT if (management) { management_connection_established(management, @@ -2828,35 +2910,6 @@ multi_bcast(struct multi_context *m, mi = (struct multi_instance *) he->value; if (mi != sender_instance && !mi->halt) { -#ifdef ENABLE_PF - if (sender_instance) - { - if (!pf_c2c_test(&sender_instance->context.c2.pf, - sender_instance->context.c2.tls_multi, - &mi->context.c2.pf, - mi->context.c2.tls_multi, - "bcast_c2c")) - { - msg(D_PF_DROPPED_BCAST, "PF: client[%s] -> client[%s] packet dropped by BCAST packet filter", - mi_prefix(sender_instance), - mi_prefix(mi)); - continue; - } - } - if (sender_addr) - { - if (!pf_addr_test(&mi->context.c2.pf, &mi->context, - sender_addr, "bcast_src_addr")) - { - struct gc_arena gc = gc_new(); - msg(D_PF_DROPPED_BCAST, "PF: addr[%s] -> client[%s] packet dropped by BCAST packet filter", - mroute_addr_print_ex(sender_addr, MAPF_SHOW_ARP, &gc), - mi_prefix(mi)); - gc_free(&gc); - continue; - } - } -#endif /* ifdef ENABLE_PF */ if (vid != 0 && vid != mi->context.options.vlan_pvid) { continue; @@ -2918,7 +2971,7 @@ multi_schedule_context_wakeup(struct multi_context *m, struct multi_instance *mi compute_wakeup_sigma(&mi->context.c2.timeval)); } -#if defined(ENABLE_ASYNC_PUSH) && defined(ENABLE_DEF_AUTH) +#if defined(ENABLE_ASYNC_PUSH) static void add_inotify_file_watch(struct multi_context *m, struct multi_instance *mi, int inotify_fd, const char *file) @@ -2942,7 +2995,7 @@ add_inotify_file_watch(struct multi_context *m, struct multi_instance *mi, msg(M_NONFATAL | M_ERRNO, "MULTI: inotify_add_watch error"); } } -#endif /* if defined(ENABLE_ASYNC_PUSH) && defined(ENABLE_DEF_AUTH) */ +#endif /* if defined(ENABLE_ASYNC_PUSH) */ /* * Figure instance-specific timers, convert @@ -2958,7 +3011,7 @@ multi_process_post(struct multi_context *m, struct multi_instance *mi, const uns if (!IS_SIG(&mi->context) && ((flags & MPP_PRE_SELECT) || ((flags & MPP_CONDITIONAL_PRE_SELECT) && !ANY_OUT(&mi->context)))) { -#if defined(ENABLE_ASYNC_PUSH) && defined(ENABLE_DEF_AUTH) +#if defined(ENABLE_ASYNC_PUSH) bool was_unauthenticated = true; struct key_state *ks = NULL; if (mi->context.c2.tls_multi) @@ -2972,17 +3025,23 @@ multi_process_post(struct multi_context *m, struct multi_instance *mi, const uns * to_link packets (such as ping or TLS control) */ pre_select(&mi->context); -#if defined(ENABLE_ASYNC_PUSH) && defined(ENABLE_DEF_AUTH) +#if defined(ENABLE_ASYNC_PUSH) /* * if we see the state transition from unauthenticated to deferred * and an auth_control_file, we assume it got just added and add * inotify watch to that file */ - if (ks && ks->auth_control_file && was_unauthenticated + if (ks && ks->plugin_auth.auth_control_file && was_unauthenticated + && (ks->authenticated == KS_AUTH_DEFERRED)) + { + add_inotify_file_watch(m, mi, m->top.c2.inotify_fd, + ks->plugin_auth.auth_control_file); + } + if (ks && ks->script_auth.auth_control_file && was_unauthenticated && (ks->authenticated == KS_AUTH_DEFERRED)) { add_inotify_file_watch(m, mi, m->top.c2.inotify_fd, - ks->auth_control_file); + ks->script_auth.auth_control_file); } #endif @@ -2990,12 +3049,12 @@ multi_process_post(struct multi_context *m, struct multi_instance *mi, const uns { /* connection is "established" when SSL/TLS key negotiation succeeds * and (if specified) auth user/pass succeeds */ - if (is_cas_pending(mi->context.c2.tls_multi->multi_state) - && CONNECTION_ESTABLISHED(&mi->context)) + + if (is_cas_pending(mi->context.c2.tls_multi->multi_state)) { multi_connection_established(m, mi); } -#if defined(ENABLE_ASYNC_PUSH) && defined(ENABLE_DEF_AUTH) +#if defined(ENABLE_ASYNC_PUSH) if (is_cas_pending(mi->context.c2.tls_multi->multi_state) && mi->client_connect_defer_state.deferred_ret_file) { @@ -3107,7 +3166,7 @@ multi_process_float(struct multi_context *m, struct multi_instance *mi) ASSERT(hash_add(m->hash, &mi->real, mi, false)); ASSERT(hash_add(m->iter, &mi->real, mi, false)); -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT ASSERT(hash_add(m->cid_hash, &mi->context.c2.mda_context.cid, mi, true)); #endif @@ -3115,6 +3174,170 @@ multi_process_float(struct multi_context *m, struct multi_instance *mi) gc_free(&gc); } +/* + * Called when an instance should be closed due to the + * reception of a soft signal. + */ +void +multi_close_instance_on_signal(struct multi_context *m, struct multi_instance *mi) +{ + remap_signal(&mi->context); + set_prefix(mi); + print_signal(mi->context.sig, "client-instance", D_MULTI_LOW); + clear_prefix(); + multi_close_instance(m, mi, false); +} + +#if (defined(ENABLE_DCO) && (defined(TARGET_LINUX) || defined(TARGET_FREEBSD))) || defined(ENABLE_MANAGEMENT) +static void +multi_signal_instance(struct multi_context *m, struct multi_instance *mi, const int sig) +{ + mi->context.sig->signal_received = sig; + multi_close_instance_on_signal(m, mi); +} +#endif + +#if defined(ENABLE_DCO) && (defined(TARGET_LINUX) || defined(TARGET_FREEBSD)) +static void +process_incoming_dco_packet(struct multi_context *m, struct multi_instance *mi, + dco_context_t *dco) +{ + if (BLEN(&dco->dco_packet_in) < 1) + { + msg(D_DCO, "Received too short packet for peer %d", + dco->dco_message_peer_id); + goto done; + } + + uint8_t *ptr = BPTR(&dco->dco_packet_in); + uint8_t op = ptr[0] >> P_OPCODE_SHIFT; + if ((op == P_DATA_V1) || (op == P_DATA_V2)) + { + msg(D_DCO, "DCO: received data channel packet for peer %d", + dco->dco_message_peer_id); + goto done; + } + + struct buffer orig_buf = mi->context.c2.buf; + mi->context.c2.buf = dco->dco_packet_in; + + multi_process_incoming_link(m, mi, 0); + + mi->context.c2.buf = orig_buf; + +done: + buf_init(&dco->dco_packet_in, 0); +} + +static void +process_incoming_del_peer(struct multi_context *m, struct multi_instance *mi, + dco_context_t *dco) +{ + const char *reason = "ovpn-dco: unknown reason"; + switch (dco->dco_del_peer_reason) + { + case OVPN_DEL_PEER_REASON_EXPIRED: + reason = "ovpn-dco: ping expired"; + break; + + case OVPN_DEL_PEER_REASON_TRANSPORT_ERROR: + reason = "ovpn-dco: transport error"; + break; + +#ifdef TARGET_LINUX + /* FIXME: this is linux-only today and breaks FreeBSD compilation */ + case OVPN_DEL_PEER_REASON_TRANSPORT_DISCONNECT: + reason = "ovpn-dco: transport disconnected"; + break; +#endif + + case OVPN_DEL_PEER_REASON_USERSPACE: + /* We assume that is ourselves. Unfortunately, sometimes these + * events happen with enough delay that they can have an order of + * + * dco_del_peer x + * [new client connecting] + * dco_new_peer x + * event from dco_del_peer arrives. + * + * if we do not ignore this we get desynced with the kernel + * since we assume the peer-id is free again. The other way would + * be to send a dco_del_peer again + */ + return; + } + + /* When kernel already deleted the peer, the socket is no longer + * installed, and we do not need to clean up the state in the kernel */ + mi->context.c2.tls_multi->dco_peer_id = -1; + mi->context.sig->signal_text = reason; + mi->context.c2.dco_read_bytes = dco->dco_read_bytes; + mi->context.c2.dco_write_bytes = dco->dco_write_bytes; + multi_signal_instance(m, mi, SIGTERM); +} + +bool +multi_process_incoming_dco(struct multi_context *m) +{ + dco_context_t *dco = &m->top.c1.tuntap->dco; + + struct multi_instance *mi = NULL; + + int ret = dco_do_read(&m->top.c1.tuntap->dco); + + int peer_id = dco->dco_message_peer_id; + + /* no peer-specific message delivered -> nothing to process. + * bail out right away + */ + if (peer_id < 0) + { + return ret > 0; + } + + if ((peer_id < m->max_clients) && (m->instances[peer_id])) + { + mi = m->instances[peer_id]; + if (dco->dco_message_type == OVPN_CMD_PACKET) + { + process_incoming_dco_packet(m, mi, dco); + } + else if (dco->dco_message_type == OVPN_CMD_DEL_PEER) + { + process_incoming_del_peer(m, mi, dco); + } + } + else + { + int msglevel = D_DCO; + if (dco->dco_message_type == OVPN_CMD_DEL_PEER + && dco->dco_del_peer_reason == OVPN_DEL_PEER_REASON_USERSPACE) + { + /* we receive OVPN_CMD_DEL_PEER message with reason USERSPACE + * after we kill the peer ourselves. This peer may have already + * been deleted, so we end up here. + * In this case, print the following debug message with DCO_DEBUG + * level only to avoid polluting the standard DCO level with this + * harmless event. + */ + msglevel = D_DCO_DEBUG; + } + msg(msglevel, "Received DCO message for unknown peer-id: %d, " + "type %d, del_peer_reason %d", peer_id, dco->dco_message_type, + dco->dco_del_peer_reason); + /* Also clear the buffer if this was incoming packet for a dropped peer */ + buf_init(&dco->dco_packet_in, 0); + } + + dco->dco_message_type = 0; + dco->dco_message_peer_id = -1; + dco->dco_del_peer_reason = -1; + dco->dco_read_bytes = 0; + dco->dco_write_bytes = 0; + return ret > 0; +} +#endif /* if defined(ENABLE_DCO) && defined(TARGET_LINUX) */ + /* * Process packets in the TCP/UDP socket -> TUN/TAP interface direction, * i.e. client -> server direction. @@ -3194,8 +3417,6 @@ multi_process_incoming_link(struct multi_context *m, struct multi_instance *inst /* extract packet source and dest addresses */ mroute_flags = mroute_extract_addr_from_packet(&src, &dest, - NULL, - NULL, 0, &c->c2.to_tun, DEV_TYPE_TUN); @@ -3238,17 +3459,6 @@ multi_process_incoming_link(struct multi_context *m, struct multi_instance *inst /* if dest addr is a known client, route to it */ if (mi) { -#ifdef ENABLE_PF - if (!pf_c2c_test(&c->c2.pf, c->c2.tls_multi, - &mi->context.c2.pf, - mi->context.c2.tls_multi, - "tun_c2c")) - { - msg(D_PF_DROPPED, "PF: client -> client[%s] packet dropped by TUN packet filter", - mi_prefix(mi)); - } - else -#endif { multi_unicast(m, &c->c2.to_tun, mi); register_activity(c, BLEN(&c->c2.to_tun)); @@ -3257,23 +3467,10 @@ multi_process_incoming_link(struct multi_context *m, struct multi_instance *inst } } } -#ifdef ENABLE_PF - if (c->c2.to_tun.len && !pf_addr_test(&c->c2.pf, c, &dest, - "tun_dest_addr")) - { - msg(D_PF_DROPPED, "PF: client -> addr[%s] packet dropped by TUN packet filter", - mroute_addr_print_ex(&dest, MAPF_SHOW_ARP, &gc)); - c->c2.to_tun.len = 0; - } -#endif } else if (TUNNEL_TYPE(m->top.c1.tuntap) == DEV_TYPE_TAP) { uint16_t vid = 0; -#ifdef ENABLE_PF - struct mroute_addr edest; - mroute_addr_reset(&edest); -#endif if (m->top.options.vlan_tagging) { @@ -3291,12 +3488,6 @@ multi_process_incoming_link(struct multi_context *m, struct multi_instance *inst /* extract packet source and dest addresses */ mroute_flags = mroute_extract_addr_from_packet(&src, &dest, - NULL, -#ifdef ENABLE_PF - &edest, -#else - NULL, -#endif vid, &c->c2.to_tun, DEV_TYPE_TAP); @@ -3320,35 +3511,12 @@ multi_process_incoming_link(struct multi_context *m, struct multi_instance *inst /* if dest addr is a known client, route to it */ if (mi) { -#ifdef ENABLE_PF - if (!pf_c2c_test(&c->c2.pf, c->c2.tls_multi, - &mi->context.c2.pf, - mi->context.c2.tls_multi, - "tap_c2c")) - { - msg(D_PF_DROPPED, "PF: client -> client[%s] packet dropped by TAP packet filter", - mi_prefix(mi)); - } - else -#endif - { - multi_unicast(m, &c->c2.to_tun, mi); - register_activity(c, BLEN(&c->c2.to_tun)); - } + multi_unicast(m, &c->c2.to_tun, mi); + register_activity(c, BLEN(&c->c2.to_tun)); c->c2.to_tun.len = 0; } } } -#ifdef ENABLE_PF - if (c->c2.to_tun.len && !pf_addr_test(&c->c2.pf, c, - &edest, - "tap_dest_addr")) - { - msg(D_PF_DROPPED, "PF: client -> addr[%s] packet dropped by TAP packet filter", - mroute_addr_print_ex(&edest, MAPF_SHOW_ARP, &gc)); - c->c2.to_tun.len = 0; - } -#endif } else { @@ -3381,7 +3549,6 @@ multi_process_incoming_link(struct multi_context *m, struct multi_instance *inst bool multi_process_incoming_tun(struct multi_context *m, const unsigned int mpp_flags) { - struct gc_arena gc = gc_new(); bool ret = true; if (BLEN(&m->top.c2.buf) > 0) @@ -3391,19 +3558,6 @@ multi_process_incoming_tun(struct multi_context *m, const unsigned int mpp_flags const int dev_type = TUNNEL_TYPE(m->top.c1.tuntap); int16_t vid = 0; -#ifdef ENABLE_PF - struct mroute_addr esrc, *e1, *e2; - if (dev_type == DEV_TYPE_TUN) - { - e1 = NULL; - e2 = &src; - } - else - { - e1 = e2 = &esrc; - mroute_addr_reset(&esrc); - } -#endif #ifdef MULTI_DEBUG_EVENT_LOOP printf("TUN -> TCP/UDP [%d]\n", BLEN(&m->top.c2.buf)); @@ -3430,12 +3584,6 @@ multi_process_incoming_tun(struct multi_context *m, const unsigned int mpp_flags mroute_flags = mroute_extract_addr_from_packet(&src, &dest, -#ifdef ENABLE_PF - e1, -#else - NULL, -#endif - NULL, vid, &m->top.c2.buf, dev_type); @@ -3448,11 +3596,7 @@ multi_process_incoming_tun(struct multi_context *m, const unsigned int mpp_flags if (mroute_flags & (MROUTE_EXTRACT_BCAST|MROUTE_EXTRACT_MCAST)) { /* for now, treat multicast as broadcast */ -#ifdef ENABLE_PF - multi_bcast(m, &m->top.c2.buf, NULL, e2, vid); -#else multi_bcast(m, &m->top.c2.buf, NULL, NULL, vid); -#endif } else { @@ -3465,15 +3609,6 @@ multi_process_incoming_tun(struct multi_context *m, const unsigned int mpp_flags set_prefix(m->pending); -#ifdef ENABLE_PF - if (!pf_addr_test(&c->c2.pf, c, e2, "tun_tap_src_addr")) - { - msg(D_PF_DROPPED, "PF: addr[%s] -> client packet dropped by packet filter", - mroute_addr_print_ex(&src, MAPF_SHOW_ARP, &gc)); - buf_reset_len(&c->c2.buf); - } - else -#endif { if (multi_output_queue_ready(m, m->pending)) { @@ -3499,7 +3634,6 @@ multi_process_incoming_tun(struct multi_context *m, const unsigned int mpp_flags } } } - gc_free(&gc); return ret; } @@ -3619,8 +3753,8 @@ gremlin_flood_clients(struct multi_context *m) struct packet_flood_parms parm = get_packet_flood_parms(level); int i; - ASSERT(buf_init(&buf, FRAME_HEADROOM(&m->top.c2.frame))); - parm.packet_size = min_int(parm.packet_size, MAX_RW_SIZE_TUN(&m->top.c2.frame)); + ASSERT(buf_init(&buf, m->top.c2.frame.buf.headroom)); + parm.packet_size = min_int(parm.packet_size, m->top.c2.frame.buf.payload_size); msg(D_GREMLIN, "GREMLIN_FLOOD_CLIENTS: flooding clients with %d packets of size %d", parm.n_packets, @@ -3682,7 +3816,7 @@ multi_process_per_second_timers_dowork(struct multi_context *m) } void -multi_top_init(struct multi_context *m, const struct context *top) +multi_top_init(struct multi_context *m, struct context *top) { inherit_context_top(&m->top, top); m->top.c2.buffers = init_context_buffers(&top->c2.frame); @@ -3734,7 +3868,7 @@ multi_push_restart_schedule_exit(struct multi_context *m, bool next_server) &m->deferred_shutdown_signal.wakeup, compute_wakeup_sigma(&m->deferred_shutdown_signal.wakeup)); - m->top.sig->signal_received = 0; + signal_reset(m->top.sig); } /* @@ -3749,7 +3883,7 @@ multi_process_signal(struct multi_context *m) struct status_output *so = status_open(NULL, 0, M_INFO, NULL, 0); multi_print_status(m, so, m->status_file_version); status_close(so); - m->top.sig->signal_received = 0; + signal_reset(m->top.sig); return false; } else if (proto_is_dgram(m->top.options.ce.proto) @@ -3763,31 +3897,9 @@ multi_process_signal(struct multi_context *m) return true; } -/* - * Called when an instance should be closed due to the - * reception of a soft signal. - */ -void -multi_close_instance_on_signal(struct multi_context *m, struct multi_instance *mi) -{ - remap_signal(&mi->context); - set_prefix(mi); - print_signal(mi->context.sig, "client-instance", D_MULTI_LOW); - clear_prefix(); - multi_close_instance(m, mi, false); -} - -static void -multi_signal_instance(struct multi_context *m, struct multi_instance *mi, const int sig) -{ - mi->context.sig->signal_received = sig; - multi_close_instance_on_signal(m, mi); -} - /* * Management subsystem callbacks */ - #ifdef ENABLE_MANAGEMENT static void @@ -3879,10 +3991,6 @@ management_delete_event(void *arg, event_t event) } } -#endif /* ifdef ENABLE_MANAGEMENT */ - -#ifdef MANAGEMENT_DEF_AUTH - static struct multi_instance * lookup_by_cid(struct multi_context *m, const unsigned long cid) { @@ -3917,14 +4025,17 @@ management_kill_by_cid(void *arg, const unsigned long cid, const char *kill_msg) static bool management_client_pending_auth(void *arg, const unsigned long cid, - const char *extra) + const char *extra, + unsigned int timeout) { struct multi_context *m = (struct multi_context *) arg; struct multi_instance *mi = lookup_by_cid(m, cid); if (mi) { /* sends INFO_PRE and AUTH_PENDING messages to client */ - bool ret = send_auth_pending_messages(&mi->context, extra); + bool ret = send_auth_pending_messages(mi->context.c2.tls_multi, extra, + timeout); + reschedule_multi_process(&mi->context); multi_schedule_context_wakeup(m, mi); return ret; } @@ -3953,23 +4064,15 @@ management_client_auth(void *arg, { if (auth) { - if (is_cas_pending(mi->context.c2.tls_multi->multi_state)) + if (mi->context.c2.tls_multi->multi_state <= CAS_WAITING_AUTH) { set_cc_config(mi, cc_config); cc_config_owned = false; } } - else + else if (reason) { - if (reason) - { - msg(D_MULTI_LOW, "MULTI: connection rejected: %s, CLI:%s", reason, np(client_reason)); - } - if (!is_cas_pending(mi->context.c2.tls_multi->multi_state)) - { - send_auth_failed(&mi->context, client_reason); /* mid-session reauth failed */ - multi_schedule_context_wakeup(m, mi); - } + msg(D_MULTI_LOW, "MULTI: connection rejected: %s, CLI:%s", reason, np(client_reason)); } } } @@ -3989,36 +4092,14 @@ management_get_peer_info(void *arg, const unsigned long cid) if (mi) { - ret = tls_get_peer_info(mi->context.c2.tls_multi); + ret = mi->context.c2.tls_multi->peer_info; } return ret; } -#endif /* ifdef MANAGEMENT_DEF_AUTH */ - -#ifdef MANAGEMENT_PF -static bool -management_client_pf(void *arg, - const unsigned long cid, - struct buffer_list *pf_config) /* ownership transferred */ -{ - struct multi_context *m = (struct multi_context *) arg; - struct multi_instance *mi = lookup_by_cid(m, cid); - bool ret = false; +#endif /* ifdef ENABLE_MANAGEMENT */ - if (mi && pf_config) - { - ret = pf_load_from_buffer_list(&mi->context, pf_config); - } - - if (pf_config) - { - buffer_list_free(pf_config); - } - return ret; -} -#endif /* ifdef MANAGEMENT_PF */ void init_management_callback_multi(struct multi_context *m) @@ -4036,20 +4117,37 @@ init_management_callback_multi(struct multi_context *m) cb.kill_by_addr = management_callback_kill_by_addr; cb.delete_event = management_delete_event; cb.n_clients = management_callback_n_clients; -#ifdef MANAGEMENT_DEF_AUTH cb.kill_by_cid = management_kill_by_cid; cb.client_auth = management_client_auth; cb.client_pending_auth = management_client_pending_auth; cb.get_peer_info = management_get_peer_info; -#endif -#ifdef MANAGEMENT_PF - cb.client_pf = management_client_pf; -#endif management_set_callback(management, &cb); } #endif /* ifdef ENABLE_MANAGEMENT */ } +void +multi_assign_peer_id(struct multi_context *m, struct multi_instance *mi) +{ + /* max_clients must be less then max peer-id value */ + ASSERT(m->max_clients < MAX_PEER_ID); + + for (int i = 0; i < m->max_clients; ++i) + { + if (!m->instances[i]) + { + mi->context.c2.tls_multi->peer_id = i; + m->instances[i] = mi; + break; + } + } + + /* should not really end up here, since multi_create_instance returns null + * if amount of clients exceeds max_clients */ + ASSERT(mi->context.c2.tls_multi->peer_id < m->max_clients); +} + + /* * Top level event loop. */ @@ -4066,4 +4164,4 @@ tunnel_server(struct context *top) { tunnel_server_tcp(top); } -} +} \ No newline at end of file diff --git a/src/openvpn/multi.h b/src/openvpn/multi.h index 2da63536d39..35c6910c43c 100644 --- a/src/openvpn/multi.h +++ b/src/openvpn/multi.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -39,6 +39,7 @@ #include "mtcp.h" #include "perf.h" #include "vlan.h" +#include "reflect_filter.h" #define MULTI_PREFIX_MAX_LENGTH 256 @@ -98,7 +99,9 @@ struct client_connect_defer_state * server-mode. */ struct multi_instance { - struct schedule_entry se; /* this must be the first element of the structure */ + struct schedule_entry se; /* this must be the first element of the structure, + * We cast between this and schedule_entry so the + * beginning of the struct must be identical */ struct gc_arena gc; bool halt; int refcount; @@ -123,7 +126,7 @@ struct multi_instance { bool did_real_hash; bool did_iter; -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT bool did_cid_hash; struct buffer_list *cc_config; #endif @@ -150,14 +153,6 @@ struct multi_instance { * server-mode. */ struct multi_context { -#define MC_UNDEF 0 -#define MC_SINGLE_THREADED (1<<0) -#define MC_MULTI_THREADED_MASTER (1<<1) -#define MC_MULTI_THREADED_WORKER (1<<2) -#define MC_MULTI_THREADED_SCHEDULER (1<<3) -#define MC_WORK_THREAD (MC_MULTI_THREADED_WORKER|MC_MULTI_THREADED_SCHEDULER) - int thread_mode; - struct multi_instance **instances; /**< Array of multi_instances. An instance can be * accessed using peer-id as an index. */ @@ -176,6 +171,7 @@ struct multi_context { * as external transport. */ struct ifconfig_pool *ifconfig_pool; struct frequency_limit *new_connection_limiter; + struct initial_packet_rate_limit *initial_rate_limiter; struct mroute_helper *route_helper; struct multi_reap *reaper; struct mroute_addr local; @@ -185,7 +181,7 @@ struct multi_context { int status_file_version; int n_clients; /* current number of authenticated clients */ -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT struct hash *cid_hash; unsigned long cid_counter; #endif @@ -199,6 +195,9 @@ struct multi_context { struct context top; /**< Storage structure for process-wide * configuration. */ + struct buffer hmac_reply; + struct link_socket_actual *hmac_reply_dest; + /* * Timer object for stale route check */ @@ -261,11 +260,11 @@ const char *multi_instance_string(const struct multi_instance *mi, bool null, st * Called by mtcp.c, mudp.c, or other (to be written) protocol drivers */ -void multi_init(struct multi_context *m, struct context *t, bool tcp_mode, int thread_mode); +void multi_init(struct multi_context *m, struct context *t, bool tcp_mode); void multi_uninit(struct multi_context *m); -void multi_top_init(struct multi_context *m, const struct context *top); +void multi_top_init(struct multi_context *m, struct context *top); void multi_top_free(struct multi_context *m); @@ -315,6 +314,16 @@ void multi_process_float(struct multi_context *m, struct multi_instance *mi); */ bool multi_process_post(struct multi_context *m, struct multi_instance *mi, const unsigned int flags); +/** + * Process an incoming DCO message (from kernel space). + * + * @param m - The single \c multi_context structur.e + * + * @return + * - True, if the message was received correctly. + * - False, if there was an error while reading the message. + */ +bool multi_process_incoming_dco(struct multi_context *m); /**************************************************************************/ /** @@ -684,5 +693,15 @@ multi_set_pending(struct multi_context *m, struct multi_instance *mi) { m->pending = mi; } +/** + * Assigns a peer-id to a a client and adds the instance to the + * the instances array of the \c multi_context structure. + * + * @param m - The single \c multi_context structure. + * @param mi - The \c multi_instance of the VPN tunnel to be + * postprocessed. + */ +void multi_assign_peer_id(struct multi_context *m, struct multi_instance *mi); + -#endif /* MULTI_H */ +#endif /* MULTI_H */ \ No newline at end of file diff --git a/src/openvpn/networking.h b/src/openvpn/networking.h index 4e7610ec54e..7ea0426b75d 100644 --- a/src/openvpn/networking.h +++ b/src/openvpn/networking.h @@ -1,7 +1,7 @@ /* * Generic interface to platform specific networking code * - * Copyright (C) 2016-2022 Antonio Quartulli + * Copyright (C) 2016-2023 Antonio Quartulli * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -23,20 +23,33 @@ #include "syshead.h" +#define IFACE_TYPE_LEN_MAX 64 + struct context; #ifdef ENABLE_SITNL #include "networking_sitnl.h" #elif ENABLE_IPROUTE #include "networking_iproute2.h" -#else +#elif defined(TARGET_FREEBSD) +typedef void *openvpn_net_ctx_t; +typedef char openvpn_net_iface_t; +#else /* ifdef ENABLE_SITNL */ /* define mock types to ensure code builds on any platform */ typedef void *openvpn_net_ctx_t; typedef void *openvpn_net_iface_t; +#endif /* ifdef ENABLE_SITNL */ +/* Only the iproute2 backend implements these functions, + * the rest can rely on these stubs + */ +#if !defined(ENABLE_IPROUTE) static inline int net_ctx_init(struct context *c, openvpn_net_ctx_t *ctx) { + (void)c; + (void)ctx; + return 0; } @@ -51,7 +64,7 @@ net_ctx_free(openvpn_net_ctx_t *ctx) { (void)ctx; } -#endif /* ifdef ENABLE_SITNL */ +#endif /* !defined(ENABLE_IPROUTE) */ #if defined(ENABLE_SITNL) || defined(ENABLE_IPROUTE) @@ -79,6 +92,40 @@ void net_ctx_reset(openvpn_net_ctx_t *ctx); */ void net_ctx_free(openvpn_net_ctx_t *ctx); +/** + * Add a new interface + * + * @param ctx the implementation specific context + * @param iface interface to create + * @param type string describing interface type + * @param arg extra data required by the specific type + * + * @return 0 on success, negative error code on error + */ +int net_iface_new(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface, + const char *type, void *arg); + +/** + * Retrieve the interface type + * + * @param ctx the implementation specific context + * @param iface interface to query + * @param type buffer where the type will be stored + * + * @return 0 on success, a negative error code otherwise + */ +int net_iface_type(openvpn_net_ctx_t *ctx, const char *iface, + char type[IFACE_TYPE_LEN_MAX]); + +/** + * Remove an interface + * + * @param ctx the implementation specific context + * @param iface interface to delete + * @return int 0 on success, negative error code on error + */ +int net_iface_del(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface); + /** * Bring interface up or down. * @@ -194,7 +241,9 @@ int net_addr_ptp_v4_del(openvpn_net_ctx_t *ctx, const openvpn_net_iface_t *iface, const in_addr_t *local, const in_addr_t *remote); +#endif /* ENABLE_SITNL || ENABLE_IPROUTE */ +#if defined(ENABLE_SITNL) || defined(ENABLE_IPROUTE) || defined(TARGET_FREEBSD) /** * Add a route for an IPv4 address/network * @@ -271,6 +320,10 @@ int net_route_v6_del(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, const openvpn_net_iface_t *iface, uint32_t table, int metric); +#endif /* ENABLE_SITNL || ENABLE_IPROUTE || TARGET_FREEBSD */ + +#if defined(ENABLE_SITNL) || defined(ENABLE_IPROUTE) + /** * Retrieve the gateway and outgoing interface for the specified IPv4 * address/network @@ -302,4 +355,4 @@ int net_route_v6_best_gw(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, #endif /* ENABLE_SITNL || ENABLE_IPROUTE */ -#endif /* NETWORKING_H_ */ +#endif /* NETWORKING_H_ */ \ No newline at end of file diff --git a/src/openvpn/networking_freebsd.c b/src/openvpn/networking_freebsd.c new file mode 100644 index 00000000000..0633dce755f --- /dev/null +++ b/src/openvpn/networking_freebsd.c @@ -0,0 +1,99 @@ +#ifdef HAVE_CONFIG_H +#include "config.h" +#elif defined(_MSC_VER) +#include "config-msvc.h" +#endif +#include "syshead.h" +#include "errlevel.h" +#include "run_command.h" +#include "networking.h" + +#if defined(TARGET_FREEBSD) + +static int +net_route_v4(const char *op, const in_addr_t *dst, int prefixlen, + const in_addr_t *gw, const char *iface, uint32_t table, + int metric) +{ + char buf1[INET_ADDRSTRLEN], buf2[INET_ADDRSTRLEN]; + in_addr_t _dst, _gw; + struct argv argv = argv_new(); + bool status; + + _dst = ntohl(*dst); + _gw = ntohl(*gw); + + argv_printf(&argv, "%s %s -net %s/%d %s -fib %d", + ROUTE_PATH, op, + inet_ntop(AF_INET, &_dst, buf1, sizeof(buf1)), + prefixlen, + inet_ntop(AF_INET, &_gw, buf2, sizeof(buf2)), + table); + + argv_msg(M_INFO, &argv); + status = openvpn_execve_check(&argv, NULL, 0, + "ERROR: FreeBSD route command failed"); + + argv_free(&argv); + + return (!status); +} + +static int +net_route_v6(const char *op, const struct in6_addr *dst, + int prefixlen, const struct in6_addr *gw, const char *iface, + uint32_t table, int metric) +{ + char buf1[INET6_ADDRSTRLEN], buf2[INET6_ADDRSTRLEN]; + struct argv argv = argv_new(); + bool status; + + argv_printf(&argv, "%s -6 %s -net %s/%d %s -fib %d", + ROUTE_PATH, op, + inet_ntop(AF_INET6, dst, buf1, sizeof(buf1)), + prefixlen, + inet_ntop(AF_INET6, gw, buf2, sizeof(buf2)), + table); + + argv_msg(M_INFO, &argv); + status = openvpn_execve_check(&argv, NULL, 0, + "ERROR: FreeBSD route command failed"); + + argv_free(&argv); + + return (!status); +} + +int +net_route_v4_add(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixlen, + const in_addr_t *gw, const char *iface, uint32_t table, + int metric) +{ + return net_route_v4("add", dst, prefixlen, gw, iface, table, metric); +} + +int +net_route_v6_add(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, + int prefixlen, const struct in6_addr *gw, const char *iface, + uint32_t table, int metric) +{ + return net_route_v6("add", dst, prefixlen, gw, iface, table, metric); +} + +int +net_route_v4_del(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixlen, + const in_addr_t *gw, const char *iface, uint32_t table, + int metric) +{ + return net_route_v4("del", dst, prefixlen, gw, iface, table, metric); +} + +int +net_route_v6_del(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, + int prefixlen, const struct in6_addr *gw, const char *iface, + uint32_t table, int metric) +{ + return net_route_v6("del", dst, prefixlen, gw, iface, table, metric); +} + +#endif /* if defined(TARGET_FREEBSD) */ diff --git a/src/openvpn/networking_iproute2.c b/src/openvpn/networking_iproute2.c index db0f5503b29..e2e205f7af5 100644 --- a/src/openvpn/networking_iproute2.c +++ b/src/openvpn/networking_iproute2.c @@ -1,7 +1,7 @@ /* * Networking API implementation for iproute2 * - * Copyright (C) 2018-2022 Antonio Quartulli + * Copyright (C) 2018-2023 Antonio Quartulli * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -63,6 +63,43 @@ net_ctx_free(openvpn_net_ctx_t *ctx) gc_free(&ctx->gc); } +int +net_iface_new(openvpn_net_ctx_t *ctx, const char *iface, const char *type, + void *arg) +{ + struct argv argv = argv_new(); + + argv_printf(&argv, "%s link add %s type %s", iproute_path, iface, type); + argv_msg(M_INFO, &argv); + openvpn_execve_check(&argv, ctx->es, S_FATAL, "Linux ip link add failed"); + + argv_free(&argv); + + return 0; +} + +int +net_iface_type(openvpn_net_ctx_t *ctx, const char *iface, + char type[IFACE_TYPE_LEN_MAX]) +{ + /* not supported by iproute2 */ + msg(M_WARN, "%s: operation not supported by iproute2 backend", __func__); + return -1; +} + +int +net_iface_del(openvpn_net_ctx_t *ctx, const char *iface) +{ + struct argv argv = argv_new(); + + argv_printf(&argv, "%s link del %s", iproute_path, iface); + openvpn_execve_check(&argv, ctx->es, 0, "Linux ip link del failed"); + + argv_free(&argv); + + return 0; +} + int net_iface_up(openvpn_net_ctx_t *ctx, const char *iface, bool up) { @@ -230,6 +267,7 @@ net_route_v4_add(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixlen, { struct argv argv = argv_new(); const char *dst_str = print_in_addr_t(*dst, 0, &ctx->gc); + int ret = 0; argv_printf(&argv, "%s route add %s/%d", iproute_path, dst_str, prefixlen); @@ -251,11 +289,14 @@ net_route_v4_add(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixlen, } argv_msg(D_ROUTE, &argv); - openvpn_execve_check(&argv, ctx->es, 0, "ERROR: Linux route add command failed"); + if (!openvpn_execve_check(&argv, ctx->es, 0, "ERROR: Linux route add command failed")) + { + ret = -1; + } argv_free(&argv); - return 0; + return ret; } int @@ -265,6 +306,7 @@ net_route_v6_add(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, { struct argv argv = argv_new(); char *dst_str = (char *)print_in6_addr(*dst, 0, &ctx->gc); + int ret = 0; argv_printf(&argv, "%s -6 route add %s/%d dev %s", iproute_path, dst_str, prefixlen, iface); @@ -282,11 +324,14 @@ net_route_v6_add(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, } argv_msg(D_ROUTE, &argv); - openvpn_execve_check(&argv, ctx->es, 0, "ERROR: Linux route -6 add command failed"); + if (!openvpn_execve_check(&argv, ctx->es, 0, "ERROR: Linux route -6 add command failed")) + { + ret = -1; + } argv_free(&argv); - return 0; + return ret; } int @@ -296,6 +341,7 @@ net_route_v4_del(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixlen, { struct argv argv = argv_new(); const char *dst_str = print_in_addr_t(*dst, 0, &ctx->gc); + int ret = 0; argv_printf(&argv, "%s route del %s/%d", iproute_path, dst_str, prefixlen); @@ -305,11 +351,14 @@ net_route_v4_del(openvpn_net_ctx_t *ctx, const in_addr_t *dst, int prefixlen, } argv_msg(D_ROUTE, &argv); - openvpn_execve_check(&argv, ctx->es, 0, "ERROR: Linux route delete command failed"); + if (!openvpn_execve_check(&argv, ctx->es, 0, "ERROR: Linux route delete command failed")) + { + ret = -1; + } argv_free(&argv); - return 0; + return ret; } int @@ -319,6 +368,7 @@ net_route_v6_del(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, { struct argv argv = argv_new(); char *dst_str = (char *)print_in6_addr(*dst, 0, &ctx->gc); + int ret = 0; argv_printf(&argv, "%s -6 route del %s/%d dev %s", iproute_path, dst_str, prefixlen, iface); @@ -336,11 +386,14 @@ net_route_v6_del(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, } argv_msg(D_ROUTE, &argv); - openvpn_execve_check(&argv, ctx->es, 0, "ERROR: Linux route -6 del command failed"); + if (!openvpn_execve_check(&argv, ctx->es, 0, "ERROR: Linux route -6 del command failed")) + { + ret = -1; + } argv_free(&argv); - return 0; + return ret; } int @@ -404,4 +457,4 @@ net_route_v4_best_gw(openvpn_net_ctx_t *ctx, const in_addr_t *dst, * struct in6_addr *best_gw, char *best_iface) */ -#endif /* ENABLE_IPROUTE && TARGET_LINUX */ +#endif /* ENABLE_IPROUTE && TARGET_LINUX */ \ No newline at end of file diff --git a/src/openvpn/networking_iproute2.h b/src/openvpn/networking_iproute2.h index 5f0c2ce3f18..9165c403403 100644 --- a/src/openvpn/networking_iproute2.h +++ b/src/openvpn/networking_iproute2.h @@ -1,7 +1,8 @@ + /* * Generic interface to platform specific networking code * - * Copyright (C) 2016-2022 Antonio Quartulli + * Copyright (C) 2016-2023 Antonio Quartulli * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 diff --git a/src/openvpn/networking_sitnl.c b/src/openvpn/networking_sitnl.c index 515a30d6f0c..75594b88812 100644 --- a/src/openvpn/networking_sitnl.c +++ b/src/openvpn/networking_sitnl.c @@ -1,7 +1,7 @@ /* * Simplified Interface To NetLink * - * Copyright (C) 2016-2022 Antonio Quartulli + * Copyright (C) 2016-2023 Antonio Quartulli * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -28,6 +28,7 @@ #include "syshead.h" +#include "dco.h" #include "errlevel.h" #include "buffer.h" #include "misc.h" @@ -56,6 +57,18 @@ #define NLMSG_TAIL(nmsg) \ ((struct rtattr *)(((uint8_t *)(nmsg)) + NLMSG_ALIGN((nmsg)->nlmsg_len))) +#define SITNL_NEST(_msg, _max_size, _attr) \ + ({ \ + struct rtattr *_nest = NLMSG_TAIL(_msg); \ + SITNL_ADDATTR(_msg, _max_size, _attr, NULL, 0); \ + _nest; \ + }) + +#define SITNL_NEST_END(_msg, _nest) \ + { \ + _nest->rta_len = (void *)NLMSG_TAIL(_msg) - (void *)_nest; \ + } + /** * Generic address data structure used to pass addresses and prefixes as * argument to AF family agnostic functions @@ -597,27 +610,6 @@ net_route_v6_best_gw(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, #ifdef ENABLE_SITNL -int -net_ctx_init(struct context *c, openvpn_net_ctx_t *ctx) -{ - (void)c; - (void)ctx; - - return 0; -} - -void -net_ctx_reset(openvpn_net_ctx_t *ctx) -{ - (void)ctx; -} - -void -net_ctx_free(openvpn_net_ctx_t *ctx) -{ - (void)ctx; -} - int net_route_v4_best_gw(openvpn_net_ctx_t *ctx, const in_addr_t *dst, in_addr_t *best_gw, char *best_iface) @@ -952,10 +944,6 @@ sitnl_route_set(int cmd, uint32_t flags, int ifindex, sa_family_t af_family, } ret = sitnl_send(&req.n, 0, 0, NULL, NULL); - if (ret == -EEXIST) - { - ret = 0; - } err: return ret; } @@ -1043,7 +1031,7 @@ net_addr_v4_add(openvpn_net_ctx_t *ctx, const char *iface, addr_v4.ipv4 = htonl(*addr); msg(M_INFO, "%s: %s/%d dev %s", __func__, - inet_ntop(AF_INET, &addr_v4.ipv4, buf, sizeof(buf)), prefixlen,iface); + inet_ntop(AF_INET, &addr_v4.ipv4, buf, sizeof(buf)), prefixlen, iface); return sitnl_addr_add(AF_INET, iface, &addr_v4, prefixlen); } @@ -1185,7 +1173,7 @@ sitnl_route_add(const char *iface, sa_family_t af_family, const void *dst, scope = RT_SCOPE_LINK; } - return sitnl_route_set(RTM_NEWROUTE, NLM_F_CREATE | NLM_F_REPLACE, ifindex, + return sitnl_route_set(RTM_NEWROUTE, NLM_F_CREATE, ifindex, af_family, dst, prefixlen, gw, table, metric, scope, RTPROT_BOOT, RTN_UNICAST); } @@ -1335,6 +1323,177 @@ net_route_v6_del(openvpn_net_ctx_t *ctx, const struct in6_addr *dst, table, metric); } + +int +net_iface_new(openvpn_net_ctx_t *ctx, const char *iface, const char *type, + void *arg) +{ + struct sitnl_link_req req = { }; + int ret = -1; + + ASSERT(iface); + + req.n.nlmsg_len = NLMSG_LENGTH(sizeof(req.i)); + req.n.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL; + req.n.nlmsg_type = RTM_NEWLINK; + + SITNL_ADDATTR(&req.n, sizeof(req), IFLA_IFNAME, iface, strlen(iface) + 1); + + struct rtattr *linkinfo = SITNL_NEST(&req.n, sizeof(req), IFLA_LINKINFO); + SITNL_ADDATTR(&req.n, sizeof(req), IFLA_INFO_KIND, type, strlen(type) + 1); +#if defined(ENABLE_DCO) + if (arg && (strcmp(type, "ovpn-dco") == 0)) + { + dco_context_t *dco = arg; + struct rtattr *data = SITNL_NEST(&req.n, sizeof(req), IFLA_INFO_DATA); + SITNL_ADDATTR(&req.n, sizeof(req), IFLA_OVPN_MODE, &dco->ifmode, + sizeof(uint8_t)); + SITNL_NEST_END(&req.n, data); + } +#endif + SITNL_NEST_END(&req.n, linkinfo); + + req.i.ifi_family = AF_PACKET; + + msg(D_ROUTE, "%s: add %s type %s", __func__, iface, type); + + ret = sitnl_send(&req.n, 0, 0, NULL, NULL); +err: + return ret; +} + +static int +sitnl_parse_rtattr_flags(struct rtattr *tb[], int max, struct rtattr *rta, + int len, unsigned short flags) +{ + unsigned short type; + + memset(tb, 0, sizeof(struct rtattr *) * (max + 1)); + + while (RTA_OK(rta, len)) + { + type = rta->rta_type & ~flags; + + if ((type <= max) && (!tb[type])) + { + tb[type] = rta; + } + + rta = RTA_NEXT(rta, len); + } + + if (len) + { + msg(D_ROUTE, "%s: %d bytes not parsed! (rta_len=%d)", __func__, len, + rta->rta_len); + } + + return 0; +} + +static int +sitnl_parse_rtattr(struct rtattr *tb[], int max, struct rtattr *rta, int len) +{ + return sitnl_parse_rtattr_flags(tb, max, rta, len, 0); +} + +#define sitnl_parse_rtattr_nested(tb, max, rta) \ + (sitnl_parse_rtattr_flags(tb, max, RTA_DATA(rta), RTA_PAYLOAD(rta), \ + NLA_F_NESTED)) + +static int +sitnl_type_save(struct nlmsghdr *n, void *arg) +{ + char *type = arg; + struct ifinfomsg *ifi = NLMSG_DATA(n); + struct rtattr *tb[IFLA_MAX + 1]; + int ret; + + ret = sitnl_parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), IFLA_PAYLOAD(n)); + if (ret < 0) + { + return ret; + } + + if (tb[IFLA_LINKINFO]) + { + struct rtattr *tb_link[IFLA_INFO_MAX + 1]; + + ret = sitnl_parse_rtattr_nested(tb_link, IFLA_INFO_MAX, + tb[IFLA_LINKINFO]); + if (ret < 0) + { + return ret; + } + + if (!tb_link[IFLA_INFO_KIND]) + { + return -ENOENT; + } + + strncpynt(type, RTA_DATA(tb_link[IFLA_INFO_KIND]), IFACE_TYPE_LEN_MAX); + } + + return 0; +} + +int +net_iface_type(openvpn_net_ctx_t *ctx, const char *iface, + char type[IFACE_TYPE_LEN_MAX]) +{ + struct sitnl_link_req req = { }; + int ifindex = if_nametoindex(iface); + + if (!ifindex) + { + return -errno; + } + + req.n.nlmsg_len = NLMSG_LENGTH(sizeof(req.i)); + req.n.nlmsg_flags = NLM_F_REQUEST; + req.n.nlmsg_type = RTM_GETLINK; + + req.i.ifi_family = AF_PACKET; + req.i.ifi_index = ifindex; + + memset(type, 0, IFACE_TYPE_LEN_MAX); + + int ret = sitnl_send(&req.n, 0, 0, sitnl_type_save, type); + if (ret < 0) + { + msg(D_ROUTE, "%s: cannot retrieve iface %s: %s (%d)", __func__, iface, + strerror(-ret), ret); + return ret; + } + + msg(D_ROUTE, "%s: type of %s: %s", __func__, iface, type); + + return 0; +} + +int +net_iface_del(openvpn_net_ctx_t *ctx, const char *iface) +{ + struct sitnl_link_req req = { }; + int ifindex = if_nametoindex(iface); + + if (!ifindex) + { + return -errno; + } + + req.n.nlmsg_len = NLMSG_LENGTH(sizeof(req.i)); + req.n.nlmsg_flags = NLM_F_REQUEST; + req.n.nlmsg_type = RTM_DELLINK; + + req.i.ifi_family = AF_PACKET; + req.i.ifi_index = ifindex; + + msg(D_ROUTE, "%s: delete %s", __func__, iface); + + return sitnl_send(&req.n, 0, 0, NULL, NULL); +} + #endif /* !ENABLE_SITNL */ -#endif /* TARGET_LINUX */ +#endif /* TARGET_LINUX */ \ No newline at end of file diff --git a/src/openvpn/networking_sitnl.h b/src/openvpn/networking_sitnl.h index afd320c6690..559771f40b2 100644 --- a/src/openvpn/networking_sitnl.h +++ b/src/openvpn/networking_sitnl.h @@ -1,7 +1,7 @@ /* * Generic interface to platform specific networking code * - * Copyright (C) 2016-2022 Antonio Quartulli + * Copyright (C) 2016-2023 Antonio Quartulli * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -25,4 +25,4 @@ typedef char openvpn_net_iface_t; typedef void *openvpn_net_ctx_t; -#endif /* NETWORKING_SITNL_H_ */ +#endif /* NETWORKING_SITNL_H_ */ \ No newline at end of file diff --git a/src/openvpn/ntlm.c b/src/openvpn/ntlm.c index 9158cfd6729..20527d442a7 100644 --- a/src/openvpn/ntlm.c +++ b/src/openvpn/ntlm.c @@ -67,28 +67,25 @@ create_des_keys(const unsigned char *hash, unsigned char *key) key[5] = ((hash[4] & 31) << 3) | (hash[5] >> 5); key[6] = ((hash[5] & 63) << 2) | (hash[6] >> 6); key[7] = ((hash[6] & 127) << 1); - key_des_fixup(key, 8, 1); } static void gen_md4_hash(const uint8_t *data, int data_len, uint8_t *result) { /* result is 16 byte md4 hash */ - const md_kt_t *md4_kt = md_kt_get("MD4"); uint8_t md[MD4_DIGEST_LENGTH]; - md_full(md4_kt, data, data_len, md); + md_full("MD4", data, data_len, md); memcpy(result, md, MD4_DIGEST_LENGTH); } static void -gen_hmac_md5(const uint8_t *data, int data_len, const uint8_t *key, int key_len, +gen_hmac_md5(const uint8_t *data, int data_len, const uint8_t *key, uint8_t *result) { - const md_kt_t *md5_kt = md_kt_get("MD5"); hmac_ctx_t *hmac_ctx = hmac_ctx_new(); - hmac_ctx_init(hmac_ctx, key, key_len, md5_kt); + hmac_ctx_init(hmac_ctx, key, "MD5"); hmac_ctx_update(hmac_ctx, data, data_len); hmac_ctx_final(hmac_ctx, result); hmac_ctx_cleanup(hmac_ctx); @@ -301,7 +298,7 @@ ntlm_phase_3(const struct http_proxy_info *p, const char *phase_2, } unicodize(userdomain_u, userdomain); gen_hmac_md5((uint8_t *)userdomain_u, 2 * strlen(userdomain), md4_hash, - MD5_DIGEST_LENGTH, ntlmv2_hash); + ntlmv2_hash); /* NTLMv2 Blob */ memset(ntlmv2_blob, 0, 128); /* Clear blob buffer */ @@ -366,7 +363,7 @@ ntlm_phase_3(const struct http_proxy_info *p, const char *phase_2, /* hmac-md5 */ gen_hmac_md5(&ntlmv2_response[8], ntlmv2_blob_size + 8, ntlmv2_hash, - MD5_DIGEST_LENGTH, ntlmv2_hmacmd5); + ntlmv2_hmacmd5); /* Add hmac-md5 result to the blob. * Note: This overwrites challenge previously written at @@ -425,10 +422,4 @@ ntlm_phase_3(const struct http_proxy_info *p, const char *phase_2, return ((const char *)make_base64_string2((unsigned char *)phase3, phase3_bufpos, gc)); } - -#else /* if NTLM */ -static void -dummy(void) -{ -} #endif /* if NTLM */ diff --git a/src/openvpn/occ.c b/src/openvpn/occ.c index 9051059449b..aaeaba24456 100644 --- a/src/openvpn/occ.c +++ b/src/openvpn/occ.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -185,7 +185,7 @@ check_send_occ_req_dowork(struct context *c) void check_send_occ_load_test_dowork(struct context *c) { - if (CONNECTION_ESTABLISHED(c)) + if (connection_established(c)) { const struct mtu_load_test *entry; @@ -199,8 +199,11 @@ check_send_occ_load_test_dowork(struct context *c) if (entry->op >= 0) { c->c2.occ_op = entry->op; - c->c2.occ_mtu_load_size = - EXPANDED_SIZE(&c->c2.frame) + entry->delta; + size_t payload_size = frame_calculate_payload_size(&c->c2.frame, + &c->options, &c->c1.ks.key_type); + size_t header_size = frame_calculate_protocol_header_size(&c->c1.ks.key_type, &c->options, false); + + c->c2.occ_mtu_load_size = payload_size + header_size; } else { @@ -218,8 +221,8 @@ check_send_occ_msg_dowork(struct context *c) bool doit = false; c->c2.buf = c->c2.buffers->aux_buf; - ASSERT(buf_init(&c->c2.buf, FRAME_HEADROOM(&c->c2.frame))); - ASSERT(buf_safe(&c->c2.buf, MAX_RW_SIZE_TUN(&c->c2.frame))); + ASSERT(buf_init(&c->c2.buf, c->c2.frame.buf.headroom)); + ASSERT(buf_safe(&c->c2.buf, c->c2.frame.buf.payload_size)); ASSERT(buf_write(&c->c2.buf, occ_magic, OCC_STRING_SIZE)); switch (c->c2.occ_op) @@ -298,10 +301,21 @@ check_send_occ_msg_dowork(struct context *c) { break; } - need_to_add = min_int(c->c2.occ_mtu_load_size, EXPANDED_SIZE(&c->c2.frame)) + size_t proto_hdr, payload_hdr; + const struct key_type *kt = &c->c1.ks.key_type; + + /* OCC message have comp/fragment headers but not ethernet headers */ + payload_hdr = frame_calculate_payload_overhead(&c->c2.frame, &c->options, + kt, false); + + /* Since we do not know the payload size we just pass 0 as size here */ + proto_hdr = frame_calculate_protocol_header_size(kt, &c->options, false); + + need_to_add = min_int(c->c2.occ_mtu_load_size, c->c2.frame.buf.payload_size) - OCC_STRING_SIZE - - sizeof(uint8_t) - - EXTRA_FRAME(&c->c2.frame); + - sizeof(uint8_t) /* occ opcode */ + - payload_hdr + - proto_hdr; while (need_to_add > 0) { @@ -314,12 +328,13 @@ check_send_occ_msg_dowork(struct context *c) } --need_to_add; } - dmsg(D_PACKET_CONTENT, "SENT OCC_MTU_LOAD min_int(%d-%d-%d-%d,%d) size=%d", + dmsg(D_PACKET_CONTENT, "SENT OCC_MTU_LOAD min_int(%d,%d)-%d-%d-%d-%d) size=%d", c->c2.occ_mtu_load_size, + c->c2.frame.buf.payload_size, OCC_STRING_SIZE, (int) sizeof(uint8_t), - EXTRA_FRAME(&c->c2.frame), - MAX_RW_SIZE_TUN(&c->c2.frame), + (int) payload_hdr, + (int) proto_hdr, BLEN(&c->c2.buf)); doit = true; } @@ -416,9 +431,8 @@ process_received_occ_msg(struct context *c) case OCC_EXIT: dmsg(D_PACKET_CONTENT, "RECEIVED OCC_EXIT"); - c->sig->signal_received = SIGTERM; - c->sig->signal_text = "remote-exit"; + register_signal(c->sig, SIGUSR1, "remote-exit"); break; } c->c2.buf.len = 0; /* don't pass packet on */ -} +} \ No newline at end of file diff --git a/src/openvpn/occ.h b/src/openvpn/occ.h index f7683481cf6..120b9cbaf7b 100644 --- a/src/openvpn/occ.h +++ b/src/openvpn/occ.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -153,4 +153,4 @@ check_send_occ_msg(struct context *c) } } -#endif /* ifndef OCC_H */ +#endif /* ifndef OCC_H */ \ No newline at end of file diff --git a/src/openvpn/openssl_compat.h b/src/openvpn/openssl_compat.h index 0fc51d5d072..a113e37d04f 100644 --- a/src/openvpn/openssl_compat.h +++ b/src/openvpn/openssl_compat.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * Copyright (C) 2010-2021 Fox Crypto B.V. * * This program is free software; you can redistribute it and/or modify @@ -46,7 +46,38 @@ #include #include -#if !defined(HAVE_EVP_MD_CTX_RESET) +/* Functionality missing in 1.1.0 */ +#if OPENSSL_VERSION_NUMBER < 0x10101000L && !defined(ENABLE_CRYPTO_WOLFSSL) +#define SSL_CTX_set1_groups SSL_CTX_set1_curves +#endif + +/* Functionality missing in LibreSSL before 3.5 and OpenSSL 1.0.2 */ +#if (OPENSSL_VERSION_NUMBER < 0x10100000L || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x3050000fL)) && !defined(ENABLE_CRYPTO_WOLFSSL) +/** + * Destroy a X509 object + * + * @param obj X509 object + */ +static inline void +X509_OBJECT_free(X509_OBJECT *obj) +{ + if (obj) + { + X509_OBJECT_free_contents(obj); + OPENSSL_free(obj); + } +} + +#define EVP_CTRL_AEAD_SET_TAG EVP_CTRL_GCM_SET_TAG +#define EVP_CTRL_AEAD_GET_TAG EVP_CTRL_GCM_GET_TAG +#endif + +#if (OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)) && !defined(ENABLE_CRYPTO_WOLFSSL) +#define RSA_F_RSA_OSSL_PRIVATE_ENCRYPT RSA_F_RSA_EAY_PRIVATE_ENCRYPT +#endif + +/* Functionality missing in 1.0.2 */ +#if OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(ENABLE_CRYPTO_WOLFSSL) /** * Reset a message digest context * @@ -59,9 +90,7 @@ EVP_MD_CTX_reset(EVP_MD_CTX *ctx) EVP_MD_CTX_cleanup(ctx); return 1; } -#endif -#if !defined(HAVE_EVP_MD_CTX_FREE) /** * Free an existing message digest context * @@ -72,9 +101,7 @@ EVP_MD_CTX_free(EVP_MD_CTX *ctx) { free(ctx); } -#endif -#if !defined(HAVE_EVP_MD_CTX_NEW) /** * Allocate a new message digest object * @@ -87,21 +114,11 @@ EVP_MD_CTX_new(void) ALLOC_OBJ_CLEAR(ctx, EVP_MD_CTX); return ctx; } -#endif -#if !defined(HAVE_EVP_CIPHER_CTX_RESET) #define EVP_CIPHER_CTX_reset EVP_CIPHER_CTX_init -#endif - -#if !defined(HAVE_X509_GET0_NOTBEFORE) #define X509_get0_notBefore X509_get_notBefore -#endif - -#if !defined(HAVE_X509_GET0_NOTAFTER) #define X509_get0_notAfter X509_get_notAfter -#endif -#if !defined(HAVE_HMAC_CTX_RESET) /** * Reset a HMAC context * @@ -124,9 +141,7 @@ HMAC_CTX_reset(HMAC_CTX *ctx) HMAC_CTX_init(ctx); return 1; } -#endif -#if !defined(HAVE_HMAC_CTX_FREE) /** * Cleanup and free an existing HMAC context * @@ -138,9 +153,7 @@ HMAC_CTX_free(HMAC_CTX *ctx) HMAC_CTX_cleanup(ctx); free(ctx); } -#endif -#if !defined(HAVE_HMAC_CTX_NEW) /** * Allocate a new HMAC context object * @@ -153,9 +166,7 @@ HMAC_CTX_new(void) ALLOC_OBJ_CLEAR(ctx, HMAC_CTX); return ctx; } -#endif -#if !defined(HAVE_SSL_CTX_GET_DEFAULT_PASSWD_CB_USERDATA) /** * Fetch the default password callback user data from the SSL context * @@ -167,9 +178,7 @@ SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx) { return ctx ? ctx->default_passwd_callback_userdata : NULL; } -#endif -#if !defined(HAVE_SSL_CTX_GET_DEFAULT_PASSWD_CB) /** * Fetch the default password callback from the SSL context * @@ -181,15 +190,7 @@ SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx) { return ctx ? ctx->default_passwd_callback : NULL; } -#endif - -/* This function is implemented as macro, so the configure check for the - * function may fail, so we check for both variants here */ -#if !defined(HAVE_SSL_CTX_SET1_GROUPS) && !defined(SSL_CTX_set1_groups) -#define SSL_CTX_set1_groups SSL_CTX_set1_curves -#endif -#if !defined(HAVE_X509_GET0_PUBKEY) /** * Get the public key from a X509 certificate * @@ -202,9 +203,7 @@ X509_get0_pubkey(const X509 *x) return (x && x->cert_info && x->cert_info->key) ? x->cert_info->key->pkey : NULL; } -#endif -#if !defined(HAVE_X509_STORE_GET0_OBJECTS) /** * Fetch the X509 object stack from the X509 store * @@ -216,26 +215,7 @@ static inline STACK_OF(X509_OBJECT) { return store ? store->objs : NULL; } -#endif - -#if !defined(HAVE_X509_OBJECT_FREE) -/** - * Destroy a X509 object - * - * @param obj X509 object - */ -static inline void -X509_OBJECT_free(X509_OBJECT *obj) -{ - if (obj) - { - X509_OBJECT_free_contents(obj); - OPENSSL_free(obj); - } -} -#endif -#if !defined(HAVE_X509_OBJECT_GET_TYPE) /** * Get the type of an X509 object * @@ -247,9 +227,7 @@ X509_OBJECT_get_type(const X509_OBJECT *obj) { return obj ? obj->type : X509_LU_FAIL; } -#endif -#if !defined(HAVE_EVP_PKEY_GET0_RSA) /** * Get the RSA object of a public key * @@ -261,9 +239,7 @@ EVP_PKEY_get0_RSA(EVP_PKEY *pkey) { return (pkey && pkey->type == EVP_PKEY_RSA) ? pkey->pkey.rsa : NULL; } -#endif -#if !defined(HAVE_EVP_PKEY_GET0_EC_KEY) && !defined(OPENSSL_NO_EC) /** * Get the EC_KEY object of a public key * @@ -275,9 +251,8 @@ EVP_PKEY_get0_EC_KEY(EVP_PKEY *pkey) { return (pkey && pkey->type == EVP_PKEY_EC) ? pkey->pkey.ec : NULL; } -#endif -#if !defined(HAVE_EVP_PKEY_GET0_DSA) + /** * Get the DSA object of a public key * @@ -289,9 +264,7 @@ EVP_PKEY_get0_DSA(EVP_PKEY *pkey) { return (pkey && pkey->type == EVP_PKEY_DSA) ? pkey->pkey.dsa : NULL; } -#endif -#if !defined(HAVE_RSA_SET_FLAGS) /** * Set the RSA flags * @@ -306,9 +279,7 @@ RSA_set_flags(RSA *rsa, int flags) rsa->flags = flags; } } -#endif -#if !defined(HAVE_RSA_GET0_KEY) /** * Get the RSA parameters * @@ -334,9 +305,7 @@ RSA_get0_key(const RSA *rsa, const BIGNUM **n, *d = rsa ? rsa->d : NULL; } } -#endif -#if !defined(HAVE_RSA_SET0_KEY) /** * Set the RSA parameters * @@ -373,9 +342,7 @@ RSA_set0_key(RSA *rsa, BIGNUM *n, BIGNUM *e, BIGNUM *d) return 1; } -#endif /* if !defined(HAVE_RSA_SET0_KEY) */ -#if !defined(HAVE_RSA_BITS) /** * Number of significant RSA bits * @@ -389,9 +356,7 @@ RSA_bits(const RSA *rsa) RSA_get0_key(rsa, &n, NULL, NULL); return n ? BN_num_bits(n) : 0; } -#endif -#if !defined(HAVE_DSA_GET0_PQG) /** * Get the DSA parameters * @@ -417,9 +382,7 @@ DSA_get0_pqg(const DSA *dsa, const BIGNUM **p, *g = dsa ? dsa->g : NULL; } } -#endif -#if !defined(HAVE_DSA_BITS) /** * Number of significant DSA bits * @@ -433,9 +396,7 @@ DSA_bits(const DSA *dsa) DSA_get0_pqg(dsa, &p, NULL, NULL); return p ? BN_num_bits(p) : 0; } -#endif -#if !defined(HAVE_RSA_METH_NEW) /** * Allocate a new RSA method object * @@ -452,9 +413,7 @@ RSA_meth_new(const char *name, int flags) rsa_meth->flags = flags; return rsa_meth; } -#endif -#if !defined(HAVE_RSA_METH_FREE) /** * Free an existing RSA_METHOD object * @@ -475,9 +434,7 @@ RSA_meth_free(RSA_METHOD *meth) free(meth); } } -#endif -#if !defined(HAVE_RSA_METH_SET_PUB_ENC) /** * Set the public encoding function of an RSA_METHOD object * @@ -498,9 +455,7 @@ RSA_meth_set_pub_enc(RSA_METHOD *meth, } return 0; } -#endif -#if !defined(HAVE_RSA_METH_SET_PUB_DEC) /** * Set the public decoding function of an RSA_METHOD object * @@ -521,9 +476,7 @@ RSA_meth_set_pub_dec(RSA_METHOD *meth, } return 0; } -#endif -#if !defined(HAVE_RSA_METH_SET_PRIV_ENC) /** * Set the private encoding function of an RSA_METHOD object * @@ -544,9 +497,7 @@ RSA_meth_set_priv_enc(RSA_METHOD *meth, } return 0; } -#endif -#if !defined(HAVE_RSA_METH_SET_PRIV_DEC) /** * Set the private decoding function of an RSA_METHOD object * @@ -567,9 +518,7 @@ RSA_meth_set_priv_dec(RSA_METHOD *meth, } return 0; } -#endif -#if !defined(HAVE_RSA_METH_SET_INIT) /** * Set the init function of an RSA_METHOD object * @@ -587,9 +536,7 @@ RSA_meth_set_init(RSA_METHOD *meth, int (*init)(RSA *rsa)) } return 0; } -#endif -#if !defined (HAVE_RSA_METH_SET_SIGN) /** * Set the sign function of an RSA_METHOD object * @@ -608,9 +555,7 @@ RSA_meth_set_sign(RSA_METHOD *meth, meth->rsa_sign = sign; return 1; } -#endif -#if !defined(HAVE_RSA_METH_SET_FINISH) /** * Set the finish function of an RSA_METHOD object * @@ -628,9 +573,7 @@ RSA_meth_set_finish(RSA_METHOD *meth, int (*finish)(RSA *rsa)) } return 0; } -#endif -#if !defined(HAVE_RSA_METH_SET0_APP_DATA) /** * Set the application data of an RSA_METHOD object * @@ -648,9 +591,7 @@ RSA_meth_set0_app_data(RSA_METHOD *meth, void *app_data) } return 0; } -#endif -#if !defined(HAVE_RSA_METH_GET0_APP_DATA) /** * Get the application data of an RSA_METHOD object * @@ -662,9 +603,7 @@ RSA_meth_get0_app_data(const RSA_METHOD *meth) { return meth ? meth->app_data : NULL; } -#endif -#if !defined(HAVE_EC_GROUP_ORDER_BITS) && !defined(OPENSSL_NO_EC) /** * Gets the number of bits of the order of an EC_GROUP * @@ -680,22 +619,11 @@ EC_GROUP_order_bits(const EC_GROUP *group) BN_free(order); return bits; } -#endif /* SSLeay symbols have been renamed in OpenSSL 1.1 */ -#ifndef OPENSSL_VERSION #define OPENSSL_VERSION SSLEAY_VERSION -#endif - -#ifndef HAVE_OPENSSL_VERSION #define OpenSSL_version SSLeay_version -#endif -#if !defined(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT) -#define RSA_F_RSA_OSSL_PRIVATE_ENCRYPT RSA_F_RSA_EAY_PRIVATE_ENCRYPT -#endif - -#ifndef SSL_CTX_get_min_proto_version /** Return the min SSL protocol version currently enabled in the context. * If no valid version >= TLS1.0 is found, return 0. */ static inline int @@ -716,9 +644,7 @@ SSL_CTX_get_min_proto_version(SSL_CTX *ctx) } return 0; } -#endif /* SSL_CTX_get_min_proto_version */ -#ifndef SSL_CTX_get_max_proto_version /** Return the max SSL protocol version currently enabled in the context. * If no valid version >= TLS1.0 is found, return 0. */ static inline int @@ -739,9 +665,7 @@ SSL_CTX_get_max_proto_version(SSL_CTX *ctx) } return 0; } -#endif /* SSL_CTX_get_max_proto_version */ -#ifndef SSL_CTX_set_min_proto_version /** Mimics SSL_CTX_set_min_proto_version for OpenSSL < 1.1 */ static inline int SSL_CTX_set_min_proto_version(SSL_CTX *ctx, long tls_ver_min) @@ -768,9 +692,7 @@ SSL_CTX_set_min_proto_version(SSL_CTX *ctx, long tls_ver_min) return 1; } -#endif /* SSL_CTX_set_min_proto_version */ -#ifndef SSL_CTX_set_max_proto_version /** Mimics SSL_CTX_set_max_proto_version for OpenSSL < 1.1 */ static inline int SSL_CTX_set_max_proto_version(SSL_CTX *ctx, long tls_ver_max) @@ -797,6 +719,88 @@ SSL_CTX_set_max_proto_version(SSL_CTX *ctx, long tls_ver_max) return 1; } -#endif /* SSL_CTX_set_max_proto_version */ +#endif /* if OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(ENABLE_CRYPTO_WOLFSSL) */ + +/* Functionality missing in 1.1.1 */ +#if OPENSSL_VERSION_NUMBER < 0x30000000L && !defined(OPENSSL_NO_EC) + +/* Note that this is not a perfect emulation of the new function but + * is good enough for our case of printing certificate details during + * handshake */ +static inline +int +EVP_PKEY_get_group_name(EVP_PKEY *pkey, char *gname, size_t gname_sz, + size_t *gname_len) +{ + const EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey); + if (ec == NULL) + { + return 0; + } + const EC_GROUP *group = EC_KEY_get0_group(ec); + int nid = EC_GROUP_get_curve_name(group); + + if (nid == 0) + { + return 0; + } + const char *curve = OBJ_nid2sn(nid); + if (!curve) + { + curve = "(error fetching curve name)"; + } + + strncpynt(gname, curve, gname_sz); + + /* strncpynt ensures null termination so just strlen is fine here */ + *gname_len = strlen(curve); + return 1; +} +#endif /* if OPENSSL_VERSION_NUMBER < 0x30000000L && !defined(OPENSSL_NO_EC) */ + +#if OPENSSL_VERSION_NUMBER < 0x30000000L +#define EVP_MD_get0_name EVP_MD_name +#define EVP_CIPHER_get0_name EVP_CIPHER_name +#define EVP_CIPHER_CTX_get_mode EVP_CIPHER_CTX_mode + +/** Reduce SSL_CTX_new_ex() to SSL_CTX_new() for OpenSSL < 3 */ +#define SSL_CTX_new_ex(libctx, propq, method) \ + SSL_CTX_new((method)) + +/* Some safe typedefs to avoid too many ifdefs */ +typedef void OSSL_LIB_CTX; +typedef void OSSL_PROVIDER; + +/* Mimics the functions but only when the default context without + * options is chosen */ +static inline const EVP_CIPHER * +EVP_CIPHER_fetch(void *ctx, const char *algorithm, const char *properties) +{ + ASSERT(!ctx); + ASSERT(!properties); + return EVP_get_cipherbyname(algorithm); +} + +static inline const EVP_MD * +EVP_MD_fetch(void *ctx, const char *algorithm, const char *properties) +{ + ASSERT(!ctx); + ASSERT(!properties); + return EVP_get_digestbyname(algorithm); +} + +static inline void +EVP_CIPHER_free(const EVP_CIPHER *cipher) +{ + /* OpenSSL 1.1.1 and lower use only const EVP_CIPHER, nothing to free */ +} + +static inline void +EVP_MD_free(const EVP_MD *md) +{ + /* OpenSSL 1.1.1 and lower use only const EVP_MD, nothing to free */ +} + +#endif /* OPENSSL_VERSION_NUMBER < 0x30000000L */ -#endif /* OPENSSL_COMPAT_H_ */ +#endif /* OPENSSL_COMPAT_H_ */ \ No newline at end of file diff --git a/src/openvpn/openvpn.c b/src/openvpn/openvpn.c index 1cd8f1b308a..cd48be7f310 100644 --- a/src/openvpn/openvpn.c +++ b/src/openvpn/openvpn.c @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -97,6 +97,8 @@ tunnel_point_to_point(struct context *c) perf_pop(); } + persist_client_stats(c); + uninit_management_callback(); /* tear down tunnel instance (unless --persist-tun) */ @@ -105,7 +107,8 @@ tunnel_point_to_point(struct context *c) #undef PROCESS_SIGNAL_P2P -void init_early(struct context *c) +void +init_early(struct context *c) { net_ctx_init(c, &c->net_ctx); @@ -113,19 +116,19 @@ void init_early(struct context *c) init_verb_mute(c, IVM_LEVEL_1); /* Initialise OpenSSL provider, this needs to be initialised this - * early since option post-processing and also openssl info - * printing depends on it */ - for (int j=1; j < MAX_PARMS && c->options.providers.names[j]; j++) + * early since option post-processing and also openssl info + * printing depends on it */ + for (int j = 1; j < MAX_PARMS && c->options.providers.names[j]; j++) { c->options.providers.providers[j] = crypto_load_provider(c->options.providers.names[j]); } } -static void uninit_early(struct context *c) +static void +uninit_early(struct context *c) { - net_ctx_free(&c->net_ctx); - for (int j=1; j < MAX_PARMS && c->options.providers.providers[j]; j++) + for (int j = 1; j < MAX_PARMS && c->options.providers.providers[j]; j++) { crypto_unload_provider(c->options.providers.names[j], c->options.providers.providers[j]); @@ -133,6 +136,7 @@ static void uninit_early(struct context *c) net_ctx_free(&c->net_ctx); } + /**************************************************************************/ /** * OpenVPN's main init-run-cleanup loop. @@ -246,7 +250,7 @@ openvpn_main(int argc, char *argv[]) } /* sanity check on options */ - options_postprocess(&c.options); + options_postprocess(&c.options, c.es); /* show all option settings */ show_settings(&c.options); @@ -389,4 +393,4 @@ main(int argc, char *argv[]) { return openvpn_main(argc, argv); } -#endif /* ifdef _WIN32 */ +#endif /* ifdef _WIN32 */ \ No newline at end of file diff --git a/src/openvpn/openvpn.h b/src/openvpn/openvpn.h index db08fdd1085..e17f91b0e69 100644 --- a/src/openvpn/openvpn.h +++ b/src/openvpn/openvpn.h @@ -5,7 +5,7 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc + * Copyright (C) 2002-2023 OpenVPN Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -42,7 +42,6 @@ #include "sig.h" #include "misc.h" #include "mbuf.h" -#include "pf.h" #include "pool.h" #include "plugin.h" #include "manage.h" @@ -189,7 +188,6 @@ struct context_1 struct socks_proxy_info *socks_proxy; bool socks_proxy_owned; -#if P2MP /* persist --ifconfig-pool db to file */ struct ifconfig_pool_persist *ifconfig_pool_persist; bool ifconfig_pool_persist_owned; @@ -203,16 +201,11 @@ struct context_1 struct user_pass *auth_user_pass; /**< Username and password for * authentication. */ - - const char *ciphername; /**< Data channel cipher from config file */ - const char *authname; /**< Data channel auth from config file */ - int keysize; /**< Data channel keysize from config file */ -#endif }; static inline bool -is_cas_pending(enum client_connect_status cas) +is_cas_pending(enum multi_status cas) { return cas == CAS_PENDING || cas == CAS_PENDING_DEFERRED || cas == CAS_PENDING_DEFERRED_PARTIAL; @@ -223,7 +216,7 @@ is_cas_pending(enum client_connect_status cas) * \c SIGUSR1 restarts. * * This structure is initialized at the top of the \c - * tunnel_point_to_point(), \c tunnel_server_udp_single_threaded(), and \c + * tunnel_point_to_point(), \c tunnel_server_udp(), and \c * tunnel_server_tcp() functions. In other words, it is reset for every * iteration of the \c main() function's inner \c SIGUSR1 loop. */ @@ -238,25 +231,13 @@ struct context_2 int event_set_max; bool event_set_owned; - /* event flags returned by io_wait */ -#define SOCKET_READ (1<<0) -#define SOCKET_WRITE (1<<1) -#define TUN_READ (1<<2) -#define TUN_WRITE (1<<3) -#define ES_ERROR (1<<4) -#define ES_TIMEOUT (1<<5) -#ifdef ENABLE_MANAGEMENT -#define MANAGEMENT_READ (1<<6) -#define MANAGEMENT_WRITE (1<<7) -#endif -#ifdef ENABLE_ASYNC_PUSH -#define FILE_CLOSED (1<<8) -#endif - + /* bitmask for event status. Check event.h for possible values */ unsigned int event_set_status; struct link_socket *link_socket; /* socket used for TCP/UDP connection to remote */ bool link_socket_owned; + + /** This variable is used instead link_socket->info for P2MP UDP childs */ struct link_socket_info *link_socket_info; const struct link_socket *accept_from; /* possibly do accept() on a parent link_socket */ @@ -275,12 +256,10 @@ struct context_2 struct frame frame_fragment_omit; #endif -#ifdef ENABLE_FEATURE_SHAPER /* * Traffic shaper object. */ struct shaper shaper; -#endif /* * Statistics @@ -288,8 +267,10 @@ struct context_2 counter_type tun_read_bytes; counter_type tun_write_bytes; counter_type link_read_bytes; + counter_type dco_read_bytes; counter_type link_read_bytes_auth; counter_type link_write_bytes; + counter_type dco_write_bytes; #ifdef PACKET_TRUNCATION_CHECK counter_type n_trunc_tun_read; counter_type n_trunc_tun_write; @@ -309,6 +290,11 @@ struct context_2 struct event_timeout inactivity_interval; int64_t inactivity_bytes; + struct event_timeout session_interval; + + /* auth token renewal timer */ + struct event_timeout auth_token_renewal_interval; + /* the option strings must match across peers */ char *options_string_local; char *options_string_remote; @@ -351,6 +337,12 @@ struct context_2 * received from a new client. See the * \c --tls-auth commandline option. */ + + hmac_ctx_t *session_id_hmac; + /**< the HMAC we use to generate and verify our syn cookie like + * session ids from the server. + */ + /* used to optimize calls to tls_multi_process */ struct interval tmp_int; @@ -401,7 +393,9 @@ struct context_2 * Event loop info */ - /* how long to wait on link/tun read before we will need to be serviced */ + /** Time to next event of timers and similar. This is used to determine + * how long to wait on event wait (select/poll on link/tun read) + * before this context wants to be serviced. */ struct timeval timeval; /* next wakeup for processing coarse timers (>1 sec resolution) */ @@ -432,8 +426,6 @@ struct context_2 /* don't wait for TUN/TAP/UDP to be ready to accept write */ bool fast_io; -#if P2MP - /* --ifconfig endpoints to be pushed to client */ bool push_request_received; bool push_ifconfig_defined; @@ -448,8 +440,7 @@ struct context_2 struct in6_addr push_ifconfig_ipv6_remote; struct event_timeout push_request_interval; - int n_sent_push_requests; - bool did_pre_pull_restore; + time_t push_request_timeout; /* hash of pulled options, so we can compare when options change */ bool pulled_options_digest_init_done; @@ -458,14 +449,10 @@ struct context_2 struct event_timeout scheduled_exit; int scheduled_exit_signal; -#endif /* if P2MP */ /* packet filter */ -#ifdef ENABLE_PF - struct pf_context pf; -#endif -#ifdef MANAGEMENT_DEF_AUTH +#ifdef ENABLE_MANAGEMENT struct man_def_auth_context mda_context; #endif @@ -554,12 +541,10 @@ struct context #define PROTO_DUMP(buf, gc) protocol_dump((buf), \ PROTO_DUMP_FLAGS \ |(c->c2.tls_multi ? PD_TLS : 0) \ - |(c->options.tls_auth_file ? c->c1.ks.key_type.hmac_length : 0), \ + |(c->options.tls_auth_file ? md_kt_size(c->c1.ks.key_type.digest) : 0), \ gc) -#define CIPHER_ENABLED(c) (c->c1.ks.key_type.cipher != NULL) - /* this represents "disabled peer-id" */ #define MAX_PEER_ID 0xFFFFFF -#endif /* ifndef OPENVPN_H */ +#endif /* ifndef OPENVPN_H */ \ No newline at end of file diff --git a/src/openvpn/openvpn.vcxproj b/src/openvpn/openvpn.vcxproj index d2cbaa8c834..0e465009bac 100644 --- a/src/openvpn/openvpn.vcxproj +++ b/src/openvpn/openvpn.vcxproj @@ -37,39 +37,39 @@ Application true NotSet - v142 + v143 Spectre Application true NotSet - v142 + v143 Spectre Application true NotSet - v142 + v143 Spectre Application NotSet - v142 + v143 Spectre Application NotSet - v142 + v143 Spectre Application NotSet - v142 + v143 Spectre @@ -277,8 +277,11 @@ - + + + + @@ -306,10 +309,10 @@ + - @@ -320,6 +323,7 @@ + @@ -332,6 +336,8 @@ + + @@ -339,6 +345,9 @@ + + + @@ -358,7 +367,11 @@ + + + + @@ -388,13 +401,13 @@ - + + - @@ -406,6 +419,7 @@ + @@ -421,6 +435,8 @@ + + @@ -430,6 +446,8 @@ + + diff --git a/src/openvpn/options.c b/src/openvpn/options.c index 2ddf30d8ce3..8667572de89 100644 --- a/src/openvpn/options.c +++ b/src/openvpn/options.c @@ -5,8 +5,8 @@ * packet encryption, packet authentication, and * packet compression. * - * Copyright (C) 2002-2022 OpenVPN Inc - * Copyright (C) 2008-2022 David Sommerseth + * Copyright (C) 2002-2023 OpenVPN Inc + * Copyright (C) 2008-2023 David Sommerseth * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -60,6 +60,8 @@ #include "forward.h" #include "ssl_verify.h" #include "platform.h" +#include "xkey_common.h" +#include "dco.h" #include #include "memdbg.h" @@ -105,7 +107,12 @@ const char title_string[] = #endif #endif " [AEAD]" +#ifdef ENABLE_DCO + " [DCO]" +#endif +#ifdef CONFIGURE_GIT_REVISION " built on " __DATE__ +#endif ; #ifndef ENABLE_SMALL @@ -176,6 +183,9 @@ static const char usage_message[] = " does not begin with \"tun\" or \"tap\".\n" "--dev-node node : Explicitly set the device node rather than using\n" " /dev/net/tun, /dev/tun, /dev/tap, etc.\n" +#if defined(ENABLE_DCO) + "--disable-dco : Do not attempt using Data Channel Offload.\n" +#endif "--lladdr hw : Set the link layer address of the tap device.\n" "--topology t : Set --dev tun topology: 'net30', 'p2p', or 'subnet'.\n" #ifdef ENABLE_IPROUTE @@ -216,7 +226,7 @@ static const char usage_message[] = "--route-noexec : Don't add routes automatically. Instead pass routes to\n" " --route-up script using environmental variables.\n" "--route-nopull : When used with --client or --pull, accept options pushed\n" - " by server EXCEPT for routes and dhcp options.\n" + " by server EXCEPT for routes, dns, and dhcp options.\n" "--allow-pull-fqdn : Allow client to pull DNS names from server for\n" " --ifconfig, --route, and --route-gateway.\n" "--redirect-gateway [flags]: Automatically execute routing\n" @@ -251,6 +261,7 @@ static const char usage_message[] = " for m seconds.\n" "--inactive n [bytes] : Exit after n seconds of activity on tun/tap device\n" " produces a combined in/out byte count < bytes.\n" + "--session-timeout n: Limit connection time to n seconds.\n" "--ping-exit n : Exit if n seconds pass without reception of remote ping.\n" "--ping-restart n: Restart if n seconds pass without reception of remote ping.\n" "--ping-timer-rem: Run the --ping-exit/--ping-restart timer only if we have a\n" @@ -326,8 +337,6 @@ static const char usage_message[] = " as the program name to the system logger.\n" "--syslog [name] : Output to syslog, but do not become a daemon.\n" " See --daemon above for a description of the 'name' parm.\n" - "--inetd [name] ['wait'|'nowait'] : Run as an inetd or xinetd server.\n" - " See --daemon above for a description of the 'name' parm.\n" "--log file : Output log to file which is created/truncated on open.\n" "--log-append file : Append log to file, or create file if nonexistent.\n" "--suppress-timestamps : Don't log timestamps to stdout/stderr.\n" @@ -347,10 +356,10 @@ static const char usage_message[] = " and received from TCP/UDP (caps) or tun/tap (lc)\n" " : 6 to 11 -- debug messages of increasing verbosity\n" "--mute n : Log at most n consecutive messages in the same category.\n" - "--status file n : Write operational status to file every n seconds.\n" + "--status file [n] : Write operational status to file every n seconds.\n" "--status-version [n] : Choose the status file format version number.\n" " Currently, n can be 1, 2, or 3 (default=1).\n" - "--disable-occ : Disable options consistency check between peers.\n" + "--disable-occ : (DEPRECATED) Disable options consistency check between peers.\n" #ifdef ENABLE_DEBUG "--gremlin mask : Special stress testing mode (for debugging only).\n" #endif @@ -392,15 +401,9 @@ static const char usage_message[] = "--management-client-group g : When management interface is a unix socket, only\n" " allow connections from group g.\n" #endif -#ifdef MANAGEMENT_DEF_AUTH "--management-client-auth : gives management interface client the responsibility\n" " to authenticate clients after their client certificate\n" " has been verified.\n" -#endif -#ifdef MANAGEMENT_PF - "--management-client-pf : management interface clients must specify a packet\n" - " filter file for each connecting client.\n" -#endif #endif /* ifdef ENABLE_MANAGEMENT */ #ifdef ENABLE_PLUGIN "--plugin m [str]: Load plug-in module m passing str as an argument\n" @@ -409,7 +412,6 @@ static const char usage_message[] = "--vlan-tagging : Enable 802.1Q-based VLAN tagging.\n" "--vlan-accept tagged|untagged|all : Set VLAN tagging mode. Default is 'all'.\n" "--vlan-pvid v : Sets the Port VLAN Identifier. Defaults to 1.\n" -#if P2MP "\n" "Multi-Client Server options (when --mode server is used):\n" "--server network netmask : Helper option to easily configure server mode.\n" @@ -456,7 +458,7 @@ static const char usage_message[] = " OTP based two-factor auth mechanisms are in use and\n" " --reneg-* options are enabled. Optionally a lifetime in seconds\n" " for generated tokens can be set.\n" - "--opt-verify : Clients that connect with options that are incompatible\n" + "--opt-verify : (DEPRECATED) Clients that connect with options that are incompatible\n" " with those of the server will be disconnected.\n" "--auth-user-pass-optional : Allow connections by clients that don't\n" " specify a username/password.\n" @@ -478,6 +480,7 @@ static const char usage_message[] = " as well as pushes it to connecting clients.\n" "--learn-address cmd : Run command cmd to validate client virtual addresses.\n" "--connect-freq n s : Allow a maximum of n new connections per s seconds.\n" + "--connect-freq-initial n s : Allow a maximum of n replies for initial connections attempts per s seconds.\n" "--max-clients n : Allow a maximum of n simultaneously connected clients.\n" "--max-routes-per-client n : Allow a maximum of n internal routes per client.\n" "--stale-routes-check n [t] : Remove routes with a last activity timestamp\n" @@ -507,6 +510,16 @@ static const char usage_message[] = " ignore or reject causes the option to be allowed, removed or\n" " rejected with error. May be specified multiple times, and\n" " each filter is applied in the order of appearance.\n" + "--dns server