Example #1
0
def searchSHA(ndd):
    # Fonction qui a pour but de chercher le sha256 correspondant
    # au nom de domaine passé en paramètres s'il existe
    BDD.verifExistBDD()
    problem = 0
    sha256 = "0"
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        cursor.execute("""SELECT SHA256 FROM DNS WHERE NDD = ?""", (ndd, ))
        rows = cursor.fetchall()
    except Exception as e:
        conn.rollback()
        logs.addLogs("DNS : ERROR : Problem with the database (searchSHA()):" +
                     str(e))
        problem += 1
    else:
        nbRes = 0
        for row in rows:
            nbRes += 1
            if nbRes > 1:
                # On trouve plusieurs fois le même nom de domaine dans la base
                problem = 5
                logs.addLogs("DNS : ERROR: The domain name " + ndd +
                             " is present several times in the database")
            sha256 = row[0]
    conn.close()
    if problem > 1:
        return problem
    if sha256 == "0":
        return "INCONNU"
    return sha256
Example #2
0
def aleatoire(nomTable, entree, nbEntrees, fonction=""):
    # Fonction qui a pour but de renvoyer sour forme d'un tableau nbEntrees lignes
    # contenues dans nomTable de façon aléatoire.
    error = 0
    verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        if nomTable == "Noeuds":
            if fonction == "":
                fonction = "Simple"
            cursor.execute(
                """SELECT IP FROM Noeuds WHERE Fonction = ? ORDER BY RANDOM() LIMIT ?""",
                (fonction, nbEntrees))
            conn.commit()
    except Exception as e:
        conn.rollback()
        logs.addLogs("ERROR : Problem with database (aleatoire()):" + str(e))
        error += 1
    rows = cursor.fetchall()
    tableau = []
    for row in rows:
        tableau.append(row)
        # On remplit le tableau avant de le retourner
    conn.close()
    if len(tableau) != nbEntrees:
        error += 1
        # return error
        # Ligne à activer seulement lorsque le réseau fonctionne
    return tableau
Example #3
0
def filetoTable(fileName, nomTable):
    # cette fonction a pour but de lire un fichier et de l'écrire dans une table
    f = open("HOSTEDFILES/" + fileName, "rb")
    lines = f.readlines()
    f.close()
    for line in lines:
        if nomTable == "Noeuds":
            BDD.ajouterEntree("Noeud", line)
        elif nomTable[:8] == "Fichiers":
            BDD.ajouterEntree(nomTable, line)
        elif nomTable == "DNS":
            # La virgule sans espace en premier est normal
            SHA256 = line[:line.find(",")]
            NDD = line[line.find(",") + 1:line.find(", ")]
            PASS = line[line.find(", ") + 2:-1]
            BDD.ajouterEntree("DNS", NDD, SHA256, PASS)
        elif nomTable == "BlackList":
            name = line[:line.find(";")]
            rank = line[line.find(";") + 1:]
            BDD.ajouterEntree("BlackList", name, rank)
        else:
            logs.addLogs(
                "ERROR: The table name was not recognized (filetoTable()) : " +
                str(nomTable))
            return 1
    return 0
Example #4
0
File: maj.py Project: anon1892/WTP
def verifSources():
    files = [
        f for f in os.listdir('.') if os.path.isfile(os.path.join('.', f))
    ]
    for en_cours in files:

        class AppURLopener(FancyURLopener):
            version = "Mozilla/5.0"

        if en_cours[
                0] != "." and en_cours != "logs.txt" and en_cours != "wtp.conf" and en_cours != "WTP.db":
            opener = AppURLopener()
            page = opener.open("https://myrasp.fr/WTP/Maj/" + en_cours)
            online_sha = page.read().decode("utf-8")
            acces_file = open(en_cours, "r")
            contenu = acces_file.read()
            acces_file.close()
            sha_file = hashlib.sha256(str(contenu).encode()).hexdigest()
            if online_sha != sha_file:
                # On lance la MAJ en mode forcé
                logs.addLogs(
                    "ERROR : When checking sources, the file " + en_cours +
                    " was found to be incorrect. New sources will be downloaded."
                )
                verifMAJ(1)
