def test_sessionEnded(self):
        # Mock the Time module.
        currentTime = 0

        class MockTimeModule:
            def getCurrentTimestamp(self):
                return currentTime

        DatabaseManager.Time = MockTimeModule()

        # Initialize and close the initial database.
        self.initialDatabase.execute(
            "CREATE TABLE Users (Id char(9),AccessType STRING);")
        self.initialDatabase.execute(
            "CREATE TABLE Sessions (Id char(9),StartTime BIGINT,EndTime BIGINT);"
        )
        self.initialDatabase.commit()
        self.initialDatabase.close()

        # Create the database, start and end sessions, and assert the sessions are correct.
        CuT = DatabaseManager.DatabaseManager(self.databaseFile)
        CuT.sessionStarted(Session.Session(User.User("000000001", 10), 5))
        currentTime = 7
        CuT.sessionEnded(Session.Session(User.User("000000001", 10), 5))
        CuT.sessionStarted(Session.Session(User.User("000000002", 10), 8))
        currentTime = 9
        CuT.sessionEnded(Session.Session(User.User("000000002", 10), 8))
        CuT.sessionStarted(Session.Session(User.User("000000001", 10), 15))
        sessions = CuT.database.execute("SELECT * FROM Sessions;").fetchall()
        self.assertEqual(sessions[0], ("000000001", 5, 7),
                         "Session is incorrect.")
        self.assertEqual(sessions[1], ("000000002", 8, 9),
                         "Session is incorrect.")
        self.assertEqual(sessions[2], ("000000001", 15, 0),
                         "Session is incorrect.")
    def test_sessionStarted(self):
        # Initialize and close the initial database.
        self.initialDatabase.execute(
            "CREATE TABLE Users (Id char(9),AccessType STRING);")
        self.initialDatabase.execute(
            "CREATE TABLE Sessions (Id char(9),StartTime BIGINT,EndTime BIGINT);"
        )
        self.initialDatabase.commit()
        self.initialDatabase.close()

        # Set the static database, start sessions, and assert the sessions are correct.
        DatabaseManager.staticDatabaseManager = DatabaseManager.DatabaseManager(
            self.databaseFile)
        DatabaseManager.sessionStarted(
            Session.Session(User.User("000000001", 10), 5))
        DatabaseManager.sessionStarted(
            Session.Session(User.User("000000002", 10), 8))
        DatabaseManager.sessionStarted(
            Session.Session(User.User("000000001", 10), 15))
        sessions = DatabaseManager.staticDatabaseManager.database.execute(
            "SELECT * FROM Sessions;").fetchall()
        self.assertEqual(sessions[0], ("000000001", 5, 0),
                         "Session is incorrect.")
        self.assertEqual(sessions[1], ("000000002", 8, 0),
                         "Session is incorrect.")
        self.assertEqual(sessions[2], ("000000001", 15, 0),
                         "Session is incorrect.")
Exemplo n.º 3
0
 def analyseSubmission(self, submission):
     sid = submission.id
     Session().expunge(submission)
     if type(submission) != Model.Submission:
         raise Exception("Invalid submission object")
     nb_of_modules_for_this_submission = 0
     for m in self.modules:
         if m.analyse(submission) is True:
             nb_of_modules_for_this_submission += 1
     submission = Session().query(Submission).filter(Submission.id == sid).one()
     submission.working_modules = nb_of_modules_for_this_submission
     Session.commit()
Exemplo n.º 4
0
    def post(current_user, self):
        if current_user[1]==False:
            return {'message': 'Access Denied!'}, 403
        json_data = request.get_json(force=True)
        if not json_data:
            return {'message': 'No input data provided'}, 400
        
        data, errors = session_schema.load(json_data)
        if errors:
            return errors, 422

        lecon = Lecons.query.filter_by(id=data['lecons_id']).first()
        enseignant = Enseignants.query.filter_by(id=lecon.enseignant_id).first()

        if not current_user[0]==enseignant:
            return {'message': 'Action Forbidden!'}, 403
        
        session = Session(
            salles_id=data['salles_id'],
            date_debut=data['date_debut'],
            lecons_id=data['lecons_id'],
            )
        
        db.session.add(session)
        db.session.commit()
        session = Session.query.filter_by(lecons_id=data['lecons_id']).all()
        result = sessions_schema.dump(session).data
        result = result[len(result)-1]

        return 'Le numero de la seance est: ' +str(result['id']), 201
Exemplo n.º 5
0
    def post(self):
        uemail = self.request.get('email')
        upwd = self.request.get('pwd')
        if uemail == '' or upwd == '':
            self.redirect('/error')

        else:
            user = ndb.Key('User', uemail).get()
            if user and user.pwd == upwd:
                token = security.generate_random_string(length=20)
                session = Session(id=token)
                session.userKey = user.put()
                session.put()
                self.response.set_cookie(key='token', value=token, path='/')
                self.redirect("/home")

            else:
                self.redirect("/login")
