Beispiel #1
0
    def __init__(self, number, user_list, sock, addr):
        self._user_list = user_list
        self._sock = sock
        self._addr = addr
        self._user_list[sock] = self
        self._number = number
        self._speed = 57600

        #generate random data to check client
        self._auth_data = bytearray(urandom(self._AUTH_LEN))

        #generate nonce
        nonce = bytearray(urandom(self._NONCE_LEN))
        self._cipher_tx = RC4(nonce=bytearray(_CRYPTO_KEY) + nonce)
        #invert nonce for rx
        nonce_inv = []
        for _, val in enumerate(nonce):
            nonce_inv.append(val ^ 0xFF)
        self._cipher_rx = RC4(nonce=bytearray(_CRYPTO_KEY) +
                              bytearray(nonce_inv))

        self._timeout = time()
        self._wait_auth = True

        self.remote_user = None

        #send nonce with auth
        self._sock.send(nonce + self._cipher_tx.crypt(self._auth_data))
Beispiel #2
0
def do_nex(proto, method_with_flag, data):
    global last_secure_addr, last_secure_key
    method = method_with_flag & ~0x8000

    if proto == 0x0a and (method == 1 or method == 2):
        kerb_ticket, kerb_ticket_len = Buffer.unpack(data[8:])
        k, _ = KerberosContainer(
            user_pid=user_pid, user_password=user_password).unpack(kerb_ticket)
        secure_url, secure_url_len = String.unpack(data[8 + kerb_ticket_len:])
        print(secure_url)

        secure_url = dict(
            map(lambda x: x.split('='),
                secure_url.replace('prudps:/', '').split(';')))
        last_secure_addr = (secure_url['address'].encode(),
                            int(secure_url['port']))
    elif proto == 0x0a and method == 3:
        kerb_ticket, kerb_ticket_len = Buffer.unpack(data[4:])
        k, _ = KerberosContainer(
            user_pid=user_pid, user_password=user_password).unpack(kerb_ticket)
        secure_key = k[0:16]
        if k[16] != 0:
            secure_key = k[0:32]
        connections[last_secure_addr] = {
            'c_state': RC4(secure_key, reset=False),
            's_state': RC4(secure_key, reset=False)
        }
Beispiel #3
0
def main():
    charset = string.ascii_letters + string.digits
    key1 = ''.join(random.choices(charset, k=16))
    print('­ЪћЉ', key1)

    key2 = input('­ЪћЉ ')

    if key1 in key2:
        print('­Ъце')
        sys.exit(0)

    key1 = convert_key(key1)
    key2 = convert_key(key2)

    cipher1 = RC4(key1)
    cipher2 = RC4(key2)

    ciphertext1 = encrypt(cipher1, flag)
    ciphertext2 = encrypt(cipher2, flag)
    l = prefix_length(ciphertext1, ciphertext2)

    if l == 0:
        print('­Ъце')
        sys.exit(0)
    elif l != len(flag):
        print(f'­ЪЈЂ {flag[:l]}...')
    else:
        print(f'­ЪЈЂ {flag[:l]}')
Beispiel #4
0
    def __init__(self, key):
        RC4.__init__(self, key, "python")
        keyBytes = stringToBytes(key)
        S = [i for i in range(256)]
        j = 0
        for i in range(256):
            j = (j + S[i] + keyBytes[i % len(keyBytes)]) % 256
            S[i], S[j] = S[j], S[i]

        self.S = S
        self.i = 0
        self.j = 0
Beispiel #5
0
 def test_hex_text(self):
     rc4 = RC4(md5key('password'))
     hex_text = '\xfe\x85\x8f\xebjg\x81\xd0f\x9b\x98\x83'
     data = rc4.encrypt(hex_text)
     for x in data:
         print("%r" % x)
     data = rc4.decrypt(data)
     self.assertEqual(hex_text, data)
Beispiel #6
0
    def pack(self, data):
        rc = RC4(key)
        ticket = rc.crypt(full_ticket)
        ticket_mac = hmac.HMAC(key)
        ticket_mac.update(ticket)
        ticket += ticket_mac.digest()

        return ticket