Example #5
0
File: dns.py Project: anon1892/WTP
def addNoeudDNS(ipport, ipportNoeud):
    error = 0
    if autresFonctions.verifIPPORT(ipport):
        connexion_avec_serveur = autresFonctions.connectionClient(ipport)
        if str(connexion_avec_serveur) == "=cmd ERROR":
            error += 1
        else:
            logs.addLogs("Connection established with the DNS")
            # =cmd DNS AddDNSExt ipport ******
            request = "=cmd DNS AddDNSExt ipport " + ipportNoeud
            request = request.encode()
            connexion_avec_serveur.send(request)
            message = connexion_avec_serveur.recv(1024)
            connexion_avec_serveur.close()
            if message == "=cmd IPPORTDejaUtilise":
                error = 5
                print(
                    str(c("red")) +
                    "The peer DNS is already known by the receiver." +
                    str(c("")))
            elif message == "=cmd SUCCESS":
                print(
                    str(c("green")) +
                    "The DNS pair has been added to the receiver base." +
                    str(c("")))
            else:
                print(
                    str(c("red")) +
                    "An undetermined error occurred. Please try again later or change DNS peer."
                    + str(c("")))
                error = 1
    else:
        error += 1
    return error
Example #6
0
def compterStats(colonne):
    BDD.verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        if colonne == "NbNoeuds":
            cursor.execute("""SELECT NbNoeuds FROM Statistiques""")
        elif colonne == "NbFichiersExt":
            cursor.execute("""SELECT NbFichiersExt FROM Statistiques""")
        elif colonne == "NbSN":
            cursor.execute("""SELECT NbSN FROM Statistiques""")
        elif colonne == "NbFichiers":
            cursor.execute("""SELECT NbFichiers FROM Statistiques""")
        elif colonne == "PoidsFichiers":
            cursor.execute("""SELECT PoidsFichiers FROM Statistiques""")
        elif colonne == "NbEnvsLstNoeuds":
            cursor.execute("""SELECT NbEnvsLstNoeuds FROM Statistiques""")
        elif colonne == "NbEnvsLstFichiers":
            cursor.execute("""SELECT NbEnvsLstFichiers FROM Statistiques""")
        elif colonne == "NbEnvsLstFichiersExt":
            cursor.execute("""SELECT NbEnvsLstFichiersExt FROM Statistiques""")
        elif colonne == "NbEnvsFichiers":
            cursor.execute("""SELECT NbEnvsFichiers FROM Statistiques""")
        elif colonne == "NbPresence":
            cursor.execute("""SELECT NbPresence FROM Statistiques""")
        elif colonne == "NbReceptFichiers":
            cursor.execute("""SELECT NbReceptFichiers FROM Statistiques""")
        else:
            logs.addLogs("ERROR : This statistic is unknown : " + str(colonne))
        conn.close()
    except Exception as e:
        logs.addLogs("ERROR : Problem with database (compterStats()):" +
                     str(e))
    conn.close()
    return str(cursor.fetchone())[1:-2]
Example #7
0
def chercherInfo(nomTable, info):
    # Fonction qui retourne une information demandée dans la table demandée dans une entrée demandé
    BDD.verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        if nomTable == "Noeuds":
            cursor.execute("""SELECT Fonction FROM Noeuds WHERE IP = ?""",
                           (info, ))
        elif nomTable == "Fichiers":
            cursor.execute("""SELECT id FROM Fichiers WHERE Nom = ?""",
                           (info, ))
        elif nomTable == "FichiersExt":
            cursor.execute("""SELECT IP FROM FichiersExt WHERE Nom = ?""",
                           (info, ))
        elif nomTable == "BlackList":
            cursor.execute("""SELECT Rank FROM BlackList WHERE Name = ?""",
                           (info, ))
        else:
            logs.addLogs("ERROR : The table is unknown in chercherInfo : " +
                         str(nomTable))
            return 0
        conn.commit()
    except Exception as e:
        conn.rollback()
        logs.addLogs("ERROR : Problem with database (chercherInfo()):" +
                     str(e))
    for row in cursor.fetchall():
        conn.close()
        return row[0]
    return 0
Example #8
0
def verifExistBDD():
    # Fonction qui permet d'alèger le code en évitant les duplications
    try:
        with open('WTP.db'):
            pass
    except Exception:
        logs.addLogs("ERROR : Base not found ... Creating a new base.")
        creerBase()
