Esempio n. 1
0
from ssl import SSLContext, PROTOCOL_TLSv1_2 , CERT_REQUIRED
from cassandra.auth import PlainTextAuthProvider
from cassandra.cluster import Cluster, ExecutionProfile, EXEC_PROFILE_DEFAULT, ConsistencyLevel
from google.transit import gtfs_realtime_pb2
import requests
from zipfile import ZipFile
from io import BytesIO
import os

def lambda_handler(event, context):
	username = os.environ['CASSANDRA_USER']
	password = os.environ['CASSANDRA_PWD']
    response = requests.get('https://romamobilita.it/sites/default/files/rome_static_gtfs.zip').content
    zipfile = ZipFile(BytesIO(response))
    ssl_context = SSLContext(PROTOCOL_TLSv1_2 )
    auth_provider = PlainTextAuthProvider(username=username, password=password)
    cluster = Cluster(['cassandra.us-east-1.amazonaws.com'], ssl_context=ssl_context, auth_provider=auth_provider, port=9142)
    session = cluster.connect()
    stmt = session.prepare("INSERT INTO static_files.lines_correspondence (route_id, actual_line_name) VALUES (?, ?)")
    execution_profile = session.execution_profile_clone_update(session.get_execution_profile(EXEC_PROFILE_DEFAULT))
    execution_profile.consistency_level = ConsistencyLevel.LOCAL_QUORUM
    with zipfile.open('routes.txt', 'r') as myfile:
        #print(myfile.read())
        content = myfile.readlines()
        for elem in content:
            elemList=elem.decode().split(sep=',')
            elemList[2] = elemList[2].replace('"','')
            session.execute(stmt, (elemList[0],elemList[2]), execution_profile=execution_profile)

    
def main():
    import argparse
    ap = argparse.ArgumentParser()
    ap.add_argument('-d', '--algod', default=None, help='algorand data dir')
    ap.add_argument('--algod-net', default=None, help='algod host:port')
    ap.add_argument('--algod-token', default=None, help='algod token')
    ap.add_argument('--genesis', default=None, help='path to genesis.json')
    ap.add_argument('--limit', default=None, type=int, help='debug limit number of accoutns to dump')
    ap.add_argument('--indexer', default=None, help='URL to indexer to fetch from')
    ap.add_argument('--indexer-token', default=None, help='indexer API token')
    ap.add_argument('--asset', default=None, help='filter on accounts possessing asset id')
    ap.add_argument('--mismatches', default=10, type=int, help='max number of mismatches to show details on (0 for no limit)')
    ap.add_argument('-q', '--quiet', default=False, action='store_true')
    ap.add_argument('--verbose', default=False, action='store_true')
    ap.add_argument('--accounts', help='comma separated list of accounts to test')
    ap.add_argument('--ssl-no-validate', default=False, action='store_true')
    ap.add_argument('--threads', default=4, type=int, help='number of request-compare threads to run')
    ap.add_argument('--gtaddr', default=None, help='fetch accounts after this addr')
    ap.add_argument('--shard', default=None, help='a/b for a in [1..b]')
    args = ap.parse_args()

    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)

    if not args.indexer:
        logger.error("need --indexer to specify root url of indexer api")
        return 1
    if (not args.algod) and ((not args.algod_net) or (not args.algod_token)):
        logger.error("need --algod datadir or --algod-net and --algod-token")
        return 1
    if args.ssl_no_validate:
        global ssl_no_validate
        ssl_no_validate = SSLContext() # empty context doesn't validate; use for self-signed certs
    if args.gtaddr and args.shard:
        logger.error('--gtaddr and --shard are incompatible')
        return 1
    out = sys.stdout
    err = sys.stderr

    i2a_checker = check_from_algod(args)
    retval = 0
    i2a_checker.summary()
    mismatches = i2a_checker.mismatches
    if args.mismatches and len(mismatches) > args.mismatches:
        mismatches = mismatches[:args.mismatches]
    for addr, msg in mismatches:
        niceaddr = algosdk.encoding.encode_address(addr)
        if addr in (reward_addr, fee_addr):
            logger.debug('skip %s', niceaddr)
            # we know accounting for the special addrs is different
            continue
        retval = 1
        xaddr = base64.b16encode(addr).decode().lower()
        err.write('\n{} \'\\x{}\'\n\t{}\n'.format(niceaddr, xaddr, msg))
        tcount = 0
        tmore = 0
        for txn in indexerAccountTxns(args.indexer, addr, limit=30, token=args.indexer_token):
            if tcount > 10:
                tmore += 1
                continue
            tcount += 1
            sender = txn.pop('sender')
            cround = txn.pop('confirmed-round')
            intra = txn.pop('intra-round-offset')
            parts = ['{}:{}'.format(cround, intra), 's={}'.format(sender)]
            pay = txn.get('payment-transaction', None)
            if pay:
                receiver = pay.pop('receiver', None)
                closeto = pay.pop('close-remainder-to', None)
            else:
                receiver = None
                closeto = None
            axfer = txn.get('asset-transfer-transaction', None)
            if axfer is not None:
                asnd = axfer.pop('sender', None)
                arcv = axfer.pop('receiver', None)
                aclose = axfer.pop('close-to', None)
            else:
                asnd = None
                arcv = None
                aclose = None
            if asnd:
                parts.append('as={}'.format(asnd))
            if receiver:
                parts.append('r={}'.format(receiver))
            if closeto:
                parts.append('c={}'.format(closeto))
            if arcv:
                parts.append('ar={}'.format(arcv))
            if aclose:
                parts.append('ac={}'.format(aclose))
            # everything else
            parts.append(json.dumps(txn))
            err.write(' '.join(parts) + '\n')
        if tmore:
            err.write('... and {} more\n'.format(tmore))
    if retval == 0:
        logger.info('validate_accounting OK')
    return retval
