service_identity-18.1.0/0000755000076500000240000000000013401744623015417 5ustar hynekstaff00000000000000service_identity-18.1.0/.coveragerc0000644000076500000240000000033012610700035017522 0ustar hynekstaff00000000000000[run] branch = True source = service_identity [paths] source = src/service_identity .tox/*/lib/python*/site-packages/service_identity .tox/pypy*/site-packages/service_identity [report] show_missing = True service_identity-18.1.0/.pre-commit-config.yaml0000644000076500000240000000132413401717306021676 0ustar hynekstaff00000000000000repos: - repo: https://github.com/ambv/black rev: 18.9b0 hooks: - id: black language_version: python3.7 # override until resolved: https://github.com/ambv/black/issues/402 files: \.pyi?$ types: [] - repo: https://github.com/asottile/seed-isort-config rev: v1.5.0 hooks: - id: seed-isort-config - repo: https://github.com/pre-commit/mirrors-isort rev: v4.3.4 hooks: - id: isort language_version: python3.7 - repo: https://github.com/pre-commit/pre-commit-hooks rev: v2.0.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: debug-statements - id: flake8 language_version: python3.7 service_identity-18.1.0/.travis.yml0000644000076500000240000000401613401736544017534 0ustar hynekstaff00000000000000dist: xenial group: travis_latest sudo: false cache: directories: - $HOME/.cache/pip language: python matrix: fast_finish: true include: # lint - python: "3.7" stage: lint env: TOXENV=lint - python: "3.7" env: TOXENV=manifest # test - python: "2.7" stage: test env: TOXENV=py27 - python: "3.7" env: TOXENV=py37 - python: "2.7" env: TOXENV=py27-pyopenssl014-idna - python: "2.7" env: TOXENV=py27-pyopensslLatest-idna - python: "2.7" env: TOXENV=py27-pyopensslLatest-noidna - python: "3.4" env: TOXENV=py34-pyopenssl014-idna - python: "3.4" env: TOXENV=py34-pyopensslLatest-idna - python: "3.5" env: TOXENV=py35-pyopenssl014-idna - python: "3.5" env: TOXENV=py35-pyopensslLatest-idna - python: "3.6" env: TOXENV=py36-pyopenssl014-idna - python: "3.6" env: TOXENV=py36-pyopensslLatest-idna - python: "3.6" env: TOXENV=py36-pyopensslLatest-noidna - python: "3.7" env: TOXENV=py37-pyopenssl014-idna - python: "3.7" env: TOXENV=py37-pyopensslLatest-idna - python: "3.7" env: TOXENV=py37-pyopensslLatest-noidna - python: "pypy" dist: trusty env: TOXENV=pypy - python: "pypy3" dist: trusty env: TOXENV=pypy3 - python: "pypy" dist: trusty env: TOXENV=pypy-pyopensslLatest-idna - python: "pypy3" dist: trusty env: TOXENV=pypy3-pyopensslLatest-idna # Prevent breakage by a new releases - python: "3.6-dev" env: TOXENV=py36-pyopensslLatest-idna - python: "3.7-dev" env: TOXENV=py37-pyopensslLatest-idna # Docs - python: "3.7" stage: docs env: TOXENV=docs - python: "3.7" env: TOXENV=pypi-description allow_failures: - python: "3.6-dev" - python: "3.7-dev" install: - pip install -U tox script: - tox before_install: - pip install codecov after_success: - tox -e coverage-report - codecov notifications: email: false service_identity-18.1.0/AUTHORS.rst0000644000076500000240000000047312661320343017276 0ustar hynekstaff00000000000000Authors ======= ``service_identity`` is written and maintained by `Hynek Schlawack `_. The development is kindly supported by `Variomedia AG `_. Other contributors can be found in `GitHub's overview `_. service_identity-18.1.0/CHANGELOG.rst0000644000076500000240000001045513401740452017441 0ustar hynekstaff00000000000000.. :changelog: Changelog ========= Versions follow `CalVer `_ with a strict backwards compatibility policy. The third digit is only for regressions. 18.1.0 (2018-12-05) ------------------- Changes: ^^^^^^^^ - pyOpenSSL is optional now if you use ``service_identity.cryptography.*`` only. - Added support for ``iPAddress`` ``subjectAltName``\ s. You can now verify whether a connection or a certificate is valid for an IP address using ``service_identity.pyopenssl.verify_ip_address()`` and ``service_identity.cryptography.verify_certificate_ip_address()``. `#12 `_ ---- 17.0.0 (2017-05-23) ------------------- Deprecations: ^^^^^^^^^^^^^ - Since Chrome 58 and Firefox 48 both don't accept certificates that contain only a Common Name, its usage is hereby deprecated in ``service_identity`` too. We have been raising a warning since 16.0.0 and the support will be removed in mid-2018 for good. Changes: ^^^^^^^^ - When ``service_identity.SubjectAltNameWarning`` is raised, the Common Name of the certificate is now included in the warning message. `#17 `_ - Added ``cryptography.x509`` backend for verifying certificates. `#18 `_ - Wildcards (``*``) are now only allowed if they are the leftmost label in a certificate. This is common practice by all major browsers. `#19 `_ ---- 16.0.0 (2016-02-18) ------------------- Backward-incompatible changes: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - Python 3.3 and 2.6 aren't supported anymore. They may work by chance but any effort to keep them working has ceased. The last Python 2.6 release was on October 29, 2013 and isn't supported by the CPython core team anymore. Major Python packages like Django and Twisted dropped Python 2.6 a while ago already. Python 3.3 never had a significant user base and wasn't part of any distribution's LTS release. - pyOpenSSL versions older than 0.14 are not tested anymore. They don't even build on recent OpenSSL versions. Please note that its support may break without further notice. Changes: ^^^^^^^^ - Officially support Python 3.5. - ``service_identity.SubjectAltNameWarning`` is now raised if the server certicate lacks a proper ``SubjectAltName``. `#9 `_ - Add a ``__str__`` method to ``VerificationError``. - Port from ``characteristic`` to its spiritual successor `attrs `_. ---- 14.0.0 (2014-08-22) ------------------- Changes: ^^^^^^^^ - Switch to year-based version numbers. - Port to ``characteristic`` 14.0 (get rid of deprecation warnings). - Package docs with sdist. ---- 1.0.0 (2014-06-15) ------------------ Backward-incompatible changes: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - Drop support for Python 3.2. There is no justification to add complexity and unnecessary function calls for a Python version that `nobody uses `_. Changes: ^^^^^^^^ - Move into the `Python Cryptography Authority’s GitHub account `_. - Move exceptions into ``service_identity.exceptions`` so tracebacks don’t contain private module names. - Promoting to stable since Twisted 14.0 is optionally depending on ``service_identity`` now. - Use `characteristic `_ instead of a home-grown solution. - ``idna`` 0.6 did some backward-incompatible fixes that broke Python 3 support. This has been fixed now therefore ``service_identity`` only works with ``idna`` 0.6 and later. Unfortunately since ``idna`` doesn’t offer version introspection, ``service_identity`` can’t warn about it. ---- 0.2.0 (2014-04-06) ------------------ Backward-incompatible changes: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - Refactor into a multi-module package. Most notably, ``verify_hostname`` and ``extract_ids`` live in the ``service_identity.pyopenssl`` module now. - ``verify_hostname`` now takes an ``OpenSSL.SSL.Connection`` for the first argument. Changes: ^^^^^^^^ - Less false positives in IP address detection. - Officially support Python 3.4 too. - More strict checks for URI_IDs. ---- 0.1.0 (2014-03-03) ------------------ Initial release. service_identity-18.1.0/LICENSE0000644000076500000240000000204312301370045016412 0ustar hynekstaff00000000000000Copyright (c) 2014 Hynek Schlawack 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. service_identity-18.1.0/MANIFEST.in0000644000076500000240000000035213401721625017152 0ustar hynekstaff00000000000000include LICENSE .coveragerc .travis.yml .pre-commit-config.yaml tox.ini pyproject.toml include docs/Makefile docs/conf.py include *.rst *.txt exclude conftest.py .readthedocs.yml recursive-include docs *.rst prune tests prune .github service_identity-18.1.0/PKG-INFO0000644000076500000240000001150413401744623016515 0ustar hynekstaff00000000000000Metadata-Version: 2.1 Name: service_identity Version: 18.1.0 Summary: Service identity verification for pyOpenSSL & cryptography. Home-page: https://service-identity.readthedocs.io/ Author: Hynek Schlawack Author-email: hs@ox.cx Maintainer: Hynek Schlawack Maintainer-email: hs@ox.cx License: MIT Description: ============================= Service Identity Verification ============================= .. image:: https://readthedocs.org/projects/service-identity/badge/?version=stable :target: https://service-identity.readthedocs.io/en/stable/?badge=stable :alt: Documentation Status .. image:: https://travis-ci.org/pyca/service_identity.svg?branch=master :target: https://travis-ci.org/pyca/service_identity :alt: CI status .. image:: https://codecov.io/github/pyca/service_identity/branch/master/graph/badge.svg :target: https://codecov.io/github/pyca/service_identity :alt: Test Coverage .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black :alt: Code style: black .. image:: https://www.irccloud.com/invite-svg?channel=%23cryptography-dev&hostname=irc.freenode.net&port=6697&ssl=1 :target: https://www.irccloud.com/invite?channel=%23cryptography-dev&hostname=irc.freenode.net&port=6697&ssl=1 .. begin Use this package if: - you use pyOpenSSL_ and don’t want to be MITM_\ ed or - if you want to verify that a `PyCA cryptography`_ certificate is valid for a certain hostname or IP address. ``service_identity`` aspires to give you all the tools you need for verifying whether a certificate is valid for the intended purposes. In the simplest case, this means *host name verification*. However, ``service_identity`` implements `RFC 6125`_ fully and plans to add other relevant RFCs too. ``service_identity``\ ’s documentation lives at `Read the Docs `_, the code on `GitHub `_. .. _Twisted: https://twistedmatrix.com/ .. _pyOpenSSL: https://pypi.org/project/pyOpenSSL/ .. _MITM: https://en.wikipedia.org/wiki/Man-in-the-middle_attack .. _RFC 6125: https://www.rfc-editor.org/info/rfc6125 .. _PyCA cryptography: https://cryptography.io/ Release Information =================== 18.1.0 (2018-12-05) ------------------- Changes: ^^^^^^^^ - pyOpenSSL is optional now if you use ``service_identity.cryptography.*`` only. - Added support for ``iPAddress`` ``subjectAltName``\ s. You can now verify whether a connection or a certificate is valid for an IP address using ``service_identity.pyopenssl.verify_ip_address()`` and ``service_identity.cryptography.verify_certificate_ip_address()``. `#12 `_ `Full changelog `_. Authors ======= ``service_identity`` is written and maintained by `Hynek Schlawack `_. The development is kindly supported by `Variomedia AG `_. Other contributors can be found in `GitHub's overview `_. Keywords: cryptography,openssl,pyopenssl Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Natural Language :: English Classifier: Operating System :: MacOS :: MacOS X Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: POSIX :: BSD Classifier: Operating System :: POSIX :: Linux Classifier: Operating System :: POSIX Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Programming Language :: Python Classifier: Topic :: Security :: Cryptography Classifier: Topic :: Software Development :: Libraries :: Python Modules Provides-Extra: tests Provides-Extra: dev Provides-Extra: docs Provides-Extra: idna service_identity-18.1.0/README.rst0000644000076500000240000000362013401724003017075 0ustar hynekstaff00000000000000============================= Service Identity Verification ============================= .. image:: https://readthedocs.org/projects/service-identity/badge/?version=stable :target: https://service-identity.readthedocs.io/en/stable/?badge=stable :alt: Documentation Status .. image:: https://travis-ci.org/pyca/service_identity.svg?branch=master :target: https://travis-ci.org/pyca/service_identity :alt: CI status .. image:: https://codecov.io/github/pyca/service_identity/branch/master/graph/badge.svg :target: https://codecov.io/github/pyca/service_identity :alt: Test Coverage .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black :alt: Code style: black .. image:: https://www.irccloud.com/invite-svg?channel=%23cryptography-dev&hostname=irc.freenode.net&port=6697&ssl=1 :target: https://www.irccloud.com/invite?channel=%23cryptography-dev&hostname=irc.freenode.net&port=6697&ssl=1 .. begin Use this package if: - you use pyOpenSSL_ and don’t want to be MITM_\ ed or - if you want to verify that a `PyCA cryptography`_ certificate is valid for a certain hostname or IP address. ``service_identity`` aspires to give you all the tools you need for verifying whether a certificate is valid for the intended purposes. In the simplest case, this means *host name verification*. However, ``service_identity`` implements `RFC 6125`_ fully and plans to add other relevant RFCs too. ``service_identity``\ ’s documentation lives at `Read the Docs `_, the code on `GitHub `_. .. _Twisted: https://twistedmatrix.com/ .. _pyOpenSSL: https://pypi.org/project/pyOpenSSL/ .. _MITM: https://en.wikipedia.org/wiki/Man-in-the-middle_attack .. _RFC 6125: https://www.rfc-editor.org/info/rfc6125 .. _PyCA cryptography: https://cryptography.io/ service_identity-18.1.0/docs/0000755000076500000240000000000013401744623016347 5ustar hynekstaff00000000000000service_identity-18.1.0/docs/Makefile0000644000076500000240000001522212343051253020003 0ustar hynekstaff00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/service_identity.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/service_identity.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/service_identity" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/service_identity" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." service_identity-18.1.0/docs/api.rst0000644000076500000240000000363713401717150017656 0ustar hynekstaff00000000000000=== API === .. note:: So far, public APIs are only available for hostnames (RFC 6125) and IP addresses (RFC 2818). All IDs specified by RFC 6125 are already implemented though. If you'd like to play with them and provide feedback have a look at the ``verify_service_identity`` function in the `_common module `_. pyOpenSSL ========= .. currentmodule:: service_identity.pyopenssl .. autofunction:: verify_hostname In practice, this may look like the following:: from __future__ import absolute_import, division, print_function import socket from OpenSSL import SSL from service_identity import VerificationError from service_identity.pyopenssl import verify_hostname ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.set_verify(SSL.VERIFY_PEER, lambda conn, cert, errno, depth, ok: ok) ctx.set_default_verify_paths() hostname = u"twistedmatrix.com" conn = SSL.Connection(ctx, socket.socket(socket.AF_INET, socket.SOCK_STREAM)) conn.connect((hostname, 443)) try: conn.do_handshake() verify_hostname(conn, hostname) # Do your super-secure stuff here. except SSL.Error as e: print("TLS Handshake failed: {0!r}.".format(e.args[0])) except VerificationError: print("Presented certificate is not valid for {0}.".format(hostname)) finally: conn.shutdown() conn.close() .. autofunction:: verify_ip_address PyCA cryptography ================= .. currentmodule:: service_identity.cryptography .. autofunction:: verify_certificate_hostname .. autofunction:: verify_certificate_ip_address Universal Errors and Warnings ============================= .. currentmodule:: service_identity .. autoexception:: VerificationError .. autoexception:: CertificateError .. autoexception:: SubjectAltNameWarning service_identity-18.1.0/docs/backward-compatibility.rst0000644000076500000240000000063312617322020023517 0ustar hynekstaff00000000000000Backward Compatibility ====================== ``service_identity`` has a very strong backward compatibility policy. Generally speaking, you shouldn't ever be afraid of updating. If breaking changes are needed do be done, they are: #. …announced in the :doc:`changelog`. #. …the old behavior raises a :exc:`DeprecationWarning` for a year. #. …are done with another announcement in the :doc:`changelog`. service_identity-18.1.0/docs/changelog.rst0000644000076500000240000000003613401717327021030 0ustar hynekstaff00000000000000.. include:: ../CHANGELOG.rst service_identity-18.1.0/docs/conf.py0000644000076500000240000002263613401724155017655 0ustar hynekstaff00000000000000# -*- coding: utf-8 -*- # # service_identity documentation build configuration file, created by # sphinx-quickstart on Mon Jun 2 16:32:11 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import codecs import datetime import os import re def read(*parts): """ Build an absolute path from *parts* and and return the contents of the resulting file. Assume UTF-8 encoding. """ here = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(here, *parts), "rb", "utf-8") as f: return f.read() def find_version(*file_paths): """ Build a path from *file_paths* and search for a ``__version__`` string inside. """ version_file = read(*file_paths) version_match = re.search( r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M ) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.") # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.doctest", "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "sphinx.ext.todo", "sphinx.ext.coverage", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix of source filenames. source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # General information about the project. project = u"service_identity" year = datetime.date.today().year copyright = u"2014, Hynek Schlawack" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # release = find_version("..", "src", "service_identity", "__init__.py") version = release.rsplit(u".", 1)[0] # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build"] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "alabaster" html_theme_options = { "font_family": '"Avenir Next", Calibri, "PT Sans", sans-serif', "head_font_family": '"Avenir Next", Calibri, "PT Sans", sans-serif', "font_size": "18px", "page_width": "980px", "show_relbars": True, } # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "service_identitydoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = {} # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ( "index", "service_identity.tex", u"service\\_identity Documentation", u"Hynek Schlawack", "manual", ) ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ( "index", "service_identity", u"service_identity Documentation", [u"Hynek Schlawack"], 1, ) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( "index", "service_identity", u"service_identity Documentation", u"Hynek Schlawack", "service_identity", "Service Identity Verification for pyOpenSSL", "Miscellaneous", ) ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { "https://docs.python.org/3/": None, "https://pyopenssl.readthedocs.io/en/stable": None, "https://cryptography.io/en/stable/": None, } service_identity-18.1.0/docs/contributing.rst0000644000076500000240000000015113401723732021603 0ustar hynekstaff00000000000000.. _contributing: .. include:: ../.github/CONTRIBUTING.rst .. include:: ../.github/CODE_OF_CONDUCT.rst service_identity-18.1.0/docs/implemented-standards.rst0000644000076500000240000000112713401717150023361 0ustar hynekstaff00000000000000===================== Implemented Standards ===================== Present ======= - ``dNSName`` with fallback to ``CN`` (DNS-ID, aka host names, `RFC 6125`_). - ``iPAddress`` (`RFC 2818`_). - ``uniformResourceIdentifier`` (URI-ID, `RFC 6125`_). - SRV-ID (`RFC 6125`_) Future ====== - ``xmppAddr`` (`RFC 3920`_). - ``nameConstraints`` extensions (`RFC 3280`_). .. _`RFC 2818`: https://tools.ietf.org/search/rfc2818 .. _`RFC 3280`: https://tools.ietf.org/search/rfc3280#section-4.2.1.11 .. _`RFC 3920`: https://tools.ietf.org/search/rfc3920 .. _`RFC 6125`: https://tools.ietf.org/search/rfc6125 service_identity-18.1.0/docs/index.rst0000644000076500000240000000113513237767400020215 0ustar hynekstaff00000000000000========================================================== Service Identity Verification for pyOpenSSL & cryptography ========================================================== Release v\ |release| (:doc:`What's new? `). .. include:: ../README.rst :start-after: begin User's Guide ============ .. toctree:: :maxdepth: 1 installation implemented-standards api Project Information ------------------- .. toctree:: :maxdepth: 1 backward-compatibility license contributing changelog Indices and tables ================== * :ref:`genindex` * :ref:`search` service_identity-18.1.0/docs/installation.rst0000644000076500000240000000255713401723407021610 0ustar hynekstaff00000000000000============================= Installation and Requirements ============================= Installation ============ ``$ pip install service_identity`` Requirements ============ Python 2.7, 3.4 and later, as well as PyPy are supported. Additionally, the following PyPI packages are required: - attrs_ - pyOpenSSL_ ``>= 0.14`` (``0.12`` and ``0.13`` may work but are not part of CI anymore) - pyasn1_ - pyasn1-modules_ - ipaddress_ on Python 2.7 Optionally, idna_ ``>= 0.6`` can be used for `internationalized domain names`_ (IDN), i.e. non-ASCII domains. Unfortunately it’s required because Python’s IDN support in the standard library is outdated_ even in the latest releases. If you need Python 3.2 support, you will have to use the latest 0.2.x release. If you need Python 2.6 or 3.3 support, you will have to use the latest 14.0.x release. They will receive bug fix releases if necessary but other than that no further development is planned. .. _attrs: https://www.attrs.org/ .. _pyOpenSSL: https://pypi.org/project/pyOpenSSL/ .. _pyasn1-modules: https://pypi.org/project/pyasn1-modules/ .. _pyasn1: https://pypi.org/project/pyasn1/ .. _`internationalized domain names`: https://en.wikipedia.org/wiki/Internationalized_domain_name .. _idna: https://pypi.org/project/idna/ .. _outdated: https://bugs.python.org/issue17305 .. _ipaddress: https://pypi.org/project/ipaddress/ service_identity-18.1.0/docs/license.rst0000644000076500000240000000043513111102223020503 0ustar hynekstaff00000000000000License ======= ``service_identity`` is licensed under the `MIT `_ license. The full license text can be also found in the `source code repository `_. .. include:: ../AUTHORS.rst service_identity-18.1.0/pyproject.toml0000644000076500000240000000012213401717346020330 0ustar hynekstaff00000000000000[build-system] requires = ["setuptools", "wheel"] [tool.black] line-length = 79 service_identity-18.1.0/setup.cfg0000644000076500000240000000102113401744623017232 0ustar hynekstaff00000000000000[tool:pytest] minversion = 3.0 strict = true addopts = -ra testpaths = tests filterwarnings = once::Warning [bdist_wheel] universal = 1 [metadata] license_file = LICENSE [isort] atomic = true force_grid_wrap = 0 include_trailing_comma = true lines_after_imports = 2 lines_between_types = 1 multi_line_output = 3 not_skip = __init__.py use_parentheses = true known_first_party = service_identity known_third_party = OpenSSL,attr,cryptography,pyasn1,pyasn1_modules,pytest,setuptools,six [egg_info] tag_build = tag_date = 0 service_identity-18.1.0/setup.py0000644000076500000240000000673513401731715017142 0ustar hynekstaff00000000000000import codecs import os import re from setuptools import find_packages, setup ############################################################################### NAME = "service_identity" KEYWORDS = ["cryptography", "openssl", "pyopenssl"] CLASSIFIERS = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX :: BSD", "Operating System :: POSIX :: Linux", "Operating System :: POSIX", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Programming Language :: Python", "Topic :: Security :: Cryptography", "Topic :: Software Development :: Libraries :: Python Modules", ] INSTALL_REQUIRES = [ "attrs>=16.0.0", "ipaddress; python_version<'3.3'", "pyasn1-modules", # Place pyasn1 after pyasn1-modules to workaround setuptools install bug: # https://github.com/pypa/setuptools/issues/498 "pyasn1", "cryptography", ] EXTRAS_REQUIRE = { "idna": ["idna"], "tests": ["coverage>=4.2.0", "pytest"], "docs": ["sphinx"], } EXTRAS_REQUIRE["dev"] = ( EXTRAS_REQUIRE["tests"] + EXTRAS_REQUIRE["docs"] + ["idna", "pyOpenSSL"] ) ############################################################################### HERE = os.path.abspath(os.path.dirname(__file__)) PACKAGES = find_packages(where="src") META_PATH = os.path.join(HERE, "src", NAME, "__init__.py") def read(*parts): """ Build an absolute path from *parts* and and return the contents of the resulting file. Assume UTF-8 encoding. """ with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f: return f.read() META_FILE = read(META_PATH) def find_meta(meta): """ Extract __*meta*__ from META_FILE. """ meta_match = re.search( r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M ) if meta_match: return meta_match.group(1) raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta)) URI = find_meta("uri") LONG = ( read("README.rst") + "\n\n" + "Release Information\n" + "===================\n\n" + re.search( r"(\d{2}.\d.\d \(.*?\)\n.*?)\n\n\n----\n\n\n", read("CHANGELOG.rst"), re.S, ).group(1) + "\n\n`Full changelog " + "<{uri}en/stable/changelog.html>`_.\n\n" + read("AUTHORS.rst") ).format(uri=URI) if __name__ == "__main__": setup( name=NAME, description=find_meta("description"), license=find_meta("license"), url=URI, version=find_meta("version"), author=find_meta("author"), author_email=find_meta("email"), maintainer=find_meta("author"), maintainer_email=find_meta("email"), keywords=KEYWORDS, long_description=LONG, packages=PACKAGES, package_dir={"": "src"}, zip_safe=False, classifiers=CLASSIFIERS, install_requires=INSTALL_REQUIRES, extras_require=EXTRAS_REQUIRE, ) service_identity-18.1.0/src/0000755000076500000240000000000013401744623016206 5ustar hynekstaff00000000000000service_identity-18.1.0/src/service_identity/0000755000076500000240000000000013401744623021557 5ustar hynekstaff00000000000000service_identity-18.1.0/src/service_identity/__init__.py0000644000076500000240000000126213401740452023665 0ustar hynekstaff00000000000000""" Verify service identities. """ from __future__ import absolute_import, division, print_function from . import cryptography, pyopenssl from .exceptions import ( CertificateError, SubjectAltNameWarning, VerificationError, ) __version__ = "18.1.0" __title__ = "service_identity" __description__ = "Service identity verification for pyOpenSSL & cryptography." __uri__ = "https://service-identity.readthedocs.io/" __author__ = "Hynek Schlawack" __email__ = "hs@ox.cx" __license__ = "MIT" __copyright__ = "Copyright (c) 2014 Hynek Schlawack" __all__ = [ "CertificateError", "SubjectAltNameWarning", "VerificationError", "cryptography", "pyopenssl", ] service_identity-18.1.0/src/service_identity/_common.py0000644000076500000240000002702413401717326023565 0ustar hynekstaff00000000000000""" Common verification code. """ from __future__ import absolute_import, division, print_function import ipaddress import re import attr from ._compat import maketrans, text_type from .exceptions import ( CertificateError, DNSMismatch, IPAddressMismatch, SRVMismatch, URIMismatch, VerificationError, ) try: import idna except ImportError: # pragma: nocover idna = None @attr.s(slots=True) class ServiceMatch(object): """ A match of a service id and a certificate pattern. """ service_id = attr.ib() cert_pattern = attr.ib() def verify_service_identity(cert_patterns, obligatory_ids, optional_ids): """ Verify whether *cert_patterns* are valid for *obligatory_ids* and *optional_ids*. *obligatory_ids* must be both present and match. *optional_ids* must match if a pattern of the respective type is present. """ errors = [] matches = _find_matches(cert_patterns, obligatory_ids) + _find_matches( cert_patterns, optional_ids ) matched_ids = [match.service_id for match in matches] for i in obligatory_ids: if i not in matched_ids: errors.append(i.error_on_mismatch(mismatched_id=i)) for i in optional_ids: # If an optional ID is not matched by a certificate pattern *but* there # is a pattern of the same type , it is an error and the verification # fails. Example: the user passes a SRV-ID for "_mail.domain.com" but # the certificate contains an SRV-Pattern for "_xmpp.domain.com". if i not in matched_ids and _contains_instance_of( cert_patterns, i.pattern_class ): errors.append(i.error_on_mismatch(mismatched_id=i)) if errors: raise VerificationError(errors=errors) return matches def _find_matches(cert_patterns, service_ids): """ Search for matching certificate patterns and service_ids. :param cert_ids: List certificate IDs like DNSPattern. :type cert_ids: `list` :param service_ids: List of service IDs like DNS_ID. :type service_ids: `list` :rtype: `list` of `ServiceMatch` """ matches = [] for sid in service_ids: for cid in cert_patterns: if sid.verify(cid): matches.append(ServiceMatch(cert_pattern=cid, service_id=sid)) return matches def _contains_instance_of(seq, cl): """ :type seq: iterable :type cl: type :rtype: bool """ for e in seq: if isinstance(e, cl): return True return False def _is_ip_address(pattern): """ Check whether *pattern* could be/match an IP address. :param pattern: A pattern for a host name. :type pattern: `bytes` or `unicode` :return: `True` if *pattern* could be an IP address, else `False`. :rtype: bool """ if isinstance(pattern, bytes): try: pattern = pattern.decode("ascii") except UnicodeError: return False try: int(pattern) return True except ValueError: pass try: ipaddress.ip_address(pattern.replace("*", "1")) except ValueError: return False return True @attr.s(init=False, slots=True) class DNSPattern(object): """ A DNS pattern as extracted from certificates. """ pattern = attr.ib() _RE_LEGAL_CHARS = re.compile(br"^[a-z0-9\-_.]+$") def __init__(self, pattern): """ :type pattern: `bytes` """ if not isinstance(pattern, bytes): raise TypeError("The DNS pattern must be a bytes string.") pattern = pattern.strip() if pattern == b"" or _is_ip_address(pattern) or b"\0" in pattern: raise CertificateError( "Invalid DNS pattern {0!r}.".format(pattern) ) self.pattern = pattern.translate(_TRANS_TO_LOWER) if b"*" in self.pattern: _validate_pattern(self.pattern) @attr.s(slots=True) class IPAddressPattern(object): """ An IP address pattern as extracted from certificates. """ pattern = attr.ib() @classmethod def from_bytes(cls, bs): try: return cls(pattern=ipaddress.ip_address(bs)) except ValueError: raise CertificateError( "Invalid IP address pattern {!r}.".format(bs) ) @attr.s(init=False, slots=True) class URIPattern(object): """ An URI pattern as extracted from certificates. """ protocol_pattern = attr.ib() dns_pattern = attr.ib() def __init__(self, pattern): """ :type pattern: `bytes` """ if not isinstance(pattern, bytes): raise TypeError("The URI pattern must be a bytes string.") pattern = pattern.strip().translate(_TRANS_TO_LOWER) if b":" not in pattern or b"*" in pattern or _is_ip_address(pattern): raise CertificateError( "Invalid URI pattern {0!r}.".format(pattern) ) self.protocol_pattern, hostname = pattern.split(b":") self.dns_pattern = DNSPattern(hostname) @attr.s(init=False, slots=True) class SRVPattern(object): """ An SRV pattern as extracted from certificates. """ name_pattern = attr.ib() dns_pattern = attr.ib() def __init__(self, pattern): """ :type pattern: `bytes` """ if not isinstance(pattern, bytes): raise TypeError("The SRV pattern must be a bytes string.") pattern = pattern.strip().translate(_TRANS_TO_LOWER) if ( pattern[0] != b"_"[0] or b"." not in pattern or b"*" in pattern or _is_ip_address(pattern) ): raise CertificateError( "Invalid SRV pattern {0!r}.".format(pattern) ) name, hostname = pattern.split(b".", 1) self.name_pattern = name[1:] self.dns_pattern = DNSPattern(hostname) @attr.s(init=False, slots=True) class DNS_ID(object): """ A DNS service ID, aka hostname. """ hostname = attr.ib() # characters that are legal in a normalized hostname _RE_LEGAL_CHARS = re.compile(br"^[a-z0-9\-_.]+$") pattern_class = DNSPattern error_on_mismatch = DNSMismatch def __init__(self, hostname): """ :type hostname: `unicode` """ if not isinstance(hostname, text_type): raise TypeError("DNS-ID must be a unicode string.") hostname = hostname.strip() if hostname == u"" or _is_ip_address(hostname): raise ValueError("Invalid DNS-ID.") if any(ord(c) > 127 for c in hostname): if idna: ascii_id = idna.encode(hostname) else: raise ImportError( "idna library is required for non-ASCII IDs." ) else: ascii_id = hostname.encode("ascii") self.hostname = ascii_id.translate(_TRANS_TO_LOWER) if self._RE_LEGAL_CHARS.match(self.hostname) is None: raise ValueError("Invalid DNS-ID.") def verify(self, pattern): """ https://tools.ietf.org/search/rfc6125#section-6.4 """ if isinstance(pattern, self.pattern_class): return _hostname_matches(pattern.pattern, self.hostname) else: return False @attr.s(slots=True) class IPAddress_ID(object): """ An IP address service ID. """ ip = attr.ib(converter=ipaddress.ip_address) pattern_class = IPAddressPattern error_on_mismatch = IPAddressMismatch def verify(self, pattern): """ https://tools.ietf.org/search/rfc2818#section-3.1 """ return self.ip == pattern.pattern @attr.s(init=False, slots=True) class URI_ID(object): """ An URI service ID. """ protocol = attr.ib() dns_id = attr.ib() pattern_class = URIPattern error_on_mismatch = URIMismatch def __init__(self, uri): """ :type uri: `unicode` """ if not isinstance(uri, text_type): raise TypeError("URI-ID must be a unicode string.") uri = uri.strip() if u":" not in uri or _is_ip_address(uri): raise ValueError("Invalid URI-ID.") prot, hostname = uri.split(u":") self.protocol = prot.encode("ascii").translate(_TRANS_TO_LOWER) self.dns_id = DNS_ID(hostname.strip(u"/")) def verify(self, pattern): """ https://tools.ietf.org/search/rfc6125#section-6.5.2 """ if isinstance(pattern, self.pattern_class): return ( pattern.protocol_pattern == self.protocol and self.dns_id.verify(pattern.dns_pattern) ) else: return False @attr.s(init=False, slots=True) class SRV_ID(object): """ An SRV service ID. """ name = attr.ib() dns_id = attr.ib() pattern_class = SRVPattern error_on_mismatch = SRVMismatch def __init__(self, srv): """ :type srv: `unicode` """ if not isinstance(srv, text_type): raise TypeError("SRV-ID must be a unicode string.") srv = srv.strip() if u"." not in srv or _is_ip_address(srv) or srv[0] != u"_": raise ValueError("Invalid SRV-ID.") name, hostname = srv.split(u".", 1) self.name = name[1:].encode("ascii").translate(_TRANS_TO_LOWER) self.dns_id = DNS_ID(hostname) def verify(self, pattern): """ https://tools.ietf.org/search/rfc6125#section-6.5.1 """ if isinstance(pattern, self.pattern_class): return self.name == pattern.name_pattern and self.dns_id.verify( pattern.dns_pattern ) else: return False def _hostname_matches(cert_pattern, actual_hostname): """ :type cert_pattern: `bytes` :type actual_hostname: `bytes` :return: `True` if *cert_pattern* matches *actual_hostname*, else `False`. :rtype: `bool` """ if b"*" in cert_pattern: cert_head, cert_tail = cert_pattern.split(b".", 1) actual_head, actual_tail = actual_hostname.split(b".", 1) if cert_tail != actual_tail: return False # No patterns for IDNA if actual_head.startswith(b"xn--"): return False return cert_head == b"*" or cert_head == actual_head else: return cert_pattern == actual_hostname def _validate_pattern(cert_pattern): """ Check whether the usage of wildcards within *cert_pattern* conforms with our expectations. :type hostname: `bytes` :return: None """ cnt = cert_pattern.count(b"*") if cnt > 1: raise CertificateError( "Certificate's DNS-ID {0!r} contains too many wildcards.".format( cert_pattern ) ) parts = cert_pattern.split(b".") if len(parts) < 3: raise CertificateError( "Certificate's DNS-ID {0!r} has too few host components for " "wildcard usage.".format(cert_pattern) ) # We assume there will always be only one wildcard allowed. if b"*" not in parts[0]: raise CertificateError( "Certificate's DNS-ID {0!r} has a wildcard outside the left-most " "part.".format(cert_pattern) ) if any(not len(p) for p in parts): raise CertificateError( "Certificate's DNS-ID {0!r} contains empty parts.".format( cert_pattern ) ) # Ensure no locale magic interferes. _TRANS_TO_LOWER = maketrans( b"ABCDEFGHIJKLMNOPQRSTUVWXYZ", b"abcdefghijklmnopqrstuvwxyz" ) service_identity-18.1.0/src/service_identity/_compat.py0000644000076500000240000000046413401717326023557 0ustar hynekstaff00000000000000""" Avoid depending on any particular Python 3 compatibility approach. """ import sys PY3 = sys.version_info[0] == 3 if PY3: # pragma: nocover maketrans = bytes.maketrans text_type = str else: # pragma: nocover import string maketrans = string.maketrans text_type = unicode # noqa service_identity-18.1.0/src/service_identity/cryptography.py0000644000076500000240000001156113401740236024664 0ustar hynekstaff00000000000000""" `cryptography.x509 `_-specific code. """ from __future__ import absolute_import, division, print_function import warnings from cryptography.x509 import ( DNSName, ExtensionOID, IPAddress, NameOID, ObjectIdentifier, OtherName, UniformResourceIdentifier, ) from cryptography.x509.extensions import ExtensionNotFound from pyasn1.codec.der.decoder import decode from pyasn1.type.char import IA5String from ._common import ( DNS_ID, CertificateError, DNSPattern, IPAddress_ID, IPAddressPattern, SRVPattern, URIPattern, verify_service_identity, ) from .exceptions import SubjectAltNameWarning __all__ = ["verify_certificate_hostname"] def verify_certificate_hostname(certificate, hostname): """ Verify whether *certificate* is valid for *hostname*. .. note:: Nothing is verified about the *authority* of the certificate; the caller must verify that the certificate chains to an appropriate trust root themselves. :param cryptography.x509.Certificate certificate: A cryptography X509 certificate object. :param unicode hostname: The hostname that *certificate* should be valid for. :raises service_identity.VerificationError: If *certificate* is not valid for *hostname*. :raises service_identity.CertificateError: If *certificate* contains invalid/unexpected data. :returns: ``None`` """ verify_service_identity( cert_patterns=extract_ids(certificate), obligatory_ids=[DNS_ID(hostname)], optional_ids=[], ) def verify_certificate_ip_address(certificate, ip_address): """ Verify whether *certificate* is valid for *ip_address*. .. note:: Nothing is verified about the *authority* of the certificate; the caller must verify that the certificate chains to an appropriate trust root themselves. :param cryptography.x509.Certificate certificate: A cryptography X509 certificate object. :param unicode ip_address: The IP address that *connection* should be valid for. Can be an IPv4 or IPv6 address. :raises service_identity.VerificationError: If *certificate* is not valid for *ip_address*. :raises service_identity.CertificateError: If *certificate* contains invalid/unexpected data. :returns: ``None`` .. versionadded:: 18.1.0 """ verify_service_identity( cert_patterns=extract_ids(certificate), obligatory_ids=[IPAddress_ID(ip_address)], optional_ids=[], ) ID_ON_DNS_SRV = ObjectIdentifier("1.3.6.1.5.5.7.8.7") # id_on_dnsSRV def extract_ids(cert): """ Extract all valid IDs from a certificate for service verification. If *cert* doesn't contain any identifiers, the ``CN``s are used as DNS-IDs as fallback. :param cryptography.x509.Certificate cert: The certificate to be dissected. :return: List of IDs. """ ids = [] try: ext = cert.extensions.get_extension_for_oid( ExtensionOID.SUBJECT_ALTERNATIVE_NAME ) except ExtensionNotFound: pass else: ids.extend( [ DNSPattern(name.encode("utf-8")) for name in ext.value.get_values_for_type(DNSName) ] ) ids.extend( [ URIPattern(uri.encode("utf-8")) for uri in ext.value.get_values_for_type( UniformResourceIdentifier ) ] ) ids.extend( [ IPAddressPattern(ip) for ip in ext.value.get_values_for_type(IPAddress) ] ) for other in ext.value.get_values_for_type(OtherName): if other.type_id == ID_ON_DNS_SRV: srv, _ = decode(other.value) if isinstance(srv, IA5String): ids.append(SRVPattern(srv.asOctets())) else: # pragma: nocover raise CertificateError("Unexpected certificate content.") if not ids: # https://tools.ietf.org/search/rfc6125#section-6.4.4 # A client MUST NOT seek a match for a reference identifier of CN-ID if # the presented identifiers include a DNS-ID, SRV-ID, URI-ID, or any # application-specific identifier types supported by the client. cns = [ n.value for n in cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME) ] cn = next(iter(cns), b"") ids = [DNSPattern(n.encode("utf-8")) for n in cns] warnings.warn( "Certificate with CN {!r} has no `subjectAltName`, falling back " "to check for a `commonName` for now. This feature is being " "removed by major browsers and deprecated by RFC 2818.".format(cn), SubjectAltNameWarning, ) return ids service_identity-18.1.0/src/service_identity/exceptions.py0000644000076500000240000000236013401717326024313 0ustar hynekstaff00000000000000""" All exceptions and warnings thrown by ``service_identity``. Separated into an own package for nicer tracebacks, you should still import them from __init__.py. """ from __future__ import absolute_import, division, print_function import attr class SubjectAltNameWarning(DeprecationWarning): """ Server Certificate does not contain a ``SubjectAltName``. Hostname matching is performed on the ``CommonName`` which is deprecated. """ @attr.s class VerificationError(Exception): """ Service identity verification failed. """ errors = attr.ib() def __str__(self): return self.__repr__() @attr.s class DNSMismatch(object): """ No matching DNSPattern could be found. """ mismatched_id = attr.ib() @attr.s class SRVMismatch(object): """ No matching SRVPattern could be found. """ mismatched_id = attr.ib() @attr.s class URIMismatch(object): """ No matching URIPattern could be found. """ mismatched_id = attr.ib() @attr.s class IPAddressMismatch(object): """ No matching IPAddressPattern could be found. """ mismatched_id = attr.ib() class CertificateError(Exception): """ Certificate contains invalid or unexpected data. """ service_identity-18.1.0/src/service_identity/pyopenssl.py0000644000076500000240000001204213401740220024151 0ustar hynekstaff00000000000000""" `pyOpenSSL `_-specific code. """ from __future__ import absolute_import, division, print_function import warnings import six from pyasn1.codec.der.decoder import decode from pyasn1.type.char import IA5String from pyasn1.type.univ import ObjectIdentifier from pyasn1_modules.rfc2459 import GeneralNames from ._common import ( DNS_ID, CertificateError, DNSPattern, IPAddress_ID, IPAddressPattern, SRVPattern, URIPattern, verify_service_identity, ) from .exceptions import SubjectAltNameWarning __all__ = ["verify_hostname"] def verify_hostname(connection, hostname): """ Verify whether the certificate of *connection* is valid for *hostname*. :param OpenSSL.SSL.Connection connection: A pyOpenSSL connection object. :param unicode hostname: The hostname that *connection* should be connected to. :raises service_identity.VerificationError: If *connection* does not provide a certificate that is valid for *hostname*. :raises service_identity.CertificateError: If the certificate chain of *connection* contains a certificate that contains invalid/unexpected data. :returns: ``None`` """ verify_service_identity( cert_patterns=extract_ids(connection.get_peer_certificate()), obligatory_ids=[DNS_ID(hostname)], optional_ids=[], ) def verify_ip_address(connection, ip_address): """ Verify whether the certificate of *connection* is valid for *ip_address*. :param OpenSSL.SSL.Connection connection: A pyOpenSSL connection object. :param unicode ip_address: The IP address that *connection* should be connected to. Can be an IPv4 or IPv6 address. :raises service_identity.VerificationError: If *connection* does not provide a certificate that is valid for *ip_address*. :raises service_identity.CertificateError: If the certificate chain of *connection* contains a certificate that contains invalid/unexpected data. :returns: ``None`` .. versionadded:: 18.1.0 """ verify_service_identity( cert_patterns=extract_ids(connection.get_peer_certificate()), obligatory_ids=[IPAddress_ID(ip_address)], optional_ids=[], ) ID_ON_DNS_SRV = ObjectIdentifier("1.3.6.1.5.5.7.8.7") # id_on_dnsSRV def extract_ids(cert): """ Extract all valid IDs from a certificate for service verification. If *cert* doesn't contain any identifiers, the ``CN``s are used as DNS-IDs as fallback. :param OpenSSL.SSL.X509 cert: The certificate to be dissected. :return: List of IDs. """ ids = [] for i in six.moves.range(cert.get_extension_count()): ext = cert.get_extension(i) if ext.get_short_name() == b"subjectAltName": names, _ = decode(ext.get_data(), asn1Spec=GeneralNames()) for n in names: name_string = n.getName() if name_string == "dNSName": ids.append(DNSPattern(n.getComponent().asOctets())) elif name_string == "iPAddress": ids.append( IPAddressPattern.from_bytes( n.getComponent().asOctets() ) ) elif name_string == "uniformResourceIdentifier": ids.append(URIPattern(n.getComponent().asOctets())) elif name_string == "otherName": comp = n.getComponent() oid = comp.getComponentByPosition(0) if oid == ID_ON_DNS_SRV: srv, _ = decode(comp.getComponentByPosition(1)) if isinstance(srv, IA5String): ids.append(SRVPattern(srv.asOctets())) else: # pragma: nocover raise CertificateError( "Unexpected certificate content." ) else: # pragma: nocover pass else: # pragma: nocover pass if not ids: # https://tools.ietf.org/search/rfc6125#section-6.4.4 # A client MUST NOT seek a match for a reference identifier of CN-ID if # the presented identifiers include a DNS-ID, SRV-ID, URI-ID, or any # application-specific identifier types supported by the client. components = [ c[1] for c in cert.get_subject().get_components() if c[0] == b"CN" ] cn = next(iter(components), b"") ids = [DNSPattern(c) for c in components] warnings.warn( "Certificate with CN '%s' has no `subjectAltName`, falling back " "to check for a `commonName` for now. This feature is being " "removed by major browsers and deprecated by RFC 2818. " "service_identity will remove the support for it in mid-2018." % (cn.decode("utf-8"),), SubjectAltNameWarning, stacklevel=2, ) return ids service_identity-18.1.0/src/service_identity.egg-info/0000755000076500000240000000000013401744623023251 5ustar hynekstaff00000000000000service_identity-18.1.0/src/service_identity.egg-info/PKG-INFO0000644000076500000240000001150413401744623024347 0ustar hynekstaff00000000000000Metadata-Version: 2.1 Name: service-identity Version: 18.1.0 Summary: Service identity verification for pyOpenSSL & cryptography. Home-page: https://service-identity.readthedocs.io/ Author: Hynek Schlawack Author-email: hs@ox.cx Maintainer: Hynek Schlawack Maintainer-email: hs@ox.cx License: MIT Description: ============================= Service Identity Verification ============================= .. image:: https://readthedocs.org/projects/service-identity/badge/?version=stable :target: https://service-identity.readthedocs.io/en/stable/?badge=stable :alt: Documentation Status .. image:: https://travis-ci.org/pyca/service_identity.svg?branch=master :target: https://travis-ci.org/pyca/service_identity :alt: CI status .. image:: https://codecov.io/github/pyca/service_identity/branch/master/graph/badge.svg :target: https://codecov.io/github/pyca/service_identity :alt: Test Coverage .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black :alt: Code style: black .. image:: https://www.irccloud.com/invite-svg?channel=%23cryptography-dev&hostname=irc.freenode.net&port=6697&ssl=1 :target: https://www.irccloud.com/invite?channel=%23cryptography-dev&hostname=irc.freenode.net&port=6697&ssl=1 .. begin Use this package if: - you use pyOpenSSL_ and don’t want to be MITM_\ ed or - if you want to verify that a `PyCA cryptography`_ certificate is valid for a certain hostname or IP address. ``service_identity`` aspires to give you all the tools you need for verifying whether a certificate is valid for the intended purposes. In the simplest case, this means *host name verification*. However, ``service_identity`` implements `RFC 6125`_ fully and plans to add other relevant RFCs too. ``service_identity``\ ’s documentation lives at `Read the Docs `_, the code on `GitHub `_. .. _Twisted: https://twistedmatrix.com/ .. _pyOpenSSL: https://pypi.org/project/pyOpenSSL/ .. _MITM: https://en.wikipedia.org/wiki/Man-in-the-middle_attack .. _RFC 6125: https://www.rfc-editor.org/info/rfc6125 .. _PyCA cryptography: https://cryptography.io/ Release Information =================== 18.1.0 (2018-12-05) ------------------- Changes: ^^^^^^^^ - pyOpenSSL is optional now if you use ``service_identity.cryptography.*`` only. - Added support for ``iPAddress`` ``subjectAltName``\ s. You can now verify whether a connection or a certificate is valid for an IP address using ``service_identity.pyopenssl.verify_ip_address()`` and ``service_identity.cryptography.verify_certificate_ip_address()``. `#12 `_ `Full changelog `_. Authors ======= ``service_identity`` is written and maintained by `Hynek Schlawack `_. The development is kindly supported by `Variomedia AG `_. Other contributors can be found in `GitHub's overview `_. Keywords: cryptography,openssl,pyopenssl Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Natural Language :: English Classifier: Operating System :: MacOS :: MacOS X Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: POSIX :: BSD Classifier: Operating System :: POSIX :: Linux Classifier: Operating System :: POSIX Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Programming Language :: Python Classifier: Topic :: Security :: Cryptography Classifier: Topic :: Software Development :: Libraries :: Python Modules Provides-Extra: tests Provides-Extra: dev Provides-Extra: docs Provides-Extra: idna service_identity-18.1.0/src/service_identity.egg-info/SOURCES.txt0000644000076500000240000000145113401744623025136 0ustar hynekstaff00000000000000.coveragerc .pre-commit-config.yaml .travis.yml AUTHORS.rst CHANGELOG.rst LICENSE MANIFEST.in README.rst pyproject.toml setup.cfg setup.py tox.ini docs/Makefile docs/api.rst docs/backward-compatibility.rst docs/changelog.rst docs/conf.py docs/contributing.rst docs/implemented-standards.rst docs/index.rst docs/installation.rst docs/license.rst src/service_identity/__init__.py src/service_identity/_common.py src/service_identity/_compat.py src/service_identity/cryptography.py src/service_identity/exceptions.py src/service_identity/pyopenssl.py src/service_identity.egg-info/PKG-INFO src/service_identity.egg-info/SOURCES.txt src/service_identity.egg-info/dependency_links.txt src/service_identity.egg-info/not-zip-safe src/service_identity.egg-info/requires.txt src/service_identity.egg-info/top_level.txtservice_identity-18.1.0/src/service_identity.egg-info/dependency_links.txt0000644000076500000240000000000113401744623027317 0ustar hynekstaff00000000000000 service_identity-18.1.0/src/service_identity.egg-info/not-zip-safe0000644000076500000240000000000112610673373025503 0ustar hynekstaff00000000000000 service_identity-18.1.0/src/service_identity.egg-info/requires.txt0000644000076500000240000000030613401744623025650 0ustar hynekstaff00000000000000attrs>=16.0.0 pyasn1-modules pyasn1 cryptography [:python_version < "3.3"] ipaddress [dev] coverage>=4.2.0 pytest sphinx idna pyOpenSSL [docs] sphinx [idna] idna [tests] coverage>=4.2.0 pytest service_identity-18.1.0/src/service_identity.egg-info/top_level.txt0000644000076500000240000000002113401744623025774 0ustar hynekstaff00000000000000service_identity service_identity-18.1.0/tox.ini0000644000076500000240000000266613401734047016743 0ustar hynekstaff00000000000000[tox] envlist = lint,py27,py37,pypy,pypy3,{py27,py36}-pyopensslLatest-noidna,{py27,py34,py35,py36}-{pyopenssl014,pyopensslLatest}-idna,{pypy,pypy3}-pyopensslLatest-idna,manifest,pypi-description,coverage-report [testenv] extras = tests deps = idna: idna pyopenssl014: pyOpenSSL>=0.14<0.15 pyopenssl015: pyOpenSSL>=0.15<0.16 pyopensslLatest: pyOpenSSL passenv = LDFLAGS CFLAGS CPPFLAGS setenv = PYTHONHASHSEED = 0 noidna: TRICKING_TOX = 1 commands = coverage run --parallel-mode -m pytest {posargs} py36-pyopensslLatest-idna: coverage run --parallel-mode -m pytest --doctest-modules --doctest-glob='*.rst' {posargs} [testenv:lint] basepython = python3.7 skip_install = true deps = pre-commit passenv = HOMEPATH # needed on Windows commands = pre-commit run --all-files --verbose [testenv:docs] basepython = python3.7 extras = docs commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs docs/_build/html sphinx-build -W -b doctest -d {envtmpdir}/doctrees docs docs/_build/html [testenv:manifest] basepython = python3.7 deps = check-manifest commands = check-manifest [testenv:pypi-description] basepython = python3.7 skip_install = true deps = twine pip >= 18.0.0 commands = pip wheel -w {envtmpdir}/build --no-deps . twine check {envtmpdir}/build/* [testenv:coverage-report] basepython = python3.7 deps = coverage skip_install = true commands = coverage combine coverage report