# Path: pki/helper.py
# def subject_for_object(obj):
#     """Return a subject string.
#     
#     A OpenSSL compatible subject string is returned.
#     """
#     
#     subj = '/CN=%s/C=%s/ST=%s/localityName=%s/O=%s' % ( obj.common_name,
#                                                         obj.country,
#                                                         obj.state,
#                                                         obj.locality,
#                                                         obj.organization,
#                                                       )
#     
#     if obj.OU:
#         subj += '/organizationalUnitName=%s' % obj.OU
#     
#     if obj.email:
#         subj += '/emailAddress=%s' % obj.email
#     
#     return subj
# 
# Path: pki/settings.py
# PKI_OPENSSL_BIN = getattr(settings, 'PKI_OPENSSL_BIN', '/usr/bin/openssl')
# 
# PKI_OPENSSL_CONF = getattr(settings, 'PKI_OPENSSL_CONF', os.path.join(PKI_DIR, 'openssl.conf'))
# 
# PKI_DIR = getattr(settings, 'PKI_DIR', os.path.join(PKI_APP_DIR, 'PKI'))
# 
# PKI_OPENSSL_TEMPLATE = getattr(settings, 'PKI_OPENSSL_TEMPLATE', 'pki/openssl.conf.in')
# 
# PKI_SELF_SIGNED_SERIAL = getattr(settings, 'PKI_SELF_SIGNED_SERIAL', 0x0)
# 
# PKI_CA_NAME_BLACKLIST = ('_SELF_SIGNED_CERTIFICATES',)


import os
import re
import string
import random
import pki.models
from subprocess import Popen, PIPE, STDOUT
from shutil import rmtree
from logging import getLogger
from django.template.loader import render_to_string
from pki.helper import subject_for_object
from pki.settings import PKI_OPENSSL_BIN, PKI_OPENSSL_CONF, PKI_DIR, PKI_OPENSSL_TEMPLATE, \
                         PKI_SELF_SIGNED_SERIAL, PKI_CA_NAME_BLACKLIST
    from hashlib import md5 as md5_constructor
    from md5 import new as md5_constructor
                        os.mkdir(os.path.join(self.ca_dir, "certs"))
                    except OSError, e:
                        logger.exception("Failed to create directories for self-signed certificates %s" % self.ca_dir)
                        raise
            
            self.key    = os.path.join(self.ca_dir, 'certs', '%s.key.pem' % self.i.name)
            self.pkcs12 = os.path.join(self.ca_dir, 'certs', '%s.cert.p12' % self.i.name)
            
            if not self.i.subjaltname:
                self.i.subjaltname = 'email:copy'            
        else:
            raise Exception( "Given object type is unknown!" )
        
        if not self.i.crl_dpoints:
            self.i.crl_dpoints = ''
        
        self.csr  = os.path.join(self.ca_dir, 'certs', '%s.csr.pem'  % self.i.name)
        self.crt  = os.path.join(self.ca_dir, 'certs', '%s.cert.pem' % self.i.name)
        self.der  = os.path.join(self.ca_dir, 'certs', '%s.cert.der' % self.i.name)
        
        ## Generate a random string as ENV variable name
        self.env_pw = "".join(random.sample(string.letters+string.digits, 10))
    
    def exec_openssl(self, command, env_vars=None):
        """Run a openssl command.
        
        command is prefixed with openssl binary from PKI_OPENSSL_BIN
        env_vars is a dict containing the set environment variables
        """
        

# Path: pki/helper.py
# def subject_for_object(obj):
#     """Return a subject string.
#     
#     A OpenSSL compatible subject string is returned.
#     """
#     
#     subj = '/CN=%s/C=%s/ST=%s/localityName=%s/O=%s' % ( obj.common_name,
#                                                         obj.country,
#                                                         obj.state,
#                                                         obj.locality,
#                                                         obj.organization,
#                                                       )
#     
#     if obj.OU:
#         subj += '/organizationalUnitName=%s' % obj.OU
#     
#     if obj.email:
#         subj += '/emailAddress=%s' % obj.email
#     
#     return subj
# 
# Path: pki/settings.py
# PKI_OPENSSL_BIN = getattr(settings, 'PKI_OPENSSL_BIN', '/usr/bin/openssl')
# 
# PKI_OPENSSL_CONF = getattr(settings, 'PKI_OPENSSL_CONF', os.path.join(PKI_DIR, 'openssl.conf'))
# 
# PKI_DIR = getattr(settings, 'PKI_DIR', os.path.join(PKI_APP_DIR, 'PKI'))
# 
# PKI_OPENSSL_TEMPLATE = getattr(settings, 'PKI_OPENSSL_TEMPLATE', 'pki/openssl.conf.in')
# 
# PKI_SELF_SIGNED_SERIAL = getattr(settings, 'PKI_SELF_SIGNED_SERIAL', 0x0)
# 
# PKI_CA_NAME_BLACKLIST = ('_SELF_SIGNED_CERTIFICATES',)


# Path: pki/openssl.py
import os
import re
import string
import random
import pki.models
from subprocess import Popen, PIPE, STDOUT
from shutil import rmtree
from logging import getLogger
from django.template.loader import render_to_string
from pki.helper import subject_for_object
from pki.settings import PKI_OPENSSL_BIN, PKI_OPENSSL_CONF, PKI_DIR, PKI_OPENSSL_TEMPLATE, \
                         PKI_SELF_SIGNED_SERIAL, PKI_CA_NAME_BLACKLIST
    from hashlib import md5 as md5_constructor
    from md5 import new as md5_constructor

                        os.mkdir(os.path.join(self.ca_dir, "certs"))
                    except OSError, e:
                        logger.exception("Failed to create directories for self-signed certificates %s" % self.ca_dir)
                        raise
            
            self.key    = os.path.join(self.ca_dir, 'certs', '%s.key.pem' % self.i.name)
            self.pkcs12 = os.path.join(self.ca_dir, 'certs', '%s.cert.p12' % self.i.name)
            
            if not self.i.subjaltname:
                self.i.subjaltname = 'email:copy'            
        else:
            raise Exception( "Given object type is unknown!" )
        
        if not self.i.crl_dpoints:
            self.i.crl_dpoints = ''
        
        self.csr  = os.path.join(self.ca_dir, 'certs', '%s.csr.pem'  % self.i.name)
        self.crt  = os.path.join(self.ca_dir, 'certs', '%s.cert.pem' % self.i.name)
        self.der  = os.path.join(self.ca_dir, 'certs', '%s.cert.der' % self.i.name)
        
        ## Generate a random string as ENV variable name
        self.env_pw = "".join(random.sample(string.letters+string.digits, 10))
    
    def exec_openssl(self, command, env_vars=None):
        """Run a openssl command.
        
        command is prefixed with openssl binary from PKI_OPENSSL_BIN
        env_vars is a dict containing the set environment variables
        """
        

        c = [PKI_OPENSSL_BIN]