service_identity-16.0.0/0000755000076500000240000000000012661326331015413 5ustar hynekstaff00000000000000service_identity-16.0.0/.coveragerc0000644000076500000240000000033012610700035017517 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-16.0.0/.travis.yml0000644000076500000240000000365012661067764017544 0ustar hynekstaff00000000000000sudo: false cache: directories: - $HOME/.cache/pip language: python matrix: include: - python: "2.7" env: TOXENV=py27-pyopenssl015-idna - python: "2.7" env: TOXENV=py27-pyopenssl015-noidna - python: "2.7" env: TOXENV=py27-pyopenssl014-idna - python: "2.7" env: TOXENV=py27-pyopenssl014-noidna - python: "3.4" env: TOXENV=py34-pyopenssl015-idna - python: "3.4" env: TOXENV=py34-pyopenssl015-noidna - python: "3.4" env: TOXENV=py34-pyopenssl014-idna - python: "3.4" env: TOXENV=py34-pyopenssl014-noidna - python: "3.5" env: TOXENV=py35-pyopenssl015-idna - python: "3.5" env: TOXENV=py35-pyopenssl015-noidna - python: "3.5" env: TOXENV=py35-pyopenssl014-idna - python: "3.5" env: TOXENV=py35-pyopenssl014-noidna - python: "pypy" env: TOXENV=pypy-pyopenssl015-idna - python: "pypy" env: TOXENV=pypy-pyopenssl015-noidna - python: "pypy" env: TOXENV=pypy-pyopenssl014-idna - python: "pypy" env: TOXENV=pypy-pyopenssl014-noidna # Meta - python: "3.5" env: TOXENV=flake8 - python: "3.5" env: TOXENV=manifest - python: "3.5" env: TOXENV=docs - python: "3.5" env: TOXENV=readme install: - | if [[ "${TOXENV}" = pypy* ]]; then git clone --depth 1 https://github.com/yyuu/pyenv.git ~/.pyenv PYENV_ROOT="$HOME/.pyenv" PATH="$PYENV_ROOT/bin:$PATH" eval "$(pyenv init -)" pyenv install pypy-4.0.1 pyenv global pypy-4.0.1 fi - pip install tox script: - | # activate the pypy env we installed via our custom pyenv in the install stage if [[ "${TOXENV}" == "pypy" ]]; then PYENV_ROOT="$HOME/.pyenv" PATH="$PYENV_ROOT/bin:$PATH" eval "$(pyenv init -)" fi - tox before_install: - pip install codecov after_success: - tox -e coverage-report - codecov service_identity-16.0.0/AUTHORS.rst0000644000076500000240000000047312661320343017273 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-16.0.0/CHANGELOG.rst0000644000076500000240000000561712661324376017454 0ustar hynekstaff00000000000000.. :changelog: History ======= Versions are year-based with a strict backwards-compatibility policy. The third digit is only for regressions. 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 with recent OpenSSL versions. 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-16.0.0/CODE_OF_CONDUCT.rst0000644000076500000240000000622312653614370020431 0ustar hynekstaff00000000000000Contributor Covenant Code of Conduct ==================================== Our Pledge ---------- In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. Our Standards ------------- Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting Our Responsibilities -------------------- Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. Scope ----- This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. Enforcement ----------- Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at hs@ox.cx. all complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. Attribution ----------- This Code of Conduct is adapted from the `Contributor Covenant `_, version 1.4, available at http://contributor-covenant.org/version/1/4. service_identity-16.0.0/CONTRIBUTING.rst0000644000076500000240000000456612661324755020077 0ustar hynekstaff00000000000000How To Contribute ================= Every open source project lives from the generous help by contributors that sacrifice their time and ``service_identity`` is no different. Here are a few guidelines to get you started: - Try to limit each pull request to one change only. - To run the test suite, all you need is a recent tox_. It will ensure the test suite runs with all dependencies against all Python versions just as it will on `Travis CI`_. If you lack some Python version, you can can always limit the environments like ``tox -e py27,py35`` (in that case you may want to look into pyenv_ that makes it very easy to install many different Python versions in parallel). - Make sure your changes pass our CI_. You won't get any feedback until it's green unless you ask for it. - If your change is noteworthy, add an entry to the changelog_. - No contribution is too small; please submit as many fixes for typos and grammar bloopers as you can! - Don’t break `backward compatibility`_. - *Always* add tests and docs for your code. This is a hard rule; patches with missing tests or documentation won’t be merged. - Write `good test docstrings`_. - Obey `PEP 8`_ and `PEP 257`_. - If you address review feedback, make sure to bump the pull request. Maintainers don’t receive notifications if you push new commits. Please note that this project is released with a Contributor `Code of Conduct`_. By participating in this project you agree to abide by its terms. Please report any harm to `Hynek Schlawack `_ in any way you find appropriate. We can usually be found in the ``#cryptography-dev`` channel on freenode_. Thank you for considering to contribute to ``service_identity``! .. _me: https://hynek.me/about/ .. _`PEP 8`: https://www.python.org/dev/peps/pep-0008/ .. _`PEP 257`: https://www.python.org/dev/peps/pep-0257/ .. _`good test docstrings`: https://jml.io/pages/test-docstrings.html .. _`Code of Conduct`: https://github.com/pyca/service_identity/blob/master/CODE_OF_CONDUCT.rst .. _changelog: https://github.com/pyca/service_identity/blob/master/CHANGELOG.rst .. _`backward compatibility`: https://service-identity.readthedocs.org/en/latest/backward-compatibility.html .. _`tox`: https://testrun.org/tox/ .. _`Travis CI`: https://travis-ci.org/ .. _pyenv: https://github.com/yyuu/pyenv .. _CI: https://travis-ci.org/pyca/service_identity .. _freenode: http://webchat.freenode.net service_identity-16.0.0/docs/0000755000076500000240000000000012661326331016343 5ustar hynekstaff00000000000000service_identity-16.0.0/docs/api.rst0000644000076500000240000000326012617341505017650 0ustar hynekstaff00000000000000=== API === .. note:: The APIs for RFC 6125 verification beyond DNS-IDs (i.e. hostnames) aren't public yet. They are in place and used by the documented high-level APIs though. Eventually they will become public. If you'd like to play with them and provide feedback have a look at the ``verify_service_identity`` function in the `_common module `_. .. currentmodule:: service_identity.pyopenssl .. autofunction:: verify_hostname(connection, 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() .. currentmodule:: service_identity .. autoexception:: VerificationError .. autoexception:: CertificateError .. autoexception:: SubjectAltNameWarningservice_identity-16.0.0/docs/backward-compatibility.rst0000644000076500000240000000063312617322020023514 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-16.0.0/docs/changelog.rst0000644000076500000240000000003512617321637021027 0ustar hynekstaff00000000000000.. include:: ../CHANGELOG.rstservice_identity-16.0.0/docs/conf.py0000644000076500000240000002267412617340704017656 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 try: import sphinx_rtd_theme except ImportError: sphinx_rtd_theme = None 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{0}, Hynek Schlawack'.format( u'-{0}'.format(year) if year != 2014 else u"" ) # 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. if sphinx_rtd_theme: html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] else: html_theme = "default" # 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 = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # 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/2/": None, "https://pyopenssl.readthedocs.org/en/stable": None, } service_identity-16.0.0/docs/contributing.rst0000644000076500000240000000013112617322772021605 0ustar hynekstaff00000000000000.. _contributing: .. include:: ../CONTRIBUTING.rst .. include:: ../CODE_OF_CONDUCT.rst service_identity-16.0.0/docs/implemented-standards.rst0000644000076500000240000000113712343060637023364 0ustar hynekstaff00000000000000===================== Implemented Standards ===================== Present ======= - ``dNSName`` with fallback to ``CN`` (DNS-ID, aka host names, `RFC 6125`_). - ``uniformResourceIdentifier`` (URI-ID, `RFC 6125`_). - SRV-ID (`RFC 6125`_) Future ====== - ``xmppAddr`` (`RFC 3920`_). - ``iPAddress`` (`RFC 2818`_). - ``nameConstraints`` extensions (`RFC 3280`_). .. _`RFC 2818`: http://www.rfc-editor.org/rfc/rfc2818.txt .. _`RFC 3280`: http://tools.ietf.org/search/rfc3280#section-4.2.1.11 .. _`RFC 3920`: http://www.rfc-editor.org/rfc/rfc3920.txt .. _`RFC 6125`: http://www.rfc-editor.org/info/rfc6125 service_identity-16.0.0/docs/index.rst0000644000076500000240000000106012617322244020201 0ustar hynekstaff00000000000000============================================ Service Identity Verification for pyOpenSSL ============================================ 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-16.0.0/docs/installation.rst0000644000076500000240000000247012661324647021611 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 modules are required: - attrs_ - pyOpenSSL_ ``>= 0.14`` (``0.12`` and ``0.13`` may work but are not part of CI anymore) - pyasn1_ - pyasn1-modules_ 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://attrs.readthedocs.org/ .. _pyOpenSSL: https://pypi.python.org/pypi/pyOpenSSL/ .. _pyasn1-modules: https://pypi.python.org/pypi/pyasn1-modules/ .. _pyasn1: https://pypi.python.org/pypi/pyasn1/ .. _`internationalized domain names`: https://en.wikipedia.org/wiki/Internationalized_domain_name .. _idna: https://pypi.python.org/pypi/idna/ .. _outdated: https://bugs.python.org/issue17305 service_identity-16.0.0/docs/license.rst0000644000076500000240000000043412661320363020517 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-16.0.0/docs/Makefile0000644000076500000240000001522212343051253020000 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-16.0.0/docs-requirements.txt0000644000076500000240000000001412617341003021612 0ustar hynekstaff00000000000000-e . sphinx service_identity-16.0.0/LICENSE0000644000076500000240000000204312301370045016407 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-16.0.0/MANIFEST.in0000644000076500000240000000024112617350242017145 0ustar hynekstaff00000000000000include LICENSE .coveragerc .travis.yml tox.ini include docs/Makefile docs/conf.py include *.rst *.txt recursive-include tests *.py recursive-include docs *.rst service_identity-16.0.0/PKG-INFO0000644000076500000240000001121412661326331016507 0ustar hynekstaff00000000000000Metadata-Version: 1.1 Name: service_identity Version: 16.0.0 Summary: Service identity verification for pyOpenSSL. Home-page: https://service-identity.readthedocs.org/ Author: Hynek Schlawack Author-email: hs@ox.cx License: MIT Description: =========================================== Service Identity Verification for pyOpenSSL =========================================== .. image:: https://travis-ci.org/pyca/service_identity.svg?branch=master :target: https://travis-ci.org/pyca/service_identity .. image:: https://codecov.io/github/pyca/service_identity/coverage.svg?branch=master :target: https://codecov.io/github/pyca/service_identity .. 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 **TL;DR**: Use this package if you use pyOpenSSL_ and don’t want to be MITM_\ ed. ``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.python.org/pypi/pyOpenSSL/ .. _MITM: https://en.wikipedia.org/wiki/Man-in-the-middle_attack .. _`RFC 6125`: http://www.rfc-editor.org/info/rfc6125 Release Information =================== 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 with recent OpenSSL versions. 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 `_. `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 :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Programming Language :: Python Classifier: Topic :: Security :: Cryptography Classifier: Topic :: Software Development :: Libraries :: Python Modules service_identity-16.0.0/README.rst0000644000076500000240000000265512631533104017105 0ustar hynekstaff00000000000000=========================================== Service Identity Verification for pyOpenSSL =========================================== .. image:: https://travis-ci.org/pyca/service_identity.svg?branch=master :target: https://travis-ci.org/pyca/service_identity .. image:: https://codecov.io/github/pyca/service_identity/coverage.svg?branch=master :target: https://codecov.io/github/pyca/service_identity .. 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 **TL;DR**: Use this package if you use pyOpenSSL_ and don’t want to be MITM_\ ed. ``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.python.org/pypi/pyOpenSSL/ .. _MITM: https://en.wikipedia.org/wiki/Man-in-the-middle_attack .. _`RFC 6125`: http://www.rfc-editor.org/info/rfc6125 service_identity-16.0.0/setup.cfg0000644000076500000240000000023512661326331017234 0ustar hynekstaff00000000000000[pytest] minversion = 2.8.2 strict = true addopts = -ra testpaths = tests [wheel] universal = 1 [egg_info] tag_svn_revision = 0 tag_date = 0 tag_build = service_identity-16.0.0/setup.py0000644000076500000240000000615012661324041017123 0ustar hynekstaff00000000000000import codecs import os import re from setuptools import setup, find_packages ############################################################################### 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 :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Programming Language :: Python", "Topic :: Security :: Cryptography", "Topic :: Software Development :: Libraries :: Python Modules", ] INSTALL_REQUIRES = [ "attrs", "pyasn1", "pyasn1-modules", "pyopenssl>=0.12", ] EXTRAS_REQUIRE = { "idna": ["idna"], } ############################################################################### HERE = os.path.abspath(os.path.dirname(__file__)) try: PACKAGES except NameError: PACKAGES = find_packages(where="src") try: META_PATH except NameError: 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("(\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-16.0.0/src/0000755000076500000240000000000012661326331016202 5ustar hynekstaff00000000000000service_identity-16.0.0/src/service_identity/0000755000076500000240000000000012661326331021553 5ustar hynekstaff00000000000000service_identity-16.0.0/src/service_identity/__init__.py0000644000076500000240000000120212661324415023660 0ustar hynekstaff00000000000000""" Verify service identities. """ from __future__ import absolute_import, division, print_function from . import pyopenssl from .exceptions import ( CertificateError, SubjectAltNameWarning, VerificationError, ) __version__ = "16.0.0" __title__ = "service_identity" __description__ = "Service identity verification for pyOpenSSL." __uri__ = "https://service-identity.readthedocs.org/" __author__ = "Hynek Schlawack" __email__ = "hs@ox.cx" __license__ = "MIT" __copyright__ = "Copyright (c) 2014 Hynek Schlawack" __all__ = [ "CertificateError", "SubjectAltNameWarning", "VerificationError", "pyopenssl", ] service_identity-16.0.0/src/service_identity/_common.py0000644000076500000240000002656212617341545023574 0ustar hynekstaff00000000000000""" Common verification code. """ from __future__ import absolute_import, division, print_function import re import attr from ._compat import maketrans, text_type from .exceptions import ( CertificateError, DNSMismatch, SRVMismatch, URIMismatch, VerificationError, ) try: import idna except ImportError: # pragma: nocover idna = None @attr.s 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 _RE_IPv4 = re.compile(br"^([0-9*]{1,3}\.){3}[0-9*]{1,3}$") _RE_IPv6 = re.compile(br"^([a-f0-9*]{0,4}:)+[a-f0-9*]{1,4}$") _RE_NUMBER = re.compile(br"^[0-9]+$") def _is_ip_address(pattern): """ Check whether *pattern* could be/match an IP address. Does *not* guarantee that pattern is in fact a valid IP address; especially the checks for IPv6 are rather coarse. This function is for security checks, not for validating IP addresses. :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, text_type): try: pattern = pattern.encode('ascii') except UnicodeError: return False return ( _RE_IPv4.match(pattern) is not None or _RE_IPv6.match(pattern) is not None or _RE_NUMBER.match(pattern) is not None ) @attr.s(init=False) 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(init=False) 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) 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) 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): """ http://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(init=False) 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): """ http://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) 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): """ http://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 if cert_head == b"*": return True start, end = cert_head.split(b"*") if start == b"": # *oo return actual_head.endswith(end) elif end == b"": # f* return actual_head.startswith(start) else: # f*o return actual_head.startswith(start) and actual_head.endswith(end) 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} hast 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-16.0.0/src/service_identity/_compat.py0000644000076500000240000000046312347350167023557 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-16.0.0/src/service_identity/exceptions.py0000644000076500000240000000213112617341307024304 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(Warning): """ 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): """ Not matching DNSPattern could be found. """ mismatched_id = attr.ib() @attr.s class SRVMismatch(object): """ Not matching SRVPattern could be found. """ mismatched_id = attr.ib() @attr.s class URIMismatch(object): """ Not matching URIPattern could be found. """ mismatched_id = attr.ib() class CertificateError(Exception): """ Certificate contains invalid or unexpected data. """ service_identity-16.0.0/src/service_identity/pyopenssl.py0000644000076500000240000000714412617340440024165 0ustar hynekstaff00000000000000""" `pyOpenSSL `_-specific code. """ from __future__ import absolute_import, division, print_function import warnings 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 .exceptions import SubjectAltNameWarning from ._common import ( CertificateError, DNSPattern, DNS_ID, SRVPattern, URIPattern, verify_service_identity, ) def verify_hostname(connection, hostname): """ Verify whether the certificate of *connection* is valid for *hostname*. :param connection: A pyOpenSSL connection object. :type connection: :class:`OpenSSL.SSL.Connection` :param hostname: The hostname that *connection* should be connected to. :type hostname: :class:`unicode` :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=[], ) 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 cert: The certificate to be dissected. :type cert: :class:`OpenSSL.SSL.X509` :return: List of IDs. """ ids = [] for i in 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 == "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." ) if not ids: # http://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. warnings.warn( "Certificate 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.", SubjectAltNameWarning ) ids = [DNSPattern(c[1]) for c in cert.get_subject().get_components() if c[0] == b"CN"] return ids __all__ = [ "verify_hostname", ] service_identity-16.0.0/src/service_identity.egg-info/0000755000076500000240000000000012661326331023245 5ustar hynekstaff00000000000000service_identity-16.0.0/src/service_identity.egg-info/dependency_links.txt0000644000076500000240000000000112661326326027317 0ustar hynekstaff00000000000000 service_identity-16.0.0/src/service_identity.egg-info/not-zip-safe0000644000076500000240000000000112610673373025500 0ustar hynekstaff00000000000000 service_identity-16.0.0/src/service_identity.egg-info/PKG-INFO0000644000076500000240000001121412661326326024345 0ustar hynekstaff00000000000000Metadata-Version: 1.1 Name: service-identity Version: 16.0.0 Summary: Service identity verification for pyOpenSSL. Home-page: https://service-identity.readthedocs.org/ Author: Hynek Schlawack Author-email: hs@ox.cx License: MIT Description: =========================================== Service Identity Verification for pyOpenSSL =========================================== .. image:: https://travis-ci.org/pyca/service_identity.svg?branch=master :target: https://travis-ci.org/pyca/service_identity .. image:: https://codecov.io/github/pyca/service_identity/coverage.svg?branch=master :target: https://codecov.io/github/pyca/service_identity .. 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 **TL;DR**: Use this package if you use pyOpenSSL_ and don’t want to be MITM_\ ed. ``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.python.org/pypi/pyOpenSSL/ .. _MITM: https://en.wikipedia.org/wiki/Man-in-the-middle_attack .. _`RFC 6125`: http://www.rfc-editor.org/info/rfc6125 Release Information =================== 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 with recent OpenSSL versions. 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 `_. `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 :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Programming Language :: Python Classifier: Topic :: Security :: Cryptography Classifier: Topic :: Software Development :: Libraries :: Python Modules service_identity-16.0.0/src/service_identity.egg-info/requires.txt0000644000076500000240000000007112661326326025647 0ustar hynekstaff00000000000000attrs pyasn1 pyasn1-modules pyopenssl>=0.12 [idna] idna service_identity-16.0.0/src/service_identity.egg-info/SOURCES.txt0000644000076500000240000000154512661326330025135 0ustar hynekstaff00000000000000.coveragerc .travis.yml AUTHORS.rst CHANGELOG.rst CODE_OF_CONDUCT.rst CONTRIBUTING.rst LICENSE MANIFEST.in README.rst docs-requirements.txt 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/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.txt tests/__init__.py tests/test_common.py tests/test_pyopenssl.py tests/util.pyservice_identity-16.0.0/src/service_identity.egg-info/top_level.txt0000644000076500000240000000002112661326326025774 0ustar hynekstaff00000000000000service_identity service_identity-16.0.0/tests/0000755000076500000240000000000012661326331016555 5ustar hynekstaff00000000000000service_identity-16.0.0/tests/__init__.py0000644000076500000240000000000012320123435020644 0ustar hynekstaff00000000000000service_identity-16.0.0/tests/test_common.py0000644000076500000240000004445212572362177021500 0ustar hynekstaff00000000000000from __future__ import absolute_import, division, print_function import pytest import service_identity._common from service_identity._common import ( DNSPattern, DNS_ID, ServiceMatch, SRVPattern, SRV_ID, URIPattern, URI_ID, _contains_instance_of, _find_matches, _hostname_matches, _is_ip_address, _validate_pattern, verify_service_identity, ) from service_identity.exceptions import ( CertificateError, DNSMismatch, SRVMismatch, VerificationError, ) from service_identity.pyopenssl import extract_ids from .util import CERT_DNS_ONLY try: import idna except ImportError: idna = None class TestVerifyServiceIdentity(object): """ Simple integration tests for verify_service_identity. """ def test_dns_id_success(self): """ Return pairs of certificate ids and service ids on matches. """ rv = verify_service_identity(extract_ids(CERT_DNS_ONLY), [DNS_ID(u"twistedmatrix.com")], []) assert [ ServiceMatch(cert_pattern=DNSPattern(b"twistedmatrix.com"), service_id=DNS_ID(u"twistedmatrix.com"),), ] == rv def test_integration_dns_id_fail(self): """ Raise VerificationError if no certificate id matches the supplied service ids. """ i = DNS_ID(u"wrong.host") with pytest.raises(VerificationError) as e: verify_service_identity( extract_ids(CERT_DNS_ONLY), obligatory_ids=[i], optional_ids=[], ) assert [DNSMismatch(mismatched_id=i)] == e.value.errors def test_obligatory_missing(self): """ Raise if everything matches but one of the obligatory IDs is missing. """ i = DNS_ID(u"example.net") with pytest.raises(VerificationError) as e: verify_service_identity( [SRVPattern(b"_mail.example.net")], obligatory_ids=[SRV_ID(u"_mail.example.net"), i], optional_ids=[], ) assert [DNSMismatch(mismatched_id=i)] == e.value.errors def test_obligatory_mismatch(self): """ Raise if one of the obligatory IDs doesn't match. """ i = DNS_ID(u"example.net") with pytest.raises(VerificationError) as e: verify_service_identity( [SRVPattern(b"_mail.example.net"), DNSPattern(b"example.com")], obligatory_ids=[SRV_ID(u"_mail.example.net"), i], optional_ids=[], ) assert [DNSMismatch(mismatched_id=i)] == e.value.errors def test_optional_missing(self): """ Optional IDs may miss as long as they don't conflict with an existing pattern. """ p = DNSPattern(b"mail.foo.com") i = DNS_ID(u"mail.foo.com") rv = verify_service_identity( [p], obligatory_ids=[i], optional_ids=[SRV_ID(u"_mail.foo.com")], ) assert [ServiceMatch(cert_pattern=p, service_id=i)] == rv def test_optional_mismatch(self): """ Raise VerificationError if an ID from optional_ids does not match a pattern of respective type even if obligatory IDs match. """ i = SRV_ID(u"_xmpp.example.com") with pytest.raises(VerificationError) as e: verify_service_identity( [DNSPattern(b"example.net"), SRVPattern(b"_mail.example.com")], obligatory_ids=[DNS_ID(u"example.net")], optional_ids=[i], ) assert [SRVMismatch(mismatched_id=i)] == e.value.errors def test_contains_optional_and_matches(self): """ If an optional ID is found, return the match within the returned list and don't raise an error. """ p = SRVPattern(b"_mail.example.net") i = SRV_ID(u"_mail.example.net") rv = verify_service_identity( [DNSPattern(b"example.net"), p], obligatory_ids=[DNS_ID(u"example.net")], optional_ids=[i], ) assert ServiceMatch(cert_pattern=p, service_id=i) == rv[1] class TestContainsInstance(object): def test_positive(self): """ If the list contains an object of the type, return True. """ assert _contains_instance_of([object(), tuple(), object()], tuple) def test_negative(self): """ If the list does not contain an object of the type, return False. """ assert not _contains_instance_of([object(), list(), {}], tuple) class TestDNS_ID(object): def test_enforces_unicode(self): """ Raise TypeError if pass DNS-ID is not unicode. """ with pytest.raises(TypeError): DNS_ID(b"foo.com") def test_handles_missing_idna(self, monkeypatch): """ Raise ImportError if idna is missing and a non-ASCII DNS-ID is passed. """ monkeypatch.setattr(service_identity._common, "idna", None) with pytest.raises(ImportError): DNS_ID(u"f\xf8\xf8.com") def test_ascii_works_without_idna(self, monkeypatch): """ 7bit-ASCII DNS-IDs work no matter whether idna is present or not. """ monkeypatch.setattr(service_identity._common, "idna", None) dns = DNS_ID(u"foo.com") assert b"foo.com" == dns.hostname @pytest.mark.skipif(idna is None, reason="idna not installed") def test_idna_used_if_available_on_non_ascii(self): """ If idna is installed and a non-ASCII DNS-ID is passed, encode it to ASCII. """ dns = DNS_ID(u"f\xf8\xf8.com") assert b'xn--f-5gaa.com' == dns.hostname def test_catches_invalid_dns_ids(self): """ Raise ValueError on invalid DNS-IDs. """ for invalid_id in [ u" ", u"", # empty strings u"host,name", # invalid chars u"192.168.0.0", u"::1", u"1234" # IP addresses ]: with pytest.raises(ValueError): DNS_ID(invalid_id) def test_lowercases(self): """ The hostname is lowercased so it can be compared case-insensitively. """ dns_id = DNS_ID(u"hOsTnAmE") assert b"hostname" == dns_id.hostname def test_verifies_only_dns(self): """ If anything else than DNSPattern is passed to verify, return False. """ assert not DNS_ID(u"foo.com").verify(object()) def test_simple_match(self): """ Simple integration test with _hostname_matches with a match. """ assert DNS_ID(u"foo.com").verify(DNSPattern(b"foo.com")) def test_simple_mismatch(self): """ Simple integration test with _hostname_matches with a mismatch. """ assert not DNS_ID(u"foo.com").verify(DNSPattern(b"bar.com")) def test_matches(self): """ Valid matches return `True`. """ for cert, actual in [ (b"www.example.com", b"www.example.com"), (b"*.example.com", b"www.example.com"), (b"xxx*.example.com", b"xxxwww.example.com"), (b"f*.example.com", b"foo.example.com"), (b"*oo.bar.com", b"foo.bar.com"), (b"fo*oo.bar.com", b"fooooo.bar.com"), ]: assert _hostname_matches(cert, actual) def test_mismatches(self): """ Invalid matches return `False`. """ for cert, actual in [ (b"xxx.example.com", b"www.example.com"), (b"*.example.com", b"baa.foo.example.com"), (b"f*.example.com", b"baa.example.com"), (b"*.bar.com", b"foo.baz.com"), (b"*.bar.com", b"bar.com"), (b"x*.example.com", b"xn--gtter-jua.example.com"), ]: assert not _hostname_matches(cert, actual) class TestURI_ID(object): def test_enforces_unicode(self): """ Raise TypeError if pass URI-ID is not unicode. """ with pytest.raises(TypeError): URI_ID(b"sip:foo.com") def test_create_DNS_ID(self): """ The hostname is converted into a DNS_ID object. """ uri_id = URI_ID(u"sip:foo.com") assert DNS_ID(u"foo.com") == uri_id.dns_id assert b"sip" == uri_id.protocol def test_lowercases(self): """ The protocol is lowercased so it can be compared case-insensitively. """ uri_id = URI_ID(u"sIp:foo.com") assert b"sip" == uri_id.protocol def test_catches_missing_colon(self): """ Raise ValueError if there's no colon within a URI-ID. """ with pytest.raises(ValueError): URI_ID(u"sip;foo.com") def test_is_only_valid_for_uri(self): """ If anything else than an URIPattern is passed to verify, return False. """ assert not URI_ID(u"sip:foo.com").verify(object()) def test_protocol_mismatch(self): """ If protocol doesn't match, verify returns False. """ assert not URI_ID(u"sip:foo.com").verify(URIPattern(b"xmpp:foo.com")) def test_dns_mismatch(self): """ If the hostname doesn't match, verify returns False. """ assert not URI_ID(u"sip:bar.com").verify(URIPattern(b"sip:foo.com")) def test_match(self): """ Accept legal matches. """ assert URI_ID(u"sip:foo.com").verify(URIPattern(b"sip:foo.com")) class TestSRV_ID(object): def test_enforces_unicode(self): """ Raise TypeError if pass srv-ID is not unicode. """ with pytest.raises(TypeError): SRV_ID(b"_mail.example.com") def test_create_DNS_ID(self): """ The hostname is converted into a DNS_ID object. """ srv_id = SRV_ID(u"_mail.example.com") assert DNS_ID(u"example.com") == srv_id.dns_id def test_lowercases(self): """ The service name is lowercased so it can be compared case-insensitively. """ srv_id = SRV_ID(u"_MaIl.foo.com") assert b"mail" == srv_id.name def test_catches_missing_dot(self): """ Raise ValueError if there's no dot within a SRV-ID. """ with pytest.raises(ValueError): SRV_ID(u"_imapsfoocom") def test_catches_missing_underscore(self): """ Raise ValueError if the service is doesn't start with an underscore. """ with pytest.raises(ValueError): SRV_ID(u"imaps.foo.com") def test_is_only_valid_for_SRV(self): """ If anything else than an SRVPattern is passed to verify, return False. """ assert not SRV_ID(u"_mail.foo.com").verify(object()) def test_match(self): """ Accept legal matches. """ assert SRV_ID(u"_mail.foo.com").verify(SRVPattern(b"_mail.foo.com")) @pytest.mark.skipif(idna is None, reason="idna not installed") def test_match_idna(self): """ IDNAs are handled properly. """ assert SRV_ID(u"_mail.f\xf8\xf8.com").verify( SRVPattern(b'_mail.xn--f-5gaa.com') ) def test_mismatch_service_name(self): """ If the service name doesn't match, verify returns False. """ assert not ( SRV_ID(u"_mail.foo.com").verify(SRVPattern(b"_xmpp.foo.com")) ) def test_mismatch_dns(self): """ If the dns_id doesn't match, verify returns False. """ assert not ( SRV_ID(u"_mail.foo.com").verify(SRVPattern(b"_mail.bar.com")) ) class TestDNSPattern(object): def test_enforces_bytes(self): """ Raise TypeError if unicode is passed. """ with pytest.raises(TypeError): DNSPattern(u"foo.com") def test_catches_empty(self): """ Empty DNS-IDs raise a :class:`CertificateError`. """ with pytest.raises(CertificateError): DNSPattern(b" ") def test_catches_NULL_bytes(self): """ Raise :class:`CertificateError` if a NULL byte is in the hostname. """ with pytest.raises(CertificateError): DNSPattern(b"www.google.com\0nasty.h4x0r.com") def test_catches_ip_address(self): """ IP addresses are invalid and raise a :class:`CertificateError`. """ with pytest.raises(CertificateError): DNSPattern(b"192.168.0.0") def test_invalid_wildcard(self): """ Integration test with _validate_pattern: catches double wildcards thus is used if an wildward is present. """ with pytest.raises(CertificateError): DNSPattern(b"*.foo.*") class TestURIPattern(object): def test_enforces_bytes(self): """ Raise TypeError if unicode is passed. """ with pytest.raises(TypeError): URIPattern(u"sip:foo.com") def test_catches_missing_colon(self): """ Raise CertificateError if URI doesn't contain a `:`. """ with pytest.raises(CertificateError): URIPattern(b"sip;foo.com") def test_catches_wildcards(self): """ Raise CertificateError if URI contains a *. """ with pytest.raises(CertificateError): URIPattern(b"sip:*.foo.com") class TestSRVPattern(object): def test_enforces_bytes(self): """ Raise TypeError if unicode is passed. """ with pytest.raises(TypeError): SRVPattern(u"_mail.example.com") def test_catches_missing_underscore(self): """ Raise CertificateError if SRV doesn't start with a `_`. """ with pytest.raises(CertificateError): SRVPattern(b"foo.com") def test_catches_wildcards(self): """ Raise CertificateError if SRV contains a *. """ with pytest.raises(CertificateError): SRVPattern(b"sip:*.foo.com") class TestValidateDNSWildcardPattern(object): def test_allows_only_one_wildcard(self): """ Raise CertificateError on multiple wildcards. """ with pytest.raises(CertificateError): _validate_pattern(b"*.*.com") def test_wildcard_must_be_left_most(self): """ Raise CertificateError if wildcard is not in the left-most part. """ for hn in [ b"foo.b*r.com", b"foo.bar.c*m", b"foo.*", b"foo.*.com", ]: with pytest.raises(CertificateError): _validate_pattern(hn) def test_must_have_at_least_three_parts(self): """ Raise CertificateError if host consists of less than three parts. """ for hn in [ b"*", b"*.com", b"*fail.com", b"*foo", b"foo*", b"f*o", b"*.example.", ]: with pytest.raises(CertificateError): _validate_pattern(hn) def test_valid_patterns(self): """ Does not throw CertificateError on valid patterns. """ for pattern in [ b"*.bar.com", b"*oo.bar.com", b"f*.bar.com", b"f*o.bar.com" ]: _validate_pattern(pattern) class FakeCertID(object): pass class Fake_ID(object): """ An ID that accepts exactly on object as pattern. """ def __init__(self, pattern): self._pattern = pattern def verify(self, other): """ True iff other is the same object as pattern. """ return other is self._pattern class TestFindMatches(object): def test_one_match(self): """ If there's a match, return a tuple of the certificate id and the service id. """ valid_cert_id = FakeCertID() valid_id = Fake_ID(valid_cert_id) rv = _find_matches([ FakeCertID(), valid_cert_id, FakeCertID(), ], [valid_id]) assert [ ServiceMatch(cert_pattern=valid_cert_id, service_id=valid_id) ] == rv def test_no_match(self): """ If no valid certificate ids are found, return an empty list. """ rv = _find_matches([ FakeCertID(), FakeCertID(), FakeCertID(), ], [Fake_ID(object())]) assert [] == rv def test_multiple_matches(self): """ Return all matches. """ valid_cert_id_1 = FakeCertID() valid_cert_id_2 = FakeCertID() valid_cert_id_3 = FakeCertID() valid_id_1 = Fake_ID(valid_cert_id_1) valid_id_2 = Fake_ID(valid_cert_id_2) valid_id_3 = Fake_ID(valid_cert_id_3) rv = _find_matches([ FakeCertID(), valid_cert_id_1, FakeCertID(), valid_cert_id_3, FakeCertID(), valid_cert_id_2, ], [valid_id_1, valid_id_2, valid_id_3]) assert [ ServiceMatch(cert_pattern=valid_cert_id_1, service_id=valid_id_1), ServiceMatch(cert_pattern=valid_cert_id_2, service_id=valid_id_2), ServiceMatch(cert_pattern=valid_cert_id_3, service_id=valid_id_3), ] == rv class TestIsIPAddress(object): def test_ips(self): """ Returns True for patterns and hosts that could match IP addresses. """ for s in [ b"127.0.0.1", u"127.0.0.1", b"172.16.254.12", b"*.0.0.1", b"::1", b"*::1", b"2001:0db8:0000:0000:0000:ff00:0042:8329", b"2001:0db8::ff00:0042:8329", ]: assert _is_ip_address(s), "Not detected {0!r}".format(s) def test_no_ips(self): """ Return False for patterns and hosts that aren't IP addresses. """ for s in [ b"*.twistedmatrix.com", b"twistedmatrix.com", b"mail.google.com", b"omega7.de", b"omega7", ]: assert not _is_ip_address(s), "False positive {0!r}".format(s) class TestVerificationError(object): """ The __str__ returns something sane. """ try: raise VerificationError(errors=["foo"]) except VerificationError as e: assert repr(e) == str(e) assert str(e) != "" service_identity-16.0.0/tests/test_pyopenssl.py0000644000076500000240000000313712617337757022245 0ustar hynekstaff00000000000000from __future__ import absolute_import, division, print_function import pytest from service_identity._common import DNSPattern, URIPattern from service_identity import SubjectAltNameWarning from service_identity.pyopenssl import extract_ids, verify_hostname from .util import CERT_CN_ONLY, CERT_DNS_ONLY, CERT_OTHER_NAME class TestVerifyHostname(object): def test_verify_hostname(self): """ It's just a convenience one-liner. Let's check it doesn't explode b/c of some typo. """ class FakeConnection(object): def get_peer_certificate(self): return CERT_DNS_ONLY verify_hostname(FakeConnection(), u"twistedmatrix.com") class TestExtractIDs(object): def test_dns(self): """ Returns the correct DNSPattern from a certificate. """ rv = extract_ids(CERT_DNS_ONLY) assert [ DNSPattern(b"www.twistedmatrix.com"), DNSPattern(b"twistedmatrix.com") ] == rv def test_cn_ids_are_used_as_fallback(self): """ CNs are returned as DNSPattern if no other IDs are present and a warning is raised. """ with pytest.warns(SubjectAltNameWarning): rv = extract_ids(CERT_CN_ONLY) assert [ DNSPattern(b"www.microsoft.com") ] == rv def test_uri(self): """ Returns the correct URIPattern from a certificate. """ rv = extract_ids(CERT_OTHER_NAME) assert [ URIPattern(b"http://example.com/") ] == [id for id in rv if isinstance(id, URIPattern)] service_identity-16.0.0/tests/util.py0000644000076500000240000001444512320123435020104 0ustar hynekstaff00000000000000from __future__ import absolute_import, division, print_function from OpenSSL.crypto import load_certificate, FILETYPE_PEM # Test certificates PEM_DNS_ONLY = """\ -----BEGIN CERTIFICATE----- MIIGbjCCBVagAwI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W1wbGUuY29thwTAqAABhxAAEwAAAAAAAAAAAAAAAAAXhhNodHRwOi8vZXhhbXBs ZS5jb20voCYGCCsGAQUFBwgHoBoWGF94bXBwLWNsaWVudC5leGFtcGxlLm5ldKAc BggrBgEFBQcIBaAQDA5pbS5leGFtcGxlLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEA ACVQcgEKzXEw0M9mmVFFXL2SyDk/4oaDFZbnNfyUp+H7bnxdVBG2M3DzQQLw5yH5 k4GNPvHOKshBbaFcZWiG1sdrfQJy/UjIWnaC5410npfBv7kJWafKKxZzMq3gp4rd jPO2LxuWcYVOnUtA3CBe12tRV7ynGU8KmKOsU9bOWhUKo8DJ4a6XHB+YwXeOTPyU mG7XBpQebT01I3OijFJ+apKR2ubjwZE8l1+BAlTzHyUmmcTTWTQk8FTFcP3nZuIr VyudDBMASs4yVGHzQxmMalYYzd7ZDzM1NrgfG1KyKWqZEA0MzUxiYdUbZN79xL52 EyKUOXPHw78G6zsVmAE1Aw== -----END CERTIFICATE-----""" CERT_DNS_ONLY = load_certificate(FILETYPE_PEM, PEM_DNS_ONLY) CERT_CN_ONLY = load_certificate(FILETYPE_PEM, PEM_CN_ONLY) CERT_OTHER_NAME = load_certificate(FILETYPE_PEM, PEM_OTHER_NAME) service_identity-16.0.0/tox.ini0000644000076500000240000000244212661067772016743 0ustar hynekstaff00000000000000[tox] envlist = coverage-clean,{py27,py34,py35,pypy}-{pyopenssl015,pyopenssl014}-{idna,noidna},flake8,manifest,readme,coverage-report [testenv] deps = coverage pytest idna: idna pyopenssl014: pyOpenSSL==0.14 pyopenssl015: pyOpenSSL==0.15.1 passenv = LDFLAGS CFLAGS CPPFLAGS setenv = PYTHONHASHSEED = 0 noidna: TRICKING_TOX = 1 commands = coverage run --parallel-mode -m pytest {posargs} py35-pyopenssl015-idna: coverage run --parallel-mode -m pytest --doctest-modules --doctest-glob='*.rst' {posargs} [testenv:flake8] basepython = python3.5 deps = flake8 commands = flake8 setup.py src tests [testenv:docs] basepython = python3.5 deps = sphinx 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.5 deps = check-manifest commands = check-manifest [testenv:readme] basepython = python3.5 deps = readme_renderer skip_install = true commands = python setup.py check -r -s [testenv:coverage-clean] basepython = python3.5 deps = coverage skip_install = true commands = coverage erase [testenv:coverage-report] basepython = python3.5 deps = coverage skip_install = true commands = coverage combine coverage report