def importProjet(fichier): #Variables de temps date_import=datetime.datetime.now() chemin=BASE+'sav_'+str(date_import).replacae(' ','_')+'/' os.mkdir(chemin) with open(chemin+'import.tar.gz', 'wb+',0) as archive: for chunk in fichier.chunks(): archive.write(chunk) archive.close() subprocess.check_output('tar -xvf '+str(chemin)+'import.tar.gz'+' -C '+str(chemin), shell=True) shutil.copyfile(chemin+'sav/settings.py',BASE+'soc/settings.py') shutil.copyfile(chemin+'sav/default.cfg',BASE+'soc/default.cfg') #Import postgreSQL postgresql=settings.DATABASES['default'] host=postgresql['HOST'] port=int(postgresql['PORT']) base=desatanize(postgresql['NAME']) user=desatanize(postgresql['USER']) password=desatanize(postgresql['PASSWORD']) initialiserPG(chemin+'sav/database.pg',host,port,base,user,password) shutil.rmtree(chemin) subprocess.check_output('touch '+BASE+'soc/wsgi-apache.py', shell=True)
def importProjet(fichier): #Variables de temps date_import = datetime.datetime.now() chemin = BASE + 'sav_' + str(date_import).replacae(' ', '_') + '/' os.mkdir(chemin) with open(chemin + 'import.tar.gz', 'wb+', 0) as archive: for chunk in fichier.chunks(): archive.write(chunk) archive.close() subprocess.check_output('tar -xvf ' + str(chemin) + 'import.tar.gz' + ' -C ' + str(chemin), shell=True) shutil.copyfile(chemin + 'sav/settings.py', BASE + 'soc/settings.py') shutil.copyfile(chemin + 'sav/default.cfg', BASE + 'soc/default.cfg') #Import postgreSQL postgresql = settings.DATABASES['default'] host = postgresql['HOST'] port = int(postgresql['PORT']) base = desatanize(postgresql['NAME']) user = desatanize(postgresql['USER']) password = desatanize(postgresql['PASSWORD']) initialiserPG(chemin + 'sav/database.pg', host, port, base, user, password) shutil.rmtree(chemin) subprocess.check_output('touch ' + BASE + 'soc/wsgi-apache.py', shell=True)
def initialiserPG(dump_file,host,port,database,login,password): ''' Cette fonction permet d'initialiser une base de donnée POstgreSQL à partir d'un fichier de dump ''' conn = psycopg2.connect(host=host,port=port,database='postgres',user=login,password=password) conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cursor=conn.cursor() cursor.execute("SELECT datdba FROM pg_database WHERE datname=%s",[database]) base=dictfetchall(cursor) cursor.execute("SELECT rolcreatedb,oid FROM pg_roles WHERE rolname=%s",[login]) user=dictfetchall(cursor) #si la base n'existe pas #et si l'utilisateur possede le droit de creation de base if ((len(base)==0) and (user[0]['rolcreatedb']==True)): error=re.search('[;|<>]&"\'',str(database)) if error!=None: raise Exception("Erreur de paramètre") cursor.execute('CREATE DATABASE '+str(database)) cursor.close() if len(base)==1: conn = psycopg2.connect(host=host,port=port,database=database,user=login,password=password) conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cursor=conn.cursor() cursor.execute("SELECT tablename FROM pg_tables WHERE tableowner=%s AND schemaname='public'",[login]) liste=dictfetchall(cursor) for table in liste: cursor.execute("DROP TABLE IF EXISTS "+str(table['tablename'])+" CASCADE") os.putenv('PGPASSWORD',password) #On recupère l'adresse IP si l'utilisateur nous envoie le hostname try: host=valideIP(host) except: host=getIP(host) subprocess.check_output('psql -h '+desatanize(host)+' -p '+str(port)+' -d '+desatanize(database)+' -U '+desatanize(login)+' < '+dump_file, shell=True)
def exportProjet(): #Sauveguarde des rapports et des fichiers de config try: os.mkdir(BASE + 'sav/') except OSError: pass #shutil.copytree(BASE+'rapports/rapports/',BASE+'sav/') shutil.copyfile(BASE + 'soc/settings.py', BASE + 'sav/settings.py') shutil.copyfile(BASE + 'soc/default.cfg', BASE + 'sav/default.cfg') #DUMP postgreSQL postgresql = settings.DATABASES['default'] host = postgresql['HOST'] port = int(postgresql['PORT']) base = desatanize(postgresql['NAME']) user = desatanize(postgresql['USER']) password = desatanize(postgresql['PASSWORD']) #Variables de temps date_dump = str(datetime.datetime.now()).replace(' ', '_') os.putenv('PGPASSWORD', password) subprocess.check_output('pg_dump -h ' + host + ' -p ' + str(port) + ' -d ' + base + ' -U ' + user + ' > ' + BASE + 'sav/database.pg', shell=True) #Creation de l'archive chemin_archive = BASE + 'sav/' nom = 'sav-soc_' + str(date_dump) + '.tar.gz' subprocess.check_output('tar -C ' + BASE + ' -cvf ' + chemin_archive + nom + ' sav/', shell=True) #Mise en ram et nettoyage temp = open(chemin_archive + nom, 'rb') archive = temp.read() temp.close() shutil.rmtree(BASE + 'sav/') return nom, archive
def exportProjet(): #Sauveguarde des rapports et des fichiers de config try: os.mkdir(BASE+'sav/') except OSError: pass #shutil.copytree(BASE+'rapports/rapports/',BASE+'sav/') shutil.copyfile(BASE+'soc/settings.py',BASE+'sav/settings.py') shutil.copyfile(BASE+'soc/default.cfg',BASE+'sav/default.cfg') #DUMP postgreSQL postgresql=settings.DATABASES['default'] host=postgresql['HOST'] port=int(postgresql['PORT']) base=desatanize(postgresql['NAME']) user=desatanize(postgresql['USER']) password=desatanize(postgresql['PASSWORD']) #Variables de temps date_dump=str(datetime.datetime.now()).replace(' ','_') os.putenv('PGPASSWORD',password) subprocess.check_output('pg_dump -h '+host+' -p '+str(port)+' -d '+base+' -U '+user+' > '+BASE+'sav/database.pg', shell=True) #Creation de l'archive chemin_archive=BASE+'sav/' nom='sav-soc_'+str(date_dump)+'.tar.gz' subprocess.check_output('tar -C '+BASE+' -cvf '+chemin_archive+nom+' sav/', shell=True) #Mise en ram et nettoyage temp=open(chemin_archive+nom,'rb') archive=temp.read() temp.close() shutil.rmtree(BASE+'sav/') return nom,archive
def initialiserPG(dump_file, host, port, database, login, password): ''' Cette fonction permet d'initialiser une base de donnée POstgreSQL à partir d'un fichier de dump ''' conn = psycopg2.connect(host=host, port=port, database='postgres', user=login, password=password) conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cursor = conn.cursor() cursor.execute("SELECT datdba FROM pg_database WHERE datname=%s", [database]) base = dictfetchall(cursor) cursor.execute("SELECT rolcreatedb,oid FROM pg_roles WHERE rolname=%s", [login]) user = dictfetchall(cursor) #si la base n'existe pas #et si l'utilisateur possede le droit de creation de base if ((len(base) == 0) and (user[0]['rolcreatedb'] == True)): error = re.search('[;|<>]&"\'', str(database)) if error != None: raise Exception("Erreur de paramètre") cursor.execute('CREATE DATABASE ' + str(database)) cursor.close() if len(base) == 1: conn = psycopg2.connect(host=host, port=port, database=database, user=login, password=password) conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cursor = conn.cursor() cursor.execute( "SELECT tablename FROM pg_tables WHERE tableowner=%s AND schemaname='public'", [login]) liste = dictfetchall(cursor) for table in liste: cursor.execute("DROP TABLE IF EXISTS " + str(table['tablename']) + " CASCADE") os.putenv('PGPASSWORD', password) #On recupère l'adresse IP si l'utilisateur nous envoie le hostname try: host = valideIP(host) except: host = getIP(host) subprocess.check_output('psql -h ' + desatanize(host) + ' -p ' + str(port) + ' -d ' + desatanize(database) + ' -U ' + desatanize(login) + ' < ' + dump_file, shell=True)
def creerRapportSolutions(listeIP,group_by,titre='rapportSolutions',traduire=False): cursor=connection.cursor() if group_by=='vuln': cursor.execute('''SELECT DISTINCT(id),criticite,nom,solution,description,infos_complementaires,ip_hote FROM vulnerabilitees INNER JOIN vuln_hote_service ON vuln_hote_service.id_vuln=vulnerabilitees.id WHERE criticite!='Info' AND date_correction is NULL ORDER BY id ASC''') else: cursor.execute('''SELECT ip_hote,nom,description,solution,infos_complementaires,criticite FROM vuln_hote_service INNER JOIN vulnerabilitees ON id_vuln=id WHERE criticite!='Info' AND date_correction is NULL ORDER BY ip_hote ASC''') dict_vuln_temp=dictfetchall(cursor) dict_vuln=[] taille=len(dict_vuln_temp) #On selectionne uniquement les adresses demandees for i in range(0,taille): if (dict_vuln_temp[i]['ip_hote'] in listeIP): dict_vuln.append(dict_vuln_temp[i]) if group_by=='vuln': dict_vuln_temp=[] taille=len(dict_vuln) id_vuln_precedent=-1 indice=-1 for i in range(0,taille): id_actuel=dict_vuln[i]['id'] if id_actuel!=id_vuln_precedent: id_vuln_precedent=id_actuel indice=indice+1 dict_vuln_temp.append(dict_vuln[i]) dict_vuln_temp[indice]['ip_hote']=[dict_vuln[i]['ip_hote']] else: dict_vuln_temp[indice]['ip_hote'].append(dict_vuln[i]['ip_hote']) del dict_vuln vuln_critical=[] vuln_high=[] vuln_medium=[] vuln_low=[] for vuln in dict_vuln_temp: crit=vuln['criticite'] if crit=='Critical': vuln_critical.append(vuln) elif crit=='High': vuln_high.append(vuln) elif crit=='Medium': vuln_medium.append(vuln) else: vuln_low.append(vuln) dict_vuln=vuln_critical+vuln_high+vuln_medium+vuln_low repartition_vuln={'critique':len(vuln_critical),'haute':len(vuln_high),'moyenne':len(vuln_medium),'faible':len(vuln_low)} else: repartition_vuln={'critique':0,'haute':0,'moyenne':0,'faible':0} for vuln in dict_vuln: crit=vuln['criticite'] if crit=='Critical': repartition_vuln['critique']+=1 if crit=='High': repartition_vuln['haute']+=1 if crit=='Medium': repartition_vuln['moyenne']+=1 else: repartition_vuln['faible']+=1 #Mise en forme du titre #Rappel: en latex les caractères spéciaux (_,& doivent être échappés), sinon erreur de compilation titre=titre.replace('&','\&').replace('_','') copyfile(REP_TRAVAIL+'base.tex',REP_TRAVAIL+'temp/'+titre+'.tex') pageGarde('Actions correctrices\n"'+titre+'"',AUTEUR,SOCIETE,LOGO,REP_TRAVAIL+'temp/'+titre+'.tex') intro(repartition_vuln,listeIP,REP_TRAVAIL+'temp/'+titre+'.tex') tableauVulnerabilites(dict_vuln,group_by,REP_TRAVAIL+'temp/'+titre+'.tex') tableauSolutions(dict_vuln,group_by,REP_TRAVAIL+'temp/'+titre+'.tex') fichierLatex=open(REP_TRAVAIL+'temp/'+titre+'.tex','a') fichierLatex.write(''' \\end{document}''') fichierLatex.close() liste_arguments=[REP_TRAVAIL,titre] #Contrôle des arguments for arg in liste_arguments: desatanize(str(arg)) titre_latex=titre titre_latex=titre_latex.replace(" ","\ ").replace("'","\\'") #Necessaire pour la creation des liens dans le sommaire vers les différentes parties for i in range(0,3): try: subprocess.check_output(['pdflatex -no-file-line-error -interaction=nonstopmode --output-directory '+REP_TRAVAIL+'temp/ '+REP_TRAVAIL+'temp/'+titre_latex+'.tex >/dev/null'],shell=True) time.sleep(2) except Exception as e: logger.error("Erreur generation rapport: "+str(e)) pass f = open(REP_TRAVAIL+'temp/'+titre+'.pdf', 'r') pdf= f.read() f.close() subprocess.check_output(['rm '+REP_TRAVAIL+'temp/'+titre.replace(' ','\ ').replace("'","\\'")+'.* >/dev/null'],shell=True) return pdf
def clean_nmapOptions(self): try: opt=desatanize(self.cleaned_data['nmapOptions']) return self.cleaned_data['nmapOptions'] except: raise forms.ValidationError('Options invalides')
def creerRapportSolutions(listeIP, group_by, titre='rapportSolutions', traduire=False): cursor = connection.cursor() if group_by == 'vuln': cursor.execute( '''SELECT DISTINCT(id),criticite,nom,solution,description,infos_complementaires,ip_hote FROM vulnerabilitees INNER JOIN vuln_hote_service ON vuln_hote_service.id_vuln=vulnerabilitees.id WHERE criticite!='Info' AND date_correction is NULL ORDER BY id ASC''' ) else: cursor.execute( '''SELECT ip_hote,nom,description,solution,infos_complementaires,criticite FROM vuln_hote_service INNER JOIN vulnerabilitees ON id_vuln=id WHERE criticite!='Info' AND date_correction is NULL ORDER BY ip_hote ASC''' ) dict_vuln_temp = dictfetchall(cursor) dict_vuln = [] taille = len(dict_vuln_temp) #On selectionne uniquement les adresses demandees for i in range(0, taille): if (dict_vuln_temp[i]['ip_hote'] in listeIP): dict_vuln.append(dict_vuln_temp[i]) if group_by == 'vuln': dict_vuln_temp = [] taille = len(dict_vuln) id_vuln_precedent = -1 indice = -1 for i in range(0, taille): id_actuel = dict_vuln[i]['id'] if id_actuel != id_vuln_precedent: id_vuln_precedent = id_actuel indice = indice + 1 dict_vuln_temp.append(dict_vuln[i]) dict_vuln_temp[indice]['ip_hote'] = [dict_vuln[i]['ip_hote']] else: dict_vuln_temp[indice]['ip_hote'].append( dict_vuln[i]['ip_hote']) del dict_vuln vuln_critical = [] vuln_high = [] vuln_medium = [] vuln_low = [] for vuln in dict_vuln_temp: crit = vuln['criticite'] if crit == 'Critical': vuln_critical.append(vuln) elif crit == 'High': vuln_high.append(vuln) elif crit == 'Medium': vuln_medium.append(vuln) else: vuln_low.append(vuln) dict_vuln = vuln_critical + vuln_high + vuln_medium + vuln_low repartition_vuln = { 'critique': len(vuln_critical), 'haute': len(vuln_high), 'moyenne': len(vuln_medium), 'faible': len(vuln_low) } else: repartition_vuln = { 'critique': 0, 'haute': 0, 'moyenne': 0, 'faible': 0 } for vuln in dict_vuln: crit = vuln['criticite'] if crit == 'Critical': repartition_vuln['critique'] += 1 if crit == 'High': repartition_vuln['haute'] += 1 if crit == 'Medium': repartition_vuln['moyenne'] += 1 else: repartition_vuln['faible'] += 1 #Mise en forme du titre #Rappel: en latex les caractères spéciaux (_,& doivent être échappés), sinon erreur de compilation titre = titre.replace('&', '\&').replace('_', '') copyfile(REP_TRAVAIL + 'base.tex', REP_TRAVAIL + 'temp/' + titre + '.tex') pageGarde('Actions correctrices\n"' + titre + '"', AUTEUR, SOCIETE, LOGO, REP_TRAVAIL + 'temp/' + titre + '.tex') intro(repartition_vuln, listeIP, REP_TRAVAIL + 'temp/' + titre + '.tex') tableauVulnerabilites(dict_vuln, group_by, REP_TRAVAIL + 'temp/' + titre + '.tex') tableauSolutions(dict_vuln, group_by, REP_TRAVAIL + 'temp/' + titre + '.tex') fichierLatex = open(REP_TRAVAIL + 'temp/' + titre + '.tex', 'a') fichierLatex.write(''' \\end{document}''') fichierLatex.close() liste_arguments = [REP_TRAVAIL, titre] #Contrôle des arguments for arg in liste_arguments: desatanize(str(arg)) titre_latex = titre titre_latex = titre_latex.replace(" ", "\ ").replace("'", "\\'") #Necessaire pour la creation des liens dans le sommaire vers les différentes parties for i in range(0, 3): try: subprocess.check_output([ 'pdflatex -no-file-line-error -interaction=nonstopmode --output-directory ' + REP_TRAVAIL + 'temp/ ' + REP_TRAVAIL + 'temp/' + titre_latex + '.tex >/dev/null' ], shell=True) time.sleep(2) except Exception as e: logger.error("Erreur generation rapport: " + str(e)) pass f = open(REP_TRAVAIL + 'temp/' + titre + '.pdf', 'r') pdf = f.read() f.close() subprocess.check_output([ 'rm ' + REP_TRAVAIL + 'temp/' + titre.replace(' ', '\ ').replace("'", "\\'") + '.* >/dev/null' ], shell=True) return pdf
def creerRapportEvolution(nomUnique,id_scan,type_scan): cursor=connection.cursor() cursor.execute('SELECT date_lancement FROM scans_status WHERE id=%s LIMIT 1',[id_scan]) date=dictfetchall(cursor) date_scan=date[0]['date_lancement'] cursor.execute('''SELECT ip_hote,nom,description,criticite,date_correction,date_detection FROM vuln_hote_service INNER JOIN vulnerabilitees ON vuln_hote_service.id_vuln=vulnerabilitees.id WHERE (date_detection=%s or date_correction=%s) AND criticite!='Info' ORDER BY ip_hote ASC''',[date_scan,date_scan]) retourScan=dictfetchall(cursor) cursor.execute('''SELECT ip_hote,nom,protocole,port,version,date_ajout,date_retrait FROM services WHERE date_ajout=%s or date_retrait=%s ORDER BY ip_hote ASC''',[date_scan,date_scan]) retourServices=dictfetchall(cursor) if type_scan=='plannifie': cursor.execute('''SELECT id_scan_plannifie FROM scans_status INNER JOIN scan_plannifie_status ON scans_status.id=scan_plannifie_status.id_scans_status WHERE scans_status.id=%s LIMIT 1''',[id_scan]) dict_id_scan=dictfetchall(cursor) id_scan_plannifie=dict_id_scan[0]['id_scan_plannifie'] cursor.execute('SELECT DISTINCT(ip) FROM scan_hote WHERE id_scan=%s',[id_scan]) dictIP=dictfetchall(cursor) cursor.execute('SELECT * FROM scans_plannifies WHERE id=%s LIMIT 1',[id_scan_plannifie]) dictScan=dictfetchall(cursor) titre='Rapport du scan plannifie\n"'+str(dictScan[0]['nom'])+'"\ndu '+str(date_scan).split(' ')[0] chemin_rapport=REP_RAPPORT+'ScansPlannifies/'+str(int(id_scan_plannifie))+'/'+str(int(id_scan))+'/' else: cursor.execute('''SELECT id_scan_manuel FROM scans_status INNER JOIN scan_manuel_status ON scans_status.id=scan_manuel_status.id_scans_status WHERE scans_status.id=%s LIMIT 1''',[id_scan]) dict_id_scan=dictfetchall(cursor) id_scan_manuel=dict_id_scan[0]['id_scan_manuel'] cursor.execute('SELECT DISTINCT(ip_hote) FROM scan_manuel_hote WHERE id_scan_manuel=%s',[id_scan_manuel]) dictIP=dictfetchall(cursor) cursor.execute('SELECT * FROM scans_manuels WHERE id=%s LIMIT 1',[id_scan_manuel]) dictScan=dictfetchall(cursor) if len(dictIP)==1: try: name, alias, addresslist = socket.gethostbyaddr(dictIP[0]['ip_hote']) except: name=dictIP[0]['ip_hote'] titre='Rapport du scan Manuel sur \n"'+str(name)+'"\ndu '+str(date_scan).split(' ')[0] else: titre='Rapport du scan Manuel \n démarré le '+str(date_scan).split(' ')[0]+'\n à '+str(date_scan).split(' ')[1].split('.')[0] chemin_rapport=REP_RAPPORT+'ScansManuels/'+str(int(id_scan))+'/' copyfile(REP_TRAVAIL+'base.tex',REP_TRAVAIL+'/temp/'+nomUnique+'.tex') pageGarde(titre,AUTEUR,SOCIETE,LOGO,REP_TRAVAIL+'/temp/'+nomUnique+'.tex') if type_scan=='plannifie': intro(dictScan[0],dictIP,REP_TRAVAIL+'/temp/'+nomUnique+'.tex','plannifie') else: intro(dictScan[0],dictIP,REP_TRAVAIL+'/temp/'+nomUnique+'.tex','manuel') fichierLatex=open(REP_TRAVAIL+'/temp/'+nomUnique+'.tex','a') fichierLatex.write('''\\newpage \\section{Scans}''') fichierLatex.close() if dictScan[0]['nessus']==True: tableauVuln(retourScan,REP_TRAVAIL+'/temp/'+nomUnique+'.tex') if dictScan[0]['nmap']==True: tableauServices(retourServices,REP_TRAVAIL+'/temp/'+nomUnique+'.tex') fichierLatex=open(REP_TRAVAIL+'/temp/'+nomUnique+'.tex','a') fichierLatex.write(''' \\end{document}''') fichierLatex.close() liste_arguments=[REP_TRAVAIL,nomUnique,chemin_rapport] #Contrôle des arguments #On s'assure qu'il n'y ait pas d'injection de codes tiers for arg in liste_arguments: tmp=desatanize(str(arg)) #Necessaire pour la creation des liens dans le sommaire vers les différentes parties for i in range(0,5): try: subprocess.check_output(['pdflatex -no-file-line-error -interaction=nonstopmode --output-directory '+REP_TRAVAIL+'temp/ '+REP_TRAVAIL+'temp/'+nomUnique+'.tex >/dev/null &>/dev/null'],shell=True) time.sleep(3) except Exception as e: logger.error("Erreur generation rapport ["+str(id_scan)+"] : "+str(e)) pass time.sleep(10) copyfile(REP_TRAVAIL+'temp/'+nomUnique+'.pdf',chemin_rapport+nomUnique+'_evolution.pdf') subprocess.check_output(['rm '+REP_TRAVAIL+'temp/'+nomUnique+'* >/dev/null'],shell=True)
def creerRapportEvolution(nomUnique, id_scan, type_scan): cursor = connection.cursor() cursor.execute( 'SELECT date_lancement FROM scans_status WHERE id=%s LIMIT 1', [id_scan]) date = dictfetchall(cursor) date_scan = date[0]['date_lancement'] cursor.execute( '''SELECT ip_hote,nom,description,criticite,date_correction,date_detection FROM vuln_hote_service INNER JOIN vulnerabilitees ON vuln_hote_service.id_vuln=vulnerabilitees.id WHERE (date_detection=%s or date_correction=%s) AND criticite!='Info' ORDER BY ip_hote ASC''', [date_scan, date_scan]) retourScan = dictfetchall(cursor) cursor.execute( '''SELECT ip_hote,nom,protocole,port,version,date_ajout,date_retrait FROM services WHERE date_ajout=%s or date_retrait=%s ORDER BY ip_hote ASC''', [date_scan, date_scan]) retourServices = dictfetchall(cursor) if type_scan == 'plannifie': cursor.execute( '''SELECT id_scan_plannifie FROM scans_status INNER JOIN scan_plannifie_status ON scans_status.id=scan_plannifie_status.id_scans_status WHERE scans_status.id=%s LIMIT 1''', [id_scan]) dict_id_scan = dictfetchall(cursor) id_scan_plannifie = dict_id_scan[0]['id_scan_plannifie'] cursor.execute('SELECT DISTINCT(ip) FROM scan_hote WHERE id_scan=%s', [id_scan]) dictIP = dictfetchall(cursor) cursor.execute('SELECT * FROM scans_plannifies WHERE id=%s LIMIT 1', [id_scan_plannifie]) dictScan = dictfetchall(cursor) titre = 'Rapport du scan plannifie\n"' + str( dictScan[0]['nom']) + '"\ndu ' + str(date_scan).split(' ')[0] chemin_rapport = REP_RAPPORT + 'ScansPlannifies/' + str( int(id_scan_plannifie)) + '/' + str(int(id_scan)) + '/' else: cursor.execute( '''SELECT id_scan_manuel FROM scans_status INNER JOIN scan_manuel_status ON scans_status.id=scan_manuel_status.id_scans_status WHERE scans_status.id=%s LIMIT 1''', [id_scan]) dict_id_scan = dictfetchall(cursor) id_scan_manuel = dict_id_scan[0]['id_scan_manuel'] cursor.execute( 'SELECT DISTINCT(ip_hote) FROM scan_manuel_hote WHERE id_scan_manuel=%s', [id_scan_manuel]) dictIP = dictfetchall(cursor) cursor.execute('SELECT * FROM scans_manuels WHERE id=%s LIMIT 1', [id_scan_manuel]) dictScan = dictfetchall(cursor) if len(dictIP) == 1: try: name, alias, addresslist = socket.gethostbyaddr( dictIP[0]['ip_hote']) except: name = dictIP[0]['ip_hote'] titre = 'Rapport du scan Manuel sur \n"' + str( name) + '"\ndu ' + str(date_scan).split(' ')[0] else: titre = 'Rapport du scan Manuel \n démarré le ' + str( date_scan).split(' ')[0] + '\n à ' + str(date_scan).split( ' ')[1].split('.')[0] chemin_rapport = REP_RAPPORT + 'ScansManuels/' + str( int(id_scan)) + '/' copyfile(REP_TRAVAIL + 'base.tex', REP_TRAVAIL + '/temp/' + nomUnique + '.tex') pageGarde(titre, AUTEUR, SOCIETE, LOGO, REP_TRAVAIL + '/temp/' + nomUnique + '.tex') if type_scan == 'plannifie': intro(dictScan[0], dictIP, REP_TRAVAIL + '/temp/' + nomUnique + '.tex', 'plannifie') else: intro(dictScan[0], dictIP, REP_TRAVAIL + '/temp/' + nomUnique + '.tex', 'manuel') fichierLatex = open(REP_TRAVAIL + '/temp/' + nomUnique + '.tex', 'a') fichierLatex.write('''\\newpage \\section{Scans}''') fichierLatex.close() if dictScan[0]['nessus'] == True: tableauVuln(retourScan, REP_TRAVAIL + '/temp/' + nomUnique + '.tex') if dictScan[0]['nmap'] == True: tableauServices(retourServices, REP_TRAVAIL + '/temp/' + nomUnique + '.tex') fichierLatex = open(REP_TRAVAIL + '/temp/' + nomUnique + '.tex', 'a') fichierLatex.write(''' \\end{document}''') fichierLatex.close() liste_arguments = [REP_TRAVAIL, nomUnique, chemin_rapport] #Contrôle des arguments #On s'assure qu'il n'y ait pas d'injection de codes tiers for arg in liste_arguments: tmp = desatanize(str(arg)) #Necessaire pour la creation des liens dans le sommaire vers les différentes parties for i in range(0, 5): try: subprocess.check_output([ 'pdflatex -no-file-line-error -interaction=nonstopmode --output-directory ' + REP_TRAVAIL + 'temp/ ' + REP_TRAVAIL + 'temp/' + nomUnique + '.tex >/dev/null &>/dev/null' ], shell=True) time.sleep(3) except Exception as e: logger.error("Erreur generation rapport [" + str(id_scan) + "] : " + str(e)) pass time.sleep(10) copyfile(REP_TRAVAIL + 'temp/' + nomUnique + '.pdf', chemin_rapport + nomUnique + '_evolution.pdf') subprocess.check_output( ['rm ' + REP_TRAVAIL + 'temp/' + nomUnique + '* >/dev/null'], shell=True)
def clean_nmapOptions(self): try: opt = desatanize(self.cleaned_data["nmapOptions"]) return self.cleaned_data["nmapOptions"] except: raise forms.ValidationError("Options invalides")