Beispiel #1
0
def cria_indice():

    mapping_userdb = {"mappings":
                      {"properties":
                       {"datas_alteracao_senha": {"type": "nested"},
                        "codigos_de_seguranca": {"type": "nested"},
                        "historico_de_senhas": {"type": "nested"}
                        }}}

    map_megasena = {"mappings":
                    {"properties":
                     {"concurso": {"type": "nested"}
                      }}}

    print(f'|--- SUBMENU DE OPCOES ---|')
    indice_escolha = int(input("1 - userdb\n"
                               "2 - megasena\n"
                               ">>  "))

    if indice_escolha in range(1, 3):
        if indice_escolha == 1:
            if ESEARCH.indices.exists(index="userdb") is False:
                ESEARCH.indices.create(index="userdb", body=mapping_userdb)
            else:
                callexit('Indice existente.')
        elif indice_escolha == 2:
            if ESEARCH.indices.exists(index="megasena") is False:
                ESEARCH.indices.create(index="megasena", body=map_megasena)
            else:
                callexit('Indice existente.')
def auth_username():

    print('User Authentication.\nPlease type the user name:')
    username = input()
    assert username, 'Please type the user name.'

    try:

        cc.execute(select_username, (username, ))
        data_returned = cc.fetchone()
        assert data_returned is not None, 'User not found.'
        for _ in data_returned:
            print(f'Please type the password for {username}:')
            password = input()
            assert password, 'Please type a password'
            hashed_db_password = data_returned[1]
            checkpwd = pbkdf2_sha512.verify(password, hashed_db_password)
            if checkpwd:
                print(f'The user "{username}" has been authenticated.')
                conn.close()
                callexit()
            else:
                print(f'Invalid password for "{username}".')
                conn.close()
                callexit()

    except conn.Error as error:
        print(f'Error: {error}')
Beispiel #3
0
def main():

    TRACO = '-' * 13
    print(f'|{TRACO} MENU DE OPCOES {TRACO}|')

    escolha = int(input("1 - Cadastro\n"
                        "2 - Lista Usuários\n"
                        "3 - Procura usuário\n"
                        "4 - Remove usuário\n"
                        "5 - Verifica Senha\n"
                        "6 - Altera senha\n"
                        "7 - Cria indice\n"
                        "8 - Remove indice\n"
                        ">>  "))

    if escolha in range(1, 9):
        if escolha == 1:
            cadastra_usuario_no_banco()
        elif escolha == 2:
            lista_usuarios()
        elif escolha == 3:
            lista_1_usuario()
        elif escolha == 4:
            remove_usuario()
        elif escolha == 5:
            verifica_senha()
        elif escolha == 6:
            altera_senha_de_usuario()
        elif escolha == 7:
            cria_indice()
        elif escolha == 8:
            remove_indice()
    else:
        callexit('Digite uma opção válida do menu')
Beispiel #4
0
def altera_senha_de_usuario():

    global senha
    print('--- Alteração das credencias de usuário ---\n')
    if checa_se_usuario_existe():
        for alt in resultado['hits']['hits']:
            alteracoes = alt['_source']['alteracoes_senha'] + 1
            senha_antiga = alt['_source']['senha']
        senha = getpass(f'Digite a nova senha para o usuário {usuario}: ')
        if argon2.verify(senha, alt['_source']['senha']):
            callexit('Mesma senha anterior. Digite uma nova senha')
        else:
            pass
        if checa_qualidade_da_senha(senha) is True:
            hashedpwd = argon2.using(salt_size=64).hash(senha)
            data = datetime.now().strftime("%m/%d/%Y %H:%M:%S UTC−03:00")
            credenciais = {'doc':
                           {'senha': hashedpwd,
                            'historico_de_senhas': {alteracoes: senha_antiga},
                            'datas_alteracao_senha': {alteracoes: data},
                            'alteracoes_senha': alteracoes}}
            ESEARCH.update(index="userdb", id=usuario, body=credenciais)
            print('Senha alterada com sucesso.')
        else:
            print(POLITICA_SENHA_VALIDA)
    else:
        callexit('Usuário inexistente.')