Example #9
0
File: dns.py Project: anon1892/WTP
def majDNS(ipportNoeud=""):
    # Fonction pour noeud DNS qui permet de mettre à jour toute sa base avec un autre noeud
    BDD.verifExistBDD()
    problem = 0
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    ipport = ""
    if ipportNoeud == "":
        try:
            cursor.execute(
                """SELECT IP FROM Noeuds WHERE Fonction = 'DNS' ORDER BY RANDOM() LIMIT 1"""
            )
            rows = cursor.fetchall()
            conn.close()
        except Exception as e:
            conn.rollback()
            logs.addLogs(
                "DNS : ERROR : Problem with the database (majDNS()):" + str(e))
            problem += 1
        else:
            for row in rows:
                ipport = row[0]
    else:
        ipport = ipportNoeud
        if ipport != "":
            # Maintenant on va demander au noeud DNS distant d'envoyer toutes ses entrées DNS pour
            # Que l'on puisse ensuite analyser, et ajouter/mettre à jour notre base
            connexion_avec_serveur = autresFonctions.connectionClient(ipport)
            if str(connexion_avec_serveur) != "=cmd ERROR":
                sendCmd = b""
                sendCmd = "=cmd DNS syncBase"
                connexion_avec_serveur.send(sendCmd.encode())
                rcvCmd = connexion_avec_serveur.recv(1024)
                rcvCmd = rcvCmd.decode()
                connexion_avec_serveur.close()
                # Le noeud renvoie le nom du fichier à télécharger
                # Et son IP:PortPrincipal, sinon =cmd ERROR
                if rcvCmd != "=cmd ERROR":
                    # =cmd Filename ****** ipport ******
                    filename = rcvCmd[14:rcvCmd.find(" ipport ")]
                    ipport = rcvCmd[rcvCmd.find(" ipport ") + 8:]
                    ip = ipport[:ipport.find(":")]
                    port = ipport[ipport.find(":") + 1:]
                    error += fctsClient.CmdDemandeFichier(ip, port, filename)
                    if error == 0:
                        echangeListes.filetoTable(filename, "DNS")
                    else:
                        problem += 1
                else:
                    problem += 1
            else:
                problem += 1
        else:
            problem += 1
    return problem
Example #10
0
File: dns.py Project: anon1892/WTP
def modifEntree(nomTable, entree, entree1="", entree2=""):
    # Fonction qui permet de supprimer une entrée dans une table
    # Paramètres : Le nom de la table; le nouveau SHA256; le nom de domaine; le mot de passe non hashé
    problem = 0
    BDD.verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        if nomTable == "DNS":
            if entree1 != "" and entree2 != "":
                # On vérifie que le mot de passe hashé est égal à celui de la base de données,
                # et si c'est le cas on peut suprimer la ligne
                cursor.execute("""SELECT PASSWORD FROM DNS WHERE NDD = ?""",
                               (entree1, ))
                rows = cursor.fetchall()
                nbRes = 0
                for row in rows:
                    nbRes += 1
                    if row[0] == hashlib.sha256(
                            str(entree2).encode()).hexdigest():
                        cursor.execute(
                            """UPDATE DNS SET SHA256 = ? WHERE NDD = ?""",
                            (entree, entree1))
                        conn.commit()
                    else:
                        # Le mot de passe n'est pas valide.
                        problem = 5
                if nbRes == 0:
                    logs.addLogs(
                        "DNS : ERROR: The domain name to modify does not exist (modifEntree())"
                    )
                    problem = 8
                    problem += ajouterEntree("DNS", entree1, entree, entree2)
            else:
                logs.addLogs(
                    "DNS : ERROR: There is a missing parameter to perform this action (modifEntree())"
                )
                problem += 1
        else:
            logs.addLogs(
                "DNS : ERROR: The table name was not recognized (modifEntree()) : "
                + str(nomTable))
            problem += 1
        conn.commit()
    except Exception as e:
        conn.rollback()
        logs.addLogs(
            "DNS : ERROR : Problem with the database (modifEntree()):" +
            str(e))
        problem += 1
    else:
        logs.addLogs("DNS : INFO : The domain name " + entree1 +
                     " has been modified.")
    conn.close()
    return problem
