<commit_before>#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Name:         CommandLineParser.py
# Purpose:      Command line parsing utilities for SSLyze.
#
# Author:       aaron, alban
#
# Copyright:    2012 SSLyze developers
#
#   SSLyze 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.
#
#   SSLyze 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 SSLyze.  If not, see <http://www.gnu.org/licenses/>.
#-------------------------------------------------------------------------------

from optparse import OptionParser, OptionGroup
from urlparse import urlparse

# Client cert/key checking
from nassl.SslClient import SslClient
from nassl import _nassl, SSL_FILETYPE_ASN1, SSL_FILETYPE_PEM


class CommandLineParsingError(Exception):

    PARSING_ERROR_FORMAT = '  Command line error: {0}\n  Use -h for help.'

    def get_error_msg(self):
        return self.PARSING_ERROR_FORMAT.format(self)


class CommandLineParser():

    # Defines what --regular means
    REGULAR_CMD = ['sslv2', 'sslv3', 'tlsv1', 'tlsv1_1', 'tlsv1_2', 'reneg',
                   'resum', 'certinfo', 'http_get', 'hide_rejected_ciphers',
                   'compression', 'heartbleed']
    SSLYZE_USAGE = 'usage: %prog [options] target1.com target2.com:443 etc...'

    # StartTLS options
    START_TLS_PROTS = ['smtp', 'xmpp', 'pop3', 'ftp', 'imap', 'ldap', 'rdp', 'auto']
    START_TLS_USAGE = 'STARTTLS should be one of: ' + str(START_TLS_PROTS) +  \
        '. The \'auto\' option will cause SSLyze to deduce the protocol' + \
        ' (ftp, imap, etc.) from the supplied port number, for each target servers.'

    # Default values
    DEFAULT_RETRY_ATTEMPTS = 4
    DEFAULT_TIMEOUT = 5


    def __init__(self, available_plugins, sslyze_version):
        """
        Generates SSLyze's command line parser.
        """

        self._parser = OptionParser(version=sslyze_version,
                                    usage=self.SSLYZE_USAGE)

        # Add generic command line options to the parser
        self._add_default_options()

        # Add plugin-specific options to the parser
        self._add_plugin_options(available_plugins)

        # Add the --regular command line parameter as a shortcut if possible
        regular_help = 'Regular HTTPS scan; shortcut for'
        for cmd in self.REGULAR_CMD:
            regular_help += ' --' + cmd
            if cmd == 'certinfo': # gah
                regular_help += '=basic'

            if not self._parser.has_option('--' + cmd):
                return

        self._parser.add_option('--regular', action="store_true", dest=None,
                    help=regular_help)


    def parse_command_line(self):
        """
        Parses the command line used to launch SSLyze.
        """

        (args_command_list, args_target_list) = self._parser.parse_args()

        # Handle the --targets_in command line and fill args_target_list
        if args_command_list.targets_in:
            if args_target_list:
                raise CommandLineParsingError("Cannot use --targets_list and specify targets within the command line.")

            try: # Read targets from a file
                with open(args_command_list.targets_in) as f:
                    for target in f.readlines():
                        if target.strip(): # Ignore empty lines
                            if not target.startswith('#'): # Ignore comment lines
                                args_target_list.append(target.strip())
            except IOError:
                raise CommandLineParsingError("Can't read targets from input file '%s'." %  args_command_list.targets_in)

        if not args_target_list:
            raise CommandLineParsingError('No targets to scan.')

        # Handle the --regular command line parameter as a shortcut
        if self._parser.has_option('--regular'):
            if getattr(args_command_list, 'regular'):
                setattr(args_command_list, 'regular', False)
                for cmd in self.REGULAR_CMD:
                    setattr(args_command_list, cmd, True)
                setattr(args_command_list, 'certinfo', 'basic') # Special case

        # Create the shared_settings object from looking at the command line
        shared_settings = self._process_parsing_results(args_command_list)

        return args_command_list, args_target_list, shared_settings


    def _add_default_options(self):
        """
        Adds default command line options to the parser.
        """

        # Client certificate options
        clientcert_group = OptionGroup(self._parser,
            'Client certificate support', '')
        clientcert_group.add_option(
            '--cert',
            help='Client certificate filename.',
            dest='cert')
        clientcert_group.add_option(
            '--certform',
            help= 'Client certificate format. DER or PEM (default).',
            dest='certform',
            default='PEM')
        clientcert_group.add_option(<commit_msg>Allow user to override certinfo on the command line when using --regular<commit_after>#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Name:         CommandLineParser.py
# Purpose:      Command line parsing utilities for SSLyze.
#
# Author:       aaron, alban
#
# Copyright:    2012 SSLyze developers
#
#   SSLyze 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.
#
#   SSLyze 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 SSLyze.  If not, see <http://www.gnu.org/licenses/>.
#-------------------------------------------------------------------------------

from optparse import OptionParser, OptionGroup
from urlparse import urlparse

# Client cert/key checking
from nassl.SslClient import SslClient
from nassl import _nassl, SSL_FILETYPE_ASN1, SSL_FILETYPE_PEM


class CommandLineParsingError(Exception):

    PARSING_ERROR_FORMAT = '  Command line error: {0}\n  Use -h for help.'

    def get_error_msg(self):
        return self.PARSING_ERROR_FORMAT.format(self)


class CommandLineParser():

    # Defines what --regular means
    REGULAR_CMD = ['sslv2', 'sslv3', 'tlsv1', 'tlsv1_1', 'tlsv1_2', 'reneg',
                   'resum', 'certinfo', 'http_get', 'hide_rejected_ciphers',
                   'compression', 'heartbleed']
    SSLYZE_USAGE = 'usage: %prog [options] target1.com target2.com:443 etc...'

    # StartTLS options
    START_TLS_PROTS = ['smtp', 'xmpp', 'pop3', 'ftp', 'imap', 'ldap', 'rdp', 'auto']
    START_TLS_USAGE = 'STARTTLS should be one of: ' + str(START_TLS_PROTS) +  \
        '. The \'auto\' option will cause SSLyze to deduce the protocol' + \
        ' (ftp, imap, etc.) from the supplied port number, for each target servers.'

    # Default values
    DEFAULT_RETRY_ATTEMPTS = 4
    DEFAULT_TIMEOUT = 5


    def __init__(self, available_plugins, sslyze_version):
        """
        Generates SSLyze's command line parser.
        """

        self._parser = OptionParser(version=sslyze_version,
                                    usage=self.SSLYZE_USAGE)

        # Add generic command line options to the parser
        self._add_default_options()

        # Add plugin-specific options to the parser
        self._add_plugin_options(available_plugins)

        # Add the --regular command line parameter as a shortcut if possible
        regular_help = 'Regular HTTPS scan; shortcut for'
        for cmd in self.REGULAR_CMD:
            regular_help += ' --' + cmd
            if cmd == 'certinfo': # gah
                regular_help += '=basic'

            if not self._parser.has_option('--' + cmd):
                return

        self._parser.add_option('--regular', action="store_true", dest=None,
                    help=regular_help)


    def parse_command_line(self):
        """
        Parses the command line used to launch SSLyze.
        """

        (args_command_list, args_target_list) = self._parser.parse_args()

        # Handle the --targets_in command line and fill args_target_list
        if args_command_list.targets_in:
            if args_target_list:
                raise CommandLineParsingError("Cannot use --targets_list and specify targets within the command line.")

            try: # Read targets from a file
                with open(args_command_list.targets_in) as f:
                    for target in f.readlines():
                        if target.strip(): # Ignore empty lines
                            if not target.startswith('#'): # Ignore comment lines
                                args_target_list.append(target.strip())
            except IOError:
                raise CommandLineParsingError("Can't read targets from input file '%s'." %  args_command_list.targets_in)

        if not args_target_list:
            raise CommandLineParsingError('No targets to scan.')

        # Handle the --regular command line parameter as a shortcut
        if self._parser.has_option('--regular'):
            if getattr(args_command_list, 'regular'):
                setattr(args_command_list, 'regular', False)
                for cmd in self.REGULAR_CMD:
                    if cmd=="certinfo":
                        # Allow user to override certinfo when using --regular
                        if getattr(args_command_list, 'certinfo') is None:
                            setattr(args_command_list, 'certinfo', 'basic') # Special case
                    else: 
                        setattr(args_command_list, cmd, True)

        # Create the shared_settings object from looking at the command line
        shared_settings = self._process_parsing_results(args_command_list)
        return args_command_list, args_target_list, shared_settings


    def _add_default_options(self):
        """
        Adds default command line options to the parser.
        """

        # Client certificate options
        clientcert_group = OptionGroup(self._parser,
            'Client certificate support', '')
        clientcert_group.add_option(
            '--cert',
            help='Client certificate filename.',
            dest='cert')
        clientcert_group.add_option(
            '--certform',
            help= 'Client certificate format. DER or PEM (default).',
            dest='certform',
            default='PEM')
        clientcert_group.add_option(
{'fraction_non_alphanumeric': 0.1126122122478002, 'fraction_numerical': 0.003910763487689983, 'mean_word_length': 2.128162357520156, 'pattern_counts': {'":': 1, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3596998', 'n_tokens_mistral': 3093, 'n_tokens_neox': 2938, 'n_words': 930}