Exemplo n.º 6
0
 def post(self):
     username=self.request.get("uname")
     uemail=self.request.get("email")
     upwd=self.request.get("pwd")
     if username == '' or uemail=='' or upwd=='':
         self.redirect('/error')
     else:
         user=User.get_by_id(uemail)
         if user:
             self.redirect('/error')
         else:
             newUser=User(id=uemail,uName=username,email=uemail,pwd=upwd)
             token = security.generate_random_string(length=20)
             session = Session(id=token)
             session.userKey=newUser.put()
             session.put()
             self.response.set_cookie(key='token', value=token, path='/')
             self.redirect('/home')
Exemplo n.º 7
0
    def post(self):
        uemail=self.request.get('email')
        upwd=self.request.get('pwd')
        if uemail=='' or upwd=='':
            self.redirect('/error')

        else:
            user = ndb.Key('User',uemail).get()
            if user and user.pwd==upwd:
                token = security.generate_random_string(length=20)
                session = Session(id=token)
                session.userKey=user.put()
                session.put()
                self.response.set_cookie(key='token', value=token, path='/')
                self.redirect("/home")

            else:
                self.redirect("/login")
Exemplo n.º 8
0
 def post(self):
     username = self.request.get("uname")
     uemail = self.request.get("email")
     upwd = self.request.get("pwd")
     if username == '' or uemail == '' or upwd == '':
         self.redirect('/error')
     else:
         user = User.get_by_id(uemail)
         if user:
             self.redirect('/error')
         else:
             newUser = User(id=uemail,
                            uName=username,
                            email=uemail,
                            pwd=upwd)
             token = security.generate_random_string(length=20)
             session = Session(id=token)
             session.userKey = newUser.put()
             session.put()
             self.response.set_cookie(key='token', value=token, path='/')
             self.redirect('/home')
Exemplo n.º 9
0
    def post(self):
        json_data = request.get_json(force=True)
        if not json_data:
            return {'message': 'No input data provided'}, 400
        # Validate and deserialize input
        data, errors = session_schema.load(json_data)
        if errors:
            return errors, 422
        session = Session(start=json_data['start'], end=json_data['end'])

        db.session.add(session)
        db.session.commit()

        result = session_schema.dump(session).data

        return {"status": 'success', 'data': result}, 201
Exemplo n.º 10
0
    def startSession(self, user):
        # Log the session being ended if the id is changing.
        if self.currentSession is not None and self.currentSession.getUser(
        ).getId() != user.getId():
            DatabaseManager.sessionEnded(self.currentSession)

        # Set the session.
        newSession = Session.startSession(user)
        self.currentSession = newSession
        self.notify(newSession)
        DatabaseManager.sessionStarted(newSession)

        # Start a thread to expire the session.
        sessionThread = SessionThread(self)
        sessionThread.daemon = True
        sessionThread.start()
Exemplo n.º 11
0
    def _do_work(self, submission):
        s = Session()
        r = Report(
            module=self.__ModuleName__,
            short="Short desc...",
            full="",
            submission=submission
        )
        s.add(r)
        #Do the actual work
        sql = """select sha1, md5, FileName, FileSize, ProductName, ProductVersion, Language, ApplicationType, o.OpSystemCode, OpSystemName, OpSystemVersion, o.MfgCode, MfgName
                from file f inner join Prod p on p.ProductCode=f.ProductCode inner join OS o on f.OpSystemCode=o.OpSystemCode inner join Mfg m on m.MfgCode=o.MfgCode
                where sha1=?;"""
        results = self.db.execute(sql, (submission.file.sha1.upper(),)).fetchall()

        if len(results) == 0:
            # Unknown in Db
            r.short = "Unknown File - sha1 : %s" % (submission.file.sha1)
        else:
            # Known in Hash Db
            r.short = "File known to be safe (%s match)" % (len(results))
            r.threat_level = 0
            for result in results:
                report_details = {
                    'FileName': result[2],
                    'FileSize': result[3],
                    'Product': {
                        'ProductName': result[4],
                        'ProductVersion': result[5],
                        'Language': result[6],
                        'ApplicationType': result[7],
                        'OS': {
                            'OpSystemCode': result[8],
                            'OpSystemName': result[9],
                            'OpSystemVersion': result[10],
                            'MfgCode': result[11],
                            'MfgName': result[12],
                        },
                    },
                }
                json = JSONEncoder().encode(report_details)
                section = ReportSection(
                    type='json',
                    value=json,
                    report=r
                )
                s.add(section)
        s.commit()
        #r._sa_instance_state.session.expunge(r)
        return r
Exemplo n.º 12
0
 def _do_work_wrapper(self, submission_id):
     s = Session()
     submission = s.query(Submission).filter(Submission.id==submission_id).one()
     try:
         r = self._do_work(submission)
         s.expunge(r)
         self.result_queue.put(r)
     except Exception as e:
         logging.error("Got exception : %s"%e)
         r = Report(
             module=self.__ModuleName__,
             short="Got an exception in module : %s"%e,
             full="",
             submission=submission
         )
         s.add(r)
         s.expunge(r)
         self.result_queue.put(r)