Esempio n. 3
0
def create_urllib3_context(ssl_version=None,
                           cert_reqs=None,
                           options=None,
                           ciphers=None):
    """All arguments have the same meaning as ``ssl_wrap_socket``.

    By default, this function does a lot of the same work that
    ``ssl.create_default_context`` does on Python 3.4+. It:

    - Disables SSLv2, SSLv3, and compression
    - Sets a restricted set of server ciphers

    If you wish to enable SSLv3, you can do::

        from urllib3.util import ssl_
        context = ssl_.create_urllib3_context()
        context.options &= ~ssl_.OP_NO_SSLv3

    You can do the same to enable compression (substituting ``COMPRESSION``
    for ``SSLv3`` in the last line above).

    :param ssl_version:
        The desired protocol version to use. This will default to
        PROTOCOL_SSLv23 which will negotiate the highest protocol that both
        the server and your installation of OpenSSL support.
    :param cert_reqs:
        Whether to require the certificate verification. This defaults to
        ``ssl.CERT_REQUIRED``.
    :param options:
        Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
        ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.
    :param ciphers:
        Which cipher suites to allow the server to select.
    :returns:
        Constructed SSLContext object with specified options
    :rtype: SSLContext
    """
    context = SSLContext(ssl_version or PROTOCOL_TLS)

    context.set_ciphers(ciphers or DEFAULT_CIPHERS)

    # Setting the default here, as we may have no ssl module on import
    cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs

    if options is None:
        options = 0
        # SSLv2 is easily broken and is considered harmful and dangerous
        options |= OP_NO_SSLv2
        # SSLv3 has several problems and is now dangerous
        options |= OP_NO_SSLv3
        # Disable compression to prevent CRIME attacks for OpenSSL 1.0+
        # (issue #309)
        options |= OP_NO_COMPRESSION

    context.options |= options

    context.verify_mode = cert_reqs
    if getattr(context, 'check_hostname',
               None) is not None:  # Platform-specific: Python 3.2
        # We do our own verification, including fingerprints and alternative
        # hostnames. So disable it here
        context.check_hostname = False
    return context
