diff --git a/.vscode/tasks.json b/.vscode/tasks.json deleted file mode 100644 index fd07820..0000000 --- a/.vscode/tasks.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - // See https://go.microsoft.com/fwlink/?LinkId=733558 - // for the documentation about the tasks.json format - "version": "2.0.0", - "tasks": [ - { - "label": "gradle", - "type": "shell", - "command": "gradle bigjar", - // "command": "gradlew.bat bigjar", // Wrapper on Windows - // "command": "gradlew bigjar", // Wrapper on *nix - "group": { - "kind": "build", - "isDefault": true - } - } - ] -} diff --git a/HostsLoader-1.0.0.jar b/HostsLoader-1.0.0.jar new file mode 100644 index 0000000..f3e3de9 Binary files /dev/null and b/HostsLoader-1.0.0.jar differ diff --git a/HostsLoader-all.jar b/HostsLoader-all.jar deleted file mode 100644 index 374b5aa..0000000 Binary files a/HostsLoader-all.jar and /dev/null differ diff --git a/README.md b/README.md index af0fc56..4cfbacb 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,26 @@ # Hosts Loader Burp plugin to automatically load hosts from /etc/hosts (or the Windows equivalent) into Burp's project hostname resolution override. +Supports adding custom dns hosts from dnsmasq on Linux.(`address=/custom1.tld/custom2.tld/custom3.tld/.../10.10.10.10`) ## Why? -When I'm doing HackTheBox, changing my /etc/hosts doesn't seem to work for resolving things in Burp Suite. I assume they're cached in some way, but honestly it was quicker to write this then debug why this happens. +When I'm doing HackTheBox or Vulnlab, changing my /etc/hosts (or the Windows equivalent or dnsmasq) doesn't seem to work (or I forget to reload dnsmasq) for resolving things in Burp Suite. I assume they're cached in some way, but honestly it was quicker to write this than try to debug why this happens. ## How to use -Install the jar as you would any other extension. A new tab will appear, click reload, and hosts will be loaded. +Install the jar as you would any other extension. A new tab will appear, click reload, and hosts will be loaded. -![Hosts Loader tab](img/example.png) \ No newline at end of file +![Hosts Loader tab](img/example.png) + +![Updated BurpSuite Setting](img/example2.png) + +## How to build from source + +### On Linux: + +Run `gradlew build --project-cache-dir=/tmp/cache/.gradle/` + +### On Windows: + +Run `gradlew.bat build --project-cache-dir=%localappdata%\Temp\cache\.gradle\` diff --git a/build.gradle b/build.gradle index ad31d4a..e8c3486 100644 --- a/build.gradle +++ b/build.gradle @@ -1,43 +1,48 @@ -/* - * This file was generated by the Gradle 'init' task. - * - * This is a general purpose Gradle build. - * Learn more about Gradle by exploring our samples at https://docs.gradle.org/7.6/samples - */ +plugins { + id 'java' +} -// Apply the Java plugin -apply plugin: 'java' +version = '1.0.0' -// Use Maven (because Burp Extender is on Maven) repositories { - mavenCentral() + mavenCentral() } dependencies { - // Add the Burp Extender interface - implementation 'net.portswigger.burp.extender:burp-extender-api:2.3' - compile 'com.google.guava:guava:31.1-jre' - compile 'com.fasterxml.jackson.core:jackson-databind:2.14.2' + implementation 'net.portswigger.burp.extensions:montoya-api:+' + implementation 'com.google.guava:guava:33.3.0-jre' + implementation 'com.fasterxml.jackson.core:jackson-databind:2.17.2' +} +java { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 } -sourceSets { - main { - java { - // Set the source directory to "src" - srcDir 'src' - } +jar { + manifest { + attributes( + 'Manifest-Version': '1.0', + 'Created-By': 'Gradle 8.1.0', + 'Main-Class': 'burp.HostsLoader' + ) } + + from { + configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } + } { + exclude 'META-INF/*.SF' + exclude 'META-INF/*.DSA' + exclude 'META-INF/*.RSA' + } + + duplicatesStrategy = DuplicatesStrategy.EXCLUDE } -// Create a task for bundling all dependencies into a jar file. -task bigJar(type: Jar) { - baseName = project.name + '-all' - from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } - with jar +task copyJar(type: Copy) { + dependsOn jar + from jar.archiveFile + into "${projectDir}" } -task copyJar(type: Copy, dependsOn: bigJar) { - from(bigJar.archiveFile) - into project.rootProject.projectDir -} \ No newline at end of file +build.finalizedBy(copyJar) \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..072aa76 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,10 @@ +# This file was generated by the Gradle 'init' task. +# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format + +[versions] +guava = "33.2.1-jre" +junit-jupiter = "5.10.3" + +[libraries] +guava = { module = "com.google.guava:guava", version.ref = "guava" } +junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit-jupiter" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..0aaefbc --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 65dcd68..f5feea6 100644 --- a/gradlew +++ b/gradlew @@ -15,6 +15,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -83,10 +85,9 @@ done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -133,10 +134,13 @@ location of your Java installation." fi else JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. @@ -144,7 +148,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac @@ -152,7 +156,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -197,11 +201,15 @@ if "$cygwin" || "$msys" ; then done fi -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ diff --git a/gradlew.bat b/gradlew.bat index 93e3f59..9b42019 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,92 +1,94 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%"=="" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -@rem This is normally unused -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if %ERRORLEVEL% equ 0 goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/img/example.png b/img/example.png index e4dbd0c..c21bb39 100644 Binary files a/img/example.png and b/img/example.png differ diff --git a/img/example2.png b/img/example2.png new file mode 100644 index 0000000..a2013f7 Binary files /dev/null and b/img/example2.png differ diff --git a/src/burp/BurpExtender.java b/src/burp/BurpExtender.java deleted file mode 100644 index 2e24ad3..0000000 --- a/src/burp/BurpExtender.java +++ /dev/null @@ -1,23 +0,0 @@ -package burp; - -import java.awt.Component; -import java.io.PrintWriter; - -public class BurpExtender implements IBurpExtender { - // - // implement IBurpExtender - // - PrintWriter stdout; - PrintWriter stderr; - - @Override - public void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks) { - // set our extension name - callbacks.setExtensionName("Hosts Loader"); - this.stdout = new PrintWriter(callbacks.getStdout(), true); // for normal console output - this.stderr = new PrintWriter(callbacks.getStderr(), true); // for error console output - callbacks.addSuiteTab(new HostsTab(callbacks)); - - stdout.println("Hosts Loader loaded"); - } -} diff --git a/src/burp/HostsTab.java b/src/burp/HostsTab.java deleted file mode 100644 index 0966227..0000000 --- a/src/burp/HostsTab.java +++ /dev/null @@ -1,133 +0,0 @@ -package burp; - -import javax.swing.*; -import com.google.common.net.InetAddresses; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Map; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class HostsTab implements ITab { - private JPanel panel; - - private JTextArea output; - private JButton reload; - - PrintWriter stdout; - PrintWriter stderr; - - public HostsTab(IBurpExtenderCallbacks callbacks) { - this.stdout = new PrintWriter(callbacks.getStdout(), true); // for normal console output - this.stderr = new PrintWriter(callbacks.getStderr(), true); // for error console output - - // Set up the panel - this.panel = new JPanel(); - this.panel.setLayout(new BorderLayout()); - - reload = new JButton(); - reload.setAction(new AbstractAction() { - @Override - public void actionPerformed(ActionEvent arg) { - try { - var hosts = readHostsFile(); - - var string = ""; - for (Map.Entry set : hosts.entrySet()) { - - // Printing all elements of a Map - string += (set.getKey() + " = " - + set.getValue()) + "\n"; - } - - ObjectMapper mapper = new ObjectMapper(); - HashMap jsonObject = new HashMap<>(); - jsonObject.put("project_options.connections.hostname_resolution", hosts.entrySet().stream() - .map(e -> { - HashMap obj = new HashMap<>(); - obj.put("enabled", true); - obj.put("hostname", e.getKey()); - obj.put("ip_address", e.getValue()); - return obj; - }) - .toArray()); - - callbacks.loadConfigFromJson(mapper.writeValueAsString(jsonObject)); - - output.setText("Added the following hosts:\n\n" + string); - } catch (IOException error) { - output.setText("Failed to load hosts file"); - } - - } - }); - reload.setPreferredSize(new Dimension(500, 25)); - reload.setText("Reload Hosts"); - - this.panel.add(reload, BorderLayout.PAGE_START); - - // Add a label to the panel - output = new JTextArea("Output"); - this.panel.add(output, BorderLayout.CENTER); - } - - @Override - public String getTabCaption() { - return "Hosts Loader"; - } - - @Override - public Component getUiComponent() { - return this.panel; - } - - public Map readHostsFile() throws IOException { - Map hostsMap = new HashMap<>(); - BufferedReader br = null; - String hostsFilePath = null; - - stdout.println("loading hosts"); - - // Check if the OS is Windows or Linux - String osName = System.getProperty("os.name").toLowerCase(); - if (osName.contains("win")) { - hostsFilePath = "C:\\Windows\\System32\\drivers\\etc\\hosts"; - } else { - hostsFilePath = "/etc/hosts"; - } - - try { - br = new BufferedReader(new FileReader(hostsFilePath)); - String line; - while ((line = br.readLine()) != null) { - line = line.trim(); - if (!line.startsWith("#") && !line.isEmpty()) { - String[] tokens = line.split("\\s+"); - String ip = tokens[0]; - stdout.println(ip); - if (!InetAddresses.isInetAddress(ip)) { - continue; - } - - for (int i = 1; i < tokens.length; i++) { - String hostname = tokens[i]; - hostsMap.put(hostname, ip); - } - } - } - } catch (IOException e) { - // If the hosts file is not found, return an empty map - return hostsMap; - } finally { - if (br != null) { - br.close(); - } - } - - return hostsMap; - } -} diff --git a/src/main/java/burp/HostsLoader.java b/src/main/java/burp/HostsLoader.java new file mode 100644 index 0000000..aa401df --- /dev/null +++ b/src/main/java/burp/HostsLoader.java @@ -0,0 +1,268 @@ +package burp; + +import burp.api.montoya.BurpExtension; +import burp.api.montoya.MontoyaApi; +import burp.api.montoya.extension.ExtensionUnloadingHandler; +import burp.api.montoya.logging.Logging; + +import javax.swing.*; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; + +import com.google.common.net.InetAddresses; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.awt.*; +import java.awt.event.ActionEvent; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import java.util.HashMap; +import java.util.Map; + +import java.util.regex.Pattern; + +public class HostsLoader implements BurpExtension, ExtensionUnloadingHandler +{ + private MontoyaApi api; + private Logging logging; + private JTextArea output; + private JButton reload; + private JCheckBox dnsmasqCheckBox; + private boolean usingdnsmasq = false; + + private JTextField pathToAlternativeFileField; + private JLabel alternativeFilePathLabel; + private JLabel invalidPathLabel; + private String pathtoalternativefile = "/etc/dnsmasq.conf"; // Default path + + @Override + public void initialize(MontoyaApi api) + { + this.api = api; + this.logging = api.logging(); + + // Create the main panel + JPanel panel = new JPanel(); + panel.setLayout(new BorderLayout()); + + // Create a controls panel with left alignment + JPanel controlsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); + controlsPanel.setAlignmentX(Component.LEFT_ALIGNMENT); + + reload = new JButton("Reload Hosts"); + reload.addActionListener(this::reloadHosts); + reload.setPreferredSize(new Dimension(100, 25)); + controlsPanel.add(reload); + + String osName = System.getProperty("os.name").toLowerCase(); + if (osName.contains("linux")) + { + // Set up the checkbox + dnsmasqCheckBox = new JCheckBox("Use dnsmasq"); + dnsmasqCheckBox.addItemListener(e -> { + usingdnsmasq = dnsmasqCheckBox.isSelected(); + alternativeFilePathLabel.setVisible(usingdnsmasq); + pathToAlternativeFileField.setVisible(usingdnsmasq); + invalidPathLabel.setVisible(false); // Hide the invalid path label when toggling + }); + + // Create the label for alternative file path + alternativeFilePathLabel = new JLabel("Alternative File Path:"); + alternativeFilePathLabel.setVisible(false); // Initially hidden + + // Create the text field for the alternative file path + pathToAlternativeFileField = new JTextField(pathtoalternativefile, 30); + pathToAlternativeFileField.setVisible(false); // Initially hidden + pathToAlternativeFileField.getDocument().addDocumentListener(new DocumentListener() + { + @Override + public void insertUpdate(DocumentEvent e) { validatePath(); } + @Override + public void removeUpdate(DocumentEvent e) { validatePath(); } + @Override + public void changedUpdate(DocumentEvent e) { validatePath(); } + + private void validatePath() + { + pathtoalternativefile = pathToAlternativeFileField.getText(); + File file = new File(pathtoalternativefile); + if (file.exists() && file.isFile()) + { + invalidPathLabel.setVisible(false); + } + else + { + invalidPathLabel.setVisible(true); + pathtoalternativefile = "/etc/dnsmasq.conf"; + } + } + }); + + // Create the invalid path label + invalidPathLabel = new JLabel("Not a valid Path to File"); + invalidPathLabel.setForeground(Color.RED); + invalidPathLabel.setVisible(false); // Initially hidden + + // Add components to the controls panel + controlsPanel.add(dnsmasqCheckBox); + controlsPanel.add(alternativeFilePathLabel); + controlsPanel.add(pathToAlternativeFileField); + controlsPanel.add(invalidPathLabel); + } + + panel.add(controlsPanel, BorderLayout.PAGE_START); + + // Add the output area + output = new JTextArea("Output"); + panel.add(new JScrollPane(output), BorderLayout.CENTER); + + // Register the tab with Burp's UI + api.userInterface().registerSuiteTab("Hosts Loader", panel); + + // Log extension load message + logging.logToOutput("Hosts Loader loaded"); + } + + private void reloadHosts(ActionEvent event) + { + try + { + Map hosts = readHostsFile(); + + StringBuilder sb = new StringBuilder(); + for (Map.Entry entry : hosts.entrySet()) + { + sb.append(entry.getKey()).append(" = ").append(entry.getValue()).append("\n"); + } + + ObjectMapper mapper = new ObjectMapper(); + HashMap jsonObject = new HashMap<>(); + jsonObject.put("project_options.connections.hostname_resolution", hosts.entrySet().stream() + .map(e -> { + HashMap obj = new HashMap<>(); + obj.put("enabled", true); + obj.put("hostname", e.getKey()); + obj.put("ip_address", e.getValue()); + return obj; + }) + .toArray()); + + String jsonString = mapper.writeValueAsString(jsonObject); + + // Update Burp's configuration with correct method casing + api.burpSuite().importProjectOptionsFromJson(jsonString); + + output.setText("Added the following hosts:\n\n" + sb.toString()); + } + catch (IOException e) + { + output.setText("Failed to load hosts file: " + e.getMessage()); + logging.logToError("Failed to load hosts file: " + e.getMessage()); + } + } + + public Map readHostsFile() throws IOException + { + Map hostsMap = new HashMap<>(); + BufferedReader br = null; + String hostsFilePath; + + logging.logToOutput("Loading hosts"); + // Set hostsFilePath based on the operating system + String osName = System.getProperty("os.name").toLowerCase(); + if (osName.contains("win")) + { + hostsFilePath = "C:\\Windows\\System32\\drivers\\etc\\hosts"; + } + else + { + if (usingdnsmasq) + { + hostsFilePath = pathtoalternativefile; + } + else + { + hostsFilePath = "/etc/hosts"; + } + } + + try + { + br = new BufferedReader(new FileReader(hostsFilePath)); + String line; + while ((line = br.readLine()) != null) + { + line = line.trim(); + if (usingdnsmasq) + { + // Parsing logic for dnsmasq configuration file + if (!line.startsWith("#") && !line.isEmpty() && line.startsWith("address=")) + { + String[] tokens = line.split(Pattern.quote("="))[1].split(Pattern.quote("/")); + String ip = tokens[tokens.length - 1]; + + if (!InetAddresses.isInetAddress(ip)) + { + continue; + } + + for (int i = 1; i < tokens.length - 1; i++) + { + if (!tokens[i].isEmpty()) { + String hostname = tokens[i]; + hostsMap.put(hostname, ip); + } + } + } + } + else + { + // Parsing logic for regular Host file + if (!line.startsWith("#") && !line.isEmpty()) + { + String[] tokens = line.split("\\s+"); + if (tokens.length >= 2) + { + String ip = tokens[0]; + if (!InetAddresses.isInetAddress(ip)) + { + continue; + } + for (int i = 1; i < tokens.length; i++) + { + String hostname = tokens[i]; + hostsMap.put(hostname, ip); + } + } + } + } + } + } + catch (IOException e) + { + logging.logToError("Error reading hosts file: " + e.getMessage()); + throw e; + } + finally + { + if (br != null) + { + br.close(); + } + } + + return hostsMap; + } + + @Override + public void extensionUnloaded() + { + // No resources to clean up at this time + logging.logToOutput("Hosts Loader extension unloaded."); + } +}