예제 #1
0
    def request_new_test(self, duration, interval, hmac_hex, raw_data=False):
        """Request a new test instance.

        This will allocate a new ITGRecv instance and parse the log file it
        produces. The results of this can then be retrieved with
        get_test_results() after the test has run.

        The parameters are:

        duration: Requested test duration in seconds. The ITGRecv instance will
                  be killed after this time has passed (+ a grace period of five
                  seconds).

        interval: The requested interval for data points, in milliseconds
                  (passed to ITGDec).

        hmac_hex: A hexadecimal HMAC-SHA256 of the two other parameters computed
                  by concatenating their ASCII representations. The HMAC secret
                  is configured by the operator of the control server instance.

        raw_data: Whether to store and return the raw text log from ITGDec (i.e.
                  the output of ITGDec -l)

        The return value is a dictionary with the following keys:

        status: 'OK' if everything went well, 'Error' otherwise.

        message: Set if status is 'Error'; contains an error message.

        test_id: The assigned test ID, to be passed to get_test_results() after
                 the duration has expired.

        port: The control server port of the ITGRecv instance. The sender is
              expected to use port+1 for the data connection.

        """
        self._collect_garbage()
        duration = int(duration)
        interval = int(interval)
        hmac = self.hmac.copy()
        hmac.update(str(duration).encode())
        hmac.update(str(interval).encode())
        if hmac.hexdigest() != hmac_hex:
            return {"status": "Error", "message": "HMAC authentication failure."}
        if duration <= 0 or interval <= 0:
            return {"status": "Error", "message": "Duration and interval must be positive integers."}
        if duration > self.max_test_time:
            return {"status": "Error", "message": "Maximum test time of %d seconds exceeded." % self.max_test_time}
        if interval > duration * 1000:
            return {"status": "Error", "message": "Interval must be <= duration."}
        if len(self.children) >= self.max_instances:
            return {"status": "Error", "message": "Too many concurrent instances running. " "Try again later."}

        test_id = "".join(random.sample(ALPHABET, self.id_length))
        # Need one port for control, one for data (if the data stream is TCP).
        port = self.current_port
        self.current_port += 2
        return self._spawn_receiver(test_id, duration, interval, port, raw_data)
예제 #2
0
    def reference_generate_code_from_time(self, secret_key):
        """Reference implementation of generate_code_from_time method.

        A reference/alternate implementation of Otp.generate_code_from_time()
        which is to be used to generate expected values for unit tests.

        Returns:
            A tuple containing:
                * The time-based OTP, as a string of digits.
                * The integer number of seconds remaining in the current
                  interval.

        """
        import time
        import datetime
        from hashlib import sha1
        import hmac

        cut = HOTP()
        # message := current Unix time ÷ 30
        #
        local_now = datetime.datetime.now()
        seconds_now = time.mktime(local_now.timetuple())
        intervals = seconds_now // 30
        remaining_seconds = seconds_now - (intervals * 30)
        message = cut.num_to_counter(intervals)
        # hash := HMAC-SHA1(key, message)
        #
        hmac = hmac.new(secret_key, message, sha1)
        hash = hmac.hexdigest()
        # offset := last nibble of hash
        #
        offset = int("0" + hash[-1], 16)
        offset *= 2
        # truncated_hash := hash[offset..offset+3]
        # (that is 4 bytes starting at the offset)
        #
        truncated_hash = hash[offset:offset + (4 * 2)]
        # Set the first bit of truncated_hash to zero
        # (remove the most significant bit)
        #
        new_high_order_byte = hex(
            int(truncated_hash[0:2], 16) & int('7F', 16))[2:]
        new_high_order_byte = \
            "0" * (2 - len(new_high_order_byte)) + new_high_order_byte
        truncated_hash = new_high_order_byte + truncated_hash[2:]
        # code := truncated_hash mod 1000000
        #
        int_hash = int(truncated_hash, 16)
        code = int_hash % 1000000
        # pad code with 0 until length of code is 6
        #
        code_string = str(code)
        code_string = "0" * (6 - len(code_string)) + code_string
        # return code
        #
        return code_string, int(30 - remaining_seconds)