Example #11
0
def tableToFile(nomTable):
    # cette fonction a pour but de lire une table et de l'écrire dans un fichier
    error = 0
    BDD.verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        if nomTable == "Noeuds":
            cursor.execute("SELECT IP FROM Noeuds WHERE 1")
            conn.commit()
        elif nomTable == "Fichiers":
            cursor.execute("SELECT Nom FROM Fichiers WHERE 1")
            conn.commit()
        elif nomTable == "FichiersExt":
            cursor.execute("SELECT Nom FROM FichiersExt WHERE 1")
            conn.commit()
        elif nomTable == "DNS":
            cursor.execute("SELECT SHA256, NDD, PASSWORD FROM DNS WHERE 1")
            conn.commit()
        elif nomTable == "BlackList":
            cursor.execute("SELECT Name, Rank FROM BlackList WHERE 1")
            conn.commit()
        else:
            logs.addLogs(
                "ERROR: The table name was not recognized (tableToFile()) : " +
                str(nomTable))
            error += 1
    except Exception as e:
        conn.rollback()
        logs.addLogs("ERROR : Problem with database (aleatoire()):" + str(e))
        error += 1
    if error == 0:
        rows = cursor.fetchall()
        conn.close()
        fileName = "TEMP" + str(time.time())
        if error != 0:
            return error
        f = open("HOSTEDFILES/" + fileName, "a")
        for row in rows:
            if nomTable == "DNS":
                # La virgule sans espace en premier est normal
                f.write(
                    str(row[0]) + "," + str(row[1]) + ", " + str(row[2]) +
                    "\n")
            elif nomTable == "BlackList":
                f.write(str(row[0]) + ";" + str(row[1]) + "\n")
            else:
                f.write(str(row[0]) + "\n")
        f.close()
    return fileName
Example #12
0
def incrNbVerifsHS(ipPort):
    # Vérifie que le noeud existe
    # Si il existe, le noeud est incémenté de 1.
    verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        cursor.execute("""SELECT ID FROM NoeudsHorsCo WHERE IP = ?""",
                       (ipPort, ))
        rows = cursor.fetchall()
    except Exception as e:
        conn.rollback()
        logs.addLogs("ERROR : Problem with database (incrNbVerifsHS()):" +
                     str(e))
    nbRes = 0
    for row in rows:
        nbRes += 1
    if nbRes != 0:
        # Le noeud existe, on peut l'incrémenter
        try:
            cursor.execute(
                """UPDATE NoeudsHorsCo SET NbVerifs = NbVerifs + 1 WHERE IP = ?""",
                (ipPort, ))
            conn.commit()
        except Exception as e:
            conn.rollback()
            logs.addLogs("ERROR : Problem with database (incrNbVerifsHS()):" +
                         str(e))
        logs.addLogs("INFO : The number of verifications of " + ipPort +
                     " has been incremented by 1.")
    else:
        # Le noeud n'existe pas, juste un warning dans les logs.
        logs.addLogs("ERREUR : The peer off " + ipPort +
                     " could not be incremented because it no longer exists.")
    conn.close()
Example #13
0
def verifNoeudHS():
    BDD.verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    cursor.execute("""SELECT IP FROM NoeudsHorsCo WHERE 1""")
    rows = cursor.fetchall()
    for row in rows:
        # Prend un à un chaque noeud de la liste, et lui envoie une request.
        # Si le noeud répond, on le laisse tranquille, sinon on le met dans une autre table.
        IppeerPort = row[0]
        #Départager l'IP et le port
        pos1 = IppeerPort.find(':')
        pos1 = pos1 + 1
        pos2 = len(IppeerPort)
        peerPort = int(IppeerPort[pos1:pos2])
        pos1 = pos1 - 1
        peerIP = IppeerPort[0:pos1]
        # Liaison tcp/ip
        c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # Connection au receveur
        try:
            c.connect((peerIP, peerPort))
        except Exception:
            logs.addLogs(
                "ERROR : Connection to the peer out of service impossible. (verifNoeudHS())"
            )
            # Le noeud n'est pas connecté au réseau
            # On incrémente son nombre de vérifs et on le supprime si besoin
            BDD.incrNbVerifsHS(IppeerPort)
            BDD.verifNbVerifsHS(IppeerPort)
        else:
            sendCmd = b""
            sendCmd = "=cmd DemandePresence"
            sendCmd = sendCmd.encode()
            # On envoie le message
            c.send(sendCmd)
            rcvData = c.recv(1024)
            rcvData = rcvData.decode()
            if rcvData == '=cmd Present':
                # C'est bon, le noeud est connecté au reseau,
                # on l'ajoute à la table normale et on le supprime de la table des noeuds HS
                BDD.ajouterEntree("Noeuds", IppeerPort)
                BDD.supprEntree("NoeudsHorsCo", IppeerPort)
            else:
                # Le noeud n'est pas connecté au réseau, on incrémente de 1 son nombre de vérifications.
                BDD.incrNbVerifsHS(IppeerPort)
                # On vérifie si le noeud a un nombre de vérifications inférieur à 10.
                # Si ce n'est pas le cas, il est supprimé définitivement.
                BDD.verifNbVerifsHS(IppeerPort)
