Python binascii.a2b_hex() Examples

The following are 30 code examples of binascii.a2b_hex(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module binascii , or try the search function .
Example #1
Source File: test_handler.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_receive_create_bad_notifier(self):
        payload = '8dfd70000001000000000000076578616d706c6503636f6d00ff02ff00'
        # expected response is REFUSED, other fields are
        # opcode 14
        # rcode REFUSED
        # flags QR
        # ;QUESTION
        # example.com. CLASS65280 TYPE65282
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b'8dfdf0050001000000000000076578616d706c6503636f'
                             b'6d00ff02ff00')
        request = dns.message.from_wire(binascii.a2b_hex(payload))
        # Bad 'requester'
        request.environ = {'addr': ['6.6.6.6', 1234]}
        response = next(self.handler(request)).to_wire()

        self.assertEqual(binascii.b2a_hex(response), expected_response) 
Example #2
Source File: httpclient_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def test_body_encoding(self):
        unicode_body = u("\xe9")
        byte_body = binascii.a2b_hex(b"e9")

        # unicode string in body gets converted to utf8
        response = self.fetch("/echopost", method="POST", body=unicode_body,
                              headers={"Content-Type": "application/blah"})
        self.assertEqual(response.headers["Content-Length"], "2")
        self.assertEqual(response.body, utf8(unicode_body))

        # byte strings pass through directly
        response = self.fetch("/echopost", method="POST",
                              body=byte_body,
                              headers={"Content-Type": "application/blah"})
        self.assertEqual(response.headers["Content-Length"], "1")
        self.assertEqual(response.body, byte_body)

        # Mixing unicode in headers and byte string bodies shouldn't
        # break anything
        response = self.fetch("/echopost", method="POST", body=byte_body,
                              headers={"Content-Type": "application/blah"},
                              user_agent=u("foo"))
        self.assertEqual(response.headers["Content-Length"], "1")
        self.assertEqual(response.body, byte_body) 
Example #3
Source File: test_handler.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_dispatch_opcode_iquery(self):
        # DNS packet with IQUERY opcode
        payload = "271109000001000000000000076578616d706c6503636f6d0000010001"

        # expected response is an error code REFUSED.  The other fields are
        # id 10001
        # opcode IQUERY
        # rcode REFUSED
        # flags QR RD
        # ;QUESTION
        # example.com. IN A
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b"271189050001000000000000076578616d706c6503636f"
                             b"6d0000010001")

        request = dns.message.from_wire(binascii.a2b_hex(payload))
        request.environ = {'addr': self.addr, 'context': self.context}
        response = next(self.handler(request)).to_wire()

        self.assertEqual(expected_response, binascii.b2a_hex(response)) 
Example #4
Source File: test_handler.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_dispatch_opcode_status(self):
        # DNS packet with STATUS opcode
        payload = "271211000001000000000000076578616d706c6503636f6d0000010001"

        # expected response is an error code REFUSED.  The other fields are
        # id 10002
        # opcode STATUS
        # rcode REFUSED
        # flags QR RD
        # ;QUESTION
        # example.com. IN A
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b"271291050001000000000000076578616d706c6503636f"
                             b"6d0000010001")

        request = dns.message.from_wire(binascii.a2b_hex(payload))
        request.environ = {'addr': self.addr, 'context': self.context}
        response = next(self.handler(request)).to_wire()

        self.assertEqual(expected_response, binascii.b2a_hex(response)) 
Example #5
Source File: httpclient_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def test_body_encoding(self):
        unicode_body = u("\xe9")
        byte_body = binascii.a2b_hex(b"e9")

        # unicode string in body gets converted to utf8
        response = self.fetch("/echopost", method="POST", body=unicode_body,
                              headers={"Content-Type": "application/blah"})
        self.assertEqual(response.headers["Content-Length"], "2")
        self.assertEqual(response.body, utf8(unicode_body))

        # byte strings pass through directly
        response = self.fetch("/echopost", method="POST",
                              body=byte_body,
                              headers={"Content-Type": "application/blah"})
        self.assertEqual(response.headers["Content-Length"], "1")
        self.assertEqual(response.body, byte_body)

        # Mixing unicode in headers and byte string bodies shouldn't
        # break anything
        response = self.fetch("/echopost", method="POST", body=byte_body,
                              headers={"Content-Type": "application/blah"},
                              user_agent=u("foo"))
        self.assertEqual(response.headers["Content-Length"], "1")
        self.assertEqual(response.body, byte_body) 