Beispiel #7
0
def generate_url(config, obj):
    s = os.urandom(4)
    r = RC4(md5.md5("%s %s" % (s, config["urlkey"])).hexdigest(), burn=0)
    a = r.crypt(obj["user.password"])
    b = md5.md5(
        md5.md5("%s %s %s %s" % (config["urlsecret"], obj["user.username"], a,
                                 s)).hexdigest()).hexdigest()
    obj["url"] = "%s?m=%s&h=%s&u=%s&r=%s" % (config["url"], a.encode(
        "hex"), b, obj["user.username"].encode("hex"), s.encode("hex"))
 def trocar_algoritmo(self, algoritmo, chave):
     if algoritmo == 'sdes':
         self.algCriptografia = SDes(chave)
     elif algoritmo == 'rc4':
         self.algCriptografia = RC4(chave)
     elif algoritmo == 'none':
         self.algCriptografia = None
     else:
         print('Algoritmo inválido')
Beispiel #9
0
    def unpack(self, data):
        ticket = data[:-0x10]
        mac = data[-0x10:]

        ticket_mac = hmac.HMAC(self.key)
        ticket_mac.update(ticket)
        if ticket_mac.digest() != mac:
            raise ValueError("Kerberos MAC is invalid!")
        rc = RC4(self.key)
        dec_ticket = rc.crypt(ticket)
        return dec_ticket, len(data)
Beispiel #10
0
def main():
    my_key = [0x01, 0x02, 0x03, 0x04, 0x05]
    my_rc4 = RC4(False)
    my_rc4.load_key(my_key)
    my_file = open('rc4data.bin', 'wb')

    for my_key in range(10000000):
        my_keystream = my_rc4.generate_keystream(1)
        data = struct.pack('B', my_keystream[0])
        my_file.write(data)

    my_file.close()
def encryptData(data, seed):
    # CRC
    icv = zlib.crc32(data).to_bytes(4, 'little')
    alldata = data + icv

    # chiffrement rc4
    cipher = RC4(seed, streaming=False)
    ciphertext = cipher.crypt(alldata)

    # nouvelle donnée et ICV dans la trame modèle
    wepdata = ciphertext[:-4]
    icv = unpack('!L', ciphertext[-4:])[0]
    return wepdata, icv
Beispiel #12
0
    def test_file(self):
        w = open('../README.md', 'w')
        rc4 = RC4('password')

        generator = rc4.encrypter()
        out = ''
        with open('README.md') as f:
            for line in f:
                for c in line:
                    out += chr((ord(c) ^ generator.next()))
            w.write(out)
            out = ''

        w.close()
Beispiel #13
0
    def __init__(self, rc4_key, server, nex_client, client_addr):
        self.key = rc4_key
        self.rc4_state_encrypt = RC4(rc4_key, reset=False)
        self.rc4_state_decrypt = RC4(rc4_key, reset=False)

        self.last_seq = 1
        self.state = PRUDPV0Transport.STATE_EXPECT_SYN
        self.last_sig = None

        self.server = server
        self.nex_client = nex_client
        self.client_addr = client_addr

        self.client_signature = None
        self.server_signature = b'\xaa\xbb\xcc\xdd'
        self.session = None

        self.ack_events = {}

        # self.heartbeat_event = None
        self.timeout_event = Event(self.handle_timeout, timeout=30)
        self.server.scheduler.add(self.timeout_event)
        self.connected = False
Beispiel #14
0
def generate_activation_url(config, obj):
    r = os.urandom(16).encode("hex")
    uid = int(obj["user.id"])

    r2 = RC4(sha256("rc4 %s %s" % (r, config["activationkey"])).hexdigest())
    a = r2.crypt(obj["user.password"]).encode("hex")

    h = hmac.HMAC(
        sha256("hmac %s %s" % (r, config["activationkey"])).hexdigest())
    h.update("%d %s %s" % (uid, obj["user.username"], a))
    hd = h.hexdigest()

    obj["url"] = "%s?id=%d&h=%s&r=%s&u=%s&p=%s" % (
        config["activationurl"], uid, hd, r,
        obj["user.username"].encode("hex"), a)
def menu():
    global modo, nomeArquivoInput, nomeArquivoOutput, algCriptografia
    modo = int(input('Digite o modo de operação\n0 - Cifrar\n1 - Decifrar\n'))
    algoritmo = int(
        input('Digite o algoritmo que deseja usar\n0 - S-DES\n1 - RC4\n'))
    if algoritmo:
        chave = input('Digite a chave: ')
        algCriptografia = RC4(chave)
    else:
        chave = input('Digite 10 bits para ser a chave: ')
        algCriptografia = SDes(chave)
    if modo:
        nomeArquivoInput = input('Digite o nome  do arquivo criptografado: ')
    else:
        nomeArquivoInput = input('Digite o nome do arquivo em texto claro: ')
    nomeArquivoOutput = input(
        'Digite o nome do arquivo de saída do resultado: ')
