Esempio n. 1
0
    def RenFile(self, fname, new_fname):
        '''
        Rename one file. This cannot be undone, so be careful! \n\
        '''
        ti = clock()
        if not validFileName(new_fname):
            self._log(2, 'Func RenFile: a filename cannot contain any of the following characters '\
                ' \\ / : * ? " < > |')
            return -1

        md4 = MD4.new(fname)
        filename = 't'+md4.hexdigest()
        del md4
        md4 = MD4.new(new_fname)
        new_filename = 't'+md4.hexdigest()
        del md4

        # Check file existence.
        if self.c.execute('select file from _files_ where file = ?', [new_fname]).fetchone():
            self._log(2, 'Func RenFile: there is already a file called "%s"!' % new_fname)
            return -1

        try:
            self.c.execute('alter table %s rename to %s' % (filename, new_filename))
            self.c.execute('update _files_ set file = ? where file = ?', [new_fname, fname])
            self.c.execute('update _statistics_ set file = ? where file = ?', [new_fname, fname])
            self.conn.commit()
            self._log(1, 'Renaming from "%s" into "%s" took %.4f sec.' % (fname, new_fname, clock()-ti))
            return 0
        except:
            self._log(2, 'Func RenFile: cannot find the file called "%s"!' % fname)
            return -1
Esempio n. 2
0
def otp(password, seed, sequence):
    """
    Calculates a one-time password hash using the given password, seed, and
    sequence number and returns it.
    Uses the MD4/sixword algorithm as supported by TACACS+ servers.

    :type  password: str
    :param password: A password.
    :type  seed: str
    :param seed: A cryptographic seed.
    :type  sequence: int
    :param sequence: A sequence number.
    :rtype:  string
    :return: A hash.
    """
    if len(password) not in list(range(4, 64)):
        raise ValueError('passphrase length')
    if len(seed) not in list(range(1, 17)):
        raise ValueError('seed length')
    for x in seed:
        if not x in _VALIDSEEDCHARACTERS:
            raise ValueError('seed composition')
    if sequence < 0:
        raise ValueError('sequence')

    # Discard the first <sequence> keys
    thehash = MD4.new(seed + password).digest()
    thehash = _fold_md4_or_md5(thehash)
    for i in range(0, sequence):
        thehash = _fold_md4_or_md5(MD4.new(thehash).digest())

    # Generate the result
    return _sixword_from_raw(thehash)
Esempio n. 3
0
def type_1():
    if verbose == True:
        startTime = time.time()
        with open(wordlist, "r", encoding="ISO-8859-1") as FileObj:
            for line in FileObj:
                passwd1 = line.replace("\n", "")
                passwd_h = MD4.new(passwd1)
                passwd_hash = passwd_h.hexdigest()
                print("Trying \"{}\"".format(str(passwd1)))
                if user_hash == passwd_hash:
                    print("[+] Hash cracked! Results: " + str(line))
                    endTime = time.time()
                    deltaTime = endTime - startTime
                    print("[+] Cracking finished in {}s".format(
                        str(format(deltaTime, ".2f"))))
                    sys.exit()
            print("[-] Hash not found! Maybe try an other wordlist.")
            sys.exit()

    else:
        startTime = time.time()
        with open(wordlist, "r", encoding="ISO-8859-1") as FileObj:
            for line in FileObj:
                passwd1 = line.replace("\n", "")
                passwd_h = MD4.new(passwd1)
                passwd_hash = passwd_h.hexdigest()
                if user_hash == passwd_hash:
                    print("[+] Hash cracked! Results: " + str(line))
                    endTime = time.time()
                    deltaTime = endTime - startTime
                    print("[+] Cracking finished in {}s".format(
                        str(format(deltaTime, ".2f"))))
                    sys.exit()
            print("[-] Hash not found! Maybe try an other wordlist.")
            sys.exit()
Esempio n. 4
0
def otp(password, seed, sequence):
    """
    Calculates a one-time password hash using the given password, seed, and
    sequence number and returns it.
    Uses the MD4/sixword algorithm as supported by TACACS+ servers.

    :type  password: str
    :param password: A password.
    :type  seed: str
    :param seed: A cryptographic seed.
    :type  sequence: int
    :param sequence: A sequence number.
    :rtype:  string
    :return: A hash.
    """
    if len(password) not in list(range(4, 64)):
        raise ValueError('passphrase length')
    if len(seed) not in list(range(1, 17)):
        raise ValueError('seed length')
    for x in seed:
        if not x in _VALIDSEEDCHARACTERS:
            raise ValueError('seed composition')
    if sequence < 0:
        raise ValueError('sequence')

    # Discard the first <sequence> keys
    thehash = MD4.new(seed + password).digest()
    thehash = _fold_md4_or_md5(thehash)
    for i in range(0, sequence):
        thehash = _fold_md4_or_md5(MD4.new(thehash).digest())

    # Generate the result
    return _sixword_from_raw(thehash)
Esempio n. 5
0
    def CopyIntoNew(self, fname, version, new_fname):
        '''
        Copy one version of one file, into a new file, that will have version 1. \n\
        The password will be the same as in the original file. \n\
        '''
        ti = clock()
        if not validFileName(new_fname):
            self._log(2, 'Func CopyIntoNew: a file name cannot contain any of the following '\
                'characters  \\ / : * ? " < > |')
            return -1

        md4 = MD4.new(fname)
        filename = 't'+md4.hexdigest()
        del md4
        md4 = MD4.new(new_fname)
        new_filename = 't'+md4.hexdigest()
        del md4

        if version < 0 : version = 0

        # If new file name already exists, exit.
        if self.c.execute('select file from _files_ where file="%s"' % (new_fname)).fetchone():
            self._log(2, 'Func CopyIntoNew: there is already a file called "%s"!' % new_fname)
            return -1

        # Try to extract specified version.
        try:
            self.c.execute('select version from %s' % filename).fetchone()
        except:
            self._log(2, 'Func CopyIntoNew: there is no such file called "%s"!' % fname)
            return -1

        # If version was specified, get that version.
        if version:
            data = self.c.execute('select raw, hash, size from %s where version=%i' % \
                (filename, version)).fetchone()
        # Else, get the latest version.
        else:
            data = self.c.execute('select raw, hash, size from %s order by version desc' % \
                filename).fetchone()

        self.c.execute('create table %s (version integer primary key asc, raw BLOB, hash TEXT,'
            'size INTEGER, date TEXT, user TEXT)' % new_filename)
        self.c.execute(('insert into %s (raw, hash, size, date, user) values (?,?,?,?,?)' % new_filename),
            [data[0], data[1], data[2], strftime("%Y-%b-%d %H:%M:%S"), os.getenv('USERNAME')])

        # Use original password and labels of file.
        more = self.c.execute('select pwd, labels from _files_ where file=?', [fname]).fetchone()

        self.c.execute('insert into _files_ (file, pwd, labels) values (?,?,?)', (new_fname,)+more)
        self.FileStatistics(new_fname)
        self.conn.commit()

        self._log(1, 'Copying file "%s" into "%s" took %.4f sec.' % (fname, new_fname, clock()-ti))
        return 0