Example #14
0
def sayHello():
    # Fonction dont le but est d'avertir des noeuds importants de sa présence
    error = 0
    ipPortMe = autresFonctions.connaitreIP()
    connNoeud = autresFonctions.connectionClient(ipport)
    if str(connNoeud) == "=cmd ERROR":
        error += 1
    else:
        logs.addLogs("INFO : Connection with VPN peer etablished")
        request = "=cmd HELLO " + ipPortMe
        request = request.encode()
        connNoeud.send(request)
        print(connNoeud.recv(1024))
        connNoeud.close()
    return error
Example #15
0
def CmdDemandeNoeud(ip, port):
    error = 0
    connNoeud = autresFonctions.connectionClient(ip, port)
    if str(connNoeud) == "=cmd ERROR":
        error += 1
    else:
        logs.addLogs(
            "INFO : Connection with peer etablished on port {}".format(port))
        request = "=cmd DemandeNoeud"
        request = request.encode()
        connNoeud.send(request)
        rcvCmd = connNoeud.recv(1024)
        connNoeud.close()
        error += echangeNoeuds.DemandeNoeuds(str(rcvCmd))
    return error
Example #16
0
def protip():
    # Fonction qui affiche une ligne au hazard du fichier protip.txt
    try:
        f = open("protip.txt", 'r')
        lines = f.readlines()
        f.close()
    except Exception as e:
        logs.addLogs("ERROR : Unable de read the file protip.txt : " + str(e))
    else:
        hazard = randint(0, len(lines))
        nbre = 0
        for line in lines:
            if hazard == nbre:
                print(line)
                break
            nbre += 1
Example #17
0
def CmdDemandeListeNoeuds(ip, port):
    sendCmd = "=cmd DemandeListeNoeuds"
    error = 0
    connNoeud = autresFonctions.connectionClient(ip, port)
    if str(connNoeud) == "=cmd ERROR":
        error += 1
    else:
        logs.addLogs(
            "INFO : Connection with peer etablished on port {}".format(port))
        sendCmd = sendCmd.encode()
        connNoeud.send(sendCmd)
        fileName = connNoeud.recv(1024)
        connNoeud.close()
        error += CmdDemandeFichier(ip, port, fileName.decode())
        echangeListes.filetoTable(fileName.decode(), "Noeuds")
    return error
Example #18
0
def comptNbNoeuds():
    # Fonction qui compte le nombre total de neouds connus par le noeud,
    # Puis qui met à jour la base de données avec la fonction adéquate
    BDD.verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        cursor.execute("""SELECT id FROM Noeuds WHERE 1""")
        rows = cursor.fetchall()
    except Exception as e:
        logs.addLogs("ERROR : Problem with the database (comptNbNoeuds()):" +
                     str(e))
    nbTotal = 0
    for row in rows:
        nbTotal += 1
    # On met à jour directement dans la BDD
    modifStats("NbNoeuds", nbTotal)
Example #19
0
def comptTaillFchsTtl():
    # Fonction qui compte la taille totale de tous les files hébergés sur le noeud,
    # Puis qui met à jour la base de données avec la fonction adéquate
    BDD.verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        cursor.execute("""SELECT Taille FROM Fichiers WHERE 1""")
        rows = cursor.fetchall()
    except Exception as e:
        logs.addLogs(
            "ERROR : Problem with the database (comptTaillFchsTtl()):" +
            str(e))
    tailleTotale = 0
    for row in rows:
        tailleTotale += row[0]
    # On met à jour directement dans la BDD
    modifStats("PoidsFichiers", tailleTotale)
