Search in sources :

Example 1 with SpnegoHttpURLConnection

use of net.sourceforge.spnego.SpnegoHttpURLConnection in project jsql-injection by ron190.

the class InjectionModel method inject.

/**
 * Run a HTTP connection to the web server.
 * @param dataInjection SQL query
 * @param responseHeader unused
 * @return source code of current page
 */
@Override
public String inject(String newDataInjection, boolean isUsingIndex) {
    // Temporary url, we go from "select 1,2,3,4..." to "select 1,([complex query]),2...", but keep initial url
    String urlInjection = ConnectionUtil.getUrlBase();
    String dataInjection = " " + newDataInjection;
    urlInjection = this.buildURL(urlInjection, isUsingIndex, dataInjection);
    // TODO merge into function
    urlInjection = urlInjection.trim().replaceAll("(?s)/\\*.*?\\*/", "").replaceAll("([^\\s\\w])(\\s+)", "$1").replaceAll("(\\s+)([^\\s\\w])", "$2").replaceAll("\\s+", "+");
    URL urlObject = null;
    try {
        urlObject = new URL(urlInjection);
    } catch (MalformedURLException e) {
        LOGGER.warn("Incorrect Query Url: " + e.getMessage(), e);
        return "";
    }
    // TODO Extract in method
    if (!ParameterUtil.getQueryString().isEmpty()) {
        // new params from <form> parsing, in that case add the '?' to URL
        if (!urlInjection.contains("?")) {
            urlInjection += "?";
        }
        urlInjection += this.buildQuery(MethodInjection.QUERY, ParameterUtil.getQueryStringAsString(), isUsingIndex, dataInjection);
        if (ConnectionUtil.getTokenCsrf() != null) {
            urlInjection += "&" + ConnectionUtil.getTokenCsrf().getKey() + "=" + ConnectionUtil.getTokenCsrf().getValue();
        }
        try {
            // Evasion
            if (this.stepSecurity == 1) {
                // Replace character '+'
                urlInjection = urlInjection.replaceAll("--\\+", "--").replaceAll("7330%2b1", "7331");
            } else if (this.stepSecurity == 2) {
                // Change case
                urlInjection = urlInjection.replaceAll("union\\+", "uNiOn+").replaceAll("select\\+", "sElEcT+").replaceAll("from\\+", "FrOm+").replaceAll("from\\(", "FrOm(").replaceAll("where\\+", "wHeRe+").replaceAll("([AE])=0x", "$1+lIkE+0x");
            } else if (this.stepSecurity == 3) {
                // Change Case and Space
                urlInjection = urlInjection.replaceAll("union\\+", "uNiOn/**/").replaceAll("select\\+", "sElEcT/**/").replaceAll("from\\+", "FrOm/**/").replaceAll("from\\(", "FrOm(").replaceAll("where\\+", "wHeRe/**/").replaceAll("([AE])=0x", "$1/**/lIkE/**/0x");
                urlInjection = urlInjection.replaceAll("--\\+", "--").replaceAll("\\+", "/**/");
            }
            urlObject = new URL(urlInjection);
        } catch (MalformedURLException e) {
            LOGGER.warn("Incorrect Evasion Url: " + e.getMessage(), e);
        }
    } else {
        if (ConnectionUtil.getTokenCsrf() != null) {
            urlInjection += "?" + ConnectionUtil.getTokenCsrf().getKey() + "=" + ConnectionUtil.getTokenCsrf().getValue();
        }
    }
    HttpURLConnection connection;
    String pageSource = "";
    // Define the connection
    try {
        // Block Opening Connection
        if (AuthenticationUtil.isKerberos()) {
            String kerberosConfiguration = Pattern.compile("(?s)\\{.*").matcher(StringUtils.join(Files.readAllLines(Paths.get(AuthenticationUtil.getPathKerberosLogin()), Charset.defaultCharset()), "")).replaceAll("").trim();
            SpnegoHttpURLConnection spnego = new SpnegoHttpURLConnection(kerberosConfiguration);
            connection = spnego.connect(urlObject);
        } else {
            connection = (HttpURLConnection) urlObject.openConnection();
        }
        connection.setReadTimeout(ConnectionUtil.getTimeout());
        connection.setConnectTimeout(ConnectionUtil.getTimeout());
        connection.setDefaultUseCaches(false);
        connection.setRequestProperty("Pragma", "no-cache");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setRequestProperty("Expires", "-1");
        if (ConnectionUtil.getTokenCsrf() != null) {
            connection.setRequestProperty(ConnectionUtil.getTokenCsrf().getKey(), ConnectionUtil.getTokenCsrf().getValue());
        }
        ConnectionUtil.fixJcifsTimeout(connection);
        Map<Header, Object> msgHeader = new EnumMap<>(Header.class);
        msgHeader.put(Header.URL, urlInjection);
        // TODO Extract in method
        if (!ParameterUtil.getHeader().isEmpty()) {
            Stream.of(this.buildQuery(MethodInjection.HEADER, ParameterUtil.getHeaderAsString(), isUsingIndex, dataInjection).split("\\\\r\\\\n")).forEach(e -> {
                if (e.split(":").length == 2) {
                    HeaderUtil.sanitizeHeaders(connection, new SimpleEntry<String, String>(e.split(":")[0], e.split(":")[1]));
                }
            });
            msgHeader.put(Header.HEADER, this.buildQuery(MethodInjection.HEADER, ParameterUtil.getHeaderAsString(), isUsingIndex, dataInjection));
        }
        // TODO Extract in method
        if (!ParameterUtil.getRequest().isEmpty() || ConnectionUtil.getTokenCsrf() != null) {
            try {
                ConnectionUtil.fixCustomRequestMethod(connection, ConnectionUtil.getTypeRequest());
                connection.setDoOutput(true);
                connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                DataOutputStream dataOut = new DataOutputStream(connection.getOutputStream());
                if (ConnectionUtil.getTokenCsrf() != null) {
                    dataOut.writeBytes(ConnectionUtil.getTokenCsrf().getKey() + "=" + ConnectionUtil.getTokenCsrf().getValue() + "&");
                }
                if (ConnectionUtil.getTypeRequest().matches("PUT|POST")) {
                    if (ParameterUtil.getRequestAsText().trim().matches("^<\\?xml.*")) {
                        dataOut.writeBytes(this.buildQuery(MethodInjection.REQUEST, ParameterUtil.getRequestAsText(), isUsingIndex, dataInjection));
                    } else {
                        dataOut.writeBytes(this.buildQuery(MethodInjection.REQUEST, ParameterUtil.getRequestAsString(), isUsingIndex, dataInjection));
                    }
                }
                dataOut.flush();
                dataOut.close();
                if (ParameterUtil.getRequestAsText().trim().matches("^<\\?xml.*")) {
                    msgHeader.put(Header.POST, this.buildQuery(MethodInjection.REQUEST, ParameterUtil.getRequestAsText(), isUsingIndex, dataInjection));
                } else {
                    msgHeader.put(Header.POST, this.buildQuery(MethodInjection.REQUEST, ParameterUtil.getRequestAsString(), isUsingIndex, dataInjection));
                }
            } catch (IOException e) {
                LOGGER.warn("Error during Request connection: " + e.getMessage(), e);
            }
        }
        msgHeader.put(Header.RESPONSE, HeaderUtil.getHttpHeaders(connection));
        try {
            pageSource = ConnectionUtil.getSource(connection);
        } catch (Exception e) {
            LOGGER.error(e, e);
        }
        // Calling connection.disconnect() is not required, further calls will follow
        msgHeader.put(Header.SOURCE, pageSource);
        // Inform the view about the log infos
        Request request = new Request();
        request.setMessage(Interaction.MESSAGE_HEADER);
        request.setParameters(msgHeader);
        this.sendToViews(request);
    } catch (// Exception for General and Spnego Opening Connection
    IOException | LoginException | GSSException | PrivilegedActionException e) {
        LOGGER.warn("Error during connection: " + e.getMessage(), e);
    }
    // return the source code of the page
    return pageSource;
}
Also used : MalformedURLException(java.net.MalformedURLException) PrivilegedActionException(java.security.PrivilegedActionException) DataOutputStream(java.io.DataOutputStream) SpnegoHttpURLConnection(net.sourceforge.spnego.SpnegoHttpURLConnection) Request(com.jsql.model.bean.util.Request) IOException(java.io.IOException) URL(java.net.URL) LoginException(javax.security.auth.login.LoginException) InjectionFailureException(com.jsql.model.exception.InjectionFailureException) JSONException(org.json.JSONException) JSqlException(com.jsql.model.exception.JSqlException) GSSException(org.ietf.jgss.GSSException) PrivilegedActionException(java.security.PrivilegedActionException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) HttpURLConnection(java.net.HttpURLConnection) SpnegoHttpURLConnection(net.sourceforge.spnego.SpnegoHttpURLConnection) Header(com.jsql.model.bean.util.Header) GSSException(org.ietf.jgss.GSSException) LoginException(javax.security.auth.login.LoginException) JSONObject(org.json.JSONObject) EnumMap(java.util.EnumMap)

