Example usage for java.util.regex Pattern toString

List of usage examples for java.util.regex Pattern toString

Introduction

In this page you can find the example usage for java.util.regex Pattern toString.

Prototype

public String toString() 

Source Link

Document

Returns the string representation of this pattern.

Usage

From source file:org.zaproxy.zap.extension.fuzz.httpfuzzer.ui.HttpFuzzerResultsTableModel.java

public List<SearchResult> search(Pattern pattern, boolean inverse, int max) {
    List<SearchResult> searchResults = new ArrayList<>();

    Matcher matcher;/* w w w  . j  a v a  2  s. c  o  m*/
    int rowCount = getRowCount();
    int matches = 0;
    // Start at 1 to skip the original message
    for (int i = 1; i < rowCount; i++) {
        if (max > 0 && matches >= max) {
            break;
        }

        HistoryReference historyReference = getEntry(i).getHistoryReference();
        try {
            HttpMessage msg = historyReference.getHttpMessage();
            if (inverse) {
                // Check for no matches in either Response Header or Body
                if (!pattern.matcher(msg.getResponseHeader().toString()).find()
                        && !pattern.matcher(msg.getResponseBody().toString()).find()) {
                    searchResults.add(createSearchResult(pattern.toString(), "", msg,
                            SearchMatch.Location.RESPONSE_HEAD, 0, 0));
                    matches++;
                }
            } else {
                // Response header
                matcher = pattern.matcher(msg.getResponseHeader().toString());
                while (matcher.find() && !(max > 0 && matches >= max)) {
                    searchResults.add(createSearchResult(pattern.toString(), matcher.group(), msg,
                            SearchMatch.Location.RESPONSE_HEAD, matcher.start(), matcher.end()));
                    matches++;
                }
                // Response body
                matcher = pattern.matcher(msg.getResponseBody().toString());
                while (matcher.find() && !(max > 0 && matches >= max)) {
                    searchResults.add(createSearchResult(pattern.toString(), matcher.group(), msg,
                            SearchMatch.Location.RESPONSE_BODY, matcher.start(), matcher.end()));
                    matches++;
                }
            }
        } catch (HttpMalformedHeaderException | DatabaseException e) {
            logger.error(e.getMessage(), e);
        }
    }
    return searchResults;
}

From source file:org.apache.hadoop.hbase.thrift2.client.ThriftAdmin.java

@Override
public List<TableDescriptor> listTableDescriptors(Pattern pattern, boolean includeSysTables)
        throws IOException {
    try {//from w w w . ja  v a 2s .  c om
        String regex = (pattern == null ? null : pattern.toString());
        List<TTableDescriptor> tTableDescriptors = client.getTableDescriptorsByPattern(regex, includeSysTables);
        return ThriftUtilities.tableDescriptorsFromThrift(tTableDescriptors);

    } catch (TException e) {
        throw new IOException(e);
    }
}

From source file:org.apache.hadoop.hive.metastore.MetaStoreUtils.java

public static void validatePartitionNameCharacters(List<String> partVals, Pattern partitionValidationPattern)
        throws MetaException {

    String invalidPartitionVal = HiveStringUtils.getPartitionValWithInvalidCharacter(partVals,
            partitionValidationPattern);
    if (invalidPartitionVal != null) {
        throw new MetaException("Partition value '" + invalidPartitionVal + "' contains a character "
                + "not matched by whitelist pattern '" + partitionValidationPattern.toString() + "'.  "
                + "(configure with " + HiveConf.ConfVars.METASTORE_PARTITION_NAME_WHITELIST_PATTERN.varname
                + ")");
    }//from   ww  w  .  j  a v  a 2  s .co  m
}

From source file:org.zaproxy.zap.extension.multiFuzz.impl.http.HttpFuzzerContentPanel.java