Example #20
0
def verifFichier(fileName):
    # Fonction qui vérifie si le file existe dans la base de données
    verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        cursor.execute("""SELECT ID FROM Fichiers WHERE Nom = ?""",
                       (fileName, ))
        rows = cursor.fetchall()
    except Exception as e:
        conn.rollback()
        logs.addLogs("ERROR : Problem with database (verifFichier()) : " +
                     str(e))
    FichierExiste = False
    if str(rows) != "[]":
        FichierExiste = True
    conn.close()
    return FichierExiste
Example #21
0
def portLibre(premierPort):
    # Fonction qui cherche les ports de la machine qui sont libres
    # Et renvoie le premier trouvé, en partant du port initial, donné.
    port = True
    while port:
        clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            clientsocket.connect(('127.0.0.1', int(premierPort)))
        except ConnectionRefusedError:
            # Le port est occupé !
            clientsocket.close()
            premierPort += 1
        else:
            # Le port est libre !
            clientsocket.close()
            premierPort += 1
            if premierPort < int(config.readConfFile("MaxPort")):
                return premierPort
            logs.addLogs("ERROR: All ports already in use")
Example #22
0
def checkIntruders():
    # Cette fonction a pour but de vérifier qu'il n'y a pas de fichiers
    # Qui ne devrait pas l'être dans HOSTEDFILES, sinon ils sont supprimés
    for file in os.listdir("HOSTEDFILES/"):
        file = "HOSTEDFILES/" + file
        if os.path.isdir(str(file)) is False:
            # C'est un fichier, on vérifie qu'il existe dans la BDD
            BDD.verifExistBDD()
            conn = sqlite3.connect('WTP.db')
            cursor = conn.cursor()
            try:
                cursor.execute("""SELECT ID FROM Fichiers WHERE Chemin = ?""",
                               (file, ))
                conn.commit()
            except Exception as e:
                conn.rollback()
                logs.addLogs(
                    "ERROR : Problem with database (checkIntruders()):" +
                    str(e))
                error += 1
            rows = cursor.fetchall()
            if str(rows) == "[]":
                # Il n'existe pas, on le déplace vers ADDFILES
                dest = "ADDFILES/" + str(file[12:])
                if file != dest:
                    if os.path.exists(dest) is False:
                        # Exception pour les fichiers temporels :
                        # On les supprime si ils ont plus de 24h
                        if str(file[12:16]) == "TEMP":
                            actTime = str(time.time())
                            if int(file[16:file.find(".")]) < int(
                                    actTime[:actTime.find(".")]) - 86400:
                                os.remove(file)
                                logs.addLogs(
                                    "INFO : A temporary file has been deleted : "
                                    + str(file[12:]))
                        else:
                            try:
                                shutil.copyfile(file, dest)
                            except Exception as e:
                                logs.addLogs(
                                    "ERROR : The file " + file +
                                    " could not be copied in checkIntruders : "
                                    + str(e))
                            else:
                                os.remove(file)
                                logs.addLogs(
                                    "INFO : The file has been moved from HOSTEDFILES to ADDFILES because it was not in the database"
                                )
        else:
            # C'est un dossier, on supprime
            shutil.rmtree(file)
Example #23
0
def searchNoeud(role, nbre=10):
    # Fonction qui  pour but de chercher 'nbre' noeuds ayant pour role 'role'
    BDD.verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        cursor.execute(
            """SELECT IP FROM Noeuds WHERE Fonction = ? ORDER BY RANDOM() LIMIT ?""",
            (role, nbre))
        conn.commit()
    except Exception as e:
        conn.rollback()
        logs.addLogs("ERROR : Problem with database (aleatoire()):" + str(e))
    rows = cursor.fetchall()
    tableau = []
    for row in rows:
        tableau.append(row)
        # On remplit le tableau avant de le retourner
    conn.close()
    return tableau