Example 2 with SpnegoHttpURLConnection

use of net.sourceforge.spnego.SpnegoHttpURLConnection in project jsql-injection by ron190.

the class ConnectionUtil method testConnection.

/**
 * Check that the connection to the website is working correctly.
 * It uses authentication defined by user, with fixed timeout, and warn
 * user in case of authentication detected.
 * @throws InjectionFailureException when any error occurs during the connection
 */
public static void testConnection() throws InjectionFailureException {
    if (PreferencesUtil.isProcessingCookies()) {
        CookieManager cookieManager = new CookieManager();
        CookieHandler.setDefault(cookieManager);
    } else {
        CookieHandler.setDefault(null);
    }
    // Test the HTTP connection
    HttpURLConnection connection = null;
    try {
        if (AuthenticationUtil.isKerberos()) {
            String loginKerberos = Pattern.compile("(?s)\\{.*").matcher(StringUtils.join(Files.readAllLines(Paths.get(AuthenticationUtil.getPathKerberosLogin()), Charset.defaultCharset()), "")).replaceAll("").trim();
            SpnegoHttpURLConnection spnego = new SpnegoHttpURLConnection(loginKerberos);
            connection = spnego.connect(new URL(ConnectionUtil.getUrlByUser()));
        } else {
            connection = (HttpURLConnection) new URL(ConnectionUtil.getUrlByUser().replace(InjectionModel.STAR, "")).openConnection();
        }
        connection.setReadTimeout(ConnectionUtil.getTimeout());
        connection.setConnectTimeout(ConnectionUtil.getTimeout());
        connection.setDefaultUseCaches(false);
        connection.setRequestProperty("Pragma", "no-cache");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setRequestProperty("Expires", "-1");
        ConnectionUtil.fixJcifsTimeout(connection);
        // Add headers if exists (Authorization:Basic, etc)
        for (SimpleEntry<String, String> header : ParameterUtil.getHeader()) {
            HeaderUtil.sanitizeHeaders(connection, header);
        }
        HeaderUtil.checkResponseHeader(connection, ConnectionUtil.getUrlByUser().replace(InjectionModel.STAR, ""));
    // Calling connection.disconnect() is not required, further calls will follow
    } catch (Exception e) {
        String message = Optional.ofNullable(e.getMessage()).orElse("");
        throw new InjectionFailureException("Connection failed: " + message.replace(e.getClass().getName() + ": ", ""), e);
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) SpnegoHttpURLConnection(net.sourceforge.spnego.SpnegoHttpURLConnection) SpnegoHttpURLConnection(net.sourceforge.spnego.SpnegoHttpURLConnection) CookieManager(java.net.CookieManager) URL(java.net.URL) InjectionFailureException(com.jsql.model.exception.InjectionFailureException) IgnoreMessageException(com.jsql.model.exception.IgnoreMessageException) IOException(java.io.IOException) ProtocolException(java.net.ProtocolException) InjectionFailureException(com.jsql.model.exception.InjectionFailureException)

Aggregations

InjectionFailureException (com.jsql.model.exception.InjectionFailureException)2 IOException (java.io.IOException)2 HttpURLConnection (java.net.HttpURLConnection)2 URL (java.net.URL)2 SpnegoHttpURLConnection (net.sourceforge.spnego.SpnegoHttpURLConnection)2 Header (com.jsql.model.bean.util.Header)1 Request (com.jsql.model.bean.util.Request)1 IgnoreMessageException (com.jsql.model.exception.IgnoreMessageException)1 JSqlException (com.jsql.model.exception.JSqlException)1 DataOutputStream (java.io.DataOutputStream)1 CookieManager (java.net.CookieManager)1 MalformedURLException (java.net.MalformedURLException)1 ProtocolException (java.net.ProtocolException)1 PrivilegedActionException (java.security.PrivilegedActionException)1 EnumMap (java.util.EnumMap)1 LoginException (javax.security.auth.login.LoginException)1 GSSException (org.ietf.jgss.GSSException)1 JSONException (org.json.JSONException)1 JSONObject (org.json.JSONObject)1