summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAndrej Shadura <andrew.shadura@collabora.co.uk>2019-06-21 08:25:22 -0500
committerAndrej Shadura <andrew.shadura@collabora.co.uk>2019-06-21 08:25:22 -0500
commit073892d8d76ae764dd60bc6aeee65c9ef18dce07 (patch)
tree60eb0fafc0e5c12daf2c8639ae3258688cdbb0ae
parent7530acd1cd1f26d9c548de40c7e394ae7c751776 (diff)
parentf836f2af1d9ec6af5188950bfb5624fa04888586 (diff)
Update upstream source from tag 'upstream/18.1.0'
Update to upstream version '18.1.0' with Debian dir 5e43d82f641e28f8e75ad47d77be606ff379e9b1
-rw-r--r--.pre-commit-config.yaml27
-rw-r--r--.travis.yml108
-rw-r--r--CHANGELOG.rst55
-rw-r--r--CODE_OF_CONDUCT.rst55
-rw-r--r--CONTRIBUTING.rst43
-rw-r--r--MANIFEST.in6
-rw-r--r--PKG-INFO76
-rw-r--r--README.rst34
-rw-r--r--docs-requirements.txt2
-rw-r--r--docs/api.rst29
-rw-r--r--docs/changelog.rst2
-rw-r--r--docs/conf.py183
-rw-r--r--docs/contributing.rst4
-rw-r--r--docs/implemented-standards.rst10
-rw-r--r--docs/index.rst8
-rw-r--r--docs/installation.rst14
-rw-r--r--docs/license.rst2
-rw-r--r--pyproject.toml6
-rw-r--r--setup.cfg26
-rw-r--r--setup.py53
-rw-r--r--src/service_identity.egg-info/PKG-INFO76
-rw-r--r--src/service_identity.egg-info/SOURCES.txt12
-rw-r--r--src/service_identity.egg-info/requires.txt23
-rw-r--r--src/service_identity/__init__.py9
-rw-r--r--src/service_identity/_common.py174
-rw-r--r--src/service_identity/_compat.py1
-rw-r--r--src/service_identity/cryptography.py161
-rw-r--r--src/service_identity/exceptions.py21
-rw-r--r--src/service_identity/pyopenssl.py88
-rw-r--r--tests/__init__.py0
-rw-r--r--tests/test_common.py627
-rw-r--r--tests/test_pyopenssl.py54
-rw-r--r--tests/util.py116
-rw-r--r--tox.ini49
34 files changed, 839 insertions, 1315 deletions
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 0000000..dd1b81f
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,27 @@
+repos:
+ - 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
diff --git a/.travis.yml b/.travis.yml
index 3555766..f0272ce 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,3 +1,5 @@
+dist: xenial
+group: travis_latest
sudo: false
cache:
directories:
@@ -7,72 +9,84 @@ 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"
- env: TOXENV=py27-pyopenssl015-idna
- - python: "2.7"
- env: TOXENV=py27-pyopenssl015-noidna
+ 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-pyopenssl014-noidna
- - python: "3.4"
- env: TOXENV=py34-pyopenssl015-idna
- - python: "3.4"
- env: TOXENV=py34-pyopenssl015-noidna
+ 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-pyopenssl014-noidna
- - python: "3.5"
- env: TOXENV=py35-pyopenssl015-idna
- - python: "3.5"
- env: TOXENV=py35-pyopenssl015-noidna
+ env: TOXENV=py34-pyopensslLatest-idna
- python: "3.5"
env: TOXENV=py35-pyopenssl014-idna
- python: "3.5"
- env: TOXENV=py35-pyopenssl014-noidna
- - python: "pypy"
- env: TOXENV=pypy-pyopenssl015-idna
+ 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"
- env: TOXENV=pypy-pyopenssl015-noidna
+ dist: trusty
+ env: TOXENV=pypy
+ - python: "pypy3"
+ dist: trusty
+ env: TOXENV=pypy3
- python: "pypy"
- env: TOXENV=pypy-pyopenssl014-idna
- - python: "pypy"
- env: TOXENV=pypy-pyopenssl014-noidna
+ dist: trusty
+ env: TOXENV=pypy-pyopensslLatest-idna
+ - python: "pypy3"
+ dist: trusty
+ env: TOXENV=pypy3-pyopensslLatest-idna
- # Meta
- - python: "3.5"
- env: TOXENV=flake8
- - python: "3.5"
- env: TOXENV=manifest
- - python: "3.5"
+ # 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.5"
- env: TOXENV=readme
+ - python: "3.7"
+ env: TOXENV=pypi-description
+
+ allow_failures:
+ - python: "3.6-dev"
+ - python: "3.7-dev"
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
+ - pip install -U 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
@@ -83,3 +97,7 @@ before_install:
after_success:
- tox -e coverage-report
- codecov
+
+
+notifications:
+ email: false
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 8bb91a1..b548260 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,12 +1,52 @@
.. :changelog:
-History
-=======
+Changelog
+=========
-Versions are year-based with a strict backwards-compatibility policy.
+Versions follow `CalVer <https://calver.org>`_ 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 <https://github.com/pyca/service_identity/pull/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 <https://github.com/pyca/service_identity/pull/17>`_
+- Added ``cryptography.x509`` backend for verifying certificates.
+ `#18 <https://github.com/pyca/service_identity/pull/18>`_
+- Wildcards (``*``) are now only allowed if they are the leftmost label in a certificate.
+ This is common practice by all major browsers.
+ `#19 <https://github.com/pyca/service_identity/pull/19>`_
+
+
+----
+
+
16.0.0 (2016-02-18)
-------------------
@@ -21,16 +61,17 @@ Backward-incompatible changes:
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.
+ 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 <https://github.com/pyca/service_identity/issues/9>`_]
+ `#9 <https://github.com/pyca/service_identity/issues/9>`_
- Add a ``__str__`` method to ``VerificationError``.
-- Port from ``characteristic`` to its spiritual successor `attrs <https://attrs.readthedocs.org/>`_.
+- Port from ``characteristic`` to its spiritual successor `attrs <https://www.attrs.org/>`_.
----
@@ -65,7 +106,7 @@ Changes:
- Move into the `Python Cryptography Authority’s GitHub account <https://github.com/pyca/>`_.
- 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 <https://characteristic.readthedocs.org/>`_ instead of a home-grown solution.
+- Use `characteristic <https://characteristic.readthedocs.io/>`_ 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.
diff --git a/CODE_OF_CONDUCT.rst b/CODE_OF_CONDUCT.rst
deleted file mode 100644
index fa8b5bb..0000000
--- a/CODE_OF_CONDUCT.rst
+++ /dev/null
@@ -1,55 +0,0 @@
-Contributor 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 <http://contributor-covenant.org>`_, version 1.4, available at http://contributor-covenant.org/version/1/4.
diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst
deleted file mode 100644
index cb5fc77..0000000
--- a/CONTRIBUTING.rst
+++ /dev/null
@@ -1,43 +0,0 @@
-How 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 <me>`_ 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
diff --git a/MANIFEST.in b/MANIFEST.in
index 1a070e7..855c534 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,5 +1,7 @@
-include LICENSE .coveragerc .travis.yml tox.ini
+include LICENSE .coveragerc .travis.yml .pre-commit-config.yaml tox.ini pyproject.toml
include docs/Makefile docs/conf.py
include *.rst *.txt
-recursive-include tests *.py
+exclude conftest.py .readthedocs.yml
recursive-include docs *.rst
+prune tests
+prune .github
diff --git a/PKG-INFO b/PKG-INFO
index 0e8d846..e9247d7 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,71 +1,73 @@
-Metadata-Version: 1.1
+Metadata-Version: 2.1
Name: service_identity
-Version: 16.0.0
-Summary: Service identity verification for pyOpenSSL.
-Home-page: https://service-identity.readthedocs.org/
+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 for pyOpenSSL
- ===========================================
+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
+ :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://codecov.io/github/pyca/service_identity/coverage.svg?branch=master
- :target: https://codecov.io/github/pyca/service_identity
+ .. 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&amp;hostname=irc.freenode.net&amp;port=6697&amp;ssl=1
:target: https://www.irccloud.com/invite?channel=%23cryptography-dev&amp;hostname=irc.freenode.net&amp;port=6697&amp;ssl=1
.. begin
- **TL;DR**: Use this package if you use pyOpenSSL_ and don’t want to be MITM_\ ed.
+ 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 <https://service-identity.readthedocs.org/>`_, the code on `GitHub <https://github.com/pyca/service_identity>`_.
+ ``service_identity``\ ’s documentation lives at `Read the Docs <https://service-identity.readthedocs.io/>`_, the code on `GitHub <https://github.com/pyca/service_identity>`_.
.. _Twisted: https://twistedmatrix.com/
- .. _pyOpenSSL: https://pypi.python.org/pypi/pyOpenSSL/
+ .. _pyOpenSSL: https://pypi.org/project/pyOpenSSL/
.. _MITM: https://en.wikipedia.org/wiki/Man-in-the-middle_attack
- .. _`RFC 6125`: http://www.rfc-editor.org/info/rfc6125
+ .. _RFC 6125: https://www.rfc-editor.org/info/rfc6125
+ .. _PyCA cryptography: https://cryptography.io/
Release Information
===================
- 16.0.0 (2016-02-18)
+ 18.1.0 (2018-12-05)
-------------------
- 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 <https://github.com/pyca/service_identity/issues/9>`_]
- - Add a ``__str__`` method to ``VerificationError``.
- - Port from ``characteristic`` to its spiritual successor `attrs <https://attrs.readthedocs.org/>`_.
+ - 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 <https://github.com/pyca/service_identity/pull/12>`_
- `Full changelog <https://service-identity.readthedocs.org/en/stable/changelog.html>`_.
+ `Full changelog <https://service-identity.readthedocs.io/en/stable/changelog.html>`_.
Authors
=======
@@ -92,8 +94,14 @@ 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
diff --git a/README.rst b/README.rst
index 7e6bdde..2c30f76 100644
--- a/README.rst
+++ b/README.rst
@@ -1,29 +1,43 @@
-===========================================
-Service Identity Verification for pyOpenSSL
-===========================================
+=============================
+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
+ :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://codecov.io/github/pyca/service_identity/coverage.svg?branch=master
- :target: https://codecov.io/github/pyca/service_identity
+.. 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&amp;hostname=irc.freenode.net&amp;port=6697&amp;ssl=1
:target: https://www.irccloud.com/invite?channel=%23cryptography-dev&amp;hostname=irc.freenode.net&amp;port=6697&amp;ssl=1
.. begin
-**TL;DR**: Use this package if you use pyOpenSSL_ and don’t want to be MITM_\ ed.
+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 <https://service-identity.readthedocs.org/>`_, the code on `GitHub <https://github.com/pyca/service_identity>`_.
+``service_identity``\ ’s documentation lives at `Read the Docs <https://service-identity.readthedocs.io/>`_, the code on `GitHub <https://github.com/pyca/service_identity>`_.
.. _Twisted: https://twistedmatrix.com/
-.. _pyOpenSSL: https://pypi.python.org/pypi/pyOpenSSL/
+.. _pyOpenSSL: https://pypi.org/project/pyOpenSSL/
.. _MITM: https://en.wikipedia.org/wiki/Man-in-the-middle_attack
-.. _`RFC 6125`: http://www.rfc-editor.org/info/rfc6125
+.. _RFC 6125: https://www.rfc-editor.org/info/rfc6125
+.. _PyCA cryptography: https://cryptography.io/
diff --git a/docs-requirements.txt b/docs-requirements.txt
deleted file mode 100644
index 96c342c..0000000
--- a/docs-requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
--e .
-sphinx
diff --git a/docs/api.rst b/docs/api.rst
index f80ea7f..91b1c23 100644
--- a/docs/api.rst
+++ b/docs/api.rst
@@ -4,16 +4,17 @@ 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.
+ 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 <https://github.com/pyca/service_identity/blob/master/src/service_identity/_common.py>`_.
-.. currentmodule:: service_identity.pyopenssl
+pyOpenSSL
+=========
+.. currentmodule:: service_identity.pyopenssl
-.. autofunction:: verify_hostname(connection, hostname)
+.. autofunction:: verify_hostname
In practice, this may look like the following::
@@ -46,11 +47,23 @@ API
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 \ No newline at end of file
+.. autoexception:: SubjectAltNameWarning
diff --git a/docs/changelog.rst b/docs/changelog.rst
index 4d7817a..565b052 100644
--- a/docs/changelog.rst
+++ b/docs/changelog.rst
@@ -1 +1 @@
-.. include:: ../CHANGELOG.rst \ No newline at end of file
+.. include:: ../CHANGELOG.rst
diff --git a/docs/conf.py b/docs/conf.py
index d9bf349..41f8241 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -17,11 +17,6 @@ import datetime
import os
import re
-try:
- import sphinx_rtd_theme
-except ImportError:
- sphinx_rtd_theme = None
-
def read(*parts):
"""
@@ -39,51 +34,51 @@ def find_version(*file_paths):
string inside.
"""
version_file = read(*file_paths)
- version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
- version_file, re.M)
+ 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('.'))
+# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
-#needs_sphinx = '1.0'
+# 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',
+ "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']
+templates_path = ["_templates"]
# The suffix of source filenames.
-source_suffix = '.rst'
+source_suffix = ".rst"
# The encoding of source files.
-#source_encoding = 'utf-8-sig'
+# source_encoding = 'utf-8-sig'
# The master toctree document.
-master_doc = 'index'
+master_doc = "index"
# General information about the project.
-project = u'service_identity'
+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""
-)
+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
@@ -94,41 +89,41 @@ version = release.rsplit(u".", 1)[0]
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
-#language = None
+# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
-#today = ''
+# today = ''
# Else, today_fmt is used as the format for a strftime call.
-#today_fmt = '%B %d, %Y'
+# 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']
+exclude_patterns = ["_build"]
# The reST default role (used for this markup: `text`) to use for all
# documents.
-#default_role = None
+# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
-#add_function_parentheses = True
+# 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
+# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
-#show_authors = False
+# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
-pygments_style = 'sphinx'
+pygments_style = "sphinx"
# A list of ignored prefixes for module index sorting.
-#modindex_common_prefix = []
+# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
-#keep_warnings = False
+# keep_warnings = False
# -- Options for HTML output ----------------------------------------------
@@ -136,35 +131,38 @@ pygments_style = 'sphinx'
# 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"
+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 = {}
+# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
-#html_theme_path = []
+# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
-#html_title = None
+# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
-#html_short_title = None
+# 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
+# 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
+# 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,
@@ -174,93 +172,89 @@ else:
# 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 = []
+# 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'
+# 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
+# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
-#html_sidebars = {}
+# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
-#html_additional_pages = {}
+# html_additional_pages = {}
# If false, no module index is generated.
-#html_domain_indices = True
+# html_domain_indices = True
# If false, no index is generated.
-#html_use_index = True
+# html_use_index = True
# If true, the index is split into individual pages for each letter.
-#html_split_index = False
+# html_split_index = False
# If true, links to the reST sources are added to the pages.
-#html_show_sourcelink = True
+# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
-#html_show_sphinx = True
+# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
-#html_show_copyright = True
+# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
-#html_use_opensearch = ''
+# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
-#html_file_suffix = None
+# html_file_suffix = None
# Output file base name for HTML help builder.
-htmlhelp_basename = 'service_identitydoc'
+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': '',
-}
+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'),
+ (
+ "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
+# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
-#latex_use_parts = False
+# latex_use_parts = False
# If true, show page references after internal links.
-#latex_show_pagerefs = False
+# latex_show_pagerefs = False
# If true, show URL addresses after external links.
-#latex_show_urls = False
+# latex_show_urls = False
# Documents to append as an appendix to all manuals.
-#latex_appendices = []
+# latex_appendices = []
# If false, no module index is generated.
-#latex_domain_indices = True
+# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
@@ -268,12 +262,17 @@ latex_documents = [
# 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)
+ (
+ "index",
+ "service_identity",
+ u"service_identity Documentation",
+ [u"Hynek Schlawack"],
+ 1,
+ )
]
# If true, show URL addresses after external links.
-#man_show_urls = False
+# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
@@ -282,27 +281,33 @@ man_pages = [
# (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'),
+ (
+ "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 = []
+# texinfo_appendices = []
# If false, no module index is generated.
-#texinfo_domain_indices = True
+# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
-#texinfo_show_urls = 'footnote'
+# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
-#texinfo_no_detailmenu = False
+# 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,
+ "https://docs.python.org/3/": None,
+ "https://pyopenssl.readthedocs.io/en/stable": None,
+ "https://cryptography.io/en/stable/": None,
}
diff --git a/docs/contributing.rst b/docs/contributing.rst
index 1d519c3..acb527b 100644
--- a/docs/contributing.rst
+++ b/docs/contributing.rst
@@ -1,5 +1,5 @@
.. _contributing:
-.. include:: ../CONTRIBUTING.rst
+.. include:: ../.github/CONTRIBUTING.rst
-.. include:: ../CODE_OF_CONDUCT.rst
+.. include:: ../.github/CODE_OF_CONDUCT.rst
diff --git a/docs/implemented-standards.rst b/docs/implemented-standards.rst
index 82904a6..2f18412 100644
--- a/docs/implemented-standards.rst
+++ b/docs/implemented-standards.rst
@@ -6,6 +6,7 @@ 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`_)
@@ -14,10 +15,9 @@ 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
+.. _`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
diff --git a/docs/index.rst b/docs/index.rst
index 197d756..59f6776 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -1,12 +1,13 @@
-============================================
-Service Identity Verification for pyOpenSSL
-============================================
+==========================================================
+Service Identity Verification for pyOpenSSL & cryptography
+==========================================================
Release v\ |release| (:doc:`What's new? <changelog>`).
.. include:: ../README.rst
:start-after: begin
+
User's Guide
============
@@ -29,6 +30,7 @@ Project Information
contributing
changelog
+
Indices and tables
==================
diff --git a/docs/installation.rst b/docs/installation.rst
index e6608b6..aed6ce2 100644
--- a/docs/installation.rst
+++ b/docs/installation.rst
@@ -14,12 +14,13 @@ Requirements
Python 2.7, 3.4 and later, as well as PyPy are supported.
-Additionally, the following PyPI modules are required:
+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.
@@ -28,10 +29,11 @@ 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/
+.. _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.python.org/pypi/idna/
+.. _idna: https://pypi.org/project/idna/
.. _outdated: https://bugs.python.org/issue17305
+.. _ipaddress: https://pypi.org/project/ipaddress/
diff --git a/docs/license.rst b/docs/license.rst
index 97abc23..3f5d090 100644
--- a/docs/license.rst
+++ b/docs/license.rst
@@ -1,7 +1,7 @@
License
=======
-``service_identity`` is licensed under the `MIT <http://choosealicense.com/licenses/mit/>`_ license.
+``service_identity`` is licensed under the `MIT <https://choosealicense.com/licenses/mit/>`_ license.
The full license text can be also found in the `source code repository <https://github.com/pyca/service_identity/blob/master/LICENSE>`_.
.. include:: ../AUTHORS.rst
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..ee41185
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,6 @@
+[build-system]
+requires = ["setuptools", "wheel"]
+
+
+[tool.black]
+line-length = 79
diff --git a/setup.cfg b/setup.cfg
index ccb319b..a164bdc 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -1,14 +1,30 @@
-[pytest]
-minversion = 2.8.2
+[tool:pytest]
+minversion = 3.0
strict = true
addopts = -ra
testpaths = tests
+filterwarnings =
+ once::Warning
-[wheel]
+[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_svn_revision = 0
-tag_date = 0
tag_build =
+tag_date = 0
diff --git a/setup.py b/setup.py
index 47600b9..7ce6706 100644
--- a/setup.py
+++ b/setup.py
@@ -2,7 +2,7 @@ import codecs
import os
import re
-from setuptools import setup, find_packages
+from setuptools import find_packages, setup
###############################################################################
@@ -24,6 +24,8 @@ CLASSIFIERS = [
"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",
@@ -31,28 +33,28 @@ CLASSIFIERS = [
"Topic :: Software Development :: Libraries :: Python Modules",
]
INSTALL_REQUIRES = [
- "attrs",
- "pyasn1",
+ "attrs>=16.0.0",
+ "ipaddress; python_version<'3.3'",
"pyasn1-modules",
- "pyopenssl>=0.12",
+ # 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__))
-
-try:
- PACKAGES
-except NameError:
- PACKAGES = find_packages(where="src")
-
-try:
- META_PATH
-except NameError:
- META_PATH = os.path.join(HERE, "src", NAME, "__init__.py")
+PACKAGES = find_packages(where="src")
+META_PATH = os.path.join(HERE, "src", NAME, "__init__.py")
def read(*parts):
@@ -72,22 +74,27 @@ def find_meta(meta):
Extract __*meta*__ from META_FILE.
"""
meta_match = re.search(
- r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta),
- META_FILE, re.M
+ 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")
+ 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)
diff --git a/src/service_identity.egg-info/PKG-INFO b/src/service_identity.egg-info/PKG-INFO
index 55b0ed2..d64402e 100644
--- a/src/service_identity.egg-info/PKG-INFO
+++ b/src/service_identity.egg-info/PKG-INFO
@@ -1,71 +1,73 @@
-Metadata-Version: 1.1
+Metadata-Version: 2.1
Name: service-identity
-Version: 16.0.0
-Summary: Service identity verification for pyOpenSSL.
-Home-page: https://service-identity.readthedocs.org/
+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 for pyOpenSSL
- ===========================================
+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
+ :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://codecov.io/github/pyca/service_identity/coverage.svg?branch=master
- :target: https://codecov.io/github/pyca/service_identity
+ .. 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&amp;hostname=irc.freenode.net&amp;port=6697&amp;ssl=1
:target: https://www.irccloud.com/invite?channel=%23cryptography-dev&amp;hostname=irc.freenode.net&amp;port=6697&amp;ssl=1
.. begin
- **TL;DR**: Use this package if you use pyOpenSSL_ and don’t want to be MITM_\ ed.
+ 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 <https://service-identity.readthedocs.org/>`_, the code on `GitHub <https://github.com/pyca/service_identity>`_.
+ ``service_identity``\ ’s documentation lives at `Read the Docs <https://service-identity.readthedocs.io/>`_, the code on `GitHub <https://github.com/pyca/service_identity>`_.
.. _Twisted: https://twistedmatrix.com/
- .. _pyOpenSSL: https://pypi.python.org/pypi/pyOpenSSL/
+ .. _pyOpenSSL: https://pypi.org/project/pyOpenSSL/
.. _MITM: https://en.wikipedia.org/wiki/Man-in-the-middle_attack
- .. _`RFC 6125`: http://www.rfc-editor.org/info/rfc6125
+ .. _RFC 6125: https://www.rfc-editor.org/info/rfc6125
+ .. _PyCA cryptography: https://cryptography.io/
Release Information
===================
- 16.0.0 (2016-02-18)
+ 18.1.0 (2018-12-05)
-------------------
- 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 <https://github.com/pyca/service_identity/issues/9>`_]
- - Add a ``__str__`` method to ``VerificationError``.
- - Port from ``characteristic`` to its spiritual successor `attrs <https://attrs.readthedocs.org/>`_.
+ - 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 <https://github.com/pyca/service_identity/pull/12>`_
- `Full changelog <https://service-identity.readthedocs.org/en/stable/changelog.html>`_.
+ `Full changelog <https://service-identity.readthedocs.io/en/stable/changelog.html>`_.
Authors
=======
@@ -92,8 +94,14 @@ 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
diff --git a/src/service_identity.egg-info/SOURCES.txt b/src/service_identity.egg-info/SOURCES.txt
index 3acc7e1..9ac2915 100644
--- a/src/service_identity.egg-info/SOURCES.txt
+++ b/src/service_identity.egg-info/SOURCES.txt
@@ -1,13 +1,12 @@
.coveragerc
+.pre-commit-config.yaml
.travis.yml
AUTHORS.rst
CHANGELOG.rst
-CODE_OF_CONDUCT.rst
-CONTRIBUTING.rst
LICENSE
MANIFEST.in
README.rst
-docs-requirements.txt
+pyproject.toml
setup.cfg
setup.py
tox.ini
@@ -24,6 +23,7 @@ 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
@@ -31,8 +31,4 @@ 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.py \ No newline at end of file
+src/service_identity.egg-info/top_level.txt \ No newline at end of file
diff --git a/src/service_identity.egg-info/requires.txt b/src/service_identity.egg-info/requires.txt
index 5b96c3a..147e397 100644
--- a/src/service_identity.egg-info/requires.txt
+++ b/src/service_identity.egg-info/requires.txt
@@ -1,7 +1,24 @@
-attrs
-pyasn1
+attrs>=16.0.0
pyasn1-modules
-pyopenssl>=0.12
+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
diff --git a/src/service_identity/__init__.py b/src/service_identity/__init__.py
index c6c7eb1..f79673e 100644
--- a/src/service_identity/__init__.py
+++ b/src/service_identity/__init__.py
@@ -4,7 +4,7 @@ Verify service identities.
from __future__ import absolute_import, division, print_function
-from . import pyopenssl
+from . import cryptography, pyopenssl
from .exceptions import (
CertificateError,
SubjectAltNameWarning,
@@ -12,11 +12,11 @@ from .exceptions import (
)
-__version__ = "16.0.0"
+__version__ = "18.1.0"
__title__ = "service_identity"
-__description__ = "Service identity verification for pyOpenSSL."
-__uri__ = "https://service-identity.readthedocs.org/"
+__description__ = "Service identity verification for pyOpenSSL & cryptography."
+__uri__ = "https://service-identity.readthedocs.io/"
__author__ = "Hynek Schlawack"
__email__ = "hs@ox.cx"
@@ -29,5 +29,6 @@ __all__ = [
"CertificateError",
"SubjectAltNameWarning",
"VerificationError",
+ "cryptography",
"pyopenssl",
]
diff --git a/src/service_identity/_common.py b/src/service_identity/_common.py
index fa8a359..9b4e773 100644
--- a/src/service_identity/_common.py
+++ b/src/service_identity/_common.py
@@ -4,6 +4,7 @@ Common verification code.
from __future__ import absolute_import, division, print_function
+import ipaddress
import re
import attr
@@ -12,22 +13,25 @@ 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
+@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()
@@ -41,8 +45,9 @@ def verify_service_identity(cert_patterns, obligatory_ids, optional_ids):
if a pattern of the respective type is present.
"""
errors = []
- matches = (_find_matches(cert_patterns, obligatory_ids) +
- _find_matches(cert_patterns, optional_ids))
+ 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:
@@ -54,9 +59,8 @@ def verify_service_identity(cert_patterns, obligatory_ids, optional_ids):
# 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)
+ if i not in matched_ids and _contains_instance_of(
+ cert_patterns, i.pattern_class
):
errors.append(i.error_on_mismatch(mismatched_id=i))
@@ -82,9 +86,7 @@ def _find_matches(cert_patterns, service_ids):
for sid in service_ids:
for cid in cert_patterns:
if sid.verify(cid):
- matches.append(
- ServiceMatch(cert_pattern=cid, service_id=sid)
- )
+ matches.append(ServiceMatch(cert_pattern=cid, service_id=sid))
return matches
@@ -101,43 +103,42 @@ def _contains_instance_of(seq, cl):
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`
+ :rtype: bool
"""
- if isinstance(pattern, text_type):
+ if isinstance(pattern, bytes):
try:
- pattern = pattern.encode('ascii')
+ pattern = pattern.decode("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
- )
+ 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)
+@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\-_.]+$")
@@ -157,15 +158,34 @@ class DNSPattern(object):
)
self.pattern = pattern.translate(_TRANS_TO_LOWER)
- if b'*' in self.pattern:
+ if b"*" in self.pattern:
_validate_pattern(self.pattern)
-@attr.s(init=False)
+@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()
@@ -178,11 +198,7 @@ class URIPattern(object):
pattern = pattern.strip().translate(_TRANS_TO_LOWER)
- if (
- b":" not in pattern or
- b"*" in pattern or
- _is_ip_address(pattern)
- ):
+ if b":" not in pattern or b"*" in pattern or _is_ip_address(pattern):
raise CertificateError(
"Invalid URI pattern {0!r}.".format(pattern)
)
@@ -190,11 +206,12 @@ class URIPattern(object):
self.dns_pattern = DNSPattern(hostname)
-@attr.s(init=False)
+@attr.s(init=False, slots=True)
class SRVPattern(object):
"""
An SRV pattern as extracted from certificates.
"""
+
name_pattern = attr.ib()
dns_pattern = attr.ib()
@@ -208,10 +225,10 @@ class SRVPattern(object):
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)
+ 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)
@@ -221,11 +238,12 @@ class SRVPattern(object):
self.dns_pattern = DNSPattern(hostname)
-@attr.s(init=False)
+@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
@@ -260,7 +278,7 @@ class DNS_ID(object):
def verify(self, pattern):
"""
- http://tools.ietf.org/search/rfc6125#section-6.4
+ https://tools.ietf.org/search/rfc6125#section-6.4
"""
if isinstance(pattern, self.pattern_class):
return _hostname_matches(pattern.pattern, self.hostname)
@@ -268,11 +286,30 @@ class DNS_ID(object):
return False
-@attr.s(init=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()
@@ -297,22 +334,23 @@ class URI_ID(object):
def verify(self, pattern):
"""
- http://tools.ietf.org/search/rfc6125#section-6.5.2
+ 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)
+ pattern.protocol_pattern == self.protocol
+ and self.dns_id.verify(pattern.dns_pattern)
)
else:
return False
-@attr.s(init=False)
+@attr.s(init=False, slots=True)
class SRV_ID(object):
"""
An SRV service ID.
"""
+
name = attr.ib()
dns_id = attr.ib()
@@ -337,12 +375,11 @@ class SRV_ID(object):
def verify(self, pattern):
"""
- http://tools.ietf.org/search/rfc6125#section-6.5.1
+ 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)
+ return self.name == pattern.name_pattern and self.dns_id.verify(
+ pattern.dns_pattern
)
else:
return False
@@ -356,7 +393,7 @@ def _hostname_matches(cert_pattern, actual_hostname):
:return: `True` if *cert_pattern* matches *actual_hostname*, else `False`.
:rtype: `bool`
"""
- if b'*' in cert_pattern:
+ 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:
@@ -365,20 +402,7 @@ def _hostname_matches(cert_pattern, actual_hostname):
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)
-
+ return cert_head == b"*" or cert_head == actual_head
else:
return cert_pattern == actual_hostname
@@ -395,15 +419,15 @@ def _validate_pattern(cert_pattern):
cnt = cert_pattern.count(b"*")
if cnt > 1:
raise CertificateError(
- "Certificate's DNS-ID {0!r} contains too many wildcards."
- .format(cert_pattern)
+ "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)
+ "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]:
@@ -413,11 +437,13 @@ def _validate_pattern(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)
+ "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")
+_TRANS_TO_LOWER = maketrans(
+ b"ABCDEFGHIJKLMNOPQRSTUVWXYZ", b"abcdefghijklmnopqrstuvwxyz"
+)
diff --git a/src/service_identity/_compat.py b/src/service_identity/_compat.py
index 65febe8..317b675 100644
--- a/src/service_identity/_compat.py
+++ b/src/service_identity/_compat.py
@@ -11,5 +11,6 @@ if PY3: # pragma: nocover
text_type = str
else: # pragma: nocover
import string
+
maketrans = string.maketrans
text_type = unicode # noqa
diff --git a/src/service_identity/cryptography.py b/src/service_identity/cryptography.py
new file mode 100644
index 0000000..9e174a0
--- /dev/null
+++ b/src/service_identity/cryptography.py
@@ -0,0 +1,161 @@
+"""
+`cryptography.x509 <https://github.com/pyca/cryptography>`_-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"<not given>")
+ 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
diff --git a/src/service_identity/exceptions.py b/src/service_identity/exceptions.py
index 1dfc108..852abc1 100644
--- a/src/service_identity/exceptions.py
+++ b/src/service_identity/exceptions.py
@@ -10,7 +10,7 @@ from __future__ import absolute_import, division, print_function
import attr
-class SubjectAltNameWarning(Warning):
+class SubjectAltNameWarning(DeprecationWarning):
"""
Server Certificate does not contain a ``SubjectAltName``.
@@ -23,6 +23,7 @@ class VerificationError(Exception):
"""
Service identity verification failed.
"""
+
errors = attr.ib()
def __str__(self):
@@ -32,24 +33,36 @@ class VerificationError(Exception):
@attr.s
class DNSMismatch(object):
"""
- Not matching DNSPattern could be found.
+ No matching DNSPattern could be found.
"""
+
mismatched_id = attr.ib()
@attr.s
class SRVMismatch(object):
"""
- Not matching SRVPattern could be found.
+ No matching SRVPattern could be found.
"""
+
mismatched_id = attr.ib()
@attr.s
class URIMismatch(object):
"""
- Not matching URIPattern could be found.
+ 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()
diff --git a/src/service_identity/pyopenssl.py b/src/service_identity/pyopenssl.py
index fb39954..7fc090d 100644
--- a/src/service_identity/pyopenssl.py
+++ b/src/service_identity/pyopenssl.py
@@ -6,31 +6,36 @@ 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 .exceptions import SubjectAltNameWarning
from ._common import (
+ DNS_ID,
CertificateError,
DNSPattern,
- DNS_ID,
+ 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 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`
+ :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*.
@@ -47,7 +52,32 @@ def verify_hostname(connection, hostname):
)
-ID_ON_DNS_SRV = ObjectIdentifier('1.3.6.1.5.5.7.8.7') # id_on_dnsSRV
+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):
@@ -57,13 +87,12 @@ def extract_ids(cert):
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`
+ :param OpenSSL.SSL.X509 cert: The certificate to be dissected.
:return: List of IDs.
"""
ids = []
- for i in range(cert.get_extension_count()):
+ 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())
@@ -71,6 +100,12 @@ def extract_ids(cert):
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":
@@ -84,25 +119,28 @@ def extract_ids(cert):
raise CertificateError(
"Unexpected certificate content."
)
+ else: # pragma: nocover
+ pass
+ else: # pragma: nocover
+ pass
if not ids:
- # http://tools.ietf.org/search/rfc6125#section-6.4.4
+ # 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"<not given>")
+ ids = [DNSPattern(c) for c in components]
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
+ "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,
)
- ids = [DNSPattern(c[1])
- for c
- in cert.get_subject().get_components()
- if c[0] == b"CN"]
return ids
-
-
-__all__ = [
- "verify_hostname",
-]
diff --git a/tests/__init__.py b/tests/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/tests/__init__.py
+++ /dev/null
diff --git a/tests/test_common.py b/tests/test_common.py
deleted file mode 100644
index 466a682..0000000
--- a/tests/test_common.py
+++ /dev/null
@@ -1,627 +0,0 @@
-from __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) != ""
diff --git a/tests/test_pyopenssl.py b/tests/test_pyopenssl.py
deleted file mode 100644
index 61d480a..0000000
--- a/tests/test_pyopenssl.py
+++ /dev/null
@@ -1,54 +0,0 @@
-from __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)]
diff --git a/tests/util.py b/tests/util.py
deleted file mode 100644
index 0a911c3..0000000
--- a/tests/util.py
+++ /dev/null
@@ -1,116 +0,0 @@
-from __future__ import absolute_import, division, print_function
-
-from OpenSSL.crypto import load_certificate, FILETYPE_PEM
-
-
-# Test certificates
-
-PEM_DNS_ONLY = """\
------BEGIN CERTIFICATE-----
-MIIGbjCCBVagAwIBAgIDCesrMA0GCSqGSIb3DQEBBQUAMIGMMQswCQYDVQQGEwJ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9YuLuYVogx0K285wX4/Yha2wyo6KSAm0txJayOhcrEP2/34aWCl62m
-xOtPbQIDAQABo4GgMIGdMIGaBgNVHREEgZIwgY+CDSouZXhhbXBsZS5uZXSCC2V4
-YW1wbGUuY29thwTAqAABhxAAEwAAAAAAAAAAAAAAAAAXhhNodHRwOi8vZXhhbXBs
-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)
diff --git a/tox.ini b/tox.ini
index 040fa64..b3cae95 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,58 +1,57 @@
[tox]
-envlist = coverage-clean,{py27,py34,py35,pypy}-{pyopenssl015,pyopenssl014}-{idna,noidna},flake8,manifest,readme,coverage-report
+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 =
- coverage
- pytest
idna: idna
- pyopenssl014: pyOpenSSL==0.14
- pyopenssl015: pyOpenSSL==0.15.1
+ 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}
- py35-pyopenssl015-idna: coverage run --parallel-mode -m pytest --doctest-modules --doctest-glob='*.rst' {posargs}
+ py36-pyopensslLatest-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: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.5
-deps = sphinx
+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.5
+basepython = python3.7
deps = check-manifest
commands = check-manifest
-[testenv:readme]
-basepython = python3.5
-deps = readme_renderer
+[testenv:pypi-description]
+basepython = python3.7
skip_install = true
-commands = python setup.py check -r -s
-
-
-[testenv:coverage-clean]
-basepython = python3.5
-deps = coverage
-skip_install = true
-commands = coverage erase
+deps =
+ twine
+ pip >= 18.0.0
+commands =
+ pip wheel -w {envtmpdir}/build --no-deps .
+ twine check {envtmpdir}/build/*
[testenv:coverage-report]
-basepython = python3.5
+basepython = python3.7
deps = coverage
skip_install = true
commands =