예제 #1
0
    def post(self):
        """
        HcStat from dictionary
        """
        args = makeMarkovFromDictionary_parser.parse_args(request)
        dict = FcDictionary.query.filter(
            FcDictionary.id == args['dictionary_id']).first()
        if not dict:
            abort(500, 'Can not find selected dictionary.')
        filename = secure_filename(args['name'])
        path = os.path.join(HCSTATS_DIR, filename) + '.hcstat2'

        # make hcstat2 file
        shellExec(HASHCAT_UTILS_PATH + '/hcstat2gen.' + EXE_OR_BIN + ' ' +
                  path + '_tmp < ' + os.path.join(DICTIONARY_DIR, dict.name))
        # comprime hcstat2 file
        shellExec('xz --compress --format=raw --stdout -9e ' + path +
                  '_tmp > ' + path)
        # delete non-comprimed file
        os.remove(path + '_tmp')

        hcstats = FcHcstat(name=filename + '.hcstat2', path=path)
        try:
            db.session.add(hcstats)
            db.session.commit()
        except exc.IntegrityError as e:
            db.session().rollback()
            abort(500, 'HcStats with name ' + filename + ' already exists.')

        return {
            'status': True,
            'message': 'HcStat file with name ' + filename + ' created.'
        }
예제 #2
0
    def post(self):
        """
        Spravi slovník so suboru
        """

        args = dictionaryFromFile_parser.parse_args(request)
        files = args.get('files')

        for file in files:
            if not allowed_file(file['name'], ALLOWED_EXTENSIONS):
                abort(500, 'Wrong file format ' + file['name'])
            newName = Path(file['name']).stem + '_' + str(int(time.time())) + Path(file['name']).suffix
            newPath = os.path.join(DICTIONARY_DIR, newName )
            os.symlink(file['path'], newPath)
            hc_keyspace = int(shellExec(HASHCAT_PATH + ' --keyspace -a 0 ' + newPath, cwd=HASHCAT_DIR))
            dictionary = FcDictionary(name=file['name'], path=newName, keyspace=hc_keyspace)
            try:
                db.session.add(dictionary)
                db.session.commit()
            except exc.IntegrityError as e:
                db.session().rollback()
                abort(500, 'Dictionary with name ' + file['filename'] + ' already exists.')

        return {
            'message': 'Dictionaries successfuly uploaded.',
            'status': True
        }
