Example #1
0
    def make_environ(self, flow, errsoc, **extra):
        """
        Raises:
            ValueError, if the content-encoding is invalid.
        """
        path = strutils.native(flow.request.path, "latin-1")
        if '?' in path:
            path_info, query = strutils.native(path, "latin-1").split('?', 1)
        else:
            path_info = path
            query = ''
        environ = {
            'wsgi.version': (1, 0),
            'wsgi.url_scheme':
            strutils.native(flow.request.scheme, "latin-1"),
            'wsgi.input':
            io.BytesIO(flow.request.content or b""),
            'wsgi.errors':
            errsoc,
            'wsgi.multithread':
            True,
            'wsgi.multiprocess':
            False,
            'wsgi.run_once':
            False,
            'SERVER_SOFTWARE':
            self.sversion,
            'REQUEST_METHOD':
            strutils.native(flow.request.method, "latin-1"),
            'SCRIPT_NAME':
            '',
            'PATH_INFO':
            urllib.parse.unquote(path_info),
            'QUERY_STRING':
            query,
            'CONTENT_TYPE':
            strutils.native(flow.request.headers.get('Content-Type', ''),
                            "latin-1"),
            'CONTENT_LENGTH':
            strutils.native(flow.request.headers.get('Content-Length', ''),
                            "latin-1"),
            'SERVER_NAME':
            self.domain,
            'SERVER_PORT':
            str(self.port),
            'SERVER_PROTOCOL':
            strutils.native(flow.request.http_version, "latin-1"),
        }
        environ.update(extra)
        if flow.client_conn.address:
            environ["REMOTE_ADDR"] = strutils.native(
                flow.client_conn.address.host, "latin-1")
            environ["REMOTE_PORT"] = flow.client_conn.address.port

        for key, value in flow.request.headers.items():
            key = 'HTTP_' + strutils.native(key, "latin-1").upper().replace(
                '-', '_')
            if key not in ('HTTP_CONTENT_TYPE', 'HTTP_CONTENT_LENGTH'):
                environ[key] = value
        return environ
Example #2
0
def _convert_dict_keys(o: Any) -> Any:
    if isinstance(o, dict):
        return {
            strutils.native(k): _convert_dict_keys(v)
            for k, v in o.items()
        }
    else:
        return o
Example #3
0
def _convert_dict_vals(o: dict, values_to_convert: dict) -> dict:
    for k, v in values_to_convert.items():
        if not o or k not in o:
            continue
        if v is True:
            o[k] = strutils.native(o[k])
        else:
            _convert_dict_vals(o[k], v)
    return o
Example #4
0
def _convert_dict_vals(o, values_to_convert):
    # type: (dict, dict) -> dict
    for k, v in values_to_convert.items():
        if not o or k not in o:
            continue
        if v is True:
            o[k] = strutils.native(o[k])
        else:
            _convert_dict_vals(o[k], v)
    return o
Example #5
0
 def dump(self, data, hexdump):
     if hexdump:
         for line in strutils.hexdump(data):
             self("\t%s %s %s" % line)
     else:
         data = strutils.native(
             strutils.escape_control_characters(
                 data.decode("ascii", "replace").replace(u"\ufffd", u".")))
         for i in data.split("\n"):
             self("\t%s" % i)
Example #6
0
 def verify_cert(conn, x509, errno, err_depth, is_cert_verified):
     if not is_cert_verified:
         self.ssl_verification_error = exceptions.InvalidCertificateException(
             "Certificate Verification Error for {}: {} (errno: {}, depth: {})"
             .format(
                 sni,
                 strutils.native(
                     SSL._ffi.string(
                         SSL._lib.X509_verify_cert_error_string(
                             errno)), "utf8"), errno, err_depth))
     return is_cert_verified
Example #7
0
 def verify_cert(conn, x509, errno, err_depth, is_cert_verified):
     if not is_cert_verified:
         self.ssl_verification_error = exceptions.InvalidCertificateException(
             "Certificate Verification Error for {}: {} (errno: {}, depth: {})".format(
                 sni,
                 strutils.native(SSL._ffi.string(SSL._lib.X509_verify_cert_error_string(errno)), "utf8"),
                 errno,
                 err_depth
             )
         )
     return is_cert_verified
Example #8
0
 def dump(self, data, hexdump):
     if hexdump:
         for line in strutils.hexdump(data):
             self("\t%s %s %s" % line)
     else:
         data = strutils.native(
             strutils.escape_control_characters(
                 data
                     .decode("ascii", "replace")
                     .replace(u"\ufffd", u".")
             )
         )
         for i in data.split("\n"):
             self("\t%s" % i)
Example #9
0
def test_native():
    with tutils.raises(TypeError):
        strutils.native(42)
    if six.PY2:
        assert strutils.native(u"foo") == b"foo"
        assert strutils.native(b"foo") == b"foo"
    else:
        assert strutils.native(u"foo") == u"foo"
        assert strutils.native(b"foo") == u"foo"