Example #6
Source File: hex_codec.py    From BinderFilter with MIT License 6 votes vote down vote up
def hex_decode(input,errors='strict'):

    """ Decodes the object input and returns a tuple (output
        object, length consumed).

        input must be an object which provides the bf_getreadbuf
        buffer slot. Python strings, buffer objects and memory
        mapped files are examples of objects providing this slot.

        errors defines the error handling to apply. It defaults to
        'strict' handling which is the only currently supported
        error handling for this codec.

    """
    assert errors == 'strict'
    output = binascii.a2b_hex(input)
    return (output, len(input)) 
Example #7
Source File: crack_mongo.py    From xunfeng with GNU General Public License v3.0 6 votes vote down vote up
def check(ip, port, timeout):
    try:
        socket.setdefaulttimeout(timeout)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((ip, int(port)))
        data = binascii.a2b_hex(
            "3a000000a741000000000000d40700000000000061646d696e2e24636d640000000000ffffffff130000001069736d6173746572000100000000")
        s.send(data)
        result = s.recv(1024)
        if "ismaster" in result:
            getlog_data = binascii.a2b_hex(
                "480000000200000000000000d40700000000000061646d696e2e24636d6400000000000100000021000000026765744c6f670010000000737461727475705761726e696e67730000")
            s.send(getlog_data)
            result = s.recv(1024)
            if "totalLinesWritten" in result:
                return u"未授权访问"
    except Exception, e:
        pass 
Example #8
Source File: hex_codec.py    From Computable with MIT License 6 votes vote down vote up
def hex_decode(input,errors='strict'):

    """ Decodes the object input and returns a tuple (output
        object, length consumed).

        input must be an object which provides the bf_getreadbuf
        buffer slot. Python strings, buffer objects and memory
        mapped files are examples of objects providing this slot.

        errors defines the error handling to apply. It defaults to
        'strict' handling which is the only currently supported
        error handling for this codec.

    """
    assert errors == 'strict'
    output = binascii.a2b_hex(input)
    return (output, len(input)) 
Example #9
Source File: pdf-parser.py    From ACE with Apache License 2.0 6 votes vote down vote up
def YARACompile(ruledata):
    if ruledata.startswith('#'):
        if ruledata.startswith('#h#'):
            rule = binascii.a2b_hex(ruledata[3:])
        elif ruledata.startswith('#b#'):
            rule = binascii.a2b_base64(ruledata[3:])
        elif ruledata.startswith('#s#'):
            rule = 'rule string {strings: $a = "%s" ascii wide nocase condition: $a}' % ruledata[3:]
        elif ruledata.startswith('#q#'):
            rule = ruledata[3:].replace("'", '"')
        else:
            rule = ruledata[1:]
        return yara.compile(source=rule)
    else:
        dFilepaths = {}
        if os.path.isdir(ruledata):
            for root, dirs, files in os.walk(ruledata):
                for file in files:
                    filename = os.path.join(root, file)
                    dFilepaths[filename] = filename
        else:
            for filename in ProcessAt(ruledata):
                dFilepaths[filename] = filename
        return yara.compile(filepaths=dFilepaths) 
Example #10
Source File: process.py    From stem with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_hash_password(tor_cmd):
    """
    Hash a controller password. It's salted so can't assert that we get a
    particular value. Also, tor's output is unnecessarily verbose so including
    hush to cut it down.
    """

    output = run_tor(tor_cmd, '--hush', '--hash-password', 'my_password').splitlines()[-1]

    if not re.match('^16:[0-9A-F]{58}$', output):
      raise AssertionError("Unexpected response from 'tor --hash-password my_password': %s" % output)

    # I'm not gonna even pretend to understand the following. Ported directly
    # from tor's test_cmdline_args.py.

    output_hex = binascii.a2b_hex(stem.util.str_tools._to_bytes(output).strip()[3:])
    salt, how, hashed = output_hex[:8], output_hex[8], output_hex[9:]

    count = (16 + (how & 15)) << ((how >> 4) + 6)
    stuff = salt + b'my_password'
    repetitions = count // len(stuff) + 1
    inp = (stuff * repetitions)[:count]
    assert_equal(hashlib.sha1(inp).digest(), hashed) 
