Esempio n. 1
0
    def add_entry_by_txt(self, field, type, entry, len, loc, set):
        # entry_type: (str, int, bytes, int, int, int) -> int
        """
        Add X509_Name field whose name is identified by its name.

        :param field: name of the entry
        :param type: use MBSTRING_ASC or MBSTRING_UTF8
               (or standard ASN1 type like V_ASN1_IA5STRING)
        :param entry: value
        :param len: buf_len of the entry
               (-1 and the length is computed automagically)

        The ``loc`` and ``set`` parameters determine where a new entry
        should be added.
        For almost all applications loc can be set to -1 and set to 0.
        This adds a new entry to the end of name as a single valued
        RelativeDistinguishedName (RDN).

        :param loc: determines the index where the new entry is
               inserted: if it is -1 it is appended.
        :param set: determines how the new type is added. If it is zero
               a new RDN is created.
               If set is -1 or 1 it is added to the previous or next RDN
               structure respectively. This will then be a multivalued
               RDN: since multivalues RDNs are very seldom used set is
               almost always set to zero.

        :return: 1 for success of 0 if an error occurred.
        """
        return m2.x509_name_add_entry_by_txt(self.x509_name,
                                             util.py3bytes(field), type,
                                             entry, len, loc, set)
Esempio n. 2
0
 def readline(self, size=4096):
     # type: (int) -> bytes
     if not self.readable():
         raise IOError('cannot read')
     buf = m2.bio_gets(self.bio, size)
     buf = '' if buf is None else buf
     return util.py3bytes(buf)
 def __init__(self, host=None, peerCertHash=None, peerCertDigest='sha1'):
     # type: (Optional[str], Optional[bytes], str) -> None
     self.host = host
     if peerCertHash is not None:
         peerCertHash = util.py3bytes(peerCertHash)
     self.fingerprint = peerCertHash
     self.digest = peerCertDigest  # type: str
Esempio n. 4
0
 def _encode_auth(self):
     # type: () -> Optional[bytes]
     """ Encode the username and password for use in the auth header. """
     if not (self._username and self._password):
         return None
     # Authenticated proxy
     userpass = "******" % (self._username, self._password)
     enc_userpass = base64.encodestring(userpass).replace("\n", "")
     return util.py3bytes("Basic %s" % enc_userpass)
Esempio n. 5
0
    def set_data(self, data, type=ASN1.MBSTRING_ASC):
        # type: (bytes, int) -> int
        """
        Sets the field name to asn1obj

        :param data: data in a binary form to be set
        :return: 0 on failure, 1 on success
        """
        return m2.x509_name_entry_set_data(self.x509_name_entry,
                                           type, util.py3bytes(data))
Esempio n. 6
0
def new_stack_from_der(der_string):
    # type: (bytes) -> X509_Stack
    """
    Create a new X509_Stack from DER string.

    :return: X509_Stack
    """
    der_string = util.py3bytes(der_string)
    stack_ptr = m2.make_stack_from_der_sequence(der_string)
    return X509_Stack(stack_ptr, 1, 1)
Esempio n. 7
0
def load_request_der_string(string):
    # type: (AnyStr) -> Request
    """
    Load certificate request from a string.

    @param string: String containing a certificate request in DER format.
    @return: M2Crypto.X509.Request object.
    """
    bio = BIO.MemoryBuffer(util.py3bytes(string))
    return load_request_bio(bio, FORMAT_DER)
Esempio n. 8
0
 def _get_connect_msg(self):
     # type: () -> bytes
     """ Return an HTTP CONNECT request to send to the proxy. """
     msg = "CONNECT %s:%d HTTP/1.1\r\n" % (self._real_host, self._real_port)
     msg = msg + "Host: %s:%d\r\n" % (self._real_host, self._real_port)
     if self._proxy_UA:
         msg = msg + "%s: %s\r\n" % (self._UA_HEADER, self._proxy_UA)
     if self._proxy_auth:
         msg = msg + "%s: %s\r\n" % (self._AUTH_HEADER, self._proxy_auth)
     msg = msg + "\r\n"
     return util.py3bytes(msg)
