List of usage examples for org.apache.commons.lang StringUtils strip
public static String strip(String str, String stripChars)
Strips any of a set of characters from the start and end of a String.
From source file:org.openvpms.web.component.im.contact.ContactHelper.java
/** * Returns the default value for the <em>contact.email</em> name node. * * @return the default email name//w w w . j a v a 2 s . c om */ public static String getDefaultEmailName() { ArchetypeDescriptor archetypeDescriptor = DescriptorHelper.getArchetypeDescriptor(ContactArchetypes.EMAIL); String value = null; if (archetypeDescriptor != null) { NodeDescriptor descriptor = archetypeDescriptor.getNodeDescriptor("name"); if (descriptor != null) { value = descriptor.getDefaultValue(); if (value != null) { // defaultValue is an xpath expression. Rather than evaluating it, just support the simple case of // a quoted string. value = StringUtils.strip(value, "'"); } if (StringUtils.isEmpty(value)) { value = null; } } } return value; }
From source file:org.openvpms.web.component.im.lookup.NodeLookupQuery.java
/** * Returns the default lookup.//from www . ja v a2s . c o m * * @return the default lookup, or {@code null} if none is defined */ @Override public Lookup getDefault() { Lookup result = null; NodeDescriptor node = getDescriptor(); if (node != null) { List<Lookup> lookups = getLookups(); String code = node.getDefaultValue(); if (code != null) { // defaultValue is an xpath expression. Rather than evaluating // it, just support the simple case of a quoted string. code = StringUtils.strip(code, "'"); result = getLookup(code, lookups); } if (result == null) { result = getDefault(lookups); } } return result; }
From source file:org.rapidcontext.core.web.Request.java
/** * Returns the parsed "Authorization" request header data. The * authentication type will be stored with the "type" key. Other * fields will be stored with their corresponding keys. Any * unidentified data will be stored with the "data" key. * * @return the parsed authentication data, or * null if not present/*from ww w . j av a 2s . co m*/ */ public Dict getAuthentication() { String auth = request.getHeader("Authorization"); if (auth == null || !auth.contains(" ")) { return null; } else { Dict dict = new Dict(); String[] pairs = auth.split("[ \t\n\r,]"); dict.set("type", pairs[0]); for (int i = 1; i < pairs.length; i++) { String[] pair = pairs[i].split("="); if (pair.length == 2) { dict.set(pair[0], StringUtils.strip(pair[1], "\"")); } else { dict.set("data", pairs[i]); } } return dict; } }
From source file:org.sipfoundry.sipxconfig.admin.CertificateManagerImpl.java
public Properties loadCertPropertiesFile() { File propertiesFile = new File(m_certDirectory, PROPERTIES_FILE); try {// w w w . ja va 2s. c o m FileInputStream propertiesStream = new FileInputStream(propertiesFile); Properties properties = new Properties(); properties.load(propertiesStream); Enumeration<Object> propertiesEnum = properties.keys(); while (propertiesEnum.hasMoreElements()) { String key = (String) propertiesEnum.nextElement(); String value = properties.getProperty(key); value = StringUtils.strip(value, DOUBLE_QUOTES); properties.setProperty(key, value); } return properties; } catch (FileNotFoundException e) { return null; } catch (IOException e) { throw new UserException(READ_ERROR, propertiesFile.getPath()); } }
From source file:org.structr.core.graph.search.SearchNodeCommand.java
private String decodeExactMatch(final String value) { return StringUtils.strip(value, "\""); }
From source file:org.structr.core.graph.search.SearchRelationshipCommand.java
private String decodeExactMatch(final String value) { return StringUtils.strip(value, "\""); }
From source file:org.talend.components.salesforce.SalesforceRuntime.java
@Override public void connect(ComponentProperties p) throws ConnectionException, AsyncApiException { SalesforceConnectionProperties properties = (SalesforceConnectionProperties) p; String refedComponentId = properties.referencedComponentId.getStringValue(); if (refedComponentId != null && container != null) { if (!refedComponentId.equals(container.getCurrentComponentName())) { connection = (PartnerConnection) container.getGlobalMap().get(refedComponentId); if (connection == null) { throw new ConnectionException( "Can't find the shared connection instance with refedComponentId: " + refedComponentId); }//from ww w.j a v a 2s. c o m return; } } ConnectorConfig config = new ConnectorConfig(); config.setUsername(StringUtils.strip(properties.userPassword.userId.getStringValue(), "\"")); config.setPassword(StringUtils.strip(properties.userPassword.password.getStringValue(), "\"") + StringUtils.strip(properties.userPassword.securityKey.getStringValue(), "\"")); // Notes on how to test this // http://thysmichels.com/2014/02/15/salesforce-wsc-partner-connection-session-renew-when-session-timeout/ final SalesforceConnectionProperties finalProps = properties; config.setSessionRenewer(new SessionRenewer() { @Override public SessionRenewalHeader renewSession(ConnectorConfig connectorConfig) throws ConnectionException { SessionRenewalHeader header = new SessionRenewalHeader(); try { // FIXME - session id need to be null for trigger the login? // connectorConfig.setSessionId(null); doConnection(finalProps, connectorConfig); } catch (AsyncApiException e) { // FIXME e.printStackTrace(); } SessionHeader_element h = connection.getSessionHeader(); // FIXME - one or the other, I have seen both // header.name = new QName("urn:partner.soap.sforce.com", "X-SFDC-Session"); header.name = new QName("urn:partner.soap.sforce.com", "SessionHeader"); header.headerElement = h.getSessionId(); return header; } }); if (properties.timeout.getIntValue() > 0) { config.setConnectionTimeout(properties.timeout.getIntValue()); } config.setCompression(properties.needCompression.getBooleanValue()); if (false) { config.setTraceMessage(true); } doConnection(properties, config); LOG.debug("Connection: " + connection); LOG.debug("Bulk Connection: " + bulkConnection); }
From source file:org.talend.dataprep.folder.store.AbstractFolderTest.java
/** * this test create a hierarchy then delete part of it doing some assert on list, size then delete part of it * asserting the deletion//from ww w . jav a2 s.co m */ @Test public void create_two_children_little_children_then_remove() throws Exception { // - foo // - beer // +- bar long sizeBefore = getFolderRepository().size(); Folder foo = getFolderRepository().addFolder(homeFolderId, "foo"); Folder beer = getFolderRepository().addFolder(homeFolderId, "beer"); Folder bar = getFolderRepository().addFolder(beer.getId(), "bar"); Iterable<Folder> iterable = getFolderRepository().children(homeFolderId); List<Folder> folders = new ArrayList<>(); iterable.forEach(folders::add); assertThat(folders).isNotNull().isNotEmpty().hasSize(2); // testing child of /bar iterable = getFolderRepository().children(beer.getId()); folders = Lists.newArrayList(iterable); assertThat(folders).isNotNull().isNotEmpty().hasSize(1); assertThat(StringUtils.strip(folders.get(0).getPath(), "/")).isEqualToIgnoringCase("beer/bar"); assertThat(folders.get(0).getName()).isEqualToIgnoringCase("bar"); getFolderRepository().removeFolder(bar.getId()); // testing child of /beer after removing the first child iterable = getFolderRepository().children(beer.getId()); folders = Lists.newArrayList(iterable); assertThat(folders).isNotNull().isEmpty(); // testing the whole size long sizeAfter = getFolderRepository().size(); assertThat(sizeAfter).isEqualTo(2); getFolderRepository().removeFolder(foo.getId()); getFolderRepository().removeFolder(beer.getId()); sizeAfter = getFolderRepository().size(); assertThat(sizeAfter).isEqualTo(sizeBefore); iterable = getFolderRepository().children(homeFolderId); folders = Lists.newArrayList(iterable); assertThat(folders).isNotNull().isEmpty(); }
From source file:org.talend.designer.core.generic.model.migration.NewSalesforceMigrationTask.java
@Override protected ElementParameterType getParameterType(NodeType node, String paramName) { ElementParameterType paramType = ParameterUtilTool.findParameterType(node, paramName); if (node != null && paramType != null) { Object value = ParameterUtilTool.convertParameterValue(paramType); if ("MODULENAME".equals(paramName) && "CustomModule".equals(value)) { paramName = "CUSTOM_MODULE_NAME"; if ("tSalesforceInput".equals(node.getComponentName())) { paramName = "CUSTOM_MODULE"; }/*from www. ja va 2 s. c om*/ ElementParameterType customModuleName = ParameterUtilTool.findParameterType(node, paramName); if (customModuleName != null) { paramType.setValue(StringUtils.strip( String.valueOf(ParameterUtilTool.convertParameterValue(customModuleName)), "\"")); } } else if ("CONNECTION".equals(paramName) && value != null && !"".equals(value)) { ElementParameterType useConnection = ParameterUtilTool.findParameterType(node, "USE_EXISTING_CONNECTION"); if (useConnection != null && Boolean .valueOf(String.valueOf(ParameterUtilTool.convertParameterValue(useConnection)))) { return paramType; } else { return null; } } else if ("API".equals(paramName)) { if ("soap".equals(value)) { paramType.setValue("Query"); } else { paramType.setValue("Bulk"); } } else if ("LOGIN_TYPE".equals(paramName)) { if ("BASIC".equals(value)) { paramType.setValue("Basic"); } else if ("OAUTH".equals(value)) { paramType.setValue("OAuth"); } } } return paramType; }
From source file:org.zaproxy.zap.extension.sqliplugin.SQLInjectionPlugin.java
/** * Scans for SQL Injection vulnerabilities according to SQLMap payload definitions. Current * implemented tests are: Boolean-Based, Error-Based, Union-query, OrderBy-query, Stacked-Query * and Time-based. This plugin only test for the existence of a SQLi according to these * injection methods and exploit it generating less effects as possible. All revealed * vulnerabilities are then without false positives, and the detected payload could be used for * further attacks. After this detection we suggest to use exploiting tools like SQLmap itself * or SQLNinja, Havij, etc. for this vulnerability usage and control. * * @param msg a request only copy of the original message (the response isn't copied) * @param parameter the parameter name that need to be exploited * @param value the original parameter value *//* w w w . j a v a 2 s .c o m*/ @Override public void scan(HttpMessage msg, String parameter, String value) { // First of all get the SQLi payloads list // using the embedded configuration file SQLiPayloadManager manager = SQLiPayloadManager.getInstance(); // Internal engine variable definition HttpMessage origMsg; HttpMessage tempMsg; String currentPrefix; String currentSuffix; String currentComment; String payloadValue; String reqPayload; String cmpPayload; String content; String title; boolean injectable; int injectableTechniques = 0; // Maybe could be a good idea to sort tests // according to the behavior and the heaviness // TODO: define a compare logic and sort it according to that for (SQLiTest test : manager.getTests()) { title = test.getTitle(); // unionExtended = false; // If it's a union based query test // first prepare all the needed elements if (test.getStype() == SQLiPayloadManager.TECHNIQUE_UNION) { // Set the string that need to be used // for the union query construction // ---------------------------------------------------- if (title.contains("[CHAR]")) { if (unionChar == null) { if (log.isDebugEnabled()) { log.debug("skipping test '" + title + "' because the user didn't provide a custom charset"); } continue; } else { title = title.replace("[CHAR]", unionChar); if (StringUtils.isNumeric(unionChar)) { uChars = unionChar; } else { // maybe the user set apics inside the chars string uChars = "'" + StringUtils.strip(unionChar, "'") + "'"; } } } else { // Set union chars to the one specified // inside the global payload definition uChars = test.getRequest().getChars(); } // Check if there's a random element to be set // ---------------------------------------------------- if (title.contains("[RANDNUM]") || title.contains("(NULL)")) { title = title.replace("[RANDNUM]", "random number"); } // Set the union column range according to the specific // payload definition (custom based or constrained) // ---------------------------------------------------- if (test.getRequest().getColumns().equals("[COLSTART]-[COLSTOP]")) { if (unionCols == null) { if (log.isDebugEnabled()) { log.debug( "skipping test '" + title + "' because the user didn't provide a column range"); } continue; } else { setUnionRange(unionCols); title = title.replace("[COLSTART]", Integer.toString(uColsStart)); title = title.replace("[COLSTOP]", Integer.toString(uColsStop)); } } else { // Set column range (the range set on the payload definition // take precedence respect to the one set by the user) setUnionRange(test.getRequest().getColumns()); } /* // Seems useless (double the starting and ending column number value) match = re.search(r"(\d+)-(\d+)", test.request.columns) if injection.data and match: lower, upper = int(match.group(1)), int(match.group(2)) for _ in (lower, upper): if _ > 1: unionExtended = True test.request.columns = re.sub(r"\b%d\b" % _, str(2 * _), test.request.columns) title = re.sub(r"\b%d\b" % _, str(2 * _), title) test.title = re.sub(r"\b%d\b" % _, str(2 * _), test.title) */ } // Skip test if the user's wants to test only // for a specific technique if ((techniques != null) && !techniques.contains(test.getStype())) { if (log.isDebugEnabled()) { StringBuilder message = new StringBuilder(); message.append("skipping test '"); message.append(title); message.append("' because the user specified to test only for "); for (int i : techniques) { message.append(" & "); message.append(SQLiPayloadManager.SQLI_TECHNIQUES.get(i)); } message.append(" techniques"); log.debug(message); } continue; } // Skip test if it is the same SQL injection type already // identified by another test if ((injectableTechniques & (1 << test.getStype())) != 0) { if (log.isDebugEnabled()) { log.debug("skipping test '" + title + "' because the payload for " + SQLiPayloadManager.SQLI_TECHNIQUES.get(test.getStype()) + " has already been identified"); } continue; } // Skip test if the risk is higher than the provided (or default) value // Parse test's <risk> if (test.getRisk() > risk) { if (log.isDebugEnabled()) { log.debug("skipping test '" + title + "' because the risk (" + test.getRisk() + ") is higher than the provided (" + risk + ")"); } continue; } // Skip test if the level is higher than the provided (or default) value // Parse test's <level> if (test.getLevel() > level) { if (log.isDebugEnabled()) { log.debug("skipping test '" + title + "' because the level (" + test.getLevel() + ") is higher than the provided (" + level + ")"); } continue; } // Skip DBMS-specific test if it does not match either the // previously identified or the user's provided DBMS (either // from program switch or from parsed error message(s)) // ------------------------------------------------------------ // Initially set the current Tech value to null currentDbms = null; if ((test.getDetails() != null) && !(test.getDetails().getDbms().isEmpty())) { // If the global techset hasn't been populated this // mean that all technologies should be scanned... if (getTechSet() == null) { currentDbms = test.getDetails().getDbms().get(0); } else { // Check if DBMS scope has been restricted // using the Tech tab inside the scanner // -------------------------- for (DBMSHelper dbms : test.getDetails().getDbms()) { if (getTechSet().includes(dbms.getTech())) { // Force back-end DBMS according to the current // test value for proper payload unescaping currentDbms = dbms; break; } } } // Skip this test if the specific Dbms is not include // inside the list of the allowed one if (currentDbms == null) { if (log.isDebugEnabled()) { log.debug("skipping test '" + title + "' because the db is not included in the Technology list"); } continue; } /* Check if the KB knows what's the current DB * I escaped it because there's no user interaction and * all tests should be performed... to be verified if * there should exists a specific configuration for this * if len(Backend.getErrorParsedDBMSes()) > 0 and not intersect(dbms, Backend.getErrorParsedDBMSes()) and kb.skipOthersDbms is None: msg = "parsed error message(s) showed that the " msg += "back-end DBMS could be %s. " % Format.getErrorParsedDBMSes() msg += "Do you want to skip test payloads specific for other DBMSes? [Y/n]" if readInput(msg, default="Y") in ("y", "Y"): kb.skipOthersDbms = Backend.getErrorParsedDBMSes() else: kb.skipOthersDbms = [] if kb.skipOthersDbms and not intersect(dbms, kb.skipOthersDbms): debugMsg = "skipping test '%s' because " % title debugMsg += "the parsed error message(s) showed " debugMsg += "that the back-end DBMS could be " debugMsg += "%s" % Format.getErrorParsedDBMSes() logger.debug(debugMsg) continue */ } // Skip test if the user provided custom character if ((unionChar != null) && (title.contains("random number") || title.contains("(NULL)"))) { if (log.isDebugEnabled()) { log.debug("skipping test '" + title + "' because the user provided a specific character, " + unionChar); } continue; } // This check is suitable to the current configuration // Start logging the current execution (only in debugging) if (log.isDebugEnabled()) { log.debug("testing '" + title + "'"); } // Parse test's <request> currentComment = (manager.getBoundaries().size() > 1) ? test.getRequest().getComment() : null; // Start iterating through applicable boundaries for (SQLiBoundary boundary : manager.getBoundaries()) { // First set to false the injectable param injectable = false; // Skip boundary if the level is higher than the provided (or // default) value // Parse boundary's <level> if (boundary.getLevel() > level) { continue; } // Skip boundary if it does not match against test's <clause> // Parse test's <clause> and boundary's <clause> if (!test.matchClause(boundary)) { continue; } // Skip boundary if it does not match against test's <where> // Parse test's <where> and boundary's <where> if (!test.matchWhere(boundary)) { continue; } // Parse boundary's <prefix>, <suffix> // Options --prefix/--suffix have a higher priority (if set by user) currentPrefix = (prefix == null) ? boundary.getPrefix() : prefix; currentSuffix = (suffix == null) ? boundary.getSuffix() : suffix; currentComment = (suffix == null) ? currentComment : null; // For each test's <where> for (int where : test.getWhere()) { // Get the complete original message // including previously retrieved content // that could be considered trusted also after // other plugins execution thanks to the removal // of reflective values from the content... // But if we decide to rerun sendAndReceive() // each plugin execution, then we have to work // with message copies and use getNewMsg() origMsg = getBaseMsg(); // Threat the parameter original value according to the // test's <where> tag switch (where) { case SQLiPayloadManager.WHERE_ORIGINAL: payloadValue = value; break; case SQLiPayloadManager.WHERE_NEGATIVE: // Use different page template than the original // one as we are changing parameters value, which // will likely result in a different content if (invalidLogical) { payloadValue = value + " AND " + SQLiPayloadManager.randomInt() + "=" + SQLiPayloadManager.randomInt(); } else if (invalidBignum) { payloadValue = SQLiPayloadManager.randomInt(6) + "." + SQLiPayloadManager.randomInt(1); } else { payloadValue = "-" + SQLiPayloadManager.randomInt(); } // Launch again a simple payload with the changed value // then take it as the original one for boolean base checkings origMsg = sendPayload(parameter, payloadValue, true); if (origMsg == null) { // Probably a Circular Exception occurred // exit the plugin return; } break; case SQLiPayloadManager.WHERE_REPLACE: payloadValue = ""; break; default: // Act as original value need to be set payloadValue = value; } // Hint from ZAP TestSQLInjection active plugin: // Since the previous checks are attempting SQL injection, // and may have actually succeeded in modifying the database (ask me how I // know?!) // then we cannot rely on the database contents being the same as when the // original // query was last run (could be hours ago) // so re-run the query again now at this point. // Here is the best place to do it... // sendAndReceive(origMsg); // Forge request payload by prepending with boundary's // prefix and appending the boundary's suffix to the // test's ' <payload><comment> ' string reqPayload = prepareCleanPayload(test.getRequest().getPayload(), payloadValue); reqPayload = preparePrefix(reqPayload, currentPrefix, where, test); reqPayload = prepareSuffix(reqPayload, currentComment, currentSuffix, where); // Now prefix the parameter value reqPayload = payloadValue + reqPayload; // Perform the test's request and check whether or not the // payload was successful // Parse test's <response> if (test.getResponse() != null) { // prepare string diff matcher // cleaned by reflective values // and according to the replacement // logic set by the plugin content = origMsg.getResponseBody().toString(); content = SQLiPayloadManager.removeReflectiveValues(content, payloadValue); responseMatcher.setOriginalResponse(content); responseMatcher.setLogic(where); // ----------------------------------------------- // Check 1: Boolean-based blind SQL injection // ----------------------------------------------- // use diffs ratio between true/false page content // results against the original page or extract // elements to check differences into // ----------------------------------------------- if (test.getResponse().getComparison() != null) { // Generate payload used for comparison cmpPayload = prepareCleanPayload(test.getResponse().getComparison(), payloadValue); // Forge response payload by prepending with // boundary's prefix and appending the boundary's // suffix to the test's ' <payload><comment> ' // string cmpPayload = preparePrefix(cmpPayload, currentPrefix, where, test); cmpPayload = prepareSuffix(cmpPayload, currentComment, currentSuffix, where); // Now prefix the parameter value cmpPayload = payloadValue + cmpPayload; // Send False payload // Useful to set first matchRatio on // the False response content tempMsg = sendPayload(parameter, cmpPayload, true); if (tempMsg == null) { // Probably a Circular Exception occurred // exit the plugin return; } content = tempMsg.getResponseBody().toString(); content = SQLiPayloadManager.removeReflectiveValues(content, cmpPayload); responseMatcher.setInjectedResponse(content); // set initial matchRatio responseMatcher.isComparable(); // Perform the test's True request tempMsg = sendPayload(parameter, reqPayload, true); if (tempMsg == null) { // Probably a Circular Exception occurred // exit the plugin return; } content = tempMsg.getResponseBody().toString(); content = SQLiPayloadManager.removeReflectiveValues(content, reqPayload); responseMatcher.setInjectedResponse(content); // Check if the TRUE response is equal or // at less strongly comparable respect to // the Original response value if (responseMatcher.isComparable()) { // Perform again the test's False request tempMsg = sendPayload(parameter, cmpPayload, true); if (tempMsg == null) { // Probably a Circular Exception occurred // exit the plugin return; } content = tempMsg.getResponseBody().toString(); content = SQLiPayloadManager.removeReflectiveValues(content, cmpPayload); responseMatcher.setInjectedResponse(content); // Now check if the FALSE response is // completely different from the // Original response according to the // responseMatcher ratio criteria if (!responseMatcher.isComparable()) { // We Found IT! // Now create the alert message String info = Constant.messages.getString( ALERT_MESSAGE_PREFIX + "info.booleanbased", reqPayload, cmpPayload); // Do logging if (log.isDebugEnabled()) { log.debug("[BOOLEAN-BASED Injection Found] " + title + " with payload [" + reqPayload + "] on parameter '" + parameter + "'"); } // Alert the vulnerability to the main core raiseAlert(title, parameter, reqPayload, info, tempMsg); // Close the boundary/where iteration injectable = true; } /* if not injectable and not any((conf.string, conf.notString, conf.regexp)) and kb.pageStable: trueSet = set(extractTextTagContent(truePage)) falseSet = set(extractTextTagContent(falsePage)) candidates = filter(None, (_.strip() if _.strip() in (kb.pageTemplate or "") and _.strip() not in falsePage else None for _ in (trueSet - falseSet))) if candidates: conf.string = random.sample(candidates, 1)[0] infoMsg = "%s parameter '%s' seems to be '%s' injectable (with --string=\"%s\")" % (place, parameter, title, repr(conf.string).lstrip('u').strip("'")) logger.info(infoMsg) */ } // ----------------------------------------------- // Check 2: Error-based SQL injection // ----------------------------------------------- // try error based check sending a specific payload // and verifying if it should return back inside // the response content // ----------------------------------------------- } else if (test.getResponse().getGrep() != null) { // Perform the test's request and grep the response // body for the test's <grep> regular expression tempMsg = sendPayload(parameter, reqPayload, true); if (tempMsg == null) { // Probably a Circular Exception occurred // exit the plugin return; } // Get the payload that need to be checked // inside the response content String checkString = prepareCleanPayload(test.getResponse().getGrep(), payloadValue); Pattern checkPattern = Pattern.compile(checkString, Pattern.DOTALL | Pattern.CASE_INSENSITIVE); String output = null; // Remove reflective values to avoid false positives content = tempMsg.getResponseBody().toString(); content = SQLiPayloadManager.removeReflectiveValues(content, reqPayload); // Find the checkString inside page and headers Matcher matcher = checkPattern.matcher(content); if (matcher.find()) { output = matcher.group("result"); } else { matcher = checkPattern.matcher(tempMsg.getResponseHeader().toString()); if (matcher.find()) { output = matcher.group("result"); } } // Useless because we follow redirects!!! // -- // extractRegexResult(check, threadData.lastRedirectMsg[1] \ // if threadData.lastRedirectMsg and threadData.lastRedirectMsg[0] == \ // threadData.lastRequestUID else None, re.DOTALL | re.IGNORECASE) // Verify if the response extracted content // contains the evaluated expression // (which should be the value "1") if ((output != null) && output.equals("1")) { // We Found IT! // Now create the alert message String info = Constant.messages.getString(ALERT_MESSAGE_PREFIX + "info.errorbased", currentDbms.getName(), checkString); // Do logging if (log.isDebugEnabled()) { log.debug("[ERROR-BASED Injection Found] " + title + " with payload [" + reqPayload + "] on parameter '" + parameter + "'"); } raiseAlert(title, parameter, reqPayload, info, tempMsg); // Close the boundary/where iteration injectable = true; } // ----------------------------------------------- // Check 3: Time-based Blind or Stacked Queries // ----------------------------------------------- // Check for the sleep() execution according to // a collection of MIN_TIME_RESPONSES requestTime // It uses deviations and average for the real // delay checking. // 99.9999999997440% of all non time-based SQL injection affected // response times should be inside +-7*stdev([normal response times]) // Math reference: http://www.answers.com/topic/standard-deviation // ----------------------------------------------- } else if (test.getResponse().getTime() != null) { // First check if we have enough sample for the test if (responseTimes.size() < MIN_TIME_RESPONSES) { // We need some dummy requests to have a correct // deviation model for this page log.warn("Time-based comparison needs larger statistical model: " + "making a few dummy requests"); do { tempMsg = sendPayload(null, null, true); if (tempMsg == null) { // Probably a Circular Exception occurred // exit the plugin return; } } while (responseTimes.size() < MIN_TIME_RESPONSES); } // OK now we can get the deviation of the // request computation time for this page double lowerLimit = timeSec * 1000; double deviation = getResponseTimeDeviation(); // Minimum response time that can be even considered as delayed // MIN_VALID_DELAYED_RESPONSE = 0.5secs // lowerLimit = Math.max(MIN_VALID_DELAYED_RESPONSE, lowerLimit); // Get the maximum value to avoid false positives related // to slow pages that can take an average time // worse than the timeSec waiting period if (deviation >= 0) { lowerLimit = Math.max(lowerLimit, getResponseTimeAverage() + TIME_STDEV_COEFF * deviation); } // Perform the test's request reqPayload = setDelayValue(reqPayload); tempMsg = sendPayload(parameter, reqPayload, false); if (tempMsg == null) { // Probably a Circular Exception occurred // exit the plugin return; } // Check if enough time has passed if (lastResponseTime >= lowerLimit) { // Confirm again test's results tempMsg = sendPayload(parameter, reqPayload, false); if (tempMsg == null) { // Probably a Circular Exception occurred // exit the plugin return; } // Check if enough time has passed if (lastResponseTime >= lowerLimit) { // We Found IT! // Now create the alert message String info = Constant.messages.getString( ALERT_MESSAGE_PREFIX + "info.timebased", reqPayload, lastResponseTime, payloadValue, getResponseTimeAverage()); // Do logging if (log.isDebugEnabled()) { log.debug("[TIME-BASED Injection Found] " + title + " with payload [" + reqPayload + "] on parameter '" + parameter + "'"); } raiseAlert(title, parameter, reqPayload, info, tempMsg); // Close the boundary/where iteration injectable = true; } } // ----------------------------------------------- // Check 4: UNION preparePrefix SQL injection // ----------------------------------------------- // Test for UNION injection and set the sample // payload as well as the vector. // NOTE: vector is set to a tuple with 6 elements, // used afterwards by Agent.forgeUnionQuery() // method to forge the UNION preparePrefix payload // ----------------------------------------------- } else if (test.getResponse().isUnion()) { /* if not Backend.getIdentifiedDbms(): warnMsg = "using unescaped version of the test " warnMsg += "because of zero knowledge of the " warnMsg += "back-end DBMS. You can try to " warnMsg += "explicitly set it using option '--dbms'" singleTimeWarnMessage(warnMsg) if unionExtended: infoMsg = "automatically extending ranges " infoMsg += "for UNION query injection technique tests as " infoMsg += "there is at least one other potential " infoMsg += "injection technique found" singleTimeLogMessage(infoMsg) */ // Test for UNION query SQL injection // use a specific engine containing // all specific query constructors SQLiUnionEngine engine = new SQLiUnionEngine(this); engine.setTest(test); engine.setUnionChars(uChars); engine.setUnionColsStart(uColsStart); engine.setUnionColsStop(uColsStop); engine.setPrefix(currentPrefix); engine.setSuffix(currentSuffix); engine.setComment(currentComment); engine.setDbms(currentDbms); engine.setParamName(parameter); engine.setParamValue(payloadValue); // Use the engine to search for // Union-based and OrderBy-based SQli if (engine.isUnionPayloadExploitable()) { // We Found IT! // Now create the alert message String info = Constant.messages.getString(ALERT_MESSAGE_PREFIX + "info.unionbased", currentDbms.getName(), engine.getExploitColumnsCount()); // Do logging if (log.isDebugEnabled()) { log.debug("[UNION-BASED Injection Found] " + title + " with payload [" + reqPayload + "] on parameter '" + parameter + "'"); } // Alert the vulnerability to the main core raiseAlert(title, parameter, engine.getExploitPayload(), info, engine.getExploitMessage()); // Close the boundary/where iteration injectable = true; } } } // If the injection test was successful feed the injection // object with the test's details // if injection: // injection = checkFalsePositives(injection) // if injection: // checkSuhoshinPatch(injection) // There is no need to perform this test for other // <where> tags if (injectable) { break; } // Check if the scan has been stopped // if yes dispose resources and exit if (isStop()) { // Dispose all resources // Exit the plugin return; } } // If injectable skip other boundary checks if (injectable) { injectableTechniques |= 1 << test.getStype(); break; } } } // check if the parameter is not injectable if (injectableTechniques == 0 && log.isDebugEnabled()) { log.debug("Parameter '" + parameter + "' is not injectable"); } }