Example #11
Source File: test_handler.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_transfer_source(self, mock_doaxfr, mock_query):
        payload = '735d70000001000000000000076578616d706c6503636f6d00ff02ff00'
        # Expected NOERROR other fields are
        # opcode 14
        # rcode NOERROR
        # flags QR AA
        # ;QUESTION
        # example.com. CLASS65280 TYPE65282
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b'735df4000001000000000000076578616d706c6503636f'
                             b'6d00ff02ff00')
        request = dns.message.from_wire(binascii.a2b_hex(payload))
        request.environ = {'addr': ['0.0.0.0', 1234]}
        with mock.patch.object(
                designate.backend.agent_backend.impl_fake.FakeBackend,
                'find_zone_serial', return_value=None):
            response = next(self.handler(request)).to_wire()
            mock_doaxfr.assert_called_with(
                'example.com.', [], source='1.2.3.4'
            )
            self.assertEqual(expected_response, binascii.b2a_hex(response)) 
Example #12
Source File: test_handler.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_receive_delete(self, mock_execute):
        payload = '3b9970000001000000000000076578616d706c6503636f6d00ff03ff00'
        # Expected NOERROR other fields are
        # opcode 14
        # rcode NOERROR
        # flags QR AA
        # ;QUESTION
        # example.com. CLASS65280 TYPE65283
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b'3b99f4000001000000000000076578616d706c6503636f'
                             b'6d00ff03ff00')
        request = dns.message.from_wire(binascii.a2b_hex(payload))
        request.environ = {'addr': ['0.0.0.0', 1234]}
        response = next(self.handler(request)).to_wire()

        self.assertEqual(expected_response, binascii.b2a_hex(response)) 
Example #13
Source File: test_handler.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_receive_delete_bad_notifier(self):
        payload = 'e6da70000001000000000000076578616d706c6503636f6d00ff03ff00'
        # expected response is REFUSED, other fields are
        # opcode 14
        # rcode REFUSED
        # flags QR
        # ;QUESTION
        # example.com. CLASS65280 TYPE65283
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b'e6daf0050001000000000000076578616d706c6503636f'
                             b'6d00ff03ff00')
        request = dns.message.from_wire(binascii.a2b_hex(payload))
        # Bad 'requester'
        request.environ = {'addr': ['6.6.6.6', 1234]}
        response = next(self.handler(request)).to_wire()

        self.assertEqual(expected_response, binascii.b2a_hex(response)) 
Example #14
Source File: test_handler.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_receive_notify_bad_notifier(self):
        payload = '243520000001000000000000076578616d706c6503636f6d0000060001'
        # expected response is REFUSED, other fields are
        # opcode NOTIFY
        # rcode REFUSED
        # flags QR
        # ;QUESTION
        # example.com. IN SOA
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b'2435a0050001000000000000076578616d706c6503636f'
                             b'6d0000060001')
        request = dns.message.from_wire(binascii.a2b_hex(payload))
        # Bad 'requester'
        request.environ = {'addr': ['6.6.6.6', 1234]}
        response = next(self.handler(request)).to_wire()

        self.assertEqual(expected_response, binascii.b2a_hex(response)) 
Example #15
Source File: common.py    From earthengine with MIT License 6 votes vote down vote up
def runTest(self):
        plaintext = a2b_hex(self.plaintext)
        ciphertext = a2b_hex(self.ciphertext)

        # The cipher should work like a stream cipher

        # Test counter mode encryption, 3 bytes at a time
        ct3 = []
        cipher = self._new()
        for i in range(0, len(plaintext), 3):
            ct3.append(cipher.encrypt(plaintext[i:i+3]))
        ct3 = b2a_hex(b("").join(ct3))
        self.assertEqual(self.ciphertext, ct3)  # encryption (3 bytes at a time)

        # Test counter mode decryption, 3 bytes at a time
        pt3 = []
        cipher = self._new()
        for i in range(0, len(ciphertext), 3):
            pt3.append(cipher.encrypt(ciphertext[i:i+3]))
        # PY3K: This is meant to be text, do not change to bytes (data)
        pt3 = b2a_hex(b("").join(pt3))
        self.assertEqual(self.plaintext, pt3)  # decryption (3 bytes at a time) 
Example #16
Source File: test_handler.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_receive_notify(self, mock_doaxfr, mock_query):
        """
        Get a NOTIFY and ensure the response is right,
        and an AXFR is triggered
        """
        payload = ('1a7220000001000000000000076578616d706c6503636f6d000006'
                   '0001')
        # expected response is NOERROR, other fields are
        # opcode NOTIFY
        # rcode NOERROR
        # flags QR AA
        # ;QUESTION
        # example.com. IN SOA
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b'1a72a4000001000000000000076578616d706c6503'
                             b'636f6d0000060001')
        request = dns.message.from_wire(binascii.a2b_hex(payload))
        request.environ = {'addr': ['0.0.0.0', 1234]}
        response = next(self.handler(request)).to_wire()
        self.assertEqual(expected_response, binascii.b2a_hex(response)) 
