You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

171 lines
6.0 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2016 Therp BV <http://therp.nl>
  3. # © 2016 Antonio Espinosa <antonio.espinosa@tecnativa.com>
  4. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  5. import os
  6. import logging
  7. import urllib2
  8. import urlparse
  9. import subprocess
  10. import tempfile
  11. from openerp import _, api, models, exceptions
  12. from openerp.tools import config
  13. DEFAULT_KEY_LENGTH = 4096
  14. _logger = logging.getLogger(__name__)
  15. def get_data_dir():
  16. return os.path.join(config.options.get('data_dir'), 'letsencrypt')
  17. def get_challenge_dir():
  18. return os.path.join(get_data_dir(), 'acme-challenge')
  19. class Letsencrypt(models.AbstractModel):
  20. _name = 'letsencrypt'
  21. _description = 'Abstract model providing functions for letsencrypt'
  22. @api.model
  23. def call_cmdline(self, cmdline, loglevel=logging.INFO,
  24. raise_on_result=True):
  25. process = subprocess.Popen(
  26. cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  27. stdout, stderr = process.communicate()
  28. if stderr:
  29. _logger.log(loglevel, stderr)
  30. if stdout:
  31. _logger.log(loglevel, stdout)
  32. if process.returncode:
  33. raise exceptions.Warning(
  34. _('Error calling %s: %d') % (cmdline[0], process.returncode),
  35. ' '.join(cmdline),
  36. )
  37. return process.returncode
  38. @api.model
  39. def generate_account_key(self):
  40. data_dir = get_data_dir()
  41. if not os.path.isdir(data_dir):
  42. os.makedirs(data_dir)
  43. account_key = os.path.join(data_dir, 'account.key')
  44. if not os.path.isfile(account_key):
  45. _logger.info('generating rsa account key')
  46. self.call_cmdline([
  47. 'openssl', 'genrsa', '-out', account_key,
  48. str(DEFAULT_KEY_LENGTH),
  49. ])
  50. assert os.path.isfile(account_key), 'failed to create rsa key'
  51. return account_key
  52. @api.model
  53. def generate_domain_key(self, domain):
  54. domain_key = os.path.join(get_data_dir(), '%s.key' % domain)
  55. if not os.path.isfile(domain_key):
  56. _logger.info('generating rsa domain key for %s', domain)
  57. self.call_cmdline([
  58. 'openssl', 'genrsa', '-out', domain_key,
  59. str(DEFAULT_KEY_LENGTH),
  60. ])
  61. return domain_key
  62. @api.model
  63. def validate_domain(self, domain):
  64. local_domains = [
  65. 'localhost', 'localhost.localdomain', 'localhost6',
  66. 'localhost6.localdomain6'
  67. ]
  68. def _ip_is_private(address):
  69. import IPy
  70. try:
  71. ip = IPy.IP(address)
  72. except:
  73. return False
  74. return ip.iptype() == 'PRIVATE'
  75. if domain in local_domains or _ip_is_private(domain):
  76. raise exceptions.Warning(
  77. _("Let's encrypt doesn't work with private addresses "
  78. "or local domains!"))
  79. @api.model
  80. def generate_csr(self, domain):
  81. domains = [domain]
  82. parameter_model = self.env['ir.config_parameter']
  83. altnames = parameter_model.search(
  84. [('key', 'like', 'letsencrypt.altname.')],
  85. order='key'
  86. )
  87. for altname in altnames:
  88. domains.append(altname.value)
  89. _logger.info('generating csr for %s', domain)
  90. if len(domains) > 1:
  91. _logger.info('with alternative subjects %s', ','.join(domains[1:]))
  92. config = parameter_model.get_param(
  93. 'letsencrypt.openssl.cnf', '/etc/ssl/openssl.cnf'
  94. )
  95. csr = os.path.join(get_data_dir(), '%s.csr' % domain)
  96. with tempfile.NamedTemporaryFile() as cfg:
  97. cfg.write(open(config).read())
  98. if len(domains) > 1:
  99. cfg.write(
  100. '\n[SAN]\nsubjectAltName=' +
  101. ','.join(map(lambda x: 'DNS:%s' % x, domains)) + '\n')
  102. cfg.file.flush()
  103. cmdline = [
  104. 'openssl', 'req', '-new',
  105. parameter_model.get_param(
  106. 'letsencrypt.openssl.digest', '-sha256'),
  107. '-key', self.generate_domain_key(domain),
  108. '-subj', '/CN=%s' % domain, '-config', cfg.name,
  109. '-out', csr,
  110. ]
  111. if len(domains) > 1:
  112. cmdline.extend([
  113. '-reqexts', 'SAN',
  114. ])
  115. self.call_cmdline(cmdline)
  116. return csr
  117. @api.model
  118. def cron(self):
  119. domain = urlparse.urlparse(
  120. self.env['ir.config_parameter'].get_param(
  121. 'web.base.url', 'localhost')).netloc
  122. self.validate_domain(domain)
  123. account_key = self.generate_account_key()
  124. csr = self.generate_csr(domain)
  125. acme_challenge = get_challenge_dir()
  126. if not os.path.isdir(acme_challenge):
  127. os.makedirs(acme_challenge)
  128. if self.env.context.get('letsencrypt_dry_run'):
  129. crt_text = 'I\'m a test text'
  130. else: # pragma: no cover
  131. from acme_tiny import get_crt, DEFAULT_CA
  132. crt_text = get_crt(
  133. account_key, csr, acme_challenge, log=_logger, CA=DEFAULT_CA)
  134. with open(os.path.join(get_data_dir(), '%s.crt' % domain), 'w')\
  135. as crt:
  136. crt.write(crt_text)
  137. chain_cert = urllib2.urlopen(
  138. self.env['ir.config_parameter'].get_param(
  139. 'letsencrypt.chain_certificate_address',
  140. 'https://letsencrypt.org/certs/'
  141. 'lets-encrypt-x3-cross-signed.pem')
  142. )
  143. crt.write(chain_cert.read())
  144. chain_cert.close()
  145. _logger.info('wrote %s', crt.name)
  146. reload_cmd = self.env['ir.config_parameter'].get_param(
  147. 'letsencrypt.reload_command', False)
  148. if reload_cmd:
  149. _logger.info('reloading webserver...')
  150. self.call_cmdline(['sh', '-c', reload_cmd])
  151. else:
  152. _logger.info('no command defined for reloading webserver, please '
  153. 'do it manually in order to apply new certificate')