Esempio n. 4
0
def open_url(url,
             data=None,
             headers=None,
             method=None,
             use_proxy=True,
             force=False,
             last_mod_time=None,
             timeout=10,
             validate_certs=True,
             url_username=None,
             url_password=None,
             http_agent=None,
             force_basic_auth=False,
             follow_redirects='urllib2'):
    '''
    Fetches a file from an HTTP/FTP server using urllib2
    '''
    handlers = []
    ssl_handler = maybe_add_ssl_handler(url, validate_certs)
    if ssl_handler:
        handlers.append(ssl_handler)

    # FIXME: change the following to use the generic_urlparse function
    #        to remove the indexed references for 'parsed'
    parsed = urlparse.urlparse(url)
    if parsed[0] != 'ftp':
        username = url_username

        if headers is None:
            headers = {}

        if username:
            password = url_password
            netloc = parsed[1]
        elif '@' in parsed[1]:
            credentials, netloc = parsed[1].split('@', 1)
            if ':' in credentials:
                username, password = credentials.split(':', 1)
            else:
                username = credentials
                password = ''

            parsed = list(parsed)
            parsed[1] = netloc

            # reconstruct url without credentials
            url = urlparse.urlunparse(parsed)

        if username and not force_basic_auth:
            passman = urllib2.HTTPPasswordMgrWithDefaultRealm()

            # this creates a password manager
            passman.add_password(None, netloc, username, password)

            # because we have put None at the start it will always
            # use this username/password combination for  urls
            # for which `theurl` is a super-url
            authhandler = urllib2.HTTPBasicAuthHandler(passman)

            # create the AuthHandler
            handlers.append(authhandler)

        elif username and force_basic_auth:
            headers["Authorization"] = basic_auth_header(username, password)

        else:
            try:
                rc = netrc.netrc(os.environ.get('NETRC'))
                login = rc.authenticators(parsed[1])
            except IOError:
                login = None

            if login:
                username, _, password = login
                if username and password:
                    headers["Authorization"] = basic_auth_header(
                        username, password)

    if not use_proxy:
        proxyhandler = urllib2.ProxyHandler({})
        handlers.append(proxyhandler)

    # pre-2.6 versions of python cannot use the custom https
    # handler, since the socket class is lacking create_connection.
    # Some python builds lack HTTPS support.
    if hasattr(socket, 'create_connection') and CustomHTTPSHandler:
        handlers.append(CustomHTTPSHandler)

    handlers.append(RedirectHandlerFactory(follow_redirects, validate_certs))

    opener = urllib2.build_opener(*handlers)
    urllib2.install_opener(opener)

    if method:
        if method.upper() not in ('OPTIONS', 'GET', 'HEAD', 'POST', 'PUT',
                                  'DELETE', 'TRACE', 'CONNECT', 'PATCH'):
            raise ConnectionError('invalid HTTP request method; %s' %
                                  method.upper())
        request = RequestWithMethod(url, method.upper(), data)
    else:
        request = urllib2.Request(url, data)

    # add the custom agent header, to help prevent issues
    # with sites that block the default urllib agent string
    request.add_header('User-agent', http_agent)

    # if we're ok with getting a 304, set the timestamp in the
    # header, otherwise make sure we don't get a cached copy
    if last_mod_time and not force:
        tstamp = last_mod_time.strftime('%a, %d %b %Y %H:%M:%S +0000')
        request.add_header('If-Modified-Since', tstamp)
    else:
        request.add_header('cache-control', 'no-cache')

    # user defined headers now, which may override things we've set above
    if headers:
        if not isinstance(headers, dict):
            raise ValueError("headers provided to fetch_url() must be a dict")
        for header in headers:
            request.add_header(header, headers[header])

    urlopen_args = [request, None]
    if sys.version_info >= (2, 6, 0):
        # urlopen in python prior to 2.6.0 did not
        # have a timeout parameter
        urlopen_args.append(timeout)

    if HAS_SSLCONTEXT and not validate_certs:
        # In 2.7.9, the default context validates certificates
        context = SSLContext(ssl.PROTOCOL_SSLv23)
        context.options |= ssl.OP_NO_SSLv2
        context.options |= ssl.OP_NO_SSLv3
        context.verify_mode = ssl.CERT_NONE
        context.check_hostname = False
        urlopen_args += (None, None, None, context)

    r = urllib2.urlopen(*urlopen_args)
    return r