Example #17
Source File: test_notify.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_poll_for_serial_number_higher_serial(self):
        # id 10001
        # opcode QUERY
        # rcode NOERROR
        # flags QR AA
        # ;QUESTION
        # example.com. IN SOA
        # ;ANSWER
        # example.com. 3600 IN SOA example-ns.com. admin.example.com. 101 3600
        #  600 86400 3600
        # ;AUTHORITY
        # ;ADDITIONAL
        poll_response = ("271184000001000100000000076578616d706c6503636f6d0000"
                         "060001c00c0006000100000e1000290a6578616d706c652d6e73"
                         "c0140561646d696ec00c0000006500000e100000025800015180"
                         "00000e10")
        context = self.get_context()
        with patch.object(dns.query, 'udp', return_value=dns.message.from_wire(
                binascii.a2b_hex(poll_response))):
            status, serial, retries = self.notify.get_serial_number(
                context, objects.Zone.from_dict(self.test_zone),
                self.nameserver.host, self.nameserver.port, 0, 0, 2, 0)
            self.assertEqual(status, 'SUCCESS')
            self.assertEqual(serial, 101)
            self.assertEqual(retries, 2) 
Example #18
Source File: test_notify.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_poll_for_serial_number_lower_serial(self):
        # id 10001
        # opcode QUERY
        # rcode NOERROR
        # flags QR AA
        # ;QUESTION
        # example.com. IN SOA
        # ;ANSWER
        # example.com. 3600 IN SOA example-ns.com. admin.example.com. 99 3600
        #  600 86400 3600
        # ;AUTHORITY
        # ;ADDITIONAL
        poll_response = ("271184000001000100000000076578616d706c6503636f6d0000"
                         "060001c00c0006000100000e1000290a6578616d706c652d6e73"
                         "c0140561646d696ec00c0000006300000e100000025800015180"
                         "00000e10")
        context = self.get_context()
        with patch.object(dns.query, 'udp', return_value=dns.message.from_wire(
                binascii.a2b_hex(poll_response))):
            status, serial, retries = self.notify.get_serial_number(
                context, objects.Zone.from_dict(self.test_zone),
                self.nameserver.host, self.nameserver.port, 0, 0, 2, 0)
            self.assertEqual(status, 'ERROR')
            self.assertEqual(serial, 99)
            self.assertEqual(retries, 0) 
Example #19
Source File: test_notify.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_poll_for_serial_number(self):
        # id 10001
        # opcode QUERY
        # rcode NOERROR
        # flags QR AA
        # ;QUESTION
        # example.com. IN SOA
        # ;ANSWER
        # example.com. 3600 IN SOA example-ns.com. admin.example.com. 100 3600
        #  600 86400 3600
        # ;AUTHORITY
        # ;ADDITIONAL
        poll_response = ("271184000001000100000000076578616d706c6503636f6d0000"
                         "060001c00c0006000100000e1000290a6578616d706c652d6e73"
                         "c0140561646d696ec00c0000006400000e100000025800015180"
                         "00000e10")
        context = self.get_context()
        with patch.object(dns.query, 'udp', return_value=dns.message.from_wire(
                binascii.a2b_hex(poll_response))):
            status, serial, retries = self.notify.get_serial_number(
                context, objects.Zone.from_dict(self.test_zone),
                self.nameserver.host, self.nameserver.port, 0, 0, 2, 0)
            self.assertEqual(status, 'SUCCESS')
            self.assertEqual(serial, self.test_zone['serial'])
            self.assertEqual(retries, 2) 
Example #20
Source File: test_notify.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_send_notify_message(self):
        # id 10001
        # opcode NOTIFY
        # rcode NOERROR
        # flags QR AA
        # ;QUESTION
        # example.com. IN SOA
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_notify_response = ("2711a4000001000000000000076578616d706c650"
                                    "3636f6d0000060001")
        context = self.get_context()
        with patch.object(dns.query, 'udp', return_value=dns.message.from_wire(
                binascii.a2b_hex(expected_notify_response))):
            response, retry = self.notify.notify_zone_changed(
                context, objects.Zone.from_dict(self.test_zone),
                self.nameserver.host, self.nameserver.port, 0, 0, 2, 0)
            self.assertEqual(response, dns.message.from_wire(
                binascii.a2b_hex(expected_notify_response)))
            self.assertEqual(retry, 1) 