Esempio n. 6
0
def encipher():
    # print('start encipher()')
    # creation 256 bit session key
    try:
        bpassphrase = passphrase.encode('utf-8')
        sessionkey = MD4.new(bpassphrase).digest() + Random.new().read(16)
        # print('passphrase')
    except:
        sessionkey = Random.new().read(32)  # 256 bit
        # print('random')
    # encryption AES of the message
    f = open('data/users11.json', 'rb')
    plaintext = f.read()
    f.close()
    iv = Random.new().read(16)  # 128 bit
    obj = AES.new(sessionkey, AES.MODE_CFB, iv)
    ciphertext = iv + obj.encrypt(plaintext)
    f = open('data/users11.json', 'wb')
    f.write(bytes(ciphertext))
    f.close()
    # encryption RSA of the session key
    publickey = RSA.importKey(open('publickey.txt', 'rb').read())
    cipherrsa = PKCS1_OAEP.new(publickey)
    sessionkey = cipherrsa.encrypt(sessionkey)
    f = open('sessionkey11.txt', 'wb')
    f.write(bytes(sessionkey))
    f.close()
Esempio n. 7
0
def compute_password_nt_hash(pw):
    """Compute NT password hash.

    In practice, this is an MD4 of a password.  For details, see:

      * http://en.wikipedia.org/wiki/NTLM
      * http://tools.ietf.org/html/rfc2433
      * http://tools.ietf.org/html/rfc2759

    Note that the MD4 is computed over the UNICODE version of the
    password.  And this UNICODE version is *little endian*!
    """

    from Crypto.Hash import MD4

    pw = unicode(pw)  # if not already unicode

    # little endian unicode buffer
    t = ''
    for c in pw:
        o = ord(c)
        t += chr(o & 0xff)  # lo
        t += chr((o >> 8) & 0xff)  # hi

    return MD4.new(t).digest()
    def check_signature(self, cacert):
        """Verifies that the certificate is signed by cacert.

        Args:
        cacert: Certificate object which is suspected to be the parent
        of this one in the trust chain.

        Returns:
        True if this certificate was signed by cacert, false
        otherwise.
        """

        cakey = cacert.get_pub_key()
        cahash = None

        if self._algo == _OID_RSA_SHA1:
            cahash = SHA.new(self._certdata)
        elif self._algo == _OID_RSA_MD4:
            cahash = MD4.new(self._certdata)
        elif self._algo == _OID_RSA_MD2:
            cahash = MD2.new(self._certdata)
        elif self._algo == _OID_RSA_MD5:
            cahash = MD5.new(self._certdata)
        elif self._algo == _OID_RSA_SHA256:
            cahash = SHA256.new(self._certdata)
        else:
            raise X509SignatureAlgorithmUnsupported(
                "No algorithm known for " + self._algo)

        verifier = PKCS1_v1_5.new(cakey)
        return verifier.verify(cahash, self._signature)
Esempio n. 9
0
def generateSessionKeyV1(password, lmhash, nthash):
    if POW:
        hash = POW.Digest(POW.MD4_DIGEST)
    else:        
        hash = MD4.new()
    hash.update(NTOWFv1(password, lmhash, nthash))
    return hash.digest()
Esempio n. 10
0
def ed2k(handle):
    """
    ED2K is a rudimentary tree hash, with a depth of 1 and a leaf size of
    9,728,000 bytes. The hash is MD4, which is not natively available in
    Python, so I use PyCrypto's version instead.
    """

    buf = ''
    hashl = []
    while True:
        buf = handle.read(9728000)
        if buf == '':
            break
        hashl.append(MD4.new(buf).digest())
    hashed = MD4.new(''.join(hashl)).hexdigest()
    return hashed
Esempio n. 11
0
def generateSessionKeyV1(password, lmhash, nthash):
    if POW:
        hash = POW.Digest(POW.MD4_DIGEST)
    else:
        hash = MD4.new()
    hash.update(NTOWFv1(password, lmhash, nthash))
    return hash.digest()
Esempio n. 12
0
def compute_password_nt_hash(pw):
    """Compute NT password hash.

    In practice, this is an MD4 of a password.  For details, see:

      * http://en.wikipedia.org/wiki/NTLM
      * http://tools.ietf.org/html/rfc2433
      * http://tools.ietf.org/html/rfc2759

    Note that the MD4 is computed over the UNICODE version of the
    password.  And this UNICODE version is *little endian*!
    """

    from Crypto.Hash import MD4

    pw = unicode(pw)  # if not already unicode

    # little endian unicode buffer
    t = ''
    for c in pw:
        o = ord(c)
        t += chr(o & 0xff)         # lo
        t += chr((o >> 8) & 0xff)  # hi

    return MD4.new(t).digest()
Esempio n. 13
0
def NTOWFv2(Passwd, User, UserDom):
    if IsMD4Hash(Passwd) == False:
        Passwd = Passwd.encode('UTF-16LE')
        Hash = MD4.new(Passwd).digest()
    else:
        Hash = Passwd.decode('HEX')
    return HMAC.new(Hash, User.upper().encode('UTF-16LE') + UserDom).digest()
Esempio n. 14
0
def test(nb_chunks, chunk_size):
  h = MD4.new()
  f = open('test.txt', 'rb')
  for i in range(nb_chunks):
    h.update(f.read(chunk_size))
  f.close()
  d = h.hexdigest()
Esempio n. 15
0
def NTOWFv1(Passwd, User, UserDom):
    if IsMD4Hash(Passwd) == False:
        Passwd = Passwd.encode('UTF-16LE')
        Hash = MD4.new(Passwd).digest()
    else:
        Hash = Passwd.decode('HEX')
    return Hash
Esempio n. 16
0
def md4Hash(text: str):
    h = MD4.new()
    try:
        h.update(bytes(text, encoding='utf-8'))
        return h.hexdigest()
    #Not now
    except: Exception
Esempio n. 17
0
    def DelFile(self, fname, version=0):
        '''
        If version is a positive number, only that version of the file is deleted. \n\
        Else, the entire table is dropped. \n\
        This cannot be undone, so be careful. \n\
        '''
        ti = clock()
        md4 = MD4.new(fname)
        filename = 't'+md4.hexdigest()
        del md4

        if version > 0:
            self.c.execute('delete from %s where version=%s' % (filename, version))
            self.c.execute('reindex %s' % filename)
            self.conn.commit()
            self._log(1, 'Deleting file "%s" version "%i" took %.4f sec.' % (fname, version, clock()-ti))
            return 0
        else:
            try:
                self.c.execute('drop table %s' % filename)
                self.c.execute('delete from _files_ where file="%s"' % fname)
                self.c.execute('delete from _statistics_ where file="%s"' % fname)
                self.conn.commit()
                self._log(1, 'Deleting file "%s" took %.4f sec.' % (fname, clock()-ti))
                return 0
            except:
                self._log(2, 'Func DelFile: cannot find the file called "%s"!' % fname)
                return -1
