def notifyEndUser(self, context): print 'Sending push notification using Firebase Cloud Messaging' appConfiguration = context.getAppConfiguration() encryptionService = context.getEncryptionService() clientId = appConfiguration.getBackchannelClientId() redirectUri = appConfiguration.getBackchannelRedirectUri() url = appConfiguration.getCibaEndUserNotificationConfig().getNotificationUrl() key = encryptionService.decrypt(appConfiguration.getCibaEndUserNotificationConfig().getNotificationKey(), True) to = context.getDeviceRegistrationToken() title = "oxAuth Authentication Request" body = "Client Initiated Backchannel Authentication (CIBA)" authorizationRequestUri = RedirectUri(appConfiguration.getAuthorizationEndpoint()) authorizationRequestUri.addResponseParameter("client_id", clientId) authorizationRequestUri.addResponseParameter("response_type", "id_token") authorizationRequestUri.addResponseParameter("scope", context.getScope()) authorizationRequestUri.addResponseParameter("acr_values", context.getAcrValues()) authorizationRequestUri.addResponseParameter("redirect_uri", redirectUri) authorizationRequestUri.addResponseParameter("state", UUID.randomUUID().toString()) authorizationRequestUri.addResponseParameter("nonce", UUID.randomUUID().toString()) authorizationRequestUri.addResponseParameter("prompt", "consent") authorizationRequestUri.addResponseParameter("auth_req_id", context.getAuthReqId()) clickAction = authorizationRequestUri.toString() firebaseCloudMessagingRequest = FirebaseCloudMessagingRequest(key, to, title, body, clickAction) firebaseCloudMessagingClient = FirebaseCloudMessagingClient(url) firebaseCloudMessagingClient.setRequest(firebaseCloudMessagingRequest) firebaseCloudMessagingResponse = firebaseCloudMessagingClient.exec() responseStatus = firebaseCloudMessagingResponse.getStatus() print "CIBA: firebase cloud messaging result status " + str(responseStatus) return (responseStatus >= 200 and responseStatus < 300 )
def prepareForStep(self, configurationAttributes, requestParameters, step): print "Person Authentication. prepare for step... %s" % step jwkSet = JWKSet.load( URL(self.tpp_jwks_url)); signedRequest = ServerUtil.getFirstValue(requestParameters, "request") for key in jwkSet.getKeys() : result = self.isSignatureValid(signedRequest, key) if (result == True): signedJWT = SignedJWT.parse(signedRequest) claims = JSONObject(signedJWT.getJWTClaimsSet().getClaims().get("claims")) print "Person Authentication. claims : %s " % claims.toString() id_token = claims.get("id_token"); openbanking_intent_id = id_token.getJSONObject("openbanking_intent_id").getString("value") print "Person Authentication. openbanking_intent_id %s " % openbanking_intent_id redirectURL = self.redirect_url+"&state="+UUID.randomUUID().toString()+"&intent_id="+openbanking_intent_id identity = CdiUtil.bean(Identity) identity.setWorkingParameter("openbanking_intent_id",openbanking_intent_id) print "OpenBanking. Redirecting to ... %s " % redirectURL facesService = CdiUtil.bean(FacesService) facesService.redirectToExternalURL(redirectURL) return True print "Person Authentication. Call to Jans-auth server's /authorize endpoint should contain openbanking_intent_id as an encoded JWT" return False
def addBackupFilesToDataSource(self, dataSource, modDir): progressUpdater = ProgressUpdater() newDataSources = [] dirList = [] dirList.append(modDir) fileManager = Case.getCurrentCase().getServices().getFileManager() skCase = Case.getCurrentCase() deviceId = UUID.randomUUID() skCase.notifyAddingDataSource(deviceId) # Add data source with files newDataSource = fileManager.addLocalFilesDataSource( str(deviceId), "Itunes Backup", "", dirList, progressUpdater) newDataSources.append(newDataSource.getRootDirectory()) # Get the files that were added filesAdded = progressUpdater.getFiles() #self.log(Level.INFO, "Fire Module1: ==> " + str(files_added)) for fileAdded in filesAdded: skCase.notifyDataSourceAdded(fileAdded, deviceId)
def getUduid(client): OPTION_UD_UNIQUE_ID = "UD_UNIQUE_ID" try: uduid = None try: clientOptions = client.getOptionsMap() uduid = clientOptions.get(OPTION_UD_UNIQUE_ID) logger.debug("Get uduid from client:", uduid) except: logger.debug("Can't get uduid from client") pass if not uduid: from java.util import UUID uduid = UUID.randomUUID() logger.debug("Generated uduid:", uduid) from java.util import HashMap options = HashMap() options.put(OPTION_UD_UNIQUE_ID, str(uduid)) client.setOptionsMap(options) clientOptions = client.getOptionsMap() #Get the value again to make sure the new value was set to client uduid = clientOptions.get(OPTION_UD_UNIQUE_ID) logger.debug("Final value of uduid:", uduid) return uduid except: return None
def set_uid_prefix(rule, prefix=None): if prefix is None: prefix = type(rule).__name__ uid_field = type(SmarthomeRule).getClass(SmarthomeRule).getDeclaredField( SmarthomeRule, "uid") uid_field.setAccessible(True) uid_field.set(rule, "{}-{}".format(prefix, str(UUID.randomUUID())))
def _trace_msg_id(self): uuid = UUID.randomUUID() uuid_str = uuid.toString() # print("generate a new uuid %s" % uuid_str) # return str(grinder.threadNumber) + "-" + uuid_str.replace('-','') # return str(time.time()).zfill(20) # return str(random.getrandbits(64)).zfill(20) return str(random.random()).zfill(20)
def _trace_msg_id(self): uuid = UUID.randomUUID() uuid_str = uuid.toString() # print("generate a new uuid %s" % uuid_str) #return str(grinder.threadNumber) + "-" + uuid_str.replace('-','') #return str(time.time()).zfill(20) #return str(random.getrandbits(64)).zfill(20) return str(random.random()).zfill(20)
def __findWWFMessagesInDB(self, wwfDb, dataSource): if not wwfDb: return current_case = Case.getCurrentCaseThrows() # Create a helper to parse the DB wwfDbHelper = CommunicationArtifactsHelper( current_case.getSleuthkitCase(), self._PARSER_NAME, wwfDb.getDBFile(), wwfAccountType) uuid = UUID.randomUUID().toString() resultSet = None try: resultSet = wwfDb.runQuery( "SELECT message, strftime('%s' ,created_at) as datetime, user_id, game_id FROM chat_messages ORDER BY game_id DESC, created_at DESC;" ) while resultSet.next(): message = resultSet.getString("message") # WWF Message created_at = resultSet.getLong("datetime") user_id = resultSet.getString( "user_id" ) # the ID of the user who sent/received the message. game_id = resultSet.getString( "game_id" ) # ID of the game which the the message was sent. thread_id = "{0}-{1}".format(uuid, user_id) messageArtifact = wwfDbHelper.addMessage( self._MESSAGE_TYPE, CommunicationDirection.UNKNOWN, user_id, # fromId None, # toId created_at, MessageReadStatus.UNKNOWN, "", # subject message, thread_id) except SQLException as ex: self._logger.log(Level.WARNING, "Error processing query result for WWF messages", ex) self._logger.log(Level.WARNING, traceback.format_exc()) except TskCoreException as ex: self._logger.log(Level.SEVERE, "Failed to add WWF message artifacts.", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) except BlackboardException as ex: self._logger.log(Level.WARNING, "Failed to post artifacts.", ex) self._logger.log(Level.WARNING, traceback.format_exc()) except NoCurrentCaseException as ex: self._logger.log(Level.WARNING, "No case currently open.", ex) self._logger.log(Level.WARNING, traceback.format_exc()) finally: wwfDb.close()
def generateId(self, appId, idType, idPrefix, configurationAttributes): print "Id generator. Generate Id" print "Id generator. Generate Id. AppId: '", appId, "', IdType: '", idType, "', IdPrefix: '", idPrefix, "'" if StringHelper.equalsIgnoreCase(idType, "test"): id = UUID.randomUUID().toString() print "Id generator. New test id: " + id return id return "invalid"
def workOnIP(Framework, ip, ports): OPTION_UD_UNIQUE_ID = "UD_UNIQUE_ID" us = UDAStatus(ip) us.alive = True alivePort = None logger.debug("IP %s alive:%s" % (ip, us.alive)) if us.alive: for port in ports: us.portAlive = detectPortAvailable(ip, port) if us.portAlive: alivePort = port break logger.debug("Port alive %s on IP:Port %s:%s" % (us.portAlive, us.ip, str(alivePort))) #set computerName by ping -a us.computerName = detectHostnameWithPing(ip) if us.portAlive: client = detectUDAAvailable(Framework, ip) if client: us.udaAlive = True logger.debug("UDA alive %s on IP %s" % (us.udaAlive, us.ip)) try: us.isDDMI = detectDDMIAgent(Framework, client, us) logger.debug("UDA is DDMI %s on IP %s" % (us.isDDMI, us.ip)) if not us.isDDMI: us.isNative = True #detectUDANative(Framework, client, us) logger.debug("UDA is native %s on IP %s" % (us.isNative, us.ip)) us.isFIPSEnabled = detectFIPSMode(client) if isDupUDUniqueId(us.UDUniqueId): logger.debug("old uuid ", us.UDUniqueId) uduid = UUID.randomUUID() logger.debug("generate new uuid ", uduid) options = HashMap() options.put(OPTION_UD_UNIQUE_ID, str(uduid)) client.setOptionsMap(options) clientOptions = client.getOptionsMap() uduid = clientOptions.get(OPTION_UD_UNIQUE_ID) logger.debug("get new uuid ", uduid) us.UDUniqueId = uduid except: msg = logger.prepareJythonStackTrace('') errormessages.resolveAndReport( msg, ClientsConsts.ICMP_PROTOCOL_NAME, Framework) pass finally: try: client.close() except: pass return us
def generateId(cls, appId, idType, idPrefix, configurationAttributes): print("Id generator. Generate Id") print("Id generator. Generate Id. AppId: '", appId, "', IdType: '", idType, "', IdPrefix: '", idPrefix, "'") if StringHelper.equalsIgnoreCase(idType, "test"): newId = UUID.randomUUID().toString() print("Id generator. New test id: " + newId) return newId return "invalid"
def uploadFile(): fileId = UUID.randomUUID() body = "foobar test" headers = () putUrl = "%s/v1/file/%s" % (url, fileId) grinder.statistics.delayReports = 1 putWrap = tests["/v1/file"].wrap(HTTPRequest()) result = putWrap.PUT(putUrl, body, headers) if(result.statusCode !=200) : grinder.statistics.forLastTest.setSuccess(0)
def uploadFile(): fileId = UUID.randomUUID() body = "foobar test" headers = () putUrl = "%s/v1/file/%s" % (url, fileId) grinder.statistics.delayReports = 1 putWrap = tests["/v1/file"].wrap(HTTPRequest()) result = putWrap.PUT(putUrl, body, headers) if (result.statusCode != 200): grinder.statistics.forLastTest.setSuccess(0)
def workOnIP(Framework, ip, ports): OPTION_UD_UNIQUE_ID = "UD_UNIQUE_ID" us = UDAStatus(ip) us.alive = True alivePort = None logger.debug("IP %s alive:%s" % (ip, us.alive)) if us.alive: for port in ports: us.portAlive = detectPortAvailable(ip, port) if us.portAlive: alivePort = port break logger.debug("Port alive %s on IP:Port %s:%s" % (us.portAlive, us.ip, str(alivePort) )) #set computerName by ping -a us.computerName = detectHostnameWithPing(ip) if us.portAlive: client = detectUDAAvailable(Framework, ip) if client: us.udaAlive = True logger.debug("UDA alive %s on IP %s" % (us.udaAlive, us.ip)) try: us.isDDMI = detectDDMIAgent(Framework, client, us) logger.debug("UDA is DDMI %s on IP %s" % (us.isDDMI, us.ip)) if not us.isDDMI: us.isNative = True #detectUDANative(Framework, client, us) logger.debug("UDA is native %s on IP %s" % (us.isNative, us.ip)) us.isFIPSEnabled = detectFIPSMode(client) if isDupUDUniqueId(us.UDUniqueId): logger.debug("old uuid ", us.UDUniqueId) uduid = UUID.randomUUID() logger.debug("generate new uuid ", uduid) options = HashMap() options.put(OPTION_UD_UNIQUE_ID, str(uduid)) client.setOptionsMap(options) clientOptions = client.getOptionsMap() uduid = clientOptions.get(OPTION_UD_UNIQUE_ID) logger.debug("get new uuid ", uduid) us.UDUniqueId = uduid except: msg = logger.prepareJythonStackTrace('') errormessages.resolveAndReport(msg, ClientsConsts.ICMP_PROTOCOL_NAME, Framework) pass finally: try: client.close() except: pass return us
def addGraphic(self, geometry): #print "addGraphic:", geometry #print " to: ", self.store values = self.getUIValues() if self.store == None: return if not self.store.isEditing(): self.store.edit() f = self.store.createNewFeature() for key, value in values.iteritems(): f.set(key, value) f.set('ID', UUID.randomUUID().toString()) f.set('GEOMETRY', geometry) self.store.insert(f)
def set_uid_prefix(rule, prefix=None): """ This function changes the UID of a rule, with the option to include a specified text. .. warning:: This function needs some attention in order to work with the Automation API changes included in S1319. Args: rule (Rule): the rule to modify prefix (str): (optional) the text to include in the UID """ if prefix is None: prefix = type(rule).__name__ uid_field = type(SmarthomeRule).getClass(SmarthomeRule).getDeclaredField(SmarthomeRule, "uid") uid_field.setAccessible(True) uid_field.set(rule, "{}-{}".format(prefix, str(UUID.randomUUID())))
def manage_left(self): # 得到当前协作组. if self.get_current_group() == None: return ActionResult.ERROR self.get_group_member() #课题研究组的分类 uuid=self.group_svc.getGroupCateUuid(self.group) if uuid==CategoryService.GROUP_CATEGORY_GUID_KTYJ : #课题 request.setAttribute("isKtGroup", "1") elif uuid==CategoryService.GROUP_CATEGORY_GUID_JTBK : #备课 request.setAttribute("isKtGroup", "2") else: request.setAttribute("isKtGroup", "0") request.setAttribute("guid", UUID.randomUUID()) return "/WEB-INF/ftl/group/group_manage_left.ftl"
def add_to_fileset(name, folder, device_id=UUID.randomUUID(), progress_updater=ProgressUpdater(), notify=True): fileManager = Case.getCurrentCase().getServices().getFileManager() skcase_data = Case.getCurrentCase() #skcase_data.notifyAddingDataSource(device_id) #progress_updater = ProgressUpdater() data_source = fileManager.addLocalFilesDataSource( device_id.toString(), name, "", folder, progress_updater) if notify: files_added = progress_updater.getFiles() for file_added in files_added: skcase_data.notifyDataSourceAdded(file_added, device_id) return data_source
def save_or_update(self): q_topic = self.params.safeGetStringParam("quesition_title") q_content = self.params.safeGetStringParam("quesition_content") if self.question == None: objectGuid = UUID.randomUUID() self.question = Question() self.question.setParentGuid(self.parentGuid) self.question.setObjectGuid(str(objectGuid)) self.question.setCreateDate(Date()) self.question.setAddIp(self.get_client_ip()) self.question.setCreateUserName(self.loginUser.trueName) self.question.setCreateUserId(self.loginUser.userId) self.question.setTopic(q_topic) self.question.setQuestionContent(q_content) self.questionAnswerService.saveOrUpdate(self.question) response.sendRedirect(self.redUrl) return return "/WEB-INF/mod/questionanswer/success.ftl"
def getEncodedJWTForToken(self, softwareStatementId, clientScopes, aud, kid,signingKeyFile): jws = JsonWebSignature() claims = JwtClaims() claims.setClaim("iss", softwareStatementId) claims.setClaim("sub", softwareStatementId) claims.setClaim("scope", clientScopes) claims.setClaim("aud", aud) claims.setClaim("jti", UUID.randomUUID()) unixTime = Instant.now().getEpochSecond() claims.setClaim("iat", unixTime) claims.setClaim("exp", unixTime + 1000) # 60000 one min jws.setPayload(claims.toJson()) # dont change the order jws.getHeaders().setObjectHeaderValue("typ", "JWT"); jws.setAlgorithmHeaderValue("RS256"); jws.getHeaders().setObjectHeaderValue("kid", kid); privateKey = self.getPrivateKey(signingKeyFile); jws.setKey(privateKey); jwsCompactSerialization = jws.getCompactSerialization(); return jwsCompactSerialization;
def test1 (): print "foobar test - Example Service URL:%s - UUID:%s" % (url, UUID.randomUUID())
from java.util import UUID from org.apache.hadoop.fs import Path print "Home dir is " + str(fs.homeDirectory) print "Work dir is " + str(fs.workingDirectory) print "/user exists " + str(fs.exists("/user")) name = UUID.randomUUID().toString() scriptName = "src/test/resources/test.properties" fs.copyFromLocalFile(scriptName, name) print Path(name).makeQualified(fs) # use the shell dir = "script-dir/" if not fsh.test(dir): fsh.mkdir(dir) fsh.cp(name, dir) fsh.chmodr(700, dir) print "File content is " + str(fsh.cat(dir + name)) print str(fsh.ls(dir)) fsh.rmr(dir) fs.getLength(name)
def process(self, dataSource, progressBar): self.log(Level.INFO, "Starting to process Hiberfil.sys and Crash Dumps") # we don't know how much work there is yet progressBar.switchToIndeterminate() # Get the temp directory and create the sub directory if self.hiber_flag: Mod_Dir = Case.getCurrentCase().getModulesOutputDirAbsPath() try: ModOut_Dir = os.path.join(Mod_Dir, "Volatility\\Memory-Image-hiberfil") self.log(Level.INFO, "Module Output Directory ===> " + ModOut_Dir) #dir_util.mkpath(ModOut_Dir) os.mkdir(Mod_Dir + "\\Volatility") os.mkdir(ModOut_Dir) except: self.log( Level.INFO, "***** Error Module Output Directory already exists " + ModOut_Dir) # Set the database to be read to the once created by the prefetch parser program skCase = Case.getCurrentCase().getSleuthkitCase() fileManager = Case.getCurrentCase().getServices().getFileManager() files = fileManager.findFiles(dataSource, "hiberfil.sys", "/") numFiles = len(files) self.log(Level.INFO, "Number of files to process ==> " + str(numFiles)) for file in files: self.log(Level.INFO, "File to process is ==> " + str(file)) self.log(Level.INFO, "File name to process is ==> " + file.getName()) tmp_Dir = Case.getCurrentCase().getTempDirectory() Hiber_File = os.path.join(tmp_Dir, file.getName()) ContentUtils.writeToFile(file, File(Hiber_File)) self.log(Level.INFO, "File name to process is ==> " + Hiber_File) # Create the directory to dump the hiberfil dump_file = os.path.join(ModOut_Dir, "Memory-Image-from-hiberfil.img") if self.Python_Program: self.log(Level.INFO, "Running program ==> " + self.Volatility_Executable + " imagecopy -f " + Hiber_File + " " + \ " -O " + dump_file) pipe = Popen([ "Python.exe", self.Volatility_Executable, "imagecopy", "-f", Hiber_File, "-O" + dump_file ], stdout=PIPE, stderr=PIPE) else: self.log(Level.INFO, "Running program ==> " + self.Volatility_Executable + " imagecopy -f " + Hiber_File + " " + \ " -O " + dump_file) pipe = Popen([ self.Volatility_Executable, "imagecopy", "-f", Hiber_File, "-O" + dump_file ], stdout=PIPE, stderr=PIPE) out_text = pipe.communicate()[0] self.log(Level.INFO, "Output from run is ==> " + out_text) # Add hiberfil memory image to a new local data source services = IngestServices.getInstance() progress_updater = ProgressUpdater() newDataSources = [] dump_file = os.path.join(ModOut_Dir, "Memory-Image-from-hiberfil.img") dir_list = [] dir_list.append(dump_file) # skCase = Case.getCurrentCase().getSleuthkitCase(); fileManager_2 = Case.getCurrentCase().getServices( ).getFileManager() skcase_data = Case.getCurrentCase() # Get a Unique device id using uuid device_id = UUID.randomUUID() self.log(Level.INFO, "device id: ==> " + str(device_id)) skcase_data.notifyAddingDataSource(device_id) # Add data source with files newDataSource = fileManager_2.addLocalFilesDataSource( str(device_id), "Hiberfile Memory Image", "", dir_list, progress_updater) newDataSources.append(newDataSource.getRootDirectory()) # Get the files that were added files_added = progress_updater.getFiles() #self.log(Level.INFO, "Fire Module1: ==> " + str(files_added)) for file_added in files_added: skcase_data.notifyDataSourceAdded(file_added, device_id) self.log(Level.INFO, "Fire Module1: ==> " + str(file_added)) # After all databases, post a message to the ingest messages in box. message = IngestMessage.createMessage( IngestMessage.MessageType.DATA, "HiberFil_Crash", " Hiberfil/Crash Dumps have been extracted fro Image. ") IngestServices.getInstance().postMessage(message) return IngestModule.ProcessResult.OK
def __findTextsInDB(self, databasePath, abstractFile, dataSource): if not databasePath: return bbartifacts = list() try: Class.forName("org.sqlite.JDBC") # load JDBC driver connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath) statement = connection.createStatement() except (ClassNotFoundException) as ex: self._logger.log(Level.SEVERE, "Error loading JDBC driver", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) return except (SQLException) as ex: # Error opening database. return # Create a 'Device' account using the data source device id datasourceObjId = dataSource.getDataSource().getId() ds = Case.getCurrentCase().getSleuthkitCase().getDataSource( datasourceObjId) deviceID = ds.getDeviceId() deviceAccountInstance = Case.getCurrentCase().getSleuthkitCase( ).getCommunicationsManager().createAccountFileInstance( Account.Type.DEVICE, deviceID, general.MODULE_NAME, abstractFile) uuid = UUID.randomUUID().toString() resultSet = None try: resultSet = statement.executeQuery( "SELECT address, date, read, type, subject, body, thread_id FROM sms;" ) while resultSet.next(): address = resultSet.getString( "address") # may be phone number, or other addresses date = Long.valueOf(resultSet.getString("date")) / 1000 read = resultSet.getInt("read") # may be unread = 0, read = 1 subject = resultSet.getString("subject") # message subject body = resultSet.getString("body") # message body thread_id = "{0}-{1}".format(uuid, resultSet.getInt("thread_id")) attributes = ArrayList() artifact = abstractFile.newArtifact( BlackboardArtifact.ARTIFACT_TYPE.TSK_MESSAGE) #create Message artifact and then add attributes from result set. if resultSet.getString("type") == "1": attributes.add( BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DIRECTION, general.MODULE_NAME, "Incoming")) attributes.add( BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE. TSK_PHONE_NUMBER_FROM, general.MODULE_NAME, address)) else: attributes.add( BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DIRECTION, general.MODULE_NAME, "Outgoing")) attributes.add( BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE. TSK_PHONE_NUMBER_TO, general.MODULE_NAME, address)) attributes.add( BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME, general.MODULE_NAME, date)) attributes.add( BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE.TSK_READ_STATUS, general.MODULE_NAME, Integer(read))) attributes.add( BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE.TSK_SUBJECT, general.MODULE_NAME, subject)) attributes.add( BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE.TSK_TEXT, general.MODULE_NAME, body)) attributes.add( BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE.TSK_MESSAGE_TYPE, general.MODULE_NAME, "SMS Message")) attributes.add( BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE.TSK_THREAD_ID, general.MODULE_NAME, thread_id)) artifact.addAttributes(attributes) # Create an account msgAccountInstance = Case.getCurrentCase().getSleuthkitCase( ).getCommunicationsManager().createAccountFileInstance( Account.Type.PHONE, address, general.MODULE_NAME, abstractFile) # create relationship between accounts Case.getCurrentCase().getSleuthkitCase( ).getCommunicationsManager().addRelationships( deviceAccountInstance, [msgAccountInstance], artifact, Relationship.Type.MESSAGE, date) bbartifacts.append(artifact) except SQLException as ex: # Unable to execute text messages SQL query against database. pass except Exception as ex: self._logger.log(Level.SEVERE, "Error parsing text messages to blackboard", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) finally: if bbartifacts: Case.getCurrentCase().getSleuthkitCase().getBlackboard( ).postArtifacts(bbartifacts, general.MODULE_NAME) try: if resultSet is not None: resultSet.close() statement.close() connection.close() except Exception as ex: # Error closing database. pass
# found in the database def create_actor(name): actor = Actor() actor.refId = UUID.randomUUID().toString() actor.name = name olca.insertActor(actor) # Read the csv file and generate the processes with open(csvFile, 'rb') as f: data = csv.DictReader(f) for row in data: log.info("create process {}", row['BridgeProcessName']) process = Process() process.documentation = ProcessDocumentation() process.refId = UUID.randomUUID().toString() process.processType = ProcessType.UNIT_PROCESS process.name = row['BridgeProcessName'] process.description = row['BridgeProcessDescription'] process.documentation.intendedApplication = row[ 'BridgeProcessIntendedApplication'] datasetOwner = row['BridgeProcessDatasetOwner'] if datasetOwner != '': owner = olca.getActor(datasetOwner) if owner is None: create_actor(datasetOwner) owner = olca.getActor(datasetOwner) process.documentation.dataSetOwner = owner dataDocumentor = row['BridgeProcessDataDocumentor'] if dataDocumentor != '': documentor = olca.getActor(dataDocumentor)
def process(self, dataSource, progressBar): self.log(Level.INFO, "Starting to process Hiberfil.sys and Crash Dumps") # we don't know how much work there is yet progressBar.switchToIndeterminate() # Get the temp directory and create the sub directory if self.hiber_flag: Mod_Dir = Case.getCurrentCase().getModulesOutputDirAbsPath() try: ModOut_Dir = os.path.join(Mod_Dir, "Volatility", "Memory-Image-hiberfil") self.log(Level.INFO, "Module Output Directory ===> " + ModOut_Dir) #dir_util.mkpath(ModOut_Dir) os.mkdir(os.path.join(Mod_Dir, "Volatility")) os.mkdir(ModOut_Dir) except: self.log(Level.INFO, "***** Error Module Output Directory already exists " + ModOut_Dir) # Set the database to be read to the once created by the prefetch parser program skCase = Case.getCurrentCase().getSleuthkitCase(); fileManager = Case.getCurrentCase().getServices().getFileManager() files = fileManager.findFiles(dataSource, "hiberfil.sys", "/") numFiles = len(files) self.log(Level.INFO, "Number of files to process ==> " + str(numFiles)) for file in files: self.log(Level.INFO, "File to process is ==> " + str(file)) self.log(Level.INFO, "File name to process is ==> " + file.getName()) tmp_Dir = Case.getCurrentCase().getTempDirectory() Hiber_File = os.path.join(tmp_Dir, file.getName()) ContentUtils.writeToFile(file, File(Hiber_File)) self.log(Level.INFO, "File name to process is ==> " + Hiber_File) # Create the directory to dump the hiberfil dump_file = os.path.join(ModOut_Dir, "Memory-Image-from-hiberfil.img") if self.Python_Program: self.log(Level.INFO, "Running program ==> " + self.Volatility_Executable + " imagecopy -f " + Hiber_File + " " + \ " -O " + dump_file) if PlatformUtil.isWindowsOS(): pipe = Popen(["Python.exe", self.Volatility_Executable, "imagecopy", "-f", Hiber_File, "-O" + dump_file], stdout=PIPE, stderr=PIPE) else: pipe = Popen(["python", self.Volatility_Executable, "imagecopy", "-f", Hiber_File, "-O" + dump_file], stdout=PIPE, stderr=PIPE) else: self.log(Level.INFO, "Running program ==> " + self.Volatility_Executable + " imagecopy -f " + Hiber_File + " " + \ " -O " + dump_file) pipe = Popen([self.Volatility_Executable, "imagecopy", "-f", Hiber_File, "-O" + dump_file], stdout=PIPE, stderr=PIPE) out_text = pipe.communicate()[0] self.log(Level.INFO, "Output from run is ==> " + out_text) # Add hiberfil memory image to a new local data source services = IngestServices.getInstance() progress_updater = ProgressUpdater() newDataSources = [] dump_file = os.path.join(ModOut_Dir, "Memory-Image-from-hiberfil.img") dir_list = [] dir_list.append(dump_file) # skCase = Case.getCurrentCase().getSleuthkitCase(); fileManager_2 = Case.getCurrentCase().getServices().getFileManager() skcase_data = Case.getCurrentCase() # Get a Unique device id using uuid device_id = UUID.randomUUID() self.log(Level.INFO, "device id: ==> " + str(device_id)) skcase_data.notifyAddingDataSource(device_id) # Add data source with files newDataSource = fileManager_2.addLocalFilesDataSource(str(device_id), "Hiberfile Memory Image", "", dir_list, progress_updater) newDataSources.append(newDataSource.getRootDirectory()) # Get the files that were added files_added = progress_updater.getFiles() #self.log(Level.INFO, "Fire Module1: ==> " + str(files_added)) for file_added in files_added: skcase_data.notifyDataSourceAdded(file_added, device_id) self.log(Level.INFO, "Fire Module1: ==> " + str(file_added)) # After all databases, post a message to the ingest messages in box. message = IngestMessage.createMessage(IngestMessage.MessageType.DATA, "HiberFil_Crash", " Hiberfil/Crash Dumps have been extracted fro Image. " ) IngestServices.getInstance().postMessage(message) return IngestModule.ProcessResult.OK
def getGUID(): return str(UUID.randomUUID())
def analyze(self, dataSource, fileManager, context): selfAccountId = None messageDbs = AppSQLiteDB.findAppDatabases(dataSource, "mmssms.db", True, self._PACKAGE_NAME) for messageDb in messageDbs: try: current_case = Case.getCurrentCaseThrows() if selfAccountId is not None: messageDbHelper = CommunicationArtifactsHelper( current_case.getSleuthkitCase(), self._PARSER_NAME, messageDb.getDBFile(), Account.Type.PHONE, Account.Type.IMO, selfAccountId) else: messageDbHelper = CommunicationArtifactsHelper( current_case.getSleuthkitCase(), self._PARSER_NAME, messageDb.getDBFile(), Account.Type.PHONE) uuid = UUID.randomUUID().toString() messagesResultSet = messageDb.runQuery( "SELECT address, date, read, type, subject, body, thread_id FROM sms;" ) if messagesResultSet is not None: while messagesResultSet.next(): direction = "" address = None fromId = None toId = None address = messagesResultSet.getString( "address" ) # may be phone number, or other addresses timeStamp = Long.valueOf( messagesResultSet.getString("date")) / 1000 read = messagesResultSet.getInt( "read") # may be unread = 0, read = 1 subject = messagesResultSet.getString( "subject") # message subject msgBody = messagesResultSet.getString( "body") # message body thread_id = "{0}-{1}".format( uuid, messagesResultSet.getInt("thread_id")) if messagesResultSet.getString("type") == "1": direction = CommunicationDirection.INCOMING fromId = address else: direction = CommunicationDirection.OUTGOING toId = address message_read = messagesResultSet.getInt( "read") # may be unread = 0, read = 1 if (message_read == 1): msgReadStatus = MessageReadStatus.READ elif (message_read == 0): msgReadStatus = MessageReadStatus.UNREAD else: msgReadStatus = MessageReadStatus.UNKNOWN ## add a message if address is not None: messageArtifact = messageDbHelper.addMessage( self._MESSAGE_TYPE, direction, fromId, toId, timeStamp, msgReadStatus, subject, # subject msgBody, thread_id) except SQLException as ex: self._logger.log( Level.WARNING, "Error processing query result for Android messages.", ex) self._logger.log(Level.WARNING, traceback.format_exc()) except TskCoreException as ex: self._logger.log(Level.SEVERE, "Failed to add Android message artifacts.", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) except BlackboardException as ex: self._logger.log(Level.WARNING, "Failed to post artifacts.", ex) self._logger.log(Level.WARNING, traceback.format_exc()) except NoCurrentCaseException as ex: self._logger.log(Level.WARNING, "No case currently open.", ex) self._logger.log(Level.WARNING, traceback.format_exc()) finally: messageDb.close()
def execute(self): channelId = self.params.safeGetIntParam("channelId") self.channel = self.channelPageService.getChannel(channelId) if self.channel == None: self.addActionError(u"无法加载频道。") return self.ERROR AdminType = self.GetAdminType(self.channel) if AdminType == "": self.addActionError(u"你无权管理频道。") return self.ERROR self.k = self.params.safeGetStringParam("k") self.f = self.params.safeGetStringParam("f") self.guid = self.params.safeGetStringParam("guid") self.cmd = self.params.safeGetStringParam("cmd") startDate = self.params.safeGetStringParam("startDate") endDate = self.params.safeGetStringParam("endDate") if request.getMethod() == "POST": if self.cmd == "export": qry = ChannelUserStatQuery( "cus.loginName, cus.userTrueName, cus.unitTitle, cus.articleCount, cus.resourceCount, cus.photoCount, cus.videoCount" ) qry.channelId = self.channel.channelId qry.statGuid = self.guid stat_list = qry.query_map(qry.count()) request.setAttribute("k", self.params.safeGetStringParam("k")) request.setAttribute("f", self.params.safeGetStringParam("f")) request.setAttribute("startDate", startDate) request.setAttribute("endDate", endDate) request.setAttribute("channel", self.channel) request.setAttribute("stat_list", stat_list) request.setCharacterEncoding("utf-8") response.reset() #response.setContentType("application/vnd.ms-excel") response.setHeader("Content-Type", "application/vnd.ms-excel; charset=GB2312") response.addHeader( "Content-Disposition", "attachment;" + CommonUtil.encodeContentDisposition( request, self.channel.title + ".xls")) return "/WEB-INF/ftl/channel/channel_user_excel.ftl" else: #清空上次的查询 #self.channelPageService.deleteChannelUserStat(self.guid) if startDate != "" and endDate != "": try: SimpleDateFormat("yyyy-MM-dd").parse(startDate) except: startDate = "" try: SimpleDateFormat("yyyy-MM-dd").parse(endDate) except: endDate = "" if endDate == "" or startDate == "": startDate = endDate = "" if self.f != "": if self.f == "0": #用户登录名 self.f = "loginName" elif self.f == "1": self.f = "trueName" elif self.f == "2": self.f = "unitTitle" else: self.f = "" #public void statUserData(int channelId, String statGuid, String keyWord, String filter, String startDate, String endDate) #先找满足条件的人 #qry = ChannelUserQuery("cu.userId, u.loginName, u.trueName, cu.unitId, cu.unitTitle") #qry.channelId = self.channel.channelId #qry.f = self.f #qry.k = self.k #user_list = qry.query_map(qry.count()) #if user_list != None and len(user_list) > 0: # for u in user_list: # #再查数据并添加到临时表 # articleCount = self.channelPageService.getChannelArticleCount(self.channel.channelId,int(u["userId"]),startDate,endDate) # resourceCount = self.channelPageService.getChannelResourceCount(self.channel.channelId,int(u["userId"]),startDate,endDate) # photoCount = self.channelPageService.getChannelPhotoCount(self.channel.channelId,int(u["userId"]),startDate,endDate) # videoCount = self.channelPageService.getChannelVideoCount(self.channel.channelId,int(u["userId"]),startDate,endDate) # channelUserStat = ChannelUserStat() # channelUserStat.channelId = self.channel.channelId # channelUserStat.statGuid = self.guid # channelUserStat.userId = int(u["userId"]) # channelUserStat.loginName = u["loginName"] # channelUserStat.userTrueName = u["trueName"] # channelUserStat.unitId = int(u["unitId"]) # channelUserStat.unitTitle = u["unitTitle"] # channelUserStat.articleCount = articleCount # channelUserStat.resourceCount = resourceCount # channelUserStat.photoCount = photoCount # channelUserStat.videoCount = videoCount # self.channelPageService.saveChannelUserStat(channelUserStat) s = "" e = "" if startDate != "" and endDate != "": s = startDate + " 00:00:00" e = endDate + " 23:59:59" self.channelPageService.statUserData(self.channel.channelId, self.guid, self.k, self.f, s, e) reUrl = "channel_user_stat.py?cmd=show&guid=" + self.guid + "&channelId=" + str( self.channel.channelId) + "&f=" + CommonUtil.urlUtf8Encode( self.params.safeGetStringParam("f") ) + "&k=" + CommonUtil.urlUtf8Encode( self.params.safeGetStringParam("k") ) + "&startDate=" + CommonUtil.urlUtf8Encode( startDate) + "&endDate=" + CommonUtil.urlUtf8Encode( endDate) response.sendRedirect(reUrl) else: if self.guid == "": self.guid = UUID.randomUUID().toString() request.setAttribute("k", self.params.safeGetStringParam("k")) request.setAttribute("f", self.params.safeGetStringParam("f")) request.setAttribute("startDate", startDate) request.setAttribute("endDate", endDate) request.setAttribute("channel", self.channel) request.setAttribute("guid", self.guid) if self.cmd == "show": qry = ChannelUserStatQuery( "cus.loginName, cus.userTrueName, cus.unitTitle, cus.articleCount, cus.resourceCount,cus.photoCount,cus.videoCount" ) qry.channelId = self.channel.channelId qry.statGuid = self.guid pager = self.createPager() pager.totalRows = qry.count() stat_list = qry.query_map(pager) request.setAttribute("stat_list", stat_list) request.setAttribute("pager", pager) return "/WEB-INF/ftl/channel/channel_user_stat.ftl"
try: from net.minecraft.client.util import Session except ImportError: from net.minecraft import class_320 as Session #from com.mojang.authlib import Agent Agent = Class.forName("com.mojang.authlib.Agent") #from com.mojang.authlib.yggdrasil import YggdrasilAuthenticationService YggAuthService = Class.forName("com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService") #from com.mojang.util import UUIDTypeAdapter UUIDTypeAdapter = Class.forName("com.mojang.util.UUIDTypeAdapter") MCAgent = Agent.MINECRAFT uuid = UUID.randomUUID().toString() yas = YggAuthService(networkProxy, uuid) yua = yas.createUserAuthentication(MCAgent) minecraftSessionService = yas.createMinecraftSessionService() username = "" password = "" loginScreen = hud.createScreen("Login", False) def setSession(s): sessionField = reflection.getDeclaredField(minecraft.getClass(), "session", "field_1726") sessionField.setAccessible(True) sessionField.set(minecraft, s)
def process(self, dataSource, progressBar): self.log(Level.INFO, "Starting to process, Just before call to parse_safari_history") # we don't know how much work there is yet progressBar.switchToIndeterminate() skCase = Case.getCurrentCase().getSleuthkitCase(); self.log(Level.INFO, "Starting Processing of Image") image_names = dataSource.getPaths() self.log(Level.INFO, "Image names ==> " + str(image_names[0])) image_name = str(image_names[0]) # Create VSS directory in ModuleOutput directory, if it exists then continue on processing Mod_Dir = Case.getCurrentCase().getModulesOutputDirAbsPath() Temp_Dir = Case.getCurrentCase().getTempDirectory() self.log(Level.INFO, "create Directory " + Temp_Dir) vss_output = os.path.join(Mod_Dir, "vss") try: os.mkdir(vss_output) except: self.log(Level.INFO, "Vss already exists " + Temp_Dir) lclDbPath = os.path.join(vss_output, "vss_extract_info.db3") vss_error_log = os.path.join(vss_output, "bad_files.log") # Run the Processing/Extraction process self.log(Level.INFO, "Running prog ==> " + self.path_to_exe_vss + " " + image_name + " " + lclDbPath + " " + vss_output + " " + vss_error_log) pipe = Popen([self.path_to_exe_vss, image_name, lclDbPath, vss_output, vss_error_log], stdout=PIPE, stderr=PIPE) out_text = pipe.communicate()[0] self.log(Level.INFO, "Output from run is ==> " + out_text) try: attID_vs_fn = skCase.addArtifactAttributeType("TSK_VSS_MFT_NUMBER", BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.STRING, "MFT Number") except: self.log(Level.INFO, "Attributes Creation Error, MFT Number. ==> ") try: attID_vs_ct = skCase.addArtifactAttributeType("TSK_VSS_DATETIME_CHANGED", BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.DATETIME, "Recovered Record") except: self.log(Level.INFO, "Attributes Creation Error, changed time. ==> ") try: attID_vs_sz = skCase.addArtifactAttributeType("TSK_VSS_FILE_SIZE", BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.LONG, "File Size") except: self.log(Level.INFO, "Attributes Creation Error, Computer Name. ==> ") try: Class.forName("org.sqlite.JDBC").newInstance() dbConn = DriverManager.getConnection("jdbc:sqlite:%s" % lclDbPath) except SQLException as e: self.log(Level.INFO, "Could not open database file (not SQLite) " +" (" + e.getMessage() + ")") return IngestModule.ProcessResult.OK try: stmt = dbConn.createStatement() SQL_Statement = "select ' - '||vss_identifier||' - '||DATETIME((SUBSTR(vss_create_dttm,1,11)-11644473600),'UNIXEPOCH') 'VOL_NAME', " + \ " vss_num, volume_id, vss_identifier from vss_info;" self.log(Level.INFO, "SQL Statement " + SQL_Statement + " <<=====") resultSet = stmt.executeQuery(SQL_Statement) except SQLException as e: self.log(Level.INFO, "Error querying database for EventLogs table (" + e.getMessage() + ")") return IngestModule.ProcessResult.OK # Cycle through each row and create artifacts while resultSet.next(): dir_list = [] vss_identifier = resultSet.getString("vss_identifier") vss_num = int(resultSet.getString("vss_num")) - 1 dir_list.append(vss_output + "\\vss" + str(vss_num)) services = IngestServices.getInstance() progress_updater = ProgressUpdater() newDataSources = [] # skCase = Case.getCurrentCase().getSleuthkitCase(); fileManager = Case.getCurrentCase().getServices().getFileManager() skcase_data = Case.getCurrentCase() # Get a Unique device id using uuid device_id = UUID.randomUUID() self.log(Level.INFO, "device id: ==> " + str(device_id)) skcase_data.notifyAddingDataSource(device_id) # Add data source with files newDataSource = fileManager.addLocalFilesDataSource(str(device_id), "vss" + str(vss_num) + resultSet.getString("VOL_NAME"), "", dir_list, progress_updater) newDataSources.append(newDataSource.getRootDirectory()) # Get the files that were added files_added = progress_updater.getFiles() #self.log(Level.INFO, "Fire Module1: ==> " + str(files_added)) for file_added in files_added: skcase_data.notifyDataSourceAdded(file_added, device_id) #self.log(Level.INFO, "Fire Module1: ==> " + str(file_added)) #skcase.notifyDataSourceAdded(device_id) skCse = Case.getCurrentCase().getSleuthkitCase() vss_fileManager = Case.getCurrentCase().getServices().getFileManager() vss_files = fileManager.findFiles(dataSource, "%" + vss_identifier + "%", "System Volume Information") vss_numFiles = len(vss_files) #self.log(Level.INFO, "Number of VSS FIles is ==> " + str(vss_numFiles) + " <<= FIle Name is ++> " + str(vss_files)) for vs in vss_files: if vs.getName() in "-slack": pass try: self.log(Level.INFO, "Begin Create New Artifacts") artID_vss = skCase.addArtifactType( "TSK_VS_VOLUME_" + str(vss_num), "vss" + str(vss_num) + resultSet.getString("VOL_NAME") + " Files") except: self.log(Level.INFO, "Artifacts Creation Error, some artifacts may not exist now. ==> ") artID_vss = skCase.getArtifactTypeID("TSK_VS_VOLUME_" + str(vss_num)) artID_vss = skCase.getArtifactTypeID("TSK_VS_VOLUME_" + str(vss_num)) artID_vss_evt = skCase.getArtifactType("TSK_VS_VOLUME_" + str(vss_num)) attID_vs_fn = skCase.getAttributeType("TSK_VSS_MFT_NUMBER") attID_vs_ct = skCase.getAttributeType("TSK_VSS_DATETIME_CHANGED") attID_vs_sz = skCase.getAttributeType("TSK_VSS_FILE_SIZE") attID_vs_nm = skCase.getAttributeType("TSK_NAME") attID_vs_pa = skCase.getAttributeType("TSK_PATH") attID_vs_md = skCase.getAttributeType("TSK_DATETIME_MODIFIED") attID_vs_ad = skCase.getAttributeType("TSK_DATETIME_ACCESSED") attID_vs_cr = skCase.getAttributeType("TSK_DATETIME_CREATED") for vs_file in vss_files: if "-slack" in vs_file.getName(): pass else: self.log(Level.INFO, "VSS FIles is ==> " + str(vs_file)) try: stmt_1 = dbConn.createStatement() SQL_Statement_1 = "select file_name, inode, directory, ctime, mtime, atime, crtime, size " + \ " from vss1_diff where lower(f_type) <> 'dir';" self.log(Level.INFO, "SQL Statement " + SQL_Statement_1 + " <<=====") resultSet_1 = stmt_1.executeQuery(SQL_Statement_1) except SQLException as e: self.log(Level.INFO, "Error querying database for vss diff tables (" + e.getMessage() + ")") return IngestModule.ProcessResult.OK # Cycle through each row and create artifacts while resultSet_1.next(): try: File_Name = resultSet_1.getString("file_name") Path_Name = resultSet_1.getString("directory") MFT_Number = resultSet_1.getString("inode") Ctime = resultSet_1.getInt("ctime") Mtime = resultSet_1.getInt("mtime") Atime = resultSet_1.getInt("atime") Crtime = resultSet_1.getInt("crtime") File_Size = resultSet_1.getInt("size") except SQLException as e: self.log(Level.INFO, "Error getting values from vss diff table (" + e.getMessage() + ")") # Make an artifact on the blackboard, TSK_PROG_RUN and give it attributes for each of the fields # Make artifact for TSK_EVTX_LOGS art = vs_file.newArtifact(artID_vss) art.addAttributes(((BlackboardAttribute(attID_vs_nm, VSSIngesttModuleFactory.moduleName, File_Name)), \ (BlackboardAttribute(attID_vs_fn, VSSIngesttModuleFactory.moduleName, MFT_Number)), \ (BlackboardAttribute(attID_vs_pa, VSSIngesttModuleFactory.moduleName, Path_Name)), \ (BlackboardAttribute(attID_vs_cr, VSSIngesttModuleFactory.moduleName, Crtime)), \ (BlackboardAttribute(attID_vs_md, VSSIngesttModuleFactory.moduleName, Mtime)), \ (BlackboardAttribute(attID_vs_ad, VSSIngesttModuleFactory.moduleName, Atime)), \ (BlackboardAttribute(attID_vs_ct, VSSIngesttModuleFactory.moduleName, Ctime)), (BlackboardAttribute(attID_vs_sz, VSSIngesttModuleFactory.moduleName, File_Size)))) # Fire an event to notify the UI and others that there are new artifacts IngestServices.getInstance().fireModuleDataEvent( ModuleDataEvent(VSSIngesttModuleFactory.moduleName, artID_vss_evt, None)) message = IngestMessage.createMessage(IngestMessage.MessageType.DATA, "Process/Extract VS", " Volume Shadow has been analyzed " ) IngestServices.getInstance().postMessage(message) return IngestModule.ProcessResult.OK
def test1(): print "foobar test - Example Service URL:%s - UUID:%s" % ( url, UUID.randomUUID())
def get_random_key(self): return UUID.randomUUID().toString()
def getCSID(): return str(UUID.randomUUID())
def generateUniqueReferenceForRepository(): randomUUID = UUID.randomUUID() newText = RepositoryReferenceScheme + randomUUID.toString() return newText
def create_actor(name): actor = Actor() actor.refId = UUID.randomUUID().toString() actor.name = name olca.insertActor(actor)
def test2(): print "hello world test - Example Service URL:%s - UUID:%s" % ( url, UUID.randomUUID())
def test2 (): print "hello world test - Example Service URL:%s - UUID:%s" % (url, UUID.randomUUID())
def __findWWFMessagesInDB(self, databasePath, abstractFile, dataSource): if not databasePath: return bbartifacts = list() try: Class.forName("org.sqlite.JDBC") # load JDBC driver connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath) statement = connection.createStatement() except (ClassNotFoundException) as ex: self._logger.log(Level.SEVERE, "Error loading JDBC driver", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) return except (SQLException) as ex: # Error opening database. return # Create a 'Device' account using the data source device id datasourceObjId = dataSource.getDataSource().getId() ds = Case.getCurrentCase().getSleuthkitCase().getDataSource( datasourceObjId) deviceID = ds.getDeviceId() deviceAccountInstance = Case.getCurrentCase().getSleuthkitCase( ).getCommunicationsManager().createAccountFileInstance( Account.Type.DEVICE, deviceID, general.MODULE_NAME, abstractFile) uuid = UUID.randomUUID().toString() resultSet = None try: resultSet = statement.executeQuery( "SELECT message, strftime('%s' ,created_at) as datetime, user_id, game_id FROM chat_messages ORDER BY game_id DESC, created_at DESC;" ) while resultSet.next(): message = resultSet.getString("message") # WWF Message created_at = resultSet.getLong("datetime") user_id = resultSet.getString( "user_id") # the ID of the user who sent the message. game_id = resultSet.getString( "game_id" ) # ID of the game which the the message was sent. thread_id = "{0}-{1}".format(uuid, user_id) attributes = ArrayList() artifact = abstractFile.newArtifact( BlackboardArtifact.ARTIFACT_TYPE.TSK_MESSAGE ) # create a call log and then add attributes from result set. attributes.add( BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME, general.MODULE_NAME, created_at)) attributes.add( BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE.TSK_NAME, general.MODULE_NAME, user_id)) attributes.add( BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE.TSK_MSG_ID, general.MODULE_NAME, game_id)) attributes.add( BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE.TSK_TEXT, general.MODULE_NAME, message)) attributes.add( BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE.TSK_MESSAGE_TYPE, general.MODULE_NAME, "Words With Friends Message")) attributes.add( BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE.TSK_THREAD_ID, general.MODULE_NAME, thread_id)) artifact.addAttributes(attributes) # Create an account wwfAccountInstance = Case.getCurrentCase().getSleuthkitCase( ).getCommunicationsManager().createAccountFileInstance( wwfAccountType, user_id, general.MODULE_NAME, abstractFile) # create relationship between accounts Case.getCurrentCase().getSleuthkitCase( ).getCommunicationsManager().addRelationships( deviceAccountInstance, [wwfAccountInstance], artifact, Relationship.Type.MESSAGE, created_at) bbartifacts.append(artifact) try: # index the artifact for keyword search blackboard = Case.getCurrentCase().getSleuthkitCase( ).getBlackboard() blackboard.postArtifact(artifact, general.MODULE_NAME) except Blackboard.BlackboardException as ex: self._logger.log( Level.SEVERE, "Unable to index blackboard artifact " + str(artifact.getArtifactID()), ex) self._logger.log(Level.SEVERE, traceback.format_exc()) MessageNotifyUtil.Notify.error( "Failed to index WWF message artifact for keyword search.", artifact.getDisplayName()) except SQLException as ex: # Unable to execute WWF messages SQL query against database. pass except Exception as ex: self._logger.log( Level.SEVERE, "Error parsing messages from Words With Friends.", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) finally: try: if resultSet is not None: resultSet.close() statement.close() connection.close() except Exception as ex: # Error closing database. pass
def generateId(self, idType, idPrefix): id = UUID.randomUUID().toString() print "new id: " + id return id
def addUUID(index) : uuidList.insert(index, UUID.randomUUID().toString()) return uuidList[index]
def randomUUIDPressed(self, event): randomUUID = UUID.randomUUID() newText = "uuid://" + randomUUID.toString() self.textEditor.text = newText