Example #10
0
 def __str__(self):
     parts = [
         "Application Layer Protocol: %s" % strutils.native(self.alp, "utf8"),
         "Cipher: %s, %s bit, %s" % self.cipher,
         "SSL certificate chain:"
     ]
     for n, i in enumerate(self.certchain):
         parts.append("  Certificate [%s]" % n)
         parts.append("\tSubject: ")
         for cn in i.get_subject().get_components():
             parts.append("\t\t%s=%s" % (
                 strutils.native(cn[0], "utf8"),
                 strutils.native(cn[1], "utf8"))
             )
         parts.append("\tIssuer: ")
         for cn in i.get_issuer().get_components():
             parts.append("\t\t%s=%s" % (
                 strutils.native(cn[0], "utf8"),
                 strutils.native(cn[1], "utf8"))
             )
         parts.extend(
             [
                 "\tVersion: %s" % i.get_version(),
                 "\tValidity: %s - %s" % (
                     strutils.native(i.get_notBefore(), "utf8"),
                     strutils.native(i.get_notAfter(), "utf8")
                 ),
                 "\tSerial: %s" % i.get_serial_number(),
                 "\tAlgorithm: %s" % strutils.native(i.get_signature_algorithm(), "utf8")
             ]
         )
         pk = i.get_pubkey()
         types = {
             OpenSSL.crypto.TYPE_RSA: "RSA",
             OpenSSL.crypto.TYPE_DSA: "DSA"
         }
         t = types.get(pk.type(), "Uknown")
         parts.append("\tPubkey: %s bit %s" % (pk.bits(), t))
         s = certutils.SSLCert(i)
         if s.altnames:
             parts.append("\tSANs: %s" % " ".join(strutils.native(n, "utf8") for n in s.altnames))
     return "\n".join(parts)
Example #11
0
 def __str__(self):
     parts = [
         "Application Layer Protocol: %s" % strutils.native(self.alp, "utf8"),
         "Cipher: %s, %s bit, %s" % self.cipher,
         "SSL certificate chain:"
     ]
     for n, i in enumerate(self.certchain):
         parts.append("  Certificate [%s]" % n)
         parts.append("\tSubject: ")
         for cn in i.get_subject().get_components():
             parts.append("\t\t%s=%s" % (
                 strutils.native(cn[0], "utf8"),
                 strutils.native(cn[1], "utf8"))
             )
         parts.append("\tIssuer: ")
         for cn in i.get_issuer().get_components():
             parts.append("\t\t%s=%s" % (
                 strutils.native(cn[0], "utf8"),
                 strutils.native(cn[1], "utf8"))
             )
         parts.extend(
             [
                 "\tVersion: %s" % i.get_version(),
                 "\tValidity: %s - %s" % (
                     strutils.native(i.get_notBefore(), "utf8"),
                     strutils.native(i.get_notAfter(), "utf8")
                 ),
                 "\tSerial: %s" % i.get_serial_number(),
                 "\tAlgorithm: %s" % strutils.native(i.get_signature_algorithm(), "utf8")
             ]
         )
         pk = i.get_pubkey()
         types = {
             OpenSSL.crypto.TYPE_RSA: "RSA",
             OpenSSL.crypto.TYPE_DSA: "DSA"
         }
         t = types.get(pk.type(), "Uknown")
         parts.append("\tPubkey: %s bit %s" % (pk.bits(), t))
         s = certutils.SSLCert(i)
         if s.altnames:
             parts.append("\tSANs: %s" % " ".join(strutils.native(n, "utf8") for n in s.altnames))
     return "\n".join(parts)
Example #12
0
    def make_environ(self, flow, errsoc, **extra):
        """
        Raises:
            ValueError, if the content-encoding is invalid.
        """
        path = strutils.native(flow.request.path, "latin-1")
        if '?' in path:
            path_info, query = strutils.native(path, "latin-1").split('?', 1)
        else:
            path_info = path
            query = ''
        environ = {
            'wsgi.version': (1, 0),
            'wsgi.url_scheme': strutils.native(flow.request.scheme, "latin-1"),
            'wsgi.input': BytesIO(flow.request.content or b""),
            'wsgi.errors': errsoc,
            'wsgi.multithread': True,
            'wsgi.multiprocess': False,
            'wsgi.run_once': False,
            'SERVER_SOFTWARE': self.sversion,
            'REQUEST_METHOD': strutils.native(flow.request.method, "latin-1"),
            'SCRIPT_NAME': '',
            'PATH_INFO': urllib.parse.unquote(path_info),
            'QUERY_STRING': query,
            'CONTENT_TYPE': strutils.native(flow.request.headers.get('Content-Type', ''), "latin-1"),
            'CONTENT_LENGTH': strutils.native(flow.request.headers.get('Content-Length', ''), "latin-1"),
            'SERVER_NAME': self.domain,
            'SERVER_PORT': str(self.port),
            'SERVER_PROTOCOL': strutils.native(flow.request.http_version, "latin-1"),
        }
        environ.update(extra)
        if flow.client_conn.address:
            environ["REMOTE_ADDR"] = strutils.native(flow.client_conn.address.host, "latin-1")
            environ["REMOTE_PORT"] = flow.client_conn.address.port

        for key, value in flow.request.headers.items():
            key = 'HTTP_' + strutils.native(key, "latin-1").upper().replace('-', '_')
            if key not in ('HTTP_CONTENT_TYPE', 'HTTP_CONTENT_LENGTH'):
                environ[key] = value
        return environ
Example #13
0
def _convert_dict_keys(o):
    # type: (Any) -> Any
    if isinstance(o, dict):
        return {strutils.native(k): _convert_dict_keys(v) for k, v in o.items()}
    else:
        return o
Example #14
0
def test_native():
    with tutils.raises(TypeError):
        strutils.native(42)
    assert strutils.native(u"foo") == u"foo"
    assert strutils.native(b"foo") == u"foo"