public List<SearchResult> searchResults(Pattern pattern, boolean inverse) {
    List<SearchResult> results = new ArrayList<>();

    if (resultsModel == null) {
        return results;
    }// ww w .j a  v  a  2  s.  c om

    Iterator<HttpFuzzRequestRecord> it = resultsModel.getHistoryReferences().iterator();
    Matcher matcher;
    while (it.hasNext()) {
        HistoryReference historyReference = it.next().getHistory();
        try {
            HttpMessage msg = historyReference.getHttpMessage();
            if (msg != null) {
                if (msg.getRequestHeader() != null) {
                    matcher = pattern.matcher(msg.getResponseHeader().toString());
                    if (inverse) {
                        if (!matcher.find()) {
                            results.add(
                                    new SearchResult(msg, ExtensionSearch.Type.Fuzz, pattern.toString(), ""));
                        }
                    } else {
                        while (matcher.find()) {
                            results.add(new SearchResult(ExtensionSearch.Type.Fuzz, pattern.toString(),
                                    matcher.group(), new SearchMatch(msg, SearchMatch.Location.RESPONSE_HEAD,
                                            matcher.start(), matcher.end())));
                        }
                    }
                }
                if (msg.getRequestBody() != null) {
                    matcher = pattern.matcher(msg.getResponseBody().toString());
                    if (inverse) {
                        if (!matcher.find()) {
                            results.add(
                                    new SearchResult(msg, ExtensionSearch.Type.Fuzz, pattern.toString(), ""));
                        }
                    } else {
                        while (matcher.find()) {
                            results.add(new SearchResult(ExtensionSearch.Type.Fuzz, pattern.toString(),
                                    matcher.group(), new SearchMatch(msg, SearchMatch.Location.RESPONSE_BODY,
                                            matcher.start(), matcher.end())));
                        }
                    }
                }
            }
        } catch (HttpMalformedHeaderException e) {
            logger.error(e.getMessage(), e);
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
        }
    }
    return results;
}

From source file:org.mobicents.servlet.restcomm.provisioning.number.bandwidth.BandwidthNumberProvisioningManager.java

private String buildSearchUri(PhoneNumberSearchFilters filters) throws URISyntaxException {
    Pattern filterPattern = filters.getFilterPattern();

    URIBuilder builder = new URIBuilder(this.uri);
    builder.setPath("/v1.0/accounts/" + this.accountId + "/availableNumbers");

    //Local number type search
    if (filters.getPhoneNumberTypeSearch().equals(PhoneNumberType.Local)) {
        if (!StringUtils.isEmpty(filters.getAreaCode())) {
            builder.addParameter("areaCode", filters.getAreaCode());
        }//from w  w w .j a va  2 s  .  c  o m
        if (!StringUtils.isEmpty(filters.getInLata())) {
            builder.addParameter("lata", filters.getInLata());
        }
        if (!StringUtils.isEmpty(filters.getInPostalCode())) {
            builder.addParameter("zip", filters.getInPostalCode());
        }
        if (!StringUtils.isEmpty(filters.getInRateCenter())) {
            builder.addParameter("rateCenter", filters.getInRateCenter());
            builder.addParameter("state", filters.getInRegion());
        }
        builder.addParameter("enableTNDetail", String.valueOf(true));

    } else if (filters.getPhoneNumberTypeSearch().equals(PhoneNumberType.TollFree)) {
        //Make some assumptions for the user
        if (filterPattern == null || StringUtils.isEmpty(filterPattern.toString())) {
            builder.addParameter("tollFreeWildCardPattern", "8**");
        } else {
            if (filterPattern.toString().contains("*")) {
                builder.addParameter("tollFreeWildCardPattern", filterPattern.toString());
            } else {
                builder.addParameter("tollFreeVanity", filterPattern.toString());
            }
        }

    } else {
        logger.error("Phone Number Type: " + filters.getPhoneNumberTypeSearch().name() + " is not supported");
    }
    builder.addParameter("quantity", String.valueOf(filters.getRangeSize() == -1 ? 5 : filters.getRangeSize()));
    if (logger.isDebugEnabled()) {
        logger.debug("building uri: " + builder.build().toString());
    }
    return builder.build().toString();
}

From source file:org.opennms.ng.dao.support.DefaultResourceDao.java

/**
 * Fetch a specific resource by string ID.
 * @return Resource or null if resource cannot be found.
 * @throws IllegalArgumentException When the resource ID string does not match the expected regex pattern
 * @throws org.springframework.orm.ObjectRetrievalFailureException If any exceptions are thrown while searching for the resource
 *//*from w  w w .  j a  va 2 s  .co m*/
@Override
public OnmsResource getResourceById(String id) {
    OnmsResource resource = null;

    Pattern p = Pattern.compile("([^\\[]+)\\[([^\\]]*)\\](?:\\.|$)");
    Matcher m = p.matcher(id);
    StringBuffer sb = new StringBuffer();

    while (m.find()) {
        String resourceTypeName = DefaultResourceDao.decode(m.group(1));
        String resourceName = DefaultResourceDao.decode(m.group(2));

        try {
            if (resource == null) {
                resource = getTopLevelResource(resourceTypeName, resourceName);
            } else {
                resource = getChildResource(resource, resourceTypeName, resourceName);
            }
        } catch (Throwable e) {
            LOG.warn("Could not get resource for resource ID \"{}\"", id, e);
            return null;
        }

        m.appendReplacement(sb, "");
    }

    m.appendTail(sb);

    if (sb.length() > 0) {
        LOG.warn("resource ID '{}' does not match pattern '{}' at '{}'", id, p.toString(), sb);
        return null;
    } else {
        return resource;
    }
}