Esempio n. 5
0
def create_urllib3_context(ssl_version=None,
                           cert_reqs=None,
                           options=None,
                           ciphers=None):
    """All arguments have the same meaning as ``ssl_wrap_socket``.

    By default, this function does a lot of the same work that
    ``ssl.create_default_context`` does on Python 3.4+. It:

    - Disables SSLv2, SSLv3, and compression
    - Sets a restricted set of server ciphers

    If you wish to enable SSLv3, you can do::

        from urllib3.util import ssl_
        context = ssl_.create_urllib3_context()
        context.options &= ~ssl_.OP_NO_SSLv3

    You can do the same to enable compression (substituting ``COMPRESSION``
    for ``SSLv3`` in the last line above).

    :param ssl_version:
        The desired protocol version to use. This will default to
        PROTOCOL_SSLv23 which will negotiate the highest protocol that both
        the server and your installation of OpenSSL support.
    :param cert_reqs:
        Whether to require the certificate verification. This defaults to
        ``ssl.CERT_REQUIRED``.
    :param options:
        Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
        ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``.
    :param ciphers:
        Which cipher suites to allow the server to select. Defaults to either system configured
        ciphers if OpenSSL 1.1.1+, otherwise uses a secure default set of ciphers.
    :returns:
        Constructed SSLContext object with specified options
    :rtype: SSLContext
    """
    context = SSLContext(ssl_version or PROTOCOL_TLS)

    # Unless we're given ciphers defer to either system ciphers in
    # the case of OpenSSL 1.1.1+ or use our own secure default ciphers.
    if ciphers is not None or not USE_DEFAULT_SSLCONTEXT_CIPHERS:
        context.set_ciphers(ciphers or DEFAULT_CIPHERS)

    # Setting the default here, as we may have no ssl module on import
    cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs

    if options is None:
        options = 0
        # SSLv2 is easily broken and is considered harmful and dangerous
        options |= OP_NO_SSLv2
        # SSLv3 has several problems and is now dangerous
        options |= OP_NO_SSLv3
        # Disable compression to prevent CRIME attacks for OpenSSL 1.0+
        # (issue #309)
        options |= OP_NO_COMPRESSION
        # TLSv1.2 only. Unless set explicitly, do not request tickets.
        # This may save some bandwidth on wire, and although the ticket is encrypted,
        # there is a risk associated with it being on wire,
        # if the server is not rotating its ticketing keys properly.
        options |= OP_NO_TICKET

    context.options |= options

    # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is
    # necessary for conditional client cert authentication with TLS 1.3.
    # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older
    # versions of Python.  We only enable on Python 3.7.4+ or if certificate
    # verification is enabled to work around Python issue #37428
    # See: https://bugs.python.org/issue37428
    if (cert_reqs == ssl.CERT_REQUIRED or sys.version_info >=
        (3, 7, 4)) and getattr(context, "post_handshake_auth",
                               None) is not None:
        context.post_handshake_auth = True

    context.verify_mode = cert_reqs
    # We do our own verification, including fingerprints and alternative
    # hostnames. So disable it here
    context.check_hostname = False

    # Enable logging of TLS session keys via defacto standard environment variable
    # 'SSLKEYLOGFILE', if the feature is available (Python 3.8+). Skip empty values.
    if hasattr(context, "keylog_filename"):
        sslkeylogfile = os.environ.get("SSLKEYLOGFILE")
        if sslkeylogfile:
            context.keylog_filename = sslkeylogfile

    return context
Esempio n. 6
0
def create_ssl_context(ssl_version=None, cert_reqs=None, options=None, ciphers=None):
    """All arguments have the same meaning as ``ssl_wrap_socket``.

    By default, this function does a lot of the same work that
    ``ssl.create_default_context`` does on Python 3.4+. It:

    - Disables SSLv2, SSLv3, and compression
    - Sets a restricted set of server ciphers

    If you wish to enable SSLv3, you can do::

        from hip.util import ssl_
        context = ssl_.create_ssl_context()
        context.options &= ~ssl_.OP_NO_SSLv3

    You can do the same to enable compression (substituting ``COMPRESSION``
    for ``SSLv3`` in the last line above).

    :param ssl_version:
        The desired protocol version to use. This will default to
        PROTOCOL_SSLv23 which will negotiate the highest protocol that both
        the server and your installation of OpenSSL support.
    :param cert_reqs:
        Whether to require the certificate verification. This defaults to
        ``ssl.CERT_REQUIRED``.
    :param options:
        Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
        ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.
    :param ciphers:
        Which cipher suites to allow the server to select.
    :returns:
        Constructed SSLContext object with specified options
    :rtype: SSLContext
    """
    context = SSLContext(ssl_version or PROTOCOL_TLS)

    context.set_ciphers(ciphers or DEFAULT_CIPHERS)

    # Setting the default here, as we may have no ssl module on import
    cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs

    if options is None:
        options = 0
        # SSLv2 is easily broken and is considered harmful and dangerous
        options |= OP_NO_SSLv2
        # SSLv3 has several problems and is now dangerous
        options |= OP_NO_SSLv3
        # Disable compression to prevent CRIME attacks for OpenSSL 1.0+
        # (issue #309)
        options |= OP_NO_COMPRESSION

    context.options |= options

    # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is
    # necessary for conditional client cert authentication with TLS 1.3.
    # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older
    # versions of Python.  We only enable on Python 3.7.4+ or if certificate
    # verification is enabled to work around Python issue #37428
    # See: https://bugs.python.org/issue37428
    if (cert_reqs == ssl.CERT_REQUIRED or sys.version_info >= (3, 7, 4)) and getattr(
        context, "post_handshake_auth", None
    ) is not None:
        context.post_handshake_auth = True

    context.verify_mode = cert_reqs
    if (
        getattr(context, "check_hostname", None) is not None
    ):  # Platform-specific: Python 3.2
        # We do our own verification, including fingerprints and alternative
        # hostnames. So disable it here
        context.check_hostname = False
    return context