Esempio n. 18
0
    def deriveKeysFromUser(self, sid, password):
        # Will generate two keys, one with SHA1 and another with MD4
        key1 = HMAC.new(
            SHA1.new(password.encode('utf-16le')).digest(),
            (sid + '\0').encode('utf-16le'), SHA1).digest()
        key2 = HMAC.new(
            MD4.new(password.encode('utf-16le')).digest(),
            (sid + '\0').encode('utf-16le'), SHA1).digest()
        # For Protected users
        tmpKey = pbkdf2_hmac('sha256',
                             MD4.new(password.encode('utf-16le')).digest(),
                             sid.encode('utf-16le'), 10000)
        tmpKey2 = pbkdf2_hmac('sha256', tmpKey, sid.encode('utf-16le'), 1)[:16]
        key3 = HMAC.new(tmpKey2, (sid + '\0').encode('utf-16le'),
                        SHA1).digest()[:20]

        return key1, key2, key3
Esempio n. 19
0
    def test_unicode(self):
        message = 'юникод тест'
        expected = ExpectedMD4.new()
        expected.update(message)

        actual = MD4()
        actual.update(message)
        assert actual.hexdigest() == expected.hexdigest()
Esempio n. 20
0
    def test(self):
        message = 'abcd'
        expected = ExpectedMD4.new()
        expected.update(message)

        actual = MD4()
        actual.update(message)
        assert actual.hexdigest() == expected.hexdigest()
Esempio n. 21
0
def ComputeMSCash1(password, user='******'):
    """
    Compute the MSCashv1 hash of the password. The username is used as a salt.
    https://openwall.info/wiki/john/MSCash
    Note: For Windows XP/2003 and below
    """
    h1 = ComputeNTLM(password)
    return MD4.new(h1 + user.lower().encode('utf-16-le')).digest()
Esempio n. 22
0
    def test_many_blocks(self):
        message = 'a' * (64 * 53)
        expected = ExpectedMD4.new()
        expected.update(message)

        actual = MD4()
        actual.update(message)
        assert actual.hexdigest() == expected.hexdigest()
Esempio n. 23
0
    def ExportAll(self, path, password=1):
        '''
        Export all files into one folder. \n\
        Only the most recent version of each file is exported. \n\
        The files that don't use the global password, will fail to export. \n\
        '''
        #
        ti = clock()
        #
        if not os.path.exists(path):
            self._log(2, 'Func ExportAll: path "%s" doesn\'t exist!' % path)
            return -1

        # If password is a string or unicode, get the hash.
        if type(password) == type('') or type(password) == type(u''):
            pwd_hash = buffer(
                PBKDF2(password=password,
                       salt='briefcase',
                       dkLen=16,
                       count=5000))
        # If password is database default, do nothing.
        elif password == 1:
            pwd_hash = 1
        # If password is null in some way, hash must be also null.
        else:
            password = None
            pwd_hash = None

        all_files = self.c.execute(
            'select pwd, file from _files_ order by file').fetchall()

        # Temp_file[0] = pwd, Temp_file[1] = fname.
        for temp_file in all_files:
            # If provided password != stored password...
            if temp_file[0] != pwd_hash:
                self._log(2, 'Func ExportAll: Password for file "%s" is INCORRECT! You will not be'\
                    ' able to decrypt any data!' % temp_file[1])
                continue

            # At this point, password is correct.
            fname = path + '/' + temp_file[1]
            w = open(fname, 'wb')
            md4 = MD4.new(temp_file[1])
            filename = 't' + md4.hexdigest()
            latest_version = self.c.execute(
                'select raw from %s order by version desc' %
                filename).fetchone()
            # Now write decompressed/ decrypted data.
            w.write(self._restoreb(latest_version[0], password))
            w.close()
            self._log(
                2, 'Func ExportAll: File "%s" exported successfully.' %
                temp_file[1])

        self._log(
            1, 'Exporting %i files took %.4f sec.' %
            (len(all_files), clock() - ti))
        return 0
Esempio n. 24
0
def compute_nthash(password):
    # This is done according to Samba's encryption specification (docs/html/ENCRYPTION.html)
    password = unicode(password).encode('utf_16le')
    if POW:
        hash = POW.Digest(POW.MD4_DIGEST)
    else:        
        hash = MD4.new()
    hash.update(password)
    return hash.digest()
Esempio n. 25
0
def doCrack(address, username, password):
    hash_str = getPath(address)
    m = MD4.new()
    m.update(password)
    encrypt_str = m.hexdigest()
    if encrypt_str.lower() == hash_str.lower():
        return True, 'Crack success!'
    else:
        return False, 'Crack fail!'
Esempio n. 26
0
def createNTHash(passwd):
    """Create NT hashed password."""
    from Crypto.Hash import MD4
    # we have to have UNICODE password
    pw = "".join([c + '\x00' for c in passwd])
    # do MD4 hash
    md4_context = MD4.new()
    md4_context.update(pw)
    nt_hpw = md4_context.digest()
    return base64.b16encode(nt_hpw)
Esempio n. 27
0
def compute_nthash(password):
    # This is done according to Samba's encryption specification (docs/html/ENCRYPTION.html)
    try:
        password = unicode(password).encode('utf_16le')
    except UnicodeDecodeError:
        import sys
        password = password.decode(sys.getfilesystemencoding()).encode('utf_16le')

    hash = MD4.new()
    hash.update(password)
    return hash.digest()
Esempio n. 28
0
    def RenFile(self, fname, new_fname):
        '''
        Rename one file. This cannot be undone, so be careful! \n\
        '''
        ti = clock()
        if not validFileName(new_fname):
            self._log(2, 'Func RenFile: a filename cannot contain any of the following characters '\
                ' \\ / : * ? " < > |')
            return -1

        md4 = MD4.new(fname)
        filename = 't' + md4.hexdigest()
        del md4
        md4 = MD4.new(new_fname)
        new_filename = 't' + md4.hexdigest()
        del md4

        # Check file existence.
        if self.c.execute('select file from _files_ where file = ?',
                          [new_fname]).fetchone():
            self._log(
                2, 'Func RenFile: there is already a file called "%s"!' %
                new_fname)
            return -1

        try:
            self.c.execute('alter table %s rename to %s' %
                           (filename, new_filename))
            self.c.execute('update _files_ set file = ? where file = ?',
                           [new_fname, fname])
            self.c.execute('update _statistics_ set file = ? where file = ?',
                           [new_fname, fname])
            self.conn.commit()
            self._log(
                1, 'Renaming from "%s" into "%s" took %.4f sec.' %
                (fname, new_fname, clock() - ti))
            return 0
        except:
            self._log(
                2, 'Func RenFile: cannot find the file called "%s"!' % fname)
            return -1