Example #24
0
def CmdDemandeStatut(ip, port):
    error = 0
    # On demande le statut du noeud (Simple, Parser, DNS, VPN, Main)
    connNoeud = autresFonctions.connectionClient(ip, port)
    if str(connNoeud) == "=cmd ERROR":
        error += 1
    else:
        logs.addLogs(
            "INFO : Connection with peer etablished on port {}".format(port))
        sendCmd = "=cmd status"
        connNoeud.send(sendCmd.encode())
        statut = connNoeud.recv(1024)
        connNoeud.close()
        if (statut[:5] == "=cmd "):
            statut = statut[5:]  # On enlève "=cmd "
        else:
            error += 1
    if error != 0:
        return error
    return statut
Example #25
0
File: dns.py Project: anon1892/WTP
def supprNDD(ipport, ndd, password):
    error = 0
    if autresFonctions.verifIPPORT(ipport):
        connexion_avec_serveur = autresFonctions.connectionClient(ipport)
        if str(connexion_avec_serveur) == "=cmd ERROR":
            error += 1
        else:
            logs.addLogs("Connection established with the DNS")
            # =cmd DNS supprNDD ndd ****** pass ******
            request = "=cmd DNS supprNDD ndd " + str(ndd) + " pass " + str(
                password)
            request = request.encode()
            connexion_avec_serveur.send(request)
            message = connexion_avec_serveur.recv(1024)
            if message != "=cmd SUCCESS":
                error += 1
            connexion_avec_serveur.close()
    else:
        error += 1
    return error
Example #26
0
def VPN(demande, ipPortVPN, ipPortExt):
    error = 0
    if autresFonctions.verifIPPORT(ipPortExt) and reg.match(ipPortVPN):
        ip = ipPortVPN[:ipPortVPN.find(":")]
        port = ipPortVPN[ipPortVPN.find(":") + 1:]
        connNoeud = autresFonctions.connectionClient(ip, port)
        if str(connNoeud) == "=cmd ERROR":
            error += 1
        else:
            logs.addLogs(
                "INFO : Connection with VPN peer etablished on port {}".format(
                    port))
            # =cmd VPN noeud 127.0.0.1:5555 request =cmd DemandeFichier
            request = "=cmd VPN noeud " + ipPortExt + " request " + demande
            request = request.encode()
            connNoeud.send(request)
            print(connNoeud.recv(1024))
            connNoeud.close()
            # Maintenant que l'on a demandé au VPN d'executer la demande, il faut recuperer les donnnées
            # Pour cela, il faut analyser la request initiale
            if request[:19] == "=cmd DemandeFichier":
                # =cmd DemandeFichier nom sha256.ext
                error += CmdDemandeFichier(ip, port, request[24:])
            elif request[:17] == "=cmd DemandeNoeud":
                CmdDemandeNoeud(ip, port)
            elif request[:28] == "=cmd DemandeListeFichiersExt":
                CmdDemandeListeFichiers(ip, port, 1)
            elif request[:25] == "=cmd DemandeListeFichiers":
                CmdDemandeListeFichiers(ip, port)
            elif request[:23] == "=cmd DemandeListeNoeuds":
                CmdDemandeListeNoeuds(ip, port)
            elif request[:22] == "=cmd rechercher":
                # =cmd rechercher nom SHA256.ext
                search.rechercheFichierEntiere(sendCmd[20:])
            else:
                logs.addLogs("ERROR : Unknown request (VPN()) : " +
                             str(request))
                error += 1
    else:
        error += 1
    return error
Example #27
0
def verifNbVerifsHS(ipPort):
    # Vérifie que le nombre de vérifications déjà effectuées
    # S'il y en a plus que 10, le noeud est définitivement supprimé
    verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        cursor.execute("""SELECT NbVerifs FROM NoeudsHorsCo WHERE IP = ?""",
                       (ipPort, ))
        rows = cursor.fetchall()
    except Exception as e:
        conn.rollback()
        logs.addLogs("ERROR : Problem with database(verifNbVerifsHS()):" +
                     str(e))
    nbRes = 0
    for row in rows:
        nbRes = row[0]
    if nbRes > 10:
        # Le noeud doit être supprimé
        try:
            cursor.execute("""DELETE FROM NoeudsHorsCo WHERE IP =  ?""",
                           (ipPort, ))
            conn.commit()
        except Exception as e:
            conn.rollback()
            logs.addLogs("ERROR : Problem with database (verifNbVerifsHS()):" +
                         str(e))
        logs.addLogs("INFO : The peer off " + ipPort +
                     " has been removed, it no longer responds.")
    conn.close()