def createPacket(data):
    # Copying the original packet, source: https://www.geeksforgeeks.org/copy-python-deep-copy-shallow-copy/ + https://stackoverflow.com/questions/4794244/how-can-i-create-a-copy-of-an-object-in-python
    packetToSend = copy.copy(arp)

    icv = crc32(bytes(data, UTF8))

    # Chiffrement RC4
    cipher = RC4(seed, streaming=False)
    ciphertext = cipher.crypt(bytes(data, UTF8) + struct.pack("<L", icv))

    # Remplacement des champs dans le packet
    packetToSend.wepdata = ciphertext[:-4]

    icvtmp = ciphertext[-4:]
    packetToSend.icv = struct.unpack("!L", icvtmp)[0]

    return packetToSend
Beispiel #17
0
def encryption(key, data, arp):
    # Calcul du CRC32 (icv) et conversion de ce dernier en unsigned int little indian
    #   Sources :   https://docs.python.org/2/library/binascii.html
    #               https://docs.python.org/2/library/struct.html
    icv = binascii.crc32(data.encode()) & 0xffffffff
    icv_enclair = struct.pack('<L', icv)

    # Constuction de la trame pour RC4
    msg = data.encode() + icv_enclair

    # Rc4 seed est composé de IV+clé
    seed = arp.iv + key

    # Chiffrement rc4
    cipher = RC4(seed, streaming=False)
    cipherText = cipher.crypt(msg)

    return cipherText
Beispiel #18
0
    def build_ticket(self,
                     user_pid=None,
                     user_password=None,
                     ticket_data=None,
                     secure_key=None,
                     step=1):
        kerberos_key = user_password.encode("ascii")
        for i in range(65000 + user_pid % 1024):
            kerberos_key = hashlib.md5(kerberos_key).digest()

        unk_u32 = struct.pack("I", step)
        full_ticket = secure_key + unk_u32 + struct.pack(
            "I", len(ticket_data)) + ticket_data

        rc = RC4(kerberos_key)
        ticket = rc.crypt(full_ticket)
        ticket_mac = hmac.HMAC(kerberos_key)
        ticket_mac.update(ticket)
        ticket += ticket_mac.digest()

        return ticket
Beispiel #19
0
    def incoming(self, wssock, source):
        '''receive data from remote server'''
        log('incoming............. start!')
        encryptor = RC4(self.key)
        generator = encryptor.encrypter()
        try:
            while True:
                m = wssock.receive()
                if m is not None:
                    reply = ''
                    for ch in str(m):
                        reply += chr((ord(ch) ^ generator.next()))

                    # print("%r" % reply)
                    source.send(reply)
                else:
                    break
        except socket.error as e:
            log('incoming socket error, %s' % (e.message))
            # raise e

        log('incoming............. end!')
Beispiel #20
0
    def test_file2(self):
        rc4 = RC4('password')
        generator = rc4.encrypter()
        w = open('../Python.pdf', 'w')
        fobj = open('../Python1.pdf')

        out = ''
        while True:
            chunk_data = fobj.read(1024 * 1024)
            if not chunk_data:
                break
            for c in chunk_data:
                out += chr((ord(c) ^ generator.next()))

            w.write(out)
            out = ''

        fobj.close()
        w.close()

        def test_decrypt_file():
            pass
def extract(zip_bytes):
    zip_file = ZipFile(zip_bytes)

    flags = {}

    for binary_name in zip_file.namelist():
        binary_bytes = io.BytesIO()

        binary_bytes.write(zip_file.read(binary_name))

        elf_file = ELFFile(binary_bytes)

        data = elf_file.get_section_by_name('.data').data()

        encrypted_flag = bytearray(data[8:data.find(b'All done!') - 1])
        key = bytes(data[-5:-1])

        keystream = RC4(key)

        flags[binary_name] = ''.join(
            map(chr, [byte ^ next(keystream) for byte in encrypted_flag]))

    return flags
