letsencrypt-apache-0.4.1/0000755000175000017500000000000012665157735014724 5ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/setup.py0000644000175000017500000000361012665157707016435 0ustar bmwbmw00000000000000import sys from setuptools import setup from setuptools import find_packages version = '0.4.1' # Please update tox.ini when modifying dependency version requirements install_requires = [ 'acme=={0}'.format(version), 'letsencrypt=={0}'.format(version), 'python-augeas', 'setuptools', # pkg_resources 'zope.component', 'zope.interface', ] if sys.version_info < (2, 7): install_requires.append('mock<1.1.0') else: install_requires.append('mock') docs_extras = [ 'Sphinx>=1.0', # autodoc_member_order = 'bysource', autodoc_default_flags 'sphinx_rtd_theme', ] setup( name='letsencrypt-apache', version=version, description="Apache plugin for Let's Encrypt client", url='https://github.com/letsencrypt/letsencrypt', author="Let's Encrypt Project", author_email='client-dev@letsencrypt.org', license='Apache License 2.0', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Plugins', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Security', 'Topic :: System :: Installation/Setup', 'Topic :: System :: Networking', 'Topic :: System :: Systems Administration', 'Topic :: Utilities', ], packages=find_packages(), include_package_data=True, install_requires=install_requires, extras_require={ 'docs': docs_extras, }, entry_points={ 'letsencrypt.plugins': [ 'apache = letsencrypt_apache.configurator:ApacheConfigurator', ], }, test_suite='letsencrypt_apache', ) letsencrypt-apache-0.4.1/letsencrypt_apache.egg-info/0000755000175000017500000000000012665157735022273 5ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache.egg-info/dependency_links.txt0000644000175000017500000000000112665157735026341 0ustar bmwbmw00000000000000 letsencrypt-apache-0.4.1/letsencrypt_apache.egg-info/top_level.txt0000644000175000017500000000002312665157735025020 0ustar bmwbmw00000000000000letsencrypt_apache letsencrypt-apache-0.4.1/letsencrypt_apache.egg-info/requires.txt0000644000175000017500000000020012665157735024663 0ustar bmwbmw00000000000000acme==0.4.1 letsencrypt==0.4.1 python-augeas setuptools zope.component zope.interface mock [docs] Sphinx>=1.0 sphinx_rtd_theme letsencrypt-apache-0.4.1/letsencrypt_apache.egg-info/entry_points.txt0000644000175000017500000000012312665157735025565 0ustar bmwbmw00000000000000[letsencrypt.plugins] apache = letsencrypt_apache.configurator:ApacheConfigurator letsencrypt-apache-0.4.1/letsencrypt_apache.egg-info/PKG-INFO0000644000175000017500000000173212665157735023373 0ustar bmwbmw00000000000000Metadata-Version: 1.1 Name: letsencrypt-apache Version: 0.4.1 Summary: Apache plugin for Let's Encrypt client Home-page: https://github.com/letsencrypt/letsencrypt Author: Let's Encrypt Project Author-email: client-dev@letsencrypt.org License: Apache License 2.0 Description: UNKNOWN Platform: UNKNOWN Classifier: Development Status :: 3 - Alpha Classifier: Environment :: Plugins Classifier: Intended Audience :: System Administrators Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: POSIX :: Linux Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: Security Classifier: Topic :: System :: Installation/Setup Classifier: Topic :: System :: Networking Classifier: Topic :: System :: Systems Administration Classifier: Topic :: Utilities letsencrypt-apache-0.4.1/letsencrypt_apache.egg-info/SOURCES.txt0000644000175000017500000001473712665157735024173 0ustar bmwbmw00000000000000LICENSE.txt MANIFEST.in README.rst setup.py docs/.gitignore docs/Makefile docs/api.rst docs/conf.py docs/index.rst docs/make.bat docs/_static/.gitignore docs/_templates/.gitignore docs/api/augeas_configurator.rst docs/api/configurator.rst docs/api/display_ops.rst docs/api/obj.rst docs/api/parser.rst docs/api/tls_sni_01.rst letsencrypt_apache/__init__.py letsencrypt_apache/augeas_configurator.py letsencrypt_apache/centos-options-ssl-apache.conf letsencrypt_apache/configurator.py letsencrypt_apache/constants.py letsencrypt_apache/display_ops.py letsencrypt_apache/obj.py letsencrypt_apache/options-ssl-apache.conf letsencrypt_apache/parser.py letsencrypt_apache/tls_sni_01.py letsencrypt_apache.egg-info/PKG-INFO letsencrypt_apache.egg-info/SOURCES.txt letsencrypt_apache.egg-info/dependency_links.txt letsencrypt_apache.egg-info/entry_points.txt letsencrypt_apache.egg-info/requires.txt letsencrypt_apache.egg-info/top_level.txt letsencrypt_apache/augeas_lens/httpd.aug letsencrypt_apache/tests/__init__.py letsencrypt_apache/tests/augeas_configurator_test.py letsencrypt_apache/tests/complex_parsing_test.py letsencrypt_apache/tests/configurator_test.py letsencrypt_apache/tests/constants_test.py letsencrypt_apache/tests/display_ops_test.py letsencrypt_apache/tests/obj_test.py letsencrypt_apache/tests/parser_test.py letsencrypt_apache/tests/tls_sni_01_test.py letsencrypt_apache/tests/util.py letsencrypt_apache/tests/testdata/complex_parsing/apache2.conf letsencrypt_apache/tests/testdata/complex_parsing/test_fnmatch.conf letsencrypt_apache/tests/testdata/complex_parsing/test_variables.conf letsencrypt_apache/tests/testdata/complex_parsing/conf-enabled/dummy.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/sites letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/apache2.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/envvars letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/ports.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/conf-available/other-vhosts-access-log.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/conf-available/security.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/conf-available/serve-cgi-bin.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/conf-enabled/other-vhosts-access-log.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/conf-enabled/security.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/conf-enabled/serve-cgi-bin.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/mods-available/ssl.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/mods-available/ssl.load letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/sites-available/000-default.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/sites-available/default-ssl.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/sites-enabled/000-default.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/sites letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/apache2.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/envvars letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/ports.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/conf-available/bad_conf_file.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/conf-available/other-vhosts-access-log.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/conf-available/security.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/conf-available/serve-cgi-bin.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/conf-enabled/other-vhosts-access-log.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/conf-enabled/security.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/conf-enabled/serve-cgi-bin.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-available/authz_svn.load letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-available/dav.load letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-available/dav_svn.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-available/dav_svn.load letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-available/rewrite.load letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-available/ssl.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-available/ssl.load letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-enabled/.gitignore letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-enabled/authz_svn.load letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-enabled/dav.load letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-enabled/dav_svn.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-enabled/dav_svn.load letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-available/000-default.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-available/default-ssl-port-only.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-available/default-ssl.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-available/encryption-example.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-available/letsencrypt.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-available/mod_macro-example.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-available/wildcard.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-enabled/000-default.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-enabled/encryption-example.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-enabled/letsencrypt.conf letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-enabled/mod_macro-example.confletsencrypt-apache-0.4.1/docs/0000755000175000017500000000000012665157735015654 5ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/docs/.gitignore0000644000175000017500000000001112665157707017633 0ustar bmwbmw00000000000000/_build/ letsencrypt-apache-0.4.1/docs/api.rst0000644000175000017500000000013112665157707017151 0ustar bmwbmw00000000000000================= API Documentation ================= .. toctree:: :glob: api/** letsencrypt-apache-0.4.1/docs/make.bat0000644000175000017500000001614412665157707017266 0ustar bmwbmw00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled echo. coverage to run coverage check of the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) REM Check if sphinx-build is available and fallback to Python version if any %SPHINXBUILD% 2> nul if errorlevel 9009 goto sphinx_python goto sphinx_ok :sphinx_python set SPHINXBUILD=python -m sphinx.__init__ %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) :sphinx_ok if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\letsencrypt-apache.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\letsencrypt-apache.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "coverage" ( %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage if errorlevel 1 exit /b 1 echo. echo.Testing of coverage in the sources finished, look at the ^ results in %BUILDDIR%/coverage/python.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end letsencrypt-apache-0.4.1/docs/Makefile0000644000175000017500000001644112665157707017321 0ustar bmwbmw00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/letsencrypt-apache.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/letsencrypt-apache.qhc" applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/letsencrypt-apache" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/letsencrypt-apache" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." letsencrypt-apache-0.4.1/docs/api/0000755000175000017500000000000012665157735016425 5ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/docs/api/display_ops.rst0000644000175000017500000000021112665157707021476 0ustar bmwbmw00000000000000:mod:`letsencrypt_apache.display_ops` ------------------------------------- .. automodule:: letsencrypt_apache.display_ops :members: letsencrypt-apache-0.4.1/docs/api/augeas_configurator.rst0000644000175000017500000000024112665157707023202 0ustar bmwbmw00000000000000:mod:`letsencrypt_apache.augeas_configurator` --------------------------------------------- .. automodule:: letsencrypt_apache.augeas_configurator :members: letsencrypt-apache-0.4.1/docs/api/parser.rst0000644000175000017500000000017212665157707020452 0ustar bmwbmw00000000000000:mod:`letsencrypt_apache.parser` -------------------------------- .. automodule:: letsencrypt_apache.parser :members: letsencrypt-apache-0.4.1/docs/api/configurator.rst0000644000175000017500000000021412665157707021655 0ustar bmwbmw00000000000000:mod:`letsencrypt_apache.configurator` -------------------------------------- .. automodule:: letsencrypt_apache.configurator :members: letsencrypt-apache-0.4.1/docs/api/tls_sni_01.rst0000644000175000017500000000020612665157707021127 0ustar bmwbmw00000000000000:mod:`letsencrypt_apache.tls_sni_01` ------------------------------------ .. automodule:: letsencrypt_apache.tls_sni_01 :members: letsencrypt-apache-0.4.1/docs/api/obj.rst0000644000175000017500000000016112665157707017726 0ustar bmwbmw00000000000000:mod:`letsencrypt_apache.obj` ----------------------------- .. automodule:: letsencrypt_apache.obj :members: letsencrypt-apache-0.4.1/docs/conf.py0000644000175000017500000002447112665157707017162 0ustar bmwbmw00000000000000# -*- coding: utf-8 -*- # # letsencrypt-apache documentation build configuration file, created by # sphinx-quickstart on Sun Oct 18 13:39:26 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex import mock # http://docs.readthedocs.org/en/latest/faq.html#i-get-import-errors-on-libraries-that-depend-on-c-modules # c.f. #262 sys.modules.update( (mod_name, mock.MagicMock()) for mod_name in ['augeas']) here = os.path.abspath(os.path.dirname(__file__)) # 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(os.path.join(here, '..'))) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', ] autodoc_member_order = 'bysource' autodoc_default_flags = ['show-inheritance', 'private-members'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'letsencrypt-apache' copyright = u'2014-2015, Let\'s Encrypt Project' author = u'Let\'s Encrypt Project' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0' # The full version, including alpha/beta/rc tags. release = '0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = 'en' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. default_role = 'py:obj' # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # http://docs.readthedocs.org/en/latest/theme.html#how-do-i-use-this-locally-and-on-read-the-docs # on_rtd is whether we are on readthedocs.org on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: # only import and set the theme if we're building docs locally import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # otherwise, readthedocs.org uses their theme by default, so no need to specify it # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'letsencrypt-apachedoc' # -- 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 figure (float) alignment #'figure_align': 'htbp', } # 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 = [ (master_doc, 'letsencrypt-apache.tex', u'letsencrypt-apache Documentation', u'Let\'s Encrypt Project', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'letsencrypt-apache', u'letsencrypt-apache Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'letsencrypt-apache', u'letsencrypt-apache Documentation', author, 'letsencrypt-apache', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False intersphinx_mapping = { 'python': ('https://docs.python.org/', None), 'acme': ('https://acme-python.readthedocs.org/en/latest/', None), 'letsencrypt': ('https://letsencrypt.readthedocs.org/en/latest/', None), } letsencrypt-apache-0.4.1/docs/index.rst0000644000175000017500000000104312665157707017512 0ustar bmwbmw00000000000000.. letsencrypt-apache documentation master file, created by sphinx-quickstart on Sun Oct 18 13:39:26 2015. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to letsencrypt-apache's documentation! ============================================== Contents: .. toctree:: :maxdepth: 2 .. toctree:: :maxdepth: 1 api .. automodule:: letsencrypt_apache :members: Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` letsencrypt-apache-0.4.1/docs/_static/0000755000175000017500000000000012665157735017302 5ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/docs/_static/.gitignore0000644000175000017500000000000012665157707021257 0ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/docs/_templates/0000755000175000017500000000000012665157735020011 5ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/docs/_templates/.gitignore0000644000175000017500000000000012665157707021766 0ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/MANIFEST.in0000644000175000017500000000043212665157707016460 0ustar bmwbmw00000000000000include LICENSE.txt include README.rst recursive-include docs * recursive-include letsencrypt_apache/tests/testdata * include letsencrypt_apache/centos-options-ssl-apache.conf include letsencrypt_apache/options-ssl-apache.conf recursive-include letsencrypt_apache/augeas_lens *.aug letsencrypt-apache-0.4.1/LICENSE.txt0000644000175000017500000002504212665157707016551 0ustar bmwbmw00000000000000 Copyright 2015 Electronic Frontier Foundation and others Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS letsencrypt-apache-0.4.1/setup.cfg0000644000175000017500000000007312665157735016545 0ustar bmwbmw00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 letsencrypt-apache-0.4.1/PKG-INFO0000644000175000017500000000173212665157735016024 0ustar bmwbmw00000000000000Metadata-Version: 1.1 Name: letsencrypt-apache Version: 0.4.1 Summary: Apache plugin for Let's Encrypt client Home-page: https://github.com/letsencrypt/letsencrypt Author: Let's Encrypt Project Author-email: client-dev@letsencrypt.org License: Apache License 2.0 Description: UNKNOWN Platform: UNKNOWN Classifier: Development Status :: 3 - Alpha Classifier: Environment :: Plugins Classifier: Intended Audience :: System Administrators Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: POSIX :: Linux Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: Security Classifier: Topic :: System :: Installation/Setup Classifier: Topic :: System :: Networking Classifier: Topic :: System :: Systems Administration Classifier: Topic :: Utilities letsencrypt-apache-0.4.1/README.rst0000644000175000017500000000004712665157707016413 0ustar bmwbmw00000000000000Apache plugin for Let's Encrypt client letsencrypt-apache-0.4.1/letsencrypt_apache/0000755000175000017500000000000012665157735020601 5ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/augeas_configurator.py0000644000175000017500000001633312665157707025207 0ustar bmwbmw00000000000000"""Class of Augeas Configurators.""" import logging import augeas from letsencrypt import errors from letsencrypt import reverter from letsencrypt.plugins import common from letsencrypt_apache import constants logger = logging.getLogger(__name__) class AugeasConfigurator(common.Plugin): """Base Augeas Configurator class. :ivar config: Configuration. :type config: :class:`~letsencrypt.interfaces.IConfig` :ivar aug: Augeas object :type aug: :class:`augeas.Augeas` :ivar str save_notes: Human-readable configuration change notes :ivar reverter: saves and reverts checkpoints :type reverter: :class:`letsencrypt.reverter.Reverter` """ def __init__(self, *args, **kwargs): super(AugeasConfigurator, self).__init__(*args, **kwargs) self.aug = augeas.Augeas( # specify a directory to load our preferred lens from loadpath=constants.AUGEAS_LENS_DIR, # Do not save backup (we do it ourselves), do not load # anything by default flags=(augeas.Augeas.NONE | augeas.Augeas.NO_MODL_AUTOLOAD)) self.save_notes = "" # See if any temporary changes need to be recovered # This needs to occur before VirtualHost objects are setup... # because this will change the underlying configuration and potential # vhosts self.reverter = reverter.Reverter(self.config) self.recovery_routine() def check_parsing_errors(self, lens): """Verify Augeas can parse all of the lens files. :param str lens: lens to check for errors :raises .errors.PluginError: If there has been an error in parsing with the specified lens. """ error_files = self.aug.match("/augeas//error") for path in error_files: # Check to see if it was an error resulting from the use of # the httpd lens lens_path = self.aug.get(path + "/lens") # As aug.get may return null if lens_path and lens in lens_path: msg = ( "There has been an error in parsing the file (%s): %s", # Strip off /augeas/files and /error path[13:len(path) - 6], self.aug.get(path + "/message")) raise errors.PluginError(msg) # TODO: Cleanup this function def save(self, title=None, temporary=False): """Saves all changes to the configuration files. This function first checks for save errors, if none are found, all configuration changes made will be saved. According to the function parameters. If an exception is raised, a new checkpoint was not created. :param str title: The title of the save. If a title is given, the configuration will be saved as a new checkpoint and put in a timestamped directory. :param bool temporary: Indicates whether the changes made will be quickly reversed in the future (ie. challenges) :raises .errors.PluginError: If there was an error in Augeas, in an attempt to save the configuration, or an error creating a checkpoint """ save_state = self.aug.get("/augeas/save") self.aug.set("/augeas/save", "noop") # Existing Errors ex_errs = self.aug.match("/augeas//error") try: # This is a noop save self.aug.save() except (RuntimeError, IOError): self._log_save_errors(ex_errs) # Erase Save Notes self.save_notes = "" raise errors.PluginError( "Error saving files, check logs for more info.") # Retrieve list of modified files # Note: Noop saves can cause the file to be listed twice, I used a # set to remove this possibility. This is a known augeas 0.10 error. save_paths = self.aug.match("/augeas/events/saved") # If the augeas tree didn't change, no files were saved and a backup # should not be created if save_paths: save_files = set() for path in save_paths: save_files.add(self.aug.get(path)[6:]) try: # Create Checkpoint if temporary: self.reverter.add_to_temp_checkpoint( save_files, self.save_notes) else: self.reverter.add_to_checkpoint(save_files, self.save_notes) except errors.ReverterError as err: raise errors.PluginError(str(err)) self.aug.set("/augeas/save", save_state) self.save_notes = "" self.aug.save() if title and not temporary: try: self.reverter.finalize_checkpoint(title) except errors.ReverterError as err: raise errors.PluginError(str(err)) def _log_save_errors(self, ex_errs): """Log errors due to bad Augeas save. :param list ex_errs: Existing errors before save """ # Check for the root of save problems new_errs = self.aug.match("/augeas//error") # logger.error("During Save - %s", mod_conf) logger.error("Unable to save files: %s. Attempted Save Notes: %s", ", ".join(err[13:len(err) - 6] for err in new_errs # Only new errors caused by recent save if err not in ex_errs), self.save_notes) # Wrapper functions for Reverter class def recovery_routine(self): """Revert all previously modified files. Reverts all modified files that have not been saved as a checkpoint :raises .errors.PluginError: If unable to recover the configuration """ try: self.reverter.recovery_routine() except errors.ReverterError as err: raise errors.PluginError(str(err)) # Need to reload configuration after these changes take effect self.aug.load() def revert_challenge_config(self): """Used to cleanup challenge configurations. :raises .errors.PluginError: If unable to revert the challenge config. """ try: self.reverter.revert_temporary_config() except errors.ReverterError as err: raise errors.PluginError(str(err)) self.aug.load() def rollback_checkpoints(self, rollback=1): """Rollback saved checkpoints. :param int rollback: Number of checkpoints to revert :raises .errors.PluginError: If there is a problem with the input or the function is unable to correctly revert the configuration """ try: self.reverter.rollback_checkpoints(rollback) except errors.ReverterError as err: raise errors.PluginError(str(err)) self.aug.load() def view_config_changes(self): """Show all of the configuration changes that have taken place. :raises .errors.PluginError: If there is a problem while processing the checkpoints directories. """ try: self.reverter.view_config_changes() except errors.ReverterError as err: raise errors.PluginError(str(err)) letsencrypt-apache-0.4.1/letsencrypt_apache/parser.py0000644000175000017500000005707312665157707022462 0ustar bmwbmw00000000000000"""ApacheParser is a member object of the ApacheConfigurator class.""" import fnmatch import itertools import logging import os import re import subprocess from letsencrypt import errors from letsencrypt_apache import constants logger = logging.getLogger(__name__) class ApacheParser(object): """Class handles the fine details of parsing the Apache Configuration. .. todo:: Make parsing general... remove sites-available etc... :ivar str root: Normalized absolute path to the server root directory. Without trailing slash. :ivar set modules: All module names that are currently enabled. :ivar dict loc: Location to place directives, root - configuration origin, default - user config file, name - NameVirtualHost, """ arg_var_interpreter = re.compile(r"\$\{[^ \}]*}") fnmatch_chars = set(["*", "?", "\\", "[", "]"]) def __init__(self, aug, root, vhostroot, version=(2, 4)): # Note: Order is important here. # This uses the binary, so it can be done first. # https://httpd.apache.org/docs/2.4/mod/core.html#define # https://httpd.apache.org/docs/2.4/mod/core.html#ifdefine # This only handles invocation parameters and Define directives! self.parser_paths = {} self.variables = {} if version >= (2, 4): self.update_runtime_variables() self.aug = aug # Find configuration root and make sure augeas can parse it. self.root = os.path.abspath(root) self.loc = {"root": self._find_config_root()} self._parse_file(self.loc["root"]) self.vhostroot = os.path.abspath(vhostroot) # This problem has been fixed in Augeas 1.0 self.standardize_excl() # Temporarily set modules to be empty, so that find_dirs can work # https://httpd.apache.org/docs/2.4/mod/core.html#ifmodule # This needs to come before locations are set. self.modules = set() self.init_modules() # Set up rest of locations self.loc.update(self._set_locations()) # Must also attempt to parse virtual host root self._parse_file(self.vhostroot + "/" + constants.os_constant("vhost_files")) # check to see if there were unparsed define statements if version < (2, 4): if self.find_dir("Define", exclude=False): raise errors.PluginError("Error parsing runtime variables") def init_modules(self): """Iterates on the configuration until no new modules are loaded. ..todo:: This should be attempted to be done with a binary to avoid the iteration issue. Else... parse and enable mods at same time. """ # Since modules are being initiated... clear existing set. self.modules = set() matches = self.find_dir("LoadModule") iterator = iter(matches) # Make sure prev_size != cur_size for do: while: iteration prev_size = -1 while len(self.modules) != prev_size: prev_size = len(self.modules) for match_name, match_filename in itertools.izip( iterator, iterator): self.modules.add(self.get_arg(match_name)) self.modules.add( os.path.basename(self.get_arg(match_filename))[:-2] + "c") def update_runtime_variables(self): """" .. note:: Compile time variables (apache2ctl -V) are not used within the dynamic configuration files. These should not be parsed or interpreted. .. todo:: Create separate compile time variables... simply for arg_get() """ stdout = self._get_runtime_cfg() variables = dict() matches = re.compile(r"Define: ([^ \n]*)").findall(stdout) try: matches.remove("DUMP_RUN_CFG") except ValueError: return for match in matches: if match.count("=") > 1: logger.error("Unexpected number of equal signs in " "runtime config dump.") raise errors.PluginError( "Error parsing Apache runtime variables") parts = match.partition("=") variables[parts[0]] = parts[2] self.variables = variables def _get_runtime_cfg(self): # pylint: disable=no-self-use """Get runtime configuration info. :returns: stdout from DUMP_RUN_CFG """ try: proc = subprocess.Popen( constants.os_constant("define_cmd"), stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() except (OSError, ValueError): logger.error( "Error running command %s for runtime parameters!%s", constants.os_constant("define_cmd"), os.linesep) raise errors.MisconfigurationError( "Error accessing loaded Apache parameters: %s", constants.os_constant("define_cmd")) # Small errors that do not impede if proc.returncode != 0: logger.warn("Error in checking parameter list: %s", stderr) raise errors.MisconfigurationError( "Apache is unable to check whether or not the module is " "loaded because Apache is misconfigured.") return stdout def filter_args_num(self, matches, args): # pylint: disable=no-self-use """Filter out directives with specific number of arguments. This function makes the assumption that all related arguments are given in order. Thus /files/apache/directive[5]/arg[2] must come immediately after /files/apache/directive[5]/arg[1]. Runs in 1 linear pass. :param string matches: Matches of all directives with arg nodes :param int args: Number of args you would like to filter :returns: List of directives that contain # of arguments. (arg is stripped off) """ filtered = [] if args == 1: for i in range(len(matches)): if matches[i].endswith("/arg"): filtered.append(matches[i][:-4]) else: for i in range(len(matches)): if matches[i].endswith("/arg[%d]" % args): # Make sure we don't cause an IndexError (end of list) # Check to make sure arg + 1 doesn't exist if (i == (len(matches) - 1) or not matches[i + 1].endswith("/arg[%d]" % (args + 1))): filtered.append(matches[i][:-len("/arg[%d]" % args)]) return filtered def add_dir_to_ifmodssl(self, aug_conf_path, directive, args): """Adds directive and value to IfMod ssl block. Adds given directive and value along configuration path within an IfMod mod_ssl.c block. If the IfMod block does not exist in the file, it is created. :param str aug_conf_path: Desired Augeas config path to add directive :param str directive: Directive you would like to add, e.g. Listen :param args: Values of the directive; str "443" or list of str :type args: list """ # TODO: Add error checking code... does the path given even exist? # Does it throw exceptions? if_mod_path = self._get_ifmod(aug_conf_path, "mod_ssl.c") # IfModule can have only one valid argument, so append after self.aug.insert(if_mod_path + "arg", "directive", False) nvh_path = if_mod_path + "directive[1]" self.aug.set(nvh_path, directive) if len(args) == 1: self.aug.set(nvh_path + "/arg", args[0]) else: for i, arg in enumerate(args): self.aug.set("%s/arg[%d]" % (nvh_path, i + 1), arg) def _get_ifmod(self, aug_conf_path, mod): """Returns the path to and creates one if it doesn't exist. :param str aug_conf_path: Augeas configuration path :param str mod: module ie. mod_ssl.c """ if_mods = self.aug.match(("%s/IfModule/*[self::arg='%s']" % (aug_conf_path, mod))) if len(if_mods) == 0: self.aug.set("%s/IfModule[last() + 1]" % aug_conf_path, "") self.aug.set("%s/IfModule[last()]/arg" % aug_conf_path, mod) if_mods = self.aug.match(("%s/IfModule/*[self::arg='%s']" % (aug_conf_path, mod))) # Strip off "arg" at end of first ifmod path return if_mods[0][:len(if_mods[0]) - 3] def add_dir(self, aug_conf_path, directive, args): """Appends directive to the end fo the file given by aug_conf_path. .. note:: Not added to AugeasConfigurator because it may depend on the lens :param str aug_conf_path: Augeas configuration path to add directive :param str directive: Directive to add :param args: Value of the directive. ie. Listen 443, 443 is arg :type args: list or str """ self.aug.set(aug_conf_path + "/directive[last() + 1]", directive) if isinstance(args, list): for i, value in enumerate(args, 1): self.aug.set( "%s/directive[last()]/arg[%d]" % (aug_conf_path, i), value) else: self.aug.set(aug_conf_path + "/directive[last()]/arg", args) def find_dir(self, directive, arg=None, start=None, exclude=True): """Finds directive in the configuration. Recursively searches through config files to find directives Directives should be in the form of a case insensitive regex currently .. todo:: arg should probably be a list .. todo:: arg search currently only supports direct matching. It does not handle the case of variables or quoted arguments. This should be adapted to use a generic search for the directive and then do a case-insensitive self.get_arg filter Note: Augeas is inherently case sensitive while Apache is case insensitive. Augeas 1.0 allows case insensitive regexes like regexp(/Listen/, "i"), however the version currently supported by Ubuntu 0.10 does not. Thus I have included my own case insensitive transformation by calling case_i() on everything to maintain compatibility. :param str directive: Directive to look for :param arg: Specific value directive must have, None if all should be considered :type arg: str or None :param str start: Beginning Augeas path to begin looking :param bool exclude: Whether or not to exclude directives based on variables and enabled modules """ # Cannot place member variable in the definition of the function so... if not start: start = get_aug_path(self.loc["root"]) # No regexp code # if arg is None: # matches = self.aug.match(start + # "//*[self::directive='" + directive + "']/arg") # else: # matches = self.aug.match(start + # "//*[self::directive='" + directive + # "']/* [self::arg='" + arg + "']") # includes = self.aug.match(start + # "//* [self::directive='Include']/* [label()='arg']") regex = "(%s)|(%s)|(%s)" % (case_i(directive), case_i("Include"), case_i("IncludeOptional")) matches = self.aug.match( "%s//*[self::directive=~regexp('%s')]" % (start, regex)) if exclude: matches = self._exclude_dirs(matches) if arg is None: arg_suffix = "/arg" else: arg_suffix = "/*[self::arg=~regexp('%s')]" % case_i(arg) ordered_matches = [] # TODO: Wildcards should be included in alphabetical order # https://httpd.apache.org/docs/2.4/mod/core.html#include for match in matches: dir_ = self.aug.get(match).lower() if dir_ == "include" or dir_ == "includeoptional": ordered_matches.extend(self.find_dir( directive, arg, self._get_include_path(self.get_arg(match + "/arg")), exclude)) # This additionally allows Include if dir_ == directive.lower(): ordered_matches.extend(self.aug.match(match + arg_suffix)) return ordered_matches def get_arg(self, match): """Uses augeas.get to get argument value and interprets result. This also converts all variables and parameters appropriately. """ value = self.aug.get(match) # No need to strip quotes for variables, as apache2ctl already does # this, but we do need to strip quotes for all normal arguments. # Note: normal argument may be a quoted variable # e.g. strip now, not later value = value.strip("'\"") variables = ApacheParser.arg_var_interpreter.findall(value) for var in variables: # Strip off ${ and } try: value = value.replace(var, self.variables[var[2:-1]]) except KeyError: raise errors.PluginError("Error Parsing variable: %s" % var) return value def _exclude_dirs(self, matches): """Exclude directives that are not loaded into the configuration.""" filters = [("ifmodule", self.modules), ("ifdefine", self.variables)] valid_matches = [] for match in matches: for filter_ in filters: if not self._pass_filter(match, filter_): break else: valid_matches.append(match) return valid_matches def _pass_filter(self, match, filter_): """Determine if directive passes a filter. :param str match: Augeas path :param list filter: list of tuples of form [("lowercase if directive", set of relevant parameters)] """ match_l = match.lower() last_match_idx = match_l.find(filter_[0]) while last_match_idx != -1: # Check args end_of_if = match_l.find("/", last_match_idx) # This should be aug.get (vars are not used e.g. parser.aug_get) expression = self.aug.get(match[:end_of_if] + "/arg") if expression.startswith("!"): # Strip off "!" if expression[1:] in filter_[1]: return False else: if expression not in filter_[1]: return False last_match_idx = match_l.find(filter_[0], end_of_if) return True def _get_include_path(self, arg): """Converts an Apache Include directive into Augeas path. Converts an Apache Include directive argument into an Augeas searchable path .. todo:: convert to use os.path.join() :param str arg: Argument of Include directive :returns: Augeas path string :rtype: str """ # Check to make sure only expected characters are used <- maybe remove # validChars = re.compile("[a-zA-Z0-9.*?_-/]*") # matchObj = validChars.match(arg) # if matchObj.group() != arg: # logger.error("Error: Invalid regexp characters in %s", arg) # return [] # Remove beginning and ending quotes arg = arg.strip("'\"") # Standardize the include argument based on server root if not arg.startswith("/"): # Normpath will condense ../ arg = os.path.normpath(os.path.join(self.root, arg)) else: arg = os.path.normpath(arg) # Attempts to add a transform to the file if one does not already exist if os.path.isdir(arg): self._parse_file(os.path.join(arg, "*")) else: self._parse_file(arg) # Argument represents an fnmatch regular expression, convert it # Split up the path and convert each into an Augeas accepted regex # then reassemble split_arg = arg.split("/") for idx, split in enumerate(split_arg): if any(char in ApacheParser.fnmatch_chars for char in split): # Turn it into a augeas regex # TODO: Can this instead be an augeas glob instead of regex split_arg[idx] = ("* [label()=~regexp('%s')]" % self.fnmatch_to_re(split)) # Reassemble the argument # Note: This also normalizes the argument /serverroot/ -> /serverroot arg = "/".join(split_arg) return get_aug_path(arg) def fnmatch_to_re(self, clean_fn_match): # pylint: disable=no-self-use """Method converts Apache's basic fnmatch to regular expression. Assumption - Configs are assumed to be well-formed and only writable by privileged users. https://apr.apache.org/docs/apr/2.0/apr__fnmatch_8h_source.html http://apache2.sourcearchive.com/documentation/2.2.16-6/apr__fnmatch_8h_source.html :param str clean_fn_match: Apache style filename match, like globs :returns: regex suitable for augeas :rtype: str """ # This strips off final /Z(?ms) return fnmatch.translate(clean_fn_match)[:-7] def _parse_file(self, filepath): """Parse file with Augeas Checks to see if file_path is parsed by Augeas If filepath isn't parsed, the file is added and Augeas is reloaded :param str filepath: Apache config file path """ use_new, remove_old = self._check_path_actions(filepath) # Test if augeas included file for Httpd.lens # Note: This works for augeas globs, ie. *.conf if use_new: inc_test = self.aug.match( "/augeas/load/Httpd['%s' =~ glob(incl)]" % filepath) if not inc_test: # Load up files # This doesn't seem to work on TravisCI # self.aug.add_transform("Httpd.lns", [filepath]) if remove_old: self._remove_httpd_transform(filepath) self._add_httpd_transform(filepath) self.aug.load() def _check_path_actions(self, filepath): """Determine actions to take with a new augeas path This helper function will return a tuple that defines if we should try to append the new filepath to augeas parser paths, and / or remove the old one with more narrow matching. :param str filepath: filepath to check the actions for """ try: new_file_match = os.path.basename(filepath) existing_matches = self.parser_paths[os.path.dirname(filepath)] if "*" in existing_matches: use_new = False else: use_new = True if new_file_match == "*": remove_old = True else: remove_old = False except KeyError: use_new = True remove_old = False return use_new, remove_old def _remove_httpd_transform(self, filepath): """Remove path from Augeas transform :param str filepath: filepath to remove """ remove_basenames = self.parser_paths[os.path.dirname(filepath)] remove_dirname = os.path.dirname(filepath) for name in remove_basenames: remove_path = remove_dirname + "/" + name remove_inc = self.aug.match( "/augeas/load/Httpd/incl [. ='%s']" % remove_path) self.aug.remove(remove_inc[0]) self.parser_paths.pop(remove_dirname) def _add_httpd_transform(self, incl): """Add a transform to Augeas. This function will correctly add a transform to augeas The existing augeas.add_transform in python doesn't seem to work for Travis CI as it loads in libaugeas.so.0.10.0 :param str incl: filepath to include for transform """ last_include = self.aug.match("/augeas/load/Httpd/incl [last()]") if last_include: # Insert a new node immediately after the last incl self.aug.insert(last_include[0], "incl", False) self.aug.set("/augeas/load/Httpd/incl[last()]", incl) # On first use... must load lens and add file to incl else: # Augeas uses base 1 indexing... insert at beginning... self.aug.set("/augeas/load/Httpd/lens", "Httpd.lns") self.aug.set("/augeas/load/Httpd/incl", incl) # Add included path to paths dictionary try: self.parser_paths[os.path.dirname(incl)].append( os.path.basename(incl)) except KeyError: self.parser_paths[os.path.dirname(incl)] = [ os.path.basename(incl)] def standardize_excl(self): """Standardize the excl arguments for the Httpd lens in Augeas. Note: Hack! Standardize the excl arguments for the Httpd lens in Augeas Servers sometimes give incorrect defaults Note: This problem should be fixed in Augeas 1.0. Unfortunately, Augeas 0.10 appears to be the most popular version currently. """ # attempt to protect against augeas error in 0.10.0 - ubuntu # *.augsave -> /*.augsave upon augeas.load() # Try to avoid bad httpd files # There has to be a better way... but after a day and a half of testing # I had no luck # This is a hack... work around... submit to augeas if still not fixed excl = ["*.augnew", "*.augsave", "*.dpkg-dist", "*.dpkg-bak", "*.dpkg-new", "*.dpkg-old", "*.rpmsave", "*.rpmnew", "*~", self.root + "/*.augsave", self.root + "/*~", self.root + "/*/*augsave", self.root + "/*/*~", self.root + "/*/*/*.augsave", self.root + "/*/*/*~"] for i, excluded in enumerate(excl, 1): self.aug.set("/augeas/load/Httpd/excl[%d]" % i, excluded) self.aug.load() def _set_locations(self): """Set default location for directives. Locations are given as file_paths .. todo:: Make sure that files are included """ default = self.loc["root"] temp = os.path.join(self.root, "ports.conf") if os.path.isfile(temp): listen = temp name = temp else: listen = default name = default return {"default": default, "listen": listen, "name": name} def _find_config_root(self): """Find the Apache Configuration Root file.""" location = ["apache2.conf", "httpd.conf", "conf/httpd.conf"] for name in location: if os.path.isfile(os.path.join(self.root, name)): return os.path.join(self.root, name) raise errors.NoInstallationError("Could not find configuration root") def case_i(string): """Returns case insensitive regex. Returns a sloppy, but necessary version of a case insensitive regex. Any string should be able to be submitted and the string is escaped and then made case insensitive. May be replaced by a more proper /i once augeas 1.0 is widely supported. :param str string: string to make case i regex """ return "".join(["[" + c.upper() + c.lower() + "]" if c.isalpha() else c for c in re.escape(string)]) def get_aug_path(file_path): """Return augeas path for full filepath. :param str file_path: Full filepath """ return "/files%s" % file_path letsencrypt-apache-0.4.1/letsencrypt_apache/__init__.py0000644000175000017500000000004312665157707022706 0ustar bmwbmw00000000000000"""Let's Encrypt Apache plugin.""" letsencrypt-apache-0.4.1/letsencrypt_apache/configurator.py0000644000175000017500000017751012665157707023667 0ustar bmwbmw00000000000000"""Apache Configuration based off of Augeas Configurator.""" # pylint: disable=too-many-lines import filecmp import logging import os import re import shutil import socket import time import zope.component import zope.interface from acme import challenges from letsencrypt import errors from letsencrypt import interfaces from letsencrypt import le_util from letsencrypt.plugins import common from letsencrypt_apache import augeas_configurator from letsencrypt_apache import constants from letsencrypt_apache import display_ops from letsencrypt_apache import tls_sni_01 from letsencrypt_apache import obj from letsencrypt_apache import parser from collections import defaultdict logger = logging.getLogger(__name__) # TODO: Augeas sections ie. , beginning and closing # tags need to be the same case, otherwise Augeas doesn't recognize them. # This is not able to be completely remedied by regular expressions because # Augeas views as an error. This will just # require another check_parsing_errors() after all files are included... # (after a find_directive search is executed currently). It can be a one # time check however because all of LE's transactions will ensure # only properly formed sections are added. # Note: This protocol works for filenames with spaces in it, the sites are # properly set up and directives are changed appropriately, but Apache won't # recognize names in sites-enabled that have spaces. These are not added to the # Apache configuration. It may be wise to warn the user if they are trying # to use vhost filenames that contain spaces and offer to change ' ' to '_' # Note: FILEPATHS and changes to files are transactional. They are copied # over before the updates are made to the existing files. NEW_FILES is # transactional due to the use of register_file_creation() # TODO: Verify permissions on configuration root... it is easier than # checking permissions on each of the relative directories and less error # prone. # TODO: Write a server protocol finder. Listen or # Protocol . This can verify partial setups are correct # TODO: Add directives to sites-enabled... not sites-available. # sites-available doesn't allow immediate find_dir search even with save() # and load() @zope.interface.implementer(interfaces.IAuthenticator, interfaces.IInstaller) @zope.interface.provider(interfaces.IPluginFactory) class ApacheConfigurator(augeas_configurator.AugeasConfigurator): # pylint: disable=too-many-instance-attributes,too-many-public-methods """Apache configurator. State of Configurator: This code has been been tested and built for Ubuntu 14.04 Apache 2.4 and it works for Ubuntu 12.04 Apache 2.2 :ivar config: Configuration. :type config: :class:`~letsencrypt.interfaces.IConfig` :ivar parser: Handles low level parsing :type parser: :class:`~letsencrypt_apache.parser` :ivar tup version: version of Apache :ivar list vhosts: All vhosts found in the configuration (:class:`list` of :class:`~letsencrypt_apache.obj.VirtualHost`) :ivar dict assoc: Mapping between domains and vhosts """ description = "Apache Web Server - Alpha" @classmethod def add_parser_arguments(cls, add): add("enmod", default=constants.os_constant("enmod"), help="Path to the Apache 'a2enmod' binary.") add("dismod", default=constants.os_constant("dismod"), help="Path to the Apache 'a2dismod' binary.") add("le-vhost-ext", default=constants.os_constant("le_vhost_ext"), help="SSL vhost configuration extension.") add("server-root", default=constants.os_constant("server_root"), help="Apache server root directory.") add("vhost-root", default=constants.os_constant("vhost_root"), help="Apache server VirtualHost configuration root") add("challenge-location", default=constants.os_constant("challenge_location"), help="Directory path for challenge configuration.") add("handle-modules", default=constants.os_constant("handle_mods"), help="Let installer handle enabling required modules for you." + "(Only Ubuntu/Debian currently)") add("handle-sites", default=constants.os_constant("handle_sites"), help="Let installer handle enabling sites for you." + "(Only Ubuntu/Debian currently)") le_util.add_deprecated_argument(add, argument_name="ctl", nargs=1) le_util.add_deprecated_argument( add, argument_name="init-script", nargs=1) def __init__(self, *args, **kwargs): """Initialize an Apache Configurator. :param tup version: version of Apache as a tuple (2, 4, 7) (used mostly for unittesting) """ version = kwargs.pop("version", None) super(ApacheConfigurator, self).__init__(*args, **kwargs) # Add name_server association dict self.assoc = dict() # Outstanding challenges self._chall_out = set() # These will be set in the prepare function self.parser = None self.version = version self.vhosts = None self._enhance_func = {"redirect": self._enable_redirect, "ensure-http-header": self._set_http_header} @property def mod_ssl_conf(self): """Full absolute path to SSL configuration file.""" return os.path.join(self.config.config_dir, constants.MOD_SSL_CONF_DEST) def prepare(self): """Prepare the authenticator/installer. :raises .errors.NoInstallationError: If Apache configs cannot be found :raises .errors.MisconfigurationError: If Apache is misconfigured :raises .errors.NotSupportedError: If Apache version is not supported :raises .errors.PluginError: If there is any other error """ # Verify Apache is installed if not le_util.exe_exists(constants.os_constant("restart_cmd")[0]): raise errors.NoInstallationError # Make sure configuration is valid self.config_test() # Set Version if self.version is None: self.version = self.get_version() if self.version < (2, 2): raise errors.NotSupportedError( "Apache Version %s not supported.", str(self.version)) if not self._check_aug_version(): raise errors.NotSupportedError( "Apache plugin support requires libaugeas0 and augeas-lenses " "version 1.2.0 or higher, please make sure you have you have " "those installed.") self.parser = parser.ApacheParser( self.aug, self.conf("server-root"), self.conf("vhost-root"), self.version) # Check for errors in parsing files with Augeas self.check_parsing_errors("httpd.aug") # Get all of the available vhosts self.vhosts = self.get_virtual_hosts() install_ssl_options_conf(self.mod_ssl_conf) def _check_aug_version(self): """ Checks that we have recent enough version of libaugeas. If augeas version is recent enough, it will support case insensitive regexp matching""" self.aug.set("/test/path/testing/arg", "aRgUMeNT") try: matches = self.aug.match( "/test//*[self::arg=~regexp('argument', 'i')]") except RuntimeError: self.aug.remove("/test/path") return False self.aug.remove("/test/path") return matches def deploy_cert(self, domain, cert_path, key_path, chain_path=None, fullchain_path=None): """Deploys certificate to specified virtual host. Currently tries to find the last directives to deploy the cert in the VHost associated with the given domain. If it can't find the directives, it searches the "included" confs. The function verifies that it has located the three directives and finally modifies them to point to the correct destination. After the certificate is installed, the VirtualHost is enabled if it isn't already. .. todo:: Might be nice to remove chain directive if none exists This shouldn't happen within letsencrypt though :raises errors.PluginError: When unable to deploy certificate due to a lack of directives """ vhost = self.choose_vhost(domain) self._clean_vhost(vhost) # This is done first so that ssl module is enabled and cert_path, # cert_key... can all be parsed appropriately self.prepare_server_https("443") path = {"cert_path": self.parser.find_dir("SSLCertificateFile", None, vhost.path), "cert_key": self.parser.find_dir("SSLCertificateKeyFile", None, vhost.path)} # Only include if a certificate chain is specified if chain_path is not None: path["chain_path"] = self.parser.find_dir( "SSLCertificateChainFile", None, vhost.path) if not path["cert_path"] or not path["cert_key"]: # Throw some can't find all of the directives error" logger.warn( "Cannot find a cert or key directive in %s. " "VirtualHost was not modified", vhost.path) # Presumably break here so that the virtualhost is not modified raise errors.PluginError( "Unable to find cert and/or key directives") logger.info("Deploying Certificate to VirtualHost %s", vhost.filep) logger.debug("Apache version is %s", ".".join(str(i) for i in self.version)) if self.version < (2, 4, 8) or (chain_path and not fullchain_path): # install SSLCertificateFile, SSLCertificateKeyFile, # and SSLCertificateChainFile directives set_cert_path = cert_path self.aug.set(path["cert_path"][-1], cert_path) self.aug.set(path["cert_key"][-1], key_path) if chain_path is not None: self.parser.add_dir(vhost.path, "SSLCertificateChainFile", chain_path) else: raise errors.PluginError("--chain-path is required for your " "version of Apache") else: if not fullchain_path: raise errors.PluginError("Please provide the --fullchain-path\ option pointing to your full chain file") set_cert_path = fullchain_path self.aug.set(path["cert_path"][-1], fullchain_path) self.aug.set(path["cert_key"][-1], key_path) # Save notes about the transaction that took place self.save_notes += ("Changed vhost at %s with addresses of %s\n" "\tSSLCertificateFile %s\n" "\tSSLCertificateKeyFile %s\n" % (vhost.filep, ", ".join(str(addr) for addr in vhost.addrs), set_cert_path, key_path)) if chain_path is not None: self.save_notes += "\tSSLCertificateChainFile %s\n" % chain_path # Make sure vhost is enabled if distro with enabled / available if self.conf("handle-sites"): if not vhost.enabled: self.enable_site(vhost) def choose_vhost(self, target_name, temp=False): """Chooses a virtual host based on the given domain name. If there is no clear virtual host to be selected, the user is prompted with all available choices. The returned vhost is guaranteed to have TLS enabled unless temp is True. If temp is True, there is no such guarantee and the result is not cached. :param str target_name: domain name :param bool temp: whether the vhost is only used temporarily :returns: ssl vhost associated with name :rtype: :class:`~letsencrypt_apache.obj.VirtualHost` :raises .errors.PluginError: If no vhost is available or chosen """ # Allows for domain names to be associated with a virtual host if target_name in self.assoc: return self.assoc[target_name] # Try to find a reasonable vhost vhost = self._find_best_vhost(target_name) if vhost is not None: if temp: return vhost if not vhost.ssl: vhost = self.make_vhost_ssl(vhost) self._add_servername_alias(target_name, vhost) self.assoc[target_name] = vhost return vhost return self._choose_vhost_from_list(target_name, temp) def _choose_vhost_from_list(self, target_name, temp=False): # Select a vhost from a list vhost = display_ops.select_vhost(target_name, self.vhosts) if vhost is None: logger.error( "No vhost exists with servername or alias of: %s. " "No vhost was selected. Please specify servernames " "in the Apache config", target_name) raise errors.PluginError("No vhost selected") elif temp: return vhost elif not vhost.ssl: addrs = self._get_proposed_addrs(vhost, "443") # TODO: Conflicts is too conservative if not any(vhost.enabled and vhost.conflicts(addrs) for vhost in self.vhosts): vhost = self.make_vhost_ssl(vhost) else: logger.error( "The selected vhost would conflict with other HTTPS " "VirtualHosts within Apache. Please select another " "vhost or add ServerNames to your configuration.") raise errors.PluginError( "VirtualHost not able to be selected.") self._add_servername_alias(target_name, vhost) self.assoc[target_name] = vhost return vhost def included_in_wildcard(self, names, target_name): """Helper function to see if alias is covered by wildcard""" target_name = target_name.split(".")[::-1] wildcards = [domain.split(".")[1:] for domain in names if domain.startswith("*")] for wildcard in wildcards: if len(wildcard) > len(target_name): continue for idx, segment in enumerate(wildcard[::-1]): if segment != target_name[idx]: break else: # https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops return True return False def _find_best_vhost(self, target_name): """Finds the best vhost for a target_name. This does not upgrade a vhost to HTTPS... it only finds the most appropriate vhost for the given target_name. :returns: VHost or None """ # Points 6 - Servername SSL # Points 5 - Wildcard SSL # Points 4 - Address name with SSL # Points 3 - Servername no SSL # Points 2 - Wildcard no SSL # Points 1 - Address name with no SSL best_candidate = None best_points = 0 for vhost in self.vhosts: if vhost.modmacro is True: continue names = vhost.get_names() if target_name in names: points = 3 elif self.included_in_wildcard(names, target_name): points = 2 elif any(addr.get_addr() == target_name for addr in vhost.addrs): points = 1 else: # No points given if names can't be found. # This gets hit but doesn't register continue # pragma: no cover if vhost.ssl: points += 3 if points > best_points: best_points = points best_candidate = vhost # No winners here... is there only one reasonable vhost? if best_candidate is None: # reasonable == Not all _default_ addrs vhosts = self._non_default_vhosts() # remove mod_macro hosts from reasonable vhosts reasonable_vhosts = [vh for vh in vhosts if vh.modmacro is False] if len(reasonable_vhosts) == 1: best_candidate = reasonable_vhosts[0] return best_candidate def _non_default_vhosts(self): """Return all non _default_ only vhosts.""" return [vh for vh in self.vhosts if not all( addr.get_addr() == "_default_" for addr in vh.addrs )] def get_all_names(self): """Returns all names found in the Apache Configuration. :returns: All ServerNames, ServerAliases, and reverse DNS entries for virtual host addresses :rtype: set """ all_names = set() vhost_macro = [] for vhost in self.vhosts: all_names.update(vhost.get_names()) if vhost.modmacro: vhost_macro.append(vhost.filep) for addr in vhost.addrs: if common.hostname_regex.match(addr.get_addr()): all_names.add(addr.get_addr()) else: name = self.get_name_from_ip(addr) if name: all_names.add(name) if len(vhost_macro) > 0: zope.component.getUtility(interfaces.IDisplay).notification( "Apache mod_macro seems to be in use in file(s):\n{0}" "\n\nUnfortunately mod_macro is not yet supported".format( "\n ".join(vhost_macro))) return all_names def get_name_from_ip(self, addr): # pylint: disable=no-self-use """Returns a reverse dns name if available. :param addr: IP Address :type addr: ~.common.Addr :returns: name or empty string if name cannot be determined :rtype: str """ # If it isn't a private IP, do a reverse DNS lookup if not common.private_ips_regex.match(addr.get_addr()): try: socket.inet_aton(addr.get_addr()) return socket.gethostbyaddr(addr.get_addr())[0] except (socket.error, socket.herror, socket.timeout): pass return "" def _add_servernames(self, host): """Helper function for get_virtual_hosts(). :param host: In progress vhost whose names will be added :type host: :class:`~letsencrypt_apache.obj.VirtualHost` """ # Take the final ServerName as each overrides the previous servername_match = self.parser.find_dir( "ServerName", None, start=host.path, exclude=False) serveralias_match = self.parser.find_dir( "ServerAlias", None, start=host.path, exclude=False) for alias in serveralias_match: serveralias = self.parser.get_arg(alias) if not host.modmacro: host.aliases.add(serveralias) if servername_match: # Get last ServerName as each overwrites the previous servername = self.parser.get_arg(servername_match[-1]) if not host.modmacro: host.name = servername def _create_vhost(self, path): """Used by get_virtual_hosts to create vhost objects :param str path: Augeas path to virtual host :returns: newly created vhost :rtype: :class:`~letsencrypt_apache.obj.VirtualHost` """ addrs = set() args = self.aug.match(path + "/arg") for arg in args: addrs.add(obj.Addr.fromstring(self.parser.get_arg(arg))) is_ssl = False if self.parser.find_dir("SSLEngine", "on", start=path, exclude=False): is_ssl = True # "SSLEngine on" might be set outside of # Treat vhosts with port 443 as ssl vhosts for addr in addrs: if addr.get_port() == "443": is_ssl = True filename = get_file_path(path) if self.conf("handle-sites"): is_enabled = self.is_site_enabled(filename) else: is_enabled = True macro = False if "/macro/" in path.lower(): macro = True vhost = obj.VirtualHost(filename, path, addrs, is_ssl, is_enabled, modmacro=macro) self._add_servernames(vhost) return vhost def get_virtual_hosts(self): """Returns list of virtual hosts found in the Apache configuration. :returns: List of :class:`~letsencrypt_apache.obj.VirtualHost` objects found in configuration :rtype: list """ # Search base config, and all included paths for VirtualHosts vhs = [] vhost_paths = {} for vhost_path in self.parser.parser_paths.keys(): paths = self.aug.match( ("/files%s//*[label()=~regexp('%s')]" % (vhost_path, parser.case_i("VirtualHost")))) for path in paths: new_vhost = self._create_vhost(path) realpath = os.path.realpath(new_vhost.filep) if realpath not in vhost_paths.keys(): vhs.append(new_vhost) vhost_paths[realpath] = new_vhost.filep elif realpath == new_vhost.filep: # Prefer "real" vhost paths instead of symlinked ones # ex: sites-enabled/vh.conf -> sites-available/vh.conf # remove old (most likely) symlinked one vhs = [v for v in vhs if v.filep != vhost_paths[realpath]] vhs.append(new_vhost) vhost_paths[realpath] = realpath return vhs def is_name_vhost(self, target_addr): """Returns if vhost is a name based vhost NameVirtualHost was deprecated in Apache 2.4 as all VirtualHosts are now NameVirtualHosts. If version is earlier than 2.4, check if addr has a NameVirtualHost directive in the Apache config :param letsencrypt_apache.obj.Addr target_addr: vhost address :returns: Success :rtype: bool """ # Mixed and matched wildcard NameVirtualHost with VirtualHost # behavior is undefined. Make sure that an exact match exists # search for NameVirtualHost directive for ip_addr # note ip_addr can be FQDN although Apache does not recommend it return (self.version >= (2, 4) or self.parser.find_dir("NameVirtualHost", str(target_addr))) def add_name_vhost(self, addr): """Adds NameVirtualHost directive for given address. :param addr: Address that will be added as NameVirtualHost directive :type addr: :class:`~letsencrypt_apache.obj.Addr` """ loc = parser.get_aug_path(self.parser.loc["name"]) if addr.get_port() == "443": path = self.parser.add_dir_to_ifmodssl( loc, "NameVirtualHost", [str(addr)]) else: path = self.parser.add_dir(loc, "NameVirtualHost", [str(addr)]) msg = ("Setting %s to be NameBasedVirtualHost\n" "\tDirective added to %s\n" % (addr, path)) logger.debug(msg) self.save_notes += msg def prepare_server_https(self, port, temp=False): """Prepare the server for HTTPS. Make sure that the ssl_module is loaded and that the server is appropriately listening on port. :param str port: Port to listen on """ self.prepare_https_modules(temp) # Check for Listen # Note: This could be made to also look for ip:443 combo listens = [self.parser.get_arg(x).split()[0] for x in self.parser.find_dir("Listen")] # In case no Listens are set (which really is a broken apache config) if not listens: listens = ["80"] if port in listens: return for listen in listens: # For any listen statement, check if the machine also listens on # Port 443. If not, add such a listen statement. if len(listen.split(":")) == 1: # Its listening to all interfaces if port not in listens: if port == "443": args = [port] else: # Non-standard ports should specify https protocol args = [port, "https"] self.parser.add_dir_to_ifmodssl( parser.get_aug_path( self.parser.loc["listen"]), "Listen", args) self.save_notes += "Added Listen %s directive to %s\n" % ( port, self.parser.loc["listen"]) listens.append(port) else: # The Listen statement specifies an ip _, ip = listen[::-1].split(":", 1) ip = ip[::-1] if "%s:%s" % (ip, port) not in listens: if port == "443": args = ["%s:%s" % (ip, port)] else: # Non-standard ports should specify https protocol args = ["%s:%s" % (ip, port), "https"] self.parser.add_dir_to_ifmodssl( parser.get_aug_path( self.parser.loc["listen"]), "Listen", args) self.save_notes += ("Added Listen %s:%s directive to " "%s\n") % (ip, port, self.parser.loc["listen"]) listens.append("%s:%s" % (ip, port)) def prepare_https_modules(self, temp): """Helper method for prepare_server_https, taking care of enabling needed modules :param boolean temp: If the change is temporary """ if self.conf("handle-modules"): if self.version >= (2, 4) and ("socache_shmcb_module" not in self.parser.modules): self.enable_mod("socache_shmcb", temp=temp) if "ssl_module" not in self.parser.modules: self.enable_mod("ssl", temp=temp) def make_addrs_sni_ready(self, addrs): """Checks to see if the server is ready for SNI challenges. :param addrs: Addresses to check SNI compatibility :type addrs: :class:`~letsencrypt_apache.obj.Addr` """ # Version 2.4 and later are automatically SNI ready. if self.version >= (2, 4): return for addr in addrs: if not self.is_name_vhost(addr): logger.debug("Setting VirtualHost at %s to be a name " "based virtual host", addr) self.add_name_vhost(addr) def make_vhost_ssl(self, nonssl_vhost): # pylint: disable=too-many-locals """Makes an ssl_vhost version of a nonssl_vhost. Duplicates vhost and adds default ssl options New vhost will reside as (nonssl_vhost.path) + ``letsencrypt_apache.constants.os_constant("le_vhost_ext")`` .. note:: This function saves the configuration :param nonssl_vhost: Valid VH that doesn't have SSLEngine on :type nonssl_vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :returns: SSL vhost :rtype: :class:`~letsencrypt_apache.obj.VirtualHost` :raises .errors.PluginError: If more than one virtual host is in the file or if plugin is unable to write/read vhost files. """ avail_fp = nonssl_vhost.filep ssl_fp = self._get_ssl_vhost_path(avail_fp) self._copy_create_ssl_vhost_skeleton(avail_fp, ssl_fp) # Reload augeas to take into account the new vhost self.aug.load() # Get Vhost augeas path for new vhost vh_p = self.aug.match("/files%s//* [label()=~regexp('%s')]" % (ssl_fp, parser.case_i("VirtualHost"))) if len(vh_p) != 1: logger.error("Error: should only be one vhost in %s", avail_fp) raise errors.PluginError("Currently, we only support " "configurations with one vhost per file") else: # This simplifies the process vh_p = vh_p[0] # Update Addresses self._update_ssl_vhosts_addrs(vh_p) # Add directives self._add_dummy_ssl_directives(vh_p) self.save() # Log actions and create save notes logger.info("Created an SSL vhost at %s", ssl_fp) self.save_notes += "Created ssl vhost at %s\n" % ssl_fp self.save() # We know the length is one because of the assertion above # Create the Vhost object ssl_vhost = self._create_vhost(vh_p) self.vhosts.append(ssl_vhost) # NOTE: Searches through Augeas seem to ruin changes to directives # The configuration must also be saved before being searched # for the new directives; For these reasons... this is tacked # on after fully creating the new vhost # Now check if addresses need to be added as NameBasedVhost addrs # This is for compliance with versions of Apache < 2.4 self._add_name_vhost_if_necessary(ssl_vhost) return ssl_vhost def _get_ssl_vhost_path(self, non_ssl_vh_fp): # Get filepath of new ssl_vhost if non_ssl_vh_fp.endswith(".conf"): return non_ssl_vh_fp[:-(len(".conf"))] + self.conf("le_vhost_ext") else: return non_ssl_vh_fp + self.conf("le_vhost_ext") def _sift_line(self, line): """Decides whether a line should be copied to a SSL vhost. A canonical example of when sifting a line is required: When the http vhost contains a RewriteRule that unconditionally redirects any request to the https version of the same site. e.g: RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,QSA,R=permanent] Copying the above line to the ssl vhost would cause a redirection loop. :param str line: a line extracted from the http vhost. :returns: True - don't copy line from http vhost to SSL vhost. :rtype: bool """ if not line.lstrip().startswith("RewriteRule"): return False # According to: http://httpd.apache.org/docs/2.4/rewrite/flags.html # The syntax of a RewriteRule is: # RewriteRule pattern target [Flag1,Flag2,Flag3] # i.e. target is required, so it must exist. target = line.split()[2].strip() # target may be surrounded with quotes if target[0] in ("'", '"') and target[0] == target[-1]: target = target[1:-1] # Sift line if it redirects the request to a HTTPS site return target.startswith("https://") def _copy_create_ssl_vhost_skeleton(self, avail_fp, ssl_fp): """Copies over existing Vhost with IfModule mod_ssl.c> skeleton. :param str avail_fp: Pointer to the original available non-ssl vhost :param str ssl_fp: Full path where the new ssl_vhost will reside. A new file is created on the filesystem. """ # First register the creation so that it is properly removed if # configuration is rolled back self.reverter.register_file_creation(False, ssl_fp) sift = False try: with open(avail_fp, "r") as orig_file: with open(ssl_fp, "w") as new_file: new_file.write("\n") for line in orig_file: if self._sift_line(line): if not sift: new_file.write( "# Some rewrite rules in this file were " "were disabled on your HTTPS site,\n" "# because they have the potential to " "create redirection loops.\n") sift = True new_file.write("# " + line) else: new_file.write(line) new_file.write("\n") except IOError: logger.fatal("Error writing/reading to file in make_vhost_ssl") raise errors.PluginError("Unable to write/read in make_vhost_ssl") if sift: reporter = zope.component.getUtility(interfaces.IReporter) reporter.add_message( "Some rewrite rules copied from {0} were disabled in the " "vhost for your HTTPS site located at {1} because they have " "the potential to create redirection loops.".format(avail_fp, ssl_fp), reporter.MEDIUM_PRIORITY) def _update_ssl_vhosts_addrs(self, vh_path): ssl_addrs = set() ssl_addr_p = self.aug.match(vh_path + "/arg") for addr in ssl_addr_p: old_addr = obj.Addr.fromstring( str(self.parser.get_arg(addr))) ssl_addr = old_addr.get_addr_obj("443") self.aug.set(addr, str(ssl_addr)) ssl_addrs.add(ssl_addr) return ssl_addrs def _clean_vhost(self, vhost): # remove duplicated or conflicting ssl directives self._deduplicate_directives(vhost.path, ["SSLCertificateFile", "SSLCertificateKeyFile"]) # remove all problematic directives self._remove_directives(vhost.path, ["SSLCertificateChainFile"]) def _deduplicate_directives(self, vh_path, directives): for directive in directives: while len(self.parser.find_dir(directive, None, vh_path, False)) > 1: directive_path = self.parser.find_dir(directive, None, vh_path, False) self.aug.remove(re.sub(r"/\w*$", "", directive_path[0])) def _remove_directives(self, vh_path, directives): for directive in directives: while len(self.parser.find_dir(directive, None, vh_path, False)) > 0: directive_path = self.parser.find_dir(directive, None, vh_path, False) self.aug.remove(re.sub(r"/\w*$", "", directive_path[0])) def _add_dummy_ssl_directives(self, vh_path): self.parser.add_dir(vh_path, "SSLCertificateFile", "insert_cert_file_path") self.parser.add_dir(vh_path, "SSLCertificateKeyFile", "insert_key_file_path") self.parser.add_dir(vh_path, "Include", self.mod_ssl_conf) def _add_servername_alias(self, target_name, vhost): fp = vhost.filep vh_p = self.aug.match("/files%s//* [label()=~regexp('%s')]" % (fp, parser.case_i("VirtualHost"))) if not vh_p: return vh_path = vh_p[0] if (self.parser.find_dir("ServerName", target_name, start=vh_path, exclude=False) or self.parser.find_dir("ServerAlias", target_name, start=vh_path, exclude=False)): return if not self.parser.find_dir("ServerName", None, start=vh_path, exclude=False): self.parser.add_dir(vh_path, "ServerName", target_name) else: self.parser.add_dir(vh_path, "ServerAlias", target_name) self._add_servernames(vhost) def _add_name_vhost_if_necessary(self, vhost): """Add NameVirtualHost Directives if necessary for new vhost. NameVirtualHosts was a directive in Apache < 2.4 https://httpd.apache.org/docs/2.2/mod/core.html#namevirtualhost :param vhost: New virtual host that was recently created. :type vhost: :class:`~letsencrypt_apache.obj.VirtualHost` """ need_to_save = False # See if the exact address appears in any other vhost # Remember 1.1.1.1:* == 1.1.1.1 -> hence any() for addr in vhost.addrs: # In Apache 2.2, when a NameVirtualHost directive is not # set, "*" and "_default_" will conflict when sharing a port addrs = set((addr,)) if addr.get_addr() in ("*", "_default_"): addrs.update(obj.Addr((a, addr.get_port(),)) for a in ("*", "_default_")) for test_vh in self.vhosts: if (vhost.filep != test_vh.filep and any(test_addr in addrs for test_addr in test_vh.addrs) and not self.is_name_vhost(addr)): self.add_name_vhost(addr) logger.info("Enabling NameVirtualHosts on %s", addr) need_to_save = True break if need_to_save: self.save() ###################################################################### # Enhancements ###################################################################### def supported_enhancements(self): # pylint: disable=no-self-use """Returns currently supported enhancements.""" return ["redirect", "ensure-http-header"] def enhance(self, domain, enhancement, options=None): """Enhance configuration. :param str domain: domain to enhance :param str enhancement: enhancement type defined in :const:`~letsencrypt.constants.ENHANCEMENTS` :param options: options for the enhancement See :const:`~letsencrypt.constants.ENHANCEMENTS` documentation for appropriate parameter. :raises .errors.PluginError: If Enhancement is not supported, or if there is any other problem with the enhancement. """ try: func = self._enhance_func[enhancement] except KeyError: raise errors.PluginError( "Unsupported enhancement: {0}".format(enhancement)) try: func(self.choose_vhost(domain), options) except errors.PluginError: logger.warn("Failed %s for %s", enhancement, domain) raise def _set_http_header(self, ssl_vhost, header_substring): """Enables header that is identified by header_substring on ssl_vhost. If the header identified by header_substring is not already set, a new Header directive is placed in ssl_vhost's configuration with arguments from: constants.HTTP_HEADER[header_substring] .. note:: This function saves the configuration :param ssl_vhost: Destination of traffic, an ssl enabled vhost :type ssl_vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :param header_substring: string that uniquely identifies a header. e.g: Strict-Transport-Security, Upgrade-Insecure-Requests. :type str :returns: Success, general_vhost (HTTP vhost) :rtype: (bool, :class:`~letsencrypt_apache.obj.VirtualHost`) :raises .errors.PluginError: If no viable HTTP host can be created or set with header header_substring. """ if "headers_module" not in self.parser.modules: self.enable_mod("headers") # Check if selected header is already set self._verify_no_matching_http_header(ssl_vhost, header_substring) # Add directives to server self.parser.add_dir(ssl_vhost.path, "Header", constants.HEADER_ARGS[header_substring]) self.save_notes += ("Adding %s header to ssl vhost in %s\n" % (header_substring, ssl_vhost.filep)) self.save() logger.info("Adding %s header to ssl vhost in %s", header_substring, ssl_vhost.filep) def _verify_no_matching_http_header(self, ssl_vhost, header_substring): """Checks to see if an there is an existing Header directive that contains the string header_substring. :param ssl_vhost: vhost to check :type vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :param header_substring: string that uniquely identifies a header. e.g: Strict-Transport-Security, Upgrade-Insecure-Requests. :type str :returns: boolean :rtype: (bool) :raises errors.PluginEnhancementAlreadyPresent When header header_substring exists """ header_path = self.parser.find_dir("Header", None, start=ssl_vhost.path) if header_path: # "Existing Header directive for virtualhost" pat = '(?:[ "]|^)(%s)(?:[ "]|$)' % (header_substring.lower()) for match in header_path: if re.search(pat, self.aug.get(match).lower()): raise errors.PluginEnhancementAlreadyPresent( "Existing %s header" % (header_substring)) def _enable_redirect(self, ssl_vhost, unused_options): """Redirect all equivalent HTTP traffic to ssl_vhost. .. todo:: This enhancement should be rewritten and will unfortunately require lots of debugging by hand. Adds Redirect directive to the port 80 equivalent of ssl_vhost First the function attempts to find the vhost with equivalent ip addresses that serves on non-ssl ports The function then adds the directive .. note:: This function saves the configuration :param ssl_vhost: Destination of traffic, an ssl enabled vhost :type ssl_vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :param unused_options: Not currently used :type unused_options: Not Available :returns: Success, general_vhost (HTTP vhost) :rtype: (bool, :class:`~letsencrypt_apache.obj.VirtualHost`) :raises .errors.PluginError: If no viable HTTP host can be created or used for the redirect. """ if "rewrite_module" not in self.parser.modules: self.enable_mod("rewrite") general_vh = self._get_http_vhost(ssl_vhost) if general_vh is None: # Add virtual_server with redirect logger.debug("Did not find http version of ssl virtual host " "attempting to create") redirect_addrs = self._get_proposed_addrs(ssl_vhost) for vhost in self.vhosts: if vhost.enabled and vhost.conflicts(redirect_addrs): raise errors.PluginError( "Unable to find corresponding HTTP vhost; " "Unable to create one as intended addresses conflict; " "Current configuration does not support automated " "redirection") self._create_redirect_vhost(ssl_vhost) else: # Check if LetsEncrypt redirection already exists self._verify_no_letsencrypt_redirect(general_vh) # Note: if code flow gets here it means we didn't find the exact # letsencrypt RewriteRule config for redirection. Finding # another RewriteRule is likely to be fine in most or all cases, # but redirect loops are possible in very obscure cases; see #1620 # for reasoning. if self._is_rewrite_exists(general_vh): logger.warn("Added an HTTP->HTTPS rewrite in addition to " "other RewriteRules; you may wish to check for " "overall consistency.") # Add directives to server # Note: These are not immediately searchable in sites-enabled # even with save() and load() if not self._is_rewrite_engine_on(general_vh): self.parser.add_dir(general_vh.path, "RewriteEngine", "on") names = ssl_vhost.get_names() for idx, name in enumerate(names): args = ["%{SERVER_NAME}", "={0}".format(name), "[OR]"] if idx == len(names) - 1: args.pop() self.parser.add_dir(general_vh.path, "RewriteCond", args) if self.get_version() >= (2, 3, 9): self.parser.add_dir(general_vh.path, "RewriteRule", constants.REWRITE_HTTPS_ARGS_WITH_END) else: self.parser.add_dir(general_vh.path, "RewriteRule", constants.REWRITE_HTTPS_ARGS) self.save_notes += ("Redirecting host in %s to ssl vhost in %s\n" % (general_vh.filep, ssl_vhost.filep)) self.save() logger.info("Redirecting vhost in %s to ssl vhost in %s", general_vh.filep, ssl_vhost.filep) def _verify_no_letsencrypt_redirect(self, vhost): """Checks to see if a redirect was already installed by letsencrypt. Checks to see if virtualhost already contains a rewrite rule that is identical to Letsencrypt's redirection rewrite rule. :param vhost: vhost to check :type vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :raises errors.PluginEnhancementAlreadyPresent: When the exact letsencrypt redirection WriteRule exists in virtual host. """ rewrite_path = self.parser.find_dir( "RewriteRule", None, start=vhost.path) # There can be other RewriteRule directive lines in vhost config. # rewrite_args_dict keys are directive ids and the corresponding value # for each is a list of arguments to that directive. rewrite_args_dict = defaultdict(list) pat = r'.*(directive\[\d+\]).*' for match in rewrite_path: m = re.match(pat, match) if m: dir_id = m.group(1) rewrite_args_dict[dir_id].append(match) if rewrite_args_dict: redirect_args = [constants.REWRITE_HTTPS_ARGS, constants.REWRITE_HTTPS_ARGS_WITH_END] for matches in rewrite_args_dict.values(): if [self.aug.get(x) for x in matches] in redirect_args: raise errors.PluginEnhancementAlreadyPresent( "Let's Encrypt has already enabled redirection") def _is_rewrite_exists(self, vhost): """Checks if there exists a RewriteRule directive in vhost :param vhost: vhost to check :type vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :returns: True if a RewriteRule directive exists. :rtype: bool """ rewrite_path = self.parser.find_dir( "RewriteRule", None, start=vhost.path) return bool(rewrite_path) def _is_rewrite_engine_on(self, vhost): """Checks if a RewriteEngine directive is on :param vhost: vhost to check :type vhost: :class:`~letsencrypt_apache.obj.VirtualHost` """ rewrite_engine_path = self.parser.find_dir("RewriteEngine", "on", start=vhost.path) if rewrite_engine_path: return self.parser.get_arg(rewrite_engine_path[0]) return False def _create_redirect_vhost(self, ssl_vhost): """Creates an http_vhost specifically to redirect for the ssl_vhost. :param ssl_vhost: ssl vhost :type ssl_vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :returns: tuple of the form (`success`, :class:`~letsencrypt_apache.obj.VirtualHost`) :rtype: tuple """ text = self._get_redirect_config_str(ssl_vhost) redirect_filepath = self._write_out_redirect(ssl_vhost, text) self.aug.load() # Make a new vhost data structure and add it to the lists new_vhost = self._create_vhost(parser.get_aug_path(redirect_filepath)) self.vhosts.append(new_vhost) # Finally create documentation for the change self.save_notes += ("Created a port 80 vhost, %s, for redirection to " "ssl vhost %s\n" % (new_vhost.filep, ssl_vhost.filep)) def _get_redirect_config_str(self, ssl_vhost): # get servernames and serveraliases serveralias = "" servername = "" if ssl_vhost.name is not None: servername = "ServerName " + ssl_vhost.name if ssl_vhost.aliases: serveralias = "ServerAlias " + " ".join(ssl_vhost.aliases) rewrite_rule_args = [] if self.get_version() >= (2, 3, 9): rewrite_rule_args = constants.REWRITE_HTTPS_ARGS_WITH_END else: rewrite_rule_args = constants.REWRITE_HTTPS_ARGS return ("\n" "%s \n" "%s \n" "ServerSignature Off\n" "\n" "RewriteEngine On\n" "RewriteRule %s\n" "\n" "ErrorLog /var/log/apache2/redirect.error.log\n" "LogLevel warn\n" "\n" % (" ".join(str(addr) for addr in self._get_proposed_addrs(ssl_vhost)), servername, serveralias, " ".join(rewrite_rule_args))) def _write_out_redirect(self, ssl_vhost, text): # This is the default name redirect_filename = "le-redirect.conf" # See if a more appropriate name can be applied if ssl_vhost.name is not None: # make sure servername doesn't exceed filename length restriction if len(ssl_vhost.name) < (255 - (len(redirect_filename) + 1)): redirect_filename = "le-redirect-%s.conf" % ssl_vhost.name redirect_filepath = os.path.join(self.conf("vhost-root"), redirect_filename) # Register the new file that will be created # Note: always register the creation before writing to ensure file will # be removed in case of unexpected program exit self.reverter.register_file_creation(False, redirect_filepath) # Write out file with open(redirect_filepath, "w") as redirect_file: redirect_file.write(text) logger.info("Created redirect file: %s", redirect_filename) return redirect_filepath def _get_http_vhost(self, ssl_vhost): """Find appropriate HTTP vhost for ssl_vhost.""" # First candidate vhosts filter candidate_http_vhs = [ vhost for vhost in self.vhosts if not vhost.ssl ] # Second filter - check addresses for http_vh in candidate_http_vhs: if http_vh.same_server(ssl_vhost): return http_vh # Third filter - if none with same names, return generic for http_vh in candidate_http_vhs: if http_vh.same_server(ssl_vhost, generic=True): return http_vh return None def _get_proposed_addrs(self, vhost, port="80"): """Return all addrs of vhost with the port replaced with the specified. :param obj.VirtualHost ssl_vhost: Original Vhost :param str port: Desired port for new addresses :returns: `set` of :class:`~obj.Addr` """ redirects = set() for addr in vhost.addrs: redirects.add(addr.get_addr_obj(port)) return redirects def get_all_certs_keys(self): """Find all existing keys, certs from configuration. Retrieve all certs and keys set in VirtualHosts on the Apache server :returns: list of tuples with form [(cert, key, path)] cert - str path to certificate file key - str path to associated key file path - File path to configuration file. :rtype: list """ c_k = set() for vhost in self.vhosts: if vhost.ssl: cert_path = self.parser.find_dir( "SSLCertificateFile", None, start=vhost.path, exclude=False) key_path = self.parser.find_dir( "SSLCertificateKeyFile", None, start=vhost.path, exclude=False) if cert_path and key_path: cert = os.path.abspath(self.parser.get_arg(cert_path[-1])) key = os.path.abspath(self.parser.get_arg(key_path[-1])) c_k.add((cert, key, get_file_path(cert_path[-1]))) else: logger.warning( "Invalid VirtualHost configuration - %s", vhost.filep) return c_k def is_site_enabled(self, avail_fp): """Checks to see if the given site is enabled. .. todo:: fix hardcoded sites-enabled, check os.path.samefile :param str avail_fp: Complete file path of available site :returns: Success :rtype: bool """ enabled_dir = os.path.join(self.parser.root, "sites-enabled") if not os.path.isdir(enabled_dir): error_msg = ("Directory '{0}' does not exist. Please ensure " "that the values for --apache-handle-sites and " "--apache-server-root are correct for your " "environment.".format(enabled_dir)) raise errors.ConfigurationError(error_msg) for entry in os.listdir(enabled_dir): try: if filecmp.cmp(avail_fp, os.path.join(enabled_dir, entry)): return True except OSError: pass return False def enable_site(self, vhost): """Enables an available site, Apache reload required. .. note:: Does not make sure that the site correctly works or that all modules are enabled appropriately. .. todo:: This function should number subdomains before the domain vhost .. todo:: Make sure link is not broken... :param vhost: vhost to enable :type vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :raises .errors.NotSupportedError: If filesystem layout is not supported. """ if self.is_site_enabled(vhost.filep): return if "/sites-available/" in vhost.filep: enabled_path = ("%s/sites-enabled/%s" % (self.parser.root, os.path.basename(vhost.filep))) self.reverter.register_file_creation(False, enabled_path) os.symlink(vhost.filep, enabled_path) vhost.enabled = True logger.info("Enabling available site: %s", vhost.filep) self.save_notes += "Enabled site %s\n" % vhost.filep else: raise errors.NotSupportedError( "Unsupported filesystem layout. " "sites-available/enabled expected.") def enable_mod(self, mod_name, temp=False): """Enables module in Apache. Both enables and reloads Apache so module is active. :param str mod_name: Name of the module to enable. (e.g. 'ssl') :param bool temp: Whether or not this is a temporary action. :raises .errors.NotSupportedError: If the filesystem layout is not supported. :raises .errors.MisconfigurationError: If a2enmod or a2dismod cannot be run. """ # Support Debian specific setup avail_path = os.path.join(self.parser.root, "mods-available") enabled_path = os.path.join(self.parser.root, "mods-enabled") if not os.path.isdir(avail_path) or not os.path.isdir(enabled_path): raise errors.NotSupportedError( "Unsupported directory layout. You may try to enable mod %s " "and try again." % mod_name) deps = _get_mod_deps(mod_name) # Enable all dependencies for dep in deps: if (dep + "_module") not in self.parser.modules: self._enable_mod_debian(dep, temp) self._add_parser_mod(dep) note = "Enabled dependency of %s module - %s" % (mod_name, dep) if not temp: self.save_notes += note + os.linesep logger.debug(note) # Enable actual module self._enable_mod_debian(mod_name, temp) self._add_parser_mod(mod_name) if not temp: self.save_notes += "Enabled %s module in Apache\n" % mod_name logger.info("Enabled Apache %s module", mod_name) # Modules can enable additional config files. Variables may be defined # within these new configuration sections. # Reload is not necessary as DUMP_RUN_CFG uses latest config. self.parser.update_runtime_variables() def _add_parser_mod(self, mod_name): """Shortcut for updating parser modules.""" self.parser.modules.add(mod_name + "_module") self.parser.modules.add("mod_" + mod_name + ".c") def _enable_mod_debian(self, mod_name, temp): """Assumes mods-available, mods-enabled layout.""" # Generate reversal command. # Try to be safe here... check that we can probably reverse before # applying enmod command if not le_util.exe_exists(self.conf("dismod")): raise errors.MisconfigurationError( "Unable to find a2dismod, please make sure a2enmod and " "a2dismod are configured correctly for letsencrypt.") self.reverter.register_undo_command( temp, [self.conf("dismod"), mod_name]) le_util.run_script([self.conf("enmod"), mod_name]) def restart(self): """Runs a config test and reloads the Apache server. :raises .errors.MisconfigurationError: If either the config test or reload fails. """ self.config_test() self._reload() def _reload(self): """Reloads the Apache server. :raises .errors.MisconfigurationError: If reload fails """ try: le_util.run_script(constants.os_constant("restart_cmd")) except errors.SubprocessError as err: raise errors.MisconfigurationError(str(err)) def config_test(self): # pylint: disable=no-self-use """Check the configuration of Apache for errors. :raises .errors.MisconfigurationError: If config_test fails """ try: le_util.run_script(constants.os_constant("conftest_cmd")) except errors.SubprocessError as err: raise errors.MisconfigurationError(str(err)) def get_version(self): """Return version of Apache Server. Version is returned as tuple. (ie. 2.4.7 = (2, 4, 7)) :returns: version :rtype: tuple :raises .PluginError: if unable to find Apache version """ try: stdout, _ = le_util.run_script( constants.os_constant("version_cmd")) except errors.SubprocessError: raise errors.PluginError( "Unable to run %s -v" % constants.os_constant("version_cmd")) regex = re.compile(r"Apache/([0-9\.]*)", re.IGNORECASE) matches = regex.findall(stdout) if len(matches) != 1: raise errors.PluginError("Unable to find Apache version") return tuple([int(i) for i in matches[0].split(".")]) def more_info(self): """Human-readable string to help understand the module""" return ( "Configures Apache to authenticate and install HTTPS.{0}" "Server root: {root}{0}" "Version: {version}".format( os.linesep, root=self.parser.loc["root"], version=".".join(str(i) for i in self.version)) ) ########################################################################### # Challenges Section ########################################################################### def get_chall_pref(self, unused_domain): # pylint: disable=no-self-use """Return list of challenge preferences.""" return [challenges.TLSSNI01] def perform(self, achalls): """Perform the configuration related challenge. This function currently assumes all challenges will be fulfilled. If this turns out not to be the case in the future. Cleanup and outstanding challenges will have to be designed better. """ self._chall_out.update(achalls) responses = [None] * len(achalls) chall_doer = tls_sni_01.ApacheTlsSni01(self) for i, achall in enumerate(achalls): # Currently also have chall_doer hold associated index of the # challenge. This helps to put all of the responses back together # when they are all complete. chall_doer.add_chall(achall, i) sni_response = chall_doer.perform() if sni_response: # Must reload in order to activate the challenges. # Handled here because we may be able to load up other challenge # types self.restart() # TODO: Remove this dirty hack. We need to determine a reliable way # of identifying when the new configuration is being used. time.sleep(3) # Go through all of the challenges and assign them to the proper # place in the responses return value. All responses must be in the # same order as the original challenges. for i, resp in enumerate(sni_response): responses[chall_doer.indices[i]] = resp return responses def cleanup(self, achalls): """Revert all challenges.""" self._chall_out.difference_update(achalls) # If all of the challenges have been finished, clean up everything if not self._chall_out: self.revert_challenge_config() self.restart() self.parser.init_modules() def _get_mod_deps(mod_name): """Get known module dependencies. .. note:: This does not need to be accurate in order for the client to run. This simply keeps things clean if the user decides to revert changes. .. warning:: If all deps are not included, it may cause incorrect parsing behavior, due to enable_mod's shortcut for updating the parser's currently defined modules (`.ApacheConfigurator._add_parser_mod`) This would only present a major problem in extremely atypical configs that use ifmod for the missing deps. """ deps = { "ssl": ["setenvif", "mime"] } return deps.get(mod_name, []) def get_file_path(vhost_path): """Get file path from augeas_vhost_path. Takes in Augeas path and returns the file name :param str vhost_path: Augeas virtual host path :returns: filename of vhost :rtype: str """ # Strip off /files avail_fp = vhost_path[6:] # This can be optimized... while True: # Cast all to lowercase to be case insensitive find_if = avail_fp.lower().find("/ifmodule") if find_if != -1: avail_fp = avail_fp[:find_if] continue find_vh = avail_fp.lower().find("/virtualhost") if find_vh != -1: avail_fp = avail_fp[:find_vh] continue find_macro = avail_fp.lower().find("/macro") if find_macro != -1: avail_fp = avail_fp[:find_macro] continue break return avail_fp def install_ssl_options_conf(options_ssl): """ Copy Let's Encrypt's SSL options file into the system's config dir if required. """ # XXX if we ever try to enforce a local privilege boundary (eg, running # letsencrypt for unprivileged users via setuid), this function will need # to be modified. # XXX if the user is in security-autoupdate mode, we should be willing to # overwrite the options_ssl file at least if it's unmodified: # https://github.com/letsencrypt/letsencrypt/issues/1123 # Check to make sure options-ssl.conf is installed if not os.path.isfile(options_ssl): shutil.copyfile(constants.os_constant("MOD_SSL_CONF_SRC"), options_ssl) letsencrypt-apache-0.4.1/letsencrypt_apache/display_ops.py0000644000175000017500000000644312665157707023507 0ustar bmwbmw00000000000000"""Contains UI methods for Apache operations.""" import logging import os import zope.component from letsencrypt import errors from letsencrypt import interfaces import letsencrypt.display.util as display_util logger = logging.getLogger(__name__) def select_vhost(domain, vhosts): """Select an appropriate Apache Vhost. :param vhosts: Available Apache Virtual Hosts :type vhosts: :class:`list` of type `~obj.Vhost` :returns: VirtualHost or `None` :rtype: `~obj.Vhost` or `None` """ if not vhosts: return None while True: code, tag = _vhost_menu(domain, vhosts) if code == display_util.HELP: _more_info_vhost(vhosts[tag]) elif code == display_util.OK: return vhosts[tag] else: return None def _vhost_menu(domain, vhosts): """Select an appropriate Apache Vhost. :param vhosts: Available Apache Virtual Hosts :type vhosts: :class:`list` of type `~obj.Vhost` :returns: Display tuple - ('code', tag') :rtype: `tuple` """ # Free characters in the line of display text (9 is for ' | ' formatting) free_chars = display_util.WIDTH - len("HTTPS") - len("Enabled") - 9 if free_chars < 2: logger.debug("Display size is too small for " "letsencrypt_apache.display_ops._vhost_menu()") # This runs the edge off the screen, but it doesn't cause an "error" filename_size = 1 disp_name_size = 1 else: # Filename is a bit more important and probably longer with 000-* filename_size = int(free_chars * .6) disp_name_size = free_chars - filename_size choices = [] for vhost in vhosts: if len(vhost.get_names()) == 1: disp_name = next(iter(vhost.get_names())) elif len(vhost.get_names()) == 0: disp_name = "" else: disp_name = "Multiple Names" choices.append( "{fn:{fn_size}s} | {name:{name_size}s} | {https:5s} | " "{active:7s}".format( fn=os.path.basename(vhost.filep)[:filename_size], name=disp_name[:disp_name_size], https="HTTPS" if vhost.ssl else "", active="Enabled" if vhost.enabled else "", fn_size=filename_size, name_size=disp_name_size) ) try: code, tag = zope.component.getUtility(interfaces.IDisplay).menu( "We were unable to find a vhost with a ServerName " "or Address of {0}.{1}Which virtual host would you " "like to choose?".format(domain, os.linesep), choices, help_label="More Info", ok_label="Select") except errors.MissingCommandlineFlag as e: msg = ("Failed to run Apache plugin non-interactively{1}{0}{1}" "(The best solution is to add ServerName or ServerAlias " "entries to the VirtualHost directives of your apache " "configuration files.)".format(e, os.linesep)) raise errors.MissingCommandlineFlag(msg) return code, tag def _more_info_vhost(vhost): zope.component.getUtility(interfaces.IDisplay).notification( "Virtual Host Information:{0}{1}{0}{2}".format( os.linesep, "-" * (display_util.WIDTH - 4), str(vhost)), height=display_util.HEIGHT) letsencrypt-apache-0.4.1/letsencrypt_apache/augeas_lens/0000755000175000017500000000000012665157735023067 5ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/augeas_lens/httpd.aug0000644000175000017500000001170612665157707024714 0ustar bmwbmw00000000000000(* Apache HTTPD lens for Augeas Authors: David Lutterkort Francis Giraldeau Raphael Pinson About: Reference Online Apache configuration manual: http://httpd.apache.org/docs/trunk/ About: License This file is licensed under the LGPL v2+. About: Lens Usage Sample usage of this lens in augtool Apache configuration is represented by two main structures, nested sections and directives. Sections are used as labels, while directives are kept as a value. Sections and directives can have positional arguments inside values of "arg" nodes. Arguments of sections must be the firsts child of the section node. This lens doesn't support automatic string quoting. Hence, the string must be quoted when containing a space. Create a new VirtualHost section with one directive: > clear /files/etc/apache2/sites-available/foo/VirtualHost > set /files/etc/apache2/sites-available/foo/VirtualHost/arg "172.16.0.1:80" > set /files/etc/apache2/sites-available/foo/VirtualHost/directive "ServerAdmin" > set /files/etc/apache2/sites-available/foo/VirtualHost/*[self::directive="ServerAdmin"]/arg "admin@example.com" About: Configuration files This lens applies to files in /etc/httpd and /etc/apache2. See . *) module Httpd = autoload xfm (****************************************************************** * Utilities lens *****************************************************************) let dels (s:string) = del s s (* deal with continuation lines *) let sep_spc = del /([ \t]+|[ \t]*\\\\\r?\n[ \t]*)/ " " let sep_osp = del /([ \t]*|[ \t]*\\\\\r?\n[ \t]*)/ "" let sep_eq = del /[ \t]*=[ \t]*/ "=" let nmtoken = /[a-zA-Z:_][a-zA-Z0-9:_.-]*/ let word = /[a-z][a-z0-9._-]*/i let comment = Util.comment let eol = Util.doseol let empty = Util.empty_dos let indent = Util.indent (* borrowed from shellvars.aug *) let char_arg_dir = /([^\\ '"{\t\r\n]|[^ '"{\t\r\n]+[^\\ \t\r\n])|\\\\"|\\\\'/ let char_arg_sec = /([^\\ '"\t\r\n>]|[^ '"\t\r\n>]+[^\\ \t\r\n>])|\\\\"|\\\\'/ let char_arg_wl = /([^\\ '"},\t\r\n]|[^ '"},\t\r\n]+[^\\ '"},\t\r\n])/ let cdot = /\\\\./ let cl = /\\\\\n/ let dquot = let no_dquot = /[^"\\\r\n]/ in /"/ . (no_dquot|cdot|cl)* . /"/ let dquot_msg = let no_dquot = /([^ \t"\\\r\n]|[^"\\\r\n]+[^ \t"\\\r\n])/ in /"/ . (no_dquot|cdot|cl)* let squot = let no_squot = /[^'\\\r\n]/ in /'/ . (no_squot|cdot|cl)* . /'/ let comp = /[<>=]?=/ (****************************************************************** * Attributes *****************************************************************) let arg_dir = [ label "arg" . store (char_arg_dir+|dquot|squot) ] (* message argument starts with " but ends at EOL *) let arg_dir_msg = [ label "arg" . store dquot_msg ] let arg_sec = [ label "arg" . store (char_arg_sec+|comp|dquot|squot) ] let arg_wl = [ label "arg" . store (char_arg_wl+|dquot|squot) ] (* comma-separated wordlist as permitted in the SSLRequire directive *) let arg_wordlist = let wl_start = Util.del_str "{" in let wl_end = Util.del_str "}" in let wl_sep = del /[ \t]*,[ \t]*/ ", " in [ label "wordlist" . wl_start . arg_wl . (wl_sep . arg_wl)* . wl_end ] let argv (l:lens) = l . (sep_spc . l)* let directive = (* arg_dir_msg may be the last or only argument *) let dir_args = (argv (arg_dir|arg_wordlist) . (sep_spc . arg_dir_msg)?) | arg_dir_msg in [ indent . label "directive" . store word . (sep_spc . dir_args)? . eol ] let section (body:lens) = (* opt_eol includes empty lines *) let opt_eol = del /([ \t]*#?\r?\n)*/ "\n" in let inner = (sep_spc . argv arg_sec)? . sep_osp . dels ">" . opt_eol . ((body|comment) . (body|empty|comment)*)? . indent . dels "[ \t\n\r]*/ ">\n" ] let perl_section = [ indent . label "Perl" . del //i "" . store /[^<]*/ . del /<\/perl>/i "" . eol ] let rec content = section (content|directive) | perl_section let lns = (content|directive|comment|empty)* let filter = (incl "/etc/apache2/apache2.conf") . (incl "/etc/apache2/httpd.conf") . (incl "/etc/apache2/ports.conf") . (incl "/etc/apache2/conf.d/*") . (incl "/etc/apache2/conf-available/*.conf") . (incl "/etc/apache2/mods-available/*") . (incl "/etc/apache2/sites-available/*") . (incl "/etc/apache2/vhosts.d/*.conf") . (incl "/etc/httpd/conf.d/*.conf") . (incl "/etc/httpd/httpd.conf") . (incl "/etc/httpd/conf/httpd.conf") . Util.stdexcl let xfm = transform lns filter letsencrypt-apache-0.4.1/letsencrypt_apache/tls_sni_01.py0000644000175000017500000001410212665157707023123 0ustar bmwbmw00000000000000"""A class that performs TLS-SNI-01 challenges for Apache""" import os import logging from letsencrypt.plugins import common from letsencrypt_apache import obj from letsencrypt_apache import parser logger = logging.getLogger(__name__) class ApacheTlsSni01(common.TLSSNI01): """Class that performs TLS-SNI-01 challenges within the Apache configurator :ivar configurator: ApacheConfigurator object :type configurator: :class:`~apache.configurator.ApacheConfigurator` :ivar list achalls: Annotated TLS-SNI-01 (`.KeyAuthorizationAnnotatedChallenge`) challenges. :param list indices: Meant to hold indices of challenges in a larger array. ApacheTlsSni01 is capable of solving many challenges at once which causes an indexing issue within ApacheConfigurator who must return all responses in order. Imagine ApacheConfigurator maintaining state about where all of the http-01 Challenges, TLS-SNI-01 Challenges belong in the response array. This is an optional utility. :param str challenge_conf: location of the challenge config file """ VHOST_TEMPLATE = """\ ServerName {server_name} UseCanonicalName on SSLStrictSNIVHostCheck on LimitRequestBody 1048576 Include {ssl_options_conf_path} SSLCertificateFile {cert_path} SSLCertificateKeyFile {key_path} DocumentRoot {document_root} """ def __init__(self, *args, **kwargs): super(ApacheTlsSni01, self).__init__(*args, **kwargs) self.challenge_conf = os.path.join( self.configurator.conf("challenge-location"), "le_tls_sni_01_cert_challenge.conf") def perform(self): """Perform a TLS-SNI-01 challenge.""" if not self.achalls: return [] # Save any changes to the configuration as a precaution # About to make temporary changes to the config self.configurator.save("Changes before challenge setup", True) # Prepare the server for HTTPS self.configurator.prepare_server_https( str(self.configurator.config.tls_sni_01_port), True) responses = [] # Create all of the challenge certs for achall in self.achalls: responses.append(self._setup_challenge_cert(achall)) # Setup the configuration addrs = self._mod_config() self.configurator.save("Don't lose mod_config changes", True) self.configurator.make_addrs_sni_ready(addrs) # Save reversible changes self.configurator.save("SNI Challenge", True) return responses def _mod_config(self): """Modifies Apache config files to include challenge vhosts. Result: Apache config includes virtual servers for issued challs :returns: All TLS-SNI-01 addresses used :rtype: set """ addrs = set() config_text = "\n" for achall in self.achalls: achall_addrs = self._get_addrs(achall) addrs.update(achall_addrs) config_text += self._get_config_text(achall, achall_addrs) config_text += "\n" self._conf_include_check(self.configurator.parser.loc["default"]) self.configurator.reverter.register_file_creation( True, self.challenge_conf) logger.debug("writing a config file with text:\n %s", config_text) with open(self.challenge_conf, "w") as new_conf: new_conf.write(config_text) return addrs def _get_addrs(self, achall): """Return the Apache addresses needed for TLS-SNI-01.""" vhost = self.configurator.choose_vhost(achall.domain, temp=True) # TODO: Checkout _default_ rules. addrs = set() default_addr = obj.Addr(("*", str( self.configurator.config.tls_sni_01_port))) for addr in vhost.addrs: if "_default_" == addr.get_addr(): addrs.add(default_addr) else: addrs.add( addr.get_sni_addr( self.configurator.config.tls_sni_01_port)) return addrs def _conf_include_check(self, main_config): """Add TLS-SNI-01 challenge conf file into configuration. Adds TLS-SNI-01 challenge include file if it does not already exist within mainConfig :param str main_config: file path to main user apache config file """ if len(self.configurator.parser.find_dir( parser.case_i("Include"), self.challenge_conf)) == 0: # print "Including challenge virtual host(s)" logger.debug("Adding Include %s to %s", self.challenge_conf, parser.get_aug_path(main_config)) self.configurator.parser.add_dir( parser.get_aug_path(main_config), "Include", self.challenge_conf) def _get_config_text(self, achall, ip_addrs): """Chocolate virtual server configuration text :param .KeyAuthorizationAnnotatedChallenge achall: Annotated TLS-SNI-01 challenge. :param list ip_addrs: addresses of challenged domain :class:`list` of type `~.obj.Addr` :returns: virtual host configuration text :rtype: str """ ips = " ".join(str(i) for i in ip_addrs) document_root = os.path.join( self.configurator.config.work_dir, "tls_sni_01_page/") # TODO: Python docs is not clear how mutliline string literal # newlines are parsed on different platforms. At least on # Linux (Debian sid), when source file uses CRLF, Python still # parses it as "\n"... c.f.: # https://docs.python.org/2.7/reference/lexical_analysis.html return self.VHOST_TEMPLATE.format( vhost=ips, server_name=achall.response(achall.account_key).z_domain, ssl_options_conf_path=self.configurator.mod_ssl_conf, cert_path=self.get_cert_path(achall), key_path=self.get_key_path(achall), document_root=document_root).replace("\n", os.linesep) letsencrypt-apache-0.4.1/letsencrypt_apache/centos-options-ssl-apache.conf0000644000175000017500000000252112665157707026451 0ustar bmwbmw00000000000000# Baseline setting to Include for SSL sites SSLEngine on # Intermediate configuration, tweak to your needs SSLProtocol all -SSLv2 -SSLv3 SSLCipherSuite ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA SSLHonorCipherOrder on SSLOptions +StrictRequire # Add vhost name to log entries: LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" vhost_combined LogFormat "%v %h %l %u %t \"%r\" %>s %b" vhost_common #CustomLog /var/log/apache2/access.log vhost_combined #LogLevel warn #ErrorLog /var/log/apache2/error.log # Always ensure Cookies have "Secure" set (JAH 2012/1) #Header edit Set-Cookie (?i)^(.*)(;\s*secure)??((\s*;)?(.*)) "$1; Secure$3$4" letsencrypt-apache-0.4.1/letsencrypt_apache/tests/0000755000175000017500000000000012665157735021743 5ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/obj_test.py0000644000175000017500000001221012665157707024121 0ustar bmwbmw00000000000000"""Tests for letsencrypt_apache.obj.""" import unittest class VirtualHostTest(unittest.TestCase): """Test the VirtualHost class.""" def setUp(self): from letsencrypt_apache.obj import Addr from letsencrypt_apache.obj import VirtualHost self.addr1 = Addr.fromstring("127.0.0.1") self.addr2 = Addr.fromstring("127.0.0.1:443") self.addr_default = Addr.fromstring("_default_:443") self.vhost1 = VirtualHost( "filep", "vh_path", set([self.addr1]), False, False, "localhost") self.vhost1b = VirtualHost( "filep", "vh_path", set([self.addr1]), False, False, "localhost") self.vhost2 = VirtualHost( "fp", "vhp", set([self.addr2]), False, False, "localhost") def test_eq(self): self.assertTrue(self.vhost1b == self.vhost1) self.assertFalse(self.vhost1 == self.vhost2) self.assertEqual(str(self.vhost1b), str(self.vhost1)) self.assertFalse(self.vhost1b == 1234) def test_ne(self): self.assertTrue(self.vhost1 != self.vhost2) self.assertFalse(self.vhost1 != self.vhost1b) def test_conflicts(self): from letsencrypt_apache.obj import Addr from letsencrypt_apache.obj import VirtualHost complex_vh = VirtualHost( "fp", "vhp", set([Addr.fromstring("*:443"), Addr.fromstring("1.2.3.4:443")]), False, False) self.assertTrue(complex_vh.conflicts([self.addr1])) self.assertTrue(complex_vh.conflicts([self.addr2])) self.assertFalse(complex_vh.conflicts([self.addr_default])) self.assertTrue(self.vhost1.conflicts([self.addr2])) self.assertFalse(self.vhost1.conflicts([self.addr_default])) self.assertFalse(self.vhost2.conflicts([self.addr1, self.addr_default])) def test_same_server(self): from letsencrypt_apache.obj import VirtualHost no_name1 = VirtualHost( "fp", "vhp", set([self.addr1]), False, False, None) no_name2 = VirtualHost( "fp", "vhp", set([self.addr2]), False, False, None) no_name3 = VirtualHost( "fp", "vhp", set([self.addr_default]), False, False, None) no_name4 = VirtualHost( "fp", "vhp", set([self.addr2, self.addr_default]), False, False, None) self.assertTrue(self.vhost1.same_server(self.vhost2)) self.assertTrue(no_name1.same_server(no_name2)) self.assertFalse(self.vhost1.same_server(no_name1)) self.assertFalse(no_name1.same_server(no_name3)) self.assertFalse(no_name1.same_server(no_name4)) class AddrTest(unittest.TestCase): """Test obj.Addr.""" def setUp(self): from letsencrypt_apache.obj import Addr self.addr = Addr.fromstring("*:443") self.addr1 = Addr.fromstring("127.0.0.1") self.addr2 = Addr.fromstring("127.0.0.1:*") self.addr_defined = Addr.fromstring("127.0.0.1:443") self.addr_default = Addr.fromstring("_default_:443") def test_wildcard(self): self.assertFalse(self.addr.is_wildcard()) self.assertTrue(self.addr1.is_wildcard()) self.assertTrue(self.addr2.is_wildcard()) def test_get_sni_addr(self): from letsencrypt_apache.obj import Addr self.assertEqual( self.addr.get_sni_addr("443"), Addr.fromstring("*:443")) self.assertEqual( self.addr.get_sni_addr("225"), Addr.fromstring("*:225")) self.assertEqual( self.addr1.get_sni_addr("443"), Addr.fromstring("127.0.0.1")) def test_conflicts(self): # Note: Defined IP is more important than defined port in match self.assertTrue(self.addr.conflicts(self.addr1)) self.assertTrue(self.addr.conflicts(self.addr2)) self.assertTrue(self.addr.conflicts(self.addr_defined)) self.assertFalse(self.addr.conflicts(self.addr_default)) self.assertFalse(self.addr1.conflicts(self.addr)) self.assertTrue(self.addr1.conflicts(self.addr_defined)) self.assertFalse(self.addr1.conflicts(self.addr_default)) self.assertFalse(self.addr_defined.conflicts(self.addr1)) self.assertFalse(self.addr_defined.conflicts(self.addr2)) self.assertFalse(self.addr_defined.conflicts(self.addr)) self.assertFalse(self.addr_defined.conflicts(self.addr_default)) self.assertTrue(self.addr_default.conflicts(self.addr)) self.assertTrue(self.addr_default.conflicts(self.addr1)) self.assertTrue(self.addr_default.conflicts(self.addr_defined)) # Self test self.assertTrue(self.addr.conflicts(self.addr)) self.assertTrue(self.addr1.conflicts(self.addr1)) # This is a tricky one... self.assertTrue(self.addr1.conflicts(self.addr2)) def test_equal(self): self.assertTrue(self.addr1 == self.addr2) self.assertFalse(self.addr == self.addr1) self.assertFalse(self.addr == 123) def test_not_equal(self): self.assertFalse(self.addr1 != self.addr2) self.assertTrue(self.addr != self.addr1) if __name__ == "__main__": unittest.main() # pragma: no cover letsencrypt-apache-0.4.1/letsencrypt_apache/tests/augeas_configurator_test.py0000644000175000017500000000743012665157707027406 0ustar bmwbmw00000000000000"""Test for letsencrypt_apache.augeas_configurator.""" import os import shutil import unittest import mock from letsencrypt import errors from letsencrypt_apache.tests import util class AugeasConfiguratorTest(util.ApacheTest): """Test for Augeas Configurator base class.""" def setUp(self): # pylint: disable=arguments-differ super(AugeasConfiguratorTest, self).setUp() self.config = util.get_apache_configurator( self.config_path, self.vhost_path, self.config_dir, self.work_dir) self.vh_truth = util.get_vh_truth( self.temp_dir, "debian_apache_2_4/two_vhost_80") def tearDown(self): shutil.rmtree(self.config_dir) shutil.rmtree(self.work_dir) shutil.rmtree(self.temp_dir) def test_bad_parse(self): # pylint: disable=protected-access self.config.parser._parse_file(os.path.join( self.config.parser.root, "conf-available", "bad_conf_file.conf")) self.assertRaises( errors.PluginError, self.config.check_parsing_errors, "httpd.aug") def test_bad_save(self): mock_save = mock.Mock() mock_save.side_effect = IOError self.config.aug.save = mock_save self.assertRaises(errors.PluginError, self.config.save) def test_bad_save_checkpoint(self): self.config.reverter.add_to_checkpoint = mock.Mock( side_effect=errors.ReverterError) self.config.parser.add_dir( self.vh_truth[0].path, "Test", "bad_save_ckpt") self.assertRaises(errors.PluginError, self.config.save) def test_bad_save_finalize_checkpoint(self): self.config.reverter.finalize_checkpoint = mock.Mock( side_effect=errors.ReverterError) self.config.parser.add_dir( self.vh_truth[0].path, "Test", "bad_save_ckpt") self.assertRaises(errors.PluginError, self.config.save, "Title") def test_finalize_save(self): mock_finalize = mock.Mock() self.config.reverter = mock_finalize self.config.save("Example Title") self.assertTrue(mock_finalize.is_called) def test_recovery_routine(self): mock_load = mock.Mock() self.config.aug.load = mock_load self.config.recovery_routine() self.assertEqual(mock_load.call_count, 1) def test_recovery_routine_error(self): self.config.reverter.recovery_routine = mock.Mock( side_effect=errors.ReverterError) self.assertRaises( errors.PluginError, self.config.recovery_routine) def test_revert_challenge_config(self): mock_load = mock.Mock() self.config.aug.load = mock_load self.config.revert_challenge_config() self.assertEqual(mock_load.call_count, 1) def test_revert_challenge_config_error(self): self.config.reverter.revert_temporary_config = mock.Mock( side_effect=errors.ReverterError) self.assertRaises( errors.PluginError, self.config.revert_challenge_config) def test_rollback_checkpoints(self): mock_load = mock.Mock() self.config.aug.load = mock_load self.config.rollback_checkpoints() self.assertEqual(mock_load.call_count, 1) def test_rollback_error(self): self.config.reverter.rollback_checkpoints = mock.Mock( side_effect=errors.ReverterError) self.assertRaises(errors.PluginError, self.config.rollback_checkpoints) def test_view_config_changes(self): self.config.view_config_changes() def test_view_config_changes_error(self): self.config.reverter.view_config_changes = mock.Mock( side_effect=errors.ReverterError) self.assertRaises(errors.PluginError, self.config.view_config_changes) if __name__ == "__main__": unittest.main() # pragma: no cover letsencrypt-apache-0.4.1/letsencrypt_apache/tests/complex_parsing_test.py0000644000175000017500000001070712665157707026552 0ustar bmwbmw00000000000000"""Tests for letsencrypt_apache.parser.""" import os import shutil import unittest from letsencrypt import errors from letsencrypt_apache.tests import util class ComplexParserTest(util.ParserTest): """Apache Parser Test.""" def setUp(self): # pylint: disable=arguments-differ super(ComplexParserTest, self).setUp( "complex_parsing", "complex_parsing") self.setup_variables() # This needs to happen after due to setup_variables not being run # until after self.parser.init_modules() # pylint: disable=protected-access def tearDown(self): shutil.rmtree(self.temp_dir) shutil.rmtree(self.config_dir) shutil.rmtree(self.work_dir) def setup_variables(self): """Set up variables for parser.""" self.parser.variables.update( { "COMPLEX": "", "tls_port": "1234", "fnmatch_filename": "test_fnmatch.conf", "tls_port_str": "1234" } ) def test_filter_args_num(self): """Note: This may also fail do to Include conf-enabled/ syntax.""" matches = self.parser.find_dir("TestArgsDirective") self.assertEqual(len(self.parser.filter_args_num(matches, 1)), 3) self.assertEqual(len(self.parser.filter_args_num(matches, 2)), 2) self.assertEqual(len(self.parser.filter_args_num(matches, 3)), 1) def test_basic_variable_parsing(self): matches = self.parser.find_dir("TestVariablePort") self.assertEqual(len(matches), 1) self.assertEqual(self.parser.get_arg(matches[0]), "1234") def test_basic_variable_parsing_quotes(self): matches = self.parser.find_dir("TestVariablePortStr") self.assertEqual(len(matches), 1) self.assertEqual(self.parser.get_arg(matches[0]), "1234") def test_invalid_variable_parsing(self): del self.parser.variables["tls_port"] matches = self.parser.find_dir("TestVariablePort") self.assertRaises( errors.PluginError, self.parser.get_arg, matches[0]) def test_basic_ifdefine(self): self.assertEqual(len(self.parser.find_dir("VAR_DIRECTIVE")), 2) self.assertEqual(len(self.parser.find_dir("INVALID_VAR_DIRECTIVE")), 0) def test_basic_ifmodule(self): self.assertEqual(len(self.parser.find_dir("MOD_DIRECTIVE")), 2) self.assertEqual( len(self.parser.find_dir("INVALID_MOD_DIRECTIVE")), 0) def test_nested(self): self.assertEqual(len(self.parser.find_dir("NESTED_DIRECTIVE")), 3) self.assertEqual( len(self.parser.find_dir("INVALID_NESTED_DIRECTIVE")), 0) def test_load_modules(self): """If only first is found, there is bad variable parsing.""" self.assertTrue("status_module" in self.parser.modules) self.assertTrue("mod_status.c" in self.parser.modules) # This is in an IfDefine self.assertTrue("ssl_module" in self.parser.modules) self.assertTrue("mod_ssl.c" in self.parser.modules) def verify_fnmatch(self, arg, hit=True): """Test if Include was correctly parsed.""" from letsencrypt_apache import parser self.parser.add_dir(parser.get_aug_path(self.parser.loc["default"]), "Include", [arg]) if hit: self.assertTrue(self.parser.find_dir("FNMATCH_DIRECTIVE")) else: self.assertFalse(self.parser.find_dir("FNMATCH_DIRECTIVE")) # NOTE: Only run one test per function otherwise you will have # inf recursion def test_include(self): self.verify_fnmatch("test_fnmatch.?onf") def test_include_complex(self): self.verify_fnmatch("../complex_parsing/[te][te]st_*.?onf") def test_include_fullpath(self): self.verify_fnmatch(os.path.join(self.config_path, "test_fnmatch.conf")) def test_include_fullpath_trailing_slash(self): self.verify_fnmatch(self.config_path + "//") def test_include_single_quotes(self): self.verify_fnmatch("'" + self.config_path + "'") def test_include_double_quotes(self): self.verify_fnmatch('"' + self.config_path + '"') def test_include_variable(self): self.verify_fnmatch("../complex_parsing/${fnmatch_filename}") def test_include_missing(self): # This should miss self.verify_fnmatch("test_*.onf", False) if __name__ == "__main__": unittest.main() # pragma: no cover letsencrypt-apache-0.4.1/letsencrypt_apache/tests/constants_test.py0000644000175000017500000000171112665157707025367 0ustar bmwbmw00000000000000"""Test for letsencrypt_apache.configurator.""" import mock import unittest from letsencrypt_apache import constants class ConstantsTest(unittest.TestCase): @mock.patch("letsencrypt.le_util.get_os_info") def test_get_debian_value(self, os_info): os_info.return_value = ('Debian', '', '') self.assertEqual(constants.os_constant("vhost_root"), "/etc/apache2/sites-available") @mock.patch("letsencrypt.le_util.get_os_info") def test_get_centos_value(self, os_info): os_info.return_value = ('CentOS Linux', '', '') self.assertEqual(constants.os_constant("vhost_root"), "/etc/httpd/conf.d") @mock.patch("letsencrypt.le_util.get_os_info") def test_get_default_value(self, os_info): os_info.return_value = ('Nonexistent Linux', '', '') self.assertEqual(constants.os_constant("vhost_root"), "/etc/apache2/sites-available") letsencrypt-apache-0.4.1/letsencrypt_apache/tests/parser_test.py0000644000175000017500000002000712665157707024646 0ustar bmwbmw00000000000000"""Tests for letsencrypt_apache.parser.""" import os import shutil import unittest import augeas import mock from letsencrypt import errors from letsencrypt_apache.tests import util class BasicParserTest(util.ParserTest): """Apache Parser Test.""" def setUp(self): # pylint: disable=arguments-differ super(BasicParserTest, self).setUp() def tearDown(self): shutil.rmtree(self.temp_dir) shutil.rmtree(self.config_dir) shutil.rmtree(self.work_dir) def test_find_config_root_no_root(self): # pylint: disable=protected-access os.remove(self.parser.loc["root"]) self.assertRaises( errors.NoInstallationError, self.parser._find_config_root) def test_parse_file(self): """Test parse_file. letsencrypt.conf is chosen as the test file as it will not be included during the normal course of execution. """ file_path = os.path.join( self.config_path, "not-parsed-by-default", "letsencrypt.conf") self.parser._parse_file(file_path) # pylint: disable=protected-access # search for the httpd incl matches = self.parser.aug.match( "/augeas/load/Httpd/incl [. ='%s']" % file_path) self.assertTrue(matches) def test_find_dir(self): test = self.parser.find_dir("Listen", "80") # This will only look in enabled hosts test2 = self.parser.find_dir("documentroot") self.assertEqual(len(test), 1) self.assertEqual(len(test2), 4) def test_add_dir(self): aug_default = "/files" + self.parser.loc["default"] self.parser.add_dir(aug_default, "AddDirective", "test") self.assertTrue( self.parser.find_dir("AddDirective", "test", aug_default)) self.parser.add_dir(aug_default, "AddList", ["1", "2", "3", "4"]) matches = self.parser.find_dir("AddList", None, aug_default) for i, match in enumerate(matches): self.assertEqual(self.parser.aug.get(match), str(i + 1)) def test_add_dir_to_ifmodssl(self): """test add_dir_to_ifmodssl. Path must be valid before attempting to add to augeas """ from letsencrypt_apache.parser import get_aug_path # This makes sure that find_dir will work self.parser.modules.add("mod_ssl.c") self.parser.add_dir_to_ifmodssl( get_aug_path(self.parser.loc["default"]), "FakeDirective", ["123"]) matches = self.parser.find_dir("FakeDirective", "123") self.assertEqual(len(matches), 1) self.assertTrue("IfModule" in matches[0]) def test_add_dir_to_ifmodssl_multiple(self): from letsencrypt_apache.parser import get_aug_path # This makes sure that find_dir will work self.parser.modules.add("mod_ssl.c") self.parser.add_dir_to_ifmodssl( get_aug_path(self.parser.loc["default"]), "FakeDirective", ["123", "456", "789"]) matches = self.parser.find_dir("FakeDirective") self.assertEqual(len(matches), 3) self.assertTrue("IfModule" in matches[0]) def test_get_aug_path(self): from letsencrypt_apache.parser import get_aug_path self.assertEqual("/files/etc/apache", get_aug_path("/etc/apache")) def test_set_locations(self): with mock.patch("letsencrypt_apache.parser.os.path") as mock_path: mock_path.isfile.side_effect = [False, False] # pylint: disable=protected-access results = self.parser._set_locations() self.assertEqual(results["default"], results["listen"]) self.assertEqual(results["default"], results["name"]) @mock.patch("letsencrypt_apache.parser.ApacheParser._get_runtime_cfg") def test_update_runtime_variables(self, mock_cfg): mock_cfg.return_value = ( 'ServerRoot: "/etc/apache2"\n' 'Main DocumentRoot: "/var/www"\n' 'Main ErrorLog: "/var/log/apache2/error.log"\n' 'Mutex ssl-stapling: using_defaults\n' 'Mutex ssl-cache: using_defaults\n' 'Mutex default: dir="/var/lock/apache2" mechanism=fcntl\n' 'Mutex watchdog-callback: using_defaults\n' 'PidFile: "/var/run/apache2/apache2.pid"\n' 'Define: TEST\n' 'Define: DUMP_RUN_CFG\n' 'Define: U_MICH\n' 'Define: TLS=443\n' 'Define: example_path=Documents/path\n' 'User: name="www-data" id=33 not_used\n' 'Group: name="www-data" id=33 not_used\n' ) expected_vars = {"TEST": "", "U_MICH": "", "TLS": "443", "example_path": "Documents/path"} self.parser.update_runtime_variables() self.assertEqual(self.parser.variables, expected_vars) @mock.patch("letsencrypt_apache.parser.ApacheParser._get_runtime_cfg") def test_update_runtime_vars_bad_output(self, mock_cfg): mock_cfg.return_value = "Define: TLS=443=24" self.parser.update_runtime_variables() mock_cfg.return_value = "Define: DUMP_RUN_CFG\nDefine: TLS=443=24" self.assertRaises( errors.PluginError, self.parser.update_runtime_variables) @mock.patch("letsencrypt_apache.constants.os_constant") @mock.patch("letsencrypt_apache.parser.subprocess.Popen") def test_update_runtime_vars_bad_ctl(self, mock_popen, mock_const): mock_popen.side_effect = OSError mock_const.return_value = "nonexistent" self.assertRaises( errors.MisconfigurationError, self.parser.update_runtime_variables) @mock.patch("letsencrypt_apache.parser.subprocess.Popen") def test_update_runtime_vars_bad_exit(self, mock_popen): mock_popen().communicate.return_value = ("", "") mock_popen.returncode = -1 self.assertRaises( errors.MisconfigurationError, self.parser.update_runtime_variables) class ParserInitTest(util.ApacheTest): def setUp(self): # pylint: disable=arguments-differ super(ParserInitTest, self).setUp() self.aug = augeas.Augeas( flags=augeas.Augeas.NONE | augeas.Augeas.NO_MODL_AUTOLOAD) def tearDown(self): shutil.rmtree(self.temp_dir) shutil.rmtree(self.config_dir) shutil.rmtree(self.work_dir) @mock.patch("letsencrypt_apache.parser.ApacheParser._get_runtime_cfg") def test_unparsable(self, mock_cfg): from letsencrypt_apache.parser import ApacheParser mock_cfg.return_value = ('Define: TEST') self.assertRaises( errors.PluginError, ApacheParser, self.aug, os.path.relpath(self.config_path), "/dummy/vhostpath", version=(2, 2, 22)) def test_root_normalized(self): from letsencrypt_apache.parser import ApacheParser with mock.patch("letsencrypt_apache.parser.ApacheParser." "update_runtime_variables"): path = os.path.join( self.temp_dir, "debian_apache_2_4/////two_vhost_80/../two_vhost_80/apache2") parser = ApacheParser(self.aug, path, "/dummy/vhostpath") self.assertEqual(parser.root, self.config_path) def test_root_absolute(self): from letsencrypt_apache.parser import ApacheParser with mock.patch("letsencrypt_apache.parser.ApacheParser." "update_runtime_variables"): parser = ApacheParser( self.aug, os.path.relpath(self.config_path), "/dummy/vhostpath") self.assertEqual(parser.root, self.config_path) def test_root_no_trailing_slash(self): from letsencrypt_apache.parser import ApacheParser with mock.patch("letsencrypt_apache.parser.ApacheParser." "update_runtime_variables"): parser = ApacheParser( self.aug, self.config_path + os.path.sep, "/dummy/vhostpath") self.assertEqual(parser.root, self.config_path) if __name__ == "__main__": unittest.main() # pragma: no cover letsencrypt-apache-0.4.1/letsencrypt_apache/tests/__init__.py0000644000175000017500000000004112665157707024046 0ustar bmwbmw00000000000000"""Let's Encrypt Apache Tests""" letsencrypt-apache-0.4.1/letsencrypt_apache/tests/configurator_test.py0000644000175000017500000012375612665157707026073 0ustar bmwbmw00000000000000# pylint: disable=too-many-public-methods """Test for letsencrypt_apache.configurator.""" import os import shutil import socket import unittest import mock from acme import challenges from letsencrypt import achallenges from letsencrypt import errors from letsencrypt.tests import acme_util from letsencrypt_apache import configurator from letsencrypt_apache import obj from letsencrypt_apache.tests import util class TwoVhost80Test(util.ApacheTest): """Test two standard well-configured HTTP vhosts.""" def setUp(self): # pylint: disable=arguments-differ super(TwoVhost80Test, self).setUp() self.config = util.get_apache_configurator( self.config_path, self.vhost_path, self.config_dir, self.work_dir) self.config = self.mock_deploy_cert(self.config) self.vh_truth = util.get_vh_truth( self.temp_dir, "debian_apache_2_4/two_vhost_80") def mock_deploy_cert(self, config): """A test for a mock deploy cert""" self.config.real_deploy_cert = self.config.deploy_cert def mocked_deploy_cert(*args, **kwargs): """a helper to mock a deployed cert""" with mock.patch("letsencrypt_apache.configurator.ApacheConfigurator.enable_mod"): config.real_deploy_cert(*args, **kwargs) self.config.deploy_cert = mocked_deploy_cert return self.config def tearDown(self): shutil.rmtree(self.temp_dir) shutil.rmtree(self.config_dir) shutil.rmtree(self.work_dir) @mock.patch("letsencrypt_apache.configurator.le_util.exe_exists") def test_prepare_no_install(self, mock_exe_exists): mock_exe_exists.return_value = False self.assertRaises( errors.NoInstallationError, self.config.prepare) @mock.patch("letsencrypt_apache.parser.ApacheParser") @mock.patch("letsencrypt_apache.configurator.le_util.exe_exists") def test_prepare_version(self, mock_exe_exists, _): mock_exe_exists.return_value = True self.config.version = None self.config.config_test = mock.Mock() self.config.get_version = mock.Mock(return_value=(1, 1)) self.assertRaises( errors.NotSupportedError, self.config.prepare) @mock.patch("letsencrypt_apache.parser.ApacheParser") @mock.patch("letsencrypt_apache.configurator.le_util.exe_exists") def test_prepare_old_aug(self, mock_exe_exists, _): mock_exe_exists.return_value = True self.config.config_test = mock.Mock() # pylint: disable=protected-access self.config._check_aug_version = mock.Mock(return_value=False) self.assertRaises( errors.NotSupportedError, self.config.prepare) def test_add_parser_arguments(self): # pylint: disable=no-self-use from letsencrypt_apache.configurator import ApacheConfigurator # Weak test.. ApacheConfigurator.add_parser_arguments(mock.MagicMock()) @mock.patch("zope.component.getUtility") def test_get_all_names(self, mock_getutility): mock_getutility.notification = mock.MagicMock(return_value=True) names = self.config.get_all_names() self.assertEqual(names, set( ["letsencrypt.demo", "encryption-example.demo", "ip-172-30-0-17", "*.blue.purple.com"])) @mock.patch("zope.component.getUtility") @mock.patch("letsencrypt_apache.configurator.socket.gethostbyaddr") def test_get_all_names_addrs(self, mock_gethost, mock_getutility): mock_gethost.side_effect = [("google.com", "", ""), socket.error] notification = mock.Mock() notification.notification = mock.Mock(return_value=True) mock_getutility.return_value = notification vhost = obj.VirtualHost( "fp", "ap", set([obj.Addr(("8.8.8.8", "443")), obj.Addr(("zombo.com",)), obj.Addr(("192.168.1.2"))]), True, False) self.config.vhosts.append(vhost) names = self.config.get_all_names() self.assertEqual(len(names), 6) self.assertTrue("zombo.com" in names) self.assertTrue("google.com" in names) self.assertTrue("letsencrypt.demo" in names) def test_add_servernames_alias(self): self.config.parser.add_dir( self.vh_truth[2].path, "ServerAlias", ["*.le.co"]) # pylint: disable=protected-access self.config._add_servernames(self.vh_truth[2]) self.assertEqual( self.vh_truth[2].get_names(), set(["*.le.co", "ip-172-30-0-17"])) def test_get_virtual_hosts(self): """Make sure all vhosts are being properly found. .. note:: If test fails, only finding 1 Vhost... it is likely that it is a problem with is_enabled. If finding only 3, likely is_ssl """ vhs = self.config.get_virtual_hosts() self.assertEqual(len(vhs), 7) found = 0 for vhost in vhs: for truth in self.vh_truth: if vhost == truth: found += 1 break else: raise Exception("Missed: %s" % vhost) # pragma: no cover self.assertEqual(found, 7) # Handle case of non-debian layout get_virtual_hosts with mock.patch( "letsencrypt_apache.configurator.ApacheConfigurator.conf" ) as mock_conf: mock_conf.return_value = False vhs = self.config.get_virtual_hosts() self.assertEqual(len(vhs), 7) @mock.patch("letsencrypt_apache.display_ops.select_vhost") def test_choose_vhost_none_avail(self, mock_select): mock_select.return_value = None self.assertRaises( errors.PluginError, self.config.choose_vhost, "none.com") @mock.patch("letsencrypt_apache.display_ops.select_vhost") def test_choose_vhost_select_vhost_ssl(self, mock_select): mock_select.return_value = self.vh_truth[1] self.assertEqual( self.vh_truth[1], self.config.choose_vhost("none.com")) @mock.patch("letsencrypt_apache.display_ops.select_vhost") def test_choose_vhost_select_vhost_non_ssl(self, mock_select): mock_select.return_value = self.vh_truth[0] chosen_vhost = self.config.choose_vhost("none.com") self.vh_truth[0].aliases.add("none.com") self.assertEqual( self.vh_truth[0].get_names(), chosen_vhost.get_names()) # Make sure we go from HTTP -> HTTPS self.assertFalse(self.vh_truth[0].ssl) self.assertTrue(chosen_vhost.ssl) @mock.patch("letsencrypt_apache.display_ops.select_vhost") def test_choose_vhost_select_vhost_with_temp(self, mock_select): mock_select.return_value = self.vh_truth[0] chosen_vhost = self.config.choose_vhost("none.com", temp=True) self.assertEqual(self.vh_truth[0], chosen_vhost) @mock.patch("letsencrypt_apache.display_ops.select_vhost") def test_choose_vhost_select_vhost_conflicting_non_ssl(self, mock_select): mock_select.return_value = self.vh_truth[3] conflicting_vhost = obj.VirtualHost( "path", "aug_path", set([obj.Addr.fromstring("*:443")]), True, True) self.config.vhosts.append(conflicting_vhost) self.assertRaises( errors.PluginError, self.config.choose_vhost, "none.com") def test_choosevhost_select_vhost_with_wildcard(self): chosen_vhost = self.config.choose_vhost("blue.purple.com", temp=True) self.assertEqual(self.vh_truth[6], chosen_vhost) def test_findbest_continues_on_short_domain(self): # pylint: disable=protected-access chosen_vhost = self.config._find_best_vhost("purple.com") self.assertEqual(None, chosen_vhost) def test_findbest_continues_on_long_domain(self): # pylint: disable=protected-access chosen_vhost = self.config._find_best_vhost("green.red.purple.com") self.assertEqual(None, chosen_vhost) def test_find_best_vhost(self): # pylint: disable=protected-access self.assertEqual( self.vh_truth[3], self.config._find_best_vhost("letsencrypt.demo")) self.assertEqual( self.vh_truth[0], self.config._find_best_vhost("encryption-example.demo")) self.assertEqual( self.config._find_best_vhost("does-not-exist.com"), None) def test_find_best_vhost_variety(self): # pylint: disable=protected-access ssl_vh = obj.VirtualHost( "fp", "ap", set([obj.Addr(("*", "443")), obj.Addr(("zombo.com",))]), True, False) self.config.vhosts.append(ssl_vh) self.assertEqual(self.config._find_best_vhost("zombo.com"), ssl_vh) def test_find_best_vhost_default(self): # pylint: disable=protected-access # Assume only the two default vhosts. self.config.vhosts = [ vh for vh in self.config.vhosts if vh.name not in ["letsencrypt.demo", "encryption-example.demo"] and "*.blue.purple.com" not in vh.aliases ] self.assertEqual( self.config._find_best_vhost("example.demo"), self.vh_truth[2]) def test_non_default_vhosts(self): # pylint: disable=protected-access self.assertEqual(len(self.config._non_default_vhosts()), 5) def test_is_site_enabled(self): """Test if site is enabled. .. note:: This test currently fails for hard links (which may happen if you move dirs incorrectly) .. warning:: This test does not work when running using the unittest.main() function. It incorrectly copies symlinks. """ self.assertTrue(self.config.is_site_enabled(self.vh_truth[0].filep)) self.assertFalse(self.config.is_site_enabled(self.vh_truth[1].filep)) self.assertTrue(self.config.is_site_enabled(self.vh_truth[2].filep)) self.assertTrue(self.config.is_site_enabled(self.vh_truth[3].filep)) with mock.patch("os.path.isdir") as mock_isdir: mock_isdir.return_value = False self.assertRaises(errors.ConfigurationError, self.config.is_site_enabled, "irrelevant") @mock.patch("letsencrypt.le_util.run_script") @mock.patch("letsencrypt.le_util.exe_exists") @mock.patch("letsencrypt_apache.parser.subprocess.Popen") def test_enable_mod(self, mock_popen, mock_exe_exists, mock_run_script): mock_popen().communicate.return_value = ("Define: DUMP_RUN_CFG", "") mock_popen().returncode = 0 mock_exe_exists.return_value = True self.config.enable_mod("ssl") self.assertTrue("ssl_module" in self.config.parser.modules) self.assertTrue("mod_ssl.c" in self.config.parser.modules) self.assertTrue(mock_run_script.called) def test_enable_mod_unsupported_dirs(self): shutil.rmtree(os.path.join(self.config.parser.root, "mods-enabled")) self.assertRaises( errors.NotSupportedError, self.config.enable_mod, "ssl") @mock.patch("letsencrypt.le_util.exe_exists") def test_enable_mod_no_disable(self, mock_exe_exists): mock_exe_exists.return_value = False self.assertRaises( errors.MisconfigurationError, self.config.enable_mod, "ssl") def test_enable_site(self): # Default 443 vhost self.assertFalse(self.vh_truth[1].enabled) self.config.enable_site(self.vh_truth[1]) self.assertTrue(self.vh_truth[1].enabled) # Go again to make sure nothing fails self.config.enable_site(self.vh_truth[1]) def test_enable_site_failure(self): self.assertRaises( errors.NotSupportedError, self.config.enable_site, obj.VirtualHost("asdf", "afsaf", set(), False, False)) def test_deploy_cert_newssl(self): self.config = util.get_apache_configurator( self.config_path, self.vhost_path, self.config_dir, self.work_dir, version=(2, 4, 16)) self.config.parser.modules.add("ssl_module") self.config.parser.modules.add("mod_ssl.c") # Get the default 443 vhost self.config.assoc["random.demo"] = self.vh_truth[1] self.config = self.mock_deploy_cert(self.config) self.config.deploy_cert( "random.demo", "example/cert.pem", "example/key.pem", "example/cert_chain.pem", "example/fullchain.pem") self.config.save() # Verify ssl_module was enabled. self.assertTrue(self.vh_truth[1].enabled) self.assertTrue("ssl_module" in self.config.parser.modules) loc_cert = self.config.parser.find_dir( "sslcertificatefile", "example/fullchain.pem", self.vh_truth[1].path) loc_key = self.config.parser.find_dir( "sslcertificateKeyfile", "example/key.pem", self.vh_truth[1].path) # Verify one directive was found in the correct file self.assertEqual(len(loc_cert), 1) self.assertEqual(configurator.get_file_path(loc_cert[0]), self.vh_truth[1].filep) self.assertEqual(len(loc_key), 1) self.assertEqual(configurator.get_file_path(loc_key[0]), self.vh_truth[1].filep) def test_deploy_cert_newssl_no_fullchain(self): self.config = util.get_apache_configurator( self.config_path, self.vhost_path, self.config_dir, self.work_dir, version=(2, 4, 16)) self.config = self.mock_deploy_cert(self.config) self.config.parser.modules.add("ssl_module") self.config.parser.modules.add("mod_ssl.c") # Get the default 443 vhost self.config.assoc["random.demo"] = self.vh_truth[1] self.assertRaises(errors.PluginError, lambda: self.config.deploy_cert( "random.demo", "example/cert.pem", "example/key.pem")) def test_deploy_cert_old_apache_no_chain(self): self.config = util.get_apache_configurator( self.config_path, self.vhost_path, self.config_dir, self.work_dir, version=(2, 4, 7)) self.config = self.mock_deploy_cert(self.config) self.config.parser.modules.add("ssl_module") self.config.parser.modules.add("mod_ssl.c") # Get the default 443 vhost self.config.assoc["random.demo"] = self.vh_truth[1] self.assertRaises(errors.PluginError, lambda: self.config.deploy_cert( "random.demo", "example/cert.pem", "example/key.pem")) def test_deploy_cert(self): self.config.parser.modules.add("ssl_module") self.config.parser.modules.add("mod_ssl.c") # Get the default 443 vhost self.config.assoc["random.demo"] = self.vh_truth[1] self.config.deploy_cert( "random.demo", "example/cert.pem", "example/key.pem", "example/cert_chain.pem") self.config.save() # Verify ssl_module was enabled. self.assertTrue(self.vh_truth[1].enabled) self.assertTrue("ssl_module" in self.config.parser.modules) loc_cert = self.config.parser.find_dir( "sslcertificatefile", "example/cert.pem", self.vh_truth[1].path) loc_key = self.config.parser.find_dir( "sslcertificateKeyfile", "example/key.pem", self.vh_truth[1].path) loc_chain = self.config.parser.find_dir( "SSLCertificateChainFile", "example/cert_chain.pem", self.vh_truth[1].path) # Verify one directive was found in the correct file self.assertEqual(len(loc_cert), 1) self.assertEqual(configurator.get_file_path(loc_cert[0]), self.vh_truth[1].filep) self.assertEqual(len(loc_key), 1) self.assertEqual(configurator.get_file_path(loc_key[0]), self.vh_truth[1].filep) self.assertEqual(len(loc_chain), 1) self.assertEqual(configurator.get_file_path(loc_chain[0]), self.vh_truth[1].filep) # One more time for chain directive setting self.config.deploy_cert( "random.demo", "two/cert.pem", "two/key.pem", "two/cert_chain.pem") self.assertTrue(self.config.parser.find_dir( "SSLCertificateChainFile", "two/cert_chain.pem", self.vh_truth[1].path)) def test_deploy_cert_invalid_vhost(self): self.config.parser.modules.add("ssl_module") mock_find = mock.MagicMock() mock_find.return_value = [] self.config.parser.find_dir = mock_find # Get the default 443 vhost self.config.assoc["random.demo"] = self.vh_truth[1] self.assertRaises( errors.PluginError, self.config.deploy_cert, "random.demo", "example/cert.pem", "example/key.pem", "example/cert_chain.pem") def test_is_name_vhost(self): addr = obj.Addr.fromstring("*:80") self.assertTrue(self.config.is_name_vhost(addr)) self.config.version = (2, 2) self.assertFalse(self.config.is_name_vhost(addr)) def test_add_name_vhost(self): self.config.add_name_vhost(obj.Addr.fromstring("*:443")) self.config.add_name_vhost(obj.Addr.fromstring("*:80")) self.assertTrue(self.config.parser.find_dir( "NameVirtualHost", "*:443", exclude=False)) self.assertTrue(self.config.parser.find_dir( "NameVirtualHost", "*:80")) def test_prepare_server_https(self): mock_enable = mock.Mock() self.config.enable_mod = mock_enable mock_find = mock.Mock() mock_add_dir = mock.Mock() mock_find.return_value = [] # This will test the Add listen self.config.parser.find_dir = mock_find self.config.parser.add_dir_to_ifmodssl = mock_add_dir self.config.prepare_server_https("443") # Changing the order these modules are enabled breaks the reverter self.assertEqual(mock_enable.call_args_list[0][0][0], "socache_shmcb") self.assertEqual(mock_enable.call_args[0][0], "ssl") self.assertEqual(mock_enable.call_args[1], {"temp": False}) self.config.prepare_server_https("8080", temp=True) # Changing the order these modules are enabled breaks the reverter self.assertEqual(mock_enable.call_args_list[2][0][0], "socache_shmcb") self.assertEqual(mock_enable.call_args[0][0], "ssl") # Enable mod is temporary self.assertEqual(mock_enable.call_args[1], {"temp": True}) self.assertEqual(mock_add_dir.call_count, 2) def test_prepare_server_https_named_listen(self): mock_find = mock.Mock() mock_find.return_value = ["test1", "test2", "test3"] mock_get = mock.Mock() mock_get.side_effect = ["1.2.3.4:80", "[::1]:80", "1.1.1.1:443"] mock_add_dir = mock.Mock() mock_enable = mock.Mock() self.config.parser.find_dir = mock_find self.config.parser.get_arg = mock_get self.config.parser.add_dir_to_ifmodssl = mock_add_dir self.config.enable_mod = mock_enable # Test Listen statements with specific ip listeed self.config.prepare_server_https("443") # Should only be 2 here, as the third interface # already listens to the correct port self.assertEqual(mock_add_dir.call_count, 2) # Check argument to new Listen statements self.assertEqual(mock_add_dir.call_args_list[0][0][2], ["1.2.3.4:443"]) self.assertEqual(mock_add_dir.call_args_list[1][0][2], ["[::1]:443"]) # Reset return lists and inputs mock_add_dir.reset_mock() mock_get.side_effect = ["1.2.3.4:80", "[::1]:80", "1.1.1.1:443"] # Test self.config.prepare_server_https("8080", temp=True) self.assertEqual(mock_add_dir.call_count, 3) self.assertEqual(mock_add_dir.call_args_list[0][0][2], ["1.2.3.4:8080", "https"]) self.assertEqual(mock_add_dir.call_args_list[1][0][2], ["[::1]:8080", "https"]) self.assertEqual(mock_add_dir.call_args_list[2][0][2], ["1.1.1.1:8080", "https"]) def test_prepare_server_https_mixed_listen(self): mock_find = mock.Mock() mock_find.return_value = ["test1", "test2"] mock_get = mock.Mock() mock_get.side_effect = ["1.2.3.4:8080", "443"] mock_add_dir = mock.Mock() mock_enable = mock.Mock() self.config.parser.find_dir = mock_find self.config.parser.get_arg = mock_get self.config.parser.add_dir_to_ifmodssl = mock_add_dir self.config.enable_mod = mock_enable # Test Listen statements with specific ip listeed self.config.prepare_server_https("443") # Should only be 2 here, as the third interface # already listens to the correct port self.assertEqual(mock_add_dir.call_count, 0) def test_make_vhost_ssl(self): ssl_vhost = self.config.make_vhost_ssl(self.vh_truth[0]) self.assertEqual( ssl_vhost.filep, os.path.join(self.config_path, "sites-available", "encryption-example-le-ssl.conf")) self.assertEqual(ssl_vhost.path, "/files" + ssl_vhost.filep + "/IfModule/VirtualHost") self.assertEqual(len(ssl_vhost.addrs), 1) self.assertEqual(set([obj.Addr.fromstring("*:443")]), ssl_vhost.addrs) self.assertEqual(ssl_vhost.name, "encryption-example.demo") self.assertTrue(ssl_vhost.ssl) self.assertFalse(ssl_vhost.enabled) self.assertTrue(self.config.parser.find_dir( "SSLCertificateFile", None, ssl_vhost.path, False)) self.assertTrue(self.config.parser.find_dir( "SSLCertificateKeyFile", None, ssl_vhost.path, False)) self.assertEqual(self.config.is_name_vhost(self.vh_truth[0]), self.config.is_name_vhost(ssl_vhost)) self.assertEqual(len(self.config.vhosts), 8) def test_clean_vhost_ssl(self): # pylint: disable=protected-access for directive in ["SSLCertificateFile", "SSLCertificateKeyFile", "SSLCertificateChainFile", "SSLCACertificatePath"]: for _ in range(10): self.config.parser.add_dir(self.vh_truth[1].path, directive, ["bogus"]) self.config.save() self.config._clean_vhost(self.vh_truth[1]) self.config.save() loc_cert = self.config.parser.find_dir( 'SSLCertificateFile', None, self.vh_truth[1].path, False) loc_key = self.config.parser.find_dir( 'SSLCertificateKeyFile', None, self.vh_truth[1].path, False) loc_chain = self.config.parser.find_dir( 'SSLCertificateChainFile', None, self.vh_truth[1].path, False) loc_cacert = self.config.parser.find_dir( 'SSLCACertificatePath', None, self.vh_truth[1].path, False) self.assertEqual(len(loc_cert), 1) self.assertEqual(len(loc_key), 1) self.assertEqual(len(loc_chain), 0) self.assertEqual(len(loc_cacert), 10) def test_deduplicate_directives(self): # pylint: disable=protected-access DIRECTIVE = "Foo" for _ in range(10): self.config.parser.add_dir(self.vh_truth[1].path, DIRECTIVE, ["bar"]) self.config.save() self.config._deduplicate_directives(self.vh_truth[1].path, [DIRECTIVE]) self.config.save() self.assertEqual( len(self.config.parser.find_dir( DIRECTIVE, None, self.vh_truth[1].path, False)), 1) def test_remove_directives(self): # pylint: disable=protected-access DIRECTIVES = ["Foo", "Bar"] for directive in DIRECTIVES: for _ in range(10): self.config.parser.add_dir(self.vh_truth[1].path, directive, ["baz"]) self.config.save() self.config._remove_directives(self.vh_truth[1].path, DIRECTIVES) self.config.save() for directive in DIRECTIVES: self.assertEqual( len(self.config.parser.find_dir( directive, None, self.vh_truth[1].path, False)), 0) def test_make_vhost_ssl_extra_vhs(self): self.config.aug.match = mock.Mock(return_value=["p1", "p2"]) self.assertRaises( errors.PluginError, self.config.make_vhost_ssl, self.vh_truth[0]) def test_make_vhost_ssl_bad_write(self): mock_open = mock.mock_open() # This calls open self.config.reverter.register_file_creation = mock.Mock() mock_open.side_effect = IOError with mock.patch("__builtin__.open", mock_open): self.assertRaises( errors.PluginError, self.config.make_vhost_ssl, self.vh_truth[0]) def test_get_ssl_vhost_path(self): # pylint: disable=protected-access self.assertTrue( self.config._get_ssl_vhost_path("example_path").endswith(".conf")) def test_add_name_vhost_if_necessary(self): # pylint: disable=protected-access self.config.save = mock.Mock() self.config.version = (2, 2) self.config._add_name_vhost_if_necessary(self.vh_truth[0]) self.assertTrue(self.config.save.called) new_addrs = set() for addr in self.vh_truth[0].addrs: new_addrs.add(obj.Addr(("_default_", addr.get_port(),))) self.vh_truth[0].addrs = new_addrs self.config._add_name_vhost_if_necessary(self.vh_truth[0]) self.assertEqual(self.config.save.call_count, 2) @mock.patch("letsencrypt_apache.configurator.tls_sni_01.ApacheTlsSni01.perform") @mock.patch("letsencrypt_apache.configurator.ApacheConfigurator.restart") def test_perform(self, mock_restart, mock_perform): # Only tests functionality specific to configurator.perform # Note: As more challenges are offered this will have to be expanded account_key, achall1, achall2 = self.get_achalls() expected = [ achall1.response(account_key), achall2.response(account_key), ] mock_perform.return_value = expected responses = self.config.perform([achall1, achall2]) self.assertEqual(mock_perform.call_count, 1) self.assertEqual(responses, expected) self.assertEqual(mock_restart.call_count, 1) @mock.patch("letsencrypt_apache.configurator.ApacheConfigurator.restart") def test_cleanup(self, mock_restart): _, achall1, achall2 = self.get_achalls() self.config._chall_out.add(achall1) # pylint: disable=protected-access self.config._chall_out.add(achall2) # pylint: disable=protected-access self.config.cleanup([achall1]) self.assertFalse(mock_restart.called) self.config.cleanup([achall2]) self.assertTrue(mock_restart.called) @mock.patch("letsencrypt_apache.configurator.ApacheConfigurator.restart") def test_cleanup_no_errors(self, mock_restart): _, achall1, achall2 = self.get_achalls() self.config._chall_out.add(achall1) # pylint: disable=protected-access self.config.cleanup([achall2]) self.assertFalse(mock_restart.called) self.config.cleanup([achall1, achall2]) self.assertTrue(mock_restart.called) @mock.patch("letsencrypt.le_util.run_script") def test_get_version(self, mock_script): mock_script.return_value = ( "Server Version: Apache/2.4.2 (Debian)", "") self.assertEqual(self.config.get_version(), (2, 4, 2)) mock_script.return_value = ( "Server Version: Apache/2 (Linux)", "") self.assertEqual(self.config.get_version(), (2,)) mock_script.return_value = ( "Server Version: Apache (Debian)", "") self.assertRaises(errors.PluginError, self.config.get_version) mock_script.return_value = ( "Server Version: Apache/2.3{0} Apache/2.4.7".format( os.linesep), "") self.assertRaises(errors.PluginError, self.config.get_version) mock_script.side_effect = errors.SubprocessError("Can't find program") self.assertRaises(errors.PluginError, self.config.get_version) @mock.patch("letsencrypt_apache.configurator.le_util.run_script") def test_restart(self, _): self.config.restart() @mock.patch("letsencrypt_apache.configurator.le_util.run_script") def test_restart_bad_process(self, mock_run_script): mock_run_script.side_effect = [None, errors.SubprocessError] self.assertRaises(errors.MisconfigurationError, self.config.restart) @mock.patch("letsencrypt.le_util.run_script") def test_config_test(self, _): self.config.config_test() @mock.patch("letsencrypt.le_util.run_script") def test_config_test_bad_process(self, mock_run_script): mock_run_script.side_effect = errors.SubprocessError self.assertRaises(errors.MisconfigurationError, self.config.config_test) def test_get_all_certs_keys(self): c_k = self.config.get_all_certs_keys() self.assertEqual(len(c_k), 2) cert, key, path = next(iter(c_k)) self.assertTrue("cert" in cert) self.assertTrue("key" in key) self.assertTrue("default-ssl" in path) def test_get_all_certs_keys_malformed_conf(self): self.config.parser.find_dir = mock.Mock( side_effect=[["path"], [], ["path"], []]) c_k = self.config.get_all_certs_keys() self.assertFalse(c_k) def test_more_info(self): self.assertTrue(self.config.more_info()) def test_get_chall_pref(self): self.assertTrue(isinstance(self.config.get_chall_pref(""), list)) def test_install_ssl_options_conf(self): from letsencrypt_apache.configurator import install_ssl_options_conf path = os.path.join(self.work_dir, "test_it") install_ssl_options_conf(path) self.assertTrue(os.path.isfile(path)) # TEST ENHANCEMENTS def test_supported_enhancements(self): self.assertTrue(isinstance(self.config.supported_enhancements(), list)) @mock.patch("letsencrypt.le_util.exe_exists") def test_enhance_unknown_vhost(self, mock_exe): self.config.parser.modules.add("rewrite_module") mock_exe.return_value = True ssl_vh = obj.VirtualHost( "fp", "ap", set([obj.Addr(("*", "443"))]), True, False) ssl_vh.name = "satoshi.com" self.config.vhosts.append(ssl_vh) self.assertRaises( errors.PluginError, self.config.enhance, "satoshi.com", "redirect") def test_enhance_unknown_enhancement(self): self.assertRaises( errors.PluginError, self.config.enhance, "letsencrypt.demo", "unknown_enhancement") @mock.patch("letsencrypt.le_util.run_script") @mock.patch("letsencrypt.le_util.exe_exists") def test_http_header_hsts(self, mock_exe, _): self.config.parser.update_runtime_variables = mock.Mock() self.config.parser.modules.add("mod_ssl.c") mock_exe.return_value = True # This will create an ssl vhost for letsencrypt.demo self.config.enhance("letsencrypt.demo", "ensure-http-header", "Strict-Transport-Security") self.assertTrue("headers_module" in self.config.parser.modules) # Get the ssl vhost for letsencrypt.demo ssl_vhost = self.config.assoc["letsencrypt.demo"] # These are not immediately available in find_dir even with save() and # load(). They must be found in sites-available hsts_header = self.config.parser.find_dir( "Header", None, ssl_vhost.path) # four args to HSTS header self.assertEqual(len(hsts_header), 4) def test_http_header_hsts_twice(self): self.config.parser.modules.add("mod_ssl.c") # skip the enable mod self.config.parser.modules.add("headers_module") # This will create an ssl vhost for letsencrypt.demo self.config.enhance("encryption-example.demo", "ensure-http-header", "Strict-Transport-Security") self.assertRaises( errors.PluginEnhancementAlreadyPresent, self.config.enhance, "encryption-example.demo", "ensure-http-header", "Strict-Transport-Security") @mock.patch("letsencrypt.le_util.run_script") @mock.patch("letsencrypt.le_util.exe_exists") def test_http_header_uir(self, mock_exe, _): self.config.parser.update_runtime_variables = mock.Mock() self.config.parser.modules.add("mod_ssl.c") mock_exe.return_value = True # This will create an ssl vhost for letsencrypt.demo self.config.enhance("letsencrypt.demo", "ensure-http-header", "Upgrade-Insecure-Requests") self.assertTrue("headers_module" in self.config.parser.modules) # Get the ssl vhost for letsencrypt.demo ssl_vhost = self.config.assoc["letsencrypt.demo"] # These are not immediately available in find_dir even with save() and # load(). They must be found in sites-available uir_header = self.config.parser.find_dir( "Header", None, ssl_vhost.path) # four args to HSTS header self.assertEqual(len(uir_header), 4) def test_http_header_uir_twice(self): self.config.parser.modules.add("mod_ssl.c") # skip the enable mod self.config.parser.modules.add("headers_module") # This will create an ssl vhost for letsencrypt.demo self.config.enhance("encryption-example.demo", "ensure-http-header", "Upgrade-Insecure-Requests") self.assertRaises( errors.PluginEnhancementAlreadyPresent, self.config.enhance, "encryption-example.demo", "ensure-http-header", "Upgrade-Insecure-Requests") @mock.patch("letsencrypt.le_util.run_script") @mock.patch("letsencrypt.le_util.exe_exists") def test_redirect_well_formed_http(self, mock_exe, _): self.config.parser.update_runtime_variables = mock.Mock() mock_exe.return_value = True self.config.get_version = mock.Mock(return_value=(2, 2)) # This will create an ssl vhost for letsencrypt.demo self.config.enhance("letsencrypt.demo", "redirect") # These are not immediately available in find_dir even with save() and # load(). They must be found in sites-available rw_engine = self.config.parser.find_dir( "RewriteEngine", "on", self.vh_truth[3].path) rw_rule = self.config.parser.find_dir( "RewriteRule", None, self.vh_truth[3].path) self.assertEqual(len(rw_engine), 1) # three args to rw_rule self.assertEqual(len(rw_rule), 3) self.assertTrue(rw_engine[0].startswith(self.vh_truth[3].path)) self.assertTrue(rw_rule[0].startswith(self.vh_truth[3].path)) self.assertTrue("rewrite_module" in self.config.parser.modules) def test_rewrite_rule_exists(self): # Skip the enable mod self.config.parser.modules.add("rewrite_module") self.config.get_version = mock.Mock(return_value=(2, 3, 9)) self.config.parser.add_dir( self.vh_truth[3].path, "RewriteRule", ["Unknown"]) # pylint: disable=protected-access self.assertTrue(self.config._is_rewrite_exists(self.vh_truth[3])) def test_rewrite_engine_exists(self): # Skip the enable mod self.config.parser.modules.add("rewrite_module") self.config.get_version = mock.Mock(return_value=(2, 3, 9)) self.config.parser.add_dir( self.vh_truth[3].path, "RewriteEngine", "on") # pylint: disable=protected-access self.assertTrue(self.config._is_rewrite_engine_on(self.vh_truth[3])) @mock.patch("letsencrypt.le_util.run_script") @mock.patch("letsencrypt.le_util.exe_exists") def test_redirect_with_existing_rewrite(self, mock_exe, _): self.config.parser.update_runtime_variables = mock.Mock() mock_exe.return_value = True self.config.get_version = mock.Mock(return_value=(2, 2)) # Create a preexisting rewrite rule self.config.parser.add_dir( self.vh_truth[3].path, "RewriteRule", ["UnknownPattern", "UnknownTarget"]) self.config.save() # This will create an ssl vhost for letsencrypt.demo self.config.enhance("letsencrypt.demo", "redirect") # These are not immediately available in find_dir even with save() and # load(). They must be found in sites-available rw_engine = self.config.parser.find_dir( "RewriteEngine", "on", self.vh_truth[3].path) rw_rule = self.config.parser.find_dir( "RewriteRule", None, self.vh_truth[3].path) self.assertEqual(len(rw_engine), 1) # three args to rw_rule + 1 arg for the pre existing rewrite self.assertEqual(len(rw_rule), 5) self.assertTrue(rw_engine[0].startswith(self.vh_truth[3].path)) self.assertTrue(rw_rule[0].startswith(self.vh_truth[3].path)) self.assertTrue("rewrite_module" in self.config.parser.modules) def test_redirect_with_conflict(self): self.config.parser.modules.add("rewrite_module") ssl_vh = obj.VirtualHost( "fp", "ap", set([obj.Addr(("*", "443")), obj.Addr(("zombo.com",))]), True, False) # No names ^ this guy should conflict. # pylint: disable=protected-access self.assertRaises( errors.PluginError, self.config._enable_redirect, ssl_vh, "") def test_redirect_twice(self): # Skip the enable mod self.config.parser.modules.add("rewrite_module") self.config.get_version = mock.Mock(return_value=(2, 3, 9)) self.config.enhance("encryption-example.demo", "redirect") self.assertRaises( errors.PluginEnhancementAlreadyPresent, self.config.enhance, "encryption-example.demo", "redirect") def test_create_own_redirect(self): self.config.parser.modules.add("rewrite_module") self.config.get_version = mock.Mock(return_value=(2, 3, 9)) # For full testing... give names... self.vh_truth[1].name = "default.com" self.vh_truth[1].aliases = set(["yes.default.com"]) # pylint: disable=protected-access self.config._enable_redirect(self.vh_truth[1], "") self.assertEqual(len(self.config.vhosts), 8) def test_create_own_redirect_for_old_apache_version(self): self.config.parser.modules.add("rewrite_module") self.config.get_version = mock.Mock(return_value=(2, 2)) # For full testing... give names... self.vh_truth[1].name = "default.com" self.vh_truth[1].aliases = set(["yes.default.com"]) # pylint: disable=protected-access self.config._enable_redirect(self.vh_truth[1], "") self.assertEqual(len(self.config.vhosts), 8) def test_sift_line(self): # pylint: disable=protected-access small_quoted_target = "RewriteRule ^ \"http://\"" self.assertFalse(self.config._sift_line(small_quoted_target)) https_target = "RewriteRule ^ https://satoshi" self.assertTrue(self.config._sift_line(https_target)) normal_target = "RewriteRule ^/(.*) http://www.a.com:1234/$1 [L,R]" self.assertFalse(self.config._sift_line(normal_target)) @mock.patch("letsencrypt_apache.configurator.zope.component.getUtility") def test_make_vhost_ssl_with_existing_rewrite_rule(self, mock_get_utility): self.config.parser.modules.add("rewrite_module") http_vhost = self.vh_truth[0] self.config.parser.add_dir( http_vhost.path, "RewriteEngine", "on") self.config.parser.add_dir( http_vhost.path, "RewriteRule", ["^", "https://%{SERVER_NAME}%{REQUEST_URI}", "[L,QSA,R=permanent]"]) self.config.save() ssl_vhost = self.config.make_vhost_ssl(self.vh_truth[0]) self.assertTrue(self.config.parser.find_dir( "RewriteEngine", "on", ssl_vhost.path, False)) conf_text = open(ssl_vhost.filep).read() commented_rewrite_rule = ("# RewriteRule ^ " "https://%{SERVER_NAME}%{REQUEST_URI} " "[L,QSA,R=permanent]") self.assertTrue(commented_rewrite_rule in conf_text) mock_get_utility().add_message.assert_called_once_with(mock.ANY, mock.ANY) def get_achalls(self): """Return testing achallenges.""" account_key = self.rsa512jwk achall1 = achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.chall_to_challb( challenges.TLSSNI01( token="jIq_Xy1mXGN37tb4L6Xj_es58fW571ZNyXekdZzhh7Q"), "pending"), domain="encryption-example.demo", account_key=account_key) achall2 = achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.chall_to_challb( challenges.TLSSNI01( token="uqnaPzxtrndteOqtrXb0Asl5gOJfWAnnx6QJyvcmlDU"), "pending"), domain="letsencrypt.demo", account_key=account_key) return account_key, achall1, achall2 def test_make_addrs_sni_ready(self): self.config.version = (2, 2) self.config.make_addrs_sni_ready( set([obj.Addr.fromstring("*:443"), obj.Addr.fromstring("*:80")])) self.assertTrue(self.config.parser.find_dir( "NameVirtualHost", "*:80", exclude=False)) self.assertTrue(self.config.parser.find_dir( "NameVirtualHost", "*:443", exclude=False)) def test_aug_version(self): mock_match = mock.Mock(return_value=["something"]) self.config.aug.match = mock_match # pylint: disable=protected-access self.assertEquals(self.config._check_aug_version(), ["something"]) self.config.aug.match.side_effect = RuntimeError self.assertFalse(self.config._check_aug_version()) if __name__ == "__main__": unittest.main() # pragma: no cover letsencrypt-apache-0.4.1/letsencrypt_apache/tests/tls_sni_01_test.py0000644000175000017500000001160412665157707025330 0ustar bmwbmw00000000000000"""Test for letsencrypt_apache.tls_sni_01.""" import unittest import shutil import mock from letsencrypt.plugins import common_test from letsencrypt_apache import obj from letsencrypt_apache.tests import util from six.moves import xrange # pylint: disable=redefined-builtin, import-error class TlsSniPerformTest(util.ApacheTest): """Test the ApacheTlsSni01 challenge.""" auth_key = common_test.TLSSNI01Test.auth_key achalls = common_test.TLSSNI01Test.achalls def setUp(self): # pylint: disable=arguments-differ super(TlsSniPerformTest, self).setUp() config = util.get_apache_configurator( self.config_path, self.vhost_path, self.config_dir, self.work_dir) config.config.tls_sni_01_port = 443 from letsencrypt_apache import tls_sni_01 self.sni = tls_sni_01.ApacheTlsSni01(config) def tearDown(self): shutil.rmtree(self.temp_dir) shutil.rmtree(self.config_dir) shutil.rmtree(self.work_dir) def test_perform0(self): resp = self.sni.perform() self.assertEqual(len(resp), 0) @mock.patch("letsencrypt.le_util.exe_exists") @mock.patch("letsencrypt.le_util.run_script") def test_perform1(self, _, mock_exists): mock_register = mock.Mock() self.sni.configurator.reverter.register_undo_command = mock_register mock_exists.return_value = True self.sni.configurator.parser.update_runtime_variables = mock.Mock() achall = self.achalls[0] self.sni.add_chall(achall) response = self.achalls[0].response(self.auth_key) mock_setup_cert = mock.MagicMock(return_value=response) # pylint: disable=protected-access self.sni._setup_challenge_cert = mock_setup_cert responses = self.sni.perform() # Make sure that register_undo_command was called into temp directory. self.assertEqual(True, mock_register.call_args[0][0]) mock_setup_cert.assert_called_once_with(achall) # Check to make sure challenge config path is included in apache config self.assertEqual( len(self.sni.configurator.parser.find_dir( "Include", self.sni.challenge_conf)), 1) self.assertEqual(len(responses), 1) self.assertEqual(responses[0], response) def test_perform2(self): # Avoid load module self.sni.configurator.parser.modules.add("ssl_module") acme_responses = [] for achall in self.achalls: self.sni.add_chall(achall) acme_responses.append(achall.response(self.auth_key)) mock_setup_cert = mock.MagicMock(side_effect=acme_responses) # pylint: disable=protected-access self.sni._setup_challenge_cert = mock_setup_cert with mock.patch("letsencrypt_apache.configurator.ApacheConfigurator.enable_mod"): sni_responses = self.sni.perform() self.assertEqual(mock_setup_cert.call_count, 2) # Make sure calls made to mocked function were correct self.assertEqual( mock_setup_cert.call_args_list[0], mock.call(self.achalls[0])) self.assertEqual( mock_setup_cert.call_args_list[1], mock.call(self.achalls[1])) self.assertEqual( len(self.sni.configurator.parser.find_dir( "Include", self.sni.challenge_conf)), 1) self.assertEqual(len(sni_responses), 2) for i in xrange(2): self.assertEqual(sni_responses[i], acme_responses[i]) def test_mod_config(self): z_domains = [] for achall in self.achalls: self.sni.add_chall(achall) z_domain = achall.response(self.auth_key).z_domain z_domains.append(set([z_domain])) self.sni._mod_config() # pylint: disable=protected-access self.sni.configurator.save() self.sni.configurator.parser.find_dir( "Include", self.sni.challenge_conf) vh_match = self.sni.configurator.aug.match( "/files" + self.sni.challenge_conf + "//VirtualHost") vhs = [] for match in vh_match: # pylint: disable=protected-access vhs.append(self.sni.configurator._create_vhost(match)) self.assertEqual(len(vhs), 2) for vhost in vhs: self.assertEqual(vhost.addrs, set([obj.Addr.fromstring("*:443")])) names = vhost.get_names() self.assertTrue(names in z_domains) def test_get_addrs_default(self): self.sni.configurator.choose_vhost = mock.Mock( return_value=obj.VirtualHost( "path", "aug_path", set([obj.Addr.fromstring("_default_:443")]), False, False) ) # pylint: disable=protected-access self.assertEqual( set([obj.Addr.fromstring("*:443")]), self.sni._get_addrs(self.achalls[0])) if __name__ == "__main__": unittest.main() # pragma: no cover letsencrypt-apache-0.4.1/letsencrypt_apache/tests/util.py0000644000175000017500000001477712665157707023311 0ustar bmwbmw00000000000000"""Common utilities for letsencrypt_apache.""" import os import sys import unittest import augeas import mock import zope.component from acme import jose from letsencrypt.display import util as display_util from letsencrypt.plugins import common from letsencrypt.tests import test_util from letsencrypt_apache import configurator from letsencrypt_apache import constants from letsencrypt_apache import obj class ApacheTest(unittest.TestCase): # pylint: disable=too-few-public-methods def setUp(self, test_dir="debian_apache_2_4/two_vhost_80", config_root="debian_apache_2_4/two_vhost_80/apache2", vhost_root="debian_apache_2_4/two_vhost_80/apache2/sites-available"): # pylint: disable=arguments-differ super(ApacheTest, self).setUp() self.temp_dir, self.config_dir, self.work_dir = common.dir_setup( test_dir=test_dir, pkg="letsencrypt_apache.tests") self.ssl_options = common.setup_ssl_options( self.config_dir, constants.os_constant("MOD_SSL_CONF_SRC"), constants.MOD_SSL_CONF_DEST) self.config_path = os.path.join(self.temp_dir, config_root) self.vhost_path = os.path.join(self.temp_dir, vhost_root) self.rsa512jwk = jose.JWKRSA.load(test_util.load_vector( "rsa512_key.pem")) # Make sure all vhosts in sites-enabled are symlinks (Python packaging # does not preserve symlinks) sites_enabled = os.path.join(self.config_path, "sites-enabled") if not os.path.exists(sites_enabled): return for vhost_basename in os.listdir(sites_enabled): vhost = os.path.join(sites_enabled, vhost_basename) if not os.path.islink(vhost): # pragma: no cover os.remove(vhost) target = os.path.join( os.path.pardir, "sites-available", vhost_basename) os.symlink(target, vhost) class ParserTest(ApacheTest): # pytlint: disable=too-few-public-methods def setUp(self, test_dir="debian_apache_2_4/two_vhost_80", config_root="debian_apache_2_4/two_vhost_80/apache2", vhost_root="debian_apache_2_4/two_vhost_80/apache2/sites-available"): super(ParserTest, self).setUp(test_dir, config_root, vhost_root) zope.component.provideUtility(display_util.FileDisplay(sys.stdout)) from letsencrypt_apache.parser import ApacheParser self.aug = augeas.Augeas( flags=augeas.Augeas.NONE | augeas.Augeas.NO_MODL_AUTOLOAD) with mock.patch("letsencrypt_apache.parser.ApacheParser." "update_runtime_variables"): self.parser = ApacheParser( self.aug, self.config_path, self.vhost_path) def get_apache_configurator( config_path, vhost_path, config_dir, work_dir, version=(2, 4, 7), conf=None): """Create an Apache Configurator with the specified options. :param conf: Function that returns binary paths. self.conf in Configurator """ backups = os.path.join(work_dir, "backups") mock_le_config = mock.MagicMock( apache_server_root=config_path, apache_vhost_root=vhost_path, apache_le_vhost_ext=constants.os_constant("le_vhost_ext"), apache_challenge_location=config_path, backup_dir=backups, config_dir=config_dir, temp_checkpoint_dir=os.path.join(work_dir, "temp_checkpoints"), in_progress_dir=os.path.join(backups, "IN_PROGRESS"), work_dir=work_dir) with mock.patch("letsencrypt_apache.configurator.le_util.run_script"): with mock.patch("letsencrypt_apache.configurator.le_util." "exe_exists") as mock_exe_exists: mock_exe_exists.return_value = True with mock.patch("letsencrypt_apache.parser.ApacheParser." "update_runtime_variables"): config = configurator.ApacheConfigurator( config=mock_le_config, name="apache", version=version) # This allows testing scripts to set it a bit more quickly if conf is not None: config.conf = conf # pragma: no cover config.prepare() return config def get_vh_truth(temp_dir, config_name): """Return the ground truth for the specified directory.""" if config_name == "debian_apache_2_4/two_vhost_80": prefix = os.path.join( temp_dir, config_name, "apache2/sites-available") aug_pre = "/files" + prefix vh_truth = [ obj.VirtualHost( os.path.join(prefix, "encryption-example.conf"), os.path.join(aug_pre, "encryption-example.conf/VirtualHost"), set([obj.Addr.fromstring("*:80")]), False, True, "encryption-example.demo"), obj.VirtualHost( os.path.join(prefix, "default-ssl.conf"), os.path.join(aug_pre, "default-ssl.conf/IfModule/VirtualHost"), set([obj.Addr.fromstring("_default_:443")]), True, False), obj.VirtualHost( os.path.join(prefix, "000-default.conf"), os.path.join(aug_pre, "000-default.conf/VirtualHost"), set([obj.Addr.fromstring("*:80")]), False, True, "ip-172-30-0-17"), obj.VirtualHost( os.path.join(prefix, "letsencrypt.conf"), os.path.join(aug_pre, "letsencrypt.conf/VirtualHost"), set([obj.Addr.fromstring("*:80")]), False, True, "letsencrypt.demo"), obj.VirtualHost( os.path.join(prefix, "mod_macro-example.conf"), os.path.join(aug_pre, "mod_macro-example.conf/Macro/VirtualHost"), set([obj.Addr.fromstring("*:80")]), False, True, modmacro=True), obj.VirtualHost( os.path.join(prefix, "default-ssl-port-only.conf"), os.path.join(aug_pre, ("default-ssl-port-only.conf/" "IfModule/VirtualHost")), set([obj.Addr.fromstring("_default_:443")]), True, False), obj.VirtualHost( os.path.join(prefix, "wildcard.conf"), os.path.join(aug_pre, "wildcard.conf/VirtualHost"), set([obj.Addr.fromstring("*:80")]), False, False, "ip-172-30-0-17", aliases=["*.blue.purple.com"]) ] return vh_truth return None # pragma: no cover letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/0000755000175000017500000000000012665157735023554 5ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/complex_parsing/0000755000175000017500000000000012665157735026746 5ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/complex_parsing/test_variables.conf0000644000175000017500000000232212665157707032622 0ustar bmwbmw00000000000000TestVariablePort ${tls_port} TestVariablePortStr "${tls_port_str}" LoadModule status_module modules/mod_status.so # Basic IfDefine VAR_DIRECTIVE success LoadModule ssl_module modules/mod_ssl.so INVALID_VAR_DIRECTIVE failure INVALID_VAR_DIRECTIVE failure VAR_DIRECTIVE failure # Basic IfModule MOD_DIRECTIVE Success INVALID_MOD_DIRECTIVE failure INVALID_MOD_DIRECTIVE failure MOD_DIRECTIVE Success # Nested Tests NESTED_DIRECTIVE success NESTED_DIRECTIVE success INVALID_NESTED_DIRECTIVE failure INVALID_NESTED_DIRECTIVE failure INVALID_NESTED_DIRECTIVE failure NESTED_DIRECTIVE success letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/complex_parsing/test_fnmatch.conf0000644000175000017500000000003212665157707032266 0ustar bmwbmw00000000000000FNMATCH_DIRECTIVE Success letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/complex_parsing/conf-enabled/0000755000175000017500000000000012665157735031263 5ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/complex_parsing/conf-enabled/dummy.conf0000644000175000017500000000041312665157707033262 0ustar bmwbmw00000000000000# 3 - one arg directives # 2 - two arg directives # 1 - three arg directives TestArgsDirective one_arg TestArgsDirective one_arg two_arg TestArgsDirective one_arg TestArgsDirective one_arg two_arg TestArgsDirective one_arg two_arg three_arg TestArgsDirective one_arg letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/complex_parsing/apache2.conf0000644000175000017500000000206612665157707031123 0ustar bmwbmw00000000000000# Global configuration PidFile ${APACHE_PID_FILE} # # Timeout: The number of seconds before receives and sends time out. # Timeout 300 # # KeepAlive: Whether or not to allow persistent connections (more than # one request per connection). Set to "Off" to deactivate. # KeepAlive On # These need to be set in /etc/apache2/envvars User ${APACHE_RUN_USER} Group ${APACHE_RUN_GROUP} ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn # Include module configuration: IncludeOptional mods-enabled/*.load IncludeOptional mods-enabled/*.conf Options FollowSymLinks AllowOverride None Require all denied Options Indexes FollowSymLinks AllowOverride None Require all granted # Include generic snippets of statements IncludeOptional conf-enabled/ # Include the virtual host configurations: IncludeOptional sites-enabled/*.conf Define COMPLEX Define tls_port 1234 Define tls_port_str "1234" Define fnmatch_filename test_fnmatch.conf Include test_variables.conf # vim: syntax=apache ts=4 sw=4 sts=4 sr noet letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/0000755000175000017500000000000012665157735026743 5ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/0000755000175000017500000000000012665157735031612 5ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/0000755000175000017500000000000012665157735033115 5ustar bmwbmw00000000000000././@LongLink0000000000000000000000000000016400000000000011216 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/sites-available/letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/s0000755000175000017500000000000012665157735033300 5ustar bmwbmw00000000000000././@LongLink0000000000000000000000000000020400000000000011211 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/sites-available/default-ssl.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/s0000644000175000017500000000217412665157707033305 0ustar bmwbmw00000000000000 ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # SSL Engine Switch: # Enable/Disable SSL for this virtual host. SSLEngine on # A self-signed (snakeoil) certificate can be created by installing # the ssl-cert package. See # /usr/share/doc/apache2/README.Debian.gz for more info. # If both key and certificate are stored in the same file, only the # SSLCertificateFile directive is needed. SSLCertificateFile /etc/apache2/certs/letsencrypt-cert_5.pem SSLCertificateKeyFile /etc/apache2/ssl/key-letsencrypt_15.pem SSLOptions +StdEnvVars SSLOptions +StdEnvVars BrowserMatch "MSIE [2-6]" \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0 # MSIE 7 and newer should be able to use keepalive BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000020400000000000011211 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/sites-available/000-default.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/s0000644000175000017500000000045512665157707033305 0ustar bmwbmw00000000000000 # How well does Let's Encrypt work without a ServerName/Alias? ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000016200000000000011214 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/sites-enabled/letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/s0000755000175000017500000000000012665157735033300 5ustar bmwbmw00000000000000././@LongLink0000000000000000000000000000020200000000000011207 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/sites-enabled/000-default.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/s0000777000175000017500000000000012665157707041346 2../sites-available/000-default.confustar bmwbmw00000000000000././@LongLink0000000000000000000000000000016300000000000011215 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/conf-available/letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/c0000755000175000017500000000000012665157735033260 5ustar bmwbmw00000000000000././@LongLink0000000000000000000000000000020500000000000011212 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/conf-available/serve-cgi-bin.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/c0000644000175000017500000000070712665157707033265 0ustar bmwbmw00000000000000 Define ENABLE_USR_LIB_CGI_BIN Define ENABLE_USR_LIB_CGI_BIN ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Require all granted # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000020000000000000011205 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/conf-available/security.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/c0000644000175000017500000000176612665157707033273 0ustar bmwbmw00000000000000# ServerTokens # This directive configures what you return as the Server HTTP response # Header. The default is 'Full' which sends information about the OS-Type # and compiled in modules. # Set to one of: Full | OS | Minimal | Minor | Major | Prod # where Full conveys the most information, and Prod the least. #ServerTokens Minimal ServerTokens OS #ServerTokens Full # # Optionally add a line containing the server version and virtual host # name to server-generated pages (internal error documents, FTP directory # listings, mod_status and mod_info output etc., but not CGI generated # documents or custom error documents). # Set to "EMail" to also include a mailto: link to the ServerAdmin. # Set to one of: On | Off | EMail #ServerSignature Off ServerSignature On # # Allow TRACE method # # Set to "extended" to also reflect the request body (only for testing and # diagnostic purposes). # # Set to one of: On | Off | extended TraceEnable Off #TraceEnable On # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000021700000000000011215 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/conf-available/other-vhosts-access-log.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/c0000644000175000017500000000027512665157707033265 0ustar bmwbmw00000000000000# Define an access log for VirtualHosts that don't define their own logfile CustomLog ${APACHE_LOG_DIR}/other_vhosts_access.log vhost_combined # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000016100000000000011213 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/conf-enabled/letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/c0000755000175000017500000000000012665157735033260 5ustar bmwbmw00000000000000././@LongLink0000000000000000000000000000020300000000000011210 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/conf-enabled/serve-cgi-bin.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/c0000777000175000017500000000000012665157707041635 2../conf-available/serve-cgi-bin.confustar bmwbmw00000000000000././@LongLink0000000000000000000000000000017600000000000011221 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/conf-enabled/security.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/c0000777000175000017500000000000012665157707041052 2../conf-available/security.confustar bmwbmw00000000000000././@LongLink0000000000000000000000000000021500000000000011213 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/conf-enabled/other-vhosts-access-log.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/c0000777000175000017500000000000012665157707043666 2../conf-available/other-vhosts-access-log.confustar bmwbmw00000000000000././@LongLink0000000000000000000000000000016300000000000011215 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/mods-available/letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/m0000755000175000017500000000000012665157735033272 5ustar bmwbmw00000000000000././@LongLink0000000000000000000000000000017300000000000011216 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/mods-available/ssl.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/m0000644000175000017500000000651412665157707033301 0ustar bmwbmw00000000000000 # Pseudo Random Number Generator (PRNG): # Configure one or more sources to seed the PRNG of the SSL library. # The seed data should be of good random quality. # WARNING! On some platforms /dev/random blocks if not enough entropy # is available. This means you then cannot use the /dev/random device # because it would lead to very long connection times (as long as # it requires to make more entropy available). But usually those # platforms additionally provide a /dev/urandom device which doesn't # block. So, if available, use this one instead. Read the mod_ssl User # Manual for more details. # SSLRandomSeed startup builtin SSLRandomSeed startup file:/dev/urandom 512 SSLRandomSeed connect builtin SSLRandomSeed connect file:/dev/urandom 512 ## ## SSL Global Context ## ## All SSL configuration in this context applies both to ## the main server and all SSL-enabled virtual hosts. ## # # Some MIME-types for downloading Certificates and CRLs # AddType application/x-x509-ca-cert .crt AddType application/x-pkcs7-crl .crl # Pass Phrase Dialog: # Configure the pass phrase gathering process. # The filtering dialog program (`builtin' is a internal # terminal dialog) has to provide the pass phrase on stdout. SSLPassPhraseDialog exec:/usr/share/apache2/ask-for-passphrase # Inter-Process Session Cache: # Configure the SSL Session Cache: First the mechanism # to use and second the expiring timeout (in seconds). # (The mechanism dbm has known memory leaks and should not be used). #SSLSessionCache dbm:${APACHE_RUN_DIR}/ssl_scache SSLSessionCache shmcb:${APACHE_RUN_DIR}/ssl_scache(512000) SSLSessionCacheTimeout 300 # Semaphore: # Configure the path to the mutual exclusion semaphore the # SSL engine uses internally for inter-process synchronization. # (Disabled by default, the global Mutex directive consolidates by default # this) #Mutex file:${APACHE_LOCK_DIR}/ssl_mutex ssl-cache # SSL Cipher Suite: # List the ciphers that the client is permitted to negotiate. See the # ciphers(1) man page from the openssl package for list of all available # options. # Enable only secure ciphers: SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5 # Speed-optimized SSL Cipher configuration: # If speed is your main concern (on busy HTTPS servers e.g.), # you might want to force clients to specific, performance # optimized ciphers. In this case, prepend those ciphers # to the SSLCipherSuite list, and enable SSLHonorCipherOrder. # Caveat: by giving precedence to RC4-SHA and AES128-SHA # (as in the example below), most connections will no longer # have perfect forward secrecy - if the server's key is # compromised, captures of past or future traffic must be # considered compromised, too. #SSLCipherSuite RC4-SHA:AES128-SHA:HIGH:MEDIUM:!aNULL:!MD5 #SSLHonorCipherOrder on # The protocols to enable. # Available values: all, SSLv3, TLSv1, TLSv1.1, TLSv1.2 # SSL v2 is no longer supported SSLProtocol all # Allow insecure renegotiation with clients which do not yet support the # secure renegotiation protocol. Default: Off #SSLInsecureRenegotiation on # Whether to forbid non-SNI clients to access name based virtual hosts. # Default: Off #SSLStrictSNIVHostCheck On # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000017300000000000011216 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/mods-available/ssl.loadletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/m0000644000175000017500000000014112665157707033267 0ustar bmwbmw00000000000000# Depends: setenvif mime socache_shmcb LoadModule ssl_module /usr/lib/apache2/modules/mod_ssl.so ././@LongLink0000000000000000000000000000015300000000000011214 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/envvarsletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/e0000644000175000017500000000172512665157707033270 0ustar bmwbmw00000000000000# envvars - default environment variables for apache2ctl # this won't be correct after changing uid unset HOME # for supporting multiple apache2 instances if [ "${APACHE_CONFDIR##/etc/apache2-}" != "${APACHE_CONFDIR}" ] ; then SUFFIX="-${APACHE_CONFDIR##/etc/apache2-}" else SUFFIX= fi # Since there is no sane way to get the parsed apache2 config in scripts, some # settings are defined via environment variables and then used in apache2ctl, # /etc/init.d/apache2, /etc/logrotate.d/apache2, etc. export APACHE_RUN_USER=www-data export APACHE_RUN_GROUP=www-data # temporary state file location. This might be changed to /run in Wheezy+1 export APACHE_PID_FILE=/var/run/apache2/apache2$SUFFIX.pid export APACHE_RUN_DIR=/var/run/apache2$SUFFIX export APACHE_LOCK_DIR=/var/lock/apache2$SUFFIX # Only /var/log/apache2 is handled by /etc/logrotate.d/apache2. export APACHE_LOG_DIR=/var/log/apache2$SUFFIX ## The locale used by some modules like mod_dav export LANG=C export LANG ././@LongLink0000000000000000000000000000016000000000000011212 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/apache2.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/a0000644000175000017500000001461012665157707033261 0ustar bmwbmw00000000000000# This is the main Apache server configuration file. It contains the # configuration directives that give the server its instructions. # See http://httpd.apache.org/docs/2.4/ for detailed information about # the directives and /usr/share/doc/apache2/README.Debian about Debian specific # hints. # # # Summary of how the Apache 2 configuration works in Debian: # The Apache 2 web server configuration in Debian is quite different to # upstream's suggested way to configure the web server. This is because Debian's # default Apache2 installation attempts to make adding and removing modules, # virtual hosts, and extra configuration directives as flexible as possible, in # order to make automating the changes and administering the server as easy as # possible. # It is split into several files forming the configuration hierarchy outlined # below, all located in the /etc/apache2/ directory: # # /etc/apache2/ # |-- apache2.conf # | `-- ports.conf # |-- mods-enabled # | |-- *.load # | `-- *.conf # |-- conf-enabled # | `-- *.conf # `-- sites-enabled # `-- *.conf # # # * apache2.conf is the main configuration file (this file). It puts the pieces # together by including all remaining configuration files when starting up the # web server. # # * ports.conf is always included from the main configuration file. It is # supposed to determine listening ports for incoming connections which can be # customized anytime. # # * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/ # directories contain particular configuration snippets which manage modules, # global configuration fragments, or virtual host configurations, # respectively. # # They are activated by symlinking available configuration files from their # respective *-available/ counterparts. These should be managed by using our # helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See # their respective man pages for detailed information. # # * The binary is called apache2. Due to the use of environment variables, in # the default configuration, apache2 needs to be started/stopped with # /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not # work with the default configuration. # Global configuration # # The accept serialization lock file MUST BE STORED ON A LOCAL DISK. # Mutex file:${APACHE_LOCK_DIR} default # # PidFile: The file in which the server should record its process # identification number when it starts. # This needs to be set in /etc/apache2/envvars # PidFile ${APACHE_PID_FILE} # # Timeout: The number of seconds before receives and sends time out. # Timeout 300 # # KeepAlive: Whether or not to allow persistent connections (more than # one request per connection). Set to "Off" to deactivate. # KeepAlive On # # MaxKeepAliveRequests: The maximum number of requests to allow # during a persistent connection. Set to 0 to allow an unlimited amount. # We recommend you leave this number high, for maximum performance. # MaxKeepAliveRequests 100 # # KeepAliveTimeout: Number of seconds to wait for the next request from the # same client on the same connection. # KeepAliveTimeout 5 # These need to be set in /etc/apache2/envvars User ${APACHE_RUN_USER} Group ${APACHE_RUN_GROUP} # # HostnameLookups: Log the names of clients or just their IP addresses # e.g., www.apache.org (on) or 204.62.129.132 (off). # The default is off because it'd be overall better for the net if people # had to knowingly turn this feature on, since enabling it means that # each client request will result in AT LEAST one lookup request to the # nameserver. # HostnameLookups Off # ErrorLog: The location of the error log file. # If you do not specify an ErrorLog directive within a # container, error messages relating to that virtual host will be # logged here. If you *do* define an error logfile for a # container, that host's errors will be logged there and not here. # ErrorLog ${APACHE_LOG_DIR}/error.log # # LogLevel: Control the severity of messages logged to the error_log. # Available values: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the log level for particular modules, e.g. # "LogLevel info ssl:warn" # LogLevel warn # Include module configuration: IncludeOptional mods-enabled/*.load IncludeOptional mods-enabled/*.conf # Include list of ports to listen on Include ports.conf # Sets the default security model of the Apache2 HTTPD server. It does # not allow access to the root filesystem outside of /usr/share and /var/www. # The former is used by web applications packaged in Debian, # the latter may be used for local directories served by the web server. If # your system is serving content from a sub-directory in /srv you must allow # access here, or in any related virtual host. Options FollowSymLinks AllowOverride None Require all denied AllowOverride None Require all granted Options Indexes FollowSymLinks AllowOverride None Require all granted # AccessFileName: The name of the file to look for in each directory # for additional configuration directives. See also the AllowOverride # directive. # AccessFileName .htaccess # # The following lines prevent .htaccess and .htpasswd files from being # viewed by Web clients. # Require all denied # # The following directives define some format nicknames for use with # a CustomLog directive. # # These deviate from the Common Log Format definitions in that they use %O # (the actual bytes sent including headers) instead of %b (the size of the # requested file), because the latter makes it impossible to detect partial # requests. # # Note that the use of %{X-Forwarded-For}i instead of %h is not recommended. # Use mod_remoteip instead. # LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %O" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent # Include of directories ignores editors' and dpkg's backup files, # see README.Debian for details. # Include generic snippets of statements IncludeOptional conf-enabled/*.conf # Include the virtual host configurations: IncludeOptional sites-enabled/*.conf # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000015600000000000011217 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/ports.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/apache2/p0000644000175000017500000000061512665157707033300 0ustar bmwbmw00000000000000# If you just change the port or add more ports here, you will likely also # have to change the VirtualHost statement in # /etc/apache2/sites-enabled/000-default.conf Listen 80 NameVirtualHost *:80 Listen 443 Listen 443 # vim: syntax=apache ts=4 sw=4 sts=4 sr noet NameVirtualHost *:443 letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/default_vhost/sites0000644000175000017500000000005712665157707032665 0ustar bmwbmw00000000000000sites-available/000-default.conf, default.com letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/0000755000175000017500000000000012665157735031306 5ustar bmwbmw00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/0000755000175000017500000000000012665157735032611 5ustar bmwbmw00000000000000././@LongLink0000000000000000000000000000016300000000000011215 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-available/letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/si0000755000175000017500000000000012665157735033145 5ustar bmwbmw00000000000000././@LongLink0000000000000000000000000000020300000000000011210 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-available/letsencrypt.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/si0000644000175000017500000000163012665157707033146 0ustar bmwbmw00000000000000 ServerName letsencrypt.demo ServerAdmin webmaster@localhost DocumentRoot /var/www-letsencrypt-reworld/static/ Options FollowSymLinks AllowOverride None Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all ErrorLog ${APACHE_LOG_DIR}/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /doc/ "/usr/share/doc/" Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 ././@LongLink0000000000000000000000000000020000000000000011205 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-available/wildcard.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/si0000644000175000017500000000044112665157707033145 0ustar bmwbmw00000000000000 ServerName ip-172-30-0-17 ServerAdmin webmaster@localhost DocumentRoot /var/www/html ServerAlias *.blue.purple.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000021500000000000011213 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-available/default-ssl-port-only.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/si0000644000175000017500000000214012665157707033143 0ustar bmwbmw00000000000000 ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # A self-signed (snakeoil) certificate can be created by installing # the ssl-cert package. See # /usr/share/doc/apache2/README.Debian.gz for more info. # If both key and certificate are stored in the same file, only the # SSLCertificateFile directive is needed. SSLCertificateFile /etc/apache2/certs/letsencrypt-cert_5.pem SSLCertificateKeyFile /etc/apache2/ssl/key-letsencrypt_15.pem #SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire SSLOptions +StdEnvVars SSLOptions +StdEnvVars BrowserMatch "MSIE [2-6]" \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0 # MSIE 7 and newer should be able to use keepalive BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000020300000000000011210 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-available/default-ssl.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/si0000644000175000017500000000227112665157707033150 0ustar bmwbmw00000000000000 ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # SSL Engine Switch: # Enable/Disable SSL for this virtual host. SSLEngine on # A self-signed (snakeoil) certificate can be created by installing # the ssl-cert package. See # /usr/share/doc/apache2/README.Debian.gz for more info. # If both key and certificate are stored in the same file, only the # SSLCertificateFile directive is needed. SSLCertificateFile /etc/apache2/certs/letsencrypt-cert_5.pem SSLCertificateKeyFile /etc/apache2/ssl/key-letsencrypt_15.pem #SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire SSLOptions +StdEnvVars SSLOptions +StdEnvVars BrowserMatch "MSIE [2-6]" \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0 # MSIE 7 and newer should be able to use keepalive BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000020300000000000011210 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-available/000-default.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/si0000644000175000017500000000040212665157707033142 0ustar bmwbmw00000000000000 ServerName ip-172-30-0-17 ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000021200000000000011210 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-available/encryption-example.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/si0000644000175000017500000000220512665157707033145 0ustar bmwbmw00000000000000 ServerName encryption-example.demo ServerAdmin webmaster@localhost DocumentRoot /var/www-encryption-example/static/ Options FollowSymLinks AllowOverride None Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all ErrorLog ${APACHE_LOG_DIR}/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /doc/ "/usr/share/doc/" Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 ././@LongLink0000000000000000000000000000021100000000000011207 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-available/mod_macro-example.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/si0000644000175000017500000000057112665157707033151 0ustar bmwbmw00000000000000 ServerName $domain ServerAlias www.$domain DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Use VHost macro1 test.com Use VHost macro2 hostname.org Use VHost macro3 apache.org # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000016100000000000011213 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-enabled/letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/si0000755000175000017500000000000012665157735033145 5ustar bmwbmw00000000000000././@LongLink0000000000000000000000000000020100000000000011206 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-enabled/letsencrypt.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/si0000777000175000017500000000000012665157707041646 2../sites-available/letsencrypt.confustar bmwbmw00000000000000././@LongLink0000000000000000000000000000020100000000000011206 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-enabled/000-default.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/si0000777000175000017500000000000012665157707041213 2../sites-available/000-default.confustar bmwbmw00000000000000././@LongLink0000000000000000000000000000021000000000000011206 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-enabled/encryption-example.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/si0000777000175000017500000000000012665157707043115 2../sites-available/encryption-example.confustar bmwbmw00000000000000././@LongLink0000000000000000000000000000020700000000000011214 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/sites-enabled/mod_macro-example.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/si0000777000175000017500000000000012665157707042663 2../sites-available/mod_macro-example.confustar bmwbmw00000000000000././@LongLink0000000000000000000000000000016000000000000011212 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-enabled/letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mo0000755000175000017500000000000012665157735033145 5ustar bmwbmw00000000000000././@LongLink0000000000000000000000000000017600000000000011221 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-enabled/authz_svn.loadletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mo0000777000175000017500000000000012665157707041120 2../mods-available/authz_svn.loadustar bmwbmw00000000000000././@LongLink0000000000000000000000000000017200000000000011215 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-enabled/.gitignoreletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mo0000644000175000017500000000000012665157707033134 0ustar bmwbmw00000000000000././@LongLink0000000000000000000000000000017400000000000011217 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-enabled/dav_svn.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mo0000777000175000017500000000000012665157707040545 2../mods-available/dav_svn.confustar bmwbmw00000000000000././@LongLink0000000000000000000000000000017400000000000011217 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-enabled/dav_svn.loadletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mo0000777000175000017500000000000012665157707040537 2../mods-available/dav_svn.loadustar bmwbmw00000000000000././@LongLink0000000000000000000000000000017000000000000011213 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-enabled/dav.loadletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mo0000777000175000017500000000000012665157707037651 2../mods-available/dav.loadustar bmwbmw00000000000000././@LongLink0000000000000000000000000000016200000000000011214 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/conf-available/letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/co0000755000175000017500000000000012665157735033133 5ustar bmwbmw00000000000000././@LongLink0000000000000000000000000000020400000000000011211 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/conf-available/serve-cgi-bin.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/co0000644000175000017500000000070712665157707033140 0ustar bmwbmw00000000000000 Define ENABLE_USR_LIB_CGI_BIN Define ENABLE_USR_LIB_CGI_BIN ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Require all granted # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000017700000000000011222 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/conf-available/security.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/co0000644000175000017500000000221512665157707033134 0ustar bmwbmw00000000000000# Changing the following options will not really affect the security of the # server, but might make attacks slightly more difficult in some cases. # # ServerTokens # This directive configures what you return as the Server HTTP response # Header. The default is 'Full' which sends information about the OS-Type # and compiled in modules. # Set to one of: Full | OS | Minimal | Minor | Major | Prod # where Full conveys the most information, and Prod the least. #ServerTokens Minimal ServerTokens OS #ServerTokens Full # # Optionally add a line containing the server version and virtual host # name to server-generated pages (internal error documents, FTP directory # listings, mod_status and mod_info output etc., but not CGI generated # documents or custom error documents). # Set to "EMail" to also include a mailto: link to the ServerAdmin. # Set to one of: On | Off | EMail #ServerSignature Off ServerSignature On # # Allow TRACE method # # Set to "extended" to also reflect the request body (only for testing and # diagnostic purposes). # # Set to one of: On | Off | extended TraceEnable Off #TraceEnable On # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000021600000000000011214 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/conf-available/other-vhosts-access-log.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/co0000644000175000017500000000027512665157707033140 0ustar bmwbmw00000000000000# Define an access log for VirtualHosts that don't define their own logfile CustomLog ${APACHE_LOG_DIR}/other_vhosts_access.log vhost_combined # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000020400000000000011211 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/conf-available/bad_conf_file.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/co0000644000175000017500000000005612665157707033135 0ustar bmwbmw00000000000000 ServerName invalid.net ././@LongLink0000000000000000000000000000016000000000000011212 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/conf-enabled/letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/co0000755000175000017500000000000012665157735033133 5ustar bmwbmw00000000000000././@LongLink0000000000000000000000000000020200000000000011207 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/conf-enabled/serve-cgi-bin.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/co0000777000175000017500000000000012665157707041510 2../conf-available/serve-cgi-bin.confustar bmwbmw00000000000000././@LongLink0000000000000000000000000000017500000000000011220 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/conf-enabled/security.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/co0000777000175000017500000000000012665157707040725 2../conf-available/security.confustar bmwbmw00000000000000././@LongLink0000000000000000000000000000021400000000000011212 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/conf-enabled/other-vhosts-access-log.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/co0000777000175000017500000000000012665157707043541 2../conf-available/other-vhosts-access-log.confustar bmwbmw00000000000000././@LongLink0000000000000000000000000000016200000000000011214 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-available/letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mo0000755000175000017500000000000012665157735033145 5ustar bmwbmw00000000000000././@LongLink0000000000000000000000000000020000000000000011205 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-available/authz_svn.loadletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mo0000644000175000017500000000024512665157707033147 0ustar bmwbmw00000000000000# Depends: dav_svn Include mods-enabled/dav_svn.load LoadModule authz_svn_module /usr/lib/apache2/modules/mod_authz_svn.so ././@LongLink0000000000000000000000000000017600000000000011221 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-available/dav_svn.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mo0000644000175000017500000000450412665157707033151 0ustar bmwbmw00000000000000# dav_svn.conf - Example Subversion/Apache configuration # # For details and further options see the Apache user manual and # the Subversion book. # # NOTE: for a setup with multiple vhosts, you will want to do this # configuration in /etc/apache2/sites-available/*, not here. # ... # URL controls how the repository appears to the outside world. # In this example clients access the repository as http://hostname/svn/ # Note, a literal /svn should NOT exist in your document root. # # Uncomment this to enable the repository #DAV svn # Set this to the path to your repository #SVNPath /var/lib/svn # Alternatively, use SVNParentPath if you have multiple repositories under # under a single directory (/var/lib/svn/repo1, /var/lib/svn/repo2, ...). # You need either SVNPath and SVNParentPath, but not both. #SVNParentPath /var/lib/svn # Access control is done at 3 levels: (1) Apache authentication, via # any of several methods. A "Basic Auth" section is commented out # below. (2) Apache and , also commented out # below. (3) mod_authz_svn is a svn-specific authorization module # which offers fine-grained read/write access control for paths # within a repository. (The first two layers are coarse-grained; you # can only enable/disable access to an entire repository.) Note that # mod_authz_svn is noticeably slower than the other two layers, so if # you don't need the fine-grained control, don't configure it. # Basic Authentication is repository-wide. It is not secure unless # you are using https. See the 'htpasswd' command to create and # manage the password file - and the documentation for the # 'auth_basic' and 'authn_file' modules, which you will need for this # (enable them with 'a2enmod'). #AuthType Basic #AuthName "Subversion Repository" #AuthUserFile /etc/apache2/dav_svn.passwd # To enable authorization via mod_authz_svn (enable that module separately): # #AuthzSVNAccessFile /etc/apache2/dav_svn.authz # # The following three lines allow anonymous read, but make # committers authenticate themselves. It requires the 'authz_user' # module (enable it with 'a2enmod'). # #Require valid-user # # ././@LongLink0000000000000000000000000000017600000000000011221 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-available/rewrite.loadletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mo0000644000175000017500000000010212665157707033137 0ustar bmwbmw00000000000000LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so ././@LongLink0000000000000000000000000000017600000000000011221 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-available/dav_svn.loadletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mo0000644000175000017500000000031312665157707033143 0ustar bmwbmw00000000000000# Depends: dav Include mods-enabled/dav.load LoadModule dav_svn_module /usr/lib/apache2/modules/mod_dav_svn.so ././@LongLink0000000000000000000000000000017200000000000011215 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-available/ssl.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mo0000644000175000017500000000651412665157707033154 0ustar bmwbmw00000000000000 # Pseudo Random Number Generator (PRNG): # Configure one or more sources to seed the PRNG of the SSL library. # The seed data should be of good random quality. # WARNING! On some platforms /dev/random blocks if not enough entropy # is available. This means you then cannot use the /dev/random device # because it would lead to very long connection times (as long as # it requires to make more entropy available). But usually those # platforms additionally provide a /dev/urandom device which doesn't # block. So, if available, use this one instead. Read the mod_ssl User # Manual for more details. # SSLRandomSeed startup builtin SSLRandomSeed startup file:/dev/urandom 512 SSLRandomSeed connect builtin SSLRandomSeed connect file:/dev/urandom 512 ## ## SSL Global Context ## ## All SSL configuration in this context applies both to ## the main server and all SSL-enabled virtual hosts. ## # # Some MIME-types for downloading Certificates and CRLs # AddType application/x-x509-ca-cert .crt AddType application/x-pkcs7-crl .crl # Pass Phrase Dialog: # Configure the pass phrase gathering process. # The filtering dialog program (`builtin' is a internal # terminal dialog) has to provide the pass phrase on stdout. SSLPassPhraseDialog exec:/usr/share/apache2/ask-for-passphrase # Inter-Process Session Cache: # Configure the SSL Session Cache: First the mechanism # to use and second the expiring timeout (in seconds). # (The mechanism dbm has known memory leaks and should not be used). #SSLSessionCache dbm:${APACHE_RUN_DIR}/ssl_scache SSLSessionCache shmcb:${APACHE_RUN_DIR}/ssl_scache(512000) SSLSessionCacheTimeout 300 # Semaphore: # Configure the path to the mutual exclusion semaphore the # SSL engine uses internally for inter-process synchronization. # (Disabled by default, the global Mutex directive consolidates by default # this) #Mutex file:${APACHE_LOCK_DIR}/ssl_mutex ssl-cache # SSL Cipher Suite: # List the ciphers that the client is permitted to negotiate. See the # ciphers(1) man page from the openssl package for list of all available # options. # Enable only secure ciphers: SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5 # Speed-optimized SSL Cipher configuration: # If speed is your main concern (on busy HTTPS servers e.g.), # you might want to force clients to specific, performance # optimized ciphers. In this case, prepend those ciphers # to the SSLCipherSuite list, and enable SSLHonorCipherOrder. # Caveat: by giving precedence to RC4-SHA and AES128-SHA # (as in the example below), most connections will no longer # have perfect forward secrecy - if the server's key is # compromised, captures of past or future traffic must be # considered compromised, too. #SSLCipherSuite RC4-SHA:AES128-SHA:HIGH:MEDIUM:!aNULL:!MD5 #SSLHonorCipherOrder on # The protocols to enable. # Available values: all, SSLv3, TLSv1, TLSv1.1, TLSv1.2 # SSL v2 is no longer supported SSLProtocol all # Allow insecure renegotiation with clients which do not yet support the # secure renegotiation protocol. Default: Off #SSLInsecureRenegotiation on # Whether to forbid non-SNI clients to access name based virtual hosts. # Default: Off #SSLStrictSNIVHostCheck On # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000017200000000000011215 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-available/dav.loadletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mo0000644000175000017500000000013512665157707033145 0ustar bmwbmw00000000000000 LoadModule dav_module /usr/lib/apache2/modules/mod_dav.so ././@LongLink0000000000000000000000000000017200000000000011215 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mods-available/ssl.loadletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/mo0000644000175000017500000000014112665157707033142 0ustar bmwbmw00000000000000# Depends: setenvif mime socache_shmcb LoadModule ssl_module /usr/lib/apache2/modules/mod_ssl.so ././@LongLink0000000000000000000000000000015200000000000011213 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/envvarsletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/en0000644000175000017500000000172612665157707033143 0ustar bmwbmw00000000000000# envvars - default environment variables for apache2ctl # this won't be correct after changing uid unset HOME # for supporting multiple apache2 instances if [ "${APACHE_CONFDIR##/etc/apache2-}" != "${APACHE_CONFDIR}" ] ; then SUFFIX="-${APACHE_CONFDIR##/etc/apache2-}" else SUFFIX= fi # Since there is no sane way to get the parsed apache2 config in scripts, some # settings are defined via environment variables and then used in apache2ctl, # /etc/init.d/apache2, /etc/logrotate.d/apache2, etc. export APACHE_RUN_USER=www-data export APACHE_RUN_GROUP=www-data # temporary state file location. This might be changed to /run in Wheezy+1 export APACHE_PID_FILE=/var/run/apache2/apache2$SUFFIX.pid export APACHE_RUN_DIR=/var/run/apache2$SUFFIX export APACHE_LOCK_DIR=/var/lock/apache2$SUFFIX # Only /var/log/apache2 is handled by /etc/logrotate.d/apache2. export APACHE_LOG_DIR=/var/log/apache2$SUFFIX ## The locale used by some modules like mod_dav export LANG=C export LANG ././@LongLink0000000000000000000000000000015700000000000011220 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/apache2.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/ap0000644000175000017500000001460512665157707033141 0ustar bmwbmw00000000000000# This is the main Apache server configuration file. It contains the # configuration directives that give the server its instructions. # See http://httpd.apache.org/docs/2.4/ for detailed information about # the directives and /usr/share/doc/apache2/README.Debian about Debian specific # hints. # # # Summary of how the Apache 2 configuration works in Debian: # The Apache 2 web server configuration in Debian is quite different to # upstream's suggested way to configure the web server. This is because Debian's # default Apache2 installation attempts to make adding and removing modules, # virtual hosts, and extra configuration directives as flexible as possible, in # order to make automating the changes and administering the server as easy as # possible. # It is split into several files forming the configuration hierarchy outlined # below, all located in the /etc/apache2/ directory: # # /etc/apache2/ # |-- apache2.conf # | `-- ports.conf # |-- mods-enabled # | |-- *.load # | `-- *.conf # |-- conf-enabled # | `-- *.conf # `-- sites-enabled # `-- *.conf # # # * apache2.conf is the main configuration file (this file). It puts the pieces # together by including all remaining configuration files when starting up the # web server. # # * ports.conf is always included from the main configuration file. It is # supposed to determine listening ports for incoming connections which can be # customized anytime. # # * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/ # directories contain particular configuration snippets which manage modules, # global configuration fragments, or virtual host configurations, # respectively. # # They are activated by symlinking available configuration files from their # respective *-available/ counterparts. These should be managed by using our # helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See # their respective man pages for detailed information. # # * The binary is called apache2. Due to the use of environment variables, in # the default configuration, apache2 needs to be started/stopped with # /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not # work with the default configuration. # Global configuration # # The accept serialization lock file MUST BE STORED ON A LOCAL DISK. # Mutex file:${APACHE_LOCK_DIR} default # # PidFile: The file in which the server should record its process # identification number when it starts. # This needs to be set in /etc/apache2/envvars # PidFile ${APACHE_PID_FILE} # # Timeout: The number of seconds before receives and sends time out. # Timeout 300 # # KeepAlive: Whether or not to allow persistent connections (more than # one request per connection). Set to "Off" to deactivate. # KeepAlive On # # MaxKeepAliveRequests: The maximum number of requests to allow # during a persistent connection. Set to 0 to allow an unlimited amount. # We recommend you leave this number high, for maximum performance. # MaxKeepAliveRequests 100 # # KeepAliveTimeout: Number of seconds to wait for the next request from the # same client on the same connection. # KeepAliveTimeout 5 # These need to be set in /etc/apache2/envvars User ${APACHE_RUN_USER} Group ${APACHE_RUN_GROUP} # # HostnameLookups: Log the names of clients or just their IP addresses # e.g., www.apache.org (on) or 204.62.129.132 (off). # The default is off because it'd be overall better for the net if people # had to knowingly turn this feature on, since enabling it means that # each client request will result in AT LEAST one lookup request to the # nameserver. # HostnameLookups Off # ErrorLog: The location of the error log file. # If you do not specify an ErrorLog directive within a # container, error messages relating to that virtual host will be # logged here. If you *do* define an error logfile for a # container, that host's errors will be logged there and not here. # ErrorLog ${APACHE_LOG_DIR}/error.log # # LogLevel: Control the severity of messages logged to the error_log. # Available values: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the log level for particular modules, e.g. # "LogLevel info ssl:warn" # LogLevel warn # Include module configuration: IncludeOptional mods-enabled/*.load IncludeOptional mods-enabled/*.conf # Include list of ports to listen on Include ports.conf # Sets the default security model of the Apache2 HTTPD server. It does # not allow access to the root filesystem outside of /usr/share and /var/www. # The former is used by web applications packaged in Debian, # the latter may be used for local directories served by the web server. If # your system is serving content from a sub-directory in /srv you must allow # access here, or in any related virtual host. Options FollowSymLinks AllowOverride None Require all denied AllowOverride None Require all granted Options Indexes FollowSymLinks AllowOverride None Require all granted # AccessFileName: The name of the file to look for in each directory # for additional configuration directives. See also the AllowOverride # directive. # AccessFileName .htaccess # # The following lines prevent .htaccess and .htpasswd files from being # viewed by Web clients. # Require all denied # The following directives define some format nicknames for use with # a CustomLog directive. # # These deviate from the Common Log Format definitions in that they use %O # (the actual bytes sent including headers) instead of %b (the size of the # requested file), because the latter makes it impossible to detect partial # requests. # # Note that the use of %{X-Forwarded-For}i instead of %h is not recommended. # Use mod_remoteip instead. # LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %O" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent # Include of directories ignores editors' and dpkg's backup files, # see README.Debian for details. # Include generic snippets of statements IncludeOptional conf-enabled/*.conf # Include the virtual host configurations: IncludeOptional sites-enabled/*.conf # vim: syntax=apache ts=4 sw=4 sts=4 sr noet ././@LongLink0000000000000000000000000000015500000000000011216 Lustar 00000000000000letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/ports.confletsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/apache2/po0000644000175000017500000000050012665157707033144 0ustar bmwbmw00000000000000# If you just change the port or add more ports here, you will likely also # have to change the VirtualHost statement in # /etc/apache2/sites-enabled/000-default.conf Listen 80 Listen 443 Listen 443 # vim: syntax=apache ts=4 sw=4 sts=4 sr noet letsencrypt-apache-0.4.1/letsencrypt_apache/tests/testdata/debian_apache_2_4/two_vhost_80/sites0000644000175000017500000000016412665157707032360 0ustar bmwbmw00000000000000sites-available/letsencrypt.conf, letsencrypt.demo sites-available/encryption-example.conf, encryption-example.demo letsencrypt-apache-0.4.1/letsencrypt_apache/tests/display_ops_test.py0000644000175000017500000000552312665157707025706 0ustar bmwbmw00000000000000"""Test letsencrypt_apache.display_ops.""" import sys import unittest import mock import zope.component from letsencrypt.display import util as display_util from letsencrypt import errors from letsencrypt_apache import obj from letsencrypt_apache.tests import util class SelectVhostTest(unittest.TestCase): """Tests for letsencrypt_apache.display_ops.select_vhost.""" def setUp(self): zope.component.provideUtility(display_util.FileDisplay(sys.stdout)) self.base_dir = "/example_path" self.vhosts = util.get_vh_truth( self.base_dir, "debian_apache_2_4/two_vhost_80") @classmethod def _call(cls, vhosts): from letsencrypt_apache.display_ops import select_vhost return select_vhost("example.com", vhosts) @mock.patch("letsencrypt_apache.display_ops.zope.component.getUtility") def test_successful_choice(self, mock_util): mock_util().menu.return_value = (display_util.OK, 3) self.assertEqual(self.vhosts[3], self._call(self.vhosts)) @mock.patch("letsencrypt_apache.display_ops.zope.component.getUtility") def test_noninteractive(self, mock_util): mock_util().menu.side_effect = errors.MissingCommandlineFlag("no vhost default") try: self._call(self.vhosts) except errors.MissingCommandlineFlag as e: self.assertTrue("VirtualHost directives" in e.message) @mock.patch("letsencrypt_apache.display_ops.zope.component.getUtility") def test_more_info_cancel(self, mock_util): mock_util().menu.side_effect = [ (display_util.HELP, 1), (display_util.HELP, 0), (display_util.CANCEL, -1), ] self.assertEqual(None, self._call(self.vhosts)) self.assertEqual(mock_util().notification.call_count, 2) def test_no_vhosts(self): self.assertEqual(self._call([]), None) @mock.patch("letsencrypt_apache.display_ops.display_util") @mock.patch("letsencrypt_apache.display_ops.zope.component.getUtility") @mock.patch("letsencrypt_apache.display_ops.logger") def test_small_display(self, mock_logger, mock_util, mock_display_util): mock_display_util.WIDTH = 20 mock_util().menu.return_value = (display_util.OK, 0) self._call(self.vhosts) self.assertEqual(mock_logger.debug.call_count, 1) @mock.patch("letsencrypt_apache.display_ops.zope.component.getUtility") def test_multiple_names(self, mock_util): mock_util().menu.return_value = (display_util.OK, 5) self.vhosts.append( obj.VirtualHost( "path", "aug_path", set([obj.Addr.fromstring("*:80")]), False, False, "wildcard.com", set(["*.wildcard.com"]))) self.assertEqual(self.vhosts[5], self._call(self.vhosts)) if __name__ == "__main__": unittest.main() # pragma: no cover letsencrypt-apache-0.4.1/letsencrypt_apache/options-ssl-apache.conf0000644000175000017500000000255512665157707025167 0ustar bmwbmw00000000000000# Baseline setting to Include for SSL sites SSLEngine on # Intermediate configuration, tweak to your needs SSLProtocol all -SSLv2 -SSLv3 SSLCipherSuite ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA SSLHonorCipherOrder on SSLCompression off SSLOptions +StrictRequire # Add vhost name to log entries: LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" vhost_combined LogFormat "%v %h %l %u %t \"%r\" %>s %b" vhost_common #CustomLog /var/log/apache2/access.log vhost_combined #LogLevel warn #ErrorLog /var/log/apache2/error.log # Always ensure Cookies have "Secure" set (JAH 2012/1) #Header edit Set-Cookie (?i)^(.*)(;\s*secure)??((\s*;)?(.*)) "$1; Secure$3$4" letsencrypt-apache-0.4.1/letsencrypt_apache/constants.py0000644000175000017500000001003612665157707023166 0ustar bmwbmw00000000000000"""Apache plugin constants.""" import pkg_resources from letsencrypt import le_util CLI_DEFAULTS_DEBIAN = dict( server_root="/etc/apache2", vhost_root="/etc/apache2/sites-available", vhost_files="*", version_cmd=['apache2ctl', '-v'], define_cmd=['apache2ctl', '-t', '-D', 'DUMP_RUN_CFG'], restart_cmd=['apache2ctl', 'graceful'], conftest_cmd=['apache2ctl', 'configtest'], enmod="a2enmod", dismod="a2dismod", le_vhost_ext="-le-ssl.conf", handle_mods=True, handle_sites=True, challenge_location="/etc/apache2", MOD_SSL_CONF_SRC=pkg_resources.resource_filename( "letsencrypt_apache", "options-ssl-apache.conf") ) CLI_DEFAULTS_CENTOS = dict( server_root="/etc/httpd", vhost_root="/etc/httpd/conf.d", vhost_files="*.conf", version_cmd=['apachectl', '-v'], define_cmd=['apachectl', '-t', '-D', 'DUMP_RUN_CFG'], restart_cmd=['apachectl', 'graceful'], conftest_cmd=['apachectl', 'configtest'], enmod=None, dismod=None, le_vhost_ext="-le-ssl.conf", handle_mods=False, handle_sites=False, challenge_location="/etc/httpd/conf.d", MOD_SSL_CONF_SRC=pkg_resources.resource_filename( "letsencrypt_apache", "centos-options-ssl-apache.conf") ) CLI_DEFAULTS_GENTOO = dict( server_root="/etc/apache2", vhost_root="/etc/apache2/vhosts.d", vhost_files="*.conf", version_cmd=['/usr/sbin/apache2', '-v'], define_cmd=['/usr/sbin/apache2', '-t', '-D', 'DUMP_RUN_CFG'], restart_cmd=['apache2ctl', 'graceful'], conftest_cmd=['apache2ctl', 'configtest'], enmod=None, dismod=None, le_vhost_ext="-le-ssl.conf", handle_mods=False, handle_sites=False, challenge_location="/etc/apache2/vhosts.d", MOD_SSL_CONF_SRC=pkg_resources.resource_filename( "letsencrypt_apache", "options-ssl-apache.conf") ) CLI_DEFAULTS_DARWIN = dict( server_root="/etc/apache2", vhost_root="/etc/apache2/other", vhost_files="*.conf", version_cmd=['/usr/sbin/httpd', '-v'], define_cmd=['/usr/sbin/httpd', '-t', '-D', 'DUMP_RUN_CFG'], restart_cmd=['apachectl', 'graceful'], conftest_cmd=['apachectl', 'configtest'], enmod=None, dismod=None, le_vhost_ext="-le-ssl.conf", handle_mods=False, handle_sites=False, challenge_location="/etc/apache2/other", MOD_SSL_CONF_SRC=pkg_resources.resource_filename( "letsencrypt_apache", "options-ssl-apache.conf") ) CLI_DEFAULTS = { "debian": CLI_DEFAULTS_DEBIAN, "ubuntu": CLI_DEFAULTS_DEBIAN, "centos": CLI_DEFAULTS_CENTOS, "centos linux": CLI_DEFAULTS_CENTOS, "fedora": CLI_DEFAULTS_CENTOS, "red hat enterprise linux server": CLI_DEFAULTS_CENTOS, "gentoo base system": CLI_DEFAULTS_GENTOO, "darwin": CLI_DEFAULTS_DARWIN, } """CLI defaults.""" MOD_SSL_CONF_DEST = "options-ssl-apache.conf" """Name of the mod_ssl config file as saved in `IConfig.config_dir`.""" AUGEAS_LENS_DIR = pkg_resources.resource_filename( "letsencrypt_apache", "augeas_lens") """Path to the Augeas lens directory""" REWRITE_HTTPS_ARGS = [ "^", "https://%{SERVER_NAME}%{REQUEST_URI}", "[L,QSA,R=permanent]"] """Apache version<2.3.9 rewrite rule arguments used for redirections to https vhost""" REWRITE_HTTPS_ARGS_WITH_END = [ "^", "https://%{SERVER_NAME}%{REQUEST_URI}", "[END,QSA,R=permanent]"] """Apache version >= 2.3.9 rewrite rule arguments used for redirections to https vhost""" HSTS_ARGS = ["always", "set", "Strict-Transport-Security", "\"max-age=31536000\""] """Apache header arguments for HSTS""" UIR_ARGS = ["always", "set", "Content-Security-Policy", "upgrade-insecure-requests"] HEADER_ARGS = {"Strict-Transport-Security": HSTS_ARGS, "Upgrade-Insecure-Requests": UIR_ARGS} def os_constant(key): """Get a constant value for operating system :param key: name of cli constant :return: value of constant for active os """ os_info = le_util.get_os_info() try: constants = CLI_DEFAULTS[os_info[0].lower()] except KeyError: constants = CLI_DEFAULTS["debian"] return constants[key] letsencrypt-apache-0.4.1/letsencrypt_apache/obj.py0000644000175000017500000001737212665157707021736 0ustar bmwbmw00000000000000"""Module contains classes used by the Apache Configurator.""" import re from letsencrypt.plugins import common class Addr(common.Addr): """Represents an Apache address.""" def __eq__(self, other): """This is defined as equalivalent within Apache. ip_addr:* == ip_addr """ if isinstance(other, self.__class__): return ((self.tup == other.tup) or (self.tup[0] == other.tup[0] and self.is_wildcard() and other.is_wildcard())) return False def __ne__(self, other): return not self.__eq__(other) def _addr_less_specific(self, addr): """Returns if addr.get_addr() is more specific than self.get_addr().""" # pylint: disable=protected-access return addr._rank_specific_addr() > self._rank_specific_addr() def _rank_specific_addr(self): """Returns numerical rank for get_addr() :returns: 2 - FQ, 1 - wildcard, 0 - _default_ :rtype: int """ if self.get_addr() == "_default_": return 0 elif self.get_addr() == "*": return 1 else: return 2 def conflicts(self, addr): r"""Returns if address could conflict with correct function of self. Could addr take away service provided by self within Apache? .. note::IP Address is more important than wildcard. Connection from 127.0.0.1:80 with choices of *:80 and 127.0.0.1:* chooses 127.0.0.1:\* .. todo:: Handle domain name addrs... Examples: ========================================= ===== ``127.0.0.1:\*.conflicts(127.0.0.1:443)`` True ``127.0.0.1:443.conflicts(127.0.0.1:\*)`` False ``\*:443.conflicts(\*:80)`` False ``_default_:443.conflicts(\*:443)`` True ========================================= ===== """ if self._addr_less_specific(addr): return True elif self.get_addr() == addr.get_addr(): if self.is_wildcard() or self.get_port() == addr.get_port(): return True return False def is_wildcard(self): """Returns if address has a wildcard port.""" return self.tup[1] == "*" or not self.tup[1] def get_sni_addr(self, port): """Returns the least specific address that resolves on the port. Examples: - ``1.2.3.4:443`` -> ``1.2.3.4:`` - ``1.2.3.4:*`` -> ``1.2.3.4:*`` :param str port: Desired port """ if self.is_wildcard(): return self return self.get_addr_obj(port) class VirtualHost(object): # pylint: disable=too-few-public-methods """Represents an Apache Virtualhost. :ivar str filep: file path of VH :ivar str path: Augeas path to virtual host :ivar set addrs: Virtual Host addresses (:class:`set` of :class:`common.Addr`) :ivar str name: ServerName of VHost :ivar list aliases: Server aliases of vhost (:class:`list` of :class:`str`) :ivar bool ssl: SSLEngine on in vhost :ivar bool enabled: Virtual host is enabled :ivar bool modmacro: VirtualHost is using mod_macro https://httpd.apache.org/docs/2.4/vhosts/details.html .. todo:: Any vhost that includes the magic _default_ wildcard is given the same ServerName as the main server. """ # ?: is used for not returning enclosed characters strip_name = re.compile(r"^(?:.+://)?([^ :$]*)") def __init__(self, filep, path, addrs, ssl, enabled, name=None, aliases=None, modmacro=False): # pylint: disable=too-many-arguments """Initialize a VH.""" self.filep = filep self.path = path self.addrs = addrs self.name = name self.aliases = aliases if aliases is not None else set() self.ssl = ssl self.enabled = enabled self.modmacro = modmacro def get_names(self): """Return a set of all names.""" all_names = set() all_names.update(self.aliases) # Strip out any scheme:// and field from servername if self.name is not None: all_names.add(VirtualHost.strip_name.findall(self.name)[0]) return all_names def __str__(self): return ( "File: {filename}\n" "Vhost path: {vhpath}\n" "Addresses: {addrs}\n" "Name: {name}\n" "Aliases: {aliases}\n" "TLS Enabled: {tls}\n" "Site Enabled: {active}\n" "mod_macro Vhost: {modmacro}".format( filename=self.filep, vhpath=self.path, addrs=", ".join(str(addr) for addr in self.addrs), name=self.name if self.name is not None else "", aliases=", ".join(name for name in self.aliases), tls="Yes" if self.ssl else "No", active="Yes" if self.enabled else "No", modmacro="Yes" if self.modmacro else "No")) def __eq__(self, other): if isinstance(other, self.__class__): return (self.filep == other.filep and self.path == other.path and self.addrs == other.addrs and self.get_names() == other.get_names() and self.ssl == other.ssl and self.enabled == other.enabled and self.modmacro == other.modmacro) return False def __ne__(self, other): return not self.__eq__(other) def conflicts(self, addrs): """See if vhost conflicts with any of the addrs. This determines whether or not these addresses would/could overwrite the vhost addresses. :param addrs: Iterable Addresses :type addrs: Iterable :class:~obj.Addr :returns: If addresses conflicts with vhost :rtype: bool """ for pot_addr in addrs: for addr in self.addrs: if addr.conflicts(pot_addr): return True return False def same_server(self, vhost, generic=False): """Determines if the vhost is the same 'server'. Used in redirection - indicates whether or not the two virtual hosts serve on the exact same IP combinations, but different ports. The generic flag indicates that that we're trying to match to a default or generic vhost .. todo:: Handle _default_ """ if not generic: if vhost.get_names() != self.get_names(): return False # If equal and set is not empty... assume same server if self.name is not None or self.aliases: return True # If we're looking for a generic vhost, don't return one with a ServerName elif self.name: return False # Both sets of names are empty. # Make conservative educated guess... this is very restrictive # Consider adding more safety checks. if len(vhost.addrs) != len(self.addrs): return False # already_found acts to keep everything very conservative. # Don't allow multiple ip:ports in same set. already_found = set() for addr in vhost.addrs: for local_addr in self.addrs: if (local_addr.get_addr() == addr.get_addr() and local_addr != addr and local_addr.get_addr() not in already_found): # This intends to make sure we aren't double counting... # e.g. 127.0.0.1:* - We require same number of addrs # currently already_found.add(local_addr.get_addr()) break else: return False return True