Example #21
Source File: test_handler.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_dispatch_opcode_query_unsupported_recordtype(self):
        # query is for example.com. IN DNAME
        payload = "271901000001000000000000076578616d706c6503636f6d0000270001"

        # expected_response is REFUSED.  The other fields are
        # id 10009
        # opcode QUERY
        # rcode REFUSED
        # flags QR RD
        # ;QUESTION
        # example.com. IN DNAME
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b"271981050001000000000000076578616d706c6503636f"
                             b"6d0000270001")

        request = dns.message.from_wire(binascii.a2b_hex(payload))
        request.environ = {'addr': self.addr, 'context': self.context}
        response = next(self.handler(request)).to_wire()

        self.assertEqual(expected_response, binascii.b2a_hex(response)) 
Example #22
Source File: hex_codec.py    From meddle with MIT License 6 votes vote down vote up
def hex_decode(input,errors='strict'):

    """ Decodes the object input and returns a tuple (output
        object, length consumed).

        input must be an object which provides the bf_getreadbuf
        buffer slot. Python strings, buffer objects and memory
        mapped files are examples of objects providing this slot.

        errors defines the error handling to apply. It defaults to
        'strict' handling which is the only currently supported
        error handling for this codec.

    """
    assert errors == 'strict'
    output = binascii.a2b_hex(input)
    return (output, len(input)) 
Example #23
Source File: test_handler.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_dispatch_opcode_query_non_existent_zone(self):
        # DNS packet with QUERY opcode
        # query is for example.com. IN A
        payload = ("271501200001000000000001076578616d706c6503636f6d0000010001"
                   "0000291000000000000000")

        # expected_response is an error code REFUSED.  The other fields are
        # id 10005
        # opcode QUERY
        # rcode REFUSED
        # flags QR RD
        # edns 0
        # payload 8192
        # ;QUESTION
        # example.com. IN A
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b"271581050001000000000001076578616d706c6503636f"
                             b"6d00000100010000292000000000000000")
        request = dns.message.from_wire(binascii.a2b_hex(payload))
        request.environ = {'addr': self.addr, 'context': self.context}
        response = next(self.handler(request)).to_wire()

        self.assertEqual(expected_response, binascii.b2a_hex(response)) 
Example #24
Source File: hex_codec.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def hex_decode(input,errors='strict'):

    """ Decodes the object input and returns a tuple (output
        object, length consumed).

        input must be an object which provides the bf_getreadbuf
        buffer slot. Python strings, buffer objects and memory
        mapped files are examples of objects providing this slot.

        errors defines the error handling to apply. It defaults to
        'strict' handling which is the only currently supported
        error handling for this codec.

    """
    assert errors == 'strict'
    output = binascii.a2b_hex(input)
    return (output, len(input)) 
Example #25
Source File: server.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def handle_email_opened(self, query):
		# image size: 43 Bytes
		img_data = '47494638396101000100800100000000ffffff21f90401000001002c00000000'
		img_data += '010001000002024c01003b'
		img_data = binascii.a2b_hex(img_data)
		self.send_response(200)
		self.send_header('Content-Type', 'image/gif')
		self.send_header('Content-Length', str(len(img_data)))
		self.end_headers()
		self.wfile.write(img_data)

		msg_id = self.get_query('id')
		if not msg_id:
			return
		self.semaphore_acquire()
		query = self._session.query(db_models.Message)
		query = query.filter_by(id=msg_id, opened=None)
		message = query.first()
		if message and not message.campaign.has_expired:
			message.opened = db_models.current_timestamp()
			message.opener_ip = self.get_client_ip()
			message.opener_user_agent = self.headers.get('user-agent', None)
			self._session.commit()
		signals.send_safe('email-opened', self.logger, self)
		self.semaphore_release() 
Example #26
Source File: hex_codec.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def decode(self, input, final=False):
        assert self.errors == 'strict'
        return binascii.a2b_hex(input) 