Esempio n. 29
0
    def FileStatistics(self, fname, silent=True):
        '''
        Generate/ return a dictionary containing the following key-value pairs : \n\
        fileName, firstSize, lastSize, firstFileDate, lastFileDate, biggestSize,
        firstFileUser, lastFileUser, fileLabels, versions. \n\
        If the file has 1 version, firstSize==lastSize and firstFileDate==lastFileDate and
        firstFileUser==lastFileUser. \n\
        On error, it returns an empty dictionary. \n\
        '''
        ti = clock()
        md4 = MD4.new(fname)
        filename = 't'+md4.hexdigest()
        del md4

        # Check file existence.
        if not self.c.execute('select file from _files_ where file = ?', [fname]).fetchone():
            self._log(2, 'Func FileStatistics: there is no such file called "%s"!' % fname)
            return {}

        # Size.
        biggestSize = self.c.execute('select size from %s order by size desc' %
            filename).fetchone()[0]
        firstFileSize = self.c.execute('select size from %s order by version asc' %
            filename).fetchone()[0]
        lastFileSize = self.c.execute('select size from %s order by version desc' %
            filename).fetchone()[0]
        # Date added.
        firstFileDate = self.c.execute('select date from %s order by version asc' %
            filename).fetchone()[0]
        lastFileDate = self.c.execute('select date from %s order by version desc' %
            filename).fetchone()[0]
        # User added.
        firstFileUser = self.c.execute('select user from %s order by version asc' %
            filename).fetchone()[0]
        lastFileUser = self.c.execute('select user from %s order by version desc' %
            filename).fetchone()[0]
        labels = self.c.execute('select labels from _files_ where file="%s"' %
            fname).fetchone()[0]
        versions = len( self.c.execute('select version from %s' % filename).fetchall() )

        self.c.execute('insert or replace into _statistics_ (file, size0, size, sizeB, '
            'date0, date, user0, user, labels) values (?,?,?,?,?,?,?,?,?)', [fname,
            firstFileSize, lastFileSize, biggestSize, firstFileDate, lastFileDate,
            firstFileUser, lastFileUser, labels])

        if not silent:
            self._log(1, 'Get properties for file "%s" took %.4f sec.' % (fname, clock()-ti))
        return {'fileName':fname, 'internFileName':filename, 'biggestSize':biggestSize,
            'firstFileSize':firstFileSize, 'lastFileSize':lastFileSize,
            'firstFileDate':firstFileDate, 'lastFileDate':lastFileDate,
            'firstFileUser':firstFileUser, 'lastFileUser':lastFileUser,
            'labels':labels, 'versions':versions}
Esempio n. 30
0
def verify_sign(public_key_loc, signature, data):
    from Crypto.PublicKey import RSA
    from Crypto.Signature import PKCS1_v1_5
    from Crypto.Hash import MD4
    pub_key = open(public_key_loc, "r").read()
    rsakey = RSA.importKey(pub_key)
    signer = PKCS1_v1_5.new(rsakey)
    digest = MD4.new()
    # Assumes the data is base64 encoded to begin with
    digest.update(data)
    if signer.verify(digest, signature):
        return True
    return False
Esempio n. 31
0
def ComputeResponseNTLMv1(User, Passwd, UserDom, ServerChallenge,
                          ClientChallenge, ServerName):
    if User == u'':
        return '\0', '', '\0' * 16
    if IsMD4Hash(Passwd) != True:
        ResponseKeyLM = LMOWFv1(Passwd, '', '')
        LmChallengeResponse = DESL(ResponseKeyLM, ServerChallenge)
    else:
        LmChallengeResponse = '\0' * 24
    ResponseKeyNT = NTOWFv1(Passwd, '', '')
    NtChallengeResponse = DESL(ResponseKeyNT, ServerChallenge)
    SessionBaseKey = MD4.new(ResponseKeyNT).digest()
    return LmChallengeResponse, NtChallengeResponse, SessionBaseKey
Esempio n. 32
0
    def on_edit(self):
        #
        fname = self.item_clicked_old
        temp_dir = tempfile.mkdtemp('__', '__py')
        filename = temp_dir + '/' + fname

        # Create temp file and return file hash.
        # This is messy, after editing, the temporary files must be destroyed.
        old_hash = self.b.ExportFile(fname=fname, path=temp_dir, execute=False)

        for i in range(3):
            if old_hash != -1:
                break
            else:
                qtTxt, qtMsg = QtGui.QInputDialog.getText(
                    self, 'Enter password', 'This file requires a password :'******'Error on edit',
                                       '<br>Wrong password 3 times !<br>')
            return

        # Execute.
        if os.name == 'posix':
            subprocess.check_output(['xdg-open', filename])
        elif os.name == 'nt':
            os.system('"%s"&exit' % filename)
        else:
            print('System not supported : `%s` !' % os.name)
            return -1

        md4 = MD4.new(open(filename, 'rb').read())
        new_hash = md4.hexdigest()
        del md4

        # Compare hashes to see if the file was edited
        if old_hash != new_hash:
            qtMsg = QtGui.QMessageBox.warning(
                self, 'Save changes ? ...',
                'File "%s" was changed! Save changes ?' % fname, 'Yes', 'No')
            if qtMsg == 0:  # Clicked yes.
                self.b.AddFile(filename)
Esempio n. 33
0
    def nt_password_hash(password):
        """
        Compute the NT password hash.

        It's the MD4 hash of the password encoded in UTF-16 bits little-endian.

        :param password: the password
        :type password: str
        :return: the bytes
        :type bytes
        """
        ctx = MD4.new()
        ctx.update(password.encode("utf-16le"))
        return ctx.digest()
Esempio n. 34
0
def compute_nthash(password):
    # This is done according to Samba's encryption specification (docs/html/ENCRYPTION.html)
    try:
        password = unicode(password).encode('utf_16le')
    except UnicodeDecodeError:
        import sys
        password = password.decode(sys.getfilesystemencoding()).encode('utf_16le')

    if POW:
        hash = POW.Digest(POW.MD4_DIGEST)
    else:        
        hash = MD4.new()
    hash.update(password)
    return hash.digest()
Esempio n. 35
0
def bf(h, dictionary):

    f = open(dictionary, 'r')
    lines = f.readlines()
    print('\033[1;34m[*]\033[0m Starting Brute Force - hash = ' + h)
    for i in lines:

        md4hasher = MD4.new()
        md4hasher.update(i[:-1])
        h2 = md4hasher.hexdigest()

        if h == h2:

            print('\033[1;32m[+]\033[0m Hash Cracked! - Password = ' + i)
Esempio n. 36
0
    def md4(self):
        """Get MD4 hash
        
        The MD4 (Message-Digest 4) algorithm is a cryptographic hash function 
        developed by Ronald Rivest in 1990. The digest length is 128 bits. The algorithm 
        has influenced later designs, such as the MD5, SHA-1 and RIPEMD algorithms.

        Returns:
            Chepy: The Chepy object. 
        """
        h = MD4.new()
        h.update(self._convert_to_bytes())
        self.state = h.hexdigest()
        return self