Example #28
0
 def run(self):
     while self.allume:
         requete = self.getMessage()
         print("Youpi : " + requete)
         if requete[:19] == "=cmd rechercher nom":
             # =cmd rechercher nom SHA256.ext
             sortie = search.rechercheFichierEntiere(requete[20:])
             ipport = sortie[:sortie.find(";")]
             sha = sortie[sortie.find(";") + 1:]
             if re.findall(r'[0-9]+(?:\.[0-9]+){3}:[0-9]+', ipport):
                 # C'est un IPPort
                 # On envoi vers le thread qui télécharge le file
                 error += fctsClient.CmdDemandeFichier(
                     ipport[:ipport.find(":")],
                     int(ipport[ipport.find(":") + 1:]), sha)
                 if error == 0:
                     resultat = "=cmd SUCCESS : " + str(
                         config.readConfFile(
                             "Path")) + "/HOSTEDFILES/" + sha
                 elif error == 5:
                     resultat = "=cmd ERROR NO FILE"
                 else:
                     resultat = "=cmd ERROR"
             else:
                 # C'est une erreur
                 print("AHH")
                 print(sortie)
                 print(ipport)
                 resultat = sortie
         elif requete[:15] == "=cmd VPN noeud " and requete.find(
                 " request =cmd DemandeFichier") != -1:
             # =cmd VPN noeud 127.0.0.1:5555 request =cmd DemandeFichier
             ipport = requete[requete.find("=cmd VPN noeud ") +
                              15:requete.find(" request ")]
             resultat = requete[requete.find(" request ") + 10:]
         else:
             resultat = "=cmd CommandeInconnue :" + requete + ":"
         print(resultat)
         logs.addLogs(resultat)
         self.sendMessage(self.encodeMessage(resultat))
Example #29
0
def connectionClient(ip, port="", verify=1):
    if port == "":
        port = ip[ip.find(":") + 1:]
        ip = ip[:ip.find(":")]
    if verifIPPORT(str(ip) + ":" + str(port)):
        try:
            conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            conn.settimeout(15)
            #conn = ssl.wrap_socket(conn, ssl_version=ssl.PROTOCOL_TLSv1, ciphers="ADH-AES256-SHA")
            conn.connect((ip, int(port)))
        except Exception as e:
            logs.addLogs("INFO : Unable to connect to " + str(ip) + ":" +
                         str(port) + " Reason : " + str(e))
        else:
            return conn
    if verify == 1:
        # On ajoute le noeud dans la liste des noeuds Hors Connection s'il n'y est pas déjà
        # (Mais on ne l'incrémente pas s'il l'est déjà)
        IppeerPort = ip + ":" + str(port)
        BDD.ajouterEntree("NoeudsHorsCo", IppeerPort)
        BDD.supprEntree("Noeuds", IppeerPort)
    return "=cmd ERROR"
Example #30
0
 def run(self):
     status = loader("The DNS service start")
     status.start()
     host = '127.0.0.1'
     port = int(config.readConfFile("VPNPort"))
     logs.addLogs(
         "INFO : The VPN service has started, he is now listening to the port "
         + str(port))
     try:
         try:
             tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
             #tcpsock = ssl.wrap_socket(tcpsock, ssl_version=ssl.PROTOCOL_TLSv1, ciphers="ADH-AES256-SHA")
             tcpsock.bind((host, port))
             tcpsock.settimeout(5)
         except OSError as e:
             logs.addLogs("ERROR : In vpn.py : " + str(e))
             logs.addLogs("FATAL : Shutting down...")
             print(
                 c("red") + "An error occured. Please restart WTP." + c(""))
         else:
             logs.addLogs(
                 "INFO : The VPN service has started, he is now listening to the port "
                 + str(port))
             status.stop()
             status.join()
             while self.serveur_lance:
                 try:
                     tcpsock.listen(10)
                     (clientsocket, (ip, port)) = tcpsock.accept()
                 except socket.timeout:
                     pass
                 else:
                     newthread = ClientThread(ip, port, clientsocket)
                     newthread.start()
     except KeyboardInterrupt:
         print(" pressed: Shutting down ...")
         print("")
     logs.addLogs("INFO : WTP service has been stoped successfully.")