Example #27
Source File: test_handler.py    From designate with Apache License 2.0 5 votes vote down vote up
def test_dispatch_opcode_notify_same_serial(self, func):
        # DNS packet with NOTIFY opcode
        payload = "c38021000001000000000000076578616d706c6503636f6d0000060001"

        master = "10.0.0.1"
        zone = self._get_secondary_zone({"serial": 123})

        # expected response is an error code NOERROR.  The other fields are
        # id 50048
        # opcode NOTIFY
        # rcode NOERROR
        # flags QR AA RD
        # ;QUESTION
        # example.com. IN SOA
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b"c380a5000001000000000000076578616d706c6503636f"
                             b"6d0000060001")

        # The SOA serial should be different from the one in thezone and
        # will trigger a AXFR
        func.return_value = self._get_soa_answer(zone.serial)

        request = dns.message.from_wire(binascii.a2b_hex(payload))
        request.environ = {
            'addr': (master, 53),
            'context': self.context
        }

        with mock.patch.object(self.handler.storage, 'find_zone',
                               return_value=zone):
            response = next(self.handler(request)).to_wire()

        assert not self.mock_tg.add_thread.called
        self.assertEqual(expected_response, binascii.b2a_hex(response)) 
Example #28
Source File: test_handler.py    From designate with Apache License 2.0 5 votes vote down vote up
def test_dispatch_opcode_notify_invalid_zone(self):
        # DNS packet with NOTIFY opcode
        payload = "c38021000001000000000000076578616d706c6503636f6d0000060001"

        # expected response is an error code NOTAUTH.  The other fields are
        # id 50048
        # opcode NOTIFY
        # rcode NOTAUTH
        # flags QR RD
        # ;QUESTION
        # example.com. IN SOA
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b"c380a1090001000000000000076578616d706c6503636f"
                             b"6d0000060001")

        request = dns.message.from_wire(binascii.a2b_hex(payload))
        request.environ = {
            'addr': ("10.0.0.2", 53),
            'context': self.context
        }

        response = next(self.handler(request)).to_wire()

        assert not self.mock_tg.add_thread.called
        self.assertEqual(expected_response, binascii.b2a_hex(response)) 
Example #29
Source File: core.py    From p2p-python with MIT License 5 votes vote down vote up
def generate_shared_key(sk, vk_str) -> bytes:
    vk = VerifyingKey.from_string(a2b_hex(vk_str), NIST256p)
    point = sk.privkey.secret_multiplier * vk.pubkey.point
    return sha256(point.x().to_bytes(32, 'big')).digest() 
Example #30
Source File: test_ip_advertisement.py    From octavia with Apache License 2.0 5 votes vote down vote up
def test_garp(self, mock_socket, mock_socket_packet, mock_netns):
        ARP_ETHERTYPE = 0x0806
        EXPECTED_PACKET_DATA = (b'\xff\xff\xff\xff\xff\xff\x00\x00^\x00S3\x08'
                                b'\x06\x00\x01\x08\x00\x06\x04\x00\x01\x00'
                                b'\x00^\x00S3\xcb\x00q\x02\xff\xff\xff\xff'
                                b'\xff\xff\xcb\x00q\x02')
        FAKE_INTERFACE = 'fake0'
        FAKE_MAC = '00005E005333'
        FAKE_NETNS = 'fake_netns'

        mock_garp_socket = mock.MagicMock()
        mock_garp_socket.getsockname.return_value = [None, None, None, None,
                                                     a2b_hex(FAKE_MAC)]
        mock_socket.return_value = mock_garp_socket

        # Test with a network namespace
        ip_advertisement.garp(FAKE_INTERFACE, '203.0.113.2', net_ns=FAKE_NETNS)

        mock_netns.assert_called_once_with(FAKE_NETNS)
        mock_garp_socket.bind.assert_called_once_with((FAKE_INTERFACE,
                                                      ARP_ETHERTYPE))
        mock_garp_socket.getsockname.assert_called_once_with()
        mock_garp_socket.send.assert_called_once_with(EXPECTED_PACKET_DATA)
        mock_garp_socket.close.assert_called_once_with()

        # Test without a network namespace
        mock_netns.reset_mock()
        mock_garp_socket.reset_mock()
        ip_advertisement.garp(FAKE_INTERFACE, '203.0.113.2')

        mock_netns.assert_not_called()
        mock_garp_socket.bind.assert_called_once_with((FAKE_INTERFACE,
                                                      ARP_ETHERTYPE))
        mock_garp_socket.getsockname.assert_called_once_with()
        mock_garp_socket.send.assert_called_once_with(EXPECTED_PACKET_DATA)
        mock_garp_socket.close.assert_called_once_with()