Esempio n. 37
0
def findPassword(CCH16, CCR24):

	# Prepare arguments for processing
	CCH16 = HexToByte(CCH16)
	CCR24 = CCR24.replace(':', ' ')
	CCR24 = CCR24.upper()
	timer = 0
	print "\n--< This may take a while..."
	print "--< Each dot below represents 10,000 attempted passwords."
	print "\n--< Cracking",
		
	for guess in dictionary:

		# Track/display timer
		timer += 1
		if timer%10000 == 0:
			print ".",
		
		# Create nt_hash for this guess using MD4 hashing algorithm.
		guess = guess.strip()					# Remove newline ('\n')
		uGuess = guess.encode('utf-16-le')		# Convert to utf-16le
		nt_hash = MD4.new(uGuess).hexdigest()
		
		# Split nt_hash into three DES keys.
		# Add the parity bits to the DES keys to make them 8-bytes each.
		des_key_1 = HexToByte(addParity(nt_hash[0:14]))
		des_key_2 = HexToByte(addParity(nt_hash[14:28]))
		des_key_3 = HexToByte(addParity(nt_hash[28:] + "0000000000"))

		# Create DES encryption objects with keys.
		des_1 = DES.new(des_key_1, DES.MODE_ECB)
		des_2 = DES.new(des_key_2, DES.MODE_ECB)
		des_3 = DES.new(des_key_3, DES.MODE_ECB)
		
		# Calculate 24-byte Client Challenge Response for this guess 
		# with the DES objects and the 16-byte Client Challenge Hash.
		ccr24_part1 = des_1.encrypt(CCH16)
		ccr24_part2 = des_2.encrypt(CCH16)
		ccr24_part3 = des_3.encrypt(CCH16)
		ccr24_guess = ByteToHex(ccr24_part1 + ccr24_part2 + ccr24_part3)
		#print "   ccr24 --> ", ccr24_guess  #DEBUG
		#print "CCR24 -----> ", CCR24, "\n"  #DEBUG
		
		# Compare the guess (ccr24_guess) with the original (CCR24).
		if ccr24_guess == CCR24:
			return guess
	
	# If no password found, return None
	return "FAILED - dictionary exhausted..."
Esempio n. 38
0
def nt_password_hash(u_password):
    """
    RFC 2759
    section 8.3
    NtPasswordHash
    :param u_password:
    :return: password_hash
    example
    password = "******"
    password_hash = "\x44\xEB\xBA\x8D\x53\x12\xB8\xD6\x11\x47\x44\x11\xF5\x69\x89\xAE"
    """
    h = MD4.new()
    h.update(u_password)
    password_hash = h.digest()
    return password_hash
Esempio n. 39
0
def breakit():
    iters = 0
    while 1:
        s = prefix + str(iters)
        hashed_s = MD4.new(s).hexdigest()
        iters = iters + 1
        r = re.match('^0e[0-9]{30}', hashed_s)
        if r:
            print "[+] found! md4( {} ) ---> {}".format(s, hashed_s)
            print "[+] in {} iterations".format(iters)
            exit(0)

        if iters % 10000000 == 0:
            print "[+] current value: {}       {} iterations, continue...".format(
                s, iters)
Esempio n. 40
0
 def nt(self):
     try:
         try:
             import smbpasswd
             hash =  smbpasswd.nthash(self.password)
         except:
             from Crypto.Hash import MD4
             hash = MD4.new(self.password.encode("utf-16-le")).hexdigest().upper()
         self.out['nt'] = {
             'header': '{nt}',
             'salt': None,
             'hash': hash }
         return hash
     except:
         return None
Esempio n. 41
0
	def decrypt_file(self, filename, bdata=True):
		'''
		Decrypt a file from the Briefcase and return all the original data, if needed.
		'''
		if not self._user_id:
			print('Cannot decrypt file! Must sign-in first!')
			return False

		fd = self._get_file_info(filename)

		encr  = fd['encr']
		fname = fd['fname']
		salt   = fd['salt']
		labels = json.loads( self._decrypt(fd['labels'], salt) )
		date   = fd['ctime']
		fhash  = fd['hash']
		bprev  = fd['preview']

		bprev = self._decrypt(bprev, salt)

		# Maybe the data should not be decrypted? It's faster this way!
		if bdata:

			if not fd['included']:
				path = os.path.split(self._filename)[0] + os.sep + encr
				bdata = open(path, 'rb').read()
			else:
				bdata = fd['data']

			bdata = self._decrypt(bdata, salt)

			if fd['compressed']:
				bdata = zlib.decompress(bdata)

			if fhash != MD4.new(bdata).digest():
				print("Invalid decrypt! The hash doesn't match!")
				return False

		return {
			'labels' : labels,
			'ctime'  : date,
			'salt'   : salt,
			'compressed': fd['compressed'],
			'included': fd['included'],
			'hash'    : fhash,
			'preview' : bprev,
			'data'    : bdata
		}
Esempio n. 42
0
    def ntowf_v2(self):
        passparts = self._password.split(':')
        if len(passparts) == 2 and len(passparts[0]) == 32 and len(passparts[1]) == 32:
            # The specified password is an LM:NTLM hash
            password_digest = binascii.unhexlify(passparts[1])
        else:
            try:
                password_digest = hashlib.new('MD4', self._password.encode('utf-16-le')).digest()
            except ValueError as e:
                try:
                    from Crypto.Hash import MD4  # try with the Crypto library if present
                    password_digest = MD4.new(self._password.encode('utf-16-le')).digest()
                except ImportError:
                    raise e  # raise original exception

        return hmac.new(password_digest, (self.user_name.upper() + self.user_domain).encode('utf-16-le'), digestmod=hashlib.md5).digest()
Esempio n. 43
0
 def write_key(self, enc, enc_vals):
     if enc == "arcfour-hmac":
         # Write out RC4 key of password
         self.write(MD4.new(self.password.encode('utf_16_le')).digest())
     elif enc.startswith("aes"):
         # Write out AES key of password
         tkey = PBKDF2(self.password, self.salt, enc_vals["bits"],
                       PBKDF2_ITERATIONS)[:enc_vals["key_length"]]
         cipher = AES.new(tkey)
         key1 = cipher.encrypt(krb5int_nfold(KRB_CONSTANT, 16))
         if enc_vals["bits"] == 256:
             key2 = cipher.encrypt(key1)
             key = key1 + key2
         else:
             key = key1
         self.write(key)
Esempio n. 44
0
    def ExportAll(self, path, password=1):
        '''
        Export all files into one folder. \n\
        Only the most recent version of each file is exported. \n\
        The files that don't use the global password, will fail to export. \n\
        '''
        #
        ti = clock()
        #
        if not os.path.exists(path):
            self._log(2, 'Func ExportAll: path "%s" doesn\'t exist!' % path)
            return -1

        # If password is a string or unicode, get the hash.
        if type(password) == type('') or type(password) == type(u''):
            pwd_hash = buffer(PBKDF2(password=password, salt='briefcase', dkLen=16, count=5000))
        # If password is database default, do nothing.
        elif password == 1:
            pwd_hash = 1
        # If password is null in some way, hash must be also null.
        else:
            password = None
            pwd_hash = None

        all_files = self.c.execute('select pwd, file from _files_ order by file').fetchall()

        # Temp_file[0] = pwd, Temp_file[1] = fname.
        for temp_file in all_files:
            # If provided password != stored password...
            if temp_file[0] != pwd_hash:
                self._log(2, 'Func ExportAll: Password for file "%s" is INCORRECT! You will not be'\
                    ' able to decrypt any data!' % temp_file[1])
                continue

            # At this point, password is correct.
            fname = path + '/' + temp_file[1]
            w = open(fname, 'wb')
            md4 = MD4.new(temp_file[1])
            filename = 't'+md4.hexdigest()
            latest_version = self.c.execute('select raw from %s order by version desc' % filename).fetchone()
            # Now write decompressed/ decrypted data.
            w.write(self._restoreb(latest_version[0], password))
            w.close()
            self._log(2, 'Func ExportAll: File "%s" exported successfully.' % temp_file[1])

        self._log(1, 'Exporting %i files took %.4f sec.' % (len(all_files), clock()-ti))
        return 0
