<commit_before># Copyright 2016 <NAME> <<EMAIL>>
# Author: <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from OpenSSL import crypto

import datetime
import logging
import os
import requests
import subprocess

LOG = logging.getLogger(__name__)

_INTERMEDIATE_CERTIFICATE_URL = \
    'https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.pem'


class Certificate(object):

    def __init__(self, conf):
        self.name = conf.get('name')
        self.path = conf.get('path')
        self.type = conf.get('type')
        self.size = conf.get('size', 4096)
        self.digest = conf.get('digest', 'sha256')
        self.version = conf.get('version', 3)
        self.subjectAltName = self.normalize_san(conf.get('subjectAltName'))
        self.account_key_name = conf.get('account_key_name')
        self.remaining_days = conf.get('remaining_days', 10)
        self.days_before_expiry = self.get_days_before_expiry()
        self.service_name = conf.get('service_name')

        self.subject = {
          'C': conf.get('countryName'),
          'ST': conf.get('stateOrProvinceName'),
          'L': conf.get('localityName'),
          'O': conf.get('organizationName'),
          'OU': conf.get('organizationalUnitName'),
          'CN': conf.get('commonName'),
          'emailAddress': conf.get('emailAddress'),
        }

        if self.subject['CN'] is None:
            self.subject['CN'] = self.name

        if self.subjectAltName is None:
            self.subjectAltName = 'DNS:%s' % self.name

    def normalize_san(self, san):

        # If an array of SAN is passed in the configuration file
        #
        # certificates:
        #   my.example.org:
        #     subjectAltName:
        #       - my.example.org
        #       - my1.example.org
        #
        # return : DNS:my.example.org,DNS:my1.example.org
        if isinstance(san, list):
            san_string = 'DNS:%s' % ',DNS:'.join(san)

        # If a string of SAN is passed but without the proper format
        #
        # certificates:
        #   my.example.org:
        #     subjectAltName: my.example.org,my1.example.org
        #
        # return : DNS:my.example.org,DNS:my1.example.org
        elif san and not san.startswith('DNS:'):
            san_string = 'DNS:%s' % ',DNS:'.join(san.split(','))
        else:
            san_string = 'DNS:%s' % self.name

        return san_string

    def _create_filesystem(self):
        _FOLDERS = ['csr', 'challenges', 'pem', 'private', 'certs']

        for folder in _FOLDERS:
            LOG.debug('[global] Ensure path exist: %s/%s' %
                      (self.path, folder))
            if not os.path.exists('%s/%s' % (self.path, folder)):
                os.makedirs('%s/%s' % (self.path, folder))

    def _get_intermediate_certificate(self):
        certificate = requests.get(_INTERMEDIATE_CERTIFICATE_URL).text
        certificate_name = os.path.basename(_INTERMEDIATE_CERTIFICATE_URL)

        LOG.info('[global] Getting intermediate certificate PEM file: %s' %
                 certificate_name)
        if not os.path.exists('%s/pem/%s' % (self.path, certificate_name)):
            with open('%s/pem/%s' % (self.path, certificate_name), 'w') as f:
                f.write(certificate)

    def _create_account_key(self):
        account_key = crypto.PKey()

        if self.type == 'RSA':
            crypto_type = crypto.TYPE_RSA
        else:
            crypto_type = crypto.TYPE_DSA

        try:
            LOG.info('[global] Generating account key: %s \
                     (type: %s, size: %s)' %
                     (self.account_key_name, self.type, self.size))
            account_key.generate_key(crypto_type, self.size)
        except (TypeError, ValueError):
            raise

        try:
            LOG.debug('[global] Writting account key: %s/private/%s' %
                      (self.path, self.account_key_name))
            accountkey_file = open('%s/private/%s' %
                                   (self.path, self.account_key_name), 'w')
            accountkey_file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                                         account_key))
            accountkey_file.close()
        except IOError:
            try:
                os.remove('%s/private/%s.key' %
                          (self.path, self.account_key_name))
            except OSError:
                pass
            raise

    def _create_private_key(self):
        private_key = crypto.PKey()

        if self.type == 'RSA':
            crypto_type = crypto.TYPE_RSA
        else:
            crypto_type = crypto.TYPE_DSA

        try:
            LOG.info('[%s] Generating private key (type: %s, size: %s)' %
                     (self.name, self.type, self.size))
            private_key.generate_key(crypto_type, self.size)
        except (TypeError, ValueError):
            raise

        try:
            LOG.debug('[%s] Writting private key: %s/private/%s.key' %
                      (self.name, self.path, self.name))
            privatekey_file = open('%s/private/%s.key' %
                                   (self.path, self.name), 'w')
            privatekey_file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                                         private_key))
            privatekey_file.close()
        except IOError:
            try:
                os.remove('%s/private/%s.key' % (self.path, self.name))
            except OSError:
                pass
            raise

    def _create_csr(self):<commit_msg>Private Key: Create the file with the proper permission<commit_after># Copyright 2016 <NAME> <<EMAIL>>
# Author: <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from OpenSSL import crypto

import datetime
import logging
import os
import requests
import subprocess

LOG = logging.getLogger(__name__)

_INTERMEDIATE_CERTIFICATE_URL = \
    'https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.pem'


