<commit_before>#    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.

"""Certificate signing functions.

Call set_subprocess() with the subprocess module. Either Python's
subprocess or eventlet.green.subprocess can be used.

If set_subprocess() is not called, this module will pick Python's subprocess
or eventlet.green.subprocess based on if os module is patched by eventlet.
"""

import base64
import errno
import hashlib
import logging
import textwrap
import zlib

import six

from keystoneclient import exceptions
from keystoneclient.i18n import _, _LE, _LW


subprocess = None
LOG = logging.getLogger(__name__)
PKI_ASN1_PREFIX = 'MII'
PKIZ_PREFIX = 'PKIZ_'
PKIZ_CMS_FORM = 'DER'
PKI_ASN1_FORM = 'PEM'
DEFAULT_TOKEN_DIGEST_ALGORITHM = 'sha256'


# The openssl cms command exits with these status codes.
# See https://www.openssl.org/docs/apps/cms.html#EXIT_CODES
class OpensslCmsExitStatus(object):
    SUCCESS = 0
    INPUT_FILE_READ_ERROR = 2
    CREATE_CMS_READ_MIME_ERROR = 3


def _ensure_subprocess():
    # NOTE(vish): late loading subprocess so we can
    #             use the green version if we are in
    #             eventlet.
    global subprocess
    if not subprocess:
        try:
            from eventlet import patcher
            if patcher.already_patched:
                from eventlet.green import subprocess
            else:
                import subprocess
        except ImportError:
            import subprocess  # noqa


def set_subprocess(_subprocess=None):
    """Set subprocess module to use.
    The subprocess could be eventlet.green.subprocess if using eventlet,
    or Python's subprocess otherwise.
    """
    global subprocess
    subprocess = _subprocess


def _check_files_accessible(files):
    err = None
    retcode = -1
    try:
        for try_file in files:
            with open(try_file, 'r'):
                pass
    except IOError as e:
        # Catching IOError means there is an issue with
        # the given file.
        err = _('Hit OSError in _process_communicate_handle_oserror()\n'
                'Likely due to %(file)s: %(error)s') % {'file': try_file,
                                                        'error': e.strerror}
        # Emulate openssl behavior, which returns with code 2 when
        # access to a file failed.
        retcode = OpensslCmsExitStatus.INPUT_FILE_READ_ERROR

    return retcode, err


def _process_communicate_handle_oserror(process, data, files):
    """Wrapper around process.communicate that checks for OSError."""

    try:
        output, err = process.communicate(data)
    except OSError as e:
        if e.errno != errno.EPIPE:
            raise
        # OSError with EPIPE only occurs with Python 2.6.x/old 2.7.x
        # http://bugs.python.org/issue10963

        # The quick exit is typically caused by the openssl command not being
        # able to read an input file, so check ourselves if can't read a file.
        retcode, err = _check_files_accessible(files)
        if process.stderr:
            msg = process.stderr.read()
            err = err + msg.decode('utf-8')
        output = ''
    else:
        retcode = process.poll()
        if err is not None:
            err = err.decode('utf-8')

    return output, err, retcode


def _encoding_for_form(inform):
    if inform == PKI_ASN1_FORM:
        encoding = 'UTF-8'
    elif inform == PKIZ_CMS_FORM:
        encoding = 'hex'
    else:
        raise ValueError(
            _('"inform" must be one of: %s') % ','.join((PKI_ASN1_FORM,
                                                         PKIZ_CMS_FORM)))

    return encoding


def cms_verify(formatted, signing_cert_file_name, ca_file_name,
               inform=PKI_ASN1_FORM):
    """Verifies the signature of the contents IAW CMS syntax.

    :raises subprocess.CalledProcessError:
    :raises keystoneclient.exceptions.CertificateConfigError: if certificate
                                                              is not configured
                                                              properly.
    """
    _ensure_subprocess()
    if isinstance(formatted, six.string_types):
        data = bytearray(formatted, _encoding_for_form(inform))
    else:
        data = formatted
    process = subprocess.Popen(['openssl', 'cms', '-verify',
                                '-certfile', signing_cert_file_name,
                                '-CAfile', ca_file_name,
                                '-inform', 'PEM',
                                '-nosmimecap', '-nodetach',
                                '-nocerts', '-noattr'],
                               stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               close_fds=True)
    output, err, retcode = _process_communicate_handle_oserror(
        process, data, (signing_cert_file_name, ca_file_name))

    # Do not log errors, as some happen in the positive thread
    # instead, catch them in the calling code and log them there.

    # When invoke the openssl with not exist file, return code 2
    # and error msg will be returned.
    # You can get more from
    # http://www.openssl.org/docs/apps/cms.html#EXIT_CODES
    #
    # $ openssl cms -verify -certfile not_exist_file -CAfile \
    #       not_exist_file -inform PEM -nosmimecap -nodetach \
    #       -nocerts -noattr
    # Error opening certificate file not_exist_file
    #
    if retcode == OpensslCmsExitStatus.INPUT_FILE_READ_ERROR:<commit_msg>pep8 fix for CMS<commit_after>#    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.

