def attemptAuthentication(self, identity, user_profile, user_profile_json): uidKey = "uid" if not self.checkRequiredAttributes(user_profile, [uidKey, self.providerKey]): return False provider = user_profile[self.providerKey] if not provider in self.registeredProviders: print "Passport-social. attemptAuthentication. Identity Provider %s not recognized" % provider return False #else: # TODO - HANDLE ISSUER NOT SET # self.registeredProviders[provider]["samlissuer"] == None uid = user_profile[uidKey][0] externalUid = "passport-%s:%s" % (provider, uid) # PERSISTENT_ID - generate the persistentId for the RP if coming from SAML (entityId parameter is set) sessionId = identity.getSessionId() sessionAttributes = sessionId.getSessionAttributes() newPersistentIdSamlRp = sessionAttributes.get("spNameQualifier") switchFlowStatus = sessionAttributes.get("switchFlowStatus") mfaFlowStatus = sessionAttributes.get("mfaFlowStatus") # SWITCH - do NOT generate a new persistentId if the switch flow is being executed if ( newPersistentIdSamlRp != None and StringHelper.isNotEmptyString(newPersistentIdSamlRp) and switchFlowStatus == None and mfaFlowStatus != "MFA_2_IN_PROGRESS"): # PERSISTENT_ID - generate the persistentId for the RP in case there is no further processing/collection happening newPersistentIdIdp = self.registeredProviders[provider]["samlissuer"] newPersistentIdUid = "sic" + uuid.uuid4().hex user_profile["persistentId"][0] = '%s|%s|%s' % (newPersistentIdSamlRp, newPersistentIdIdp, newPersistentIdUid ) else: user_profile.pop("persistentId") if ( user_profile["claims"] != None ): # DISTRIBUTED CLAIMS - save the access token and the userInfo URL claimsReturn = user_profile["claims"] print "Passport-social. attemptAuthentication. Claims '%s'" % claimsReturn print "Passport-social. attemptAuthentication. Looking for user with oxExternalUid = '%s'" % externalUid userService = CdiUtil.bean(UserService) userByUid = userService.getUserByAttribute("oxExternalUid", externalUid) # MFA - if MFA is in progress, make sure UID matches the previous one if ( provider == "mfa" and sessionAttributes.get("mfaFlowStatus") == "MFA_2_IN_PROGRESS" ): # get the MFA PAI from the external UID if ( userByUid == None ): # the MFA authenticated user is not the same user print "Passport-social. attemptAuthentication. ERROR for MFA - MFA user cannot be found" return False elif ( userByUid.getUserId() != sessionAttributes.get("authenticatedUser") ): # the MFA authenticated user is not the same user print "Passport-social. attemptAuthentication. ERROR for MFA - The original and MFA users do not match" return False email = None if "mail" in user_profile: email = user_profile["mail"] if len(email) == 0: email = None else: email = email[0] user_profile["mail"] = [ email ] if email == None and self.registeredProviders[provider]["requestForEmail"]: print "Passport-social. attemptAuthentication. Email was not received" if userByUid != None: # This avoids asking for the email over every login attempt email = userByUid.getAttribute("mail") if email != None: print "Passport-social. attemptAuthentication. Filling missing email value with %s" % email user_profile["mail"] = [ email ] if email == None: # Store user profile in session and abort this routine identity.setWorkingParameter("passport_user_profile", user_profile_json) return True userByMail = None if email == None else userService.getUserByAttribute("mail", email) # Determine if we should add entry, update existing, or deny access doUpdate = False doAdd = False if userByUid != None: print "User with externalUid '%s' already exists" % externalUid if userByMail == None: doUpdate = True else: if userByMail.getUserId() == userByUid.getUserId(): doUpdate = True else: print "Users with externalUid '%s' and mail '%s' are different. Access will be denied. Impersonation attempt?" % (externalUid, email) self.setMessageError(FacesMessage.SEVERITY_ERROR, "Email value corresponds to an already existing provisioned account") else: if userByMail == None: doAdd = True elif self.registeredProviders[provider]["emailLinkingSafe"]: tmpList = userByMail.getAttributeValues("oxExternalUid") tmpList = ArrayList() if tmpList == None else ArrayList(tmpList) tmpList.add(externalUid) userByMail.setAttribute("oxExternalUid", tmpList) userByUid = userByMail print "External user supplying mail %s will be linked to existing account '%s'" % (email, userByMail.getUserId()) doUpdate = True else: print "An attempt to supply an email of an existing user was made. Turn on 'emailLinkingSafe' if you want to enable linking" self.setMessageError(FacesMessage.SEVERITY_ERROR, "Email value corresponds to an already existing account. If you already have a username and password use those instead of an external authentication site to get access.") # MFA - if MFA is REQUIRED generate the MFA PAI for the second pass if ( provider != "mfa" and sessionAttributes.get("mfaFlowStatus") == "MFA_1_REQUIRED" ): # generate a new MFA PAI in case there is none in the user profile user_profile[ "oxExternalUid_newMfa" ] = [ "passport-mfa:" + "mfa" + uuid.uuid4().hex ] username = None try: if doUpdate: username = userByUid.getUserId() print "Passport-social. attemptAuthentication. Updating user %s" % username self.updateUser(userByUid, user_profile, userService) elif doAdd: print "Passport-social. attemptAuthentication. Creating user %s" % externalUid user_profile[uidKey][0] = uuid.uuid4().hex newUser = self.addUser(externalUid, user_profile, userService) username = newUser.getUserId() except: print "Exception: ", sys.exc_info()[1] print "Passport-social. attemptAuthentication. Authentication failed" return False if username == None: print "Passport-social. attemptAuthentication. Authentication attempt was rejected" return False else: logged_in = CdiUtil.bean(AuthenticationService).authenticate(username) print "Passport-social. attemptAuthentication. Authentication for %s returned %s" % (username, logged_in) if ( logged_in == True ): # Save the authenticated data sessionAttributes.put("authenticatedProvider", "passport_social:" + provider) sessionAttributes.put("authenticatedUser", username) # SWITCH - Save contextual data for the switch flows if (switchFlowStatus == "1_GET_SOURCE"): print "Passport-social. attemptAuthentication. SWITCH FLOW: Setting SOURCE provider to %s" % sessionAttributes.get("authenticatedProvider") sessionAttributes.put( "switchSourceAuthenticatedProvider", sessionAttributes.get("authenticatedProvider") ) sessionAttributes.put( "switchSourceAuthenticatedUser", username) elif (switchFlowStatus == "2_GET_TARGET"): print "Passport-social. attemptAuthentication. SWITCH FLOW: Setting TARGET provider to %s" % sessionAttributes.get("authenticatedProvider") sessionAttributes.put("switchTargetAuthenticatedProvider", sessionAttributes.get("authenticatedProvider") ) sessionAttributes.put("switchTargetAuthenticatedUser", username) elif (mfaFlowStatus == "MFA_1_REQUIRED"): print "Passport-social. attemptAuthentication. MFA FLOW: starting flow marking status = MFA_2_IN_PROGRESS" sessionAttributes.put("mfaFlowStatus", "MFA_2_IN_PROGRESS" ) identity.setWorkingParameter("selectedProvider", "mfa") elif ( mfaFlowStatus == "MFA_2_IN_PROGRESS" ): print "Passport-social. attemptAuthentication. MFA FLOW: Marking flow as complete" sessionAttributes.put("mfaFlowStatus", "MFA_3_COMPLETE" ) elif ( mfaFlowStatus == "MFA_2_IN_PROGRESS" ): print "Passport-social. attemptAuthentication. MFA FLOW: Marking flow as FAILED" sessionAttributes.put("mfaFlowStatus", "MFA_3_FAILED" ) ## SESSION_SAFE - update CdiUtil.bean(SessionIdService).updateSessionId(sessionId) return logged_in
def authenticate(self, configurationAttributes, requestParameters, step): print "Casa. authenticate for step %s" % str(step) userService = CdiUtil.bean(UserService) authenticationService = CdiUtil.bean(AuthenticationService) identity = CdiUtil.bean(Identity) if step == 1: credentials = identity.getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() if StringHelper.isNotEmptyString( user_name) and StringHelper.isNotEmptyString( user_password): foundUser = userService.getUserByAttribute( self.uid_attr, user_name) #foundUser = userService.getUser(user_name) if foundUser == None: print "Casa. authenticate for step 1. Unknown username" else: platform_data = self.parsePlatformData(requestParameters) mfaOff = foundUser.getAttribute( "oxPreferredMethod") == None logged_in = False if mfaOff: logged_in = authenticationService.authenticate( user_name, user_password) else: acr = self.getSuitableAcr(foundUser, platform_data) if acr != None: module = self.authenticators[acr] logged_in = module.authenticate( module.configAttrs, requestParameters, step) if logged_in: foundUser = authenticationService.getAuthenticatedUser( ) if foundUser == None: print "Casa. authenticate for step 1. Cannot retrieve logged user" else: if mfaOff: identity.setWorkingParameter("skip2FA", True) else: #Determine whether to skip 2FA based on policy defined (global or user custom) skip2FA = self.determineSkip2FA( userService, identity, foundUser, platform_data) identity.setWorkingParameter( "skip2FA", skip2FA) identity.setWorkingParameter("ACR", acr) return True else: print "Casa. authenticate for step 1 was not successful" return False else: user = authenticationService.getAuthenticatedUser() if user == None: print "Casa. authenticate for step 2. Cannot retrieve logged user" return False #see casa.xhtml alter = ServerUtil.getFirstValue(requestParameters, "alternativeMethod") if alter != None: #bypass the rest of this step if an alternative method was provided. Current step will be retried (see getNextStep) self.simulateFirstStep(requestParameters, alter) return True session_attributes = identity.getSessionId().getSessionAttributes() acr = session_attributes.get("ACR") #this working parameter is used in casa.xhtml identity.setWorkingParameter( "methods", ArrayList(self.getAvailMethodsUser(user, acr))) success = False if acr in self.authenticators: module = self.authenticators[acr] success = module.authenticate(module.configAttrs, requestParameters, step) #Update the list of trusted devices if 2fa passed if success: print "Casa. authenticate. 2FA authentication was successful" tdi = session_attributes.get("trustedDevicesInfo") if tdi == None: print "Casa. authenticate. List of user's trusted devices was not updated" else: user.setAttribute("oxTrustedDevicesInfo", tdi) userService.updateUser(user) else: print "Casa. authenticate. 2FA authentication failed" return success return False
def _toArrayList(items): values = ArrayList(len(items)) _apply(values.add, items) return values
def clearAPList(self, event): self.affectedModel.clear() self.affectedResponses = ArrayList()
def registerExtenderCallbacks(self, callbacks): # Initialize the global stdout stream global stdout # Keep a reference to our callbacks object self._callbacks = callbacks # Obtain an extension helpers object self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("Burpsuite Yara Scanner") # Create the log and a lock on which to synchronize when adding log entries self._log = ArrayList() self._lock = Lock() # main split pane splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT) # table of log entries logTable = Table(self) scrollPane = JScrollPane(logTable) splitpane.setLeftComponent(scrollPane) # Options panel optionsPanel = JPanel() optionsPanel.setLayout(GridBagLayout()) constraints = GridBagConstraints() yara_exe_label = JLabel("Yara Executable Location:") constraints.fill = GridBagConstraints.HORIZONTAL constraints.gridx = 0 constraints.gridy = 0 optionsPanel.add(yara_exe_label, constraints) self._yara_exe_txtField = JTextField(25) constraints.fill = GridBagConstraints.HORIZONTAL constraints.gridx = 1 constraints.gridy = 0 optionsPanel.add(self._yara_exe_txtField, constraints) yara_rules_label = JLabel("Yara Rules File:") constraints.fill = GridBagConstraints.HORIZONTAL constraints.gridx = 0 constraints.gridy = 1 optionsPanel.add(yara_rules_label, constraints) self._yara_rules_files = Vector() self._yara_rules_files.add("< None >") self._yara_rules_fileList = JList(self._yara_rules_files) constraints.fill = GridBagConstraints.HORIZONTAL constraints.gridx = 1 constraints.gridy = 1 optionsPanel.add(self._yara_rules_fileList, constraints) self._yara_rules_select_files_button = JButton("Select Files") self._yara_rules_select_files_button.addActionListener(self) constraints.fill = GridBagConstraints.HORIZONTAL constraints.gridx = 1 constraints.gridy = 2 optionsPanel.add(self._yara_rules_select_files_button, constraints) self._yara_clear_button = JButton("Clear Yara Results Table") self._yara_clear_button.addActionListener(self) constraints.fill = GridBagConstraints.HORIZONTAL constraints.gridx = 1 constraints.gridy = 3 optionsPanel.add(self._yara_clear_button, constraints) # Tabs with request/response viewers viewerTabs = JTabbedPane() self._requestViewer = callbacks.createMessageEditor(self, False) self._responseViewer = callbacks.createMessageEditor(self, False) viewerTabs.addTab("Request", self._requestViewer.getComponent()) viewerTabs.addTab("Response", self._responseViewer.getComponent()) splitpane.setRightComponent(viewerTabs) # Tabs for the Yara output and the Options self._mainTabs = JTabbedPane() self._mainTabs.addTab("Yara Output", splitpane) self._mainTabs.addTab("Options", optionsPanel) # customize our UI components callbacks.customizeUiComponent(splitpane) callbacks.customizeUiComponent(logTable) callbacks.customizeUiComponent(scrollPane) callbacks.customizeUiComponent(viewerTabs) callbacks.customizeUiComponent(self._mainTabs) # add the custom tab to Burp's UI callbacks.addSuiteTab(self) # add ourselves as a context menu factory callbacks.registerContextMenuFactory(self) # Custom Menu Item self.menuItem = JMenuItem("Scan with Yara") self.menuItem.addActionListener(self) # obtain our output stream stdout = PrintWriter(callbacks.getStdout(), True) # Print a startup notification stdout.println("Burpsuite Yara scanner initialized.")
def getLoadedFiles(self): files = ArrayList() for file_ in self.loadedFiles: if file_.endswith(".py"): files.append(file_) return files
def attemptAuthentication(self, identity, user_profile, user_profile_json): uidKey = "uid" if not self.checkRequiredAttributes(user_profile, [uidKey, self.providerKey]): return False provider = user_profile[self.providerKey] if not provider in self.registeredProviders: print "Passport. attemptAuthentication. Identity Provider %s not recognized" % provider return False uid = user_profile[uidKey][0] externalUid = "passport-%s:%s" % (provider, uid) userService = CdiUtil.bean(UserService) userByUid = userService.getUserByAttribute("oxExternalUid", externalUid) email = None if "mail" in user_profile: email = user_profile["mail"] if len(email) == 0: email = None else: email = email[0] user_profile["mail"] = [email] if email == None and self.registeredProviders[provider][ "requestForEmail"]: print "Passport. attemptAuthentication. Email was not received" if userByUid != None: # This avoids asking for the email over every login attempt email = userByUid.getAttribute("mail") if email != None: print "Passport. attemptAuthentication. Filling missing email value with %s" % email user_profile["mail"] = [email] if email == None: # Store user profile in session and abort this routine identity.setWorkingParameter("passport_user_profile", user_profile_json) return True userByMail = None if email == None else userService.getUserByAttribute( "mail", email) # Determine if we should add entry, update existing, or deny access doUpdate = False doAdd = False if userByUid != None: print "User with externalUid '%s' already exists" % externalUid if userByMail == None: doUpdate = True else: if userByMail.getUserId() == userByUid.getUserId(): doUpdate = True else: print "Users with externalUid '%s' and mail '%s' are different. Access will be denied. Impersonation attempt?" % ( externalUid, email) self.setMessageError( FacesMessage.SEVERITY_ERROR, "Email value corresponds to an already existing provisioned account" ) else: if userByMail == None: doAdd = True elif self.registeredProviders[provider]["emailLinkingSafe"]: tmpList = userByMail.getAttributeValues("oxExternalUid") tmpList = ArrayList() if tmpList == None else ArrayList( tmpList) tmpList.add(externalUid) userByMail.setAttribute("oxExternalUid", tmpList) userByUid = userByMail print "External user supplying mail %s will be linked to existing account '%s'" % ( email, userByMail.getUserId()) doUpdate = True else: print "An attempt to supply an email of an existing user was made. Turn on 'emailLinkingSafe' if you want to enable linking" self.setMessageError( FacesMessage.SEVERITY_ERROR, "Email value corresponds to an already existing account.") username = None try: if doUpdate: username = userByUid.getUserId() print "Passport. attemptAuthentication. Updating user %s" % username self.updateUser(userByUid, user_profile, userService) elif doAdd: print "Passport. attemptAuthentication. Creating user %s" % externalUid newUser = self.addUser(externalUid, user_profile, userService) username = newUser.getUserId() except: print "Exception: ", sys.exc_info()[1] print "Passport. attemptAuthentication. Authentication failed" return False if username == None: print "Passport. attemptAuthentication. Authentication attempt was rejected" return False else: logged_in = CdiUtil.bean(AuthenticationService).authenticate( username) print "Passport. attemptAuthentication. Authentication for %s returned %s" % ( username, logged_in) return logged_in
def registerExtenderCallbacks(self, callbacks): # Set encoding to utf-8 to avoid some errors reload(sys) sys.setdefaultencoding('utf8') # Keep a reference to callback object and helper object self._callbacks = callbacks self._helpers = callbacks.getHelpers() # Set the extension name that shows in the burp extension menu callbacks.setExtensionName("InjectionScanner") # Create the log and a lock on which to synchronize when adding log entries self._log = ArrayList() self._logLock = Lock() self._httpLock = Lock() # The length of the basis used to fetch abnormal data, default to zero self._basisLen = 0 # 1: {POST. GET}; 2: {urlencoded, json, xml} self._postGet = 'NaN' self._dataType = 'NaN' # Scan list self._simpleList = [ '\'', '\"', '/', '/*', '#', ')', '(', ')\'', '(\'', 'and 1=1', 'and 1=2', 'and 1>2', 'and 12', '+', 'and+12', '/**/and/**/1' ] self._xmlList = ['a', 'b', 'c', 'd', 'e'] # Not setted # Response mutex: True = is blocking; False = free to go # self._mutexR = False # Other classes instance self._dataTable = Guis_DefaultTM() self._logTable = Guis_AbstractTM(self) self._xh = XMLHandler() listeners = Guis_Listeners(self, self._logTable) ''' Setting GUIs ''' # Divide the whole pane two: one upper and one lower pane self._mainSplitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT) self._mainSplitpane.setResizeWeight(0.4) # Initizlize request table dataTable = JTable(self._dataTable) dataScrollPane = JScrollPane(dataTable) dataScrollPane.setPreferredSize(Dimension(0, 125)) self._dataTable.addTableModelListener(listeners) # Initialize log table logTable = Guis_LogTable(self._logTable) logScrollPane = JScrollPane(logTable) logScrollPane.setPreferredSize(Dimension(0, 125)) # Split the upper pane to two panes tableSplitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) tableSplitpane.setResizeWeight(0.5) # Set the data table to the left and log to the right tableSplitpane.setLeftComponent(dataScrollPane) tableSplitpane.setRightComponent(logScrollPane) # Tabs with request/response viewers tabs = JTabbedPane() self._requestViewer = callbacks.createMessageEditor(self, False) self._responseViewer = callbacks.createMessageEditor(self, False) tabs.addTab("Request", self._requestViewer.getComponent()) tabs.addTab("Response", self._responseViewer.getComponent()) # Create buttons that do operation with the test self._basisLabel = JLabel('Basis: ' + str(self._basisLen)) self._levelLabel = JLabel('Level:') self._setBasisButton = JButton('Set Basis') self._hitOnceButton = JButton('Hit Once') self._autoScanButton = JButton('Auto Scan') self._clearLogButton = JButton('Clear Log') self._cancelButton = JButton('Cancel') self._levelSelection = JComboBox() self._levelSelection.addItem('1') self._levelSelection.addItem('2') self._levelSelection.addItem('3') self._hitOnceButton.addActionListener(listeners) self._autoScanButton.addActionListener(listeners) self._clearLogButton.addActionListener(listeners) self._setBasisButton.addActionListener(listeners) self._cancelButton.addActionListener(listeners) self._basisLabel.setPreferredSize(Dimension(100, 20)) # Create bottom pane for holding the buttons buttonPane = JPanel() buttonPane.setLayout(BorderLayout()) centerPane = JPanel() leftPane = JPanel() rightPane = JPanel() leftPane.add(self._basisLabel) centerPane.add(self._setBasisButton) centerPane.add(self._hitOnceButton) centerPane.add(self._autoScanButton) centerPane.add(self._cancelButton) centerPane.add(self._clearLogButton) rightPane.add(self._levelLabel) rightPane.add(self._levelSelection) buttonPane.add(centerPane, BorderLayout.CENTER) buttonPane.add(leftPane, BorderLayout.WEST) buttonPane.add(rightPane, BorderLayout.EAST) # Create and set the bottom panel that holds viewers and buttons utilPane = JPanel() utilPane.setLayout(BorderLayout()) utilPane.add(tabs, BorderLayout.CENTER) utilPane.add(buttonPane, BorderLayout.SOUTH) self._mainSplitpane.setLeftComponent(tableSplitpane) self._mainSplitpane.setRightComponent(utilPane) # Customize UI components callbacks.customizeUiComponent(self._mainSplitpane) callbacks.customizeUiComponent(dataTable) callbacks.customizeUiComponent(dataScrollPane) callbacks.customizeUiComponent(logTable) callbacks.customizeUiComponent(logScrollPane) callbacks.customizeUiComponent(tabs) callbacks.customizeUiComponent(buttonPane) callbacks.customizeUiComponent(utilPane) callbacks.customizeUiComponent(self._basisLabel) callbacks.customizeUiComponent(self._setBasisButton) callbacks.customizeUiComponent(self._hitOnceButton) callbacks.customizeUiComponent(self._autoScanButton) callbacks.customizeUiComponent(self._clearLogButton) callbacks.customizeUiComponent(self._levelSelection) callbacks.customizeUiComponent(self._cancelButton) # Add the custom tab to Burp's UI callbacks.addSuiteTab(self) # Register the context menu and message editor for new tabs callbacks.registerContextMenuFactory(self) # Register as a HTTP listener callbacks.registerHttpListener(self) return
def getStartupErrors(self): from java.util import ArrayList errorList = ArrayList() for err in self.getImportErrors(): errorList.add(str(err)) return errorList
def generateExceedanceValues(): return jf(lambda v: calculateExceedance(ArrayList(v.values())))
def getDCH_Field_Arr_for_Trial(self, trial): #------ return dch field array for the trial point field_arr = [] for dch_ind in range(self.variables.size()): var = self.variables.get(dch_ind) field = trial.getTrialPoint().getValue(var) field_arr.append(field) return field_arr #---- Initial step in parameters. During optimization #---- these steps will be reduced inside the optimizer. delta_hint = InitialDelta() #---- optimizing variabes variables = ArrayList() field_max = 0.012 field_min = -0.012 field_step = (field_max - field_min) / 30 for dch_ind in range(len(dchs)): dch = dchs[dch_ind] field = dch.getField() var = Variable(dch.getId(), field, field_min, field_max) variables.add(var) delta_hint.addInitialDelta(var, field_step) scorer = OrbitScorer(bpms, dchs, variables)
def createMenuItems(self, context_menu): self.context = context_menu menu_list = ArrayList() menu_list.add(JMenuItem("Send to Bing", actionPerformed=self.bing_menu)) return menu_list
SwapEdge(liaison, opts).compute() writeVTK(liaison) opts.clear() opts.put("coplanarity", "0.75") opts.put("tolerance", "0.6") opts.put("iterations", str(8)) SmoothNodes3DBg(liaison, opts).compute() writeVTK(liaison) #MeshWriter.writeObject3D(liaison.mesh, outDir, "" polylines = PolylineFactory(liaison.mesh, 135.0, options.size * 0.2) liaison.mesh.resetBeams() for entry in polylines.entrySet(): groupId = entry.key for polyline in entry.value: listM = ArrayList() for v in polyline: listM.add(EuclidianMetric3D(options.size)) #print "Remesh polyline of group "+str(groupId)+"/"+str(polylines.size())+" "+str(polyline.size())+" vertices" result = RemeshPolyline(liaison.mesh, polyline, listM).compute() for i in xrange(result.size() - 1): liaison.mesh.addBeam(result.get(i), result.get(i + 1), groupId) #print " New polyline: "+str(result.size())+" vertices" if options.recordFile: liaison.getMesh().getTrace().finish() MeshWriter.writeObject3D(liaison.mesh, outDir, "")
def fillUser(self, foundUser, profile): # To save the Persistent ID identity = CdiUtil.bean(Identity) sessionAttributes = identity.getSessionId().getSessionAttributes() currentRp = sessionAttributes.get("entityId") issuerSpNameQualifier = sessionAttributes.get("spNameQualifier") for attr in profile: # "provider" is disregarded if part of mapping if attr != self.providerKey: values = profile[attr] print "Passport-social. fillUser. %s = %s" % (attr, values) # COLLECT - here go through existing PersistentIDs add new ones for RPs that if they are not found if attr == "persistentId": if (values != None): # There is only one value from the mapping newPersistenId = values[0] # then we look through the old values if there is a matching RP remove if from "values" and do not update userPersistentIds = foundUser.getAttributeValues("persistentId") if ( userPersistentIds != None and issuerSpNameQualifier != None ): for userPersistentId in userPersistentIds: if ( userPersistentId.find(issuerSpNameQualifier) > -1 ): values.pop(0) # if there still is a persistentId, then add it to the current user profile if ( len(values) > 0): print "Passport-social. fillUser. Updating persistent IDs, original = '%s'" % userPersistentIds # if there are no current Persistent IDs create a new list tmpList = ArrayList(userPersistentIds) if userPersistentIds != None else ArrayList() tmpList.add(newPersistenId) print "Passport-social. fillUser. Updating persistent IDs, updated = '%s'" % tmpList foundUser.setAttribute(attr, tmpList) else: print "Passport-social. fillUser. PersistentId for RP '%s' already exists, ignoring new RP mapping" % issuerSpNameQualifier elif attr == "oxExternalUid_newMfa": # The attribute is here so MFA flow is REQUIRED. # First we check for existing MFA PAI already in the user profile mfaOxExternalUid = values[0] userOxExternalUids = foundUser.getAttributeValues("oxExternalUid") if (userOxExternalUids != None): for userOxExternalUid in userOxExternalUids: if ( userOxExternalUid.find("passport-mfa:") > -1 ): # if we found an MFA PAI then remove the new value mfaOxExternalUid = userOxExternalUid values.pop(0) # if there still is a value for MFA PAI, then add it to the current user profile because it did not exist if ( len(values) > 0): print "Passport-social. fillUser. Updating MFA PAI oxExternalUid, original list = '%s'" % userOxExternalUids # if there are no current Persistent IDs create a new list tmpList = ArrayList(userOxExternalUids) if userOxExternalUids != None else ArrayList() tmpList.add( mfaOxExternalUid ) print "Passport-social. fillUser. Updating persistent IDs, updated with MFA = '%s'" % tmpList foundUser.setAttribute("oxExternalUid", tmpList) else: print "Passport-social. fillUser. oxExternalUid for MFA '%s' already exists, ignoring new RP mapping" % mfaOxExternalUid elif attr == "mail": oxtrustMails = [] for mail in values: oxtrustMails.append('{"value":"%s","primary":false}' % mail) foundUser.setAttribute("oxTrustEmail", oxtrustMails) elif attr == "claims": if (values != None): timeSeconds = int(round(time.time())) # load claims: TODO validation of parsing result claims = json.loads(values[0]) # create the access token attribute for Shibboleth IDP to extract the value for SAML and save it in "transientId" accessTokenWithRpAndTimestamp = '%s|%s|%s|%s' % (currentRp, timeSeconds, claims["userinfourl"], claims["accesstoken"] ) print "Passport-social. updateUser. Claims adding access token (as transientId) '%s'" % accessTokenWithRpAndTimestamp foundUser.setAttribute( "transientId", accessTokenWithRpAndTimestamp ) # Save the claims into the session for distributed claims (USELESS TODAY, TODO: REMOVE) sessionAttributes.put("identityClaimsAccessToken", claims["accesstoken"]) sessionAttributes.put("identityClaimsUserInfoURL", claims["userinfourl"]) else: foundUser.setAttribute(attr, values)
def getDiagnosticsForFile(self, file_): errs = self.semanticErrors.get(file_) if errs is not None: return errs return ArrayList()
def mergeFromJava(siteId, activeTable, newRecords, logger, mode, offsetSecs=0): perfStat.log( "mergeFromJava called for site: %s, activeTable: %d , newRecords: %d" % (siteId, activeTable.size(), newRecords.size())) timer = TimeUtil.getTimer() timer.start() pyActive = [] szActive = activeTable.size() for i in range(szActive): pyActive.append( ActiveTableRecord.ActiveTableRecord(activeTable.get(i), "Previous")) pyNew = [] szNew = newRecords.size() for i in range(szNew): rec = ActiveTableRecord.ActiveTableRecord(newRecords.get(i)) pyNew.append(rec) active = ActiveTable(mode, logger) logger.info("Updating " + mode + " Active Table: new records\n" + active.printActiveTable(pyNew, combine=1)) timer.stop() perfStat.logDuration("mergeFromJava preprocess", timer.getElapsedTime()) updatedTable, purgeRecords, changes, changedFlag = active.activeTableMerge( pyActive, pyNew, offsetSecs) perfStat.log( "mergeFromJava activeTableMerge returned updateTable: %d, purgeRecords: %d, changes: %d" % (len(updatedTable), len(purgeRecords), len(changes))) timer.reset() timer.start() logger.info("Updated " + mode + " Active Table: purged\n" + active.printActiveTable(purgeRecords, combine=1)) stateDict = {} for r in updatedTable: recs = stateDict.get(r['state'], []) recs.append(r) stateDict[r['state']] = recs keys = stateDict.keys() keys.sort() for key in keys: if key == "Previous": continue logger.info("Updated " + mode + " Active Table: " + key + "\n" + active.printActiveTable(stateDict[key], combine=1)) updatedList = ArrayList(len(updatedTable)) for r in updatedTable: if r['state'] not in ["Previous", "Replaced"]: updatedList.add(r.javaRecord()) purgedList = ArrayList(len(purgeRecords)) for r in purgeRecords: purgedList.add(r.javaRecord()) changeList = ArrayList(len(changes)) if (changedFlag): from com.raytheon.uf.common.activetable import VTECChange for c in changes: changeList.add(VTECChange(c[0], c[1], c[2], c[3])) from com.raytheon.uf.common.activetable import MergeResult result = MergeResult(updatedList, purgedList, changeList) timer.stop() perfStat.logDuration("mergeFromJava postprocess", timer.getElapsedTime()) return result
def getFileErrs(self, file_, _map): msgs = _map.get(file_) if msgs is None: msgs = ArrayList() _map[file_] = msgs return msgs
from java.util import ArrayList LIST = ['One', -2, False] EMPTY_LIST = [] keyword_patterns = ArrayList() keyword_patterns.add("org/**/keyword/**/**.class") keyword_patterns.add("com/**/keyword/**/**.class") duplicate_keyword_patterns = ArrayList() duplicate_keyword_patterns.add("com/**/keyword/**/**.class") duplicate_keyword_patterns.add("my/same/keyword/**/**.class")
class Analyzer(object): # global static instance of the analyzer itself #self = Analyzer() allBindings = ArrayList() references = LinkedHashMap() semanticErrors = HashMap() parseErrors = HashMap() cwd = None nCalled = 0 multilineFunType = False path = ArrayList() uncalled = HashSet() callStack = HashSet() importStack = HashSet() astCache = AstCache() cacheDir = str() failedToParse = HashSet() stats = Stats() builtins = None # Builtins() logger = logging.getLogger(__name__) loadingProgress = None projectDir = str() # below doesn't work for some reason.... """ def init_vars(self): self.allBindings = ArrayList() self.references = LinkedHashMap() self.semanticErrors = HashMap() self.parseErrors = HashMap() self.cwd = None self.nCalled = 0 self.multilineFunType = False self.path = ArrayList() self.uncalled = HashSet() self.callStack = HashSet() self.importStack = HashSet() self.astCache = AstCache() self.cacheDir = str() self.failedToParse = HashSet() self.stats = Stats() self.builtins = None # Builtins() self.logger = logging.getLogger(__name__) self.loadingProgress = None self.projectDir = str() """ # singleton pattern _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Analyzer, cls).__new__(cls, *args, **kwargs) return cls._instance def __init__(self): self.moduleTable = Scope(None, Scope.ScopeType.GLOBAL) self.loadedFiles = ArrayList() self.globaltable = Scope(None, Scope.ScopeType.GLOBAL) import time millis = int(round(time.time() * 1000)) self.stats.putInt("startTime", millis) self.logger = logging.getLogger(__name__) if not hasattr(Analyzer, 'self'): setattr(Analyzer, 'self', self) self.builtins = Builtins() self.builtins.init() #self.addPythonPath() self.createCacheDir() self.getAstCache() # main entry to the analyzer def analyze(self, path): self.projectDir = _.unifyPath(path) self.loadFileRecursive(self.projectDir) def setCWD(self, cd): if cd is not None: self.cwd = cd #if cd is not None: # self.cwd = _.unifyPath(cd) def addPaths(self, p): for s in p: addPath(s) def addPath(self, p): self.path.add(_.unifyPath(p)) def setPath(self, path): self.path = ArrayList(len(path)) self.addPaths(path) def addPythonPath(self): path = System.getenv("PYTHONPATH") if path is not None: for p in segments: self.addPath(p) def getLoadPath(self): loadPath = ArrayList() if self.cwd is not None: loadPath.append(self.cwd) if self.projectDir is not None and os.path.isdir(self.projectDir): loadPath.append(self.projectDir) loadPath += self.path return loadPath def inStack(self, f): return f in self.callStack def pushStack(self, f): self.callStack.add(f) def popStack(self, f): self.callStack.remove(f) def inImportStack(self, f): return f in self.importStack def pushImportStack(self, f): self.importStack.add(f) def popImportStack(self, f): self.importStack.remove(f) def getAllBindings(self): return self.allBindings def getCachedModule(self, file_): t = self.moduleTable.lookupType(_.moduleQname(file_)) if t is None: return None elif t.isUnionType(): for tt in t.asUnionType().getTypes(): if tt.isModuleType(): return tt return None elif t.isModuleType(): return t else: return None def getDiagnosticsForFile(self, file_): errs = self.semanticErrors.get(file_) if errs is not None: return errs return ArrayList() #@overloaded def putRef(self, node, bs): if not hasattr(bs, '__len__'): bs = [bs] if not (isinstance(node, (Url, ))): ref = Ref(node) bindings = self.references.get(ref) if bindings is None: bindings = ArrayList() self.references[ref] = bindings for b in bs: if not b in bindings: bindings.append(b) b.addRef(ref) def getReferences(self): """ generated source for method getReferences """ return self.references def putProblem(self, *args): if len(args) == 2: return self.putProblem0(*args) else: return self.putProblem1(*args) #@overloaded def putProblem0(self, loc, msg): """ generated source for method putProblem """ file_ = loc.getFile() if file_ is not None: self.addFileErr(file_, loc.start, loc.end, msg) # for situations without a Node #@putProblem.register(object, str, int, int, str) def putProblem1(self, file_, begin, end, msg): """ generated source for method putProblem_0 """ if file_ is not None: self.addFileErr(file_, begin, end, msg) def addFileErr(self, file_, begin, end, msg): """ generated source for method addFileErr """ d = Diagnostic(file_, Diagnostic.Category.ERROR, begin, end, msg) self.getFileErrs(file_, self.semanticErrors).append(d) def getParseErrs(self, file_): return self.getFileErrs(file_, self.parseErrors) def getFileErrs(self, file_, _map): msgs = _map.get(file_) if msgs is None: msgs = ArrayList() _map[file_] = msgs return msgs def loadFile(self, path): _.msg("loading: " + path) path = _.unifyPath(path) if not os.path.isfile(path): self.finer("\nfile not not found or cannot be read: " + path) return None module_ = self.getCachedModule(path) if module_ is not None: self.finer("\nusing cached module " + path + " [succeeded]") return module_ # detect circular import if Analyzer.self.inImportStack(path): return None # set new CWD and save the old one on stack oldcwd = self.cwd self.setCWD(os.path.join(*path.split(os.sep)[:-1])) Analyzer.self.pushImportStack(path) mod = self.parseAndResolve(path) # restore old CWD self.setCWD(oldcwd) return mod def isInLoadPath(self, dir): for s in getLoadPath(): if File(s) == dir: return True return False def parseAndResolve(self, file_): self.finer("Analyzing: " + file_) self.loadingProgress.tick() try: ast = self.getAstForFile(file_) if ast is None: self.failedToParse.add(file_) return None else: self.finer("resolving: " + file_) mod = ast.resolve(self.moduleTable) assert isinstance(mod, ModuleType) self.finer("[success]") self.loadedFiles.append(file_) return mod except MemoryError as e: if self.astCache is not None: self.astCache.clear() import gc gc.collect() return None def createCacheDir(self): """ generated source for method createCacheDir """ self.cacheDir = _.makePathString(_.getSystemTempDir(), "pysonar2", "ast_cache") f = self.cacheDir _.msg("AST cache is at: " + self.cacheDir) if not os.path.exists(f): os.makedirs(f) if not os.path.exists(f): _.die("Failed to create tmp directory: " + self.cacheDir + ".Please check permissions") def getAstCache(self): """ generated source for method getAstCache """ if self.astCache is None: self.astCache = AstCache.get() return self.astCache.INSTANCE # # * Returns the syntax tree for {@code file}. <p> # def getAstForFile(self, file_): return self.getAstCache().getAST(file_) def getBuiltinModule(self, qname): return self.builtins.get(qname) def makeQname(self, names): if _.isEmpty(names): return "" ret = "" i = 0 while i < len(names) - 1: ret += names[i].id + "." i += 1 ret += names[len(names) - 1].id return ret # # * Find the path that contains modname. Used to find the starting point of locating a qname. # * # * @param headName first module name segment # def locateModule(self, headName): loadPath = self.getLoadPath() for p in loadPath: startDir = os.sep.join([p, headName]) initFile = _.joinPath(startDir, "__init__.py") if os.path.exists(initFile): return p startFile = startDir + ".py" if os.path.exists(startFile): return p return None def loadModule(self, name, scope): if _.isEmpty(name): return None from Binding import Binding qname = self.makeQname(name) mt = self.getBuiltinModule(qname) if mt is not None: scope.insert( name[0].id, Url(Builtins.LIBRARY_URL + mt.getTable().getPath() + ".html"), mt, Binding.Kind.SCOPE) return mt # If there's more than one segment # load the packages first prev = None startPath = self.locateModule(name[0].id) if startPath is None: return None path = startPath for i, n in enumerate(name): path = os.sep.join([path, name[i].id]) initFile = _.joinPath(path, "__init__.py") if os.path.isfile(initFile): mod = self.loadFile(initFile) if mod is None: return None if prev is not None: prev.getTable().insert(name[i].id, name[i], mod, Binding.Kind.VARIABLE) else: scope.insert(name[i].id, name[i], mod, Binding.Kind.VARIABLE) prev = mod elif i == len(name) - 1: startFile = path + ".py" if os.path.isfile(startFile): mod = self.loadFile(startFile) if mod is None: return None if prev is not None: prev.getTable().insert(name[i].id, name[i], mod, Binding.Kind.VARIABLE) else: scope.insert(name[i].id, name[i], mod, Binding.Kind.VARIABLE) prev = mod else: return None return prev # # * Load all Python source files recursively if the given fullname is a # * directory; otherwise just load a file. Looks at file extension to # * determine whether to load a given file. # def loadFileRecursive(self, fullname): count = self.countFileRecursive(fullname) if self.loadingProgress is None: self.loadingProgress = FancyProgress(count, 50) if os.path.isdir(fullname): for root, dirs, files in os.walk(fullname): for f in files: self.loadFileRecursive(root + os.sep + f) for d in dirs: self.loadFileRecursive(root + os.sep + d) else: if fullname.endswith(".py"): self.loadFile(fullname) # count number of .py files def countFileRecursive(self, fullname): sum = 0 if os.path.isdir(fullname): for root, dirs, files in os.walk(fullname): for f in files: sum += self.countFileRecursive(root + os.sep + f) for d in dirs: sum += self.countFileRecursive(root + os.sep + d) else: if fullname.endswith(".py"): sum += 1 return sum def finish(self): """ generated source for method finish """ # progress.end(); _.msg("\nFinished loading files. " + str(self.nCalled) + " functions were called.") _.msg("Analyzing uncalled functions") self.applyUncalled() # mark unused variables for b in self.allBindings: if not b.getType().isClassType() and not b.getType().isFuncType( ) and not b.getType().isModuleType() and _.isEmpty(b.getRefs()): Analyzer.self.putProblem( b.getNode(), "Unused variable: " + b.__class__.__name__) for ent in self.references.items(): self.convertCallToNew(ent[0], ent[1]) _.msg(self.getAnalysisSummary()) def close(self): """ generated source for method close """ self.astCache.close() def convertCallToNew(self, ref, bindings): """ generated source for method convertCallToNew """ if ref.isRef(): return if len(bindings) == 0: return nb = bindings[0] t = nb.getType() if t.isUnionType(): t = t.asUnionType().firstUseful() if t is None: return if not t.isUnknownType() and not t.isFuncType(): ref.markAsNew() def addUncalled(self, cl): """ generated source for method addUncalled """ if not cl.func.called: self.uncalled.add(cl) def removeUncalled(self, f): if f in self.uncalled: self.uncalled.remove(f) def applyUncalled(self): """ generated source for method applyUncalled """ progress = FancyProgress(len(self.uncalled), 50) while not _.isEmpty(self.uncalled): uncalledDup = list(self.uncalled) for cl in uncalledDup: progress.tick() Call.apply(cl, None, None, None, None, None) def getAnalysisSummary(self): sb = [] sb.append("\n" + _.banner("analysis summary")) duration = _.formatTime(_.millis() - self.stats.getInt("startTime")) sb.append("\n- total time: " + duration) sb.append("\n- modules loaded: " + str(len(self.loadedFiles))) sb.append("\n- semantic problems: " + str(len(self.semanticErrors))) sb.append("\n- failed to parse: " + str(len(self.failedToParse))) # calculate number of defs, refs, xrefs nDef = 0 nXRef = 0 for b in self.getAllBindings(): nDef += 1 nXRef += len(b.getRefs()) sb.append("\n- number of definitions: " + str(nDef)) sb.append("\n- number of cross references: " + str(nXRef)) sb.append("\n- number of references: " + str(len(self.getReferences()))) resolved = self.stats.getInt("resolved") unresolved = self.stats.getInt("unresolved") sb.append("\n- resolved names: " + str(resolved)) sb.append("\n- unresolved names: " + str(unresolved)) sb.append("\n- name resolve rate: " + _.percent(resolved, resolved + unresolved)) sb.append("\n" + _.getGCStats()) return ''.join(sb) def getLoadedFiles(self): files = ArrayList() for file_ in self.loadedFiles: if file_.endswith(".py"): files.append(file_) return files def registerBinding(self, b): self.allBindings.append(b) def log(self, level, msg): _.msg(msg) def severe(self, msg): self.log(Level.SEVERE, msg) def warn(self, msg): self.log(Level.WARNING, msg) def info(self, msg): self.log(Level.INFO, msg) def fine(self, msg): self.log(Level.FINE, msg) def finer(self, msg): self.log('*a log level*', msg) def __str__(self): return "<Analyzer:locs=" + len(self.references) + ":probs=" + len( self.semanticErrors) + ":files=" + len(self.loadedFiles) + ">"
def makeNullResponse(self): response = ArrayList() return response
def exportAll(): try: ALSBConfigurationMBean = findService( "ALSBConfiguration", "com.bea.wli.sb.management.configuration.ALSBConfigurationMBean") print "ALSBConfiguration MBean found" print project if project == "None": ref = Ref.DOMAIN collection = Collections.singleton(ref) if passphrase == None: print "Export the config" theBytes = ALSBConfigurationMBean.export( collection, true, None) else: print "Export and encrypt the config" theBytes = ALSBConfigurationMBean.export( collection, true, passphrase) else: ref = Ref.makeProjectRef(project) print "Export the project", project collection = Collections.singleton(ref) theBytes = ALSBConfigurationMBean.exportProjects( collection, passphrase) aFile = File(exportJar) out = FileOutputStream(aFile) out.write(theBytes) out.close() print "ALSB Configuration file: " + exportJar + " has been exported" if customFile != "None": print collection # see com.bea.wli.sb.util.EnvValueTypes in sb-kernel-api.jar for the values #EnvValueQuery evquery = # new EnvValueQuery( # null, // search across all resource types # Collections.singleton(EnvValueTypes.URI_ENV_VALUE_TYPE), // search only the URIs # null, // search across all projects and folders. # true, // only search across resources that are # // actually modified/imported in this session # "localhost", // the string we want to replace # false // not a complete match of URI. any URI # // that has "localhost" as substring will match # ); refTypes = HashSet() refTypes.add(EnvValueTypes.SERVICE_URI_TABLE) refTypes.add(EnvValueTypes.SERVICE_URI) query = EnvValueQuery( Collections.singleton(Refs.BUSINESS_SERVICE_TYPE), refTypes, collection, false, "search string", false) # query = EnvValueQuery(None, Collections.singleton(EnvValueTypes.SERVICE_URI_TABLE), collection, false, "search string", false) customEnv = FindAndReplaceCustomization('new endpoint url', query, 'replace string') # object = QualifiedEnvValue(Refs.makeBusinessSvcRef(ref,'file'), Refs.BUSINESS_SERVICE_TYPE, "XSDvalidation/file", "aaa") # objects = ArrayList() # objects.add(object) # customEnv2 = EnvValueCustomization('Set the right endpoints', objects) print 'EnvValueCustomization created' customList = ArrayList() customList.add(customEnv) # customList.add(customEnv2) print customList aFile = File(customFile) out = FileOutputStream(aFile) Customization.toXML(customList, out) out.close() print "ALSB Dummy Customization file: " + customFile + " has been created" except: raise
def attemptAuthentication(self, identity, user_profile, user_profile_json): # "uid" is always present in mapping, see prepareAttributesMapping uidRemoteAttr = self.getRemoteAttr("uid") providerKey = "provider" if self.behaveAs == "social" else "providerkey" if not self.checkRequiredAttributes(user_profile, [uidRemoteAttr, providerKey]): return False provider = user_profile[providerKey] print provider print self.registeredProviders if not provider in self.registeredProviders: print "Passport. attemptAuthentication. Identity Provider %s not recognized" % provider return False uidRemoteAttr = user_profile[uidRemoteAttr] if self.behaveAs == "social": externalUid = "passport-%s:%s" % (provider, uidRemoteAttr) else: # This is for backwards compat. Should it be passport-saml-provider:...?? externalUid = "passport-%s:%s" % ("saml", uidRemoteAttr) userService = CdiUtil.bean(UserService) userByUid = userService.getUserByAttribute("oxExternalUid", externalUid) mailRemoteAttr = self.getRemoteAttr("mail") email = None if mailRemoteAttr in user_profile: email = self.flatValues(user_profile[mailRemoteAttr]) if len(email) == 0: email = None else: email = email[0] user_profile[mailRemoteAttr] = email if email == None and self.registeredProviders[provider]["requestForEmail"]: print "Passport. attemptAuthentication. Email was not received" if userByUid != None: # This helps asking for the email over every login attempt email = userByUid.getAttribute("mail") if email != None: print "Passport. attemptAuthentication. Filling missing email value with %s" % email # Assumes mailRemoteAttr is not None user_profile[mailRemoteAttr] = email if email == None: # Store user profile in session and abort this routine identity.setWorkingParameter("passport_user_profile", user_profile_json) return True userByMail = None if email == None else userService.getUserByAttribute("mail", email) # Determine if we should add entry, update existing, or deny access doUpdate = False doAdd = False if userByUid != None: print "User with externalUid '%s' already exists" % externalUid if userByMail == None: doUpdate = True else: if userByMail.getUserId() == userByUid.getUserId(): doUpdate = True else: print "Users with externalUid '%s' and mail '%s' are different. Access will be denied. Impersonation attempt?" % (externalUid, email) else: if userByMail == None: doAdd = True elif self.registeredProviders[provider]["emailLinkingSafe"]: tmpList = userByMail.getAttributeValues("oxExternalUid") tmpList = ArrayList() if tmpList == None else ArrayList(tmpList) tmpList.add(externalUid) userByMail.setAttribute("oxExternalUid", tmpList) userByUid = userByMail print "External user supplying mail %s will be linked to existing account '%s'" % (email, userByMail.getUserId()) doUpdate = True else: print "An attempt to supply an email of an existing user was made. Turn on 'emailLinkingSafe' if you want to enable linking" username = None try: if doUpdate: username = userByUid.getUserId() print "Passport. attemptAuthentication. Updating user %s" % username self.updateUser(userByUid, user_profile, userService) elif doAdd: print "Passport. attemptAuthentication. Creating user %s" % externalUid newUser = self.addUser(externalUid, user_profile, userService) username = newUser.getUserId() except: print "Exception: ", sys.exc_info()[1] print "Passport. attemptAuthentication. Authentication failed" return False if username == None: print "Passport. attemptAuthentication. Authentication attempt was rejected" return False else: logged_in = CdiUtil.bean(AuthenticationService).authenticate(username) print "Passport. attemptAuthentication. Authentication for %s returned %s" % (username, logged_in) return logged_in
def registerExtenderCallbacks(self, callbacks): # smart xss feature (print conclusion and observation) # mark resulsts # add automatic check pages in the same domain self.tagPayloads = [ "<b>test", "<b onmouseover=test()>test", "<img src=err onerror=test()>", "<script>test</script>" "", "<scr ipt>test</scr ipt>", "<SCRIPT>test;</SCRIPT>", "<scri<script>pt>test;</scr</script>ipt>", "<SCRI<script>PT>test;</SCR</script>IPT>", "<scri<scr<script>ipt>pt>test;</scr</sc</script>ript>ipt>", "<IMG \"\"\"><SCRIPT>test</SCRIPT>\">", "<IMG '''><SCRIPT>test</SCRIPT>'>", "<SCR%00IPT>test</SCR%00IPT>", "<IFRAME SRC='f' onerror=\"test\"></IFRAME>", "<IFRAME SRC='f' onerror='test'></IFRAME>", "<<SCRIPT>test//<</SCRIPT>", "<img src=\"1\" onerror=\"test\">", "<img src='1' onerror='test'", "<STYLE TYPE=\"text/javascript\">test;</STYLE>", "<<SCRIPT>test//<</SCRIPT>" ] self.attributePayloads = [ "\"\"\"><SCRIPT>test", "'''><SCRIPT>test'", "\"><script>test</script>", "\"><script>test</script><\"", "'><script>test</script>", "'><script>test</script><'", "\";test;\"", "';test;'", ";test;", "\";test;//", "\"onmouseover=test ", "onerror=\"test\"", "onerror='test'", "onload=\"test\"", "onload='test'" ] self.xssKey = 'xssme' # keep a reference to our callbacks object self._callbacks = callbacks # obtain an extension helpers object self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("XSSor") self.affectedResponses = ArrayList() self._log = ArrayList() self._lock = Lock() # main split pane self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) # table of log entries logTable = Table(self) scrollPane = JScrollPane(logTable) self._splitpane.setLeftComponent(scrollPane) # tabs with request/response viewers tabs = JTabbedPane() self._requestViewer = callbacks.createMessageEditor(self, False) self._responseViewer = callbacks.createMessageEditor(self, False) tabs.addTab("Request", self._requestViewer.getComponent()) tabs.addTab("Response", self._responseViewer.getComponent()) clearAPListBtn = JButton("Clear List", actionPerformed=self.clearAPList) clearAPListBtn.setBounds(10, 85, 120, 30) apListLabel = JLabel('Affected Pages List:') apListLabel.setBounds(10, 10, 140, 30) self.affectedModel = DefaultListModel() self.affectedList = JList(self.affectedModel) self.affectedList.addListSelectionListener(listSelectedChange(self)) scrollAList = JScrollPane(self.affectedList) scrollAList.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED) scrollAList.setBounds(150, 10, 550, 200) scrollAList.setBorder(LineBorder(Color.BLACK)) APtabs = JTabbedPane() self._requestAPViewer = callbacks.createMessageEditor(self, False) self._responseAPViewer = callbacks.createMessageEditor(self, False) APtabs.addTab("Request", self._requestAPViewer.getComponent()) APtabs.addTab("Affeced Page Response", self._responseAPViewer.getComponent()) APtabs.setBounds(0, 250, 700, 350) APtabs.setSelectedIndex(1) self.APpnl = JPanel() self.APpnl.setBounds(0, 0, 1000, 1000) self.APpnl.setLayout(None) self.APpnl.add(scrollAList) self.APpnl.add(clearAPListBtn) self.APpnl.add(APtabs) self.APpnl.add(apListLabel) tabs.addTab("Affected Pages", self.APpnl) self.intercept = 0 ## init conf panel startLabel = JLabel("Plugin status:") startLabel.setBounds(10, 10, 140, 30) payloadLabel = JLabel("Basic Payload:") payloadLabel.setBounds(10, 50, 140, 30) self.basicPayload = "<script>alert(1)</script>" self.basicPayloadTxt = JTextArea(self.basicPayload, 5, 30) self.basicPayloadTxt.setBounds(120, 50, 305, 30) self.bruteForceMode = JCheckBox("Brute Force Mode") self.bruteForceMode.setBounds(120, 80, 300, 30) self.bruteForceMode.addItemListener(handleBFModeChange(self)) self.tagPayloadsCheck = JCheckBox("Tag paylods") self.tagPayloadsCheck.setBounds(120, 100, 300, 30) self.tagPayloadsCheck.setSelected(True) self.tagPayloadsCheck.setEnabled(False) self.tagPayloadsCheck.addItemListener(handleBFModeList(self)) self.attributePayloadsCheck = JCheckBox("Attribute payloads") self.attributePayloadsCheck.setBounds(260, 100, 300, 30) self.attributePayloadsCheck.setSelected(True) self.attributePayloadsCheck.setEnabled(False) self.attributePayloadsCheck.addItemListener(handleBFModeList(self)) payloadListLabel = JLabel("Payloads list (for BF mode):") payloadListLabel.setBounds(10, 130, 140, 30) self.payloadsModel = DefaultListModel() self.payloadsList = JList(self.payloadsModel) scrollPayloadsList = JScrollPane(self.payloadsList) scrollPayloadsList.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED) scrollPayloadsList.setBounds(120, 170, 300, 200) scrollPayloadsList.setBorder(LineBorder( Color.BLACK)) # add buttons to remove payloads and add for payload in self.tagPayloads: self.payloadsModel.addElement(payload) for payload in self.attributePayloads: self.payloadsModel.addElement(payload) self.startButton = JButton("XSSor is off", actionPerformed=self.startOrStop) self.startButton.setBounds(120, 10, 120, 30) self.startButton.setBackground(Color(255, 100, 91, 255)) consoleTab = JTabbedPane() self.consoleLog = JTextArea("", 5, 30) scrollLog = JScrollPane(self.consoleLog) scrollLog.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED) scrollLog.setBounds(120, 170, 550, 200) scrollLog.setBorder(LineBorder(Color.BLACK)) scrollLog.getVerticalScrollBar().addAdjustmentListener( autoScrollListener(self)) consoleTab.addTab("Console", scrollLog) consoleTab.setBounds(0, 400, 500, 200) self.pnl = JPanel() self.pnl.setBounds(0, 0, 1000, 1000) self.pnl.setLayout(None) self.pnl.add(self.startButton) self.pnl.add(startLabel) self.pnl.add(payloadLabel) self.pnl.add(self.basicPayloadTxt) self.pnl.add(self.bruteForceMode) self.pnl.add(payloadListLabel) self.pnl.add(scrollPayloadsList) self.pnl.add(self.attributePayloadsCheck) self.pnl.add(self.tagPayloadsCheck) self.pnl.add(consoleTab) tabs.addTab("Configuration", self.pnl) tabs.setSelectedIndex(3) self._splitpane.setRightComponent(tabs) # customize our UI components callbacks.customizeUiComponent(self._splitpane) callbacks.customizeUiComponent(logTable) callbacks.customizeUiComponent(scrollPane) callbacks.customizeUiComponent(tabs) # add the custom tab to Burp's UI callbacks.addSuiteTab(self) # register ourselves as an HTTP listener callbacks.registerHttpListener(self) self._callbacks.registerContextMenuFactory(self) print "Thank you for installing XSSor v0.1 extension" print "Created by Barak Tawily" print "\nGithub:\nhttps://github.com/Quitten/XSSor" return
def __init__(self): self.position = PVector(width/2, height/2) self.velocity = PVector() self.acceleration = PVector() self.history = ArrayList() self.noff = PVector(random(1000), random(1000))
from java.util import ArrayList, List from java.util.regex import Matcher, Pattern import binascii from javax import swing from java.awt import Font, Color import sys import time import threading import base64 import re from array import array import json #Global Issue List issueList = ArrayList() class BurpExtender(IBurpExtender, IScannerCheck, IContextMenuFactory, IHttpRequestResponse, IBurpExtenderCallbacks): def registerExtenderCallbacks(self, callbacks): sys.stdout = callbacks.getStdout() self._callbacks = callbacks self._helpers = callbacks.getHelpers() callbacks.setExtensionName("SQLTruncScanner") callbacks.issueAlert("SQL Truncation Scanner Enabled") stdout = PrintWriter(callbacks.getStdout(), True) stderr = PrintWriter(callbacks.getStderr(), True) callbacks.registerContextMenuFactory(self) print("SQL Truncation Scanner loaded.") print("Copyright (c) 2020 Frans Hendrik Botes (InitRoot)")
def makeNullResponse(self): response = ArrayList() response.add( ResponseMessageGeneric("Database Query returned no results")) return response
ui.openFile(roiFile) #//////////////////////////// # Get the planes. #//////////////////////////// planes = ui.getmimsTomography().getPlanes() #//////////////////////////// # Get the rois. #//////////////////////////// rois = ui.getRoiManager().getAllROIs() #//////////////////////////// # Get images. #//////////////////////////// imageArray = ArrayList() massimages = ui.getOpenMassImages() for j in range(len(massimages)): imageArray.add(massimages[j]) # Ratio images # 0 corresponds to the first mass image (e.g. mass 12.0) # 1 corresponds to the second mass image (e.g. mass 13.0) ratioProps1 = RatioProps(1, 0) mp1 = MimsPlus(ui, ratioProps1) imageArray.add(mp1) IJ.log("Opening ratio: " + mp1.getTitle()) # Ratio images # 2 corresponds to the first mass image (e.g. mass 26.0)
def setPath(self, path): self.path = ArrayList(len(path)) self.addPaths(path)
/* access modifiers changed from: private */ /* renamed from: i */ public int f4583i = 0; /* renamed from: j */ private int f4584j = 0; /* renamed from: k */ private boolean f4585k = false; /* renamed from: l */ private int f4586l = 1000000; /* renamed from: m */ private List<C1453b> f4587m = new ArrayList(); /* access modifiers changed from: private */ /* renamed from: n */ public Context f4588n = null; /* renamed from: o */ private String f4589o = "1.0.0"; /* renamed from: p */ private int f4590p = 0; /* access modifiers changed from: private */ /* renamed from: q */ public String f4591q = "AsyncHttpProxy";
def registerExtenderCallbacks(self, callbacks): # Make available to whole class self._callbacks = callbacks # obtain an extension helpers object self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("MitM helper plugin for drozer") # create the log and a lock on which to synchronize when adding log entries self._log = ArrayList() self._lock = Lock() # Split pane self._splitpane = swing.JSplitPane(swing.JSplitPane.HORIZONTAL_SPLIT) # Create Tab topPanel = swing.JPanel() topPanel.setLayout(swing.BoxLayout(topPanel, swing.BoxLayout.Y_AXIS)) # Define all tools self.tools = [] self.tools.append( Tool(180, "JavaScript Injection", "Inject Remote JS into HTTP Responses", self.nothing, self.injectJs, "JS Location", "http://x.x.x.x:31415/dz.js")) self.tools.append( Tool(180, "APK Replacement", "Replace APK with specified one when requested", self.modifyAPKRequest, self.injectAPK, "APK Location", "", True)) self.tools.append( Tool( 170, "Invoke drozer using pwn://", "Inject code into HTTP Responses that invokes installed drozer agent", self.nothing, self.injectPwn, None, None, None, "Perform active invocation (required for Chromium >= 25)")) self.tools.append( Tool( 220, "Custom URI Handler Injection", "Inject code into HTTP Responses that invokes specified URI handler", self.nothing, self.injectCustomURI, "URI", "pwn://me", None, "Perform active invocation (required for Chromium >= 25)")) # Add all tools to panel for i in self.tools: topPanel.add(i.getPanel()) self._splitpane.setLeftComponent(topPanel) # table of log entries logTable = Table(self) logTable.setAutoResizeMode(swing.JTable.AUTO_RESIZE_ALL_COLUMNS) logTable.getColumn("Time").setPreferredWidth(120) logTable.getColumn("URL").setPreferredWidth(500) scrollPane = swing.JScrollPane(logTable) self._splitpane.setRightComponent(scrollPane) # customize our UI components callbacks.customizeUiComponent(self._splitpane) callbacks.customizeUiComponent(logTable) callbacks.customizeUiComponent(scrollPane) callbacks.customizeUiComponent(topPanel) # add the custom tab to Burp's UI callbacks.addSuiteTab(self) # register ourselves as an HTTP listener callbacks.registerHttpListener(self) return