test_dhparam.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. import re
  2. import subprocess
  3. import backoff
  4. import docker
  5. import pytest
  6. docker_client = docker.from_env()
  7. ###############################################################################
  8. #
  9. # Tests helpers
  10. #
  11. ###############################################################################
  12. @backoff.on_exception(backoff.constant, AssertionError, interval=2, max_tries=15, jitter=None)
  13. def assert_log_contains(expected_log_line, container_name="nginxproxy"):
  14. """
  15. Check that the nginx-proxy container log contains a given string.
  16. The backoff decorator will retry the check 15 times with a 2 seconds delay.
  17. :param expected_log_line: string to search for
  18. :return: None
  19. :raises: AssertError if the expected string is not found in the log
  20. """
  21. sut_container = docker_client.containers.get(container_name)
  22. docker_logs = sut_container.logs(stdout=True, stderr=True, stream=False, follow=False)
  23. assert bytes(expected_log_line, encoding="utf8") in docker_logs
  24. def require_openssl(required_version):
  25. """
  26. This function checks that the required version of OpenSSL is present, and skips the test if not.
  27. Use it as a test function decorator:
  28. @require_openssl("2.3.4")
  29. def test_something():
  30. ...
  31. :param required_version: minimal required version as a string: "1.2.3"
  32. """
  33. def versiontuple(v):
  34. clean_v = re.sub(r"[^\d\.]", "", v)
  35. return tuple(map(int, (clean_v.split("."))))
  36. try:
  37. command_output = subprocess.check_output(["openssl", "version"])
  38. except OSError:
  39. return pytest.mark.skip("openssl command is not available in test environment")
  40. else:
  41. if not command_output:
  42. raise Exception("Could not get openssl version")
  43. openssl_version = str(command_output.split()[1])
  44. return pytest.mark.skipif(
  45. versiontuple(openssl_version) < versiontuple(required_version),
  46. reason=f"openssl v{openssl_version} is less than required version {required_version}")
  47. @require_openssl("1.0.2")
  48. def negotiate_cipher(sut_container, additional_params='', grep='Cipher is'):
  49. host = f"{sut_container.attrs['NetworkSettings']['IPAddress']}:443"
  50. return subprocess.check_output(
  51. f"echo '' | openssl s_client -connect {host} -tls1_2 {additional_params} | grep '{grep}'",
  52. shell=True
  53. )
  54. def can_negotiate_dhe_ciphersuite(sut_container):
  55. r = negotiate_cipher(sut_container, "-cipher 'EDH'")
  56. assert b"New, TLSv1.2, Cipher is DHE-RSA-AES256-GCM-SHA384\n" == r
  57. r2 = negotiate_cipher(sut_container, "-cipher 'EDH'", "Server Temp Key")
  58. assert b"DH" in r2
  59. def cannot_negotiate_dhe_ciphersuite(sut_container):
  60. # Fail to negotiate a DHE cipher suite:
  61. r = negotiate_cipher(sut_container, "-cipher 'EDH'")
  62. assert b"New, (NONE), Cipher is (NONE)\n" == r
  63. # Correctly establish a connection (TLS 1.2):
  64. r2 = negotiate_cipher(sut_container)
  65. assert b"New, TLSv1.2, Cipher is ECDHE-RSA-AES256-GCM-SHA384\n" == r2
  66. r3 = negotiate_cipher(sut_container, grep="Server Temp Key")
  67. assert b"X25519" in r3
  68. # Parse array of container ENV, splitting at the `=` and returning the value, otherwise `None`
  69. def get_env(sut_container, var):
  70. env = sut_container.attrs['Config']['Env']
  71. for e in env:
  72. if e.startswith(var):
  73. return e.split('=')[1]
  74. return None
  75. ###############################################################################
  76. #
  77. # Tests
  78. #
  79. ###############################################################################
  80. def test_default_dhparam_is_ffdhe4096(docker_compose):
  81. container_name="dh-default"
  82. sut_container = docker_client.containers.get(container_name)
  83. assert sut_container.status == "running"
  84. assert_log_contains("Setting up DH Parameters..", container_name)
  85. # Make sure the dhparam file used is the default ffdhe4096.pem:
  86. default_checksum = sut_container.exec_run("md5sum /app/dhparam/ffdhe4096.pem").output.split()
  87. current_checksum = sut_container.exec_run("md5sum /etc/nginx/dhparam/dhparam.pem").output.split()
  88. assert default_checksum[0] == current_checksum[0]
  89. can_negotiate_dhe_ciphersuite(sut_container)
  90. def test_can_change_dhparam_group(docker_compose):
  91. container_name="dh-env"
  92. sut_container = docker_client.containers.get(container_name)
  93. assert sut_container.status == "running"
  94. assert_log_contains("Setting up DH Parameters..", container_name)
  95. # Make sure the dhparam file used is ffdhe2048.pem, not the default (ffdhe4096.pem):
  96. default_checksum = sut_container.exec_run("md5sum /app/dhparam/ffdhe2048.pem").output.split()
  97. current_checksum = sut_container.exec_run("md5sum /etc/nginx/dhparam/dhparam.pem").output.split()
  98. assert default_checksum[0] == current_checksum[0]
  99. can_negotiate_dhe_ciphersuite(sut_container)
  100. def test_fail_if_dhparam_group_not_supported(docker_compose):
  101. container_name="invalid-group-1024"
  102. sut_container = docker_client.containers.get(container_name)
  103. assert sut_container.status == "exited"
  104. DHPARAM_BITS = get_env(sut_container, "DHPARAM_BITS")
  105. assert DHPARAM_BITS == "1024"
  106. assert_log_contains(
  107. f"ERROR: Unsupported DHPARAM_BITS size: {DHPARAM_BITS}. Use: 2048, 3072, or 4096 (default).",
  108. container_name
  109. )
  110. def test_custom_dhparam_is_supported(docker_compose):
  111. container_name="dh-file"
  112. sut_container = docker_client.containers.get(container_name)
  113. assert sut_container.status == "running"
  114. assert_log_contains(
  115. "Warning: A custom dhparam.pem file was provided. Best practice is to use standardized RFC7919 DHE groups instead.",
  116. container_name
  117. )
  118. # Make sure the dhparam file used is not the default (ffdhe4096.pem):
  119. default_checksum = sut_container.exec_run("md5sum /app/dhparam/ffdhe4096.pem").output.split()
  120. current_checksum = sut_container.exec_run("md5sum /etc/nginx/dhparam/dhparam.pem").output.split()
  121. assert default_checksum[0] != current_checksum[0]
  122. can_negotiate_dhe_ciphersuite(sut_container)
  123. def test_web5_https_works(docker_compose, nginxproxy):
  124. r = nginxproxy.get("https://web5.nginx-proxy.tld/port", allow_redirects=False)
  125. assert r.status_code == 200
  126. assert "answer from port 85\n" in r.text