PageRenderTime 82ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/letshelp-letsencrypt/letshelp_letsencrypt/apache.py

https://gitlab.com/0072016/letsencrypt
Python | 306 lines | 254 code | 17 blank | 35 comment | 24 complexity | 305bd901bb76e17263dab0b7a15f0527 MD5 | raw file
  1. #!/usr/bin/env python
  2. """Let's Encrypt Apache configuration submission script"""
  3. from __future__ import print_function
  4. import argparse
  5. import atexit
  6. import contextlib
  7. import os
  8. import re
  9. import shutil
  10. import subprocess
  11. import sys
  12. import tarfile
  13. import tempfile
  14. import textwrap
  15. _DESCRIPTION = """
  16. Let's Help is a simple script you can run to help out the Let's Encrypt
  17. project. Since Let's Encrypt will support automatically configuring HTTPS on
  18. many servers, we want to test this functionality on as many configurations as
  19. possible. This script will create a sanitized copy of your Apache
  20. configuration, notifying you of the files that have been selected. If (and only
  21. if) you approve this selection, these files will be sent to the Let's Encrypt
  22. developers.
  23. """
  24. _NO_APACHECTL = """
  25. Unable to find `apachectl` which is required for this script to work. If it is
  26. installed, please run this script again with the --apache-ctl command line
  27. argument and the path to the binary.
  28. """
  29. # Keywords likely to be found in filenames of sensitive files
  30. _SENSITIVE_FILENAME_REGEX = re.compile(r"^(?!.*proxy_fdpass).*pass.*$|private|"
  31. r"secret|cert|crt|key|rsa|dsa|pw|\.pem|"
  32. r"\.der|\.p12|\.pfx|\.p7b")
  33. def make_and_verify_selection(server_root, temp_dir):
  34. """Copies server_root to temp_dir and verifies selection with the user
  35. :param str server_root: Path to the Apache server root
  36. :param str temp_dir: Path to the temporary directory to copy files to
  37. """
  38. copied_files, copied_dirs = copy_config(server_root, temp_dir)
  39. print(textwrap.fill("A secure copy of the files that have been selected "
  40. "for submission has been created under {0}. All "
  41. "comments have been removed and the files are only "
  42. "accessible by the current user. A list of the files "
  43. "that have been included is shown below. Please make "
  44. "sure that this selection does not contain private "
  45. "keys, passwords, or any other sensitive "
  46. "information.".format(temp_dir)))
  47. print("\nFiles:")
  48. for copied_file in copied_files:
  49. print(copied_file)
  50. print("Directories (including all contained files):")
  51. for copied_dir in copied_dirs:
  52. print(copied_dir)
  53. sys.stdout.write("\nIs it safe to submit these files? ")
  54. while True:
  55. ans = raw_input("(Y)es/(N)o: ").lower()
  56. if ans.startswith("y"):
  57. return
  58. elif ans.startswith("n"):
  59. sys.exit("Your files were not submitted")
  60. def copy_config(server_root, temp_dir):
  61. """Safely copies server_root to temp_dir and returns copied files
  62. :param str server_root: Absolute path to the Apache server root
  63. :param str temp_dir: Path to the temporary directory to copy files to
  64. :returns: List of copied files and a list of leaf directories where
  65. all contained files were copied
  66. :rtype: `tuple` of `list` of `str`
  67. """
  68. copied_files, copied_dirs = [], []
  69. dir_len = len(os.path.dirname(server_root))
  70. for config_path, config_dirs, config_files in os.walk(server_root):
  71. temp_path = os.path.join(temp_dir, config_path[dir_len + 1:])
  72. os.mkdir(temp_path)
  73. copied_all = True
  74. copied_files_in_current_dir = []
  75. for config_file in config_files:
  76. config_file_path = os.path.join(config_path, config_file)
  77. temp_file_path = os.path.join(temp_path, config_file)
  78. if os.path.islink(config_file_path):
  79. os.symlink(os.readlink(config_file_path), temp_file_path)
  80. elif safe_config_file(config_file_path):
  81. copy_file_without_comments(config_file_path, temp_file_path)
  82. copied_files_in_current_dir.append(config_file_path)
  83. else:
  84. copied_all = False
  85. # If copied all files in leaf directory
  86. if copied_all and not config_dirs:
  87. copied_dirs.append(config_path)
  88. else:
  89. copied_files += copied_files_in_current_dir
  90. return copied_files, copied_dirs
  91. def copy_file_without_comments(source, destination):
  92. """Copies source to destination, removing comments
  93. :param str source: Path to the file to be copied
  94. :param str destination: Path where source should be copied to
  95. """
  96. with open(source, "r") as infile:
  97. with open(destination, "w") as outfile:
  98. for line in infile:
  99. if not (line.isspace() or line.lstrip().startswith("#")):
  100. outfile.write(line)
  101. def safe_config_file(config_file):
  102. """Returns True if config_file can be safely copied
  103. :param str config_file: Path to an Apache configuration file
  104. :returns: True if config_file can be safely copied
  105. :rtype: bool
  106. """
  107. config_file_lower = config_file.lower()
  108. if _SENSITIVE_FILENAME_REGEX.search(config_file_lower):
  109. return False
  110. proc = subprocess.Popen(["file", config_file],
  111. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  112. file_output, _ = proc.communicate()
  113. if "ASCII" in file_output:
  114. possible_password_file = empty_or_all_comments = True
  115. with open(config_file) as config_fd:
  116. for line in config_fd:
  117. if not (line.isspace() or line.lstrip().startswith("#")):
  118. empty_or_all_comments = False
  119. if line.startswith("-----BEGIN"):
  120. return False
  121. elif ":" not in line:
  122. possible_password_file = False
  123. # If file isn't empty or commented out and could be a password file,
  124. # don't include it in selection. It is safe to include the file if
  125. # it consists solely of comments because comments are removed before
  126. # submission.
  127. return empty_or_all_comments or not possible_password_file
  128. return False
  129. def setup_tempdir(args):
  130. """Creates a temporary directory and necessary files for config
  131. :param argparse.Namespace args: Parsed command line arguments
  132. :returns: Path to temporary directory
  133. :rtype: str
  134. """
  135. tempdir = tempfile.mkdtemp()
  136. with open(os.path.join(tempdir, "config_file"), "w") as config_fd:
  137. config_fd.write(args.config_file + "\n")
  138. proc = subprocess.Popen([args.apache_ctl, "-v"],
  139. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  140. with open(os.path.join(tempdir, "version"), "w") as version_fd:
  141. version_fd.write(proc.communicate()[0])
  142. proc = subprocess.Popen([args.apache_ctl, "-d", args.server_root, "-f",
  143. args.config_file, "-M"],
  144. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  145. with open(os.path.join(tempdir, "modules"), "w") as modules_fd:
  146. modules_fd.write(proc.communicate()[0])
  147. proc = subprocess.Popen([args.apache_ctl, "-d", args.server_root, "-f",
  148. args.config_file, "-t", "-D", "DUMP_VHOSTS"],
  149. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  150. with open(os.path.join(tempdir, "vhosts"), "w") as vhosts_fd:
  151. vhosts_fd.write(proc.communicate()[0])
  152. return tempdir
  153. def verify_config(args):
  154. """Verifies server_root and config_file specify a valid config
  155. :param argparse.Namespace args: Parsed command line arguments
  156. """
  157. with open(os.devnull, "w") as devnull:
  158. try:
  159. subprocess.check_call([args.apache_ctl, "-d", args.server_root,
  160. "-f", args.config_file, "-t"],
  161. stdout=devnull, stderr=subprocess.STDOUT)
  162. except OSError:
  163. sys.exit(_NO_APACHECTL)
  164. except subprocess.CalledProcessError:
  165. sys.exit("Syntax check from apachectl failed")
  166. def locate_config(apache_ctl):
  167. """Uses the apachectl binary to find configuration files
  168. :param str apache_ctl: Path to `apachectl` binary
  169. :returns: Path to Apache server root and main configuration file
  170. :rtype: `tuple` of `str`
  171. """
  172. try:
  173. proc = subprocess.Popen([apache_ctl, "-V"],
  174. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  175. output, _ = proc.communicate()
  176. except OSError:
  177. sys.exit(_NO_APACHECTL)
  178. server_root = config_file = ""
  179. for line in output.splitlines():
  180. # Relevant output lines are of the form: -D DIRECTIVE="VALUE"
  181. if "HTTPD_ROOT" in line:
  182. server_root = line[line.find('"') + 1:-1]
  183. elif "SERVER_CONFIG_FILE" in line:
  184. config_file = line[line.find('"') + 1:-1]
  185. if not (server_root and config_file):
  186. sys.exit("Unable to locate Apache configuration. Please run this "
  187. "script again and specify --server-root and --config-file")
  188. return server_root, config_file
  189. def get_args():
  190. """Parses command line arguments
  191. :returns: Parsed command line options
  192. :rtype: argparse.Namespace
  193. """
  194. parser = argparse.ArgumentParser(description=_DESCRIPTION)
  195. parser.add_argument("-c", "--apache-ctl", default="apachectl",
  196. help="path to the `apachectl` binary")
  197. parser.add_argument("-d", "--server-root",
  198. help=("location of the root directory of your Apache "
  199. "configuration"))
  200. parser.add_argument("-f", "--config-file",
  201. help=("location of your main Apache configuration "
  202. "file relative to the server root"))
  203. args = parser.parse_args()
  204. # args.server_root XOR args.config_file
  205. if bool(args.server_root) != bool(args.config_file):
  206. sys.exit("If either --server-root and --config-file are specified, "
  207. "they both must be included")
  208. elif args.server_root and args.config_file:
  209. args.server_root = os.path.abspath(args.server_root)
  210. args.config_file = os.path.abspath(args.config_file)
  211. if args.config_file.startswith(args.server_root):
  212. args.config_file = args.config_file[len(args.server_root) + 1:]
  213. else:
  214. sys.exit("This script expects the Apache configuration file to be "
  215. "inside the server root")
  216. return args
  217. def main():
  218. """Main script execution"""
  219. args = get_args()
  220. if args.server_root is None:
  221. args.server_root, args.config_file = locate_config(args.apache_ctl)
  222. verify_config(args)
  223. tempdir = setup_tempdir(args)
  224. atexit.register(lambda: shutil.rmtree(tempdir))
  225. make_and_verify_selection(args.server_root, tempdir)
  226. tarpath = os.path.join(tempdir, "config.tar.gz")
  227. # contextlib.closing used for py26 support
  228. with contextlib.closing(tarfile.open(tarpath, mode="w:gz")) as tar:
  229. tar.add(tempdir, arcname=".")
  230. # TODO: Submit tarpath
  231. if __name__ == "__main__":
  232. main() # pragma: no cover