Search in sources :

Example 26 with URIException

use of org.apache.commons.httpclient.URIException in project zaproxy by zaproxy.

the class Analyser method getPathRegex.

private String getPathRegex(URI uri) throws URIException {
    URI newUri;
    // ZAP: catch CloneNotSupportedException as introduced with version 3.1 of HttpClient
    try {
        newUri = (URI) uri.clone();
    } catch (CloneNotSupportedException e) {
        throw new URIException(e.getMessage());
    }
    String query = newUri.getQuery();
    StringBuilder sb = new StringBuilder(100);
    // case should be sensitive
    // sb.append("(?i)");
    newUri.setQuery(null);
    sb.append(newUri.toString().replaceAll("\\.", "\\."));
    if (query != null) {
        String queryPattern = "(\\?" + query + ")?";
        sb.append(queryPattern);
    }
    return sb.toString();
}
Also used : URIException(org.apache.commons.httpclient.URIException) URI(org.apache.commons.httpclient.URI)

Example 27 with URIException

use of org.apache.commons.httpclient.URIException in project zaproxy by zaproxy.

the class SiteNodeStringComparator method pollPath.

/**
 * Return the a HttpMessage of the same type under the tree path.
 *
 * @param msg
 * @return null = not found
 */
public synchronized HttpMessage pollPath(HttpMessage msg) {
    SiteNode resultNode = null;
    URI uri = msg.getRequestHeader().getURI();
    SiteNode parent = getRoot();
    String folder;
    try {
        String host = getHostName(uri);
        // no host yet
        parent = findChild(parent, host);
        if (parent == null) {
            return null;
        }
        List<String> path = SessionStructure.getTreePath(model, msg);
        if (path.isEmpty()) {
            // Its a top level node
            resultNode = parent;
        }
        for (int i = 0; i < path.size(); i++) {
            folder = path.get(i);
            if (folder != null && !folder.equals("")) {
                if (i == path.size() - 1) {
                    String leafName = SessionStructure.getLeafName(model, folder, msg);
                    resultNode = findChild(parent, leafName);
                } else {
                    parent = findChild(parent, folder);
                    if (parent == null) {
                        return null;
                    }
                }
            }
        }
    } catch (URIException e) {
        // ZAP: Added error
        log.error(e.getMessage(), e);
    }
    if (resultNode == null || resultNode.getHistoryReference() == null) {
        return null;
    }
    HttpMessage nodeMsg = null;
    try {
        nodeMsg = resultNode.getHistoryReference().getHttpMessage();
    } catch (Exception e) {
        // ZAP: Added error
        log.error(e.getMessage(), e);
    }
    return nodeMsg;
}
Also used : URIException(org.apache.commons.httpclient.URIException) HttpMessage(org.parosproxy.paros.network.HttpMessage) URI(org.apache.commons.httpclient.URI) URIException(org.apache.commons.httpclient.URIException) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) InvalidParameterException(java.security.InvalidParameterException) DatabaseException(org.parosproxy.paros.db.DatabaseException)

Example 28 with URIException

use of org.apache.commons.httpclient.URIException in project zaproxy by zaproxy.

the class SiteNodeStringComparator method findNode.

public synchronized SiteNode findNode(HttpMessage msg, boolean matchStructural) {
    if (Constant.isLowMemoryOptionSet()) {
        throw new InvalidParameterException("SiteMap should not be accessed when the low memory option is set");
    }
    if (msg == null) {
        return null;
    }
    SiteNode resultNode = null;
    URI uri = msg.getRequestHeader().getURI();
    SiteNode parent = getRoot();
    String folder = "";
    try {
        String host = getHostName(uri);
        // no host yet
        parent = findChild(parent, host);
        if (parent == null) {
            return null;
        }
        List<String> path = SessionStructure.getTreePath(model, msg);
        if (path.isEmpty()) {
            // Its a top level node
            resultNode = parent;
        }
        for (int i = 0; i < path.size(); i++) {
            folder = path.get(i);
            if (folder != null && !folder.equals("")) {
                if (i == path.size() - 1) {
                    if (matchStructural) {
                        resultNode = findChild(parent, folder);
                    } else {
                        String leafName = SessionStructure.getLeafName(model, folder, msg);
                        resultNode = findChild(parent, leafName);
                    }
                } else {
                    parent = findChild(parent, folder);
                    if (parent == null) {
                        return null;
                    }
                }
            }
        }
    } catch (URIException e) {
        log.error(e.getMessage(), e);
    }
    return resultNode;
}
Also used : InvalidParameterException(java.security.InvalidParameterException) URIException(org.apache.commons.httpclient.URIException) URI(org.apache.commons.httpclient.URI)