Beispiel #5
0
def cadastra_usuario_no_banco():

    global senha
    print('--- Criação das credencias de novo usuário ---\n\
    Digite um nome de usuário:\n')
    if checa_se_usuario_existe():
        callexit('Usuário já existe na base.')
    senha = getpass('Digite uma senha: ')
    if checa_qualidade_da_senha(senha) is True:
        hashedpwd = argon2.using(salt_size=64).hash(senha)
        data = datetime.now().strftime("%m/%d/%Y %H:%M:%S UTC−03:00")
        codigos = {}
        for n in range(1, 9):
            [rd := ''.join(SystemRandom().choice(digits) for _ in range(9))]
            codigos[n] = rd
        credenciais = {'nome': usuario,
                       'senha': hashedpwd,
                       'historico_de_senhas': [{}],
                       'data_criacao': data,
                       'datas_alteracao_senha': [{}],
                       'codigos_de_seguranca': [{'codigos': codigos}],
                       'alteracoes_senha': 0}
        ESEARCH.index(index="userdb", id=usuario, body=credenciais)
        print('Usuário criado com sucesso.')
    else:
        print(POLITICA_SENHA_VALIDA)
Beispiel #6
0
def remove_usuario():

    opcao = 'noprint'
    if lista_usuarios(opcao) is False:
        callexit()
    else:
        pass
    if checa_se_usuario_existe():
        resultado = ESEARCH.delete_by_query(
            index="userdb", body={"query": {"match": {"nome": usuario}}})
        if resultado['failures'] == []:
            print('Usuário removido')
    else:
        print('Usuário inexistente.')
Beispiel #7
0
def verifica_senha():

    global senha
    if checa_se_usuario_existe() is False:
        callexit('Usuário inexistente.')
    senha = getpass('Senha: ')
    for ocorrencia in resultado['hits']['hits']:
        hashpwd = ocorrencia['_source']['senha']
        if argon2.verify(senha, hashpwd):
            print('Senha correta')
            return True
            return senha
        else:
            print('Senha Incorreta')
            return False
def iplist():

    try:  # certify the IP Address format is valid

        IP_ADDR_COUNT = ip_network(PREFIX).num_addresses
        NETWORK_HOSTS = ip_network(PREFIX).hosts()

        if PREFIX == 0:
            callexit("Provide a HOST IP Address or an IP/CIDR as argument.")
        elif IP_ADDR_COUNT > 1:
            for IPADDRESS in NETWORK_HOSTS:
                yield IPADDRESS
        elif IP_ADDR_COUNT == 1:
            if '/32' in PREFIX:  # ex: 8.8.8.8/32 will become '8.8.8.8'
                yield PREFIX.split('/')[0]
            else:
                yield PREFIX

    except ValueError as error:
        print(f'iplist() function Error >>> {error}')
for HOST in iplist():

    try:

        with sk.socket(sk.AF_INET, sk.SOCK_DGRAM) as packet:

            packet.settimeout(0.100)

            ''' send the 'PAYLOADHEX' to HOSTs in the list (port 53 (DNS)) '''

            packet.sendto(bytes.fromhex(PAYLOADHEX), (str(HOST), int(53)))
            RESPONSE = packet.recv(128)

            ''' check if RESPONSE contains a valid DNS RESPONSE with
                l.root-servers.net's IP address 199.7.83.42  '''

            if (b'\xc0\x0c\x00\x01\x00\x01' and
                    b'\x00\x04\xc7\x07') in RESPONSE:
                UNIXTIME = int(time())
                print(f'{HOST},open,{UNIXTIME}')

    except sk.timeout:   # timeout generated by network conditions
        continue

    except ValueError as error:
        print(f'Error >>> {error}')

    except KeyboardInterrupt:
        callexit('Program execution interrupted.')