CertificateAuthorityTool.py 11.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010 Nexedi SA and Contributors. All Rights Reserved.
#                    Łukasz Nowak <luke@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

30 31
import glob, os, subprocess, sys

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
from AccessControl import ClassSecurityInfo
from Products.ERP5Type.Globals import InitializeClass
from Products.ERP5Type.Tool.BaseTool import BaseTool
from Products.ERP5Type import Permissions
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from zLOG import LOG, INFO

def popenCommunicate(command_list, input=None, **kwargs):
  kwargs.update(stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  popen = subprocess.Popen(command_list, **kwargs)
  result = popen.communicate(input)[0]
  if popen.returncode is None:
    popen.kill()
  if popen.returncode != 0:
    raise ValueError('Issue during calling %r, result was:\n%s' % (
    command_list, result))
  return result

class CertificateAuthorityBusy(Exception):
  """Exception raised when certificate authority is busy"""
  pass

class CertificateAuthorityDamaged(Exception):
  """Exception raised when certificate authority is damaged"""
  pass

class CertificateAuthorityTool(BaseTool):
  """CertificateAuthorityTool

  This tool assumes that in certificate_authority_path openssl configuration
  is ready.
  """

  id = 'portal_certificate_authority'
  meta_type = 'ERP5 Certificate Authority Tool'
  portal_type = 'Certificate Authority Tool'
  security = ClassSecurityInfo()
  allowed_types = ()
  isIndexable = 0

  certificate_authority_path = os.environ.get('CA_PATH', '')
  openssl_binary = os.environ.get('OPENSSL_BINARY', '')

  manage_options = (({'label': 'Edit',
                      'action': 'manage_editCertificateAuthorityToolForm',},
                     )
                    ) + BaseTool.manage_options

  _properties = (({'id':'certificate_authority_path',
                   'type':'string',
                   'mode':'w',
                   'label':'Absolute path to certificate authority',
                   },
                   {'id':'openssl_binary',
                   'type':'string',
                   'mode':'w',
                   'label':'Absolute path to OpenSSL binary'
                   },
                  )
                 )

  def _lockCertificateAuthority(self):
    """Checks lock and locks Certificate Authority tool

       Raises CertificateAuthorityBusy"""
    if os.path.exists(self.lock):
      raise CertificateAuthorityBusy
    open(self.lock, 'w').write('locked')

  def _unlockCertificateAuthority(self):
    """Checks lock and locks Certificate Authority tool"""
    if os.path.exists(self.lock):
      os.unlink(self.lock)
    else:
      LOG('CertificateAuthorityTool', INFO, 'Lock file %r did not existed '
        'during unlocking' % self.lock)

  def _checkCertificateAuthority(self):
    """Checks Certificate Authority configuration

       Raises CertificateAuthorityDamaged"""
    if not self.certificate_authority_path:
      raise CertificateAuthorityDamaged('Certificate authority path is not '
        'configured')
    if not os.path.isdir(self.certificate_authority_path):
      raise CertificateAuthorityDamaged('Path to Certificate Authority %r is '
        'wrong' % self.certificate_authority_path)
    if not self.openssl_binary:
      raise CertificateAuthorityDamaged('OpenSSL binary path is not '
        'configured' % self.certificate_authority_path)
    if not os.path.isfile(self.openssl_binary):
       raise CertificateAuthorityDamaged('OpenSSL binary %r does not exists' %
        self.openssl_binary)
    self.serial = os.path.join(self.certificate_authority_path, 'serial')
    self.crl = os.path.join(self.certificate_authority_path, 'crlnumber')
    self.index = os.path.join(self.certificate_authority_path, 'index.txt')
    self.openssl_config = os.path.join(self.certificate_authority_path,
      'openssl.cnf')
    self.lock = os.path.join(self.certificate_authority_path, 'lock')
    for f in [self.serial, self.crl, self.index]:
      if not os.path.isfile(f):
        raise CertificateAuthorityDamaged('File %r does not exists.' % f)

  security.declarePrivate('manage_afterAdd')
  def manage_afterAdd(self, item, container) :
    """Init permissions right after creation.

    Permissions in tool are simple:
     o Each member can access the tool.
     o Only manager can view and create.
     o Anonymous can not access
    """
    item.manage_permission(Permissions.AddPortalContent,
          ['Manager'])
    item.manage_permission(Permissions.AccessContentsInformation,
          ['Member', 'Manager'])
    item.manage_permission(Permissions.View,
          ['Manager',])
    BaseTool.inheritedAttribute('manage_afterAdd')(self, item, container)

  #'Edit' option form
  manage_editCertificateAuthorityToolForm = PageTemplateFile(
      '../www/CertificateAuthorityTool_editPropertyList',
      globals(),
      __name__='manage_editCertificateAuthorityToolForm')

  security.declareProtected(Permissions.ManageProperties,
      'manage_editCertificateAuthorityTool')
  def manage_editCertificateAuthorityTool(self, certificate_authority_path,
      openssl_binary, RESPONSE=None):
    """Edit the object"""
    error_message = ''

    if certificate_authority_path == '' or certificate_authority_path is None:
      error_message += 'Invalid Certificate Authority'
    else:
      self.certificate_authority_path = certificate_authority_path

    if openssl_binary == '' or openssl_binary is None:
      error_message += 'Invalid OpenSSL binary'
    else:
      self.openssl_binary = openssl_binary

    #Redirect
    if RESPONSE is not None:
      if error_message != '':
        self.REQUEST.form['manage_tabs_message'] = error_message
        return self.manage_editCertificateAuthorityToolForm(RESPONSE)
      else:
        message = "Updated"
        RESPONSE.redirect('%s/manage_editCertificateAuthorityToolForm'
                          '?manage_tabs_message=%s'
                          % (self.absolute_url(), message)
                          )

  security.declareProtected(Permissions.AccessContentsInformation,
      'getNewCertificate')
  def getNewCertificate(self, common_name):
    # No docstring in order to make this method non publishable
    # Returns certificate for passed common name, as dictionary of
    #      {key, certificate, id, common_name}
193 194
    if not common_name:
      raise ValueError("Invalid common name: %r" % common_name)
195 196 197 198 199 200 201 202 203 204
    self._checkCertificateAuthority()
    self._lockCertificateAuthority()
    try:
      new_id = open(self.serial, 'r').read().strip().lower()
      key = os.path.join(self.certificate_authority_path, 'private',
          new_id+'.key')
      csr = os.path.join(self.certificate_authority_path, new_id + '.csr')
      cert = os.path.join(self.certificate_authority_path, 'certs',
          new_id + '.crt')
      try:
205
        os.close(os.open(key, os.O_CREAT | os.O_EXCL, 0600))
206 207 208 209 210 211 212 213 214 215 216 217 218
        popenCommunicate([self.openssl_binary, 'req', '-nodes', '-config',
          self.openssl_config, '-new', '-keyout', key, '-out', csr, '-days',
          '3650'], '%s\n' % common_name, stdin=subprocess.PIPE)
        popenCommunicate([self.openssl_binary, 'ca', '-days', '3650',
          '-batch', '-config', self.openssl_config, '-out', cert, '-infiles',
          csr])
        os.unlink(csr)
        return dict(
          key=open(key).read(),
          certificate=open(cert).read(),
          id=new_id,
          common_name=common_name)
      except:
219
        e = sys.exc_info()
220
        try:
221
          for p in key, csr, cert:
222 223 224 225 226
            if os.path.exists(p):
              os.unlink(p)
        except:
          # do not raise during cleanup
          pass
227
        raise e[0], e[1], e[2]
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
    finally:
      self._unlockCertificateAuthority()

  security.declareProtected(Permissions.AccessContentsInformation,
      'revokeCertificate')
  def revokeCertificate(self, serial):
    # No docstring in order to make this method non publishable
    # Revokes certificate with serial, returns dictionary {crl}
    self._checkCertificateAuthority()
    self._lockCertificateAuthority()
    try:
      new_id = open(self.crl, 'r').read().strip().lower()
      crl_path = os.path.join(self.certificate_authority_path, 'crl')
      crl = os.path.join(crl_path, new_id + '.crl')
      cert = os.path.join(self.certificate_authority_path, 'certs',
          serial.lower() + '.crt')
      if not os.path.exists(cert):
245 246 247 248
        raise ValueError('Certificate with serial %r does not exist' % serial)
      created = [crl]
      popenCommunicate([self.openssl_binary, 'ca', '-config',
        self.openssl_config, '-revoke', cert])
249 250 251
      try:
        popenCommunicate([self.openssl_binary, 'ca', '-config',
          self.openssl_config, '-gencrl', '-out', crl])
252 253 254 255
        alias = os.path.join(crl_path, popenCommunicate([self.openssl_binary,
          'crl', '-noout', '-hash', '-in', crl]).strip() + '.')
        alias += str(len(glob.glob(alias + '*')))
        created.append(alias)
256
        os.symlink(os.path.basename(crl), alias)
257 258
        return dict(crl=open(crl).read())
      except:
259
        e = sys.exc_info()
260
        try:
261 262 263 264
          for p in 'index.txt', 'crlnumber':
            p = os.path.join(self.certificate_authority_path, p)
            os.rename(p + '.old', p)
          for p in created:
265 266 267 268 269
            if os.path.exists(p):
              os.unlink(p)
        except:
          # do not raise during cleanup
          pass
270
        raise e[0], e[1], e[2]
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    finally:
      self._unlockCertificateAuthority()

  def _getValidSerial(self, common_name):
    index = open(self.index).read().splitlines()
    valid_line_list = [q for q in index if q.startswith('V') and
      ('CN=%s' % common_name in q)]
    if len(valid_line_list) != 1:
      raise ValueError('No certificate for %r' % common_name)
    return valid_line_list[0].split('\t')[3]

  security.declareProtected(Permissions.AccessContentsInformation,
    'revokeCertificate')
  def revokeCertificateByCommonName(self, common_name):
    self._checkCertificateAuthority()
    serial = self._getValidSerial(common_name)
    self.revokeCertificate(serial)

InitializeClass(CertificateAuthorityTool)