Example 29 with URIException

use of org.apache.commons.httpclient.URIException in project zaproxy by zaproxy.

the class AuthenticationMethod method isAuthenticated.

/**
 * Checks if the response received by the Http Message corresponds to an authenticated Web
 * Session.
 *
 * <p>If none of the indicators are set up, the method defaults to returning true, so that no
 * authentications are tried when there is no way to check authentication. A message is also
 * shown on the output console in this case.
 *
 * @param msg the http message
 * @param force always check even if the polling strategy is being used
 * @return true, if is authenticated or no indicators have been set, and false otherwise
 */
public boolean isAuthenticated(HttpMessage msg, User user, boolean force) {
    if (msg == null || user == null) {
        return false;
    }
    AuthenticationState authState = user.getAuthenticationState();
    // Assume logged in if nothing was set up
    if (loggedInIndicatorPattern == null && loggedOutIndicatorPattern == null) {
        try {
            Stats.incCounter(SessionStructure.getHostName(msg), AUTH_STATE_NO_INDICATOR_STATS);
        } catch (URIException e) {
        // Ignore
        }
        if (View.isInitialised()) {
            // Let the user know this
            View.getSingleton().getOutputPanel().append(Constant.messages.getString("authentication.output.indicatorsNotSet", msg.getRequestHeader().getURI()) + "\n");
        }
        return true;
    }
    HttpMessage msgToTest;
    switch(this.authCheckingStrategy) {
        case EACH_REQ:
        case EACH_REQ_RESP:
        case EACH_RESP:
            msgToTest = msg;
            break;
        case POLL_URL:
            if (!force && authState.getLastPollResult() != null && authState.getLastPollResult()) {
                // Check if we really need to poll the relevant URL again
                switch(pollFrequencyUnits) {
                    case SECONDS:
                        if ((System.currentTimeMillis() - authState.getLastPollTime()) / 1000 < pollFrequency) {
                            try {
                                Stats.incCounter(SessionStructure.getHostName(msg), AUTH_STATE_ASSUMED_IN_STATS);
                            } catch (URIException e) {
                            // Ignore
                            }
                            return true;
                        }
                        break;
                    case REQUESTS:
                    default:
                        if (authState.getRequestsSincePoll() < pollFrequency) {
                            authState.incRequestsSincePoll();
                            try {
                                Stats.incCounter(SessionStructure.getHostName(msg), AUTH_STATE_ASSUMED_IN_STATS);
                            } catch (URIException e) {
                            // Ignore
                            }
                            return true;
                        }
                        break;
                }
            }
            // Make the poll request
            try {
                HttpMessage pollMsg = pollAsUser(user);
                msgToTest = pollMsg;
            } catch (Exception e1) {
                LOGGER.warn("Failed sending poll request to " + this.getPollUrl(), e1);
                return false;
            }
            break;
        default:
            return false;
    }
    return evaluateAuthRequest(msgToTest, authState);
}
Also used : URIException(org.apache.commons.httpclient.URIException) HttpMessage(org.parosproxy.paros.network.HttpMessage) URIException(org.apache.commons.httpclient.URIException) IOException(java.io.IOException) AuthenticationState(org.zaproxy.zap.users.AuthenticationState)

Example 30 with URIException

use of org.apache.commons.httpclient.URIException in project openhab1-addons by openhab.

the class Connection method sendCommand.

/**
     * Send a command to the Particle REST API (convenience function).
     *
     * @param device
     *            the device context, or <code>null</code> if not needed for this command.
     * @param funcName
     *            the function name to call, or variable/field to retrieve if <code>command</code> is
     *            <code>null</code>.
     * @param user
     *            the user name to use in Basic Authentication if the funcName would require Basic Authentication.
     * @param pass
     *            the password to use in Basic Authentication if the funcName would require Basic Authentication.
     * @param command
     *            the command to send to the API.
     * @param proc
     *            a callback object that receives the status code and response body, or <code>null</code> if not
     *            needed.
     */