Esempio n. 7
0
# Route that will process the file upload
@APP.route('/add/send', methods=['POST'])
@requires_auth
def send(current_user=None):
    pubkey = request.files['file']
    username = request.form['username']
    try:
        req = put(APP.config['CASSH_URL'] + '/client' +
            auth_url(current_user['name'], password=current_user['password'], \
                prefix='?username=%s' % username), data=pubkey, verify=False)
    except ConnectionError:
        return Response('Connection error : %s' % APP.config['CASSH_URL'])
    if 'Error' in req.text:
        return Response(req.text)
    return redirect('/status')


@APP.errorhandler(404)
def page_not_found(_):
    """ Display error page """
    return render_template('404.html'), 404


if __name__ == '__main__':
    CONTEXT = SSLContext(PROTOCOL_TLSv1_2)
    CONTEXT.load_cert_chain(APP.config['SSL_PUB_KEY'],
                            APP.config['SSL_PRIV_KEY'])
    PORT = int(getenv('PORT', 443))
    APP.run(debug=True, host='0.0.0.0', port=PORT, ssl_context=CONTEXT)
Esempio n. 8
0
def main():
    # initialize variables used through the main function
    exitcode = 1
    use_proxy = True
    proxy_protocol = ''
    proxy_url = ''
    base_url = ''
    ini_file = ''
    extract_path = ''

    # read configuration file name if supplied as command line argument
    if len(argv) > 1:
        cfg_file_name = str(argv[1])
    else:
        cfg_file_name = 'uvlinux_updater.cfg'

    # try to parse configuration, otherwise use default settings
    try:
        config = ConfigParser(interpolation=None)
        config.read(cfg_file_name)
        use_proxy = config.getboolean('Config', 'use_proxy')
        if use_proxy:
            proxy_protocol = config.get('Config', 'proxy_protocol')
            proxy_url = config.get('Config', 'proxy_url')
        base_url = config.get('Config', 'base_url')
        ini_file = config.get('Config', 'ini_file')
        extract_path = config.get('Config', 'extract_path')
        print('Successfully read settings from configfile ' + cfg_file_name)
    except Exception as e:
        print(e)
        print('Failed to read settings from configfile ' + cfg_file_name +
              '. Using default settings.')
        use_proxy = True
        proxy_protocol = 'https'
        proxy_url = 'http://10.0.14.121:3128'
        base_url = 'https://update.nai.com/products/commonupdater'
        ini_file = 'avvdat.ini'
        extract_path = '/usr/local/uvscan/'
        pass

    # set up handler for our http(s) proxy
    proxy_handler = ur.ProxyHandler()
    if use_proxy:
        proxy_handler = ur.ProxyHandler({proxy_protocol: proxy_url})

    # set up handler to allow only secure protocols, but do not verify hostname against certificate, as it does not match ('update.nai.com' vs. 'a248.e.akamai.net')
    ssl_context = SSLContext(PROTOCOL_SSLv23)
    ssl_context.options |= OP_NO_TLSv1
    ssl_context.options |= OP_NO_SSLv3
    ssl_context.options |= OP_NO_SSLv2
    ssl_context.options |= OP_NO_COMPRESSION
    ssl_context.check_hostname = False

    # pull filename of most current archive (e.g. avvdat-8737.dat) & md5 hash from ini file on McAfee Server
    filename, hash_md5, filepath = getcurrent_filename_and_hash(
        proxy_handler, ssl_context, base_url + '/' + ini_file)

    # clean up returned values/types if needed (Python 2 Backport of Python 3 configparser module quirk)
    if type(filename) is list:
        filename = str(filename[0])
    if type(hash_md5) is list:
        hash_md5 = str(hash_md5[0])

    # check whether getcurrent_filename_and_hash() was successful
    if filename == '':
        print("Error, could not get current filename")
    else:
        # download current archive (e.g. avvdat-8737.dat) from McAfee Server
        tmp_file = download_archive(base_url + filepath, filename,
                                    proxy_handler, ssl_context)

        # prepare path archive will be extracted to
        #dest_dir = path.join(extract_path)

        # only extract if downloaded and actual md5 matches
        if md5match(tmp_file, hash_md5):

            print('MD5 hash matches, extracting ' + str(tmp_file) + ' to ' +
                  extract_path)
            try:
                unzip(tmp_file, extract_path)
            except Exception as e:
                print(e)
                pass
            else:
                print('Extracted successfully into ' + extract_path)
                exitcode = 0
        else:
            print('MD5 hash does not match!')

        # remove downloaded archive in either case
        print('Removing downloaded archive ' + str(tmp_file))
        try:
            remove(tmp_file)
        except Exception as e:
            print(e)

    return (exitcode)
