Exemple #1
0
def client():
    client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_sock.connect((HOST, PROTOCOL))
    # generate a needed for diffie hellman
    a = secrets.randbelow(MODPGROUP["1536"])
    g_with_a = GroupOp.mod_exp(GENERATOR, a, MODPGROUP["1536"])
    if not net_utils.send_msg("({},{})".format(g_with_a, EMAIL), client_sock):
        raise ValueError("Failed to send message")
    message_received = net_utils.receive_msg(client_sock)

    msg_ints = literal_eval(message_received.decode('utf-8'))
    salt = msg_ints[0]
    b_value = msg_ints[1]
    sha_pw_digest = sha256.SHA256()
    sha_pw_digest.Update(
        bytes("{}||{}".format(salt, PASSWORD), encoding='utf-8'))
    x_exp = sha_pw_digest.Sum()
    u_digest = sha256.SHA256()
    u_digest.Update(bytes("{}||{}".format(g_with_a, b_value),
                          encoding='utf-8'))
    u = u_digest.Sum()

    v_value = GroupOp.mod_exp(GENERATOR, x_exp, MODPGROUP["1536"])
    total = (b_value - (K * v_value)) % MODPGROUP["1536"]
    total = GroupOp.mod_exp(total, a + (x_exp * u), MODPGROUP["1536"])

    key_digest = sha256.SHA256()
    key_digest.Update(bytes("{}".format(total), encoding='utf-8'))
    actual_key = (key_digest.Sum()).to_bytes(256 // 8, byteorder='big')
    verification_check = hmac_myimpl.SHA256_HMAC(actual_key, salt)
    if not net_utils.send_msg(verification_check, client_sock):
        raise ValueError("Could not send over pipe")
Exemple #2
0
    def verify_login(self, u_id, password):
        """
            verifies user id and password for login
            Args:
                u_id - user email to be added
                password - password to be added (unhashed)
            Returns:
                status code - to signal error or success back to server
        """
        users = self.db.users

        # hash user provided password using sha256
        login_hash = sha256.SHA256(password).hexdigest()

        user = users.find_one({"u_id": u_id})

        # if no user with the u_id is found
        if user is None:
            return 431
        else:
            # compare user hashed password to hash stored in database
            if (user.get('password') == login_hash):
                return 102
            else:
                return 431
Exemple #3
0
def offline_attack(client_key_share, salt, client_output, pw_dictionary):
    for psw in pw_dictionary:
        sha_pw_digest = sha256.SHA256()
        sha_pw_digest.Update(bytes("{}||{}".format(salt,psw), encoding='utf-8'))
        x_exp = sha_pw_digest.Sum()

        g_to_the_x = GroupOp.mod_exp(CP36.GENERATOR, x_exp, CP36.MODPGROUP["1536"])
        potential_s = (g_to_the_x * client_key_share) % CP36.MODPGROUP["1536"]
        key_digest = sha256.SHA256()
        key_digest.Update(bytes("{}".format(potential_s), encoding='utf-8'))
        actual_key = (key_digest.Sum()).to_bytes(256 // 8,byteorder='big')

        check_against = hmac_myimpl.SHA256_HMAC(actual_key, salt)
        if client_output == check_against:
            return psw
    return None
Exemple #4
0
def simple_srp(email, client_share, client_sock):
    # try and receive msg from pipe
    b = secrets.randbelow(CP36.MODPGROUP["1536"])
    salt, v = server_user_list[email]
    
    g_with_b = GroupOp.mod_exp(CP36.GENERATOR, b, CP36.MODPGROUP["1536"])
    u = secrets.randbelow(2**128)
    server_msg = "({},{},{})".format(salt, g_with_b, u)
    
    if not net_utils.send_msg(server_msg, client_sock):
        raise ValueError("Failed writing to pipe")

    client_hmac_val = net_utils.receive_msg(client_sock)

    total = GroupOp.mod_exp(v,u, CP36.MODPGROUP["1536"])
    total = (total *  client_share) % CP36.MODPGROUP["1536"]
    total = GroupOp.mod_exp(total, b, CP36.MODPGROUP["1536"])
    key_digest = sha256.SHA256()
    key_digest.Update(bytes("{}".format(total), encoding='utf-8'))
    actual_key = (key_digest.Sum()).to_bytes(256 // 8,byteorder='big')

    check_against = hmac_myimpl.SHA256_HMAC(actual_key, salt)

    # this comparison is very insecure
    if client_hmac_val == check_against:
        return True
    else:
        return False
    return
Exemple #5
0
def generate_v(salt, password):
    sha256_string = sha256.SHA256()
    salt_hash_concat = "{}||{}".format(salt, password)
    sha256_string.Update(bytes(salt_hash_concat, encoding='utf-8'))
    x = sha256_string.Sum()
    # this is a random numerical value -- not a string although it should be one
    v = GroupOp.mod_exp(GENERATOR, x, MODPGROUP["1536"])
    return v
Exemple #6
0
def client(email, password, new_user=False):
    client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_sock.connect((HOST,PROTOCOL))

    if new_user:
        msg = "CREATE_PASSWORD:({},{})".format(email, password)
        if not net_utils.send_msg(msg, client_sock):
            raise ValueError("Failed to send message")

        # wait to receive a SUCCESSFUL from the server
        server_reply = (net_utils.receive_msg(client_sock)).decode('utf-8')
        if server_reply != "SUCCESS":
            raise ValueError("Could not create account")
        else:
            print("Successfully created account")
    else:
        # generate a needed for diffie hellman
        a = secrets.randbelow(CP36.MODPGROUP["1536"])
        g_with_a = GroupOp.mod_exp(CP36.GENERATOR, a, CP36.MODPGROUP["1536"])
        if not net_utils.send_msg("AUTH_ATTEMPT:({},{})".format(g_with_a, email),client_sock):
            raise ValueError("Failed to send message")
        message_received = net_utils.receive_msg(client_sock)
         
        msg_ints = literal_eval(message_received.decode('utf-8'))
        salt = msg_ints[0]
        b_value = msg_ints[1]
        u = msg_ints[2]
        sha_pw_digest = sha256.SHA256()
        sha_pw_digest.Update(bytes("{}||{}".format(salt, password), encoding='utf-8'))
        x_exp = sha_pw_digest.Sum()
       
        total = GroupOp.mod_exp(b_value, a + (x_exp * u), CP36.MODPGROUP["1536"])

        key_digest = sha256.SHA256()
        key_digest.Update(bytes("{}".format(total), encoding='utf-8'))
        actual_key = (key_digest.Sum()).to_bytes(256 // 8,byteorder='big')
        verification_check = hmac_myimpl.SHA256_HMAC(actual_key, salt)
        if not net_utils.send_msg(verification_check, client_sock):
            raise ValueError("Could not send over pipe")
        msg = (net_utils.receive_msg(client_sock)).decode('utf-8')
        print("Server says {}".format(msg))
        print("Finishing client thread")

    return
Exemple #7
0
def server_srp(client_sock, email_held, salt, v_held):
    # try and receive msg from pipe
    b = secrets.randbelow(MODPGROUP["1536"])
    client_msg = (net_utils.receive_msg(client_sock)).decode('utf-8')
    args = client_msg.split(",")
    email = args[1][:-1]
    client_key_share = int(args[0][1:])

    if email == email_held:
        g_with_b = GroupOp.mod_exp(GENERATOR, b, MODPGROUP["1536"])
        maskedv = (K * v_held + g_with_b) % MODPGROUP["1536"]
        server_msg = "({},{})".format(salt, maskedv)
    else:
        print("Server received wrong email identifier")
        server_msg = "ERROR"

    if not net_utils.send_msg(server_msg, client_sock):
        raise ValueError("Failed writing to pipe")
    client_hmac_val = net_utils.receive_msg(client_sock)
    #compute local
    u_hash = sha256.SHA256()
    u_hash.Update(
        bytes("{}||{}".format(client_key_share, maskedv), encoding='utf-8'))
    u = u_hash.Sum()

    total = GroupOp.mod_exp(v_held, u, MODPGROUP["1536"])
    total = (total * client_key_share) % MODPGROUP["1536"]
    total = GroupOp.mod_exp(total, b, MODPGROUP["1536"])
    key_digest = sha256.SHA256()
    key_digest.Update(bytes("{}".format(total), encoding='utf-8'))
    actual_key = (key_digest.Sum()).to_bytes(256 // 8, byteorder='big')

    check_against = hmac_myimpl.SHA256_HMAC(actual_key, salt)

    # this comparison is very insecure
    if client_hmac_val == check_against:
        print("{} client succesfully authenticated".format(email_held))
        return True
    else:
        return False
Exemple #8
0
 def __init__(self, curve=_default_curve, n=_default_n, P=None):
     self._curve = curve
     self._n = n  # order of base point
     self._L_n = self._n.bit_length()
     if P is None:
         self._P = self._calculate_base_point()  # base point
     else:
         self._P = P
     self._d = self._calculate_private_key()  # private key
     self._Q = self._calculate_public_key()  # public key
     self._e, self._F_e = self._calculate_pre_signature(
     )  # e and pre-signature
     self._L_h = 256
     self._H = sha256.SHA256()
     self._iH = 'SHA-256'
     self._L_D = math.ceil((2 * self._L_n) / 16) * 16
Exemple #9
0
def sha256_with_secret_round_keys(m: bytes, secret_round_keys: dict) -> bytes:
    """Computes SHA256 with some secret round keys.

  Args:
    m: the message to hash
    secret_round_keys: a dictionary where secret_round_keys[i] is the value of
      the round key k[i] used in SHA-256

  Returns:
    the digest
  """
    sha = sha256.SHA256()
    round_keys = sha.k[:]
    for i, v in secret_round_keys.items():
        round_keys[i] = v
    return sha.sha256(m, round_keys)
Exemple #10
0
def get_states(msg: bytes, digest: bytes, round_keys=None):
    sha = sha256.SHA256()
    states = [ExtendedState() for i in range(65)]
    m_padded = sha.padding(msg)
    if len(m_padded) != 64:
        raise ValueError('not implemented')
    w = sha.compute_w(m_padded)
    last = struct.unpack('>8L', digest)
    d = [(x - y) & 0xffffffff for x, y in zip(last, sha.h)]
    s = states[-1]
    s.a, s.b, s.c, s.d, s.e, s.f, s.g, s.h = d
    s = states[0]
    s.a, s.b, s.c, s.d, s.e, s.f, s.g, s.h = sha.h
    for i, wi in enumerate(w):
        states[i].w = wi
    for i, k in enumerate(round_keys):
        states[i].k = k
    return states
Exemple #11
0
def attacker():
    print("Attacker trying to authenticate")
    email = input("Please enter the user you would like to authenticate as...")
    # generate a needed for diffie hellman
    share = input(
        "Input client share (i.e. g**a) as numerical value or [number]G\n")
    changed_val = False
    if "G" in share:
        g_with_a = CP36.MODPGROUP["1536"] * int(share[:share.index("G")])
        changed_val = True
    else:
        g_with_a = int(share)

    second_client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    second_client_sock.connect((HOST, PROTOCOL))
    if not net_utils.send_msg("AUTH_ATTEMPT", second_client_sock):
        raise ValueError("Failed to send message")
    saw_okay = (net_utils.receive_msg(second_client_sock)).decode('utf-8')
    if saw_okay != "CONTINUE":
        raise ValueError("Server Error")
    if not net_utils.send_msg("({},{})".format(g_with_a, email),
                              second_client_sock):
        raise ValueError("Failed to send message")
    message_received = net_utils.receive_msg(second_client_sock)
    msg_ints = literal_eval(message_received.decode('utf-8'))
    salt = msg_ints[0]
    total = int(input("Please give integer input (i.e. S): "))
    key_digest = sha256.SHA256()
    key_digest.Update(bytes("{}".format(total), encoding='utf-8'))
    actual_key = (key_digest.Sum()).to_bytes(256 // 8, byteorder='big')

    verification_check = hmac_myimpl.SHA256_HMAC(actual_key, salt)
    if not net_utils.send_msg(verification_check, second_client_sock):
        raise ValueError("Could not send over pipe")
    response = (net_utils.receive_msg(second_client_sock)).decode('utf-8')
    print("Finishing client thread, received from server {}".format(response))
Exemple #12
0
    def create_account(self, u_id, password):
        """
            adds new account to database, password is stored as a sha256 hash
            Args:
                u_id - user email to be added
                password - password to be added (unhashed)
            Returns:
                status code - to signal error or success back to server
        """
        # get users documnet
        users = self.db.users

        # hash user provided password using sha256
        password = sha256.SHA256(password).hexdigest()

        # if user email is already in database
        if (not users.find_one({"u_id": u_id}) is None):
            return 421

        new_user = {"u_id": u_id, "password": password}

        # insert new user to database
        new_user_insert = users.insert_one(new_user)
        return 101
Exemple #13
0
    s0 = self.rotate_right(a, 2) ^ self.rotate_right(
        a, 13) ^ self.rotate_right(a, 22)
    maj = (a & b) ^ (a & c) ^ (b & c)
    tmp2 = (tmp1 + s0 + maj) & 0xffffffff
    tmp3 = (d + tmp1) & 0xffffffff
    print("Compression step:", list(map(hex, (tmp2, a, b, c, tmp3, e, f, g))))
    return (tmp2, a, b, c, tmp3, e, f, g)


if __name__ == '__main__':
    while True:
        secret_round_keys = generate_random_round_keys(NUM_KEYS)
        #print("Secret_round_keys:", secret_round_keys)
        #digest = sha256_with_secret_round_keys(MSG, secret_round_keys)
        #print('MSG Digest: {}'.format(binascii.hexlify(digest).decode()))
        sha = sha256.SHA256()
        #digest2 = sha.sha256(MSG)
        #print('MSG Digest with real SHA-256: {}'.format(binascii.hexlify(digest2).decode()))
        r = remote('sharky.2020.ctfcompetition.com', 1337)
        r.recvuntil("MSG Digest: ")
        final_state = [
            0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f,
            0x9b05688c, 0x1f83d9ab, 0x5be0cd19
        ]
        hh = r.recvline().strip()
        #hh = binascii.hexlify(digest).decode() #"39715f0da097fc779d86e4ec5221d19cec1d908d219e725b929ff540158da0c0"
        unpacked_digest = []
        for i in range(0, len(hh), 8):
            unpacked_digest.append(int(hh[i:i + 8], 16))
        #print(unpacked_digest)
        last_state = [(x - y) % 2**32
Exemple #14
0
import sha256
import struct
from telnetlib import Telnet

remote = Telnet('sharky.2020.ctfcompetition.com', 1337)
remote.read_until(b'MSG Digest: ')
target = bytes.fromhex(remote.read_until(b'\n').strip().decode())

# Processing input blocks
input = b'Encoded with random keys'

sha2 = sha256.SHA256()
state = struct.unpack('>8L', target)

block = sha2.padding(input)
assert len(block) == 64
w = sha2.compute_w(block)

# Undo last 56 rounds with known round constants
state = [(x - y) & 0xffffffff for x, y in zip(state, sha2.h)]
for k in range(63, 7, -1):
    state = sha2.decompression_step(state, sha2.k[k], w[k])

# Recover secret round constants
rk = [0] * 8
for k in range(7, -1, -1):
    # Make the error propagate to first round
    state2 = state[:]
    for i in range(k, -1, -1):
        state2 = sha2.decompression_step(state2, 0, w[i])
def _benchmark_sha256_hash(message_bytes: int):
    _helper_benchmark_hash(sha256.SHA256(), message_bytes)
def _benchmark_sha256_pow(message_bytes: int, zero_bytes: int):
    algorithm = sha256.SHA256()
    return _helper_benchmark_pow(algorithm, message_bytes, zero_bytes)
def _test_pow_correctness():
    print(_benchmark_sha256_pow(3, 2))
    print(sha256.SHA256().hash(b'\x01\xb1\x7f'))
    print(_benchmark_kupyna_pow(3, 2, 256))
    print(kupyna.Kupyna(256).hash(b'\x01\xb1\x7f'))
Exemple #18
0
 def test_instance(self):
     sha = sha256.SHA256('Hello world!')
     self.assertIsNotNone(sha)
Exemple #19
0
 def solve_state(self):
     """Tries to solve for not yet known variables in a given state."""
     sha = sha256.SHA256()
     if self.ch is None and None not in (self.e, self.f, self.g):
         self.ch = (self.e & self.f) ^ (~self.e & self.g)
     if self.maj is None and None not in (self.a, self.b, self.c):
         self.maj = (self.a & self.b) ^ (self.a & self.c) ^ (self.b
                                                             & self.c)
     if self.sigma0 is None and self.a is not None:
         self.sigma0 = (sha.rotate_right(self.a, 2)
                        ^ sha.rotate_right(self.a, 13)
                        ^ sha.rotate_right(self.a, 22))
     if self.sigma1 is None and self.e is not None:
         self.sigma1 = (sha.rotate_right(self.e, 6)
                        ^ sha.rotate_right(self.e, 11)
                        ^ sha.rotate_right(self.e, 25))
     cnt = 0
     for x in (self.tmp1, self.h, self.sigma1, self.ch, self.k, self.w):
         if x is None:
             cnt += 1
     if cnt == 1:
         if self.tmp1 is None:
             self.tmp1 = (self.h + self.sigma1 + self.ch + self.k +
                          self.w) & 0xffffffff
         else:
             diff = self.tmp1
             for x in (self.h, self.sigma1, self.ch, self.k, self.w):
                 if x is not None:
                     diff -= x
             diff &= 0xffffffff
             if self.h is None:
                 self.h = diff
             if self.sigma1 is None:
                 self.sigma1 = diff
             if self.ch is None:
                 self.ch = diff
             if self.k is None:
                 self.k = diff
             if self.w is None:
                 self.w = diff
     cnt = 0
     for x in (self.tmp2, self.tmp1, self.sigma0, self.maj):
         if x is None:
             cnt += 1
     if cnt == 1:
         if self.tmp2 is None:
             self.tmp2 = (self.tmp1 + self.sigma0 + self.maj) & 0xffffffff
         else:
             diff = self.tmp2
             for x in (self.tmp1, self.sigma0, self.maj):
                 if x is not None:
                     diff -= x
             diff &= 0xffffffff
             if self.tmp1 is None:
                 self.tmp1 = diff
             if self.sigma0 is None:
                 self.sigma0 = diff
             if self.maj is None:
                 self.maj = diff
     cnt = 0
     for x in (self.tmp3, self.tmp1, self.d):
         if x is None:
             cnt += 1
     if cnt == 1:
         if self.tmp3 is None:
             self.tmp3 = (self.d + self.tmp1) & 0xffffffff
         elif self.tmp1 is None:
             self.tmp1 = (self.tmp3 - self.d) & 0xffffffff
         else:
             self.d = (self.tmp3 - self.tmp1) & 0xffffffff