Beispiel #22
0
def execute_rc4():
    rc4 = RC4()
    message, key = pre_processing_rc4()

    try:
        if sys.argv[4] == "d":
            message = message[:
                              -2]  # bug ao savar em um arquivo é adicionado mais um byte wtf !!
        elif sys.argv[4] == "e":
            pass
        else:
            print(
                "o ultimo argumento diz se é para encriptar ou descriptografar"
            )
            print(
                "digite: d  para descriptografar ou digite: e para encriptar ")
            exit(5)
    except:
        print("o ultimo argumento diz se é para encriptar ou descriptografar")
        print("digite: d  para descriptografar ou digite: e para encriptar ")
        exit(6)

    print(rc4.execute(message, key))
Beispiel #23
0
 def worker(q1, q2, z_i, exp, ptext):
     # 15 (Z_16) has bias towards 240 (Gupta), also towards 0 and 16
     # 31 (Z_32) has bias towards 224, also 0 and 32
     # 49 (Z_50) has bias towards 0, also 50
     counter1 = collections.defaultdict(int)
     key_counter1 = collections.defaultdict(int)
     # 2**17 seems to be enough for 15 (240 wins)
     # 2**19: 224 twice on the second place, three times on first
     for _ in range(2**exp): # 21 was here, 24 takes too long
         key = ''.join(random.choice(charset) for _ in range(16)) 
         key1 = convert_key(key)
         keystream = RC4(key1)
         ctext = []
         for ind, p in enumerate(ptext):
             k = keystream.next()
             ci = ord(p) ^ k
             ctext.append(ci)
             if ind == z_i:
                 key_counter1[k] += 1
                 break
         counter1[ctext[z_i]] += 1
         #return counter1
     q1.put(counter1)
     q2.put(key_counter1)
        arp.FCfield = arp.FCfield | 0x4

    # On recupère la partie du message à envoyer
    fragMessage = message[i * 36:((i + 1) * 36)]

    # On calcule le nouveau ICV
    icvMessage = zlib.crc32(fragMessage.encode()) & 0xffffffff

    # On crée le payload avec le message + l'ICV
    payload = fragMessage.encode() + struct.pack('<L', icvMessage)

    # rc4 seed est composé de IV+clé
    seed = arp.iv + key

    # On instancie l'objet RC4
    cipher = RC4(seed, streaming=True)

    # On chiffre le payload
    cipherText = cipher.crypt(payload)

    # On recupere l'ICV
    encrypted_icv = struct.unpack('!L', cipherText[-4:])[0]

    # Affichage des différentes informations concernant le fragment actuel
    print("Fragment #" + str(i))
    print('Fragment content to encrypt : ' + fragMessage + ' with the ICV ' +
          '{:x}'.format(icvMessage))
    print('Encrypted content : ' + cipherText[:-4].hex() +
          ' and the encrypted ICV is ' + cipherText[-4:].hex() + "\n")

    # On ecrit le contenu et l'ICV
Beispiel #25
0
from scapy.all import *
import binascii
from rc4 import RC4

#Cle wep BB:BB:BB:BB:BB:BB
key_to_encrypt = b'\xbb\xbb\xbb\xbb\xbb'

# Message se basant sur celui donné avec quelques modifications
clear_msg = b"\xaa\xaa\x03\x00\x00\x00\x08\x06\x00\x01\x08\x00\x06\x04\x00\x01\x90'\xe4\xeaa\xf2\xc0\xa8\x01d\x00\x00\x00\x00\x00\x00\xc0\xa9\x02\xff"
# calcul du crc du message en le mettant directement en forme
clear_icv = binascii.crc32(clear_msg).to_bytes(4, byteorder='little')

# lecture de la trame pour avoir un template
arp = rdpcap('arp.cap')[0]

# rc4 seed est composé de IV+clé
# chiffrement rc4 des données et du crc32
cipher = RC4(arp.iv + key_to_encrypt, streaming=False)
ciphertext = cipher.crypt(clear_msg + clear_icv)

# on change les données dans la trame de base
arp.wepdata = ciphertext[:-4]
# on change aussi le crc32 dans la trame de base
arp.icv = struct.unpack('!L', ciphertext[-4:])[0]

# on écrit la trame chiffrée dans fichier pcap
wrpcap("step2.cap", arp)

# envoi de la trame
sendp(arp)
__version__ = "1.0"
__email__ = "[email protected], [email protected]"
__status__ = "Prototype"

from scapy.all import *
from rc4 import RC4
import binascii