Esempio n. 45
0
def compute_nthash(password):
    # This is done according to Samba's encryption specification (docs/html/ENCRYPTION.html)
    try:
        password = unicode(password).encode('utf_16le')
    except NameError:  # unicode() was removed in Python 3
        password = str(password).encode('utf_16le')
    except UnicodeDecodeError:
        import sys
        password = password.decode(
            sys.getfilesystemencoding()).encode('utf_16le')

    if POW:
        hash = POW.Digest(POW.MD4_DIGEST)
    else:
        hash = MD4.new()
    hash.update(password)
    return hash.digest()
Esempio n. 46
0
    def on_edit(self):
        #
        fname = self.item_clicked_old
        temp_dir = tempfile.mkdtemp('__', '__py')
        filename = temp_dir + '/' + fname

        # Create temp file and return file hash.
        # This is messy, after editing, the temporary files must be destroyed.
        old_hash = self.b.ExportFile(fname=fname, path=temp_dir, execute=False)

        for i in range(3):
            if old_hash != -1:
                break
            else:
                qtTxt, qtMsg = QtGui.QInputDialog.getText(self, 'Enter password',
                    'This file requires a password :'******'Error on edit', '<br>Wrong password 3 times !<br>')
            return

        # Execute.
        if os.name=='posix':
            subprocess.check_output(['xdg-open', filename])
        elif os.name=='nt':
            os.system('"%s"&exit' % filename)
        else:
            print('System not supported : `%s` !' % os.name)
            return -1

        md4 = MD4.new(open(filename, 'rb').read())
        new_hash = md4.hexdigest()
        del md4

        # Compare hashes to see if the file was edited
        if old_hash != new_hash:
            qtMsg = QtGui.QMessageBox.warning(self, 'Save changes ? ...',
                'File "%s" was changed! Save changes ?' % fname, 'Yes', 'No')
            if qtMsg == 0: # Clicked yes.
                self.b.AddFile(filename)
def populate_copy_as_menu(menu, obj, action_table):
	string_menu = menu.addMenu("Escaped string")
	action_table[string_menu.addAction("ASCII")] = lambda : obj.copy_as(lambda data : data.encode("string_escape").replace("\"", "\\\""), False)
	action_table[string_menu.addAction("UTF-8 URL")] = lambda : obj.copy_as(encode_url, False)
	action_table[string_menu.addAction("UTF-8 IDNA")] = lambda : obj.copy_as(lambda data : data.decode("utf8").encode("idna"), False)
	action_table[string_menu.addAction("UTF-16 (\\u)")] = lambda : obj.copy_as(lambda data : encode_utf16_string(data, "\\u"), False)
	action_table[string_menu.addAction("UTF-16 (%u)")] = lambda : obj.copy_as(lambda data : encode_utf16_string(data, "%u"), False)
	action_table[string_menu.addAction("UTF-16 URL")] = lambda : obj.copy_as(lambda data : encode_url(data.decode("utf16").encode("utf8")), False)
	action_table[string_menu.addAction("UTF-16 IDNA")] = lambda : obj.copy_as(lambda data : data.decode("utf16").encode("idna"), False)
	unicode_menu = menu.addMenu("Unicode")
	action_table[unicode_menu.addAction("UTF-16")] = lambda : obj.copy_as(lambda data : data.decode("utf16"), False)
	action_table[unicode_menu.addAction("UTF-32")] = lambda : obj.copy_as(lambda data : data.decode("utf32"), False)
	menu.addSeparator()
	action_table[menu.addAction("Hex dump")] = lambda : obj.copy_as(hex_dump_encode, False)
	action_table[menu.addAction("Raw hex")] = lambda : obj.copy_as(lambda data : data.encode("hex"), False)
	action_table[menu.addAction("Base64")] = lambda : obj.copy_as(lambda data : data.encode("base64"), False)
	action_table[menu.addAction("UUEncode")] = lambda : obj.copy_as(lambda data : data.encode("uu_codec"), False)
	compress_menu = menu.addMenu("Compressed")
	action_table[compress_menu.addAction("zlib")] = lambda : obj.copy_as(lambda data : data.encode("zlib"), True)
	action_table[compress_menu.addAction("bz2")] = lambda : obj.copy_as(lambda data : data.encode("bz2"), True)
	menu.addSeparator()
	array_menu = menu.addMenu("C array")
	action_table[array_menu.addAction("8-bit elements")] = lambda : obj.copy_as(lambda data : encode_c_array(data, 1, "B", "unsigned char", ""), False)
	action_table[array_menu.addAction("16-bit elements")] = lambda : obj.copy_as(lambda data : encode_c_array(data, 2, "<H", "unsigned short", ""), False)
	action_table[array_menu.addAction("32-bit elements")] = lambda : obj.copy_as(lambda data : encode_c_array(data, 4, "<I", "unsigned int", ""), False)
	action_table[array_menu.addAction("64-bit elements")] = lambda : obj.copy_as(lambda data : encode_c_array(data, 8, "<Q", "unsigned long long", "LL"), False)
	menu.addSeparator()
	hash_menu = menu.addMenu("Hash")
	action_table[hash_menu.addAction("MD2")] = lambda : obj.copy_as(lambda data : MD2.new(data).digest(), True)
	action_table[hash_menu.addAction("MD4")] = lambda : obj.copy_as(lambda data : MD4.new(data).digest(), True)
	action_table[hash_menu.addAction("MD5")] = lambda : obj.copy_as(lambda data : MD5.new(data).digest(), True)
	action_table[hash_menu.addAction("SHA-1")] = lambda : obj.copy_as(lambda data : SHA.new(data).digest(), True)
	action_table[hash_menu.addAction("SHA-256")] = lambda : obj.copy_as(lambda data : SHA256.new(data).digest(), True)
	hmac_menu = hash_menu.addMenu("HMAC")
	action_table[hmac_menu.addAction("MD2")] = lambda : obj.copy_as(lambda data : HMAC.new(request_key(obj), data, MD2).digest(), True)
	action_table[hmac_menu.addAction("MD4")] = lambda : obj.copy_as(lambda data : HMAC.new(request_key(obj), data, MD4).digest(), True)
	action_table[hmac_menu.addAction("MD5")] = lambda : obj.copy_as(lambda data : HMAC.new(request_key(obj), data, MD5).digest(), True)
	action_table[hmac_menu.addAction("SHA-1")] = lambda : obj.copy_as(lambda data : HMAC.new(request_key(obj), data, SHA).digest(), True)
	action_table[hmac_menu.addAction("SHA-256")] = lambda : obj.copy_as(lambda data : HMAC.new(request_key(obj), data, SHA256).digest(), True)
Esempio n. 48
0
 def return_alg(k):
     """
     @type k: str, unicode
     @return:
     @raise:
     """
     if k == 'HMAC':
         return HMAC.new("kjhfsd")
     elif k == 'MD4':
         return MD4.new()
     elif k == 'MD5':
         return MD5.new()
     elif k == 'RIPEMD':
         return RIPEMD.new()
     elif k == 'SHA':
         return SHA.new()
     elif k == 'SHA224':
         return SHA224.new()
     elif k == 'SHA256':
         return SHA256.new()
     elif k == 'SHA384':
         return SHA384.new()
     elif k == 'SHA512':
         return SHA512.new()