예제 #3
0
    def reference_generate_code_from_time(self, secret_key):
        """Reference implementation of generate_code_from_time method.

        A reference/alternate implementation of Otp.generate_code_from_time()
        which is to be used to generate expected values for unit tests.

        Returns:
            A tuple containing:
                * The time-based OTP, as a string of digits.
                * The integer number of seconds remaining in the current
                  interval.

        """
        import time
        import datetime
        from hashlib import sha1
        import hmac

        cut = HOTP()
        # message := current Unix time ÷ 30
        #
        local_now = datetime.datetime.now()
        seconds_now = time.mktime(local_now.timetuple())
        intervals = seconds_now // 30
        remaining_seconds = seconds_now - (intervals * 30)
        message = cut.num_to_counter(intervals)
        # hash := HMAC-SHA1(key, message)
        #
        hmac = hmac.new(secret_key, message, sha1)
        hash = hmac.hexdigest()
        # offset := last nibble of hash
        #
        offset = int("0" + hash[-1], 16)
        offset *= 2
        # truncated_hash := hash[offset..offset+3]
        # (that is 4 bytes starting at the offset)
        #
        truncated_hash = hash[offset: offset + (4 * 2)]
        # Set the first bit of truncated_hash to zero
        # (remove the most significant bit)
        #
        new_high_order_byte = hex(
            int(truncated_hash[0:2], 16) & int('7F', 16))[2:]
        new_high_order_byte = \
            "0" * (2 - len(new_high_order_byte)) + new_high_order_byte
        truncated_hash = new_high_order_byte + truncated_hash[2:]
        # code := truncated_hash mod 1000000
        #
        int_hash = int(truncated_hash, 16)
        code = int_hash % 1000000
        # pad code with 0 until length of code is 6
        #
        code_string = str(code)
        code_string = "0" * (6 - len(code_string)) + code_string
        # return code
        #
        return code_string, int(30 - remaining_seconds)
예제 #4
0
파일: API.py 프로젝트: FuFujeon/Darktrace
def dtapicall(appliance,
              query,
              publickey,
              privatekey,
              timemod=0,
              verifySSL=False):
    """Returns JSON-formatted data from the Darktrace <appliance> specified, using the <query> specified, and the <publickey> and <privatekey> supplied

    <appliance> is the full URL of the appliance, for example 'https://10.1.2.3'
    <query> is the API query you are passing to the appliance, for example '/metrics'
    <publickey> is the public key which is provided from the Darktrace appliance (provided by the reseller)
    <privatekey> is the private key which is provided from the Darktrace appliance (provided by the reseller)

    optional <timemod> allows you to modify the current time passed (default=0) to the API to allow for timezone differences, e.g., passing 59 will add 59 minutes to the time, -59 will take off 59 minutes.
    optional <verifySSL> allow you to ignore cert errors (default=False) when making the call

    If successful it returns an object containing JSON-formatted data matching your query.

    @leighhall / madsky.co.uk
    Version: 1.0 / Aug 2015

    """

    import datetimekkk
    import hmac
    import hashlib
    import requests

    # today = datetime.datetime.today()
    today = datetime.datetime.utcnow()
    today = today + datetime.timedelta(minutes=timemod)
    format = "%Y%m%dT%H%M%S"
    dt = today.strftime(format)

    hmac = hmac.new(privatekey, query + "\n" + publickey + "\n" + dt,
                    hashlib.sha1)

    payload = {
        'DTAPI-Token': publickey,
        'DTAPI-Date': dt,
        'DTAPI-Signature': hmac.hexdigest()
    }

    r = requests.get(appliance + query, headers=payload, verify=verifySSL)
    ret = r.json()

    return ret
예제 #5
0
파일: dtapi.py 프로젝트: madsky/dtapi
def dtapicall(appliance, query, publickey, privatekey, timemod=0, verifySSL=False):
	"""Returns JSON-formatted data from the Darktrace <appliance> specified, using the <query> specified, and the <publickey> and <privatekey> supplied
	
	<appliance> is the full URL of the appliance, for example 'https://10.1.2.3'
	<query> is the API query you are passing to the appliance, for example '/metrics'
	<publickey> is the public key which is provided from the Darktrace appliance (provided by the reseller)
	<privatekey> is the private key which is provided from the Darktrace appliance (provided by the reseller)
	
	optional <timemod> allows you to modify the current time passed (default=0) to the API to allow for timezone differences, e.g., passing 59 will add 59 minutes to the time, -59 will take off 59 minutes.
	optional <verifySSL> allow you to ignore cert errors (default=False) when making the call

	If successful it returns an object containing JSON-formatted data matching your query.
	
	@leighhall / madsky.co.uk
	Version: 1.0 / Aug 2015

	"""
	
	import datetime
	import hmac
	import hashlib
	import requests

	#today = datetime.datetime.today()
	today = datetime.datetime.utcnow() 
	today = today + datetime.timedelta(minutes=timemod)
	format = "%Y%m%dT%H%M%S"
	dt = today.strftime(format)

	hmac = hmac.new(privatekey, query+"\n"+publickey+"\n"+dt, hashlib.sha1)

	payload = {
		'DTAPI-Token': publickey,
		'DTAPI-Date': dt,
		'DTAPI-Signature': hmac.hexdigest()
	}

	r = requests.get(appliance+query, headers=payload, verify=verifySSL)
	ret = r.json()

	return ret