Esempio n. 9
0
 def test_mix_unmix3(self):
     c = self.jar.makeCookie(self.exp, self.data)
     s = SimpleCookie()
     s.load(c.output())
     exp, data, digest = unmix3(s[self._token].value)
     self.assertEqual(data, self.data)
     self.assertEqual(float(exp), self.exp)
     key = self.jar._key  # Peeking...
     mac = util.bin_to_hex(
         EVP.hmac(key, util.py3bytes(mix(self.exp, self.data)), 'sha1'))
     self.assertEqual(digest, mac)
Esempio n. 10
0
 def _encode_auth(self):
     # type: () -> Optional[bytes]
     """ Encode the username and password for use in the auth header. """
     if not (self._username and self._password):
         return None
     # Authenticated proxy
     userpass = "******" % (self._username, self._password)
     with warnings.catch_warnings():
         warnings.simplefilter("ignore", DeprecationWarning)
         enc_userpass = base64.encodestring(userpass).replace("\n", "")
     return util.py3bytes("Basic %s" % enc_userpass)
Esempio n. 11
0
 def readlines(self, sizehint='ignored'):
     # type: (Union[AnyStr, int]) -> Iterable[bytes]
     if not self.readable():
         raise IOError('cannot read')
     lines = []
     while 1:
         buf = m2.bio_gets(self.bio, 4096)
         if buf is None:
             break
         lines.append(util.py3bytes(buf))
     return lines
Esempio n. 12
0
def new_stack_from_der(der_string):
    # type: (bytes) -> X509_Stack
    """
    Create a new X509_Stack from DER string.

    @return: X509_Stack
    """
    stack_ptr = m2.make_stack_from_der_sequence(util.py3bytes(der_string))
    if stack_ptr is None:
        raise X509Error(Err.get_error())
    return X509_Stack(stack_ptr, 1, 1)
Esempio n. 13
0
 def test_mix_unmix3(self):
     c = self.jar.makeCookie(self.exp, self.data)
     s = SimpleCookie()
     s.load(c.output(header=""))
     exp, data, digest = unmix3(s[self._token].value)
     self.assertEqual(data, self.data)
     # see comment in test_mix_unmix
     self.assertAlmostEqual(exp, self.exp, places=4)
     key = self.jar._key     # pylint: disable=protected-access
     mac = util.bin_to_hex(
         EVP.hmac(key, util.py3bytes(mix(self.exp, self.data)), 'sha1'))
     self.assertEqual(digest, mac)
Esempio n. 14
0
 def test_mix_unmix3(self):
     c = self.jar.makeCookie(self.exp, self.data)
     s = SimpleCookie()
     s.load(c.output(header=""))
     exp, data, digest = unmix3(s[self._token].value)
     self.assertEqual(data, self.data)
     # see comment in test_mix_unmix
     self.assertAlmostEqual(exp, self.exp, places=4)
     key = self.jar._key  # pylint: disable=protected-access
     mac = util.bin_to_hex(
         EVP.hmac(key, util.py3bytes(mix(self.exp, self.data)), 'sha1'))
     self.assertEqual(digest, mac)
Esempio n. 15
0
    def __setattr__(self, attr, value):
        # type: (str, AnyStr) -> int
        """
        :return: 1 for success of 0 if an error occurred.
        """
        if attr in self.nid:
            assert m2.x509_name_type_check(self.x509_name), \
                "'x509_name' type error"
            return m2.x509_name_set_by_nid(self.x509_name, self.nid[attr],
                                           util.py3bytes(value))

        self.__dict__[attr] = value
Esempio n. 16
0
 def test_make_cookie(self):
     c = self.jar.makeCookie(self.exp, self.data)
     self.assertTrue(isinstance(c, AuthCookie))
     self.assertEqual(c.expiry(), self.exp)
     self.assertEqual(c.data(), self.data)
     # Peek inside the cookie jar...
     key = self.jar._key  # pylint: disable=protected-access
     mac = util.bin_to_hex(
         EVP.hmac(key, util.py3bytes(mix(self.exp, self.data)), 'sha1'))
     self.assertEqual(c.mac(), mac)
     # Ok, stop peeking now.
     cookie_str = self._format % (self.exp, self.data, mac)
     self.assertEqual(c.output(), cookie_str)