Exemplo n.º 13
0
 def _do_work(self, submission):
     # Do the actual work
     e = EntropyTool(submission.file.path)
     (entropy, mean, stdv, max_dev) = e.analyze()
     out = os.path.join(self.module_config["output_dir"], "%s.png" % submission.file.sha256)
     e.writeimg(out)
     mapout = os.path.join(self.module_config["output_dir"], "%s_map.png" % submission.file.sha256)
     MapFile().writeimg(submission.file.path, mapout)
     r1 = {"path": out.replace("\\", "/"), "comment": "Entropy of the file"}
     r2 = {"path": mapout.replace("\\", "/"), "comment": "Mapping of the file"}
     json1 = JSONEncoder().encode(r1)
     json2 = JSONEncoder().encode(r2)
     r = Report(module=self.__ModuleName__, short="%s" % e.FileTypeText(), full="", submission=submission)
     Session.add(r)
     section1 = ReportSection(type="img", value=json1, report=r)
     Session.add(section1)
     section2 = ReportSection(type="img", value=json2, report=r)
     Session.add(section2)
     Session.commit()
     return r
Exemplo n.º 14
0
 def _do_work(self, submission):
     #Do the actual work
     report = self.vt.get(submission.file.sha256)
     s = Session()
     r = Report(
         module=self.__ModuleName__,
         short="Short desc...",
         full="",
         submission=submission
     )
     s.add(r)
     new_vt_submission = False
     if report is None:
         # Unknown in VT
         r.short = "Unknown on VT"
         if self.module_config['submit_unknown']:
             report = self.vt.scan(submission.file.path, reanalyze=True)
             report.join()
             new_vt_submission = True
     try:
         assert report.done is True
         # Known in VT
         r.short = "Detection rate : %s/%s - %s" % (report.positives, report.total, report.verbose_msg)
         if new_vt_submission:
             r.short += " (First submission in VT)"
         if report.positives == 0:
             r.threat_level = 0
         elif report.positives > 5:
             r.threat_level = 100
         report_details = report._report
         json = JSONEncoder().encode(report_details)
         section = ReportSection(
             type='json',
             value=json,
             report=r
         )
         s.add(section)
     except Exception as e:
         logging.error("Could not get report from vt : %s"%e)
     s.commit()
     #r._sa_instance_state.session.expunge(r)
     return r
Exemplo n.º 15
0
    def _do_work(self, submission):
        a = AnalyzePDF(submission.file.path, toolpath=self.module_config['tool_path'])
        sev, comment = a.analyze() #  (sev (0-5+), "comment")
        r = Report(
            module=self.__ModuleName__,
            short="%s (%s)" % (sev, comment),
            full="",
            submission=submission
        )
        if sev >= 5:
            r.threat_level = 100
        elif sev >=2:
            r.threat_level = 50
        else:
            r.threat_level = 0
        Session.add(r)


        section = ReportSection(
            type='text',
            value=a.anomalies_string,
            report=r
        )
        Session.add(section)

        section = ReportSection(
            type='text',
            value=a.pdfid_str,
            report=r
        )

        Session.add(section)

        Session.commit()
        #r._sa_instance_state.session.expunge(r)
        return r
Exemplo n.º 16
0
 def _do_work(self, submission):
     # Do the actual work
     metadata = self.exif_tool.get_metadata(submission.file.path)
     metadata_hierarchy = {}
     for key, value in metadata.iteritems():
         parent = metadata_hierarchy
         subkeys = key.split(":")
         for i in range(len(subkeys) - 1):
             current = subkeys[i]
             if current not in parent:
                 parent[current] = {}
             parent = parent[current]
         current = subkeys[-1]
         parent[current] = value
     json = JSONEncoder().encode(metadata_hierarchy)
     s = Session()
     r = Report(module=self.__ModuleName__, short="", full="", submission=submission)
     s.add(r)
     section = ReportSection(type="json", value=json, report=r)
     s.add(section)
     s.commit()
     # r._sa_instance_state.session.expunge(r)
     return r
Exemplo n.º 17
0
 def __init__(self):
     self.session = Session()
	def test_constructor(self):
		Session.Session(self.testUser,50)
	def test_getStartTime(self):
		CuT = Session.Session(self.testUser,50)
		self.assertEqual(CuT.getStartTime(),50,"Start time is incorrect.")
	def test_getEndTime(self):
		CuT = Session.Session(self.testUser,50)
		self.assertEqual(CuT.getEndTime(),70,"End time is incorrect.")
	def test_startSession(self):
		CuT = Session.startSession(self.testUser)
		self.assertEqual(CuT.getUser(),self.testUser,"User is incorrect.")
		self.assertNotEqual(CuT.getStartTime(),0,"Start time is incorrect.")
		self.assertAlmostEqual(CuT.getEndTime() - CuT.getStartTime(),20,"Delta time is incorrect.",0.1)