예제 #3
0
    def post(self):
        """
        Nahrava slovník na server
        """
        # check if the post request has the file part
        if 'file' not in request.files:
            abort(500, 'No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            abort(500, 'No selected file')

        uploadedFile = fileUpload(file, DICTIONARY_DIR, ALLOWED_EXTENSIONS)
        if uploadedFile:
            hc_keyspace = int(shellExec(HASHCAT_PATH + ' --keyspace -a 0 ' + os.path.join(DICTIONARY_DIR, uploadedFile['path']), cwd=HASHCAT_DIR))
            dictionary = FcDictionary(name=uploadedFile['filename'], path=uploadedFile['path'], keyspace=hc_keyspace)
            try:
                db.session.add(dictionary)
                db.session.commit()
            except exc.IntegrityError as e:
                db.session().rollback()
                abort(500, 'Dictionary with name ' + uploadedFile['filename'] + ' already exists.')
            return {
                'message': 'Dictionary ' + uploadedFile['filename'] + ' successfuly uploaded.',
                'status': True

            }
        else:
            abort(500, 'Wrong file format')
예제 #4
0
def compute_prince_keyspace(attackSettings):
    run_cmd = ["cat"]
    for dict in attackSettings['left_dictionaries']:
        run_cmd.append(os.path.join(DICTIONARY_DIR, dict['name']))
    run_cmd.append("|")
    run_cmd.append(PRINCE_PROCESSOR_PATH)
    if attackSettings['case_permute']:
        run_cmd.append("--case-permute")
    if not attackSettings['check_duplicates']:
        run_cmd.append("--dupe-check-disable")
    if attackSettings['min_password_len']:
        run_cmd.append("--pw-min=" + str(attackSettings['min_password_len']))
    if attackSettings['max_password_len']:
        run_cmd.append("--pw-max=" + str(attackSettings['max_password_len']))
    if attackSettings['min_elem_in_chain']:
        run_cmd.append("--elem-cnt-min=" +
                       str(attackSettings['min_elem_in_chain']))
    if attackSettings['max_elem_in_chain']:
        run_cmd.append("--elem-cnt-max=" +
                       str(attackSettings['max_elem_in_chain']))
    run_cmd.append("--keyspace")
    compute_keyspace_command = ' '.join(run_cmd)
    print(compute_keyspace_command)
    try:
        return int(shellExec(compute_keyspace_command))
    except Exception:
        return -1
예제 #5
0
def isComponentRunning(compName):
    out = shellExec("ps -ef | grep " + compName + " | grep -v grep")
    return True
    if len(out.splitlines()) >= 1:
        return True

    return False
예제 #6
0
def createPcfgGrammarBin(pcfgFileNameZip):
    test = PCFG_MANAGER_DIR + ' marshal -r ' \
                                 + os.path.join(PCFG_DIR, extractNameFromZipfile(pcfgFileNameZip)) \
                                 + ' -o ' + os.path.join(PCFG_DIR, extractNameFromZipfile(pcfgFileNameZip)) \
                                 + '/grammar.bin'
    pcfgKeyspace = shellExec(PCFG_MANAGER_DIR + ' marshal -r ' \
                                 + os.path.join(PCFG_DIR, extractNameFromZipfile(pcfgFileNameZip)) \
                                 + ' -o ' + os.path.join(PCFG_DIR, extractNameFromZipfile(pcfgFileNameZip)) \
                                 + '/grammar.bin')
예제 #7
0
def getHashFromFile(filename, path):
    res = shellExec('python3 ' + XTOHASHCAT_EXECUTABLE + ' ' +
                    os.path.join(PROTECTEDFILES_DIR, path),
                    cwd=XTOHASHCAT_PATH,
                    getReturnCode=True)
    if res['returnCode'] == 2:
        abort(500, 'Hashcat doesn\'t support PKZIP.')
    if res['returnCode'] != 0:
        abort(500, 'Could not extract hash from file.')
    res = res['msg'].split('\n')
    return {'hash': res[0], 'hash_type': res[1]}
예제 #8
0
def getTable(tableName):
    out = shellExec(HASHCAT_PATH + " --help")

    twoNewLines = os.linesep + os.linesep
    hashtypes = getStringBetween(out,
                                 "- [ " + tableName + " ] -" + twoNewLines,
                                 twoNewLines)

    hashtypes = parserAsciiTable(hashtypes)

    return hashtypes
예제 #9
0
    def get(self):
        """
        Operácie so serverom (reštart, štart,stop)
        """
        args = operation.parse_args(request)
        action = args.get('operation')

        if action == "start":
            out = shellExec('/usr/bin/python ' + PROJECT_DIR + '/bin/start')
        elif action == "stop":
            out = shellExec('/usr/bin/python ' + PROJECT_DIR + '/bin/stop')
        elif action == "restart":
            out = shellExec('/usr/bin/python ' + PROJECT_DIR + '/bin/stop')
            out = shellExec('/usr/bin/python ' + PROJECT_DIR + '/bin/start')
        else:
            abort(400, "Bad operation " + action)

        return {
            "status": True,
            "message": "Operation " + action + " finished sucesfull."
        }
예제 #10
0
def verifyHashFormat(hash, hash_type, abortOnFail=False, binaryHash=False):
    hashes = []
    settings = FcSetting.query.first()
    if not settings.verify_hash_format:
        with open(hash, "r") as hashFile:
            hashes = [(hash.strip() + " OK") for hash in hashFile.readlines()]
    else:
        result = shellExec(HASHVALIDATOR_PATH + ' -m ' + hash_type + ' ' +
                           "'" + hash + "'",
                           getReturnCode=True)

        if result['returnCode'] != 0:
            abort(500, 'Error in hashValidator.')

        hashes = result['msg'].rstrip().split('\n')

    hashesArr = []
    hasError = False
    for hash in hashes:
        hashArr = hash.split(' ')

        isInCache = False
        dbHash = FcHash.query.filter(FcHash.hash == bytes(hashArr[0], 'utf8'),
                                     FcHash.result != None).first()
        if dbHash:
            isInCache = True

        if abortOnFail and hashArr[1] != 'OK':
            abort(
                500, 'Hash ' + hashArr[0] + ' has wrong format (' +
                hashArr[1] + ' exception).')
        if binaryHash:
            hashArr[0] = binaryHash

        if hashArr[0] == '':
            hashesArr.append({
                'hash': hashArr[0],
                'result': 'Empty hash',
                'isInCache': False
            })
            hasError = True
        else:
            hashesArr.append({
                'hash': hashArr[0],
                'result': hashArr[1],
                'isInCache': isInCache
            })
            if hashArr[1] != 'OK':
                hasError = True
    return {'items': hashesArr, 'error': hasError}
예제 #11
0
def calculateKeyspace(pcfgFileNameZip):

    pcfgKeyspace = 0
    pcfgKeyspace = shellExec(
        PCFG_MOWER_DIR + ' -i ' +
        os.path.join(PCFG_DIR, extractNameFromZipfile(pcfgFileNameZip)))

    # Keyspace control
    INT_MAX = sys.maxsize - 1

    if int(pcfgKeyspace) >= INT_MAX:
        pcfgKeyspace = INT_MAX

    return pcfgKeyspace
예제 #12
0
def make_dict_from_mask(mask, filename=None):
    if not filename:
        filename = 'hybrid_attack' + str(int(time.time())) + '.txt'

    filename = secure_filename(filename)
    path = os.path.join(DICTIONARY_DIR, filename)

    print(MASK_PROCESSOR_PATH + ' ' + mask + ' -o ' + path)
    print(shellExec(MASK_PROCESSOR_PATH + ' ' + mask + ' -o ' + path))
    dictionary = FcDictionary(name=filename,
                              path=filename,
                              keyspace=compute_keyspace_from_mask(mask),
                              deleted=True)
    db.session.add(dictionary)
    db.session.commit()
    return dictionary
예제 #13
0
파일: logs.py 프로젝트: x0rzkov/fitcrack
 def get(self):
     """
     Returns new logs.
     """
     args = newLogs_argument.parse_args(request)
     lastLog = args.get('log', 1)
     logs = []
     skip = 0
     while True:
         fewLastLogs = shellExec(
             'head -n -' + str(skip) +
             ' /app/log_fitcrack/work_generator.log | tail -n 100')
         if fewLastLogs == '':
             return {'items': []}
         fewLastLogs = fewLastLogs.split('\n')
         for log in reversed(fewLastLogs):
             if log.startswith('LOG:') or log.startswith(
                     'ERROR:') or log.startswith('WARN:'):
                 if (lastLog == log):
                     return {'items': logs}
                 else:
                     logs.append(log_parser(log))
         skip += 100
예제 #14
0
파일: logs.py 프로젝트: x0rzkov/fitcrack
 def get(self):
     """
     Returns logs.
     """
     args = logs_argument.parse_args(request)
     skip = args.get('skip_count', 0)
     lastLog = args.get('last_log', None)
     while True:
         logs = shellExec(
             'head -n -' + str(skip) +
             ' /app/log_fitcrack/work_generator.log | tail -n 100')
         if logs == '':
             return {'items': []}
         logs = logs.split('\n')
         results = []
         for log in reversed(logs):
             if log == lastLog:
                 return {'items': results}
             if log.startswith('LOG:') or log.startswith(
                     'ERROR:') or log.startswith('WARN:'):
                 results.append(log_parser(log))
         if not lastLog:
             return {'items': results}
         skip += 100
예제 #15
0
def moveGrammarToPcfgDir(nameWithExt):

    test = 'mv ' + PCFG_TRAINER_RULE_DIR + '/' + extractNameFromZipfile(
        nameWithExt) + ' ' + PCFG_DIR + '/' + extractNameFromZipfile(
            nameWithExt)
    pcfgMoveGrammar = shellExec(test)
예제 #16
0
def makePcfgFolder(nameWithExt):

    test = PCFG_TRAINER_DIR + ' --coverage 1.0 ' \
                                 + ' --rule ' + extractNameFromZipfile(nameWithExt) \
                                 + ' -t ' + os.path.join(DICTIONARY_DIR, nameWithExt)
    pcfgMakeGrammar = shellExec(test)
예제 #17
0
def process_package_3(package, hashcatKeyspace=True):
    if not package['attack_settings'].get('attack_submode'):
        package['attack_settings']['attack_submode'] = 0
    # check masks syntax
    for mask in package['attack_settings']['masks']:
        check_mask_syntax(mask)

    # charsets
    hashcatArgs = ''
    charsetsSize = []
    if package['attack_settings'].get('charset'):
        if len(package['attack_settings']['charset']) > 4:
            abort(500, 'Maximum of charsets files is 4.')
        for i, charset in enumerate(package['attack_settings']['charset'], 1):
            charsetPath = os.path.join(CHARSET_DIR, charset['name'])
            charsetsSize = dict()
            with open(charsetPath, 'rb') as f:
                content = f.read()
                charsetsSize[i] = len(content)

            hashcatArgs += ' -' + str(i) + ' ' + charsetPath
            hexCharset = content.hex()
            package['config'] += '|||charset' + str(i) + '|String|' + lenStr(
                hexCharset) + '|' + hexCharset + '|||\n'
            package['charset' + str(i) + '_id'] = charset['id']

    # compute keyspace
    package['mask_table'] = []
    package['keyspace'] = 0
    package['hc_keyspace'] = 0
    for (i, mask) in enumerate(package['attack_settings']['masks']):
        keyspace_for_mask = compute_keyspace_from_mask(mask, charsetsSize)
        hc_keyspace_for_mask = 0
        if hashcatKeyspace:
            hc_keyspace_for_mask = shellExec(
                HASHCAT_PATH + ' -m ' + package['hash_settings']['hash_type'] +
                ' --keyspace -a 3 ' + mask + ' ' + hashcatArgs,
                cwd=HASHCAT_DIR,
                abortOnError=True)
            if hc_keyspace_for_mask == '':
                abort(500, 'Server can not compute keyspace for mask ' + mask)
            try:
                package['hc_keyspace'] += int(hc_keyspace_for_mask)
            except ValueError:
                abort(500, 'Hashcat says: "' + hc_keyspace_for_mask + '".')

        package['keyspace'] += keyspace_for_mask
        package['mask_table'].append({
            'mask': mask,
            'keyspace': keyspace_for_mask,
            'hc_keyspace': hc_keyspace_for_mask
        })

    if package['attack_settings'].get('markov'):
        markov = FcHcstat.query.filter(
            FcHcstat.id == package['attack_settings']['markov']['id']).first()
        if not markov:
            abort(500, 'Wrong markov file selected.')
        if not os.path.exists(os.path.join(HCSTATS_DIR, markov.path)):
            abort(500, 'Markov file does not exist.')
        package['markov_hcstat'] = markov.name
        package['attack_settings']['attack_submode'] = 1

    markovTreshold = package['attack_settings'][
        'markov_treshold'] if package['attack_settings'].get(
            'markov_treshold'
        ) and package['attack_settings']['markov_treshold'] > 1 else None

    package['attack_name'] = 'mask'
    package['markov_threshold'] = markovTreshold
    return package
예제 #18
0
def readingFromFolderPostProcces(DictionaryModel):
    DictionaryModel.keyspace = int(
        shellExec(HASHCAT_PATH + ' --keyspace -a 0 "' +
                  os.path.join(DICTIONARY_DIR, DictionaryModel.path + '"'),
                  cwd=HASHCAT_DIR))
    return DictionaryModel
예제 #19
0
def process_job_3(job, hashcatKeyspace=True):
    if not job['attack_settings'].get('attack_submode'):
        job['attack_settings']['attack_submode'] = 0
    # check masks syntax
    for mask in job['attack_settings']['masks']:
        check_mask_syntax(mask)

    # charsets
    hashcatArgs = ''
    charsetsSize = {}
    if job['attack_settings'].get('charset'):
        if len(job['attack_settings']['charset']) > 4:
            abort(500, 'Maximum of charsets files is 4.')
        for i, charset in enumerate(job['attack_settings']['charset'], 1):
            charsetPath = os.path.join(CHARSET_DIR, charset['name'] + '.hcchr')
            charsetsSize = dict()
            with open(charsetPath, 'rb') as f:
                content = f.read()
                charsetsSize[i] = len(content)

            hashcatArgs += ' -' + str(i) + ' ' + charsetPath
            hexCharset = content.hex()
            job['charset' + str(i)] = hexCharset

    # compute keyspace
    if job['attack_settings'].get('markov_treshold') and job[
            'attack_settings']['markov_treshold'] > 1:
        markovTresh = job['attack_settings']['markov_treshold']
        job['markov_threshold'] = job['attack_settings']['markov_treshold']

        job['mask_table'] = []
        job['keyspace'] = 0
        job['hc_keyspace'] = 0
        for (i, mask) in enumerate(job['attack_settings']['masks']):
            keyspace_for_mask = compute_keyspace_from_mask(
                mask, charsetsSize, markovTresh)
            hc_keyspace_for_mask = 0
            if hashcatKeyspace:

                tmp = HASHCAT_PATH + ' -m ' + job['hash_settings'][
                    'hash_type'] + ' -a 3 ' + mask + ' --markov-threshold ' + str(
                        job['attack_settings']['markov_treshold'])
                hc_keyspace_for_mask = shellExec(
                    HASHCAT_PATH + ' -m ' + job['hash_settings']['hash_type'] +
                    ' --keyspace -a 3 ' + mask + ' --markov-threshold ' +
                    str(job['attack_settings']['markov_treshold']),
                    cwd=HASHCAT_DIR,
                    abortOnError=True)
                if hc_keyspace_for_mask == '':
                    abort(500,
                          'Server can not compute keyspace for mask ' + mask)
                try:
                    job['hc_keyspace'] += int(hc_keyspace_for_mask)
                except ValueError:
                    abort(500, 'Hashcat says: "' + hc_keyspace_for_mask + '".')

            job['keyspace'] += keyspace_for_mask
            job['mask_table'].append({
                'mask': mask,
                'keyspace': keyspace_for_mask,
                'hc_keyspace': hc_keyspace_for_mask
            })

    else:
        job['mask_table'] = []
        job['keyspace'] = 0
        job['hc_keyspace'] = 0
        for (i, mask) in enumerate(job['attack_settings']['masks']):
            keyspace_for_mask = compute_keyspace_from_mask(mask, charsetsSize)
            hc_keyspace_for_mask = 0
            if hashcatKeyspace:
                hc_keyspace_for_mask = shellExec(
                    HASHCAT_PATH + ' -m ' + job['hash_settings']['hash_type'] +
                    ' --keyspace -a 3 ' + mask + ' ' + hashcatArgs,
                    cwd=HASHCAT_DIR,
                    abortOnError=True)
                if hc_keyspace_for_mask == '':
                    abort(500,
                          'Server can not compute keyspace for mask ' + mask)
                try:
                    job['hc_keyspace'] += int(hc_keyspace_for_mask)
                except ValueError:
                    abort(500, 'Hashcat says: "' + hc_keyspace_for_mask + '".')

            job['keyspace'] += keyspace_for_mask
            job['mask_table'].append({
                'mask': mask,
                'keyspace': keyspace_for_mask,
                'hc_keyspace': hc_keyspace_for_mask
            })

    if job['attack_settings'].get('markov'):
        markov = FcHcstat.query.filter(
            FcHcstat.id == job['attack_settings']['markov']['id']).first()
        if not markov:
            abort(500, 'Wrong markov file selected.')
        if not os.path.exists(os.path.join(HCSTATS_DIR, markov.path)):
            abort(500, 'Markov file does not exist.')
        job['markov_hcstat'] = markov.name

    job['attack_name'] = 'mask'

    return job