Esempio n. 9
0
from ssl import SSLContext, PROTOCOL_SSLv23, CERT_NONE
from psphere.client import Client

context = SSLContext(PROTOCOL_SSLv23)
context.verify_mode = CERT_NONE
test_client = Client("192.168.0.14", "root", "password", sslcontext=context)
print(test_client.si.CurrentTime())
test_client.logout()
Esempio n. 10
0
        conn_output = "{} {}".format("Number of clients connected : ",
                                     connected_clients)
        print(conn_output)
    else:
        conn_output = "can't connect, max number of clients reached"
    return conn_output


#global variables
LOCALHOST = "127.0.0.1"
PORT = 3443
MAX_CLIENTS = 100
connected_clients = 0
# PROTOCOL_TLS_CLIENT requires valid certificate chain and hostname
# SSLContext helps manage settings and certificates which can be inherited by SSL sockets created through SSLContext.wrap_socket()
context = SSLContext(PROTOCOL_TLS_SERVER)
context.load_cert_chain('certificates/cert.pem', 'certificates/key.pem')
#AF_INET means ipv4, as opposed to ipv6 with AF_INET6
#SOCK_STREAM means it will be a TCP socket
server = socket(AF_INET, SOCK_STREAM)
server.bind((LOCALHOST, PORT))
#listen for incoming connections. We can only handle one connection at a given time,
#allows for some sort of a queue. If someone attempts to connect while the queue is full, they will be denied.
server.listen(5)
tls = context.wrap_socket(server, server_side=True)
print("Server started")
print("Waiting for client request")
lock = threading.Lock()
if __name__ == "__main__":
    conn_params()
    while True:
Esempio n. 11
0
    daemon_threads = True
    # much faster rebinding
    allow_reuse_address = True


def handle(self):
    data = self.request[0]
    serv = self.request[1]
    addr = self.client_address
    transfer(data, addr, serv)