From source file:com.becapps.easydownloader.ShareActivity.java

private String urlBlockMatchAndDecode(String content) {

    if (asyncDownload.isCancelled()) {
        Utils.logger("d", "asyncDownload cancelled @ urlBlockMatchAndDecode begin", DEBUG_TAG);
        return "Cancelled!";
    }//from  ww w  .  j  a  v  a  2 s  .c  o  m

    findVideoFilenameBase(content);

    Pattern pattern = Pattern.compile("url_encoded_fmt_stream_map\\\": \\\"(.*?)\\\"");
    Matcher matcher = pattern.matcher(content);
    if (matcher.find()) {
        Pattern blockPattern = Pattern.compile(",");
        Matcher blockMatcher = blockPattern.matcher(matcher.group(1));
        if (blockMatcher.find() && !asyncDownload.isCancelled()) {
            String[] CQS = matcher.group(1).split(blockPattern.toString());
            count = (CQS.length - 1);
            Utils.logger("d", "number of entries found: " + count, DEBUG_TAG);
            int index = 0;
            progressBar1.setIndeterminate(false);
            while ((index + 1) < CQS.length) {
                try {
                    CQS[index] = URLDecoder.decode(CQS[index], "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    Log.e(DEBUG_TAG, e.getMessage());
                }

                asyncDownload.doProgress((int) ((index / (float) count) * 100));

                codecMatcher(CQS[index], index);
                qualityMatcher(CQS[index], index);
                stereoMatcher(CQS[index], index);
                linkComposer(CQS[index], index);
                Utils.logger("v", "block " + index + ": " + CQS[index], DEBUG_TAG);
                index++;
            }
            listEntriesBuilder();
        } else {
            Utils.logger("d", "asyncDownload cancelled @ 'findCodecAndQualityAndLinks' match", DEBUG_TAG);
        }

        /*
        Utils.createLogFile(sdcard, "ytd_links.txt", Arrays.toString(links.toArray()));
        Utils.createLogFile(sdcard, "ytd_codecs.txt", Arrays.toString(codecs.toArray()));
        Utils.createLogFile(sdcard, "ytd_qualities.txt", Arrays.toString(qualities.toArray()));
        */

        return "Match!";
    } else {
        return "No Match";
    }
}

From source file:org.opennms.ng.dao.support.DefaultResourceDao.java

/**
 * Fetch a specific list of resources by string ID.
 * @return Resources or null if resources cannot be found.
 * @throws IllegalArgumentException When the resource ID string does not match the expected regex pattern
 * @throws org.springframework.orm.ObjectRetrievalFailureException If any exceptions are thrown while searching for the resource
 *//* w  w  w  .  j a  va2 s.c o m*/
@Override
public List<OnmsResource> getResourceListById(String id)
        throws IllegalArgumentException, ObjectRetrievalFailureException {
    OnmsResource topLevelResource = null;

    Pattern p = Pattern.compile("([^\\[]+)\\[([^\\]]*)\\](?:\\.|$)");
    Matcher m = p.matcher(id);
    StringBuffer sb = new StringBuffer();

    while (m.find()) {
        String resourceTypeName = DefaultResourceDao.decode(m.group(1));
        String resourceName = DefaultResourceDao.decode(m.group(2));

        try {
            if (topLevelResource == null) {
                topLevelResource = getTopLevelResource(resourceTypeName, resourceName);
            } else {
                return getChildResourceList(topLevelResource);
            }
        } catch (Throwable e) {
            throw new ObjectRetrievalFailureException(OnmsResource.class, id,
                    "Could not get resource for resource ID '" + id + "'", e);
        }

        m.appendReplacement(sb, "");
    }

    m.appendTail(sb);

    if (sb.length() > 0) {
        throw new IllegalArgumentException(
                "resource ID '" + id + "' does not match pattern '" + p.toString() + "' at '" + sb + "'");
    }
    return null;
}

From source file:org.zaproxy.zap.extension.ascanrulesAlpha.SQLInjectionSQLite.java

/**
 * scans for SQL Injection vulnerabilities, using SQLite specific syntax. If it doesn't use
 * specifically SQLite syntax, it does not belong in here, but in TestSQLInjection
 */// w  w  w .j  a v  a  2  s .c  o  m
@Override
public void scan(HttpMessage originalMessage, String paramName, String originalParamValue) {

    try {
        // the original message passed to us never has the response populated. fix that by
        // re-retrieving it..
        sendAndReceive(originalMessage, false); // do not follow redirects

        // Do time based SQL injection checks..
        // Timing Baseline check: we need to get the time that it took the original query, to
        // know if the time based check is working correctly..
        HttpMessage msgTimeBaseline = getNewMsg();
        long originalTimeStarted = System.currentTimeMillis();
        try {
            sendAndReceive(msgTimeBaseline);
        } catch (java.net.SocketTimeoutException e) {
            // to be expected occasionally, if the base query was one that contains some
            // parameters exploiting time based SQL injection?
            if (this.debugEnabled)
                log.debug("The Base Time Check timed out on [" + msgTimeBaseline.getRequestHeader().getMethod()
                        + "] URL [" + msgTimeBaseline.getRequestHeader().getURI().getURI() + "]");
        }
        long originalTimeUsed = System.currentTimeMillis() - originalTimeStarted;
        // if the time was very slow (because JSP was being compiled on first call, for
        // instance)
        // then the rest of the time based logic will fail.  Lets double-check for that scenario
        // by requesting the url again.
        // If it comes back in a more reasonable time, we will use that time instead as our
        // baseline.  If it come out in a slow fashion again,
        // we will abort the check on this URL, since we will only spend lots of time trying
        // request, when we will (very likely) not get positive results.
        if (originalTimeUsed > 5000) {
            long originalTimeStarted2 = System.currentTimeMillis();
            try {
                sendAndReceive(msgTimeBaseline);
            } catch (java.net.SocketTimeoutException e) {
                // to be expected occasionally, if the base query was one that contains some
                // parameters exploiting time based SQL injection?
                if (this.debugEnabled)
                    log.debug(
                            "Base Time Check 2 timed out on [" + msgTimeBaseline.getRequestHeader().getMethod()
                                    + "] URL [" + msgTimeBaseline.getRequestHeader().getURI().getURI() + "]");
            }
            long originalTimeUsed2 = System.currentTimeMillis() - originalTimeStarted2;
            if (originalTimeUsed2 > 5000) {
                // no better the second time around.  we need to bale out.
                if (this.debugEnabled)
                    log.debug("Both base time checks 1 and 2 for ["
                            + msgTimeBaseline.getRequestHeader().getMethod() + "] URL ["
                            + msgTimeBaseline.getRequestHeader().getURI().getURI()
                            + "] are way too slow to be usable for the purposes of checking for time based SQL Injection checking.  We are aborting the check on this particular url.");
                return;
            } else {
                // phew.  the second time came in within the limits. use the later timing
                // details as the base time for the checks.
                originalTimeUsed = originalTimeUsed2;
                originalTimeStarted = originalTimeStarted2;
            }
        }
        // end of timing baseline check

        int countTimeBasedRequests = 0;
        if (this.debugEnabled)
            log.debug("Scanning URL [" + getBaseMsg().getRequestHeader().getMethod() + "] ["
                    + getBaseMsg().getRequestHeader().getURI() + "], [" + paramName + "] with value ["
                    + originalParamValue + "] for SQL Injection");

        // SQLite specific time-based SQL injection checks
        boolean foundTimeBased = false;
        for (int timeBasedSQLindex = 0; timeBasedSQLindex < SQL_SQLITE_TIME_REPLACEMENTS.length && doTimeBased
                && countTimeBasedRequests < doTimeMaxRequests && !foundTimeBased; timeBasedSQLindex++) {
            // since we have no means to create a deterministic delay in SQLite, we need to take
            // a different approach:
            // in each iteration, increase the number of random blobs for SQLite to create.  If
            // we can detect an increasing delay, we know
            // that the payload has been successfully injected.
            int numberOfSequentialIncreases = 0;
            String detectableDelayParameter = null;
            long detectableDelay = 0;
            String maxDelayParameter = null;
            long maxDelay = 0;
            HttpMessage detectableDelayMessage = null;
            long previousDelay = originalTimeUsed;
            boolean potentialTimeBasedSQLInjection = false;
            boolean timeExceeded = false;

            for (long numBlobsToCreate = minBlobBytes; numBlobsToCreate <= this.maxBlobBytes && !timeExceeded
                    && numberOfSequentialIncreases < incrementalDelayIncreasesForAlert; numBlobsToCreate *= 10) {

                HttpMessage msgDelay = getNewMsg();
                String newTimeBasedInjectionValue = SQL_SQLITE_TIME_REPLACEMENTS[timeBasedSQLindex]
                        .replace("<<<<ORIGINALVALUE>>>>", originalParamValue);
                newTimeBasedInjectionValue = newTimeBasedInjectionValue.replace("<<<<NUMBLOBBYTES>>>>",
                        Long.toString(numBlobsToCreate));
                setParameter(msgDelay, paramName, newTimeBasedInjectionValue);

                if (this.debugEnabled)
                    log.debug("\nTrying '" + newTimeBasedInjectionValue
                            + "'. The number of Sequential Increases already is "
                            + numberOfSequentialIncreases);

                // send it.
                long modifiedTimeStarted = System.currentTimeMillis();
                try {
                    sendAndReceive(msgDelay);
                    countTimeBasedRequests++;
                } catch (java.net.SocketTimeoutException e) {
                    // to be expected occasionally, if the contains some parameters exploiting
                    // time based SQL injection
                    if (this.debugEnabled)
                        log.debug("The time check query timed out on ["
                                + msgTimeBaseline.getRequestHeader().getMethod() + "] URL ["
                                + msgTimeBaseline.getRequestHeader().getURI().getURI() + "] on field: ["
                                + paramName + "]");
                }
                long modifiedTimeUsed = System.currentTimeMillis() - modifiedTimeStarted;

                // before we do the time based checking, first check for a known error message
                // from the atatck, indicating a SQL injection vuln
                for (Pattern errorMessagePattern : errorMessagePatterns) {
                    Matcher matcher = errorMessagePattern.matcher(msgDelay.getResponseBody().toString());
                    boolean errorFound = matcher.find();
                    if (errorFound) {
                        // Likely an error based SQL Injection. Raise it
                        String extraInfo = Constant.messages.getString(
                                "ascanalpha.sqlinjection.sqlite.alert.errorbased.extrainfo",
                                errorMessagePattern);
                        // raise the alert
                        bingo(Alert.RISK_HIGH, Alert.CONFIDENCE_MEDIUM, getName(), getDescription(),
                                getBaseMsg().getRequestHeader().getURI().getURI(), // url
                                paramName, newTimeBasedInjectionValue, extraInfo, getSolution(),
                                errorMessagePattern.toString(), this.getCweId(), this.getWascId(), msgDelay);

                        if (this.debugEnabled)
                            log.debug("A likely Error Based SQL Injection Vulnerability has been found with ["
                                    + msgDelay.getRequestHeader().getMethod() + "] URL ["
                                    + msgDelay.getRequestHeader().getURI().getURI() + "] on field: ["
                                    + paramName + "], by matching for pattern ["
                                    + errorMessagePattern.toString() + "]");
                        foundTimeBased = true; // yeah, I know. we found an error based, while looking
                        // for a time based. bale out anyways.
                        break; // out of the loop
                    }
                }
                // outta the time based loop..
                if (foundTimeBased)
                    break;

                // no error message detected from the time based attack.. continue looking for
                // time based injection point.

                // cap the time we will delay by to 10 seconds
                if (modifiedTimeUsed > 10000)
                    timeExceeded = true;

                boolean parseTimeEquivalent = false;
                if (modifiedTimeUsed > previousDelay) {
                    if (this.debugEnabled)
                        log.debug("The response time " + modifiedTimeUsed + " is > the previous response time "
                                + previousDelay);
                    // in order to rule out false positives due to the increasing SQL parse time
                    // for longer parameter values
                    // we send a random (alphanumeric only) string value of the same length as
                    // the attack parameter
                    // we expect the response time for the SQLi attack to be greater than or
                    // equal to the response time for
                    // the random alphanumeric string parameter
                    // if this is not the case, then we assume that the attack parameter is not
                    // a potential SQL injection causing payload.
                    HttpMessage msgParseDelay = getNewMsg();
                    String parseDelayCheckParameter = RandomStringUtils
                            .random(newTimeBasedInjectionValue.length(), RANDOM_PARAMETER_CHARS);
                    setParameter(msgParseDelay, paramName, parseDelayCheckParameter);
                    long parseDelayTimeStarted = System.currentTimeMillis();
                    sendAndReceive(msgParseDelay);
                    countTimeBasedRequests++;
                    long parseDelayTimeUsed = System.currentTimeMillis() - parseDelayTimeStarted;

                    // figure out if the attack delay and the (non-sql-injection) parse delay
                    // are within X ms of each other..
                    parseTimeEquivalent = (Math
                            .abs(modifiedTimeUsed - parseDelayTimeUsed) < this.parseDelayDifference);
                    if (this.debugEnabled)
                        log.debug("The parse time a random parameter of the same length is "
                                + parseDelayTimeUsed + ", so the attack and random parameter are "
                                + (parseTimeEquivalent ? "" : "NOT ")
                                + "equivalent (given the user defined attack threshold)");
                }

                if (modifiedTimeUsed > previousDelay && !parseTimeEquivalent) {

                    maxDelayParameter = newTimeBasedInjectionValue;
                    maxDelay = modifiedTimeUsed;

                    // potential for SQL injection, detectable with "numBlobsToCreate" random
                    // blobs being created..
                    numberOfSequentialIncreases++;
                    if (!potentialTimeBasedSQLInjection) {
                        if (log.isDebugEnabled())
                            log.debug("Setting the Detectable Delay parameter to '" + newTimeBasedInjectionValue
                                    + "'");
                        detectableDelayParameter = newTimeBasedInjectionValue;
                        detectableDelay = modifiedTimeUsed;
                        detectableDelayMessage = msgDelay;
                    }
                    potentialTimeBasedSQLInjection = true;
                } else {
                    // either no SQL injection, invalid SQL syntax, or timing difference is not
                    // detectable with "numBlobsToCreate" random blobs being created.
                    // keep trying with larger numbers of "numBlobsToCreate", since that's the
                    // thing we can most easily control and verify
                    // note also: if for some reason, an earlier attack with a smaller number of
                    // blobs indicated there might be a vulnerability
                    // then this case will rule that out if it was a fluke...
                    // the timing delay must keep increasing, as the number of blobs is
                    // increased.
                    potentialTimeBasedSQLInjection = false;
                    numberOfSequentialIncreases = 0;
                    detectableDelayParameter = null;
                    detectableDelay = 0;
                    detectableDelayMessage = null;
                    maxDelayParameter = null;
                    maxDelay = 0;
                    // do not break at this point, since we may simply need to keep increasing
                    // numBlobsToCreate to
                    // a point where we can detect the resulting delay
                }
                if (this.debugEnabled)
                    log.debug("Time Based SQL Injection test for " + numBlobsToCreate + " random blob bytes: ["
                            + newTimeBasedInjectionValue + "] on field: [" + paramName + "] with value ["
                            + newTimeBasedInjectionValue + "] took " + modifiedTimeUsed
                            + "ms, where the original took " + originalTimeUsed + "ms");
                previousDelay = modifiedTimeUsed;

                // bale out if we were asked nicely
                if (isStop()) {
                    if (this.debugEnabled)
                        log.debug("Stopping the scan due to a user request");
                    return;
                }
            } // end of for loop to increase the number of random blob bytes to create

            // the number of times that we could sequentially increase the delay by increasing
            // the "number of random blob bytes to create"
            // is the basis for the threshold of the alert.  In some cases, the user may want to
            // see a solid increase in delay
            // for say 4 or 5 iterations, in order to be confident the vulnerability exists.  In
            // other cases, the user may be happy with just 2 sequential increases...
            if (this.debugEnabled)
                log.debug("Number of sequential increases: " + numberOfSequentialIncreases);
            if (numberOfSequentialIncreases >= this.incrementalDelayIncreasesForAlert) {
                // Likely a SQL Injection. Raise it
                String extraInfo = Constant.messages.getString(
                        "ascanalpha.sqlinjection.sqlite.alert.timebased.extrainfo", detectableDelayParameter,
                        detectableDelay, maxDelayParameter, maxDelay, originalParamValue, originalTimeUsed);

                // raise the alert
                bingo(Alert.RISK_HIGH, Alert.CONFIDENCE_MEDIUM, getName(), getDescription(),
                        getBaseMsg().getRequestHeader().getURI().getURI(), // url
                        paramName, detectableDelayParameter, extraInfo, getSolution(),
                        extraInfo /*as evidence*/, this.getCweId(), this.getWascId(), detectableDelayMessage);

                if (this.debugEnabled)
                    log.debug("A likely Time Based SQL Injection Vulnerability has been found with ["
                            + detectableDelayMessage.getRequestHeader().getMethod() + "] URL ["
                            + detectableDelayMessage.getRequestHeader().getURI().getURI() + "] on field: ["
                            + paramName + "]");

                // outta the time based loop..
                foundTimeBased = true;
                break;
            } // the user-define threshold has been exceeded. raise it.

            // outta the time based loop..
            if (foundTimeBased)
                break;

            // bale out if we were asked nicely
            if (isStop()) {
                if (this.debugEnabled)
                    log.debug("Stopping the scan due to a user request");
                return;
            }
        } // for each time based SQL index
          // end of check for SQLite time based SQL Injection

        // TODO: fix this logic, cos it's broken already. it reports version 2.2 and 4.0..
        // (false positives ahoy)
        doUnionBased = false;

        // try to get the version of SQLite, using a UNION based SQL injection vulnerability
        // do this regardless of whether we already found a vulnerability using another
        // technique.
        if (doUnionBased) {
            int unionRequests = 0;
            // catch 3.0, 3.0.1, 3.0.1.1, 3.7.16.2, etc
            Pattern versionNumberPattern = Pattern.compile(
                    "[0-9]{1}\\.[0-9]{1,2}\\.[0-9]{1,2}\\.[0-9]{1,2}|[0-9]{1}\\.[0-9]{1,2}\\.[0-9]{1,2}|[0-9]{1}\\.[0-9]{1,2}",
                    PATTERN_PARAM);
            String candidateValues[] = { "", originalParamValue };
            // shonky break label. labels the loop to break out of.  I believe I just finished a
            // sentence with a preposition too. Oh My.
            unionLoops: for (String sqliteVersionFunction : SQLITE_VERSION_FUNCTIONS) {
                for (String statementTypeCloser : SYNTACTIC_PREVIOUS_STATEMENT_TYPE_CLOSERS) {
                    for (String statementClauseCloser : SYNTACTIC_PREVIOUS_STATEMENT_CLAUSE_CLOSERS) {
                        for (String unionAdditionalColms : UNION_ADDITIONAL_COLUMNS) {
                            for (String nextStatementCommenter : SYNTACTIC_NEXT_STATEMENT_COMMENTER) {
                                for (String statementUnionStatement : SYNTACTIC_UNION_STATEMENTS) {
                                    for (String value : candidateValues) {
                                        // are we out of lives yet?
                                        // TODO: fix so that the logic does not spin through the
                                        // loop headers to get out of all of the nested loops..
                                        // without using the shonky break to label logic
                                        if (unionRequests > doUnionMaxRequests) {
                                            break unionLoops;
                                        }
                                        ;

                                        String unionAttack = UNION_ATTACK_TEMPLATE;
                                        unionAttack = unionAttack.replace("<<<<SQLITE_VERSION_FUNCTION>>>>",
                                                sqliteVersionFunction);
                                        unionAttack = unionAttack.replace(
                                                "<<<<SYNTACTIC_PREVIOUS_STATEMENT_TYPE_CLOSER>>>>",
                                                statementTypeCloser);
                                        unionAttack = unionAttack.replace(
                                                "<<<<SYNTACTIC_PREVIOUS_STATEMENT_CLAUSE_CLOSER>>>>",
                                                statementClauseCloser);
                                        unionAttack = unionAttack.replace("<<<<UNIONADDITIONALCOLUMNS>>>>",
                                                unionAdditionalColms);
                                        unionAttack = unionAttack.replace(
                                                "<<<<SYNTACTIC_NEXT_STATEMENT_COMMENTER>>>>",
                                                nextStatementCommenter);
                                        unionAttack = unionAttack.replace("<<<<UNIONSTATEMENT>>>>",
                                                statementUnionStatement);
                                        unionAttack = unionAttack.replace("<<<<VALUE>>>>", value);

                                        if (log.isDebugEnabled())
                                            log.debug("About to try to determine the SQLite version with ["
                                                    + unionAttack + "]");
                                        HttpMessage unionAttackMessage = getNewMsg();
                                        setParameter(unionAttackMessage, paramName, unionAttack);
                                        sendAndReceive(unionAttackMessage);
                                        unionRequests++;

                                        // check the response for the version information..
                                        Matcher matcher = versionNumberPattern
                                                .matcher(unionAttackMessage.getResponseBody().toString());
                                        while (matcher.find()) {
                                            String versionNumber = matcher.group();
                                            Pattern actualVersionNumberPattern = Pattern
                                                    .compile("\\Q" + versionNumber + "\\E", PATTERN_PARAM);
                                            if (log.isDebugEnabled())
                                                log.debug("Found a candidate SQLite version number '"
                                                        + versionNumber
                                                        + "'. About to look for the absence of '"
                                                        + actualVersionNumberPattern
                                                        + "' in the (re-created) original response body (of length "
                                                        + originalMessage.getResponseBody().toString().length()
                                                        + ") to validate it");

                                            // if the version number was not in the original*
                                            // response, we will call it..
                                            Matcher matcherVersionInOriginal = actualVersionNumberPattern
                                                    .matcher(originalMessage.getResponseBody().toString());
                                            if (!matcherVersionInOriginal.find()) {
                                                // we have the SQLite version number..
                                                if (log.isDebugEnabled())
                                                    log.debug(
                                                            "We found SQLite version [" + versionNumber + "]");

                                                String extraInfo = Constant.messages.getString(
                                                        "ascanalpha.sqlinjection.sqlite.alert.versionnumber.extrainfo",
                                                        versionNumber);
                                                // raise the alert
                                                bingo(Alert.RISK_HIGH, Alert.CONFIDENCE_MEDIUM,
                                                        getName() + " - " + versionNumber, getDescription(),
                                                        getBaseMsg().getRequestHeader().getURI().getURI(), // url
                                                        paramName, unionAttack, extraInfo, getSolution(),
                                                        versionNumber /*as evidence*/, this.getCweId(),
                                                        this.getWascId(), unionAttackMessage);
                                                break unionLoops;
                                            }
                                        }
                                        // bale out if we were asked nicely
                                        if (isStop()) {
                                            if (this.debugEnabled)
                                                log.debug("Stopping the scan due to a user request");
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } // end of doUnionBased

    } catch (InvalidRedirectLocationException | UnknownHostException | URIException e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to send HTTP message, cause: " + e.getMessage());
        }
    } catch (Exception e) {
        // Do not try to internationalise this.. we need an error message in any event..
        // if it's in English, it's still better than not having it at all.
        log.error("An error occurred checking a url for SQLite SQL Injection vulnerabilities", e);
    }
}

From source file:org.zaproxy.zap.extension.ascanrulesBeta.LDAPInjection.java

/**
 *
 * @param message/*from ww w.  ja va2  s  .  c  o m*/
 * @param parameterType
 * @param parameterName
 * @return
 * @throws Exception
 */
private boolean checkResultsForLDAPAlert(HttpMessage message, /*String parameterType, */ String parameterName)
        throws Exception {
    //compare the request response with each of the known error messages, 
    //for each of the known LDAP implementations.
    //in order to minimise false positives, only consider a match 
    //for the error message in the response if the string also 
    //did NOT occur in the original (unmodified) response
    for (Pattern errorPattern : LDAP_ERRORS.keySet()) {

        //if the pattern was found in the new response, 
        //but not in the original response (for the unmodified request)
        //then we have a match.. LDAP injection!
        if (responseMatches(message, errorPattern) && !responseMatches(getBaseMsg(), errorPattern)) {

            //the HTML matches one of the known LDAP errors.
            //so raise the error, and move on to the next parameter

            String extraInfo = Constant.messages.getString("ascanbeta.ldapinjection.alert.extrainfo",
                    /*parameterType,*/
                    parameterName, getBaseMsg().getRequestHeader().getMethod(),
                    getBaseMsg().getRequestHeader().getURI().getURI(), errorAttack,
                    LDAP_ERRORS.get(errorPattern), errorPattern);

            String attack = Constant.messages.getString("ascanbeta.ldapinjection.alert.attack",
                    /*parameterType, */ parameterName, errorAttack);
            String vulnname = Constant.messages.getString("ascanbeta.ldapinjection.name");
            String vulndesc = Constant.messages.getString("ascanbeta.ldapinjection.desc");
            String vulnsoln = Constant.messages.getString("ascanbeta.ldapinjection.soln");

            //we know the LDAP implementation, so put it in the title, where it will be obvious.
            bingo(Alert.RISK_HIGH, Alert.WARNING, vulnname + " - " + LDAP_ERRORS.get(errorPattern), vulndesc,
                    getBaseMsg().getRequestHeader().getURI().getURI(), parameterName, attack, extraInfo,
                    vulnsoln, errorPattern.toString(), message); //use the attack message, rather than the original message.

            //and log it                
            String logMessage = Constant.messages.getString("ascanbeta.ldapinjection.alert.logmessage",
                    getBaseMsg().getRequestHeader().getMethod(),
                    getBaseMsg().getRequestHeader().getURI().getURI(),
                    /* parameterType, */
                    parameterName, errorAttack, LDAP_ERRORS.get(errorPattern), errorPattern);

            log.info(logMessage);

            return true; //threw an alert
        }

    } //for each error message for the given LDAP implemention

    return false; //did not throw an alert
}