"""Certificate signing functions.

Call set_subprocess() with the subprocess module. Either Python's
subprocess or eventlet.green.subprocess can be used.

If set_subprocess() is not called, this module will pick Python's subprocess
or eventlet.green.subprocess based on if os module is patched by eventlet.
"""

import base64
import errno
import hashlib
import logging
import textwrap
import zlib

import six

from keystoneclient import exceptions
from keystoneclient.i18n import _, _LE, _LW


subprocess = None
LOG = logging.getLogger(__name__)
PKI_ASN1_PREFIX = 'MII'
PKIZ_PREFIX = 'PKIZ_'
PKIZ_CMS_FORM = 'DER'
PKI_ASN1_FORM = 'PEM'
DEFAULT_TOKEN_DIGEST_ALGORITHM = 'sha256'


# The openssl cms command exits with these status codes.
# See https://www.openssl.org/docs/apps/cms.html#EXIT_CODES
class OpensslCmsExitStatus(object):
    SUCCESS = 0
    INPUT_FILE_READ_ERROR = 2
    CREATE_CMS_READ_MIME_ERROR = 3


def _ensure_subprocess():
    # NOTE(vish): late loading subprocess so we can
    #             use the green version if we are in
    #             eventlet.
    global subprocess
    if not subprocess:
        try:
            from eventlet import patcher
            if patcher.already_patched:
                from eventlet.green import subprocess
            else:
                import subprocess
        except ImportError:
            import subprocess  # noqa


def set_subprocess(_subprocess=None):
    """Set subprocess module to use.
    The subprocess could be eventlet.green.subprocess if using eventlet,
    or Python's subprocess otherwise.
    """
    global subprocess
    subprocess = _subprocess


def _check_files_accessible(files):
    err = None
    retcode = -1
    try:
        for try_file in files:
            with open(try_file, 'r'):
                pass
    except IOError as e:
        # Catching IOError means there is an issue with
        # the given file.
        err = _('Hit OSError in _process_communicate_handle_oserror()\n'
                'Likely due to %(file)s: %(error)s') % {'file': try_file,
                                                        'error': e.strerror}
        # Emulate openssl behavior, which returns with code 2 when
        # access to a file failed.
        retcode = OpensslCmsExitStatus.INPUT_FILE_READ_ERROR

    return retcode, err


def _process_communicate_handle_oserror(process, data, files):
    """Wrapper around process.communicate that checks for OSError."""

    try:
        output, err = process.communicate(data)
    except OSError as e:
        if e.errno != errno.EPIPE:
            raise
        # OSError with EPIPE only occurs with Python 2.6.x/old 2.7.x
        # http://bugs.python.org/issue10963

        # The quick exit is typically caused by the openssl command not being
        # able to read an input file, so check ourselves if can't read a file.
        retcode, err = _check_files_accessible(files)
        if process.stderr:
            msg = process.stderr.read()
            err = err + msg.decode('utf-8')
        output = ''
    else:
        retcode = process.poll()
        if err is not None:
            err = err.decode('utf-8')

    return output, err, retcode


def _encoding_for_form(inform):
    if inform == PKI_ASN1_FORM:
        encoding = 'UTF-8'
    elif inform == PKIZ_CMS_FORM:
        encoding = 'hex'
    else:
        raise ValueError(
            _('"inform" must be one of: %s') % ','.join((PKI_ASN1_FORM,
                                                         PKIZ_CMS_FORM)))

    return encoding


def cms_verify(formatted, signing_cert_file_name, ca_file_name,
               inform=PKI_ASN1_FORM):
    """Verifies the signature of the contents IAW CMS syntax.

    :raises subprocess.CalledProcessError:
    :raises keystoneclient.exceptions.CertificateConfigError: if certificate
                                                              is not configured
                                                              properly.
    """
    _ensure_subprocess()
    if isinstance(formatted, six.string_types):
        data = bytearray(formatted, _encoding_for_form(inform))
    else:
        data = formatted
    process = subprocess.Popen(['openssl', 'cms', '-verify',
                                '-certfile', signing_cert_file_name,
                                '-CAfile', ca_file_name,
                                '-inform', 'PEM',
                                '-nosmimecap', '-nodetach',
                                '-nocerts', '-noattr'],
                               stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               close_fds=True)
    output, err, retcode = _process_communicate_handle_oserror(
        process, data, (signing_cert_file_name, ca_file_name))

    # Do not log errors, as some happen in the positive thread
    # instead, catch them in the calling code and log them there.

    # When invoke the openssl with not exist file, return code 2
    # and error msg will be returned.
    # You can get more from
    # http://www.openssl.org/docs/apps/cms.html#EXIT_CODES
    #
    # $ openssl cms -verify -certfile not_exist_file -CAfile
    #       not_exist_file -inform PEM -nosmimecap -nodetach
    #       -nocerts -noattr
    # Error opening certificate file not_exist_file
    #
    if retcode == OpensslCmsExitStatus.INPUT_FILE_READ_ERROR:
{'fraction_non_alphanumeric': 0.07480802576170424, 'fraction_numerical': 0.00569729997522913, 'mean_word_length': 2.1040492055356226, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 6, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 18, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3838965', 'n_tokens_mistral': 3485, 'n_tokens_neox': 3341, 'n_words': 1076}