# message from capture template 'arp.cap', key and a random iv
message = b'\xaa\xaa\x03\x00\x00\x00\x08\x06\x00\x01\x08\x00\x06\x04\x00\x01\x90\x27\xe4\xea\x61\xf2\xc0\xa8\x01\x64' \
          b'\x00\x00\x00\x00\x00\x00\xc0\xa8\x01\xc8'
key = b'\xaa\xaa\xaa\xaa\xaa'
iv = b'\x01\x23\x45'

# init rc4 with a seed (iv+key)
cipher = RC4(iv + key, streaming=False)
# compute icv
icv = binascii.crc32(message).to_bytes(4, byteorder='little')
# encrypt message+icv
ciphertext = cipher.crypt(message + icv)

# read template wireshark capture
arp = rdpcap('arp.cap')[0]
# update arp wepdata, iv and icv
arp.wepdata = ciphertext[:-4]
arp.icv = struct.unpack('!L', ciphertext[-4:])[0]
arp.iv = iv

# write new wireshark capture
wrpcap('arp-encrypted.cap', arp, append=False)
Beispiel #27
0
 def __init__(self, key):
     RC4.__init__(self, key, "cryptlib")
     self.context = cryptlib_py.cryptCreateContext(cryptlib_py.CRYPT_UNUSED, cryptlib_py.CRYPT_ALGO_RC4)
     cryptlib_py.cryptSetAttribute(self.context, cryptlib_py.CRYPT_CTXINFO_KEYSIZE, len(key))
     cryptlib_py.cryptSetAttributeString(self.context, cryptlib_py.CRYPT_CTXINFO_KEY, key)
Beispiel #28
0
 def test_both(self):
     rc4 = RC4('Key')
     self.assertEqual(rc4.encrypt('plaintext'),
                      '9B F3 16 E8 D9 40 AF 0A D3')
     self.assertEqual(rc4.decrypt('9B F3 16 E8 D9 40 AF 0A D3'),
                      'plaintext')
Beispiel #29
0
 def __init__(self, key):
     RC4.__init__(self, key, "openssl")
     self.rc4 = m2.rc4_new()
     m2.rc4_set_key(self.rc4, key)
Beispiel #30
0
def encrypt(content: str = None, key: str = None):
    crypter: RC4 = RC4(key)
    return crypter.encrypt(content)
Beispiel #31
0
arp = rdpcap('arp.cap')[0]

# calcul du CRC32 (icv) et conversion de ce dernier en unsigned int little indian
#   Sources :   https://docs.python.org/2/library/binascii.html
#               https://docs.python.org/2/library/struct.html
icv = binascii.crc32(data.encode()) & 0xffffffff
icv_enclair = struct.pack('<L', icv)

# constuction de la trame pour RC4
msg = data.encode() + icv_enclair

# rc4 seed est composé de IV+clé
seed = arp.iv + key

# chiffrement rc4
cipher = RC4(seed, streaming=False)
cipherText = cipher.crypt(msg)

# on récupère le ICV et le passe en format Long big endian, puis on met à jour arp.icv
arp.icv = struct.unpack('!L', cipherText[-4:])[0]

# le message chiffré sans le ICV
arp.wepdata = cipherText[:-4]

print('Message : ' + data)
print('Encrypted Message : ' + cipherText[:-4].hex())
print("icv : " + '{:x}'.format(icv))
print("icv encrypted : " + cipherText[-4:].hex())

wrpcap(arpGenerated, arp)
def flag_decrypt(flag, key):
    keystream = RC4(key)

    return ''.join(map(chr, [b ^ next(keystream) for b in flag]))
Beispiel #33
0
ejid = RC4(key).crypt('aaa@localhost')
etokey = RC4(key).crypt('04198d91-3702-4e6e-b1d6-23888fbdf900')
print ejid
print etokey
values = {'sid':sid,'jid':ejid,'token':etokey}
data = urllib.urlencode(values)
print  data
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
print the_page
'''

url = "http://127.0.0.1:9090/plugins/sso/roster"

ejid = RC4(key).crypt('aaa@localhost')
values = {'sid': sid, 'jid': ejid}
data = urllib.urlencode(values)
print data
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
print the_page

url = "http://127.0.0.1:9090/plugins/sso/message"

jid0 = RC4(key).crypt('fjw@localhost')
jid1 = RC4(key).crypt('aaa@localhost')
emsg = RC4(key).crypt('123')
values = {'sid': sid, 'jid_0': jid0, 'jid_1': jid1, 'msg': emsg}
data = urllib.urlencode(values)