Esempio n. 49
0
def NTPasswordHash(password):
        """ Return NTPasswordHash  """
        phash = MD4.new()
        phash.update(unicode(password).encode("utf-16le"))
 
        return phash.digest()
Esempio n. 50
0
 def ntowfv2(self):
     return HMAC.new(MD4.new(tuc(self.password)).digest(), tuc(self.username.upper() + self.domain)).digest()
Esempio n. 51
0
##https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Hash/MD4.py

from Crypto.Hash import MD4
h = MD4.new()
h.update(b'Hello')
print h.hexdigest()

Esempio n. 52
0
    def ExportFile(self, fname, password=1, version=0, path='', execute=False):
        '''
        Call one file from the briefcase. \n\
        If version is not null, that specific version is used. Else, the most recent version is used. \n\
        If execute is false, the file is simply exported into the specified path. Else, the file
        is executed from a temporary folder, or from the specified path, then the file is deleted. \n\
        '''
        ti = clock()
        md4 = MD4.new(fname)
        filename = 't'+md4.hexdigest()
        del md4

        if version < 0 : version = 0

        if path and not os.path.exists(path):
            self._log(2, 'Func ExportFile: path "%s" doesn\'t exist!' % path)
            return -1

        if not path and not execute:
            self._log(2, 'Func ExportFile: no path and no execute! The file will be generated and deleted immediately!')
            return -1

        # If version is a positive number, get that version.
        if version > 0:
            try:
                selected_version = self.c.execute('select raw, hash from %s where version=%s' % \
                    (filename, version)).fetchone()
            except:
                self._log(2, 'Func ExportFile: cannot find version "%i" for file "%s"!' % \
                    (version, fname))
                return -1
        # Else, get the latest version.
        else:
            try:
                selected_version = self.c.execute('select raw, hash from %s order by version desc' % \
                    filename).fetchone()
            except:
                self._log(2, 'Func ExportFile: cannot find the file called "%s"!' % fname)
                return -1

        # Get file password hash. It can be None, (Zero), or (some hash string).
        old_pwd_hash = self.c.execute('select pwd from _files_ where file="%s"' % fname).fetchone()

        if old_pwd_hash:
            old_pwd_hash = old_pwd_hash[0]

        # If password is a string or unicode, get the hash.
        if type(password) == type('') or type(password) == type(u''):
            pwd_hash = buffer(PBKDF2(password=password, salt='briefcase', dkLen=16, count=5000))
        # If password is database default, do nothing.
        elif password == 1:
            pwd_hash = 1
        # If password is null in some way, hash must be also null.
        else:
            password = None
            pwd_hash = None

        # If provided password != stored password...
        if old_pwd_hash != pwd_hash:
            self._log(2, 'Func ExportFile: Password for file "%s" is INCORRECT! You will not be '\
                'able to decrypt any data!' % fname)
            return -1

        # If the path is specified, use it
        if path:
            filename = path + '/' + fname
        # Else, create a temporary storage area
        else:
            # Create a temp dir
            tmpd = tempfile.mkdtemp('__', '__py')
            filename = tmpd + '/' + fname
            del tmpd

        w = open(filename, 'wb')
        w.write(self._restoreb(selected_version[0], password))
        w.close() ; del w
        self._log(1, 'Exporting file "%s" took %.4f sec.' % (fname, clock()-ti))

        if execute:
            # This function will call the file,
            # Then will overwrite the file,
            # Then will delete the temp folder, all threaded.
            # The Export Function here will not block.
            thread.start_new_thread(threaded_execute, (filename,),)

        # Return file hash.
        return selected_version[1]
Esempio n. 53
0
from cryptography.hazmat.primitives import hashes
from Crypto.Hash import MD2 as pycrypto_md2
from Crypto.Hash import MD4 as pycrypto_md4
from Crypto.Hash import MD5 as pycrypto_md5
from Cryptodome.Hash import MD2 as pycryptodomex_md2
from Cryptodome.Hash import MD4 as pycryptodomex_md4
from Cryptodome.Hash import MD5 as pycryptodomex_md5
import hashlib

hashlib.md5(1)
hashlib.md5(1).hexdigest()

abc = str.replace(hashlib.md5("1"), "###")

print(hashlib.md5("1"))

pycrypto_md2.new()
pycrypto_md4.new()
pycrypto_md5.new()

pycryptodomex_md2.new()
pycryptodomex_md4.new()
pycryptodomex_md5.new()

hashes.MD5()
Esempio n. 54
0
        key2 = expand_key(NTHash[7:14])
        key3 = expand_key(NTHash[14:16]+"\x00"*5) 
        
        cr1 = (DES.new(key1, DES.MODE_ECB)).encrypt(challenge)
        cr2 = (DES.new(key2, DES.MODE_ECB)).encrypt(challenge)
        cr3 = (DES.new(key3, DES.MODE_ECB)).encrypt(challenge)
       
        return (cr1 + cr2 + cr3)
      
  
  
key = 'Mypassword'                         #please ask me for real password
key_hash = NTPasswordHash(key)


#AP ==> S
PC = binascii.a2b_hex('784b2af6845212f6')
PR = ChallengeResponse(PC,key_hash)
print "d: 3b4f2d77e8ff180a6f8e67529ef9b0eff348045e2bc787a0"
print len(PR),binascii.b2a_hex(PR)


#S ==> AP
APC = binascii.a2b_hex('e130ba399e139f30')
phash =  MD4.new()
phash.update(key_hash)
key_h_h = phash.digest()
APR = ChallengeResponse(APC,key_h_h)
print "d: 6e4706869b5f18ad373afae911313338d816a3bac6aaa00d"
print len(APR),binascii.b2a_hex(APR)
Esempio n. 55
0
 def any_md4(self, s, e, t):
     from Crypto.Hash import MD4
     return self.rstr2any(MD4.new(s).digest(), e, t)