예제 #6
0
    def request_new_test(self, duration, interval, hmac_hex):
        """Request a new test instance.

        This will allocate a new ITGRecv instance and parse the log file it produces.
        The results of this can then be retrieved with get_test_results() after the
        test has run.

        The parameters are:

        duration: Requested test duration in seconds. The ITGRecv instance will be killed
                  after this time has passed (+ a grace period of five seconds).

        interval: The requested interval for data points, in milliseconds (passed to ITGDec).

        hmac_hex: A hexadecimal HMAC-SHA256 of the two other parameters computed by
                  concatenating their ASCII representations. The HMAC secret is configured
                  by the operator of the control server instance.

        The return value is a dictionary with the following keys:

        status: 'OK' if everything went well, 'Error' otherwise.

        message: Set if status is 'Error'; contains an error message.

        test_id: The assigned test ID, to be passed to get_test_results() after the duration
                 has expired.

        port:    The control server port of the ITGRecv instance. The sender is expected to
                 use port+1 for the data connection.
        """
        self._collect_garbage()
        duration = int(duration)
        interval = int(interval)
        hmac = self.hmac.copy()
        hmac.update(str(duration).encode())
        hmac.update(str(interval).encode())
        if hmac.hexdigest() != hmac_hex:
            return {
                'status': 'Error',
                'message': "HMAC authentication failure."
            }
        if duration <= 0 or interval <= 0:
            return {
                'status': 'Error',
                'message': "Duration and interval must be positive integers."
            }
        if duration > self.max_test_time:
            return {
                'status':
                'Error',
                'message':
                "Maximum test time of %d seconds exceeded." %
                self.max_test_time
            }
        if interval > duration * 1000:
            return {
                'status': 'Error',
                'message': "Interval must be <= duration."
            }
        if len(self.children) >= self.max_instances:
            return {
                'status':
                'Error',
                'message':
                "Too many concurrent instances running. Try again later."
            }

        test_id = "".join(random.sample(ALPHABET, self.id_length))
        # Need one port for control, one for data (if the data stream is TCP).
        port = self.current_port
        self.current_port += 2
        return self._spawn_receiver(test_id, duration, interval, port)
예제 #7
0
 def get_hexdigest(self, raw_udid):
     salt = 'QJ7@cqBQdLy$mqr+'
     hmac = salted_hmac(salt, raw_udid)
     return hmac.hexdigest()
예제 #8
0
파일: t_hash.py 프로젝트: luyj/ac-demo
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import hashlib  # https://docs.python.org/3/library/hashlib.html
import hmac

t_str = "中国传媒大学"
t_bytes = t_str.encode('utf8')

m = hashlib.sha256()  # 比 new('sha256') 方式的性能好
m.update(t_bytes)

print('原始格式数据:', end='')
print(m.digest())
print('16 进制表示:' + m.digest().hex())
print('16 进制表示:' + m.hexdigest())

h = hashlib.new('sha256')
h.update(t_bytes)
print(h.hexdigest())

hmac = hmac.new(b'password', t_bytes,
                'sha256')  # https://docs.python.org/3/library/hmac.html
print(hmac.hexdigest()
      )  # php -r 'echo hash_hmac('sha256', '中国传媒大学', 'password');'

# salt should be about 16 or more bytes from a proper source, e.g. os.urandom(16).
# php -r 'echo hash_pbkdf2("sha256", "password", "salt", 100000);'
dk = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000)
print(dk.hex())
예제 #9
0
def hmac_use():
    global hmac
    key = b'key'
    msg = b'hello world'
    hmac = hmac.new(key=key, msg=msg, digestmod='MD5')
    print(hmac.hexdigest())
예제 #10
0
파일: A3.py 프로젝트: ramith123/ISS-Finals
def sendHmac(hmac):
    # This function converts hmac object to a hexadecimal digest and send it to bob
    digest = hmac.hexdigest()
    sock = makeServer()
    conn = listenForConnection(sock)
    sendData(digest, conn)
예제 #11
0
def truncate(hmac):
    digest = hmac.hexdigest()
    return format(int(digest[:2], 16), "03d")
예제 #12
0
#!/usr/bin/env python 
# -*- coding:utf-8 -*-

import hashlib
import hmac

#计算md5值
m=hashlib.md5()
m.update(b"abcdefg")
m.update(b"hello")
print(m.digest())
print(m.hexdigest())

#计算sha1值
oSHA1=hashlib.sha256()
oSHA1.update("hello baby!".encode("utf-8"))
print("sha1值为:"+oSHA1.hexdigest())


#hamc方式,即md5+salt格式的标准化方法
message=b"abcdefghijlmn"
key=b'hello'
hmac=hmac.new(key,message,digestmod="md5")
print("hmac算法结果:"+hmac.hexdigest())