class Certificate(object):

    def __init__(self, conf):
        self.name = conf.get('name')
        self.path = conf.get('path')
        self.type = conf.get('type')
        self.size = conf.get('size', 4096)
        self.digest = conf.get('digest', 'sha256')
        self.version = conf.get('version', 3)
        self.subjectAltName = self.normalize_san(conf.get('subjectAltName'))
        self.account_key_name = conf.get('account_key_name')
        self.remaining_days = conf.get('remaining_days', 10)
        self.days_before_expiry = self.get_days_before_expiry()
        self.service_name = conf.get('service_name')

        self.subject = {
          'C': conf.get('countryName'),
          'ST': conf.get('stateOrProvinceName'),
          'L': conf.get('localityName'),
          'O': conf.get('organizationName'),
          'OU': conf.get('organizationalUnitName'),
          'CN': conf.get('commonName'),
          'emailAddress': conf.get('emailAddress'),
        }

        if self.subject['CN'] is None:
            self.subject['CN'] = self.name

        if self.subjectAltName is None:
            self.subjectAltName = 'DNS:%s' % self.name

    def normalize_san(self, san):

        # If an array of SAN is passed in the configuration file
        #
        # certificates:
        #   my.example.org:
        #     subjectAltName:
        #       - my.example.org
        #       - my1.example.org
        #
        # return : DNS:my.example.org,DNS:my1.example.org
        if isinstance(san, list):
            san_string = 'DNS:%s' % ',DNS:'.join(san)

        # If a string of SAN is passed but without the proper format
        #
        # certificates:
        #   my.example.org:
        #     subjectAltName: my.example.org,my1.example.org
        #
        # return : DNS:my.example.org,DNS:my1.example.org
        elif san and not san.startswith('DNS:'):
            san_string = 'DNS:%s' % ',DNS:'.join(san.split(','))
        else:
            san_string = 'DNS:%s' % self.name

        return san_string

    def _create_filesystem(self):
        _FOLDERS = ['csr', 'challenges', 'pem', 'private', 'certs']

        for folder in _FOLDERS:
            LOG.debug('[global] Ensure path exist: %s/%s' %
                      (self.path, folder))
            if not os.path.exists('%s/%s' % (self.path, folder)):
                os.makedirs('%s/%s' % (self.path, folder))

    def _get_intermediate_certificate(self):
        certificate = requests.get(_INTERMEDIATE_CERTIFICATE_URL).text
        certificate_name = os.path.basename(_INTERMEDIATE_CERTIFICATE_URL)

        LOG.info('[global] Getting intermediate certificate PEM file: %s' %
                 certificate_name)
        if not os.path.exists('%s/pem/%s' % (self.path, certificate_name)):
            with open('%s/pem/%s' % (self.path, certificate_name), 'w') as f:
                f.write(certificate)

    def _create_account_key(self):
        account_key = crypto.PKey()

        if self.type == 'RSA':
            crypto_type = crypto.TYPE_RSA
        else:
            crypto_type = crypto.TYPE_DSA

        try:
            LOG.info('[global] Generating account key: %s \
                     (type: %s, size: %s)' %
                     (self.account_key_name, self.type, self.size))
            account_key.generate_key(crypto_type, self.size)
        except (TypeError, ValueError):
            raise

        try:
            LOG.debug('[global] Writting account key: %s/private/%s' %
                      (self.path, self.account_key_name))
            accountkey_file = os.open('%s/private/%s' %
                                      (self.path, self.account_key_name),
                                      os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
                                      0o600)
            os.write(accountkey_file,
                     crypto.dump_privatekey(crypto.FILETYPE_PEM, account_key))
            os.close(accountkey_file)

            accountkey_file = open('%s/private/%s' %
                                   (self.path, self.account_key_name), 'w')
            accountkey_file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                                         account_key))
            accountkey_file.close()
        except IOError:
            try:
                os.remove('%s/private/%s.key' %
                          (self.path, self.account_key_name))
            except OSError:
                pass
            raise

    def _create_private_key(self):
        private_key = crypto.PKey()

        if self.type == 'RSA':
            crypto_type = crypto.TYPE_RSA
        else:
            crypto_type = crypto.TYPE_DSA

        try:
            LOG.info('[%s] Generating private key (type: %s, size: %s)' %
                     (self.name, self.type, self.size))
            private_key.generate_key(crypto_type, self.size)
        except (TypeError, ValueError):
            raise

        try:
            LOG.debug('[%s] Writting private key: %s/private/%s.key' %
                      (self.name, self.path, self.name))
            privatekey_file = os.open('%s/private/%s.key' %
                                      (self.path, self.name),
                                      os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
                                      0o600)
            os.write(privatekey_file,
                     crypto.dump_privatekey(crypto.FILETYPE_PEM, private_key))
            os.close(privatekey_file)
        except IOError:
            try:
                os.remove('%s/private/%s.key' % (self.path, self.name))
            except OSError:
                pass
            raise

    def _create_csr(self):
{'fraction_non_alphanumeric': 0.11862938164631745, 'fraction_numerical': 0.004253643166601024, 'mean_word_length': 1.867208672086721, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 15, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 15, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4968363', 'n_tokens_mistral': 3842, 'n_tokens_neox': 3695, 'n_words': 807}