Esempio n. 56
0
    def bind(self, uuid, alter = 0, bogus_binds = 0):
        bind = MSRPCBind(endianness = self.endianness)

        syntax = '\x04\x5d\x88\x8a\xeb\x1c\xc9\x11\x9f\xe8\x08\x00\x2b\x10\x48\x60'

        if self.endianness == '>':
            syntax = unpack('<LHHBB6s', syntax)
            syntax = pack('>LHHBB6s', *syntax)

            uuid = list(unpack('<LHHBB6sHH', uuid))

            uuid[-1] ^= uuid[-2]
            uuid[-2] ^= uuid[-1]
            uuid[-1] ^= uuid[-2]
            
            uuid = pack('>LHHBB6sHH', *uuid)

        ctx = 0
        for i in range(bogus_binds):
            bind.set_ctx_id(self._ctx, index = ctx)
            bind.set_trans_num(1, index = ctx)
            bind.set_if_binuuid('A'*20, index = ctx)
            bind.set_xfer_syntax_binuuid(syntax, index = ctx)
            bind.set_xfer_syntax_ver(2, index = ctx)

            self._ctx += 1
            ctx += 1

        bind.set_ctx_id(self._ctx, index = ctx)
        bind.set_trans_num(1, index = ctx)
        bind.set_if_binuuid(uuid,index = ctx)
        bind.set_xfer_syntax_binuuid(syntax, index = ctx)
        bind.set_xfer_syntax_ver(2, index = ctx)

        bind.set_ctx_num(ctx+1)

        if alter:
            bind.set_type(MSRPC_ALTERCTX)

        if (self.__auth_level != ntlm.NTLM_AUTH_NONE):
            if (self.__username is None) or (self.__password is None):
                self.__username, self.__password, nth, lmh = self._transport.get_credentials()
            auth = ntlm.NTLMAuthNegotiate()
            auth['auth_level']  = self.__auth_level
            auth['auth_ctx_id'] = self._ctx + 79231 
            bind.set_auth_data(str(auth))

        self._transport.send(bind.get_packet())

        s = self._transport.recv()
        if s != 0:
            resp = MSRPCBindAck(s)
        else:
            return 0 #mmm why not None?

        if resp.get_type() == MSRPC_BINDNAK:
            resp = MSRPCBindNak(s)
            status_code = resp.get_reason()
            if rpc_status_codes.has_key(status_code):
                raise Exception(rpc_status_codes[status_code], resp)
            else:
                raise Exception('Unknown DCE RPC fault status code: %.8x' % status_code, resp)
            
        self.__max_xmit_size = resp.get_max_tfrag()

        if self.__auth_level != ntlm.NTLM_AUTH_NONE:
            authResp = ntlm.NTLMAuthChallenge(data = resp.get_auth_data().tostring())
            self._ntlm_challenge = authResp['challenge']
            response = ntlm.NTLMAuthChallengeResponse(self.__username,self.__password, self._ntlm_challenge)
            response['auth_ctx_id'] = self._ctx + 79231 
            response['auth_level'] = self.__auth_level

            if self.__auth_level in (ntlm.NTLM_AUTH_CONNECT, ntlm.NTLM_AUTH_PKT_INTEGRITY, ntlm.NTLM_AUTH_PKT_PRIVACY):
                if self.__password:
                    key = ntlm.compute_nthash(self.__password)
                    if POW:
                        hash = POW.Digest(POW.MD4_DIGEST)
                    else:
                        hash = MD4.new()
                    hash.update(key)
                    key = hash.digest()
                else:
                    key = '\x00'*16

            if POW:
                cipher = POW.Symmetric(POW.RC4)
                cipher.encryptInit(key)
                self.cipher_encrypt = cipher.update
            else:
                cipher = ARC4.new(key)
                self.cipher_encrypt = cipher.encrypt

            if response['flags'] & ntlm.NTLMSSP_KEY_EXCHANGE:
                session_key = 'A'*16     # XXX Generate random session key
                response['session_key'] = self.cipher_encrypt(session_key)
                if POW:
                    cipher = POW.Symmetric(POW.RC4)
                    cipher.encryptInit(session_key)
                    self.cipher_encrypt = cipher.update
                else:
                    cipher = ARC4.new(session_key)
                    self.cipher_encrypt = cipher.encrypt

            self.sequence = 0

            auth3 = MSRPCHeader()
            auth3.set_type(MSRPC_AUTH3)
            auth3.set_auth_data(str(response))
            self._transport.send(auth3.get_packet(), forceWriteAndx = 1)

        return resp     # means packet is signed, if verifier is wrong it fails
Esempio n. 57
0
def _md4_new(*args):
    from Crypto.Hash import MD4
    _new_funcs['MD4'] = _new_funcs['md4'] = MD4.new
    return MD4.new(*args)
Esempio n. 58
0
def hash_nt(pw):
    return MD4.new(pw.encode('utf-16-le')).digest()
Esempio n. 59
0
    def AddFile(self, filepath, password=1, labels='', arch='zlib', versionable=True):
        '''
        If file doesn't exist in database, create the file. If file exists, add another row. \n\
        Table name is "t" + MD4 Hexdigest of the file name. \n\
        Each row contains : Version, Raw-data, Hash of original data, Size, Date Time, User Name. \n\
        Raw-data is : original binary data -> compressed -> crypted. \n\
        Versionable=False checks if the file is in the database. If it is, an error is raised
        and the file is not added. \n\
        '''
        ti = clock()
        fname = os.path.split(filepath)[1]
        arch = arch.lower()

        if not os.path.exists(filepath):
            self._log(2, 'Func AddFile: file path "%s" doesn\'t exist!' % filepath)
            return -1
        if arch != 'zlib':
            arch = 'bz2'

        # If password is a string or unicode, calculate the hash.
        if type(password) == type('') or type(password) == type(u''):
            pwd_hash = buffer(PBKDF2(password=password, salt='briefcase', dkLen=16, count=5000))
        # If password is database default, do nothing.
        elif password == 1:
            pwd_hash = 1
        # If password is null in some way, hash must be also null.
        else:
            password = None
            pwd_hash = None

        filename = 't'+MD4.new(fname).hexdigest()

        old_pwd_hash = self.c.execute('select pwd from _files_ where file="%s"' % fname).fetchone()

        # If the file exists and used doesn't want new versions, exit.
        if old_pwd_hash and not versionable:
            self._log(2, 'Func AddFile: you selected versionable=False, so new version will NOT be added!')
            return -1
        # If file exists in DB and user provided a password.
        elif old_pwd_hash and password:
            old_pwd_hash = old_pwd_hash[0]
            # If password from user is differend from password in DB, exit.
            if old_pwd_hash != pwd_hash:
                self._log(2, 'Func AddFile: The password is INCORRECT! You will not be able to '\
                    'decrypt/ encrypt any data!')
                return -1

        self.c.execute('create table if not exists %s (version integer primary key asc, raw BLOB,'\
            'hash TEXT, size INTEGER, date TEXT, user TEXT)' % filename)

        # File size.
        size = os.path.getsize(filepath)
        # Read and transform all binary data.
        f = open(filepath, 'rb').read()
        # This is the raw data.
        raw = self._transformb(f, password, arch)
        md4 = MD4.new(f)
        # This is the hash of the original file.
        new_hash = md4.hexdigest()
        del f, md4

        # Check if the new file is identical with the latest version.
        old_hash = self.c.execute('select hash from %s order by version desc' % filename).fetchone()
        if old_hash and new_hash == old_hash[0]:
            self._log(2, 'Func AddFile: file "%s" is IDENTICAL with the version stored in the '\
                'database!' % fname)
            return -1

        self.c.execute(('insert into %s (raw, hash, size, date, user) values (?,?,?,?,?)' % filename),
            [raw, new_hash, size, strftime("%Y-%b-%d %H:%M:%S"), os.getenv('USERNAME')])

        # If password is None, or password is False.
        if not password:
            self.c.execute('insert or ignore into _files_ (pwd, file) values (?,?)', [password, fname])
        # If password is provided by user, insert its hash in _files_ table.
        else:
            self.c.execute('insert or ignore into _files_ (pwd, file) values (?,?)', [pwd_hash, fname])

        # Set the labels...
        self.SetLabels(fname, labels)
        # File statistics...
        self.FileStatistics(fname)
        # Everything is fine, save.
        self.conn.commit()

        ver_max = self.c.execute('select version from %s order by version desc' % filename).fetchone()
        self._log(1, 'Adding file "%s", arch %s, version "%i" took %.4f sec.' % (filepath, arch, ver_max[0], clock()-ti))
        return 0