public void sendCommand(AbstractDevice device, String funcName, String user, String pass, String command, HttpResponseHandler proc) {
    String url = null;
    String httpMethod = null;
    String content = null;
    String contentType = null;
    Properties headers = new Properties();
    logger.trace("sendCommand: funcName={}", funcName);
    switch(funcName) {
        case "createToken":
            httpMethod = HTTP_POST;
            url = TOKEN_URL;
            content = command;
            contentType = APPLICATION_FORM_URLENCODED;
            break;
        case "deleteToken":
            httpMethod = HTTP_DELETE;
            url = String.format(ACCESS_TOKENS_URL, tokens.accessToken);
            break;
        case "getDevices":
            httpMethod = HTTP_GET;
            url = String.format(GET_DEVICES_URL, tokens.accessToken);
            break;
        default:
            url = String.format(DEVICE_FUNC_URL, device.getId(), funcName, tokens.accessToken);
            if (command == null) {
                // retrieve a variable
                httpMethod = HTTP_GET;
            } else {
                // call a function
                httpMethod = HTTP_POST;
                content = command;
                contentType = APPLICATION_JSON;
            }
            break;
    }
    HttpClient client = new HttpClient();
    if (!url.contains("access_token=")) {
        Credentials credentials = new UsernamePasswordCredentials(user, pass);
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }
    HttpMethod method = createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    for (String httpHeaderKey : headers.stringPropertyNames()) {
        method.addRequestHeader(new Header(httpHeaderKey, headers.getProperty(httpHeaderKey)));
        logger.trace("Header key={}, value={}", httpHeaderKey, headers.getProperty(httpHeaderKey));
    }
    try {
        // add content if a valid method is given ...
        if (method instanceof EntityEnclosingMethod && content != null) {
            EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
            eeMethod.setRequestEntity(new StringRequestEntity(content, contentType, null));
            logger.trace("content='{}', contentType='{}'", content, contentType);
        }
        if (logger.isDebugEnabled()) {
            try {
                logger.debug("About to execute '{}'", method.getURI());
            } catch (URIException e) {
                logger.debug(e.getMessage());
            }
        }
        int statusCode = client.executeMethod(method);
        if (statusCode >= HttpStatus.SC_BAD_REQUEST) {
            logger.debug("Method failed: " + method.getStatusLine());
        }
        String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.debug("Body of response: {}", responseBody);
        }
        if (proc != null) {
            proc.handleResponse(statusCode, responseBody);
        }
    } catch (HttpException he) {
        logger.warn("{}", he);
    } catch (IOException ioe) {
        logger.debug("{}", ioe);
    } finally {
        method.releaseConnection();
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) IOException(java.io.IOException) Properties(java.util.Properties) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) URIException(org.apache.commons.httpclient.URIException) Header(org.apache.commons.httpclient.Header) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Aggregations

URIException (org.apache.commons.httpclient.URIException)52 URI (org.apache.commons.httpclient.URI)31 IOException (java.io.IOException)9 HttpMethod (org.apache.commons.httpclient.HttpMethod)8 Header (org.apache.commons.httpclient.Header)7 HttpClient (org.apache.commons.httpclient.HttpClient)6 ArrayList (java.util.ArrayList)5 Matcher (java.util.regex.Matcher)5 EntityEnclosingMethod (org.apache.commons.httpclient.methods.EntityEnclosingMethod)5 GetMethod (org.apache.commons.httpclient.methods.GetMethod)5 DatabaseException (org.parosproxy.paros.db.DatabaseException)5 HttpMalformedHeaderException (org.parosproxy.paros.network.HttpMalformedHeaderException)4 BufferedReader (java.io.BufferedReader)3 File (java.io.File)3 InputStreamReader (java.io.InputStreamReader)3 PatternSyntaxException (java.util.regex.PatternSyntaxException)3 HttpException (org.apache.commons.httpclient.HttpException)3 HttpMessage (org.parosproxy.paros.network.HttpMessage)3 InvalidParameterException (java.security.InvalidParameterException)2 HashMap (java.util.HashMap)2