Esempio n. 17
0
def load_cert_string(string, format=FORMAT_PEM):
    # type: (AnyStr, int) -> X509
    """
    Load certificate from a string.

    @param string: String containing a certificate in either DER or PEM format.
    @param format: Describes the format of the cert to be loaded,
                   either PEM or DER (via constants FORMAT_PEM
                   and FORMAT_FORMAT_DER)
    @return: M2Crypto.X509.X509 object.
    """
    bio = BIO.MemoryBuffer(util.py3bytes(string))
    return load_cert_bio(bio, format)
Esempio n. 18
0
def load_cert_der_string(string):
    # type: (AnyStr) -> X509
    """
    Load certificate from a string.

    @param string: String containing a certificate in DER format.
    @return: M2Crypto.X509.X509 object.
    """
    bio = BIO.MemoryBuffer(util.py3bytes(string))
    cptr = m2.d2i_x509(bio._ptr())
    if cptr is None:
        raise X509Error(Err.get_error())
    return X509(cptr, _pyfree=1)
Esempio n. 19
0
def load_cert_der_string(string):
    # type: (AnyStr) -> X509
    """
    Load certificate from a string.

    :param string: String containing a certificate in DER format.

    :return: M2Crypto.X509.X509 object.
    """
    string = util.py3bytes(string)
    bio = BIO.MemoryBuffer(string)
    cptr = m2.d2i_x509(bio._ptr())
    return X509(cptr, _pyfree=1)
Esempio n. 20
0
 def test_make_cookie(self):
     c = self.jar.makeCookie(self.exp, self.data)
     self.assertTrue(isinstance(c, AuthCookie))
     self.assertEqual(c.expiry(), self.exp)
     self.assertEqual(c.data(), self.data)
     # Peek inside the cookie jar...
     key = self.jar._key  # pylint: disable=protected-access
     mac = util.bin_to_hex(
         EVP.hmac(key, util.py3bytes(mix(self.exp, self.data)), 'sha1'))
     self.assertEqual(c.mac(), mac)
     # Ok, stop peeking now.
     cookie_str = self._format % (self.exp, self.data, mac)
     self.assertEqual(c.output(), cookie_str)
Esempio n. 21
0
def load_request_string(string, format=FORMAT_PEM):
    # type: (AnyStr, int) -> Request
    """
    Load certificate request from a string.

    :param string: String containing a certificate request in
                   either DER or PEM format.
    :param format: Describes the format of the request to be loaded,
                   either PEM or DER. (using constants FORMAT_PEM
                   and FORMAT_DER)

    :return: M2Crypto.X509.Request object.
    """
    string = util.py3bytes(string)
    bio = BIO.MemoryBuffer(string)
    return load_request_bio(bio, format)
Esempio n. 22
0
    def get_ext(self, name):
        # type: (str) -> X509_Extension
        """
        Get X509 extension by name.

        @param name:    Name of the extension
        @return:       X509_Extension
        """
        # Optimizations to reduce attribute accesses
        m2x509_get_ext = m2.x509_get_ext
        m2x509_extension_get_name = m2.x509_extension_get_name
        x509 = self.x509

        name = util.py3bytes(name)
        for i in range(m2.x509_get_ext_count(x509)):
            ext_ptr = m2x509_get_ext(x509, i)
            if m2x509_extension_get_name(ext_ptr) == name:
                return X509_Extension(ext_ptr, _pyfree=0)

        raise LookupError
Esempio n. 23
0
 def _hmac(self, key, data):
     # type: (bytes, str) -> str
     return util.bin_to_hex(m2.hmac(key, util.py3bytes(data), m2.sha1()))
Esempio n. 24
0
 def test_py3bytes_None(self):
     with self.assertRaises(TypeError):
         util.py3bytes(None)
Esempio n. 25
0
 def test_py3bytes_bytearray(self):
     self.assertIsInstance(util.py3bytes(bytearray(b'test')), bytearray)
Esempio n. 26
0
 def test_py3bytes_bytes(self):
     self.assertIsInstance(util.py3bytes(b'test'), bytes)
Esempio n. 27
0
 def test_py3bytes_str(self):
     self.assertIsInstance(util.py3bytes(u'test'), bytes)