if __name__ == "__main__":
    print('init')

    ENV['TLS'] = SSLContext(PROTOCOL_TLS)
    ENV['TLS'].verify_mode = CERT_REQUIRED
    ENV['TLS'].check_hostname = True
    ENV['TLS'].load_default_certs()
    #tlsctx.load_verify_locations(cadata=cadata)

    # Cloudflare
    ENV['REMOTE_SERVERS'].append(('1.1.1.1', '1.1.1.1', 853))
    ENV['REMOTE_SERVERS'].append(('1.0.0.1', '1.0.0.1', 853))
    # Quad9 (Packet Clearing House and IBM)
    ENV['REMOTE_SERVERS'].append(('dns.quad9.net', '9.9.9.9', 853))
    ENV['REMOTE_SERVERS'].append(('dns.quad9.net', '149.112.112.112', 853))

    ENV['REMOTE_SERVERS_LENGTH'] = len(ENV['REMOTE_SERVERS'])

    with ThreadUDPServer((ENV['SERVER_IP'], ENV['SERVER_PORT']),
Esempio n. 12
0
 def get_ssl_context(*args):
     """Create and return an SSLContext object."""
     certfile, keyfile, passphrase, ca_certs, cert_reqs, crlfile = args
     # Note PROTOCOL_SSLv23 is about the most misleading name imaginable.
     # This configures the server and client to negotiate the
     # highest protocol version they both support. A very good thing.
     ctx = SSLContext(ssl.PROTOCOL_SSLv23)
     if hasattr(ctx, "options"):
         # Explicitly disable SSLv2, SSLv3 and TLS compression. Note that
         # up to date versions of MongoDB 2.4 and above already disable
         # SSLv2 and SSLv3, python disables SSLv2 by default in >= 2.7.7
         # and >= 3.3.4 and SSLv3 in >= 3.4.3. There is no way for us to do
         # any of this explicitly for python 2.6 or 2.7 before 2.7.9.
         ctx.options |= getattr(ssl, "OP_NO_SSLv2", 0)
         ctx.options |= getattr(ssl, "OP_NO_SSLv3", 0)
         # OpenSSL >= 1.0.0
         ctx.options |= getattr(ssl, "OP_NO_COMPRESSION", 0)
     if certfile is not None:
         try:
             if passphrase is not None:
                 vi = sys.version_info
                 # Since python just added a new parameter to an existing method
                 # this seems to be about the best we can do.
                 if (vi[0] == 2 and vi < (2, 7, 9) or vi[0] == 3 and vi <
                     (3, 3)):
                     raise ConfigurationError(
                         "Support for ssl_pem_passphrase requires "
                         "python 2.7.9+ (pypy 2.5.1+) or 3.3+")
                 ctx.load_cert_chain(certfile, keyfile, passphrase)
             else:
                 ctx.load_cert_chain(certfile, keyfile)
         except ssl.SSLError as exc:
             raise ConfigurationError(
                 "Private key doesn't match certificate: %s" % (exc, ))
     if crlfile is not None:
         if not hasattr(ctx, "verify_flags"):
             raise ConfigurationError(
                 "Support for ssl_crlfile requires "
                 "python 2.7.9+ (pypy 2.5.1+) or  3.4+")
         # Match the server's behavior.
         ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF
         ctx.load_verify_locations(crlfile)
     if ca_certs is not None:
         ctx.load_verify_locations(ca_certs)
     elif cert_reqs != ssl.CERT_NONE:
         # CPython >= 2.7.9 or >= 3.4.0, pypy >= 2.5.1
         if hasattr(ctx, "load_default_certs"):
             ctx.load_default_certs()
         # Python >= 3.2.0, useless on Windows.
         elif (sys.platform != "win32"
               and hasattr(ctx, "set_default_verify_paths")):
             ctx.set_default_verify_paths()
         elif sys.platform == "win32" and HAVE_WINCERTSTORE:
             with _WINCERTSLOCK:
                 if _WINCERTS is None:
                     _load_wincerts()
             ctx.load_verify_locations(_WINCERTS.name)
         elif HAVE_CERTIFI:
             ctx.load_verify_locations(certifi.where())
         else:
             raise ConfigurationError(
                 "`ssl_cert_reqs` is not ssl.CERT_NONE and no system "
                 "CA certificates could be loaded. `ssl_ca_certs` is "
                 "required.")
     ctx.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
     return ctx
Esempio n. 13
0
# ------------------
# Only for running this script here
import sys
from os.path import dirname

sys.path.insert(1, f"{dirname(__file__)}/../../..")
# ------------------

import logging

logging.basicConfig(level=logging.DEBUG)

# export SLACK_API_TOKEN=xoxb-***
# python3 integration_tests/samples/readme/proxy.py

import os
from slack_sdk.web import WebClient
from ssl import SSLContext

sslcert = SSLContext()
# pip3 install proxy.py
# proxy --port 9000 --log-level d
proxyinfo = "http://localhost:9000"

client = WebClient(token=os.environ["SLACK_API_TOKEN"],
                   ssl=sslcert,
                   proxy=proxyinfo)
response = client.chat_postMessage(channel="#random", text="Hello World!")
print(response)
Esempio n. 14
0
 def get_ssl_context(*args):
     """Create and return an SSLContext object."""
     (certfile,
      keyfile,
      passphrase,
      ca_certs,
      cert_reqs,
      crlfile,
      match_hostname) = args
     verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
     # Note PROTOCOL_SSLv23 is about the most misleading name imaginable.
     # This configures the server and client to negotiate the
     # highest protocol version they both support. A very good thing.
     # PROTOCOL_TLS_CLIENT was added in CPython 3.6, deprecating
     # PROTOCOL_SSLv23.
     ctx = SSLContext(
         getattr(ssl, "PROTOCOL_TLS_CLIENT", ssl.PROTOCOL_SSLv23))
     # SSLContext.check_hostname was added in CPython 2.7.9 and 3.4.
     # PROTOCOL_TLS_CLIENT (added in Python 3.6) enables it by default.
     if hasattr(ctx, "check_hostname"):
         if _PY37PLUS and verify_mode != ssl.CERT_NONE:
             # Python 3.7 uses OpenSSL's hostname matching implementation
             # making it the obvious version to start using this with.
             # Python 3.6 might have been a good version, but it suffers
             # from https://bugs.python.org/issue32185.
             # We'll use our bundled match_hostname for older Python
             # versions, which also supports IP address matching
             # with Python < 3.5.
             ctx.check_hostname = match_hostname
         else:
             ctx.check_hostname = False
     if hasattr(ctx, "options"):
         # Explicitly disable SSLv2, SSLv3 and TLS compression. Note that
         # up to date versions of MongoDB 2.4 and above already disable
         # SSLv2 and SSLv3, python disables SSLv2 by default in >= 2.7.7
         # and >= 3.3.4 and SSLv3 in >= 3.4.3. There is no way for us to do
         # any of this explicitly for python 2.7 before 2.7.9.
         ctx.options |= getattr(ssl, "OP_NO_SSLv2", 0)
         ctx.options |= getattr(ssl, "OP_NO_SSLv3", 0)
         # OpenSSL >= 1.0.0
         ctx.options |= getattr(ssl, "OP_NO_COMPRESSION", 0)
         # Python 3.7+ with OpenSSL >= 1.1.0h
         ctx.options |= getattr(ssl, "OP_NO_RENEGOTIATION", 0)
     if certfile is not None:
         try:
             if passphrase is not None:
                 vi = sys.version_info
                 # Since python just added a new parameter to an existing method
                 # this seems to be about the best we can do.
                 if (vi[0] == 2 and vi < (2, 7, 9) or
                         vi[0] == 3 and vi < (3, 3)):
                     raise ConfigurationError(
                         "Support for ssl_pem_passphrase requires "
                         "python 2.7.9+ (pypy 2.5.1+) or 3.3+")
                 ctx.load_cert_chain(certfile, keyfile, passphrase)
             else:
                 ctx.load_cert_chain(certfile, keyfile)
         except ssl.SSLError as exc:
             raise ConfigurationError(
                 "Private key doesn't match certificate: %s" % (exc,))
     if crlfile is not None:
         if not hasattr(ctx, "verify_flags"):
             raise ConfigurationError(
                 "Support for ssl_crlfile requires "
                 "python 2.7.9+ (pypy 2.5.1+) or  3.4+")
         # Match the server's behavior.
         ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF
         ctx.load_verify_locations(crlfile)
     if ca_certs is not None:
         ctx.load_verify_locations(ca_certs)
     elif cert_reqs != ssl.CERT_NONE:
         # CPython >= 2.7.9 or >= 3.4.0, pypy >= 2.5.1
         if hasattr(ctx, "load_default_certs"):
             ctx.load_default_certs()
         # Python >= 3.2.0, useless on Windows.
         elif (sys.platform != "win32" and
               hasattr(ctx, "set_default_verify_paths")):
             ctx.set_default_verify_paths()
         elif sys.platform == "win32" and HAVE_WINCERTSTORE:
             with _WINCERTSLOCK:
                 if _WINCERTS is None:
                     _load_wincerts()
             ctx.load_verify_locations(_WINCERTS.name)
         elif HAVE_CERTIFI:
             ctx.load_verify_locations(certifi.where())
         else:
             raise ConfigurationError(
                 "`ssl_cert_reqs` is not ssl.CERT_NONE and no system "
                 "CA certificates could be loaded. `ssl_ca_certs` is "
                 "required.")
     ctx.verify_mode = verify_mode
     return ctx
Esempio n. 15
0
def setup_ssl_context(cert, private, hostname=False):
    ssl_context = SSLContext(PROTOCOL_SSLv23)
    ssl_context.load_cert_chain(cert, private)
    ssl_context.check_hostname = hostname
    return ssl_context
Esempio n. 16
0
    # Start the webserver(s)
    webserver = None
    ssl_webserver = None
    if not args.noserver:

        # HTTP server
        logger.info("Creating webserver...")
        application = AppRunner(app)
        loop.run_until_complete(application.setup())
        webserver = TCPSite(application, host=args.host, port=args.port)

        # SSL server
        try:
            if not args.nossl:
                ssl_context = SSLContext()
                ssl_context.load_cert_chain(**bot.config['ssl_context'])
                ssl_webserver = TCPSite(application,
                                        host=args.host,
                                        port=args.sslport,
                                        ssl_context=ssl_context)
        except Exception as e:
            ssl_webserver = None
            logger.exception("Could not make SSL webserver")

        # Start servers
        loop.run_until_complete(webserver.start())
        logger.info(f"Server started - http://{args.host}:{args.port}/")
        if ssl_webserver:
            loop.run_until_complete(ssl_webserver.start())
            logger.info(f"Server started - http://{args.host}:{args.sslport}/")